export type PendingTextIntent = { text: string; dialogKey: string; messageKey: string; dialogId?: string; }; const STORAGE_KEY = "han.pending-message"; let pendingTextIntent: PendingTextIntent | null = null; let pendingFileIntent: PendingFileIntent | null = null; export type PendingFileIntent = { file: File; dialogKey: string; dialogId?: string; messageKey: string; }; export function createPendingTextIntent(text: string): PendingTextIntent { return { text, dialogKey: crypto.randomUUID(), messageKey: crypto.randomUUID(), }; } export function savePendingTextIntent(intent: PendingTextIntent) { pendingTextIntent = intent; if (typeof window !== "undefined") { window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(intent)); } } export function loadPendingTextIntent(): PendingTextIntent | null { if (pendingTextIntent) return pendingTextIntent; if (typeof window === "undefined") return null; const raw = window.sessionStorage.getItem(STORAGE_KEY); if (!raw) return null; try { const value = JSON.parse(raw) as Partial; if ( typeof value.text !== "string" || typeof value.dialogKey !== "string" || typeof value.messageKey !== "string" ) { return null; } pendingTextIntent = { text: value.text, dialogKey: value.dialogKey, messageKey: value.messageKey, ...(typeof value.dialogId === "string" ? { dialogId: value.dialogId } : {}), }; return pendingTextIntent; } catch { return null; } } export function bindPendingTextIntent(intent: PendingTextIntent, dialogId: string) { const bound = { ...intent, dialogId }; savePendingTextIntent(bound); return bound; } export function clearPendingTextIntent() { pendingTextIntent = null; if (typeof window !== "undefined") { window.sessionStorage.removeItem(STORAGE_KEY); } } export function savePendingFileIntent(intent: PendingFileIntent) { pendingFileIntent = intent; } export function bindPendingFileIntent(dialogId: string) { if (pendingFileIntent) pendingFileIntent = { ...pendingFileIntent, dialogId }; } export function pendingDialogKey() { return loadPendingTextIntent()?.dialogKey ?? pendingFileIntent?.dialogKey; } export function loadPendingFileIntent(dialogId: string) { return pendingFileIntent?.dialogId === dialogId ? pendingFileIntent : null; } export function clearPendingFileIntent() { pendingFileIntent = null; }