@ai-matrx/canvas 0.3.0 → 0.4.0
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 +8 -0
- package/README.md +5 -0
- package/dist/react.cjs +23 -7
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +7 -0
- package/dist/react.d.ts +7 -0
- package/dist/react.js +23 -7
- package/dist/react.js.map +1 -1
- package/dist/styles.css +17 -0
- package/package.json +1 -1
package/dist/react.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react.ts","../src/react/provider.tsx","../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/toggleKind.ts","../src/react/layer.tsx","../src/react/registry.ts","../src/react/CanvasColumn.tsx","../src/react/CanvasPane.tsx","../src/react/chrome.tsx","../src/react/icons.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * @ai-matrx/canvas/react — the canvas column, panes, tabs, toggle, provider,\n * hooks, the kind registry, and THE canvas chrome (panel frame, header\n * buttons, tab strip, browser bar). Import `@ai-matrx/canvas/styles.css` once.\n */\n\nexport {\n CanvasProvider,\n CanvasWindowScope,\n useCanvas,\n useOptionalCanvas,\n useCanvasState,\n useOptionalCanvasState,\n useCanvasKindToggle,\n useCanvasIsPresented,\n useCanvasWindowId,\n useCanvasNativeBodies,\n useCanvasKinds,\n useCanvasKind,\n useCanvasHostPorts,\n type CanvasProviderProps,\n type CanvasHostPorts,\n type CanvasTabStripMode,\n} from \"./react/provider\";\nexport {\n defineCanvasKind,\n registerCanvasKind,\n registerCanvasKinds,\n getCanvasKind,\n listCanvasKinds,\n canvasSessionKey,\n type CanvasKind,\n type CanvasKindProps,\n type CanvasMenuItem,\n type AnyCanvasKind,\n} from \"./react/registry\";\nexport { CanvasColumn, CanvasFrame, CanvasToggle, useCanvasColumnWidth, type CanvasColumnProps } from \"./react/CanvasColumn\";\nexport { CanvasPaneView, itemTitle } from \"./react/CanvasPane\";\nexport {\n CanvasPanel,\n CanvasPanelEmpty,\n CanvasHeaderButton,\n CanvasMenuTrigger,\n CanvasTab,\n BrowserTabs,\n BrowserBar,\n type CanvasPanelProps,\n type CanvasHeaderButtonProps,\n type CanvasTabProps,\n type BrowserTab,\n type BrowserTabsProps,\n type BrowserBarProps,\n} from \"./react/chrome\";\nexport type {\n CanvasFloating,\n CanvasOverlayPort,\n CanvasMenuEntry,\n CanvasShowMenu,\n CanvasNativeRect,\n CanvasNativeBodyInfo,\n CanvasNativeBodyFrame,\n} from \"./react/layer\";\n","\"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 useRef,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from \"react\";\nimport {\n CANVAS_DEFAULT_KEY,\n CANVAS_MAIN_WINDOW,\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 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}\n\n/** Phones show an open canvas full screen; a remembered \"open\" never takes over a phone on load. */\nconst PHONE_MAX_WIDTH = 767;\nconst isPhoneViewport = () => typeof window !== \"undefined\" && window.innerWidth <= 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 ...hostPorts\n}: CanvasProviderProps) {\n const portsRef = useRef<CanvasHostPorts>(hostPorts);\n portsRef.current = hostPorts;\n const [{ controller, layer }] = 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 }),\n layer: createCanvasLayer(() => portsRef.current),\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: CanvasContextValue = { controller, windowId, ports: hostPorts, layer, regionWidth, tabStrip };\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 id = canvasWindowId(windowId);\n const value: CanvasContextValue = { ...parent, windowId: id, controller: parent.controller.forWindow(id) };\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","/**\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\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}\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\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_MAIN_WINDOW,\n CANVAS_MIN_WIDTH,\n type CanvasExtraWindow,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasLayoutNode,\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}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 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\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] = 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: CanvasItem = { id: itemId, kind, key, title: title ?? null, data: data ?? null, openedAt: now, updatedAt: 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}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\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 stackSplit: 0.5,\n sideSplit: 0.5,\n paneMinWidth: 0,\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\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 { 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 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\", 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_MAIN_WINDOW,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasOpenInput,\n type CanvasOrientation,\n type CanvasPaneId,\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\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 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}\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 };\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 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 (options.isKnownKind && !options.isKnownKind(input.kind)) {\n onError({ code: \"unknown-kind\", message: `No canvas kind \"${input.kind}\" is registered.`, detail: input });\n return null;\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 null;\n }\n }\n const target = input.target ?? \"focused\";\n const splitShare = target === \"split-down\" ? rules.stackSplit : target === \"split-right\" ? rules.sideSplit : undefined;\n const resolved: CanvasOpenInput = input.windowId || windowId === CANVAS_MAIN_WINDOW ? input : { ...input, 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 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 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","/**\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 *\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 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 controller.close(itemId);\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 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 /** The canvas, acting for the window this pane is in. */\n readonly canvas: CanvasController;\n readonly windowId: CanvasWindowId;\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 /** Stays mounted while its tab is in the background (live chat, a running tool). */\n readonly keepAlive?: boolean;\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 /** 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\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_MIN_SPLIT_FRACTION,\n canvasShortcutHint,\n clampDraggedCanvasWidth,\n fitCanvasWidth,\n selectCanvasIsFullscreen,\n selectCanvasIsOpen,\n selectCanvasLayout,\n selectCanvasWidth,\n selectCanvasWindowItemCount,\n shouldStackSplit,\n type CanvasLayoutNode,\n} from \"../index\";\nimport { CanvasPaneView } from \"./CanvasPane\";\nimport { PanelRightIcon } from \"./icons\";\nimport { useCanvas, useCanvasInternals, useCanvasState, useRegisterCanvasPresence } from \"./provider\";\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 } = 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 region = useRegionWidth();\n const [dragWidth, setDragWidth] = useState<number | null>(null);\n useRegisterCanvasPresence();\n\n if (!isOpen || !layout) return null;\n const fitted = fitCanvasWidth(width, region, controller.rules);\n const shown = dragWidth ?? fitted;\n\n return (\n <aside\n className={[\"mxc-column\", className].filter(Boolean).join(\" \")}\n data-fullscreen={isFullscreen ? \"\" : undefined}\n data-placement={placement}\n data-mxc-window={windowId}\n aria-label=\"Canvas\"\n style={{ ...style, [\"--mxc-width\" as string]: `${shown}px` }}\n >\n {placement === \"docked\" && !isFullscreen ? (\n <WidthHandle\n width={fitted}\n region={region}\n onDrag={(next) => {\n setDragWidth(next);\n onLiveWidth?.(next);\n }}\n />\n ) : null}\n <div className=\"mxc-layout\">\n <LayoutNodeView node={layout} />\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 } | null>(null);\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 = { x: event.clientX, width };\n document.documentElement.dataset.mxcResizing = \"\";\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 = null;\n delete document.documentElement.dataset.mxcResizing;\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 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 document.documentElement.dataset.mxcResizing = 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 delete document.documentElement.dataset.mxcResizing;\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 onClick={() => controller.toggle()}\n />\n {count > 0 && !isOpen ? <span className=\"mxc-toggle-badge\">{count}</span> : null}\n </span>\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 * One pane, drawn with THE canvas chrome (CanvasPanel): a header — the title\n * (one tab) or the tab strip, the kind's leading controls, the kind's own\n * button, \"…\", expand, close — over the active item's body. Tabs drag between\n * panes (and windows). An empty pane shows the launcher of every kind that\n * offers one. A native-body kind gets a placeholder whose frame is reported to\n * the host in the same frame the layout changed.\n */\n\nimport {\n Component,\n Suspense,\n lazy,\n useEffect,\n useLayoutEffect,\n useRef,\n type ComponentType,\n type DragEvent,\n type ErrorInfo,\n type ReactNode,\n} from \"react\";\nimport * as Menu from \"@radix-ui/react-dropdown-menu\";\nimport type { CanvasItem, CanvasItemId, CanvasPaneId, CanvasWindowId } from \"../index\";\nimport {\n CANVAS_MAIN_WINDOW,\n canvasShortcutHint,\n selectCanvasFocusedPaneId,\n selectCanvasIsFullscreen,\n selectCanvasPaneCount,\n} from \"../index\";\nimport { CanvasMenuTrigger, CanvasPanel, CanvasPanelEmpty, CanvasTab } from \"./chrome\";\nimport { AlertIcon, DockIcon, PopOutIcon, SplitDownIcon, SplitRightIcon } from \"./icons\";\nimport { toCanvasRect, type CanvasMenuEntry, type CanvasNativeRect } from \"./layer\";\nimport { useCanvas, useCanvasInternals, useCanvasKind, useCanvasKinds, useCanvasState } from \"./provider\";\nimport type { AnyCanvasKind, CanvasKindProps, CanvasMenuItem } from \"./registry\";\n\nconst DRAG_MIME = \"application/x-matrx-canvas-item\";\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 panes 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\nexport function itemTitle(item: CanvasItem, kind: AnyCanvasKind | undefined): string {\n if (item.title) return item.title;\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/** Drag handlers shared by a tab and a single-tab title: the dragged tab is announced so native views can step aside. */\nfunction 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(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\nexport function CanvasPaneView({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n const { windowId, layer, ports, tabStrip } = useCanvasInternals();\n const pane = useCanvasState((s) => s.panes[paneId]);\n const items = useCanvasState((s) => s.items);\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(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 active = pane?.activeItemId ? items[pane.activeItemId] : undefined;\n const kind = useCanvasKind(active?.kind ?? \"\");\n const drop = useRef<(() => void) | null>(null);\n const sectionRef = useRef<HTMLElement>(null);\n\n useEffect(() => () => drop.current?.(), []);\n if (!pane) return null;\n\n const kindProps: CanvasKindProps | null =\n active && kind ? { item: active, data: active.data, paneId, isFocused: focused, canvas, windowId } : null;\n const Leading = kind?.HeaderLeading;\n const Action = kind?.HeaderAction;\n const single = tabStrip === \"auto\" && pane.itemIds.length === 1 && active;\n\n const hideDrop = () => {\n drop.current?.();\n drop.current = null;\n };\n const onDragOver = (event: DragEvent) => {\n if (!event.dataTransfer.types.includes(DRAG_MIME)) return;\n event.preventDefault();\n event.dataTransfer.dropEffect = \"move\";\n if (!drop.current && sectionRef.current) {\n drop.current = layer.show({ type: \"drop-indicator\", rect: toCanvasRect(sectionRef.current.getBoundingClientRect()), paneId });\n }\n };\n const onDragLeave = (event: DragEvent) => {\n const next = event.relatedTarget as Node | null;\n if (next && sectionRef.current?.contains(next)) return;\n hideDrop();\n };\n const onDrop = (event: DragEvent) => {\n hideDrop();\n const itemId = event.dataTransfer.getData(DRAG_MIME) as CanvasItemId;\n if (!itemId) return;\n event.preventDefault();\n canvas.moveItem(itemId, paneId);\n };\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 single && active ? (\n <SingleTitle item={active} kind={kind} />\n ) : pane.itemIds.length > 0 ? (\n <div className=\"mxc-tabs\" role=\"tablist\" aria-label=\"Canvas tabs\">\n {pane.itemIds.map((itemId, index) => (\n <ItemTab key={itemId} itemId={itemId} paneId={paneId} index={index} active={itemId === pane.activeItemId} />\n ))}\n </div>\n ) : (\n <span className=\"mxc-panel-title\">New tab</span>\n )\n }\n leading={Leading && kindProps ? <Leading {...kindProps} /> : null}\n actions={Action && kindProps ? <Action {...kindProps} /> : null}\n renderMenu={() => <PaneMenu paneId={paneId} windowId={windowId} activeItem={active} kind={kind} kindProps={kindProps} tabCount={pane.itemIds.length} role={role} />}\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 onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n >\n {pane.itemIds.length === 0 ? (\n <Launcher paneId={paneId} />\n ) : (\n pane.itemIds.map((itemId) => {\n const item = items[itemId];\n if (!item) return null;\n const isActive = itemId === pane.activeItemId;\n return <ItemBody key={itemId} item={item} paneId={paneId} windowId={windowId} isActive={isActive} isFocused={focused && isActive} hasNativePort={!!ports.onNativeBodyFrame} />;\n })\n )}\n </CanvasPanel>\n );\n}\n\nfunction SingleTitle({ item, kind }: { item: CanvasItem; kind: AnyCanvasKind | undefined }) {\n const title = itemTitle(item, kind);\n const drag = useTabDrag(item.id, title);\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <span className=\"mxc-panel-title\" data-draggable=\"\" title={title} {...drag}>\n <Icon className=\"mxc-title-icon\" />\n <span className=\"mxc-tab-title\">{title}</span>\n </span>\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 = useCanvasKind(item?.kind ?? \"\");\n const ref = useRef<HTMLDivElement>(null);\n const title = item ? itemTitle(item, kind) : \"\";\n const drag = useTabDrag(itemId, title);\n useEffect(() => {\n if (active) ref.current?.scrollIntoView?.({ block: \"nearest\", inline: \"nearest\" });\n }, [active]);\n if (!item) return null;\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <CanvasTab\n ref={ref}\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(DRAG_MIME)) event.preventDefault();\n }}\n onDrop={(event) => {\n const dragged = event.dataTransfer.getData(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}: {\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}) {\n const canvas = useCanvas();\n const { ports, layer } = useCanvasInternals();\n const moveId = tabCount > 1 ? activeItem?.id : undefined;\n const blocking = useRef<(() => void) | null>(null);\n useEffect(() => () => blocking.current?.(), []);\n\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 const sections: MenuAction[][] = [\n [...kindItems, ...hostItems].map((entry) => ({ ...entry, id: `item:${entry.id}` })),\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 ...(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 const showMenu = ports.showMenu;\n if (showMenu) {\n // The host draws the menu (above native views); the package keeps the handlers.\n const entries: CanvasMenuEntry[] = [];\n const handlers = new Map<string, () => void>();\n sections.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 return (\n <CanvasMenuTrigger\n onClick={(event) => {\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 {sections.map((section, i) => (\n <MenuSection key={i} first={i === 0} actions={section} />\n ))}\n </Menu.Content>\n </Menu.Portal>\n </Menu.Root>\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\nfunction ItemBody({\n item,\n paneId,\n windowId,\n isActive,\n isFocused,\n hasNativePort,\n}: {\n item: CanvasItem;\n paneId: CanvasPaneId;\n windowId: CanvasWindowId;\n isActive: boolean;\n isFocused: boolean;\n hasNativePort: boolean;\n}) {\n const canvas = useCanvas();\n const kind = useCanvasKind(item.kind);\n if (!isActive && !kind?.keepAlive) return null;\n const props: CanvasKindProps = { item, data: item.data, paneId, isFocused, canvas, windowId };\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 let body: ReactNode;\n if (!kind) {\n body = <ItemProblem message=\"This item can no longer be shown.\" onClose={() => canvas.close(item.id)} />;\n } else if (unavailable) {\n body = <CanvasPanelEmpty>{unavailable}</CanvasPanelEmpty>;\n } else if (kind.body === \"native\") {\n body = hasNativePort ? (\n <NativeBody itemId={item.id} windowId={windowId}>\n {kindComponent(kind) ? <Rendered kind={kind} item={item} props={props} /> : null}\n </NativeBody>\n ) : (\n <CanvasPanelEmpty>Opens in the desktop app</CanvasPanelEmpty>\n );\n } else {\n body = <Rendered kind={kind} item={item} props={props} />;\n }\n return (\n <div className=\"mxc-item\" hidden={!isActive} data-kind={item.kind}>\n {body}\n </div>\n );\n}\n\nfunction Rendered({ kind, item, props }: { kind: AnyCanvasKind; item: CanvasItem; props: CanvasKindProps }) {\n const canvas = useCanvas();\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 (layout effect — before paint, so the view moves in the same frame as\n * the CSS), on every resize of the element, on window resize, and whenever the\n * host asks (`useCanvasNativeBodies().remeasure()`); null once it is hidden or gone.\n */\nfunction NativeBody({ itemId, windowId, children }: { itemId: CanvasItemId; windowId: CanvasWindowId; 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 = 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\nfunction Launcher({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n const kinds = useCanvasKinds().filter((kind) => kind.launcher);\n if (kinds.length === 0) return <CanvasPanelEmpty>Nothing open</CanvasPanelEmpty>;\n return (\n <div className=\"mxc-launcher\">\n {kinds.map((kind) => {\n const Icon = kind.icon;\n const launcher = kind.launcher;\n if (!launcher) return null;\n return (\n <button\n key={kind.id}\n type=\"button\"\n className=\"mxc-launcher-item\"\n onClick={() =>\n canvas.open({\n kind: kind.id,\n key: launcher.key,\n data: launcher.data,\n title: launcher.title ?? null,\n target: { paneId },\n })\n }\n >\n <Icon className=\"mxc-launcher-icon\" />\n <span>{launcher.title ?? kind.label}</span>\n </button>\n );\n })}\n </div>\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 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\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 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 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 className=\"mxc-tab-title\">{shown}</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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,IAAAA,gBAQO;;;ACqBA,IAAM,qBAAqB;AAwG3B,IAAM,mBAAmB;AACzB,IAAM,uBAAuB;AAC7B,IAAM,4BAA4B;;;AC9IzC,IAAM,MAAM;AAEL,SAAS,aAAa,MAAc,KAA2B;AACpE,SAAO,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG;AAC5B;AAOO,SAAS,cAAc,KAA2B;AACvD,SAAO,QAAQ,GAAG;AACpB;AAEO,SAAS,eAAe,KAA4B;AACzD,SAAO,SAAS,GAAG;AACrB;AAOO,SAAS,YAAY,OAAgB,OAAO,QAAuB;AACxE,MAAI,UAAU,KAAM,QAAO;AAC3B,UAAQ,OAAO,OAAO;AAAA,IACpB,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,OAAO,SAAS,KAAK,IAAI,OAAO;AAAA,IACzC,KAAK,UAAU;AACb,UAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,iBAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,gBAA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E,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,8CAAC,SAAI,WAAW,CAAC,aAAa,SAAS,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,GAAG,oBAAkB,SAAS,KAAK,QAClG;AAAA,iDAAC,SAAI,WAAU,kBAAiB,QAAQ,UAAU,cAC/C,UACH;AAAA,IACA,6CAAC,gBAAa;AAAA,KAChB;AAEJ;","names":["import_react","frame","focused","isMac","frame","frame","import_jsx_runtime","isMac","import_react","import_react","import_react","import_jsx_runtime","import_jsx_runtime","CanvasHeaderButton","CanvasMenuTrigger","CanvasPanel","CanvasTab","import_jsx_runtime","import_jsx_runtime","useIsoLayoutEffect","isMac"]}
|
|
1
|
+
{"version":3,"sources":["../src/react.ts","../src/react/provider.tsx","../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/toggleKind.ts","../src/react/layer.tsx","../src/react/registry.ts","../src/react/CanvasColumn.tsx","../src/react/CanvasPane.tsx","../src/react/chrome.tsx","../src/react/icons.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * @ai-matrx/canvas/react — the canvas column, panes, tabs, toggle, provider,\n * hooks, the kind registry, and THE canvas chrome (panel frame, header\n * buttons, tab strip, browser bar). Import `@ai-matrx/canvas/styles.css` once.\n */\n\nexport {\n CanvasProvider,\n CanvasWindowScope,\n useCanvas,\n useOptionalCanvas,\n useCanvasState,\n useOptionalCanvasState,\n useCanvasKindToggle,\n useCanvasIsPresented,\n useCanvasWindowId,\n useCanvasNativeBodies,\n useCanvasKinds,\n useCanvasKind,\n useCanvasHostPorts,\n type CanvasProviderProps,\n type CanvasHostPorts,\n type CanvasTabStripMode,\n} from \"./react/provider\";\nexport {\n defineCanvasKind,\n registerCanvasKind,\n registerCanvasKinds,\n getCanvasKind,\n listCanvasKinds,\n canvasSessionKey,\n type CanvasKind,\n type CanvasKindProps,\n type CanvasMenuItem,\n type AnyCanvasKind,\n} from \"./react/registry\";\nexport { CanvasColumn, CanvasFrame, CanvasToggle, useCanvasColumnWidth, type CanvasColumnProps } from \"./react/CanvasColumn\";\nexport { CanvasPaneView, itemTitle } from \"./react/CanvasPane\";\nexport {\n CanvasPanel,\n CanvasPanelEmpty,\n CanvasHeaderButton,\n CanvasMenuTrigger,\n CanvasTab,\n BrowserTabs,\n BrowserBar,\n type CanvasPanelProps,\n type CanvasHeaderButtonProps,\n type CanvasTabProps,\n type BrowserTab,\n type BrowserTabsProps,\n type BrowserBarProps,\n} from \"./react/chrome\";\nexport type {\n CanvasFloating,\n CanvasOverlayPort,\n CanvasMenuEntry,\n CanvasShowMenu,\n CanvasNativeRect,\n CanvasNativeBodyInfo,\n CanvasNativeBodyFrame,\n} from \"./react/layer\";\n","\"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 useRef,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from \"react\";\nimport {\n CANVAS_DEFAULT_KEY,\n CANVAS_MAIN_WINDOW,\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 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}\n\n/** Phones show an open canvas full screen; a remembered \"open\" never takes over a phone on load. */\nconst PHONE_MAX_WIDTH = 767;\nconst isPhoneViewport = () => typeof window !== \"undefined\" && window.innerWidth <= 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 ...hostPorts\n}: CanvasProviderProps) {\n const portsRef = useRef<CanvasHostPorts>(hostPorts);\n portsRef.current = hostPorts;\n const [{ controller, layer }] = 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 }),\n layer: createCanvasLayer(() => portsRef.current),\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: CanvasContextValue = { controller, windowId, ports: hostPorts, layer, regionWidth, tabStrip };\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 id = canvasWindowId(windowId);\n const value: CanvasContextValue = { ...parent, windowId: id, controller: parent.controller.forWindow(id) };\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","/**\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\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}\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\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_MAIN_WINDOW,\n CANVAS_MIN_WIDTH,\n type CanvasExtraWindow,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasLayoutNode,\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}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 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\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] = 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: CanvasItem = { id: itemId, kind, key, title: title ?? null, data: data ?? null, openedAt: now, updatedAt: 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}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\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 stackSplit: 0.5,\n sideSplit: 0.5,\n paneMinWidth: 0,\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\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 { 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 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\", 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_MAIN_WINDOW,\n type CanvasItem,\n type CanvasItemId,\n type CanvasJson,\n type CanvasOpenInput,\n type CanvasOrientation,\n type CanvasPaneId,\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\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 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}\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 };\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 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 (options.isKnownKind && !options.isKnownKind(input.kind)) {\n onError({ code: \"unknown-kind\", message: `No canvas kind \"${input.kind}\" is registered.`, detail: input });\n return null;\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 null;\n }\n }\n const target = input.target ?? \"focused\";\n const splitShare = target === \"split-down\" ? rules.stackSplit : target === \"split-right\" ? rules.sideSplit : undefined;\n const resolved: CanvasOpenInput = input.windowId || windowId === CANVAS_MAIN_WINDOW ? input : { ...input, 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 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 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","/**\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 *\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 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 controller.close(itemId);\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 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 /** The canvas, acting for the window this pane is in. */\n readonly canvas: CanvasController;\n readonly windowId: CanvasWindowId;\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 /** Stays mounted while its tab is in the background (live chat, a running tool). */\n readonly keepAlive?: boolean;\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\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_MIN_SPLIT_FRACTION,\n canvasShortcutHint,\n clampDraggedCanvasWidth,\n fitCanvasWidth,\n selectCanvasIsFullscreen,\n selectCanvasIsOpen,\n selectCanvasLayout,\n selectCanvasWidth,\n selectCanvasWindowItemCount,\n shouldStackSplit,\n type CanvasLayoutNode,\n} from \"../index\";\nimport { CanvasPaneView } from \"./CanvasPane\";\nimport { PanelRightIcon } from \"./icons\";\nimport { useCanvas, useCanvasInternals, useCanvasState, useRegisterCanvasPresence } from \"./provider\";\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 } = 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 region = useRegionWidth();\n const [dragWidth, setDragWidth] = useState<number | null>(null);\n useRegisterCanvasPresence();\n\n if (!isOpen || !layout) return null;\n const fitted = fitCanvasWidth(width, region, controller.rules);\n const shown = dragWidth ?? fitted;\n\n return (\n <aside\n className={[\"mxc-column\", className].filter(Boolean).join(\" \")}\n data-fullscreen={isFullscreen ? \"\" : undefined}\n data-placement={placement}\n data-mxc-window={windowId}\n aria-label=\"Canvas\"\n style={{ ...style, [\"--mxc-width\" as string]: `${shown}px` }}\n >\n {placement === \"docked\" && !isFullscreen ? (\n <WidthHandle\n width={fitted}\n region={region}\n onDrag={(next) => {\n setDragWidth(next);\n onLiveWidth?.(next);\n }}\n />\n ) : null}\n <div className=\"mxc-layout\">\n <LayoutNodeView node={layout} />\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 } | null>(null);\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 = { x: event.clientX, width };\n document.documentElement.dataset.mxcResizing = \"\";\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 = null;\n delete document.documentElement.dataset.mxcResizing;\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 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 document.documentElement.dataset.mxcResizing = 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 delete document.documentElement.dataset.mxcResizing;\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 onClick={() => controller.toggle()}\n />\n {count > 0 && !isOpen ? <span className=\"mxc-toggle-badge\">{count}</span> : null}\n </span>\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 * One pane, drawn with THE canvas chrome (CanvasPanel): a header — the title\n * (one tab) or the tab strip, the kind's leading controls, the kind's own\n * button, \"…\", expand, close — over the active item's body. Tabs drag between\n * panes (and windows). An empty pane shows the launcher of every kind that\n * offers one. A native-body kind gets a placeholder whose frame is reported to\n * the host in the same frame the layout changed.\n */\n\nimport {\n Component,\n Suspense,\n lazy,\n useEffect,\n useLayoutEffect,\n useRef,\n type ComponentType,\n type DragEvent,\n type ErrorInfo,\n type ReactNode,\n} from \"react\";\nimport * as Menu from \"@radix-ui/react-dropdown-menu\";\nimport type { CanvasItem, CanvasItemId, CanvasPaneId, CanvasWindowId } from \"../index\";\nimport {\n CANVAS_MAIN_WINDOW,\n canvasShortcutHint,\n selectCanvasFocusedPaneId,\n selectCanvasIsFullscreen,\n selectCanvasPaneCount,\n} from \"../index\";\nimport { CanvasMenuTrigger, CanvasPanel, CanvasPanelEmpty, CanvasTab } from \"./chrome\";\nimport { AlertIcon, DockIcon, PopOutIcon, SplitDownIcon, SplitRightIcon } from \"./icons\";\nimport { toCanvasRect, type CanvasMenuEntry, type CanvasNativeRect } from \"./layer\";\nimport { useCanvas, useCanvasInternals, useCanvasKind, useCanvasKinds, useCanvasState } from \"./provider\";\nimport type { AnyCanvasKind, CanvasKindProps, CanvasMenuItem } from \"./registry\";\n\nconst DRAG_MIME = \"application/x-matrx-canvas-item\";\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 panes 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\nexport function itemTitle(item: CanvasItem, kind: AnyCanvasKind | undefined): string {\n if (item.title) return item.title;\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/** Drag handlers shared by a tab and a single-tab title: the dragged tab is announced so native views can step aside. */\nfunction 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(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\nexport function CanvasPaneView({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n const { windowId, layer, ports, tabStrip } = useCanvasInternals();\n const pane = useCanvasState((s) => s.panes[paneId]);\n const items = useCanvasState((s) => s.items);\n const isFullscreen = useCanvasState((s) => selectCanvasIsFullscreen(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 active = pane?.activeItemId ? items[pane.activeItemId] : undefined;\n const kind = useCanvasKind(active?.kind ?? \"\");\n const drop = useRef<(() => void) | null>(null);\n const sectionRef = useRef<HTMLElement>(null);\n\n useEffect(() => () => drop.current?.(), []);\n if (!pane) return null;\n\n const kindProps: CanvasKindProps | null =\n active && kind ? { item: active, data: active.data, paneId, isFocused: focused, canvas, windowId } : null;\n const Leading = kind?.HeaderLeading;\n const Action = kind?.HeaderAction;\n const Toolbar = kind?.Toolbar;\n const single = tabStrip === \"auto\" && pane.itemIds.length === 1 && active;\n\n const hideDrop = () => {\n drop.current?.();\n drop.current = null;\n };\n const onDragOver = (event: DragEvent) => {\n if (!event.dataTransfer.types.includes(DRAG_MIME)) return;\n event.preventDefault();\n event.dataTransfer.dropEffect = \"move\";\n if (!drop.current && sectionRef.current) {\n drop.current = layer.show({ type: \"drop-indicator\", rect: toCanvasRect(sectionRef.current.getBoundingClientRect()), paneId });\n }\n };\n const onDragLeave = (event: DragEvent) => {\n const next = event.relatedTarget as Node | null;\n if (next && sectionRef.current?.contains(next)) return;\n hideDrop();\n };\n const onDrop = (event: DragEvent) => {\n hideDrop();\n const itemId = event.dataTransfer.getData(DRAG_MIME) as CanvasItemId;\n if (!itemId) return;\n event.preventDefault();\n canvas.moveItem(itemId, paneId);\n };\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 single && active ? (\n <SingleTitle item={active} kind={kind} />\n ) : pane.itemIds.length > 0 ? (\n <div className=\"mxc-tabs\" role=\"tablist\" aria-label=\"Canvas tabs\">\n {pane.itemIds.map((itemId, index) => (\n <ItemTab key={itemId} itemId={itemId} paneId={paneId} index={index} active={itemId === pane.activeItemId} />\n ))}\n </div>\n ) : (\n <span className=\"mxc-panel-title\">New tab</span>\n )\n }\n leading={Leading && kindProps ? <Leading {...kindProps} /> : null}\n actions={Action && kindProps ? <Action {...kindProps} /> : null}\n renderMenu={() => <PaneMenu paneId={paneId} windowId={windowId} activeItem={active} kind={kind} kindProps={kindProps} tabCount={pane.itemIds.length} role={role} />}\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 onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\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 {pane.itemIds.length === 0 ? (\n <Launcher paneId={paneId} />\n ) : (\n pane.itemIds.map((itemId) => {\n const item = items[itemId];\n if (!item) return null;\n const isActive = itemId === pane.activeItemId;\n return <ItemBody key={itemId} item={item} paneId={paneId} windowId={windowId} isActive={isActive} isFocused={focused && isActive} hasNativePort={!!ports.onNativeBodyFrame} />;\n })\n )}\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\nfunction SingleTitle({ item, kind }: { item: CanvasItem; kind: AnyCanvasKind | undefined }) {\n const title = itemTitle(item, kind);\n const drag = useTabDrag(item.id, title);\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <span className=\"mxc-panel-title\" data-draggable=\"\" title={title} {...drag}>\n <Icon className=\"mxc-title-icon\" />\n <span className=\"mxc-tab-title\">{title}</span>\n </span>\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 = useCanvasKind(item?.kind ?? \"\");\n const ref = useRef<HTMLDivElement>(null);\n const title = item ? itemTitle(item, kind) : \"\";\n const drag = useTabDrag(itemId, title);\n useEffect(() => {\n if (active) ref.current?.scrollIntoView?.({ block: \"nearest\", inline: \"nearest\" });\n }, [active]);\n if (!item) return null;\n const Icon = kind?.icon ?? AlertIcon;\n return (\n <CanvasTab\n ref={ref}\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(DRAG_MIME)) event.preventDefault();\n }}\n onDrop={(event) => {\n const dragged = event.dataTransfer.getData(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}: {\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}) {\n const canvas = useCanvas();\n const { ports, layer } = useCanvasInternals();\n const moveId = tabCount > 1 ? activeItem?.id : undefined;\n const blocking = useRef<(() => void) | null>(null);\n useEffect(() => () => blocking.current?.(), []);\n\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 const sections: MenuAction[][] = [\n [...kindItems, ...hostItems].map((entry) => ({ ...entry, id: `item:${entry.id}` })),\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 ...(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 const showMenu = ports.showMenu;\n if (showMenu) {\n // The host draws the menu (above native views); the package keeps the handlers.\n const entries: CanvasMenuEntry[] = [];\n const handlers = new Map<string, () => void>();\n sections.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 return (\n <CanvasMenuTrigger\n onClick={(event) => {\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 {sections.map((section, i) => (\n <MenuSection key={i} first={i === 0} actions={section} />\n ))}\n </Menu.Content>\n </Menu.Portal>\n </Menu.Root>\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\nfunction ItemBody({\n item,\n paneId,\n windowId,\n isActive,\n isFocused,\n hasNativePort,\n}: {\n item: CanvasItem;\n paneId: CanvasPaneId;\n windowId: CanvasWindowId;\n isActive: boolean;\n isFocused: boolean;\n hasNativePort: boolean;\n}) {\n const canvas = useCanvas();\n const kind = useCanvasKind(item.kind);\n if (!isActive && !kind?.keepAlive) return null;\n const props: CanvasKindProps = { item, data: item.data, paneId, isFocused, canvas, windowId };\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 let body: ReactNode;\n if (!kind) {\n body = <ItemProblem message=\"This item can no longer be shown.\" onClose={() => canvas.close(item.id)} />;\n } else if (unavailable) {\n body = <CanvasPanelEmpty>{unavailable}</CanvasPanelEmpty>;\n } else if (kind.body === \"native\") {\n body = hasNativePort ? (\n <NativeBody itemId={item.id} windowId={windowId}>\n {kindComponent(kind) ? <Rendered kind={kind} item={item} props={props} /> : null}\n </NativeBody>\n ) : (\n <CanvasPanelEmpty>Opens in the desktop app</CanvasPanelEmpty>\n );\n } else {\n body = <Rendered kind={kind} item={item} props={props} />;\n }\n return (\n <div className=\"mxc-item\" hidden={!isActive} data-kind={item.kind}>\n {body}\n </div>\n );\n}\n\nfunction Rendered({ kind, item, props }: { kind: AnyCanvasKind; item: CanvasItem; props: CanvasKindProps }) {\n const canvas = useCanvas();\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 (layout effect — before paint, so the view moves in the same frame as\n * the CSS), on every resize of the element, on window resize, and whenever the\n * host asks (`useCanvasNativeBodies().remeasure()`); null once it is hidden or gone.\n */\nfunction NativeBody({ itemId, windowId, children }: { itemId: CanvasItemId; windowId: CanvasWindowId; 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 = 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\nfunction Launcher({ paneId }: { paneId: CanvasPaneId }) {\n const canvas = useCanvas();\n const kinds = useCanvasKinds().filter((kind) => kind.launcher);\n if (kinds.length === 0) return <CanvasPanelEmpty>Nothing open</CanvasPanelEmpty>;\n return (\n <div className=\"mxc-launcher\">\n {kinds.map((kind) => {\n const Icon = kind.icon;\n const launcher = kind.launcher;\n if (!launcher) return null;\n return (\n <button\n key={kind.id}\n type=\"button\"\n className=\"mxc-launcher-item\"\n onClick={() =>\n canvas.open({\n kind: kind.id,\n key: launcher.key,\n data: launcher.data,\n title: launcher.title ?? null,\n target: { paneId },\n })\n }\n >\n <Icon className=\"mxc-launcher-icon\" />\n <span>{launcher.title ?? kind.label}</span>\n </button>\n );\n })}\n </div>\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 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\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 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 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 className=\"mxc-tab-title\">{shown}</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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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KAAK,CAAC,SAAS,6CAAC,UAAK,WAAU,oBAAoB,iBAAM,IAAU;AAAA,KAC9E;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,8CAAC,SAAI,WAAW,CAAC,aAAa,SAAS,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,GAAG,oBAAkB,SAAS,KAAK,QAClG;AAAA,iDAAC,SAAI,WAAU,kBAAiB,QAAQ,UAAU,cAC/C,UACH;AAAA,IACA,6CAAC,gBAAa;AAAA,KAChB;AAEJ;","names":["import_react","frame","focused","isMac","frame","frame","import_jsx_runtime","isMac","import_react","import_react","import_react","import_jsx_runtime","import_jsx_runtime","CanvasHeaderButton","CanvasMenuTrigger","CanvasPanel","CanvasTab","import_jsx_runtime","import_jsx_runtime","useIsoLayoutEffect","isMac"]}
|