adminFront/src/pages/dashboard/Content/Support/Chat/Chat.tsx

247 lines
8.9 KiB
TypeScript
Raw Normal View History

2023-03-29 12:51:36 +00:00
import { Box, IconButton, InputAdornment, TextField, Typography, useMediaQuery, useTheme } from "@mui/material";
2023-04-07 13:33:25 +00:00
import { addOrUpdateMessages, clearMessageState, incrementMessageApiPage, setIsPreventAutoscroll, setMessageFetchState, useMessageStore } from "@root/stores/messages";
2023-03-21 13:00:10 +00:00
import Message from "./Message";
import SendIcon from "@mui/icons-material/Send";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import { KeyboardEvent, useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { GetMessagesRequest, TicketMessage } from "@root/model/ticket";
import { getTicketMessages, sendTicketMessage, subscribeToTicketMessages } from "@root/api/tickets";
import { enqueueSnackbar } from "notistack";
2023-03-21 14:43:08 +00:00
import { useTicketStore } from "@root/stores/tickets";
2023-04-07 13:33:25 +00:00
import { throttle } from "@root/utils/throttle";
2023-04-18 11:06:23 +00:00
import { authStore } from "@root/stores/auth";
2023-03-20 15:27:42 +00:00
2023-03-20 15:27:42 +00:00
export default function Chat() {
const token = authStore(state => state.token);
2023-04-07 13:33:25 +00:00
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const tickets = useTicketStore(state => state.tickets);
const messages = useMessageStore(state => state.messages);
const [messageField, setMessageField] = useState<string>("");
const ticketId = useParams().ticketId;
const chatBoxRef = useRef<HTMLDivElement>(null);
const messageApiPage = useMessageStore(state => state.apiPage);
const messagesPerPage = useMessageStore(state => state.messagesPerPage);
const messagesFetchStateRef = useRef(useMessageStore.getState().fetchState);
const isPreventAutoscroll = useMessageStore(state => state.isPreventAutoscroll);
const lastMessageId = useMessageStore(state => state.lastMessageId);
2023-04-18 11:06:23 +00:00
2023-04-07 13:33:25 +00:00
const ticket = tickets.find(ticket => ticket.id === ticketId);
2023-04-18 11:06:23 +00:00
useEffect(function fetchTicketMessages() {
if (!ticketId) return;
2023-04-18 11:06:23 +00:00
2023-04-07 13:33:25 +00:00
const getTicketsBody: GetMessagesRequest = {
amt: messagesPerPage,
page: messageApiPage,
ticket: ticketId,
};
const controller = new AbortController();
setMessageFetchState("fetching");
getTicketMessages({
body: getTicketsBody,
signal: controller.signal,
}).then(result => {
if (result?.length > 0) {
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
2023-04-07 13:33:25 +00:00
addOrUpdateMessages(result);
setMessageFetchState("idle");
} else setMessageFetchState("all fetched");
}).catch(error => {
console.log("Error fetching messages", error);
enqueueSnackbar(error.message);
2023-03-21 13:00:10 +00:00
});
2023-04-07 13:33:25 +00:00
return () => {
controller.abort();
};
}, [messageApiPage, messagesPerPage, ticketId]);
2023-04-18 11:06:23 +00:00
2023-04-07 13:33:25 +00:00
useEffect(function subscribeToMessages() {
if (!ticketId) return;
if (!token) return;
const unsubscribe = subscribeToTicketMessages({
ticketId,
accessToken: token,
onMessage(event) {
try {
const newMessage = JSON.parse(event.data) as TicketMessage;
console.log("SSE: parsed newMessage:", newMessage);
addOrUpdateMessages([newMessage]);
} catch (error) {
console.log("SSE: couldn't parse:", event.data);
console.log("Error parsing message SSE", error);
}
},
onError(event) {
console.log("SSE Error:", event);
},
});
2023-04-18 11:06:23 +00:00
2023-04-07 13:33:25 +00:00
return () => {
unsubscribe();
clearMessageState();
setIsPreventAutoscroll(false);
};
}, [ticketId, token]);
2023-04-07 13:33:25 +00:00
useEffect(function attachScrollHandler() {
if (!chatBoxRef.current) return;
const chatBox = chatBoxRef.current;
const scrollHandler = () => {
const scrollBottom = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight;
const isPreventAutoscroll = scrollBottom > chatBox.clientHeight;
setIsPreventAutoscroll(isPreventAutoscroll);
if (messagesFetchStateRef.current !== "idle") return;
if (chatBox.scrollTop < chatBox.clientHeight) {
incrementMessageApiPage();
}
};
const throttledScrollHandler = throttle(scrollHandler, 200);
chatBox.addEventListener("scroll", throttledScrollHandler);
return () => {
chatBox.removeEventListener("scroll", throttledScrollHandler);
};
}, []);
useEffect(function scrollOnNewMessage() {
if (!chatBoxRef.current) return;
if (!isPreventAutoscroll) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lastMessageId]);
useEffect(() => useMessageStore.subscribe(state => (messagesFetchStateRef.current = state.fetchState)), []);
function scrollToBottom(behavior?: ScrollBehavior) {
if (!chatBoxRef.current) return;
const chatBox = chatBoxRef.current;
chatBox.scroll({
left: 0,
top: chatBox.scrollHeight,
behavior,
});
}
function handleSendMessage() {
if (!ticket || !messageField) return;
sendTicketMessage({
body: {
files: [],
lang: "ru",
message: messageField,
ticket: ticket.id,
}
});
setMessageField("");
}
2023-04-18 11:06:23 +00:00
function handleAddAttachment() { }
2023-04-18 11:06:23 +00:00
2023-04-07 13:33:25 +00:00
function handleTextfieldKeyPress(e: KeyboardEvent) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
2023-03-21 13:00:10 +00:00
}
2023-04-07 13:33:25 +00:00
return (
<Box sx={{
border: "1px solid",
borderColor: theme.palette.grayDark.main,
height: "600px",
borderRadius: "3px",
p: "8px",
display: "flex",
flex: upMd ? "2 0 0" : undefined,
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
gap: "8px",
}}>
<Typography>{ticket ? ticket.title : "Выберите тикет"}</Typography>
<Box
ref={chatBoxRef}
sx={{
width: "100%",
backgroundColor: "#46474a",
flexGrow: 1,
display: "flex",
flexDirection: "column",
gap: "12px",
p: "8px",
overflow: "auto",
colorScheme: "dark",
}}
>
{ticket && messages.map(message =>
<Message key={message.id} message={message} isSelf={ticket.user !== message.user_id} />
)}
</Box>
{ticket &&
<TextField
value={messageField}
onChange={e => setMessageField(e.target.value)}
onKeyPress={handleTextfieldKeyPress}
id="message-input"
placeholder="Написать сообщение"
fullWidth
multiline
maxRows={8}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleSendMessage}
sx={{
height: "45px",
width: "45px",
p: 0,
}}
>
<SendIcon sx={{ color: theme.palette.golden.main }} />
</IconButton>
<IconButton
onClick={handleAddAttachment}
sx={{
height: "45px",
width: "45px",
p: 0,
}}
>
<AttachFileIcon sx={{ color: theme.palette.golden.main }} />
</IconButton>
</InputAdornment>
)
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
}
}}
/>
}
2023-04-07 13:33:25 +00:00
</Box>
);
2023-03-22 09:24:51 +00:00
}