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:
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 (
|
||||
<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>
|
||||
{screen === "picker" ? (
|
||||
<>
|
||||
<div className={styles.header}>
|
||||
<span>{t("chat.title")}</span>
|
||||
<button type="button" className={styles.iconBtn} onClick={() => setOpen(false)} aria-label={t("chat.close")}>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<div className={styles.picker}>
|
||||
{admin.available && (
|
||||
<button type="button" className={styles.adminRow} onClick={() => openThread({ admin: true })}>
|
||||
<span className={styles.adminIcon}>
|
||||
<Shield size={18} />
|
||||
</span>
|
||||
<span className={styles.adminCopy}>
|
||||
<strong>{t("chat.admin")}</strong>
|
||||
<small>{ t("chat.adminSubtitle")}</small>
|
||||
</span>
|
||||
{adminUnread > 0 && (
|
||||
<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>
|
||||
<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>
|
||||
|
||||
{targetsNext && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.loadMore}
|
||||
disabled={loadingTargets}
|
||||
onClick={() => loadTargets(targetsNext, true)}
|
||||
>
|
||||
{t("chat.loadMore")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.header}>
|
||||
<button type="button" className={styles.iconBtn} onClick={backToPicker} aria-label={t("chat.back")}>
|
||||
<ArrowLeft size={18} />
|
||||
</button>
|
||||
<span className={styles.headerTitle}>{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() || !conversation?.id} aria-label={t("chat.send")}>
|
||||
<Send size={16} />
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={styles.fab}
|
||||
onClick={() => (open ? setOpen(false) : openThread())}
|
||||
onClick={() => {
|
||||
if (open) {
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
setScreen("picker");
|
||||
setOpen(true);
|
||||
}}
|
||||
aria-label={t("chat.title")}
|
||||
>
|
||||
{open ? <X size={22} /> : <MessageCircle size={22} />}
|
||||
@@ -294,3 +487,8 @@ export default function ChatWidget() {
|
||||
</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.",
|
||||
loading: "Loading...",
|
||||
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: "Напишите сообщение, и мы скоро ответим.",
|
||||
loading: "Загрузка...",
|
||||
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!",
|
||||
},
|
||||
chat: {
|
||||
title: "Goldaw",
|
||||
title: "Admin",
|
||||
placeholder: "Hat ýazyň...",
|
||||
send: "Ugrat",
|
||||
empty: "Hat ýazyň, biz gysga wagtda jogap bereris.",
|
||||
loading: "Ýüklenýär...",
|
||||
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