@@ -1,2 +1,3 @@ export * from './chats.store' -export * from './use-chat-actions' \ No newline at end of file +export * from './use-chat-actions' +export * from './use-current-chat' @@ -13,6 +13,8 @@ export function useChatActions() { const [loaded, setLoaded] = useState(false) + const { currentChat, setCurrentChat } = useCurrentChat() + const onRenameChat = makePrivateRequest(async (uid: string, title: string) => { const chat = chats.find((x) => x.uid === uid) @@ -31,12 +33,37 @@ export function useChatActions() { const onRemoveChat = makePrivateRequest(async (uid: string) => { const chat = chats.find((x) => x.uid === uid) - const { status } = await removeChat(uid) if (status !== 204 || !chat) return showMessage('Ошибка при переименовании чата') - setChats([...chats.filter((c) => c.uid !== uid)]) + const currentIndex = chats.findIndex((chat) => chat.uid === currentChat) + const isRemovingCurrent = currentChat === uid + + const updatedChats = chats.filter((c) => c.uid !== uid) + setChats(updatedChats) + + if (isRemovingCurrent) { + let newCurrentChat: string | null = null + + // Пытаемся найти подходящий чат для перехода + if (updatedChats.length > 0) { + // Сначала пробуем следующий чат + if (currentIndex < updatedChats.length) { + newCurrentChat = updatedChats[currentIndex]?.uid || null + } + // Если нет - берем предыдущий + if (!newCurrentChat && currentIndex > 0) { + newCurrentChat = updatedChats[currentIndex - 1]?.uid || null + } + // Если все еще нет - берем первый + if (!newCurrentChat) { + newCurrentChat = updatedChats[0]?.uid || null + } + } + + setCurrentChat(newCurrentChat) + } }) const onCreateChat = makePrivateRequest(async (dto: CreateChatDTO) => { @@ -47,6 +74,7 @@ export function useChatActions() { const chats = useChatsStore.getState().chats setChats([chat, ...chats]) + setCurrentChat(chat.uid) }) return { @@ -0,0 +1,12 @@ +import { create } from 'zustand' +import { ChatDTO } from '#/entities/chat/types' + +interface CurrentChatStore { + currentChat: ChatDTO | null + setCurrentChat: (chat: ChatDTO | null) => void +} + +export const useCurrentChat = create((set) => ({ + currentChat: null, + setCurrentChat: (currentChat) => set({ currentChat }), +})) @@ -45,8 +45,15 @@ export const ChatButton = forwardRef( + ) })