some changes

This commit is contained in:
Mekan1206 committed 2026-08-15 17:51:20 +05:00
1 parent 8f3079801b
commit 6bcad79475
12 files changed
+933 -3

No files matched your search

+3 -1
View File
@@ -8,6 +8,7 @@ import PageLoader from "./components/Loader/pageLoader.jsx";
import ScrollToTop from "./components/ScrollToTop";
import { AuthProvider } from "./context/authContext.jsx";
import ChatWidget from "./components/ChatWidget";
function App() {
const [isLoading, setIsLoading] = useState(true);
@@ -46,8 +47,9 @@ function App() {
<>
<Router />
<ScrollToTop />
<ChatWidget />
{isVisible && (
<BackTop visibilityHeight={500} duration={800}>
<BackTop visibilityHeight={500} duration={800} style={{ right: 24, bottom: 96 }}>
<div
style={{
height: 40,
+55
View File
@@ -0,0 +1,55 @@
import { baseApi } from "./baseApi";
export const chatApi = baseApi.injectEndpoints({
endpoints: (builder) => ({
getSupportConversation: builder.query({
query: () => ({
url: "/chat/support",
headers: { Accept: "application/json" },
}),
transformResponse: (response) => response.data ?? null,
}),
startSupportConversation: builder.mutation({
query: () => ({
url: "/chat/support",
method: "POST",
headers: { Accept: "application/json" },
}),
transformResponse: (response) => response.data,
}),
getChatMessages: builder.query({
query: ({ conversationId, page = 1, perPage = 50 }) => ({
url: `/chat/conversations/${conversationId}/messages?perPage=${perPage}&page=${page}`,
headers: { Accept: "application/json" },
}),
transformResponse: (response) => ({
items: response.data || [],
pagination: response.pagination || {},
}),
}),
sendChatMessage: builder.mutation({
query: ({ conversationId, body }) => ({
url: `/chat/conversations/${conversationId}/messages`,
method: "POST",
body: { body },
headers: { Accept: "application/json" },
}),
transformResponse: (response) => response.data,
}),
readChat: builder.mutation({
query: (conversationId) => ({
url: `/chat/conversations/${conversationId}/read`,
method: "POST",
headers: { Accept: "application/json" },
}),
}),
}),
});
export const {
useGetSupportConversationQuery,
useStartSupportConversationMutation,
useLazyGetChatMessagesQuery,
useSendChatMessageMutation,
useReadChatMutation,
} = chatApi;
+52
View File
@@ -1,12 +1,64 @@
import { configureStore } from "@reduxjs/toolkit";
import { baseApi } from "./api/baseApi";
<<<<<<< Updated upstream
=======
import { categoriesApi } from "./api/categories";
import { searchApi } from "./api/searchApi";
import { cartApi } from "./api/cartApi";
import { brandsApi } from "./api/brandsApi";
import { collectionsApi } from "./api/collectionsApi";
import { favoritesApi } from "./api/favoritesApi";
import { legalPagesApi } from "./api/legalPagesApi";
import { locationApi } from "./api/locationApi";
import { orderApi } from "./api/orderApi";
import { mediaApi } from "./api/bannersApi";
import { reviewsApi } from "./api/reviewApi";
import { profileApi } from "./api/myProfileApi";
import { contactApi } from "./api/contactUs";
import { chatApi } from "./api/chatApi";
>>>>>>> Stashed changes
const store = configureStore({
reducer: {
[baseApi.reducerPath]: baseApi.reducer,
<<<<<<< Updated upstream
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(baseApi.middleware),
=======
[categoriesApi.reducerPath]: categoriesApi.reducer,
[searchApi.reducerPath]: searchApi.reducer,
[cartApi.reducerPath]: cartApi.reducer,
[brandsApi.reducerPath]: brandsApi.reducer,
[collectionsApi.reducerPath]: collectionsApi.reducer,
[favoritesApi.reducerPath]: favoritesApi.reducer,
[legalPagesApi.reducerPath]: legalPagesApi.reducer,
[locationApi.reducerPath]: locationApi.reducer,
[orderApi.reducerPath]: orderApi.reducer,
[mediaApi.reducerPath]: mediaApi.reducer,
[reviewsApi.reducerPath]: reviewsApi.reducer,
[profileApi.reducerPath]: profileApi.reducer,
[contactApi.reducerPath]: contactApi.reducer,
[chatApi.reducerPath]: chatApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(
baseApi.middleware,
categoriesApi.middleware,
searchApi.middleware,
brandsApi.middleware,
collectionsApi.middleware,
favoritesApi.middleware,
legalPagesApi.middleware,
locationApi.middleware,
orderApi.middleware,
reviewsApi.middleware,
mediaApi.middleware,
profileApi.middleware,
contactApi.middleware,
chatApi.middleware,
),
>>>>>>> Stashed changes
});
export default store;
@@ -0,0 +1,167 @@
.wrap {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 1100;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 12px;
}
.panel {
width: 380px;
max-width: calc(100vw - 32px);
height: 520px;
max-height: calc(100vh - 120px);
background: #fff;
border-radius: 16px;
box-shadow: 0 12px 40px rgba(15, 23, 42, 0.2);
display: flex;
flex-direction: column;
overflow: hidden;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 16px;
background: #d32824;
color: #fff;
font-weight: 700;
}
.iconBtn {
border: 0;
background: transparent;
color: #fff;
cursor: pointer;
display: flex;
padding: 4px;
}
.messages {
flex: 1;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 8px;
background: #f8fafc;
}
.empty {
margin: auto;
color: #94a3b8;
font-size: 13px;
text-align: center;
padding: 0 16px;
}
.bubble {
max-width: 80%;
padding: 8px 12px;
border-radius: 14px;
font-size: 14px;
line-height: 1.4;
white-space: pre-wrap;
word-break: break-word;
}
.bubble span {
display: block;
margin-top: 4px;
font-size: 11px;
opacity: 0.7;
}
.in {
align-self: flex-start;
background: #fff;
color: #0f172a;
}
.out {
align-self: flex-end;
background: #d32824;
color: #fff;
}
.composer {
display: flex;
gap: 8px;
padding: 10px 12px;
border-top: 1px solid #e2e8f0;
background: #fff;
}
.composer textarea {
flex: 1;
resize: none;
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 8px 10px;
font: inherit;
min-height: 40px;
max-height: 96px;
}
.composer button {
width: 40px;
border: 0;
border-radius: 10px;
background: #d32824;
color: #fff;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.composer button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.fab {
position: relative;
width: 56px;
height: 56px;
border: 0;
border-radius: 50%;
background: #d32824;
color: #fff;
cursor: pointer;
box-shadow: 0 8px 20px rgba(211, 40, 36, 0.35);
display: flex;
align-items: center;
justify-content: center;
}
.badge {
position: absolute;
top: -4px;
right: -4px;
min-width: 20px;
height: 20px;
padding: 0 6px;
border-radius: 999px;
background: #0f172a;
color: #fff;
font-size: 11px;
font-weight: 700;
line-height: 20px;
}
@media (max-width: 480px) {
.wrap {
right: 16px;
bottom: 16px;
}
.panel {
width: calc(100vw - 32px);
height: calc(100vh - 100px);
}
}
+296
View File
@@ -0,0 +1,296 @@
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>
);
}
+8
View File
@@ -231,4 +231,12 @@ export default {
about_paragraph4:
"We are always open to co-operation and welcome feedback. Do you have an idea, question or suggestion? Write to us - we will be happy to answer!",
},
chat: {
title: "Support",
placeholder: "Write a message...",
send: "Send",
empty: "Send a message and we will reply soon.",
loading: "Loading...",
close: "Close",
},
};
+8
View File
@@ -229,4 +229,12 @@ export default {
about_paragraph4:
"Мы всегда открыты к сотрудничеству и рады обратной связи. Есть идея, вопрос или предложение? Напишите нам — мы с удовольствием ответим!",
},
chat: {
title: "Поддержка",
placeholder: "Напишите сообщение...",
send: "Отправить",
empty: "Напишите сообщение, и мы скоро ответим.",
loading: "Загрузка...",
close: "Закрыть",
},
};
+8
View File
@@ -231,4 +231,12 @@ export default {
about_paragraph4:
"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",
placeholder: "Hat ýazyň...",
send: "Ugrat",
empty: "Hat ýazyň, biz gysga wagtda jogap bereris.",
loading: "Ýüklenýär...",
close: "Ýap",
},
};
+80
View File
@@ -0,0 +1,80 @@
import Echo from "laravel-echo";
import Pusher from "pusher-js";
let echoClient = null;
let echoToken = null;
function getToken() {
const authTokenCookie = document.cookie
.split("; ")
.find((row) => row.startsWith("authToken="));
const guestTokenCookie = document.cookie
.split("; ")
.find((row) => row.startsWith("guestToken="));
if (authTokenCookie) return authTokenCookie.split("=")[1];
if (localStorage.getItem("authToken")) return localStorage.getItem("authToken");
if (guestTokenCookie) return guestTokenCookie.split("=")[1];
if (localStorage.getItem("guestToken")) return localStorage.getItem("guestToken");
return null;
}
function apiOrigin() {
const url = import.meta.env.VITE_API_URL || "https://mm.com.tm/api/v1/";
return url.replace(/\/?api\/v1\/?$/, "");
}
export function getChatEcho() {
const key = import.meta.env.VITE_REVERB_APP_KEY;
const token = getToken();
if (!key || !token) {
return null;
}
if (echoClient && echoToken !== token) {
echoClient.disconnect();
echoClient = null;
}
if (echoClient) {
return echoClient;
}
window.Pusher = Pusher;
const scheme = import.meta.env.VITE_REVERB_SCHEME || "http";
const port = Number(import.meta.env.VITE_REVERB_PORT || (scheme === "https" ? 443 : 8080));
const host = import.meta.env.VITE_REVERB_HOST || "127.0.0.1";
echoToken = token;
echoClient = new Echo({
broadcaster: "reverb",
key,
wsHost: host,
wsPort: port,
wssPort: port,
forceTLS: scheme === "https",
enabledTransports: ["ws", "wss"],
disableStats: true,
Pusher,
authEndpoint: `${apiOrigin()}/broadcasting/auth`,
auth: {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
},
},
});
return echoClient;
}
export function leaveChatChannel(conversationId) {
if (!echoClient || !conversationId) {
return;
}
echoClient.leave(`chat.${conversationId}`);
}