@ai-matrx/canvas 0.7.1 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +1 -1
- package/dist/index.cjs +5 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/react.cjs +24 -5
- package/dist/react.cjs.map +1 -1
- package/dist/react.js +24 -5
- package/dist/react.js.map +1 -1
- package/dist/styles.css +14 -9
- package/package.json +1 -1
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/provider.tsx","../src/react/menuItems.ts","../src/core/types.ts","../src/core/ids.ts","../src/core/layout.ts","../src/core/reducer.ts","../src/core/store.ts","../src/core/persistence.ts","../src/core/rules.ts","../src/core/commands.ts","../src/core/controller.ts","../src/core/selectors.ts","../src/core/presentation.ts","../src/core/toggleKind.ts","../src/react/layer.tsx","../src/react/registry.ts","../src/react/CanvasColumn.tsx","../src/react/bodies.tsx","../src/react/chrome.tsx","../src/react/icons.tsx","../src/react/dnd.ts","../src/react/launcher.tsx","../src/react/presentation.tsx","../src/react/slots.ts","../src/react/resizeGesture.ts","../src/react/CanvasPane.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * CanvasProvider — binds a store, starts persistence, binds the shortcut table,\n * and hands every descendant the ONE controller (acting for this provider's\n * window). A host adds it once at its root — a desktop host once per window,\n * each over the same remote store with its own `windowId`.\n */\n\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type ComponentType,\n type ReactNode,\n} from \"react\";\nimport { createCanvasItemMenus, type CanvasItemMenus } from \"./menuItems\";\nimport {\n CANVAS_DEFAULT_KEY,\n CANVAS_MAIN_WINDOW,\n CANVAS_PHONE_MAX_WIDTH,\n CANVAS_SHORTCUTS,\n selectCanvasKindVisibility,\n toggleKind,\n type CanvasKindVisibility,\n type ToggleKindInput,\n canvasWindowFrame,\n canvasWindowId,\n createCanvasController,\n createCanvasStore,\n createLocalStorageCanvasPersistence,\n matchesCanvasAccelerator,\n runCanvasCommand,\n type CanvasController,\n type CanvasErrorSink,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasLayoutRules,\n type CanvasPersistencePort,\n type CanvasSessionHooks,\n type CanvasShortcutWhen,\n type CanvasState,\n type CanvasStoreBinding,\n type CanvasWindowId,\n} from \"../index\";\nimport {\n CanvasDomOverlay,\n createCanvasLayer,\n type CanvasLayer,\n type CanvasNativeBodyFrame,\n type CanvasOverlayPort,\n type CanvasShowMenu,\n} from \"./layer\";\nimport {\n canvasSessionKey,\n getCanvasKind,\n getCanvasKindsVersion,\n listCanvasKinds,\n subscribeCanvasKinds,\n type AnyCanvasKind,\n type CanvasMenuItem,\n} from \"./registry\";\n\n/**\n * What the host answers ONCE for every kind. Saving, sharing and history are\n * \"handled globally\" here; the window ports let a desktop host draw floating\n * things and native bodies its own way. Every port has a working default.\n */\nexport interface CanvasHostPorts {\n /** Extra \"…\" menu entries for an item (share, save to cloud, version history…). */\n readonly itemActions?: ((item: CanvasItem, kind: AnyCanvasKind | undefined) => readonly CanvasMenuItem[]) | undefined;\n /**\n * Opens a window that renders this canvas for the returned window id (web: a\n * floating panel with <CanvasWindowScope>; desktop: a BrowserWindow with its\n * own provider). The item then moves there. Absent ⇒ no \"Pop out\" entry, and\n * `controller.popOut` is refused aloud.\n */\n readonly popOut?: ((item: CanvasItem) => Promise<{ readonly windowId: string } | null>) | undefined;\n /** A tab docked back out of `fromWindowId`. Close that window once the state no longer lists it. */\n readonly dockBack?: ((itemId: CanvasItemId, fromWindowId: CanvasWindowId) => void) | undefined;\n /** Draws the \"…\" menu (Electron `Menu.popup`). Default: the package's DOM menu. */\n readonly showMenu?: CanvasShowMenu | undefined;\n /** Draws tooltips, drop indicators and tab drags above native views. Default: in the DOM. */\n readonly overlay?: CanvasOverlayPort | undefined;\n /** Where each native-body kind's view goes, reported in the frame the layout changed. */\n readonly onNativeBodyFrame?: CanvasNativeBodyFrame | undefined;\n}\n\nexport type CanvasTabStripMode = \"auto\" | \"always\";\n\ninterface CanvasContextValue {\n readonly controller: CanvasController;\n readonly windowId: CanvasWindowId;\n readonly ports: CanvasHostPorts;\n readonly layer: CanvasLayer;\n /** Width of the region the canvas shares with the content beside it; null = the window. */\n readonly regionWidth: number | null;\n readonly tabStrip: CanvasTabStripMode;\n readonly launcherEntries: CanvasLauncherEntryStore;\n /** Menu entries bodies contribute to their pane's one menu. */\n readonly itemMenus: CanvasItemMenus;\n}\n\n/**\n * One contextual launcher entry: a page offers something about ITSELF in the\n * canvas's \"New tab\" launcher (\"This chat's documents\" on a chat page) for as\n * long as it is mounted. Shown before the global kinds.\n */\nexport interface CanvasLauncherEntry {\n readonly kind: string;\n readonly key: string;\n readonly data?: CanvasJson | undefined;\n /** The entry's label (and the new tab's title). Default: the kind's label. */\n readonly title?: string | null | undefined;\n /** Default: the kind's icon. */\n readonly icon?: ComponentType<{ className?: string }> | undefined;\n}\n\nexport interface CanvasLauncherEntryStore {\n add(entry: CanvasLauncherEntry): () => void;\n list(): readonly CanvasLauncherEntry[];\n subscribe(listener: () => void): () => void;\n}\n\nfunction createLauncherEntryStore(): CanvasLauncherEntryStore {\n let entries: readonly CanvasLauncherEntry[] = [];\n const listeners = new Set<() => void>();\n const emit = () => {\n for (const listener of [...listeners]) listener();\n };\n return {\n add(entry) {\n entries = [...entries, entry];\n emit();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n entries = entries.filter((e) => e !== entry);\n emit();\n };\n },\n list: () => entries,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n/** Phones show an open canvas full screen; a remembered \"open\" never takes over a phone on load. */\nconst isPhoneViewport = () => typeof window !== \"undefined\" && window.innerWidth <= CANVAS_PHONE_MAX_WIDTH;\n\nconst isMacPlatform = () =>\n typeof navigator !== \"undefined\" && /mac|iphone|ipad/i.test((navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform ?? navigator.platform ?? \"\");\n\n/** Escape belongs to a menu, dialog or listbox when one has focus. */\nfunction escapeBelongsElsewhere(event: KeyboardEvent): boolean {\n if (event.defaultPrevented) return true;\n const active = typeof document === \"undefined\" ? null : document.activeElement;\n return !!active?.closest?.('[role=\"menu\"], [role=\"dialog\"], [role=\"alertdialog\"], [role=\"listbox\"]');\n}\n\nconst CanvasContext = createContext<CanvasContextValue | null>(null);\n\nexport interface CanvasProviderProps extends CanvasHostPorts {\n readonly children: ReactNode;\n /** A Redux-bound store (bindCanvasToReduxStore), a remote one (createRemoteCanvasStore), or omit for a standalone store. */\n readonly store?: CanvasStoreBinding;\n /** `null` turns memory off. Default: localStorage. Ignored for a remote store (its owner saves). */\n readonly persistence?: CanvasPersistencePort | null;\n readonly onError?: CanvasErrorSink;\n /** Binds the shortcut table's web shortcuts (⌘\\ toggles, Esc leaves expand…). Default true. */\n readonly hotkeys?: boolean;\n /** The window this provider renders. Default: the main window. */\n readonly windowId?: string;\n /** Width and split numbers, read once. Default: CANVAS_WEB_LAYOUT_RULES. */\n readonly layoutRules?: Partial<CanvasLayoutRules>;\n /** Live width of the region the canvas shares with the content beside it (desktop: right of the sidebar). Default: the window. */\n readonly regionWidth?: number | null;\n /** \"auto\": a pane with one tab shows a title instead of a tab strip. Default \"auto\". */\n readonly tabStrip?: CanvasTabStripMode;\n}\n\nfunction sessionHooksFor(kindId: string): CanvasSessionHooks | undefined {\n const kind = getCanvasKind(kindId);\n if (!kind || kind.restore !== \"session\") return undefined;\n return {\n sessionKey: (item) => canvasSessionKey(kind, item),\n onAttach: kind.onAttach,\n onDetach: kind.onDetach,\n };\n}\n\nexport function CanvasProvider({\n children,\n store,\n persistence,\n onError,\n hotkeys = true,\n windowId: windowIdProp,\n layoutRules,\n regionWidth = null,\n tabStrip = \"auto\",\n itemActions,\n popOut,\n dockBack,\n showMenu,\n overlay,\n onNativeBodyFrame,\n}: CanvasProviderProps) {\n // One identity per set of ports: a provider re-rendering for its parent must\n // not re-render every canvas consumer (the context value below is stable too).\n const hostPorts = useMemo<CanvasHostPorts>(\n () => ({ itemActions, popOut, dockBack, showMenu, overlay, onNativeBodyFrame }),\n [itemActions, popOut, dockBack, showMenu, overlay, onNativeBodyFrame],\n );\n const portsRef = useRef<CanvasHostPorts>(hostPorts);\n portsRef.current = hostPorts;\n const [{ controller, layer, launcherEntries, itemMenus }] = useState(() => ({\n controller: createCanvasController({\n store: store ?? createCanvasStore(),\n persistence: persistence === undefined ? createLocalStorageCanvasPersistence() : persistence,\n isRestorable: (kind) => getCanvasKind(kind)?.restore !== false,\n mayRestoreOpen: () => !isPhoneViewport(),\n onError,\n windowId: windowIdProp ?? CANVAS_MAIN_WINDOW,\n layoutRules,\n windowPorts: () => portsRef.current,\n sessions: sessionHooksFor,\n preferredTarget: (kind) => getCanvasKind(kind)?.preferredTarget,\n }),\n layer: createCanvasLayer(() => portsRef.current),\n launcherEntries: createLauncherEntryStore(),\n itemMenus: createCanvasItemMenus(),\n }));\n const windowId = controller.windowId;\n\n useEffect(() => controller.start(), [controller]);\n\n useEffect(() => {\n if (!hotkeys) return;\n const isMac = isMacPlatform();\n const applies = (when: CanvasShortcutWhen, event: KeyboardEvent) => {\n if (!controller.isPresented()) return false; // no column here — nothing to act on\n if (when === \"presented\") return true;\n if (when === \"fullscreen\") return !!canvasWindowFrame(controller.getState(), windowId)?.isFullscreen && !escapeBelongsElsewhere(event);\n const column = document.activeElement?.closest?.(\"[data-mxc-window]\");\n return column?.getAttribute(\"data-mxc-window\") === windowId;\n };\n const onKey = (event: KeyboardEvent) => {\n for (const shortcut of CANVAS_SHORTCUTS) {\n if (!shortcut.web || !matchesCanvasAccelerator(event, shortcut.accelerator, isMac)) continue;\n if (!applies(shortcut.when, event)) return;\n if (runCanvasCommand(controller, shortcut.id)) event.preventDefault();\n return;\n }\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [controller, hotkeys, windowId]);\n\n const value = useMemo<CanvasContextValue>(\n () => ({ controller, windowId, ports: hostPorts, layer, regionWidth, tabStrip, launcherEntries, itemMenus }),\n [controller, windowId, hostPorts, layer, regionWidth, tabStrip, launcherEntries, itemMenus],\n );\n return (\n <CanvasContext.Provider value={value}>\n {children}\n {hostPorts.overlay ? null : <CanvasDomOverlay layer={layer} />}\n </CanvasContext.Provider>\n );\n}\n\n/**\n * Renders a subtree as ANOTHER window of the same canvas — the web host's\n * pop-out panel: `<CanvasWindowScope windowId={id}><CanvasColumn placement=\"fill\"/></CanvasWindowScope>`.\n */\nexport function CanvasWindowScope({ windowId, children }: { windowId: string; children: ReactNode }) {\n const parent = useCanvasContext();\n const value = useMemo<CanvasContextValue>(() => {\n const id = canvasWindowId(windowId);\n return { ...parent, windowId: id, controller: parent.controller.forWindow(id) };\n }, [parent, windowId]);\n return <CanvasContext.Provider value={value}>{children}</CanvasContext.Provider>;\n}\n\nfunction useCanvasContext(): CanvasContextValue {\n const value = useContext(CanvasContext);\n if (!value) throw new Error(\"[@ai-matrx/canvas] useCanvas* must be used inside <CanvasProvider>.\");\n return value;\n}\n\n/** Package-internal: the whole context (layer, ports, region). */\nexport function useCanvasInternals(): CanvasContextValue {\n return useCanvasContext();\n}\n\nexport function useOptionalCanvasInternals(): CanvasContextValue | null {\n return useContext(CanvasContext);\n}\n\n/** The controller (acting for this window): open, close, toggle, split… */\nexport function useCanvas(): CanvasController {\n return useCanvasContext().controller;\n}\n\n/** Same as useCanvas, but null outside a provider (for components that may render anywhere). */\nexport function useOptionalCanvas(): CanvasController | null {\n return useContext(CanvasContext)?.controller ?? null;\n}\n\n/** The window this subtree renders. */\nexport function useCanvasWindowId(): CanvasWindowId {\n return useContext(CanvasContext)?.windowId ?? CANVAS_MAIN_WINDOW;\n}\n\nexport function useCanvasHostPorts(): CanvasHostPorts {\n return useCanvasContext().ports;\n}\n\n/**\n * Native-body controls. `remeasure()` re-reports every native body's frame now —\n * call it on each animation frame while the host animates its own layout (a\n * sidebar collapsing moves the canvas without resizing it).\n */\nexport function useCanvasNativeBodies(): { readonly remeasure: () => void } {\n return useCanvasContext().layer.native;\n}\n\n/** Registers a mounted canvas column with the controller for its lifetime. */\nexport function useRegisterCanvasPresence(): void {\n const context = useContext(CanvasContext);\n const controller = context?.controller;\n const windowId = context?.windowId;\n useEffect(() => controller?.registerPresentation(windowId), [controller, windowId]);\n}\n\nconst noPresence = () => () => undefined;\n\n/** True when a canvas column is on screen for this window — the ONE availability answer. */\nexport function useCanvasIsPresented(): boolean {\n const context = useContext(CanvasContext);\n const controller = context?.controller;\n return useSyncExternalStore(\n controller ? controller.subscribePresentation : noPresence,\n () => controller?.isPresented() ?? false,\n () => false,\n );\n}\n\n/** Subscribes to a slice of canvas state. The selector must return stable values. */\nexport function useCanvasState<T>(selector: (state: CanvasState) => T): T {\n const { store } = useCanvasContext().controller;\n return useSyncExternalStore(\n store.subscribe,\n () => selector(store.getState()),\n () => selector(store.getState()),\n );\n}\n\nconst NO_SUBSCRIPTION = () => () => undefined;\n\n/**\n * Like useCanvasState, but safe outside a provider: returns `fallback` there.\n * For components that may render in a tree with no canvas (a bare test, an\n * embed). `fallback` must be referentially stable (a primitive or null).\n */\nexport function useOptionalCanvasState<T>(selector: (state: CanvasState) => T, fallback: T): T {\n const store = useContext(CanvasContext)?.controller.store;\n const read = () => (store ? selector(store.getState()) : fallback);\n return useSyncExternalStore(store ? store.subscribe : NO_SUBSCRIPTION, read, read);\n}\n\n/**\n * A toolbar icon's view of one kind: \"absent\" | \"background\" | \"visible\"\n * (a primitive, so it never loops), plus the click that toggles or focuses it.\n */\nexport function useCanvasKindToggle(input: ToggleKindInput): {\n readonly visibility: CanvasKindVisibility;\n readonly isOpen: boolean;\n readonly isVisible: boolean;\n readonly toggle: () => CanvasKindVisibility;\n} {\n const controller = useCanvasContext().controller;\n const key = input.key ?? CANVAS_DEFAULT_KEY;\n const visibility = useCanvasState((s) => selectCanvasKindVisibility(s, input.kind, key));\n return {\n visibility,\n isOpen: visibility !== \"absent\",\n isVisible: visibility === \"visible\",\n toggle: () => toggleKind(controller, input),\n };\n}\n\n/** Re-renders when kinds register, so late-registered kinds appear. */\nexport function useCanvasKinds(): readonly AnyCanvasKind[] {\n useSyncExternalStore(subscribeCanvasKinds, getCanvasKindsVersion, getCanvasKindsVersion);\n return listCanvasKinds();\n}\n\nexport function useCanvasKind(id: string): AnyCanvasKind | undefined {\n useSyncExternalStore(subscribeCanvasKinds, getCanvasKindsVersion, getCanvasKindsVersion);\n return getCanvasKind(id);\n}\n\nconst NO_ENTRIES: readonly CanvasLauncherEntry[] = Object.freeze([]);\nconst noEntries = () => NO_ENTRIES;\n\n/**\n * Offers `entry` in the canvas's \"New tab\" launcher while the calling\n * component is mounted — a route registers what is about IT (a chat's\n * documents, a table's saved views). Contextual entries show before the\n * global kinds. A no-op outside a CanvasProvider.\n */\nexport function useCanvasLauncherEntry(entry: CanvasLauncherEntry): void {\n const store = useContext(CanvasContext)?.launcherEntries;\n const fingerprint = JSON.stringify([entry.kind, entry.key, entry.title ?? null, entry.data ?? null]);\n const icon = entry.icon;\n useEffect(() => {\n if (!store) return undefined;\n const [kind, key, title, data] = JSON.parse(fingerprint) as [string, string, string | null, CanvasJson];\n return store.add({ kind, key, title, data, ...(icon ? { icon } : {}) });\n }, [store, fingerprint, icon]);\n}\n\n/** Contextual launcher entries, latest registration of each `kind::key` only, in registration order. */\nexport function useCanvasLauncherEntries(): readonly CanvasLauncherEntry[] {\n const store = useContext(CanvasContext)?.launcherEntries;\n const all = useSyncExternalStore(store ? store.subscribe : NO_SUBSCRIPTION, store ? store.list : noEntries, store ? store.list : noEntries);\n const seen = new Set<string>();\n const out: CanvasLauncherEntry[] = [];\n for (let i = all.length - 1; i >= 0; i -= 1) {\n const entry = all[i];\n if (!entry || seen.has(`${entry.kind}::${entry.key}`)) continue;\n seen.add(`${entry.kind}::${entry.key}`);\n out.unshift(entry);\n }\n return out;\n}\n","\"use client\";\n\n/**\n * Menu entries a BODY contributes to its pane's one menu.\n *\n * A pane has ONE menu (\"⋮\"): the kind's `menuItems`, then what the body\n * offers right now (a record's own actions, a document's export), then the\n * host's `itemActions`, then the pane's own actions (Split, Pop out, Close\n * others). A body never draws a second overflow button in the header; it\n * calls `useCanvasMenuItems(itemId, items)` and its entries join that menu.\n *\n * Entries carry callbacks, so they live here (per provider), never in the\n * store. The menu reads them when it opens, so a body re-rendering never\n * re-renders a pane.\n */\n\nimport { useEffect, useLayoutEffect, useRef } from \"react\";\nimport type { CanvasItemId } from \"../index\";\nimport { useCanvasInternals } from \"./provider\";\nimport type { CanvasMenuItem } from \"./registry\";\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nexport interface CanvasItemMenus {\n /** Registers a live source of entries for an item; returns the unregister. */\n register(itemId: CanvasItemId, read: () => readonly CanvasMenuItem[]): () => void;\n /** Every registered entry for an item, in registration order. */\n read(itemId: CanvasItemId): readonly CanvasMenuItem[];\n}\n\nexport function createCanvasItemMenus(): CanvasItemMenus {\n const sources = new Map<CanvasItemId, Set<() => readonly CanvasMenuItem[]>>();\n return {\n register(itemId, read) {\n let set = sources.get(itemId);\n if (!set) sources.set(itemId, (set = new Set()));\n set.add(read);\n return () => {\n const current = sources.get(itemId);\n current?.delete(read);\n if (current && current.size === 0) sources.delete(itemId);\n };\n },\n read(itemId) {\n const out: CanvasMenuItem[] = [];\n for (const read of sources.get(itemId) ?? []) {\n try {\n out.push(...read());\n } catch (error) {\n console.error(\"[@ai-matrx/canvas] a body's menu entries threw\", error);\n }\n }\n return out;\n },\n };\n}\n\n/**\n * Puts `items` into the pane menu of the tab `itemId` (the body's own\n * actions), after the kind's `menuItems`. The latest `items` are read each\n * time the menu opens; pass `[]` to offer nothing.\n */\nexport function useCanvasMenuItems(itemId: CanvasItemId | string | null | undefined, items: readonly CanvasMenuItem[]): void {\n const { itemMenus } = useCanvasInternals();\n const latest = useRef(items);\n latest.current = items;\n useIsoLayoutEffect(() => {\n if (!itemId) return undefined;\n return itemMenus.register(itemId as CanvasItemId, () => latest.current);\n }, [itemMenus, itemId]);\n}\n","/**\n * @ai-matrx/canvas — core types.\n *\n * The canvas is ONE docked column on the right edge of an application. It holds\n * panes; panes hold tabs; every tab is one CanvasItem. A CanvasItem is\n * identified by `kind` + `key`, so opening the same thing twice always lands on\n * the existing tab instead of creating a duplicate.\n *\n * Everything in CanvasState is plain JSON: it lives in the host's Redux store\n * (or the package's own standalone store), it is persisted between sessions,\n * and it can be inspected. No functions, no class instances, no React nodes.\n */\n\n/** Any value that survives JSON.stringify → JSON.parse unchanged. */\nexport type CanvasJson =\n | string\n | number\n | boolean\n | null\n | readonly CanvasJson[]\n | { readonly [key: string]: CanvasJson | undefined };\n\ndeclare const itemIdBrand: unique symbol;\ndeclare const paneIdBrand: unique symbol;\ndeclare const splitIdBrand: unique symbol;\ndeclare const windowIdBrand: unique symbol;\n\n/** `${kind}::${key}` — the identity of one thing on the canvas. */\nexport type CanvasItemId = string & { readonly [itemIdBrand]: true };\nexport type CanvasPaneId = string & { readonly [paneIdBrand]: true };\nexport type CanvasSplitId = string & { readonly [splitIdBrand]: true };\n/**\n * One application window that renders a canvas. Single-window hosts only ever\n * see `CANVAS_MAIN_WINDOW`; a desktop host with one store in its main process\n * gives every other window (a second app window, a popped-out tab) its own id.\n */\nexport type CanvasWindowId = string & { readonly [windowIdBrand]: true };\n\nexport const CANVAS_MAIN_WINDOW = \"main\" as CanvasWindowId;\n\n/**\n * Where a tab was before it navigated in place (`controller.navigate`). Plain\n * JSON, so history persists with the layout; Back reopens the last entry.\n */\nexport interface CanvasHistoryEntry {\n readonly kind: string;\n readonly key: string;\n readonly title: string | null;\n readonly data: CanvasJson;\n /**\n * The body this content had (its item's `instance`). Back and a navigate to\n * a kept step reuse it, so the SAME live body comes back (a typed draft, a\n * scroll position) while the layer still holds it mounted.\n */\n readonly instance?: string | undefined;\n}\n\n/** The built-in \"New tab\" item: the launcher, shown as a tab. Never registered as a kind. */\nexport const CANVAS_LAUNCHER_KIND = \"canvas.launcher\";\n\n/** How many steps Back can go in one tab. Older entries fall off. */\nexport const CANVAS_HISTORY_LIMIT = 50;\n\n/**\n * How many earlier contents of one tab keep their body MOUNTED (hidden), in\n * each direction: the newest steps Back reaches, and the contents Back left\n * (`CanvasItem.kept`). Older steps still work — their body mounts fresh.\n * Only closing the tab disposes the kept bodies.\n */\nexport const CANVAS_KEEP_ALIVE_DEPTH = 5;\n\nexport interface CanvasItem {\n readonly id: CanvasItemId;\n /** Registered kind id (see `registerCanvasKind`). */\n readonly kind: string;\n /** Stable key inside the kind — an artifact id, a conversation id, \"default\". */\n readonly key: string;\n /** Explicit tab title. `null` ⇒ the kind's `title(data)` or its label. */\n readonly title: string | null;\n readonly data: CanvasJson;\n readonly openedAt: number;\n readonly updatedAt: number;\n /** Earlier contents of this tab, oldest first (navigate in place). Absent = no Back. */\n readonly history?: readonly CanvasHistoryEntry[] | undefined;\n /**\n * Contents this tab showed that Back has stepped away from (newest last, at\n * most CANVAS_KEEP_ALIVE_DEPTH). Navigating to one again brings back its\n * live body instead of a new one: \"+\" → Quick Chat → type → Back → Quick\n * Chat finds the draft.\n */\n readonly kept?: readonly CanvasHistoryEntry[] | undefined;\n /**\n * Where Forward goes (newest-to-visit LAST): every step Back left, in order.\n * A navigate to anything else clears it, as in a browser. Absent = no Forward.\n */\n readonly forward?: readonly CanvasHistoryEntry[] | undefined;\n /**\n * The mounted body's identity. Minted when the item is created and kept by\n * `rekey`, so a draft that receives its durable id keeps its live body.\n * Absent on items saved before 0.5.0 (the item id stands in).\n */\n readonly instance?: string | undefined;\n}\n\nexport interface CanvasPane {\n readonly id: CanvasPaneId;\n readonly itemIds: readonly CanvasItemId[];\n readonly activeItemId: CanvasItemId | null;\n}\n\n/** \"horizontal\" = children side by side; \"vertical\" = children stacked. */\nexport type CanvasOrientation = \"horizontal\" | \"vertical\";\n\nexport type CanvasLayoutNode =\n | { readonly type: \"pane\"; readonly paneId: CanvasPaneId }\n | {\n readonly type: \"split\";\n readonly id: CanvasSplitId;\n readonly orientation: CanvasOrientation;\n readonly children: readonly CanvasLayoutNode[];\n /** Fractions, one per child, summing to 1. */\n readonly sizes: readonly number[];\n };\n\n/**\n * What one window shows: its column's visibility, full screen, width and its\n * own tree of panes. Panes and items are shared across windows (ids are\n * global), so moving a tab between windows is an ordinary move.\n */\nexport interface CanvasWindowFrame {\n readonly isOpen: boolean;\n /**\n * \"Expanded\": the column fills everything the HOST gives it (the web: the\n * whole window; the desktop: everything right of the sidebar). One flag —\n * the host's placement decides what \"everything\" is.\n */\n readonly isFullscreen: boolean;\n /** Column width in CSS pixels; null until the person drags it — the host's layout rule decides. */\n readonly width: number | null;\n readonly layout: CanvasLayoutNode;\n readonly focusedPaneId: CanvasPaneId;\n}\n\n/** A window other than the main one. */\nexport interface CanvasExtraWindow extends CanvasWindowFrame {\n readonly id: CanvasWindowId;\n /**\n * \"window\": another app window with its own column.\n * \"pop-out\": a window holding tabs popped out of `home`; \"Dock back\" returns them there.\n */\n readonly role: \"window\" | \"pop-out\";\n /** Where this window's tabs go when it closes or a tab docks back. */\n readonly home: CanvasWindowId;\n}\n\n/**\n * The whole canvas. The top-level frame fields ARE the main window's frame, so\n * a single-window host reads `state.isOpen`, `state.layout`… exactly as before;\n * every other window lives in `windows`.\n */\nexport interface CanvasState extends CanvasWindowFrame {\n readonly version: 1;\n /** Windows other than the main one. Empty for single-window hosts. Never restored after a reload. */\n readonly windows: { readonly [windowId: string]: CanvasExtraWindow };\n readonly panes: { readonly [paneId: string]: CanvasPane };\n readonly items: { readonly [itemId: string]: CanvasItem };\n /** Monotonic counter for minting pane/split ids — keeps the reducer pure. */\n readonly seq: number;\n /** True once a persisted snapshot was applied (or there was none). */\n readonly hydrated: boolean;\n}\n\n/** Where a newly opened item goes. Existing items never move on open. */\nexport type CanvasOpenTarget =\n | \"focused\"\n | \"split-right\"\n | \"split-down\"\n | { readonly paneId: CanvasPaneId };\n\n/** Where a NEW item of a kind prefers to open while the canvas already shows something. */\nexport type CanvasPreferredTarget = \"focused\" | \"split-right\" | \"split-down\";\n\n/** What a tab navigates to in place. */\nexport interface CanvasNavigateInput {\n readonly kind: string;\n readonly key: string;\n readonly title?: string | null | undefined;\n readonly data?: CanvasJson | undefined;\n}\n\nexport interface CanvasOpenInput {\n readonly kind: string;\n /** Which window a NEW item opens in. Default: the controller's window (main). An existing item stays where it is. */\n readonly windowId?: CanvasWindowId | undefined;\n readonly key: string;\n readonly title?: string | null | undefined;\n readonly data?: CanvasJson | undefined;\n readonly target?: CanvasOpenTarget | undefined;\n /** Reveal the canvas when it is put away. Default true. */\n readonly reveal?: boolean | undefined;\n /** Make the item the pane's active tab. Default true. */\n readonly activate?: boolean | undefined;\n}\n\nexport const CANVAS_MIN_WIDTH = 360;\nexport const CANVAS_DEFAULT_WIDTH = 640;\nexport const CANVAS_MIN_SPLIT_FRACTION = 0.12;\n\n/** A rectangle in window CSS pixels (getBoundingClientRect coordinates). */\nexport interface CanvasRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n","import type { CanvasItemId, CanvasJson, CanvasPaneId, CanvasSplitId, CanvasWindowId } from \"./types\";\n\nconst SEP = \"::\";\n\nexport function canvasItemId(kind: string, key: string): CanvasItemId {\n return `${kind}${SEP}${key}` as CanvasItemId;\n}\n\nexport function parseCanvasItemId(id: CanvasItemId): { kind: string; key: string } {\n const at = id.indexOf(SEP);\n return at < 0 ? { kind: id, key: \"\" } : { kind: id.slice(0, at), key: id.slice(at + SEP.length) };\n}\n\nexport function paneIdFromSeq(seq: number): CanvasPaneId {\n return `pane-${seq}` as CanvasPaneId;\n}\n\nexport function splitIdFromSeq(seq: number): CanvasSplitId {\n return `split-${seq}` as CanvasSplitId;\n}\n\n/**\n * Returns the path of the first value that is NOT plain JSON, or null when the\n * whole value is JSON. Functions, class instances, Dates, Maps, NaN and\n * Infinity all fail — they would silently vanish or change on persist.\n */\nexport function findNonJson(value: unknown, path = \"data\"): string | null {\n if (value === null) return null;\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return null;\n case \"number\":\n return Number.isFinite(value) ? null : path;\n case \"object\": {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const bad = findNonJson(value[i], `${path}[${i}]`);\n if (bad) return bad;\n }\n return null;\n }\n const proto = Object.getPrototypeOf(value) as unknown;\n if (proto !== Object.prototype && proto !== null) return path;\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (v === undefined) continue;\n const bad = findNonJson(v, `${path}.${k}`);\n if (bad) return bad;\n }\n return null;\n }\n default:\n return path;\n }\n}\n\nexport function isCanvasJson(value: unknown): value is CanvasJson {\n return findNonJson(value) === null;\n}\n\n/** Brands a host's window id. `CANVAS_MAIN_WINDOW` is the default window. */\nexport function canvasWindowId(id: string): CanvasWindowId {\n return id as CanvasWindowId;\n}\n","/**\n * Pure helpers over the canvas layout tree. Every function returns a new tree\n * and never mutates its input.\n */\n\nimport {\n CANVAS_MIN_SPLIT_FRACTION,\n type CanvasLayoutNode,\n type CanvasOrientation,\n type CanvasPaneId,\n type CanvasSplitId,\n} from \"./types\";\n\nexport function listPaneIds(node: CanvasLayoutNode): CanvasPaneId[] {\n if (node.type === \"pane\") return [node.paneId];\n return node.children.flatMap(listPaneIds);\n}\n\nexport function containsPane(node: CanvasLayoutNode, paneId: CanvasPaneId): boolean {\n if (node.type === \"pane\") return node.paneId === paneId;\n return node.children.some((child) => containsPane(child, paneId));\n}\n\nfunction evenSizes(count: number): number[] {\n return Array.from({ length: count }, () => 1 / count);\n}\n\n/** Renormalizes to sum 1; falls back to even sizes for garbage input. */\nexport function normalizeSizes(sizes: readonly number[], count: number): number[] {\n if (sizes.length !== count || sizes.some((s) => !Number.isFinite(s) || s <= 0)) {\n return evenSizes(count);\n }\n const total = sizes.reduce((sum, s) => sum + s, 0);\n return sizes.map((s) => s / total);\n}\n\n/**\n * Places `newPaneId` beside `paneId`. When the pane's parent already splits in\n * the same orientation the new pane becomes a sibling (sharing the pane's\n * space); otherwise the pane is replaced by a new two-way split.\n */\nexport function splitPane(\n node: CanvasLayoutNode,\n paneId: CanvasPaneId,\n newPaneId: CanvasPaneId,\n orientation: CanvasOrientation,\n newSplitId: CanvasSplitId,\n /** The existing pane's share of the space it gives up (0.7 = the 70/30 divider). */\n firstShare = 0.5,\n): CanvasLayoutNode {\n const first = Number.isFinite(firstShare) ? Math.min(1 - CANVAS_MIN_SPLIT_FRACTION, Math.max(CANVAS_MIN_SPLIT_FRACTION, firstShare)) : 0.5;\n if (node.type === \"pane\") {\n if (node.paneId !== paneId) return node;\n return {\n type: \"split\",\n id: newSplitId,\n orientation,\n children: [node, { type: \"pane\", paneId: newPaneId }],\n sizes: [first, 1 - first],\n };\n }\n const index = node.children.findIndex(\n (child) => child.type === \"pane\" && child.paneId === paneId,\n );\n if (index >= 0 && node.orientation === orientation) {\n const share = node.sizes[index] ?? 1 / node.children.length;\n const children = [...node.children];\n children.splice(index + 1, 0, { type: \"pane\", paneId: newPaneId });\n const sizes = [...node.sizes];\n sizes.splice(index, 1, share * first, share * (1 - first));\n return { ...node, children, sizes: normalizeSizes(sizes, children.length) };\n }\n return {\n ...node,\n children: node.children.map((child) =>\n splitPane(child, paneId, newPaneId, orientation, newSplitId, first),\n ),\n };\n}\n\n/**\n * Removes a pane. A split left with one child collapses into that child, and\n * the removed pane's space goes to its siblings proportionally. Returns null\n * when the tree held only that pane.\n */\nexport function removePane(\n node: CanvasLayoutNode,\n paneId: CanvasPaneId,\n): CanvasLayoutNode | null {\n if (node.type === \"pane\") return node.paneId === paneId ? null : node;\n const children: CanvasLayoutNode[] = [];\n const sizes: number[] = [];\n node.children.forEach((child, i) => {\n const next = removePane(child, paneId);\n if (next) {\n children.push(next);\n sizes.push(node.sizes[i] ?? 1 / node.children.length);\n }\n });\n if (children.length === 0) return null;\n if (children.length === 1) return children[0] ?? null;\n return { ...node, children, sizes: normalizeSizes(sizes, children.length) };\n}\n\nexport function containsSplit(node: CanvasLayoutNode, splitId: CanvasSplitId): boolean {\n if (node.type === \"pane\") return false;\n return node.id === splitId || node.children.some((child) => containsSplit(child, splitId));\n}\n\nexport function resizeSplit(\n node: CanvasLayoutNode,\n splitId: CanvasSplitId,\n sizes: readonly number[],\n): CanvasLayoutNode {\n if (node.type === \"pane\") return node;\n if (node.id === splitId) {\n const clamped = sizes.map((s) => Math.max(CANVAS_MIN_SPLIT_FRACTION, s));\n return { ...node, sizes: normalizeSizes(clamped, node.children.length) };\n }\n return {\n ...node,\n children: node.children.map((child) => resizeSplit(child, splitId, sizes)),\n };\n}\n\n/** True when the tree is well formed against the set of known panes. */\nexport function isValidLayout(\n node: unknown,\n knownPanes: ReadonlySet<string>,\n seen: Set<string> = new Set(),\n): node is CanvasLayoutNode {\n if (!node || typeof node !== \"object\") return false;\n const n = node as Record<string, unknown>;\n if (n.type === \"pane\") {\n const id = n.paneId;\n if (typeof id !== \"string\" || !knownPanes.has(id) || seen.has(id)) return false;\n seen.add(id);\n return true;\n }\n if (n.type !== \"split\") return false;\n if (typeof n.id !== \"string\") return false;\n if (n.orientation !== \"horizontal\" && n.orientation !== \"vertical\") return false;\n if (!Array.isArray(n.children) || n.children.length < 2) return false;\n if (!Array.isArray(n.sizes) || n.sizes.length !== n.children.length) return false;\n return n.children.every((child) => isValidLayout(child, knownPanes, seen));\n}\n","/**\n * THE canvas reducer. Plain Redux-compatible reducer + action creators with no\n * Redux Toolkit dependency, so it mounts in a host's RTK store\n * (`canvasHost: canvasReducer`), runs inside the package's own standalone\n * store, or runs in a desktop main process behind IPC — identical behaviour.\n *\n * Identity law: an item is `kind::key`. Opening an item that is already on the\n * canvas never duplicates it — it refreshes its data/title, activates its tab\n * and focuses its pane, wherever that pane is (in whichever window).\n *\n * Windows: the top-level frame fields are the MAIN window's; every other window\n * (a second app window, a popped-out tab) lives in `state.windows`. Panes and\n * items are global, so a tab moves between windows like between panes.\n */\n\nimport { canvasItemId, paneIdFromSeq, splitIdFromSeq } from \"./ids\";\nimport { containsPane, containsSplit, isValidLayout, listPaneIds, normalizeSizes, removePane, resizeSplit, splitPane } from \"./layout\";\nimport {\n CANVAS_HISTORY_LIMIT,\n CANVAS_KEEP_ALIVE_DEPTH,\n CANVAS_LAUNCHER_KIND,\n CANVAS_MAIN_WINDOW,\n CANVAS_MIN_WIDTH,\n type CanvasExtraWindow,\n type CanvasHistoryEntry,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasLayoutNode,\n type CanvasNavigateInput,\n type CanvasOpenInput,\n type CanvasOrientation,\n type CanvasPane,\n type CanvasPaneId,\n type CanvasSplitId,\n type CanvasState,\n type CanvasWindowFrame,\n type CanvasWindowId,\n} from \"./types\";\n\nconst P = \"matrxCanvas/\";\n\n/** What happens to a closing window's tabs: back to its home window, or closed with it. */\nexport type CanvasWindowCloseMode = \"dock\" | \"close\";\n\nexport type CanvasAction =\n | { type: `${typeof P}open`; payload: CanvasOpenInput & { now: number; splitShare?: number | undefined } }\n | { type: `${typeof P}update`; payload: { itemId: CanvasItemId; data?: CanvasJson | undefined; title?: string | null | undefined; now: number } }\n | { type: `${typeof P}rekey`; payload: { itemId: CanvasItemId; key: string } }\n | { type: `${typeof P}navigate`; payload: { itemId: CanvasItemId; to: CanvasNavigateInput; now: number } }\n | { type: `${typeof P}back`; payload: { itemId: CanvasItemId; now: number } }\n | { type: `${typeof P}forward`; payload: { itemId: CanvasItemId; now: number } }\n | { type: `${typeof P}closeItem`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}closeOthers`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}activate`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}focusPane`; payload: { paneId: CanvasPaneId } }\n | { type: `${typeof P}moveItem`; payload: { itemId: CanvasItemId; toPaneId: CanvasPaneId; index?: number | undefined } }\n | { type: `${typeof P}splitPane`; payload: { paneId: CanvasPaneId; orientation: CanvasOrientation; moveItemId?: CanvasItemId | undefined; share?: number | undefined } }\n | { type: `${typeof P}closePane`; payload: { paneId: CanvasPaneId } }\n | { type: `${typeof P}resizeSplit`; payload: { splitId: CanvasSplitId; sizes: readonly number[] } }\n | { type: `${typeof P}setOpen`; payload: { open: boolean; windowId?: CanvasWindowId | undefined } }\n | { type: `${typeof P}toggle`; payload?: { windowId?: CanvasWindowId | undefined } | undefined }\n | { type: `${typeof P}setFullscreen`; payload: { fullscreen: boolean; windowId?: CanvasWindowId | undefined } }\n | { type: `${typeof P}setWidth`; payload: { width: number; windowId?: CanvasWindowId | undefined } }\n | { type: `${typeof P}popOut`; payload: { itemId: CanvasItemId; windowId: CanvasWindowId } }\n | { type: `${typeof P}dockBack`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}closeWindow`; payload: { windowId: CanvasWindowId; mode: CanvasWindowCloseMode } }\n | { type: `${typeof P}hydrate`; payload: { snapshot: CanvasState | null } }\n | { type: `${typeof P}reset` };\n\nconst win = (windowId: CanvasWindowId | undefined) => (windowId && windowId !== CANVAS_MAIN_WINDOW ? { windowId } : {});\n\nexport const canvasActions = {\n open: (input: CanvasOpenInput, options?: { splitShare?: number | undefined }): CanvasAction => ({\n type: `${P}open`,\n payload: { ...input, now: Date.now(), ...(options?.splitShare !== undefined ? { splitShare: options.splitShare } : {}) },\n }),\n update: (itemId: CanvasItemId, patch: { data?: CanvasJson | undefined; title?: string | null | undefined }): CanvasAction => ({\n type: `${P}update`,\n payload: { itemId, ...patch, now: Date.now() },\n }),\n /** Gives an item a new identity in place (e.g. a draft that was just saved and now has an id). */\n rekey: (itemId: CanvasItemId, key: string): CanvasAction => ({ type: `${P}rekey`, payload: { itemId, key } }),\n /** Replaces a tab's content with another item in place, remembering what it showed (Back returns). */\n navigate: (itemId: CanvasItemId, to: CanvasNavigateInput): CanvasAction => ({ type: `${P}navigate`, payload: { itemId, to, now: Date.now() } }),\n /** Returns a tab to what it showed before its last navigate. */\n back: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}back`, payload: { itemId, now: Date.now() } }),\n /** Re-does the last Back (the step Back left), with that step's live body. */\n forward: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}forward`, payload: { itemId, now: Date.now() } }),\n closeItem: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}closeItem`, payload: { itemId } }),\n closeOthers: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}closeOthers`, payload: { itemId } }),\n activate: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}activate`, payload: { itemId } }),\n focusPane: (paneId: CanvasPaneId): CanvasAction => ({ type: `${P}focusPane`, payload: { paneId } }),\n moveItem: (itemId: CanvasItemId, toPaneId: CanvasPaneId, index?: number): CanvasAction => ({\n type: `${P}moveItem`,\n payload: { itemId, toPaneId, index },\n }),\n /** `share` = the existing pane's fraction of the space (layout rules' stackSplit / sideSplit). */\n splitPane: (paneId: CanvasPaneId, orientation: CanvasOrientation, moveItemId?: CanvasItemId, share?: number): CanvasAction => ({\n type: `${P}splitPane`,\n payload: { paneId, orientation, moveItemId, ...(share !== undefined ? { share } : {}) },\n }),\n closePane: (paneId: CanvasPaneId): CanvasAction => ({ type: `${P}closePane`, payload: { paneId } }),\n resizeSplit: (splitId: CanvasSplitId, sizes: readonly number[]): CanvasAction => ({\n type: `${P}resizeSplit`,\n payload: { splitId, sizes },\n }),\n setOpen: (open: boolean, windowId?: CanvasWindowId): CanvasAction => ({ type: `${P}setOpen`, payload: { open, ...win(windowId) } }),\n toggle: (windowId?: CanvasWindowId): CanvasAction =>\n windowId && windowId !== CANVAS_MAIN_WINDOW ? { type: `${P}toggle`, payload: { windowId } } : { type: `${P}toggle` },\n setFullscreen: (fullscreen: boolean, windowId?: CanvasWindowId): CanvasAction => ({\n type: `${P}setFullscreen`,\n payload: { fullscreen, ...win(windowId) },\n }),\n setWidth: (width: number, windowId?: CanvasWindowId): CanvasAction => ({ type: `${P}setWidth`, payload: { width, ...win(windowId) } }),\n /** Moves a tab into its own pop-out window `windowId` (made by the host's popOut port). */\n popOut: (itemId: CanvasItemId, windowId: CanvasWindowId): CanvasAction => ({ type: `${P}popOut`, payload: { itemId, windowId } }),\n /** Returns a popped-out tab to the window it came from. */\n dockBack: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}dockBack`, payload: { itemId } }),\n /** A host window closed: its tabs dock home (default) or close with it. The main window never closes. */\n closeWindow: (windowId: CanvasWindowId, mode: CanvasWindowCloseMode = \"dock\"): CanvasAction => ({\n type: `${P}closeWindow`,\n payload: { windowId, mode },\n }),\n hydrate: (snapshot: CanvasState | null): CanvasAction => ({ type: `${P}hydrate`, payload: { snapshot } }),\n reset: (): CanvasAction => ({ type: `${P}reset` }),\n} as const;\n\nexport function isCanvasAction(action: unknown): action is CanvasAction {\n return (\n !!action &&\n typeof action === \"object\" &&\n typeof (action as { type?: unknown }).type === \"string\" &&\n (action as { type: string }).type.startsWith(P)\n );\n}\n\nexport function createInitialCanvasState(): CanvasState {\n const paneId = paneIdFromSeq(1);\n return {\n version: 1,\n isOpen: false,\n isFullscreen: false,\n width: null,\n layout: { type: \"pane\", paneId },\n focusedPaneId: paneId,\n windows: {},\n panes: { [paneId]: { id: paneId, itemIds: [], activeItemId: null } },\n items: {},\n seq: 1,\n hydrated: false,\n };\n}\n\n// ── window helpers ─────────────────────────────────────────────────────────\n\n/** Every window id, main first. */\nexport function listCanvasWindowIds(state: CanvasState): CanvasWindowId[] {\n return [CANVAS_MAIN_WINDOW, ...(Object.keys(state.windows ?? {}) as CanvasWindowId[])];\n}\n\n/** A window's frame, or null when that window does not exist. */\nexport function canvasWindowFrame(state: CanvasState, windowId: CanvasWindowId = CANVAS_MAIN_WINDOW): CanvasWindowFrame | null {\n return windowId === CANVAS_MAIN_WINDOW ? state : (state.windows?.[windowId] ?? null);\n}\n\n/** The window whose layout holds this pane. */\nexport function canvasWindowOfPane(state: CanvasState, paneId: CanvasPaneId): CanvasWindowId | null {\n for (const id of listCanvasWindowIds(state)) {\n const frame = canvasWindowFrame(state, id);\n if (frame && containsPane(frame.layout, paneId)) return id;\n }\n return null;\n}\n\n/** The window an item is in right now (null when it is not on the canvas). */\nexport function canvasWindowOfItem(state: CanvasState, itemId: CanvasItemId): CanvasWindowId | null {\n const pane = paneOf(state, itemId);\n return pane ? canvasWindowOfPane(state, pane.id) : null;\n}\n\ntype FramePatch = { -readonly [K in keyof CanvasWindowFrame]?: CanvasWindowFrame[K] };\n\nfunction withFrame(state: CanvasState, windowId: CanvasWindowId, patch: FramePatch): CanvasState {\n if (windowId === CANVAS_MAIN_WINDOW) return { ...state, ...patch };\n const current = state.windows[windowId];\n if (!current) return state;\n return { ...state, windows: { ...state.windows, [windowId]: { ...current, ...patch } } };\n}\n\n/** A non-main window comes into being the first time something targets it. */\nfunction ensureWindow(state: CanvasState, windowId: CanvasWindowId, role: CanvasExtraWindow[\"role\"] = \"window\", home: CanvasWindowId = CANVAS_MAIN_WINDOW): CanvasState {\n if (windowId === CANVAS_MAIN_WINDOW || state.windows[windowId]) return state;\n const seq = state.seq + 1;\n const paneId = paneIdFromSeq(seq);\n const frame: CanvasExtraWindow = {\n id: windowId,\n role,\n home,\n isOpen: false,\n isFullscreen: false,\n width: null,\n layout: { type: \"pane\", paneId },\n focusedPaneId: paneId,\n };\n return {\n ...state,\n seq,\n panes: { ...state.panes, [paneId]: { id: paneId, itemIds: [], activeItemId: null } },\n windows: { ...state.windows, [windowId]: frame },\n };\n}\n\nfunction removeWindow(state: CanvasState, windowId: CanvasWindowId): CanvasState {\n const frame = state.windows[windowId];\n if (!frame) return state;\n const panes = { ...state.panes };\n for (const paneId of listPaneIds(frame.layout)) delete panes[paneId];\n const windows = { ...state.windows };\n delete windows[windowId];\n return { ...state, panes, windows };\n}\n\nfunction windowItemIds(state: CanvasState, windowId: CanvasWindowId): CanvasItemId[] {\n const frame = canvasWindowFrame(state, windowId);\n if (!frame) return [];\n return listPaneIds(frame.layout).flatMap((paneId) => state.panes[paneId]?.itemIds ?? []);\n}\n\n/** A pop-out window left with no tabs has nothing to show and goes away. */\nfunction dropEmptyPopOut(state: CanvasState, windowId: CanvasWindowId | null): CanvasState {\n if (!windowId || windowId === CANVAS_MAIN_WINDOW) return state;\n const frame = state.windows[windowId];\n if (!frame || frame.role !== \"pop-out\" || windowItemIds(state, windowId).length > 0) return state;\n return removeWindow(state, windowId);\n}\n\n// ── pane helpers ───────────────────────────────────────────────────────────\n\nfunction paneOf(state: CanvasState, itemId: CanvasItemId): CanvasPane | null {\n for (const pane of Object.values(state.panes)) {\n if (pane.itemIds.includes(itemId)) return pane;\n }\n return null;\n}\n\nfunction withPane(state: CanvasState, pane: CanvasPane): CanvasState {\n return { ...state, panes: { ...state.panes, [pane.id]: pane } };\n}\n\nfunction focus(state: CanvasState, paneId: CanvasPaneId): CanvasState {\n const windowId = canvasWindowOfPane(state, paneId);\n return windowId ? withFrame(state, windowId, { focusedPaneId: paneId }) : state;\n}\n\n/** After removing `itemId` from a tab list, the neighbour that takes focus. */\nfunction nextActive(itemIds: readonly CanvasItemId[], removed: CanvasItemId, current: CanvasItemId | null): CanvasItemId | null {\n if (current !== removed) return current;\n const index = itemIds.indexOf(removed);\n const rest = itemIds.filter((id) => id !== removed);\n return rest[Math.min(index, rest.length - 1)] ?? null;\n}\n\nfunction detachItem(state: CanvasState, itemId: CanvasItemId): CanvasState {\n const pane = paneOf(state, itemId);\n if (!pane) return state;\n return withPane(state, {\n ...pane,\n itemIds: pane.itemIds.filter((id) => id !== itemId),\n activeItemId: nextActive(pane.itemIds, itemId, pane.activeItemId),\n });\n}\n\nfunction dropPane(state: CanvasState, paneId: CanvasPaneId): CanvasState {\n const windowId = canvasWindowOfPane(state, paneId);\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!windowId || !frame) return state;\n const layout = removePane(frame.layout, paneId);\n if (!layout) return state; // never remove a window's last pane\n const panes = { ...state.panes };\n delete panes[paneId];\n const focusedPaneId = frame.focusedPaneId === paneId ? (listPaneIds(layout)[0] ?? frame.focusedPaneId) : frame.focusedPaneId;\n return withFrame({ ...state, panes }, windowId, { layout, focusedPaneId });\n}\n\nfunction addSplit(\n state: CanvasState,\n paneId: CanvasPaneId,\n orientation: CanvasOrientation,\n share: number | undefined,\n): { state: CanvasState; newPaneId: CanvasPaneId } | null {\n const windowId = canvasWindowOfPane(state, paneId);\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!windowId || !frame) return null;\n const seq = state.seq + 1;\n const newPaneId = paneIdFromSeq(seq);\n const layout = splitPane(frame.layout, paneId, newPaneId, orientation, splitIdFromSeq(seq), share ?? 0.5);\n const next = withFrame(\n { ...state, seq, panes: { ...state.panes, [newPaneId]: { id: newPaneId, itemIds: [], activeItemId: null } } },\n windowId,\n { layout, focusedPaneId: newPaneId },\n );\n return { newPaneId, state: next };\n}\n\nfunction insertInto(state: CanvasState, paneId: CanvasPaneId, itemId: CanvasItemId, activate: boolean, index?: number): CanvasState {\n const pane = state.panes[paneId];\n if (!pane) return state;\n const itemIds = [...pane.itemIds.filter((id) => id !== itemId)];\n const at = index === undefined ? afterActive(itemIds, pane.activeItemId) : Math.max(0, Math.min(index, itemIds.length));\n itemIds.splice(at, 0, itemId);\n return withPane(state, {\n ...pane,\n itemIds,\n activeItemId: activate || pane.activeItemId === null ? itemId : pane.activeItemId,\n });\n}\n\n/** New tabs open right after the active tab, the way browsers do it. */\nfunction afterActive(itemIds: readonly CanvasItemId[], active: CanvasItemId | null): number {\n const index = active ? itemIds.indexOf(active) : -1;\n return index < 0 ? itemIds.length : index + 1;\n}\n\n/** Moves one item into another window's focused pane (docking, folding). */\nfunction sendHome(state: CanvasState, itemId: CanvasItemId, home: CanvasWindowId, activate: boolean): CanvasState {\n const homeFrame = canvasWindowFrame(state, home) ?? state;\n const target = canvasWindowFrame(state, home) ? home : CANVAS_MAIN_WINDOW;\n let next = detachItem(state, itemId);\n next = insertInto(next, homeFrame.focusedPaneId, itemId, activate);\n return activate ? withFrame(next, target, { focusedPaneId: homeFrame.focusedPaneId }) : next;\n}\n\n/** A new item. `instance` names its mounted body for as long as the item lives (rekey keeps it). */\nfunction newItem(\n kind: string,\n key: string,\n title: string | null,\n data: CanvasJson,\n now: number,\n steps?: {\n readonly history?: readonly CanvasHistoryEntry[];\n readonly kept?: readonly CanvasHistoryEntry[];\n readonly forward?: readonly CanvasHistoryEntry[];\n readonly instance?: string | undefined;\n },\n): CanvasItem {\n const id = canvasItemId(kind, key);\n const history = steps?.history ?? [];\n const kept = steps?.kept ?? [];\n const forward = steps?.forward ?? [];\n return {\n id,\n kind,\n key,\n title,\n data,\n openedAt: now,\n updatedAt: now,\n // A reused instance is the SAME live body coming back (Back, or returning to a kept step).\n instance: steps?.instance ?? `${now.toString(36)}:${id}`,\n ...(history.length > 0 ? { history: history.slice(-CANVAS_HISTORY_LIMIT) } : {}),\n ...(kept.length > 0 ? { kept: kept.slice(-CANVAS_KEEP_ALIVE_DEPTH) } : {}),\n ...(forward.length > 0 ? { forward: forward.slice(-CANVAS_HISTORY_LIMIT) } : {}),\n };\n}\n\nfunction historyEntry(item: CanvasItem): CanvasHistoryEntry {\n return { kind: item.kind, key: item.key, title: item.title, data: item.data, ...(item.instance ? { instance: item.instance } : {}) };\n}\n\n/**\n * Puts `next` where `current` is (same pane, same position, same active state)\n * and drops `current`. Both identities must differ and `next` must be absent.\n */\nfunction replaceInPlace(state: CanvasState, current: CanvasItem, next: CanvasItem): CanvasState {\n const pane = paneOf(state, current.id);\n if (!pane) return state;\n const items = { ...state.items, [next.id]: next };\n delete items[current.id];\n const withItems: CanvasState = { ...state, items };\n const replaced = withPane(withItems, {\n ...pane,\n itemIds: pane.itemIds.map((id) => (id === current.id ? next.id : id)),\n activeItemId: pane.activeItemId === current.id ? next.id : pane.activeItemId,\n });\n return focus(replaced, pane.id);\n}\n\n/** Focuses an existing item wherever it is and reveals its window. */\nfunction focusExisting(state: CanvasState, itemId: CanvasItemId): CanvasState {\n const pane = paneOf(state, itemId);\n if (!pane) return state;\n const next = focus(withPane(state, { ...pane, activeItemId: itemId }), pane.id);\n const windowId = canvasWindowOfPane(next, pane.id);\n return windowId ? withFrame(next, windowId, { isOpen: true }) : next;\n}\n\nfunction sanitizeHistory(raw: unknown): CanvasHistoryEntry[] {\n if (!Array.isArray(raw)) return [];\n const out: CanvasHistoryEntry[] = [];\n for (const entry of raw as unknown[]) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Partial<CanvasHistoryEntry>;\n if (typeof e.kind !== \"string\" || typeof e.key !== \"string\") continue;\n out.push({\n kind: e.kind,\n key: e.key,\n title: typeof e.title === \"string\" ? e.title : null,\n data: e.data ?? null,\n ...(typeof e.instance === \"string\" && e.instance ? { instance: e.instance } : {}),\n });\n }\n return out.slice(-CANVAS_HISTORY_LIMIT);\n}\n\n/** A saved item with only the fields this version understands, history validated. */\nfunction sanitizeItem(item: CanvasItem): CanvasItem {\n const history = sanitizeHistory((item as { history?: unknown }).history);\n const kept = sanitizeHistory((item as { kept?: unknown }).kept).slice(-CANVAS_KEEP_ALIVE_DEPTH);\n const forward = sanitizeHistory((item as { forward?: unknown }).forward);\n const { history: _history, kept: _kept, forward: _forward, instance, ...rest } = item;\n return {\n ...rest,\n ...(typeof instance === \"string\" && instance ? { instance } : {}),\n ...(history.length > 0 ? { history } : {}),\n ...(kept.length > 0 ? { kept } : {}),\n ...(forward.length > 0 ? { forward } : {}),\n };\n}\n\nfunction clampWidth(width: number): number | null {\n return Number.isFinite(width) ? Math.max(CANVAS_MIN_WIDTH, Math.round(width)) : null;\n}\n\n// ── memory ─────────────────────────────────────────────────────────────────\n\n/**\n * Every window but the main one is a session thing: its tabs come home to the\n * main window's focused pane (nothing is lost) and the window goes away. Used\n * for what is saved and for what is restored.\n */\nexport function foldCanvasWindows(state: CanvasState): CanvasState {\n const extra = Object.keys(state.windows ?? {}) as CanvasWindowId[];\n if (extra.length === 0) return state.windows ? state : { ...state, windows: {} };\n let next = state;\n for (const windowId of extra) {\n for (const itemId of windowItemIds(next, windowId)) next = sendHome(next, itemId, CANVAS_MAIN_WINDOW, false);\n next = removeWindow(next, windowId);\n }\n return next;\n}\n\n/**\n * Validates a persisted snapshot. Anything malformed is dropped back to the\n * initial state rather than half-applied — a corrupt layout must never crash\n * the shell. Extra windows are folded home; full screen never comes back.\n */\nexport function sanitizeCanvasSnapshot(raw: unknown): CanvasState | null {\n if (!raw || typeof raw !== \"object\") return null;\n const s = raw as Partial<CanvasState> & { windows?: unknown };\n if (s.version !== 1 || !s.panes || typeof s.panes !== \"object\" || !s.items || typeof s.items !== \"object\" || !s.layout) return null;\n const paneIds = new Set(Object.keys(s.panes));\n const seen = new Set<string>();\n if (!isValidLayout(s.layout, paneIds, seen)) return null;\n\n // Extra windows: each must be a well-formed frame over panes nobody else uses.\n const windows: Record<string, CanvasExtraWindow> = {};\n if (s.windows && typeof s.windows === \"object\") {\n for (const [id, value] of Object.entries(s.windows as Record<string, unknown>)) {\n if (!value || typeof value !== \"object\" || id === CANVAS_MAIN_WINDOW) continue;\n const w = value as Partial<CanvasExtraWindow>;\n const claimed = new Set(seen);\n if (!isValidLayout(w.layout, paneIds, claimed)) continue;\n for (const pane of claimed) seen.add(pane);\n const layoutPanes = listPaneIds(w.layout);\n const focused = w.focusedPaneId && layoutPanes.includes(w.focusedPaneId) ? w.focusedPaneId : layoutPanes[0];\n if (!focused) continue;\n windows[id] = {\n id: id as CanvasWindowId,\n role: w.role === \"pop-out\" ? \"pop-out\" : \"window\",\n home: typeof w.home === \"string\" ? (w.home as CanvasWindowId) : CANVAS_MAIN_WINDOW,\n isOpen: w.isOpen === true,\n isFullscreen: false,\n width: typeof w.width === \"number\" ? clampWidth(w.width) : null,\n layout: normalizeLayout(w.layout),\n focusedPaneId: focused,\n };\n }\n }\n // Every pane must belong to exactly one window's layout.\n if (seen.size !== paneIds.size) return null;\n\n const items: Record<string, CanvasItem> = {};\n for (const [id, item] of Object.entries(s.items)) {\n if (item && typeof item.kind === \"string\" && typeof item.key === \"string\" && canvasItemId(item.kind, item.key) === id) {\n items[id] = sanitizeItem(item);\n }\n }\n const placed = new Set<string>();\n const panes: Record<string, CanvasPane> = {};\n for (const [id, pane] of Object.entries(s.panes)) {\n const itemIds = (Array.isArray(pane.itemIds) ? pane.itemIds : []).filter((itemId) => itemId in items && !placed.has(itemId));\n for (const itemId of itemIds) placed.add(itemId);\n const activeItemId = pane.activeItemId && itemIds.includes(pane.activeItemId) ? pane.activeItemId : (itemIds[0] ?? null);\n panes[id] = { id: id as CanvasPaneId, itemIds, activeItemId };\n }\n const mainPanes = listPaneIds(s.layout);\n const focused = s.focusedPaneId && mainPanes.includes(s.focusedPaneId) ? s.focusedPaneId : mainPanes[0];\n if (!focused) return null;\n const layout = normalizeLayout(s.layout);\n // seq must stay ahead of every id already minted, or the next split collides.\n const highest = Math.max(highestIdNumber(layout), ...Object.values(windows).map((w) => highestIdNumber(w.layout)));\n const seq = Math.max(typeof s.seq === \"number\" && Number.isFinite(s.seq) ? s.seq : 0, highest);\n let state: CanvasState = {\n version: 1,\n isOpen: s.isOpen === true,\n // Full screen is a moment, not a preference: a reload never starts there.\n isFullscreen: false,\n width: typeof s.width === \"number\" ? clampWidth(s.width) : null,\n layout,\n focusedPaneId: focused,\n windows,\n panes,\n items,\n seq,\n hydrated: true,\n };\n state = foldCanvasWindows(state);\n // An item that lost its pane is put back where it can be seen, never kept invisible.\n for (const id of Object.keys(items) as CanvasItemId[]) {\n if (!placed.has(id)) state = insertInto(state, state.focusedPaneId, id, false);\n }\n return state;\n}\n\nfunction normalizeLayout(node: CanvasLayoutNode): CanvasLayoutNode {\n if (node.type === \"pane\") return node;\n return { ...node, sizes: normalizeSizes(node.sizes, node.children.length), children: node.children.map(normalizeLayout) };\n}\n\nfunction highestIdNumber(node: CanvasLayoutNode): number {\n const own = Number((node.type === \"pane\" ? node.paneId : node.id).split(\"-\").pop());\n const mine = Number.isFinite(own) ? own : 0;\n return node.type === \"pane\" ? mine : Math.max(mine, ...node.children.map(highestIdNumber));\n}\n\n// ── reducer ────────────────────────────────────────────────────────────────\n\nexport function canvasReducer(state: CanvasState = createInitialCanvasState(), action: { type: string }): CanvasState {\n if (!isCanvasAction(action)) return state;\n // A state saved before windows existed carries no `windows` map.\n if (!state.windows) state = { ...state, windows: {} };\n switch (action.type) {\n case `${P}open`: {\n const { kind, key, title, data, target = \"focused\", reveal = true, activate = true, now, splitShare } = action.payload;\n const itemId = canvasItemId(kind, key);\n const existing = state.items[itemId];\n let next = state;\n let revealIn: CanvasWindowId = action.payload.windowId ?? CANVAS_MAIN_WINDOW;\n if (existing) {\n const item: CanvasItem = {\n ...existing,\n ...(data !== undefined ? { data } : {}),\n ...(title !== undefined ? { title } : {}),\n updatedAt: now,\n };\n next = { ...next, items: { ...next.items, [itemId]: item } };\n const pane = paneOf(next, itemId);\n if (pane) {\n revealIn = canvasWindowOfPane(next, pane.id) ?? CANVAS_MAIN_WINDOW;\n if (activate) next = focus(withPane(next, { ...pane, activeItemId: itemId }), pane.id);\n } else {\n next = ensureWindow(next, revealIn);\n const frame = canvasWindowFrame(next, revealIn) ?? next;\n next = insertInto(next, frame.focusedPaneId, itemId, true);\n }\n } else {\n const item = newItem(kind, key, title ?? null, data ?? null, now);\n next = ensureWindow({ ...next, items: { ...next.items, [itemId]: item } }, revealIn);\n const frame = canvasWindowFrame(next, revealIn) ?? next;\n let paneId: CanvasPaneId = frame.focusedPaneId;\n if (typeof target === \"object\" && next.panes[target.paneId]) {\n paneId = target.paneId;\n revealIn = canvasWindowOfPane(next, paneId) ?? revealIn;\n } else if (target === \"split-right\" || target === \"split-down\") {\n const split = addSplit(next, frame.focusedPaneId, target === \"split-right\" ? \"horizontal\" : \"vertical\", splitShare);\n if (split) {\n next = split.state;\n paneId = split.newPaneId;\n }\n }\n next = insertInto(next, paneId, itemId, activate);\n if (activate) next = focus(next, paneId);\n }\n return reveal ? withFrame(next, revealIn, { isOpen: true }) : next;\n }\n case `${P}update`: {\n const { itemId, data, title, now } = action.payload;\n const item = state.items[itemId];\n if (!item) return state;\n return {\n ...state,\n items: {\n ...state.items,\n [itemId]: { ...item, ...(data !== undefined ? { data } : {}), ...(title !== undefined ? { title } : {}), updatedAt: now },\n },\n };\n }\n case `${P}rekey`: {\n const { itemId, key } = action.payload;\n const item = state.items[itemId];\n if (!item || item.key === key) return state;\n const nextId = canvasItemId(item.kind, key);\n // The new identity is already open elsewhere: keep that one, drop this.\n if (state.items[nextId]) return canvasReducer(canvasReducer(state, canvasActions.closeItem(itemId)), canvasActions.activate(nextId));\n const items = { ...state.items, [nextId]: { ...item, id: nextId, key } };\n delete items[itemId];\n const panes: Record<string, CanvasPane> = {};\n for (const pane of Object.values(state.panes)) {\n panes[pane.id] = pane.itemIds.includes(itemId)\n ? {\n ...pane,\n itemIds: pane.itemIds.map((id) => (id === itemId ? nextId : id)),\n activeItemId: pane.activeItemId === itemId ? nextId : pane.activeItemId,\n }\n : pane;\n }\n return { ...state, items, panes };\n }\n case `${P}navigate`: {\n const { itemId, to, now } = action.payload;\n const current = state.items[itemId];\n if (!current || !paneOf(state, itemId)) return state;\n const targetId = canvasItemId(to.kind, to.key);\n if (targetId === itemId) {\n // Navigating to itself is a refresh, never a history step.\n const refresh: CanvasAction = { type: `${P}update`, payload: { itemId, data: to.data, title: to.title, now } };\n return canvasReducer(state, refresh);\n }\n if (state.items[targetId]) {\n // Identity law: the thing is already open — focus it there, never a second copy.\n // A launcher tab has done its job and closes; any other tab keeps what it shows.\n const focused = focusExisting(state, targetId);\n return current.kind === CANVAS_LAUNCHER_KIND ? canvasReducer(focused, canvasActions.closeItem(itemId)) : focused;\n }\n const history = [...(current.history ?? []), historyEntry(current)];\n // Going to something this tab showed before Back left it: its live body comes back.\n const keptAll = current.kept ?? [];\n const keptIndex = keptAll.findIndex((entry) => canvasItemId(entry.kind, entry.key) === targetId);\n const revived = keptIndex >= 0 ? keptAll[keptIndex] : undefined;\n const kept = keptAll.filter((_, i) => i !== keptIndex);\n // Navigating to exactly where Forward points is a Forward; anywhere else ends the forward trail.\n const forwardAll = current.forward ?? [];\n const nextForward = forwardAll[forwardAll.length - 1];\n const forward = nextForward && canvasItemId(nextForward.kind, nextForward.key) === targetId ? forwardAll.slice(0, -1) : [];\n return replaceInPlace(\n state,\n current,\n newItem(\n to.kind,\n to.key,\n to.title !== undefined ? to.title : (revived?.title ?? null),\n to.data !== undefined ? to.data : (revived?.data ?? null),\n now,\n { history, kept, forward, instance: revived?.instance },\n ),\n );\n }\n case `${P}back`: {\n const { itemId, now } = action.payload;\n const current = state.items[itemId];\n const history = current?.history ?? [];\n const entry = history[history.length - 1];\n if (!current || !entry || !paneOf(state, itemId)) return state;\n const targetId = canvasItemId(entry.kind, entry.key);\n if (targetId === itemId) return state;\n if (state.items[targetId]) {\n // What Back would return to was opened elsewhere since: go there; this step is done.\n return focusExisting(canvasReducer(state, canvasActions.closeItem(itemId)), targetId);\n }\n // Back returns the SAME body (its instance) and keeps the one it leaves, so going forward again finds it.\n const kept = [...(current.kept ?? []).filter((k) => canvasItemId(k.kind, k.key) !== itemId), historyEntry(current)];\n const forward = [...(current.forward ?? []), historyEntry(current)];\n return replaceInPlace(\n state,\n current,\n newItem(entry.kind, entry.key, entry.title, entry.data, now, { history: history.slice(0, -1), kept, forward, instance: entry.instance }),\n );\n }\n case `${P}forward`: {\n const { itemId, now } = action.payload;\n const current = state.items[itemId];\n const forwardAll = current?.forward ?? [];\n const entry = forwardAll[forwardAll.length - 1];\n if (!current || !entry || !paneOf(state, itemId)) return state;\n const targetId = canvasItemId(entry.kind, entry.key);\n if (targetId === itemId) return state;\n if (state.items[targetId]) {\n // Where Forward points was opened elsewhere since: go there; this step is done (as Back does).\n return focusExisting(canvasReducer(state, canvasActions.closeItem(itemId)), targetId);\n }\n // Forward returns the SAME body Back left (its instance, still held in `kept`).\n const keptAll = current.kept ?? [];\n const revived = keptAll.find((k) => canvasItemId(k.kind, k.key) === targetId);\n const kept = keptAll.filter((k) => canvasItemId(k.kind, k.key) !== targetId);\n return replaceInPlace(\n state,\n current,\n newItem(entry.kind, entry.key, entry.title, entry.data, now, {\n history: [...(current.history ?? []), historyEntry(current)],\n kept,\n forward: forwardAll.slice(0, -1),\n instance: revived?.instance ?? entry.instance,\n }),\n );\n }\n case `${P}closeItem`: {\n const { itemId } = action.payload;\n if (!state.items[itemId]) return state;\n const pane = paneOf(state, itemId);\n const windowId = pane ? canvasWindowOfPane(state, pane.id) : null;\n let next = detachItem(state, itemId);\n const items = { ...next.items };\n delete items[itemId];\n next = { ...next, items };\n // A pane emptied by closing its last tab goes away, unless it is its window's only one.\n if (pane && next.panes[pane.id]?.itemIds.length === 0) next = dropPane(next, pane.id);\n return dropEmptyPopOut(next, windowId);\n }\n case `${P}closeOthers`: {\n const { itemId } = action.payload;\n const pane = paneOf(state, itemId);\n if (!pane) return state;\n const items = { ...state.items };\n for (const id of pane.itemIds) if (id !== itemId) delete items[id];\n return { ...withPane(state, { ...pane, itemIds: [itemId], activeItemId: itemId }), items };\n }\n case `${P}activate`: {\n const pane = paneOf(state, action.payload.itemId);\n if (!pane) return state;\n return focus(withPane(state, { ...pane, activeItemId: action.payload.itemId }), pane.id);\n }\n case `${P}focusPane`: {\n const windowId = canvasWindowOfPane(state, action.payload.paneId);\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!windowId || !frame || frame.focusedPaneId === action.payload.paneId) return state;\n return withFrame(state, windowId, { focusedPaneId: action.payload.paneId });\n }\n case `${P}moveItem`: {\n const { itemId, toPaneId, index } = action.payload;\n const from = paneOf(state, itemId);\n if (!from || !state.panes[toPaneId]) return state;\n // Dropped back onto its own pane with no position: nothing moved.\n if (from.id === toPaneId && index === undefined) return canvasReducer(state, canvasActions.focusPane(toPaneId));\n const fromWindow = canvasWindowOfPane(state, from.id);\n let next = from.id === toPaneId ? state : detachItem(state, itemId);\n next = focus(insertInto(next, toPaneId, itemId, true, index), toPaneId);\n if (from.id !== toPaneId && next.panes[from.id]?.itemIds.length === 0) next = dropPane(next, from.id);\n return dropEmptyPopOut(next, fromWindow);\n }\n case `${P}splitPane`: {\n const { paneId, orientation, moveItemId, share } = action.payload;\n const pane = state.panes[paneId];\n if (!pane) return state;\n const split = addSplit(state, paneId, orientation, share);\n if (!split) return state;\n let next = split.state;\n // The new pane takes the requested tab when its old pane keeps something;\n // otherwise it starts empty and shows the launcher.\n if (moveItemId && pane.itemIds.includes(moveItemId) && pane.itemIds.length > 1) {\n next = detachItem(next, moveItemId);\n next = insertInto(next, split.newPaneId, moveItemId, true);\n }\n return next;\n }\n case `${P}closePane`: {\n const pane = state.panes[action.payload.paneId];\n const windowId = pane ? canvasWindowOfPane(state, pane.id) : null;\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!pane || !windowId || !frame) return state;\n const onlyPane = listPaneIds(frame.layout).length === 1;\n if (onlyPane) {\n // A pop-out's last pane closing closes the window; its tabs go home.\n if (windowId !== CANVAS_MAIN_WINDOW && state.windows[windowId]?.role === \"pop-out\") {\n return canvasReducer(state, canvasActions.closeWindow(windowId, \"dock\"));\n }\n // Closing the last pane puts the canvas away and KEEPS its tabs — the\n // toggle brings everything back exactly as it was.\n return withFrame(state, windowId, { isOpen: false, isFullscreen: false });\n }\n const items = { ...state.items };\n for (const id of pane.itemIds) delete items[id];\n return dropPane({ ...state, items }, pane.id);\n }\n case `${P}resizeSplit`: {\n const { splitId, sizes } = action.payload;\n for (const windowId of listCanvasWindowIds(state)) {\n const frame = canvasWindowFrame(state, windowId);\n if (frame && containsSplit(frame.layout, splitId)) {\n return withFrame(state, windowId, { layout: resizeSplit(frame.layout, splitId, sizes) });\n }\n }\n return state;\n }\n case `${P}setOpen`: {\n const { open, windowId = CANVAS_MAIN_WINDOW } = action.payload;\n const next = open ? ensureWindow(state, windowId) : state;\n const frame = canvasWindowFrame(next, windowId);\n if (!frame || frame.isOpen === open) return next;\n return withFrame(next, windowId, { isOpen: open, isFullscreen: open ? frame.isFullscreen : false });\n }\n case `${P}toggle`: {\n const windowId = action.payload?.windowId ?? CANVAS_MAIN_WINDOW;\n const next = ensureWindow(state, windowId);\n const frame = canvasWindowFrame(next, windowId);\n if (!frame) return state;\n return withFrame(next, windowId, { isOpen: !frame.isOpen, isFullscreen: frame.isOpen ? false : frame.isFullscreen });\n }\n case `${P}setFullscreen`: {\n const { fullscreen, windowId = CANVAS_MAIN_WINDOW } = action.payload;\n const next = fullscreen ? ensureWindow(state, windowId) : state;\n const frame = canvasWindowFrame(next, windowId);\n if (!frame) return state;\n return withFrame(next, windowId, { isFullscreen: fullscreen, isOpen: fullscreen ? true : frame.isOpen });\n }\n case `${P}setWidth`: {\n const { width, windowId = CANVAS_MAIN_WINDOW } = action.payload;\n const next = ensureWindow(state, windowId);\n return withFrame(next, windowId, { width: clampWidth(width) });\n }\n case `${P}popOut`: {\n const { itemId, windowId } = action.payload;\n const from = paneOf(state, itemId);\n if (!from || windowId === CANVAS_MAIN_WINDOW) return state;\n const fromWindow = canvasWindowOfPane(state, from.id) ?? CANVAS_MAIN_WINDOW;\n if (fromWindow === windowId) return state;\n let next = ensureWindow(state, windowId, \"pop-out\", fromWindow);\n const target = canvasWindowFrame(next, windowId);\n if (!target) return state;\n next = detachItem(next, itemId);\n next = insertInto(next, target.focusedPaneId, itemId, true);\n next = withFrame(next, windowId, { isOpen: true, focusedPaneId: target.focusedPaneId });\n if (next.panes[from.id]?.itemIds.length === 0) next = dropPane(next, from.id);\n next = dropEmptyPopOut(next, fromWindow);\n // The window it left has nothing left to show: put its column away.\n if (canvasWindowFrame(next, fromWindow) && windowItemIds(next, fromWindow).length === 0) {\n next = withFrame(next, fromWindow, { isOpen: false, isFullscreen: false });\n }\n return next;\n }\n case `${P}dockBack`: {\n const { itemId } = action.payload;\n const windowId = canvasWindowOfItem(state, itemId);\n if (!windowId || windowId === CANVAS_MAIN_WINDOW) return state;\n const frame = state.windows[windowId];\n if (!frame) return state;\n const home = canvasWindowFrame(state, frame.home) ? frame.home : CANVAS_MAIN_WINDOW;\n let next = sendHome(state, itemId, home, true);\n next = withFrame(next, home, { isOpen: true });\n const left = paneOf(state, itemId);\n if (left && next.panes[left.id]?.itemIds.length === 0) next = dropPane(next, left.id);\n return dropEmptyPopOut(next, windowId);\n }\n case `${P}closeWindow`: {\n const { windowId, mode } = action.payload;\n const frame = state.windows[windowId];\n if (!frame) return state;\n const itemIds = windowItemIds(state, windowId);\n let next = state;\n if (mode === \"close\") {\n const items = { ...next.items };\n for (const id of itemIds) delete items[id];\n next = { ...next, items };\n } else if (itemIds.length > 0) {\n const home = canvasWindowFrame(state, frame.home) ? frame.home : CANVAS_MAIN_WINDOW;\n const active = state.panes[frame.focusedPaneId]?.activeItemId ?? null;\n for (const id of itemIds) next = sendHome(next, id, home, id === active);\n next = withFrame(next, home, { isOpen: true });\n }\n return removeWindow(next, windowId);\n }\n case `${P}hydrate`: {\n const snapshot = action.payload.snapshot ? sanitizeCanvasSnapshot(action.payload.snapshot) : null;\n if (!snapshot) return { ...state, hydrated: true };\n // Anything opened before hydration finished wins over the snapshot.\n let next: CanvasState = snapshot;\n for (const item of Object.values(state.items)) {\n const pane = paneOf(state, item.id);\n next = { ...next, items: { ...next.items, [item.id]: item } };\n if (!paneOf(next, item.id)) next = insertInto(next, next.focusedPaneId, item.id, pane?.activeItemId === item.id);\n }\n return { ...next, isOpen: next.isOpen || state.isOpen, hydrated: true };\n }\n case `${P}reset`:\n return { ...createInitialCanvasState(), hydrated: true };\n default:\n return state;\n }\n}\n","/**\n * The store seam. The canvas never owns a second copy of its state: it reads\n * and writes through a CanvasStoreBinding.\n *\n * - A host WITH Redux mounts `canvasReducer` in its root reducer and binds it:\n * bindCanvasToReduxStore(store, (root) => root.canvasHost)\n * - A host WITHOUT Redux (a Vite tool, an Electron window) calls\n * createCanvasStore()\n * which runs the very same reducer in a tiny standalone store.\n */\n\nimport { canvasReducer, createInitialCanvasState, type CanvasAction } from \"./reducer\";\nimport type { CanvasState } from \"./types\";\n\nexport interface CanvasStoreBinding {\n getState(): CanvasState;\n dispatch(action: CanvasAction): void;\n subscribe(listener: () => void): () => void;\n /**\n * \"remote\": the state lives in another process (createRemoteCanvasStore) —\n * that process hydrates and saves it, so a controller over this binding\n * never does. Absent means \"local\".\n */\n readonly authority?: \"local\" | \"remote\";\n}\n\nexport function createCanvasStore(initial?: CanvasState): CanvasStoreBinding {\n let state = initial ?? createInitialCanvasState();\n const listeners = new Set<() => void>();\n return {\n getState: () => state,\n dispatch(action) {\n const next = canvasReducer(state, action);\n if (next === state) return;\n state = next;\n for (const listener of [...listeners]) listener();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n/** The minimum of a Redux store the canvas needs. */\nexport interface ReduxStoreLike<TRoot> {\n getState(): TRoot;\n dispatch(action: CanvasAction): unknown;\n subscribe(listener: () => void): () => void;\n}\n\nexport function bindCanvasToReduxStore<TRoot>(\n store: ReduxStoreLike<TRoot>,\n select: (root: TRoot) => CanvasState,\n): CanvasStoreBinding {\n return {\n getState: () => select(store.getState()),\n dispatch: (action) => {\n store.dispatch(action);\n },\n subscribe: (listener) => store.subscribe(listener),\n };\n}\n","/**\n * Remembering the canvas between sessions — a table stake, never optional.\n *\n * The default port writes to localStorage under a versioned key. Items whose\n * kind opts out (`restore: false`, e.g. a live session that cannot come back)\n * are dropped from the snapshot, and panes they leave empty are dropped too.\n */\n\nimport { removePane } from \"./layout\";\nimport { foldCanvasWindows } from \"./reducer\";\nimport type { CanvasItemId, CanvasState } from \"./types\";\n\nexport interface CanvasPersistencePort {\n load(): CanvasState | null | Promise<CanvasState | null>;\n save(snapshot: CanvasState): void | Promise<void>;\n}\n\nexport const CANVAS_STORAGE_KEY = \"ai-matrx.canvas.v1\";\n\nexport function createLocalStorageCanvasPersistence(\n key: string = CANVAS_STORAGE_KEY,\n storage: Pick<Storage, \"getItem\" | \"setItem\"> | null = typeof window === \"undefined\" ? null : safeLocalStorage(),\n): CanvasPersistencePort {\n return {\n load() {\n if (!storage) throw new Error(\"Canvas storage is unavailable; allow browser storage or provide a persistence port.\");\n const raw = storage.getItem(key);\n if (!raw) return null;\n return JSON.parse(raw) as CanvasState;\n },\n save(snapshot) {\n if (!storage) throw new Error(\"Canvas storage is unavailable; allow browser storage or provide a persistence port.\");\n storage.setItem(key, JSON.stringify(snapshot));\n },\n };\n}\n\n/**\n * Memory over any key-value store — an Electron main process's `state/kv`,\n * electron-store, IndexedDB behind a promise, a test map. Values are written\n * as plain JSON objects (not strings) so a structured store keeps them\n * inspectable; a string-only store can wrap this with JSON.stringify.\n */\nexport interface CanvasKeyValueStore {\n get(key: string): unknown;\n set(key: string, value: unknown): void | Promise<void>;\n}\n\nexport function createKeyValueCanvasPersistence(kv: CanvasKeyValueStore, key: string = CANVAS_STORAGE_KEY): CanvasPersistencePort {\n return {\n async load() {\n const raw = await kv.get(key);\n if (raw === undefined || raw === null) return null;\n return (typeof raw === \"string\" ? JSON.parse(raw) : raw) as CanvasState;\n },\n save: (snapshot) => kv.set(key, JSON.parse(JSON.stringify(snapshot)) as unknown),\n };\n}\n\nfunction safeLocalStorage(): Storage | null {\n try {\n const probe = \"__mxc_probe__\";\n window.localStorage.setItem(probe, \"1\");\n window.localStorage.removeItem(probe);\n return window.localStorage;\n } catch {\n return null; // load/save report through the controller's existing error sink.\n }\n}\n\n/**\n * Builds the snapshot that is actually written: only restorable items, and\n * every window but the main one folded home (other windows never come back).\n */\nexport function toPersistableSnapshot(\n state: CanvasState,\n isRestorable: (kind: string) => boolean,\n): CanvasState {\n state = foldCanvasWindows(state);\n const keep = new Set<CanvasItemId>(\n Object.values(state.items).filter((item) => isRestorable(item.kind)).map((item) => item.id),\n );\n if (keep.size === Object.keys(state.items).length) return state;\n const items = Object.fromEntries(Object.entries(state.items).filter(([id]) => keep.has(id as CanvasItemId)));\n let layout = state.layout;\n const panes: Record<string, CanvasState[\"panes\"][string]> = {};\n for (const pane of Object.values(state.panes)) {\n const itemIds = pane.itemIds.filter((id) => keep.has(id));\n if (itemIds.length === 0 && pane.itemIds.length > 0) {\n const pruned = removePane(layout, pane.id);\n if (pruned) {\n layout = pruned;\n continue;\n }\n }\n panes[pane.id] = {\n ...pane,\n itemIds,\n activeItemId: pane.activeItemId && keep.has(pane.activeItemId) ? pane.activeItemId : (itemIds[0] ?? null),\n };\n }\n const focusedPaneId = panes[state.focusedPaneId] ? state.focusedPaneId : (Object.values(panes)[0]?.id ?? state.focusedPaneId);\n return { ...state, items, panes, layout, focusedPaneId };\n}\n","/**\n * Layout rules — the host-tunable numbers behind the column's width and how its\n * panes share space. Pure functions, so a desktop main process can place native\n * views with exactly the numbers the renderer draws with.\n *\n * The canvas always shrinks FIRST: while the window narrows, the centre keeps\n * `centreMinWidth` and the canvas gives way down to `minWidth`; only then does\n * the centre squeeze. Side-by-side panes narrower than `paneMinWidth` stack\n * instead of squeezing.\n */\n\nimport { CANVAS_DEFAULT_WIDTH, CANVAS_MIN_WIDTH } from \"./types\";\n\n/** The web's narrowest side-by-side pane (px): below it, a side-by-side split renders stacked. */\nexport const CANVAS_PANE_MIN_WIDTH = 280;\n\nexport interface CanvasLayoutRules {\n /** Width before the person drags the edge: CSS px, or a fraction of the region the canvas shares. */\n readonly defaultWidth: number | { readonly fraction: number };\n /** The narrowest the canvas column gets on a desktop-sized window. */\n readonly minWidth: number;\n /** Room the content beside the canvas always keeps (the canvas shrinks first). */\n readonly centreMinWidth: number;\n /** The FIRST pane's share when a pane splits down (stacked). 0.7 = the 70/30 divider. */\n readonly stackSplit: number;\n /** The first pane's share when a pane splits right (side by side). */\n readonly sideSplit: number;\n /** Side-by-side panes that would be narrower than this render stacked. 0 = never. */\n readonly paneMinWidth: number;\n}\n\n/** The web app's numbers (the defaults). */\nexport const CANVAS_WEB_LAYOUT_RULES: CanvasLayoutRules = {\n defaultWidth: CANVAS_DEFAULT_WIDTH,\n minWidth: CANVAS_MIN_WIDTH,\n centreMinWidth: 420,\n // Split down 70/30 like the desktop: what opens below (notifications, a feed) is the smaller pane.\n stackSplit: 0.7,\n sideSplit: 0.5,\n // A pane narrower than this cannot show a header (Back, a readable tab, \"+\", the menu, close) and a\n // body side by side with another: a split right that would go under it stacks instead.\n paneMinWidth: CANVAS_PANE_MIN_WIDTH,\n};\n\n/** The desktop app's numbers (Claude desktop's proportions). */\nexport const CANVAS_DESKTOP_LAYOUT_RULES: CanvasLayoutRules = {\n defaultWidth: { fraction: 0.36 },\n minWidth: CANVAS_MIN_WIDTH,\n centreMinWidth: 520,\n stackSplit: 0.7,\n sideSplit: 0.5,\n paneMinWidth: 360,\n};\n\nconst clampFraction = (value: number, fallback: number) =>\n Number.isFinite(value) ? Math.min(0.88, Math.max(0.12, value)) : fallback;\n\n/** Fills missing fields from the web defaults and repairs nonsense values. */\nexport function resolveCanvasLayoutRules(rules?: Partial<CanvasLayoutRules> | null): CanvasLayoutRules {\n const merged = { ...CANVAS_WEB_LAYOUT_RULES, ...(rules ?? {}) };\n const positive = (value: number, fallback: number) => (Number.isFinite(value) && value >= 0 ? value : fallback);\n return {\n defaultWidth:\n typeof merged.defaultWidth === \"number\"\n ? positive(merged.defaultWidth, CANVAS_DEFAULT_WIDTH)\n : { fraction: Math.min(1, Math.max(0.05, Number.isFinite(merged.defaultWidth.fraction) ? merged.defaultWidth.fraction : 0.36)) },\n minWidth: positive(merged.minWidth, CANVAS_MIN_WIDTH),\n centreMinWidth: positive(merged.centreMinWidth, CANVAS_WEB_LAYOUT_RULES.centreMinWidth),\n stackSplit: clampFraction(merged.stackSplit, 0.5),\n sideSplit: clampFraction(merged.sideSplit, 0.5),\n paneMinWidth: positive(merged.paneMinWidth, 0),\n };\n}\n\n/** The width before the person chose one. `region` is the space the canvas shares (0 = unknown). */\nexport function defaultCanvasWidth(rules: CanvasLayoutRules, region: number): number {\n if (typeof rules.defaultWidth === \"number\") return rules.defaultWidth;\n return region > 0 ? Math.round(region * rules.defaultWidth.fraction) : CANVAS_DEFAULT_WIDTH;\n}\n\n/**\n * The column's width right now: the stored width (or the rule's default),\n * fitted so the centre keeps `centreMinWidth` and the canvas never goes under\n * `minWidth`. A width remembered on a wide monitor never crushes a laptop.\n */\nexport function fitCanvasWidth(stored: number | null, region: number, rules: CanvasLayoutRules): number {\n const wanted = stored ?? defaultCanvasWidth(rules, region);\n if (region <= 0) return Math.max(rules.minWidth, wanted);\n return Math.max(rules.minWidth, Math.min(wanted, region - rules.centreMinWidth));\n}\n\n/** Clamp for a dragged width: the same bounds as fitting. */\nexport function clampDraggedCanvasWidth(next: number, region: number, rules: CanvasLayoutRules): number {\n const max = Math.max(rules.minWidth, region - rules.centreMinWidth);\n return Math.min(max, Math.max(rules.minWidth, Math.round(next)));\n}\n\n/** Whether a side-by-side split this wide (px) with this many children renders stacked. */\nexport function shouldStackSplit(width: number, children: number, rules: CanvasLayoutRules): boolean {\n return rules.paneMinWidth > 0 && width > 0 && width < rules.paneMinWidth * children;\n}\n","/**\n * The canvas's keyboard shortcuts, as DATA. A web host gets them bound in the\n * DOM by `CanvasProvider`; a desktop host binds the same table in its main\n * process (menu accelerators / `before-input-event`), because keys pressed\n * inside a native web view never reach the renderer's DOM. Every shortcut runs\n * through `runCanvasCommand`, so both paths do exactly the same thing.\n */\n\nimport type { CanvasController } from \"./controller\";\nimport { canvasWindowFrame } from \"./reducer\";\nimport type { CanvasWindowId } from \"./types\";\n\nexport type CanvasCommandId =\n | \"canvas.toggle\"\n | \"canvas.toggleFullscreen\"\n | \"canvas.exitFullscreen\"\n | \"canvas.closeTab\"\n | \"canvas.nextTab\"\n | \"canvas.previousTab\"\n | \"canvas.splitRight\"\n | \"canvas.splitDown\"\n | \"canvas.back\"\n | \"canvas.forward\";\n\n/**\n * When a shortcut applies:\n * - \"presented\": a canvas column is on screen in this window;\n * - \"fullscreen\": the canvas is expanded (and Escape is not owned by a menu or dialog);\n * - \"canvas-focus\": keyboard focus is inside the canvas (a tab, a pane, a native body).\n */\nexport type CanvasShortcutWhen = \"presented\" | \"fullscreen\" | \"canvas-focus\";\n\nexport interface CanvasShortcut {\n readonly id: CanvasCommandId;\n /** Electron accelerator syntax: \"CmdOrCtrl+\\\\\", \"Escape\", \"Ctrl+Shift+Tab\". */\n readonly accelerator: string;\n readonly when: CanvasShortcutWhen;\n readonly label: string;\n /** False when browsers reserve the keys (⌘W, Ctrl+Tab): only a desktop host can bind it. */\n readonly web: boolean;\n}\n\nexport const CANVAS_SHORTCUTS: readonly CanvasShortcut[] = [\n { id: \"canvas.toggle\", accelerator: \"CmdOrCtrl+\\\\\", when: \"presented\", label: \"Show or hide canvas\", web: true },\n { id: \"canvas.exitFullscreen\", accelerator: \"Escape\", when: \"fullscreen\", label: \"Restore canvas\", web: true },\n { id: \"canvas.toggleFullscreen\", accelerator: \"CmdOrCtrl+Shift+Enter\", when: \"canvas-focus\", label: \"Expand canvas\", web: true },\n { id: \"canvas.splitRight\", accelerator: \"CmdOrCtrl+Alt+\\\\\", when: \"canvas-focus\", label: \"Split right\", web: true },\n { id: \"canvas.splitDown\", accelerator: \"CmdOrCtrl+Alt+Shift+\\\\\", when: \"canvas-focus\", label: \"Split down\", web: true },\n // Browsers own ⌘[ / ⌘] for their own history: data for a desktop host (and the header's Back / Forward).\n { id: \"canvas.back\", accelerator: \"CmdOrCtrl+[\", when: \"canvas-focus\", label: \"Back\", web: false },\n { id: \"canvas.forward\", accelerator: \"CmdOrCtrl+]\", when: \"canvas-focus\", label: \"Forward\", web: false },\n { id: \"canvas.closeTab\", accelerator: \"CmdOrCtrl+W\", when: \"canvas-focus\", label: \"Close tab\", web: false },\n { id: \"canvas.nextTab\", accelerator: \"Ctrl+Tab\", when: \"canvas-focus\", label: \"Next tab\", web: false },\n { id: \"canvas.previousTab\", accelerator: \"Ctrl+Shift+Tab\", when: \"canvas-focus\", label: \"Previous tab\", web: false },\n];\n\n/** The tooltip hint for a command, e.g. \"⌘\\\\\" on a Mac. */\nexport function canvasShortcutHint(id: CanvasCommandId, isMac: boolean): string | null {\n const shortcut = CANVAS_SHORTCUTS.find((entry) => entry.id === id);\n if (!shortcut) return null;\n return shortcut.accelerator\n .split(\"+\")\n .map((part) => {\n if (part === \"CmdOrCtrl\") return isMac ? \"⌘\" : \"Ctrl+\";\n if (part === \"Ctrl\") return isMac ? \"⌃\" : \"Ctrl+\";\n if (part === \"Alt\") return isMac ? \"⌥\" : \"Alt+\";\n if (part === \"Shift\") return isMac ? \"⇧\" : \"Shift+\";\n if (part === \"Escape\") return \"Esc\";\n return part;\n })\n .join(\"\");\n}\n\n/**\n * Runs one command against a window's canvas. Returns true when it did\n * something (so a binding knows whether to swallow the key).\n */\nexport function runCanvasCommand(controller: CanvasController, id: CanvasCommandId, windowId: CanvasWindowId = controller.windowId): boolean {\n const state = controller.getState();\n const frame = canvasWindowFrame(state, windowId);\n const pane = frame ? state.panes[frame.focusedPaneId] : undefined;\n switch (id) {\n case \"canvas.toggle\":\n controller.toggle(windowId);\n return true;\n case \"canvas.toggleFullscreen\":\n controller.setFullscreen(!(frame?.isFullscreen ?? false), windowId);\n return true;\n case \"canvas.exitFullscreen\":\n if (!frame?.isFullscreen) return false;\n controller.setFullscreen(false, windowId);\n return true;\n case \"canvas.closeTab\":\n if (!frame?.isOpen || !pane?.activeItemId) return false;\n controller.close(pane.activeItemId);\n return true;\n case \"canvas.nextTab\":\n case \"canvas.previousTab\": {\n if (!frame?.isOpen || !pane?.activeItemId || pane.itemIds.length < 2) return false;\n const at = pane.itemIds.indexOf(pane.activeItemId);\n const step = id === \"canvas.nextTab\" ? 1 : -1;\n const next = pane.itemIds[(at + step + pane.itemIds.length) % pane.itemIds.length];\n if (next) controller.activate(next);\n return true;\n }\n case \"canvas.splitRight\":\n case \"canvas.splitDown\":\n if (!frame?.isOpen || !pane) return false;\n controller.splitPane(pane.id, id === \"canvas.splitRight\" ? \"horizontal\" : \"vertical\", pane.itemIds.length > 1 ? (pane.activeItemId ?? undefined) : undefined);\n return true;\n case \"canvas.back\":\n if (!frame?.isOpen || !pane?.activeItemId) return false;\n return controller.back(pane.activeItemId) !== null;\n case \"canvas.forward\":\n if (!frame?.isOpen || !pane?.activeItemId) return false;\n return controller.forward(pane.activeItemId) !== null;\n default:\n return false;\n }\n}\n\n/** The subset of a KeyboardEvent an accelerator is matched against. */\nexport interface CanvasKeyInput {\n readonly key: string;\n readonly code?: string;\n readonly metaKey: boolean;\n readonly ctrlKey: boolean;\n readonly altKey: boolean;\n readonly shiftKey: boolean;\n}\n\nconst CODE_FOR: Record<string, string> = { \"\\\\\": \"Backslash\", \"[\": \"BracketLeft\", \"]\": \"BracketRight\", Tab: \"Tab\", Escape: \"Escape\", Enter: \"Enter\" };\n\n/**\n * Whether a key event is this accelerator. \"CmdOrCtrl\" is ⌘ on a Mac and Ctrl\n * elsewhere; symbol keys match by physical key (⌥\\ types « on a Mac).\n */\nexport function matchesCanvasAccelerator(input: CanvasKeyInput, accelerator: string, isMac: boolean): boolean {\n const parts = accelerator.split(\"+\");\n // \"CmdOrCtrl+\\\\\" splits into [..., \"\\\\\"]; a trailing \"+\" key would split empty.\n const key = parts.pop() ?? \"\";\n const want = { meta: false, ctrl: false, alt: false, shift: false };\n for (const part of parts) {\n if (part === \"CmdOrCtrl\") want[isMac ? \"meta\" : \"ctrl\"] = true;\n else if (part === \"Cmd\" || part === \"Meta\") want.meta = true;\n else if (part === \"Ctrl\") want.ctrl = true;\n else if (part === \"Alt\") want.alt = true;\n else if (part === \"Shift\") want.shift = true;\n }\n if (input.metaKey !== want.meta || input.ctrlKey !== want.ctrl || input.altKey !== want.alt || input.shiftKey !== want.shift) return false;\n const code = CODE_FOR[key] ?? (/^[A-Z]$/i.test(key) ? `Key${key.toUpperCase()}` : undefined);\n if (code && input.code === code) return true;\n return input.key.toLowerCase() === key.toLowerCase();\n}\n","/**\n * The canvas controller: the ONE imperative API every caller uses. It wraps a\n * store binding, validates what callers hand it (so the reducer stays pure and\n * trusting), and owns hydration, autosave, pop-outs and session lifecycles.\n *\n * A controller acts for ONE window by default (`controller.windowId`, main\n * unless the host says otherwise); `forWindow(id)` gives the same canvas seen\n * from another window. Nothing fails silently: a refused open, a pop-out the\n * host cannot do, a throwing session hook — each is reported through the\n * error sink.\n */\n\nimport { canvasActions, canvasWindowOfItem, canvasWindowFrame, listCanvasWindowIds, sanitizeCanvasSnapshot, type CanvasAction, type CanvasWindowCloseMode } from \"./reducer\";\nimport { canvasItemId, canvasWindowId, findNonJson } from \"./ids\";\nimport { listPaneIds } from \"./layout\";\nimport { toPersistableSnapshot, type CanvasPersistencePort } from \"./persistence\";\nimport { resolveCanvasLayoutRules, type CanvasLayoutRules } from \"./rules\";\nimport type { CanvasStoreBinding } from \"./store\";\nimport {\n CANVAS_LAUNCHER_KIND,\n CANVAS_MAIN_WINDOW,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasNavigateInput,\n type CanvasOpenInput,\n type CanvasOpenTarget,\n type CanvasOrientation,\n type CanvasPaneId,\n type CanvasPreferredTarget,\n type CanvasSplitId,\n type CanvasState,\n type CanvasWindowId,\n} from \"./types\";\n\nexport interface CanvasErrorReport {\n readonly code:\n | \"non-json-data\"\n | \"unknown-kind\"\n | \"persistence-load\"\n | \"persistence-save\"\n | \"pop-out-unavailable\"\n | \"pop-out-refused\"\n | \"pop-out-failed\"\n | \"session-hook\";\n readonly message: string;\n readonly detail?: unknown;\n}\n\nexport type CanvasErrorSink = (report: CanvasErrorReport) => void;\n\nexport const consoleCanvasErrorSink: CanvasErrorSink = (report) => {\n console.error(`[@ai-matrx/canvas] ${report.code}: ${report.message}`, report.detail ?? \"\");\n};\n\n/**\n * The host's window abilities. Without `popOut` a pop-out is refused aloud and\n * no \"Pop out\" entry is shown.\n */\nexport interface CanvasWindowPorts {\n /**\n * Opens a window (web: a floating panel; desktop: a BrowserWindow) that will\n * render the canvas for the returned window id, then the package moves the\n * item there. Resolve null to refuse.\n */\n readonly popOut?: ((item: CanvasItem) => Promise<{ readonly windowId: string } | null>) | undefined;\n /** Called after a tab docked back out of `fromWindowId` (close that window when the state no longer lists it). */\n readonly dockBack?: ((itemId: CanvasItemId, fromWindowId: CanvasWindowId) => void) | undefined;\n}\n\n/** Why a session-backed item attached or detached. */\nexport type CanvasSessionAttachReason = \"open\" | \"restore\" | \"arrive\";\nexport type CanvasSessionDetachReason = \"close\" | \"leave\" | \"unmount\";\n\nexport interface CanvasSessionEvent<R extends string> {\n readonly item: CanvasItem;\n readonly sessionKey: string;\n /** The window the item is in (attach) or was in (detach). */\n readonly windowId: CanvasWindowId;\n readonly reason: R;\n}\n\n/**\n * A kind with `restore: \"session\"`: its tab is a view onto a process the host\n * keeps (a terminal). Closing the tab DETACHES (the process lives on); a\n * restore or a move REATTACHES. The package only calls these; the host owns the\n * process side.\n */\nexport interface CanvasSessionHooks {\n readonly sessionKey: (item: CanvasItem) => string | null;\n readonly onAttach?: ((event: CanvasSessionEvent<CanvasSessionAttachReason>) => void) | undefined;\n readonly onDetach?: ((event: CanvasSessionEvent<CanvasSessionDetachReason>) => void) | undefined;\n}\n\nexport interface CanvasControllerOptions {\n readonly store: CanvasStoreBinding;\n readonly persistence?: CanvasPersistencePort | null | undefined;\n /** Kinds that may not come back after a reload. Default: every kind restores. */\n readonly isRestorable?: ((kind: string) => boolean) | undefined;\n /** When given, opens of an unregistered kind are refused and reported. */\n readonly isKnownKind?: ((kind: string) => boolean) | undefined;\n readonly onError?: CanvasErrorSink | undefined;\n readonly saveDelayMs?: number | undefined;\n /**\n * Whether a remembered \"open\" may be restored right now. A host returns\n * false where an open canvas would take the whole screen (a phone).\n */\n readonly mayRestoreOpen?: (() => boolean) | undefined;\n /** The window this controller acts for by default. Default: the main window. */\n readonly windowId?: string | undefined;\n /** Width and split numbers (see CANVAS_WEB_LAYOUT_RULES / CANVAS_DESKTOP_LAYOUT_RULES). */\n readonly layoutRules?: Partial<CanvasLayoutRules> | undefined;\n /** Read on every use, so a provider can hand in its latest ports. */\n readonly windowPorts?: (() => CanvasWindowPorts) | undefined;\n /** Session hooks for a kind, or undefined when the kind is not session-backed. */\n readonly sessions?: ((kind: string) => CanvasSessionHooks | undefined) | undefined;\n /**\n * Where a NEW item of a kind opens while the canvas already shows something\n * (a kind's `preferredTarget`). An explicit `target` always wins.\n */\n readonly preferredTarget?: ((kind: string) => CanvasPreferredTarget | undefined) | undefined;\n}\n\nexport interface CanvasController {\n readonly store: CanvasStoreBinding;\n /** The window this controller acts for by default. */\n readonly windowId: CanvasWindowId;\n readonly rules: CanvasLayoutRules;\n /** The same canvas, acting for another window. */\n forWindow(windowId: string): CanvasController;\n getState(): CanvasState;\n open(input: CanvasOpenInput): CanvasItemId | null;\n update(itemId: CanvasItemId, patch: { data?: CanvasJson | undefined; title?: string | null | undefined }): boolean;\n /** Gives an item a new identity in place (a draft that was saved and now has a durable id). */\n rekey(itemId: CanvasItemId, key: string): CanvasItemId | null;\n /**\n * Replaces a tab's content with another item IN PLACE and records history,\n * so the pane header offers Back. Identity still holds: when the target is\n * already open, it is focused where it is (a launcher tab then closes; any\n * other tab keeps what it shows). Returns the item now shown, or null.\n */\n navigate(itemId: CanvasItemId, to: CanvasNavigateInput): CanvasItemId | null;\n /** Returns a tab to what it showed before (see navigate). Null when it has no history. */\n back(itemId: CanvasItemId): CanvasItemId | null;\n /** Re-does the last Back with the same live body. Null when there is nothing forward. */\n forward(itemId: CanvasItemId): CanvasItemId | null;\n /** Opens the launcher as a new tab in a pane (default: this window's focused pane), or focuses the one already there. */\n newTab(paneId?: CanvasPaneId): CanvasItemId;\n close(itemId: CanvasItemId): void;\n closeOthers(itemId: CanvasItemId): void;\n activate(itemId: CanvasItemId): void;\n focusPane(paneId: CanvasPaneId): void;\n moveItem(itemId: CanvasItemId, toPaneId: CanvasPaneId, index?: number): void;\n /** Splits with the layout rules' share (stackSplit for \"vertical\", sideSplit for \"horizontal\"). */\n splitPane(paneId: CanvasPaneId, orientation: CanvasOrientation, moveItemId?: CanvasItemId): void;\n closePane(paneId: CanvasPaneId): void;\n resizeSplit(splitId: CanvasSplitId, sizes: readonly number[]): void;\n show(windowId?: CanvasWindowId): void;\n hide(windowId?: CanvasWindowId): void;\n toggle(windowId?: CanvasWindowId): void;\n setFullscreen(fullscreen: boolean, windowId?: CanvasWindowId): void;\n setWidth(width: number, windowId?: CanvasWindowId): void;\n /** Moves a tab into its own window through the host's popOut port. Refused aloud without one. */\n popOut(itemId: CanvasItemId): Promise<CanvasWindowId | null>;\n /** Returns a popped-out tab to the window it came from. False when it is not popped out. */\n dockBack(itemId: CanvasItemId): boolean;\n /** A host window closed: its tabs dock home (default) or close with it. */\n closeWindow(windowId: CanvasWindowId, mode?: CanvasWindowCloseMode): void;\n /** Is this exact thing on the canvas right now (in any window)? */\n has(kind: string, key: string): boolean;\n /**\n * Is a canvas column on screen (in this window, or in `windowId`)? A store\n * can exist in a layout that shows no column (a kiosk, a meeting stage);\n * opening there must be refused aloud.\n */\n isPresented(windowId?: CanvasWindowId): boolean;\n /** Called by a column on mount; returns the unmount callback. */\n registerPresentation(windowId?: CanvasWindowId): () => void;\n subscribePresentation(listener: () => void): () => void;\n /** Loads the persisted snapshot, starts autosave and session tracking. Returns a disposer. */\n start(): () => void;\n}\n\ninterface Shared {\n readonly options: CanvasControllerOptions;\n readonly onError: CanvasErrorSink;\n readonly rules: CanvasLayoutRules;\n readonly presentations: Map<CanvasWindowId, number>;\n readonly presentationListeners: Set<() => void>;\n readonly views: Map<CanvasWindowId, CanvasController>;\n /** Windows whose controllers are started (session tracking scope for a remote store). */\n readonly started: Map<CanvasWindowId, number>;\n sessionStop: (() => void) | null;\n /** Mints \"New tab\" keys (unique per controller family). */\n launcherSeq: number;\n}\n\nexport function createCanvasController(options: CanvasControllerOptions): CanvasController {\n const shared: Shared = {\n options,\n onError: options.onError ?? consoleCanvasErrorSink,\n rules: resolveCanvasLayoutRules(options.layoutRules),\n presentations: new Map(),\n presentationListeners: new Set(),\n views: new Map(),\n started: new Map(),\n sessionStop: null,\n launcherSeq: 0,\n };\n return view(shared, canvasWindowId(options.windowId ?? CANVAS_MAIN_WINDOW));\n}\n\nfunction view(shared: Shared, windowId: CanvasWindowId): CanvasController {\n const cached = shared.views.get(windowId);\n if (cached) return cached;\n const { options, onError, rules } = shared;\n const { store, persistence = null } = options;\n const isRestorable = options.isRestorable ?? (() => true);\n const dispatch = (action: CanvasAction) => store.dispatch(action);\n const notifyPresentation = () => {\n for (const listener of [...shared.presentationListeners]) listener();\n };\n const shareFor = (orientation: CanvasOrientation) => (orientation === \"vertical\" ? rules.stackSplit : rules.sideSplit);\n\n /** Refuses aloud what may not be opened: an unknown kind, data that is not plain JSON. */\n const acceptable = (input: { readonly kind: string; readonly key: string; readonly data?: CanvasJson | undefined }): boolean => {\n if (input.kind !== CANVAS_LAUNCHER_KIND && options.isKnownKind && !options.isKnownKind(input.kind)) {\n onError({ code: \"unknown-kind\", message: `No canvas kind \"${input.kind}\" is registered.`, detail: input });\n return false;\n }\n if (input.data !== undefined) {\n const bad = findNonJson(input.data);\n if (bad) {\n onError({\n code: \"non-json-data\",\n message: `Canvas data for \"${input.kind}\" must be plain JSON; ${bad} is not.`,\n detail: { kind: input.kind, key: input.key },\n });\n return false;\n }\n }\n return true;\n };\n\n /**\n * A kind's preferred place for a NEW item, applied only while the canvas\n * already shows something in this window: a pane already holding that kind\n * takes it (one notifications pane, not a new split per press); otherwise\n * the preferred split of the focused pane. A put-away or empty canvas, or an\n * item that already exists, just opens where it would anyway.\n */\n const preferredTargetFor = (input: CanvasOpenInput): CanvasOpenTarget => {\n const preferred = options.preferredTarget?.(input.kind);\n if (!preferred || preferred === \"focused\") return \"focused\";\n const state = store.getState();\n if (canvasItemId(input.kind, input.key) in state.items) return \"focused\";\n const frame = canvasWindowFrame(state, input.windowId ?? windowId);\n if (!frame?.isOpen) return \"focused\";\n const panes = listPaneIds(frame.layout);\n const holding = panes.find((paneId) => state.panes[paneId]?.itemIds.some((id) => state.items[id]?.kind === input.kind));\n if (holding) return { paneId: holding };\n return state.panes[frame.focusedPaneId]?.activeItemId ? preferred : \"focused\";\n };\n\n const controller: CanvasController = {\n store,\n windowId,\n rules,\n forWindow: (id) => view(shared, canvasWindowId(id)),\n getState: () => store.getState(),\n open(input) {\n if (!acceptable(input)) return null;\n const target = input.target ?? preferredTargetFor(input);\n const splitShare = target === \"split-down\" ? rules.stackSplit : target === \"split-right\" ? rules.sideSplit : undefined;\n const withTarget: CanvasOpenInput = input.target === target ? input : { ...input, target };\n const resolved: CanvasOpenInput = withTarget.windowId || windowId === CANVAS_MAIN_WINDOW ? withTarget : { ...withTarget, windowId };\n dispatch(canvasActions.open(resolved, splitShare === undefined ? undefined : { splitShare }));\n return canvasItemId(input.kind, input.key);\n },\n update(itemId, patch) {\n if (patch.data !== undefined) {\n const bad = findNonJson(patch.data);\n if (bad) {\n onError({ code: \"non-json-data\", message: `Canvas update for ${itemId} must be plain JSON; ${bad} is not.` });\n return false;\n }\n }\n if (!store.getState().items[itemId]) return false;\n dispatch(canvasActions.update(itemId, patch));\n return true;\n },\n navigate(itemId, to) {\n if (!store.getState().items[itemId] || !acceptable(to)) return null;\n dispatch(canvasActions.navigate(itemId, to));\n const shown = canvasItemId(to.kind, to.key);\n return shown in store.getState().items ? shown : null;\n },\n back(itemId) {\n const history = store.getState().items[itemId]?.history ?? [];\n const entry = history[history.length - 1];\n if (!entry) return null;\n dispatch(canvasActions.back(itemId));\n return canvasItemId(entry.kind, entry.key);\n },\n forward(itemId) {\n const forward = store.getState().items[itemId]?.forward ?? [];\n const entry = forward[forward.length - 1];\n if (!entry) return null;\n dispatch(canvasActions.forward(itemId));\n return canvasItemId(entry.kind, entry.key);\n },\n newTab(paneId) {\n const state = store.getState();\n const frame = canvasWindowFrame(state, windowId);\n const target = paneId && state.panes[paneId] ? paneId : (frame?.focusedPaneId ?? state.focusedPaneId);\n const existing = state.panes[target]?.itemIds.find((id) => state.items[id]?.kind === CANVAS_LAUNCHER_KIND);\n if (existing) {\n dispatch(canvasActions.activate(existing));\n dispatch(canvasActions.setOpen(true, canvasWindowOfItem(store.getState(), existing) ?? windowId));\n return existing;\n }\n // Minted here, not in the reducer, so a remote store can name it before the main process answers.\n shared.launcherSeq += 1;\n const key = `${Date.now().toString(36)}-${shared.launcherSeq}`;\n dispatch(canvasActions.open({ kind: CANVAS_LAUNCHER_KIND, key, target: { paneId: target }, ...(windowId === CANVAS_MAIN_WINDOW ? {} : { windowId }) }));\n return canvasItemId(CANVAS_LAUNCHER_KIND, key);\n },\n rekey(itemId, key) {\n const item = store.getState().items[itemId];\n if (!item) return null;\n dispatch(canvasActions.rekey(itemId, key));\n return canvasItemId(item.kind, key);\n },\n close: (itemId) => dispatch(canvasActions.closeItem(itemId)),\n closeOthers: (itemId) => dispatch(canvasActions.closeOthers(itemId)),\n activate: (itemId) => dispatch(canvasActions.activate(itemId)),\n focusPane: (paneId) => dispatch(canvasActions.focusPane(paneId)),\n moveItem: (itemId, toPaneId, index) => dispatch(canvasActions.moveItem(itemId, toPaneId, index)),\n splitPane: (paneId, orientation, moveItemId) => dispatch(canvasActions.splitPane(paneId, orientation, moveItemId, shareFor(orientation))),\n closePane: (paneId) => dispatch(canvasActions.closePane(paneId)),\n resizeSplit: (splitId, sizes) => dispatch(canvasActions.resizeSplit(splitId, sizes)),\n show: (w = windowId) => dispatch(canvasActions.setOpen(true, w)),\n hide: (w = windowId) => dispatch(canvasActions.setOpen(false, w)),\n toggle: (w = windowId) => dispatch(canvasActions.toggle(w)),\n setFullscreen: (fullscreen, w = windowId) => dispatch(canvasActions.setFullscreen(fullscreen, w)),\n setWidth: (width, w = windowId) => dispatch(canvasActions.setWidth(width, w)),\n async popOut(itemId) {\n const item = store.getState().items[itemId];\n if (!item) return null;\n const port = options.windowPorts?.().popOut;\n if (!port) {\n onError({ code: \"pop-out-unavailable\", message: \"This app cannot pop canvas tabs out into their own window.\", detail: { itemId } });\n return null;\n }\n let result: { readonly windowId: string } | null;\n try {\n result = await port(item);\n } catch (error) {\n onError({ code: \"pop-out-failed\", message: \"The window for this tab could not be opened.\", detail: error });\n return null;\n }\n if (!result) {\n onError({ code: \"pop-out-refused\", message: \"The app declined to pop this tab out.\", detail: { itemId } });\n return null;\n }\n const target = canvasWindowId(result.windowId);\n dispatch(canvasActions.popOut(itemId, target));\n return target;\n },\n dockBack(itemId) {\n const state = store.getState();\n const from = canvasWindowOfItem(state, itemId);\n if (!from || from === CANVAS_MAIN_WINDOW || state.windows[from]?.role !== \"pop-out\") return false;\n dispatch(canvasActions.dockBack(itemId));\n options.windowPorts?.().dockBack?.(itemId, from);\n return true;\n },\n closeWindow: (w, mode = \"dock\") => dispatch(canvasActions.closeWindow(w, mode)),\n has: (kind, key) => canvasItemId(kind, key) in store.getState().items,\n isPresented: (w = windowId) => (shared.presentations.get(w) ?? 0) > 0,\n registerPresentation(w = windowId) {\n shared.presentations.set(w, (shared.presentations.get(w) ?? 0) + 1);\n notifyPresentation();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n shared.presentations.set(w, Math.max(0, (shared.presentations.get(w) ?? 1) - 1));\n notifyPresentation();\n };\n },\n subscribePresentation(listener) {\n shared.presentationListeners.add(listener);\n return () => shared.presentationListeners.delete(listener);\n },\n start() {\n let disposed = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let lastSaved: CanvasState | null = null;\n // Another process owns a remote store: it hydrates and saves; this side only renders.\n const owns = store.authority !== \"remote\";\n const memory = owns ? persistence : null;\n\n const save = () => {\n timer = null;\n const state = store.getState();\n if (!memory || !state.hydrated || state === lastSaved) return;\n lastSaved = state;\n try {\n void Promise.resolve(memory.save(toPersistableSnapshot(state, isRestorable))).catch((error: unknown) =>\n onError({ code: \"persistence-save\", message: \"Saving the canvas layout failed.\", detail: error }),\n );\n } catch (error) {\n onError({ code: \"persistence-save\", message: \"Saving the canvas layout failed.\", detail: error });\n }\n };\n\n // A host store dispatches constantly (streaming, typing). Only a change\n // to the CANVAS state reschedules the save, or a busy app starves it.\n let seen = store.getState();\n const unsubscribe = store.subscribe(() => {\n if (!memory || disposed) return;\n const current = store.getState();\n if (current === seen) return;\n seen = current;\n if (timer) clearTimeout(timer);\n timer = setTimeout(save, options.saveDelayMs ?? 250);\n });\n\n if (!owns || store.getState().hydrated) {\n // Already hydrated (a second provider over the same store), or owned elsewhere.\n } else if (!memory) {\n dispatch(canvasActions.hydrate(null));\n } else {\n Promise.resolve()\n .then(() => memory.load())\n .then(\n (snapshot) => {\n if (disposed) return;\n const openedThisSession = store.getState().isOpen;\n const validSnapshot = snapshot === null ? null : sanitizeCanvasSnapshot(snapshot);\n if (snapshot !== null && validSnapshot === null) {\n onError({ code: \"persistence-load\", message: \"The saved canvas layout is invalid. Clear the saved layout or repair the persistence port.\" });\n }\n dispatch(canvasActions.hydrate(validSnapshot));\n if (!openedThisSession && options.mayRestoreOpen && !options.mayRestoreOpen() && store.getState().isOpen) {\n dispatch(canvasActions.setOpen(false));\n }\n },\n (error: unknown) => {\n onError({ code: \"persistence-load\", message: \"The saved canvas layout could not be read.\", detail: error });\n if (!disposed) dispatch(canvasActions.hydrate(null));\n },\n );\n }\n\n const stopSessions = startSessions(shared, windowId);\n\n return () => {\n disposed = true;\n unsubscribe();\n stopSessions();\n if (timer) {\n clearTimeout(timer);\n save();\n }\n };\n },\n };\n shared.views.set(windowId, controller);\n return controller;\n}\n\n/**\n * Session lifecycle tracking, once per controller family. A local store is\n * one process showing every window, so it tracks them all; a remote store is\n * one window's renderer, so it tracks only the windows started here — a tab\n * moving to another process's window LEAVES and ARRIVES there.\n */\nfunction startSessions(shared: Shared, windowId: CanvasWindowId): () => void {\n const { options, onError } = shared;\n const sessions = options.sessions;\n if (!sessions) return () => undefined;\n shared.started.set(windowId, (shared.started.get(windowId) ?? 0) + 1);\n let stopped = false;\n if (!shared.sessionStop) {\n const store = options.store;\n const local = store.authority !== \"remote\";\n let tracked: Map<CanvasItemId, { item: CanvasItem; key: string; windowId: CanvasWindowId }> | null = null;\n\n const call = (fn: () => void) => {\n try {\n fn();\n } catch (error) {\n onError({ code: \"session-hook\", message: \"A canvas session hook threw.\", detail: error });\n }\n };\n\n const read = (fn: () => string | null): string | null => {\n try {\n return fn();\n } catch (error) {\n onError({ code: \"session-hook\", message: \"A canvas kind's sessionKey threw.\", detail: error });\n return null;\n }\n };\n\n let prevItems = new Set<CanvasItemId>();\n const snapshot = (state: CanvasState) => {\n const out = new Map<CanvasItemId, { item: CanvasItem; key: string; windowId: CanvasWindowId }>();\n for (const w of listCanvasWindowIds(state)) {\n if (!local && !shared.started.has(w)) continue;\n const frame = canvasWindowFrame(state, w);\n if (!frame) continue;\n for (const paneId of listPaneIds(frame.layout)) {\n for (const itemId of state.panes[paneId]?.itemIds ?? []) {\n const item = state.items[itemId];\n const hooks = item ? sessions(item.kind) : undefined;\n if (!item || !hooks) continue;\n const key = read(() => hooks.sessionKey(item));\n if (key) out.set(itemId, { item, key, windowId: w });\n }\n }\n }\n return out;\n };\n\n const sync = () => {\n const state = options.store.getState();\n if (!state.hydrated) return;\n const next = snapshot(state);\n const first = tracked === null;\n const prev = tracked ?? new Map();\n for (const [id, entry] of prev) {\n const now = next.get(id);\n if (now && now.key === entry.key) continue;\n const hooks = sessions(entry.item.kind);\n const reason: CanvasSessionDetachReason = state.items[id] && !now ? \"leave\" : \"close\";\n call(() => hooks?.onDetach?.({ item: entry.item, sessionKey: entry.key, windowId: entry.windowId, reason }));\n }\n for (const [id, entry] of next) {\n const before = prev.get(id);\n if (before && before.key === entry.key) continue;\n const hooks = sessions(entry.item.kind);\n const reason: CanvasSessionAttachReason = first ? \"restore\" : prevItems.has(id) ? \"arrive\" : \"open\";\n call(() => hooks?.onAttach?.({ item: entry.item, sessionKey: entry.key, windowId: entry.windowId, reason }));\n }\n tracked = next;\n prevItems = new Set(Object.keys(state.items) as CanvasItemId[]);\n };\n let lastState: CanvasState | null = null;\n const unsubscribe = store.subscribe(() => {\n const state = store.getState();\n if (state === lastState) return;\n lastState = state;\n sync();\n });\n sync();\n shared.sessionStop = () => {\n unsubscribe();\n for (const entry of tracked?.values() ?? []) {\n const hooks = sessions(entry.item.kind);\n call(() => hooks?.onDetach?.({ item: entry.item, sessionKey: entry.key, windowId: entry.windowId, reason: \"unmount\" }));\n }\n tracked = null;\n };\n }\n return () => {\n if (stopped) return;\n stopped = true;\n const left = (shared.started.get(windowId) ?? 1) - 1;\n if (left > 0) shared.started.set(windowId, left);\n else shared.started.delete(windowId);\n if (shared.started.size === 0 && shared.sessionStop) {\n const stop = shared.sessionStop;\n shared.sessionStop = null;\n stop();\n }\n };\n}\n","/**\n * Selectors over CanvasState. Each returns a value that is referentially\n * stable for an unchanged state, so they are safe in useSyncExternalStore and\n * in a host's useSelector. Window-scoped selectors default to the main window;\n * an unknown window reads as closed and empty.\n */\n\nimport { listPaneIds } from \"./layout\";\nimport { canvasWindowFrame, canvasWindowOfItem } from \"./reducer\";\nimport {\n CANVAS_MAIN_WINDOW,\n type CanvasExtraWindow,\n type CanvasHistoryEntry,\n type CanvasItem,\n type CanvasItemId,\n type CanvasLayoutNode,\n type CanvasPane,\n type CanvasPaneId,\n type CanvasState,\n type CanvasWindowId,\n} from \"./types\";\n\nconst frame = (s: CanvasState, w: CanvasWindowId | undefined) => canvasWindowFrame(s, w ?? CANVAS_MAIN_WINDOW);\n\nexport const selectCanvasIsOpen = (s: CanvasState, windowId?: CanvasWindowId): boolean => frame(s, windowId)?.isOpen ?? false;\nexport const selectCanvasIsFullscreen = (s: CanvasState, windowId?: CanvasWindowId): boolean => frame(s, windowId)?.isFullscreen ?? false;\n/** The width the person chose, or null while the host's layout rule decides. */\nexport const selectCanvasWidth = (s: CanvasState, windowId?: CanvasWindowId): number | null => frame(s, windowId)?.width ?? null;\nexport const selectCanvasLayout = (s: CanvasState, windowId?: CanvasWindowId): CanvasLayoutNode | null => frame(s, windowId)?.layout ?? null;\nexport const selectCanvasFocusedPaneId = (s: CanvasState, windowId?: CanvasWindowId): CanvasPaneId | null =>\n frame(s, windowId)?.focusedPaneId ?? null;\nexport const selectCanvasIsHydrated = (s: CanvasState): boolean => s.hydrated;\n/** Every item on the canvas, in every window. */\nexport const selectCanvasItemCount = (s: CanvasState): number => Object.keys(s.items).length;\n\nexport const selectCanvasPane = (s: CanvasState, paneId: CanvasPaneId): CanvasPane | undefined => s.panes[paneId];\nexport const selectCanvasItem = (s: CanvasState, itemId: CanvasItemId): CanvasItem | undefined => s.items[itemId];\n\nexport function selectCanvasPaneCount(s: CanvasState, windowId?: CanvasWindowId): number {\n const layout = frame(s, windowId)?.layout;\n return layout ? listPaneIds(layout).length : 0;\n}\n\n/** Items shown in one window. */\nexport function selectCanvasWindowItemCount(s: CanvasState, windowId?: CanvasWindowId): number {\n const layout = frame(s, windowId)?.layout;\n if (!layout) return 0;\n return listPaneIds(layout).reduce((sum, paneId) => sum + (s.panes[paneId]?.itemIds.length ?? 0), 0);\n}\n\n/** The item the person is looking at in a window's focused pane. */\nexport function selectCanvasActiveItem(s: CanvasState, windowId?: CanvasWindowId): CanvasItem | null {\n const f = frame(s, windowId);\n const pane = f ? s.panes[f.focusedPaneId] : undefined;\n return pane?.activeItemId ? (s.items[pane.activeItemId] ?? null) : null;\n}\n\nconst NO_WINDOWS: CanvasState[\"windows\"] = Object.freeze({});\n\n/** Windows other than main (second app windows and pop-outs), by id. Stable per state. */\nexport function selectCanvasWindows(s: CanvasState): CanvasState[\"windows\"] {\n return s.windows ?? NO_WINDOWS;\n}\n\n/** One extra window, or undefined (main is never in this map). */\nexport const selectCanvasExtraWindow = (s: CanvasState, windowId: CanvasWindowId): CanvasExtraWindow | undefined => s.windows?.[windowId];\n\n/** The window an item is in, or null when it is not on the canvas. */\nexport const selectCanvasWindowOfItem = canvasWindowOfItem;\n\nconst NO_HISTORY: readonly CanvasHistoryEntry[] = Object.freeze([]);\n\n/** What a tab showed before, oldest first. Stable per state. */\nexport function selectCanvasItemHistory(s: CanvasState, itemId: CanvasItemId): readonly CanvasHistoryEntry[] {\n return s.items[itemId]?.history ?? NO_HISTORY;\n}\n\n/** Whether a tab offers Back (it navigated in place). */\nexport const selectCanvasCanGoBack = (s: CanvasState, itemId: CanvasItemId): boolean => (s.items[itemId]?.history?.length ?? 0) > 0;\n\n/** Whether a tab offers Forward (it went Back and has not navigated elsewhere since). */\nexport const selectCanvasCanGoForward = (s: CanvasState, itemId: CanvasItemId): boolean => (s.items[itemId]?.forward?.length ?? 0) > 0;\n\n/**\n * The ONE pane a phone presents: the focused pane when it holds a tab, else\n * the first pane that does (an empty pane is never presented over tabs that\n * exist — the header and the body always describe the same pane), else the\n * focused one.\n */\nexport function selectCanvasPresentedPaneId(s: CanvasState, windowId?: CanvasWindowId): CanvasPaneId | null {\n const f = frame(s, windowId);\n if (!f) return null;\n const ids = listPaneIds(f.layout);\n const holds = (id: CanvasPaneId) => (s.panes[id]?.itemIds.length ?? 0) > 0;\n const focused = ids.find((id) => id === f.focusedPaneId);\n if (focused && holds(focused)) return focused;\n return ids.find(holds) ?? focused ?? ids[0] ?? null;\n}\n","/**\n * Presentation — what a body knows about the space the canvas gives it.\n *\n * A body rendered in the canvas is told so, and told its live shape: a tall\n * narrow pane is not a wide page. Content that lays itself out in a direction\n * (a graph, a timeline, a row of cards) reads `orientation` and flows down a\n * portrait pane instead of across it. Pure data and pure functions, so a\n * desktop main process can compute the same answer for a native view.\n */\n\nexport type CanvasPresentationOrientation = \"portrait\" | \"landscape\" | \"square\";\n\nexport interface CanvasPresentation {\n /** Always \"canvas\" — a body rendered anywhere else gets no presentation at all. */\n readonly host: \"canvas\";\n /** The body's size in CSS pixels, live. */\n readonly width: number;\n readonly height: number;\n readonly orientation: CanvasPresentationOrientation;\n /** Narrower than `CANVAS_NARROW_WIDTH`: one column of content at most. */\n readonly isNarrow: boolean;\n /** The canvas is expanded to fill the space its host gives it. */\n readonly isFullscreen: boolean;\n /** How many panes the window's canvas shows right now. */\n readonly paneCount: number;\n}\n\n/**\n * THE phone breakpoint: a viewport at most this wide (CSS px) is a phone —\n * the canvas is a full-screen layer and presents ONE pane at a time. Same\n * number as styles.css `@media (max-width: 767px)`.\n */\nexport const CANVAS_PHONE_MAX_WIDTH = 767;\n\n/** Under this width (px) a body is narrow. */\nexport const CANVAS_NARROW_WIDTH = 480;\n\n/** Width ÷ height past which a body is landscape (and under whose inverse, portrait). */\nconst SQUARE_BAND = 1.2;\n\nexport function canvasOrientation(width: number, height: number): CanvasPresentationOrientation {\n if (!(width > 0) || !(height > 0)) return \"square\";\n const ratio = width / height;\n if (ratio >= SQUARE_BAND) return \"landscape\";\n if (ratio <= 1 / SQUARE_BAND) return \"portrait\";\n return \"square\";\n}\n\nexport function canvasPresentation(input: {\n readonly width: number;\n readonly height: number;\n readonly isFullscreen: boolean;\n readonly paneCount: number;\n}): CanvasPresentation {\n const width = Math.max(0, Math.round(input.width));\n const height = Math.max(0, Math.round(input.height));\n return {\n host: \"canvas\",\n width,\n height,\n orientation: canvasOrientation(width, height),\n isNarrow: width > 0 && width < CANVAS_NARROW_WIDTH,\n isFullscreen: input.isFullscreen,\n paneCount: Math.max(1, input.paneCount),\n };\n}\n\n/**\n * Which way content with a layout direction should flow: \"vertical\" (top to\n * bottom) in a portrait or narrow body, \"horizontal\" (left to right) otherwise\n * and outside the canvas.\n */\nexport function preferredFlowDirection(presentation: CanvasPresentation | null | undefined): \"vertical\" | \"horizontal\" {\n if (!presentation) return \"horizontal\";\n if (presentation.orientation === \"portrait\") return \"vertical\";\n if (presentation.orientation === \"landscape\") return \"horizontal\";\n return presentation.isNarrow ? \"vertical\" : \"horizontal\";\n}\n","/**\n * \"Toggle or focus this kind\" — what a toolbar icon does (the desktop's\n * Terminal/Review/Browser icons, the web's quick-tool launchers):\n *\n * absent → open it (and reveal the canvas)\n * background → bring it forward: activate its tab, focus its pane, reveal\n * visible → close it (default) or put the canvas away (`whenVisible: \"hide\"`);\n * closing the canvas's LAST tab puts the canvas away too — a toggle\n * never leaves an empty \"New tab\" launcher behind\n *\n * \"Visible\" means: on the canvas, the active tab of its pane, and its window's\n * canvas is open. The same item in a popped-out window counts in that window.\n */\n\nimport { canvasItemId } from \"./ids\";\nimport { canvasWindowFrame, canvasWindowOfItem } from \"./reducer\";\nimport type { CanvasController } from \"./controller\";\nimport { selectCanvasWindowItemCount } from \"./selectors\";\nimport type { CanvasJson, CanvasState } from \"./types\";\n\nexport type CanvasKindVisibility = \"absent\" | \"background\" | \"visible\";\n\nexport const CANVAS_DEFAULT_KEY = \"default\";\n\n/** Stable primitive result — safe in useSyncExternalStore and useSelector. */\nexport function selectCanvasKindVisibility(state: CanvasState, kind: string, key: string = CANVAS_DEFAULT_KEY): CanvasKindVisibility {\n const itemId = canvasItemId(kind, key);\n if (!state.items[itemId]) return \"absent\";\n const windowId = canvasWindowOfItem(state, itemId);\n if (!windowId) return \"background\";\n const isOpen = canvasWindowFrame(state, windowId)?.isOpen ?? false;\n const pane = Object.values(state.panes).find((p) => p.itemIds.includes(itemId));\n return isOpen && pane?.activeItemId === itemId ? \"visible\" : \"background\";\n}\n\nexport interface ToggleKindInput {\n readonly kind: string;\n /** Default \"default\" — one instance of the kind (a toolbar tool). */\n readonly key?: string | undefined;\n /** Data for a NEW item; an existing item keeps its data. */\n readonly data?: CanvasJson | undefined;\n readonly title?: string | null | undefined;\n /** What a click does when the item is already in front. Default \"close\". */\n readonly whenVisible?: \"close\" | \"hide\" | undefined;\n}\n\n/** Returns what the item is after the click. */\nexport function toggleKind(controller: CanvasController, input: ToggleKindInput): CanvasKindVisibility {\n const key = input.key ?? CANVAS_DEFAULT_KEY;\n const itemId = canvasItemId(input.kind, key);\n const before = selectCanvasKindVisibility(controller.getState(), input.kind, key);\n\n if (before === \"visible\") {\n if ((input.whenVisible ?? \"close\") === \"close\") {\n const windowId = canvasWindowOfItem(controller.getState(), itemId);\n controller.close(itemId);\n // That was everything this canvas held: put it away instead of leaving an empty launcher open.\n if (windowId && selectCanvasWindowItemCount(controller.getState(), windowId) === 0) controller.hide(windowId);\n } else {\n controller.hide(canvasWindowOfItem(controller.getState(), itemId) ?? undefined);\n }\n return selectCanvasKindVisibility(controller.getState(), input.kind, key);\n }\n\n if (before === \"background\") {\n // An existing item is never re-fed data: open() activates, focuses its pane and reveals.\n controller.open({ kind: input.kind, key });\n const windowId = canvasWindowOfItem(controller.getState(), itemId);\n if (windowId) controller.show(windowId);\n return selectCanvasKindVisibility(controller.getState(), input.kind, key);\n }\n\n const opened = controller.open({\n kind: input.kind,\n key,\n ...(input.data !== undefined ? { data: input.data } : {}),\n ...(input.title !== undefined ? { title: input.title } : {}),\n });\n return opened ? selectCanvasKindVisibility(controller.getState(), input.kind, key) : \"absent\";\n}\n","\"use client\";\n\n/**\n * Everything that must be able to draw ABOVE a native view.\n *\n * A desktop host draws some canvas bodies outside the DOM (an Electron\n * WebContentsView). Native views always paint over the page, so anything the\n * canvas floats — tooltips, drop indicators, the tab being dragged, menus —\n * goes through ports the host can implement in its own overlay layer. The\n * defaults draw in the DOM (a portal on document.body), which is right for\n * every host without native views.\n *\n * While package DOM floats over the canvas (a DOM menu is open, a tab is being\n * dragged), native bodies are reported `visible: false` so the host can hide\n * them: the DOM underneath must be seen, and must receive the drop.\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { CanvasItemId, CanvasPaneId, CanvasRect, CanvasWindowId } from \"../index\";\n\n/** One floating thing. Plain data, so a host can draw it in another process. */\nexport type CanvasFloating =\n | { readonly type: \"tooltip\"; readonly text: string; readonly anchor: CanvasRect; readonly side: \"top\" | \"bottom\" }\n | { readonly type: \"drop-indicator\"; readonly rect: CanvasRect; readonly paneId: CanvasPaneId }\n | { readonly type: \"tab-drag\"; readonly itemId: CanvasItemId; readonly title: string };\n\nexport interface CanvasOverlayPort {\n /** Shows a floating element above everything (native views included); returns its remover. */\n show(element: CanvasFloating): () => void;\n}\n\n/** A serializable \"…\" menu: the package keeps the handlers, a host draws the entries. */\nexport type CanvasMenuEntry =\n | { readonly type: \"item\"; readonly id: string; readonly label: string; readonly destructive?: boolean }\n | { readonly type: \"separator\" };\n\n/** Shows a menu at `anchor` (e.g. Electron `Menu.popup`); resolves the chosen entry id, or null. */\nexport type CanvasShowMenu = (entries: readonly CanvasMenuEntry[], anchor: CanvasRect) => Promise<string | null>;\n\n/** A native body's frame: window CSS pixels plus the device pixel ratio. */\nexport interface CanvasNativeRect extends CanvasRect {\n readonly devicePixelRatio: number;\n}\n\nexport interface CanvasNativeBodyInfo {\n /** False while package DOM floats over the canvas (a DOM menu, a tab drag): hide the native view. */\n readonly visible: boolean;\n readonly windowId: CanvasWindowId;\n}\n\n/** Reports where a native body sits; null when it is hidden or gone. Called in the frame the layout changed. */\nexport type CanvasNativeBodyFrame = (itemId: CanvasItemId, rect: CanvasNativeRect | null, info: CanvasNativeBodyInfo) => void;\n\nexport interface CanvasLayer {\n /** Shows through the host overlay port, or the DOM default. */\n show(element: CanvasFloating): () => void;\n /** Marks package DOM floating over the canvas (default DOM menu, tab drag). */\n beginBlocking(): () => void;\n isBlocked(): boolean;\n readonly dom: {\n list(): readonly (readonly [number, CanvasFloating])[];\n subscribe(listener: () => void): () => void;\n };\n readonly native: {\n register(measure: () => void): () => void;\n report(itemId: CanvasItemId, rect: CanvasNativeRect | null, info: CanvasNativeBodyInfo): void;\n /** Re-measures every native body now (call it per frame while the host animates its own layout). */\n remeasure(): void;\n };\n}\n\ninterface LayerPorts {\n readonly overlay?: CanvasOverlayPort | undefined;\n readonly onNativeBodyFrame?: CanvasNativeBodyFrame | undefined;\n}\n\nexport function createCanvasLayer(getPorts: () => LayerPorts): CanvasLayer {\n let elements: readonly (readonly [number, CanvasFloating])[] = [];\n let nextId = 1;\n const domListeners = new Set<() => void>();\n const emitDom = () => {\n for (const listener of [...domListeners]) listener();\n };\n let blocking = 0;\n const measures = new Set<() => void>();\n const last = new Map<CanvasItemId, string>();\n\n const remeasure = () => {\n for (const measure of [...measures]) measure();\n };\n\n return {\n show(element) {\n const host = getPorts().overlay;\n if (host) return host.show(element);\n const id = nextId++;\n elements = [...elements, [id, element] as const];\n emitDom();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n elements = elements.filter(([key]) => key !== id);\n emitDom();\n };\n },\n beginBlocking() {\n blocking += 1;\n remeasure();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n blocking -= 1;\n remeasure();\n };\n },\n isBlocked: () => blocking > 0,\n dom: {\n list: () => elements,\n subscribe(listener) {\n domListeners.add(listener);\n return () => domListeners.delete(listener);\n },\n },\n native: {\n register(measure) {\n measures.add(measure);\n return () => measures.delete(measure);\n },\n report(itemId, rect, info) {\n const key = rect\n ? `${rect.x},${rect.y},${rect.width},${rect.height},${rect.devicePixelRatio},${info.visible},${info.windowId}`\n : `null,${info.windowId}`;\n if (last.get(itemId) === key) return;\n if (rect) last.set(itemId, key);\n else last.delete(itemId);\n getPorts().onNativeBodyFrame?.(itemId, rect, info);\n },\n remeasure,\n },\n };\n}\n\n/** Floating elements drawn in the DOM when the host gives no overlay port. */\nexport function CanvasDomOverlay({ layer }: { layer: CanvasLayer }) {\n const elements = useSyncExternalStore(layer.dom.subscribe, layer.dom.list, layer.dom.list);\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n if (!mounted || elements.length === 0 || typeof document === \"undefined\") return null;\n return createPortal(\n <div className=\"mxc-overlay\" aria-hidden=\"true\">\n {elements.map(([id, element]) => (\n <FloatingView key={id} element={element} />\n ))}\n </div>,\n document.body,\n );\n}\n\nfunction FloatingView({ element }: { element: CanvasFloating }) {\n if (element.type === \"drop-indicator\") {\n const { x, y, width, height } = element.rect;\n return <div className=\"mxc-drop-indicator\" style={{ left: x, top: y, width, height }} />;\n }\n if (element.type === \"tooltip\") return <Tooltip element={element} />;\n return null;\n}\n\nfunction Tooltip({ element }: { element: Extract<CanvasFloating, { type: \"tooltip\" }> }) {\n const ref = useRef<HTMLDivElement>(null);\n const { anchor, side, text } = element;\n const top = side === \"bottom\" ? anchor.y + anchor.height + 6 : anchor.y - 6;\n const centre = anchor.x + anchor.width / 2;\n // Kept inside the window: a close button sits at the window's right edge.\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n const width = el.offsetWidth;\n const left = Math.min(Math.max(4, centre - width / 2), Math.max(4, window.innerWidth - width - 4));\n el.style.left = `${left}px`;\n el.style.visibility = \"visible\";\n }, [centre, text]);\n return (\n <div ref={ref} className=\"mxc-tooltip\" data-side={side} role=\"tooltip\" style={{ top, left: centre, visibility: \"hidden\" }}>\n {text}\n </div>\n );\n}\n\n/** A DOMRect as plain data. */\nexport function toCanvasRect(rect: { left: number; top: number; width: number; height: number }): CanvasRect {\n return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };\n}\n","/**\n * THE canvas kind registry. A kind is one sort of thing the canvas can show —\n * an artifact, a document, a chat, a notification feed. Any feature adds a\n * kind with ONE call and never touches canvas code:\n *\n * registerCanvasKind(defineCanvasKind<{ noteId: string }>({\n * id: \"note\",\n * label: \"Note\",\n * icon: NoteIcon,\n * load: () => import(\"./NoteCanvasView\"),\n * title: (data) => data.noteId,\n * }));\n *\n * The registry lives on globalThis under a Symbol.for key so duplicated\n * bundles (ESM + CJS, two chunks) share ONE registry.\n */\n\nimport type { ComponentType, ReactNode } from \"react\";\nimport type {\n CanvasController,\n CanvasItem,\n CanvasJson,\n CanvasPaneId,\n CanvasPreferredTarget,\n CanvasPresentation,\n CanvasSessionAttachReason,\n CanvasSessionDetachReason,\n CanvasSessionEvent,\n CanvasWindowId,\n} from \"../index\";\n\nexport interface CanvasKindProps<TData extends CanvasJson = CanvasJson> {\n readonly item: CanvasItem;\n readonly data: TData;\n readonly paneId: CanvasPaneId;\n readonly isFocused: boolean;\n /**\n * On screen right now: its tab is active and its canvas is open. A body\n * stays mounted while hidden (a background tab, a put-away canvas) — pause\n * costly work (polling, animation) while this is false.\n */\n readonly isVisible: boolean;\n /** The canvas, acting for the window this pane is in. */\n readonly canvas: CanvasController;\n readonly windowId: CanvasWindowId;\n /**\n * The space this body has, live: size, orientation, narrow, expanded, pane\n * count. Lay content out for it (a graph in a tall narrow pane flows top to\n * bottom). Nested components read the same value with `useCanvasPresentation()`.\n */\n readonly presentation: CanvasPresentation;\n}\n\nexport interface CanvasMenuItem {\n readonly id: string;\n readonly label: string;\n readonly icon?: ReactNode;\n readonly onSelect: () => void;\n readonly destructive?: boolean;\n}\n\nexport interface CanvasKind<TData extends CanvasJson = CanvasJson> {\n readonly id: string;\n /** Singular noun shown in menus and the empty-pane launcher. */\n readonly label: string;\n readonly icon: ComponentType<{ className?: string }>;\n /** Eager component. Provide this OR `load` (optional for a native body or an `unavailable` placeholder). */\n readonly component?: ComponentType<CanvasKindProps<TData>>;\n /** Lazy component — the kind's code loads only when a tab of it renders. */\n readonly load?: () => Promise<{ default: ComponentType<CanvasKindProps<TData>> }>;\n /** Tab title from the item's data. Falls back to the item's title, then `label`. */\n readonly title?: (data: TData, item: CanvasItem) => string;\n /**\n * Comes back after a reload. Default true; false for live things that cannot\n * resume. \"session\": the tab is a view onto a process the HOST keeps (a\n * terminal) — it comes back, closing it DETACHES (onDetach) instead of\n * killing, and a restore or a move REATTACHES (onAttach).\n */\n readonly restore?: boolean | \"session\";\n /** restore \"session\": the session's key. Default: `data.sessionKey` when it is a string. */\n readonly sessionKey?: (data: TData, item: CanvasItem) => string | null;\n /** restore \"session\": the tab now shows this session (\"open\" | \"restore\" | \"arrive\"). */\n readonly onAttach?: (event: CanvasSessionEvent<CanvasSessionAttachReason>) => void;\n /** restore \"session\": the tab no longer shows it (\"close\" | \"leave\" | \"unmount\"). Never kill the process here. */\n readonly onDetach?: (event: CanvasSessionEvent<CanvasSessionDetachReason>) => void;\n /**\n * @deprecated Since 0.5.0 every body stays mounted from the first time it\n * is shown until its tab closes — through tab switches, splits, moves,\n * expand and the canvas being put away. This field changes nothing.\n */\n readonly keepAlive?: boolean;\n /**\n * Opt OUT of staying mounted: the body unmounts whenever it is not on\n * screen (a hidden tab, a put-away canvas) and mounts fresh when shown.\n * Only for genuinely heavy bodies whose state is cheap to rebuild.\n */\n readonly unmountWhenHidden?: boolean;\n /**\n * Where a NEW item of this kind opens while the canvas already shows\n * something: \"split-down\" puts it in a pane below (the layout rules' split\n * share — a feed under the work), \"split-right\" beside, \"focused\" (default)\n * in the focused pane. A pane already showing this kind takes it instead of\n * a new split. A caller's explicit `target` always wins.\n */\n readonly preferredTarget?: CanvasPreferredTarget;\n /**\n * \"native\": the body is drawn by the HOST outside the DOM (an Electron\n * WebContentsView). The pane renders a placeholder and reports its rect\n * through the provider's `onNativeBodyFrame`. Default \"dom\".\n */\n readonly body?: \"dom\" | \"native\";\n /**\n * An honest one-line state instead of the body while its backend is not\n * there (\"Files · next release\", \"No changes to show\"). Return null to show\n * the body. Read on every render.\n */\n readonly unavailable?: (data: TData, item: CanvasItem) => string | null;\n /** When set, the kind is offered in an empty pane's launcher. */\n readonly launcher?: { readonly key: string; readonly data: TData; readonly title?: string };\n /**\n * Controls at the START of the pane header, after the title or tabs: a\n * \"+ new terminal\", a browser's back / forward / reload / address bar. The\n * slot grows to fill the header.\n */\n readonly HeaderLeading?: ComponentType<CanvasKindProps<TData>>;\n /** The kind's own button, rendered left of the pane's \"…\" menu. */\n readonly HeaderAction?: ComponentType<CanvasKindProps<TData>>;\n /**\n * A toolbar ROW between the pane header and the body, for the active item\n * only (a browser's back / forward / reload / address / screenshot). Always\n * DOM, never covered by a native view: a `body: \"native\"` frame is measured\n * BELOW it.\n */\n readonly Toolbar?: ComponentType<CanvasKindProps<TData>>;\n /** Kind-specific entries for the pane's \"…\" menu. */\n readonly menuItems?: (props: CanvasKindProps<TData>) => readonly CanvasMenuItem[];\n}\n\n/** Erased form stored in the registry. */\nexport type AnyCanvasKind = CanvasKind<CanvasJson>;\n\n/**\n * Typed authoring helper. The data type is a promise the kind's opener keeps;\n * the registry stores the erased form (the cast is the one registration seam).\n */\nexport function defineCanvasKind<TData extends CanvasJson>(kind: CanvasKind<TData>): AnyCanvasKind {\n if (!kind.component && !kind.load && kind.body !== \"native\" && !kind.unavailable) {\n throw new Error(`[@ai-matrx/canvas] kind \"${kind.id}\" needs a component, a load(), a native body or an unavailable() state.`);\n }\n return kind as unknown as AnyCanvasKind;\n}\n\n/** The session key of an item of a session kind (`kind.sessionKey`, else `data.sessionKey`). */\nexport function canvasSessionKey(kind: AnyCanvasKind, item: CanvasItem): string | null {\n if (kind.sessionKey) return kind.sessionKey(item.data, item);\n const data = item.data;\n if (data && typeof data === \"object\" && !Array.isArray(data)) {\n const key = (data as { readonly [key: string]: CanvasJson | undefined }).sessionKey;\n return typeof key === \"string\" && key ? key : null;\n }\n return null;\n}\n\ninterface RegistryState {\n kinds: Map<string, AnyCanvasKind>;\n listeners: Set<() => void>;\n version: number;\n}\n\nconst REGISTRY = Symbol.for(\"ai-matrx.canvas.kinds\");\n\nfunction registry(): RegistryState {\n const g = globalThis as unknown as { [REGISTRY]?: RegistryState };\n g[REGISTRY] ??= { kinds: new Map(), listeners: new Set(), version: 0 };\n return g[REGISTRY];\n}\n\nfunction notify(state: RegistryState) {\n state.version += 1;\n for (const listener of [...state.listeners]) listener();\n}\n\n/** Registers (or replaces) a kind. Returns an unregister function. */\nexport function registerCanvasKind(kind: AnyCanvasKind): () => void {\n const state = registry();\n state.kinds.set(kind.id, kind);\n notify(state);\n return () => {\n if (state.kinds.get(kind.id) === kind) {\n state.kinds.delete(kind.id);\n notify(state);\n }\n };\n}\n\nexport function registerCanvasKinds(kinds: readonly AnyCanvasKind[]): () => void {\n const undo = kinds.map(registerCanvasKind);\n return () => undo.forEach((fn) => fn());\n}\n\nexport function getCanvasKind(id: string): AnyCanvasKind | undefined {\n return registry().kinds.get(id);\n}\n\nexport function listCanvasKinds(): AnyCanvasKind[] {\n return [...registry().kinds.values()];\n}\n\nexport function subscribeCanvasKinds(listener: () => void): () => void {\n const state = registry();\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nexport function getCanvasKindsVersion(): number {\n return registry().version;\n}\n","\"use client\";\n\n/**\n * The canvas column: full height, right edge, its own strip of the top of the\n * window. Width drags from the left edge; panes split in either direction;\n * expanded, it fills whatever space the HOST placed it in. On a phone it\n * becomes a full-screen layer.\n *\n * Hosts with their own shell place <CanvasColumn/> and read\n * `useCanvasColumnWidth()` for the track size (desktop: tell the provider the\n * `regionWidth` the canvas shares). Hosts without one wrap their app in\n * <CanvasFrame>. A pop-out window renders `<CanvasColumn placement=\"fill\"/>`.\n *\n * The column NEVER unmounts while its provider lives: put away, it is 0 wide,\n * `inert` and hidden, and every body in it keeps its state. Opening, closing,\n * expanding and width changes animate on ONE motion contract —\n * `--mxc-motion-duration` / `--mxc-motion-ease` (default 600ms,\n * cubic-bezier(0.4, 0, 0.2, 1): the shell sidebar's slide) — and the content\n * keeps its width while the column slides, so it moves instead of reflowing.\n * A host shell that reflows beside the column transitions on the same two\n * properties (see README § Motion).\n */\n\nimport {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n type CSSProperties,\n type PointerEvent as ReactPointerEvent,\n type ReactNode,\n} from \"react\";\nimport { TapTargetButton, TapTargetButtonTransparent } from \"@ai-matrx/tap-target\";\nimport {\n CANVAS_DEFAULT_KEY,\n CANVAS_PHONE_MAX_WIDTH,\n listPaneIds,\n selectCanvasPresentedPaneId,\n CANVAS_MIN_SPLIT_FRACTION,\n canvasShortcutHint,\n clampDraggedCanvasWidth,\n fitCanvasWidth,\n selectCanvasIsFullscreen,\n selectCanvasIsOpen,\n selectCanvasLayout,\n selectCanvasWidth,\n selectCanvasWindowItemCount,\n shouldStackSplit,\n type CanvasJson,\n type CanvasLayoutNode,\n type CanvasPaneId,\n} from \"../index\";\nimport { CanvasBodyLayer } from \"./bodies\";\nimport { beginCanvasResize } from \"./resizeGesture\";\nimport { CanvasPaneView } from \"./CanvasPane\";\nimport { PanelRightIcon } from \"./icons\";\nimport { useCanvas, useCanvasInternals, useCanvasKind, useCanvasKindToggle, useCanvasState, useRegisterCanvasPresence } from \"./provider\";\nimport { CanvasSinglePaneContext, CanvasSlotsContext, createCanvasSlots } from \"./slots\";\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nfunction subscribeViewport(listener: () => void) {\n window.addEventListener(\"resize\", listener);\n return () => window.removeEventListener(\"resize\", listener);\n}\n\n/** The window's width, live; 0 during server render. */\nfunction useViewportWidth(): number {\n return useSyncExternalStore(subscribeViewport, () => window.innerWidth, () => 0);\n}\n\n/** The width of the space the canvas shares: the host's `regionWidth`, else the window. */\nfunction useRegionWidth(): number {\n const viewport = useViewportWidth();\n const { regionWidth } = useCanvasInternals();\n return regionWidth ?? viewport;\n}\n\n/** The column's rendered width in px for this window: 0 when put away, null when expanded. */\nexport function useCanvasColumnWidth(): number | null {\n const { controller, windowId } = useCanvasInternals();\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const width = useCanvasState((s) => selectCanvasWidth(s, windowId));\n const region = useRegionWidth();\n if (!isOpen) return 0;\n if (isFullscreen) return null;\n return fitCanvasWidth(width, region, controller.rules);\n}\n\nexport interface CanvasColumnProps {\n readonly className?: string;\n readonly style?: CSSProperties;\n /** Called with the live width while the edge is dragged, then null — lets a host shell reflow in step. */\n readonly onLiveWidth?: (width: number | null) => void;\n /** \"docked\": the right-edge column with a width handle. \"fill\": fills its container (a pop-out window). */\n readonly placement?: \"docked\" | \"fill\";\n}\n\nexport function CanvasColumn({ className, style, onLiveWidth, placement = \"docked\" }: CanvasColumnProps) {\n const { controller, windowId, layer } = useCanvasInternals();\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const width = useCanvasState((s) => selectCanvasWidth(s, windowId));\n const layout = useCanvasState((s) => selectCanvasLayout(s, windowId));\n const presentedPaneId = useCanvasState((s) => selectCanvasPresentedPaneId(s, windowId));\n const region = useRegionWidth();\n const viewport = useViewportWidth();\n // A phone presents ONE pane at a time (the focused one, carrying every pane's tabs); the\n // layout tree is untouched, so a wider screen gets its split back.\n const singlePane = placement === \"docked\" && viewport > 0 && viewport <= CANVAS_PHONE_MAX_WIDTH;\n const [dragWidth, setDragWidth] = useState<number | null>(null);\n const [slots] = useState(createCanvasSlots);\n const ref = useRef<HTMLElement>(null);\n useRegisterCanvasPresence();\n\n // While the column slides, native views follow it frame by frame (DOM bodies move with the column).\n useEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n let frame = 0;\n let running = false;\n const tick = () => {\n layer.native.remeasure();\n frame = running ? requestAnimationFrame(tick) : 0;\n };\n const start = (event: TransitionEvent) => {\n if (event.target !== el || running) return;\n running = true;\n frame = requestAnimationFrame(tick);\n };\n const stop = (event: TransitionEvent) => {\n if (event.target !== el) return;\n running = false;\n if (frame) cancelAnimationFrame(frame);\n frame = 0;\n layer.native.remeasure();\n };\n el.addEventListener(\"transitionrun\", start);\n el.addEventListener(\"transitionend\", stop);\n el.addEventListener(\"transitioncancel\", stop);\n return () => {\n running = false;\n if (frame) cancelAnimationFrame(frame);\n el.removeEventListener(\"transitionrun\", start);\n el.removeEventListener(\"transitionend\", stop);\n el.removeEventListener(\"transitioncancel\", stop);\n };\n }, [layer]);\n\n if (!layout) return null;\n const fitted = fitCanvasWidth(width, region, controller.rules);\n const shown = dragWidth ?? fitted;\n\n return (\n <aside\n ref={ref}\n className={[\"mxc-column\", className].filter(Boolean).join(\" \")}\n data-open={isOpen ? \"\" : undefined}\n data-fullscreen={isOpen && isFullscreen ? \"\" : undefined}\n data-placement={placement}\n data-mxc-window={windowId}\n aria-label=\"Canvas\"\n aria-hidden={isOpen ? undefined : true}\n inert={!isOpen}\n style={{ ...style, [\"--mxc-width\" as string]: `${shown}px` }}\n >\n <div className=\"mxc-column-inner\">\n {placement === \"docked\" && isOpen && !isFullscreen ? (\n <WidthHandle\n width={fitted}\n region={region}\n onDrag={(next) => {\n setDragWidth(next);\n onLiveWidth?.(next);\n }}\n />\n ) : null}\n <CanvasSlotsContext.Provider value={slots}>\n <CanvasSinglePaneContext.Provider value={singlePane}>\n <div className=\"mxc-layout\" data-single-pane={singlePane ? \"\" : undefined}>\n {singlePane ? <CanvasPaneView paneId={presentedPaneId ?? listPaneIds(layout)[0]!} /> : <LayoutNodeView node={layout} />}\n </div>\n <CanvasBodyLayer />\n </CanvasSinglePaneContext.Provider>\n </CanvasSlotsContext.Provider>\n </div>\n </aside>\n );\n}\n\nfunction WidthHandle({ width, region, onDrag }: { width: number; region: number; onDrag: (width: number | null) => void }) {\n const canvas = useCanvas();\n const start = useRef<{ x: number; width: number; end: () => void } | null>(null);\n useEffect(() => () => start.current?.end(), []);\n const clamp = (next: number) => clampDraggedCanvasWidth(next, region, canvas.rules);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n event.preventDefault();\n event.currentTarget.setPointerCapture(event.pointerId);\n start.current?.end();\n start.current = { x: event.clientX, width, end: beginCanvasResize(\"\") };\n };\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!start.current) return;\n onDrag(clamp(start.current.width + (start.current.x - event.clientX)));\n };\n const finish = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!start.current) return;\n const next = clamp(start.current.width + (start.current.x - event.clientX));\n start.current.end();\n start.current = null;\n onDrag(null);\n canvas.setWidth(next);\n };\n\n return (\n <div\n className=\"mxc-width-handle\"\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label=\"Resize canvas\"\n aria-valuenow={width}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={finish}\n onPointerCancel={finish}\n onLostPointerCapture={finish}\n onDoubleClick={() => canvas.setWidth(clamp(Math.round(region / 2)))}\n onKeyDown={(event) => {\n if (event.key === \"ArrowLeft\") canvas.setWidth(clamp(width + 32));\n if (event.key === \"ArrowRight\") canvas.setWidth(clamp(width - 32));\n }}\n />\n );\n}\n\nfunction LayoutNodeView({ node }: { node: CanvasLayoutNode }) {\n if (node.type === \"pane\") return <CanvasPaneView paneId={node.paneId} />;\n return <SplitView node={node} />;\n}\n\n/** Live width of an element, measured only when `enabled` (a rule needs it). */\nfunction useMeasuredWidth(ref: { current: HTMLElement | null }, enabled: boolean): number {\n const [width, setWidth] = useState(0);\n useIsoLayoutEffect(() => {\n const el = ref.current;\n if (!enabled || !el) return;\n setWidth(el.getBoundingClientRect().width);\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => setWidth(el.getBoundingClientRect().width));\n observer.observe(el);\n return () => observer.disconnect();\n }, [enabled]);\n return width;\n}\n\nfunction SplitView({ node }: { node: Extract<CanvasLayoutNode, { type: \"split\" }> }) {\n const canvas = useCanvas();\n const ref = useRef<HTMLDivElement>(null);\n const [liveSizes, setLiveSizes] = useState<readonly number[] | null>(null);\n const sizes = liveSizes ?? node.sizes;\n const measuredWidth = useMeasuredWidth(ref, node.orientation === \"horizontal\" && canvas.rules.paneMinWidth > 0);\n // Narrow windows stack side-by-side panes instead of squeezing them.\n const stacked = node.orientation === \"horizontal\" && shouldStackSplit(measuredWidth, node.children.length, canvas.rules);\n const orientation = stacked ? \"vertical\" : node.orientation;\n const horizontal = orientation === \"horizontal\";\n\n const beginDrag = (index: number) => (event: ReactPointerEvent<HTMLDivElement>) => {\n const el = ref.current;\n if (!el) return;\n event.preventDefault();\n event.currentTarget.setPointerCapture(event.pointerId);\n const rect = el.getBoundingClientRect();\n const total = horizontal ? rect.width : rect.height;\n const origin = horizontal ? event.clientX : event.clientY;\n const base = [...node.sizes];\n const pair = (base[index] ?? 0) + (base[index + 1] ?? 0);\n const target = event.currentTarget;\n const end = beginCanvasResize(horizontal ? \"col\" : \"row\");\n\n const compute = (pos: number) => {\n const delta = (pos - origin) / total;\n const min = CANVAS_MIN_SPLIT_FRACTION;\n const first = Math.min(pair - min, Math.max(min, (base[index] ?? 0) + delta));\n const next = [...base];\n next[index] = first;\n next[index + 1] = pair - first;\n return next;\n };\n const move = (e: PointerEvent) => setLiveSizes(compute(horizontal ? e.clientX : e.clientY));\n const up = (e: PointerEvent) => {\n target.removeEventListener(\"pointermove\", move);\n target.removeEventListener(\"pointerup\", up);\n target.removeEventListener(\"pointercancel\", up);\n end();\n setLiveSizes(null);\n canvas.resizeSplit(node.id, compute(horizontal ? e.clientX : e.clientY));\n };\n target.addEventListener(\"pointermove\", move);\n target.addEventListener(\"pointerup\", up);\n target.addEventListener(\"pointercancel\", up);\n };\n\n return (\n <div ref={ref} className=\"mxc-split\" data-orientation={orientation} data-stacked={stacked ? \"\" : undefined}>\n {node.children.map((child, i) => (\n <SplitChild\n key={child.type === \"pane\" ? child.paneId : child.id}\n size={sizes[i] ?? 1 / node.children.length}\n handle={\n i < node.children.length - 1 ? (\n <div\n className=\"mxc-split-handle\"\n role=\"separator\"\n aria-orientation={horizontal ? \"vertical\" : \"horizontal\"}\n onPointerDown={beginDrag(i)}\n onDoubleClick={() => canvas.resizeSplit(node.id, node.children.map(() => 1 / node.children.length))}\n />\n ) : null\n }\n >\n <LayoutNodeView node={child} />\n </SplitChild>\n ))}\n </div>\n );\n}\n\nfunction SplitChild({ size, handle, children }: { size: number; handle: ReactNode; children: ReactNode }) {\n return (\n <>\n <div className=\"mxc-split-child\" style={{ flexGrow: size, flexBasis: 0 }}>\n {children}\n </div>\n {handle}\n </>\n );\n}\n\nconst isMac = () => typeof navigator !== \"undefined\" && /mac|iphone|ipad/i.test(navigator.platform ?? \"\");\n\n/**\n * THE one button that opens and puts away the canvas (this window's).\n *\n * `variant` follows the tap-target PLACEMENT RULES (all glass or none): a host\n * whose header row is glass (a bar floating over scrolling content) passes\n * `\"glass\"` so the toggle matches its neighbours; on a solid bar keep the\n * default `\"transparent\"`.\n */\nexport function CanvasToggle({\n className,\n variant = \"transparent\",\n}: {\n className?: string;\n variant?: \"glass\" | \"transparent\";\n}) {\n const { controller, windowId } = useCanvasInternals();\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const count = useCanvasState((s) => selectCanvasWindowItemCount(s, windowId));\n const hint = canvasShortcutHint(\"canvas.toggle\", isMac());\n const Button = variant === \"glass\" ? TapTargetButton : TapTargetButtonTransparent;\n return (\n <span className={[\"mxc-toggle\", className].filter(Boolean).join(\" \")} data-open={isOpen ? \"\" : undefined}>\n <Button\n ariaLabel={isOpen ? \"Hide canvas\" : \"Show canvas\"}\n tooltip={`${isOpen ? \"Hide canvas\" : \"Show canvas\"}${hint ? ` (${hint})` : \"\"}`}\n icon={<PanelRightIcon />}\n pressed={isOpen}\n onClick={() => controller.toggle()}\n />\n {count > 0 && !isOpen ? <span className=\"mxc-toggle-badge\">{count}</span> : null}\n </span>\n );\n}\n\n/** One icon of a `CanvasKindIcons` cluster. A string is a kind on its \"default\" tab. */\nexport interface CanvasKindIcon {\n readonly kind: string;\n /** Default \"default\" — one instance of the kind (a toolbar tool). */\n readonly key?: string | undefined;\n /** Data for a NEW item; an open one keeps its own. */\n readonly data?: CanvasJson | undefined;\n readonly title?: string | null | undefined;\n /** What a press does while the item is in front: close it (default) or put the canvas away. */\n readonly whenVisible?: \"close\" | \"hide\" | undefined;\n /** Accessible name and tooltip. Default: the kind's label. */\n readonly label?: string | undefined;\n}\n\n/**\n * A cluster of icon buttons for pinned kinds — the tool icons of a header\n * (Terminal, Review, Browser…). Each toggles or focuses its kind and is drawn\n * pressed while its item is in front, so web and desktop show the same\n * cluster. A kind that is not registered draws nothing.\n */\nexport function CanvasKindIcons({\n kinds,\n variant = \"transparent\",\n className,\n label = \"Canvas tools\",\n}: {\n kinds: readonly (string | CanvasKindIcon)[];\n variant?: \"glass\" | \"transparent\";\n className?: string;\n label?: string;\n}) {\n return (\n <span role=\"group\" aria-label={label} className={[\"mxc-kind-icons\", className].filter(Boolean).join(\" \")}>\n {kinds.map((entry) => {\n const icon = typeof entry === \"string\" ? { kind: entry } : entry;\n return <KindIconButton key={`${icon.kind}::${icon.key ?? CANVAS_DEFAULT_KEY}`} icon={icon} variant={variant} />;\n })}\n </span>\n );\n}\n\nfunction KindIconButton({ icon, variant }: { icon: CanvasKindIcon; variant: \"glass\" | \"transparent\" }) {\n const kind = useCanvasKind(icon.kind);\n const toggle = useCanvasKindToggle({\n kind: icon.kind,\n key: icon.key,\n data: icon.data,\n title: icon.title,\n whenVisible: icon.whenVisible,\n });\n if (!kind) return null;\n const Icon = kind.icon;\n const Button = variant === \"glass\" ? TapTargetButton : TapTargetButtonTransparent;\n const name = icon.label ?? kind.label;\n return (\n <Button\n ariaLabel={name}\n tooltip={name}\n icon={<Icon />}\n pressed={toggle.isVisible}\n onClick={() => void toggle.toggle()}\n />\n );\n}\n\n/**\n * For hosts without their own shell (a Vite app, an Electron window): the app\n * on the left, the canvas column on the right, expand handled.\n */\nexport function CanvasFrame({ children, className }: { children: ReactNode; className?: string }) {\n const { windowId } = useCanvasInternals();\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n return (\n <div className={[\"mxc-frame\", className].filter(Boolean).join(\" \")} data-canvas-open={isOpen ? \"\" : undefined}>\n <div className=\"mxc-frame-main\" hidden={isOpen && isFullscreen}>\n {children}\n </div>\n <CanvasColumn />\n </div>\n );\n}\n","\"use client\";\n\n/**\n * THE stable body layer. Every item open in a window's canvas has ONE body,\n * rendered here — at the column root, keyed by the item's instance — and\n * placed over its pane's body slot by measured rect.\n *\n * tab switch → hide (never unmount)\n * split / move / resize → re-place (never remount, never re-parent)\n * expand / put away → re-place / hide\n *\n * So a body's React state, DOM focus and scroll position survive everything\n * but closing its tab. A body mounts the first time it is shown (a restored\n * background tab costs nothing until it is opened) and then stays mounted; a\n * kind may opt out with `unmountWhenHidden`. Native bodies are bodies on a\n * slot too: their placeholder lives in the same host and reports its frame.\n *\n * Moving a tab to ANOTHER window remounts it: that is a different column (on\n * the desktop, a different process).\n */\n\nimport {\n Component,\n Suspense,\n lazy,\n memo,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type ErrorInfo,\n type ReactNode,\n} from \"react\";\nimport {\n CANVAS_KEEP_ALIVE_DEPTH,\n canvasItemId,\n canvasPresentation,\n canvasWindowFrame,\n listPaneIds,\n selectCanvasPresentedPaneId,\n type CanvasController,\n type CanvasHistoryEntry,\n type CanvasItem,\n type CanvasItemId,\n type CanvasPaneId,\n type CanvasPresentation,\n type CanvasState,\n type CanvasWindowId,\n} from \"../index\";\nimport { CanvasPanelEmpty } from \"./chrome\";\nimport { usePaneDrop } from \"./dnd\";\nimport { AlertIcon } from \"./icons\";\nimport { toCanvasRect, type CanvasNativeRect } from \"./layer\";\nimport { useItemKind } from \"./launcher\";\nimport { CanvasPresentationContext } from \"./presentation\";\nimport { useCanvas, useCanvasInternals, useCanvasState } from \"./provider\";\nimport type { AnyCanvasKind, CanvasKindProps } from \"./registry\";\nimport { useCanvasSinglePane, useCanvasSlots, useSlotSize, type CanvasSlots } from \"./slots\";\n\n// The browser runs layout effects; a server render has no layout to report.\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\n// One lazy component per kind, shared across bodies and re-renders.\nconst LAZY = Symbol.for(\"ai-matrx.canvas.lazy\");\nfunction kindComponent(kind: AnyCanvasKind): ComponentType<CanvasKindProps> | null {\n if (kind.component) return kind.component;\n const holder = kind as AnyCanvasKind & { [LAZY]?: ComponentType<CanvasKindProps> };\n if (!holder[LAZY] && kind.load) holder[LAZY] = lazy(kind.load);\n return holder[LAZY] ?? null;\n}\n\n/** Forgets a kind's cached lazy component so \"Try again\" re-runs a failed chunk load. */\nfunction resetKindComponent(kind: AnyCanvasKind | undefined) {\n if (kind) delete (kind as AnyCanvasKind & { [LAZY]?: unknown })[LAZY];\n}\n\n/** The live presentation of a pane's slot (shared by its header controls and its bodies). */\nexport function usePanePresentation(slots: CanvasSlots, paneId: CanvasPaneId, isFullscreen: boolean, paneCount: number): CanvasPresentation {\n const size = useSlotSize(slots, paneId);\n return useMemo(\n () => canvasPresentation({ width: size.width, height: size.height, isFullscreen, paneCount }),\n [size.width, size.height, isFullscreen, paneCount],\n );\n}\n\ninterface Placed {\n readonly hostId: string;\n /** The live item — for a kept step, the tab that keeps it. */\n readonly itemId: CanvasItemId;\n readonly paneId: CanvasPaneId;\n readonly active: boolean;\n /** An earlier content of the tab, held mounted and hidden so Back (or forward) returns the same body. */\n readonly kept: boolean;\n}\n\ninterface LayerShape {\n readonly isOpen: boolean;\n readonly isFullscreen: boolean;\n readonly focusedPaneId: string;\n /** The one pane a phone presents (selectCanvasPresentedPaneId). */\n readonly presentedPaneId: string;\n readonly paneCount: number;\n readonly placed: readonly Placed[];\n}\n\nconst hostKey = (item: CanvasItem) => item.instance ?? item.id;\nconst SEP = \"\\u0001\";\nconst ROW = \"\\u0002\";\n\n/** When a body was first created: an instance starts with its birth time (base 36). Fallback: the item's. */\nfunction bornAt(instance: string | undefined, fallback: number): number {\n const stamp = instance ? Number.parseInt(instance.slice(0, instance.indexOf(\":\")), 36) : Number.NaN;\n return Number.isFinite(stamp) ? stamp : fallback;\n}\n\n/**\n * The earlier contents of a tab whose bodies stay mounted (hidden): the newest\n * CANVAS_KEEP_ALIVE_DEPTH steps Back reaches and the steps Back left. Only\n * entries that carry the body's instance can be kept.\n */\nexport function keptCanvasSteps(item: CanvasItem): readonly CanvasHistoryEntry[] {\n const back = (item.history ?? []).slice(-CANVAS_KEEP_ALIVE_DEPTH);\n const forward = (item.kept ?? []).slice(-CANVAS_KEEP_ALIVE_DEPTH);\n return [...back, ...forward].filter((entry) => !!entry.instance);\n}\n\n/**\n * What the layer needs, as ONE string — so the layer re-renders only when a\n * tab opens, closes, moves, activates, navigates or the frame changes, never\n * when a tab's DATA changes (each body reads its own item). Bodies are in a\n * STABLE order (when each was born): moving a tab, Back or forward never\n * reorders the DOM (a moved iframe reloads).\n */\nfunction layerSignature(state: CanvasState, windowId: CanvasWindowId, onlyPane?: CanvasPaneId): string {\n const frame = canvasWindowFrame(state, windowId);\n if (!frame) return \"\";\n const rows: { born: number; hostId: string; row: string }[] = [];\n const seen = new Set<string>();\n const add = (hostId: string, born: number, fields: string[]) => {\n if (seen.has(hostId)) return;\n seen.add(hostId);\n rows.push({ born, hostId, row: [hostId, ...fields].join(SEP) });\n };\n const paneIds = listPaneIds(frame.layout);\n for (const paneId of onlyPane ? [onlyPane] : paneIds) {\n const pane = state.panes[paneId];\n for (const itemId of pane?.itemIds ?? []) {\n const item = state.items[itemId];\n if (!item) continue;\n add(hostKey(item), bornAt(item.instance, item.openedAt), [itemId, paneId, pane?.activeItemId === itemId ? \"1\" : \"0\", \"0\"]);\n for (const step of keptCanvasSteps(item)) add(step.instance!, bornAt(step.instance, item.openedAt), [itemId, paneId, \"0\", \"1\"]);\n }\n }\n rows.sort((a, b) => a.born - b.born || a.hostId.localeCompare(b.hostId));\n const head = [\n frame.isOpen ? \"1\" : \"0\",\n frame.isFullscreen ? \"1\" : \"0\",\n frame.focusedPaneId,\n String(paneIds.length),\n selectCanvasPresentedPaneId(state, windowId) ?? \"\",\n ].join(SEP);\n return [head, ...rows.map((r) => r.row)].join(ROW);\n}\n\nfunction parseSignature(signature: string): LayerShape | null {\n if (!signature) return null;\n const [head = \"\", ...rows] = signature.split(ROW);\n const [open, full, focusedPaneId = \"\", count = \"1\", presentedPaneId = \"\"] = head.split(SEP);\n return {\n isOpen: open === \"1\",\n isFullscreen: full === \"1\",\n focusedPaneId,\n presentedPaneId,\n paneCount: Number(count) || 1,\n placed: rows.map((row) => {\n const [hostId = \"\", itemId = \"\", paneId = \"\", active, kept] = row.split(SEP);\n return { hostId, itemId: itemId as CanvasItemId, paneId: paneId as CanvasPaneId, active: active === \"1\", kept: kept === \"1\" };\n }),\n };\n}\n\ninterface HostEntry {\n readonly element: HTMLDivElement;\n readonly paneId: CanvasPaneId;\n}\n\ninterface Placement {\n register(key: string, entry: HostEntry): () => void;\n place(): void;\n}\n\nfunction createPlacement(getRoot: () => HTMLElement | null, slots: CanvasSlots, afterPlace: () => void): Placement {\n const hosts = new Map<string, HostEntry>();\n let placing = false;\n const place = () => {\n const root = getRoot();\n if (!root || placing) return;\n placing = true;\n try {\n slots.measure();\n const base = root.getBoundingClientRect();\n for (const { element, paneId } of hosts.values()) {\n const slot = slots.slot(paneId);\n if (!slot) {\n element.dataset.placed = \"false\";\n continue;\n }\n const box = slot.getBoundingClientRect();\n const style = element.style;\n style.left = `${box.left - base.left}px`;\n style.top = `${box.top - base.top}px`;\n style.width = `${box.width}px`;\n style.height = `${box.height}px`;\n element.dataset.placed = \"true\";\n }\n } finally {\n placing = false;\n }\n afterPlace();\n };\n return {\n register(key, entry) {\n hosts.set(key, entry);\n return () => {\n if (hosts.get(key) === entry) hosts.delete(key);\n };\n },\n place,\n };\n}\n\n/**\n * The column's body layer: every body of this window, placed over its pane.\n * Rendered by `CanvasColumn` after the layout, so slots are registered first.\n */\nexport function CanvasBodyLayer() {\n const { windowId, layer } = useCanvasInternals();\n const slots = useCanvasSlots();\n const signature = useCanvasState((s) => layerSignature(s, windowId));\n // A phone shows one pane: only that pane's active body is on screen.\n const single = useCanvasSinglePane();\n const root = useRef<HTMLDivElement>(null);\n const [placement] = useState(() =>\n slots ? createPlacement(() => root.current, slots, () => layer.native.remeasure()) : null,\n );\n\n // Every commit can move a slot (a split, a toolbar row, a closed pane): re-place before paint.\n useIsoLayoutEffect(() => placement?.place());\n // Between commits: a slot resized (a split dragged, the column resized, the window resized).\n useIsoLayoutEffect(() => (slots && placement ? slots.subscribe(placement.place) : undefined), [slots, placement]);\n\n const shape = parseSignature(signature);\n if (!slots || !placement || !shape) return null;\n return (\n <div ref={root} className=\"mxc-bodies\" data-mxc-bodies={windowId}>\n {shape.placed.map(({ hostId, itemId, paneId, active, kept }) => (\n <BodyHost\n key={hostId}\n hostId={hostId}\n itemId={itemId}\n kept={kept}\n paneId={paneId}\n visible={shape.isOpen && active && (!single || paneId === shape.presentedPaneId)}\n focused={active && shape.focusedPaneId === paneId}\n isFullscreen={shape.isFullscreen}\n paneCount={shape.paneCount}\n slots={slots}\n placement={placement}\n />\n ))}\n </div>\n );\n}\n\n/**\n * A pane rendered on its own (outside a CanvasColumn): its bodies render in\n * its slot, in flow. Moving a tab between such panes remounts its body — the\n * stable layer is the column's.\n */\nexport function CanvasPaneInlineBodies({ paneId, slots }: { paneId: CanvasPaneId; slots: CanvasSlots }) {\n const { windowId } = useCanvasInternals();\n const shape = parseSignature(useCanvasState((s) => layerSignature(s, windowId, paneId)));\n if (!shape) return null;\n return (\n <>\n {shape.placed.map(({ hostId, itemId, active, kept }) => (\n <BodyHost\n key={hostId}\n hostId={hostId}\n itemId={itemId}\n kept={kept}\n paneId={paneId}\n visible={active}\n focused={active && shape.focusedPaneId === paneId}\n isFullscreen={shape.isFullscreen}\n paneCount={shape.paneCount}\n slots={slots}\n placement={null}\n />\n ))}\n </>\n );\n}\n\n/** A kept step rendered as the item it was (its body sees the same identity it had live). */\nfunction stepAsItem(step: CanvasHistoryEntry, openedAt: number): CanvasItem {\n return {\n id: canvasItemId(step.kind, step.key),\n kind: step.kind,\n key: step.key,\n title: step.title,\n data: step.data,\n openedAt,\n updatedAt: openedAt,\n ...(step.instance ? { instance: step.instance } : {}),\n };\n}\n\n/** One body's host. Memoized on primitives: it re-renders for its OWN item, pane, visibility or focus — never another tab's. */\nconst BodyHost = memo(function BodyHost({\n hostId,\n itemId,\n kept,\n paneId,\n visible,\n focused,\n isFullscreen,\n paneCount,\n slots,\n placement,\n}: {\n hostId: string;\n itemId: CanvasItemId;\n kept: boolean;\n paneId: CanvasPaneId;\n visible: boolean;\n focused: boolean;\n isFullscreen: boolean;\n paneCount: number;\n slots: CanvasSlots;\n placement: Placement | null;\n}) {\n const canvas = useCanvas();\n const { windowId, ports } = useCanvasInternals();\n const live = useCanvasState((s) => (kept ? undefined : s.items[itemId]));\n // A kept step: the entry (a stable object until the tab's history changes) stands in as its item.\n const step = useCanvasState((s) => {\n const ownerItem = kept ? s.items[itemId] : undefined;\n return ownerItem ? keptCanvasSteps(ownerItem).find((e) => e.instance === hostId) : undefined;\n });\n const owner = useCanvasState((s) => (kept ? s.items[itemId]?.openedAt : undefined));\n const keptItem = useMemo(() => (step ? stepAsItem(step, owner ?? 0) : undefined), [step, owner]);\n const item = kept ? keptItem : live;\n const kind = useItemKind(item?.kind ?? \"\");\n const element = useRef<HTMLDivElement>(null);\n // Mounted from the first time it is on screen until its tab closes.\n const [everShown, setEverShown] = useState(visible);\n if (visible && !everShown) setEverShown(true);\n const mounted = kind?.unmountWhenHidden ? visible : everShown;\n const presentation = usePanePresentation(slots, paneId, isFullscreen, paneCount);\n const drop = usePaneDrop(paneId, () => slots.section(paneId));\n\n useIsoLayoutEffect(() => {\n const el = element.current;\n if (!placement || !el) return undefined;\n return placement.register(hostId, { element: el, paneId });\n }, [placement, hostId, paneId]);\n\n if (!item) return null;\n return (\n <div\n ref={element}\n className=\"mxc-item-host\"\n data-inline={placement ? undefined : \"\"}\n data-placed={placement ? \"false\" : undefined}\n data-visible={visible ? \"true\" : \"false\"}\n data-kind={item.kind}\n data-item={item.id}\n data-kept={kept ? \"\" : undefined}\n data-pane={paneId}\n inert={!visible}\n aria-hidden={visible ? undefined : true}\n onPointerDownCapture={() => {\n if (!focused) canvas.focusPane(paneId);\n }}\n {...drop}\n >\n {mounted ? (\n <CanvasPresentationContext.Provider value={presentation}>\n <div className=\"mxc-item\" data-kind={item.kind}>\n <ItemContent\n item={item}\n kind={kind}\n paneId={paneId}\n windowId={windowId}\n focused={focused}\n visible={visible}\n presentation={presentation}\n canvas={canvas}\n hasNativePort={!!ports.onNativeBodyFrame}\n />\n </div>\n </CanvasPresentationContext.Provider>\n ) : null}\n </div>\n );\n});\n\nfunction ItemContent({\n item,\n kind,\n paneId,\n windowId,\n focused,\n visible,\n presentation,\n canvas,\n hasNativePort,\n}: {\n item: CanvasItem;\n kind: AnyCanvasKind | undefined;\n paneId: CanvasPaneId;\n windowId: CanvasWindowId;\n focused: boolean;\n visible: boolean;\n presentation: CanvasPresentation;\n canvas: CanvasController;\n hasNativePort: boolean;\n}) {\n let unavailable: string | null = null;\n try {\n unavailable = kind?.unavailable?.(item.data, item) ?? null;\n } catch (error) {\n console.error(`[@ai-matrx/canvas] \"${item.kind}\" unavailable() threw`, error);\n }\n if (!kind) return <ItemProblem message=\"This item can no longer be shown.\" onClose={() => canvas.close(item.id)} />;\n if (unavailable) return <CanvasPanelEmpty>{unavailable}</CanvasPanelEmpty>;\n const rendered = kindComponent(kind) ? (\n <Rendered kind={kind} item={item} paneId={paneId} isFocused={focused} isVisible={visible} canvas={canvas} windowId={windowId} presentation={presentation} />\n ) : null;\n if (kind.body === \"native\") {\n return hasNativePort ? (\n <NativeBody itemId={item.id} windowId={windowId} visible={visible}>\n {rendered}\n </NativeBody>\n ) : (\n <CanvasPanelEmpty>Opens in the desktop app</CanvasPanelEmpty>\n );\n }\n return rendered;\n}\n\n/**\n * The kind's component. Memoized on what it is given: a body re-renders when\n * ITS item, pane, focus or presentation changes — never because another tab\n * opened or a split moved.\n */\nconst Rendered = memo(function Rendered({\n kind,\n item,\n paneId,\n isFocused,\n isVisible,\n canvas,\n windowId,\n presentation,\n}: {\n kind: AnyCanvasKind;\n item: CanvasItem;\n paneId: CanvasPaneId;\n isFocused: boolean;\n isVisible: boolean;\n canvas: CanvasController;\n windowId: CanvasWindowId;\n presentation: CanvasPresentation;\n}) {\n const props: CanvasKindProps = { item, data: item.data, paneId, isFocused, isVisible, canvas, windowId, presentation };\n return (\n <ItemBoundary item={item} onClose={() => canvas.close(item.id)} onRetry={() => resetKindComponent(kind)}>\n <Suspense fallback={<div className=\"mxc-loading\" aria-busy=\"true\" />}>\n <KindRender kind={kind} props={props} />\n </Suspense>\n </ItemBoundary>\n );\n});\n\nfunction KindRender({ kind, props }: { kind: AnyCanvasKind; props: CanvasKindProps }) {\n const Render = kindComponent(kind);\n if (!Render) throw new Error(`[@ai-matrx/canvas] kind \"${kind.id}\" has nothing to render.`);\n return <Render {...props} />;\n}\n\n/**\n * The placeholder a native view sits on. Its frame is reported on every\n * render, whenever the layer re-places bodies, on resize, and whenever the\n * host asks (`useCanvasNativeBodies().remeasure()`); null while hidden or gone.\n */\nfunction NativeBody({ itemId, windowId, visible, children }: { itemId: CanvasItemId; windowId: CanvasWindowId; visible: boolean; children: ReactNode }) {\n const { layer } = useCanvasInternals();\n const ref = useRef<HTMLDivElement>(null);\n const measure = useRef<() => void>(() => undefined);\n measure.current = () => {\n const el = ref.current;\n const box = visible && el?.isConnected ? el.getBoundingClientRect() : null;\n if (!box || box.width <= 0 || box.height <= 0) {\n layer.native.report(itemId, null, { visible: false, windowId });\n return;\n }\n const rect: CanvasNativeRect = { ...toCanvasRect(box), devicePixelRatio: window.devicePixelRatio || 1 };\n layer.native.report(itemId, rect, { visible: !layer.isBlocked(), windowId });\n };\n useIsoLayoutEffect(() => measure.current());\n useIsoLayoutEffect(() => {\n const el = ref.current;\n const run = () => measure.current();\n const observer = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(run);\n if (el) observer?.observe(el);\n const unregister = layer.native.register(run);\n window.addEventListener(\"resize\", run);\n return () => {\n observer?.disconnect();\n unregister();\n window.removeEventListener(\"resize\", run);\n layer.native.report(itemId, null, { visible: false, windowId });\n };\n }, [itemId, windowId, layer]);\n return (\n <div ref={ref} className=\"mxc-native-body\" data-native-body={itemId}>\n {children}\n </div>\n );\n}\n\nfunction ItemProblem({ message, onClose, onRetry }: { message: string; onClose: () => void; onRetry?: () => void }) {\n return (\n <div className=\"mxc-problem\" role=\"alert\">\n <AlertIcon />\n <p>{message}</p>\n <div className=\"mxc-problem-actions\">\n {onRetry ? (\n <button type=\"button\" className=\"mxc-text-button\" onClick={onRetry}>\n Try again\n </button>\n ) : null}\n <button type=\"button\" className=\"mxc-text-button\" onClick={onClose}>\n Close tab\n </button>\n </div>\n </div>\n );\n}\n\ninterface BoundaryProps {\n item: CanvasItem;\n onClose: () => void;\n onRetry: () => void;\n children: ReactNode;\n}\n\nclass ItemBoundary extends Component<BoundaryProps, { error: Error | null }> {\n override state: { error: Error | null } = { error: null };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n override componentDidCatch(error: Error, info: ErrorInfo) {\n console.error(`[@ai-matrx/canvas] \"${this.props.item.kind}\" failed to render`, error, info.componentStack);\n }\n\n override render() {\n if (this.state.error) {\n return (\n <ItemProblem\n message=\"This item failed to load.\"\n onClose={this.props.onClose}\n onRetry={() => {\n this.props.onRetry();\n this.setState({ error: null });\n }}\n />\n );\n }\n return this.props.children;\n }\n}\n","\"use client\";\n\n/**\n * THE canvas chrome — the one implementation of a panel frame, its header\n * buttons, a tab strip and a browser bar. Every canvas pane draws with these,\n * and a host that frames its own panels (a desktop canvas not yet on kinds)\n * uses the same components, so there is one look everywhere.\n *\n * Presentational and store-free: they render outside a CanvasProvider too\n * (tooltips then fall back to the native `title`). Structural CSS only —\n * colours come from --mxc-* tokens.\n */\n\nimport {\n forwardRef,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ButtonHTMLAttributes,\n type FocusEvent,\n type HTMLAttributes,\n type PointerEvent as ReactPointerEvent,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport { ArrowLeftIcon, ArrowRightIcon, CloseIcon, GlobeIcon, MaximizeIcon, MinimizeIcon, MoreIcon, PanelRightIcon, PlusIcon, RotateCwIcon } from \"./icons\";\nimport { toCanvasRect } from \"./layer\";\nimport { useOptionalCanvasInternals } from \"./provider\";\n\n// The browser runs layout effects; a server render has no layout to measure.\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\n/**\n * Marks a tab whose name is really cut (more than a pixel: system fonts\n * measure a fraction wider than their intrinsic size, which would put an\n * ellipsis on a name that fits). Only a cut name fades at its end.\n */\nexport function useTruncated(title: string) {\n const ref = useRef<HTMLSpanElement>(null);\n const [truncated, setTruncated] = useState(false);\n useIsoLayoutEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n const check = () => setTruncated(el.scrollWidth - el.clientWidth > 1);\n check();\n const observer = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(check);\n observer?.observe(el);\n return () => observer?.disconnect();\n }, [title]);\n return { ref, truncated };\n}\n\nconst cx = (...names: (string | false | null | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/** Tooltip handlers: through the canvas overlay (above native views) inside a provider, the native title outside. */\nfunction useTooltip(text: string | undefined) {\n const internals = useOptionalCanvasInternals();\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const hide = useRef<(() => void) | null>(null);\n const close = () => {\n if (timer.current) clearTimeout(timer.current);\n timer.current = null;\n hide.current?.();\n hide.current = null;\n };\n useEffect(() => close, []);\n if (!text) return { close, handlers: {} };\n if (!internals) return { close, handlers: { title: text } };\n const open = (element: HTMLElement, delay: number) => {\n close();\n timer.current = setTimeout(() => {\n timer.current = null;\n if (!element.isConnected) return;\n hide.current = internals.layer.show({ type: \"tooltip\", text, anchor: toCanvasRect(element.getBoundingClientRect()), side: \"bottom\" });\n }, delay);\n };\n return {\n close,\n handlers: {\n onPointerEnter: (event: ReactPointerEvent<HTMLElement>) => {\n if (event.pointerType === \"mouse\") open(event.currentTarget, 450);\n },\n onPointerLeave: close,\n onPointerDown: close,\n onFocus: (event: FocusEvent<HTMLElement>) => {\n if (event.currentTarget.matches(\":focus-visible\")) open(event.currentTarget, 0);\n },\n onBlur: close,\n },\n };\n}\n\nexport interface CanvasHeaderButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, \"children\" | \"title\"> {\n /** Accessible name and tooltip. */\n readonly label: string;\n /** Appended to the tooltip, e.g. \"⌘\\\\\". */\n readonly shortcut?: string | null | undefined;\n /** False draws the button dimmed and inert (a browser's Back with no history). Default true. */\n readonly available?: boolean;\n /** \"sm\" = a pane-header action (24px); \"md\" = a browser bar button (28px). */\n readonly size?: \"sm\" | \"md\";\n readonly pressed?: boolean;\n readonly children: ReactNode;\n}\n\n/** The one icon button of the canvas chrome. */\nexport const CanvasHeaderButton = forwardRef<HTMLButtonElement, CanvasHeaderButtonProps>(function CanvasHeaderButton(\n { label, shortcut, available = true, size = \"sm\", pressed, className, children, onClick, onPointerEnter, onPointerLeave, onPointerDown, onFocus, onBlur, ...rest },\n ref,\n) {\n const tooltip = useTooltip(shortcut ? `${label} (${shortcut})` : label);\n const own = tooltip.handlers as {\n title?: string;\n onPointerEnter?: (event: ReactPointerEvent<HTMLElement>) => void;\n onPointerLeave?: () => void;\n onPointerDown?: () => void;\n onFocus?: (event: FocusEvent<HTMLElement>) => void;\n onBlur?: () => void;\n };\n return (\n <button\n ref={ref}\n type=\"button\"\n aria-label={label}\n aria-pressed={pressed}\n data-slot=\"canvas-panel-action\"\n data-size={size}\n data-available={available ? undefined : \"false\"}\n className={cx(\"mxc-icon-button\", className)}\n {...rest}\n {...(own.title ? { title: own.title } : {})}\n aria-disabled={available ? rest[\"aria-disabled\"] : true}\n onClick={(event) => {\n tooltip.close();\n if (available) onClick?.(event);\n }}\n onPointerEnter={(event) => {\n onPointerEnter?.(event);\n own.onPointerEnter?.(event);\n }}\n onPointerLeave={(event) => {\n onPointerLeave?.(event);\n own.onPointerLeave?.();\n }}\n onPointerDown={(event) => {\n onPointerDown?.(event);\n own.onPointerDown?.();\n }}\n onFocus={(event) => {\n onFocus?.(event);\n own.onFocus?.(event);\n }}\n onBlur={(event) => {\n onBlur?.(event);\n own.onBlur?.();\n }}\n >\n {children}\n </button>\n );\n});\n\nexport interface CanvasPanelProps extends Omit<HTMLAttributes<HTMLElement>, \"title\"> {\n readonly panelId: string;\n /** The header title (a single-tab pane, a panel with no tabs). */\n readonly title: ReactNode;\n /** Controls after the title or tabs: \"+ new terminal\", a browser's bar. Grows to fill the header. */\n readonly leading?: ReactNode;\n /** A custom start of the header instead of the title (a tab strip). `leading` still follows it. */\n readonly header?: ReactNode;\n /** Controls just before the \"…\" menu (a kind's own button). */\n readonly actions?: ReactNode;\n /** The \"…\" menu: the host renders its own menu around the trigger it receives. */\n readonly renderMenu?: ((trigger: ReactElement) => ReactNode) | undefined;\n readonly expanded?: boolean | undefined;\n readonly onToggleExpand?: (() => void) | undefined;\n readonly expandShortcut?: string | null | undefined;\n /** Phones only: put the canvas away without closing anything. */\n readonly onHide?: (() => void) | undefined;\n readonly onClose?: (() => void) | undefined;\n readonly closeLabel?: string | undefined;\n readonly focused?: boolean | undefined;\n /** Where the header's own body element goes (the pane body). */\n readonly bodyProps?: HTMLAttributes<HTMLDivElement> | undefined;\n}\n\n/** The menu trigger every panel shares. */\nexport const CanvasMenuTrigger = forwardRef<HTMLButtonElement, Omit<CanvasHeaderButtonProps, \"label\" | \"children\"> & { label?: string }>(\n function CanvasMenuTrigger({ label = \"More\", ...props }, ref) {\n return (\n <CanvasHeaderButton ref={ref} label={label} {...props}>\n <MoreIcon />\n </CanvasHeaderButton>\n );\n },\n);\n\n/** The frame every canvas panel shares: header (title or tabs · leading · actions · … · expand · close) over a body. */\nexport const CanvasPanel = forwardRef<HTMLElement, CanvasPanelProps>(function CanvasPanel({\n panelId,\n title,\n leading,\n header,\n actions,\n renderMenu,\n expanded = false,\n onToggleExpand,\n expandShortcut,\n onHide,\n onClose,\n closeLabel = \"Close\",\n focused,\n bodyProps,\n className,\n children,\n ...props\n}, ref) {\n return (\n <section\n ref={ref}\n data-slot=\"canvas-panel\"\n data-panel={panelId}\n data-expanded={expanded ? \"\" : undefined}\n data-focused={focused ? \"\" : undefined}\n aria-label={typeof title === \"string\" ? title : undefined}\n className={cx(\"mxc-panel\", className)}\n {...props}\n >\n <header data-slot=\"canvas-panel-header\" className=\"mxc-pane-header\">\n {header ?? <span className=\"mxc-panel-title\">{title}</span>}\n <div className=\"mxc-pane-leading\">{leading}</div>\n <div className=\"mxc-pane-actions\">\n {actions}\n {renderMenu ? renderMenu(<CanvasMenuTrigger />) : null}\n {onToggleExpand ? (\n <CanvasHeaderButton className=\"mxc-desktop-only\" label={expanded ? \"Restore\" : \"Expand\"} shortcut={expandShortcut} onClick={onToggleExpand}>\n {expanded ? <MinimizeIcon /> : <MaximizeIcon />}\n </CanvasHeaderButton>\n ) : null}\n {onHide ? (\n <CanvasHeaderButton className=\"mxc-phone-only\" label=\"Hide canvas\" onClick={onHide}>\n <PanelRightIcon />\n </CanvasHeaderButton>\n ) : null}\n {onClose ? (\n <CanvasHeaderButton label={closeLabel} onClick={onClose}>\n <CloseIcon />\n </CanvasHeaderButton>\n ) : null}\n </div>\n </header>\n <div data-slot=\"canvas-panel-body\" {...bodyProps} className={cx(\"mxc-pane-body\", bodyProps?.className)}>\n {children}\n </div>\n </section>\n );\n});\n\n/** The one-line honest state of a panel with nothing to show, or whose backend has not shipped. */\nexport function CanvasPanelEmpty({ children, className }: { children: ReactNode; className?: string }) {\n return (\n <div data-slot=\"canvas-panel-empty\" className={cx(\"mxc-empty-line\", className)}>\n {children}\n </div>\n );\n}\n\nexport interface CanvasTabProps extends Omit<HTMLAttributes<HTMLDivElement>, \"title\" | \"onSelect\"> {\n readonly title: string;\n readonly icon: ReactNode;\n /** Small trailing state after the title, e.g. \"exited\". */\n readonly note?: string | undefined;\n readonly active: boolean;\n readonly onSelect: () => void;\n /** Absent ⇒ no close button. */\n readonly onClose?: (() => void) | undefined;\n}\n\n/** One tab of a strip. */\nexport const CanvasTab = forwardRef<HTMLDivElement, CanvasTabProps>(function CanvasTab(\n { title, icon, note, active, onSelect, onClose, className, onKeyDown, onClick, ...rest },\n ref,\n) {\n const shown = title || \"New tab\";\n const name = useTruncated(shown);\n return (\n <div\n ref={ref}\n role=\"tab\"\n aria-selected={active}\n tabIndex={active ? 0 : -1}\n data-slot=\"browser-tab\"\n data-active={active ? \"\" : undefined}\n data-truncated={name.truncated ? \"\" : undefined}\n title={shown}\n className={cx(\"mxc-tab\", className)}\n {...rest}\n onClick={(event) => {\n onClick?.(event);\n onSelect();\n }}\n onKeyDown={(event) => {\n onKeyDown?.(event);\n if (event.defaultPrevented) return;\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n onSelect();\n }\n }}\n >\n <span className=\"mxc-tab-icon\">{icon}</span>\n <span ref={name.ref} className=\"mxc-tab-title\">\n {shown}\n </span>\n {note ? <span className=\"mxc-tab-note\" data-slot=\"browser-tab-note\">{note}</span> : null}\n {onClose ? (\n <button\n type=\"button\"\n className=\"mxc-tab-close\"\n data-slot=\"browser-tab-close\"\n aria-label={`Close ${shown}`}\n onClick={(event) => {\n event.stopPropagation();\n onClose();\n }}\n >\n <CloseIcon />\n </button>\n ) : null}\n </div>\n );\n});\n\nexport interface BrowserTab {\n readonly id: string;\n readonly title: string;\n /** A favicon URL; a globe is drawn without one. */\n readonly icon?: string | null | undefined;\n /** A glyph instead of a favicon (a terminal tab draws its prompt icon). */\n readonly glyph?: ReactNode;\n /** Small trailing state after the title, e.g. \"exited\". */\n readonly note?: string | undefined;\n}\n\nexport interface BrowserTabsProps {\n readonly tabs: readonly BrowserTab[];\n readonly activeId: string | null;\n readonly onSelect: (id: string) => void;\n readonly onClose: (id: string) => void;\n /** Absent ⇒ no \"+\" button. */\n readonly onNew?: (() => void) | undefined;\n /** The \"+\" button's name (default \"New tab\"). */\n readonly newLabel?: string;\n /** The tab list's name (default \"Tabs\"). */\n readonly label?: string;\n readonly className?: string;\n}\n\n/** A tab strip for any panel with its own tabs: a browser's pages, a terminal's shells. */\nexport function BrowserTabs({ tabs, activeId, onSelect, onClose, onNew, newLabel = \"New tab\", label = \"Tabs\", className }: BrowserTabsProps) {\n return (\n <div data-slot=\"browser-tabs\" role=\"tablist\" aria-label={label} className={cx(\"mxc-tabs\", className)}>\n {tabs.map((tab) => (\n <CanvasTab\n key={tab.id}\n data-tab={tab.id}\n title={tab.title}\n note={tab.note}\n active={tab.id === activeId}\n icon={tab.glyph ?? (tab.icon ? <img src={tab.icon} alt=\"\" className=\"mxc-favicon\" /> : <GlobeIcon />)}\n onSelect={() => onSelect(tab.id)}\n onClose={() => onClose(tab.id)}\n />\n ))}\n {onNew ? (\n <CanvasHeaderButton label={newLabel} data-slot=\"browser-tab-new\" onClick={onNew}>\n <PlusIcon />\n </CanvasHeaderButton>\n ) : null}\n </div>\n );\n}\n\nexport interface BrowserBarProps {\n readonly url: string;\n readonly canGoBack: boolean;\n readonly canGoForward: boolean;\n readonly onBack: () => void;\n readonly onForward: () => void;\n readonly onReload: () => void;\n /** Called with the typed address when the person presses Enter. */\n readonly onNavigate: (address: string) => void;\n /** Controls after the address (screenshot, open in your browser, more). */\n readonly trailing?: ReactNode;\n readonly className?: string;\n}\n\n/** A browser's back · forward · reload · address bar, for a kind's leading slot or its body. */\nexport function BrowserBar({ url, canGoBack, canGoForward, onBack, onForward, onReload, onNavigate, trailing, className }: BrowserBarProps) {\n const [draft, setDraft] = useState(url);\n const [editing, setEditing] = useState(false);\n useEffect(() => {\n if (!editing) setDraft(url);\n }, [url, editing]);\n\n return (\n <div data-slot=\"browser-bar\" className={cx(\"mxc-browser-bar\", className)}>\n <CanvasHeaderButton size=\"md\" label=\"Back\" available={canGoBack} onClick={onBack}>\n <ArrowLeftIcon />\n </CanvasHeaderButton>\n <CanvasHeaderButton size=\"md\" label=\"Forward\" available={canGoForward} onClick={onForward}>\n <ArrowRightIcon />\n </CanvasHeaderButton>\n <CanvasHeaderButton size=\"md\" label=\"Reload\" onClick={onReload}>\n <RotateCwIcon />\n </CanvasHeaderButton>\n <form\n className=\"mxc-address-form\"\n onSubmit={(event) => {\n event.preventDefault();\n setEditing(false);\n onNavigate(draft.trim());\n (event.currentTarget.elements.namedItem(\"address\") as HTMLInputElement | null)?.blur();\n }}\n >\n <input\n name=\"address\"\n aria-label=\"Address\"\n data-slot=\"browser-address\"\n className=\"mxc-address\"\n value={draft}\n placeholder=\"Search or enter an address\"\n spellCheck={false}\n onFocus={(event) => {\n setEditing(true);\n event.currentTarget.select();\n }}\n onBlur={() => setEditing(false)}\n onChange={(event) => setDraft(event.target.value)}\n />\n </form>\n {trailing ? <div data-slot=\"browser-bar-trailing\" className=\"mxc-browser-bar-trailing\">{trailing}</div> : null}\n </div>\n );\n}\n","/**\n * Inlined glyphs (C19): the package carries its own icons and depends on no\n * icon library. Paths follow the Lucide 24×24 grid so they sit beside Lucide\n * icons in a host without looking foreign.\n */\n\nimport type { SVGProps } from \"react\";\n\ntype IconProps = SVGProps<SVGSVGElement> & { className?: string };\n\nfunction Glyph({ children, ...props }: IconProps) {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n {...props}\n >\n {children}\n </svg>\n );\n}\n\nexport const CloseIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M18 6 6 18\" />\n <path d=\"m6 6 12 12\" />\n </Glyph>\n);\n\nexport const MaximizeIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M15 3h6v6\" />\n <path d=\"m21 3-7 7\" />\n <path d=\"m3 21 7-7\" />\n <path d=\"M9 21H3v-6\" />\n </Glyph>\n);\n\nexport const MinimizeIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m14 10 7-7\" />\n <path d=\"M20 10h-6V4\" />\n <path d=\"m3 21 7-7\" />\n <path d=\"M4 14h6v6\" />\n </Glyph>\n);\n\nexport const MoreIcon = (p: IconProps) => (\n <Glyph {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"1\" />\n <circle cx=\"12\" cy=\"5\" r=\"1\" />\n <circle cx=\"12\" cy=\"19\" r=\"1\" />\n </Glyph>\n);\n\nexport const SplitRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M12 3v18\" />\n </Glyph>\n);\n\nexport const SplitDownIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M3 12h18\" />\n </Glyph>\n);\n\nexport const PanelRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M15 3v18\" />\n </Glyph>\n);\n\nexport const PopOutIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M15 3h6v6\" />\n <path d=\"M10 14 21 3\" />\n <path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\" />\n </Glyph>\n);\n\nexport const AlertIcon = (p: IconProps) => (\n <Glyph {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 8v4\" />\n <path d=\"M12 16h.01\" />\n </Glyph>\n);\n\nexport const ArrowLeftIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m12 19-7-7 7-7\" />\n <path d=\"M19 12H5\" />\n </Glyph>\n);\n\nexport const ArrowRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M5 12h14\" />\n <path d=\"m12 5 7 7-7 7\" />\n </Glyph>\n);\n\nexport const RotateCwIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8\" />\n <path d=\"M21 3v5h-5\" />\n </Glyph>\n);\n\nexport const GlobeIcon = (p: IconProps) => (\n <Glyph {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\" />\n <path d=\"M2 12h20\" />\n </Glyph>\n);\n\nexport const PlusIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M5 12h14\" />\n <path d=\"M12 5v14\" />\n </Glyph>\n);\n\n/** Dock back: a tab returns from its own window into the canvas. */\nexport const DockIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6\" />\n <path d=\"M21 3 12 12\" />\n <path d=\"M12 6v6h6\" />\n </Glyph>\n);\n\n/** The \"New tab\" launcher (Lucide layout-grid). */\nexport const LayoutGridIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"7\" height=\"7\" x=\"3\" y=\"3\" rx=\"1\" />\n <rect width=\"7\" height=\"7\" x=\"14\" y=\"3\" rx=\"1\" />\n <rect width=\"7\" height=\"7\" x=\"14\" y=\"14\" rx=\"1\" />\n <rect width=\"7\" height=\"7\" x=\"3\" y=\"14\" rx=\"1\" />\n </Glyph>\n);\n\nexport const ChevronLeftIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m15 18-6-6 6-6\" />\n </Glyph>\n);\n\nexport const ChevronRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m9 18 6-6-6-6\" />\n </Glyph>\n);\n\nexport const ChevronDownIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m6 9 6 6 6-6\" />\n </Glyph>\n);\n","\"use client\";\n\n/**\n * Tab drag and drop. A tab (or a single tab's title) drags; a pane — its\n * chrome AND the body placed over its slot — takes the drop.\n */\n\nimport { useEffect, useRef, type DragEvent } from \"react\";\nimport type { CanvasItemId, CanvasPaneId } from \"../index\";\nimport { toCanvasRect } from \"./layer\";\nimport { useCanvas, useCanvasInternals } from \"./provider\";\n\nexport const CANVAS_DRAG_MIME = \"application/x-matrx-canvas-item\";\n\n/** Drag handlers shared by a tab and a single tab's title: the dragged tab is announced so native views can step aside. */\nexport function useTabDrag(itemId: CanvasItemId, title: string) {\n const { layer } = useCanvasInternals();\n const active = useRef<(() => void)[]>([]);\n const end = () => {\n for (const dispose of active.current.splice(0)) dispose();\n };\n useEffect(() => end, []);\n return {\n draggable: true,\n onDragStart: (event: DragEvent) => {\n event.dataTransfer.setData(CANVAS_DRAG_MIME, itemId);\n event.dataTransfer.effectAllowed = \"move\";\n end();\n active.current.push(layer.beginBlocking(), layer.show({ type: \"tab-drag\", itemId, title }));\n },\n onDragEnd: end,\n };\n}\n\n/**\n * Drop handlers for one pane. `getOutline` is the element whose rect the drop\n * indicator draws (the pane's panel). Used by the pane's chrome and by every\n * body placed over the pane, so a tab dropped anywhere on the pane lands there.\n */\nexport function usePaneDrop(paneId: CanvasPaneId, getOutline: () => HTMLElement | null) {\n const canvas = useCanvas();\n const { layer } = useCanvasInternals();\n const drop = useRef<(() => void) | null>(null);\n useEffect(() => () => drop.current?.(), []);\n const hide = () => {\n drop.current?.();\n drop.current = null;\n };\n return {\n onDragOver: (event: DragEvent<HTMLElement>) => {\n if (!event.dataTransfer.types.includes(CANVAS_DRAG_MIME)) return;\n event.preventDefault();\n event.dataTransfer.dropEffect = \"move\";\n const outline = getOutline();\n if (!drop.current && outline) {\n drop.current = layer.show({ type: \"drop-indicator\", rect: toCanvasRect(outline.getBoundingClientRect()), paneId });\n }\n },\n onDragLeave: (event: DragEvent<HTMLElement>) => {\n const next = event.relatedTarget as Node | null;\n if (next && event.currentTarget.contains(next)) return;\n hide();\n },\n onDrop: (event: DragEvent<HTMLElement>) => {\n hide();\n const itemId = event.dataTransfer.getData(CANVAS_DRAG_MIME) as CanvasItemId;\n if (!itemId) return;\n event.preventDefault();\n canvas.moveItem(itemId, paneId);\n },\n };\n}\n","\"use client\";\n\n/**\n * The launcher — what a \"New tab\" shows: what this page offers (contextual\n * entries, `useCanvasLauncherEntry`) first, then every kind that offers a\n * launcher. Choosing NAVIGATES the tab in place, so its header offers Back to\n * the launcher: nothing reached from inside the canvas is ever a dead end.\n *\n * The launcher tab is a built-in item (`CANVAS_LAUNCHER_KIND`) that is never\n * registered — `useItemKind` resolves it here.\n */\n\nimport type { ComponentType } from \"react\";\nimport { CANVAS_LAUNCHER_KIND, canvasItemId, type CanvasJson, type CanvasNavigateInput, type CanvasPaneId } from \"../index\";\nimport { CanvasPanelEmpty } from \"./chrome\";\nimport { LayoutGridIcon } from \"./icons\";\nimport { useCanvas, useCanvasKind, useCanvasKinds, useCanvasLauncherEntries } from \"./provider\";\nimport type { AnyCanvasKind, CanvasKindProps } from \"./registry\";\n\ninterface Choice {\n readonly id: string;\n readonly label: string;\n readonly icon: ComponentType<{ className?: string }>;\n readonly input: CanvasNavigateInput;\n}\n\nfunction useChoices(): { readonly contextual: readonly Choice[]; readonly global: readonly Choice[] } {\n const entries = useCanvasLauncherEntries();\n const kinds = useCanvasKinds();\n const byId = new Map(kinds.map((kind) => [kind.id, kind] as const));\n const contextual: Choice[] = [];\n for (const entry of entries) {\n const kind = byId.get(entry.kind);\n // An entry for a kind this app does not have would open a broken tab: it is not offered.\n if (!kind) continue;\n contextual.push({\n id: `ctx:${canvasItemId(entry.kind, entry.key)}`,\n label: entry.title ?? kind.label,\n icon: entry.icon ?? kind.icon,\n input: { kind: entry.kind, key: entry.key, title: entry.title ?? null, ...(entry.data !== undefined ? { data: entry.data } : {}) },\n });\n }\n const global: Choice[] = [];\n for (const kind of kinds) {\n const launcher = kind.launcher;\n if (!launcher) continue;\n global.push({\n id: `kind:${kind.id}`,\n label: launcher.title ?? kind.label,\n icon: kind.icon,\n input: { kind: kind.id, key: launcher.key, data: launcher.data as CanvasJson, title: launcher.title ?? null },\n });\n }\n return { contextual, global };\n}\n\n/**\n * A double-click on a launcher item: the first click opens the item, and the\n * new body appears right under the pointer. The rest of that SAME multi-click\n * (detail ≥ 2: the second press, its click, the dblclick) must not land in the\n * new body — it would select a word or press a button there. Swallowed in the\n * capture phase for a short window; a fresh click (detail 1) passes.\n */\nconst FOLLOW_UP_MS = 600;\nfunction swallowFollowUpClicks() {\n if (typeof window === \"undefined\") return;\n const types = [\"pointerdown\", \"mousedown\", \"pointerup\", \"mouseup\", \"click\", \"dblclick\"] as const;\n const swallow = (event: Event) => {\n if ((event as MouseEvent).detail >= 2 || event.type === \"dblclick\") {\n event.preventDefault();\n event.stopPropagation();\n }\n };\n for (const type of types) window.addEventListener(type, swallow, true);\n setTimeout(() => {\n for (const type of types) window.removeEventListener(type, swallow, true);\n }, FOLLOW_UP_MS);\n}\n\nfunction LauncherGrid({ onChoose }: { onChoose: (input: CanvasNavigateInput) => void }) {\n const { contextual, global } = useChoices();\n if (contextual.length === 0 && global.length === 0) return <CanvasPanelEmpty>Nothing to open</CanvasPanelEmpty>;\n const section = (label: string | null, choices: readonly Choice[]) =>\n choices.length === 0 ? null : (\n <section className=\"mxc-launcher-section\" aria-label={label ?? \"Open\"}>\n {label ? <h3 className=\"mxc-launcher-heading\">{label}</h3> : null}\n <div className=\"mxc-launcher-grid\">\n {choices.map((choice) => {\n const Icon = choice.icon;\n return (\n <button\n key={choice.id}\n type=\"button\"\n className=\"mxc-launcher-item\"\n onClick={(event) => {\n // The second click of a double-click: the item is already chosen.\n if (event.detail >= 2) return;\n swallowFollowUpClicks();\n onChoose(choice.input);\n }}\n >\n <Icon className=\"mxc-launcher-icon\" />\n <span>{choice.label}</span>\n </button>\n );\n })}\n </div>\n </section>\n );\n return (\n <div className=\"mxc-launcher\">\n {section(contextual.length > 0 ? \"On this page\" : null, contextual)}\n {section(contextual.length > 0 ? \"Open\" : null, global)}\n </div>\n );\n}\n\n/** The body of a \"New tab\": choosing navigates THIS tab, so Back returns here. */\nfunction LauncherBody({ item, canvas }: CanvasKindProps) {\n return <LauncherGrid onChoose={(input) => void canvas.navigate(item.id, input)} />;\n}\n\n/** A pane with no tabs: choosing opens a \"New tab\" there and navigates it, so Back returns to the launcher. */\nexport function EmptyPaneLauncher({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n return (\n <LauncherGrid\n onChoose={(input) => {\n const tab = canvas.newTab(paneId);\n canvas.navigate(tab, input);\n }}\n />\n );\n}\n\nexport const CANVAS_LAUNCHER_KIND_DEFINITION: AnyCanvasKind = {\n id: CANVAS_LAUNCHER_KIND,\n label: \"New tab\",\n icon: LayoutGridIcon,\n component: LauncherBody,\n};\n\n/** A kind by id, the built-in launcher included. */\nexport function useItemKind(kindId: string): AnyCanvasKind | undefined {\n const registered = useCanvasKind(kindId);\n return kindId === CANVAS_LAUNCHER_KIND ? CANVAS_LAUNCHER_KIND_DEFINITION : registered;\n}\n\n/** Non-hook form of useItemKind. */\nexport function resolveItemKind(kindId: string, lookup: (id: string) => AnyCanvasKind | undefined): AnyCanvasKind | undefined {\n return kindId === CANVAS_LAUNCHER_KIND ? CANVAS_LAUNCHER_KIND_DEFINITION : lookup(kindId);\n}\n","\"use client\";\n\n/**\n * The presentation context: every canvas body is rendered inside it, so any\n * component nested in a body — a renderer three levels down, a chart inside a\n * document — can ask where it is and what shape it has.\n */\n\nimport { createContext, useContext } from \"react\";\nimport type { CanvasPresentation } from \"../index\";\n\nexport const CanvasPresentationContext = createContext<CanvasPresentation | null>(null);\n\n/**\n * The live presentation of the canvas body this component renders in: size,\n * orientation, narrow, expanded, pane count. `null` outside the canvas — so a\n * component used both on a page and in a canvas adapts only in the canvas.\n *\n * const p = useCanvasPresentation();\n * const direction = preferredFlowDirection(p); // \"vertical\" in a tall narrow pane\n */\nexport function useCanvasPresentation(): CanvasPresentation | null {\n return useContext(CanvasPresentationContext);\n}\n","\"use client\";\n\n/**\n * Body slots — where each pane's body area IS on screen.\n *\n * A pane draws its chrome (header, tabs, toolbar row) and an empty body SLOT.\n * Item bodies are not rendered inside the pane: they live once, in the\n * column's stable body layer, and are placed over their pane's slot. A tab\n * switch, a split, a move between panes, a resize or expand only re-places a\n * body — it never unmounts or re-parents it, so its state, focus and scroll\n * survive. A DOM body and a native body are the same thing: a body on a slot.\n *\n * The registry measures every slot (ResizeObserver where there is one) and\n * tells subscribers when anything moved, so the layer re-places in the frame\n * the layout changed.\n */\n\nimport { createContext, useContext, useSyncExternalStore } from \"react\";\nimport type { CanvasPaneId } from \"../index\";\n\nexport interface CanvasSlotSize {\n readonly width: number;\n readonly height: number;\n}\n\nconst ZERO: CanvasSlotSize = Object.freeze({ width: 0, height: 0 });\n\nexport interface CanvasSlots {\n /** A pane's body slot mounted. */\n set(paneId: CanvasPaneId, element: HTMLElement): void;\n /** A pane's body slot went away (only when `element` is still the registered one). */\n unset(paneId: CanvasPaneId, element: HTMLElement | null): void;\n /** A pane's whole panel (the drop target's outline). */\n setSection(paneId: CanvasPaneId, element: HTMLElement | null): void;\n slot(paneId: CanvasPaneId): HTMLElement | null;\n section(paneId: CanvasPaneId): HTMLElement | null;\n /** The slot's measured size; the same object until it changes. */\n size(paneId: CanvasPaneId): CanvasSlotSize;\n /** Re-reads every slot's size now (no ResizeObserver, or a host-driven change). */\n measure(): void;\n /** Called after any slot mounts, unmounts or resizes. */\n subscribe(listener: () => void): () => void;\n}\n\nexport function createCanvasSlots(): CanvasSlots {\n const slots = new Map<CanvasPaneId, HTMLElement>();\n const sections = new Map<CanvasPaneId, HTMLElement>();\n const sizes = new Map<CanvasPaneId, CanvasSlotSize>();\n const listeners = new Set<() => void>();\n let observer: ResizeObserver | null = null;\n\n const emit = () => {\n for (const listener of [...listeners]) listener();\n };\n const read = (paneId: CanvasPaneId, element: HTMLElement): boolean => {\n const box = element.getBoundingClientRect();\n const width = Math.round(box.width);\n const height = Math.round(box.height);\n const previous = sizes.get(paneId);\n if (previous && previous.width === width && previous.height === height) return false;\n sizes.set(paneId, { width, height });\n return true;\n };\n const measureAll = (): boolean => {\n let changed = false;\n for (const [paneId, element] of slots) changed = read(paneId, element) || changed;\n return changed;\n };\n const watch = (): ResizeObserver | null => {\n if (observer || typeof ResizeObserver === \"undefined\") return observer;\n observer = new ResizeObserver(() => {\n measureAll();\n // Always: a slot can move without resizing when a sibling resizes.\n emit();\n });\n return observer;\n };\n\n return {\n set(paneId, element) {\n if (slots.get(paneId) === element) return;\n const previous = slots.get(paneId);\n if (previous) observer?.unobserve(previous);\n slots.set(paneId, element);\n watch()?.observe(element);\n read(paneId, element);\n emit();\n },\n unset(paneId, element) {\n const current = slots.get(paneId);\n if (!current || (element && current !== element)) return;\n observer?.unobserve(current);\n slots.delete(paneId);\n sizes.delete(paneId);\n emit();\n },\n setSection(paneId, element) {\n if (element) sections.set(paneId, element);\n else sections.delete(paneId);\n },\n slot: (paneId) => slots.get(paneId) ?? null,\n section: (paneId) => sections.get(paneId) ?? null,\n size: (paneId) => sizes.get(paneId) ?? ZERO,\n measure() {\n if (measureAll()) emit();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\nexport const CanvasSlotsContext = createContext<CanvasSlots | null>(null);\n\n/** The column's slot registry, or null for a pane rendered on its own. */\nexport function useCanvasSlots(): CanvasSlots | null {\n return useContext(CanvasSlotsContext);\n}\n\n/**\n * True while the column presents ONE pane at a time (a phone): the focused\n * pane shows every pane's tabs in its strip, and only its body is on screen.\n * The layout tree is untouched, so a wider screen gets its split back.\n */\nexport const CanvasSinglePaneContext = createContext(false);\n\nexport function useCanvasSinglePane(): boolean {\n return useContext(CanvasSinglePaneContext);\n}\n\n/** A pane slot's live size. */\nexport function useSlotSize(slots: CanvasSlots, paneId: CanvasPaneId): CanvasSlotSize {\n return useSyncExternalStore(\n slots.subscribe,\n () => slots.size(paneId),\n () => ZERO,\n );\n}\n","/**\n * One resize gesture (the canvas edge, a split handle). While it runs:\n * `:root[data-mxc-resizing]` (cursor, no motion, `user-select: none` in\n * styles.css), any selection already on the page is cleared, and the\n * document refuses to START a selection — so dragging an edge across the\n * page never selects its text, whatever CSS the host loaded.\n */\nexport function beginCanvasResize(mode: \"\" | \"col\" | \"row\"): () => void {\n if (typeof document === \"undefined\") return () => undefined;\n const root = document.documentElement;\n root.dataset.mxcResizing = mode;\n document.getSelection?.()?.removeAllRanges();\n const refuse = (event: Event) => event.preventDefault();\n document.addEventListener(\"selectstart\", refuse, true);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n delete root.dataset.mxcResizing;\n document.removeEventListener(\"selectstart\", refuse, true);\n };\n}\n","\"use client\";\n\n/**\n * One pane, drawn with THE canvas chrome (CanvasPanel): a header — Back (when\n * the tab navigated in place), the title (one tab) or the tab strip, \"+\" New\n * tab, the kind's leading controls, the kind's own button, \"…\", expand, close\n * — over an empty body SLOT. The bodies themselves live in the column's stable\n * body layer and are placed over this slot (see bodies.tsx), so nothing in a\n * body remounts when this pane re-renders, splits or receives a tab. An empty\n * pane shows the launcher. Tabs drag between panes (and windows).\n */\n\nimport { Component, useEffect, useLayoutEffect, useRef, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from \"react\";\nimport * as Menu from \"@radix-ui/react-dropdown-menu\";\nimport type { CanvasItem, CanvasItemId, CanvasPaneId, CanvasState, CanvasWindowId } from \"../index\";\nimport {\n CANVAS_LAUNCHER_KIND,\n CANVAS_MAIN_WINDOW,\n canvasShortcutHint,\n canvasWindowFrame,\n listPaneIds,\n selectCanvasCanGoBack,\n selectCanvasCanGoForward,\n selectCanvasFocusedPaneId,\n selectCanvasIsFullscreen,\n selectCanvasIsOpen,\n selectCanvasPaneCount,\n} from \"../index\";\nimport { CanvasPaneInlineBodies, usePanePresentation } from \"./bodies\";\nimport { CanvasHeaderButton, CanvasMenuTrigger, CanvasPanel, CanvasTab, useTruncated } from \"./chrome\";\nimport { CANVAS_DRAG_MIME, usePaneDrop, useTabDrag } from \"./dnd\";\nimport {\n AlertIcon,\n ArrowLeftIcon,\n ArrowRightIcon,\n ChevronDownIcon,\n CloseIcon,\n DockIcon,\n PlusIcon,\n PopOutIcon,\n SplitDownIcon,\n SplitRightIcon,\n} from \"./icons\";\nimport { toCanvasRect, type CanvasMenuEntry } from \"./layer\";\nimport { EmptyPaneLauncher, resolveItemKind, useItemKind } from \"./launcher\";\nimport { useCanvas, useCanvasInternals, useCanvasState } from \"./provider\";\nimport { getCanvasKind, type AnyCanvasKind, type CanvasKindProps, type CanvasMenuItem } from \"./registry\";\nimport { createCanvasSlots, useCanvasSinglePane, useCanvasSlots } from \"./slots\";\n\n// The browser runs layout effects; a server render has no layout to report.\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nexport function itemTitle(item: CanvasItem, kind: AnyCanvasKind | undefined): string {\n if (item.title) return item.title;\n if (item.kind === CANVAS_LAUNCHER_KIND) return \"New tab\";\n if (kind?.title) {\n try {\n const title = kind.title(item.data, item);\n if (title) return title;\n } catch {\n // fall through to the label — a title function must never break the tab strip\n }\n }\n return kind?.label ?? item.kind;\n}\n\nconst isMac = () => typeof navigator !== \"undefined\" && /mac|iphone|ipad/i.test(navigator.platform ?? \"\");\n\n/** One tab of a strip and the pane it lives in (a phone's strip shows every pane's tabs). */\ninterface StripTab {\n readonly itemId: CanvasItemId;\n readonly paneId: CanvasPaneId;\n /** Its index inside its own pane (where a tab dropped on it lands). */\n readonly index: number;\n}\n\n/** Every tab of this window in layout order, as one string (stable while nothing structural changes). */\nfunction windowTabsSignature(state: CanvasState, windowId: CanvasWindowId): string {\n const frame = canvasWindowFrame(state, windowId);\n if (!frame) return \"\";\n const rows: string[] = [];\n for (const paneId of listPaneIds(frame.layout)) {\n for (const itemId of state.panes[paneId]?.itemIds ?? []) rows.push(`${itemId}\\u0001${paneId}`);\n }\n return rows.join(\"\\u0002\");\n}\n\nfunction parseWindowTabs(signature: string): StripTab[] {\n if (!signature) return [];\n const perPane = new Map<string, number>();\n return signature.split(\"\\u0002\").map((row) => {\n const [itemId = \"\", paneId = \"\"] = row.split(\"\\u0001\");\n const index = perPane.get(paneId) ?? 0;\n perPane.set(paneId, index + 1);\n return { itemId: itemId as CanvasItemId, paneId: paneId as CanvasPaneId, index };\n });\n}\n\nexport function CanvasPaneView({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n const { windowId, tabStrip } = useCanvasInternals();\n // A pane outside a CanvasColumn renders its own bodies in flow.\n const columnSlots = useCanvasSlots();\n const [ownSlots] = useState(createCanvasSlots);\n const slots = columnSlots ?? ownSlots;\n const pane = useCanvasState((s) => s.panes[paneId]);\n // Only this pane's active item: another tab's data never re-renders this pane.\n const active = useCanvasState((s) => {\n const activeId = s.panes[paneId]?.activeItemId;\n return activeId ? s.items[activeId] : undefined;\n });\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const focused = useCanvasState((s) => selectCanvasFocusedPaneId(s, windowId) === paneId);\n const paneCount = useCanvasState((s) => selectCanvasPaneCount(s, windowId));\n const role = useCanvasState((s) => (windowId === CANVAS_MAIN_WINDOW ? \"main\" : (s.windows[windowId]?.role ?? \"window\")));\n const canGoBack = useCanvasState((s) => (active ? selectCanvasCanGoBack(s, active.id) : false));\n const canGoForward = useCanvasState((s) => (active ? selectCanvasCanGoForward(s, active.id) : false));\n const kind = useItemKind(active?.kind ?? \"\");\n // A phone presents one pane: its strip carries every pane's tabs, so nothing is out of reach.\n const singlePane = useCanvasSinglePane();\n const windowTabs = useCanvasState((s) => (singlePane ? windowTabsSignature(s, windowId) : \"\"));\n const sectionRef = useRef<HTMLElement>(null);\n const bodyRef = useRef<HTMLDivElement>(null);\n const presentation = usePanePresentation(slots, paneId, isFullscreen, paneCount);\n const drop = usePaneDrop(paneId, () => sectionRef.current);\n\n useIsoLayoutEffect(() => {\n const body = bodyRef.current;\n const section = sectionRef.current;\n if (body) slots.set(paneId, body);\n slots.setSection(paneId, section);\n return () => {\n slots.unset(paneId, body);\n if (slots.section(paneId) === section) slots.setSection(paneId, null);\n };\n }, [slots, paneId]);\n\n if (!pane) return null;\n\n const kindProps: CanvasKindProps | null =\n active && kind ? { item: active, data: active.data, paneId, isFocused: focused, isVisible: isOpen, canvas, windowId, presentation } : null;\n const Leading = kind?.HeaderLeading;\n const Action = kind?.HeaderAction;\n const Toolbar = kind?.Toolbar;\n const tabs: StripTab[] = singlePane ? parseWindowTabs(windowTabs) : pane.itemIds.map((itemId, index) => ({ itemId, paneId, index }));\n const single = tabStrip === \"auto\" && tabs.length === 1 && active;\n\n const closeLabel = role === \"pop-out\" && paneCount === 1 ? \"Close window\" : paneCount > 1 ? \"Close pane\" : \"Close canvas\";\n\n return (\n <CanvasPanel\n ref={sectionRef}\n panelId={paneId}\n className=\"mxc-pane\"\n title={active ? itemTitle(active, kind) : \"Canvas\"}\n focused={focused}\n data-mxc-pane={paneId}\n header={\n <>\n {canGoBack && active ? (\n <CanvasHeaderButton className=\"mxc-back\" label=\"Back\" shortcut={canvasShortcutHint(\"canvas.back\", isMac())} onClick={() => void canvas.back(active.id)}>\n <ArrowLeftIcon />\n </CanvasHeaderButton>\n ) : null}\n {canGoForward && active ? (\n <CanvasHeaderButton\n className=\"mxc-forward\"\n label=\"Forward\"\n shortcut={canvasShortcutHint(\"canvas.forward\", isMac())}\n onClick={() => void canvas.forward(active.id)}\n >\n <ArrowRightIcon />\n </CanvasHeaderButton>\n ) : null}\n {single && active ? (\n <SingleTitle item={active} kind={kind} />\n ) : tabs.length > 0 ? (\n <TabStrip tabs={tabs} activeItemId={pane.activeItemId} />\n ) : (\n <span className=\"mxc-panel-title\">New tab</span>\n )}\n <CanvasHeaderButton className=\"mxc-new-tab\" label=\"New tab\" onClick={() => void canvas.newTab(paneId)}>\n <PlusIcon />\n </CanvasHeaderButton>\n </>\n }\n leading={Leading && kindProps ? <Leading {...kindProps} /> : null}\n actions={\n Action && kindProps ? (\n // Its own gapless row: a kind's tap buttons space themselves (the tap-target placement rule).\n <span className=\"mxc-kind-actions\">\n <Action {...kindProps} />\n </span>\n ) : null\n }\n renderMenu={() => (\n <PaneMenu\n paneId={paneId}\n windowId={windowId}\n activeItem={active}\n kind={kind}\n kindProps={kindProps}\n tabCount={pane.itemIds.length}\n role={role}\n canSplit={!singlePane}\n />\n )}\n expanded={isFullscreen}\n onToggleExpand={() => canvas.setFullscreen(!isFullscreen)}\n expandShortcut={canvasShortcutHint(\"canvas.toggleFullscreen\", isMac())}\n onHide={windowId === CANVAS_MAIN_WINDOW ? () => canvas.hide() : undefined}\n onClose={() => canvas.closePane(paneId)}\n closeLabel={closeLabel}\n onPointerDownCapture={() => {\n if (!focused) canvas.focusPane(paneId);\n }}\n {...drop}\n >\n {Toolbar && kindProps ? (\n <div className=\"mxc-item-toolbar\" data-kind={active?.kind}>\n <ToolbarBoundary kindId={kind?.id ?? \"\"}>\n <Toolbar {...kindProps} />\n </ToolbarBoundary>\n </div>\n ) : null}\n <div ref={bodyRef} className=\"mxc-pane-slot\" data-mxc-slot={paneId}>\n {pane.itemIds.length === 0 ? <EmptyPaneLauncher paneId={paneId} /> : columnSlots ? null : <CanvasPaneInlineBodies paneId={paneId} slots={slots} />}\n </div>\n </CanvasPanel>\n );\n}\n\n/** A toolbar that throws renders nothing — it must never take the pane down. */\nclass ToolbarBoundary extends Component<{ kindId: string; children: ReactNode }, { failed: boolean }> {\n override state = { failed: false };\n\n static getDerivedStateFromError() {\n return { failed: true };\n }\n\n override componentDidCatch(error: unknown) {\n console.error(`[@ai-matrx/canvas] \"${this.props.kindId}\" Toolbar threw`, error);\n }\n\n override render() {\n return this.state.failed ? null : this.props.children;\n }\n}\n\n/** One tab: its title (draggable) and a close for it — a lone tab is never a trap. */\nfunction SingleTitle({ item, kind }: { item: CanvasItem; kind: AnyCanvasKind | undefined }) {\n const canvas = useCanvas();\n const title = itemTitle(item, kind);\n const drag = useTabDrag(item.id, title);\n const name = useTruncated(title);\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <span className=\"mxc-panel-title mxc-single-title\" data-draggable=\"\" data-truncated={name.truncated ? \"\" : undefined} title={title} {...drag}>\n <Icon className=\"mxc-title-icon\" />\n <span ref={name.ref} className=\"mxc-tab-title\">\n {title}\n </span>\n <button type=\"button\" className=\"mxc-tab-close\" data-slot=\"browser-tab-close\" aria-label={`Close ${title}`} onClick={() => canvas.close(item.id)}>\n <CloseIcon />\n </button>\n </span>\n );\n}\n\n/** A background tab's floor (px): icon + ~7 letters + \"…\" (\"Messag…\"). Mirrored to CSS as --mxc-tab-min. */\nexport const CANVAS_TAB_MIN_WIDTH = 88;\n/** The active tab's floor (px): icon + ~8 letters + \"…\" + its close. Mirrored to CSS as --mxc-tab-active-min. */\nexport const CANVAS_ACTIVE_TAB_MIN_WIDTH = 112;\n/** The \"All tabs\" button and the gaps around it (px). */\nconst TAB_LIST_BUTTON_ROOM = 36;\nconst TAB_GAP = 2;\n\n/**\n * Which tabs the strip shows at this width: all of them when every tab fits\n * at its floor, else as many as fit — always the active one — and the rest\n * are reached through the \"All tabs\" menu (Chrome / VS Code). Pure, so the\n * rule is testable without a layout engine. `width <= 0` (not measured yet)\n * shows everything.\n */\nexport function fitCanvasTabs(\n count: number,\n activeIndex: number,\n width: number,\n): { start: number; end: number; overflow: boolean; compact: boolean } {\n if (count <= 0) return { start: 0, end: 0, overflow: false, compact: false };\n const need = (n: number) => CANVAS_ACTIVE_TAB_MIN_WIDTH + (n - 1) * (CANVAS_TAB_MIN_WIDTH + TAB_GAP);\n if (width <= 0 || need(count) <= width) return { start: 0, end: count, overflow: false, compact: false };\n // One tab that does not fit at its floor: it is the title, as narrow as it must be (nothing to list).\n if (count === 1) return { start: 0, end: 1, overflow: false, compact: true };\n let fit = 1;\n while (fit + 1 < count && need(fit + 1) + TAB_LIST_BUTTON_ROOM <= width) fit += 1;\n const active = Math.min(Math.max(activeIndex, 0), count - 1);\n // Keep the strip's left edge still while the active tab is in the first window; else end on it.\n const start = active < fit ? 0 : active - fit + 1;\n return { start, end: start + fit, overflow: true, compact: need(fit) + TAB_LIST_BUTTON_ROOM > width };\n}\n\n/**\n * The tab strip. It takes the header's free width (never its own content's:\n * flex-basis 0, so what it shows never changes how wide it is). Tabs are as\n * wide as their names; when room runs short they shrink with an ellipsis to\n * their floor (icon + ~6 letters; the active tab keeps more), and past that\n * the tabs that do not fit go into the \"All tabs\" menu — the active tab is\n * always shown. At the narrowest the strip is the active tab's title and that\n * menu. Nothing in the header ever overlaps another control.\n */\nfunction TabStrip({ tabs, activeItemId }: { tabs: readonly StripTab[]; activeItemId: CanvasItemId | null }) {\n const canvas = useCanvas();\n const strip = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState(0);\n useIsoLayoutEffect(() => {\n const el = strip.current;\n if (!el) return undefined;\n const read = () => setWidth(Math.floor(el.getBoundingClientRect().width));\n read();\n const observer = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(read);\n observer?.observe(el);\n return () => observer?.disconnect();\n }, []);\n const activeIndex = Math.max(0, tabs.findIndex((tab) => tab.itemId === activeItemId));\n const fit = fitCanvasTabs(tabs.length, activeIndex, width);\n const shown = tabs.slice(fit.start, fit.end);\n const hidden = tabs.length - shown.length;\n return (\n <div\n ref={strip}\n className=\"mxc-tabstrip\"\n data-overflow={fit.overflow ? \"\" : undefined}\n data-compact={fit.compact ? \"\" : undefined}\n style={{ [\"--mxc-tab-min\" as string]: `${CANVAS_TAB_MIN_WIDTH}px`, [\"--mxc-tab-active-min\" as string]: `${CANVAS_ACTIVE_TAB_MIN_WIDTH}px` }}\n >\n <div\n className=\"mxc-tabs\"\n role=\"tablist\"\n aria-label=\"Canvas tabs\"\n onWheel={(event) => {\n // The wheel steps through tabs when some are out of sight (there is nothing to scroll).\n if (!fit.overflow || Math.abs(event.deltaY) < Math.abs(event.deltaX) || tabs.length < 2) return;\n const next = tabs[(activeIndex + (event.deltaY > 0 ? 1 : -1) + tabs.length) % tabs.length];\n if (next) canvas.activate(next.itemId);\n }}\n >\n {shown.map((tab) => (\n <ItemTab key={tab.itemId} itemId={tab.itemId} paneId={tab.paneId} index={tab.index} active={tab.itemId === activeItemId} />\n ))}\n </div>\n {fit.overflow ? <TabListMenu tabs={tabs} activeItemId={activeItemId} hidden={hidden} /> : null}\n </div>\n );\n}\n\n/** \"All tabs\": every tab of the strip by name, the active one marked — where tabs that do not fit are reached. */\nfunction TabListMenu({ tabs, activeItemId, hidden }: { tabs: readonly StripTab[]; activeItemId: CanvasItemId | null; hidden: number }) {\n const canvas = useCanvas();\n const { ports, layer } = useCanvasInternals();\n const blocking = useRef<(() => void) | null>(null);\n useEffect(() => () => blocking.current?.(), []);\n const label = `All tabs (${tabs.length})`;\n const trigger = (props: { onClick?: (event: ReactMouseEvent<HTMLButtonElement>) => void }) => (\n <CanvasHeaderButton className=\"mxc-tab-list\" label={label} data-hidden-count={hidden} {...props}>\n <ChevronDownIcon />\n <span className=\"mxc-tab-list-count\" aria-hidden=\"true\">\n {hidden}\n </span>\n </CanvasHeaderButton>\n );\n const showMenu = ports.showMenu;\n if (showMenu) {\n return trigger({\n onClick: (event) => {\n const state = canvas.getState();\n const entries: CanvasMenuEntry[] = tabs.map((tab) => {\n const item = state.items[tab.itemId];\n const title = item ? itemTitle(item, resolveItemKind(item.kind, getCanvasKind)) : tab.itemId;\n return { type: \"item\", id: tab.itemId, label: tab.itemId === activeItemId ? `${title} (current)` : title };\n });\n void showMenu(entries, toCanvasRect(event.currentTarget.getBoundingClientRect())).then(\n (chosen) => {\n if (chosen) canvas.activate(chosen as CanvasItemId);\n },\n (error: unknown) => console.error(\"[@ai-matrx/canvas] the host menu failed\", error),\n );\n },\n });\n }\n return (\n <Menu.Root\n onOpenChange={(open) => {\n blocking.current?.();\n blocking.current = open ? layer.beginBlocking() : null;\n }}\n >\n <Menu.Trigger asChild>{trigger({})}</Menu.Trigger>\n <Menu.Portal>\n <Menu.Content align=\"end\" sideOffset={4} className=\"mxc-menu mxc-tab-list-menu\" aria-label=\"All tabs\">\n {tabs.map((tab) => (\n <TabListEntry key={tab.itemId} itemId={tab.itemId} active={tab.itemId === activeItemId} />\n ))}\n </Menu.Content>\n </Menu.Portal>\n </Menu.Root>\n );\n}\n\nfunction TabListEntry({ itemId, active }: { itemId: CanvasItemId; active: boolean }) {\n const canvas = useCanvas();\n const item = useCanvasState((s) => s.items[itemId]);\n const kind = useItemKind(item?.kind ?? \"\");\n if (!item) return null;\n const Icon = kind?.icon ?? AlertIcon;\n const title = itemTitle(item, kind);\n return (\n <Menu.Item\n className=\"mxc-menu-item mxc-tab-list-item\"\n data-active={active ? \"\" : undefined}\n aria-current={active ? \"true\" : undefined}\n title={title}\n onSelect={() => canvas.activate(itemId)}\n >\n <Icon />\n <span className=\"mxc-tab-list-title\">{title}</span>\n </Menu.Item>\n );\n}\n\nfunction ItemTab({ itemId, paneId, index, active }: { itemId: CanvasItemId; paneId: CanvasPaneId; index: number; active: boolean }) {\n const canvas = useCanvas();\n const item = useCanvasState((s) => s.items[itemId]);\n const kind = useItemKind(item?.kind ?? \"\");\n const title = item ? itemTitle(item, kind) : \"\";\n const drag = useTabDrag(itemId, title);\n if (!item) return null;\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <CanvasTab\n title={title}\n icon={<Icon />}\n active={active}\n onSelect={() => canvas.activate(itemId)}\n onClose={() => canvas.close(itemId)}\n {...drag}\n onDragOver={(event) => {\n if (event.dataTransfer.types.includes(CANVAS_DRAG_MIME)) event.preventDefault();\n }}\n onDrop={(event) => {\n const dragged = event.dataTransfer.getData(CANVAS_DRAG_MIME) as CanvasItemId;\n if (!dragged) return;\n // Dropped ON a tab: take that tab's place (the pane-level drop still clears its indicator).\n event.preventDefault();\n if (dragged !== itemId) canvas.moveItem(dragged, paneId, index);\n }}\n onAuxClick={(event) => {\n if (event.button === 1) canvas.close(itemId);\n }}\n />\n );\n}\n\ninterface MenuAction {\n readonly id: string;\n readonly label: string;\n readonly icon?: ReactNode;\n readonly destructive?: boolean;\n readonly onSelect: () => void;\n}\n\nfunction PaneMenu({\n paneId,\n windowId,\n activeItem,\n kind,\n kindProps,\n tabCount,\n role,\n canSplit,\n}: {\n paneId: CanvasPaneId;\n windowId: CanvasWindowId;\n activeItem: CanvasItem | undefined;\n kind: AnyCanvasKind | undefined;\n kindProps: CanvasKindProps | null;\n tabCount: number;\n role: \"main\" | \"window\" | \"pop-out\";\n /** False on a phone: it presents one pane, so a split would show an empty pane under the header of another. */\n canSplit: boolean;\n}) {\n const canvas = useCanvas();\n const { ports, layer, itemMenus } = useCanvasInternals();\n const moveId = tabCount > 1 ? activeItem?.id : undefined;\n const blocking = useRef<(() => void) | null>(null);\n useEffect(() => () => blocking.current?.(), []);\n\n // Built when the menu OPENS, so what a body offers (useCanvasMenuItems) is current.\n const buildSections = (): MenuAction[][] => {\n const kindItems: readonly CanvasMenuItem[] = kind?.menuItems && kindProps ? safeMenu(() => kind.menuItems?.(kindProps)) : [];\n const hostItems: readonly CanvasMenuItem[] = activeItem && ports.itemActions ? safeMenu(() => ports.itemActions?.(activeItem, kind)) : [];\n // What the body offers right now (useCanvasMenuItems) — read as the menu is built, never a second \"…\".\n const bodyItems: readonly CanvasMenuItem[] = activeItem ? itemMenus.read(activeItem.id) : [];\n return [\n [...kindItems, ...bodyItems, ...hostItems].map((entry) => ({ ...entry, id: `item:${entry.id}` })),\n [\n ...(canSplit\n ? [\n { id: \"split-right\", label: \"Split right\", icon: <SplitRightIcon />, onSelect: () => canvas.splitPane(paneId, \"horizontal\", moveId) },\n { id: \"split-down\", label: \"Split down\", icon: <SplitDownIcon />, onSelect: () => canvas.splitPane(paneId, \"vertical\", moveId) },\n ]\n : []),\n ...(activeItem && role === \"pop-out\"\n ? [{ id: \"dock-back\", label: \"Dock back\", icon: <DockIcon />, onSelect: () => void canvas.dockBack(activeItem.id) }]\n : activeItem && ports.popOut\n ? [{ id: \"pop-out\", label: \"Pop out\", icon: <PopOutIcon />, onSelect: () => void canvas.popOut(activeItem.id) }]\n : []),\n ],\n activeItem\n ? [\n { id: \"close-tab\", label: \"Close tab\", onSelect: () => canvas.close(activeItem.id) },\n ...(tabCount > 1 ? [{ id: \"close-others\", label: \"Close other tabs\", onSelect: () => canvas.closeOthers(activeItem.id) }] : []),\n ]\n : [],\n ].filter((section) => section.length > 0);\n };\n\n const showMenu = ports.showMenu;\n if (showMenu) {\n // The host draws the menu (above native views); the package keeps the handlers.\n return (\n <CanvasMenuTrigger\n onClick={(event) => {\n const entries: CanvasMenuEntry[] = [];\n const handlers = new Map<string, () => void>();\n buildSections().forEach((section, i) => {\n if (i > 0) entries.push({ type: \"separator\" });\n for (const action of section) {\n entries.push({ type: \"item\", id: action.id, label: action.label, ...(action.destructive ? { destructive: true } : {}) });\n handlers.set(action.id, action.onSelect);\n }\n });\n const anchor = toCanvasRect(event.currentTarget.getBoundingClientRect());\n void showMenu(entries, anchor).then(\n (chosen) => {\n if (chosen) handlers.get(chosen)?.();\n },\n (error: unknown) => console.error(\"[@ai-matrx/canvas] the host menu failed\", error),\n );\n }}\n />\n );\n }\n\n return (\n <Menu.Root\n onOpenChange={(open) => {\n // A DOM menu over a native view must be seen: tell the host to step its views aside.\n blocking.current?.();\n blocking.current = open ? layer.beginBlocking() : null;\n }}\n >\n <Menu.Trigger asChild>\n <CanvasMenuTrigger />\n </Menu.Trigger>\n <Menu.Portal>\n <Menu.Content align=\"end\" sideOffset={4} className=\"mxc-menu\">\n <MenuSections build={buildSections} />\n </Menu.Content>\n </Menu.Portal>\n </Menu.Root>\n );\n}\n\n/** Rendered only while the menu is open: the sections are read then. */\nfunction MenuSections({ build }: { build: () => MenuAction[][] }) {\n return (\n <>\n {build().map((section, i) => (\n <MenuSection key={i} first={i === 0} actions={section} />\n ))}\n </>\n );\n}\n\nfunction MenuSection({ first, actions }: { first: boolean; actions: readonly MenuAction[] }) {\n return (\n <>\n {first ? null : <Menu.Separator className=\"mxc-menu-separator\" />}\n {actions.map((action) => (\n <Menu.Item key={action.id} onSelect={action.onSelect} className=\"mxc-menu-item\" data-destructive={action.destructive ? \"\" : undefined}>\n {action.icon}\n {action.label}\n </Menu.Item>\n ))}\n </>\n );\n}\n\nfunction safeMenu(build: () => readonly CanvasMenuItem[] | undefined): readonly CanvasMenuItem[] {\n try {\n return build() ?? [];\n } catch (error) {\n console.error(\"[@ai-matrx/canvas] a menu builder threw\", error);\n return [];\n }\n}\n\n"],"mappings":";;;;AASA;AAAA,EACE;AAAA,EACA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA,YAAAC;AAAA,EACA,wBAAAC;AAAA,OAGK;;;ACHP,SAAS,WAAW,iBAAiB,cAAc;AAKnD,IAAM,qBAAqB,OAAO,WAAW,cAAc,YAAY;AAShE,SAAS,wBAAyC;AACvD,QAAM,UAAU,oBAAI,IAAwD;AAC5E,SAAO;AAAA,IACL,SAAS,QAAQ,MAAM;AACrB,UAAI,MAAM,QAAQ,IAAI,MAAM;AAC5B,UAAI,CAAC,IAAK,SAAQ,IAAI,QAAS,MAAM,oBAAI,IAAI,CAAE;AAC/C,UAAI,IAAI,IAAI;AACZ,aAAO,MAAM;AACX,cAAM,UAAU,QAAQ,IAAI,MAAM;AAClC,iBAAS,OAAO,IAAI;AACpB,YAAI,WAAW,Q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;AAEJ;AAEA,SAAS,eAAe,EAAE,MAAM,QAAQ,GAA+D;AACrG,QAAM,OAAO,cAAc,KAAK,IAAI;AACpC,QAAM,SAAS,oBAAoB;AAAA,IACjC,MAAM,KAAK;AAAA,IACX,KAAK,KAAK;AAAA,IACV,MAAM,KAAK;AAAA,IACX,OAAO,KAAK;AAAA,IACZ,aAAa,KAAK;AAAA,EACpB,CAAC;AACD,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,OAAO,KAAK;AAClB,QAAM,SAAS,YAAY,UAAU,kBAAkB;AACvD,QAAM,OAAO,KAAK,SAAS,KAAK;AAChC,SACE,gBAAAA;AAAA,IAAC;AAAA;AAAA,MACC,WAAW;AAAA,MACX,SAAS;AAAA,MACT,MAAM,gBAAAA,KAAC,QAAK;AAAA,MACZ,SAAS,OAAO;AAAA,MAChB,SAAS,MAAM,KAAK,OAAO,OAAO;AAAA;AAAA,EACpC;AAEJ;AAMO,SAAS,YAAY,EAAE,UAAU,UAAU,GAAgD;AAChG,QAAM,EAAE,SAAS,IAAI,mBAAmB;AACxC,QAAM,eAAe,eAAe,CAAC,MAAM,yBAAyB,GAAG,QAAQ,CAAC;AAChF,QAAM,SAAS,eAAe,CAAC,MAAM,mBAAmB,GAAG,QAAQ,CAAC;AACpE,SACE,gBAAAC,MAAC,SAAI,WAAW,CAAC,aAAa,SAAS,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,GAAG,oBAAkB,SAAS,KAAK,QAClG;AAAA,oBAAAD,KAAC,SAAI,WAAU,kBAAiB,QAAQ,UAAU,cAC/C,UACH;AAAA,IACA,gBAAAA,KAAC,gBAAa;AAAA,KAChB;AAEJ;","names":["useEffect","useRef","useState","useSyncExternalStore","frame","focused","isMac","frame","frame","useEffect","useLayoutEffect","useRef","jsx","useRef","useState","useEffect","isMac","useSyncExternalStore","useEffect","useLayoutEffect","useRef","useState","useSyncExternalStore","useEffect","useLayoutEffect","useMemo","useRef","useState","useEffect","useLayoutEffect","useRef","useState","jsx","jsxs","jsx","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","useRef","useState","CanvasHeaderButton","CanvasMenuTrigger","CanvasPanel","CanvasTab","useEffect","useRef","useRef","useEffect","jsx","jsxs","createContext","useContext","createContext","useContext","useSyncExternalStore","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","useMemo","SEP","frame","useRef","useState","BodyHost","Rendered","Component","useEffect","useLayoutEffect","useRef","useState","Fragment","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","frame","useState","useRef","Component","Fragment","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","useSyncExternalStore","useState","useRef","frame","isMac"]}
|
|
1
|
+
{"version":3,"sources":["../src/react/provider.tsx","../src/react/menuItems.ts","../src/core/types.ts","../src/core/ids.ts","../src/core/layout.ts","../src/core/reducer.ts","../src/core/store.ts","../src/core/persistence.ts","../src/core/rules.ts","../src/core/commands.ts","../src/core/controller.ts","../src/core/selectors.ts","../src/core/presentation.ts","../src/core/toggleKind.ts","../src/react/layer.tsx","../src/react/registry.ts","../src/react/CanvasColumn.tsx","../src/react/bodies.tsx","../src/react/chrome.tsx","../src/react/icons.tsx","../src/react/dnd.ts","../src/react/launcher.tsx","../src/react/presentation.tsx","../src/react/slots.ts","../src/react/resizeGesture.ts","../src/react/CanvasPane.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * CanvasProvider — binds a store, starts persistence, binds the shortcut table,\n * and hands every descendant the ONE controller (acting for this provider's\n * window). A host adds it once at its root — a desktop host once per window,\n * each over the same remote store with its own `windowId`.\n */\n\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type ComponentType,\n type ReactNode,\n} from \"react\";\nimport { createCanvasItemMenus, type CanvasItemMenus } from \"./menuItems\";\nimport {\n CANVAS_DEFAULT_KEY,\n CANVAS_MAIN_WINDOW,\n CANVAS_PHONE_MAX_WIDTH,\n CANVAS_SHORTCUTS,\n selectCanvasKindVisibility,\n toggleKind,\n type CanvasKindVisibility,\n type ToggleKindInput,\n canvasWindowFrame,\n canvasWindowId,\n createCanvasController,\n createCanvasStore,\n createLocalStorageCanvasPersistence,\n matchesCanvasAccelerator,\n runCanvasCommand,\n type CanvasController,\n type CanvasErrorSink,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasLayoutRules,\n type CanvasPersistencePort,\n type CanvasSessionHooks,\n type CanvasShortcutWhen,\n type CanvasState,\n type CanvasStoreBinding,\n type CanvasWindowId,\n} from \"../index\";\nimport {\n CanvasDomOverlay,\n createCanvasLayer,\n type CanvasLayer,\n type CanvasNativeBodyFrame,\n type CanvasOverlayPort,\n type CanvasShowMenu,\n} from \"./layer\";\nimport {\n canvasSessionKey,\n getCanvasKind,\n getCanvasKindsVersion,\n listCanvasKinds,\n subscribeCanvasKinds,\n type AnyCanvasKind,\n type CanvasMenuItem,\n} from \"./registry\";\n\n/**\n * What the host answers ONCE for every kind. Saving, sharing and history are\n * \"handled globally\" here; the window ports let a desktop host draw floating\n * things and native bodies its own way. Every port has a working default.\n */\nexport interface CanvasHostPorts {\n /** Extra \"…\" menu entries for an item (share, save to cloud, version history…). */\n readonly itemActions?: ((item: CanvasItem, kind: AnyCanvasKind | undefined) => readonly CanvasMenuItem[]) | undefined;\n /**\n * Opens a window that renders this canvas for the returned window id (web: a\n * floating panel with <CanvasWindowScope>; desktop: a BrowserWindow with its\n * own provider). The item then moves there. Absent ⇒ no \"Pop out\" entry, and\n * `controller.popOut` is refused aloud.\n */\n readonly popOut?: ((item: CanvasItem) => Promise<{ readonly windowId: string } | null>) | undefined;\n /** A tab docked back out of `fromWindowId`. Close that window once the state no longer lists it. */\n readonly dockBack?: ((itemId: CanvasItemId, fromWindowId: CanvasWindowId) => void) | undefined;\n /** Draws the \"…\" menu (Electron `Menu.popup`). Default: the package's DOM menu. */\n readonly showMenu?: CanvasShowMenu | undefined;\n /** Draws tooltips, drop indicators and tab drags above native views. Default: in the DOM. */\n readonly overlay?: CanvasOverlayPort | undefined;\n /** Where each native-body kind's view goes, reported in the frame the layout changed. */\n readonly onNativeBodyFrame?: CanvasNativeBodyFrame | undefined;\n}\n\nexport type CanvasTabStripMode = \"auto\" | \"always\";\n\ninterface CanvasContextValue {\n readonly controller: CanvasController;\n readonly windowId: CanvasWindowId;\n readonly ports: CanvasHostPorts;\n readonly layer: CanvasLayer;\n /** Width of the region the canvas shares with the content beside it; null = the window. */\n readonly regionWidth: number | null;\n readonly tabStrip: CanvasTabStripMode;\n readonly launcherEntries: CanvasLauncherEntryStore;\n /** Menu entries bodies contribute to their pane's one menu. */\n readonly itemMenus: CanvasItemMenus;\n}\n\n/**\n * One contextual launcher entry: a page offers something about ITSELF in the\n * canvas's \"New tab\" launcher (\"This chat's documents\" on a chat page) for as\n * long as it is mounted. Shown before the global kinds.\n */\nexport interface CanvasLauncherEntry {\n readonly kind: string;\n readonly key: string;\n readonly data?: CanvasJson | undefined;\n /** The entry's label (and the new tab's title). Default: the kind's label. */\n readonly title?: string | null | undefined;\n /** Default: the kind's icon. */\n readonly icon?: ComponentType<{ className?: string }> | undefined;\n}\n\nexport interface CanvasLauncherEntryStore {\n add(entry: CanvasLauncherEntry): () => void;\n list(): readonly CanvasLauncherEntry[];\n subscribe(listener: () => void): () => void;\n}\n\nfunction createLauncherEntryStore(): CanvasLauncherEntryStore {\n let entries: readonly CanvasLauncherEntry[] = [];\n const listeners = new Set<() => void>();\n const emit = () => {\n for (const listener of [...listeners]) listener();\n };\n return {\n add(entry) {\n entries = [...entries, entry];\n emit();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n entries = entries.filter((e) => e !== entry);\n emit();\n };\n },\n list: () => entries,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n/** Phones show an open canvas full screen; a remembered \"open\" never takes over a phone on load. */\nconst isPhoneViewport = () => typeof window !== \"undefined\" && window.innerWidth <= CANVAS_PHONE_MAX_WIDTH;\n\nconst isMacPlatform = () =>\n typeof navigator !== \"undefined\" && /mac|iphone|ipad/i.test((navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform ?? navigator.platform ?? \"\");\n\n/** Escape belongs to a menu, dialog or listbox when one has focus. */\nfunction escapeBelongsElsewhere(event: KeyboardEvent): boolean {\n if (event.defaultPrevented) return true;\n const active = typeof document === \"undefined\" ? null : document.activeElement;\n return !!active?.closest?.('[role=\"menu\"], [role=\"dialog\"], [role=\"alertdialog\"], [role=\"listbox\"]');\n}\n\nconst CanvasContext = createContext<CanvasContextValue | null>(null);\n\nexport interface CanvasProviderProps extends CanvasHostPorts {\n readonly children: ReactNode;\n /** A Redux-bound store (bindCanvasToReduxStore), a remote one (createRemoteCanvasStore), or omit for a standalone store. */\n readonly store?: CanvasStoreBinding;\n /** `null` turns memory off. Default: localStorage. Ignored for a remote store (its owner saves). */\n readonly persistence?: CanvasPersistencePort | null;\n readonly onError?: CanvasErrorSink;\n /** Binds the shortcut table's web shortcuts (⌘\\ toggles, Esc leaves expand…). Default true. */\n readonly hotkeys?: boolean;\n /** The window this provider renders. Default: the main window. */\n readonly windowId?: string;\n /** Width and split numbers, read once. Default: CANVAS_WEB_LAYOUT_RULES. */\n readonly layoutRules?: Partial<CanvasLayoutRules>;\n /** Live width of the region the canvas shares with the content beside it (desktop: right of the sidebar). Default: the window. */\n readonly regionWidth?: number | null;\n /** \"auto\": a pane with one tab shows a title instead of a tab strip. Default \"auto\". */\n readonly tabStrip?: CanvasTabStripMode;\n}\n\nfunction sessionHooksFor(kindId: string): CanvasSessionHooks | undefined {\n const kind = getCanvasKind(kindId);\n if (!kind || kind.restore !== \"session\") return undefined;\n return {\n sessionKey: (item) => canvasSessionKey(kind, item),\n onAttach: kind.onAttach,\n onDetach: kind.onDetach,\n };\n}\n\nexport function CanvasProvider({\n children,\n store,\n persistence,\n onError,\n hotkeys = true,\n windowId: windowIdProp,\n layoutRules,\n regionWidth = null,\n tabStrip = \"auto\",\n itemActions,\n popOut,\n dockBack,\n showMenu,\n overlay,\n onNativeBodyFrame,\n}: CanvasProviderProps) {\n // One identity per set of ports: a provider re-rendering for its parent must\n // not re-render every canvas consumer (the context value below is stable too).\n const hostPorts = useMemo<CanvasHostPorts>(\n () => ({ itemActions, popOut, dockBack, showMenu, overlay, onNativeBodyFrame }),\n [itemActions, popOut, dockBack, showMenu, overlay, onNativeBodyFrame],\n );\n const portsRef = useRef<CanvasHostPorts>(hostPorts);\n portsRef.current = hostPorts;\n const [{ controller, layer, launcherEntries, itemMenus }] = useState(() => ({\n controller: createCanvasController({\n store: store ?? createCanvasStore(),\n persistence: persistence === undefined ? createLocalStorageCanvasPersistence() : persistence,\n isRestorable: (kind) => getCanvasKind(kind)?.restore !== false,\n mayRestoreOpen: () => !isPhoneViewport(),\n onError,\n windowId: windowIdProp ?? CANVAS_MAIN_WINDOW,\n layoutRules,\n windowPorts: () => portsRef.current,\n sessions: sessionHooksFor,\n preferredTarget: (kind) => getCanvasKind(kind)?.preferredTarget,\n }),\n layer: createCanvasLayer(() => portsRef.current),\n launcherEntries: createLauncherEntryStore(),\n itemMenus: createCanvasItemMenus(),\n }));\n const windowId = controller.windowId;\n\n useEffect(() => controller.start(), [controller]);\n\n useEffect(() => {\n if (!hotkeys) return;\n const isMac = isMacPlatform();\n const applies = (when: CanvasShortcutWhen, event: KeyboardEvent) => {\n if (!controller.isPresented()) return false; // no column here — nothing to act on\n if (when === \"presented\") return true;\n if (when === \"fullscreen\") return !!canvasWindowFrame(controller.getState(), windowId)?.isFullscreen && !escapeBelongsElsewhere(event);\n const column = document.activeElement?.closest?.(\"[data-mxc-window]\");\n return column?.getAttribute(\"data-mxc-window\") === windowId;\n };\n const onKey = (event: KeyboardEvent) => {\n for (const shortcut of CANVAS_SHORTCUTS) {\n if (!shortcut.web || !matchesCanvasAccelerator(event, shortcut.accelerator, isMac)) continue;\n if (!applies(shortcut.when, event)) return;\n if (runCanvasCommand(controller, shortcut.id)) event.preventDefault();\n return;\n }\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [controller, hotkeys, windowId]);\n\n const value = useMemo<CanvasContextValue>(\n () => ({ controller, windowId, ports: hostPorts, layer, regionWidth, tabStrip, launcherEntries, itemMenus }),\n [controller, windowId, hostPorts, layer, regionWidth, tabStrip, launcherEntries, itemMenus],\n );\n return (\n <CanvasContext.Provider value={value}>\n {children}\n {hostPorts.overlay ? null : <CanvasDomOverlay layer={layer} />}\n </CanvasContext.Provider>\n );\n}\n\n/**\n * Renders a subtree as ANOTHER window of the same canvas — the web host's\n * pop-out panel: `<CanvasWindowScope windowId={id}><CanvasColumn placement=\"fill\"/></CanvasWindowScope>`.\n */\nexport function CanvasWindowScope({ windowId, children }: { windowId: string; children: ReactNode }) {\n const parent = useCanvasContext();\n const value = useMemo<CanvasContextValue>(() => {\n const id = canvasWindowId(windowId);\n return { ...parent, windowId: id, controller: parent.controller.forWindow(id) };\n }, [parent, windowId]);\n return <CanvasContext.Provider value={value}>{children}</CanvasContext.Provider>;\n}\n\nfunction useCanvasContext(): CanvasContextValue {\n const value = useContext(CanvasContext);\n if (!value) throw new Error(\"[@ai-matrx/canvas] useCanvas* must be used inside <CanvasProvider>.\");\n return value;\n}\n\n/** Package-internal: the whole context (layer, ports, region). */\nexport function useCanvasInternals(): CanvasContextValue {\n return useCanvasContext();\n}\n\nexport function useOptionalCanvasInternals(): CanvasContextValue | null {\n return useContext(CanvasContext);\n}\n\n/** The controller (acting for this window): open, close, toggle, split… */\nexport function useCanvas(): CanvasController {\n return useCanvasContext().controller;\n}\n\n/** Same as useCanvas, but null outside a provider (for components that may render anywhere). */\nexport function useOptionalCanvas(): CanvasController | null {\n return useContext(CanvasContext)?.controller ?? null;\n}\n\n/** The window this subtree renders. */\nexport function useCanvasWindowId(): CanvasWindowId {\n return useContext(CanvasContext)?.windowId ?? CANVAS_MAIN_WINDOW;\n}\n\nexport function useCanvasHostPorts(): CanvasHostPorts {\n return useCanvasContext().ports;\n}\n\n/**\n * Native-body controls. `remeasure()` re-reports every native body's frame now —\n * call it on each animation frame while the host animates its own layout (a\n * sidebar collapsing moves the canvas without resizing it).\n */\nexport function useCanvasNativeBodies(): { readonly remeasure: () => void } {\n return useCanvasContext().layer.native;\n}\n\n/** Registers a mounted canvas column with the controller for its lifetime. */\nexport function useRegisterCanvasPresence(): void {\n const context = useContext(CanvasContext);\n const controller = context?.controller;\n const windowId = context?.windowId;\n useEffect(() => controller?.registerPresentation(windowId), [controller, windowId]);\n}\n\nconst noPresence = () => () => undefined;\n\n/** True when a canvas column is on screen for this window — the ONE availability answer. */\nexport function useCanvasIsPresented(): boolean {\n const context = useContext(CanvasContext);\n const controller = context?.controller;\n return useSyncExternalStore(\n controller ? controller.subscribePresentation : noPresence,\n () => controller?.isPresented() ?? false,\n () => false,\n );\n}\n\n/** Subscribes to a slice of canvas state. The selector must return stable values. */\nexport function useCanvasState<T>(selector: (state: CanvasState) => T): T {\n const { store } = useCanvasContext().controller;\n return useSyncExternalStore(\n store.subscribe,\n () => selector(store.getState()),\n () => selector(store.getState()),\n );\n}\n\nconst NO_SUBSCRIPTION = () => () => undefined;\n\n/**\n * Like useCanvasState, but safe outside a provider: returns `fallback` there.\n * For components that may render in a tree with no canvas (a bare test, an\n * embed). `fallback` must be referentially stable (a primitive or null).\n */\nexport function useOptionalCanvasState<T>(selector: (state: CanvasState) => T, fallback: T): T {\n const store = useContext(CanvasContext)?.controller.store;\n const read = () => (store ? selector(store.getState()) : fallback);\n return useSyncExternalStore(store ? store.subscribe : NO_SUBSCRIPTION, read, read);\n}\n\n/**\n * A toolbar icon's view of one kind: \"absent\" | \"background\" | \"visible\"\n * (a primitive, so it never loops), plus the click that toggles or focuses it.\n */\nexport function useCanvasKindToggle(input: ToggleKindInput): {\n readonly visibility: CanvasKindVisibility;\n readonly isOpen: boolean;\n readonly isVisible: boolean;\n readonly toggle: () => CanvasKindVisibility;\n} {\n const controller = useCanvasContext().controller;\n const key = input.key ?? CANVAS_DEFAULT_KEY;\n const visibility = useCanvasState((s) => selectCanvasKindVisibility(s, input.kind, key));\n return {\n visibility,\n isOpen: visibility !== \"absent\",\n isVisible: visibility === \"visible\",\n toggle: () => toggleKind(controller, input),\n };\n}\n\n/** Re-renders when kinds register, so late-registered kinds appear. */\nexport function useCanvasKinds(): readonly AnyCanvasKind[] {\n useSyncExternalStore(subscribeCanvasKinds, getCanvasKindsVersion, getCanvasKindsVersion);\n return listCanvasKinds();\n}\n\nexport function useCanvasKind(id: string): AnyCanvasKind | undefined {\n useSyncExternalStore(subscribeCanvasKinds, getCanvasKindsVersion, getCanvasKindsVersion);\n return getCanvasKind(id);\n}\n\nconst NO_ENTRIES: readonly CanvasLauncherEntry[] = Object.freeze([]);\nconst noEntries = () => NO_ENTRIES;\n\n/**\n * Offers `entry` in the canvas's \"New tab\" launcher while the calling\n * component is mounted — a route registers what is about IT (a chat's\n * documents, a table's saved views). Contextual entries show before the\n * global kinds. A no-op outside a CanvasProvider.\n */\nexport function useCanvasLauncherEntry(entry: CanvasLauncherEntry): void {\n const store = useContext(CanvasContext)?.launcherEntries;\n const fingerprint = JSON.stringify([entry.kind, entry.key, entry.title ?? null, entry.data ?? null]);\n const icon = entry.icon;\n useEffect(() => {\n if (!store) return undefined;\n const [kind, key, title, data] = JSON.parse(fingerprint) as [string, string, string | null, CanvasJson];\n return store.add({ kind, key, title, data, ...(icon ? { icon } : {}) });\n }, [store, fingerprint, icon]);\n}\n\n/** Contextual launcher entries, latest registration of each `kind::key` only, in registration order. */\nexport function useCanvasLauncherEntries(): readonly CanvasLauncherEntry[] {\n const store = useContext(CanvasContext)?.launcherEntries;\n const all = useSyncExternalStore(store ? store.subscribe : NO_SUBSCRIPTION, store ? store.list : noEntries, store ? store.list : noEntries);\n const seen = new Set<string>();\n const out: CanvasLauncherEntry[] = [];\n for (let i = all.length - 1; i >= 0; i -= 1) {\n const entry = all[i];\n if (!entry || seen.has(`${entry.kind}::${entry.key}`)) continue;\n seen.add(`${entry.kind}::${entry.key}`);\n out.unshift(entry);\n }\n return out;\n}\n","\"use client\";\n\n/**\n * Menu entries a BODY contributes to its pane's one menu.\n *\n * A pane has ONE menu (\"⋮\"): the kind's `menuItems`, then what the body\n * offers right now (a record's own actions, a document's export), then the\n * host's `itemActions`, then the pane's own actions (Split, Pop out, Close\n * others). A body never draws a second overflow button in the header; it\n * calls `useCanvasMenuItems(itemId, items)` and its entries join that menu.\n *\n * Entries carry callbacks, so they live here (per provider), never in the\n * store. The menu reads them when it opens, so a body re-rendering never\n * re-renders a pane.\n */\n\nimport { useEffect, useLayoutEffect, useRef } from \"react\";\nimport type { CanvasItemId } from \"../index\";\nimport { useCanvasInternals } from \"./provider\";\nimport type { CanvasMenuItem } from \"./registry\";\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nexport interface CanvasItemMenus {\n /** Registers a live source of entries for an item; returns the unregister. */\n register(itemId: CanvasItemId, read: () => readonly CanvasMenuItem[]): () => void;\n /** Every registered entry for an item, in registration order. */\n read(itemId: CanvasItemId): readonly CanvasMenuItem[];\n}\n\nexport function createCanvasItemMenus(): CanvasItemMenus {\n const sources = new Map<CanvasItemId, Set<() => readonly CanvasMenuItem[]>>();\n return {\n register(itemId, read) {\n let set = sources.get(itemId);\n if (!set) sources.set(itemId, (set = new Set()));\n set.add(read);\n return () => {\n const current = sources.get(itemId);\n current?.delete(read);\n if (current && current.size === 0) sources.delete(itemId);\n };\n },\n read(itemId) {\n const out: CanvasMenuItem[] = [];\n for (const read of sources.get(itemId) ?? []) {\n try {\n out.push(...read());\n } catch (error) {\n console.error(\"[@ai-matrx/canvas] a body's menu entries threw\", error);\n }\n }\n return out;\n },\n };\n}\n\n/**\n * Puts `items` into the pane menu of the tab `itemId` (the body's own\n * actions), after the kind's `menuItems`. The latest `items` are read each\n * time the menu opens; pass `[]` to offer nothing.\n */\nexport function useCanvasMenuItems(itemId: CanvasItemId | string | null | undefined, items: readonly CanvasMenuItem[]): void {\n const { itemMenus } = useCanvasInternals();\n const latest = useRef(items);\n latest.current = items;\n useIsoLayoutEffect(() => {\n if (!itemId) return undefined;\n return itemMenus.register(itemId as CanvasItemId, () => latest.current);\n }, [itemMenus, itemId]);\n}\n","/**\n * @ai-matrx/canvas — core types.\n *\n * The canvas is ONE docked column on the right edge of an application. It holds\n * panes; panes hold tabs; every tab is one CanvasItem. A CanvasItem is\n * identified by `kind` + `key`, so opening the same thing twice always lands on\n * the existing tab instead of creating a duplicate.\n *\n * Everything in CanvasState is plain JSON: it lives in the host's Redux store\n * (or the package's own standalone store), it is persisted between sessions,\n * and it can be inspected. No functions, no class instances, no React nodes.\n */\n\n/** Any value that survives JSON.stringify → JSON.parse unchanged. */\nexport type CanvasJson =\n | string\n | number\n | boolean\n | null\n | readonly CanvasJson[]\n | { readonly [key: string]: CanvasJson | undefined };\n\ndeclare const itemIdBrand: unique symbol;\ndeclare const paneIdBrand: unique symbol;\ndeclare const splitIdBrand: unique symbol;\ndeclare const windowIdBrand: unique symbol;\n\n/** `${kind}::${key}` — the identity of one thing on the canvas. */\nexport type CanvasItemId = string & { readonly [itemIdBrand]: true };\nexport type CanvasPaneId = string & { readonly [paneIdBrand]: true };\nexport type CanvasSplitId = string & { readonly [splitIdBrand]: true };\n/**\n * One application window that renders a canvas. Single-window hosts only ever\n * see `CANVAS_MAIN_WINDOW`; a desktop host with one store in its main process\n * gives every other window (a second app window, a popped-out tab) its own id.\n */\nexport type CanvasWindowId = string & { readonly [windowIdBrand]: true };\n\nexport const CANVAS_MAIN_WINDOW = \"main\" as CanvasWindowId;\n\n/**\n * Where a tab was before it navigated in place (`controller.navigate`). Plain\n * JSON, so history persists with the layout; Back reopens the last entry.\n */\nexport interface CanvasHistoryEntry {\n readonly kind: string;\n readonly key: string;\n readonly title: string | null;\n readonly data: CanvasJson;\n /**\n * The body this content had (its item's `instance`). Back and a navigate to\n * a kept step reuse it, so the SAME live body comes back (a typed draft, a\n * scroll position) while the layer still holds it mounted.\n */\n readonly instance?: string | undefined;\n}\n\n/** The built-in \"New tab\" item: the launcher, shown as a tab. Never registered as a kind. */\nexport const CANVAS_LAUNCHER_KIND = \"canvas.launcher\";\n\n/** How many steps Back can go in one tab. Older entries fall off. */\nexport const CANVAS_HISTORY_LIMIT = 50;\n\n/**\n * How many earlier contents of one tab keep their body MOUNTED (hidden), in\n * each direction: the newest steps Back reaches, and the contents Back left\n * (`CanvasItem.kept`). Older steps still work — their body mounts fresh.\n * Only closing the tab disposes the kept bodies.\n */\nexport const CANVAS_KEEP_ALIVE_DEPTH = 5;\n\nexport interface CanvasItem {\n readonly id: CanvasItemId;\n /** Registered kind id (see `registerCanvasKind`). */\n readonly kind: string;\n /** Stable key inside the kind — an artifact id, a conversation id, \"default\". */\n readonly key: string;\n /** Explicit tab title. `null` ⇒ the kind's `title(data)` or its label. */\n readonly title: string | null;\n readonly data: CanvasJson;\n readonly openedAt: number;\n readonly updatedAt: number;\n /** Earlier contents of this tab, oldest first (navigate in place). Absent = no Back. */\n readonly history?: readonly CanvasHistoryEntry[] | undefined;\n /**\n * Contents this tab showed that Back has stepped away from (newest last, at\n * most CANVAS_KEEP_ALIVE_DEPTH). Navigating to one again brings back its\n * live body instead of a new one: \"+\" → Quick Chat → type → Back → Quick\n * Chat finds the draft.\n */\n readonly kept?: readonly CanvasHistoryEntry[] | undefined;\n /**\n * Where Forward goes (newest-to-visit LAST): every step Back left, in order.\n * A navigate to anything else clears it, as in a browser. Absent = no Forward.\n */\n readonly forward?: readonly CanvasHistoryEntry[] | undefined;\n /**\n * The mounted body's identity. Minted when the item is created and kept by\n * `rekey`, so a draft that receives its durable id keeps its live body.\n * Absent on items saved before 0.5.0 (the item id stands in).\n */\n readonly instance?: string | undefined;\n}\n\nexport interface CanvasPane {\n readonly id: CanvasPaneId;\n readonly itemIds: readonly CanvasItemId[];\n readonly activeItemId: CanvasItemId | null;\n}\n\n/** \"horizontal\" = children side by side; \"vertical\" = children stacked. */\nexport type CanvasOrientation = \"horizontal\" | \"vertical\";\n\nexport type CanvasLayoutNode =\n | { readonly type: \"pane\"; readonly paneId: CanvasPaneId }\n | {\n readonly type: \"split\";\n readonly id: CanvasSplitId;\n readonly orientation: CanvasOrientation;\n readonly children: readonly CanvasLayoutNode[];\n /** Fractions, one per child, summing to 1. */\n readonly sizes: readonly number[];\n };\n\n/**\n * What one window shows: its column's visibility, full screen, width and its\n * own tree of panes. Panes and items are shared across windows (ids are\n * global), so moving a tab between windows is an ordinary move.\n */\nexport interface CanvasWindowFrame {\n readonly isOpen: boolean;\n /**\n * \"Expanded\": the column fills everything the HOST gives it (the web: the\n * whole window; the desktop: everything right of the sidebar). One flag —\n * the host's placement decides what \"everything\" is.\n */\n readonly isFullscreen: boolean;\n /** Column width in CSS pixels; null until the person drags it — the host's layout rule decides. */\n readonly width: number | null;\n readonly layout: CanvasLayoutNode;\n readonly focusedPaneId: CanvasPaneId;\n}\n\n/** A window other than the main one. */\nexport interface CanvasExtraWindow extends CanvasWindowFrame {\n readonly id: CanvasWindowId;\n /**\n * \"window\": another app window with its own column.\n * \"pop-out\": a window holding tabs popped out of `home`; \"Dock back\" returns them there.\n */\n readonly role: \"window\" | \"pop-out\";\n /** Where this window's tabs go when it closes or a tab docks back. */\n readonly home: CanvasWindowId;\n}\n\n/**\n * The whole canvas. The top-level frame fields ARE the main window's frame, so\n * a single-window host reads `state.isOpen`, `state.layout`… exactly as before;\n * every other window lives in `windows`.\n */\nexport interface CanvasState extends CanvasWindowFrame {\n readonly version: 1;\n /** Windows other than the main one. Empty for single-window hosts. Never restored after a reload. */\n readonly windows: { readonly [windowId: string]: CanvasExtraWindow };\n readonly panes: { readonly [paneId: string]: CanvasPane };\n readonly items: { readonly [itemId: string]: CanvasItem };\n /** Monotonic counter for minting pane/split ids — keeps the reducer pure. */\n readonly seq: number;\n /** True once a persisted snapshot was applied (or there was none). */\n readonly hydrated: boolean;\n}\n\n/** Where a newly opened item goes. Existing items never move on open. */\nexport type CanvasOpenTarget =\n | \"focused\"\n | \"split-right\"\n | \"split-down\"\n | { readonly paneId: CanvasPaneId };\n\n/** Where a NEW item of a kind prefers to open while the canvas already shows something. */\nexport type CanvasPreferredTarget = \"focused\" | \"split-right\" | \"split-down\";\n\n/** What a tab navigates to in place. */\nexport interface CanvasNavigateInput {\n readonly kind: string;\n readonly key: string;\n readonly title?: string | null | undefined;\n readonly data?: CanvasJson | undefined;\n}\n\nexport interface CanvasOpenInput {\n readonly kind: string;\n /** Which window a NEW item opens in. Default: the controller's window (main). An existing item stays where it is. */\n readonly windowId?: CanvasWindowId | undefined;\n readonly key: string;\n readonly title?: string | null | undefined;\n readonly data?: CanvasJson | undefined;\n readonly target?: CanvasOpenTarget | undefined;\n /** Reveal the canvas when it is put away. Default true. */\n readonly reveal?: boolean | undefined;\n /** Make the item the pane's active tab. Default true. */\n readonly activate?: boolean | undefined;\n}\n\nexport const CANVAS_MIN_WIDTH = 360;\nexport const CANVAS_DEFAULT_WIDTH = 640;\nexport const CANVAS_MIN_SPLIT_FRACTION = 0.12;\n\n/** A rectangle in window CSS pixels (getBoundingClientRect coordinates). */\nexport interface CanvasRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n","import type { CanvasItemId, CanvasJson, CanvasPaneId, CanvasSplitId, CanvasWindowId } from \"./types\";\n\nconst SEP = \"::\";\n\nexport function canvasItemId(kind: string, key: string): CanvasItemId {\n return `${kind}${SEP}${key}` as CanvasItemId;\n}\n\nexport function parseCanvasItemId(id: CanvasItemId): { kind: string; key: string } {\n const at = id.indexOf(SEP);\n return at < 0 ? { kind: id, key: \"\" } : { kind: id.slice(0, at), key: id.slice(at + SEP.length) };\n}\n\nexport function paneIdFromSeq(seq: number): CanvasPaneId {\n return `pane-${seq}` as CanvasPaneId;\n}\n\nexport function splitIdFromSeq(seq: number): CanvasSplitId {\n return `split-${seq}` as CanvasSplitId;\n}\n\n/**\n * Returns the path of the first value that is NOT plain JSON, or null when the\n * whole value is JSON. Functions, class instances, Dates, Maps, NaN and\n * Infinity all fail — they would silently vanish or change on persist.\n */\nexport function findNonJson(value: unknown, path = \"data\"): string | null {\n if (value === null) return null;\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return null;\n case \"number\":\n return Number.isFinite(value) ? null : path;\n case \"object\": {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const bad = findNonJson(value[i], `${path}[${i}]`);\n if (bad) return bad;\n }\n return null;\n }\n const proto = Object.getPrototypeOf(value) as unknown;\n if (proto !== Object.prototype && proto !== null) return path;\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (v === undefined) continue;\n const bad = findNonJson(v, `${path}.${k}`);\n if (bad) return bad;\n }\n return null;\n }\n default:\n return path;\n }\n}\n\nexport function isCanvasJson(value: unknown): value is CanvasJson {\n return findNonJson(value) === null;\n}\n\n/** Brands a host's window id. `CANVAS_MAIN_WINDOW` is the default window. */\nexport function canvasWindowId(id: string): CanvasWindowId {\n return id as CanvasWindowId;\n}\n","/**\n * Pure helpers over the canvas layout tree. Every function returns a new tree\n * and never mutates its input.\n */\n\nimport {\n CANVAS_MIN_SPLIT_FRACTION,\n type CanvasLayoutNode,\n type CanvasOrientation,\n type CanvasPaneId,\n type CanvasSplitId,\n} from \"./types\";\n\nexport function listPaneIds(node: CanvasLayoutNode): CanvasPaneId[] {\n if (node.type === \"pane\") return [node.paneId];\n return node.children.flatMap(listPaneIds);\n}\n\nexport function containsPane(node: CanvasLayoutNode, paneId: CanvasPaneId): boolean {\n if (node.type === \"pane\") return node.paneId === paneId;\n return node.children.some((child) => containsPane(child, paneId));\n}\n\nfunction evenSizes(count: number): number[] {\n return Array.from({ length: count }, () => 1 / count);\n}\n\n/** Renormalizes to sum 1; falls back to even sizes for garbage input. */\nexport function normalizeSizes(sizes: readonly number[], count: number): number[] {\n if (sizes.length !== count || sizes.some((s) => !Number.isFinite(s) || s <= 0)) {\n return evenSizes(count);\n }\n const total = sizes.reduce((sum, s) => sum + s, 0);\n return sizes.map((s) => s / total);\n}\n\n/**\n * Places `newPaneId` beside `paneId`. When the pane's parent already splits in\n * the same orientation the new pane becomes a sibling (sharing the pane's\n * space); otherwise the pane is replaced by a new two-way split.\n */\nexport function splitPane(\n node: CanvasLayoutNode,\n paneId: CanvasPaneId,\n newPaneId: CanvasPaneId,\n orientation: CanvasOrientation,\n newSplitId: CanvasSplitId,\n /** The existing pane's share of the space it gives up (0.7 = the 70/30 divider). */\n firstShare = 0.5,\n): CanvasLayoutNode {\n const first = Number.isFinite(firstShare) ? Math.min(1 - CANVAS_MIN_SPLIT_FRACTION, Math.max(CANVAS_MIN_SPLIT_FRACTION, firstShare)) : 0.5;\n if (node.type === \"pane\") {\n if (node.paneId !== paneId) return node;\n return {\n type: \"split\",\n id: newSplitId,\n orientation,\n children: [node, { type: \"pane\", paneId: newPaneId }],\n sizes: [first, 1 - first],\n };\n }\n const index = node.children.findIndex(\n (child) => child.type === \"pane\" && child.paneId === paneId,\n );\n if (index >= 0 && node.orientation === orientation) {\n const share = node.sizes[index] ?? 1 / node.children.length;\n const children = [...node.children];\n children.splice(index + 1, 0, { type: \"pane\", paneId: newPaneId });\n const sizes = [...node.sizes];\n sizes.splice(index, 1, share * first, share * (1 - first));\n return { ...node, children, sizes: normalizeSizes(sizes, children.length) };\n }\n return {\n ...node,\n children: node.children.map((child) =>\n splitPane(child, paneId, newPaneId, orientation, newSplitId, first),\n ),\n };\n}\n\n/**\n * Removes a pane. A split left with one child collapses into that child, and\n * the removed pane's space goes to its siblings proportionally. Returns null\n * when the tree held only that pane.\n */\nexport function removePane(\n node: CanvasLayoutNode,\n paneId: CanvasPaneId,\n): CanvasLayoutNode | null {\n if (node.type === \"pane\") return node.paneId === paneId ? null : node;\n const children: CanvasLayoutNode[] = [];\n const sizes: number[] = [];\n node.children.forEach((child, i) => {\n const next = removePane(child, paneId);\n if (next) {\n children.push(next);\n sizes.push(node.sizes[i] ?? 1 / node.children.length);\n }\n });\n if (children.length === 0) return null;\n if (children.length === 1) return children[0] ?? null;\n return { ...node, children, sizes: normalizeSizes(sizes, children.length) };\n}\n\nexport function containsSplit(node: CanvasLayoutNode, splitId: CanvasSplitId): boolean {\n if (node.type === \"pane\") return false;\n return node.id === splitId || node.children.some((child) => containsSplit(child, splitId));\n}\n\nexport function resizeSplit(\n node: CanvasLayoutNode,\n splitId: CanvasSplitId,\n sizes: readonly number[],\n): CanvasLayoutNode {\n if (node.type === \"pane\") return node;\n if (node.id === splitId) {\n const clamped = sizes.map((s) => Math.max(CANVAS_MIN_SPLIT_FRACTION, s));\n return { ...node, sizes: normalizeSizes(clamped, node.children.length) };\n }\n return {\n ...node,\n children: node.children.map((child) => resizeSplit(child, splitId, sizes)),\n };\n}\n\n/** True when the tree is well formed against the set of known panes. */\nexport function isValidLayout(\n node: unknown,\n knownPanes: ReadonlySet<string>,\n seen: Set<string> = new Set(),\n): node is CanvasLayoutNode {\n if (!node || typeof node !== \"object\") return false;\n const n = node as Record<string, unknown>;\n if (n.type === \"pane\") {\n const id = n.paneId;\n if (typeof id !== \"string\" || !knownPanes.has(id) || seen.has(id)) return false;\n seen.add(id);\n return true;\n }\n if (n.type !== \"split\") return false;\n if (typeof n.id !== \"string\") return false;\n if (n.orientation !== \"horizontal\" && n.orientation !== \"vertical\") return false;\n if (!Array.isArray(n.children) || n.children.length < 2) return false;\n if (!Array.isArray(n.sizes) || n.sizes.length !== n.children.length) return false;\n return n.children.every((child) => isValidLayout(child, knownPanes, seen));\n}\n","/**\n * THE canvas reducer. Plain Redux-compatible reducer + action creators with no\n * Redux Toolkit dependency, so it mounts in a host's RTK store\n * (`canvasHost: canvasReducer`), runs inside the package's own standalone\n * store, or runs in a desktop main process behind IPC — identical behaviour.\n *\n * Identity law: an item is `kind::key`. Opening an item that is already on the\n * canvas never duplicates it — it refreshes its data/title, activates its tab\n * and focuses its pane, wherever that pane is (in whichever window).\n *\n * Windows: the top-level frame fields are the MAIN window's; every other window\n * (a second app window, a popped-out tab) lives in `state.windows`. Panes and\n * items are global, so a tab moves between windows like between panes.\n */\n\nimport { canvasItemId, paneIdFromSeq, splitIdFromSeq } from \"./ids\";\nimport { containsPane, containsSplit, isValidLayout, listPaneIds, normalizeSizes, removePane, resizeSplit, splitPane } from \"./layout\";\nimport {\n CANVAS_HISTORY_LIMIT,\n CANVAS_KEEP_ALIVE_DEPTH,\n CANVAS_LAUNCHER_KIND,\n CANVAS_MAIN_WINDOW,\n CANVAS_MIN_WIDTH,\n type CanvasExtraWindow,\n type CanvasHistoryEntry,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasLayoutNode,\n type CanvasNavigateInput,\n type CanvasOpenInput,\n type CanvasOrientation,\n type CanvasPane,\n type CanvasPaneId,\n type CanvasSplitId,\n type CanvasState,\n type CanvasWindowFrame,\n type CanvasWindowId,\n} from \"./types\";\n\nconst P = \"matrxCanvas/\";\n\n/** What happens to a closing window's tabs: back to its home window, or closed with it. */\nexport type CanvasWindowCloseMode = \"dock\" | \"close\";\n\nexport type CanvasAction =\n | { type: `${typeof P}open`; payload: CanvasOpenInput & { now: number; splitShare?: number | undefined } }\n | { type: `${typeof P}update`; payload: { itemId: CanvasItemId; data?: CanvasJson | undefined; title?: string | null | undefined; now: number } }\n | { type: `${typeof P}rekey`; payload: { itemId: CanvasItemId; key: string } }\n | { type: `${typeof P}navigate`; payload: { itemId: CanvasItemId; to: CanvasNavigateInput; now: number } }\n | { type: `${typeof P}back`; payload: { itemId: CanvasItemId; now: number } }\n | { type: `${typeof P}forward`; payload: { itemId: CanvasItemId; now: number } }\n | { type: `${typeof P}closeItem`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}closeOthers`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}activate`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}focusPane`; payload: { paneId: CanvasPaneId } }\n | { type: `${typeof P}moveItem`; payload: { itemId: CanvasItemId; toPaneId: CanvasPaneId; index?: number | undefined } }\n | { type: `${typeof P}splitPane`; payload: { paneId: CanvasPaneId; orientation: CanvasOrientation; moveItemId?: CanvasItemId | undefined; share?: number | undefined } }\n | { type: `${typeof P}closePane`; payload: { paneId: CanvasPaneId } }\n | { type: `${typeof P}resizeSplit`; payload: { splitId: CanvasSplitId; sizes: readonly number[] } }\n | { type: `${typeof P}setOpen`; payload: { open: boolean; windowId?: CanvasWindowId | undefined } }\n | { type: `${typeof P}toggle`; payload?: { windowId?: CanvasWindowId | undefined } | undefined }\n | { type: `${typeof P}setFullscreen`; payload: { fullscreen: boolean; windowId?: CanvasWindowId | undefined } }\n | { type: `${typeof P}setWidth`; payload: { width: number; windowId?: CanvasWindowId | undefined } }\n | { type: `${typeof P}popOut`; payload: { itemId: CanvasItemId; windowId: CanvasWindowId } }\n | { type: `${typeof P}dockBack`; payload: { itemId: CanvasItemId } }\n | { type: `${typeof P}closeWindow`; payload: { windowId: CanvasWindowId; mode: CanvasWindowCloseMode } }\n | { type: `${typeof P}hydrate`; payload: { snapshot: CanvasState | null } }\n | { type: `${typeof P}reset` };\n\nconst win = (windowId: CanvasWindowId | undefined) => (windowId && windowId !== CANVAS_MAIN_WINDOW ? { windowId } : {});\n\nexport const canvasActions = {\n open: (input: CanvasOpenInput, options?: { splitShare?: number | undefined }): CanvasAction => ({\n type: `${P}open`,\n payload: { ...input, now: Date.now(), ...(options?.splitShare !== undefined ? { splitShare: options.splitShare } : {}) },\n }),\n update: (itemId: CanvasItemId, patch: { data?: CanvasJson | undefined; title?: string | null | undefined }): CanvasAction => ({\n type: `${P}update`,\n payload: { itemId, ...patch, now: Date.now() },\n }),\n /** Gives an item a new identity in place (e.g. a draft that was just saved and now has an id). */\n rekey: (itemId: CanvasItemId, key: string): CanvasAction => ({ type: `${P}rekey`, payload: { itemId, key } }),\n /** Replaces a tab's content with another item in place, remembering what it showed (Back returns). */\n navigate: (itemId: CanvasItemId, to: CanvasNavigateInput): CanvasAction => ({ type: `${P}navigate`, payload: { itemId, to, now: Date.now() } }),\n /** Returns a tab to what it showed before its last navigate. */\n back: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}back`, payload: { itemId, now: Date.now() } }),\n /** Re-does the last Back (the step Back left), with that step's live body. */\n forward: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}forward`, payload: { itemId, now: Date.now() } }),\n closeItem: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}closeItem`, payload: { itemId } }),\n closeOthers: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}closeOthers`, payload: { itemId } }),\n activate: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}activate`, payload: { itemId } }),\n focusPane: (paneId: CanvasPaneId): CanvasAction => ({ type: `${P}focusPane`, payload: { paneId } }),\n moveItem: (itemId: CanvasItemId, toPaneId: CanvasPaneId, index?: number): CanvasAction => ({\n type: `${P}moveItem`,\n payload: { itemId, toPaneId, index },\n }),\n /** `share` = the existing pane's fraction of the space (layout rules' stackSplit / sideSplit). */\n splitPane: (paneId: CanvasPaneId, orientation: CanvasOrientation, moveItemId?: CanvasItemId, share?: number): CanvasAction => ({\n type: `${P}splitPane`,\n payload: { paneId, orientation, moveItemId, ...(share !== undefined ? { share } : {}) },\n }),\n closePane: (paneId: CanvasPaneId): CanvasAction => ({ type: `${P}closePane`, payload: { paneId } }),\n resizeSplit: (splitId: CanvasSplitId, sizes: readonly number[]): CanvasAction => ({\n type: `${P}resizeSplit`,\n payload: { splitId, sizes },\n }),\n setOpen: (open: boolean, windowId?: CanvasWindowId): CanvasAction => ({ type: `${P}setOpen`, payload: { open, ...win(windowId) } }),\n toggle: (windowId?: CanvasWindowId): CanvasAction =>\n windowId && windowId !== CANVAS_MAIN_WINDOW ? { type: `${P}toggle`, payload: { windowId } } : { type: `${P}toggle` },\n setFullscreen: (fullscreen: boolean, windowId?: CanvasWindowId): CanvasAction => ({\n type: `${P}setFullscreen`,\n payload: { fullscreen, ...win(windowId) },\n }),\n setWidth: (width: number, windowId?: CanvasWindowId): CanvasAction => ({ type: `${P}setWidth`, payload: { width, ...win(windowId) } }),\n /** Moves a tab into its own pop-out window `windowId` (made by the host's popOut port). */\n popOut: (itemId: CanvasItemId, windowId: CanvasWindowId): CanvasAction => ({ type: `${P}popOut`, payload: { itemId, windowId } }),\n /** Returns a popped-out tab to the window it came from. */\n dockBack: (itemId: CanvasItemId): CanvasAction => ({ type: `${P}dockBack`, payload: { itemId } }),\n /** A host window closed: its tabs dock home (default) or close with it. The main window never closes. */\n closeWindow: (windowId: CanvasWindowId, mode: CanvasWindowCloseMode = \"dock\"): CanvasAction => ({\n type: `${P}closeWindow`,\n payload: { windowId, mode },\n }),\n hydrate: (snapshot: CanvasState | null): CanvasAction => ({ type: `${P}hydrate`, payload: { snapshot } }),\n reset: (): CanvasAction => ({ type: `${P}reset` }),\n} as const;\n\nexport function isCanvasAction(action: unknown): action is CanvasAction {\n return (\n !!action &&\n typeof action === \"object\" &&\n typeof (action as { type?: unknown }).type === \"string\" &&\n (action as { type: string }).type.startsWith(P)\n );\n}\n\nexport function createInitialCanvasState(): CanvasState {\n const paneId = paneIdFromSeq(1);\n return {\n version: 1,\n isOpen: false,\n isFullscreen: false,\n width: null,\n layout: { type: \"pane\", paneId },\n focusedPaneId: paneId,\n windows: {},\n panes: { [paneId]: { id: paneId, itemIds: [], activeItemId: null } },\n items: {},\n seq: 1,\n hydrated: false,\n };\n}\n\n// ── window helpers ─────────────────────────────────────────────────────────\n\n/** Every window id, main first. */\nexport function listCanvasWindowIds(state: CanvasState): CanvasWindowId[] {\n return [CANVAS_MAIN_WINDOW, ...(Object.keys(state.windows ?? {}) as CanvasWindowId[])];\n}\n\n/** A window's frame, or null when that window does not exist. */\nexport function canvasWindowFrame(state: CanvasState, windowId: CanvasWindowId = CANVAS_MAIN_WINDOW): CanvasWindowFrame | null {\n return windowId === CANVAS_MAIN_WINDOW ? state : (state.windows?.[windowId] ?? null);\n}\n\n/** The window whose layout holds this pane. */\nexport function canvasWindowOfPane(state: CanvasState, paneId: CanvasPaneId): CanvasWindowId | null {\n for (const id of listCanvasWindowIds(state)) {\n const frame = canvasWindowFrame(state, id);\n if (frame && containsPane(frame.layout, paneId)) return id;\n }\n return null;\n}\n\n/** The window an item is in right now (null when it is not on the canvas). */\nexport function canvasWindowOfItem(state: CanvasState, itemId: CanvasItemId): CanvasWindowId | null {\n const pane = paneOf(state, itemId);\n return pane ? canvasWindowOfPane(state, pane.id) : null;\n}\n\ntype FramePatch = { -readonly [K in keyof CanvasWindowFrame]?: CanvasWindowFrame[K] };\n\nfunction withFrame(state: CanvasState, windowId: CanvasWindowId, patch: FramePatch): CanvasState {\n if (windowId === CANVAS_MAIN_WINDOW) return { ...state, ...patch };\n const current = state.windows[windowId];\n if (!current) return state;\n return { ...state, windows: { ...state.windows, [windowId]: { ...current, ...patch } } };\n}\n\n/** A non-main window comes into being the first time something targets it. */\nfunction ensureWindow(state: CanvasState, windowId: CanvasWindowId, role: CanvasExtraWindow[\"role\"] = \"window\", home: CanvasWindowId = CANVAS_MAIN_WINDOW): CanvasState {\n if (windowId === CANVAS_MAIN_WINDOW || state.windows[windowId]) return state;\n const seq = state.seq + 1;\n const paneId = paneIdFromSeq(seq);\n const frame: CanvasExtraWindow = {\n id: windowId,\n role,\n home,\n isOpen: false,\n isFullscreen: false,\n width: null,\n layout: { type: \"pane\", paneId },\n focusedPaneId: paneId,\n };\n return {\n ...state,\n seq,\n panes: { ...state.panes, [paneId]: { id: paneId, itemIds: [], activeItemId: null } },\n windows: { ...state.windows, [windowId]: frame },\n };\n}\n\nfunction removeWindow(state: CanvasState, windowId: CanvasWindowId): CanvasState {\n const frame = state.windows[windowId];\n if (!frame) return state;\n const panes = { ...state.panes };\n for (const paneId of listPaneIds(frame.layout)) delete panes[paneId];\n const windows = { ...state.windows };\n delete windows[windowId];\n return { ...state, panes, windows };\n}\n\nfunction windowItemIds(state: CanvasState, windowId: CanvasWindowId): CanvasItemId[] {\n const frame = canvasWindowFrame(state, windowId);\n if (!frame) return [];\n return listPaneIds(frame.layout).flatMap((paneId) => state.panes[paneId]?.itemIds ?? []);\n}\n\n/** A pop-out window left with no tabs has nothing to show and goes away. */\nfunction dropEmptyPopOut(state: CanvasState, windowId: CanvasWindowId | null): CanvasState {\n if (!windowId || windowId === CANVAS_MAIN_WINDOW) return state;\n const frame = state.windows[windowId];\n if (!frame || frame.role !== \"pop-out\" || windowItemIds(state, windowId).length > 0) return state;\n return removeWindow(state, windowId);\n}\n\n// ── pane helpers ───────────────────────────────────────────────────────────\n\nfunction paneOf(state: CanvasState, itemId: CanvasItemId): CanvasPane | null {\n for (const pane of Object.values(state.panes)) {\n if (pane.itemIds.includes(itemId)) return pane;\n }\n return null;\n}\n\nfunction withPane(state: CanvasState, pane: CanvasPane): CanvasState {\n return { ...state, panes: { ...state.panes, [pane.id]: pane } };\n}\n\nfunction focus(state: CanvasState, paneId: CanvasPaneId): CanvasState {\n const windowId = canvasWindowOfPane(state, paneId);\n return windowId ? withFrame(state, windowId, { focusedPaneId: paneId }) : state;\n}\n\n/** After removing `itemId` from a tab list, the neighbour that takes focus. */\nfunction nextActive(itemIds: readonly CanvasItemId[], removed: CanvasItemId, current: CanvasItemId | null): CanvasItemId | null {\n if (current !== removed) return current;\n const index = itemIds.indexOf(removed);\n const rest = itemIds.filter((id) => id !== removed);\n return rest[Math.min(index, rest.length - 1)] ?? null;\n}\n\nfunction detachItem(state: CanvasState, itemId: CanvasItemId): CanvasState {\n const pane = paneOf(state, itemId);\n if (!pane) return state;\n return withPane(state, {\n ...pane,\n itemIds: pane.itemIds.filter((id) => id !== itemId),\n activeItemId: nextActive(pane.itemIds, itemId, pane.activeItemId),\n });\n}\n\nfunction dropPane(state: CanvasState, paneId: CanvasPaneId): CanvasState {\n const windowId = canvasWindowOfPane(state, paneId);\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!windowId || !frame) return state;\n const layout = removePane(frame.layout, paneId);\n if (!layout) return state; // never remove a window's last pane\n const panes = { ...state.panes };\n delete panes[paneId];\n const focusedPaneId = frame.focusedPaneId === paneId ? (listPaneIds(layout)[0] ?? frame.focusedPaneId) : frame.focusedPaneId;\n return withFrame({ ...state, panes }, windowId, { layout, focusedPaneId });\n}\n\nfunction addSplit(\n state: CanvasState,\n paneId: CanvasPaneId,\n orientation: CanvasOrientation,\n share: number | undefined,\n): { state: CanvasState; newPaneId: CanvasPaneId } | null {\n const windowId = canvasWindowOfPane(state, paneId);\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!windowId || !frame) return null;\n const seq = state.seq + 1;\n const newPaneId = paneIdFromSeq(seq);\n const layout = splitPane(frame.layout, paneId, newPaneId, orientation, splitIdFromSeq(seq), share ?? 0.5);\n const next = withFrame(\n { ...state, seq, panes: { ...state.panes, [newPaneId]: { id: newPaneId, itemIds: [], activeItemId: null } } },\n windowId,\n { layout, focusedPaneId: newPaneId },\n );\n return { newPaneId, state: next };\n}\n\nfunction insertInto(state: CanvasState, paneId: CanvasPaneId, itemId: CanvasItemId, activate: boolean, index?: number): CanvasState {\n const pane = state.panes[paneId];\n if (!pane) return state;\n const itemIds = [...pane.itemIds.filter((id) => id !== itemId)];\n const at = index === undefined ? afterActive(itemIds, pane.activeItemId) : Math.max(0, Math.min(index, itemIds.length));\n itemIds.splice(at, 0, itemId);\n return withPane(state, {\n ...pane,\n itemIds,\n activeItemId: activate || pane.activeItemId === null ? itemId : pane.activeItemId,\n });\n}\n\n/** New tabs open right after the active tab, the way browsers do it. */\nfunction afterActive(itemIds: readonly CanvasItemId[], active: CanvasItemId | null): number {\n const index = active ? itemIds.indexOf(active) : -1;\n return index < 0 ? itemIds.length : index + 1;\n}\n\n/** Moves one item into another window's focused pane (docking, folding). */\nfunction sendHome(state: CanvasState, itemId: CanvasItemId, home: CanvasWindowId, activate: boolean): CanvasState {\n const homeFrame = canvasWindowFrame(state, home) ?? state;\n const target = canvasWindowFrame(state, home) ? home : CANVAS_MAIN_WINDOW;\n let next = detachItem(state, itemId);\n next = insertInto(next, homeFrame.focusedPaneId, itemId, activate);\n return activate ? withFrame(next, target, { focusedPaneId: homeFrame.focusedPaneId }) : next;\n}\n\n/** A new item. `instance` names its mounted body for as long as the item lives (rekey keeps it). */\nfunction newItem(\n kind: string,\n key: string,\n title: string | null,\n data: CanvasJson,\n now: number,\n steps?: {\n readonly history?: readonly CanvasHistoryEntry[];\n readonly kept?: readonly CanvasHistoryEntry[];\n readonly forward?: readonly CanvasHistoryEntry[];\n readonly instance?: string | undefined;\n },\n): CanvasItem {\n const id = canvasItemId(kind, key);\n const history = steps?.history ?? [];\n const kept = steps?.kept ?? [];\n const forward = steps?.forward ?? [];\n return {\n id,\n kind,\n key,\n title,\n data,\n openedAt: now,\n updatedAt: now,\n // A reused instance is the SAME live body coming back (Back, or returning to a kept step).\n instance: steps?.instance ?? `${now.toString(36)}:${id}`,\n ...(history.length > 0 ? { history: history.slice(-CANVAS_HISTORY_LIMIT) } : {}),\n ...(kept.length > 0 ? { kept: kept.slice(-CANVAS_KEEP_ALIVE_DEPTH) } : {}),\n ...(forward.length > 0 ? { forward: forward.slice(-CANVAS_HISTORY_LIMIT) } : {}),\n };\n}\n\nfunction historyEntry(item: CanvasItem): CanvasHistoryEntry {\n return { kind: item.kind, key: item.key, title: item.title, data: item.data, ...(item.instance ? { instance: item.instance } : {}) };\n}\n\n/**\n * Puts `next` where `current` is (same pane, same position, same active state)\n * and drops `current`. Both identities must differ and `next` must be absent.\n */\nfunction replaceInPlace(state: CanvasState, current: CanvasItem, next: CanvasItem): CanvasState {\n const pane = paneOf(state, current.id);\n if (!pane) return state;\n const items = { ...state.items, [next.id]: next };\n delete items[current.id];\n const withItems: CanvasState = { ...state, items };\n const replaced = withPane(withItems, {\n ...pane,\n itemIds: pane.itemIds.map((id) => (id === current.id ? next.id : id)),\n activeItemId: pane.activeItemId === current.id ? next.id : pane.activeItemId,\n });\n return focus(replaced, pane.id);\n}\n\n/** Focuses an existing item wherever it is and reveals its window. */\nfunction focusExisting(state: CanvasState, itemId: CanvasItemId): CanvasState {\n const pane = paneOf(state, itemId);\n if (!pane) return state;\n const next = focus(withPane(state, { ...pane, activeItemId: itemId }), pane.id);\n const windowId = canvasWindowOfPane(next, pane.id);\n return windowId ? withFrame(next, windowId, { isOpen: true }) : next;\n}\n\nfunction sanitizeHistory(raw: unknown): CanvasHistoryEntry[] {\n if (!Array.isArray(raw)) return [];\n const out: CanvasHistoryEntry[] = [];\n for (const entry of raw as unknown[]) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Partial<CanvasHistoryEntry>;\n if (typeof e.kind !== \"string\" || typeof e.key !== \"string\") continue;\n out.push({\n kind: e.kind,\n key: e.key,\n title: typeof e.title === \"string\" ? e.title : null,\n data: e.data ?? null,\n ...(typeof e.instance === \"string\" && e.instance ? { instance: e.instance } : {}),\n });\n }\n return out.slice(-CANVAS_HISTORY_LIMIT);\n}\n\n/** A saved item with only the fields this version understands, history validated. */\nfunction sanitizeItem(item: CanvasItem): CanvasItem {\n const history = sanitizeHistory((item as { history?: unknown }).history);\n const kept = sanitizeHistory((item as { kept?: unknown }).kept).slice(-CANVAS_KEEP_ALIVE_DEPTH);\n const forward = sanitizeHistory((item as { forward?: unknown }).forward);\n const { history: _history, kept: _kept, forward: _forward, instance, ...rest } = item;\n return {\n ...rest,\n ...(typeof instance === \"string\" && instance ? { instance } : {}),\n ...(history.length > 0 ? { history } : {}),\n ...(kept.length > 0 ? { kept } : {}),\n ...(forward.length > 0 ? { forward } : {}),\n };\n}\n\nfunction clampWidth(width: number): number | null {\n return Number.isFinite(width) ? Math.max(CANVAS_MIN_WIDTH, Math.round(width)) : null;\n}\n\n// ── memory ─────────────────────────────────────────────────────────────────\n\n/**\n * Every window but the main one is a session thing: its tabs come home to the\n * main window's focused pane (nothing is lost) and the window goes away. Used\n * for what is saved and for what is restored.\n */\nexport function foldCanvasWindows(state: CanvasState): CanvasState {\n const extra = Object.keys(state.windows ?? {}) as CanvasWindowId[];\n if (extra.length === 0) return state.windows ? state : { ...state, windows: {} };\n let next = state;\n for (const windowId of extra) {\n for (const itemId of windowItemIds(next, windowId)) next = sendHome(next, itemId, CANVAS_MAIN_WINDOW, false);\n next = removeWindow(next, windowId);\n }\n return next;\n}\n\n/**\n * Validates a persisted snapshot. Anything malformed is dropped back to the\n * initial state rather than half-applied — a corrupt layout must never crash\n * the shell. Extra windows are folded home; full screen never comes back.\n */\nexport function sanitizeCanvasSnapshot(raw: unknown): CanvasState | null {\n if (!raw || typeof raw !== \"object\") return null;\n const s = raw as Partial<CanvasState> & { windows?: unknown };\n if (s.version !== 1 || !s.panes || typeof s.panes !== \"object\" || !s.items || typeof s.items !== \"object\" || !s.layout) return null;\n const paneIds = new Set(Object.keys(s.panes));\n const seen = new Set<string>();\n if (!isValidLayout(s.layout, paneIds, seen)) return null;\n\n // Extra windows: each must be a well-formed frame over panes nobody else uses.\n const windows: Record<string, CanvasExtraWindow> = {};\n if (s.windows && typeof s.windows === \"object\") {\n for (const [id, value] of Object.entries(s.windows as Record<string, unknown>)) {\n if (!value || typeof value !== \"object\" || id === CANVAS_MAIN_WINDOW) continue;\n const w = value as Partial<CanvasExtraWindow>;\n const claimed = new Set(seen);\n if (!isValidLayout(w.layout, paneIds, claimed)) continue;\n for (const pane of claimed) seen.add(pane);\n const layoutPanes = listPaneIds(w.layout);\n const focused = w.focusedPaneId && layoutPanes.includes(w.focusedPaneId) ? w.focusedPaneId : layoutPanes[0];\n if (!focused) continue;\n windows[id] = {\n id: id as CanvasWindowId,\n role: w.role === \"pop-out\" ? \"pop-out\" : \"window\",\n home: typeof w.home === \"string\" ? (w.home as CanvasWindowId) : CANVAS_MAIN_WINDOW,\n isOpen: w.isOpen === true,\n isFullscreen: false,\n width: typeof w.width === \"number\" ? clampWidth(w.width) : null,\n layout: normalizeLayout(w.layout),\n focusedPaneId: focused,\n };\n }\n }\n // Every pane must belong to exactly one window's layout.\n if (seen.size !== paneIds.size) return null;\n\n const items: Record<string, CanvasItem> = {};\n for (const [id, item] of Object.entries(s.items)) {\n if (item && typeof item.kind === \"string\" && typeof item.key === \"string\" && canvasItemId(item.kind, item.key) === id) {\n items[id] = sanitizeItem(item);\n }\n }\n const placed = new Set<string>();\n const panes: Record<string, CanvasPane> = {};\n for (const [id, pane] of Object.entries(s.panes)) {\n const itemIds = (Array.isArray(pane.itemIds) ? pane.itemIds : []).filter((itemId) => itemId in items && !placed.has(itemId));\n for (const itemId of itemIds) placed.add(itemId);\n const activeItemId = pane.activeItemId && itemIds.includes(pane.activeItemId) ? pane.activeItemId : (itemIds[0] ?? null);\n panes[id] = { id: id as CanvasPaneId, itemIds, activeItemId };\n }\n const mainPanes = listPaneIds(s.layout);\n const focused = s.focusedPaneId && mainPanes.includes(s.focusedPaneId) ? s.focusedPaneId : mainPanes[0];\n if (!focused) return null;\n const layout = normalizeLayout(s.layout);\n // seq must stay ahead of every id already minted, or the next split collides.\n const highest = Math.max(highestIdNumber(layout), ...Object.values(windows).map((w) => highestIdNumber(w.layout)));\n const seq = Math.max(typeof s.seq === \"number\" && Number.isFinite(s.seq) ? s.seq : 0, highest);\n let state: CanvasState = {\n version: 1,\n isOpen: s.isOpen === true,\n // Full screen is a moment, not a preference: a reload never starts there.\n isFullscreen: false,\n width: typeof s.width === \"number\" ? clampWidth(s.width) : null,\n layout,\n focusedPaneId: focused,\n windows,\n panes,\n items,\n seq,\n hydrated: true,\n };\n state = foldCanvasWindows(state);\n // An item that lost its pane is put back where it can be seen, never kept invisible.\n for (const id of Object.keys(items) as CanvasItemId[]) {\n if (!placed.has(id)) state = insertInto(state, state.focusedPaneId, id, false);\n }\n return state;\n}\n\nfunction normalizeLayout(node: CanvasLayoutNode): CanvasLayoutNode {\n if (node.type === \"pane\") return node;\n return { ...node, sizes: normalizeSizes(node.sizes, node.children.length), children: node.children.map(normalizeLayout) };\n}\n\nfunction highestIdNumber(node: CanvasLayoutNode): number {\n const own = Number((node.type === \"pane\" ? node.paneId : node.id).split(\"-\").pop());\n const mine = Number.isFinite(own) ? own : 0;\n return node.type === \"pane\" ? mine : Math.max(mine, ...node.children.map(highestIdNumber));\n}\n\n// ── reducer ────────────────────────────────────────────────────────────────\n\nexport function canvasReducer(state: CanvasState = createInitialCanvasState(), action: { type: string }): CanvasState {\n if (!isCanvasAction(action)) return state;\n // A state saved before windows existed carries no `windows` map.\n if (!state.windows) state = { ...state, windows: {} };\n switch (action.type) {\n case `${P}open`: {\n const { kind, key, title, data, target = \"focused\", reveal = true, activate = true, now, splitShare } = action.payload;\n const itemId = canvasItemId(kind, key);\n const existing = state.items[itemId];\n let next = state;\n let revealIn: CanvasWindowId = action.payload.windowId ?? CANVAS_MAIN_WINDOW;\n if (existing) {\n const item: CanvasItem = {\n ...existing,\n ...(data !== undefined ? { data } : {}),\n ...(title !== undefined ? { title } : {}),\n updatedAt: now,\n };\n next = { ...next, items: { ...next.items, [itemId]: item } };\n const pane = paneOf(next, itemId);\n if (pane) {\n revealIn = canvasWindowOfPane(next, pane.id) ?? CANVAS_MAIN_WINDOW;\n if (activate) next = focus(withPane(next, { ...pane, activeItemId: itemId }), pane.id);\n } else {\n next = ensureWindow(next, revealIn);\n const frame = canvasWindowFrame(next, revealIn) ?? next;\n next = insertInto(next, frame.focusedPaneId, itemId, true);\n }\n } else {\n const item = newItem(kind, key, title ?? null, data ?? null, now);\n next = ensureWindow({ ...next, items: { ...next.items, [itemId]: item } }, revealIn);\n const frame = canvasWindowFrame(next, revealIn) ?? next;\n let paneId: CanvasPaneId = frame.focusedPaneId;\n if (typeof target === \"object\" && next.panes[target.paneId]) {\n paneId = target.paneId;\n revealIn = canvasWindowOfPane(next, paneId) ?? revealIn;\n } else if (target === \"split-right\" || target === \"split-down\") {\n const split = addSplit(next, frame.focusedPaneId, target === \"split-right\" ? \"horizontal\" : \"vertical\", splitShare);\n if (split) {\n next = split.state;\n paneId = split.newPaneId;\n }\n }\n next = insertInto(next, paneId, itemId, activate);\n if (activate) next = focus(next, paneId);\n }\n return reveal ? withFrame(next, revealIn, { isOpen: true }) : next;\n }\n case `${P}update`: {\n const { itemId, data, title, now } = action.payload;\n const item = state.items[itemId];\n if (!item) return state;\n return {\n ...state,\n items: {\n ...state.items,\n [itemId]: { ...item, ...(data !== undefined ? { data } : {}), ...(title !== undefined ? { title } : {}), updatedAt: now },\n },\n };\n }\n case `${P}rekey`: {\n const { itemId, key } = action.payload;\n const item = state.items[itemId];\n if (!item || item.key === key) return state;\n const nextId = canvasItemId(item.kind, key);\n // The new identity is already open elsewhere: keep that one, drop this.\n if (state.items[nextId]) return canvasReducer(canvasReducer(state, canvasActions.closeItem(itemId)), canvasActions.activate(nextId));\n const items = { ...state.items, [nextId]: { ...item, id: nextId, key } };\n delete items[itemId];\n const panes: Record<string, CanvasPane> = {};\n for (const pane of Object.values(state.panes)) {\n panes[pane.id] = pane.itemIds.includes(itemId)\n ? {\n ...pane,\n itemIds: pane.itemIds.map((id) => (id === itemId ? nextId : id)),\n activeItemId: pane.activeItemId === itemId ? nextId : pane.activeItemId,\n }\n : pane;\n }\n return { ...state, items, panes };\n }\n case `${P}navigate`: {\n const { itemId, to, now } = action.payload;\n const current = state.items[itemId];\n if (!current || !paneOf(state, itemId)) return state;\n const targetId = canvasItemId(to.kind, to.key);\n if (targetId === itemId) {\n // Navigating to itself is a refresh, never a history step.\n const refresh: CanvasAction = { type: `${P}update`, payload: { itemId, data: to.data, title: to.title, now } };\n return canvasReducer(state, refresh);\n }\n if (state.items[targetId]) {\n // Identity law: the thing is already open — focus it there, never a second copy.\n // A launcher tab has done its job and closes; any other tab keeps what it shows.\n const focused = focusExisting(state, targetId);\n return current.kind === CANVAS_LAUNCHER_KIND ? canvasReducer(focused, canvasActions.closeItem(itemId)) : focused;\n }\n const history = [...(current.history ?? []), historyEntry(current)];\n // Going to something this tab showed before Back left it: its live body comes back.\n const keptAll = current.kept ?? [];\n const keptIndex = keptAll.findIndex((entry) => canvasItemId(entry.kind, entry.key) === targetId);\n const revived = keptIndex >= 0 ? keptAll[keptIndex] : undefined;\n const kept = keptAll.filter((_, i) => i !== keptIndex);\n // Navigating to exactly where Forward points is a Forward; anywhere else ends the forward trail.\n const forwardAll = current.forward ?? [];\n const nextForward = forwardAll[forwardAll.length - 1];\n const forward = nextForward && canvasItemId(nextForward.kind, nextForward.key) === targetId ? forwardAll.slice(0, -1) : [];\n return replaceInPlace(\n state,\n current,\n newItem(\n to.kind,\n to.key,\n to.title !== undefined ? to.title : (revived?.title ?? null),\n to.data !== undefined ? to.data : (revived?.data ?? null),\n now,\n { history, kept, forward, instance: revived?.instance },\n ),\n );\n }\n case `${P}back`: {\n const { itemId, now } = action.payload;\n const current = state.items[itemId];\n const history = current?.history ?? [];\n const entry = history[history.length - 1];\n if (!current || !entry || !paneOf(state, itemId)) return state;\n const targetId = canvasItemId(entry.kind, entry.key);\n if (targetId === itemId) return state;\n if (state.items[targetId]) {\n // What Back would return to was opened elsewhere since: go there; this step is done.\n return focusExisting(canvasReducer(state, canvasActions.closeItem(itemId)), targetId);\n }\n // Back returns the SAME body (its instance) and keeps the one it leaves, so going forward again finds it.\n const kept = [...(current.kept ?? []).filter((k) => canvasItemId(k.kind, k.key) !== itemId), historyEntry(current)];\n const forward = [...(current.forward ?? []), historyEntry(current)];\n return replaceInPlace(\n state,\n current,\n newItem(entry.kind, entry.key, entry.title, entry.data, now, { history: history.slice(0, -1), kept, forward, instance: entry.instance }),\n );\n }\n case `${P}forward`: {\n const { itemId, now } = action.payload;\n const current = state.items[itemId];\n const forwardAll = current?.forward ?? [];\n const entry = forwardAll[forwardAll.length - 1];\n if (!current || !entry || !paneOf(state, itemId)) return state;\n const targetId = canvasItemId(entry.kind, entry.key);\n if (targetId === itemId) return state;\n if (state.items[targetId]) {\n // Where Forward points was opened elsewhere since: go there; this step is done (as Back does).\n return focusExisting(canvasReducer(state, canvasActions.closeItem(itemId)), targetId);\n }\n // Forward returns the SAME body Back left (its instance, still held in `kept`).\n const keptAll = current.kept ?? [];\n const revived = keptAll.find((k) => canvasItemId(k.kind, k.key) === targetId);\n const kept = keptAll.filter((k) => canvasItemId(k.kind, k.key) !== targetId);\n return replaceInPlace(\n state,\n current,\n newItem(entry.kind, entry.key, entry.title, entry.data, now, {\n history: [...(current.history ?? []), historyEntry(current)],\n kept,\n forward: forwardAll.slice(0, -1),\n instance: revived?.instance ?? entry.instance,\n }),\n );\n }\n case `${P}closeItem`: {\n const { itemId } = action.payload;\n if (!state.items[itemId]) return state;\n const pane = paneOf(state, itemId);\n const windowId = pane ? canvasWindowOfPane(state, pane.id) : null;\n let next = detachItem(state, itemId);\n const items = { ...next.items };\n delete items[itemId];\n next = { ...next, items };\n // A pane emptied by closing its last tab goes away, unless it is its window's only one.\n if (pane && next.panes[pane.id]?.itemIds.length === 0) next = dropPane(next, pane.id);\n return dropEmptyPopOut(next, windowId);\n }\n case `${P}closeOthers`: {\n const { itemId } = action.payload;\n const pane = paneOf(state, itemId);\n if (!pane) return state;\n const items = { ...state.items };\n for (const id of pane.itemIds) if (id !== itemId) delete items[id];\n return { ...withPane(state, { ...pane, itemIds: [itemId], activeItemId: itemId }), items };\n }\n case `${P}activate`: {\n const pane = paneOf(state, action.payload.itemId);\n if (!pane) return state;\n return focus(withPane(state, { ...pane, activeItemId: action.payload.itemId }), pane.id);\n }\n case `${P}focusPane`: {\n const windowId = canvasWindowOfPane(state, action.payload.paneId);\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!windowId || !frame || frame.focusedPaneId === action.payload.paneId) return state;\n return withFrame(state, windowId, { focusedPaneId: action.payload.paneId });\n }\n case `${P}moveItem`: {\n const { itemId, toPaneId, index } = action.payload;\n const from = paneOf(state, itemId);\n if (!from || !state.panes[toPaneId]) return state;\n // Dropped back onto its own pane with no position: nothing moved.\n if (from.id === toPaneId && index === undefined) return canvasReducer(state, canvasActions.focusPane(toPaneId));\n const fromWindow = canvasWindowOfPane(state, from.id);\n let next = from.id === toPaneId ? state : detachItem(state, itemId);\n next = focus(insertInto(next, toPaneId, itemId, true, index), toPaneId);\n if (from.id !== toPaneId && next.panes[from.id]?.itemIds.length === 0) next = dropPane(next, from.id);\n return dropEmptyPopOut(next, fromWindow);\n }\n case `${P}splitPane`: {\n const { paneId, orientation, moveItemId, share } = action.payload;\n const pane = state.panes[paneId];\n if (!pane) return state;\n const split = addSplit(state, paneId, orientation, share);\n if (!split) return state;\n let next = split.state;\n // The new pane takes the requested tab when its old pane keeps something;\n // otherwise it starts empty and shows the launcher.\n if (moveItemId && pane.itemIds.includes(moveItemId) && pane.itemIds.length > 1) {\n next = detachItem(next, moveItemId);\n next = insertInto(next, split.newPaneId, moveItemId, true);\n }\n return next;\n }\n case `${P}closePane`: {\n const pane = state.panes[action.payload.paneId];\n const windowId = pane ? canvasWindowOfPane(state, pane.id) : null;\n const frame = windowId ? canvasWindowFrame(state, windowId) : null;\n if (!pane || !windowId || !frame) return state;\n const onlyPane = listPaneIds(frame.layout).length === 1;\n if (onlyPane) {\n // A pop-out's last pane closing closes the window; its tabs go home.\n if (windowId !== CANVAS_MAIN_WINDOW && state.windows[windowId]?.role === \"pop-out\") {\n return canvasReducer(state, canvasActions.closeWindow(windowId, \"dock\"));\n }\n // Closing the last pane puts the canvas away and KEEPS its tabs — the\n // toggle brings everything back exactly as it was.\n return withFrame(state, windowId, { isOpen: false, isFullscreen: false });\n }\n const items = { ...state.items };\n for (const id of pane.itemIds) delete items[id];\n return dropPane({ ...state, items }, pane.id);\n }\n case `${P}resizeSplit`: {\n const { splitId, sizes } = action.payload;\n for (const windowId of listCanvasWindowIds(state)) {\n const frame = canvasWindowFrame(state, windowId);\n if (frame && containsSplit(frame.layout, splitId)) {\n return withFrame(state, windowId, { layout: resizeSplit(frame.layout, splitId, sizes) });\n }\n }\n return state;\n }\n case `${P}setOpen`: {\n const { open, windowId = CANVAS_MAIN_WINDOW } = action.payload;\n const next = open ? ensureWindow(state, windowId) : state;\n const frame = canvasWindowFrame(next, windowId);\n if (!frame || frame.isOpen === open) return next;\n return withFrame(next, windowId, { isOpen: open, isFullscreen: open ? frame.isFullscreen : false });\n }\n case `${P}toggle`: {\n const windowId = action.payload?.windowId ?? CANVAS_MAIN_WINDOW;\n const next = ensureWindow(state, windowId);\n const frame = canvasWindowFrame(next, windowId);\n if (!frame) return state;\n return withFrame(next, windowId, { isOpen: !frame.isOpen, isFullscreen: frame.isOpen ? false : frame.isFullscreen });\n }\n case `${P}setFullscreen`: {\n const { fullscreen, windowId = CANVAS_MAIN_WINDOW } = action.payload;\n const next = fullscreen ? ensureWindow(state, windowId) : state;\n const frame = canvasWindowFrame(next, windowId);\n if (!frame) return state;\n return withFrame(next, windowId, { isFullscreen: fullscreen, isOpen: fullscreen ? true : frame.isOpen });\n }\n case `${P}setWidth`: {\n const { width, windowId = CANVAS_MAIN_WINDOW } = action.payload;\n const next = ensureWindow(state, windowId);\n return withFrame(next, windowId, { width: clampWidth(width) });\n }\n case `${P}popOut`: {\n const { itemId, windowId } = action.payload;\n const from = paneOf(state, itemId);\n if (!from || windowId === CANVAS_MAIN_WINDOW) return state;\n const fromWindow = canvasWindowOfPane(state, from.id) ?? CANVAS_MAIN_WINDOW;\n if (fromWindow === windowId) return state;\n let next = ensureWindow(state, windowId, \"pop-out\", fromWindow);\n const target = canvasWindowFrame(next, windowId);\n if (!target) return state;\n next = detachItem(next, itemId);\n next = insertInto(next, target.focusedPaneId, itemId, true);\n next = withFrame(next, windowId, { isOpen: true, focusedPaneId: target.focusedPaneId });\n if (next.panes[from.id]?.itemIds.length === 0) next = dropPane(next, from.id);\n next = dropEmptyPopOut(next, fromWindow);\n // The window it left has nothing left to show: put its column away.\n if (canvasWindowFrame(next, fromWindow) && windowItemIds(next, fromWindow).length === 0) {\n next = withFrame(next, fromWindow, { isOpen: false, isFullscreen: false });\n }\n return next;\n }\n case `${P}dockBack`: {\n const { itemId } = action.payload;\n const windowId = canvasWindowOfItem(state, itemId);\n if (!windowId || windowId === CANVAS_MAIN_WINDOW) return state;\n const frame = state.windows[windowId];\n if (!frame) return state;\n const home = canvasWindowFrame(state, frame.home) ? frame.home : CANVAS_MAIN_WINDOW;\n let next = sendHome(state, itemId, home, true);\n next = withFrame(next, home, { isOpen: true });\n const left = paneOf(state, itemId);\n if (left && next.panes[left.id]?.itemIds.length === 0) next = dropPane(next, left.id);\n return dropEmptyPopOut(next, windowId);\n }\n case `${P}closeWindow`: {\n const { windowId, mode } = action.payload;\n const frame = state.windows[windowId];\n if (!frame) return state;\n const itemIds = windowItemIds(state, windowId);\n let next = state;\n if (mode === \"close\") {\n const items = { ...next.items };\n for (const id of itemIds) delete items[id];\n next = { ...next, items };\n } else if (itemIds.length > 0) {\n const home = canvasWindowFrame(state, frame.home) ? frame.home : CANVAS_MAIN_WINDOW;\n const active = state.panes[frame.focusedPaneId]?.activeItemId ?? null;\n for (const id of itemIds) next = sendHome(next, id, home, id === active);\n next = withFrame(next, home, { isOpen: true });\n }\n return removeWindow(next, windowId);\n }\n case `${P}hydrate`: {\n const snapshot = action.payload.snapshot ? sanitizeCanvasSnapshot(action.payload.snapshot) : null;\n if (!snapshot) return { ...state, hydrated: true };\n // Anything opened before hydration finished wins over the snapshot.\n let next: CanvasState = snapshot;\n for (const item of Object.values(state.items)) {\n const pane = paneOf(state, item.id);\n next = { ...next, items: { ...next.items, [item.id]: item } };\n if (!paneOf(next, item.id)) next = insertInto(next, next.focusedPaneId, item.id, pane?.activeItemId === item.id);\n }\n return { ...next, isOpen: next.isOpen || state.isOpen, hydrated: true };\n }\n case `${P}reset`:\n return { ...createInitialCanvasState(), hydrated: true };\n default:\n return state;\n }\n}\n","/**\n * The store seam. The canvas never owns a second copy of its state: it reads\n * and writes through a CanvasStoreBinding.\n *\n * - A host WITH Redux mounts `canvasReducer` in its root reducer and binds it:\n * bindCanvasToReduxStore(store, (root) => root.canvasHost)\n * - A host WITHOUT Redux (a Vite tool, an Electron window) calls\n * createCanvasStore()\n * which runs the very same reducer in a tiny standalone store.\n */\n\nimport { canvasReducer, createInitialCanvasState, type CanvasAction } from \"./reducer\";\nimport type { CanvasState } from \"./types\";\n\nexport interface CanvasStoreBinding {\n getState(): CanvasState;\n dispatch(action: CanvasAction): void;\n subscribe(listener: () => void): () => void;\n /**\n * \"remote\": the state lives in another process (createRemoteCanvasStore) —\n * that process hydrates and saves it, so a controller over this binding\n * never does. Absent means \"local\".\n */\n readonly authority?: \"local\" | \"remote\";\n}\n\nexport function createCanvasStore(initial?: CanvasState): CanvasStoreBinding {\n let state = initial ?? createInitialCanvasState();\n const listeners = new Set<() => void>();\n return {\n getState: () => state,\n dispatch(action) {\n const next = canvasReducer(state, action);\n if (next === state) return;\n state = next;\n for (const listener of [...listeners]) listener();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n/** The minimum of a Redux store the canvas needs. */\nexport interface ReduxStoreLike<TRoot> {\n getState(): TRoot;\n dispatch(action: CanvasAction): unknown;\n subscribe(listener: () => void): () => void;\n}\n\nexport function bindCanvasToReduxStore<TRoot>(\n store: ReduxStoreLike<TRoot>,\n select: (root: TRoot) => CanvasState,\n): CanvasStoreBinding {\n return {\n getState: () => select(store.getState()),\n dispatch: (action) => {\n store.dispatch(action);\n },\n subscribe: (listener) => store.subscribe(listener),\n };\n}\n","/**\n * Remembering the canvas between sessions — a table stake, never optional.\n *\n * The default port writes to localStorage under a versioned key. Items whose\n * kind opts out (`restore: false`, e.g. a live session that cannot come back)\n * are dropped from the snapshot, and panes they leave empty are dropped too.\n */\n\nimport { removePane } from \"./layout\";\nimport { foldCanvasWindows } from \"./reducer\";\nimport type { CanvasItemId, CanvasState } from \"./types\";\n\nexport interface CanvasPersistencePort {\n load(): CanvasState | null | Promise<CanvasState | null>;\n save(snapshot: CanvasState): void | Promise<void>;\n}\n\nexport const CANVAS_STORAGE_KEY = \"ai-matrx.canvas.v1\";\n\nexport function createLocalStorageCanvasPersistence(\n key: string = CANVAS_STORAGE_KEY,\n storage: Pick<Storage, \"getItem\" | \"setItem\"> | null = typeof window === \"undefined\" ? null : safeLocalStorage(),\n): CanvasPersistencePort {\n return {\n load() {\n if (!storage) throw new Error(\"Canvas storage is unavailable; allow browser storage or provide a persistence port.\");\n const raw = storage.getItem(key);\n if (!raw) return null;\n return JSON.parse(raw) as CanvasState;\n },\n save(snapshot) {\n if (!storage) throw new Error(\"Canvas storage is unavailable; allow browser storage or provide a persistence port.\");\n storage.setItem(key, JSON.stringify(snapshot));\n },\n };\n}\n\n/**\n * Memory over any key-value store — an Electron main process's `state/kv`,\n * electron-store, IndexedDB behind a promise, a test map. Values are written\n * as plain JSON objects (not strings) so a structured store keeps them\n * inspectable; a string-only store can wrap this with JSON.stringify.\n */\nexport interface CanvasKeyValueStore {\n get(key: string): unknown;\n set(key: string, value: unknown): void | Promise<void>;\n}\n\nexport function createKeyValueCanvasPersistence(kv: CanvasKeyValueStore, key: string = CANVAS_STORAGE_KEY): CanvasPersistencePort {\n return {\n async load() {\n const raw = await kv.get(key);\n if (raw === undefined || raw === null) return null;\n return (typeof raw === \"string\" ? JSON.parse(raw) : raw) as CanvasState;\n },\n save: (snapshot) => kv.set(key, JSON.parse(JSON.stringify(snapshot)) as unknown),\n };\n}\n\nfunction safeLocalStorage(): Storage | null {\n try {\n const probe = \"__mxc_probe__\";\n window.localStorage.setItem(probe, \"1\");\n window.localStorage.removeItem(probe);\n return window.localStorage;\n } catch {\n return null; // load/save report through the controller's existing error sink.\n }\n}\n\n/**\n * Builds the snapshot that is actually written: only restorable items, and\n * every window but the main one folded home (other windows never come back).\n */\nexport function toPersistableSnapshot(\n state: CanvasState,\n isRestorable: (kind: string) => boolean,\n): CanvasState {\n state = foldCanvasWindows(state);\n const keep = new Set<CanvasItemId>(\n Object.values(state.items).filter((item) => isRestorable(item.kind)).map((item) => item.id),\n );\n if (keep.size === Object.keys(state.items).length) return state;\n const items = Object.fromEntries(Object.entries(state.items).filter(([id]) => keep.has(id as CanvasItemId)));\n let layout = state.layout;\n const panes: Record<string, CanvasState[\"panes\"][string]> = {};\n for (const pane of Object.values(state.panes)) {\n const itemIds = pane.itemIds.filter((id) => keep.has(id));\n if (itemIds.length === 0 && pane.itemIds.length > 0) {\n const pruned = removePane(layout, pane.id);\n if (pruned) {\n layout = pruned;\n continue;\n }\n }\n panes[pane.id] = {\n ...pane,\n itemIds,\n activeItemId: pane.activeItemId && keep.has(pane.activeItemId) ? pane.activeItemId : (itemIds[0] ?? null),\n };\n }\n const focusedPaneId = panes[state.focusedPaneId] ? state.focusedPaneId : (Object.values(panes)[0]?.id ?? state.focusedPaneId);\n return { ...state, items, panes, layout, focusedPaneId };\n}\n","/**\n * Layout rules — the host-tunable numbers behind the column's width and how its\n * panes share space. Pure functions, so a desktop main process can place native\n * views with exactly the numbers the renderer draws with.\n *\n * The canvas always shrinks FIRST: while the window narrows, the centre keeps\n * `centreMinWidth` and the canvas gives way down to `minWidth`; only then does\n * the centre squeeze. Side-by-side panes narrower than `paneMinWidth` stack\n * instead of squeezing.\n */\n\nimport { CANVAS_DEFAULT_WIDTH, CANVAS_MIN_WIDTH } from \"./types\";\n\n/** The web's narrowest side-by-side pane (px): below it, a side-by-side split renders stacked. */\nexport const CANVAS_PANE_MIN_WIDTH = 280;\n\nexport interface CanvasLayoutRules {\n /** Width before the person drags the edge: CSS px, or a fraction of the region the canvas shares. */\n readonly defaultWidth: number | { readonly fraction: number };\n /** The narrowest the canvas column gets on a desktop-sized window. */\n readonly minWidth: number;\n /** Room the content beside the canvas always keeps (the canvas shrinks first). */\n readonly centreMinWidth: number;\n /** The FIRST pane's share when a pane splits down (stacked). 0.7 = the 70/30 divider. */\n readonly stackSplit: number;\n /** The first pane's share when a pane splits right (side by side). */\n readonly sideSplit: number;\n /** Side-by-side panes that would be narrower than this render stacked. 0 = never. */\n readonly paneMinWidth: number;\n}\n\n/** The web app's numbers (the defaults). */\nexport const CANVAS_WEB_LAYOUT_RULES: CanvasLayoutRules = {\n defaultWidth: CANVAS_DEFAULT_WIDTH,\n minWidth: CANVAS_MIN_WIDTH,\n // The page beside the canvas keeps room for its route header (title, mode switch,\n // the shell's own controls): a 2026-10-03 census of 40 routes found headers 29-67px\n // wide at 420 with a 900px canvas. Hosts pass `regionWidth` so this is the PAGE's\n // width, not the window's.\n centreMinWidth: 600,\n // Split down 70/30 like the desktop: what opens below (notifications, a feed) is the smaller pane.\n stackSplit: 0.7,\n sideSplit: 0.5,\n // A pane narrower than this cannot show a header (Back, a readable tab, \"+\", the menu, close) and a\n // body side by side with another: a split right that would go under it stacks instead.\n paneMinWidth: CANVAS_PANE_MIN_WIDTH,\n};\n\n/** The desktop app's numbers (Claude desktop's proportions). */\nexport const CANVAS_DESKTOP_LAYOUT_RULES: CanvasLayoutRules = {\n defaultWidth: { fraction: 0.36 },\n minWidth: CANVAS_MIN_WIDTH,\n centreMinWidth: 520,\n stackSplit: 0.7,\n sideSplit: 0.5,\n paneMinWidth: 360,\n};\n\nconst clampFraction = (value: number, fallback: number) =>\n Number.isFinite(value) ? Math.min(0.88, Math.max(0.12, value)) : fallback;\n\n/** Fills missing fields from the web defaults and repairs nonsense values. */\nexport function resolveCanvasLayoutRules(rules?: Partial<CanvasLayoutRules> | null): CanvasLayoutRules {\n const merged = { ...CANVAS_WEB_LAYOUT_RULES, ...(rules ?? {}) };\n const positive = (value: number, fallback: number) => (Number.isFinite(value) && value >= 0 ? value : fallback);\n return {\n defaultWidth:\n typeof merged.defaultWidth === \"number\"\n ? positive(merged.defaultWidth, CANVAS_DEFAULT_WIDTH)\n : { fraction: Math.min(1, Math.max(0.05, Number.isFinite(merged.defaultWidth.fraction) ? merged.defaultWidth.fraction : 0.36)) },\n minWidth: positive(merged.minWidth, CANVAS_MIN_WIDTH),\n centreMinWidth: positive(merged.centreMinWidth, CANVAS_WEB_LAYOUT_RULES.centreMinWidth),\n stackSplit: clampFraction(merged.stackSplit, 0.5),\n sideSplit: clampFraction(merged.sideSplit, 0.5),\n paneMinWidth: positive(merged.paneMinWidth, 0),\n };\n}\n\n/** The width before the person chose one. `region` is the space the canvas shares (0 = unknown). */\nexport function defaultCanvasWidth(rules: CanvasLayoutRules, region: number): number {\n if (typeof rules.defaultWidth === \"number\") return rules.defaultWidth;\n return region > 0 ? Math.round(region * rules.defaultWidth.fraction) : CANVAS_DEFAULT_WIDTH;\n}\n\n/**\n * The column's width right now: the stored width (or the rule's default),\n * fitted so the centre keeps `centreMinWidth` and the canvas never goes under\n * `minWidth`. A width remembered on a wide monitor never crushes a laptop.\n */\nexport function fitCanvasWidth(stored: number | null, region: number, rules: CanvasLayoutRules): number {\n const wanted = stored ?? defaultCanvasWidth(rules, region);\n if (region <= 0) return Math.max(rules.minWidth, wanted);\n return Math.max(rules.minWidth, Math.min(wanted, region - rules.centreMinWidth));\n}\n\n/** Clamp for a dragged width: the same bounds as fitting. */\nexport function clampDraggedCanvasWidth(next: number, region: number, rules: CanvasLayoutRules): number {\n const max = Math.max(rules.minWidth, region - rules.centreMinWidth);\n return Math.min(max, Math.max(rules.minWidth, Math.round(next)));\n}\n\n/** Whether a side-by-side split this wide (px) with this many children renders stacked. */\nexport function shouldStackSplit(width: number, children: number, rules: CanvasLayoutRules): boolean {\n return rules.paneMinWidth > 0 && width > 0 && width < rules.paneMinWidth * children;\n}\n","/**\n * The canvas's keyboard shortcuts, as DATA. A web host gets them bound in the\n * DOM by `CanvasProvider`; a desktop host binds the same table in its main\n * process (menu accelerators / `before-input-event`), because keys pressed\n * inside a native web view never reach the renderer's DOM. Every shortcut runs\n * through `runCanvasCommand`, so both paths do exactly the same thing.\n */\n\nimport type { CanvasController } from \"./controller\";\nimport { canvasWindowFrame } from \"./reducer\";\nimport type { CanvasWindowId } from \"./types\";\n\nexport type CanvasCommandId =\n | \"canvas.toggle\"\n | \"canvas.toggleFullscreen\"\n | \"canvas.exitFullscreen\"\n | \"canvas.closeTab\"\n | \"canvas.nextTab\"\n | \"canvas.previousTab\"\n | \"canvas.splitRight\"\n | \"canvas.splitDown\"\n | \"canvas.back\"\n | \"canvas.forward\";\n\n/**\n * When a shortcut applies:\n * - \"presented\": a canvas column is on screen in this window;\n * - \"fullscreen\": the canvas is expanded (and Escape is not owned by a menu or dialog);\n * - \"canvas-focus\": keyboard focus is inside the canvas (a tab, a pane, a native body).\n */\nexport type CanvasShortcutWhen = \"presented\" | \"fullscreen\" | \"canvas-focus\";\n\nexport interface CanvasShortcut {\n readonly id: CanvasCommandId;\n /** Electron accelerator syntax: \"CmdOrCtrl+\\\\\", \"Escape\", \"Ctrl+Shift+Tab\". */\n readonly accelerator: string;\n readonly when: CanvasShortcutWhen;\n readonly label: string;\n /** False when browsers reserve the keys (⌘W, Ctrl+Tab): only a desktop host can bind it. */\n readonly web: boolean;\n}\n\nexport const CANVAS_SHORTCUTS: readonly CanvasShortcut[] = [\n { id: \"canvas.toggle\", accelerator: \"CmdOrCtrl+\\\\\", when: \"presented\", label: \"Show or hide canvas\", web: true },\n { id: \"canvas.exitFullscreen\", accelerator: \"Escape\", when: \"fullscreen\", label: \"Restore canvas\", web: true },\n { id: \"canvas.toggleFullscreen\", accelerator: \"CmdOrCtrl+Shift+Enter\", when: \"canvas-focus\", label: \"Expand canvas\", web: true },\n { id: \"canvas.splitRight\", accelerator: \"CmdOrCtrl+Alt+\\\\\", when: \"canvas-focus\", label: \"Split right\", web: true },\n { id: \"canvas.splitDown\", accelerator: \"CmdOrCtrl+Alt+Shift+\\\\\", when: \"canvas-focus\", label: \"Split down\", web: true },\n // Browsers own ⌘[ / ⌘] for their own history: data for a desktop host (and the header's Back / Forward).\n { id: \"canvas.back\", accelerator: \"CmdOrCtrl+[\", when: \"canvas-focus\", label: \"Back\", web: false },\n { id: \"canvas.forward\", accelerator: \"CmdOrCtrl+]\", when: \"canvas-focus\", label: \"Forward\", web: false },\n { id: \"canvas.closeTab\", accelerator: \"CmdOrCtrl+W\", when: \"canvas-focus\", label: \"Close tab\", web: false },\n { id: \"canvas.nextTab\", accelerator: \"Ctrl+Tab\", when: \"canvas-focus\", label: \"Next tab\", web: false },\n { id: \"canvas.previousTab\", accelerator: \"Ctrl+Shift+Tab\", when: \"canvas-focus\", label: \"Previous tab\", web: false },\n];\n\n/** The tooltip hint for a command, e.g. \"⌘\\\\\" on a Mac. */\nexport function canvasShortcutHint(id: CanvasCommandId, isMac: boolean): string | null {\n const shortcut = CANVAS_SHORTCUTS.find((entry) => entry.id === id);\n if (!shortcut) return null;\n return shortcut.accelerator\n .split(\"+\")\n .map((part) => {\n if (part === \"CmdOrCtrl\") return isMac ? \"⌘\" : \"Ctrl+\";\n if (part === \"Ctrl\") return isMac ? \"⌃\" : \"Ctrl+\";\n if (part === \"Alt\") return isMac ? \"⌥\" : \"Alt+\";\n if (part === \"Shift\") return isMac ? \"⇧\" : \"Shift+\";\n if (part === \"Escape\") return \"Esc\";\n return part;\n })\n .join(\"\");\n}\n\n/**\n * Runs one command against a window's canvas. Returns true when it did\n * something (so a binding knows whether to swallow the key).\n */\nexport function runCanvasCommand(controller: CanvasController, id: CanvasCommandId, windowId: CanvasWindowId = controller.windowId): boolean {\n const state = controller.getState();\n const frame = canvasWindowFrame(state, windowId);\n const pane = frame ? state.panes[frame.focusedPaneId] : undefined;\n switch (id) {\n case \"canvas.toggle\":\n controller.toggle(windowId);\n return true;\n case \"canvas.toggleFullscreen\":\n controller.setFullscreen(!(frame?.isFullscreen ?? false), windowId);\n return true;\n case \"canvas.exitFullscreen\":\n if (!frame?.isFullscreen) return false;\n controller.setFullscreen(false, windowId);\n return true;\n case \"canvas.closeTab\":\n if (!frame?.isOpen || !pane?.activeItemId) return false;\n controller.close(pane.activeItemId);\n return true;\n case \"canvas.nextTab\":\n case \"canvas.previousTab\": {\n if (!frame?.isOpen || !pane?.activeItemId || pane.itemIds.length < 2) return false;\n const at = pane.itemIds.indexOf(pane.activeItemId);\n const step = id === \"canvas.nextTab\" ? 1 : -1;\n const next = pane.itemIds[(at + step + pane.itemIds.length) % pane.itemIds.length];\n if (next) controller.activate(next);\n return true;\n }\n case \"canvas.splitRight\":\n case \"canvas.splitDown\":\n if (!frame?.isOpen || !pane) return false;\n controller.splitPane(pane.id, id === \"canvas.splitRight\" ? \"horizontal\" : \"vertical\", pane.itemIds.length > 1 ? (pane.activeItemId ?? undefined) : undefined);\n return true;\n case \"canvas.back\":\n if (!frame?.isOpen || !pane?.activeItemId) return false;\n return controller.back(pane.activeItemId) !== null;\n case \"canvas.forward\":\n if (!frame?.isOpen || !pane?.activeItemId) return false;\n return controller.forward(pane.activeItemId) !== null;\n default:\n return false;\n }\n}\n\n/** The subset of a KeyboardEvent an accelerator is matched against. */\nexport interface CanvasKeyInput {\n readonly key: string;\n readonly code?: string;\n readonly metaKey: boolean;\n readonly ctrlKey: boolean;\n readonly altKey: boolean;\n readonly shiftKey: boolean;\n}\n\nconst CODE_FOR: Record<string, string> = { \"\\\\\": \"Backslash\", \"[\": \"BracketLeft\", \"]\": \"BracketRight\", Tab: \"Tab\", Escape: \"Escape\", Enter: \"Enter\" };\n\n/**\n * Whether a key event is this accelerator. \"CmdOrCtrl\" is ⌘ on a Mac and Ctrl\n * elsewhere; symbol keys match by physical key (⌥\\ types « on a Mac).\n */\nexport function matchesCanvasAccelerator(input: CanvasKeyInput, accelerator: string, isMac: boolean): boolean {\n const parts = accelerator.split(\"+\");\n // \"CmdOrCtrl+\\\\\" splits into [..., \"\\\\\"]; a trailing \"+\" key would split empty.\n const key = parts.pop() ?? \"\";\n const want = { meta: false, ctrl: false, alt: false, shift: false };\n for (const part of parts) {\n if (part === \"CmdOrCtrl\") want[isMac ? \"meta\" : \"ctrl\"] = true;\n else if (part === \"Cmd\" || part === \"Meta\") want.meta = true;\n else if (part === \"Ctrl\") want.ctrl = true;\n else if (part === \"Alt\") want.alt = true;\n else if (part === \"Shift\") want.shift = true;\n }\n if (input.metaKey !== want.meta || input.ctrlKey !== want.ctrl || input.altKey !== want.alt || input.shiftKey !== want.shift) return false;\n const code = CODE_FOR[key] ?? (/^[A-Z]$/i.test(key) ? `Key${key.toUpperCase()}` : undefined);\n if (code && input.code === code) return true;\n return input.key.toLowerCase() === key.toLowerCase();\n}\n","/**\n * The canvas controller: the ONE imperative API every caller uses. It wraps a\n * store binding, validates what callers hand it (so the reducer stays pure and\n * trusting), and owns hydration, autosave, pop-outs and session lifecycles.\n *\n * A controller acts for ONE window by default (`controller.windowId`, main\n * unless the host says otherwise); `forWindow(id)` gives the same canvas seen\n * from another window. Nothing fails silently: a refused open, a pop-out the\n * host cannot do, a throwing session hook — each is reported through the\n * error sink.\n */\n\nimport { canvasActions, canvasWindowOfItem, canvasWindowFrame, listCanvasWindowIds, sanitizeCanvasSnapshot, type CanvasAction, type CanvasWindowCloseMode } from \"./reducer\";\nimport { canvasItemId, canvasWindowId, findNonJson } from \"./ids\";\nimport { listPaneIds } from \"./layout\";\nimport { toPersistableSnapshot, type CanvasPersistencePort } from \"./persistence\";\nimport { resolveCanvasLayoutRules, type CanvasLayoutRules } from \"./rules\";\nimport type { CanvasStoreBinding } from \"./store\";\nimport {\n CANVAS_LAUNCHER_KIND,\n CANVAS_MAIN_WINDOW,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasNavigateInput,\n type CanvasOpenInput,\n type CanvasOpenTarget,\n type CanvasOrientation,\n type CanvasPaneId,\n type CanvasPreferredTarget,\n type CanvasSplitId,\n type CanvasState,\n type CanvasWindowId,\n} from \"./types\";\n\nexport interface CanvasErrorReport {\n readonly code:\n | \"non-json-data\"\n | \"unknown-kind\"\n | \"persistence-load\"\n | \"persistence-save\"\n | \"pop-out-unavailable\"\n | \"pop-out-refused\"\n | \"pop-out-failed\"\n | \"session-hook\";\n readonly message: string;\n readonly detail?: unknown;\n}\n\nexport type CanvasErrorSink = (report: CanvasErrorReport) => void;\n\nexport const consoleCanvasErrorSink: CanvasErrorSink = (report) => {\n console.error(`[@ai-matrx/canvas] ${report.code}: ${report.message}`, report.detail ?? \"\");\n};\n\n/**\n * The host's window abilities. Without `popOut` a pop-out is refused aloud and\n * no \"Pop out\" entry is shown.\n */\nexport interface CanvasWindowPorts {\n /**\n * Opens a window (web: a floating panel; desktop: a BrowserWindow) that will\n * render the canvas for the returned window id, then the package moves the\n * item there. Resolve null to refuse.\n */\n readonly popOut?: ((item: CanvasItem) => Promise<{ readonly windowId: string } | null>) | undefined;\n /** Called after a tab docked back out of `fromWindowId` (close that window when the state no longer lists it). */\n readonly dockBack?: ((itemId: CanvasItemId, fromWindowId: CanvasWindowId) => void) | undefined;\n}\n\n/** Why a session-backed item attached or detached. */\nexport type CanvasSessionAttachReason = \"open\" | \"restore\" | \"arrive\";\nexport type CanvasSessionDetachReason = \"close\" | \"leave\" | \"unmount\";\n\nexport interface CanvasSessionEvent<R extends string> {\n readonly item: CanvasItem;\n readonly sessionKey: string;\n /** The window the item is in (attach) or was in (detach). */\n readonly windowId: CanvasWindowId;\n readonly reason: R;\n}\n\n/**\n * A kind with `restore: \"session\"`: its tab is a view onto a process the host\n * keeps (a terminal). Closing the tab DETACHES (the process lives on); a\n * restore or a move REATTACHES. The package only calls these; the host owns the\n * process side.\n */\nexport interface CanvasSessionHooks {\n readonly sessionKey: (item: CanvasItem) => string | null;\n readonly onAttach?: ((event: CanvasSessionEvent<CanvasSessionAttachReason>) => void) | undefined;\n readonly onDetach?: ((event: CanvasSessionEvent<CanvasSessionDetachReason>) => void) | undefined;\n}\n\nexport interface CanvasControllerOptions {\n readonly store: CanvasStoreBinding;\n readonly persistence?: CanvasPersistencePort | null | undefined;\n /** Kinds that may not come back after a reload. Default: every kind restores. */\n readonly isRestorable?: ((kind: string) => boolean) | undefined;\n /** When given, opens of an unregistered kind are refused and reported. */\n readonly isKnownKind?: ((kind: string) => boolean) | undefined;\n readonly onError?: CanvasErrorSink | undefined;\n readonly saveDelayMs?: number | undefined;\n /**\n * Whether a remembered \"open\" may be restored right now. A host returns\n * false where an open canvas would take the whole screen (a phone).\n */\n readonly mayRestoreOpen?: (() => boolean) | undefined;\n /** The window this controller acts for by default. Default: the main window. */\n readonly windowId?: string | undefined;\n /** Width and split numbers (see CANVAS_WEB_LAYOUT_RULES / CANVAS_DESKTOP_LAYOUT_RULES). */\n readonly layoutRules?: Partial<CanvasLayoutRules> | undefined;\n /** Read on every use, so a provider can hand in its latest ports. */\n readonly windowPorts?: (() => CanvasWindowPorts) | undefined;\n /** Session hooks for a kind, or undefined when the kind is not session-backed. */\n readonly sessions?: ((kind: string) => CanvasSessionHooks | undefined) | undefined;\n /**\n * Where a NEW item of a kind opens while the canvas already shows something\n * (a kind's `preferredTarget`). An explicit `target` always wins.\n */\n readonly preferredTarget?: ((kind: string) => CanvasPreferredTarget | undefined) | undefined;\n}\n\nexport interface CanvasController {\n readonly store: CanvasStoreBinding;\n /** The window this controller acts for by default. */\n readonly windowId: CanvasWindowId;\n readonly rules: CanvasLayoutRules;\n /** The same canvas, acting for another window. */\n forWindow(windowId: string): CanvasController;\n getState(): CanvasState;\n open(input: CanvasOpenInput): CanvasItemId | null;\n update(itemId: CanvasItemId, patch: { data?: CanvasJson | undefined; title?: string | null | undefined }): boolean;\n /** Gives an item a new identity in place (a draft that was saved and now has a durable id). */\n rekey(itemId: CanvasItemId, key: string): CanvasItemId | null;\n /**\n * Replaces a tab's content with another item IN PLACE and records history,\n * so the pane header offers Back. Identity still holds: when the target is\n * already open, it is focused where it is (a launcher tab then closes; any\n * other tab keeps what it shows). Returns the item now shown, or null.\n */\n navigate(itemId: CanvasItemId, to: CanvasNavigateInput): CanvasItemId | null;\n /** Returns a tab to what it showed before (see navigate). Null when it has no history. */\n back(itemId: CanvasItemId): CanvasItemId | null;\n /** Re-does the last Back with the same live body. Null when there is nothing forward. */\n forward(itemId: CanvasItemId): CanvasItemId | null;\n /** Opens the launcher as a new tab in a pane (default: this window's focused pane), or focuses the one already there. */\n newTab(paneId?: CanvasPaneId): CanvasItemId;\n close(itemId: CanvasItemId): void;\n closeOthers(itemId: CanvasItemId): void;\n activate(itemId: CanvasItemId): void;\n focusPane(paneId: CanvasPaneId): void;\n moveItem(itemId: CanvasItemId, toPaneId: CanvasPaneId, index?: number): void;\n /** Splits with the layout rules' share (stackSplit for \"vertical\", sideSplit for \"horizontal\"). */\n splitPane(paneId: CanvasPaneId, orientation: CanvasOrientation, moveItemId?: CanvasItemId): void;\n closePane(paneId: CanvasPaneId): void;\n resizeSplit(splitId: CanvasSplitId, sizes: readonly number[]): void;\n show(windowId?: CanvasWindowId): void;\n hide(windowId?: CanvasWindowId): void;\n toggle(windowId?: CanvasWindowId): void;\n setFullscreen(fullscreen: boolean, windowId?: CanvasWindowId): void;\n setWidth(width: number, windowId?: CanvasWindowId): void;\n /** Moves a tab into its own window through the host's popOut port. Refused aloud without one. */\n popOut(itemId: CanvasItemId): Promise<CanvasWindowId | null>;\n /** Returns a popped-out tab to the window it came from. False when it is not popped out. */\n dockBack(itemId: CanvasItemId): boolean;\n /** A host window closed: its tabs dock home (default) or close with it. */\n closeWindow(windowId: CanvasWindowId, mode?: CanvasWindowCloseMode): void;\n /** Is this exact thing on the canvas right now (in any window)? */\n has(kind: string, key: string): boolean;\n /**\n * Is a canvas column on screen (in this window, or in `windowId`)? A store\n * can exist in a layout that shows no column (a kiosk, a meeting stage);\n * opening there must be refused aloud.\n */\n isPresented(windowId?: CanvasWindowId): boolean;\n /** Called by a column on mount; returns the unmount callback. */\n registerPresentation(windowId?: CanvasWindowId): () => void;\n subscribePresentation(listener: () => void): () => void;\n /** Loads the persisted snapshot, starts autosave and session tracking. Returns a disposer. */\n start(): () => void;\n}\n\ninterface Shared {\n readonly options: CanvasControllerOptions;\n readonly onError: CanvasErrorSink;\n readonly rules: CanvasLayoutRules;\n readonly presentations: Map<CanvasWindowId, number>;\n readonly presentationListeners: Set<() => void>;\n readonly views: Map<CanvasWindowId, CanvasController>;\n /** Windows whose controllers are started (session tracking scope for a remote store). */\n readonly started: Map<CanvasWindowId, number>;\n sessionStop: (() => void) | null;\n /** Mints \"New tab\" keys (unique per controller family). */\n launcherSeq: number;\n}\n\nexport function createCanvasController(options: CanvasControllerOptions): CanvasController {\n const shared: Shared = {\n options,\n onError: options.onError ?? consoleCanvasErrorSink,\n rules: resolveCanvasLayoutRules(options.layoutRules),\n presentations: new Map(),\n presentationListeners: new Set(),\n views: new Map(),\n started: new Map(),\n sessionStop: null,\n launcherSeq: 0,\n };\n return view(shared, canvasWindowId(options.windowId ?? CANVAS_MAIN_WINDOW));\n}\n\nfunction view(shared: Shared, windowId: CanvasWindowId): CanvasController {\n const cached = shared.views.get(windowId);\n if (cached) return cached;\n const { options, onError, rules } = shared;\n const { store, persistence = null } = options;\n const isRestorable = options.isRestorable ?? (() => true);\n const dispatch = (action: CanvasAction) => store.dispatch(action);\n const notifyPresentation = () => {\n for (const listener of [...shared.presentationListeners]) listener();\n };\n const shareFor = (orientation: CanvasOrientation) => (orientation === \"vertical\" ? rules.stackSplit : rules.sideSplit);\n\n /** Refuses aloud what may not be opened: an unknown kind, data that is not plain JSON. */\n const acceptable = (input: { readonly kind: string; readonly key: string; readonly data?: CanvasJson | undefined }): boolean => {\n if (input.kind !== CANVAS_LAUNCHER_KIND && options.isKnownKind && !options.isKnownKind(input.kind)) {\n onError({ code: \"unknown-kind\", message: `No canvas kind \"${input.kind}\" is registered.`, detail: input });\n return false;\n }\n if (input.data !== undefined) {\n const bad = findNonJson(input.data);\n if (bad) {\n onError({\n code: \"non-json-data\",\n message: `Canvas data for \"${input.kind}\" must be plain JSON; ${bad} is not.`,\n detail: { kind: input.kind, key: input.key },\n });\n return false;\n }\n }\n return true;\n };\n\n /**\n * A kind's preferred place for a NEW item, applied only while the canvas\n * already shows something in this window: a pane already holding that kind\n * takes it (one notifications pane, not a new split per press); otherwise\n * the preferred split of the focused pane. A put-away or empty canvas, or an\n * item that already exists, just opens where it would anyway.\n */\n const preferredTargetFor = (input: CanvasOpenInput): CanvasOpenTarget => {\n const preferred = options.preferredTarget?.(input.kind);\n if (!preferred || preferred === \"focused\") return \"focused\";\n const state = store.getState();\n if (canvasItemId(input.kind, input.key) in state.items) return \"focused\";\n const frame = canvasWindowFrame(state, input.windowId ?? windowId);\n if (!frame?.isOpen) return \"focused\";\n const panes = listPaneIds(frame.layout);\n const holding = panes.find((paneId) => state.panes[paneId]?.itemIds.some((id) => state.items[id]?.kind === input.kind));\n if (holding) return { paneId: holding };\n return state.panes[frame.focusedPaneId]?.activeItemId ? preferred : \"focused\";\n };\n\n const controller: CanvasController = {\n store,\n windowId,\n rules,\n forWindow: (id) => view(shared, canvasWindowId(id)),\n getState: () => store.getState(),\n open(input) {\n if (!acceptable(input)) return null;\n const target = input.target ?? preferredTargetFor(input);\n const splitShare = target === \"split-down\" ? rules.stackSplit : target === \"split-right\" ? rules.sideSplit : undefined;\n const withTarget: CanvasOpenInput = input.target === target ? input : { ...input, target };\n const resolved: CanvasOpenInput = withTarget.windowId || windowId === CANVAS_MAIN_WINDOW ? withTarget : { ...withTarget, windowId };\n dispatch(canvasActions.open(resolved, splitShare === undefined ? undefined : { splitShare }));\n return canvasItemId(input.kind, input.key);\n },\n update(itemId, patch) {\n if (patch.data !== undefined) {\n const bad = findNonJson(patch.data);\n if (bad) {\n onError({ code: \"non-json-data\", message: `Canvas update for ${itemId} must be plain JSON; ${bad} is not.` });\n return false;\n }\n }\n if (!store.getState().items[itemId]) return false;\n dispatch(canvasActions.update(itemId, patch));\n return true;\n },\n navigate(itemId, to) {\n if (!store.getState().items[itemId] || !acceptable(to)) return null;\n dispatch(canvasActions.navigate(itemId, to));\n const shown = canvasItemId(to.kind, to.key);\n return shown in store.getState().items ? shown : null;\n },\n back(itemId) {\n const history = store.getState().items[itemId]?.history ?? [];\n const entry = history[history.length - 1];\n if (!entry) return null;\n dispatch(canvasActions.back(itemId));\n return canvasItemId(entry.kind, entry.key);\n },\n forward(itemId) {\n const forward = store.getState().items[itemId]?.forward ?? [];\n const entry = forward[forward.length - 1];\n if (!entry) return null;\n dispatch(canvasActions.forward(itemId));\n return canvasItemId(entry.kind, entry.key);\n },\n newTab(paneId) {\n const state = store.getState();\n const frame = canvasWindowFrame(state, windowId);\n const target = paneId && state.panes[paneId] ? paneId : (frame?.focusedPaneId ?? state.focusedPaneId);\n const existing = state.panes[target]?.itemIds.find((id) => state.items[id]?.kind === CANVAS_LAUNCHER_KIND);\n if (existing) {\n dispatch(canvasActions.activate(existing));\n dispatch(canvasActions.setOpen(true, canvasWindowOfItem(store.getState(), existing) ?? windowId));\n return existing;\n }\n // Minted here, not in the reducer, so a remote store can name it before the main process answers.\n shared.launcherSeq += 1;\n const key = `${Date.now().toString(36)}-${shared.launcherSeq}`;\n dispatch(canvasActions.open({ kind: CANVAS_LAUNCHER_KIND, key, target: { paneId: target }, ...(windowId === CANVAS_MAIN_WINDOW ? {} : { windowId }) }));\n return canvasItemId(CANVAS_LAUNCHER_KIND, key);\n },\n rekey(itemId, key) {\n const item = store.getState().items[itemId];\n if (!item) return null;\n dispatch(canvasActions.rekey(itemId, key));\n return canvasItemId(item.kind, key);\n },\n close: (itemId) => dispatch(canvasActions.closeItem(itemId)),\n closeOthers: (itemId) => dispatch(canvasActions.closeOthers(itemId)),\n activate: (itemId) => dispatch(canvasActions.activate(itemId)),\n focusPane: (paneId) => dispatch(canvasActions.focusPane(paneId)),\n moveItem: (itemId, toPaneId, index) => dispatch(canvasActions.moveItem(itemId, toPaneId, index)),\n splitPane: (paneId, orientation, moveItemId) => dispatch(canvasActions.splitPane(paneId, orientation, moveItemId, shareFor(orientation))),\n closePane: (paneId) => dispatch(canvasActions.closePane(paneId)),\n resizeSplit: (splitId, sizes) => dispatch(canvasActions.resizeSplit(splitId, sizes)),\n show: (w = windowId) => dispatch(canvasActions.setOpen(true, w)),\n hide: (w = windowId) => dispatch(canvasActions.setOpen(false, w)),\n toggle: (w = windowId) => dispatch(canvasActions.toggle(w)),\n setFullscreen: (fullscreen, w = windowId) => dispatch(canvasActions.setFullscreen(fullscreen, w)),\n setWidth: (width, w = windowId) => dispatch(canvasActions.setWidth(width, w)),\n async popOut(itemId) {\n const item = store.getState().items[itemId];\n if (!item) return null;\n const port = options.windowPorts?.().popOut;\n if (!port) {\n onError({ code: \"pop-out-unavailable\", message: \"This app cannot pop canvas tabs out into their own window.\", detail: { itemId } });\n return null;\n }\n let result: { readonly windowId: string } | null;\n try {\n result = await port(item);\n } catch (error) {\n onError({ code: \"pop-out-failed\", message: \"The window for this tab could not be opened.\", detail: error });\n return null;\n }\n if (!result) {\n onError({ code: \"pop-out-refused\", message: \"The app declined to pop this tab out.\", detail: { itemId } });\n return null;\n }\n const target = canvasWindowId(result.windowId);\n dispatch(canvasActions.popOut(itemId, target));\n return target;\n },\n dockBack(itemId) {\n const state = store.getState();\n const from = canvasWindowOfItem(state, itemId);\n if (!from || from === CANVAS_MAIN_WINDOW || state.windows[from]?.role !== \"pop-out\") return false;\n dispatch(canvasActions.dockBack(itemId));\n options.windowPorts?.().dockBack?.(itemId, from);\n return true;\n },\n closeWindow: (w, mode = \"dock\") => dispatch(canvasActions.closeWindow(w, mode)),\n has: (kind, key) => canvasItemId(kind, key) in store.getState().items,\n isPresented: (w = windowId) => (shared.presentations.get(w) ?? 0) > 0,\n registerPresentation(w = windowId) {\n shared.presentations.set(w, (shared.presentations.get(w) ?? 0) + 1);\n notifyPresentation();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n shared.presentations.set(w, Math.max(0, (shared.presentations.get(w) ?? 1) - 1));\n notifyPresentation();\n };\n },\n subscribePresentation(listener) {\n shared.presentationListeners.add(listener);\n return () => shared.presentationListeners.delete(listener);\n },\n start() {\n let disposed = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let lastSaved: CanvasState | null = null;\n // Another process owns a remote store: it hydrates and saves; this side only renders.\n const owns = store.authority !== \"remote\";\n const memory = owns ? persistence : null;\n\n const save = () => {\n timer = null;\n const state = store.getState();\n if (!memory || !state.hydrated || state === lastSaved) return;\n lastSaved = state;\n try {\n void Promise.resolve(memory.save(toPersistableSnapshot(state, isRestorable))).catch((error: unknown) =>\n onError({ code: \"persistence-save\", message: \"Saving the canvas layout failed.\", detail: error }),\n );\n } catch (error) {\n onError({ code: \"persistence-save\", message: \"Saving the canvas layout failed.\", detail: error });\n }\n };\n\n // A host store dispatches constantly (streaming, typing). Only a change\n // to the CANVAS state reschedules the save, or a busy app starves it.\n let seen = store.getState();\n const unsubscribe = store.subscribe(() => {\n if (!memory || disposed) return;\n const current = store.getState();\n if (current === seen) return;\n seen = current;\n if (timer) clearTimeout(timer);\n timer = setTimeout(save, options.saveDelayMs ?? 250);\n });\n\n if (!owns || store.getState().hydrated) {\n // Already hydrated (a second provider over the same store), or owned elsewhere.\n } else if (!memory) {\n dispatch(canvasActions.hydrate(null));\n } else {\n Promise.resolve()\n .then(() => memory.load())\n .then(\n (snapshot) => {\n if (disposed) return;\n const openedThisSession = store.getState().isOpen;\n const validSnapshot = snapshot === null ? null : sanitizeCanvasSnapshot(snapshot);\n if (snapshot !== null && validSnapshot === null) {\n onError({ code: \"persistence-load\", message: \"The saved canvas layout is invalid. Clear the saved layout or repair the persistence port.\" });\n }\n dispatch(canvasActions.hydrate(validSnapshot));\n if (!openedThisSession && options.mayRestoreOpen && !options.mayRestoreOpen() && store.getState().isOpen) {\n dispatch(canvasActions.setOpen(false));\n }\n },\n (error: unknown) => {\n onError({ code: \"persistence-load\", message: \"The saved canvas layout could not be read.\", detail: error });\n if (!disposed) dispatch(canvasActions.hydrate(null));\n },\n );\n }\n\n const stopSessions = startSessions(shared, windowId);\n\n return () => {\n disposed = true;\n unsubscribe();\n stopSessions();\n if (timer) {\n clearTimeout(timer);\n save();\n }\n };\n },\n };\n shared.views.set(windowId, controller);\n return controller;\n}\n\n/**\n * Session lifecycle tracking, once per controller family. A local store is\n * one process showing every window, so it tracks them all; a remote store is\n * one window's renderer, so it tracks only the windows started here — a tab\n * moving to another process's window LEAVES and ARRIVES there.\n */\nfunction startSessions(shared: Shared, windowId: CanvasWindowId): () => void {\n const { options, onError } = shared;\n const sessions = options.sessions;\n if (!sessions) return () => undefined;\n shared.started.set(windowId, (shared.started.get(windowId) ?? 0) + 1);\n let stopped = false;\n if (!shared.sessionStop) {\n const store = options.store;\n const local = store.authority !== \"remote\";\n let tracked: Map<CanvasItemId, { item: CanvasItem; key: string; windowId: CanvasWindowId }> | null = null;\n\n const call = (fn: () => void) => {\n try {\n fn();\n } catch (error) {\n onError({ code: \"session-hook\", message: \"A canvas session hook threw.\", detail: error });\n }\n };\n\n const read = (fn: () => string | null): string | null => {\n try {\n return fn();\n } catch (error) {\n onError({ code: \"session-hook\", message: \"A canvas kind's sessionKey threw.\", detail: error });\n return null;\n }\n };\n\n let prevItems = new Set<CanvasItemId>();\n const snapshot = (state: CanvasState) => {\n const out = new Map<CanvasItemId, { item: CanvasItem; key: string; windowId: CanvasWindowId }>();\n for (const w of listCanvasWindowIds(state)) {\n if (!local && !shared.started.has(w)) continue;\n const frame = canvasWindowFrame(state, w);\n if (!frame) continue;\n for (const paneId of listPaneIds(frame.layout)) {\n for (const itemId of state.panes[paneId]?.itemIds ?? []) {\n const item = state.items[itemId];\n const hooks = item ? sessions(item.kind) : undefined;\n if (!item || !hooks) continue;\n const key = read(() => hooks.sessionKey(item));\n if (key) out.set(itemId, { item, key, windowId: w });\n }\n }\n }\n return out;\n };\n\n const sync = () => {\n const state = options.store.getState();\n if (!state.hydrated) return;\n const next = snapshot(state);\n const first = tracked === null;\n const prev = tracked ?? new Map();\n for (const [id, entry] of prev) {\n const now = next.get(id);\n if (now && now.key === entry.key) continue;\n const hooks = sessions(entry.item.kind);\n const reason: CanvasSessionDetachReason = state.items[id] && !now ? \"leave\" : \"close\";\n call(() => hooks?.onDetach?.({ item: entry.item, sessionKey: entry.key, windowId: entry.windowId, reason }));\n }\n for (const [id, entry] of next) {\n const before = prev.get(id);\n if (before && before.key === entry.key) continue;\n const hooks = sessions(entry.item.kind);\n const reason: CanvasSessionAttachReason = first ? \"restore\" : prevItems.has(id) ? \"arrive\" : \"open\";\n call(() => hooks?.onAttach?.({ item: entry.item, sessionKey: entry.key, windowId: entry.windowId, reason }));\n }\n tracked = next;\n prevItems = new Set(Object.keys(state.items) as CanvasItemId[]);\n };\n let lastState: CanvasState | null = null;\n const unsubscribe = store.subscribe(() => {\n const state = store.getState();\n if (state === lastState) return;\n lastState = state;\n sync();\n });\n sync();\n shared.sessionStop = () => {\n unsubscribe();\n for (const entry of tracked?.values() ?? []) {\n const hooks = sessions(entry.item.kind);\n call(() => hooks?.onDetach?.({ item: entry.item, sessionKey: entry.key, windowId: entry.windowId, reason: \"unmount\" }));\n }\n tracked = null;\n };\n }\n return () => {\n if (stopped) return;\n stopped = true;\n const left = (shared.started.get(windowId) ?? 1) - 1;\n if (left > 0) shared.started.set(windowId, left);\n else shared.started.delete(windowId);\n if (shared.started.size === 0 && shared.sessionStop) {\n const stop = shared.sessionStop;\n shared.sessionStop = null;\n stop();\n }\n };\n}\n","/**\n * Selectors over CanvasState. Each returns a value that is referentially\n * stable for an unchanged state, so they are safe in useSyncExternalStore and\n * in a host's useSelector. Window-scoped selectors default to the main window;\n * an unknown window reads as closed and empty.\n */\n\nimport { listPaneIds } from \"./layout\";\nimport { canvasWindowFrame, canvasWindowOfItem } from \"./reducer\";\nimport {\n CANVAS_MAIN_WINDOW,\n type CanvasExtraWindow,\n type CanvasHistoryEntry,\n type CanvasItem,\n type CanvasItemId,\n type CanvasLayoutNode,\n type CanvasPane,\n type CanvasPaneId,\n type CanvasState,\n type CanvasWindowId,\n} from \"./types\";\n\nconst frame = (s: CanvasState, w: CanvasWindowId | undefined) => canvasWindowFrame(s, w ?? CANVAS_MAIN_WINDOW);\n\nexport const selectCanvasIsOpen = (s: CanvasState, windowId?: CanvasWindowId): boolean => frame(s, windowId)?.isOpen ?? false;\nexport const selectCanvasIsFullscreen = (s: CanvasState, windowId?: CanvasWindowId): boolean => frame(s, windowId)?.isFullscreen ?? false;\n/** The width the person chose, or null while the host's layout rule decides. */\nexport const selectCanvasWidth = (s: CanvasState, windowId?: CanvasWindowId): number | null => frame(s, windowId)?.width ?? null;\nexport const selectCanvasLayout = (s: CanvasState, windowId?: CanvasWindowId): CanvasLayoutNode | null => frame(s, windowId)?.layout ?? null;\nexport const selectCanvasFocusedPaneId = (s: CanvasState, windowId?: CanvasWindowId): CanvasPaneId | null =>\n frame(s, windowId)?.focusedPaneId ?? null;\nexport const selectCanvasIsHydrated = (s: CanvasState): boolean => s.hydrated;\n/** Every item on the canvas, in every window. */\nexport const selectCanvasItemCount = (s: CanvasState): number => Object.keys(s.items).length;\n\nexport const selectCanvasPane = (s: CanvasState, paneId: CanvasPaneId): CanvasPane | undefined => s.panes[paneId];\nexport const selectCanvasItem = (s: CanvasState, itemId: CanvasItemId): CanvasItem | undefined => s.items[itemId];\n\nexport function selectCanvasPaneCount(s: CanvasState, windowId?: CanvasWindowId): number {\n const layout = frame(s, windowId)?.layout;\n return layout ? listPaneIds(layout).length : 0;\n}\n\n/** Items shown in one window. */\nexport function selectCanvasWindowItemCount(s: CanvasState, windowId?: CanvasWindowId): number {\n const layout = frame(s, windowId)?.layout;\n if (!layout) return 0;\n return listPaneIds(layout).reduce((sum, paneId) => sum + (s.panes[paneId]?.itemIds.length ?? 0), 0);\n}\n\n/** The item the person is looking at in a window's focused pane. */\nexport function selectCanvasActiveItem(s: CanvasState, windowId?: CanvasWindowId): CanvasItem | null {\n const f = frame(s, windowId);\n const pane = f ? s.panes[f.focusedPaneId] : undefined;\n return pane?.activeItemId ? (s.items[pane.activeItemId] ?? null) : null;\n}\n\nconst NO_WINDOWS: CanvasState[\"windows\"] = Object.freeze({});\n\n/** Windows other than main (second app windows and pop-outs), by id. Stable per state. */\nexport function selectCanvasWindows(s: CanvasState): CanvasState[\"windows\"] {\n return s.windows ?? NO_WINDOWS;\n}\n\n/** One extra window, or undefined (main is never in this map). */\nexport const selectCanvasExtraWindow = (s: CanvasState, windowId: CanvasWindowId): CanvasExtraWindow | undefined => s.windows?.[windowId];\n\n/** The window an item is in, or null when it is not on the canvas. */\nexport const selectCanvasWindowOfItem = canvasWindowOfItem;\n\nconst NO_HISTORY: readonly CanvasHistoryEntry[] = Object.freeze([]);\n\n/** What a tab showed before, oldest first. Stable per state. */\nexport function selectCanvasItemHistory(s: CanvasState, itemId: CanvasItemId): readonly CanvasHistoryEntry[] {\n return s.items[itemId]?.history ?? NO_HISTORY;\n}\n\n/** Whether a tab offers Back (it navigated in place). */\nexport const selectCanvasCanGoBack = (s: CanvasState, itemId: CanvasItemId): boolean => (s.items[itemId]?.history?.length ?? 0) > 0;\n\n/** Whether a tab offers Forward (it went Back and has not navigated elsewhere since). */\nexport const selectCanvasCanGoForward = (s: CanvasState, itemId: CanvasItemId): boolean => (s.items[itemId]?.forward?.length ?? 0) > 0;\n\n/**\n * The ONE pane a phone presents: the focused pane when it holds a tab, else\n * the first pane that does (an empty pane is never presented over tabs that\n * exist — the header and the body always describe the same pane), else the\n * focused one.\n */\nexport function selectCanvasPresentedPaneId(s: CanvasState, windowId?: CanvasWindowId): CanvasPaneId | null {\n const f = frame(s, windowId);\n if (!f) return null;\n const ids = listPaneIds(f.layout);\n const holds = (id: CanvasPaneId) => (s.panes[id]?.itemIds.length ?? 0) > 0;\n const focused = ids.find((id) => id === f.focusedPaneId);\n if (focused && holds(focused)) return focused;\n return ids.find(holds) ?? focused ?? ids[0] ?? null;\n}\n","/**\n * Presentation — what a body knows about the space the canvas gives it.\n *\n * A body rendered in the canvas is told so, and told its live shape: a tall\n * narrow pane is not a wide page. Content that lays itself out in a direction\n * (a graph, a timeline, a row of cards) reads `orientation` and flows down a\n * portrait pane instead of across it. Pure data and pure functions, so a\n * desktop main process can compute the same answer for a native view.\n */\n\nexport type CanvasPresentationOrientation = \"portrait\" | \"landscape\" | \"square\";\n\nexport interface CanvasPresentation {\n /** Always \"canvas\" — a body rendered anywhere else gets no presentation at all. */\n readonly host: \"canvas\";\n /** The body's size in CSS pixels, live. */\n readonly width: number;\n readonly height: number;\n readonly orientation: CanvasPresentationOrientation;\n /** Narrower than `CANVAS_NARROW_WIDTH`: one column of content at most. */\n readonly isNarrow: boolean;\n /** The canvas is expanded to fill the space its host gives it. */\n readonly isFullscreen: boolean;\n /** How many panes the window's canvas shows right now. */\n readonly paneCount: number;\n}\n\n/**\n * THE phone breakpoint: a viewport at most this wide (CSS px) is a phone —\n * the canvas is a full-screen layer and presents ONE pane at a time. Same\n * number as styles.css `@media (max-width: 767px)`.\n */\nexport const CANVAS_PHONE_MAX_WIDTH = 767;\n\n/** Under this width (px) a body is narrow. */\nexport const CANVAS_NARROW_WIDTH = 480;\n\n/** Width ÷ height past which a body is landscape (and under whose inverse, portrait). */\nconst SQUARE_BAND = 1.2;\n\nexport function canvasOrientation(width: number, height: number): CanvasPresentationOrientation {\n if (!(width > 0) || !(height > 0)) return \"square\";\n const ratio = width / height;\n if (ratio >= SQUARE_BAND) return \"landscape\";\n if (ratio <= 1 / SQUARE_BAND) return \"portrait\";\n return \"square\";\n}\n\nexport function canvasPresentation(input: {\n readonly width: number;\n readonly height: number;\n readonly isFullscreen: boolean;\n readonly paneCount: number;\n}): CanvasPresentation {\n const width = Math.max(0, Math.round(input.width));\n const height = Math.max(0, Math.round(input.height));\n return {\n host: \"canvas\",\n width,\n height,\n orientation: canvasOrientation(width, height),\n isNarrow: width > 0 && width < CANVAS_NARROW_WIDTH,\n isFullscreen: input.isFullscreen,\n paneCount: Math.max(1, input.paneCount),\n };\n}\n\n/**\n * Which way content with a layout direction should flow: \"vertical\" (top to\n * bottom) in a portrait or narrow body, \"horizontal\" (left to right) otherwise\n * and outside the canvas.\n */\nexport function preferredFlowDirection(presentation: CanvasPresentation | null | undefined): \"vertical\" | \"horizontal\" {\n if (!presentation) return \"horizontal\";\n if (presentation.orientation === \"portrait\") return \"vertical\";\n if (presentation.orientation === \"landscape\") return \"horizontal\";\n return presentation.isNarrow ? \"vertical\" : \"horizontal\";\n}\n","/**\n * \"Toggle or focus this kind\" — what a toolbar icon does (the desktop's\n * Terminal/Review/Browser icons, the web's quick-tool launchers):\n *\n * absent → open it (and reveal the canvas)\n * background → bring it forward: activate its tab, focus its pane, reveal\n * visible → close it (default) or put the canvas away (`whenVisible: \"hide\"`);\n * closing the canvas's LAST tab puts the canvas away too — a toggle\n * never leaves an empty \"New tab\" launcher behind\n *\n * \"Visible\" means: on the canvas, the active tab of its pane, and its window's\n * canvas is open. The same item in a popped-out window counts in that window.\n */\n\nimport { canvasItemId } from \"./ids\";\nimport { canvasWindowFrame, canvasWindowOfItem } from \"./reducer\";\nimport type { CanvasController } from \"./controller\";\nimport { selectCanvasWindowItemCount } from \"./selectors\";\nimport type { CanvasJson, CanvasState } from \"./types\";\n\nexport type CanvasKindVisibility = \"absent\" | \"background\" | \"visible\";\n\nexport const CANVAS_DEFAULT_KEY = \"default\";\n\n/** Stable primitive result — safe in useSyncExternalStore and useSelector. */\nexport function selectCanvasKindVisibility(state: CanvasState, kind: string, key: string = CANVAS_DEFAULT_KEY): CanvasKindVisibility {\n const itemId = canvasItemId(kind, key);\n if (!state.items[itemId]) return \"absent\";\n const windowId = canvasWindowOfItem(state, itemId);\n if (!windowId) return \"background\";\n const isOpen = canvasWindowFrame(state, windowId)?.isOpen ?? false;\n const pane = Object.values(state.panes).find((p) => p.itemIds.includes(itemId));\n return isOpen && pane?.activeItemId === itemId ? \"visible\" : \"background\";\n}\n\nexport interface ToggleKindInput {\n readonly kind: string;\n /** Default \"default\" — one instance of the kind (a toolbar tool). */\n readonly key?: string | undefined;\n /** Data for a NEW item; an existing item keeps its data. */\n readonly data?: CanvasJson | undefined;\n readonly title?: string | null | undefined;\n /** What a click does when the item is already in front. Default \"close\". */\n readonly whenVisible?: \"close\" | \"hide\" | undefined;\n}\n\n/** Returns what the item is after the click. */\nexport function toggleKind(controller: CanvasController, input: ToggleKindInput): CanvasKindVisibility {\n const key = input.key ?? CANVAS_DEFAULT_KEY;\n const itemId = canvasItemId(input.kind, key);\n const before = selectCanvasKindVisibility(controller.getState(), input.kind, key);\n\n if (before === \"visible\") {\n if ((input.whenVisible ?? \"close\") === \"close\") {\n const windowId = canvasWindowOfItem(controller.getState(), itemId);\n controller.close(itemId);\n // That was everything this canvas held: put it away instead of leaving an empty launcher open.\n if (windowId && selectCanvasWindowItemCount(controller.getState(), windowId) === 0) controller.hide(windowId);\n } else {\n controller.hide(canvasWindowOfItem(controller.getState(), itemId) ?? undefined);\n }\n return selectCanvasKindVisibility(controller.getState(), input.kind, key);\n }\n\n if (before === \"background\") {\n // An existing item is never re-fed data: open() activates, focuses its pane and reveals.\n controller.open({ kind: input.kind, key });\n const windowId = canvasWindowOfItem(controller.getState(), itemId);\n if (windowId) controller.show(windowId);\n return selectCanvasKindVisibility(controller.getState(), input.kind, key);\n }\n\n const opened = controller.open({\n kind: input.kind,\n key,\n ...(input.data !== undefined ? { data: input.data } : {}),\n ...(input.title !== undefined ? { title: input.title } : {}),\n });\n return opened ? selectCanvasKindVisibility(controller.getState(), input.kind, key) : \"absent\";\n}\n","\"use client\";\n\n/**\n * Everything that must be able to draw ABOVE a native view.\n *\n * A desktop host draws some canvas bodies outside the DOM (an Electron\n * WebContentsView). Native views always paint over the page, so anything the\n * canvas floats — tooltips, drop indicators, the tab being dragged, menus —\n * goes through ports the host can implement in its own overlay layer. The\n * defaults draw in the DOM (a portal on document.body), which is right for\n * every host without native views.\n *\n * While package DOM floats over the canvas (a DOM menu is open, a tab is being\n * dragged), native bodies are reported `visible: false` so the host can hide\n * them: the DOM underneath must be seen, and must receive the drop.\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { CanvasItemId, CanvasPaneId, CanvasRect, CanvasWindowId } from \"../index\";\n\n/** One floating thing. Plain data, so a host can draw it in another process. */\nexport type CanvasFloating =\n | { readonly type: \"tooltip\"; readonly text: string; readonly anchor: CanvasRect; readonly side: \"top\" | \"bottom\" }\n | { readonly type: \"drop-indicator\"; readonly rect: CanvasRect; readonly paneId: CanvasPaneId }\n | { readonly type: \"tab-drag\"; readonly itemId: CanvasItemId; readonly title: string };\n\nexport interface CanvasOverlayPort {\n /** Shows a floating element above everything (native views included); returns its remover. */\n show(element: CanvasFloating): () => void;\n}\n\n/** A serializable \"…\" menu: the package keeps the handlers, a host draws the entries. */\nexport type CanvasMenuEntry =\n | { readonly type: \"item\"; readonly id: string; readonly label: string; readonly destructive?: boolean }\n | { readonly type: \"separator\" };\n\n/** Shows a menu at `anchor` (e.g. Electron `Menu.popup`); resolves the chosen entry id, or null. */\nexport type CanvasShowMenu = (entries: readonly CanvasMenuEntry[], anchor: CanvasRect) => Promise<string | null>;\n\n/** A native body's frame: window CSS pixels plus the device pixel ratio. */\nexport interface CanvasNativeRect extends CanvasRect {\n readonly devicePixelRatio: number;\n}\n\nexport interface CanvasNativeBodyInfo {\n /** False while package DOM floats over the canvas (a DOM menu, a tab drag): hide the native view. */\n readonly visible: boolean;\n readonly windowId: CanvasWindowId;\n}\n\n/** Reports where a native body sits; null when it is hidden or gone. Called in the frame the layout changed. */\nexport type CanvasNativeBodyFrame = (itemId: CanvasItemId, rect: CanvasNativeRect | null, info: CanvasNativeBodyInfo) => void;\n\nexport interface CanvasLayer {\n /** Shows through the host overlay port, or the DOM default. */\n show(element: CanvasFloating): () => void;\n /** Marks package DOM floating over the canvas (default DOM menu, tab drag). */\n beginBlocking(): () => void;\n isBlocked(): boolean;\n readonly dom: {\n list(): readonly (readonly [number, CanvasFloating])[];\n subscribe(listener: () => void): () => void;\n };\n readonly native: {\n register(measure: () => void): () => void;\n report(itemId: CanvasItemId, rect: CanvasNativeRect | null, info: CanvasNativeBodyInfo): void;\n /** Re-measures every native body now (call it per frame while the host animates its own layout). */\n remeasure(): void;\n };\n}\n\ninterface LayerPorts {\n readonly overlay?: CanvasOverlayPort | undefined;\n readonly onNativeBodyFrame?: CanvasNativeBodyFrame | undefined;\n}\n\nexport function createCanvasLayer(getPorts: () => LayerPorts): CanvasLayer {\n let elements: readonly (readonly [number, CanvasFloating])[] = [];\n let nextId = 1;\n const domListeners = new Set<() => void>();\n const emitDom = () => {\n for (const listener of [...domListeners]) listener();\n };\n let blocking = 0;\n const measures = new Set<() => void>();\n const last = new Map<CanvasItemId, string>();\n\n const remeasure = () => {\n for (const measure of [...measures]) measure();\n };\n\n return {\n show(element) {\n const host = getPorts().overlay;\n if (host) return host.show(element);\n const id = nextId++;\n elements = [...elements, [id, element] as const];\n emitDom();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n elements = elements.filter(([key]) => key !== id);\n emitDom();\n };\n },\n beginBlocking() {\n blocking += 1;\n remeasure();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n blocking -= 1;\n remeasure();\n };\n },\n isBlocked: () => blocking > 0,\n dom: {\n list: () => elements,\n subscribe(listener) {\n domListeners.add(listener);\n return () => domListeners.delete(listener);\n },\n },\n native: {\n register(measure) {\n measures.add(measure);\n return () => measures.delete(measure);\n },\n report(itemId, rect, info) {\n const key = rect\n ? `${rect.x},${rect.y},${rect.width},${rect.height},${rect.devicePixelRatio},${info.visible},${info.windowId}`\n : `null,${info.windowId}`;\n if (last.get(itemId) === key) return;\n if (rect) last.set(itemId, key);\n else last.delete(itemId);\n getPorts().onNativeBodyFrame?.(itemId, rect, info);\n },\n remeasure,\n },\n };\n}\n\n/** Floating elements drawn in the DOM when the host gives no overlay port. */\nexport function CanvasDomOverlay({ layer }: { layer: CanvasLayer }) {\n const elements = useSyncExternalStore(layer.dom.subscribe, layer.dom.list, layer.dom.list);\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n if (!mounted || elements.length === 0 || typeof document === \"undefined\") return null;\n return createPortal(\n <div className=\"mxc-overlay\" aria-hidden=\"true\">\n {elements.map(([id, element]) => (\n <FloatingView key={id} element={element} />\n ))}\n </div>,\n document.body,\n );\n}\n\nfunction FloatingView({ element }: { element: CanvasFloating }) {\n if (element.type === \"drop-indicator\") {\n const { x, y, width, height } = element.rect;\n return <div className=\"mxc-drop-indicator\" style={{ left: x, top: y, width, height }} />;\n }\n if (element.type === \"tooltip\") return <Tooltip element={element} />;\n return null;\n}\n\nfunction Tooltip({ element }: { element: Extract<CanvasFloating, { type: \"tooltip\" }> }) {\n const ref = useRef<HTMLDivElement>(null);\n const { anchor, side, text } = element;\n const top = side === \"bottom\" ? anchor.y + anchor.height + 6 : anchor.y - 6;\n const centre = anchor.x + anchor.width / 2;\n // Kept inside the window: a close button sits at the window's right edge.\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n const width = el.offsetWidth;\n const left = Math.min(Math.max(4, centre - width / 2), Math.max(4, window.innerWidth - width - 4));\n el.style.left = `${left}px`;\n el.style.visibility = \"visible\";\n }, [centre, text]);\n return (\n <div ref={ref} className=\"mxc-tooltip\" data-side={side} role=\"tooltip\" style={{ top, left: centre, visibility: \"hidden\" }}>\n {text}\n </div>\n );\n}\n\n/** A DOMRect as plain data. */\nexport function toCanvasRect(rect: { left: number; top: number; width: number; height: number }): CanvasRect {\n return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };\n}\n","/**\n * THE canvas kind registry. A kind is one sort of thing the canvas can show —\n * an artifact, a document, a chat, a notification feed. Any feature adds a\n * kind with ONE call and never touches canvas code:\n *\n * registerCanvasKind(defineCanvasKind<{ noteId: string }>({\n * id: \"note\",\n * label: \"Note\",\n * icon: NoteIcon,\n * load: () => import(\"./NoteCanvasView\"),\n * title: (data) => data.noteId,\n * }));\n *\n * The registry lives on globalThis under a Symbol.for key so duplicated\n * bundles (ESM + CJS, two chunks) share ONE registry.\n */\n\nimport type { ComponentType, ReactNode } from \"react\";\nimport type {\n CanvasController,\n CanvasItem,\n CanvasJson,\n CanvasPaneId,\n CanvasPreferredTarget,\n CanvasPresentation,\n CanvasSessionAttachReason,\n CanvasSessionDetachReason,\n CanvasSessionEvent,\n CanvasWindowId,\n} from \"../index\";\n\nexport interface CanvasKindProps<TData extends CanvasJson = CanvasJson> {\n readonly item: CanvasItem;\n readonly data: TData;\n readonly paneId: CanvasPaneId;\n readonly isFocused: boolean;\n /**\n * On screen right now: its tab is active and its canvas is open. A body\n * stays mounted while hidden (a background tab, a put-away canvas) — pause\n * costly work (polling, animation) while this is false.\n */\n readonly isVisible: boolean;\n /** The canvas, acting for the window this pane is in. */\n readonly canvas: CanvasController;\n readonly windowId: CanvasWindowId;\n /**\n * The space this body has, live: size, orientation, narrow, expanded, pane\n * count. Lay content out for it (a graph in a tall narrow pane flows top to\n * bottom). Nested components read the same value with `useCanvasPresentation()`.\n */\n readonly presentation: CanvasPresentation;\n}\n\nexport interface CanvasMenuItem {\n readonly id: string;\n readonly label: string;\n readonly icon?: ReactNode;\n readonly onSelect: () => void;\n readonly destructive?: boolean;\n}\n\nexport interface CanvasKind<TData extends CanvasJson = CanvasJson> {\n readonly id: string;\n /** Singular noun shown in menus and the empty-pane launcher. */\n readonly label: string;\n readonly icon: ComponentType<{ className?: string }>;\n /** Eager component. Provide this OR `load` (optional for a native body or an `unavailable` placeholder). */\n readonly component?: ComponentType<CanvasKindProps<TData>>;\n /** Lazy component — the kind's code loads only when a tab of it renders. */\n readonly load?: () => Promise<{ default: ComponentType<CanvasKindProps<TData>> }>;\n /** Tab title from the item's data. Falls back to the item's title, then `label`. */\n readonly title?: (data: TData, item: CanvasItem) => string;\n /**\n * Comes back after a reload. Default true; false for live things that cannot\n * resume. \"session\": the tab is a view onto a process the HOST keeps (a\n * terminal) — it comes back, closing it DETACHES (onDetach) instead of\n * killing, and a restore or a move REATTACHES (onAttach).\n */\n readonly restore?: boolean | \"session\";\n /** restore \"session\": the session's key. Default: `data.sessionKey` when it is a string. */\n readonly sessionKey?: (data: TData, item: CanvasItem) => string | null;\n /** restore \"session\": the tab now shows this session (\"open\" | \"restore\" | \"arrive\"). */\n readonly onAttach?: (event: CanvasSessionEvent<CanvasSessionAttachReason>) => void;\n /** restore \"session\": the tab no longer shows it (\"close\" | \"leave\" | \"unmount\"). Never kill the process here. */\n readonly onDetach?: (event: CanvasSessionEvent<CanvasSessionDetachReason>) => void;\n /**\n * @deprecated Since 0.5.0 every body stays mounted from the first time it\n * is shown until its tab closes — through tab switches, splits, moves,\n * expand and the canvas being put away. This field changes nothing.\n */\n readonly keepAlive?: boolean;\n /**\n * Opt OUT of staying mounted: the body unmounts whenever it is not on\n * screen (a hidden tab, a put-away canvas) and mounts fresh when shown.\n * Only for genuinely heavy bodies whose state is cheap to rebuild.\n */\n readonly unmountWhenHidden?: boolean;\n /**\n * Where a NEW item of this kind opens while the canvas already shows\n * something: \"split-down\" puts it in a pane below (the layout rules' split\n * share — a feed under the work), \"split-right\" beside, \"focused\" (default)\n * in the focused pane. A pane already showing this kind takes it instead of\n * a new split. A caller's explicit `target` always wins.\n */\n readonly preferredTarget?: CanvasPreferredTarget;\n /**\n * \"native\": the body is drawn by the HOST outside the DOM (an Electron\n * WebContentsView). The pane renders a placeholder and reports its rect\n * through the provider's `onNativeBodyFrame`. Default \"dom\".\n */\n readonly body?: \"dom\" | \"native\";\n /**\n * An honest one-line state instead of the body while its backend is not\n * there (\"Files · next release\", \"No changes to show\"). Return null to show\n * the body. Read on every render.\n */\n readonly unavailable?: (data: TData, item: CanvasItem) => string | null;\n /** When set, the kind is offered in an empty pane's launcher. */\n readonly launcher?: { readonly key: string; readonly data: TData; readonly title?: string };\n /**\n * Controls at the START of the pane header, after the title or tabs: a\n * \"+ new terminal\", a browser's back / forward / reload / address bar. The\n * slot grows to fill the header.\n */\n readonly HeaderLeading?: ComponentType<CanvasKindProps<TData>>;\n /** The kind's own button, rendered left of the pane's \"…\" menu. */\n readonly HeaderAction?: ComponentType<CanvasKindProps<TData>>;\n /**\n * A toolbar ROW between the pane header and the body, for the active item\n * only (a browser's back / forward / reload / address / screenshot). Always\n * DOM, never covered by a native view: a `body: \"native\"` frame is measured\n * BELOW it.\n */\n readonly Toolbar?: ComponentType<CanvasKindProps<TData>>;\n /** Kind-specific entries for the pane's \"…\" menu. */\n readonly menuItems?: (props: CanvasKindProps<TData>) => readonly CanvasMenuItem[];\n}\n\n/** Erased form stored in the registry. */\nexport type AnyCanvasKind = CanvasKind<CanvasJson>;\n\n/**\n * Typed authoring helper. The data type is a promise the kind's opener keeps;\n * the registry stores the erased form (the cast is the one registration seam).\n */\nexport function defineCanvasKind<TData extends CanvasJson>(kind: CanvasKind<TData>): AnyCanvasKind {\n if (!kind.component && !kind.load && kind.body !== \"native\" && !kind.unavailable) {\n throw new Error(`[@ai-matrx/canvas] kind \"${kind.id}\" needs a component, a load(), a native body or an unavailable() state.`);\n }\n return kind as unknown as AnyCanvasKind;\n}\n\n/** The session key of an item of a session kind (`kind.sessionKey`, else `data.sessionKey`). */\nexport function canvasSessionKey(kind: AnyCanvasKind, item: CanvasItem): string | null {\n if (kind.sessionKey) return kind.sessionKey(item.data, item);\n const data = item.data;\n if (data && typeof data === \"object\" && !Array.isArray(data)) {\n const key = (data as { readonly [key: string]: CanvasJson | undefined }).sessionKey;\n return typeof key === \"string\" && key ? key : null;\n }\n return null;\n}\n\ninterface RegistryState {\n kinds: Map<string, AnyCanvasKind>;\n listeners: Set<() => void>;\n version: number;\n}\n\nconst REGISTRY = Symbol.for(\"ai-matrx.canvas.kinds\");\n\nfunction registry(): RegistryState {\n const g = globalThis as unknown as { [REGISTRY]?: RegistryState };\n g[REGISTRY] ??= { kinds: new Map(), listeners: new Set(), version: 0 };\n return g[REGISTRY];\n}\n\nfunction notify(state: RegistryState) {\n state.version += 1;\n for (const listener of [...state.listeners]) listener();\n}\n\n/** Registers (or replaces) a kind. Returns an unregister function. */\nexport function registerCanvasKind(kind: AnyCanvasKind): () => void {\n const state = registry();\n state.kinds.set(kind.id, kind);\n notify(state);\n return () => {\n if (state.kinds.get(kind.id) === kind) {\n state.kinds.delete(kind.id);\n notify(state);\n }\n };\n}\n\nexport function registerCanvasKinds(kinds: readonly AnyCanvasKind[]): () => void {\n const undo = kinds.map(registerCanvasKind);\n return () => undo.forEach((fn) => fn());\n}\n\nexport function getCanvasKind(id: string): AnyCanvasKind | undefined {\n return registry().kinds.get(id);\n}\n\nexport function listCanvasKinds(): AnyCanvasKind[] {\n return [...registry().kinds.values()];\n}\n\nexport function subscribeCanvasKinds(listener: () => void): () => void {\n const state = registry();\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nexport function getCanvasKindsVersion(): number {\n return registry().version;\n}\n","\"use client\";\n\n/**\n * The canvas column: full height, right edge, its own strip of the top of the\n * window. Width drags from the left edge; panes split in either direction;\n * expanded, it fills whatever space the HOST placed it in. On a phone it\n * becomes a full-screen layer.\n *\n * Hosts with their own shell place <CanvasColumn/> and read\n * `useCanvasColumnWidth()` for the track size (desktop: tell the provider the\n * `regionWidth` the canvas shares). Hosts without one wrap their app in\n * <CanvasFrame>. A pop-out window renders `<CanvasColumn placement=\"fill\"/>`.\n *\n * The column NEVER unmounts while its provider lives: put away, it is 0 wide,\n * `inert` and hidden, and every body in it keeps its state. Opening, closing,\n * expanding and width changes animate on ONE motion contract —\n * `--mxc-motion-duration` / `--mxc-motion-ease` (default 600ms,\n * cubic-bezier(0.4, 0, 0.2, 1): the shell sidebar's slide) — and the content\n * keeps its width while the column slides, so it moves instead of reflowing.\n * A host shell that reflows beside the column transitions on the same two\n * properties (see README § Motion).\n */\n\nimport {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n type CSSProperties,\n type PointerEvent as ReactPointerEvent,\n type ReactNode,\n} from \"react\";\nimport { TapTargetButton, TapTargetButtonTransparent } from \"@ai-matrx/tap-target\";\nimport {\n CANVAS_DEFAULT_KEY,\n CANVAS_PHONE_MAX_WIDTH,\n listPaneIds,\n selectCanvasPresentedPaneId,\n CANVAS_MIN_SPLIT_FRACTION,\n canvasShortcutHint,\n clampDraggedCanvasWidth,\n fitCanvasWidth,\n selectCanvasIsFullscreen,\n selectCanvasIsOpen,\n selectCanvasLayout,\n selectCanvasWidth,\n selectCanvasWindowItemCount,\n shouldStackSplit,\n type CanvasJson,\n type CanvasLayoutNode,\n type CanvasPaneId,\n} from \"../index\";\nimport { CanvasBodyLayer } from \"./bodies\";\nimport { beginCanvasResize } from \"./resizeGesture\";\nimport { CanvasPaneView } from \"./CanvasPane\";\nimport { PanelRightIcon } from \"./icons\";\nimport { useCanvas, useCanvasInternals, useCanvasKind, useCanvasKindToggle, useCanvasState, useRegisterCanvasPresence } from \"./provider\";\nimport { CanvasSinglePaneContext, CanvasSlotsContext, createCanvasSlots } from \"./slots\";\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nfunction subscribeViewport(listener: () => void) {\n window.addEventListener(\"resize\", listener);\n return () => window.removeEventListener(\"resize\", listener);\n}\n\n/** The window's width, live; 0 during server render. */\nfunction useViewportWidth(): number {\n return useSyncExternalStore(subscribeViewport, () => window.innerWidth, () => 0);\n}\n\n/** The width of the space the canvas shares: the host's `regionWidth`, else the window. */\nfunction useRegionWidth(): number {\n const viewport = useViewportWidth();\n const { regionWidth } = useCanvasInternals();\n return regionWidth ?? viewport;\n}\n\n/** The column's rendered width in px for this window: 0 when put away, null when expanded. */\nexport function useCanvasColumnWidth(): number | null {\n const { controller, windowId } = useCanvasInternals();\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const width = useCanvasState((s) => selectCanvasWidth(s, windowId));\n const region = useRegionWidth();\n if (!isOpen) return 0;\n if (isFullscreen) return null;\n return fitCanvasWidth(width, region, controller.rules);\n}\n\nexport interface CanvasColumnProps {\n readonly className?: string;\n readonly style?: CSSProperties;\n /** Called with the live width while the edge is dragged, then null — lets a host shell reflow in step. */\n readonly onLiveWidth?: (width: number | null) => void;\n /** \"docked\": the right-edge column with a width handle. \"fill\": fills its container (a pop-out window). */\n readonly placement?: \"docked\" | \"fill\";\n}\n\nexport function CanvasColumn({ className, style, onLiveWidth, placement = \"docked\" }: CanvasColumnProps) {\n const { controller, windowId, layer } = useCanvasInternals();\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const width = useCanvasState((s) => selectCanvasWidth(s, windowId));\n const layout = useCanvasState((s) => selectCanvasLayout(s, windowId));\n const presentedPaneId = useCanvasState((s) => selectCanvasPresentedPaneId(s, windowId));\n const region = useRegionWidth();\n const viewport = useViewportWidth();\n // A phone presents ONE pane at a time (the focused one, carrying every pane's tabs); the\n // layout tree is untouched, so a wider screen gets its split back.\n const singlePane = placement === \"docked\" && viewport > 0 && viewport <= CANVAS_PHONE_MAX_WIDTH;\n const [dragWidth, setDragWidth] = useState<number | null>(null);\n const [slots] = useState(createCanvasSlots);\n const ref = useRef<HTMLElement>(null);\n useRegisterCanvasPresence();\n\n // While the column slides, native views follow it frame by frame (DOM bodies move with the column).\n useEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n let frame = 0;\n let running = false;\n const tick = () => {\n layer.native.remeasure();\n frame = running ? requestAnimationFrame(tick) : 0;\n };\n const start = (event: TransitionEvent) => {\n if (event.target !== el || running) return;\n running = true;\n frame = requestAnimationFrame(tick);\n };\n const stop = (event: TransitionEvent) => {\n if (event.target !== el) return;\n running = false;\n if (frame) cancelAnimationFrame(frame);\n frame = 0;\n layer.native.remeasure();\n };\n el.addEventListener(\"transitionrun\", start);\n el.addEventListener(\"transitionend\", stop);\n el.addEventListener(\"transitioncancel\", stop);\n return () => {\n running = false;\n if (frame) cancelAnimationFrame(frame);\n el.removeEventListener(\"transitionrun\", start);\n el.removeEventListener(\"transitionend\", stop);\n el.removeEventListener(\"transitioncancel\", stop);\n };\n }, [layer]);\n\n if (!layout) return null;\n const fitted = fitCanvasWidth(width, region, controller.rules);\n const shown = dragWidth ?? fitted;\n\n return (\n <aside\n ref={ref}\n className={[\"mxc-column\", className].filter(Boolean).join(\" \")}\n data-open={isOpen ? \"\" : undefined}\n data-fullscreen={isOpen && isFullscreen ? \"\" : undefined}\n data-placement={placement}\n data-mxc-window={windowId}\n aria-label=\"Canvas\"\n aria-hidden={isOpen ? undefined : true}\n inert={!isOpen}\n style={{ ...style, [\"--mxc-width\" as string]: `${shown}px` }}\n >\n <div className=\"mxc-column-inner\">\n {placement === \"docked\" && isOpen && !isFullscreen ? (\n <WidthHandle\n width={fitted}\n region={region}\n onDrag={(next) => {\n setDragWidth(next);\n onLiveWidth?.(next);\n }}\n />\n ) : null}\n <CanvasSlotsContext.Provider value={slots}>\n <CanvasSinglePaneContext.Provider value={singlePane}>\n <div className=\"mxc-layout\" data-single-pane={singlePane ? \"\" : undefined}>\n {singlePane ? <CanvasPaneView paneId={presentedPaneId ?? listPaneIds(layout)[0]!} /> : <LayoutNodeView node={layout} />}\n </div>\n <CanvasBodyLayer />\n </CanvasSinglePaneContext.Provider>\n </CanvasSlotsContext.Provider>\n </div>\n </aside>\n );\n}\n\nfunction WidthHandle({ width, region, onDrag }: { width: number; region: number; onDrag: (width: number | null) => void }) {\n const canvas = useCanvas();\n const start = useRef<{ x: number; width: number; end: () => void } | null>(null);\n useEffect(() => () => start.current?.end(), []);\n const clamp = (next: number) => clampDraggedCanvasWidth(next, region, canvas.rules);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n event.preventDefault();\n event.currentTarget.setPointerCapture(event.pointerId);\n start.current?.end();\n start.current = { x: event.clientX, width, end: beginCanvasResize(\"\") };\n };\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!start.current) return;\n onDrag(clamp(start.current.width + (start.current.x - event.clientX)));\n };\n const finish = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!start.current) return;\n const next = clamp(start.current.width + (start.current.x - event.clientX));\n start.current.end();\n start.current = null;\n onDrag(null);\n canvas.setWidth(next);\n };\n\n return (\n <div\n className=\"mxc-width-handle\"\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label=\"Resize canvas\"\n aria-valuenow={width}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={finish}\n onPointerCancel={finish}\n onLostPointerCapture={finish}\n onDoubleClick={() => canvas.setWidth(clamp(Math.round(region / 2)))}\n onKeyDown={(event) => {\n if (event.key === \"ArrowLeft\") canvas.setWidth(clamp(width + 32));\n if (event.key === \"ArrowRight\") canvas.setWidth(clamp(width - 32));\n }}\n />\n );\n}\n\nfunction LayoutNodeView({ node }: { node: CanvasLayoutNode }) {\n if (node.type === \"pane\") return <CanvasPaneView paneId={node.paneId} />;\n return <SplitView node={node} />;\n}\n\n/** Live width of an element, measured only when `enabled` (a rule needs it). */\nfunction useMeasuredWidth(ref: { current: HTMLElement | null }, enabled: boolean): number {\n const [width, setWidth] = useState(0);\n useIsoLayoutEffect(() => {\n const el = ref.current;\n if (!enabled || !el) return;\n setWidth(el.getBoundingClientRect().width);\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => setWidth(el.getBoundingClientRect().width));\n observer.observe(el);\n return () => observer.disconnect();\n }, [enabled]);\n return width;\n}\n\nfunction SplitView({ node }: { node: Extract<CanvasLayoutNode, { type: \"split\" }> }) {\n const canvas = useCanvas();\n const ref = useRef<HTMLDivElement>(null);\n const [liveSizes, setLiveSizes] = useState<readonly number[] | null>(null);\n const sizes = liveSizes ?? node.sizes;\n const measuredWidth = useMeasuredWidth(ref, node.orientation === \"horizontal\" && canvas.rules.paneMinWidth > 0);\n // Narrow windows stack side-by-side panes instead of squeezing them.\n const stacked = node.orientation === \"horizontal\" && shouldStackSplit(measuredWidth, node.children.length, canvas.rules);\n const orientation = stacked ? \"vertical\" : node.orientation;\n const horizontal = orientation === \"horizontal\";\n\n const beginDrag = (index: number) => (event: ReactPointerEvent<HTMLDivElement>) => {\n const el = ref.current;\n if (!el) return;\n event.preventDefault();\n event.currentTarget.setPointerCapture(event.pointerId);\n const rect = el.getBoundingClientRect();\n const total = horizontal ? rect.width : rect.height;\n const origin = horizontal ? event.clientX : event.clientY;\n const base = [...node.sizes];\n const pair = (base[index] ?? 0) + (base[index + 1] ?? 0);\n const target = event.currentTarget;\n const end = beginCanvasResize(horizontal ? \"col\" : \"row\");\n\n const compute = (pos: number) => {\n const delta = (pos - origin) / total;\n const min = CANVAS_MIN_SPLIT_FRACTION;\n const first = Math.min(pair - min, Math.max(min, (base[index] ?? 0) + delta));\n const next = [...base];\n next[index] = first;\n next[index + 1] = pair - first;\n return next;\n };\n const move = (e: PointerEvent) => setLiveSizes(compute(horizontal ? e.clientX : e.clientY));\n const up = (e: PointerEvent) => {\n target.removeEventListener(\"pointermove\", move);\n target.removeEventListener(\"pointerup\", up);\n target.removeEventListener(\"pointercancel\", up);\n end();\n setLiveSizes(null);\n canvas.resizeSplit(node.id, compute(horizontal ? e.clientX : e.clientY));\n };\n target.addEventListener(\"pointermove\", move);\n target.addEventListener(\"pointerup\", up);\n target.addEventListener(\"pointercancel\", up);\n };\n\n return (\n <div ref={ref} className=\"mxc-split\" data-orientation={orientation} data-stacked={stacked ? \"\" : undefined}>\n {node.children.map((child, i) => (\n <SplitChild\n key={child.type === \"pane\" ? child.paneId : child.id}\n size={sizes[i] ?? 1 / node.children.length}\n handle={\n i < node.children.length - 1 ? (\n <div\n className=\"mxc-split-handle\"\n role=\"separator\"\n aria-orientation={horizontal ? \"vertical\" : \"horizontal\"}\n onPointerDown={beginDrag(i)}\n onDoubleClick={() => canvas.resizeSplit(node.id, node.children.map(() => 1 / node.children.length))}\n />\n ) : null\n }\n >\n <LayoutNodeView node={child} />\n </SplitChild>\n ))}\n </div>\n );\n}\n\nfunction SplitChild({ size, handle, children }: { size: number; handle: ReactNode; children: ReactNode }) {\n return (\n <>\n <div className=\"mxc-split-child\" style={{ flexGrow: size, flexBasis: 0 }}>\n {children}\n </div>\n {handle}\n </>\n );\n}\n\nconst isMac = () => typeof navigator !== \"undefined\" && /mac|iphone|ipad/i.test(navigator.platform ?? \"\");\n\n/**\n * THE one button that opens and puts away the canvas (this window's).\n *\n * `variant` follows the tap-target PLACEMENT RULES (all glass or none): a host\n * whose header row is glass (a bar floating over scrolling content) passes\n * `\"glass\"` so the toggle matches its neighbours; on a solid bar keep the\n * default `\"transparent\"`.\n */\nexport function CanvasToggle({\n className,\n variant = \"transparent\",\n}: {\n className?: string;\n variant?: \"glass\" | \"transparent\";\n}) {\n const { controller, windowId } = useCanvasInternals();\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const count = useCanvasState((s) => selectCanvasWindowItemCount(s, windowId));\n const hint = canvasShortcutHint(\"canvas.toggle\", isMac());\n const Button = variant === \"glass\" ? TapTargetButton : TapTargetButtonTransparent;\n return (\n <span className={[\"mxc-toggle\", className].filter(Boolean).join(\" \")} data-open={isOpen ? \"\" : undefined}>\n <Button\n ariaLabel={isOpen ? \"Hide canvas\" : \"Show canvas\"}\n tooltip={`${isOpen ? \"Hide canvas\" : \"Show canvas\"}${hint ? ` (${hint})` : \"\"}`}\n icon={<PanelRightIcon />}\n pressed={isOpen}\n onClick={() => controller.toggle()}\n />\n {count > 0 && !isOpen ? <span className=\"mxc-toggle-badge\">{count}</span> : null}\n </span>\n );\n}\n\n/** One icon of a `CanvasKindIcons` cluster. A string is a kind on its \"default\" tab. */\nexport interface CanvasKindIcon {\n readonly kind: string;\n /** Default \"default\" — one instance of the kind (a toolbar tool). */\n readonly key?: string | undefined;\n /** Data for a NEW item; an open one keeps its own. */\n readonly data?: CanvasJson | undefined;\n readonly title?: string | null | undefined;\n /** What a press does while the item is in front: close it (default) or put the canvas away. */\n readonly whenVisible?: \"close\" | \"hide\" | undefined;\n /** Accessible name and tooltip. Default: the kind's label. */\n readonly label?: string | undefined;\n}\n\n/**\n * A cluster of icon buttons for pinned kinds — the tool icons of a header\n * (Terminal, Review, Browser…). Each toggles or focuses its kind and is drawn\n * pressed while its item is in front, so web and desktop show the same\n * cluster. A kind that is not registered draws nothing.\n */\nexport function CanvasKindIcons({\n kinds,\n variant = \"transparent\",\n className,\n label = \"Canvas tools\",\n}: {\n kinds: readonly (string | CanvasKindIcon)[];\n variant?: \"glass\" | \"transparent\";\n className?: string;\n label?: string;\n}) {\n return (\n <span role=\"group\" aria-label={label} className={[\"mxc-kind-icons\", className].filter(Boolean).join(\" \")}>\n {kinds.map((entry) => {\n const icon = typeof entry === \"string\" ? { kind: entry } : entry;\n return <KindIconButton key={`${icon.kind}::${icon.key ?? CANVAS_DEFAULT_KEY}`} icon={icon} variant={variant} />;\n })}\n </span>\n );\n}\n\nfunction KindIconButton({ icon, variant }: { icon: CanvasKindIcon; variant: \"glass\" | \"transparent\" }) {\n const kind = useCanvasKind(icon.kind);\n const toggle = useCanvasKindToggle({\n kind: icon.kind,\n key: icon.key,\n data: icon.data,\n title: icon.title,\n whenVisible: icon.whenVisible,\n });\n if (!kind) return null;\n const Icon = kind.icon;\n const Button = variant === \"glass\" ? TapTargetButton : TapTargetButtonTransparent;\n const name = icon.label ?? kind.label;\n return (\n <Button\n ariaLabel={name}\n tooltip={name}\n icon={<Icon />}\n pressed={toggle.isVisible}\n onClick={() => void toggle.toggle()}\n />\n );\n}\n\n/**\n * For hosts without their own shell (a Vite app, an Electron window): the app\n * on the left, the canvas column on the right, expand handled.\n */\nexport function CanvasFrame({ children, className }: { children: ReactNode; className?: string }) {\n const { windowId } = useCanvasInternals();\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n return (\n <div className={[\"mxc-frame\", className].filter(Boolean).join(\" \")} data-canvas-open={isOpen ? \"\" : undefined}>\n <div className=\"mxc-frame-main\" hidden={isOpen && isFullscreen}>\n {children}\n </div>\n <CanvasColumn />\n </div>\n );\n}\n","\"use client\";\n\n/**\n * THE stable body layer. Every item open in a window's canvas has ONE body,\n * rendered here — at the column root, keyed by the item's instance — and\n * placed over its pane's body slot by measured rect.\n *\n * tab switch → hide (never unmount)\n * split / move / resize → re-place (never remount, never re-parent)\n * expand / put away → re-place / hide\n *\n * So a body's React state, DOM focus and scroll position survive everything\n * but closing its tab. A body mounts the first time it is shown (a restored\n * background tab costs nothing until it is opened) and then stays mounted; a\n * kind may opt out with `unmountWhenHidden`. Native bodies are bodies on a\n * slot too: their placeholder lives in the same host and reports its frame.\n *\n * Moving a tab to ANOTHER window remounts it: that is a different column (on\n * the desktop, a different process).\n */\n\nimport {\n Component,\n Suspense,\n lazy,\n memo,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type ErrorInfo,\n type ReactNode,\n} from \"react\";\nimport {\n CANVAS_KEEP_ALIVE_DEPTH,\n canvasItemId,\n canvasPresentation,\n canvasWindowFrame,\n listPaneIds,\n selectCanvasPresentedPaneId,\n type CanvasController,\n type CanvasHistoryEntry,\n type CanvasItem,\n type CanvasItemId,\n type CanvasPaneId,\n type CanvasPresentation,\n type CanvasState,\n type CanvasWindowId,\n} from \"../index\";\nimport { CanvasPanelEmpty } from \"./chrome\";\nimport { usePaneDrop } from \"./dnd\";\nimport { AlertIcon } from \"./icons\";\nimport { toCanvasRect, type CanvasNativeRect } from \"./layer\";\nimport { useItemKind } from \"./launcher\";\nimport { CanvasPresentationContext } from \"./presentation\";\nimport { useCanvas, useCanvasInternals, useCanvasState } from \"./provider\";\nimport type { AnyCanvasKind, CanvasKindProps } from \"./registry\";\nimport { useCanvasSinglePane, useCanvasSlots, useSlotSize, type CanvasSlots } from \"./slots\";\n\n// The browser runs layout effects; a server render has no layout to report.\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\n// One lazy component per kind, shared across bodies and re-renders.\nconst LAZY = Symbol.for(\"ai-matrx.canvas.lazy\");\nfunction kindComponent(kind: AnyCanvasKind): ComponentType<CanvasKindProps> | null {\n if (kind.component) return kind.component;\n const holder = kind as AnyCanvasKind & { [LAZY]?: ComponentType<CanvasKindProps> };\n if (!holder[LAZY] && kind.load) holder[LAZY] = lazy(kind.load);\n return holder[LAZY] ?? null;\n}\n\n/** Forgets a kind's cached lazy component so \"Try again\" re-runs a failed chunk load. */\nfunction resetKindComponent(kind: AnyCanvasKind | undefined) {\n if (kind) delete (kind as AnyCanvasKind & { [LAZY]?: unknown })[LAZY];\n}\n\n/** The live presentation of a pane's slot (shared by its header controls and its bodies). */\nexport function usePanePresentation(slots: CanvasSlots, paneId: CanvasPaneId, isFullscreen: boolean, paneCount: number): CanvasPresentation {\n const size = useSlotSize(slots, paneId);\n return useMemo(\n () => canvasPresentation({ width: size.width, height: size.height, isFullscreen, paneCount }),\n [size.width, size.height, isFullscreen, paneCount],\n );\n}\n\ninterface Placed {\n readonly hostId: string;\n /** The live item — for a kept step, the tab that keeps it. */\n readonly itemId: CanvasItemId;\n readonly paneId: CanvasPaneId;\n readonly active: boolean;\n /** An earlier content of the tab, held mounted and hidden so Back (or forward) returns the same body. */\n readonly kept: boolean;\n}\n\ninterface LayerShape {\n readonly isOpen: boolean;\n readonly isFullscreen: boolean;\n readonly focusedPaneId: string;\n /** The one pane a phone presents (selectCanvasPresentedPaneId). */\n readonly presentedPaneId: string;\n readonly paneCount: number;\n readonly placed: readonly Placed[];\n}\n\nconst hostKey = (item: CanvasItem) => item.instance ?? item.id;\nconst SEP = \"\\u0001\";\nconst ROW = \"\\u0002\";\n\n/** When a body was first created: an instance starts with its birth time (base 36). Fallback: the item's. */\nfunction bornAt(instance: string | undefined, fallback: number): number {\n const stamp = instance ? Number.parseInt(instance.slice(0, instance.indexOf(\":\")), 36) : Number.NaN;\n return Number.isFinite(stamp) ? stamp : fallback;\n}\n\n/**\n * The earlier contents of a tab whose bodies stay mounted (hidden): the newest\n * CANVAS_KEEP_ALIVE_DEPTH steps Back reaches and the steps Back left. Only\n * entries that carry the body's instance can be kept.\n */\nexport function keptCanvasSteps(item: CanvasItem): readonly CanvasHistoryEntry[] {\n const back = (item.history ?? []).slice(-CANVAS_KEEP_ALIVE_DEPTH);\n const forward = (item.kept ?? []).slice(-CANVAS_KEEP_ALIVE_DEPTH);\n return [...back, ...forward].filter((entry) => !!entry.instance);\n}\n\n/**\n * What the layer needs, as ONE string — so the layer re-renders only when a\n * tab opens, closes, moves, activates, navigates or the frame changes, never\n * when a tab's DATA changes (each body reads its own item). Bodies are in a\n * STABLE order (when each was born): moving a tab, Back or forward never\n * reorders the DOM (a moved iframe reloads).\n */\nfunction layerSignature(state: CanvasState, windowId: CanvasWindowId, onlyPane?: CanvasPaneId): string {\n const frame = canvasWindowFrame(state, windowId);\n if (!frame) return \"\";\n const rows: { born: number; hostId: string; row: string }[] = [];\n const seen = new Set<string>();\n const add = (hostId: string, born: number, fields: string[]) => {\n if (seen.has(hostId)) return;\n seen.add(hostId);\n rows.push({ born, hostId, row: [hostId, ...fields].join(SEP) });\n };\n const paneIds = listPaneIds(frame.layout);\n for (const paneId of onlyPane ? [onlyPane] : paneIds) {\n const pane = state.panes[paneId];\n for (const itemId of pane?.itemIds ?? []) {\n const item = state.items[itemId];\n if (!item) continue;\n add(hostKey(item), bornAt(item.instance, item.openedAt), [itemId, paneId, pane?.activeItemId === itemId ? \"1\" : \"0\", \"0\"]);\n for (const step of keptCanvasSteps(item)) add(step.instance!, bornAt(step.instance, item.openedAt), [itemId, paneId, \"0\", \"1\"]);\n }\n }\n rows.sort((a, b) => a.born - b.born || a.hostId.localeCompare(b.hostId));\n const head = [\n frame.isOpen ? \"1\" : \"0\",\n frame.isFullscreen ? \"1\" : \"0\",\n frame.focusedPaneId,\n String(paneIds.length),\n selectCanvasPresentedPaneId(state, windowId) ?? \"\",\n ].join(SEP);\n return [head, ...rows.map((r) => r.row)].join(ROW);\n}\n\nfunction parseSignature(signature: string): LayerShape | null {\n if (!signature) return null;\n const [head = \"\", ...rows] = signature.split(ROW);\n const [open, full, focusedPaneId = \"\", count = \"1\", presentedPaneId = \"\"] = head.split(SEP);\n return {\n isOpen: open === \"1\",\n isFullscreen: full === \"1\",\n focusedPaneId,\n presentedPaneId,\n paneCount: Number(count) || 1,\n placed: rows.map((row) => {\n const [hostId = \"\", itemId = \"\", paneId = \"\", active, kept] = row.split(SEP);\n return { hostId, itemId: itemId as CanvasItemId, paneId: paneId as CanvasPaneId, active: active === \"1\", kept: kept === \"1\" };\n }),\n };\n}\n\ninterface HostEntry {\n readonly element: HTMLDivElement;\n readonly paneId: CanvasPaneId;\n}\n\ninterface Placement {\n register(key: string, entry: HostEntry): () => void;\n place(): void;\n}\n\nfunction createPlacement(getRoot: () => HTMLElement | null, slots: CanvasSlots, afterPlace: () => void): Placement {\n const hosts = new Map<string, HostEntry>();\n let placing = false;\n const place = () => {\n const root = getRoot();\n if (!root || placing) return;\n placing = true;\n try {\n slots.measure();\n const base = root.getBoundingClientRect();\n for (const { element, paneId } of hosts.values()) {\n const slot = slots.slot(paneId);\n if (!slot) {\n element.dataset.placed = \"false\";\n continue;\n }\n const box = slot.getBoundingClientRect();\n const style = element.style;\n style.left = `${box.left - base.left}px`;\n style.top = `${box.top - base.top}px`;\n style.width = `${box.width}px`;\n style.height = `${box.height}px`;\n element.dataset.placed = \"true\";\n }\n } finally {\n placing = false;\n }\n afterPlace();\n };\n return {\n register(key, entry) {\n hosts.set(key, entry);\n return () => {\n if (hosts.get(key) === entry) hosts.delete(key);\n };\n },\n place,\n };\n}\n\n/**\n * The column's body layer: every body of this window, placed over its pane.\n * Rendered by `CanvasColumn` after the layout, so slots are registered first.\n */\nexport function CanvasBodyLayer() {\n const { windowId, layer } = useCanvasInternals();\n const slots = useCanvasSlots();\n const signature = useCanvasState((s) => layerSignature(s, windowId));\n // A phone shows one pane: only that pane's active body is on screen.\n const single = useCanvasSinglePane();\n const root = useRef<HTMLDivElement>(null);\n const [placement] = useState(() =>\n slots ? createPlacement(() => root.current, slots, () => layer.native.remeasure()) : null,\n );\n\n // Every commit can move a slot (a split, a toolbar row, a closed pane): re-place before paint.\n useIsoLayoutEffect(() => placement?.place());\n // Between commits: a slot resized (a split dragged, the column resized, the window resized).\n useIsoLayoutEffect(() => (slots && placement ? slots.subscribe(placement.place) : undefined), [slots, placement]);\n\n const shape = parseSignature(signature);\n if (!slots || !placement || !shape) return null;\n return (\n <div ref={root} className=\"mxc-bodies\" data-mxc-bodies={windowId}>\n {shape.placed.map(({ hostId, itemId, paneId, active, kept }) => (\n <BodyHost\n key={hostId}\n hostId={hostId}\n itemId={itemId}\n kept={kept}\n paneId={paneId}\n visible={shape.isOpen && active && (!single || paneId === shape.presentedPaneId)}\n focused={active && shape.focusedPaneId === paneId}\n isFullscreen={shape.isFullscreen}\n paneCount={shape.paneCount}\n slots={slots}\n placement={placement}\n />\n ))}\n </div>\n );\n}\n\n/**\n * A pane rendered on its own (outside a CanvasColumn): its bodies render in\n * its slot, in flow. Moving a tab between such panes remounts its body — the\n * stable layer is the column's.\n */\nexport function CanvasPaneInlineBodies({ paneId, slots }: { paneId: CanvasPaneId; slots: CanvasSlots }) {\n const { windowId } = useCanvasInternals();\n const shape = parseSignature(useCanvasState((s) => layerSignature(s, windowId, paneId)));\n if (!shape) return null;\n return (\n <>\n {shape.placed.map(({ hostId, itemId, active, kept }) => (\n <BodyHost\n key={hostId}\n hostId={hostId}\n itemId={itemId}\n kept={kept}\n paneId={paneId}\n visible={active}\n focused={active && shape.focusedPaneId === paneId}\n isFullscreen={shape.isFullscreen}\n paneCount={shape.paneCount}\n slots={slots}\n placement={null}\n />\n ))}\n </>\n );\n}\n\n/** A kept step rendered as the item it was (its body sees the same identity it had live). */\nfunction stepAsItem(step: CanvasHistoryEntry, openedAt: number): CanvasItem {\n return {\n id: canvasItemId(step.kind, step.key),\n kind: step.kind,\n key: step.key,\n title: step.title,\n data: step.data,\n openedAt,\n updatedAt: openedAt,\n ...(step.instance ? { instance: step.instance } : {}),\n };\n}\n\n/** One body's host. Memoized on primitives: it re-renders for its OWN item, pane, visibility or focus — never another tab's. */\nconst BodyHost = memo(function BodyHost({\n hostId,\n itemId,\n kept,\n paneId,\n visible,\n focused,\n isFullscreen,\n paneCount,\n slots,\n placement,\n}: {\n hostId: string;\n itemId: CanvasItemId;\n kept: boolean;\n paneId: CanvasPaneId;\n visible: boolean;\n focused: boolean;\n isFullscreen: boolean;\n paneCount: number;\n slots: CanvasSlots;\n placement: Placement | null;\n}) {\n const canvas = useCanvas();\n const { windowId, ports } = useCanvasInternals();\n const live = useCanvasState((s) => (kept ? undefined : s.items[itemId]));\n // A kept step: the entry (a stable object until the tab's history changes) stands in as its item.\n const step = useCanvasState((s) => {\n const ownerItem = kept ? s.items[itemId] : undefined;\n return ownerItem ? keptCanvasSteps(ownerItem).find((e) => e.instance === hostId) : undefined;\n });\n const owner = useCanvasState((s) => (kept ? s.items[itemId]?.openedAt : undefined));\n const keptItem = useMemo(() => (step ? stepAsItem(step, owner ?? 0) : undefined), [step, owner]);\n const item = kept ? keptItem : live;\n const kind = useItemKind(item?.kind ?? \"\");\n const element = useRef<HTMLDivElement>(null);\n // Mounted from the first time it is on screen until its tab closes.\n const [everShown, setEverShown] = useState(visible);\n if (visible && !everShown) setEverShown(true);\n const mounted = kind?.unmountWhenHidden ? visible : everShown;\n const presentation = usePanePresentation(slots, paneId, isFullscreen, paneCount);\n const drop = usePaneDrop(paneId, () => slots.section(paneId));\n\n useIsoLayoutEffect(() => {\n const el = element.current;\n if (!placement || !el) return undefined;\n return placement.register(hostId, { element: el, paneId });\n }, [placement, hostId, paneId]);\n\n if (!item) return null;\n return (\n <div\n ref={element}\n className=\"mxc-item-host\"\n data-inline={placement ? undefined : \"\"}\n data-placed={placement ? \"false\" : undefined}\n data-visible={visible ? \"true\" : \"false\"}\n data-kind={item.kind}\n data-item={item.id}\n data-kept={kept ? \"\" : undefined}\n data-pane={paneId}\n inert={!visible}\n aria-hidden={visible ? undefined : true}\n onPointerDownCapture={() => {\n if (!focused) canvas.focusPane(paneId);\n }}\n {...drop}\n >\n {mounted ? (\n <CanvasPresentationContext.Provider value={presentation}>\n <div className=\"mxc-item\" data-kind={item.kind}>\n <ItemContent\n item={item}\n kind={kind}\n paneId={paneId}\n windowId={windowId}\n focused={focused}\n visible={visible}\n presentation={presentation}\n canvas={canvas}\n hasNativePort={!!ports.onNativeBodyFrame}\n />\n </div>\n </CanvasPresentationContext.Provider>\n ) : null}\n </div>\n );\n});\n\nfunction ItemContent({\n item,\n kind,\n paneId,\n windowId,\n focused,\n visible,\n presentation,\n canvas,\n hasNativePort,\n}: {\n item: CanvasItem;\n kind: AnyCanvasKind | undefined;\n paneId: CanvasPaneId;\n windowId: CanvasWindowId;\n focused: boolean;\n visible: boolean;\n presentation: CanvasPresentation;\n canvas: CanvasController;\n hasNativePort: boolean;\n}) {\n let unavailable: string | null = null;\n try {\n unavailable = kind?.unavailable?.(item.data, item) ?? null;\n } catch (error) {\n console.error(`[@ai-matrx/canvas] \"${item.kind}\" unavailable() threw`, error);\n }\n if (!kind) return <ItemProblem message=\"This item can no longer be shown.\" onClose={() => canvas.close(item.id)} />;\n if (unavailable) return <CanvasPanelEmpty>{unavailable}</CanvasPanelEmpty>;\n const rendered = kindComponent(kind) ? (\n <Rendered kind={kind} item={item} paneId={paneId} isFocused={focused} isVisible={visible} canvas={canvas} windowId={windowId} presentation={presentation} />\n ) : null;\n if (kind.body === \"native\") {\n return hasNativePort ? (\n <NativeBody itemId={item.id} windowId={windowId} visible={visible}>\n {rendered}\n </NativeBody>\n ) : (\n <CanvasPanelEmpty>Opens in the desktop app</CanvasPanelEmpty>\n );\n }\n return rendered;\n}\n\n/**\n * The kind's component. Memoized on what it is given: a body re-renders when\n * ITS item, pane, focus or presentation changes — never because another tab\n * opened or a split moved.\n */\nconst Rendered = memo(function Rendered({\n kind,\n item,\n paneId,\n isFocused,\n isVisible,\n canvas,\n windowId,\n presentation,\n}: {\n kind: AnyCanvasKind;\n item: CanvasItem;\n paneId: CanvasPaneId;\n isFocused: boolean;\n isVisible: boolean;\n canvas: CanvasController;\n windowId: CanvasWindowId;\n presentation: CanvasPresentation;\n}) {\n const props: CanvasKindProps = { item, data: item.data, paneId, isFocused, isVisible, canvas, windowId, presentation };\n return (\n <ItemBoundary item={item} onClose={() => canvas.close(item.id)} onRetry={() => resetKindComponent(kind)}>\n <Suspense fallback={<div className=\"mxc-loading\" aria-busy=\"true\" />}>\n <KindRender kind={kind} props={props} />\n </Suspense>\n </ItemBoundary>\n );\n});\n\nfunction KindRender({ kind, props }: { kind: AnyCanvasKind; props: CanvasKindProps }) {\n const Render = kindComponent(kind);\n if (!Render) throw new Error(`[@ai-matrx/canvas] kind \"${kind.id}\" has nothing to render.`);\n return <Render {...props} />;\n}\n\n/**\n * The placeholder a native view sits on. Its frame is reported on every\n * render, whenever the layer re-places bodies, on resize, and whenever the\n * host asks (`useCanvasNativeBodies().remeasure()`); null while hidden or gone.\n */\nfunction NativeBody({ itemId, windowId, visible, children }: { itemId: CanvasItemId; windowId: CanvasWindowId; visible: boolean; children: ReactNode }) {\n const { layer } = useCanvasInternals();\n const ref = useRef<HTMLDivElement>(null);\n const measure = useRef<() => void>(() => undefined);\n measure.current = () => {\n const el = ref.current;\n const box = visible && el?.isConnected ? el.getBoundingClientRect() : null;\n if (!box || box.width <= 0 || box.height <= 0) {\n layer.native.report(itemId, null, { visible: false, windowId });\n return;\n }\n const rect: CanvasNativeRect = { ...toCanvasRect(box), devicePixelRatio: window.devicePixelRatio || 1 };\n layer.native.report(itemId, rect, { visible: !layer.isBlocked(), windowId });\n };\n useIsoLayoutEffect(() => measure.current());\n useIsoLayoutEffect(() => {\n const el = ref.current;\n const run = () => measure.current();\n const observer = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(run);\n if (el) observer?.observe(el);\n const unregister = layer.native.register(run);\n window.addEventListener(\"resize\", run);\n return () => {\n observer?.disconnect();\n unregister();\n window.removeEventListener(\"resize\", run);\n layer.native.report(itemId, null, { visible: false, windowId });\n };\n }, [itemId, windowId, layer]);\n return (\n <div ref={ref} className=\"mxc-native-body\" data-native-body={itemId}>\n {children}\n </div>\n );\n}\n\nfunction ItemProblem({ message, onClose, onRetry }: { message: string; onClose: () => void; onRetry?: () => void }) {\n return (\n <div className=\"mxc-problem\" role=\"alert\">\n <AlertIcon />\n <p>{message}</p>\n <div className=\"mxc-problem-actions\">\n {onRetry ? (\n <button type=\"button\" className=\"mxc-text-button\" onClick={onRetry}>\n Try again\n </button>\n ) : null}\n <button type=\"button\" className=\"mxc-text-button\" onClick={onClose}>\n Close tab\n </button>\n </div>\n </div>\n );\n}\n\ninterface BoundaryProps {\n item: CanvasItem;\n onClose: () => void;\n onRetry: () => void;\n children: ReactNode;\n}\n\nclass ItemBoundary extends Component<BoundaryProps, { error: Error | null }> {\n override state: { error: Error | null } = { error: null };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n override componentDidCatch(error: Error, info: ErrorInfo) {\n console.error(`[@ai-matrx/canvas] \"${this.props.item.kind}\" failed to render`, error, info.componentStack);\n }\n\n override render() {\n if (this.state.error) {\n return (\n <ItemProblem\n message=\"This item failed to load.\"\n onClose={this.props.onClose}\n onRetry={() => {\n this.props.onRetry();\n this.setState({ error: null });\n }}\n />\n );\n }\n return this.props.children;\n }\n}\n","\"use client\";\n\n/**\n * THE canvas chrome — the one implementation of a panel frame, its header\n * buttons, a tab strip and a browser bar. Every canvas pane draws with these,\n * and a host that frames its own panels (a desktop canvas not yet on kinds)\n * uses the same components, so there is one look everywhere.\n *\n * Presentational and store-free: they render outside a CanvasProvider too\n * (tooltips then fall back to the native `title`). Structural CSS only —\n * colours come from --mxc-* tokens.\n */\n\nimport {\n forwardRef,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ButtonHTMLAttributes,\n type FocusEvent,\n type HTMLAttributes,\n type PointerEvent as ReactPointerEvent,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport { ArrowLeftIcon, ArrowRightIcon, CloseIcon, GlobeIcon, MaximizeIcon, MinimizeIcon, MoreIcon, PanelRightIcon, PlusIcon, RotateCwIcon } from \"./icons\";\nimport { toCanvasRect } from \"./layer\";\nimport { useOptionalCanvasInternals } from \"./provider\";\n\n// The browser runs layout effects; a server render has no layout to measure.\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\n/**\n * Marks a tab whose name is really cut (more than a pixel: system fonts\n * measure a fraction wider than their intrinsic size, which would put an\n * ellipsis on a name that fits). Only a cut name fades at its end.\n */\nexport function useTruncated(title: string) {\n const ref = useRef<HTMLSpanElement>(null);\n const [truncated, setTruncated] = useState(false);\n useIsoLayoutEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n const check = () => setTruncated(el.scrollWidth - el.clientWidth > 1);\n check();\n const observer = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(check);\n observer?.observe(el);\n return () => observer?.disconnect();\n }, [title]);\n return { ref, truncated };\n}\n\nconst cx = (...names: (string | false | null | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/** Tooltip handlers: through the canvas overlay (above native views) inside a provider, the native title outside. */\nfunction useTooltip(text: string | undefined) {\n const internals = useOptionalCanvasInternals();\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const hide = useRef<(() => void) | null>(null);\n const close = () => {\n if (timer.current) clearTimeout(timer.current);\n timer.current = null;\n hide.current?.();\n hide.current = null;\n };\n useEffect(() => close, []);\n if (!text) return { close, handlers: {} };\n if (!internals) return { close, handlers: { title: text } };\n const open = (element: HTMLElement, delay: number) => {\n close();\n timer.current = setTimeout(() => {\n timer.current = null;\n if (!element.isConnected) return;\n hide.current = internals.layer.show({ type: \"tooltip\", text, anchor: toCanvasRect(element.getBoundingClientRect()), side: \"bottom\" });\n }, delay);\n };\n return {\n close,\n handlers: {\n onPointerEnter: (event: ReactPointerEvent<HTMLElement>) => {\n if (event.pointerType === \"mouse\") open(event.currentTarget, 450);\n },\n onPointerLeave: close,\n onPointerDown: close,\n onFocus: (event: FocusEvent<HTMLElement>) => {\n if (event.currentTarget.matches(\":focus-visible\")) open(event.currentTarget, 0);\n },\n onBlur: close,\n },\n };\n}\n\nexport interface CanvasHeaderButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, \"children\" | \"title\"> {\n /** Accessible name and tooltip. */\n readonly label: string;\n /** Appended to the tooltip, e.g. \"⌘\\\\\". */\n readonly shortcut?: string | null | undefined;\n /** False draws the button dimmed and inert (a browser's Back with no history). Default true. */\n readonly available?: boolean;\n /** \"sm\" = a pane-header action (24px); \"md\" = a browser bar button (28px). */\n readonly size?: \"sm\" | \"md\";\n readonly pressed?: boolean;\n readonly children: ReactNode;\n}\n\n/** The one icon button of the canvas chrome. */\nexport const CanvasHeaderButton = forwardRef<HTMLButtonElement, CanvasHeaderButtonProps>(function CanvasHeaderButton(\n { label, shortcut, available = true, size = \"sm\", pressed, className, children, onClick, onPointerEnter, onPointerLeave, onPointerDown, onFocus, onBlur, ...rest },\n ref,\n) {\n const tooltip = useTooltip(shortcut ? `${label} (${shortcut})` : label);\n const own = tooltip.handlers as {\n title?: string;\n onPointerEnter?: (event: ReactPointerEvent<HTMLElement>) => void;\n onPointerLeave?: () => void;\n onPointerDown?: () => void;\n onFocus?: (event: FocusEvent<HTMLElement>) => void;\n onBlur?: () => void;\n };\n return (\n <button\n ref={ref}\n type=\"button\"\n aria-label={label}\n aria-pressed={pressed}\n data-slot=\"canvas-panel-action\"\n data-size={size}\n data-available={available ? undefined : \"false\"}\n className={cx(\"mxc-icon-button\", className)}\n {...rest}\n {...(own.title ? { title: own.title } : {})}\n aria-disabled={available ? rest[\"aria-disabled\"] : true}\n onClick={(event) => {\n tooltip.close();\n if (available) onClick?.(event);\n }}\n onPointerEnter={(event) => {\n onPointerEnter?.(event);\n own.onPointerEnter?.(event);\n }}\n onPointerLeave={(event) => {\n onPointerLeave?.(event);\n own.onPointerLeave?.();\n }}\n onPointerDown={(event) => {\n onPointerDown?.(event);\n own.onPointerDown?.();\n }}\n onFocus={(event) => {\n onFocus?.(event);\n own.onFocus?.(event);\n }}\n onBlur={(event) => {\n onBlur?.(event);\n own.onBlur?.();\n }}\n >\n {children}\n </button>\n );\n});\n\nexport interface CanvasPanelProps extends Omit<HTMLAttributes<HTMLElement>, \"title\"> {\n readonly panelId: string;\n /** The header title (a single-tab pane, a panel with no tabs). */\n readonly title: ReactNode;\n /** Controls after the title or tabs: \"+ new terminal\", a browser's bar. Grows to fill the header. */\n readonly leading?: ReactNode;\n /** A custom start of the header instead of the title (a tab strip). `leading` still follows it. */\n readonly header?: ReactNode;\n /** Controls just before the \"…\" menu (a kind's own button). */\n readonly actions?: ReactNode;\n /** The \"…\" menu: the host renders its own menu around the trigger it receives. */\n readonly renderMenu?: ((trigger: ReactElement) => ReactNode) | undefined;\n readonly expanded?: boolean | undefined;\n readonly onToggleExpand?: (() => void) | undefined;\n readonly expandShortcut?: string | null | undefined;\n /** Phones only: put the canvas away without closing anything. */\n readonly onHide?: (() => void) | undefined;\n readonly onClose?: (() => void) | undefined;\n readonly closeLabel?: string | undefined;\n readonly focused?: boolean | undefined;\n /** Where the header's own body element goes (the pane body). */\n readonly bodyProps?: HTMLAttributes<HTMLDivElement> | undefined;\n}\n\n/** The menu trigger every panel shares. */\nexport const CanvasMenuTrigger = forwardRef<HTMLButtonElement, Omit<CanvasHeaderButtonProps, \"label\" | \"children\"> & { label?: string }>(\n function CanvasMenuTrigger({ label = \"More\", ...props }, ref) {\n return (\n <CanvasHeaderButton ref={ref} label={label} {...props}>\n <MoreIcon />\n </CanvasHeaderButton>\n );\n },\n);\n\n/** The frame every canvas panel shares: header (title or tabs · leading · actions · … · expand · close) over a body. */\nexport const CanvasPanel = forwardRef<HTMLElement, CanvasPanelProps>(function CanvasPanel({\n panelId,\n title,\n leading,\n header,\n actions,\n renderMenu,\n expanded = false,\n onToggleExpand,\n expandShortcut,\n onHide,\n onClose,\n closeLabel = \"Close\",\n focused,\n bodyProps,\n className,\n children,\n ...props\n}, ref) {\n return (\n <section\n ref={ref}\n data-slot=\"canvas-panel\"\n data-panel={panelId}\n data-expanded={expanded ? \"\" : undefined}\n data-focused={focused ? \"\" : undefined}\n aria-label={typeof title === \"string\" ? title : undefined}\n className={cx(\"mxc-panel\", className)}\n {...props}\n >\n <header data-slot=\"canvas-panel-header\" className=\"mxc-pane-header\">\n {header ?? <span className=\"mxc-panel-title\">{title}</span>}\n <div className=\"mxc-pane-leading\">{leading}</div>\n <div className=\"mxc-pane-actions\">\n {actions}\n {renderMenu ? renderMenu(<CanvasMenuTrigger />) : null}\n {onToggleExpand ? (\n <CanvasHeaderButton className=\"mxc-desktop-only\" label={expanded ? \"Restore\" : \"Expand\"} shortcut={expandShortcut} onClick={onToggleExpand}>\n {expanded ? <MinimizeIcon /> : <MaximizeIcon />}\n </CanvasHeaderButton>\n ) : null}\n {onHide ? (\n <CanvasHeaderButton className=\"mxc-phone-only\" label=\"Hide canvas\" onClick={onHide}>\n <PanelRightIcon />\n </CanvasHeaderButton>\n ) : null}\n {onClose ? (\n <CanvasHeaderButton label={closeLabel} onClick={onClose}>\n <CloseIcon />\n </CanvasHeaderButton>\n ) : null}\n </div>\n </header>\n <div data-slot=\"canvas-panel-body\" {...bodyProps} className={cx(\"mxc-pane-body\", bodyProps?.className)}>\n {children}\n </div>\n </section>\n );\n});\n\n/** The one-line honest state of a panel with nothing to show, or whose backend has not shipped. */\nexport function CanvasPanelEmpty({ children, className }: { children: ReactNode; className?: string }) {\n return (\n <div data-slot=\"canvas-panel-empty\" className={cx(\"mxc-empty-line\", className)}>\n {children}\n </div>\n );\n}\n\nexport interface CanvasTabProps extends Omit<HTMLAttributes<HTMLDivElement>, \"title\" | \"onSelect\"> {\n readonly title: string;\n readonly icon: ReactNode;\n /** Small trailing state after the title, e.g. \"exited\". */\n readonly note?: string | undefined;\n readonly active: boolean;\n readonly onSelect: () => void;\n /** Absent ⇒ no close button. */\n readonly onClose?: (() => void) | undefined;\n}\n\n/** One tab of a strip. */\nexport const CanvasTab = forwardRef<HTMLDivElement, CanvasTabProps>(function CanvasTab(\n { title, icon, note, active, onSelect, onClose, className, onKeyDown, onClick, ...rest },\n ref,\n) {\n const shown = title || \"New tab\";\n const name = useTruncated(shown);\n return (\n <div\n ref={ref}\n role=\"tab\"\n aria-selected={active}\n tabIndex={active ? 0 : -1}\n data-slot=\"browser-tab\"\n data-active={active ? \"\" : undefined}\n data-truncated={name.truncated ? \"\" : undefined}\n title={shown}\n className={cx(\"mxc-tab\", className)}\n {...rest}\n onClick={(event) => {\n onClick?.(event);\n onSelect();\n }}\n onKeyDown={(event) => {\n onKeyDown?.(event);\n if (event.defaultPrevented) return;\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n onSelect();\n }\n }}\n >\n <span className=\"mxc-tab-icon\">{icon}</span>\n <span ref={name.ref} className=\"mxc-tab-title\">\n {shown}\n </span>\n {note ? <span className=\"mxc-tab-note\" data-slot=\"browser-tab-note\">{note}</span> : null}\n {onClose ? (\n <button\n type=\"button\"\n className=\"mxc-tab-close\"\n data-slot=\"browser-tab-close\"\n aria-label={`Close ${shown}`}\n onClick={(event) => {\n event.stopPropagation();\n onClose();\n }}\n >\n <CloseIcon />\n </button>\n ) : null}\n </div>\n );\n});\n\nexport interface BrowserTab {\n readonly id: string;\n readonly title: string;\n /** A favicon URL; a globe is drawn without one. */\n readonly icon?: string | null | undefined;\n /** A glyph instead of a favicon (a terminal tab draws its prompt icon). */\n readonly glyph?: ReactNode;\n /** Small trailing state after the title, e.g. \"exited\". */\n readonly note?: string | undefined;\n}\n\nexport interface BrowserTabsProps {\n readonly tabs: readonly BrowserTab[];\n readonly activeId: string | null;\n readonly onSelect: (id: string) => void;\n readonly onClose: (id: string) => void;\n /** Absent ⇒ no \"+\" button. */\n readonly onNew?: (() => void) | undefined;\n /** The \"+\" button's name (default \"New tab\"). */\n readonly newLabel?: string;\n /** The tab list's name (default \"Tabs\"). */\n readonly label?: string;\n readonly className?: string;\n}\n\n/** A tab strip for any panel with its own tabs: a browser's pages, a terminal's shells. */\nexport function BrowserTabs({ tabs, activeId, onSelect, onClose, onNew, newLabel = \"New tab\", label = \"Tabs\", className }: BrowserTabsProps) {\n return (\n <div data-slot=\"browser-tabs\" role=\"tablist\" aria-label={label} className={cx(\"mxc-tabs\", className)}>\n {tabs.map((tab) => (\n <CanvasTab\n key={tab.id}\n data-tab={tab.id}\n title={tab.title}\n note={tab.note}\n active={tab.id === activeId}\n icon={tab.glyph ?? (tab.icon ? <img src={tab.icon} alt=\"\" className=\"mxc-favicon\" /> : <GlobeIcon />)}\n onSelect={() => onSelect(tab.id)}\n onClose={() => onClose(tab.id)}\n />\n ))}\n {onNew ? (\n <CanvasHeaderButton label={newLabel} data-slot=\"browser-tab-new\" onClick={onNew}>\n <PlusIcon />\n </CanvasHeaderButton>\n ) : null}\n </div>\n );\n}\n\nexport interface BrowserBarProps {\n readonly url: string;\n readonly canGoBack: boolean;\n readonly canGoForward: boolean;\n readonly onBack: () => void;\n readonly onForward: () => void;\n readonly onReload: () => void;\n /** Called with the typed address when the person presses Enter. */\n readonly onNavigate: (address: string) => void;\n /** Controls after the address (screenshot, open in your browser, more). */\n readonly trailing?: ReactNode;\n readonly className?: string;\n}\n\n/** A browser's back · forward · reload · address bar, for a kind's leading slot or its body. */\nexport function BrowserBar({ url, canGoBack, canGoForward, onBack, onForward, onReload, onNavigate, trailing, className }: BrowserBarProps) {\n const [draft, setDraft] = useState(url);\n const [editing, setEditing] = useState(false);\n useEffect(() => {\n if (!editing) setDraft(url);\n }, [url, editing]);\n\n return (\n <div data-slot=\"browser-bar\" className={cx(\"mxc-browser-bar\", className)}>\n <CanvasHeaderButton size=\"md\" label=\"Back\" available={canGoBack} onClick={onBack}>\n <ArrowLeftIcon />\n </CanvasHeaderButton>\n <CanvasHeaderButton size=\"md\" label=\"Forward\" available={canGoForward} onClick={onForward}>\n <ArrowRightIcon />\n </CanvasHeaderButton>\n <CanvasHeaderButton size=\"md\" label=\"Reload\" onClick={onReload}>\n <RotateCwIcon />\n </CanvasHeaderButton>\n <form\n className=\"mxc-address-form\"\n onSubmit={(event) => {\n event.preventDefault();\n setEditing(false);\n onNavigate(draft.trim());\n (event.currentTarget.elements.namedItem(\"address\") as HTMLInputElement | null)?.blur();\n }}\n >\n <input\n name=\"address\"\n aria-label=\"Address\"\n data-slot=\"browser-address\"\n className=\"mxc-address\"\n value={draft}\n placeholder=\"Search or enter an address\"\n spellCheck={false}\n onFocus={(event) => {\n setEditing(true);\n event.currentTarget.select();\n }}\n onBlur={() => setEditing(false)}\n onChange={(event) => setDraft(event.target.value)}\n />\n </form>\n {trailing ? <div data-slot=\"browser-bar-trailing\" className=\"mxc-browser-bar-trailing\">{trailing}</div> : null}\n </div>\n );\n}\n","/**\n * Inlined glyphs (C19): the package carries its own icons and depends on no\n * icon library. Paths follow the Lucide 24×24 grid so they sit beside Lucide\n * icons in a host without looking foreign.\n */\n\nimport type { SVGProps } from \"react\";\n\ntype IconProps = SVGProps<SVGSVGElement> & { className?: string };\n\nfunction Glyph({ children, ...props }: IconProps) {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n {...props}\n >\n {children}\n </svg>\n );\n}\n\nexport const CloseIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M18 6 6 18\" />\n <path d=\"m6 6 12 12\" />\n </Glyph>\n);\n\nexport const MaximizeIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M15 3h6v6\" />\n <path d=\"m21 3-7 7\" />\n <path d=\"m3 21 7-7\" />\n <path d=\"M9 21H3v-6\" />\n </Glyph>\n);\n\nexport const MinimizeIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m14 10 7-7\" />\n <path d=\"M20 10h-6V4\" />\n <path d=\"m3 21 7-7\" />\n <path d=\"M4 14h6v6\" />\n </Glyph>\n);\n\nexport const MoreIcon = (p: IconProps) => (\n <Glyph {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"1\" />\n <circle cx=\"12\" cy=\"5\" r=\"1\" />\n <circle cx=\"12\" cy=\"19\" r=\"1\" />\n </Glyph>\n);\n\nexport const SplitRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M12 3v18\" />\n </Glyph>\n);\n\nexport const SplitDownIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M3 12h18\" />\n </Glyph>\n);\n\nexport const PanelRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M15 3v18\" />\n </Glyph>\n);\n\nexport const PopOutIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M15 3h6v6\" />\n <path d=\"M10 14 21 3\" />\n <path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\" />\n </Glyph>\n);\n\nexport const AlertIcon = (p: IconProps) => (\n <Glyph {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 8v4\" />\n <path d=\"M12 16h.01\" />\n </Glyph>\n);\n\nexport const ArrowLeftIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m12 19-7-7 7-7\" />\n <path d=\"M19 12H5\" />\n </Glyph>\n);\n\nexport const ArrowRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M5 12h14\" />\n <path d=\"m12 5 7 7-7 7\" />\n </Glyph>\n);\n\nexport const RotateCwIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8\" />\n <path d=\"M21 3v5h-5\" />\n </Glyph>\n);\n\nexport const GlobeIcon = (p: IconProps) => (\n <Glyph {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\" />\n <path d=\"M2 12h20\" />\n </Glyph>\n);\n\nexport const PlusIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M5 12h14\" />\n <path d=\"M12 5v14\" />\n </Glyph>\n);\n\n/** Dock back: a tab returns from its own window into the canvas. */\nexport const DockIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6\" />\n <path d=\"M21 3 12 12\" />\n <path d=\"M12 6v6h6\" />\n </Glyph>\n);\n\n/** The \"New tab\" launcher (Lucide layout-grid). */\nexport const LayoutGridIcon = (p: IconProps) => (\n <Glyph {...p}>\n <rect width=\"7\" height=\"7\" x=\"3\" y=\"3\" rx=\"1\" />\n <rect width=\"7\" height=\"7\" x=\"14\" y=\"3\" rx=\"1\" />\n <rect width=\"7\" height=\"7\" x=\"14\" y=\"14\" rx=\"1\" />\n <rect width=\"7\" height=\"7\" x=\"3\" y=\"14\" rx=\"1\" />\n </Glyph>\n);\n\nexport const ChevronLeftIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m15 18-6-6 6-6\" />\n </Glyph>\n);\n\nexport const ChevronRightIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m9 18 6-6-6-6\" />\n </Glyph>\n);\n\nexport const ChevronDownIcon = (p: IconProps) => (\n <Glyph {...p}>\n <path d=\"m6 9 6 6 6-6\" />\n </Glyph>\n);\n","\"use client\";\n\n/**\n * Tab drag and drop. A tab (or a single tab's title) drags; a pane — its\n * chrome AND the body placed over its slot — takes the drop.\n */\n\nimport { useEffect, useRef, type DragEvent } from \"react\";\nimport type { CanvasItemId, CanvasPaneId } from \"../index\";\nimport { toCanvasRect } from \"./layer\";\nimport { useCanvas, useCanvasInternals } from \"./provider\";\n\nexport const CANVAS_DRAG_MIME = \"application/x-matrx-canvas-item\";\n\n/** Drag handlers shared by a tab and a single tab's title: the dragged tab is announced so native views can step aside. */\nexport function useTabDrag(itemId: CanvasItemId, title: string) {\n const { layer } = useCanvasInternals();\n const active = useRef<(() => void)[]>([]);\n const end = () => {\n for (const dispose of active.current.splice(0)) dispose();\n };\n useEffect(() => end, []);\n return {\n draggable: true,\n onDragStart: (event: DragEvent) => {\n event.dataTransfer.setData(CANVAS_DRAG_MIME, itemId);\n event.dataTransfer.effectAllowed = \"move\";\n end();\n active.current.push(layer.beginBlocking(), layer.show({ type: \"tab-drag\", itemId, title }));\n },\n onDragEnd: end,\n };\n}\n\n/**\n * Drop handlers for one pane. `getOutline` is the element whose rect the drop\n * indicator draws (the pane's panel). Used by the pane's chrome and by every\n * body placed over the pane, so a tab dropped anywhere on the pane lands there.\n */\nexport function usePaneDrop(paneId: CanvasPaneId, getOutline: () => HTMLElement | null) {\n const canvas = useCanvas();\n const { layer } = useCanvasInternals();\n const drop = useRef<(() => void) | null>(null);\n useEffect(() => () => drop.current?.(), []);\n const hide = () => {\n drop.current?.();\n drop.current = null;\n };\n return {\n onDragOver: (event: DragEvent<HTMLElement>) => {\n if (!event.dataTransfer.types.includes(CANVAS_DRAG_MIME)) return;\n event.preventDefault();\n event.dataTransfer.dropEffect = \"move\";\n const outline = getOutline();\n if (!drop.current && outline) {\n drop.current = layer.show({ type: \"drop-indicator\", rect: toCanvasRect(outline.getBoundingClientRect()), paneId });\n }\n },\n onDragLeave: (event: DragEvent<HTMLElement>) => {\n const next = event.relatedTarget as Node | null;\n if (next && event.currentTarget.contains(next)) return;\n hide();\n },\n onDrop: (event: DragEvent<HTMLElement>) => {\n hide();\n const itemId = event.dataTransfer.getData(CANVAS_DRAG_MIME) as CanvasItemId;\n if (!itemId) return;\n event.preventDefault();\n canvas.moveItem(itemId, paneId);\n },\n };\n}\n","\"use client\";\n\n/**\n * The launcher — what a \"New tab\" shows: what this page offers (contextual\n * entries, `useCanvasLauncherEntry`) first, then every kind that offers a\n * launcher. Choosing NAVIGATES the tab in place, so its header offers Back to\n * the launcher: nothing reached from inside the canvas is ever a dead end.\n *\n * The launcher tab is a built-in item (`CANVAS_LAUNCHER_KIND`) that is never\n * registered — `useItemKind` resolves it here.\n */\n\nimport type { ComponentType } from \"react\";\nimport { CANVAS_LAUNCHER_KIND, canvasItemId, type CanvasJson, type CanvasNavigateInput, type CanvasPaneId } from \"../index\";\nimport { CanvasPanelEmpty } from \"./chrome\";\nimport { LayoutGridIcon } from \"./icons\";\nimport { useCanvas, useCanvasKind, useCanvasKinds, useCanvasLauncherEntries } from \"./provider\";\nimport type { AnyCanvasKind, CanvasKindProps } from \"./registry\";\n\ninterface Choice {\n readonly id: string;\n readonly label: string;\n readonly icon: ComponentType<{ className?: string }>;\n readonly input: CanvasNavigateInput;\n}\n\nfunction useChoices(): { readonly contextual: readonly Choice[]; readonly global: readonly Choice[] } {\n const entries = useCanvasLauncherEntries();\n const kinds = useCanvasKinds();\n const byId = new Map(kinds.map((kind) => [kind.id, kind] as const));\n const contextual: Choice[] = [];\n for (const entry of entries) {\n const kind = byId.get(entry.kind);\n // An entry for a kind this app does not have would open a broken tab: it is not offered.\n if (!kind) continue;\n contextual.push({\n id: `ctx:${canvasItemId(entry.kind, entry.key)}`,\n label: entry.title ?? kind.label,\n icon: entry.icon ?? kind.icon,\n input: { kind: entry.kind, key: entry.key, title: entry.title ?? null, ...(entry.data !== undefined ? { data: entry.data } : {}) },\n });\n }\n const global: Choice[] = [];\n for (const kind of kinds) {\n const launcher = kind.launcher;\n if (!launcher) continue;\n global.push({\n id: `kind:${kind.id}`,\n label: launcher.title ?? kind.label,\n icon: kind.icon,\n input: { kind: kind.id, key: launcher.key, data: launcher.data as CanvasJson, title: launcher.title ?? null },\n });\n }\n return { contextual, global };\n}\n\n/**\n * A double-click on a launcher item: the first click opens the item, and the\n * new body appears right under the pointer. The rest of that SAME multi-click\n * (detail ≥ 2: the second press, its click, the dblclick) must not land in the\n * new body — it would select a word or press a button there. Swallowed in the\n * capture phase for a short window; a fresh click (detail 1) passes.\n */\nconst FOLLOW_UP_MS = 600;\nfunction swallowFollowUpClicks() {\n if (typeof window === \"undefined\") return;\n const types = [\"pointerdown\", \"mousedown\", \"pointerup\", \"mouseup\", \"click\", \"dblclick\"] as const;\n const swallow = (event: Event) => {\n if ((event as MouseEvent).detail >= 2 || event.type === \"dblclick\") {\n event.preventDefault();\n event.stopPropagation();\n }\n };\n for (const type of types) window.addEventListener(type, swallow, true);\n setTimeout(() => {\n for (const type of types) window.removeEventListener(type, swallow, true);\n }, FOLLOW_UP_MS);\n}\n\nfunction LauncherGrid({ onChoose }: { onChoose: (input: CanvasNavigateInput) => void }) {\n const { contextual, global } = useChoices();\n if (contextual.length === 0 && global.length === 0) return <CanvasPanelEmpty>Nothing to open</CanvasPanelEmpty>;\n const section = (label: string | null, choices: readonly Choice[]) =>\n choices.length === 0 ? null : (\n <section className=\"mxc-launcher-section\" aria-label={label ?? \"Open\"}>\n {label ? <h3 className=\"mxc-launcher-heading\">{label}</h3> : null}\n <div className=\"mxc-launcher-grid\">\n {choices.map((choice) => {\n const Icon = choice.icon;\n return (\n <button\n key={choice.id}\n type=\"button\"\n className=\"mxc-launcher-item\"\n onClick={(event) => {\n // The second click of a double-click: the item is already chosen.\n if (event.detail >= 2) return;\n swallowFollowUpClicks();\n onChoose(choice.input);\n }}\n >\n <Icon className=\"mxc-launcher-icon\" />\n <span>{choice.label}</span>\n </button>\n );\n })}\n </div>\n </section>\n );\n return (\n <div className=\"mxc-launcher\">\n {section(contextual.length > 0 ? \"On this page\" : null, contextual)}\n {section(contextual.length > 0 ? \"Open\" : null, global)}\n </div>\n );\n}\n\n/** The body of a \"New tab\": choosing navigates THIS tab, so Back returns here. */\nfunction LauncherBody({ item, canvas }: CanvasKindProps) {\n return <LauncherGrid onChoose={(input) => void canvas.navigate(item.id, input)} />;\n}\n\n/** A pane with no tabs: choosing opens a \"New tab\" there and navigates it, so Back returns to the launcher. */\nexport function EmptyPaneLauncher({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n return (\n <LauncherGrid\n onChoose={(input) => {\n const tab = canvas.newTab(paneId);\n canvas.navigate(tab, input);\n }}\n />\n );\n}\n\nexport const CANVAS_LAUNCHER_KIND_DEFINITION: AnyCanvasKind = {\n id: CANVAS_LAUNCHER_KIND,\n label: \"New tab\",\n icon: LayoutGridIcon,\n component: LauncherBody,\n};\n\n/** A kind by id, the built-in launcher included. */\nexport function useItemKind(kindId: string): AnyCanvasKind | undefined {\n const registered = useCanvasKind(kindId);\n return kindId === CANVAS_LAUNCHER_KIND ? CANVAS_LAUNCHER_KIND_DEFINITION : registered;\n}\n\n/** Non-hook form of useItemKind. */\nexport function resolveItemKind(kindId: string, lookup: (id: string) => AnyCanvasKind | undefined): AnyCanvasKind | undefined {\n return kindId === CANVAS_LAUNCHER_KIND ? CANVAS_LAUNCHER_KIND_DEFINITION : lookup(kindId);\n}\n","\"use client\";\n\n/**\n * The presentation context: every canvas body is rendered inside it, so any\n * component nested in a body — a renderer three levels down, a chart inside a\n * document — can ask where it is and what shape it has.\n */\n\nimport { createContext, useContext } from \"react\";\nimport type { CanvasPresentation } from \"../index\";\n\nexport const CanvasPresentationContext = createContext<CanvasPresentation | null>(null);\n\n/**\n * The live presentation of the canvas body this component renders in: size,\n * orientation, narrow, expanded, pane count. `null` outside the canvas — so a\n * component used both on a page and in a canvas adapts only in the canvas.\n *\n * const p = useCanvasPresentation();\n * const direction = preferredFlowDirection(p); // \"vertical\" in a tall narrow pane\n */\nexport function useCanvasPresentation(): CanvasPresentation | null {\n return useContext(CanvasPresentationContext);\n}\n","\"use client\";\n\n/**\n * Body slots — where each pane's body area IS on screen.\n *\n * A pane draws its chrome (header, tabs, toolbar row) and an empty body SLOT.\n * Item bodies are not rendered inside the pane: they live once, in the\n * column's stable body layer, and are placed over their pane's slot. A tab\n * switch, a split, a move between panes, a resize or expand only re-places a\n * body — it never unmounts or re-parents it, so its state, focus and scroll\n * survive. A DOM body and a native body are the same thing: a body on a slot.\n *\n * The registry measures every slot (ResizeObserver where there is one) and\n * tells subscribers when anything moved, so the layer re-places in the frame\n * the layout changed.\n */\n\nimport { createContext, useContext, useSyncExternalStore } from \"react\";\nimport type { CanvasPaneId } from \"../index\";\n\nexport interface CanvasSlotSize {\n readonly width: number;\n readonly height: number;\n}\n\nconst ZERO: CanvasSlotSize = Object.freeze({ width: 0, height: 0 });\n\nexport interface CanvasSlots {\n /** A pane's body slot mounted. */\n set(paneId: CanvasPaneId, element: HTMLElement): void;\n /** A pane's body slot went away (only when `element` is still the registered one). */\n unset(paneId: CanvasPaneId, element: HTMLElement | null): void;\n /** A pane's whole panel (the drop target's outline). */\n setSection(paneId: CanvasPaneId, element: HTMLElement | null): void;\n slot(paneId: CanvasPaneId): HTMLElement | null;\n section(paneId: CanvasPaneId): HTMLElement | null;\n /** The slot's measured size; the same object until it changes. */\n size(paneId: CanvasPaneId): CanvasSlotSize;\n /** Re-reads every slot's size now (no ResizeObserver, or a host-driven change). */\n measure(): void;\n /** Called after any slot mounts, unmounts or resizes. */\n subscribe(listener: () => void): () => void;\n}\n\nexport function createCanvasSlots(): CanvasSlots {\n const slots = new Map<CanvasPaneId, HTMLElement>();\n const sections = new Map<CanvasPaneId, HTMLElement>();\n const sizes = new Map<CanvasPaneId, CanvasSlotSize>();\n const listeners = new Set<() => void>();\n let observer: ResizeObserver | null = null;\n\n const emit = () => {\n for (const listener of [...listeners]) listener();\n };\n const read = (paneId: CanvasPaneId, element: HTMLElement): boolean => {\n const box = element.getBoundingClientRect();\n const width = Math.round(box.width);\n const height = Math.round(box.height);\n const previous = sizes.get(paneId);\n if (previous && previous.width === width && previous.height === height) return false;\n sizes.set(paneId, { width, height });\n return true;\n };\n const measureAll = (): boolean => {\n let changed = false;\n for (const [paneId, element] of slots) changed = read(paneId, element) || changed;\n return changed;\n };\n const watch = (): ResizeObserver | null => {\n if (observer || typeof ResizeObserver === \"undefined\") return observer;\n observer = new ResizeObserver(() => {\n measureAll();\n // Always: a slot can move without resizing when a sibling resizes.\n emit();\n });\n return observer;\n };\n\n return {\n set(paneId, element) {\n if (slots.get(paneId) === element) return;\n const previous = slots.get(paneId);\n if (previous) observer?.unobserve(previous);\n slots.set(paneId, element);\n watch()?.observe(element);\n read(paneId, element);\n emit();\n },\n unset(paneId, element) {\n const current = slots.get(paneId);\n if (!current || (element && current !== element)) return;\n observer?.unobserve(current);\n slots.delete(paneId);\n sizes.delete(paneId);\n emit();\n },\n setSection(paneId, element) {\n if (element) sections.set(paneId, element);\n else sections.delete(paneId);\n },\n slot: (paneId) => slots.get(paneId) ?? null,\n section: (paneId) => sections.get(paneId) ?? null,\n size: (paneId) => sizes.get(paneId) ?? ZERO,\n measure() {\n if (measureAll()) emit();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\nexport const CanvasSlotsContext = createContext<CanvasSlots | null>(null);\n\n/** The column's slot registry, or null for a pane rendered on its own. */\nexport function useCanvasSlots(): CanvasSlots | null {\n return useContext(CanvasSlotsContext);\n}\n\n/**\n * True while the column presents ONE pane at a time (a phone): the focused\n * pane shows every pane's tabs in its strip, and only its body is on screen.\n * The layout tree is untouched, so a wider screen gets its split back.\n */\nexport const CanvasSinglePaneContext = createContext(false);\n\nexport function useCanvasSinglePane(): boolean {\n return useContext(CanvasSinglePaneContext);\n}\n\n/** A pane slot's live size. */\nexport function useSlotSize(slots: CanvasSlots, paneId: CanvasPaneId): CanvasSlotSize {\n return useSyncExternalStore(\n slots.subscribe,\n () => slots.size(paneId),\n () => ZERO,\n );\n}\n","/**\n * One resize gesture (the canvas edge, a split handle). While it runs:\n * `:root[data-mxc-resizing]` (cursor, no motion, `user-select: none` in\n * styles.css), any selection already on the page is cleared, and the\n * document refuses to START a selection — so dragging an edge across the\n * page never selects its text, whatever CSS the host loaded.\n */\nexport function beginCanvasResize(mode: \"\" | \"col\" | \"row\"): () => void {\n if (typeof document === \"undefined\") return () => undefined;\n const root = document.documentElement;\n root.dataset.mxcResizing = mode;\n document.getSelection?.()?.removeAllRanges();\n const refuse = (event: Event) => event.preventDefault();\n document.addEventListener(\"selectstart\", refuse, true);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n delete root.dataset.mxcResizing;\n document.removeEventListener(\"selectstart\", refuse, true);\n };\n}\n","\"use client\";\n\n/**\n * One pane, drawn with THE canvas chrome (CanvasPanel): a header — Back (when\n * the tab navigated in place), the title (one tab) or the tab strip, \"+\" New\n * tab, the kind's leading controls, the kind's own button, \"…\", expand, close\n * — over an empty body SLOT. The bodies themselves live in the column's stable\n * body layer and are placed over this slot (see bodies.tsx), so nothing in a\n * body remounts when this pane re-renders, splits or receives a tab. An empty\n * pane shows the launcher. Tabs drag between panes (and windows).\n */\n\nimport { Component, useEffect, useLayoutEffect, useRef, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from \"react\";\nimport * as Menu from \"@radix-ui/react-dropdown-menu\";\nimport type { CanvasItem, CanvasItemId, CanvasPaneId, CanvasState, CanvasWindowId } from \"../index\";\nimport {\n CANVAS_LAUNCHER_KIND,\n CANVAS_MAIN_WINDOW,\n canvasShortcutHint,\n canvasWindowFrame,\n listPaneIds,\n selectCanvasCanGoBack,\n selectCanvasCanGoForward,\n selectCanvasFocusedPaneId,\n selectCanvasIsFullscreen,\n selectCanvasIsOpen,\n selectCanvasPaneCount,\n} from \"../index\";\nimport { CanvasPaneInlineBodies, usePanePresentation } from \"./bodies\";\nimport { CanvasHeaderButton, CanvasMenuTrigger, CanvasPanel, CanvasTab, useTruncated } from \"./chrome\";\nimport { CANVAS_DRAG_MIME, usePaneDrop, useTabDrag } from \"./dnd\";\nimport {\n AlertIcon,\n ArrowLeftIcon,\n ArrowRightIcon,\n ChevronDownIcon,\n CloseIcon,\n DockIcon,\n PlusIcon,\n PopOutIcon,\n SplitDownIcon,\n SplitRightIcon,\n} from \"./icons\";\nimport { toCanvasRect, type CanvasMenuEntry } from \"./layer\";\nimport { EmptyPaneLauncher, resolveItemKind, useItemKind } from \"./launcher\";\nimport { useCanvas, useCanvasInternals, useCanvasState } from \"./provider\";\nimport { getCanvasKind, type AnyCanvasKind, type CanvasKindProps, type CanvasMenuItem } from \"./registry\";\nimport { createCanvasSlots, useCanvasSinglePane, useCanvasSlots } from \"./slots\";\n\n// The browser runs layout effects; a server render has no layout to report.\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nexport function itemTitle(item: CanvasItem, kind: AnyCanvasKind | undefined): string {\n if (item.title) return item.title;\n if (item.kind === CANVAS_LAUNCHER_KIND) return \"New tab\";\n if (kind?.title) {\n try {\n const title = kind.title(item.data, item);\n if (title) return title;\n } catch {\n // fall through to the label — a title function must never break the tab strip\n }\n }\n return kind?.label ?? item.kind;\n}\n\nconst isMac = () => typeof navigator !== \"undefined\" && /mac|iphone|ipad/i.test(navigator.platform ?? \"\");\n\n/** One tab of a strip and the pane it lives in (a phone's strip shows every pane's tabs). */\ninterface StripTab {\n readonly itemId: CanvasItemId;\n readonly paneId: CanvasPaneId;\n /** Its index inside its own pane (where a tab dropped on it lands). */\n readonly index: number;\n}\n\n/** Every tab of this window in layout order, as one string (stable while nothing structural changes). */\nfunction windowTabsSignature(state: CanvasState, windowId: CanvasWindowId): string {\n const frame = canvasWindowFrame(state, windowId);\n if (!frame) return \"\";\n const rows: string[] = [];\n for (const paneId of listPaneIds(frame.layout)) {\n for (const itemId of state.panes[paneId]?.itemIds ?? []) rows.push(`${itemId}\\u0001${paneId}`);\n }\n return rows.join(\"\\u0002\");\n}\n\nfunction parseWindowTabs(signature: string): StripTab[] {\n if (!signature) return [];\n const perPane = new Map<string, number>();\n return signature.split(\"\\u0002\").map((row) => {\n const [itemId = \"\", paneId = \"\"] = row.split(\"\\u0001\");\n const index = perPane.get(paneId) ?? 0;\n perPane.set(paneId, index + 1);\n return { itemId: itemId as CanvasItemId, paneId: paneId as CanvasPaneId, index };\n });\n}\n\nexport function CanvasPaneView({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n const { windowId, tabStrip } = useCanvasInternals();\n // A pane outside a CanvasColumn renders its own bodies in flow.\n const columnSlots = useCanvasSlots();\n const [ownSlots] = useState(createCanvasSlots);\n const slots = columnSlots ?? ownSlots;\n const pane = useCanvasState((s) => s.panes[paneId]);\n // Only this pane's active item: another tab's data never re-renders this pane.\n const active = useCanvasState((s) => {\n const activeId = s.panes[paneId]?.activeItemId;\n return activeId ? s.items[activeId] : undefined;\n });\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(s, windowId));\n const isOpen = useCanvasState((s) => selectCanvasIsOpen(s, windowId));\n const focused = useCanvasState((s) => selectCanvasFocusedPaneId(s, windowId) === paneId);\n const paneCount = useCanvasState((s) => selectCanvasPaneCount(s, windowId));\n const role = useCanvasState((s) => (windowId === CANVAS_MAIN_WINDOW ? \"main\" : (s.windows[windowId]?.role ?? \"window\")));\n const canGoBack = useCanvasState((s) => (active ? selectCanvasCanGoBack(s, active.id) : false));\n const canGoForward = useCanvasState((s) => (active ? selectCanvasCanGoForward(s, active.id) : false));\n const kind = useItemKind(active?.kind ?? \"\");\n // A phone presents one pane: its strip carries every pane's tabs, so nothing is out of reach.\n const singlePane = useCanvasSinglePane();\n const windowTabs = useCanvasState((s) => (singlePane ? windowTabsSignature(s, windowId) : \"\"));\n const sectionRef = useRef<HTMLElement>(null);\n const bodyRef = useRef<HTMLDivElement>(null);\n const presentation = usePanePresentation(slots, paneId, isFullscreen, paneCount);\n const drop = usePaneDrop(paneId, () => sectionRef.current);\n\n useIsoLayoutEffect(() => {\n const body = bodyRef.current;\n const section = sectionRef.current;\n if (body) slots.set(paneId, body);\n slots.setSection(paneId, section);\n return () => {\n slots.unset(paneId, body);\n if (slots.section(paneId) === section) slots.setSection(paneId, null);\n };\n }, [slots, paneId]);\n\n if (!pane) return null;\n\n const kindProps: CanvasKindProps | null =\n active && kind ? { item: active, data: active.data, paneId, isFocused: focused, isVisible: isOpen, canvas, windowId, presentation } : null;\n const Leading = kind?.HeaderLeading;\n const Action = kind?.HeaderAction;\n const Toolbar = kind?.Toolbar;\n const tabs: StripTab[] = singlePane ? parseWindowTabs(windowTabs) : pane.itemIds.map((itemId, index) => ({ itemId, paneId, index }));\n const single = tabStrip === \"auto\" && tabs.length === 1 && active;\n\n const closeLabel = role === \"pop-out\" && paneCount === 1 ? \"Close window\" : paneCount > 1 ? \"Close pane\" : \"Close canvas\";\n\n return (\n <CanvasPanel\n ref={sectionRef}\n panelId={paneId}\n className=\"mxc-pane\"\n title={active ? itemTitle(active, kind) : \"Canvas\"}\n focused={focused}\n data-mxc-pane={paneId}\n header={\n <>\n {canGoBack && active ? (\n <CanvasHeaderButton className=\"mxc-back\" label=\"Back\" shortcut={canvasShortcutHint(\"canvas.back\", isMac())} onClick={() => void canvas.back(active.id)}>\n <ArrowLeftIcon />\n </CanvasHeaderButton>\n ) : null}\n {canGoForward && active ? (\n <CanvasHeaderButton\n className=\"mxc-forward\"\n label=\"Forward\"\n shortcut={canvasShortcutHint(\"canvas.forward\", isMac())}\n onClick={() => void canvas.forward(active.id)}\n >\n <ArrowRightIcon />\n </CanvasHeaderButton>\n ) : null}\n {single && active ? (\n <SingleTitle item={active} kind={kind} />\n ) : tabs.length > 0 ? (\n <TabStrip tabs={tabs} activeItemId={pane.activeItemId} />\n ) : (\n <span className=\"mxc-panel-title\">New tab</span>\n )}\n <CanvasHeaderButton className=\"mxc-new-tab\" label=\"New tab\" onClick={() => void canvas.newTab(paneId)}>\n <PlusIcon />\n </CanvasHeaderButton>\n </>\n }\n leading={Leading && kindProps ? <Leading {...kindProps} /> : null}\n actions={\n Action && kindProps ? (\n // Its own gapless row: a kind's tap buttons space themselves (the tap-target placement rule).\n <span className=\"mxc-kind-actions\">\n <Action {...kindProps} />\n </span>\n ) : null\n }\n renderMenu={() => (\n <PaneMenu\n paneId={paneId}\n windowId={windowId}\n activeItem={active}\n kind={kind}\n kindProps={kindProps}\n tabCount={pane.itemIds.length}\n role={role}\n canSplit={!singlePane}\n />\n )}\n expanded={isFullscreen}\n onToggleExpand={() => canvas.setFullscreen(!isFullscreen)}\n expandShortcut={canvasShortcutHint(\"canvas.toggleFullscreen\", isMac())}\n onHide={windowId === CANVAS_MAIN_WINDOW ? () => canvas.hide() : undefined}\n onClose={() => canvas.closePane(paneId)}\n closeLabel={closeLabel}\n onPointerDownCapture={() => {\n if (!focused) canvas.focusPane(paneId);\n }}\n {...drop}\n >\n {Toolbar && kindProps ? (\n <div className=\"mxc-item-toolbar\" data-kind={active?.kind}>\n <ToolbarBoundary kindId={kind?.id ?? \"\"}>\n <Toolbar {...kindProps} />\n </ToolbarBoundary>\n </div>\n ) : null}\n <div ref={bodyRef} className=\"mxc-pane-slot\" data-mxc-slot={paneId}>\n {pane.itemIds.length === 0 ? <EmptyPaneLauncher paneId={paneId} /> : columnSlots ? null : <CanvasPaneInlineBodies paneId={paneId} slots={slots} />}\n </div>\n </CanvasPanel>\n );\n}\n\n/** A toolbar that throws renders nothing — it must never take the pane down. */\nclass ToolbarBoundary extends Component<{ kindId: string; children: ReactNode }, { failed: boolean }> {\n override state = { failed: false };\n\n static getDerivedStateFromError() {\n return { failed: true };\n }\n\n override componentDidCatch(error: unknown) {\n console.error(`[@ai-matrx/canvas] \"${this.props.kindId}\" Toolbar threw`, error);\n }\n\n override render() {\n return this.state.failed ? null : this.props.children;\n }\n}\n\n/** One tab: its title (draggable) and a close for it — a lone tab is never a trap. */\nfunction SingleTitle({ item, kind }: { item: CanvasItem; kind: AnyCanvasKind | undefined }) {\n const canvas = useCanvas();\n const title = itemTitle(item, kind);\n const drag = useTabDrag(item.id, title);\n const name = useTruncated(title);\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <span className=\"mxc-panel-title mxc-single-title\" data-draggable=\"\" data-truncated={name.truncated ? \"\" : undefined} title={title} {...drag}>\n <Icon className=\"mxc-title-icon\" />\n <span ref={name.ref} className=\"mxc-tab-title\">\n {title}\n </span>\n <button type=\"button\" className=\"mxc-tab-close\" data-slot=\"browser-tab-close\" aria-label={`Close ${title}`} onClick={() => canvas.close(item.id)}>\n <CloseIcon />\n </button>\n </span>\n );\n}\n\n/** A background tab's floor (px): icon + ~7 letters + \"…\" (\"Messag…\"). Mirrored to CSS as --mxc-tab-min. */\nexport const CANVAS_TAB_MIN_WIDTH = 88;\n/** The active tab's floor (px): icon + ~8 letters + \"…\" + its close. Mirrored to CSS as --mxc-tab-active-min. */\nexport const CANVAS_ACTIVE_TAB_MIN_WIDTH = 112;\n/** The \"All tabs\" button and the gaps around it (px). */\nconst TAB_LIST_BUTTON_ROOM = 36;\nconst TAB_GAP = 2;\n\n/**\n * Which tabs the strip shows at this width: all of them when every tab fits\n * at its floor, else as many as fit — always the active one — and the rest\n * are reached through the \"All tabs\" menu (Chrome / VS Code). Pure, so the\n * rule is testable without a layout engine. `width <= 0` (not measured yet)\n * shows everything.\n */\nexport function fitCanvasTabs(\n count: number,\n activeIndex: number,\n width: number,\n): { start: number; end: number; overflow: boolean; compact: boolean } {\n if (count <= 0) return { start: 0, end: 0, overflow: false, compact: false };\n const need = (n: number) => CANVAS_ACTIVE_TAB_MIN_WIDTH + (n - 1) * (CANVAS_TAB_MIN_WIDTH + TAB_GAP);\n if (width <= 0 || need(count) <= width) return { start: 0, end: count, overflow: false, compact: false };\n // One tab that does not fit at its floor: it is the title, as narrow as it must be (nothing to list).\n if (count === 1) return { start: 0, end: 1, overflow: false, compact: true };\n let fit = 1;\n while (fit + 1 < count && need(fit + 1) + TAB_LIST_BUTTON_ROOM <= width) fit += 1;\n const active = Math.min(Math.max(activeIndex, 0), count - 1);\n // Keep the strip's left edge still while the active tab is in the first window; else end on it.\n const start = active < fit ? 0 : active - fit + 1;\n return { start, end: start + fit, overflow: true, compact: need(fit) + TAB_LIST_BUTTON_ROOM > width };\n}\n\n/**\n * The tab strip. It takes the header's free width (never its own content's:\n * flex-basis 0, so what it shows never changes how wide it is). Tabs are as\n * wide as their names; when room runs short they shrink with an ellipsis to\n * their floor (icon + ~6 letters; the active tab keeps more), and past that\n * the tabs that do not fit go into the \"All tabs\" menu — the active tab is\n * always shown. At the narrowest the strip is the active tab's title and that\n * menu. Nothing in the header ever overlaps another control.\n */\nfunction TabStrip({ tabs, activeItemId }: { tabs: readonly StripTab[]; activeItemId: CanvasItemId | null }) {\n const canvas = useCanvas();\n const strip = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState(0);\n // The fit is read from the strip's real width, so it is re-read whenever that width can have settled:\n // on mount, on the strip's own resize, once fonts have loaded, after layout (next frames) and whenever\n // the tabs change (restored items render after the first paint). A pre-layout width never stands.\n const read = useRef<() => void>(() => {});\n useIsoLayoutEffect(() => {\n const el = strip.current;\n if (!el) return undefined;\n let live = true;\n const measure = () => {\n if (live) setWidth(Math.floor(el.getBoundingClientRect().width));\n };\n read.current = measure;\n measure();\n const observer = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(measure);\n observer?.observe(el);\n void document.fonts?.ready?.then(measure);\n const frame = typeof requestAnimationFrame === \"undefined\" ? 0 : requestAnimationFrame(() => requestAnimationFrame(measure));\n return () => {\n live = false;\n observer?.disconnect();\n if (frame && typeof cancelAnimationFrame !== \"undefined\") cancelAnimationFrame(frame);\n };\n }, []);\n useIsoLayoutEffect(() => {\n read.current();\n }, [tabs.length]);\n const activeIndex = Math.max(0, tabs.findIndex((tab) => tab.itemId === activeItemId));\n const fit = fitCanvasTabs(tabs.length, activeIndex, width);\n const shown = tabs.slice(fit.start, fit.end);\n const hidden = tabs.length - shown.length;\n return (\n <div\n ref={strip}\n className=\"mxc-tabstrip\"\n data-overflow={fit.overflow ? \"\" : undefined}\n data-compact={fit.compact ? \"\" : undefined}\n style={{ [\"--mxc-tab-min\" as string]: `${CANVAS_TAB_MIN_WIDTH}px`, [\"--mxc-tab-active-min\" as string]: `${CANVAS_ACTIVE_TAB_MIN_WIDTH}px` }}\n >\n <div\n className=\"mxc-tabs\"\n role=\"tablist\"\n aria-label=\"Canvas tabs\"\n onWheel={(event) => {\n // The wheel steps through tabs when some are out of sight (there is nothing to scroll).\n if (!fit.overflow || Math.abs(event.deltaY) < Math.abs(event.deltaX) || tabs.length < 2) return;\n const next = tabs[(activeIndex + (event.deltaY > 0 ? 1 : -1) + tabs.length) % tabs.length];\n if (next) canvas.activate(next.itemId);\n }}\n >\n {shown.map((tab) => (\n <ItemTab key={tab.itemId} itemId={tab.itemId} paneId={tab.paneId} index={tab.index} active={tab.itemId === activeItemId} />\n ))}\n </div>\n {fit.overflow ? <TabListMenu tabs={tabs} activeItemId={activeItemId} hidden={hidden} /> : null}\n </div>\n );\n}\n\n/** \"All tabs\": every tab of the strip by name, the active one marked — where tabs that do not fit are reached. */\nfunction TabListMenu({ tabs, activeItemId, hidden }: { tabs: readonly StripTab[]; activeItemId: CanvasItemId | null; hidden: number }) {\n const canvas = useCanvas();\n const { ports, layer } = useCanvasInternals();\n const blocking = useRef<(() => void) | null>(null);\n useEffect(() => () => blocking.current?.(), []);\n const label = `All tabs (${tabs.length})`;\n const trigger = (props: { onClick?: (event: ReactMouseEvent<HTMLButtonElement>) => void }) => (\n <CanvasHeaderButton className=\"mxc-tab-list\" label={label} data-hidden-count={hidden} {...props}>\n <ChevronDownIcon />\n <span className=\"mxc-tab-list-count\" aria-hidden=\"true\">\n {hidden}\n </span>\n </CanvasHeaderButton>\n );\n const showMenu = ports.showMenu;\n if (showMenu) {\n return trigger({\n onClick: (event) => {\n const state = canvas.getState();\n const entries: CanvasMenuEntry[] = tabs.map((tab) => {\n const item = state.items[tab.itemId];\n const title = item ? itemTitle(item, resolveItemKind(item.kind, getCanvasKind)) : tab.itemId;\n return { type: \"item\", id: tab.itemId, label: tab.itemId === activeItemId ? `${title} (current)` : title };\n });\n void showMenu(entries, toCanvasRect(event.currentTarget.getBoundingClientRect())).then(\n (chosen) => {\n if (chosen) canvas.activate(chosen as CanvasItemId);\n },\n (error: unknown) => console.error(\"[@ai-matrx/canvas] the host menu failed\", error),\n );\n },\n });\n }\n return (\n <Menu.Root\n onOpenChange={(open) => {\n blocking.current?.();\n blocking.current = open ? layer.beginBlocking() : null;\n }}\n >\n <Menu.Trigger asChild>{trigger({})}</Menu.Trigger>\n <Menu.Portal>\n <Menu.Content align=\"end\" sideOffset={4} className=\"mxc-menu mxc-tab-list-menu\" aria-label=\"All tabs\">\n {tabs.map((tab) => (\n <TabListEntry key={tab.itemId} itemId={tab.itemId} active={tab.itemId === activeItemId} />\n ))}\n </Menu.Content>\n </Menu.Portal>\n </Menu.Root>\n );\n}\n\nfunction TabListEntry({ itemId, active }: { itemId: CanvasItemId; active: boolean }) {\n const canvas = useCanvas();\n const item = useCanvasState((s) => s.items[itemId]);\n const kind = useItemKind(item?.kind ?? \"\");\n if (!item) return null;\n const Icon = kind?.icon ?? AlertIcon;\n const title = itemTitle(item, kind);\n return (\n <Menu.Item\n className=\"mxc-menu-item mxc-tab-list-item\"\n data-active={active ? \"\" : undefined}\n aria-current={active ? \"true\" : undefined}\n title={title}\n onSelect={() => canvas.activate(itemId)}\n >\n <Icon />\n <span className=\"mxc-tab-list-title\">{title}</span>\n </Menu.Item>\n );\n}\n\nfunction ItemTab({ itemId, paneId, index, active }: { itemId: CanvasItemId; paneId: CanvasPaneId; index: number; active: boolean }) {\n const canvas = useCanvas();\n const item = useCanvasState((s) => s.items[itemId]);\n const kind = useItemKind(item?.kind ?? \"\");\n const title = item ? itemTitle(item, kind) : \"\";\n const drag = useTabDrag(itemId, title);\n if (!item) return null;\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <CanvasTab\n title={title}\n icon={<Icon />}\n active={active}\n onSelect={() => canvas.activate(itemId)}\n onClose={() => canvas.close(itemId)}\n {...drag}\n onDragOver={(event) => {\n if (event.dataTransfer.types.includes(CANVAS_DRAG_MIME)) event.preventDefault();\n }}\n onDrop={(event) => {\n const dragged = event.dataTransfer.getData(CANVAS_DRAG_MIME) as CanvasItemId;\n if (!dragged) return;\n // Dropped ON a tab: take that tab's place (the pane-level drop still clears its indicator).\n event.preventDefault();\n if (dragged !== itemId) canvas.moveItem(dragged, paneId, index);\n }}\n onAuxClick={(event) => {\n if (event.button === 1) canvas.close(itemId);\n }}\n />\n );\n}\n\ninterface MenuAction {\n readonly id: string;\n readonly label: string;\n readonly icon?: ReactNode;\n readonly destructive?: boolean;\n readonly onSelect: () => void;\n}\n\nfunction PaneMenu({\n paneId,\n windowId,\n activeItem,\n kind,\n kindProps,\n tabCount,\n role,\n canSplit,\n}: {\n paneId: CanvasPaneId;\n windowId: CanvasWindowId;\n activeItem: CanvasItem | undefined;\n kind: AnyCanvasKind | undefined;\n kindProps: CanvasKindProps | null;\n tabCount: number;\n role: \"main\" | \"window\" | \"pop-out\";\n /** False on a phone: it presents one pane, so a split would show an empty pane under the header of another. */\n canSplit: boolean;\n}) {\n const canvas = useCanvas();\n const { ports, layer, itemMenus } = useCanvasInternals();\n const moveId = tabCount > 1 ? activeItem?.id : undefined;\n const blocking = useRef<(() => void) | null>(null);\n useEffect(() => () => blocking.current?.(), []);\n\n // Built when the menu OPENS, so what a body offers (useCanvasMenuItems) is current.\n const buildSections = (): MenuAction[][] => {\n const kindItems: readonly CanvasMenuItem[] = kind?.menuItems && kindProps ? safeMenu(() => kind.menuItems?.(kindProps)) : [];\n const hostItems: readonly CanvasMenuItem[] = activeItem && ports.itemActions ? safeMenu(() => ports.itemActions?.(activeItem, kind)) : [];\n // What the body offers right now (useCanvasMenuItems) — read as the menu is built, never a second \"…\".\n const bodyItems: readonly CanvasMenuItem[] = activeItem ? itemMenus.read(activeItem.id) : [];\n return [\n [...kindItems, ...bodyItems, ...hostItems].map((entry) => ({ ...entry, id: `item:${entry.id}` })),\n [\n ...(canSplit\n ? [\n { id: \"split-right\", label: \"Split right\", icon: <SplitRightIcon />, onSelect: () => canvas.splitPane(paneId, \"horizontal\", moveId) },\n { id: \"split-down\", label: \"Split down\", icon: <SplitDownIcon />, onSelect: () => canvas.splitPane(paneId, \"vertical\", moveId) },\n ]\n : []),\n ...(activeItem && role === \"pop-out\"\n ? [{ id: \"dock-back\", label: \"Dock back\", icon: <DockIcon />, onSelect: () => void canvas.dockBack(activeItem.id) }]\n : activeItem && ports.popOut\n ? [{ id: \"pop-out\", label: \"Pop out\", icon: <PopOutIcon />, onSelect: () => void canvas.popOut(activeItem.id) }]\n : []),\n ],\n activeItem\n ? [\n { id: \"close-tab\", label: \"Close tab\", onSelect: () => canvas.close(activeItem.id) },\n ...(tabCount > 1 ? [{ id: \"close-others\", label: \"Close other tabs\", onSelect: () => canvas.closeOthers(activeItem.id) }] : []),\n ]\n : [],\n ].filter((section) => section.length > 0);\n };\n\n const showMenu = ports.showMenu;\n if (showMenu) {\n // The host draws the menu (above native views); the package keeps the handlers.\n return (\n <CanvasMenuTrigger\n onClick={(event) => {\n const entries: CanvasMenuEntry[] = [];\n const handlers = new Map<string, () => void>();\n buildSections().forEach((section, i) => {\n if (i > 0) entries.push({ type: \"separator\" });\n for (const action of section) {\n entries.push({ type: \"item\", id: action.id, label: action.label, ...(action.destructive ? { destructive: true } : {}) });\n handlers.set(action.id, action.onSelect);\n }\n });\n const anchor = toCanvasRect(event.currentTarget.getBoundingClientRect());\n void showMenu(entries, anchor).then(\n (chosen) => {\n if (chosen) handlers.get(chosen)?.();\n },\n (error: unknown) => console.error(\"[@ai-matrx/canvas] the host menu failed\", error),\n );\n }}\n />\n );\n }\n\n return (\n <Menu.Root\n onOpenChange={(open) => {\n // A DOM menu over a native view must be seen: tell the host to step its views aside.\n blocking.current?.();\n blocking.current = open ? layer.beginBlocking() : null;\n }}\n >\n <Menu.Trigger asChild>\n <CanvasMenuTrigger />\n </Menu.Trigger>\n <Menu.Portal>\n <Menu.Content align=\"end\" sideOffset={4} className=\"mxc-menu\">\n <MenuSections build={buildSections} />\n </Menu.Content>\n </Menu.Portal>\n </Menu.Root>\n );\n}\n\n/** Rendered only while the menu is open: the sections are read then. */\nfunction MenuSections({ build }: { build: () => MenuAction[][] }) {\n return (\n <>\n {build().map((section, i) => (\n <MenuSection key={i} first={i === 0} actions={section} />\n ))}\n </>\n );\n}\n\nfunction MenuSection({ first, actions }: { first: boolean; actions: readonly MenuAction[] }) {\n return (\n <>\n {first ? null : <Menu.Separator className=\"mxc-menu-separator\" />}\n {actions.map((action) => (\n <Menu.Item key={action.id} onSelect={action.onSelect} className=\"mxc-menu-item\" data-destructive={action.destructive ? \"\" : undefined}>\n {action.icon}\n {action.label}\n </Menu.Item>\n ))}\n </>\n );\n}\n\nfunction safeMenu(build: () => readonly CanvasMenuItem[] | undefined): readonly CanvasMenuItem[] {\n try {\n return build() ?? [];\n } catch (error) {\n console.error(\"[@ai-matrx/canvas] a menu builder threw\", error);\n return [];\n }\n}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AC;AACD,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,OAAO,KAAK;AAClB,QAAM,SAAS,YAAY,UAAU,kBAAkB;AACvD,QAAM,OAAO,KAAK,SAAS,KAAK;AAChC,SACE,gBAAAA;AAAA,IAAC;AAAA;AAAA,MACC,WAAW;AAAA,MACX,SAAS;AAAA,MACT,MAAM,gBAAAA,KAAC,QAAK;AAAA,MACZ,SAAS,OAAO;AAAA,MAChB,SAAS,MAAM,KAAK,OAAO,OAAO;AAAA;AAAA,EACpC;AAEJ;AAMO,SAAS,YAAY,EAAE,UAAU,UAAU,GAAgD;AAChG,QAAM,EAAE,SAAS,IAAI,mBAAmB;AACxC,QAAM,eAAe,eAAe,CAAC,MAAM,yBAAyB,GAAG,QAAQ,CAAC;AAChF,QAAM,SAAS,eAAe,CAAC,MAAM,mBAAmB,GAAG,QAAQ,CAAC;AACpE,SACE,gBAAAC,MAAC,SAAI,WAAW,CAAC,aAAa,SAAS,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,GAAG,oBAAkB,SAAS,KAAK,QAClG;AAAA,oBAAAD,KAAC,SAAI,WAAU,kBAAiB,QAAQ,UAAU,cAC/C,UACH;AAAA,IACA,gBAAAA,KAAC,gBAAa;AAAA,KAChB;AAEJ;","names":["useEffect","useRef","useState","useSyncExternalStore","frame","focused","isMac","frame","frame","useEffect","useLayoutEffect","useRef","jsx","useRef","useState","useEffect","isMac","useSyncExternalStore","useEffect","useLayoutEffect","useRef","useState","useSyncExternalStore","useEffect","useLayoutEffect","useMemo","useRef","useState","useEffect","useLayoutEffect","useRef","useState","jsx","jsxs","jsx","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","useRef","useState","CanvasHeaderButton","CanvasMenuTrigger","CanvasPanel","CanvasTab","useEffect","useRef","useRef","useEffect","jsx","jsxs","createContext","useContext","createContext","useContext","useSyncExternalStore","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","useMemo","SEP","frame","useRef","useState","BodyHost","Rendered","Component","useEffect","useLayoutEffect","useRef","useState","Fragment","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","frame","useState","useRef","Component","Fragment","jsx","jsxs","useIsoLayoutEffect","useEffect","useLayoutEffect","useSyncExternalStore","useState","useRef","frame","isMac"]}
|