| import { usePathname } from "next/navigation"; |
| import { parseAsString, useQueryState } from "nuqs"; |
| import { useEffect, useState } from "react"; |
|
|
| |
| function extractChatId(pathname: string): string | null { |
| const segments = pathname.split("/").filter(Boolean); |
| const chatIndex = segments.indexOf("chat"); |
|
|
| |
| if (chatIndex !== -1) { |
| const id = segments[chatIndex + 1]; |
| if (id) { |
| return id; |
| } |
| } |
|
|
| return null; |
| } |
|
|
| export function useChatInterface() { |
| const pathname = usePathname(); |
| const [, setSelectedType] = useQueryState("artifact-type", parseAsString); |
|
|
| |
| const [chatId, setChatIdState] = useState<string | null>(() => |
| extractChatId(pathname), |
| ); |
|
|
| |
| const handleNavigateAway = () => { |
| setSelectedType(null); |
| document.title = "Overview | Midday"; |
| }; |
|
|
| |
| useEffect(() => { |
| const id = extractChatId(pathname); |
| setChatIdState(id); |
|
|
| if (!id) { |
| handleNavigateAway(); |
| } |
| }, [pathname, setSelectedType]); |
|
|
| |
| useEffect(() => { |
| const handlePopState = () => { |
| const id = extractChatId(window.location.pathname); |
| setChatIdState(id); |
|
|
| if (!id) { |
| handleNavigateAway(); |
| } |
| }; |
|
|
| window.addEventListener("popstate", handlePopState); |
| return () => window.removeEventListener("popstate", handlePopState); |
| }, [setSelectedType]); |
|
|
| const isHome = !chatId; |
| const isChatPage = Boolean(chatId); |
|
|
| const setChatId = (id: string) => { |
| |
| const currentSearch = window.location.search; |
| const segments = pathname.split("/").filter(Boolean); |
|
|
| |
| const hasLocale = segments[0]?.length === 2; |
| const locale = hasLocale ? segments[0] : null; |
|
|
| const newPath = locale |
| ? `/${locale}/chat/${id}${currentSearch}` |
| : `/chat/${id}${currentSearch}`; |
|
|
| window.history.pushState({}, "", newPath); |
| setChatIdState(id); |
| }; |
|
|
| return { |
| isHome, |
| isChatPage, |
| chatId, |
| setChatId, |
| }; |
| } |
|
|