297 lines
8.9 KiB
JavaScript
297 lines
8.9 KiB
JavaScript
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { MessageCircle, Send, X } from "lucide-react";
|
|
import { useAuth } from "../../context/authContext";
|
|
import {
|
|
useGetSupportConversationQuery,
|
|
useLazyGetChatMessagesQuery,
|
|
useReadChatMutation,
|
|
useSendChatMessageMutation,
|
|
useStartSupportConversationMutation,
|
|
} from "../../app/api/chatApi";
|
|
import { getChatEcho, leaveChatChannel } from "../../utils/echo";
|
|
import styles from "./ChatWidget.module.scss";
|
|
|
|
function formatTime(value) {
|
|
if (!value) return "";
|
|
const date = new Date(value);
|
|
if (Number.isNaN(date.getTime())) return "";
|
|
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
|
}
|
|
|
|
export default function ChatWidget() {
|
|
const { t } = useTranslation();
|
|
const { authToken, guestToken } = useAuth();
|
|
const ready = Boolean(authToken || guestToken);
|
|
|
|
const [open, setOpen] = useState(false);
|
|
const [hidden, setHidden] = useState(false);
|
|
const [conversation, setConversation] = useState(null);
|
|
const [messages, setMessages] = useState([]);
|
|
const [nextPage, setNextPage] = useState(null);
|
|
const [draft, setDraft] = useState("");
|
|
const [unread, setUnread] = useState(0);
|
|
const [loadingThread, setLoadingThread] = useState(false);
|
|
|
|
const listRef = useRef(null);
|
|
const subscribedId = useRef(null);
|
|
const openRef = useRef(open);
|
|
openRef.current = open;
|
|
const pendingPrepend = useRef(false);
|
|
|
|
const { data: existing, error } = useGetSupportConversationQuery(undefined, {
|
|
skip: !ready || hidden,
|
|
pollingInterval: open ? 0 : 15000,
|
|
});
|
|
const [startSupport] = useStartSupportConversationMutation();
|
|
const [fetchMessages] = useLazyGetChatMessagesQuery();
|
|
const [sendMessage, { isLoading: sending }] = useSendChatMessageMutation();
|
|
const [markRead] = useReadChatMutation();
|
|
|
|
useEffect(() => {
|
|
const status = error?.status;
|
|
if (status === 403 || status === 422) {
|
|
setHidden(true);
|
|
}
|
|
}, [error]);
|
|
|
|
useEffect(() => {
|
|
if (!existing) {
|
|
return;
|
|
}
|
|
setConversation(existing);
|
|
if (!open) {
|
|
setUnread(existing.unread_count || 0);
|
|
}
|
|
}, [existing, open]);
|
|
|
|
useLayoutEffect(() => {
|
|
if (!open || loadingThread || pendingPrepend.current) {
|
|
return;
|
|
}
|
|
const el = listRef.current;
|
|
if (!el) {
|
|
return;
|
|
}
|
|
el.scrollTop = el.scrollHeight;
|
|
}, [messages, open, loadingThread]);
|
|
|
|
const appendMessage = useCallback((message) => {
|
|
setMessages((current) => {
|
|
if (current.some((item) => item.id === message.id)) {
|
|
return current;
|
|
}
|
|
return [...current, message];
|
|
});
|
|
}, []);
|
|
|
|
const loadPage = useCallback(
|
|
async (conversationId, page = 1, prepend = false) => {
|
|
const result = await fetchMessages({ conversationId, page, perPage: 50 }).unwrap();
|
|
const items = (result.items || []).slice().reverse();
|
|
setNextPage(result.pagination?.next_page_url ? page + 1 : null);
|
|
setMessages((current) => {
|
|
if (!prepend) {
|
|
return items;
|
|
}
|
|
const known = new Set(current.map((item) => item.id));
|
|
return [...items.filter((item) => !known.has(item.id)), ...current];
|
|
});
|
|
return items;
|
|
},
|
|
[fetchMessages]
|
|
);
|
|
|
|
const openThread = useCallback(async () => {
|
|
setOpen(true);
|
|
setLoadingThread(true);
|
|
try {
|
|
let current = conversation;
|
|
if (!current?.id) {
|
|
current = await startSupport().unwrap();
|
|
setConversation(current);
|
|
}
|
|
await loadPage(current.id, 1, false);
|
|
await markRead(current.id);
|
|
setUnread(0);
|
|
} catch (err) {
|
|
if (err?.status === 403 || err?.status === 422) {
|
|
setHidden(true);
|
|
setOpen(false);
|
|
}
|
|
} finally {
|
|
setLoadingThread(false);
|
|
}
|
|
}, [conversation, loadPage, markRead, startSupport]);
|
|
|
|
useEffect(() => {
|
|
const conversationId = conversation?.id;
|
|
if (!conversationId || hidden) {
|
|
return undefined;
|
|
}
|
|
|
|
const echo = getChatEcho();
|
|
if (!echo) {
|
|
return undefined;
|
|
}
|
|
|
|
if (subscribedId.current && subscribedId.current !== conversationId) {
|
|
leaveChatChannel(subscribedId.current);
|
|
}
|
|
|
|
subscribedId.current = conversationId;
|
|
echo.private(`chat.${conversationId}`).listen(".message.sent", (payload) => {
|
|
appendMessage(payload);
|
|
if (openRef.current) {
|
|
markRead(conversationId);
|
|
setUnread(0);
|
|
} else {
|
|
setUnread((count) => count + 1);
|
|
}
|
|
});
|
|
|
|
return () => {
|
|
leaveChatChannel(conversationId);
|
|
subscribedId.current = null;
|
|
};
|
|
}, [appendMessage, conversation?.id, hidden, markRead]);
|
|
|
|
useEffect(() => {
|
|
if (!open || !conversation?.id || getChatEcho()) {
|
|
return undefined;
|
|
}
|
|
|
|
const timer = setInterval(async () => {
|
|
try {
|
|
const result = await fetchMessages({
|
|
conversationId: conversation.id,
|
|
page: 1,
|
|
perPage: 50,
|
|
}).unwrap();
|
|
const items = (result.items || []).slice().reverse();
|
|
setMessages((current) => {
|
|
const known = new Set(current.map((item) => item.id));
|
|
const incoming = items.filter((item) => !known.has(item.id));
|
|
return incoming.length ? [...current, ...incoming] : current;
|
|
});
|
|
} catch {
|
|
// polling is best-effort
|
|
}
|
|
}, 4000);
|
|
|
|
return () => clearInterval(timer);
|
|
}, [conversation?.id, fetchMessages, open]);
|
|
|
|
const handleScroll = async () => {
|
|
if (!listRef.current || !nextPage || !conversation?.id || loadingThread) {
|
|
return;
|
|
}
|
|
if (listRef.current.scrollTop > 40) {
|
|
return;
|
|
}
|
|
pendingPrepend.current = true;
|
|
const previousHeight = listRef.current.scrollHeight;
|
|
await loadPage(conversation.id, nextPage, true);
|
|
requestAnimationFrame(() => {
|
|
if (listRef.current) {
|
|
listRef.current.scrollTop = listRef.current.scrollHeight - previousHeight;
|
|
}
|
|
pendingPrepend.current = false;
|
|
});
|
|
};
|
|
|
|
const handleSend = async (event) => {
|
|
event.preventDefault();
|
|
const body = draft.trim();
|
|
if (!body || sending) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
let current = conversation;
|
|
if (!current?.id) {
|
|
current = await startSupport().unwrap();
|
|
setConversation(current);
|
|
}
|
|
const message = await sendMessage({
|
|
conversationId: current.id,
|
|
body,
|
|
}).unwrap();
|
|
appendMessage(message);
|
|
setDraft("");
|
|
} catch (err) {
|
|
if (err?.status === 403 || err?.status === 422) {
|
|
setHidden(true);
|
|
}
|
|
}
|
|
};
|
|
|
|
if (!ready || hidden) {
|
|
return null;
|
|
}
|
|
|
|
const otherName = conversation?.user?.name || t("chat.title");
|
|
const otherId = conversation?.user?.id;
|
|
|
|
return (
|
|
<div className={styles.wrap}>
|
|
{open && (
|
|
<div className={styles.panel} role="dialog" aria-label={t("chat.title")}>
|
|
<div className={styles.header}>
|
|
<span>{otherName}</span>
|
|
<button type="button" className={styles.iconBtn} onClick={() => setOpen(false)} aria-label={t("chat.close")}>
|
|
<X size={18} />
|
|
</button>
|
|
</div>
|
|
<div className={styles.messages} ref={listRef} onScroll={handleScroll}>
|
|
{loadingThread && <p className={styles.empty}>{t("chat.loading")}</p>}
|
|
{!loadingThread && messages.length === 0 && (
|
|
<p className={styles.empty}>{t("chat.empty")}</p>
|
|
)}
|
|
{messages.map((message) => {
|
|
const mine = otherId ? message.user?.id !== otherId : true;
|
|
return (
|
|
<div
|
|
key={message.id}
|
|
className={`${styles.bubble} ${mine ? styles.out : styles.in}`}
|
|
>
|
|
<div>{message.body}</div>
|
|
<span>{formatTime(message.created_at)}</span>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
<form className={styles.composer} onSubmit={handleSend}>
|
|
<textarea
|
|
value={draft}
|
|
onChange={(event) => setDraft(event.target.value)}
|
|
placeholder={t("chat.placeholder")}
|
|
rows={1}
|
|
maxLength={5000}
|
|
onKeyDown={(event) => {
|
|
if (event.key === "Enter" && !event.shiftKey) {
|
|
event.preventDefault();
|
|
handleSend(event);
|
|
}
|
|
}}
|
|
/>
|
|
<button type="submit" disabled={sending || !draft.trim()} aria-label={t("chat.send")}>
|
|
<Send size={16} />
|
|
</button>
|
|
</form>
|
|
</div>
|
|
)}
|
|
|
|
<button
|
|
type="button"
|
|
className={styles.fab}
|
|
onClick={() => (open ? setOpen(false) : openThread())}
|
|
aria-label={t("chat.title")}
|
|
>
|
|
{open ? <X size={22} /> : <MessageCircle size={22} />}
|
|
{!open && unread > 0 && <span className={styles.badge}>{unread > 99 ? "99+" : unread}</span>}
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|