From 347ec3536d05cc41a320638b143ff752ee11b357 Mon Sep 17 00:00:00 2001 From: Mekan1206 Date: Sun, 16 Aug 2026 17:01:26 +0500 Subject: [PATCH] Refactor chat API and UI components to support new chat target functionality. Introduced `getChatTargets` and `startChatTarget` endpoints, updated `ChatWidget` to handle chat targets and conversations, and added new styles for improved UI. Updated localization files for new terms related to admin support and channels. --- src/app/api/chatApi.js | 40 +- .../ChatWidget/ChatWidget.module.scss | 177 ++++++++ src/components/ChatWidget/index.jsx | 400 +++++++++++++----- src/i18n/locales/en.js | 8 + src/i18n/locales/ru.js | 8 + src/i18n/locales/tm.js | 10 +- 6 files changed, 532 insertions(+), 111 deletions(-) diff --git a/src/app/api/chatApi.js b/src/app/api/chatApi.js index a76ed09..a389900 100644 --- a/src/app/api/chatApi.js +++ b/src/app/api/chatApi.js @@ -2,17 +2,37 @@ import { baseApi } from "./baseApi"; export const chatApi = baseApi.injectEndpoints({ endpoints: (builder) => ({ - getSupportConversation: builder.query({ - query: () => ({ - url: "/chat/support", + getChatTargets: builder.query({ + query: ({ q = "", page = 1, perPage = 20, viewer: _viewer } = {}) => { + const params = new URLSearchParams(); + params.set("page", String(page)); + params.set("perPage", String(perPage)); + if (q) { + params.set("q", q); + } + return { + url: `/chat/targets?${params.toString()}`, + headers: { Accept: "application/json" }, + }; + }, + transformResponse: (response) => ({ + admin: response.data?.admin ?? { available: false, name: null }, + channels: response.data?.channels || [], + pagination: response.pagination || {}, + }), + }), + getChatConversations: builder.query({ + query: (_viewer) => ({ + url: "/chat/conversations", headers: { Accept: "application/json" }, }), - transformResponse: (response) => response.data ?? null, + transformResponse: (response) => response.data || [], }), - startSupportConversation: builder.mutation({ - query: () => ({ - url: "/chat/support", + startChatTarget: builder.mutation({ + query: (body) => ({ + url: "/chat/start-target", method: "POST", + body, headers: { Accept: "application/json" }, }), transformResponse: (response) => response.data, @@ -47,8 +67,10 @@ export const chatApi = baseApi.injectEndpoints({ }); export const { - useGetSupportConversationQuery, - useStartSupportConversationMutation, + useGetChatTargetsQuery, + useLazyGetChatTargetsQuery, + useGetChatConversationsQuery, + useStartChatTargetMutation, useLazyGetChatMessagesQuery, useSendChatMessageMutation, useReadChatMutation, diff --git a/src/components/ChatWidget/ChatWidget.module.scss b/src/components/ChatWidget/ChatWidget.module.scss index dff3d4f..ddb8108 100644 --- a/src/components/ChatWidget/ChatWidget.module.scss +++ b/src/components/ChatWidget/ChatWidget.module.scss @@ -41,6 +41,183 @@ padding: 4px; } +.headerTitle { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0 8px; +} + +.picker { + flex: 1; + overflow-y: auto; + background: #f8fafc; + display: flex; + flex-direction: column; + min-height: 0; +} + +.adminRow { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + border: 0; + border-bottom: 1px solid #e2e8f0; + background: linear-gradient(180deg, #fff5f5 0%, #fff 100%); + padding: 14px 16px; + cursor: pointer; + text-align: left; +} + +.adminRow:hover { + background: #fff1f1; +} + +.adminIcon { + width: 40px; + height: 40px; + border-radius: 12px; + background: #d32824; + color: #fff; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} + +.adminCopy { + display: flex; + flex-direction: column; + min-width: 0; + flex: 1; +} + +.adminCopy strong { + font-size: 14px; + color: #0f172a; +} + +.adminCopy small { + font-size: 12px; + color: #64748b; +} + +.sectionLabel { + margin: 0; + padding: 12px 16px 6px; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + color: #64748b; +} + +.search { + display: flex; + align-items: center; + gap: 8px; + margin: 0 16px 8px; + padding: 8px 10px; + background: #fff; + border: 1px solid #e2e8f0; + border-radius: 10px; + color: #94a3b8; +} + +.search input { + flex: 1; + border: 0; + outline: none; + font: inherit; + font-size: 13px; + background: transparent; + color: #0f172a; +} + +.channelList { + display: flex; + flex-direction: column; +} + +.channelRow { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + border: 0; + border-bottom: 1px solid #f1f5f9; + background: #fff; + padding: 10px 16px; + cursor: pointer; + text-align: left; +} + +.channelRow:hover { + background: #f8fafc; +} + +.avatar, +.avatarFallback { + width: 36px; + height: 36px; + border-radius: 10px; + object-fit: cover; + flex-shrink: 0; + background: #e2e8f0; +} + +.avatarFallback { + display: flex; + align-items: center; + justify-content: center; + color: #64748b; +} + +.channelName { + flex: 1; + min-width: 0; + font-size: 14px; + font-weight: 600; + color: #0f172a; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.rowBadge { + min-width: 18px; + height: 18px; + padding: 0 6px; + border-radius: 999px; + background: #d32824; + color: #fff; + font-size: 11px; + font-weight: 700; + line-height: 18px; + text-align: center; +} + +.loadMore { + margin: 8px 16px 16px; + border: 1px solid #e2e8f0; + background: #fff; + border-radius: 10px; + padding: 8px 12px; + font: inherit; + font-size: 13px; + font-weight: 600; + color: #334155; + cursor: pointer; +} + +.loadMore:disabled { + opacity: 0.6; + cursor: not-allowed; +} + .messages { flex: 1; overflow-y: auto; diff --git a/src/components/ChatWidget/index.jsx b/src/components/ChatWidget/index.jsx index 6800e85..34bca39 100644 --- a/src/components/ChatWidget/index.jsx +++ b/src/components/ChatWidget/index.jsx @@ -1,13 +1,14 @@ -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; -import { MessageCircle, Send, X } from "lucide-react"; +import { ArrowLeft, MessageCircle, Search, Send, Shield, X } from "lucide-react"; import { useAuth } from "../../context/authContext"; import { - useGetSupportConversationQuery, + useGetChatConversationsQuery, useLazyGetChatMessagesQuery, + useLazyGetChatTargetsQuery, useReadChatMutation, useSendChatMessageMutation, - useStartSupportConversationMutation, + useStartChatTargetMutation, } from "../../app/api/chatApi"; import { getChatEcho, leaveChatChannel } from "../../utils/echo"; import styles from "./ChatWidget.module.scss"; @@ -19,54 +20,117 @@ function formatTime(value) { return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); } -export default function ChatWidget() { +function unreadFor(conversations, threadKey) { + const match = conversations.find((item) => item.thread_key === threadKey); + return match?.unread_count || 0; +} + +function ChatWidget() { const { t } = useTranslation(); const { authToken, guestToken } = useAuth(); - const ready = Boolean(authToken || guestToken); + const identity = authToken || guestToken; + const ready = Boolean(identity); const [open, setOpen] = useState(false); + const [screen, setScreen] = useState("picker"); 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 [searchInput, setSearchInput] = useState(""); + const [search, setSearch] = useState(""); + const [channels, setChannels] = useState([]); + const [admin, setAdmin] = useState({ available: false, name: null }); + const [targetsNext, setTargetsNext] = useState(null); + const [loadingTargets, setLoadingTargets] = useState(false); const listRef = useRef(null); const subscribedId = useRef(null); const openRef = useRef(open); openRef.current = open; + const screenRef = useRef(screen); + screenRef.current = screen; + const conversationRef = useRef(conversation); + conversationRef.current = conversation; const pendingPrepend = useRef(false); + const requestGen = useRef(0); - const { data: existing, error } = useGetSupportConversationQuery(undefined, { + const { data: inboxData, error: inboxError } = useGetChatConversationsQuery(identity, { skip: !ready || hidden, - pollingInterval: open ? 0 : 15000, + pollingInterval: 15000, }); - const [startSupport] = useStartSupportConversationMutation(); + const inbox = Array.isArray(inboxData) ? inboxData : []; + const [fetchTargets] = useLazyGetChatTargetsQuery(); + const [startTarget] = useStartChatTargetMutation(); const [fetchMessages] = useLazyGetChatMessagesQuery(); const [sendMessage, { isLoading: sending }] = useSendChatMessageMutation(); const [markRead] = useReadChatMutation(); + const unread = useMemo( + () => inbox.reduce((sum, item) => sum + (item.unread_count || 0), 0), + [inbox] + ); + useEffect(() => { - const status = error?.status; - if (status === 403 || status === 422) { + const timer = setTimeout(() => { + setSearch(searchInput.trim()); + }, 300); + return () => clearTimeout(timer); + }, [searchInput]); + + useEffect(() => { + requestGen.current += 1; + setHidden(false); + setOpen(false); + setScreen("picker"); + setConversation(null); + setMessages([]); + setNextPage(null); + setDraft(""); + setLoadingThread(false); + setSearchInput(""); + setSearch(""); + setChannels([]); + setAdmin({ available: false, name: null }); + setTargetsNext(null); + }, [identity]); + + useEffect(() => { + if (inboxError?.status === 403) { setHidden(true); } - }, [error]); + }, [inboxError]); + + const loadTargets = useCallback( + async (page = 1, append = false) => { + setLoadingTargets(true); + try { + const result = await fetchTargets({ q: search, page, perPage: 20, viewer: identity }).unwrap(); + setAdmin(result.admin || { available: false, name: null }); + setChannels((current) => (append ? [...current, ...(result.channels || [])] : result.channels || [])); + setTargetsNext(result.pagination?.next_page_url ? page + 1 : null); + } catch (err) { + if (err?.status === 403) { + setHidden(true); + } + } finally { + setLoadingTargets(false); + } + }, + [fetchTargets, identity, search] + ); useEffect(() => { - if (!existing) { + if (!ready || hidden) { return; } - setConversation(existing); - if (!open) { - setUnread(existing.unread_count || 0); - } - }, [existing, open]); + loadTargets(1, false); + }, [hidden, loadTargets, ready]); useLayoutEffect(() => { - if (!open || loadingThread || pendingPrepend.current) { + if (!open || screen !== "thread" || loadingThread || pendingPrepend.current) { return; } const el = listRef.current; @@ -74,7 +138,7 @@ export default function ChatWidget() { return; } el.scrollTop = el.scrollHeight; - }, [messages, open, loadingThread]); + }, [loadingThread, messages, open, screen]); const appendMessage = useCallback((message) => { setMessages((current) => { @@ -86,8 +150,11 @@ export default function ChatWidget() { }, []); const loadPage = useCallback( - async (conversationId, page = 1, prepend = false) => { + async (conversationId, page = 1, prepend = false, gen = requestGen.current) => { const result = await fetchMessages({ conversationId, page, perPage: 50 }).unwrap(); + if (gen !== requestGen.current) { + return []; + } const items = (result.items || []).slice().reverse(); setNextPage(result.pagination?.next_page_url ? page + 1 : null); setMessages((current) => { @@ -102,31 +169,57 @@ export default function ChatWidget() { [fetchMessages] ); - const openThread = useCallback(async () => { - setOpen(true); - setLoadingThread(true); - try { - let current = conversation; - if (!current?.id) { - current = await startSupport().unwrap(); + const openThread = useCallback( + async (body) => { + const gen = ++requestGen.current; + setScreen("thread"); + setLoadingThread(true); + setMessages([]); + setDraft(""); + setNextPage(null); + try { + const current = await startTarget(body).unwrap(); + if (gen !== requestGen.current) { + return; + } setConversation(current); + await loadPage(current.id, 1, false, gen); + if (gen !== requestGen.current) { + return; + } + await markRead(current.id); + } catch (err) { + if (gen !== requestGen.current) { + return; + } + if (err?.status === 403) { + setHidden(true); + setOpen(false); + } + setScreen("picker"); + setConversation(null); + } finally { + if (gen === requestGen.current) { + setLoadingThread(false); + } } - 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]); + }, + [loadPage, markRead, startTarget] + ); + + const backToPicker = useCallback(() => { + requestGen.current += 1; + setScreen("picker"); + setConversation(null); + setMessages([]); + setDraft(""); + setNextPage(null); + setLoadingThread(false); + }, []); useEffect(() => { const conversationId = conversation?.id; - if (!conversationId || hidden) { + if (!conversationId || hidden || screen !== "thread") { return undefined; } @@ -141,12 +234,12 @@ export default function ChatWidget() { subscribedId.current = conversationId; echo.private(`chat.${conversationId}`).listen(".message.sent", (payload) => { + if (conversationRef.current?.id !== conversationId || screenRef.current !== "thread") { + return; + } appendMessage(payload); if (openRef.current) { markRead(conversationId); - setUnread(0); - } else { - setUnread((count) => count + 1); } }); @@ -154,20 +247,27 @@ export default function ChatWidget() { leaveChatChannel(conversationId); subscribedId.current = null; }; - }, [appendMessage, conversation?.id, hidden, markRead]); + }, [appendMessage, conversation?.id, hidden, markRead, screen]); useEffect(() => { - if (!open || !conversation?.id || getChatEcho()) { + if (!open || screen !== "thread" || !conversation?.id || getChatEcho()) { return undefined; } + const conversationId = conversation.id; const timer = setInterval(async () => { + if (requestGen.current && conversationRef.current?.id !== conversationId) { + return; + } try { const result = await fetchMessages({ - conversationId: conversation.id, + conversationId, page: 1, perPage: 50, }).unwrap(); + if (conversationRef.current?.id !== conversationId) { + return; + } const items = (result.items || []).slice().reverse(); setMessages((current) => { const known = new Set(current.map((item) => item.id)); @@ -180,7 +280,7 @@ export default function ChatWidget() { }, 4000); return () => clearInterval(timer); - }, [conversation?.id, fetchMessages, open]); + }, [conversation?.id, fetchMessages, open, screen]); const handleScroll = async () => { if (!listRef.current || !nextPage || !conversation?.id || loadingThread) { @@ -203,89 +303,182 @@ export default function ChatWidget() { const handleSend = async (event) => { event.preventDefault(); const body = draft.trim(); - if (!body || sending) { + if (!body || sending || !conversation?.id) { return; } try { - let current = conversation; - if (!current?.id) { - current = await startSupport().unwrap(); - setConversation(current); - } const message = await sendMessage({ - conversationId: current.id, + conversationId: conversation.id, body, }).unwrap(); appendMessage(message); setDraft(""); } catch (err) { - if (err?.status === 403 || err?.status === 422) { + if (err?.status === 403) { setHidden(true); } } }; - if (!ready || hidden) { + const emptyCatalog = !admin.available && channels.length === 0 && !search && !loadingTargets; + const nothingToShow = emptyCatalog && inbox.length === 0; + + if (!ready || hidden || (nothingToShow && !open)) { return null; } - const otherName = conversation?.user?.name || t("chat.title"); + const otherName = conversation?.channel?.name || t("chat.title"); const otherId = conversation?.user?.id; + const adminUnread = unreadFor(inbox, "admin"); return (
{open && (
-
- {otherName} - -
-
- {loadingThread &&

{t("chat.loading")}

} - {!loadingThread && messages.length === 0 && ( -

{t("chat.empty")}

- )} - {messages.map((message) => { - const mine = otherId ? message.user?.id !== otherId : true; - return ( -
-
{message.body}
- {formatTime(message.created_at)} + {screen === "picker" ? ( + <> +
+ {t("chat.title")} + +
+
+ {admin.available && ( + + )} + +

{t("chat.channels")}

+ + + {loadingTargets && channels.length === 0 && ( +

{t("chat.loading")}

+ )} + {!loadingTargets && channels.length === 0 && ( +

{search ? t("chat.noResults") : t("chat.noChannels")}

+ )} + +
+ {channels.map((channel) => { + const count = unreadFor(inbox, `channel:${channel.id}`); + return ( + + ); + })}
- ); - })} -
-
-