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.
This commit is contained in:
1 parent
53cb864863
commit
347ec3536d
6 files changed
+532
-111
No files matched your search
+31
-9
@@ -2,17 +2,37 @@ import { baseApi } from "./baseApi";
|
|||||||
|
|
||||||
export const chatApi = baseApi.injectEndpoints({
|
export const chatApi = baseApi.injectEndpoints({
|
||||||
endpoints: (builder) => ({
|
endpoints: (builder) => ({
|
||||||
getSupportConversation: builder.query({
|
getChatTargets: builder.query({
|
||||||
query: () => ({
|
query: ({ q = "", page = 1, perPage = 20, viewer: _viewer } = {}) => {
|
||||||
url: "/chat/support",
|
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" },
|
headers: { Accept: "application/json" },
|
||||||
}),
|
}),
|
||||||
transformResponse: (response) => response.data ?? null,
|
transformResponse: (response) => response.data || [],
|
||||||
}),
|
}),
|
||||||
startSupportConversation: builder.mutation({
|
startChatTarget: builder.mutation({
|
||||||
query: () => ({
|
query: (body) => ({
|
||||||
url: "/chat/support",
|
url: "/chat/start-target",
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
body,
|
||||||
headers: { Accept: "application/json" },
|
headers: { Accept: "application/json" },
|
||||||
}),
|
}),
|
||||||
transformResponse: (response) => response.data,
|
transformResponse: (response) => response.data,
|
||||||
@@ -47,8 +67,10 @@ export const chatApi = baseApi.injectEndpoints({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const {
|
export const {
|
||||||
useGetSupportConversationQuery,
|
useGetChatTargetsQuery,
|
||||||
useStartSupportConversationMutation,
|
useLazyGetChatTargetsQuery,
|
||||||
|
useGetChatConversationsQuery,
|
||||||
|
useStartChatTargetMutation,
|
||||||
useLazyGetChatMessagesQuery,
|
useLazyGetChatMessagesQuery,
|
||||||
useSendChatMessageMutation,
|
useSendChatMessageMutation,
|
||||||
useReadChatMutation,
|
useReadChatMutation,
|
||||||
|
|||||||
@@ -41,6 +41,183 @@
|
|||||||
padding: 4px;
|
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 {
|
.messages {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
|
|||||||
+299
-101
@@ -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 { 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 { useAuth } from "../../context/authContext";
|
||||||
import {
|
import {
|
||||||
useGetSupportConversationQuery,
|
useGetChatConversationsQuery,
|
||||||
useLazyGetChatMessagesQuery,
|
useLazyGetChatMessagesQuery,
|
||||||
|
useLazyGetChatTargetsQuery,
|
||||||
useReadChatMutation,
|
useReadChatMutation,
|
||||||
useSendChatMessageMutation,
|
useSendChatMessageMutation,
|
||||||
useStartSupportConversationMutation,
|
useStartChatTargetMutation,
|
||||||
} from "../../app/api/chatApi";
|
} from "../../app/api/chatApi";
|
||||||
import { getChatEcho, leaveChatChannel } from "../../utils/echo";
|
import { getChatEcho, leaveChatChannel } from "../../utils/echo";
|
||||||
import styles from "./ChatWidget.module.scss";
|
import styles from "./ChatWidget.module.scss";
|
||||||
@@ -19,54 +20,117 @@ function formatTime(value) {
|
|||||||
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
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 { t } = useTranslation();
|
||||||
const { authToken, guestToken } = useAuth();
|
const { authToken, guestToken } = useAuth();
|
||||||
const ready = Boolean(authToken || guestToken);
|
const identity = authToken || guestToken;
|
||||||
|
const ready = Boolean(identity);
|
||||||
|
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
const [screen, setScreen] = useState("picker");
|
||||||
const [hidden, setHidden] = useState(false);
|
const [hidden, setHidden] = useState(false);
|
||||||
const [conversation, setConversation] = useState(null);
|
const [conversation, setConversation] = useState(null);
|
||||||
const [messages, setMessages] = useState([]);
|
const [messages, setMessages] = useState([]);
|
||||||
const [nextPage, setNextPage] = useState(null);
|
const [nextPage, setNextPage] = useState(null);
|
||||||
const [draft, setDraft] = useState("");
|
const [draft, setDraft] = useState("");
|
||||||
const [unread, setUnread] = useState(0);
|
|
||||||
const [loadingThread, setLoadingThread] = useState(false);
|
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 listRef = useRef(null);
|
||||||
const subscribedId = useRef(null);
|
const subscribedId = useRef(null);
|
||||||
const openRef = useRef(open);
|
const openRef = useRef(open);
|
||||||
openRef.current = open;
|
openRef.current = open;
|
||||||
|
const screenRef = useRef(screen);
|
||||||
|
screenRef.current = screen;
|
||||||
|
const conversationRef = useRef(conversation);
|
||||||
|
conversationRef.current = conversation;
|
||||||
const pendingPrepend = useRef(false);
|
const pendingPrepend = useRef(false);
|
||||||
|
const requestGen = useRef(0);
|
||||||
|
|
||||||
const { data: existing, error } = useGetSupportConversationQuery(undefined, {
|
const { data: inboxData, error: inboxError } = useGetChatConversationsQuery(identity, {
|
||||||
skip: !ready || hidden,
|
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 [fetchMessages] = useLazyGetChatMessagesQuery();
|
||||||
const [sendMessage, { isLoading: sending }] = useSendChatMessageMutation();
|
const [sendMessage, { isLoading: sending }] = useSendChatMessageMutation();
|
||||||
const [markRead] = useReadChatMutation();
|
const [markRead] = useReadChatMutation();
|
||||||
|
|
||||||
|
const unread = useMemo(
|
||||||
|
() => inbox.reduce((sum, item) => sum + (item.unread_count || 0), 0),
|
||||||
|
[inbox]
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const status = error?.status;
|
const timer = setTimeout(() => {
|
||||||
if (status === 403 || status === 422) {
|
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);
|
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(() => {
|
useEffect(() => {
|
||||||
if (!existing) {
|
if (!ready || hidden) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setConversation(existing);
|
loadTargets(1, false);
|
||||||
if (!open) {
|
}, [hidden, loadTargets, ready]);
|
||||||
setUnread(existing.unread_count || 0);
|
|
||||||
}
|
|
||||||
}, [existing, open]);
|
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (!open || loadingThread || pendingPrepend.current) {
|
if (!open || screen !== "thread" || loadingThread || pendingPrepend.current) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const el = listRef.current;
|
const el = listRef.current;
|
||||||
@@ -74,7 +138,7 @@ export default function ChatWidget() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
el.scrollTop = el.scrollHeight;
|
el.scrollTop = el.scrollHeight;
|
||||||
}, [messages, open, loadingThread]);
|
}, [loadingThread, messages, open, screen]);
|
||||||
|
|
||||||
const appendMessage = useCallback((message) => {
|
const appendMessage = useCallback((message) => {
|
||||||
setMessages((current) => {
|
setMessages((current) => {
|
||||||
@@ -86,8 +150,11 @@ export default function ChatWidget() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const loadPage = useCallback(
|
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();
|
const result = await fetchMessages({ conversationId, page, perPage: 50 }).unwrap();
|
||||||
|
if (gen !== requestGen.current) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
const items = (result.items || []).slice().reverse();
|
const items = (result.items || []).slice().reverse();
|
||||||
setNextPage(result.pagination?.next_page_url ? page + 1 : null);
|
setNextPage(result.pagination?.next_page_url ? page + 1 : null);
|
||||||
setMessages((current) => {
|
setMessages((current) => {
|
||||||
@@ -102,31 +169,57 @@ export default function ChatWidget() {
|
|||||||
[fetchMessages]
|
[fetchMessages]
|
||||||
);
|
);
|
||||||
|
|
||||||
const openThread = useCallback(async () => {
|
const openThread = useCallback(
|
||||||
setOpen(true);
|
async (body) => {
|
||||||
setLoadingThread(true);
|
const gen = ++requestGen.current;
|
||||||
try {
|
setScreen("thread");
|
||||||
let current = conversation;
|
setLoadingThread(true);
|
||||||
if (!current?.id) {
|
setMessages([]);
|
||||||
current = await startSupport().unwrap();
|
setDraft("");
|
||||||
|
setNextPage(null);
|
||||||
|
try {
|
||||||
|
const current = await startTarget(body).unwrap();
|
||||||
|
if (gen !== requestGen.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
setConversation(current);
|
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);
|
[loadPage, markRead, startTarget]
|
||||||
setUnread(0);
|
);
|
||||||
} catch (err) {
|
|
||||||
if (err?.status === 403 || err?.status === 422) {
|
const backToPicker = useCallback(() => {
|
||||||
setHidden(true);
|
requestGen.current += 1;
|
||||||
setOpen(false);
|
setScreen("picker");
|
||||||
}
|
setConversation(null);
|
||||||
} finally {
|
setMessages([]);
|
||||||
setLoadingThread(false);
|
setDraft("");
|
||||||
}
|
setNextPage(null);
|
||||||
}, [conversation, loadPage, markRead, startSupport]);
|
setLoadingThread(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const conversationId = conversation?.id;
|
const conversationId = conversation?.id;
|
||||||
if (!conversationId || hidden) {
|
if (!conversationId || hidden || screen !== "thread") {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,12 +234,12 @@ export default function ChatWidget() {
|
|||||||
|
|
||||||
subscribedId.current = conversationId;
|
subscribedId.current = conversationId;
|
||||||
echo.private(`chat.${conversationId}`).listen(".message.sent", (payload) => {
|
echo.private(`chat.${conversationId}`).listen(".message.sent", (payload) => {
|
||||||
|
if (conversationRef.current?.id !== conversationId || screenRef.current !== "thread") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
appendMessage(payload);
|
appendMessage(payload);
|
||||||
if (openRef.current) {
|
if (openRef.current) {
|
||||||
markRead(conversationId);
|
markRead(conversationId);
|
||||||
setUnread(0);
|
|
||||||
} else {
|
|
||||||
setUnread((count) => count + 1);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -154,20 +247,27 @@ export default function ChatWidget() {
|
|||||||
leaveChatChannel(conversationId);
|
leaveChatChannel(conversationId);
|
||||||
subscribedId.current = null;
|
subscribedId.current = null;
|
||||||
};
|
};
|
||||||
}, [appendMessage, conversation?.id, hidden, markRead]);
|
}, [appendMessage, conversation?.id, hidden, markRead, screen]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open || !conversation?.id || getChatEcho()) {
|
if (!open || screen !== "thread" || !conversation?.id || getChatEcho()) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const conversationId = conversation.id;
|
||||||
const timer = setInterval(async () => {
|
const timer = setInterval(async () => {
|
||||||
|
if (requestGen.current && conversationRef.current?.id !== conversationId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const result = await fetchMessages({
|
const result = await fetchMessages({
|
||||||
conversationId: conversation.id,
|
conversationId,
|
||||||
page: 1,
|
page: 1,
|
||||||
perPage: 50,
|
perPage: 50,
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
|
if (conversationRef.current?.id !== conversationId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const items = (result.items || []).slice().reverse();
|
const items = (result.items || []).slice().reverse();
|
||||||
setMessages((current) => {
|
setMessages((current) => {
|
||||||
const known = new Set(current.map((item) => item.id));
|
const known = new Set(current.map((item) => item.id));
|
||||||
@@ -180,7 +280,7 @@ export default function ChatWidget() {
|
|||||||
}, 4000);
|
}, 4000);
|
||||||
|
|
||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, [conversation?.id, fetchMessages, open]);
|
}, [conversation?.id, fetchMessages, open, screen]);
|
||||||
|
|
||||||
const handleScroll = async () => {
|
const handleScroll = async () => {
|
||||||
if (!listRef.current || !nextPage || !conversation?.id || loadingThread) {
|
if (!listRef.current || !nextPage || !conversation?.id || loadingThread) {
|
||||||
@@ -203,89 +303,182 @@ export default function ChatWidget() {
|
|||||||
const handleSend = async (event) => {
|
const handleSend = async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const body = draft.trim();
|
const body = draft.trim();
|
||||||
if (!body || sending) {
|
if (!body || sending || !conversation?.id) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let current = conversation;
|
|
||||||
if (!current?.id) {
|
|
||||||
current = await startSupport().unwrap();
|
|
||||||
setConversation(current);
|
|
||||||
}
|
|
||||||
const message = await sendMessage({
|
const message = await sendMessage({
|
||||||
conversationId: current.id,
|
conversationId: conversation.id,
|
||||||
body,
|
body,
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
appendMessage(message);
|
appendMessage(message);
|
||||||
setDraft("");
|
setDraft("");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err?.status === 403 || err?.status === 422) {
|
if (err?.status === 403) {
|
||||||
setHidden(true);
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const otherName = conversation?.user?.name || t("chat.title");
|
const otherName = conversation?.channel?.name || t("chat.title");
|
||||||
const otherId = conversation?.user?.id;
|
const otherId = conversation?.user?.id;
|
||||||
|
const adminUnread = unreadFor(inbox, "admin");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.wrap}>
|
<div className={styles.wrap}>
|
||||||
{open && (
|
{open && (
|
||||||
<div className={styles.panel} role="dialog" aria-label={t("chat.title")}>
|
<div className={styles.panel} role="dialog" aria-label={t("chat.title")}>
|
||||||
<div className={styles.header}>
|
{screen === "picker" ? (
|
||||||
<span>{otherName}</span>
|
<>
|
||||||
<button type="button" className={styles.iconBtn} onClick={() => setOpen(false)} aria-label={t("chat.close")}>
|
<div className={styles.header}>
|
||||||
<X size={18} />
|
<span>{t("chat.title")}</span>
|
||||||
</button>
|
<button type="button" className={styles.iconBtn} onClick={() => setOpen(false)} aria-label={t("chat.close")}>
|
||||||
</div>
|
<X size={18} />
|
||||||
<div className={styles.messages} ref={listRef} onScroll={handleScroll}>
|
</button>
|
||||||
{loadingThread && <p className={styles.empty}>{t("chat.loading")}</p>}
|
</div>
|
||||||
{!loadingThread && messages.length === 0 && (
|
<div className={styles.picker}>
|
||||||
<p className={styles.empty}>{t("chat.empty")}</p>
|
{admin.available && (
|
||||||
)}
|
<button type="button" className={styles.adminRow} onClick={() => openThread({ admin: true })}>
|
||||||
{messages.map((message) => {
|
<span className={styles.adminIcon}>
|
||||||
const mine = otherId ? message.user?.id !== otherId : true;
|
<Shield size={18} />
|
||||||
return (
|
</span>
|
||||||
<div
|
<span className={styles.adminCopy}>
|
||||||
key={message.id}
|
<strong>{t("chat.admin")}</strong>
|
||||||
className={`${styles.bubble} ${mine ? styles.out : styles.in}`}
|
<small>{ t("chat.adminSubtitle")}</small>
|
||||||
>
|
</span>
|
||||||
<div>{message.body}</div>
|
{adminUnread > 0 && (
|
||||||
<span>{formatTime(message.created_at)}</span>
|
<span className={styles.rowBadge}>{adminUnread > 99 ? "99+" : adminUnread}</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className={styles.sectionLabel}>{t("chat.channels")}</p>
|
||||||
|
<label className={styles.search}>
|
||||||
|
<Search size={14} />
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
value={searchInput}
|
||||||
|
onChange={(event) => setSearchInput(event.target.value)}
|
||||||
|
placeholder={t("chat.search")}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{loadingTargets && channels.length === 0 && (
|
||||||
|
<p className={styles.empty}>{t("chat.loading")}</p>
|
||||||
|
)}
|
||||||
|
{!loadingTargets && channels.length === 0 && (
|
||||||
|
<p className={styles.empty}>{search ? t("chat.noResults") : t("chat.noChannels")}</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className={styles.channelList}>
|
||||||
|
{channels.map((channel) => {
|
||||||
|
const count = unreadFor(inbox, `channel:${channel.id}`);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={channel.id}
|
||||||
|
type="button"
|
||||||
|
className={styles.channelRow}
|
||||||
|
onClick={() => openThread({ channel_id: channel.id })}
|
||||||
|
>
|
||||||
|
{channel.image ? (
|
||||||
|
<img src={channel.image} alt="" className={styles.avatar} />
|
||||||
|
) : (
|
||||||
|
<span className={styles.avatarFallback}>
|
||||||
|
<MessageCircle size={16} />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className={styles.channelName}>{channel.name}</span>
|
||||||
|
{count > 0 && (
|
||||||
|
<span className={styles.rowBadge}>{count > 99 ? "99+" : count}</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
);
|
|
||||||
})}
|
{targetsNext && (
|
||||||
</div>
|
<button
|
||||||
<form className={styles.composer} onSubmit={handleSend}>
|
type="button"
|
||||||
<textarea
|
className={styles.loadMore}
|
||||||
value={draft}
|
disabled={loadingTargets}
|
||||||
onChange={(event) => setDraft(event.target.value)}
|
onClick={() => loadTargets(targetsNext, true)}
|
||||||
placeholder={t("chat.placeholder")}
|
>
|
||||||
rows={1}
|
{t("chat.loadMore")}
|
||||||
maxLength={5000}
|
</button>
|
||||||
onKeyDown={(event) => {
|
)}
|
||||||
if (event.key === "Enter" && !event.shiftKey) {
|
</div>
|
||||||
event.preventDefault();
|
</>
|
||||||
handleSend(event);
|
) : (
|
||||||
}
|
<>
|
||||||
}}
|
<div className={styles.header}>
|
||||||
/>
|
<button type="button" className={styles.iconBtn} onClick={backToPicker} aria-label={t("chat.back")}>
|
||||||
<button type="submit" disabled={sending || !draft.trim()} aria-label={t("chat.send")}>
|
<ArrowLeft size={18} />
|
||||||
<Send size={16} />
|
</button>
|
||||||
</button>
|
<span className={styles.headerTitle}>{otherName}</span>
|
||||||
</form>
|
<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() || !conversation?.id} aria-label={t("chat.send")}>
|
||||||
|
<Send size={16} />
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={styles.fab}
|
className={styles.fab}
|
||||||
onClick={() => (open ? setOpen(false) : openThread())}
|
onClick={() => {
|
||||||
|
if (open) {
|
||||||
|
setOpen(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setScreen("picker");
|
||||||
|
setOpen(true);
|
||||||
|
}}
|
||||||
aria-label={t("chat.title")}
|
aria-label={t("chat.title")}
|
||||||
>
|
>
|
||||||
{open ? <X size={22} /> : <MessageCircle size={22} />}
|
{open ? <X size={22} /> : <MessageCircle size={22} />}
|
||||||
@@ -294,3 +487,8 @@ export default function ChatWidget() {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default function ChatWidgetHost() {
|
||||||
|
const { authToken, guestToken } = useAuth();
|
||||||
|
return <ChatWidget key={authToken || guestToken || "anon"} />;
|
||||||
|
}
|
||||||
@@ -238,5 +238,13 @@ export default {
|
|||||||
empty: "Send a message and we will reply soon.",
|
empty: "Send a message and we will reply soon.",
|
||||||
loading: "Loading...",
|
loading: "Loading...",
|
||||||
close: "Close",
|
close: "Close",
|
||||||
|
admin: "Admin",
|
||||||
|
adminSubtitle: "Site support",
|
||||||
|
channels: "Stores",
|
||||||
|
search: "Search stores...",
|
||||||
|
noChannels: "No stores available for chat.",
|
||||||
|
noResults: "No stores match your search.",
|
||||||
|
back: "Back",
|
||||||
|
loadMore: "Load more",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -236,5 +236,13 @@ export default {
|
|||||||
empty: "Напишите сообщение, и мы скоро ответим.",
|
empty: "Напишите сообщение, и мы скоро ответим.",
|
||||||
loading: "Загрузка...",
|
loading: "Загрузка...",
|
||||||
close: "Закрыть",
|
close: "Закрыть",
|
||||||
|
admin: "Админ",
|
||||||
|
adminSubtitle: "Поддержка сайта",
|
||||||
|
channels: "Магазины",
|
||||||
|
search: "Поиск магазинов...",
|
||||||
|
noChannels: "Нет магазинов для чата.",
|
||||||
|
noResults: "Магазины не найдены.",
|
||||||
|
back: "Назад",
|
||||||
|
loadMore: "Ещё",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -232,11 +232,19 @@ export default {
|
|||||||
"Hyzmatdaşlyga elmydama açyk we pikirleri kabul edýäris. Pikiriňiz, soragyňyz ýa-da teklibiňiz barmy? Bize ýazyň - jogap bermäge şat bolarys!",
|
"Hyzmatdaşlyga elmydama açyk we pikirleri kabul edýäris. Pikiriňiz, soragyňyz ýa-da teklibiňiz barmy? Bize ýazyň - jogap bermäge şat bolarys!",
|
||||||
},
|
},
|
||||||
chat: {
|
chat: {
|
||||||
title: "Goldaw",
|
title: "Admin",
|
||||||
placeholder: "Hat ýazyň...",
|
placeholder: "Hat ýazyň...",
|
||||||
send: "Ugrat",
|
send: "Ugrat",
|
||||||
empty: "Hat ýazyň, biz gysga wagtda jogap bereris.",
|
empty: "Hat ýazyň, biz gysga wagtda jogap bereris.",
|
||||||
loading: "Ýüklenýär...",
|
loading: "Ýüklenýär...",
|
||||||
close: "Ýap",
|
close: "Ýap",
|
||||||
|
admin: "Admin",
|
||||||
|
adminSubtitle: "Saýt goldawy",
|
||||||
|
channels: "Dükanlar",
|
||||||
|
search: "Dükan gözle...",
|
||||||
|
noChannels: "Söhbet üçin dükan ýok.",
|
||||||
|
noResults: "Dükan tapylmady.",
|
||||||
|
back: "Yza",
|
||||||
|
loadMore: "Ýene",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
Reference in new issue
Block a user