8 Commits
5 changed files with 565 additions and 524 deletions
@@ -4,6 +4,7 @@ using System.Threading;
using System.Threading.Tasks;
using Knot.Contracts.Conversations.Application.Abstractions;
using Knot.Contracts.Conversations.Domain;
using Knot.Contracts.Messaging.Application.Abstractions;
using Knot.Modules.Conversations.Infrastructure.SignalR;
using Knot.Shared.Kernel;
using Knot.Shared.Kernel.Storage;
+4 -2
View File
@@ -194,7 +194,8 @@ const translations = {
clearChatConfirm: 'Очистить историю чата для себя? Собеседник сохранит свою историю.',
clearHistory: 'Очистить историю',
clearHistoryConfirm: 'Очистить историю?',
deleteChatConfirm: 'Удалить чат? Это действие нельзя отменить.',
deleteChatConfirm: 'Удалить чат? Это действие нельзя отменить. Чат будет удалён у всех участников.',
deleteGroupChatConfirm: 'Удалить чат? Это действие нельзя отменить. Чат будет удалён у всех участников.',
pinChat: 'Закрепить чат',
unpinChat: 'Открепить чат',
chatCleared: 'Очищено',
@@ -574,7 +575,8 @@ const translations = {
clearChatConfirm: 'Clear chat history for yourself? The other person will keep their history.',
clearHistory: 'Clear history',
clearHistoryConfirm: 'Clear history?',
deleteChatConfirm: 'Delete this chat? This action cannot be undone.',
deleteChatConfirm: 'Delete this chat? This action cannot be undone. The chat will be removed for all participants.',
deleteGroupChatConfirm: 'Delete this chat? This action cannot be undone. The chat will be removed for all participants.',
pinChat: 'Pin chat',
unpinChat: 'Unpin chat',
chatCleared: 'Chat cleared',
@@ -65,6 +65,8 @@ export default function ChatPage() {
const [activeTab, setActiveTab] = useState('chats');
const { t } = useLang();
const activeChat = useChatStore((state) => state.activeChat);
useEffect(() => {
groupCallOpenRef.current = groupCallOpen;
groupCallChatIdRef.current = groupCallChatId;
@@ -335,6 +337,16 @@ export default function ChatPage() {
};
}, [user?.id]);
// Join chat group when activeChat changes
useEffect(() => {
if (activeChat) {
const socket = getSocket();
if (socket) {
socket.emit('join_chat', activeChat);
}
}
}, [activeChat]);
const handleStartCall = (targetUser: UserBasic, type: 'voice' | 'video') => {
setCallTarget(targetUser);
setCallType(type);
@@ -371,8 +383,6 @@ export default function ChatPage() {
setGroupCallOpen(false);
};
const activeChat = useChatStore((state) => state.activeChat);
return (
<motion.div
initial={{ opacity: 0 }}
@@ -104,7 +104,7 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
// Wait a bit for React to render
setTimeout(() => {
if (!tryScroll()) {
NotificationStore.useNotificationStore.getState().addNotification('warning', (t as any)('messageNotFound') || 'Message not found');
NotificationStore.useNotificationStore.getState().addNotification('warning', (t as any)('messageNotFound') || 'Message not found');
}
}, 300);
} else {
@@ -137,25 +137,25 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
useEffect(() => {
if (!chat?.isImporting || !chat?.importJobId) {
setImportStatus(null);
return;
setImportStatus(null);
return;
}
const poll = async () => {
try {
const data = await httpClient.request<any>(`/import/telegram/status/${chat.importJobId}`);
setImportStatus({ processed: data.processedMessages, total: data.totalMessages, status: data.status });
if (data.status === 'Completed' || data.status === 'Failed') {
setImportStatus(null);
loadChats();
}
} catch (e: any) {
if (e.status === 404) {
console.warn('Import job not found');
} else {
console.error('Failed to poll status', e);
}
try {
const data = await httpClient.request<any>(`/import/telegram/status/${chat.importJobId}`);
setImportStatus({ processed: data.processedMessages, total: data.totalMessages, status: data.status });
if (data.status === 'Completed' || data.status === 'Failed') {
setImportStatus(null);
loadChats();
}
} catch (e: any) {
if (e.status === 404) {
console.warn('Import job not found');
} else {
console.error('Failed to poll status', e);
}
}
};
poll();
@@ -187,12 +187,31 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
// Refs and logic for tracking session's first unread message to show the divider exactly once per load
const sessionUnreadRef = useRef<{ chatId: string, msgId: string | null }>({ chatId: '', msgId: null });
if (activeChat && activeChat !== sessionUnreadRef.current.chatId && !isLoadingMessages) {
const firstUnreadMsg = chatMessages.find(
(m) => m.senderId !== user?.id && !m.readBy?.some((r) => r.userId === user?.id)
);
sessionUnreadRef.current = { chatId: activeChat, msgId: firstUnreadMsg ? firstUnreadMsg.id : null };
}
// Update sessionUnreadRef when chat changes OR when messages are marked as read
useEffect(() => {
if (!activeChat || isLoadingMessages) return;
// Reset on chat change
if (activeChat !== sessionUnreadRef.current.chatId) {
const firstUnreadMsg = chatMessages.find(
(m) => m.senderId !== user?.id && !m.readBy?.some((r) => r.userId === user?.id)
);
sessionUnreadRef.current = { chatId: activeChat, msgId: firstUnreadMsg ? firstUnreadMsg.id : null };
} else {
// Update if the first unread message was read (msgId no longer exists in unread list)
const firstUnreadMsg = chatMessages.find(
(m) => m.senderId !== user?.id && !m.readBy?.some((r) => r.userId === user?.id)
);
if (sessionUnreadRef.current.msgId && !firstUnreadMsg) {
// All messages are now read
sessionUnreadRef.current.msgId = null;
} else if (firstUnreadMsg && sessionUnreadRef.current.msgId !== firstUnreadMsg.id) {
// First unread changed (some messages were read)
sessionUnreadRef.current.msgId = firstUnreadMsg.id;
}
}
}, [activeChat, chatMessages, user?.id, isLoadingMessages]);
const firstUnreadId = activeChat === sessionUnreadRef.current.chatId ? sessionUnreadRef.current.msgId : null;
const initialScrollChatId = useRef<string | null>(null);
@@ -280,9 +299,9 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
isAtBottomRef.current = isAtBottomNow;
if (isAtBottomNow) {
localStorage.setItem(`chat_at_bottom_${chatId}`, 'true');
localStorage.removeItem(`chat_anchor_${chatId}`);
return;
localStorage.setItem(`chat_at_bottom_${chatId}`, 'true');
localStorage.removeItem(`chat_anchor_${chatId}`);
return;
}
const messageElements = container.querySelectorAll('[data-message-id]');
@@ -304,8 +323,8 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
}
if (anchor && anchor.id) {
localStorage.setItem(`chat_anchor_${chatId}`, JSON.stringify(anchor));
localStorage.removeItem(`chat_at_bottom_${chatId}`);
localStorage.setItem(`chat_anchor_${chatId}`, JSON.stringify(anchor));
localStorage.removeItem(`chat_at_bottom_${chatId}`);
}
}, [activeChat, scrollReady, chatMessages]);
@@ -333,13 +352,13 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
// Поиск ближайшего, если точное сообщение еще не загружено
if (!el) {
const msgIndex = chatMessages.findIndex(m => m.id === id);
if (msgIndex !== -1) {
for (let i = msgIndex; i < chatMessages.length; i++) {
const nextEl = container.querySelector(`[data-message-id="${chatMessages[i].id}"]`) as HTMLElement;
if (nextEl) { el = nextEl; break; }
}
}
const msgIndex = chatMessages.findIndex(m => m.id === id);
if (msgIndex !== -1) {
for (let i = msgIndex; i < chatMessages.length; i++) {
const nextEl = container.querySelector(`[data-message-id="${chatMessages[i].id}"]`) as HTMLElement;
if (nextEl) { el = nextEl; break; }
}
}
}
if (el) {
@@ -405,18 +424,18 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
// Сохраняем позицию старого чата
if (prevChatIdRef.current && scrollContainerRef.current && scrollReady) {
saveScrollPosition(prevChatIdRef.current);
saveScrollPosition(prevChatIdRef.current);
}
setScrollReady(false);
prevChatIdRef.current = activeChat;
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTop = 0;
scrollContainerRef.current.scrollTop = 0;
}
const timer = setTimeout(() => {
isInitializingRef.current = false;
isInitializingRef.current = false;
}, 600);
return () => clearTimeout(timer);
@@ -509,10 +528,10 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
isScrollingToBottomRef.current = true;
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTo({
top: scrollContainerRef.current.scrollHeight,
behavior: 'smooth'
});
scrollContainerRef.current.scrollTo({
top: scrollContainerRef.current.scrollHeight,
behavior: 'smooth'
});
}
setTimeout(() => {
@@ -573,6 +592,7 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
{
root: scrollContainerRef.current,
threshold: 0.1,
rootMargin: '0px',
}
);
@@ -584,7 +604,26 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
unreadElements.forEach((el: Element) => {
const id = el.getAttribute('data-message-id');
if (id && !sentReadIdsRef.current.has(id)) {
observer.observe(el);
// Check if element is already visible
const rect = el.getBoundingClientRect();
const containerRect = scrollContainerRef.current!.getBoundingClientRect();
const isVisible = rect.top >= containerRect.top && rect.bottom <= containerRect.bottom;
if (isVisible) {
// Mark as read immediately without waiting for intersection
const seqId = parseInt(el.getAttribute('data-sequence-id') || '0', 10);
if (seqId > 0) {
socket.emit('read_messages', {
chatId: activeChat,
lastReadMessageId: id,
lastReadSequenceId: seqId,
});
useChatStore.getState().markRead(activeChat, user.id, seqId);
sentReadIdsRef.current.add(id);
}
} else {
observer.observe(el);
}
}
});
};
@@ -646,7 +685,7 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
<section className="flex-1 h-full flex flex-col items-center justify-center bg-[#010101] relative overflow-hidden">
{/* Background Knot Texture */}
<div className="absolute inset-0 opacity-[0.04] pointer-events-none flex items-center justify-center">
<span className="material-symbols-outlined text-white text-[500px] select-none">cloud_download</span>
<span className="material-symbols-outlined text-white text-[500px] select-none">cloud_download</span>
</div>
{/* Chat Empty State View */}
@@ -1153,7 +1192,7 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
<div className="flex items-center justify-between mb-2 px-1">
<span className="text-xs font-black uppercase tracking-widest text-primary">
{importStatus?.status === 'Processing' ? 'Обработка' :
importStatus?.status === 'Queued' ? 'В очереди' : 'Загрузка'}
importStatus?.status === 'Queued' ? 'В очереди' : 'Загрузка'}
</span>
<span className="text-xs font-black text-on-surface tabular-nums">
{importStatus?.processed || 0} / {importStatus?.total || 0}
@@ -1227,7 +1266,7 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
</p>
<p className="text-sm text-zinc-300 truncate font-medium">
{chatPinnedMessages[pinnedIndex % chatPinnedMessages.length]?.content ||
(chatPinnedMessages[pinnedIndex % chatPinnedMessages.length]?.media?.length > 0 ? t('media') : '...')}
(chatPinnedMessages[pinnedIndex % chatPinnedMessages.length]?.media?.length > 0 ? t('media') : '...')}
</p>
</div>
</button>
File diff suppressed because it is too large Load Diff