import { useEffect, useRef, useState } from 'react' import type { HistoryOwner } from './history/entry' import type { NavigationState } from './navigation' import type { EditorNavigation, LayerName } from './useEditorNavigation' /** * A dirty dialog lost when the editor goes (a Back of several entries, BDR-078: a Back * cannot be refused, and a draft is never stored). One flag in this tab's sessionStorage * says so to the next mount of the same sheet for the same account (criterion 17). */ const PREFIX = 'faunosteo:editor:left-draft:' export const leftDraftKey = ({ sheetId, userId }: HistoryOwner) => `${PREFIX}${sheetId}:${userId}` /** The top layer first: the dialog the user was typing in when they left. */ const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding'] function storage(): Storage | null { try { return typeof sessionStorage === 'undefined' ? null : sessionStorage } catch { return null } } /** The element the layer showed: a key, a reference, a creation's parent. Never text. */ function elementOf(state: NavigationState, layer: LayerName): unknown { if (layer === 'reference') { const { reference } = state return reference && 'edit' in reference ? { kind: 'reference', id: reference.edit } : null } const { finding } = state if (!finding) return null return 'key' in finding ? finding.key : finding.create.parent } /** Called as the editor goes: a layer whose form holds changes leaves the flag. */ function flagIfDirty(owner: HistoryOwner, nav: EditorNavigation): void { if (!owner.sheetId || !owner.userId) return // A forced ask has no side effect: a dirty form answers with its note. const layer = LAYERS_TOP_DOWN.find((l) => nav.guards.ask(l, true).note) if (!layer) return const flag = { kind: layer, key: elementOf(nav.state, layer) } try { storage()?.setItem(leftDraftKey(owner), JSON.stringify(flag)) } catch { // A full or blocked storage: the leave goes unsaid, as before. } } /** True when the flag is there; read once per mount. */ function readFlag(owner: HistoryOwner): boolean { try { return storage()?.getItem(leftDraftKey(owner)) != null } catch { return false } } function clearFlag(owner: HistoryOwner): void { try { storage()?.removeItem(leftDraftKey(owner)) } catch { // Nothing to clear. } } /** * Whether the last editor of this sheet and account left with a dirty dialog: shown once, * then cleared. The editor's own cleanup runs before its dialogs' (a deleted tree is * cleaned up from its root), so their guards still answer when it flags. */ export function useLeftDraft( nav: EditorNavigation, owner: HistoryOwner, ): boolean { const latest = useRef(nav) latest.current = nav const [left] = useState(() => readFlag(owner)) useEffect(() => { clearFlag(owner) return () => flagIfDirty(owner, latest.current) }, [owner]) return left }