Rev 15860 | Rev 15975 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useRef, useState } from "react";
import { axios } from "../../../utils";
import { useForm } from "react-hook-form";
import Emojione from "./emojione/Emojione";
import FileModal from "./fileModal/FileModal";
import MessagesList from "./messages/MessagesList";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import InsertEmoticonIcon from "@mui/icons-material/InsertEmoticon";
import SendIcon from "@mui/icons-material/Send";
import styles from "./chat.module.scss";
const permittedFiles =
"video/mp4, video/mpeg, video/webm, application/pdf, image/jpeg, image/png, image/jpg";
const Chat = ({ entity }) => {
const [oldMessages, setOldMessages] = useState([]);
const [messages, setMessages] = useState([]);
const [totalPages, setTotalPages] = useState(1);
const [currentPage, setCurrentPage] = useState(1);
const [loading, setLoading] = useState(false);
const [showEmojione, setShowEmojione] = useState(false);
const [selectedFile, setSelectedFile] = useState("");
const { handleSubmit, register } = useForm();
const bottomToScroll = useRef(null);
const inputTextEl = useRef(null);
const fileInputEl = useRef(null);
const divToScroll = useRef(null);
const {
url_get_all_messages,
url_send,
url_upload,
url_close,
url_mark_seen,
type,
} = entity;
// Get messages
const getMessages = () => {
setLoading(true);
axios
.get(url_get_all_messages)
.then(({ data: response }) => {
const { data, success } = response;
if (!success) {
return console.log("Ha ocurrido un error");
}
const messageResponse = [...data.items].reverse();
const updatedMessages = messageResponse.reduce(
(acum, updatedMessage) => {
if (
messages.findIndex(
(message) => message.id === updatedMessage.id
) === -1
) {
acum = [...acum, updatedMessage];
}
return acum;
},
[]
);
if (updatedMessages.length > 0) {
setMessages([...messages, ...updatedMessages]);
setTotalPages(data.pages);
scrollToBottom();
}
})
.finally(() => setLoading(false));
};
const onIntersection = (entities) => {
const target = entities[0];
if (target.isIntersecting && currentPage < totalPages) {
setCurrentPage((prevState) => prevState + 1);
bottomToScroll.current.scrollBy(0, 200);
}
};
const getOldMessages = () => {
setLoading(true);
axios
.get(`${url_get_all_messages}?page=${currentPage}`)
.then(({ data: response }) => {
const { data, success } = response;
if (success && data.page > 1) {
setOldMessages([...data.items.slice().reverse(), ...oldMessages]);
}
})
.finally(() => setLoading(false));
};
//Utilitys
const scrollToBottom = () => {
const divToScrollEl = divToScroll.current;
divToScrollEl.scrollIntoView({ behavior: "smooth" });
};
const onClickEmoji = (event) => {
const shortname = event.currentTarget.dataset.shortname;
inputTextEl.current.value += shortname;
inputTextEl.current.focus();
};
const handleUploadFile = ({ target }) => {
const file = target.files[0];
if (!file) {
return;
}
setSelectedFile(file);
};
const removeSelectedFile = () => {
setSelectedFile("");
};
// On send
const onHandleSubmit = (data, event) => {
const formData = new FormData();
Object.entries(data).map(([key, value]) => formData.append(key, value));
event.target.reset();
axios.post(url_send, formData).then((response) => setShowEmojione(false));
};
const handleSendFile = () => {
const formData = new FormData();
formData.append("file", selectedFile);
axios.post(url_upload, formData).then(({ data: response }) => {
const { success, data } = response;
if (!success) {
console.log("Ha ocurrido un error: " + data);
return;
}
setSelectedFile("");
setShowEmojione(false);
});
};
useEffect(() => {
let timeInterval;
if (loading) return;
timeInterval = setTimeout(() => getMessages(), 2000);
return () => {
clearTimeout(timeInterval);
};
}, [loading]);
useEffect(() => {
setMessages([]);
setOldMessages([]);
setTotalPages(1);
setCurrentPage(1);
}, [entity]);
useEffect(() => getOldMessages(), [currentPage]);
useEffect(() => axios.post(url_mark_seen), []);
return (
<div className={styles.chat}>
<div className={styles.messagesContainer} ref={bottomToScroll}>
<MessagesList
isLastPage={currentPage >= totalPages}
messages={[...oldMessages, ...messages]}
onIntersection={onIntersection}
/>
<div ref={divToScroll} />
</div>
<div className={styles.chat__input__container}>
{showEmojione && <Emojione onClickEmoji={onClickEmoji} />}
<form
onSubmit={handleSubmit(onHandleSubmit)}
encType="multipart/form-data"
>
<button
type="button"
className={"btn " + styles.icon_btn}
onClick={() => fileInputEl.current.click()}
>
<AttachFileIcon />
</button>
<button
type="button"
className={"btn " + styles.icon_btn}
onClick={() => setShowEmojione(!showEmojione)}
>
<InsertEmoticonIcon />
</button>
<input
type="file"
ref={(e) => (fileInputEl.current = e)}
accept={permittedFiles}
onChange={handleUploadFile}
hidden
/>
<textarea
className={styles.chatInput}
placeholder="Escribe un mensaje"
rows="1"
ref={inputTextEl}
/>
<button type="submit" className={"btn " + styles.send_btn}>
<SendIcon />
</button>
</form>
</div>
{selectedFile && (
<FileModal
file={selectedFile}
onCancel={removeSelectedFile}
onSend={handleSendFile}
/>
)}
</div>
);
};
export default Chat;