import { useState } from 'react' /** The layout of a board: the order of the panel ids, the width chosen for a panel, and the hidden and the folded panels. */ export type Layout = { order: string[]; widths: Record; hidden: string[]; folded: string[] } const EMPTY: Layout = { order: [], widths: {}, hidden: [], folded: [] } /** The layout kept in localStorage under key, or an empty one when there is none or it cannot be read. */ function readLayout(key: string): Layout { try { const value: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null') if (value !== null && typeof value === 'object') { const stored = value as Partial const strings = (items: unknown) => (Array.isArray(items) ? items.filter((item): item is string => typeof item === 'string') : []) return { order: strings(stored.order), widths: stored.widths !== null && typeof stored.widths === 'object' ? stored.widths : {}, hidden: strings(stored.hidden), folded: strings(stored.folded), } } } catch { // A layout that cannot be read is replaced by the default. } return EMPTY } /** The layout of a board kept in the browser's localStorage under key, and a function that changes and keeps it. */ function useLayout(key: string): [Layout, (change: (current: Layout) => Layout) => void] { const [layout, setLayout] = useState(() => readLayout(key)) function update(change: (current: Layout) => Layout) { setLayout((current) => { const next = change(current) window.localStorage.setItem(key, JSON.stringify(next)) return next }) } return [layout, update] } /** The state of a page's board: its layout kept in the browser under key, whether it is edited, and the Panels dialog. */ export type BoardState = ReturnType export function useBoard(key: string) { const [layout, setLayout] = useLayout(key) const [editing, setEditing] = useState(false) const [choosing, setChoosing] = useState(false) return { layout, setLayout, editing, setEditing, choosing, setChoosing } }