// Parse chat ID from GET parameter export function getChatIdFromUrl() { const params = new URLSearchParams(window.location.search); return params.get('chat'); } // Update URL with GET parameter export function updateUrlWithChatId(chatId) { const url = new URL(window.location.href); if (chatId) { url.searchParams.set('chat', chatId); } else { url.searchParams.delete('chat'); } window.history.replaceState({}, "", url); } // which chat is on screen right now export let activeChatId = $state(null); export function switchChat(chatId) { activeChatId = chatId; updateUrlWithChatId(chatId); } export function newChat() { const id = "chat_" + crypto.randomUUID(); switchChat(id); return id; } // restore last opened chat (or create first one) (() => { const ids = JSON.parse(localStorage.getItem("chat_ids") || "[]"); const urlChatId = getChatIdFromUrl(); if (urlChatId) { switchChat(urlChatId); } else if (ids.length) { switchChat(ids[0]); } else { newChat(); } })();