react-dockable-desktop 7.10.0 → 7.11.0-next.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 +118 -1
- package/README.md +8 -4
- package/dist/index.cjs +8 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +270 -2
- package/dist/index.d.ts +270 -2
- package/dist/index.js +8 -6
- package/dist/index.js.map +1 -1
- package/dist/styles.css +32 -0
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/index.tsx","../src/components/PanelRegistry.ts","../src/components/WindowManagerContext.tsx","../src/components/FormContainerContext.ts","../src/components/workspace/panelHost.ts","../src/components/domPreservation.ts","../src/utils/documentMirror.ts","../src/components/predefinedMessages.ts","../src/core/messages.ts","../src/components/serializable.ts","../src/components/sameUpdate.ts","../src/core/eventBus.ts","../src/core/layoutTree.ts","../src/core/serialize.ts","../src/core/workspaceCore.ts","../src/utils/useLatestRef.ts","../src/WorkspaceClient.ts","../src/components/WorkspaceInstanceContext.ts","../src/components/PanelProviderContext.tsx","../src/components/SidePanelRenderer.tsx","../src/forms/ConfirmationForm.tsx","../src/forms/dialogIcons.tsx","../src/utils/escapeStack.ts","../src/hooks/useContainerRect.ts","../src/forms/AlertForm.tsx","../src/components/ContextMenu.tsx","../src/utils/rtl.ts","../src/utils/menuKeyboard.ts","../src/components/DockableDesktopProvider.tsx","../src/components/ToolbarContext.tsx","../src/components/PanelContributionContext.tsx","../src/components/WindowManager.tsx","../src/utils/useIsClient.ts","../src/hooks/useColorScheme.ts","../src/components/workspace/panelMount.tsx","../src/components/workspace/DragGhost.tsx","../src/components/workspace/WorkspaceGrid.tsx","../src/components/dragResize.ts","../src/components/workspace/LeafGroup.tsx","../src/components/workspace/helpers.ts","../src/components/workspace/icons.tsx","../src/components/workspace/WorkspaceZones.tsx","../src/components/workspace/FloatingWindows.tsx","../src/components/workspace/Taskbar.tsx","../src/components/workspace/useDragTargets.ts","../src/components/workspace/tabDrag.ts","../src/components/workspace/workspaceMenus.ts","../src/components/workspace/useWorkspaceSize.ts","../src/components/workspace/floatingWindowDrag.ts","../src/components/ModalStackRenderer.tsx","../src/components/Sidebar.tsx","../src/components/Toolbar.tsx","../src/components/Toast.tsx","../src/components/panelOverlay/PanelOverlayRoot.tsx","../src/components/panelOverlay/context.ts","../src/core/stretch.ts","../src/components/panelOverlay/FloatingWidget.tsx","../src/components/anchorGeometry.ts","../src/core/panelOverlayGeometry.ts","../src/components/panelOverlay/PanelToolbar.tsx","../src/components/panelOverlay/ToolbarSearch.tsx","../src/components/panelOverlay/useFloatingWidgets.tsx"],"sourcesContent":["/**\n * The 7.0 public API layer: `createWorkspace()`, the hooks a panel or an app component uses, and\n * the two components that replace several 6.x ones (`RddSidePanels`, `RddContextMenu`).\n *\n * Everything here is built on the library's internal modules; `src/index.ts` exports it together\n * with the internal components under their 7.0 names.\n */\nimport React, { forwardRef, useContext, useEffect, useLayoutEffect, useMemo, useRef } from 'react';\nimport { WorkspaceClient, type PanelDefinition, type WorkspaceClientConfig } from '../WorkspaceClient';\nimport type { OpenPanelOptions } from '../types';\nimport { WorkspaceInstanceContext } from '../components/WorkspaceInstanceContext';\nimport { useOptionalWindowManagerState, usePredefinedMessages, type MessageDescriptor, type PanelInfo } from '../components/WindowManagerContext';\nimport { useFormContainer, type CloseOptions, type ContainerType, type FormContainerContract } from '../components/FormContainerContext';\nimport type { DirtyStateOptions } from '../components/dirtyOptions';\nimport { usePanelActions, usePanelState, type OverlayInstance, type OverlayId, type ModalOptions, type SidePanelOptions } from '../components/PanelProviderContext';\nexport type { OverlayInstance, OverlayId };\nimport SidePanelRenderer, { LeftPanelRenderer, RightPanelRenderer } from '../components/SidePanelRenderer';\nimport ConfirmationForm, { type RddConfirmProps } from '../forms/ConfirmationForm';\nimport AlertForm, { type RddAlertProps } from '../forms/AlertForm';\nimport { ContextMenu, ContextMenuProvider, type ContextMenuAdapter, type ContextMenuHandle, type ContextMenuProps } from '../components/ContextMenu';\n\n// ─── Workspace ──────────────────────────────────────────────────────────────────\n\n/** Configuration for `createWorkspace()`. */\nexport interface WorkspaceConfig extends Omit<WorkspaceClientConfig, 'predefinedMessages'> {\n /** Overrides any subset of the built-in message table. */\n messages?: Record<string, MessageDescriptor>;\n}\n\n/**\n * A workspace: the layout, every action on it, the panel registry and the event bus. It is live\n * from the moment it is created — calls made before any `<DockableDesktopProvider>` mounts apply\n * immediately.\n */\n// An interface rather than an alias, so the API reference lists the members under this name.\nexport interface Workspace<TEvents extends object = Record<string, unknown>> extends WorkspaceClient<TEvents> {}\n\n/** The type-only mark {@link definePanels} puts on a map. No such value exists at runtime. */\ndeclare const panelsBrand: unique symbol;\n\n/** A panel map marked by {@link definePanels}, so `createWorkspace` types `openPanel` from it (7.10.0). */\nexport type PanelMap<TPanels extends Record<string, PanelDefinition> = Record<string, PanelDefinition>> = TPanels & { readonly [panelsBrand]: true };\n\n/** The props `openPanel` passes to a registered panel: its component's props, without `panelId`. */\nexport type PanelPropsOf<TDefinition> = TDefinition extends { component: React.ComponentType<infer P> } ? Omit<P, 'panelId'> : never;\n\n/**\n * Marks a panel map for typing (7.10.0). Returns it unchanged; a workspace created from it gets a\n * typed `openPanel`: only registered names, and `props` checked against that panel's component.\n *\n * @example\n * ```ts\n * const panels = definePanels({ map: { component: MapPanel }, chart: { component: ChartPanel } });\n * const workspace = createWorkspace({ panels });\n * workspace.openPanel('c1', 'chart', { props: { series: 3 } }); // checked against ChartPanel's props\n * ```\n */\nexport function definePanels<const TPanels extends Record<string, PanelDefinition>>(panels: TPanels): PanelMap<TPanels> {\n return panels as PanelMap<TPanels>;\n}\n\n/**\n * A workspace created from {@link definePanels}: the same object, with `openPanel` typed from the\n * registry. Pass it anywhere a {@link Workspace} goes. `useWorkspace()` stays untyped; keep this\n * one for typed calls.\n */\nexport interface TypedWorkspace<TPanels extends Record<string, PanelDefinition>, TEvents extends object = Record<string, unknown>> extends Workspace<TEvents> {\n /** `openPanel`, typed: a registered name, and that panel's props. */\n openPanel<K extends keyof TPanels & string>(id: string, component: K, options?: OpenPanelOptions<PanelPropsOf<TPanels[K]>>): void;\n}\n\n/**\n * Creates a workspace from a map marked by {@link definePanels} (7.10.0): `openPanel` takes only\n * the registered names, with `props` checked against each panel's component. To name the events\n * as well, pass both type arguments: `createWorkspace<typeof panels, AppEvents>({ panels })`.\n */\nexport function createWorkspace<TPanels extends Record<string, PanelDefinition>, TEvents extends object = Record<string, unknown>>(config: WorkspaceConfig & { panels: PanelMap<TPanels> }): TypedWorkspace<TPanels, TEvents>;\n/**\n * Creates a workspace. Pass it to `<DockableDesktopProvider workspace={…}>`.\n *\n * @example\n * ```ts\n * interface AppEvents { 'layer:select': { layerId: string } }\n * export const workspace = createWorkspace<AppEvents>({\n * panels: { map: { component: MapPanel } },\n * initialState: localStorage.getItem('layout'),\n * });\n * ```\n */\nexport function createWorkspace<TEvents extends object = Record<string, unknown>>(config?: WorkspaceConfig): Workspace<TEvents>;\nexport function createWorkspace(config: WorkspaceConfig = {}): Workspace {\n const { messages, ...rest } = config;\n return new WorkspaceClient({ ...rest, predefinedMessages: messages });\n}\n\n/**\n * The workspace of the nearest `<DockableDesktopProvider>`. A stable object: it never changes, so\n * a component that only calls actions never re-renders because of it.\n */\nexport function useWorkspace<TEvents extends object = Record<string, unknown>>(): Workspace<TEvents> {\n const ws = useContext(WorkspaceInstanceContext);\n if (!ws) throw new Error('useWorkspace must be used within <DockableDesktopProvider>');\n return ws as Workspace<TEvents>;\n}\n\n// ─── Panel side ─────────────────────────────────────────────────────────────────\n\n/** The state of a workspace panel: where it is. */\nexport type PanelState = PanelInfo['state'];\n\n/**\n * What a panel component knows about, and can do to, its own container. See {@link usePanel}.\n *\n * **Identity.** `id` and the five functions (`close`, `minimize`, `setDirty`, `setTitle`,\n * `setIcon`) never change identity for the panel's lifetime. The handle object itself changes\n * when `containerType`, `isActive`, `isMinimized` or `isFloating` does. So don't list the handle\n * in a dependency array: depend on the function you call, or on the values you write.\n */\nexport interface PanelHandle {\n /** This panel's instance id. */\n id: string;\n /** Where it is rendered. Updates live (a docked panel that is floated re-renders as `'floating-window'`). */\n containerType: ContainerType;\n /** A workspace panel that is the globally active one. Always false in a modal or drawer. */\n isActive: boolean;\n /** A workspace panel that is minimized to the taskbar. */\n isMinimized: boolean;\n /** A workspace panel shown as a floating window. */\n isFloating: boolean;\n /** Asks the container to close, honouring close guards and the dirty flag. */\n close: (options?: CloseOptions) => void;\n /** Minimizes a workspace panel. No effect in a modal or drawer. */\n minimize: () => void;\n /** Marks the panel as having unsaved changes. */\n setDirty: (dirty: boolean, options?: DirtyStateOptions) => void;\n /** Changes the title shown on the tab, window or modal. */\n setTitle: (title: string | MessageDescriptor | (() => string)) => void;\n /**\n * Changes the icon on the panel's tab, floating title bar and taskbar button, or in a modal's or\n * drawer's header. In a workspace panel, `null` goes back to the registration's\n * `defaultOptions.icon`. The icon is not saved by `saveLayout()`.\n */\n setIcon: (icon: React.ReactNode) => void;\n}\n\n/**\n * The panel's own container: its id, where it is, and what it can do. Works in docked panels,\n * floating windows, modals and side drawers.\n *\n * The functions on the handle are stable; the handle object is not (see {@link PanelHandle}).\n * To keep the tab title in step with a document:\n *\n * ```tsx\n * const { setTitle, setDirty } = usePanel();\n * useEffect(() => { setTitle(doc.title); setDirty(doc.dirty); }, [setTitle, setDirty, doc.title, doc.dirty]);\n * ```\n */\nexport function usePanel(): PanelHandle {\n const c = useFormContainer();\n const id = c.instanceId;\n // Select primitives only: a selector returning the whole panel record would give a new handle\n // on every write to the panel (title, dirty, props), including the panel's own writes.\n const state = useOptionalWindowManagerState(s => s.panels[id]?.state, undefined);\n const isActive = useOptionalWindowManagerState(s => s.activePanelId === id, false);\n const containerType: ContainerType = state\n ? (state === 'floating' ? 'floating-window' : 'dockable-panel')\n : (c.containerType ?? 'standalone');\n // A modal's or drawer's container object changes when its title or dirty flag does, so the\n // mutators read it through a ref and never change identity themselves.\n const cRef = useRef(c);\n useLayoutEffect(() => { cRef.current = c; });\n const mutators = useMemo(() => ({\n close: (options?: CloseOptions) => cRef.current.requestClose(options),\n minimize: () => cRef.current.requestMinimize?.(),\n setDirty: (dirty: boolean, options?: DirtyStateOptions) => cRef.current.setDirty(dirty, options),\n setTitle: (title: string | MessageDescriptor | (() => string)) => cRef.current.setTitle(title as Parameters<FormContainerContract['setTitle']>[0]),\n setIcon: (icon: React.ReactNode) => cRef.current.setIcon?.(icon),\n // New functions when the panel changes, so an effect that depends on them re-runs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [id]);\n return useMemo<PanelHandle>(() => ({\n id,\n containerType,\n isActive: !!state && isActive,\n isMinimized: state === 'minimized',\n isFloating: state === 'floating',\n ...mutators,\n }), [mutators, id, containerType, state, isActive]);\n}\n\n/** Lifecycle callbacks for {@link usePanelEvents}. Each is called at the moment it describes. */\nexport interface PanelEvents {\n onActivate?: () => void;\n onDeactivate?: () => void;\n onMinimize?: () => void;\n onRestore?: () => void;\n onClose?: () => void;\n onResize?: (width: number, height: number) => void;\n onContainerTypeChange?: (type: ContainerType) => void;\n}\n\n/**\n * Subscribes to the panel's lifecycle. Call it at the top level of the panel component; it always\n * calls the latest callbacks passed in and cleans up on unmount — no dependency array.\n */\nexport function usePanelEvents(events: PanelEvents): void {\n const c = useFormContainer();\n const ref = useRef(events);\n useLayoutEffect(() => { ref.current = events; });\n useEffect(() => {\n const offs = [\n c.onActivate?.(() => ref.current.onActivate?.()),\n c.onDeactivate?.(() => ref.current.onDeactivate?.()),\n c.onMinimize?.(() => ref.current.onMinimize?.()),\n c.onRestore?.(() => ref.current.onRestore?.()),\n c.onClose?.(() => ref.current.onClose?.()),\n c.onResize?.((w, h) => ref.current.onResize?.(w, h)),\n c.onContainerTypeChange?.((t) => ref.current.onContainerTypeChange?.(t)),\n ];\n return () => { offs.forEach(off => off?.()); };\n }, [c]);\n}\n\n/**\n * Registers a close guard: resolve `false` to keep the panel open (ask the user, save first, …).\n * Pass `null` to register none. Always calls the latest guard passed in.\n */\nexport function useBeforeClose(guard: (() => boolean | Promise<boolean>) | null): void {\n const c = useFormContainer();\n const ref = useRef(guard);\n useLayoutEffect(() => { ref.current = guard; });\n // Registered once; a null guard allows the close, so switching it off needs no re-registration.\n useEffect(() => c.onCloseRequested(() => (ref.current ? ref.current() : true)), [c]);\n}\n\n/**\n * Reports the panel's restorable state, pulled fresh on every `saveLayout()` and saved as the\n * panel's props. Pass `null` to report none. Always calls the latest function passed in.\n */\nexport function useSaveState(getState: (() => unknown) | null): void {\n const c = useFormContainer();\n const ref = useRef(getState);\n useLayoutEffect(() => { ref.current = getState; });\n // Registered once; reporting undefined (a null function) means \"use the panel's static props\".\n useEffect(() => c.registerStateProvider?.(() => ref.current?.()), [c]);\n}\n\n// ─── Overlays: modals and side drawers ──────────────────────────────────────────\n\ntype OverlayUpdate = Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>;\n\n/** Returned by {@link useModals}. */\nexport interface ModalsApi {\n /** Open modals, bottom to top. */\n stack: OverlayInstance[];\n /** The top modal, or null. */\n topmost: OverlayInstance | null;\n open: <P extends object>(component: React.ComponentType<P>, props: P, options?: ModalOptions) => OverlayId;\n close: (id: OverlayId) => void;\n closeAll: () => void;\n get: (id: OverlayId) => OverlayInstance | undefined;\n update: (id: OverlayId, updates: OverlayUpdate) => void;\n setDirty: (id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => void;\n /**\n * Opens an {@link RddConfirm} and resolves `true` when it is confirmed, `false` when it is\n * cancelled or dismissed (Escape, the backdrop, the ×, or a close by code).\n */\n confirm: (options: ConfirmOptions) => Promise<boolean>;\n /** Opens an {@link RddAlert} and resolves once it is acknowledged or dismissed. */\n alert: (options: AlertOptions) => Promise<void>;\n}\n\n/** Options of {@link ModalsApi.confirm}. The title defaults to the `modalTitle` message. */\nexport interface ConfirmOptions {\n message: RddConfirmProps['message'];\n title?: ModalOptions['title'];\n alert?: string;\n alertType?: RddConfirmProps['alertType'];\n icon?: React.ReactNode | null;\n /** Labels the buttons Yes and No instead of OK and Cancel. */\n yesNo?: boolean;\n /** Defaults to `'small'`. */\n size?: ModalOptions['size'];\n}\n\n/** Options of {@link ModalsApi.alert}. The title defaults to the `alertTitle` message. */\nexport interface AlertOptions {\n message: RddAlertProps['message'];\n title?: ModalOptions['title'];\n alertType?: RddAlertProps['alertType'];\n icon?: React.ReactNode | null;\n okLabel?: RddAlertProps['okLabel'];\n /** Defaults to `'small'`. */\n size?: ModalOptions['size'];\n}\n\n/** Returned by {@link useSidePanels}. */\nexport interface SidePanelsApi {\n left: OverlayInstance | null;\n right: OverlayInstance | null;\n openLeft: <P extends object>(component: React.ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n openRight: <P extends object>(component: React.ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n close: (id: OverlayId) => void;\n /** Closes both drawers. */\n closeAll: () => void;\n get: (id: OverlayId) => OverlayInstance | undefined;\n update: (id: OverlayId, updates: OverlayUpdate) => void;\n setDirty: (id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => void;\n}\n\n/** Opens and tracks modals. */\nexport function useModals(): ModalsApi {\n const { modals } = usePanelState();\n const a = usePanelActions();\n const messages = usePredefinedMessages();\n return useMemo<ModalsApi>(() => ({\n stack: modals,\n topmost: modals[modals.length - 1] ?? null,\n open: a.openModal,\n close: a.close,\n closeAll: a.closeAllModals,\n get: a.getInstance,\n update: a.updateInstance,\n setDirty: a.setDirty,\n confirm: ({ message, title, alert, alertType, icon, yesNo, size = 'small' }) => new Promise<boolean>(resolve => {\n a.openModal(ConfirmationForm, { message, alert, alertType, icon, useYesNoTitles: yesNo, onSettled: resolve },\n { title: title ?? messages.modalTitle, size });\n }),\n alert: ({ message, title, alertType, icon, okLabel, size = 'small' }) => new Promise<void>(resolve => {\n a.openModal(AlertForm, { message, alertType, icon, okLabel, onSettled: resolve },\n { title: title ?? messages.alertTitle, size });\n }),\n }), [modals, a, messages]);\n}\n\n/** Opens and tracks the left and right side drawers. */\nexport function useSidePanels(): SidePanelsApi {\n const { leftPanel, rightPanel } = usePanelState();\n const a = usePanelActions();\n return useMemo<SidePanelsApi>(() => ({\n left: leftPanel,\n right: rightPanel,\n openLeft: a.openLeftPanel,\n openRight: a.openRightPanel,\n close: a.close,\n closeAll: () => {\n if (leftPanel) a.close(leftPanel.id);\n if (rightPanel) a.close(rightPanel.id);\n },\n get: a.getInstance,\n update: a.updateInstance,\n setDirty: a.setDirty,\n }), [leftPanel, rightPanel, a]);\n}\n\n// ─── Components ─────────────────────────────────────────────────────────────────\n\n/** Props for {@link RddSidePanels}. */\nexport interface RddSidePanelsProps {\n /** Render only one side's drawer. Omit to render both. */\n side?: 'left' | 'right';\n /** Width used when an `openLeft`/`openRight` call doesn't give one. Number = px. @default 400 */\n defaultWidth?: number | string;\n}\n\n/** Renders the side drawers opened through {@link useSidePanels}. */\nexport function RddSidePanels({ side, defaultWidth }: RddSidePanelsProps): React.ReactElement {\n if (side === 'left') return <LeftPanelRenderer defaultWidth={defaultWidth} />;\n if (side === 'right') return <RightPanelRenderer defaultWidth={defaultWidth} />;\n return <SidePanelRenderer defaultWidth={defaultWidth} />;\n}\n\n/** Props for {@link RddContextMenu}. */\nexport type RddContextMenuProps = ContextMenuProps & {\n /** With children: the context-menu implementation for them. @default the built-in menu */\n adapter?: ContextMenuAdapter;\n /**\n * With children, `RddContextMenu` provides a context menu to them (`useContextMenu()` inside\n * shows it) — for a surface outside `<DockableDesktopProvider>`, or to override the menu for a\n * subtree. Without children, it is a single menu you drive through its `ref`.\n */\n children?: React.ReactNode;\n};\n\n/**\n * A context menu. Inside `<DockableDesktopProvider>` one is already provided — use\n * `useContextMenu()` or `showContextMenu()` and you need no `RddContextMenu` at all.\n */\nexport const RddContextMenu: React.ForwardRefExoticComponent<RddContextMenuProps & React.RefAttributes<ContextMenuHandle>> = forwardRef<ContextMenuHandle, RddContextMenuProps>(function RddContextMenu(\n { children, adapter, ...menuProps },\n ref,\n) {\n if (children !== undefined) {\n return <ContextMenuProvider adapter={adapter} {...menuProps}>{children}</ContextMenuProvider>;\n }\n return <ContextMenu ref={ref} {...menuProps} />;\n});\n","import type { ComponentType } from 'react';\nimport type { FloatAnchor } from '../types';\n\n/**\n * Represents a registered component configuration template inside the panel catalog registry.\n */\nexport interface PanelRegistryEntry {\n /** The React component type registered. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: a registry holds components with different props; unknown would reject them\n Component: ComponentType<any>;\n /** Default metadata settings configuration applied on instantiation. */\n defaultOptions?: {\n /** Tab and window headers text — plain string or i18n descriptor. */\n title?: string | { id: string; defaultMessage?: string; values?: Record<string, string | number> } | (() => string);\n /** Icon placed next to title tags. */\n icon?: React.ReactNode;\n /** Initial mounting state inside the desktop layout grid. */\n initialTarget?: 'floating' | 'docked' | 'tabbed';\n /** Custom default bounds applied when the container is floated. */\n favoritePosition?: { x: number | string; y: number | string; width: number | string; height: number | string };\n /** Enables/disables window drag interactions. */\n canDrag?: boolean;\n /**\n * `false`: the user can't make this panel floating. A tab drag can't end in a floating window\n * (dropped on nothing or on a corner, it stays where it was), and the \"Float\" and taskbar\n * \"Maximize\" menu items are hidden. A window the app floated itself can still be moved. The\n * app's own `floatPanel` always works. @default true (7.9.0)\n */\n canFloat?: boolean;\n /**\n * `false`: the user can't dock this panel. Dragging it offers no group, tab or edge targets\n * (corners still anchor a floating window), so it stays floating. The app's own docking calls\n * always work; give the type `initialTarget: 'floating'` so it opens floating. @default true (7.9.0)\n */\n canDock?: boolean;\n /** Enables/disables minimizing of the panel instance. */\n canMinimize?: boolean;\n /** Enables/disables closing actions for the tab/window. */\n canClose?: boolean;\n /** Corner of the workspace to anchor newly-opened floating windows to. */\n defaultAnchor?: FloatAnchor;\n /** Disables live WebGL rendering canvas thumbnails inside the taskbar hover popup previews. */\n disableLivePreview?: boolean;\n /** Custom header actions renderer, placing custom components in the window/tab titlebar. */\n renderHeaderActions?: (panelId: string) => React.ReactNode;\n /**\n * Class added to each panel of this type, on its own content element (`.rdd-panel-content`),\n * which moves with the panel between groups, windows and the taskbar preview. (7.8.0)\n */\n className?: string;\n /** Class added to the tab of each panel of this type. (7.8.0) */\n tabClassName?: string;\n /**\n * `false` unmounts the panel's component while it is hidden (an unselected tab, or minimized)\n * and mounts it afresh when it is shown, to free what a heavy, rarely shown panel holds. Its\n * own state is lost each time; its tab, title and lifecycle continue (`onClose` is not called),\n * and the taskbar shows a placeholder instead of a live preview. While it is unmounted, a\n * guard it registered with `useBeforeClose` is not active (its dirty flag still is), and\n * `saveLayout()` saves its open-time props. @default true: panels stay mounted and keep their\n * state, as they always have. (7.8.0)\n */\n keepAlive?: boolean;\n };\n}\n\n/**\n * Registry mapping catalog entries to allow programmatic panel instantiation\n * inside dynamic layout cells or floating windows.\n * Exported so `createWorkspace()` can create scoped, per-instance registries.\n */\nexport class PanelRegistry {\n private registry = new Map<string, PanelRegistryEntry>();\n\n /**\n * Register a new component to the panel catalog registry.\n * @param id - Unique string identifier.\n * @param Component - React component instance template.\n * @param defaultOptions - Custom default settings configuration.\n */\n register<P extends object>(\n id: string,\n Component: ComponentType<P>,\n defaultOptions?: PanelRegistryEntry['defaultOptions']\n ): void {\n this.registry.set(id, {\n Component: Component as PanelRegistryEntry['Component'],\n defaultOptions\n });\n }\n\n /**\n * Retrieve a registered panel configuration by identifier.\n */\n get(id: string): PanelRegistryEntry | undefined {\n return this.registry.get(id);\n }\n\n /**\n * Returns a list of all registered panel entry identifiers.\n */\n getRegisteredIds(): string[] {\n return Array.from(this.registry.keys());\n }\n}\n\n/** Global singleton instance of the Panel Registry. */\nexport const globalPanelRegistry: PanelRegistry = new PanelRegistry();\n","import React, { createContext, useContext, useState, useMemo, useEffect, useSyncExternalStore } from 'react';\nimport { useFormContainer } from './FormContainerContext';\nimport { globalPanelRegistry } from './PanelRegistry';\nimport { createPanelHost, PanelHostContext, type PanelHost } from './workspace/panelHost';\nimport { claimDocumentMirror, releaseDocumentMirror } from '../utils/documentMirror';\nimport type { PanelRegistry } from './PanelRegistry';\nimport { defaultPredefinedMessages } from './predefinedMessages';\nimport type { MessageKey } from './predefinedMessages';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport type { ContextMenuItem } from './ContextMenu';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, WorkspaceActions, InternalWindowActions, HostClasses, WindowManagerProviderProps, WorkspaceCore } from '../types';\nimport { defaultFormatMessage } from '../core/messages';\nimport { createWorkspaceCore } from '../core/workspaceCore';\nimport { useLatestRef } from '../utils/useLatestRef';\nexport type { MessageKey } from './predefinedMessages';\nexport { defaultPredefinedMessages } from './predefinedMessages';\nexport type { DirtyStateOptions };\n\n// Moved in 7.6.1; re-exported so every existing import of this module keeps working.\nexport type { MessageDescriptor, MessageFormatter, SplitOrientation, SplitDirection, DropPosition, DropTarget, PanelDrop, PanelDropTarget, TabContentProps, LayoutGridNode, LayoutLeafNode, LayoutNode, FloatAnchor, FloatingWindow, PanelInfo, OpenPanelOptions, WorkspaceState, WorkspaceActions, InternalWindowActions, HostClasses, SerializedLayout, WindowManagerProviderProps, WorkspaceCoreConfig, WorkspaceCore } from '../types';\nexport { defaultFormatMessage, formatLabel } from '../core/messages';\nexport { createWorkspaceCore } from '../core/workspaceCore';\n\nconst WindowActionsContext = createContext<InternalWindowActions | null>(null);\nconst WindowI18nContext = createContext<MessageFormatter | null>(null);\n\ninterface WindowStoreSyncContextValue {\n getSnapshot: () => WorkspaceState;\n subscribeToState: (callback: () => void) => () => void;\n}\n/** @internal Snapshot + subscribe for selector hooks (`useWorkspaceState(selector)`, `usePanel`). */\nexport const WindowStoreSyncContext: React.Context<WindowStoreSyncContextValue | null> = createContext<WindowStoreSyncContextValue | null>(null);\n\nconst WindowPredefinedMessagesContext = createContext<Record<MessageKey, MessageDescriptor>>(defaultPredefinedMessages);\n\n\nconst StyleClassContext = createContext<HostClasses>({});\n\n/** Custom hook to read configured style class contexts. */\nexport const useStyleClasses = (): HostClasses => useContext(StyleClassContext);\n\nconst RegistryContext = createContext<PanelRegistry>(globalPanelRegistry);\n\n/**\n * React hook to read the scoped {@link PanelRegistry} for the current provider.\n * When the provider was given a workspace from `createWorkspace()`, this returns that workspace's\n * private registry. Otherwise it returns the global `globalPanelRegistry` singleton.\n *\n * @group Hooks\n * @returns The panel registry instance in scope.\n * @example\n * ```tsx\n * function MyComponent() {\n * const registry = useRegistry();\n * const entry = registry.get('map');\n * return entry ? <entry.Component panelId=\"preview\" /> : null;\n * }\n * ```\n */\nexport const useRegistry = (): PanelRegistry => useContext(RegistryContext);\n\n\nexport const WindowManagerProvider: React.FC<WindowManagerProviderProps> = ({\n children,\n client,\n formatMessage,\n predefinedMessages,\n dir: dirProp,\n modalClass,\n modalBodyClass,\n sidePanelClass,\n sidePanelBodyClass,\n windowClass,\n windowBodyClass,\n zIndexBase: zIndexBaseProp\n}) => {\n // The workspace store: the client's own, or one owned by this provider (then panels come from\n // the global globalPanelRegistry, as before). The store is live before this mounts; nothing connects.\n const [core] = useState<WorkspaceCore>(() => {\n const c = client\n ? client._core\n : createWorkspaceCore({ registry: globalPanelRegistry, dir: dirProp, zIndexBase: zIndexBaseProp });\n c.applyProviderDefaults({ dir: dirProp, zIndexBase: zIndexBaseProp });\n return c;\n });\n const registry = client?.registry ?? globalPanelRegistry;\n // This workspace's own panel DOM, sizes and lifecycle handlers — never shared with another provider.\n const [panelHost] = useState<PanelHost>(createPanelHost);\n const actions = core.actions;\n\n // Effective config: client config takes precedence over individual provider props\n const effectiveFormatMessage = client?.config.formatMessage ?? formatMessage;\n const effectivePredefinedMessages = client?.config.predefinedMessages ?? predefinedMessages;\n const effectiveDir = client?.config.dir ?? dirProp;\n const effectiveZIndexBase = client?.config.zIndexBase ?? zIndexBaseProp ?? 1000;\n\n const mergedMessages = useMemo(() => ({\n ...defaultPredefinedMessages,\n ...effectivePredefinedMessages\n }), [effectivePredefinedMessages]);\n\n // Mirror the z-index base onto document.documentElement as a CSS variable so the\n // library's portaled chrome (ContextMenu, Toast, Toolbar's flyout, ModalStackRenderer),\n // which renders outside this provider's own DOM subtree, shifts in lockstep with\n // the floating windows' z counter.\n // Through the document mirror, keyed by this workspace's panel host (as RddDesktop's skin is), so\n // two workspaces on one page don't strip each other's base on unmount.\n useEffect(() => {\n claimDocumentMirror(panelHost, { zBase: effectiveZIndexBase });\n }, [panelHost, effectiveZIndexBase]);\n useEffect(() => () => releaseDocumentMirror(panelHost, ['zBase']), [panelHost]);\n\n useEffect(() => {\n if (effectiveDir) actions.setDirection(effectiveDir);\n }, [effectiveDir, actions]);\n\n\n const styleClasses = useMemo(() => ({\n modalClass,\n modalBodyClass,\n sidePanelClass,\n sidePanelBodyClass,\n windowClass,\n windowBodyClass\n }), [modalClass, modalBodyClass, sidePanelClass, sidePanelBodyClass, windowClass, windowBodyClass]);\n\n useEffect(() => {\n if (process.env.NODE_ENV !== 'development') return;\n\n // Check 1: styles.css sentinel — catches the \"forgot to import\" case precisely\n try {\n const sentinel = getComputedStyle(document.documentElement)\n .getPropertyValue('--rdd-styles-loaded').trim();\n if (sentinel !== '1') {\n console.error(\n \"[react-dockable-desktop] styles.css is not imported.\\n\" +\n \"Add this to your entry file (main.tsx / index.tsx):\\n\" +\n \" import 'react-dockable-desktop/styles.css'\\n\" +\n \"Without it the workspace renders as a black screen with no console errors.\"\n );\n }\n } catch { /* getComputedStyle unavailable (SSR) */ }\n\n }, []);\n\n const syncContextValue = useMemo<WindowStoreSyncContextValue>(\n () => ({ getSnapshot: core.getSnapshot, subscribeToState: core.subscribeToState }),\n [core]\n );\n\n return (\n <StyleClassContext.Provider value={styleClasses}>\n <RegistryContext.Provider value={registry}>\n <WindowStoreSyncContext.Provider value={syncContextValue}>\n <WindowActionsContext.Provider value={actions}>\n <WindowI18nContext.Provider value={effectiveFormatMessage || defaultFormatMessage}>\n <WindowPredefinedMessagesContext.Provider value={mergedMessages}>\n <PanelHostContext.Provider value={panelHost}>\n {children}\n </PanelHostContext.Provider>\n </WindowPredefinedMessagesContext.Provider>\n </WindowI18nContext.Provider>\n </WindowActionsContext.Provider>\n </WindowStoreSyncContext.Provider>\n </RegistryContext.Provider>\n </StyleClassContext.Provider>\n );\n};\n\nconst noopSubscribe = (_cb: () => void): (() => void) => () => {};\nconst outsideProvider = (): never => { throw new Error('useWorkspaceState must be used within <DockableDesktopProvider>'); };\n\n/**\n * The live workspace state. The component re-renders whenever it changes — or, given a selector,\n * only when the selected value changes.\n *\n * For reads without a subscription, call the workspace's `isOpen()` or `getOpenPanelIds()`.\n *\n * The selector must return a value that stays the same while the state does — a primitive, or a\n * part of the state as it is (`s => s.panels[id]`). A selector that builds a new object or array\n * on each call (`s => ({ n: s.floating.length })`, `s => s.floating.map(...)`) is a new value\n * every time React asks, and React stops with \"Maximum update depth exceeded\". Select the parts\n * separately, or\n * derive the object with `useMemo` from what you selected.\n *\n * @returns The current workspace state, or the selector's result.\n * @throws Error if used outside `<DockableDesktopProvider>`.\n * @example\n * ```tsx\n * function PanelCount() {\n * const count = useWorkspaceState(s => Object.keys(s.panels).length);\n * return <span>{count} open</span>;\n * }\n * ```\n */\nexport function useWindowManagerState(): WorkspaceState;\nexport function useWindowManagerState<T>(selector: (state: WorkspaceState) => T): T;\nexport function useWindowManagerState<T>(selector?: (state: WorkspaceState) => T): WorkspaceState | T {\n // Straight from the store, with the selector inside the subscription: until 7.7.2 this also read\n // a context holding the whole state, so it re-rendered on every change whatever the selector\n // returned.\n const syncCtx = useContext(WindowStoreSyncContext);\n const read = (): WorkspaceState | T => {\n const snap = syncCtx!.getSnapshot();\n return selector ? selector(snap) : snap;\n };\n return useSyncExternalStore(syncCtx?.subscribeToState ?? noopSubscribe, syncCtx ? read : outsideProvider, syncCtx ? read : outsideProvider);\n}\n\n/**\n * @internal `useWorkspaceState(selector)` for components that may also render outside a provider\n * (sidebar, toasts, panel overlays, a panel used standalone): `fallback` there instead of throwing.\n */\nexport function useOptionalWindowManagerState<T>(selector: (state: WorkspaceState) => T, fallback: T): T {\n const syncCtx = useContext(WindowStoreSyncContext);\n const read = (): T => (syncCtx ? selector(syncCtx.getSnapshot()) : fallback);\n return useSyncExternalStore(syncCtx?.subscribeToState ?? noopSubscribe, read, read);\n}\n\n/**\n * React hook to retrieve all layout mutation actions.\n * Returns the public {@link WorkspaceActions} interface.\n *\n * @group Hooks\n * @returns The full set of workspace mutation methods.\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n * @example\n * ```tsx\n * function Toolbar() {\n * const actions = useWindowManagerActions();\n * return (\n * <button onClick={() => actions.openPanel('map-1', 'map')}>Open Map</button>\n * );\n * }\n * ```\n */\nexport const useWindowManagerActions = (): WorkspaceActions => {\n const ctx = useContext(WindowActionsContext);\n if (!ctx) throw new Error('useWorkspace must be used within <DockableDesktopProvider>');\n return ctx;\n};\n\n/**\n * @internal — used by WindowManager.tsx rendering components only.\n * Returns the full {@link InternalWindowActions} including `setActivePanel`.\n */\nexport const useWindowManagerActionsInternal = (): InternalWindowActions => {\n const ctx = useContext(WindowActionsContext);\n if (!ctx) throw new Error('react-dockable-desktop components must be used within <DockableDesktopProvider>');\n return ctx;\n};\n\n\n/**\n * React hook to retrieve the active i18n formatter.\n */\nexport const useFormatMessage = (): MessageFormatter => {\n const formatter = useContext(WindowI18nContext);\n return formatter || defaultFormatMessage;\n};\n\n\n/**\n * React hook providing pub-sub helper methods for inter-panel event messaging.\n */\nexport const usePanelContext = (): Pick<WorkspaceActions, 'publish' | 'subscribe'> => {\n const { publish, subscribe } = useWindowManagerActions();\n return { publish, subscribe };\n};\n\n/**\n * React hook to fetch the localizable predefined message map catalog.\n */\nexport const usePredefinedMessages = (): Record<MessageKey, MessageDescriptor> => {\n return useContext(WindowPredefinedMessagesContext);\n};\n\n/**\n * React hook to retrieve the panel instance ID for the component currently rendered inside\n * the dockable desktop. Works for docked, floating, modal, and side-panel containers.\n * Opt-in — components that don't need the ID require no changes.\n *\n * @group Hooks\n * @returns The unique panel instance ID string.\n * @example\n * ```tsx\n * function MyPanel() {\n * const panelId = usePanelId();\n * const { closePanel } = useWindowManagerActions();\n * return <button onClick={() => closePanel(panelId)}>Close</button>;\n * }\n * ```\n */\nexport const usePanelId = (): string => useFormContainer().instanceId;\n\n/**\n * React hook for injecting custom context menu items into a panel's context menu from inside the panel component.\n * Items are dynamic — the array is re-read each time the menu opens, so state-driven changes (enable/disable, add/remove) work automatically.\n * The hook knows which panel it is in — no id needed.\n *\n * @param items - Array of `ContextMenuItem` entries (simple items, separators, submenus).\n * @example\n * ```tsx\n * import { usePanelContextMenu } from 'dockable-windows';\n *\n * function MyPanel() {\n * const [dirty, setDirty] = useState(false);\n * usePanelContextMenu([\n * { label: 'Save', action: () => save() },\n * { label: 'Revert', action: () => revert() },\n * ]);\n * return <Editor onChange={() => setDirty(true)} />;\n * }\n * ```\n */\nexport function usePanelContextMenu(items: ContextMenuItem[]): void {\n const ctx = useContext(WindowActionsContext);\n const panelId = usePanelId();\n const register = ctx?.registerPanelContextMenu;\n const itemsRef = useLatestRef(items);\n\n useEffect(() => {\n if (!register || !panelId) return;\n return register(panelId, () => itemsRef.current);\n }, [panelId, register, itemsRef]);\n}\n","import { createContext, useContext, useSyncExternalStore, type Context, type Provider } from 'react';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport type { MessageDescriptor } from '../types';\n\n/**\n * Options used when requesting to close a container.\n */\nexport interface CloseOptions {\n /** If true, bypasses any dirty state warnings or custom close guards. */\n force?: boolean;\n}\n\n/** Represents the type of container context a panel/form is currently rendered inside. */\nexport type ContainerType =\n | 'left-panel'\n | 'right-panel'\n | 'modal'\n | 'dockable-panel' // panel currently docked in the grid\n | 'floating-window' // panel currently in a detached floating window\n | 'standalone';\n\n/**\n * Contract interface exposed by a container (like a tab, window, modal, or side-panel)\n * to its children forms, enabling them to control or listen to container events.\n */\nexport interface FormContainerContract {\n /** Request the container to close itself. Bypassed by default unless options.force is true. */\n requestClose: (options?: CloseOptions) => void;\n /** Mark the form's content as dirty (having unsaved changes), triggering alert dialogs on close. */\n setDirty: (dirty: boolean, options?: DirtyStateOptions) => void;\n /** Register a custom close guard handler. Returning false or a promise resolving to false blocks closing. */\n onCloseRequested: (handler: () => boolean | Promise<boolean>) => (() => void);\n /**\n * Registers a callback reporting this panel's *current* restorable state, pulled fresh by\n * `workspace.saveLayout()` every time it's called — for panels whose static open-time\n * props can't capture state accumulated after opening (scroll position, an in-progress edit, a\n * view-mode toggle). Only meaningful for docked/floating panels — left/right side panels and\n * modals already have a complete answer to this via `openLeftPanel`/`openRightPanel`/\n * `openModal`'s own `props` argument plus `updateInstance`, so this is `undefined` there.\n * The returned value must be synchronous — `saveLayout()` itself never returns a `Promise`.\n * Return `undefined` to fall back to the static `props` this panel was opened with.\n */\n registerStateProvider?: (getState: () => unknown) => (() => void);\n /** Change the display title of the containing tab or window dynamically. */\n setTitle: (title: string | MessageDescriptor | (() => string)) => void;\n /** Change the tab or window icon dynamically. */\n setIcon?: (icon: React.ReactNode) => void;\n /** The type of container the panel is mounted in. Reflects the state at mount time; subscribe to {@link onContainerTypeChange} for live updates. */\n containerType?: ContainerType;\n /** Unique identifier of the panel or window instance. */\n instanceId: string;\n /** Subscribe to the container's close event. Returns an unsubscribe function. */\n onClose?: (handler: () => void) => () => void;\n /** Subscribe to the container's minimize event. Returns an unsubscribe function. */\n onMinimize?: (handler: () => void) => () => void;\n /** Subscribe to the container's restore event. Returns an unsubscribe function. */\n onRestore?: (handler: () => void) => () => void;\n /** Subscribe to the container's window resize event, returning width and height. Returns an unsubscribe function. */\n onResize?: (handler: (width: number, height: number) => void) => () => void;\n /** Request the container to minimize itself to the taskbar. No-op if the container type does not support minimize. */\n requestMinimize?: () => void;\n /** Returns the current rendered dimensions of this panel, or `null` if the panel has not been laid out yet. */\n getDimensions?: () => { width: number; height: number } | null;\n /**\n * Subscribe to this panel becoming the globally active panel.\n * Fires when `activePanelId` transitions to this panel's id.\n * Returns an unsubscribe function.\n */\n onActivate?: (handler: () => void) => () => void;\n /**\n * Subscribe to this panel losing active status.\n * Fires when `activePanelId` transitions away from this panel's id,\n * and also fires if the panel is destroyed while it is active.\n * Returns an unsubscribe function.\n */\n onDeactivate?: (handler: () => void) => () => void;\n /**\n * Subscribe to changes in the panel's container type (e.g. docked ↔ floating).\n * Does not fire for minimize/restore cycles — use {@link onMinimize} / {@link onRestore} for those.\n * Returns an unsubscribe function.\n */\n onContainerTypeChange?: (handler: (type: ContainerType) => void) => () => void;\n}\n\nconst defaultContract: FormContainerContract = {\n requestClose: () => {\n console.warn('FormContainerContract: requestClose called but no container is present');\n },\n setDirty: () => {},\n onCloseRequested: () => () => {},\n registerStateProvider: () => () => {},\n setTitle: () => {},\n setIcon: () => {},\n containerType: 'standalone',\n instanceId: 'standalone',\n onClose: () => () => {},\n onMinimize: () => () => {},\n onRestore: () => () => {},\n onResize: () => () => {},\n requestMinimize: () => {},\n getDimensions: () => null,\n onActivate: () => () => {},\n onDeactivate: () => () => {},\n onContainerTypeChange: () => () => {},\n};\n\n/**\n * Context that supplies the {@link FormContainerContract} to panels inside the Window Manager.\n */\nexport const FormContainerContext: Context<FormContainerContract> = createContext<FormContainerContract>(defaultContract);\nexport const FormContainerProvider: Provider<FormContainerContract> = FormContainerContext.Provider;\n\n/**\n * React hook to retrieve the current {@link FormContainerContract} from context.\n * Enables sub-forms to trigger close/minimize requests, mark themselves dirty,\n * rename their tabs, query dimensions, or subscribe to lifecycle events\n * (resize, close, minimize, restore, activate, deactivate, container-type changes).\n */\nexport const useFormContainer = (): FormContainerContract => {\n return useContext(FormContainerContext);\n};\n\n/**\n * Reactive alternative to measuring the panel's container yourself.\n * Returns the panel's current `{ width, height }`, or `null` before it has been laid\n * out, and re-renders whenever the panel's rendered box changes — including resizes\n * caused by the workspace itself (a grid split being dragged, docking, floating, or\n * tab activation), not just resizes of an element the panel created.\n */\nexport const usePanelSize = (): { width: number; height: number } | null => {\n const { onResize, getDimensions } = useFormContainer();\n return useSyncExternalStore(\n (onStoreChange) => (onResize ? onResize(() => onStoreChange()) : () => {}),\n () => (getDimensions ? getDimensions() : null)\n );\n};\n","/**\n * @file panelHost.ts\n * @description Where one workspace keeps its panels' DOM, sizes and lifecycle handlers.\n *\n * One host per provider, never module-level. These used to be three module-level maps keyed by\n * panel id alone, so every workspace on the page shared them: each workspace's cleanup deleted the\n * other workspaces' cached elements (their panels remounted blank), and two workspaces with the same\n * panel id rendered into one element and fired each other's lifecycle handlers. vdd's `PanelDomCache`\n * and ndd's `PanelHost` are per desktop for the same reason.\n */\nimport { createContext, useContext, type Context } from 'react';\nimport { trackPanelDom } from '../domPreservation';\nimport type { ContainerType } from '../FormContainerContext';\n\nexport interface PanelLifecycleRegistry {\n onClose: Set<() => void>;\n onMinimize: Set<() => void>;\n onRestore: Set<() => void>;\n onResize: Set<(w: number, h: number) => void>;\n onActivate: Set<() => void>;\n onDeactivate: Set<() => void>;\n onContainerTypeChange: Set<(type: ContainerType) => void>;\n}\n\nexport interface PanelHost {\n /** The panel's preserved element: created on first use, then moved between slots, never remounted. */\n getOrCreateElement(id: string): HTMLDivElement;\n /** The panel's element if it has one. */\n getElement(id: string): HTMLDivElement | undefined;\n /** Ids of the panels this host holds an element for. */\n ids(): string[];\n /** Drops a closed panel's element (and with it, its recorded scroll and focus). */\n forget(id: string): void;\n /** The panel's last on-screen size, or undefined before it was first laid out. */\n getDimensions(id: string): { width: number; height: number } | undefined;\n setDimensions(id: string, size: { width: number; height: number }): void;\n getLifecycle(id: string): PanelLifecycleRegistry | undefined;\n getOrCreateLifecycle(id: string): PanelLifecycleRegistry;\n deleteLifecycle(id: string): void;\n}\n\nexport function createPanelHost(): PanelHost {\n const elements = new Map<string, HTMLDivElement>();\n const dimensions = new Map<string, { width: number; height: number }>();\n const lifecycle = new Map<string, PanelLifecycleRegistry>();\n\n return {\n getOrCreateElement(id) {\n let el = elements.get(id);\n if (!el) {\n el = document.createElement('div');\n el.className = 'rdd-panel-dom';\n elements.set(id, el);\n trackPanelDom(el);\n }\n return el;\n },\n getElement: (id) => elements.get(id),\n ids: () => Array.from(elements.keys()),\n forget: (id) => { elements.delete(id); },\n getDimensions: (id) => dimensions.get(id),\n setDimensions: (id, size) => { dimensions.set(id, size); },\n getLifecycle: (id) => lifecycle.get(id),\n getOrCreateLifecycle(id) {\n let entry = lifecycle.get(id);\n if (!entry) {\n entry = {\n onClose: new Set(),\n onMinimize: new Set(),\n onRestore: new Set(),\n onResize: new Set(),\n onActivate: new Set(),\n onDeactivate: new Set(),\n onContainerTypeChange: new Set(),\n };\n lifecycle.set(id, entry);\n }\n return entry;\n },\n deleteLifecycle: (id) => { lifecycle.delete(id); },\n };\n}\n\n/** @internal The nearest provider's panel host. */\nexport const PanelHostContext: Context<PanelHost | null> = createContext<PanelHost | null>(null);\n\n/** @internal The nearest provider's panel host. Throws outside a provider, as the slots never render there. */\nexport function usePanelHost(): PanelHost {\n const host = useContext(PanelHostContext);\n if (!host) throw new Error('[react-dockable-desktop] panel slots must render inside <DockableDesktopProvider>');\n return host;\n}\n","/**\n * Scroll offsets and focus for panel DOM that is moved rather than remounted.\n *\n * A panel's element is never unmounted: it moves between slots — a tab group, a floating window,\n * the taskbar preview, the hidden parking container. React state survives that; browser state\n * does not. A detached or `display: none` subtree loses every scroll offset, and the focused\n * element inside it loses focus. So every tab switch, minimize/restore, float and dock used to\n * put a long list back at the top and drop the caret out of the field being typed in.\n *\n * Offsets and the focused element are recorded *continuously* while the panel is on screen: by\n * the time React runs an effect cleanup the element has already been detached, and reads 0.\n *\n * Keyed by the panel's cached element rather than its id: each workspace has its own elements, so two\n * workspaces on one page — even with the same panel ids — keep separate records, and a record goes\n * away with its element.\n */\n\ninterface PanelDomRecord {\n /** Last on-screen scroll offset of each scrolled element inside the panel. */\n scrolls: Map<Element, { top: number; left: number }>;\n /** The element inside the panel that last had focus. */\n focused: HTMLElement | null;\n}\n\nconst records = new WeakMap<HTMLElement, PanelDomRecord>();\n\n/** A detached or display:none element has no client rects; its scroll offsets read 0. */\nconst isOnScreen = (el: Element): boolean => el.isConnected && el.getClientRects().length > 0;\n\n/** Starts recording scroll offsets and focus inside a panel's cached element. Idempotent. */\nexport function trackPanelDom(root: HTMLElement): void {\n if (records.has(root)) return;\n const record: PanelDomRecord = { scrolls: new Map(), focused: null };\n records.set(root, record);\n\n root.addEventListener('scroll', (e) => {\n const target = e.target;\n // Defensive: an element being hidden or detached resets its offset to 0, and some browsers\n // report that as a scroll event. Chrome doesn't, so no test exercises this guard.\n if (!(target instanceof Element) || !isOnScreen(target)) return;\n record.scrolls.set(target, { top: target.scrollTop, left: target.scrollLeft });\n }, { capture: true, passive: true });\n\n root.addEventListener('focusin', (e) => {\n if (e.target instanceof HTMLElement) record.focused = e.target;\n });\n}\n\n/**\n * Re-applies a panel's recorded state after its element was attached to a new slot.\n *\n * Scroll offsets are always restored. Focus is restored only when `refocus` is true — the panel\n * is the active one — and focus was actually lost (it is on <body>), so a panel restored in the\n * background, or one the user has already moved away from, never takes focus.\n *\n * Runs now and once more on the next frame: content that lays out lazily (virtualised lists,\n * images) may not be tall enough to accept the offset on the first pass.\n */\nexport function restorePanelDom(root: HTMLElement, { refocus }: { refocus: boolean }): void {\n const record = records.get(root);\n if (!record) return;\n const apply = () => {\n record.scrolls.forEach(({ top, left }, el) => {\n if (!el.isConnected) { record.scrolls.delete(el); return; }\n if (el.scrollTop !== top) el.scrollTop = top;\n if (el.scrollLeft !== left) el.scrollLeft = left;\n });\n const focused = record.focused;\n const focusWasLost = document.activeElement === null || document.activeElement === document.body;\n if (refocus && focusWasLost && focused?.isConnected && isOnScreen(focused)) {\n // The element keeps its own selection range, so focusing it puts the caret back too.\n focused.focus({ preventScroll: true });\n }\n };\n apply();\n if (typeof requestAnimationFrame !== 'undefined') requestAnimationFrame(apply);\n}\n\n/** Drops a closed panel's records. */\nexport function forgetPanelDom(root: HTMLElement): void {\n records.delete(root);\n}\n","/**\n * What a workspace mirrors onto `<html>`: its skin, its animations opt-out and its stacking base.\n *\n * Chrome that renders outside the workspace element (the toolbar, the sidebar, portaled menus, toasts,\n * flyouts, modals) can only inherit these from the document, so they are written there. The document\n * is shared by every workspace on the page, which is why this module keeps state at module level, per\n * document — and why it is a stack of owners rather than a plain write: with two workspaces mounted,\n * each used to overwrite the other, and unmounting either one removed the values for the one still on\n * screen.\n *\n * Each field shows the most recently mounted owner that claims it. An owner releases only the fields\n * it claimed; releasing the last claim of a field removes it from `<html>`, as a single workspace\n * always did. A field nobody claims is never touched, so a value the page set itself survives.\n */\n\nexport interface DocumentMirrorValues {\n /** `data-rdd-skin`. `null` claims \"no skin attribute\". */\n skin?: string | null;\n /** The `rdd-no-animations` class. */\n noAnimations?: boolean;\n /** `--rdd-z-base`. */\n zBase?: number;\n}\n\ntype Field = keyof DocumentMirrorValues;\nconst FIELDS: readonly Field[] = ['skin', 'noAnimations', 'zBase'];\n\ninterface Claim { owner: object; values: DocumentMirrorValues }\n\nconst stacks = new WeakMap<Document, Claim[]>();\n\nfunction apply(doc: Document, stack: readonly Claim[], touched: readonly Field[]): void {\n const root = doc.documentElement;\n // The newest owner that claims a field decides it.\n const pick = <K extends Field>(field: K): { claimed: boolean; value?: DocumentMirrorValues[K] } => {\n for (let i = stack.length - 1; i >= 0; i--) {\n if (field in stack[i].values) return { claimed: true, value: stack[i].values[field] };\n }\n return { claimed: false };\n };\n\n if (touched.includes('skin')) {\n const skin = pick('skin');\n if (skin.claimed && skin.value) root.setAttribute('data-rdd-skin', skin.value);\n else root.removeAttribute('data-rdd-skin');\n }\n if (touched.includes('noAnimations')) {\n const noAnimations = pick('noAnimations');\n root.classList.toggle('rdd-no-animations', noAnimations.claimed && noAnimations.value === true);\n }\n if (touched.includes('zBase')) {\n const zBase = pick('zBase');\n if (zBase.claimed && zBase.value !== undefined) root.style.setProperty('--rdd-z-base', String(zBase.value));\n else root.style.removeProperty('--rdd-z-base');\n }\n}\n\n/**\n * Claims (or updates) `owner`'s values. A first claim puts the owner on top; an update keeps its\n * place, so changing one workspace's skin never lets it jump over a workspace mounted after it.\n */\nexport function claimDocumentMirror(owner: object, values: DocumentMirrorValues, doc: Document = document): void {\n const stack = stacks.get(doc) ?? [];\n stacks.set(doc, stack);\n const claim = stack.find(c => c.owner === owner);\n if (claim) Object.assign(claim.values, values);\n else stack.push({ owner, values: { ...values } });\n apply(doc, stack, Object.keys(values) as Field[]);\n}\n\n/** Releases `owner`'s claim on `fields`; the owner leaves the stack once it claims nothing. */\nexport function releaseDocumentMirror(owner: object, fields: readonly Field[] = FIELDS, doc: Document = document): void {\n const stack = stacks.get(doc);\n if (!stack) return;\n const index = stack.findIndex(c => c.owner === owner);\n if (index === -1) return;\n const claim = stack[index];\n const released = fields.filter(field => field in claim.values);\n for (const field of released) delete claim.values[field];\n if (Object.keys(claim.values).length === 0) stack.splice(index, 1);\n apply(doc, stack, released);\n}\n","/**\n * @file predefinedMessages.ts\n * @description Provides the default localizable message catalogs and translation keys\n * utilized by Dockable Desktop's context menus, headers, and tooltips.\n *\n * Each value's `id` is the react-intl message ID that the consumer should\n * define in their IntlProvider messages table. The `defaultMessage` is used\n * as a fallback when no external formatter is provided.\n *\n * Pass a partial or full override as `createWorkspace({ messages })` or\n * `<DockableDesktopProvider messages={…}>` to customise labels without replacing the whole table.\n */\nexport const defaultPredefinedMessages = {\n floatWindow: { id: 'dockable-desktop-floatWindow', defaultMessage: 'Float Window' },\n minimizePanel: { id: 'dockable-desktop-minimizePanel', defaultMessage: 'Minimize Panel' },\n closeTab: { id: 'dockable-desktop-closeTab', defaultMessage: 'Close Tab' },\n restorePanel: { id: 'dockable-desktop-restorePanel', defaultMessage: 'Restore Panel' },\n maximizePanel: { id: 'dockable-desktop-maximizePanel', defaultMessage: 'Maximize Panel' },\n closePanel: { id: 'dockable-desktop-closePanel', defaultMessage: 'Close Panel' },\n dockWindow: { id: 'dockable-desktop-dockWindow', defaultMessage: 'Dock Window' },\n minimize: { id: 'dockable-desktop-minimize', defaultMessage: 'Minimize' },\n maximize: { id: 'dockable-desktop-maximize', defaultMessage: 'Maximize' },\n restoreSize: { id: 'dockable-desktop-restoreSize', defaultMessage: 'Restore Size' },\n close: { id: 'dockable-desktop-close', defaultMessage: 'Close' },\n closeEmptyGroup: { id: 'dockable-desktop-closeEmptyGroup', defaultMessage: 'Close empty split group' },\n unsavedChangesTitle: { id: 'dockable-desktop-unsavedChangesTitle', defaultMessage: 'Unsaved Changes' },\n unsavedChangesMessage: { id: 'dockable-desktop-unsavedChangesMessage', defaultMessage: '\"{title}\" has unsaved changes. Do you want to discard your changes and close?' },\n discardChanges: { id: 'dockable-desktop-discardChanges', defaultMessage: 'Discard Changes' },\n cancel: { id: 'dockable-desktop-cancel', defaultMessage: 'Cancel' },\n yes: { id: 'dockable-desktop-yes', defaultMessage: 'Yes' },\n no: { id: 'dockable-desktop-no', defaultMessage: 'No' },\n ok: { id: 'dockable-desktop-ok', defaultMessage: 'OK' },\n closePanelTooltip: { id: 'dockable-desktop-closePanelTooltip', defaultMessage: 'Close panel' },\n closeTooltip: { id: 'dockable-desktop-closeTooltip', defaultMessage: 'Close' },\n // Accessible names and placeholders (6.4.0) — previously hard-coded in English.\n notifications: { id: 'dockable-desktop-notifications', defaultMessage: 'Notifications' },\n closeNotification: { id: 'dockable-desktop-closeNotification', defaultMessage: 'Close notification' },\n scrollTabsLeft: { id: 'dockable-desktop-scrollTabsLeft', defaultMessage: 'Scroll tabs left' },\n scrollTabsRight: { id: 'dockable-desktop-scrollTabsRight', defaultMessage: 'Scroll tabs right' },\n scrollTaskbarLeft: { id: 'dockable-desktop-scrollTaskbarLeft', defaultMessage: 'Scroll taskbar left' },\n scrollTaskbarRight: { id: 'dockable-desktop-scrollTaskbarRight', defaultMessage: 'Scroll taskbar right' },\n moreActions: { id: 'dockable-desktop-moreActions', defaultMessage: 'More actions' },\n search: { id: 'dockable-desktop-search', defaultMessage: 'Search' },\n closeSearch: { id: 'dockable-desktop-closeSearch', defaultMessage: 'Close search' },\n searchPlaceholder: { id: 'dockable-desktop-searchPlaceholder', defaultMessage: 'Search…' },\n modalTitle: { id: 'dockable-desktop-modalTitle', defaultMessage: 'Confirmation' },\n // Default title of useModals().alert() (7.7.0).\n alertTitle: { id: 'dockable-desktop-alertTitle', defaultMessage: 'Information' },\n emptyGroup: { id: 'dockable-desktop-emptyGroup', defaultMessage: 'Empty Workspace Section' },\n emptyGrid: { id: 'dockable-desktop-emptyGrid', defaultMessage: 'Grid Empty' },\n componentUnregistered: { id: 'dockable-desktop-componentUnregistered', defaultMessage: 'Component Unregistered' },\n componentKey: { id: 'dockable-desktop-componentKey', defaultMessage: 'Key: {key}' },\n untitledPanel: { id: 'dockable-desktop-untitledPanel', defaultMessage: 'Panel' },\n} as const;\n\n/**\n * Union of every key in `defaultMessages`.\n *\n * Import this type in your i18n message tables to get a compile-time\n * guarantee that all keys are present and no typos exist:\n *\n * import type { MessageKey } from 'react-dockable-desktop';\n *\n * const myMessages: Record<MessageKey, string> = { ... };\n */\nexport type MessageKey = keyof typeof defaultPredefinedMessages;\n","/**\n * @file messages.ts\n * @description Resolving a label — a string, a message descriptor or a thunk — to text.\n */\nimport type { MessageDescriptor, MessageFormatter } from '../types';\n\n/**\n * @internal The formatter used when the app passes none: the descriptor's `defaultMessage` (or its\n * id) with each `{key}` replaced by its value — every occurrence (7.4.1; it replaced only the first).\n */\nexport const defaultFormatMessage: MessageFormatter = (msg) => {\n let text = msg.defaultMessage || msg.id;\n if (msg.values) {\n for (const [key, value] of Object.entries(msg.values)) text = text.split(`{${key}}`).join(String(value));\n }\n return text;\n};\n\n/**\n * Helper to resolve dynamic label strings or localizable descriptor objects into text.\n */\nexport const formatLabel = (\n label: string | MessageDescriptor | (() => string) | undefined,\n formatter: MessageFormatter\n): string => {\n if (!label) return '';\n if (typeof label === 'string') return label;\n // A thunk (7.4.0) is called each time the label is rendered, so it follows the app's own locale.\n if (typeof label === 'function') return label();\n return formatter(label);\n};\n","import { isValidElement } from 'react';\n\n/**\n * Recursively checks whether a value can round-trip through `JSON.stringify`/`JSON.parse`\n * without silently losing information.\n *\n * Deliberately **not** a `JSON.stringify` try/catch — that call doesn't throw for the actual\n * failure case this guards against: a function-valued property is simply dropped by\n * `JSON.stringify`, not rejected. This walks the value tree instead, returning `false` as soon as\n * it finds a function, symbol, `undefined`, React element, or any non-plain object (a class\n * instance, `Map`, `Set`, `RegExp`, etc.).\n *\n * `Date` is treated as an explicit exception — serializable-enough, matching `JSON.stringify`'s\n * own behavior — even though it doesn't round-trip back to a `Date` instance on parse. That's a\n * smaller, more tolerable gotcha than a silently-vanishing function, so it's documented rather\n * than treated as a disqualifying case.\n *\n * Used to decide whether a docked/floating panel's `props` can be included in\n * the workspace's `saveLayout()` output — see {@link PanelInfo.serializable}.\n */\nexport function isSerializable(value: unknown): boolean {\n if (value === null) return true;\n if (value === undefined) return false;\n\n const type = typeof value;\n if (type === 'string' || type === 'number' || type === 'boolean') return true;\n if (type === 'function' || type === 'symbol' || type === 'bigint') return false;\n\n // type === 'object' from here on.\n if (value instanceof Date) return true;\n if (isValidElement(value)) return false;\n if (Array.isArray(value)) return value.every(isSerializable);\n\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return false; // class instance, Map, Set, RegExp, Error, etc.\n\n return Object.values(value as Record<string, unknown>).every(isSerializable);\n}\n","/**\n * @file sameUpdate.ts\n * @description Equality checks that let the title and dirty setters skip a write that changes\n * nothing, so a panel that writes the same value on every render doesn't re-render forever.\n */\nimport type { DirtyStateOptions } from './dirtyOptions';\n\ntype Title = string | { id: string; defaultMessage?: string; values?: Record<string, unknown> } | (() => string);\n\nfunction shallowEqual(a: object | undefined, b: object | undefined): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n const ka = Object.keys(a);\n if (ka.length !== Object.keys(b).length) return false;\n return ka.every(k => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k]);\n}\n\n/** A string title, or a message descriptor with the same id, default text and values. */\nexport function sameTitle(a: Title | undefined, b: Title | undefined): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;\n return a.id === b.id && a.defaultMessage === b.defaultMessage && shallowEqual(a.values, b.values);\n}\n\n/** Dirty options with the same title, message and alert. */\nexport function sameDirtyOptions(a: DirtyStateOptions | undefined, b: DirtyStateOptions | undefined): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof DirtyStateOptions>;\n for (const k of keys) {\n const x = a[k], y = b[k];\n if (k === 'title' || k === 'message' ? !sameTitle(x as Title | undefined, y as Title | undefined) : x !== y) return false;\n }\n return true;\n}\n","/**\n * @file eventBus.ts\n * @description The workspace's pub/sub event bus.\n */\n\n// Event Bus class for pub-sub communication between panels\nexport class PanelEventBus {\n private listeners: Record<string, ((data: unknown) => void)[]> = {};\n\n subscribe(event: string, callback: (data: unknown) => void): () => void {\n if (!this.listeners[event]) {\n this.listeners[event] = [];\n }\n this.listeners[event].push(callback);\n return () => {\n this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);\n };\n }\n\n publish(event: string, data: unknown): void {\n if (this.listeners[event]) {\n // One subscriber that throws must not stop delivery to the rest (7.4.1), nor the action\n // that published — loadLayout, a close — halfway through.\n for (const cb of this.listeners[event]) {\n try {\n cb(data);\n } catch (e) {\n console.error(`[react-dockable-desktop] A subscriber to \"${event}\" threw:`, e);\n }\n }\n }\n }\n}\n","/**\n * @file layoutTree.ts\n * @description Pure functions over the layout tree: which panel is visibly active, repairing a\n * loaded tree, and the tree edits the workspace actions are built from.\n */\nimport type { SplitOrientation, SplitDirection, LayoutLeafNode, LayoutNode, FloatingWindow, PanelInfo, SerializedLayout } from '../types';\n\nexport const EMPTY_LEAF: LayoutLeafNode = {\n type: 'leaf',\n id: 'group-default',\n panels: [],\n activePanelId: null,\n};\n\n/** The subset of a layout needed to reason about which panel is visibly active. */\nexport type ActiveTargetScope = Pick<SerializedLayout, 'gridRoot' | 'floating' | 'panels'>;\n\n/**\n * Whether `id` names a panel the user can actually see, and which may therefore be the globally\n * active one: the selected tab of some leaf, or a floating window. A minimized panel never\n * qualifies — it stays mounted (see the persistence port in `WindowManager.tsx`), so leaving it\n * active would keep routing `useActiveContribution()` to a panel that isn't on screen.\n *\n * Used both to validate a persisted `activePanelId` on load and to guard the one written by\n * `saveLayout`, so the two directions can't disagree about what \"active\" is allowed to mean.\n */\nexport function isVisibleActiveTarget(id: string, scope: ActiveTargetScope): boolean {\n const info = scope.panels[id];\n if (!info || info.state === 'minimized') return false;\n if (scope.floating.some(w => w.id === id)) return true;\n const isLeafSelection = (node: LayoutNode): boolean =>\n node.type === 'leaf'\n ? node.activePanelId === id\n : node.children.some(isLeafSelection);\n return scope.gridRoot ? isLeafSelection(scope.gridRoot) : false;\n}\n\n/**\n * Derives the globally active panel for a restored layout.\n *\n * Replaces the original `Object.keys(panels)[0]` seed, which picked the first key of a flat,\n * insertion-ordered record that knows nothing about tab order or docked/floating/minimized — so\n * unless the user happened to have the first-opened panel selected when they saved, the workspace\n * came back with one panel visible and a *different*, invisible one marked active. Every\n * `LayoutLeafNode` already persists its own `activePanelId`, so the answer was on disk all along.\n *\n * Order:\n * 1. The first leaf in document order whose own selected tab is a valid target.\n * 2. Otherwise the frontmost (highest `z`) floating window — matching `focusPanel`'s own\n * \"highest z is on top\" rule, and keeping float-only layouts from restoring with nothing\n * active at all.\n * 3. Otherwise `null`.\n *\n * Depth-first, not breadth-first: for a grid whose first child is itself a split, a level-by-level\n * walk reaches the *second* child's leaf before the first child's leaves and picks the wrong tab.\n * Mirrors `findFirstLeafId`'s traversal shape for exactly that reason.\n */\nexport function deriveActivePanelId(scope: ActiveTargetScope): string | null {\n const isCandidate = (id: string | null): boolean =>\n id !== null && !!scope.panels[id] && scope.panels[id].state !== 'minimized';\n\n const fromLeaves = (node: LayoutNode): string | null => {\n if (node.type === 'leaf') {\n return isCandidate(node.activePanelId) ? node.activePanelId : null;\n }\n for (const child of node.children) {\n const found = fromLeaves(child);\n if (found) return found;\n }\n return null;\n };\n\n const selected = scope.gridRoot ? fromLeaves(scope.gridRoot) : null;\n if (selected) return selected;\n\n let frontmost: FloatingWindow | null = null;\n for (const w of scope.floating) {\n if (!isCandidate(w.id)) continue;\n if (!frontmost || w.z > frontmost.z) frontmost = w;\n }\n return frontmost?.id ?? null;\n}\n\n/**\n * The globally active panel after a placement action (float / dock / move / close-group).\n *\n * Those actions change which tab a leaf shows without going through `focusPanel`, and each one\n * used to leave `activePanelId` wherever it was — often on a tab the move had just hidden, so the\n * visible tab rendered unfocused and `useActiveContribution()` kept serving the hidden\n * panel's controls. The moved panel is what the user just acted on, so it wins when it is\n * visible; otherwise the previous active panel is kept if it still is; otherwise it is derived.\n */\nexport function resolveActivePanelId(\n next: ActiveTargetScope & { activePanelId: string | null },\n preferId: string | null,\n): string | null {\n if (preferId && isVisibleActiveTarget(preferId, next)) return preferId;\n if (next.activePanelId && isVisibleActiveTarget(next.activePanelId, next)) return next.activePanelId;\n return deriveActivePanelId(next);\n}\n\n/**\n * Shared shape-check + migration for a parsed (but not yet validated) layout payload,\n * used by both `parseInitialState` (the `initialState`/`createWorkspace({ initialState })`\n * entry point) and `loadLayout` — previously these duplicated the check independently\n * and only one of them ran the stickyRight/stickyBottom migration, so a layout fed\n * through `initialState` silently skipped it. `version` is read but not yet branched on\n * — it's read here so a future migration has a version to gate on without needing\n * another ad hoc field-presence sniff like this one.\n *\n * Also resolves `activePanelId`, for the same reason the shape-check lives here: both entry\n * points need it and previously seeded it themselves, identically wrongly, in two places.\n */\n/**\n * Heal a saved layout that names the same panel twice, or names none of them.\n *\n * Until 6.3.1, dropping a lone docked panel onto its own group put that panel in two leaves,\n * and `saveLayout()` wrote the result out — so the duplicate came back on every reload, for\n * good. Repairing on read means a layout stored by an affected version loads clean with\n * nothing asked of the application. It changes only what is *read*: `saveLayout()`'s output\n * format is untouched.\n *\n * The repairs, in order: a leaf panel id the layout's `panels` doesn't have is dropped (7.4.1);\n * a panel id that appears in more than one leaf is kept in the first one only; a leaf emptied\n * by either keeps existing only if it asked to (`keepOnEmpty`); a branch left with one child\n * collapses into it, with sizes re-normalised; a branch whose sizes don't match its children,\n * or aren't finite positive numbers, gets even sizes (7.4.1); and a panel the layout says is\n * docked but that no leaf lists is appended to the first leaf, since \"open but in no group\"\n * renders nothing and cannot be reached.\n */\nexport function repairLayoutTree(\n gridRoot: LayoutNode,\n panels: Record<string, PanelInfo>\n): { gridRoot: LayoutNode; repairs: string[] } {\n const repairs: string[] = [];\n const seen = new Set<string>();\n\n const walk = (node: LayoutNode): LayoutNode | null => {\n if (node.type === 'leaf') {\n const kept = node.panels.filter(panelId => {\n if (!panels[panelId]) {\n repairs.push(`group \"${node.id}\" listed panel \"${panelId}\", which the layout doesn't have`);\n return false;\n }\n if (seen.has(panelId)) {\n repairs.push(`panel \"${panelId}\" was listed in more than one group`);\n return false;\n }\n seen.add(panelId);\n return true;\n });\n if (kept.length === node.panels.length) return node;\n if (kept.length === 0 && !node.keepOnEmpty) return null;\n const activePanelId = node.activePanelId && kept.includes(node.activePanelId)\n ? node.activePanelId\n : (kept[0] ?? null);\n return { ...node, panels: kept, activePanelId };\n }\n\n const children = node.children.map(walk).filter((c): c is LayoutNode => c !== null);\n // Identity, not count: a child can survive the walk and still have been repaired inside.\n // Comparing lengths alone returned the original branch and discarded those repairs.\n // Sizes that don't match the children, or aren't finite positive numbers, would give a child\n // `flex-basis: NaN%` (7.4.1): such a branch gets even sizes.\n const sizesOk = (sizes: unknown[], n: number) =>\n Array.isArray(sizes) && sizes.length === n && sizes.every(v => typeof v === 'number' && Number.isFinite(v) && v > 0);\n const unchanged = children.length === node.children.length && children.every((c, i) => c === node.children[i]);\n if (unchanged && sizesOk(node.sizes, children.length)) return node;\n if (children.length === 0) return null;\n if (children.length === 1) return children[0];\n if (unchanged) {\n repairs.push(`a split had sizes ${JSON.stringify(node.sizes)} for ${children.length} children`);\n return { ...node, sizes: children.map(() => 1 / children.length) };\n }\n const kept = Array.isArray(node.sizes) ? node.sizes.slice(0, children.length) : [];\n if (!sizesOk(kept, children.length)) return { ...node, children, sizes: children.map(() => 1 / children.length) };\n const sum = kept.reduce((a, b) => a + b, 0);\n return { ...node, children, sizes: kept.map(s => s / sum) };\n };\n\n let root = walk(gridRoot) || EMPTY_LEAF;\n\n const orphans = Object.values(panels).filter(p => p.state === 'docked' && !seen.has(p.id));\n if (orphans.length > 0) {\n const attach = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n const ids = orphans.map(p => p.id);\n return { ...node, panels: [...node.panels, ...ids], activePanelId: node.activePanelId ?? ids[0] };\n }\n return { ...node, children: [attach(node.children[0]), ...node.children.slice(1)] };\n };\n for (const orphan of orphans) {\n repairs.push(`panel \"${orphan.id}\" is docked but was in no group`);\n }\n root = attach(root);\n }\n\n return { gridRoot: root, repairs };\n}\n\n// Recursive helpers to manipulate layout tree\nexport const removePanelFromTree = (node: LayoutNode, id: string): LayoutNode | null => {\n if (node.type === 'leaf') {\n const idx = node.panels.indexOf(id);\n if (idx === -1) return node;\n const panels = node.panels.filter(p => p !== id);\n const activePanelId = node.activePanelId === id\n ? (panels[idx] || panels[idx - 1] || panels[0] || null)\n : node.activePanelId;\n const updatedLeaf = { ...node, panels, activePanelId };\n // Auto-remove this leaf when it becomes empty, unless keepOnEmpty is set\n if (panels.length === 0 && !node.keepOnEmpty) return null;\n return updatedLeaf;\n } else {\n const children = node.children\n .map(c => removePanelFromTree(c, id))\n .filter((c): c is LayoutNode => c !== null);\n\n if (children.length === 0) return null;\n if (children.length === 1) return children[0];\n\n // Re-normalize sizes\n const sizes = node.sizes.slice(0, children.length);\n const sum = sizes.reduce((a, b) => a + b, 0);\n return {\n ...node,\n children,\n sizes: sizes.map(s => s / sum)\n };\n }\n};\n\nexport const addPanelToLeaf = (node: LayoutNode, leafId: string, panelId: string): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.id === leafId) {\n const panels = node.panels.includes(panelId) ? node.panels : [...node.panels, panelId];\n return { ...node, panels, activePanelId: panelId };\n }\n return node;\n } else {\n return {\n ...node,\n children: node.children.map(c => addPanelToLeaf(c, leafId, panelId))\n };\n }\n};\n\n/**\n * Is `panelId` the only panel in `leafId`?\n *\n * The question every dock reducer has to ask *before* it removes anything. Removing a\n * panel deletes an emptied leaf, so a drop onto the dragged panel's own leaf destroys the\n * very target it names — and the placement that follows has nowhere to go. Dropping a lone\n * panel onto itself is a no-op by definition: the result would be the layout it already\n * has.\n */\nexport const isLoneOccupant = (node: LayoutNode, leafId: string, panelId: string): boolean => {\n if (node.type === 'leaf') {\n return node.id === leafId && node.panels.length === 1 && node.panels[0] === panelId;\n }\n return node.children.some(c => isLoneOccupant(c, leafId, panelId));\n};\n\n/** Does `leafId` name a leaf that is actually in the tree? */\nexport const hasLeaf = (node: LayoutNode, leafId: string): boolean =>\n node.type === 'leaf' ? node.id === leafId : node.children.some(c => hasLeaf(c, leafId));\n\n/** Whether a docked panel is the one shown in its group. */\nexport const isShownInGrid = (node: LayoutNode, panelId: string): boolean => {\n if (node.type === 'leaf') return node.panels.includes(panelId) && node.activePanelId === panelId;\n return node.children.some(c => isShownInGrid(c, panelId));\n};\n\n/** The id of the group (leaf) that holds `panelId` in the grid, or null if it is not docked. */\nexport const findLeafIdOf = (node: LayoutNode, panelId: string): string | null => {\n if (node.type === 'leaf') return node.panels.includes(panelId) ? node.id : null;\n for (const child of node.children) {\n const id = findLeafIdOf(child, panelId);\n if (id) return id;\n }\n return null;\n};\n\nexport const findFirstLeafId = (node: LayoutNode): string | null => {\n if (node.type === 'leaf') return node.id;\n for (const child of node.children) {\n const id = findFirstLeafId(child);\n if (id) return id;\n }\n return null;\n};\n\n// Helper to split a layout leaf node into a branch (for drag split targets)\nexport const splitLeafInTree = (\n node: LayoutNode,\n leafId: string,\n panelId: string,\n position: SplitDirection,\n splitRatio: number\n): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.id === leafId) {\n const newLeaf: LayoutLeafNode = {\n type: 'leaf',\n id: `group-split-${Date.now()}-${Math.floor(Math.random() * 1000)}`,\n panels: [panelId],\n activePanelId: panelId\n };\n const orientation: SplitOrientation = (position === 'left' || position === 'right') ? 'horizontal' : 'vertical';\n const children = (position === 'left' || position === 'top') ? [newLeaf, node] : [node, newLeaf];\n const sizes = (position === 'left' || position === 'top')\n ? [splitRatio, 1 - splitRatio]\n : [1 - splitRatio, splitRatio];\n return {\n type: 'branch',\n orientation,\n sizes,\n children\n };\n }\n return node;\n } else {\n return {\n ...node,\n children: node.children.map(c => splitLeafInTree(c, leafId, panelId, position, splitRatio))\n };\n }\n};\n","/**\n * @file serialize.ts\n * @description Reading a saved layout: parsing, migrating, and repairing it on load.\n */\nimport type { LayoutNode, FloatAnchor, PanelInfo, WorkspaceState, SerializedLayout } from '../types';\nimport { EMPTY_LEAF, isVisibleActiveTarget, deriveActivePanelId, repairLayoutTree } from './layoutTree';\nimport type { ActiveTargetScope } from './layoutTree';\n\nexport type ParsedLayoutPayload = Pick<SerializedLayout, 'gridRoot' | 'floating' | 'minimized' | 'panels'> & {\n /** Resolved by `parseLayoutPayload` — the persisted value when still valid, else derived. */\n activePanelId: string | null;\n};\n\n/** The geometry a newly floated panel gets, and what a saved window's unusable geometry is repaired to. */\nexport const DEFAULT_FLOAT_RECT = { x: 300, y: 150, width: 450, height: 350 } as const;\n\n/**\n * A saved window's x/y/width/height, made finite (7.4.0). A NaN, Infinity or missing number would\n * otherwise reach the window's style — React logs \"`NaN` is an invalid value for the `left` css\n * style property\" at every start-up — so each is replaced by the default a new float gets, and the\n * repair is reported. A string (a CSS length) is kept as it is.\n */\nexport function finiteGeometry<T extends Record<string, unknown>>(fw: T, repairs: string[]): T {\n let out = fw;\n for (const k of ['x', 'y', 'width', 'height'] as const) {\n const v = fw[k];\n if (typeof v === 'string' || (typeof v === 'number' && Number.isFinite(v))) continue;\n out = { ...out, [k]: DEFAULT_FLOAT_RECT[k] } as T;\n repairs.push(`floating window \"${fw.id}\" had ${k} = ${String(v)}`);\n }\n return out;\n}\n\n/** A saved window as read from storage, before repair: possibly a pre-anchor layout (`stickyRight`/`stickyBottom`). */\ntype RawWindow = Record<string, unknown>;\n\nexport function parseLayoutPayload(input: unknown): ParsedLayoutPayload | null {\n const parsed = input as Partial<Record<'gridRoot' | 'floating' | 'minimized' | 'panels' | 'activePanelId', unknown>> | null;\n if (!parsed || !parsed.gridRoot || !Array.isArray(parsed.floating) || !Array.isArray(parsed.minimized) || !parsed.panels) {\n return null;\n }\n // const version = typeof parsed.version === 'number' ? parsed.version : 0; // reserved for future migrations\n const geometryRepairs: string[] = [];\n // Past the shape check the payload is trusted, as before; each window only gets its geometry\n // repaired and a pre-anchor layout converted.\n const floating = (parsed.floating as RawWindow[]).map(fw => finiteGeometry(fw, geometryRepairs)).map(fw => {\n if ('stickyRight' in fw || 'stickyBottom' in fw) {\n const anchor: FloatAnchor | null = fw.stickyRight && fw.stickyBottom ? 'bottom-right'\n : fw.stickyRight ? 'top-right'\n : fw.stickyBottom ? 'bottom-left'\n : null;\n const { stickyRight: _sr, stickyBottom: _sb, ...rest } = fw;\n return { ...rest, anchor };\n }\n return fw;\n }) as unknown as SerializedLayout['floating'];\n const panels = parsed.panels as Record<string, PanelInfo>;\n // Repair before anything reads the tree: activePanelId resolution below asks which panels\n // are visible, and a duplicated or orphaned panel would make that answer meaningless.\n const repaired = repairLayoutTree(parsed.gridRoot as LayoutNode, panels);\n if (repaired.repairs.length > 0 && process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] Repaired the saved layout on load: ${repaired.repairs.join('; ')}. ` +\n `(Layouts saved by versions before 6.3.1 can list a panel twice — dropping a lone docked ` +\n `panel onto its own group duplicated it.) The repair is applied every time it is read, so ` +\n `saving again from this session stores the corrected layout.`\n );\n }\n if (geometryRepairs.length > 0 && process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] Repaired the saved layout on load: ${geometryRepairs.join('; ')}. ` +\n `Each is replaced by the default a new floating window gets (${JSON.stringify(DEFAULT_FLOAT_RECT)}); ` +\n `saving again from this session stores the corrected layout.`\n );\n }\n const gridRoot = repaired.gridRoot;\n const scope: ActiveTargetScope = { gridRoot, floating, panels };\n\n // A persisted value wins when it still names a visible panel; anything stale (the panel was\n // closed, minimized, or pruned from this snapshot) falls back to deriving from the grid, which\n // is also the path every pre-`activePanelId` layout takes.\n const persisted = typeof parsed.activePanelId === 'string' ? parsed.activePanelId : null;\n let activePanelId: string | null = null;\n if (persisted !== null) {\n if (isVisibleActiveTarget(persisted, scope)) {\n activePanelId = persisted;\n } else if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] Ignoring the saved layout's activePanelId (\"${persisted}\") — ` +\n `it doesn't name a currently visible panel (it may have been closed, minimized, or ` +\n `excluded from the snapshot as non-serializable). Falling back to the selected tab of ` +\n `the first leaf in the grid.`\n );\n }\n }\n if (activePanelId === null) activePanelId = deriveActivePanelId(scope);\n\n return { gridRoot, floating, minimized: parsed.minimized as SerializedLayout['minimized'], panels, activePanelId };\n}\n\nexport function parseInitialState(json: string | null): Pick<WorkspaceState, 'gridRoot' | 'floating' | 'minimized' | 'panels' | 'activePanelId'> {\n if (json) {\n try {\n const payload = parseLayoutPayload(JSON.parse(json));\n if (payload) return payload;\n } catch {\n // fall through to empty canvas\n }\n }\n return { gridRoot: EMPTY_LEAF, floating: [], minimized: [], panels: {}, activePanelId: null };\n}\n","/**\n * @file workspaceCore.ts\n * @description The workspace store: the layout state, every action on it, and the event bus. It\n * has no React dependency; a provider only subscribes to it.\n */\nimport type React from 'react';\nimport type { DirtyStateOptions } from '../components/dirtyOptions';\nimport type { ContextMenuItem, ShowContextMenuOptions } from '../components/ContextMenu';\nimport { isSerializable } from '../components/serializable';\nimport { sameTitle, sameDirtyOptions } from '../components/sameUpdate';\nimport type { PanelDropTarget, MessageDescriptor, SplitOrientation, SplitDirection, DropPosition, LayoutLeafNode, LayoutNode, FloatAnchor, FloatingWindow, PanelInfo, OpenPanelOptions, WorkspaceState, InternalWindowActions, SerializedLayout, WorkspaceCoreConfig, WorkspaceCore } from '../types';\nimport { PanelEventBus } from './eventBus';\nimport { EMPTY_LEAF, isVisibleActiveTarget, deriveActivePanelId, resolveActivePanelId, removePanelFromTree, addPanelToLeaf, isLoneOccupant, hasLeaf, findFirstLeafId, findLeafIdOf, splitLeafInTree } from './layoutTree';\nimport { DEFAULT_FLOAT_RECT, parseLayoutPayload, parseInitialState } from './serialize';\n\n/**\n * @internal Builds a workspace store: the layout state, every action on it, and the event bus.\n * It has no React dependency — it exists (and accepts calls) before any provider mounts, and a\n * provider only subscribes to it. See `createWorkspace()` for the public face.\n */\nexport function createWorkspaceCore(config: WorkspaceCoreConfig): WorkspaceCore {\n const registry = config.registry;\n\n const effectiveDir = config.dir;\n const effectiveZIndexBase = config.zIndexBase ?? 1000;\n\n let state: WorkspaceState = (() => {\n const layout = parseInitialState(config.initialState ?? null);\n return {\n ...layout,\n draggedPanelId: null,\n dir: effectiveDir || 'ltr',\n isRtl: effectiveDir === 'rtl',\n splitRatio: Math.min(0.9, Math.max(0.1, config.defaultSplitRatio ?? 0.5)),\n edgeSplitRatio: Math.min(0.9, Math.max(0.1, config.defaultEdgeSplitRatio ?? 0.2)),\n };\n })();\n\n // The state lives here, outside React: actions apply immediately, before or after any provider\n // mounts, and the provider reads it through useSyncExternalStore.\n const listeners = new Set<() => void>();\n const setState = (update: WorkspaceState | ((prev: WorkspaceState) => WorkspaceState)): void => {\n const prev = state;\n const next = typeof update === 'function' ? update(prev) : update;\n if (next === prev) return;\n state = next;\n listeners.forEach(listener => listener());\n };\n // Read-only view kept under the old name, so every `stateRef.current` read sees live state.\n const stateRef = { get current(): WorkspaceState { return state; } };\n const getSnapshot = (): WorkspaceState => state;\n const subscribeToState = (cb: () => void): (() => void) => {\n listeners.add(cb);\n return () => { listeners.delete(cb); };\n };\n\n const closeGuardsRef: { current: Record<string, () => boolean | Promise<boolean>> } = { current: {} };\n const stateProvidersRef: { current: Record<string, () => unknown> } = { current: {} };\n\n const eventBusRef = { current: new PanelEventBus() };\n // Seeded from the restored windows (7.4.1): starting at the base, a focused restored window was\n // given a z below the others and dropped behind them, and a new float opened beneath them.\n const topZ = (floating: FloatingWindow[]): number =>\n floating.reduce((top, w) => (Number.isFinite(w.z) && w.z > top ? w.z : top), effectiveZIndexBase);\n const maxZRef = { current: topZ(state.floating) };\n\n const subscribe: InternalWindowActions['subscribe'] = (event, callback) => {\n return eventBusRef.current.subscribe(event, callback);\n };\n\n const publish: InternalWindowActions['publish'] = (event, data) => {\n eventBusRef.current.publish(event, data);\n };\n\n // Helper: Find free cascading location for floating window\n const getCascadedPosition = (\n fav: { x: number | string; y: number | string; width: number | string; height: number | string },\n currentFloating: FloatingWindow[]\n ) => {\n let x = typeof fav.x === 'string' ? parseFloat(fav.x) : fav.x;\n let y = typeof fav.y === 'string' ? parseFloat(fav.y) : fav.y;\n let width = typeof fav.width === 'string' ? parseFloat(fav.width) : fav.width;\n let height = typeof fav.height === 'string' ? parseFloat(fav.height) : fav.height;\n\n // Fallbacks if parseFloat fails and returns NaN\n if (isNaN(x)) x = 300;\n if (isNaN(y)) y = 150;\n if (isNaN(width)) width = 450;\n if (isNaN(height)) height = 350;\n\n const isOverlapping = (pos: { x: number; y: number }) => {\n return currentFloating.some(w => {\n const wx = typeof w.x === 'string' ? parseFloat(w.x) : w.x;\n const wy = typeof w.y === 'string' ? parseFloat(w.y) : w.y;\n return !w.maximized && Math.abs(wx - pos.x) < 20 && Math.abs(wy - pos.y) < 20;\n });\n };\n\n let attempts = 0;\n while (isOverlapping({ x, y }) && attempts < 10) {\n x += 30;\n y += 30;\n attempts++;\n }\n\n // Capture safe viewport boundaries (min 1024x768 fallback if not measured or in headless environments)\n // (and on the server, where a workspace can already be opened into before anything mounts)\n const viewW = Math.max(100, (typeof window !== 'undefined' && window.innerWidth) || 1024);\n const viewH = Math.max(100, (typeof window !== 'undefined' && window.innerHeight) || 768);\n\n if (x + width > viewW || y + height > viewH) {\n x = 100 + (attempts % 5) * 30;\n y = 100 + (attempts % 5) * 30;\n }\n\n // Final safety clamp to make sure window title bar is always visible and clickable\n x = Math.max(0, Math.min(x, viewW - 100));\n y = Math.max(0, Math.min(y, viewH - 40));\n\n return { x, y, width, height };\n };\n\n const focusPanel = (id: string) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n if (panel.state === 'floating') {\n const win = prev.floating.find(w => w.id === id);\n if (!win) return prev;\n const alreadyTop = !prev.floating.some(w => w.z > win.z);\n if (alreadyTop && prev.activePanelId === id) return prev; // no-op — StrictMode safe\n if (!alreadyTop) maxZRef.current += 1;\n return {\n ...prev,\n floating: prev.floating.map(w =>\n w.id === id ? { ...w, z: alreadyTop ? win.z : maxZRef.current } : w\n ),\n activePanelId: id\n };\n } else if (panel.state === 'docked') {\n if (prev.activePanelId === id) return prev; // no-op\n const selectActiveInTree = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.panels.includes(id)) {\n return { ...node, activePanelId: id };\n }\n return node;\n } else {\n return { ...node, children: node.children.map(selectActiveInTree) };\n }\n };\n return {\n ...prev,\n gridRoot: selectActiveInTree(prev.gridRoot),\n activePanelId: id\n };\n }\n if (prev.activePanelId === id) return prev; // no-op for minimized\n return { ...prev, activePanelId: id };\n });\n };\n\n\n // State transitions shared by more than one action. Each takes the previous state and returns\n // the next one (or `prev` itself when there is nothing to do), so an action can chain them\n // inside a single `setState` — maximizing a minimized panel is restore, then float, then\n // maximize, and must not render the intermediate states.\n\n /** Brings a minimized panel back where it was: its old floating rect, or its old group. */\n const applyRestore = (prev: WorkspaceState, id: string, activate: boolean): WorkspaceState => {\n const panel = prev.panels[id];\n if (!panel || panel.state !== 'minimized') return prev;\n\n const nextMinimized = prev.minimized.filter(m => m.id !== id);\n const prevState = panel.previousState || 'docked';\n // A restored panel is, by definition, visible again — so unlike the minimize path there is\n // nothing to derive: it is itself the only correct candidate. Leaving activePanelId behind\n // reproduced the 6de3381 defect class in reverse (visible tab rendered unfocused, and every\n // contributed control stayed bound to whatever replaced this panel while it was minimized).\n const nextActive = activate ? id : prev.activePanelId;\n const entry = registry.get(panel.component);\n\n const floatBack = (): WorkspaceState => {\n maxZRef.current += 1;\n const favPos = panel.lastFloatingRect || entry?.defaultOptions?.favoritePosition || { x: 300, y: 150, width: 450, height: 350 };\n const cascaded = getCascadedPosition(favPos, prev.floating);\n return {\n ...prev,\n minimized: nextMinimized,\n floating: [\n ...prev.floating,\n {\n ...cascaded,\n id,\n z: maxZRef.current,\n anchor: panel.lastFloatingRect?.anchor ?? null\n }\n ],\n panels: { ...prev.panels, [id]: { ...panel, state: 'floating' } },\n activePanelId: nextActive\n };\n };\n\n if (prevState === 'floating') return floatBack();\n\n if (panel.lastLeafId && hasLeaf(prev.gridRoot, panel.lastLeafId)) {\n return {\n ...prev,\n minimized: nextMinimized,\n gridRoot: addPanelToLeaf(prev.gridRoot, panel.lastLeafId, id),\n panels: { ...prev.panels, [id]: { ...panel, state: 'docked' } },\n activePanelId: nextActive\n };\n }\n // Leaf group ceased to exist: float it instead if floatable!\n if (entry?.defaultOptions?.canDrag !== false) return floatBack();\n\n // Leaf group ceased to exist but not floatable: dock into fallback leaf group\n const targetLeafId = findFirstLeafId(prev.gridRoot) || 'group-default';\n return {\n ...prev,\n minimized: nextMinimized,\n gridRoot: addPanelToLeaf(prev.gridRoot, targetLeafId, id),\n panels: { ...prev.panels, [id]: { ...panel, state: 'docked' } },\n activePanelId: nextActive\n };\n };\n\n /** Turns a docked panel into a floating window. Refused for `canDrag: false` panels. */\n const applyFloat = (\n prev: WorkspaceState,\n id: string,\n { rect, anchor, activate = true }: { rect?: { x: number; y: number; width: number; height: number }; anchor?: FloatAnchor | null; activate?: boolean } = {},\n ): WorkspaceState => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n const entry = registry.get(panel.component);\n if (entry?.defaultOptions?.canDrag === false) return prev;\n\n const favPos = rect || entry?.defaultOptions?.favoritePosition || DEFAULT_FLOAT_RECT;\n const cleanRoot = removePanelFromTree(prev.gridRoot, id);\n // Floating an already-floating panel re-places it rather than adding a second window.\n const otherWindows = prev.floating.filter(w => w.id !== id);\n maxZRef.current += 1;\n const cascaded = getCascadedPosition(favPos, otherWindows);\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: cleanRoot || { type: 'leaf', id: 'group-default', panels: [], activePanelId: null },\n floating: [...otherWindows, { ...cascaded, id, z: maxZRef.current, anchor: anchor ?? null }],\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'floating' }\n }\n };\n return { ...next, activePanelId: resolveActivePanelId(next, activate ? id : null) };\n };\n\n /** Docks a panel into `targetLeafId`, or the first group when that id is missing. */\n const applyDock = (prev: WorkspaceState, id: string, targetLeafId?: string, activate = true): WorkspaceState => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n const nextFloating = prev.floating.filter(w => w.id !== id);\n const cleanRoot = removePanelFromTree(prev.gridRoot, id) || EMPTY_LEAF;\n // The caller asked for this panel to be docked, so an id that no longer names a group\n // falls back to the first one rather than docking it nowhere. Removing the panel can\n // itself delete the requested group, which is why this is checked against `cleanRoot`.\n const requested = targetLeafId && hasLeaf(cleanRoot, targetLeafId) ? targetLeafId : undefined;\n const leafId = requested || findFirstLeafId(cleanRoot) || EMPTY_LEAF.id;\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: addPanelToLeaf(cleanRoot, leafId, id),\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'docked' }\n }\n };\n return { ...next, activePanelId: resolveActivePanelId(next, activate ? id : null) };\n };\n\n const openPanel = <P extends object = Record<string, unknown>>(id: string, component: string, options?: OpenPanelOptions<P>) => {\n // Dedup redirect: resolve to an already-open panel of the same component/dedupeKey, if any,\n // before anything else runs — the caller's own `id`/`props` are ignored for this call in\n // that case, the same way re-opening an already-open exact `id` already focuses it instead\n // of duplicating it.\n let resolvedId = id;\n if (options?.dedupeKey !== undefined) {\n const match = Object.values(stateRef.current.panels).find(\n p => p.component === component && p.dedupeKey === options.dedupeKey\n );\n if (match) resolvedId = match.id;\n }\n const isNew = !(resolvedId in stateRef.current.panels);\n const isRedirect = resolvedId !== id;\n const shouldFocus = options?.focus !== false;\n const propsProvided = options?.props !== undefined;\n const serializable = propsProvided ? isSerializable(options.props) : true;\n\n // Re-opening a minimized panel is a restore, and must land where `restorePanel` would: its\n // old group or floating rect. This used to re-place it from the registry's initial target\n // (the first group, or the default floating position) and publish nothing, so an autosave\n // keyed on `layout:changed` missed it. An explicit `initialTarget` still wins.\n if (stateRef.current.panels[resolvedId]?.state === 'minimized') {\n const explicitTarget = options?.initialTarget;\n setState(prev => {\n const restored = applyRestore(prev, resolvedId, shouldFocus);\n const state = restored.panels[resolvedId]?.state;\n if (explicitTarget === 'floating' && state === 'docked') {\n return applyFloat(restored, resolvedId, { activate: shouldFocus });\n }\n if (explicitTarget && explicitTarget !== 'floating' && state === 'floating') {\n return applyDock(restored, resolvedId, undefined, shouldFocus);\n }\n return restored;\n });\n eventBusRef.current.publish('panel:restored', { id: resolvedId });\n eventBusRef.current.publish('layout:changed', {});\n return;\n }\n\n const dockTo = options?.dockTo;\n if (dockTo && isNew && process.env.NODE_ENV === 'development' && !findLeafIdOf(stateRef.current.gridRoot, dockTo.panel)) {\n console.warn(\n `[react-dockable-desktop] openPanel(\"${resolvedId}\") could not dock beside \"${dockTo.panel}\": ` +\n `that panel is not docked (not open, floating or minimized), so the new panel was placed as usual.`\n );\n }\n\n setState(prev => {\n const exists = prev.panels[resolvedId];\n const entry = registry.get(component);\n const title = options?.title || entry?.defaultOptions?.title || resolvedId;\n const target = options?.initialTarget || entry?.defaultOptions?.initialTarget || 'docked';\n const favPos = entry?.defaultOptions?.favoritePosition || { x: 300, y: 150, width: 450, height: 350 };\n const activePanelId = shouldFocus ? resolvedId : prev.activePanelId;\n\n // Case 1: Already exists (a minimized one was handled above, before this update)\n if (exists) {\n if (exists.state === 'minimized') {\n return applyRestore(prev, resolvedId, shouldFocus);\n } else if (exists.state === 'floating') {\n if (shouldFocus) focusPanel(resolvedId);\n return prev;\n } else {\n // Focus in tab group\n const selectActiveInTree = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.panels.includes(resolvedId)) {\n return { ...node, activePanelId: resolvedId };\n }\n return node;\n } else {\n return { ...node, children: node.children.map(selectActiveInTree) };\n }\n };\n return {\n ...prev,\n gridRoot: selectActiveInTree(prev.gridRoot),\n activePanelId\n };\n }\n }\n\n // Case 2: New panel. `dockTo` beside a docked panel wins over the target.\n const dockLeaf = dockTo ? findLeafIdOf(prev.gridRoot, dockTo.panel) : null;\n const targetState = dockLeaf ? 'docked' : (target === 'tabbed' ? 'docked' : target);\n const newPanelInfo: PanelInfo = {\n id: resolvedId,\n title,\n component,\n state: targetState,\n props: options?.props as Record<string, unknown> | undefined,\n serializable,\n dedupeKey: options?.dedupeKey,\n };\n const nextPanels = { ...prev.panels, [resolvedId]: newPanelInfo };\n\n if (dockTo && dockLeaf) {\n const share = Math.min(0.9, Math.max(0.1, dockTo.size ?? prev.splitRatio));\n return {\n ...prev,\n gridRoot: dockTo.position === 'center'\n ? addPanelToLeaf(prev.gridRoot, dockLeaf, resolvedId)\n : splitLeafInTree(prev.gridRoot, dockLeaf, resolvedId, dockTo.position, share),\n panels: nextPanels,\n activePanelId\n };\n }\n\n if (target === 'floating') {\n maxZRef.current += 1;\n const cascaded = getCascadedPosition(favPos, prev.floating);\n\n const anchor = options?.anchor ?? entry?.defaultOptions?.defaultAnchor ?? null;\n\n return {\n ...prev,\n floating: [...prev.floating, { ...cascaded, id: resolvedId, z: maxZRef.current, anchor }],\n panels: nextPanels,\n activePanelId\n };\n } else {\n const firstLeaf = findFirstLeafId(prev.gridRoot) || 'group-default';\n return {\n ...prev,\n gridRoot: addPanelToLeaf(prev.gridRoot, firstLeaf, resolvedId),\n panels: nextPanels,\n activePanelId\n };\n }\n });\n if (isNew) eventBusRef.current.publish('panel:opened', { id: resolvedId, component });\n if (isNew || isRedirect) eventBusRef.current.publish('layout:changed', {});\n };\n\n const closePanel = (id: string) => {\n const exists = id in stateRef.current.panels;\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n const registryEntry = registry.get(panel.component);\n if (registryEntry?.defaultOptions?.canClose === false) {\n return prev;\n }\n\n delete closeGuardsRef.current[id];\n delete stateProvidersRef.current[id];\n\n const nextPanels = { ...prev.panels };\n delete nextPanels[id];\n\n const nextRoot = removePanelFromTree(prev.gridRoot, id)\n || { type: 'leaf' as const, id: 'group-default', panels: [], activePanelId: null };\n const nextFloating = prev.floating.filter(w => w.id !== id);\n\n // Closing the active panel used to leave `activePanelId` pointing at the panel just deleted.\n // `removePanelFromTree` has already promoted the next tab in its leaf, so re-deriving picks\n // whatever the user can now actually see.\n const nextActivePanelId = prev.activePanelId === id\n ? deriveActivePanelId({ gridRoot: nextRoot, floating: nextFloating, panels: nextPanels })\n : prev.activePanelId;\n\n return {\n ...prev,\n gridRoot: nextRoot,\n floating: nextFloating,\n minimized: prev.minimized.filter(m => m.id !== id),\n panels: nextPanels,\n activePanelId: nextActivePanelId\n };\n });\n if (exists) {\n eventBusRef.current.publish('panel:closed', { id });\n eventBusRef.current.publish('layout:changed', {});\n }\n };\n\n const registerCloseGuard = (id: string, guard: () => boolean | Promise<boolean>) => {\n closeGuardsRef.current[id] = guard;\n };\n\n const unregisterCloseGuard = (id: string) => {\n delete closeGuardsRef.current[id];\n };\n\n const registerStateProvider = (id: string, provider: () => unknown) => {\n stateProvidersRef.current[id] = provider;\n };\n\n const unregisterStateProvider = (id: string) => {\n delete stateProvidersRef.current[id];\n };\n\n const setPanelDirty = (id: string, dirty: boolean, options?: DirtyStateOptions) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n if (!!panel.dirty === dirty && sameDirtyOptions(panel.dirtyOptions, options)) return prev;\n return {\n ...prev,\n panels: {\n ...prev.panels,\n [id]: { ...panel, dirty, dirtyOptions: options }\n }\n };\n });\n };\n\n const updatePanelTitle = (id: string, title: string | MessageDescriptor | (() => string)) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n if (sameTitle(panel.title, title)) return prev;\n return {\n ...prev,\n panels: {\n ...prev.panels,\n [id]: { ...panel, title }\n }\n };\n });\n };\n\n const setPanelIcon = (id: string, icon: React.ReactNode | null) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n const next = icon ?? undefined;\n if (panel.icon === next) return prev;\n return { ...prev, panels: { ...prev.panels, [id]: { ...panel, icon: next } } };\n });\n };\n\n const requestClosePanel = async (id: string, options?: { force?: boolean; onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }) => {\n if (options?.force) {\n closePanel(id);\n return;\n }\n\n // 1. Check custom close guard\n const guard = closeGuardsRef.current[id];\n if (guard) {\n const canClose = await guard();\n if (!canClose) return;\n }\n\n // 2. Check automatic dirty flag\n const panel = stateRef.current.panels[id];\n if (panel?.dirty) {\n if (options?.onConfirm) {\n const discard = await options.onConfirm(panel.dirtyOptions);\n if (!discard) return;\n } else {\n return;\n }\n }\n\n closePanel(id);\n };\n\n const minimizePanel = (id: string) => {\n const wasActive = stateRef.current.panels[id]?.state !== 'minimized' && id in stateRef.current.panels;\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel || panel.state === 'minimized') return prev;\n\n const registryEntry = registry.get(panel.component);\n if (registryEntry?.defaultOptions?.canMinimize === false) {\n return prev;\n }\n\n let lastFloatingRect: PanelInfo['lastFloatingRect'] = undefined;\n let lastLeafId: string | undefined = undefined;\n\n if (panel.state === 'floating') {\n const win = prev.floating.find(w => w.id === id);\n if (win) {\n lastFloatingRect = {\n x: Number(win.x),\n y: Number(win.y),\n width: Number(win.width),\n height: Number(win.height),\n anchor: win.anchor ?? null\n };\n }\n } else if (panel.state === 'docked') {\n const findLeafForPanel = (node: LayoutNode): string | null => {\n if (node.type === 'leaf') {\n return node.panels.includes(id) ? node.id : null;\n } else {\n for (const child of node.children) {\n const res = findLeafForPanel(child);\n if (res) return res;\n }\n return null;\n }\n };\n lastLeafId = findLeafForPanel(prev.gridRoot) ?? undefined;\n }\n\n const nextRoot = removePanelFromTree(prev.gridRoot, id)\n || { type: 'leaf' as const, id: 'group-default', panels: [], activePanelId: null };\n const nextFloating = prev.floating.filter(w => w.id !== id);\n const nextPanels: Record<string, PanelInfo> = {\n ...prev.panels,\n [id]: {\n ...panel,\n state: 'minimized',\n previousState: panel.state,\n lastFloatingRect,\n lastLeafId\n }\n };\n\n // A minimized panel is off screen but still mounted (see the persistence port in\n // WindowManager.tsx), so leaving it active kept `useActivePanelContribution()` — and every\n // contributed control — wired to a panel the user can't see. `deriveActivePanelId` skips\n // minimized panels, so this lands on whatever became visible in its place.\n const nextActivePanelId = prev.activePanelId === id\n ? deriveActivePanelId({ gridRoot: nextRoot, floating: nextFloating, panels: nextPanels })\n : prev.activePanelId;\n\n return {\n ...prev,\n gridRoot: nextRoot,\n floating: nextFloating,\n minimized: [...prev.minimized, { id, title: panel.title, component: panel.component }],\n panels: nextPanels,\n activePanelId: nextActivePanelId\n };\n });\n if (wasActive) {\n eventBusRef.current.publish('panel:minimized', { id });\n eventBusRef.current.publish('layout:changed', {});\n }\n };\n\n const restorePanel = (id: string, options?: { focus?: boolean }) => {\n const wasMinimized = stateRef.current.panels[id]?.state === 'minimized';\n const shouldFocus = options?.focus !== false;\n setState(prev => applyRestore(prev, id, shouldFocus));\n if (wasMinimized) {\n eventBusRef.current.publish('panel:restored', { id });\n eventBusRef.current.publish('layout:changed', {});\n }\n };\n\n const floatPanel = (id: string, rect?: { x: number; y: number; width: number; height: number }, anchor?: FloatAnchor | null) => {\n const panel = stateRef.current.panels[id];\n const willFloat = !!panel && registry.get(panel.component)?.defaultOptions?.canDrag !== false;\n setState(prev => applyFloat(prev, id, { rect, anchor }));\n if (willFloat) eventBusRef.current.publish('layout:changed', {});\n };\n\n const dockPanel = (id: string, targetLeafId?: string) => {\n const exists = id in stateRef.current.panels;\n setState(prev => applyDock(prev, id, targetLeafId));\n if (exists) eventBusRef.current.publish('layout:changed', {});\n };\n\n\n const setDraggedPanelId = (id: string | null) => {\n setState(prev => ({ ...prev, draggedPanelId: id }));\n };\n\n const dockPanelToGroup = (id: string, targetLeafId: string, position: DropPosition) => {\n const before = stateRef.current;\n const willMove = id in before.panels\n && hasLeaf(before.gridRoot, targetLeafId)\n && !isLoneOccupant(before.gridRoot, targetLeafId, id);\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n // Dropping a lone panel onto its own group asks for the layout it already has. Taking\n // it literally deletes the target leaf on the way in, and the split then ran against\n // the pre-removal tree, leaving the same panel in two leaves — one of them showing\n // nothing, since a panel's DOM can only live in one slot.\n if (isLoneOccupant(prev.gridRoot, targetLeafId, id)) return prev;\n\n // A group that is not in the tree cannot receive anything. Placing into it would strip\n // the panel from the layout and leave it \"open\" but in no group — visible nowhere, and\n // recoverable only by minimizing and restoring it.\n if (!hasLeaf(prev.gridRoot, targetLeafId)) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] dockPanelToGroup(\"${id}\", \"${targetLeafId}\") was ignored: ` +\n `no group with that id is in the layout. Emptying a group removes it, so an id held ` +\n `across a layout change can name a group that no longer exists.`\n );\n }\n return prev;\n }\n\n const nextFloating = prev.floating.filter(w => w.id !== id);\n // `null` from removePanelFromTree means the tree is now empty — not \"nothing was\n // removed\". Falling back to `prev.gridRoot` here is what put the panel in two leaves.\n const cleanRoot = removePanelFromTree(prev.gridRoot, id) || EMPTY_LEAF;\n\n let newRoot: LayoutNode;\n if (position === 'center') {\n newRoot = addPanelToLeaf(cleanRoot, targetLeafId, id);\n } else {\n newRoot = splitLeafInTree(cleanRoot, targetLeafId, id, position, prev.splitRatio);\n }\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: newRoot,\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'docked' }\n },\n draggedPanelId: null\n };\n return { ...next, activePanelId: resolveActivePanelId(next, id) };\n });\n if (willMove) eventBusRef.current.publish('layout:changed', {});\n };\n\n const dockPanelToWorkspaceEdge = (id: string, position: SplitDirection) => {\n const before = stateRef.current;\n const willMove = id in before.panels && removePanelFromTree(before.gridRoot, id) !== null;\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n const nextFloating = prev.floating.filter(w => w.id !== id);\n const cleanRoot = removePanelFromTree(prev.gridRoot, id);\n\n // The sole docked panel already fills the workspace, so docking it to an edge asks for\n // the layout it has. Acting on it duplicated the panel into the new edge leaf while the\n // old one still listed it, exactly as a drop on its own group did.\n if (cleanRoot === null) return prev;\n\n const newLeaf: LayoutLeafNode = {\n type: 'leaf',\n id: `group-edge-${Date.now()}-${Math.floor(Math.random() * 1000)}`,\n panels: [id],\n activePanelId: id\n };\n\n const orientation: SplitOrientation = (position === 'left' || position === 'right') ? 'horizontal' : 'vertical';\n const children = (position === 'left' || position === 'top')\n ? [newLeaf, cleanRoot]\n : [cleanRoot, newLeaf];\n\n const r = prev.edgeSplitRatio;\n const newRoot: LayoutNode = {\n type: 'branch',\n orientation,\n sizes: (position === 'left' || position === 'top') ? [r, 1 - r] : [1 - r, r],\n children\n };\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: newRoot,\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'docked' }\n },\n draggedPanelId: null\n };\n return { ...next, activePanelId: resolveActivePanelId(next, id) };\n });\n if (willMove) eventBusRef.current.publish('layout:changed', {});\n };\n\n const movePanelOrder = (panelId: string, targetLeafId: string, targetIndex: number) => {\n const before = stateRef.current;\n const willMove = panelId in before.panels\n && hasLeaf(before.gridRoot, targetLeafId)\n && !isLoneOccupant(before.gridRoot, targetLeafId, panelId);\n setState(prev => {\n const panel = prev.panels[panelId];\n if (!panel) return prev;\n\n // A lone panel dropped on its own tab strip is already where it is being sent. Today\n // the reinsertion happens to cancel out; guarded so that stays true rather than\n // depending on it.\n if (isLoneOccupant(prev.gridRoot, targetLeafId, panelId)) return prev;\n\n if (!hasLeaf(prev.gridRoot, targetLeafId)) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] movePanelOrder(\"${panelId}\", \"${targetLeafId}\") was ignored: ` +\n `no group with that id is in the layout.`\n );\n }\n return prev;\n }\n\n // 1. Remove panel from its current group in the layout tree\n const cleanRoot = removePanelFromTree(prev.gridRoot, panelId);\n\n // 2. Insert panel at specific index in target leaf ID\n const insertInLeaf = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.id === targetLeafId) {\n const remaining = node.panels.filter(p => p !== panelId);\n const index = Math.max(0, Math.min(targetIndex, remaining.length));\n const newPanels = [...remaining];\n newPanels.splice(index, 0, panelId);\n return {\n ...node,\n panels: newPanels,\n activePanelId: panelId\n };\n }\n return node;\n } else {\n return {\n ...node,\n children: node.children.map(insertInLeaf)\n };\n }\n };\n\n const newRoot = insertInLeaf(cleanRoot || EMPTY_LEAF);\n const nextFloating = prev.floating.filter(w => w.id !== panelId);\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: newRoot,\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [panelId]: { ...panel, state: 'docked' }\n },\n draggedPanelId: null\n };\n return { ...next, activePanelId: resolveActivePanelId(next, panelId) };\n });\n if (willMove) eventBusRef.current.publish('layout:changed', {});\n };\n\n const closeLeafGroup = async (leafId: string, options?: { onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }) => {\n const findLeaf = (node: LayoutNode): LayoutLeafNode | null => {\n if (node.type === 'leaf') return node.id === leafId ? node : null;\n for (const child of node.children) {\n const found = findLeaf(child);\n if (found) return found;\n }\n return null;\n };\n\n const leaf = findLeaf(stateRef.current.gridRoot);\n if (!leaf || leaf.canClose === false) return;\n\n // Closing a group closes its tabs, each through the same guarded path as the tab's own ×:\n // a close guard can refuse, and a dirty panel is kept unless `onConfirm` agrees. Removing\n // the leaf outright used to leave its panels \"open\" but in no group — rendered nowhere.\n for (const panelId of [...leaf.panels]) {\n await requestClosePanel(panelId, { onConfirm: options?.onConfirm });\n }\n\n const removeLeafFromTree = (node: LayoutNode): LayoutNode | null => {\n if (node.type === 'leaf') {\n return node.id === leafId ? null : node;\n }\n const children = node.children\n .map(c => removeLeafFromTree(c))\n .filter((c): c is LayoutNode => c !== null);\n\n if (children.length === 0) return null;\n if (children.length === 1) return children[0];\n\n // Re-normalize sizes\n const sizes = node.sizes.slice(0, children.length);\n const sum = sizes.reduce((a, b) => a + b, 0);\n return {\n ...node,\n children,\n sizes: sizes.map(s => s / sum)\n };\n };\n\n // A panel that refused to close keeps its group. An emptied `keepOnEmpty` group is still in\n // the tree at this point, and is the one case left to remove here.\n // Each closed tab already published its own layout:changed; publish here only if this step\n // changed the layout too.\n let removed = false;\n setState(prev => {\n const current = findLeaf(prev.gridRoot);\n if (!current || current.panels.length > 0) return prev;\n removed = true;\n const next: WorkspaceState = {\n ...prev,\n gridRoot: removeLeafFromTree(prev.gridRoot) || { type: 'leaf', id: 'group-default', panels: [], activePanelId: null }\n };\n return { ...next, activePanelId: resolveActivePanelId(next, null) };\n });\n if (removed) eventBusRef.current.publish('layout:changed', {});\n };\n\n const maximizePanel = (id: string) => {\n const panel = stateRef.current.panels[id];\n if (!panel) return;\n\n if (panel.state === 'minimized') {\n // \"Maximize\" on a minimized panel (the taskbar menu offers it) is restore + maximize.\n // Only floating windows maximize, so a panel that comes back docked is floated first —\n // unless it can't be dragged, in which case it is just restored to its group. The\n // taskbar menu hides the item for that case.\n setState(prev => {\n const restored = applyRestore(prev, id, true);\n if (restored === prev) return prev;\n let next = restored;\n if (restored.panels[id]?.state === 'docked') {\n next = applyFloat(restored, id);\n if (next === restored) return restored;\n }\n return {\n ...next,\n floating: next.floating.map(w => w.id === id ? { ...w, maximized: true } : w),\n activePanelId: id\n };\n });\n eventBusRef.current.publish('panel:restored', { id });\n eventBusRef.current.publish('layout:changed', {});\n return;\n }\n\n if (panel.state === 'docked') {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] maximizePanel(\"${id}\") was ignored: only floating windows can ` +\n `be maximized. Float the panel first with floatPanel(\"${id}\").`\n );\n }\n return;\n }\n\n setState(prev => ({\n ...prev,\n floating: prev.floating.map(w => w.id === id ? { ...w, maximized: !w.maximized } : w)\n }));\n };\n\n const updateSplitSizes = (path: number[], sizes: number[]) => {\n const updateInTree = (node: LayoutNode, depth: number): LayoutNode => {\n if (node.type === 'leaf') return node;\n if (depth === path.length) {\n return { ...node, sizes };\n }\n const idx = path[depth];\n const children = node.children.map((c, i) => i === idx ? updateInTree(c, depth + 1) : c);\n return { ...node, children };\n };\n\n setState(prev => ({\n ...prev,\n gridRoot: updateInTree(prev.gridRoot, 0)\n }));\n };\n\n const updateFloatingPosition = (id: string, updates: Partial<Pick<FloatingWindow, 'x' | 'y' | 'width' | 'height' | 'anchor'>>) => {\n setState(prev => ({\n ...prev,\n floating: prev.floating.map(w => w.id === id ? { ...w, ...updates } : w)\n }));\n };\n\n // Docking rules (7.9.0): what the *user* may do. The type's own canFloat / canDock first, then\n // the app's canDrop. Never consulted by the app's own API calls.\n const isDropAllowed = (panelId: string, to: PanelDropTarget): boolean => {\n const panel = stateRef.current.panels[panelId];\n if (!panel) return false;\n const options = registry.get(panel.component)?.defaultOptions;\n if (to.kind === 'float') {\n // Blocks *becoming* floating; a window that already floats may still change corner.\n if (options?.canFloat === false && panel.state !== 'floating') return false;\n } else if (options?.canDock === false) {\n return false;\n }\n if (!config.canDrop) return true;\n try {\n return config.canDrop({ panelId, component: panel.component, to }) !== false;\n } catch (e) {\n console.error('[react-dockable-desktop] canDrop threw; the move is allowed:', e);\n return true;\n }\n };\n\n const saveLayout = () => {\n const currentPanels = stateRef.current.panels;\n const excludedIds: string[] = [];\n const includedPanels: Record<string, PanelInfo> = {};\n\n // A registered state provider (see registerStateProvider) is pulled fresh on every save —\n // a panel's serializability can flip over its lifetime, so this is never cached from open\n // time for provider-backed panels. Panels with no provider keep their static open-time\n // props/serializable classification unchanged.\n for (const [id, info] of Object.entries(currentPanels)) {\n const provider = stateProvidersRef.current[id];\n const dynamicValue = provider?.();\n const hasDynamicValue = provider !== undefined && dynamicValue !== undefined;\n const effectiveProps = hasDynamicValue ? (dynamicValue as Record<string, unknown>) : info.props;\n const effectiveSerializable = hasDynamicValue ? isSerializable(dynamicValue) : info.serializable;\n\n if (effectiveSerializable) {\n // The runtime icon is a React element: never part of a saved layout.\n const { icon: _icon, ...saved } = info;\n // A function title (7.4.0) can't be saved; the restored panel takes its registered default.\n if (typeof saved.title === 'function') delete (saved as Partial<PanelInfo>).title;\n includedPanels[id] = hasDynamicValue ? { ...saved, props: effectiveProps, serializable: effectiveSerializable } : saved;\n } else {\n excludedIds.push(id);\n }\n }\n\n // Non-serializable panels are excluded from this saved snapshot — pruned from gridRoot/\n // floating/minimized too, so a restore never references a panel with no data to recreate it\n // meaningfully. This computes a derived copy for the JSON string only; none of this touches\n // stateRef/setState, so the live, on-screen workspace is completely unaffected — an excluded\n // panel keeps existing and working normally on screen, it simply won't be there after the\n // *next* loadLayout().\n let gridRoot = stateRef.current.gridRoot;\n let floating = stateRef.current.floating;\n let minimized = stateRef.current.minimized;\n for (const id of excludedIds) {\n gridRoot = removePanelFromTree(gridRoot, id) || { type: 'leaf', id: 'group-default', panels: [], activePanelId: null };\n floating = floating.filter(w => w.id !== id);\n minimized = minimized.filter(m => m.id !== id);\n }\n\n if (excludedIds.length > 0) {\n eventBusRef.current.publish('layout:panels-excluded', {\n panels: excludedIds.map(id => ({ id, component: currentPanels[id].component }))\n });\n }\n\n // Validated against the *pruned* snapshot, not the live state: if the active panel was itself\n // excluded above, or is minimized, the field is omitted entirely rather than persisted as an id\n // this payload's own `panels` doesn't contain. A restore then derives it — see\n // `deriveActivePanelId`.\n const liveActive = stateRef.current.activePanelId;\n const activePanelId = liveActive !== null && isVisibleActiveTarget(liveActive, { gridRoot, floating, panels: includedPanels })\n ? liveActive\n : null;\n\n const payload: SerializedLayout = {\n version: 2, // v2: panels may carry `props`/`dedupeKey`; the payload may omit panels the\n // live workspace still has open (see the exclusion pass above).\n ...(activePanelId !== null ? { activePanelId } : {}),\n gridRoot,\n floating,\n minimized: minimized.map(m => (typeof m.title === 'function' ? { id: m.id, component: m.component } : m)) as SerializedLayout['minimized'],\n panels: includedPanels\n };\n return JSON.stringify(payload);\n };\n\n const loadLayout = (layoutJson: string): boolean => {\n try {\n const payload = parseLayoutPayload(JSON.parse(layoutJson));\n if (!payload) return false;\n maxZRef.current = Math.max(maxZRef.current, topZ(payload.floating));\n setState(prev => {\n // A panel that stays open keeps its runtime icon: the component that set it isn't\n // re-mounted, so it wouldn't set it again.\n const panels: Record<string, PanelInfo> = {};\n for (const [id, saved] of Object.entries(payload.panels)) {\n // A panel saved without a title — it had a function title, which a layout can't hold —\n // takes its registered default title, as a newly opened one would.\n const info = saved.title ? saved : { ...saved, title: registry.get(saved.component)?.defaultOptions?.title || id };\n const was = prev.panels[id];\n panels[id] = was?.icon !== undefined && was.component === info.component ? { ...info, icon: was.icon } : info;\n }\n const titleOf = (m: { id: string; title?: PanelInfo['title'] }) => m.title || panels[m.id]?.title || m.id;\n return {\n ...prev,\n gridRoot: payload.gridRoot,\n floating: payload.floating,\n minimized: payload.minimized.map(m => (m.title ? m : { ...m, title: titleOf(m) })),\n panels,\n draggedPanelId: null,\n activePanelId: payload.activePanelId\n };\n });\n return true;\n } catch (e) {\n console.error('Failed to parse layout configuration:', e);\n return false;\n }\n };\n\n const setActivePanel = (id: string | null) => {\n setState(prev => {\n if (prev.activePanelId === id) return prev;\n return { ...prev, activePanelId: id };\n });\n };\n\n const setDirection = (dir: 'ltr' | 'rtl') => {\n setState(prev => {\n if (prev.dir === dir) return prev;\n return { ...prev, dir, isRtl: dir === 'rtl' };\n });\n };\n\n const isOpen = (id: string) => id in stateRef.current.panels;\n\n const getOpenPanelIds = () => Object.keys(stateRef.current.panels);\n\n const findPanelId = (component: string, dedupeKey: string): string | null => {\n const match = Object.values(stateRef.current.panels).find(\n p => p.component === component && p.dedupeKey === dedupeKey\n );\n return match?.id ?? null;\n };\n\n const customMenuGettersRef: { current: Map<string, () => ContextMenuItem[]> } = { current: new Map() };\n\n const showContextMenuFnRef: { current: ((options: ShowContextMenuOptions) => void) | null } = { current: null };\n const registerContextMenuFn = (fn: (options: ShowContextMenuOptions) => void) => {\n showContextMenuFnRef.current = fn;\n return () => { showContextMenuFnRef.current = null; };\n };\n // The menu is portaled out of the workspace: tell it the workspace's direction, for a menu opened\n // without an event to take it from (the menu prefers the event's target when there is one).\n const showContextMenu = (options: ShowContextMenuOptions) => {\n showContextMenuFnRef.current?.({ dir: stateRef.current.dir, ...options });\n };\n\n const registerPanelContextMenu = (panelId: string, getItems: () => ContextMenuItem[]) => {\n customMenuGettersRef.current.set(panelId, getItems);\n return () => { customMenuGettersRef.current.delete(panelId); };\n };\n\n const getPanelContextMenuItems = (panelId: string): ContextMenuItem[] =>\n customMenuGettersRef.current.get(panelId)?.() ?? [];\n\n const actions: InternalWindowActions = {\n openPanel,\n closePanel,\n minimizePanel,\n restorePanel,\n floatPanel,\n dockPanel,\n maximizePanel,\n updateSplitSizes,\n updateFloatingPosition,\n isDropAllowed,\n focusPanel,\n isOpen,\n getOpenPanelIds,\n findPanelId,\n saveLayout,\n loadLayout,\n publish,\n subscribe,\n setDraggedPanelId,\n dockPanelToGroup,\n movePanelOrder,\n closeLeafGroup,\n registerCloseGuard,\n unregisterCloseGuard,\n registerStateProvider,\n unregisterStateProvider,\n setPanelDirty,\n updatePanelTitle,\n setPanelIcon,\n requestClosePanel,\n dockPanelToWorkspaceEdge,\n setActivePanel,\n setDirection,\n registerPanelContextMenu,\n getPanelContextMenuItems,\n showContextMenu,\n registerContextMenuFn,\n };\n\n const applyProviderDefaults = (defaults: { dir?: 'ltr' | 'rtl'; zIndexBase?: number }): void => {\n if (config.dir === undefined && defaults.dir) setDirection(defaults.dir);\n if (config.zIndexBase === undefined && defaults.zIndexBase !== undefined && state.floating.length === 0) {\n maxZRef.current = defaults.zIndexBase;\n }\n };\n\n return { actions, getSnapshot, subscribeToState, applyProviderDefaults };\n}\n","import { useInsertionEffect, useRef, type RefObject } from 'react';\n\n/**\n * A ref that holds the latest `value`, for event handlers and effects to read without being\n * re-created. Never read it during render.\n *\n * It is updated in an insertion effect rather than during render (which the React Compiler rules\n * forbid, and which can publish a value from a render React then discards). Insertion effects run\n * before every layout effect of the commit, so even a child's effect, which runs before its\n * parent's, already sees this render's value.\n */\nexport function useLatestRef<T>(value: T): RefObject<T> {\n const ref = useRef(value);\n useInsertionEffect(() => { ref.current = value; });\n return ref;\n}\n","import type { ComponentType, ReactNode } from 'react';\nimport { PanelRegistry } from './components/PanelRegistry';\nimport type { PanelRegistryEntry } from './components/PanelRegistry';\nimport { createWorkspaceCore, type WorkspaceCore } from './components/WindowManagerContext';\nimport type {\n PanelDrop,\n WorkspaceActions,\n MessageFormatter,\n MessageDescriptor,\n DropPosition,\n SplitDirection,\n DirtyStateOptions,\n FloatingWindow,\n} from './components/WindowManagerContext';\nimport type { ShowContextMenuOptions } from './components/ContextMenu';\n\n/** Built-in lifecycle events always available on the workspace event bus. */\nexport interface BuiltInEvents {\n 'panel:opened': { id: string; component: string };\n 'panel:closed': { id: string };\n 'panel:minimized': { id: string };\n 'panel:restored': { id: string };\n /**\n * Fires whenever something `saveLayout()` would capture changes — open/close/minimize/restore,\n * float/dock/re-order/dock-to-edge, closing a group, maximizing a minimized panel, and an\n * `openPanel` `dedupeKey` redirect. Coalesces those into one signal for autosave-style\n * consumers, so they don't need to subscribe to separate events. Does **not** cover a\n * `registerStateProvider` callback's return value changing on its own — that's a pull, there's\n * no way to observe it changing without the panel separately notifying — nor split-ratio drags,\n * floating-window moves and resizes, or toggling a floating window's maximized state.\n */\n 'layout:changed': Record<string, never>;\n /**\n * Fires from inside `saveLayout()` itself, only when that specific call excluded at least one\n * panel (a panel whose current `props` — static or from a `registerStateProvider` — failed\n * {@link isSerializable}). A passive `PanelInfo.serializable` flag alone isn't enough for this:\n * nobody may be polling it at the exact moment a save happens and something silently drops out\n * (e.g. a floating window rendering data from a live class instance). This is deliberately just\n * a signal, not a UI opinion — decide for yourself whether that becomes a toast, a console\n * warning, or nothing.\n */\n 'layout:panels-excluded': { panels: { id: string; component: string }[] };\n}\n\n/** Per-panel definition supplied to `createWorkspace({ panels })`. */\nexport interface PanelDefinition {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: a registry holds components with different props; unknown would reject them\n component: ComponentType<any>;\n defaultOptions?: PanelRegistryEntry['defaultOptions'];\n}\n\n/** Configuration object accepted by `createWorkspace()`. */\nexport interface WorkspaceClientConfig {\n /**\n * Declarative panel catalog. Replaces imperative globalPanelRegistry.register() calls.\n * Keys are the component identifiers used in openPanel() and serialised layouts.\n */\n panels?: Record<string, PanelDefinition>;\n /**\n * Serialised layout produced by a previous saveLayout() call.\n * Pass null or omit to start with an empty canvas.\n *\n * Parsed synchronously before the first render. The restored `activePanelId` is the one the\n * snapshot recorded, or — for layouts saved before that was persisted — the selected tab of\n * the first leaf in the grid.\n */\n initialState?: string | null;\n /** Custom i18n formatter for all internal strings. */\n formatMessage?: MessageFormatter;\n /** Override any subset of the built-in predefined message catalog. */\n predefinedMessages?: Record<string, MessageDescriptor>;\n /** Initial layout direction. */\n dir?: 'ltr' | 'rtl';\n /**\n * Fraction of the target panel the new panel takes when dropped on a panel's\n * top/bottom/left/right cross target. Range 0.1–0.9. Default: 0.5.\n */\n defaultSplitRatio?: number;\n /**\n * Fraction of the workspace the new panel takes when dropped on the workspace\n * outer edge. Range 0.1–0.9. Default: 0.2.\n */\n defaultEdgeSplitRatio?: number;\n /**\n * Starting z-index for floating windows and the library's own chrome overlays\n * (context menu, toolbar flyout, modal stack, toast, workspace edge zones),\n * all of which shift together via `--rdd-z-base`. Set this above/below a host\n * app's own modal z-index range to control stacking against it. Default: 1000.\n */\n zIndexBase?: number;\n /**\n * Veto where users can move panels (7.9.0). Called for each place a dragged panel could go, and\n * for the built-in \"Float\" and \"Maximize\" menu items: return `false` and that target isn't\n * offered (its drop zone doesn't appear) and the move doesn't happen. It runs after the panel\n * type's own `canFloat` / `canDock`, and only for what the user does: the app's own calls\n * (`floatPanel`, `dockPanelToGroup`, `openPanel`) always work. Keep it fast and pure; it runs\n * while the pointer moves.\n *\n * @example\n * ```ts\n * createWorkspace({\n * panels,\n * // Nothing but tool panels in the left group.\n * canDrop: ({ component, to }) => !(to.kind === 'group' && to.leafId === 'tools' && component !== 'tool'),\n * });\n * ```\n */\n canDrop?: (drop: PanelDrop) => boolean;\n}\n\n/**\n * A workspace: the layout, every action on it, the panel registry and the event bus. Create one\n * with `createWorkspace()` outside the React tree and pass it to\n * `<DockableDesktopProvider workspace={…}>`; inside the tree, `useWorkspace()` returns it.\n *\n * Pattern: TanStack QueryClient / Redux store — configuration and imperative access live on the\n * workspace; rendering is delegated to the thin React provider.\n *\n * @remarks\n * The workspace is live from the moment it is created: calls made before any provider mounts\n * apply immediately, and a provider that mounts later shows the result.\n *\n * @example\n * const workspace = createWorkspace<MyEvents>({\n * panels: {\n * map: { component: MapPanel },\n * editor: { component: EditorPanel, defaultOptions: { title: 'Code Editor' } },\n * },\n * initialState: localStorage.getItem('layout'),\n * });\n *\n * <DockableDesktopProvider workspace={workspace}>\n * <RddDesktop />\n * </DockableDesktopProvider>\n *\n * // Imperative access from anywhere:\n * workspace.saveLayout();\n * workspace.openPanel('map-1', 'map');\n * workspace.focusPanel('map-1');\n */\n// `object`, not `Record<string, unknown>`: an event map declared as an `interface` (the form the\n// docs use) has no index signature and so never satisfied the Record constraint (TS2344).\nexport class WorkspaceClient<TUserEvents extends object = Record<string, unknown>> {\n /** Scoped panel registry — fully independent from the global singleton. */\n readonly registry: PanelRegistry;\n\n /** Serialised layout to restore on mount, or null to start with an empty canvas. */\n readonly initialState: string | null;\n\n /** Non-rendering configuration forwarded to the provider. */\n readonly config: Pick<WorkspaceClientConfig, 'formatMessage' | 'predefinedMessages' | 'dir' | 'defaultSplitRatio' | 'defaultEdgeSplitRatio' | 'zIndexBase'>;\n\n /** @internal The workspace store. Live from construction; a provider only subscribes to it. */\n readonly _core: WorkspaceCore;\n\n /** The store's actions, to which every method below forwards. */\n private get _actions(): WorkspaceActions { return this._core.actions; }\n\n constructor(config: WorkspaceClientConfig = {}) {\n this.registry = new PanelRegistry();\n this.initialState = config.initialState ?? null;\n this.config = {\n formatMessage: config.formatMessage,\n predefinedMessages: config.predefinedMessages,\n dir: config.dir,\n defaultSplitRatio: config.defaultSplitRatio,\n defaultEdgeSplitRatio: config.defaultEdgeSplitRatio,\n zIndexBase: config.zIndexBase,\n };\n\n if (config.panels) {\n for (const [id, def] of Object.entries(config.panels)) {\n this.registry.register(id, def.component, def.defaultOptions);\n }\n }\n\n // Every method is bound to this workspace, so `const { openPanel } = useWorkspace()` works —\n // destructuring a class instance's methods otherwise loses `this`.\n for (const key of Object.getOwnPropertyNames(WorkspaceClient.prototype) as Array<keyof this>) {\n const descriptor = Object.getOwnPropertyDescriptor(WorkspaceClient.prototype, key);\n if (key === 'constructor' || !descriptor || typeof descriptor.value !== 'function') continue;\n (this as Record<keyof this, unknown>)[key] = (descriptor.value as (...a: unknown[]) => unknown).bind(this);\n }\n\n this._core = createWorkspaceCore({\n registry: this.registry,\n initialState: this.initialState,\n dir: config.dir,\n zIndexBase: config.zIndexBase,\n defaultSplitRatio: config.defaultSplitRatio,\n defaultEdgeSplitRatio: config.defaultEdgeSplitRatio,\n canDrop: config.canDrop,\n });\n }\n\n private _dispatch(fn: (actions: WorkspaceActions) => void): void {\n fn(this._actions);\n }\n\n private _subscribeRaw(event: string, cb: (data: unknown) => void): () => void {\n return this._actions.subscribe(event, cb);\n }\n\n // ── Forwarding methods — mirrors the WorkspaceActions public interface ────────\n\n openPanel(...args: Parameters<WorkspaceActions['openPanel']>): void { this._actions.openPanel(...args); }\n\n closePanel(id: string): void { this._dispatch(a => a.closePanel(id)); }\n\n minimizePanel(id: string): void { this._dispatch(a => a.minimizePanel(id)); }\n\n restorePanel(...args: Parameters<WorkspaceActions['restorePanel']>): void {\n this._dispatch(a => a.restorePanel(...args));\n }\n\n floatPanel(...args: Parameters<WorkspaceActions['floatPanel']>): void {\n this._dispatch(a => a.floatPanel(...args));\n }\n\n dockPanel(...args: Parameters<WorkspaceActions['dockPanel']>): void {\n this._dispatch(a => a.dockPanel(...args));\n }\n\n maximizePanel(id: string): void { this._dispatch(a => a.maximizePanel(id)); }\n\n /**\n * Activates the given panel regardless of its current state.\n * For floating panels: raises z-index so the window appears on top.\n * For docked panels: selects the tab within its leaf group.\n */\n focusPanel(id: string): void { this._dispatch(a => a.focusPanel(id)); }\n\n /** Returns `true` if a panel with this ID is currently open. */\n isOpen(id: string): boolean { return this._actions.isOpen(id); }\n\n /** Returns the IDs of all currently open panels. */\n getOpenPanelIds(): string[] { return this._actions.getOpenPanelIds(); }\n\n /** Finds an already-open panel of the given component with a matching `dedupeKey` (set via\n * `openPanel`'s `dedupeKey` option). Returns `null` if none is open. */\n findPanelId(component: string, dedupeKey: string): string | null {\n return this._actions.findPanelId(component, dedupeKey);\n }\n\n saveLayout(): string { return this._actions.saveLayout(); }\n\n loadLayout(json: string): boolean { return this._actions.loadLayout(json); }\n\n setDirection(dir: 'ltr' | 'rtl'): void { this._dispatch(a => a.setDirection(dir)); }\n\n /** Updates the split-size fractions at the given grid path. */\n updateSplitSizes(path: number[], sizes: number[]): void {\n this._dispatch(a => a.updateSplitSizes(path, sizes));\n }\n\n /** Updates position/size/anchor of a floating panel. */\n updateFloatingPosition(id: string, updates: Partial<Pick<FloatingWindow, 'x' | 'y' | 'width' | 'height' | 'anchor'>>): void {\n this._dispatch(a => a.updateFloatingPosition(id, updates));\n }\n\n /** @internal Drives the drag-in-progress visual state; normally only the library's own drag UI calls this. */\n setDraggedPanelId(id: string | null): void { this._dispatch(a => a.setDraggedPanelId(id)); }\n\n /** Docks a panel into an existing leaf group at the given drop position. */\n dockPanelToGroup(id: string, targetLeafId: string, position: DropPosition): void {\n this._dispatch(a => a.dockPanelToGroup(id, targetLeafId, position));\n }\n\n /** Reorders a panel's tab within its leaf group. */\n movePanelOrder(panelId: string, targetLeafId: string, targetIndex: number): void {\n this._dispatch(a => a.movePanelOrder(panelId, targetLeafId, targetIndex));\n }\n\n /**\n * Closes a leaf group: each of its tabs is closed through the guarded close path, then the\n * group is removed once empty. A tab whose close guard refuses — or a dirty tab that\n * `onConfirm` doesn't approve — stays open, and so does its group.\n * Resolves once every close request has been settled.\n */\n closeLeafGroup(leafId: string, options?: { onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }): Promise<void> {\n return this._actions.closeLeafGroup(leafId, options);\n }\n\n /** Registers a guard that can veto closing the given panel. */\n registerCloseGuard(id: string, guard: () => boolean | Promise<boolean>): void {\n this._dispatch(a => a.registerCloseGuard(id, guard));\n }\n\n /** Removes a previously registered close guard. */\n unregisterCloseGuard(id: string): void { this._dispatch(a => a.unregisterCloseGuard(id)); }\n\n /** Registers a callback reporting a panel's current restorable state, pulled fresh on every\n * `saveLayout()` call — see {@link BuiltInEvents}'s `'layout:panels-excluded'` doc and\n * `FormContainerContract.registerStateProvider`. */\n registerStateProvider(id: string, provider: () => unknown): void {\n this._dispatch(a => a.registerStateProvider(id, provider));\n }\n\n /** Removes a previously registered state provider. */\n unregisterStateProvider(id: string): void { this._dispatch(a => a.unregisterStateProvider(id)); }\n\n /** Sets/clears a panel's dirty (unsaved changes) flag. */\n setPanelDirty(id: string, dirty: boolean, options?: DirtyStateOptions): void {\n this._dispatch(a => a.setPanelDirty(id, dirty, options));\n }\n\n /** Updates a panel's displayed title. */\n updatePanelTitle(id: string, title: string | MessageDescriptor | (() => string)): void {\n this._dispatch(a => a.updatePanelTitle(id, title));\n }\n\n /** Sets an open panel's tab/window/taskbar icon; `null` restores its registration's icon. Not saved by `saveLayout()`. */\n setPanelIcon(id: string, icon: ReactNode | null): void {\n this._dispatch(a => a.setPanelIcon(id, icon));\n }\n\n /**\n * Requests that a panel close, honoring any registered close guard and its dirty flag: a dirty\n * panel closes only if `onConfirm` resolves `true` (without `onConfirm` it stays open).\n * `force: true` skips both. Resolves once the close (or the refusal) has been decided.\n */\n requestClosePanel(id: string, options?: { force?: boolean; onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }): Promise<void> {\n return this._actions.requestClosePanel(id, options);\n }\n\n /** Docks a panel to one of the workspace's outer edges. */\n dockPanelToWorkspaceEdge(id: string, position: SplitDirection): void {\n this._dispatch(a => a.dockPanelToWorkspaceEdge(id, position));\n }\n\n /** Shows a context menu using the app's configured ContextMenuAdapter. */\n showContextMenu(options: ShowContextMenuOptions): void { this._dispatch(a => a.showContextMenu(options)); }\n\n // ── Typed event bus ───────────────────────────────────────────────────────\n\n publish<K extends keyof (TUserEvents & BuiltInEvents)>(\n event: K,\n data: (TUserEvents & BuiltInEvents)[K]\n ): void {\n this._dispatch(a => a.publish(event as string, data));\n }\n\n subscribe<K extends keyof (TUserEvents & BuiltInEvents)>(\n event: K,\n callback: (data: (TUserEvents & BuiltInEvents)[K]) => void\n ): () => void {\n return this._subscribeRaw(event as string, callback as (data: unknown) => void);\n }\n\n // ── Lifecycle callbacks ───────────────────────────────────────────────────\n\n /** Subscribe to panel open events. Fires only for newly created panels. */\n onPanelOpen(callback: (id: string, component: string) => void): () => void {\n return this._subscribeRaw('panel:opened', data => {\n const d = data as BuiltInEvents['panel:opened'];\n callback(d.id, d.component);\n });\n }\n\n /** Subscribe to panel close events. */\n onPanelClose(callback: (id: string) => void): () => void {\n return this._subscribeRaw('panel:closed', data => {\n callback((data as BuiltInEvents['panel:closed']).id);\n });\n }\n\n /** Subscribe to panel minimize events. */\n onPanelMinimize(callback: (id: string) => void): () => void {\n return this._subscribeRaw('panel:minimized', data => {\n callback((data as BuiltInEvents['panel:minimized']).id);\n });\n }\n\n /** Subscribe to panel restore events. */\n onPanelRestore(callback: (id: string) => void): () => void {\n return this._subscribeRaw('panel:restored', data => {\n callback((data as BuiltInEvents['panel:restored']).id);\n });\n }\n\n /** Subscribe to the coalesced layout-change signal — see {@link BuiltInEvents}'s\n * `'layout:changed'` doc for exactly what it covers (and doesn't). */\n onLayoutChanged(callback: () => void): () => void {\n return this._subscribeRaw('layout:changed', () => callback());\n }\n\n /** Subscribe to notification that a `saveLayout()` call excluded one or more panels because\n * their current props weren't serializable — see {@link BuiltInEvents}'s\n * `'layout:panels-excluded'` doc. */\n onPanelsExcluded(callback: (panels: { id: string; component: string }[]) => void): () => void {\n return this._subscribeRaw('layout:panels-excluded', data => {\n callback((data as BuiltInEvents['layout:panels-excluded']).panels);\n });\n }\n}\n","import { createContext, type Context } from 'react';\nimport type { WorkspaceClient } from '../WorkspaceClient';\n\n/**\n * @internal The workspace object behind the nearest `<DockableDesktopProvider>`. `useWorkspace()`\n * reads it. Kept in its own module so the store (WindowManagerContext) and the workspace class\n * (WorkspaceClient) don't import each other at runtime.\n */\nexport const WorkspaceInstanceContext: Context<WorkspaceClient<object> | null> = createContext<WorkspaceClient<object> | null>(null);\n","import React, { createContext, useContext, useState, useCallback, useMemo, useRef } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport { usePredefinedMessages } from './WindowManagerContext';\nimport { sameTitle, sameDirtyOptions } from './sameUpdate';\nimport { useLatestRef } from '../utils/useLatestRef';\nexport type { DirtyStateOptions };\n\n/** Unique string identifier for panel/modal instances. */\nexport type OverlayId = string;\n\n/**\n * Descriptor object for localizable panel titles, supporting context translation systems.\n */\nexport interface PanelTitleDescriptor {\n /** The translation dictionary key. */\n id: string;\n /** Fallback string if translation key is missing. */\n defaultMessage?: string;\n /** Parameters to inject into the translated text string. */\n values?: Record<string, string | number>;\n}\n\n/**\n * A panel, window, drawer or modal title: a plain string, a localizable descriptor, or (7.4.0) a\n * function returning the text — called each time the title is rendered, so a title built with the\n * app's own translation function follows a language change. A function title is not saved in a\n * layout: a restored panel takes its registered default title.\n */\nexport type PanelTitle = string | PanelTitleDescriptor | (() => string);\n\n/** Configuration options applied when opening a SidePanel. */\nexport interface SidePanelOptions {\n /** Display title for the side-panel header. */\n title?: PanelTitle;\n /** Icon displayed next to the panel title. */\n icon?: React.ReactNode;\n /** Specific CSS width (e.g. 300, '40%') for the panel container. */\n width?: number | string;\n /**\n * CSS padding for the panel body content — a number (px) or any CSS value/shorthand\n * (e.g. `'10px 16px'`). Default: `0` (edge-to-edge) — pass `10` to restore the pre-v6.0.0\n * default, or any value your content needs.\n */\n bodyPadding?: number | string;\n}\n\n/** Configuration options applied when opening a Modal. */\nexport interface ModalOptions {\n /** Display title for the modal header. */\n title?: PanelTitle;\n /** Icon displayed in the modal title bar. */\n icon?: React.ReactNode;\n /** Size modifier affecting CSS max-width rules. */\n size?: 'small' | 'medium' | 'large' | 'fullscreen' | 'auto';\n /** If false, hides the modal backdrop exit click and header close button. */\n closable?: boolean;\n /**\n * CSS padding for the modal body content — a number (px) or any CSS value/shorthand\n * (e.g. `'10px 16px'`). Default: `0` (edge-to-edge) — pass `10` to restore the pre-v6.0.0\n * default, or any value your content needs.\n */\n bodyPadding?: number | string;\n}\n\n/**\n * Represents a rendered instance of a panel or modal in the layout.\n */\nexport interface OverlayInstance {\n /** Unique ID generated for this instance. */\n id: OverlayId;\n /** React Component to mount inside the panel. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: overlays of every component share this type; unknown would reject them\n Component: ComponentType<any>;\n /** Property props passed to the Component. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: read back by callers through get()/stack\n props: Record<string, any>;\n /** The target rendering layout zone. */\n containerType: 'left-panel' | 'right-panel' | 'modal';\n /** Configuration metadata settings. */\n options: SidePanelOptions | ModalOptions;\n /** True if the form container has unsaved user edits. */\n dirty?: boolean;\n /** Custom warning options applied to the automatic unsaved changes modal. */\n dirtyOptions?: DirtyStateOptions;\n}\n\n/** Stores the active layout structures for floating overlays. */\nexport interface OverlayState {\n /** The currently open left drawer panel instance, or null. */\n leftPanel: OverlayInstance | null;\n /** The currently open right drawer panel instance, or null. */\n rightPanel: OverlayInstance | null;\n /** Stack containing all active floating modal instances. */\n modals: OverlayInstance[];\n}\n\n/** Exposes methods to trigger state actions on drawers and modals. */\nexport interface PanelActions {\n /** Mounts a panel in the left-side container drawer. */\n openLeftPanel: <P extends object>(Component: ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n /** Mounts a panel in the right-side container drawer. */\n openRightPanel: <P extends object>(Component: ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n /** Pushes a new modal component instance to the top of the stack. */\n openModal: <P extends object>(Component: ComponentType<P>, props: P, options?: ModalOptions) => OverlayId;\n /** Closes an instance by ID. */\n close: (id: OverlayId) => void;\n /** Closes all drawers and modals in a single action. */\n closeAll: () => void;\n /** Closes all open modals. */\n closeAllModals: () => void;\n /** Retrieves metadata for an active instance by ID. */\n getInstance: (id: OverlayId) => OverlayInstance | undefined;\n /** Updates the props, configuration options, or dirty flag of an active panel. */\n updateInstance: (id: OverlayId, updates: Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>) => void;\n /** Flags an instance as dirty (contains unsaved changes). */\n setDirty: (id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => void;\n /** Subscribes a custom close confirmation intercept handler. */\n registerCloseHandler: (id: OverlayId, handler: () => Promise<boolean>) => void;\n /** Unsubscribes close confirmation handler. */\n unregisterCloseHandler: (id: OverlayId) => void;\n /**\n * Subscribes to an instance being removed, by any path (`close`, `closeAll`, `closeAllModals`, or\n * a side panel being replaced). Fires once; returns an unsubscribe function.\n */\n onInstanceClose: (id: OverlayId, handler: () => void) => () => void;\n}\n\nlet idCounter = 0;\nconst generateId = (): OverlayId => `panel-${++idCounter}-${Date.now()}`;\n\nconst closeHandlers = new Map<OverlayId, () => Promise<boolean>>();\n\n/** True when applying `updates` to `current` would leave every field as it is. */\nfunction changesNothing(current: OverlayInstance, updates: Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>): boolean {\n if ('props' in updates && updates.props !== current.props) return false;\n if ('dirty' in updates && !!updates.dirty !== !!current.dirty) return false;\n if ('dirtyOptions' in updates && !sameDirtyOptions(updates.dirtyOptions, current.dirtyOptions)) return false;\n if ('options' in updates && updates.options !== current.options) {\n const next = updates.options as Record<string, unknown>, prev = current.options as Record<string, unknown>;\n const keys = new Set([...Object.keys(next), ...Object.keys(prev)]);\n for (const k of keys) {\n if (k === 'title' ? !sameTitle(next[k] as never, prev[k] as never) : next[k] !== prev[k]) return false;\n }\n }\n return true;\n}\n\nconst initialState: OverlayState = {\n leftPanel: null,\n rightPanel: null,\n modals: [],\n};\n\nconst PanelStateContext = createContext<OverlayState | null>(null);\nconst PanelActionsContext = createContext<PanelActions | null>(null);\n\n/**\n * PanelProvider component manages the state and action handlers\n * for drawers (left/right) and active stacked modal overlays.\n */\nexport const PanelProvider: React.FC<{ children: ReactNode }> = ({ children }) => {\n const [state, setState] = useState<OverlayState>(initialState);\n // A message descriptor, not a string: titles are formatted when rendered, so the default title\n // follows the app's formatter and `predefinedMessages` like every other label.\n const defaultModalTitle = usePredefinedMessages().modalTitle;\n\n const stateRef = useLatestRef(state);\n\n // Close listeners per instance. Fired from the actions that remove an instance, never from an\n // unmount, so StrictMode's simulated unmount can't fire them.\n const closeListeners = useRef(new Map<OverlayId, Set<() => void>>());\n\n const onInstanceClose = useCallback((id: OverlayId, handler: () => void) => {\n const listeners = closeListeners.current;\n if (!listeners.has(id)) listeners.set(id, new Set());\n listeners.get(id)!.add(handler);\n return () => { listeners.get(id)?.delete(handler); };\n }, []);\n\n const notifyClosed = useCallback((ids: (OverlayId | undefined)[]) => {\n for (const id of ids) {\n if (!id) continue;\n const handlers = closeListeners.current.get(id);\n closeListeners.current.delete(id);\n handlers?.forEach(h => h());\n }\n }, []);\n\n const registerCloseHandler = useCallback((id: OverlayId, handler: () => Promise<boolean>) => {\n closeHandlers.set(id, handler);\n }, []);\n\n const unregisterCloseHandler = useCallback((id: OverlayId) => {\n closeHandlers.delete(id);\n }, []);\n\n const openLeftPanel = useCallback(\n async <P extends object>(\n Component: ComponentType<P>,\n props: P,\n options: SidePanelOptions = {}\n ): Promise<OverlayId | null> => {\n const currentPanel = stateRef.current.leftPanel;\n if (currentPanel) {\n const handler = closeHandlers.get(currentPanel.id);\n if (handler) {\n const canClose = await handler();\n if (!canClose) return null;\n }\n }\n\n const id = generateId();\n const instance: OverlayInstance = {\n id,\n Component: Component as OverlayInstance['Component'],\n props: props as OverlayInstance['props'],\n containerType: 'left-panel',\n options,\n };\n setState(s => ({ ...s, leftPanel: instance }));\n notifyClosed([currentPanel?.id]);\n return id;\n },\n [notifyClosed, stateRef]\n );\n\n const openRightPanel = useCallback(\n async <P extends object>(\n Component: ComponentType<P>,\n props: P,\n options: SidePanelOptions = {}\n ): Promise<OverlayId | null> => {\n const currentPanel = stateRef.current.rightPanel;\n if (currentPanel) {\n const handler = closeHandlers.get(currentPanel.id);\n if (handler) {\n const canClose = await handler();\n if (!canClose) return null;\n }\n }\n\n const id = generateId();\n const instance: OverlayInstance = {\n id,\n Component: Component as OverlayInstance['Component'],\n props: props as OverlayInstance['props'],\n containerType: 'right-panel',\n options,\n };\n setState(s => ({ ...s, rightPanel: instance }));\n notifyClosed([currentPanel?.id]);\n return id;\n },\n [notifyClosed, stateRef]\n );\n\n const openModal = useCallback(\n <P extends object>(\n Component: ComponentType<P>,\n props: P,\n options: ModalOptions = {}\n ): OverlayId => {\n const id = generateId();\n const formTitle = (props as { title?: PanelTitle }).title;\n \n const modalOptions: ModalOptions = {\n ...options,\n title: options.title || formTitle || defaultModalTitle,\n };\n\n const instance: OverlayInstance = {\n id,\n Component: Component as OverlayInstance['Component'],\n props: props as OverlayInstance['props'],\n containerType: 'modal',\n options: modalOptions,\n };\n setState(s => ({ ...s, modals: [...s.modals, instance] }));\n return id;\n },\n [defaultModalTitle]\n );\n\n const close = useCallback((id: OverlayId) => {\n setState(s => ({\n leftPanel: s.leftPanel?.id === id ? null : s.leftPanel,\n rightPanel: s.rightPanel?.id === id ? null : s.rightPanel,\n modals: s.modals.filter(m => m.id !== id),\n }));\n notifyClosed([id]);\n }, [notifyClosed]);\n\n const closeAll = useCallback(() => {\n const { leftPanel, rightPanel, modals } = stateRef.current;\n setState(initialState);\n notifyClosed([leftPanel?.id, rightPanel?.id, ...modals.map(m => m.id)]);\n }, [notifyClosed, stateRef]);\n\n const closeAllModals = useCallback(() => {\n const { modals } = stateRef.current;\n setState(s => ({ ...s, modals: [] }));\n notifyClosed(modals.map(m => m.id));\n }, [notifyClosed, stateRef]);\n\n const getInstance = useCallback(\n (id: OverlayId): OverlayInstance | undefined => {\n if (state.leftPanel?.id === id) return state.leftPanel;\n if (state.rightPanel?.id === id) return state.rightPanel;\n return state.modals.find(m => m.id === id);\n },\n [state]\n );\n\n const updateInstance = useCallback(\n (\n id: OverlayId,\n updates: Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>\n ) => {\n setState(s => {\n const target = s.leftPanel?.id === id ? s.leftPanel : s.rightPanel?.id === id ? s.rightPanel : s.modals.find(m => m.id === id);\n if (!target || changesNothing(target, updates)) return s;\n return {\n leftPanel: s.leftPanel?.id === id ? { ...s.leftPanel, ...updates } : s.leftPanel,\n rightPanel: s.rightPanel?.id === id ? { ...s.rightPanel, ...updates } : s.rightPanel,\n modals: s.modals.map(m => m.id === id ? { ...m, ...updates } : m),\n };\n });\n },\n []\n );\n\n const setDirty = useCallback((id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => {\n updateInstance(id, { dirty, dirtyOptions: options });\n }, [updateInstance]);\n\n const actions = useMemo<PanelActions>(\n () => ({\n openLeftPanel,\n openRightPanel,\n openModal,\n close,\n closeAll,\n closeAllModals,\n getInstance,\n updateInstance,\n setDirty,\n registerCloseHandler,\n unregisterCloseHandler,\n onInstanceClose,\n }),\n [\n openLeftPanel,\n openRightPanel,\n openModal,\n close,\n closeAll,\n closeAllModals,\n getInstance,\n updateInstance,\n setDirty,\n registerCloseHandler,\n unregisterCloseHandler,\n onInstanceClose,\n ]\n );\n\n return (\n <PanelStateContext.Provider value={state}>\n <PanelActionsContext.Provider value={actions}>\n {children}\n </PanelActionsContext.Provider>\n </PanelStateContext.Provider>\n );\n};\n\n/**\n * React hook to retrieve the active floating/drawer panels state.\n * @throws Error if used outside of a {@link PanelProvider}.\n */\nexport const usePanelState = (): OverlayState => {\n const ctx = useContext(PanelStateContext);\n if (!ctx) throw new Error('useModals / useSidePanels must be used within <DockableDesktopProvider>');\n return ctx;\n};\n\n/**\n * React hook to retrieve actions enabling drawer toggles and modal push actions.\n * @throws Error if used outside of a {@link PanelProvider}.\n */\nexport const usePanelActions = (): PanelActions => {\n const ctx = useContext(PanelActionsContext);\n if (!ctx) throw new Error('useModals / useSidePanels must be used within <DockableDesktopProvider>');\n return ctx;\n};\n","import React, { useCallback, useRef, useEffect, useState, useMemo } from 'react';\nimport { usePanelState, usePanelActions } from './PanelProviderContext';\nimport { FormContainerProvider, type FormContainerContract, type CloseOptions } from './FormContainerContext';\nimport type { OverlayInstance, SidePanelOptions, PanelTitle } from './PanelProviderContext';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport { useFormatMessage, formatLabel, useStyleClasses, usePredefinedMessages, useWindowManagerState } from './WindowManagerContext';\nimport ConfirmationForm from '../forms/ConfirmationForm';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { useContainerRect, type ContainerRect } from '../hooks/useContainerRect';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Props for the internal {@link SidePanelRendererItem} component.\n */\ninterface SidePanelRendererItemProps {\n /** The panel instance containing metadata, component type, and rendering state. */\n panel: OverlayInstance;\n /** Floating anchor edge side for the drawer panel. */\n position: 'left' | 'right';\n /** Default width applied if no panel override configuration is provided. */\n defaultWidth?: number | string;\n /** On-screen rect of the app's own container, or null to default to the full viewport. */\n containerRect: ContainerRect | null;\n}\n\n/**\n * SidePanelRendererItem component renders an individual left or right drawer panel instance\n * wrapped inside the FormContainerProvider context. Handles dirty state verification before close.\n */\nconst SidePanelRendererItem: React.FC<SidePanelRendererItemProps> = ({ panel, position, defaultWidth, containerRect }) => {\n const { close, openModal, updateInstance, setDirty, registerCloseHandler, unregisterCloseHandler, onInstanceClose } = usePanelActions();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const dir = useWindowManagerState(s => s.dir);\n const { sidePanelClass, sidePanelBodyClass } = useStyleClasses();\n const closeHandlerRef = useRef<(() => boolean | Promise<boolean>) | null>(null);\n\n const { id, Component, props, options, dirty, dirtyOptions } = panel;\n const panelOptions = options as SidePanelOptions;\n const [icon, setIconState] = useState<React.ReactNode>(panelOptions.icon || null);\n\n const optionsRef = useLatestRef(panelOptions);\n\n const baseTitle = formatLabel(panelOptions.title, formatMessage);\n\n const handleClose = useCallback(async (options?: CloseOptions) => {\n if (options?.force) {\n close(id);\n return;\n }\n\n if (closeHandlerRef.current) {\n const canClose = await closeHandlerRef.current();\n if (!canClose) return;\n close(id);\n return;\n }\n\n if (dirty) {\n openModal(\n ConfirmationForm,\n {\n title: dirtyOptions?.title || predefinedMessages.unsavedChangesTitle,\n message: dirtyOptions?.message || {\n id: predefinedMessages.unsavedChangesMessage.id,\n defaultMessage: predefinedMessages.unsavedChangesMessage.defaultMessage,\n values: { title: baseTitle }\n },\n alert: dirtyOptions?.alert,\n alertType: dirtyOptions?.alertType || 'danger',\n useYesNoTitles: true,\n onOK: () => close(id),\n },\n { size: 'small' }\n );\n return;\n }\n\n close(id);\n }, [close, openModal, id, dirty, dirtyOptions, baseTitle, predefinedMessages]);\n\n const canClose = useCallback(async (): Promise<boolean> => {\n if (closeHandlerRef.current) {\n return await closeHandlerRef.current();\n }\n return !dirty;\n }, [dirty]);\n\n useEffect(() => {\n registerCloseHandler(id, canClose);\n return () => unregisterCloseHandler(id);\n }, [id, canClose, registerCloseHandler, unregisterCloseHandler]);\n\n const handleSetDirty = useCallback((dirty: boolean, options?: DirtyStateOptions) => setDirty(id, dirty, options), [setDirty, id]);\n const handleSetTitle = useCallback((title: PanelTitle) => updateInstance(id, { options: { ...optionsRef.current, title } }), [updateInstance, id, optionsRef]);\n const handleSetIcon = useCallback((newIcon: React.ReactNode) => setIconState(newIcon), []);\n const handleOnCloseRequested = useCallback((handler: () => boolean | Promise<boolean>) => {\n closeHandlerRef.current = handler;\n return () => { closeHandlerRef.current = null; };\n }, []);\n\n const handleOnClose = useCallback((handler: () => void) => onInstanceClose(id, handler), [onInstanceClose, id]);\n\n const contract: FormContainerContract = useMemo(() => ({\n requestClose: handleClose,\n setDirty: handleSetDirty,\n setTitle: handleSetTitle,\n setIcon: handleSetIcon,\n onCloseRequested: handleOnCloseRequested,\n containerType: position === 'left' ? 'left-panel' : 'right-panel',\n instanceId: id,\n onClose: handleOnClose,\n }), [handleClose, handleOnClose, handleSetDirty, handleSetTitle, handleSetIcon, handleOnCloseRequested, position, id]);\n\n const displayTitle = dirty ? `${baseTitle} *` : baseTitle;\n\n // Modals sit above drawers on the shared Escape stack, so an open modal answers first; of\n // two open drawers, the one opened last does.\n useEscapeLayer(true, 'drawer', handleClose);\n\n const width = panelOptions.width || defaultWidth || 400;\n const widthStyle = typeof width === 'number' ? `${width}px` : width;\n\n const bodyPadding = panelOptions.bodyPadding;\n const bodyPaddingStyle = bodyPadding != null\n ? (typeof bodyPadding === 'number' ? `${bodyPadding}px` : bodyPadding)\n : undefined;\n\n return (\n <div\n className={`rdd-side-panel rdd-side-panel-${position} rdd-side-panel-visible ${sidePanelClass ?? ''}`}\n style={{\n width: widthStyle,\n ...(containerRect ? {\n top: containerRect.top,\n height: containerRect.height,\n bottom: 'auto',\n ...(position === 'right' ? { right: containerRect.right } : { left: containerRect.left }),\n } : {}),\n }}\n dir={dir}\n >\n <div className=\"rdd-side-panel-window\">\n <div className=\"rdd-side-panel-header\">\n {icon && <div className=\"rdd-side-panel-icon\">{icon}</div>}\n <h4 className=\"rdd-side-panel-title\">{displayTitle}</h4>\n <button\n className=\"rdd-side-panel-close-button\"\n onClick={() => handleClose()}\n title={formatMessage(predefinedMessages.closeTooltip)}\n type=\"button\"\n >\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\" />\n </svg>\n </button>\n </div>\n <div\n className={`rdd-side-panel-body ${sidePanelBodyClass ?? ''}`}\n style={bodyPaddingStyle != null ? { padding: bodyPaddingStyle } : undefined}\n >\n <FormContainerProvider value={contract}>\n <Component {...props} panelId={id} />\n </FormContainerProvider>\n </div>\n </div>\n </div>\n );\n};\n\nexport interface SidePanelRendererProps {\n /**\n * Default panel width applied when openLeftPanel/openRightPanel do not specify one.\n * Accepts a number (treated as px) or any CSS width string (e.g. '40vw').\n * Falls back to 400px if omitted.\n */\n defaultWidth?: number | string;\n}\n\n/**\n * Renders an always-present, zero-footprint anchor (`display: contents` — no box\n * of its own, no layout/visual effect) so its parent element — the container the\n * consuming app actually placed the workspace into — can be measured via\n * {@link useContainerRect}, independent of whether any panel is currently open.\n */\nconst SidePanelAnchor: React.FC<{ children: (containerRect: ContainerRect | null) => React.ReactNode }> = ({ children }) => {\n const anchorRef = useRef<HTMLDivElement>(null);\n const containerRect = useContainerRect(anchorRef);\n return <div ref={anchorRef} className=\"rdd-side-panel-anchor\">{children(containerRect)}</div>;\n};\n\n/**\n * Renders both side drawers when open. Public as `<RddSidePanels>`.\n */\nexport const SidePanelRenderer: React.FC<SidePanelRendererProps> = ({ defaultWidth }) => {\n const { leftPanel, rightPanel } = usePanelState();\n return (\n <SidePanelAnchor>\n {(containerRect) => (\n <>\n {leftPanel && <SidePanelRendererItem key={leftPanel.id} panel={leftPanel} position=\"left\" defaultWidth={defaultWidth} containerRect={containerRect} />}\n {rightPanel && <SidePanelRendererItem key={rightPanel.id} panel={rightPanel} position=\"right\" defaultWidth={defaultWidth} containerRect={containerRect} />}\n </>\n )}\n </SidePanelAnchor>\n );\n};\n\n/**\n * LeftPanelRenderer component renders ONLY the left side drawer if it is currently active.\n */\nexport const LeftPanelRenderer: React.FC<SidePanelRendererProps> = ({ defaultWidth }) => {\n const { leftPanel } = usePanelState();\n return (\n <SidePanelAnchor>\n {(containerRect) => leftPanel ? <SidePanelRendererItem key={leftPanel.id} panel={leftPanel} position=\"left\" defaultWidth={defaultWidth} containerRect={containerRect} /> : null}\n </SidePanelAnchor>\n );\n};\n\n/**\n * RightPanelRenderer component renders ONLY the right side drawer if it is currently active.\n */\nexport const RightPanelRenderer: React.FC<SidePanelRendererProps> = ({ defaultWidth }) => {\n const { rightPanel } = usePanelState();\n return (\n <SidePanelAnchor>\n {(containerRect) => rightPanel ? <SidePanelRendererItem key={rightPanel.id} panel={rightPanel} position=\"right\" defaultWidth={defaultWidth} containerRect={containerRect} /> : null}\n </SidePanelAnchor>\n );\n};\n\nexport default SidePanelRenderer;\n","import React, { useEffect, useRef } from 'react';\nimport { useFormContainer } from '../components/FormContainerContext';\nimport { useFormatMessage, usePredefinedMessages } from '../components/WindowManagerContext';\nimport { DialogIcon } from './dialogIcons';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Props for the {@link RddConfirm} component.\n */\nexport interface RddConfirmProps {\n /** Optional custom title text or localizable descriptor for the dialog container. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n title?: string | { id: string; defaultMessage?: string; values?: any } | (() => string);\n /** Main message text or localizable descriptor to display. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n message: string | { id: string; defaultMessage?: string; values?: any };\n /** Optional auxiliary top alert notification text. */\n alert?: string;\n /** Type style classification for the alert notice banner. */\n alertType?: 'info' | 'warning' | 'success' | 'danger';\n /** If true, changes action button labels to 'Yes' and 'No' instead of 'OK' and 'Cancel'. */\n useYesNoTitles?: boolean;\n /** Callback fired when the user selects the confirm button. */\n onOK?: () => void;\n /** Callback fired when the user selects the cancel button. */\n onCancel?: () => void;\n /**\n * Fired exactly once, however the dialog ends: `true` for the confirm button (or Enter),\n * `false` for the cancel button, Escape, the backdrop, the × or the modal being closed by code.\n */\n onSettled?: (ok: boolean) => void;\n /**\n * The icon left of the message. Omit it for the built-in question icon, pass `null` for none,\n * or pass your own node. It is coloured by `alertType`.\n */\n icon?: React.ReactNode | null;\n}\n\n/**\n * RddConfirm component renders a standard dialog content layout,\n * allowing users to confirm actions or abort them. Exposes action callbacks.\n */\nexport const ConfirmationForm: React.FC<RddConfirmProps> = ({\n title,\n message,\n alert,\n alertType = 'info',\n useYesNoTitles = false,\n onOK,\n onCancel,\n onSettled,\n icon,\n}) => {\n const { requestClose, setTitle, onClose } = useFormContainer();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const confirmButtonRef = useRef<HTMLButtonElement>(null);\n\n // Settle once. The container reports every close, so Escape, the backdrop, the × and a close by\n // code settle as \"not confirmed\"; after a button the guard swallows that report.\n const settledRef = useRef(false);\n const onSettledRef = useLatestRef(onSettled);\n const settle = (ok: boolean) => {\n if (settledRef.current) return;\n settledRef.current = true;\n onSettledRef.current?.(ok);\n };\n const settleRef = useLatestRef(settle);\n\n useEffect(() => onClose?.(() => settleRef.current(false)), [onClose, settleRef]);\n\n useEffect(() => {\n if (title) {\n const resolvedTitle = typeof title === 'string' ? title : typeof title === 'function' ? title() : formatMessage(title);\n setTitle(resolvedTitle);\n }\n }, [title, setTitle, formatMessage]);\n\n useEffect(() => {\n confirmButtonRef.current?.focus({ preventScroll: true });\n }, []);\n\n const resolvedMessage = typeof message === 'string' ? message : formatMessage(message);\n\n const cancelLabel = useYesNoTitles\n ? formatMessage(predefinedMessages.no)\n : formatMessage(predefinedMessages.cancel);\n\n const confirmLabel = useYesNoTitles\n ? formatMessage(predefinedMessages.yes)\n : formatMessage(predefinedMessages.ok);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n settle(true);\n onOK?.();\n requestClose();\n };\n\n const handleCancel = () => {\n settle(false);\n onCancel?.();\n requestClose();\n };\n\n return (\n <form onSubmit={handleSubmit} className=\"rdd-confirmation-form-body\">\n {alert && (\n <div className={`rdd-confirmation-alert rdd-confirmation-alert-${alertType}`}>\n <span>ℹ️</span>\n <span>{alert}</span>\n </div>\n )}\n\n <div className=\"rdd-dialog-content\">\n <DialogIcon icon={icon} type={alertType} question />\n <div className=\"rdd-confirmation-message\">\n {resolvedMessage}\n </div>\n </div>\n\n <hr className=\"rdd-confirmation-divider\" />\n\n <div className=\"rdd-confirmation-actions\">\n <button\n type=\"button\"\n className=\"rdd-btn rdd-btn-sm rdd-btn-outline\"\n onClick={handleCancel}\n data-rdd-confirm-cancel\n >\n {cancelLabel}\n </button>\n <button\n type=\"submit\"\n className=\"rdd-btn rdd-btn-sm rdd-btn-primary\"\n ref={confirmButtonRef}\n data-rdd-confirm-ok\n >\n {confirmLabel}\n </button>\n </div>\n </form>\n );\n};\n\nexport default ConfirmationForm;\n","import React from 'react';\n\n/** The four alert types the confirmation and alert dialogs take. */\nexport type DialogAlertType = 'info' | 'warning' | 'success' | 'danger';\n\n// Built-in dialog icons, drawn in currentColor so the `rdd-dialog-icon-{type}` class colours them.\n// Same 16-unit grid and stroke as the toast icons.\n\nconst QuestionIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M6.25 6.25a1.75 1.75 0 1 1 2.6 1.53c-.5.28-.85.7-.85 1.27v.2M8 11.25v.01\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"/>\n </svg>\n);\nconst InfoIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M8 5v.01M8 7.5v3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst SuccessIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5 8l2 2 4-4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"/>\n </svg>\n);\nconst WarningIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <path d=\"M8 2.5L14 13.5H2L8 2.5z\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinejoin=\"round\"/>\n <path d=\"M8 7v2.5M8 11.5v.01\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst DangerIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5.5 5.5l5 5M10.5 5.5l-5 5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\n\nconst TYPE_ICONS: Record<DialogAlertType, React.FC> = {\n info: InfoIcon,\n success: SuccessIcon,\n warning: WarningIcon,\n danger: DangerIcon,\n};\n\n/**\n * The icon slot left of a dialog's message. `icon` undefined draws the built-in icon (`question`\n * for a confirmation, the type's icon for an alert), `null` draws nothing, anything else is drawn\n * in its place.\n */\nexport const DialogIcon: React.FC<{ icon: React.ReactNode | undefined; type: DialogAlertType; question?: boolean }> = ({ icon, type, question }) => {\n if (icon === null) return null;\n const Builtin = question ? QuestionIcon : TYPE_ICONS[type];\n return (\n <div className={`rdd-dialog-icon rdd-dialog-icon-${type}`} data-rdd-dialog-icon={icon === undefined ? 'default' : 'custom'}>\n {icon === undefined ? <Builtin /> : icon}\n </div>\n );\n};\n","import { useEffect, useLayoutEffect, useRef } from 'react';\n\n/**\n * One Escape closes one overlay: the one on top.\n *\n * Every overlay used to add its own `keydown` listener to `document`. `stopPropagation()` does\n * not stop the other listeners on the same node, so a single key press closed a context menu\n * *and* the modal under it, or both side drawers at once. Overlays now register here instead,\n * and one shared listener hands each Escape to the topmost registration only.\n *\n * \"Topmost\" is by layer first — popups (context menu, toolbar flyout) above modals, modals above\n * drawers, matching how they are stacked on screen — then by registration order within a layer.\n *\n * The listener is on `document` in the bubble phase, so it runs after React's own handlers\n * (which are attached to the root container). A control that handles Escape itself — the panel\n * search box, or an app's own widget — claims it with `preventDefault()`, and the overlay stays.\n */\nexport type EscapeLayer = 'drawer' | 'modal' | 'popup';\n\nconst LAYER_RANK: Record<EscapeLayer, number> = { drawer: 1, modal: 2, popup: 3 };\n\ninterface EscapeEntry {\n layer: EscapeLayer;\n order: number;\n onEscape: () => void;\n}\n\nconst entries: EscapeEntry[] = [];\nlet nextOrder = 0;\n\nfunction handleKeyDown(e: KeyboardEvent): void {\n if (e.key !== 'Escape' || e.defaultPrevented || entries.length === 0) return;\n let top = entries[0];\n for (const entry of entries) {\n const higher = LAYER_RANK[entry.layer] - LAYER_RANK[top.layer];\n if (higher > 0 || (higher === 0 && entry.order > top.order)) top = entry;\n }\n e.preventDefault();\n top.onEscape();\n}\n\n/**\n * Registers an overlay for Escape. Returns the function that unregisters it.\n * `onEscape` may do nothing (a modal that can't be closed) — the key is still consumed, so it\n * doesn't fall through to whatever is underneath.\n */\nexport function pushEscape(layer: EscapeLayer, onEscape: () => void): () => void {\n const entry: EscapeEntry = { layer, order: nextOrder++, onEscape };\n entries.push(entry);\n if (entries.length === 1) document.addEventListener('keydown', handleKeyDown);\n return () => {\n const index = entries.indexOf(entry);\n if (index === -1) return;\n entries.splice(index, 1);\n if (entries.length === 0) document.removeEventListener('keydown', handleKeyDown);\n };\n}\n\n/**\n * Registers an overlay for Escape while `active` is true.\n *\n * The overlay's place in the stack is fixed when it becomes active; `onEscape` is read through a\n * ref, so a new callback identity on re-render does not move it to the top.\n */\nexport function useEscapeLayer(active: boolean, layer: EscapeLayer, onEscape: () => void): void {\n const onEscapeRef = useRef(onEscape);\n useLayoutEffect(() => {\n onEscapeRef.current = onEscape;\n });\n useEffect(() => {\n if (!active) return;\n return pushEscape(layer, () => onEscapeRef.current());\n }, [active, layer]);\n}\n","import { useLayoutEffect, useState, type RefObject } from 'react';\n\n/** On-screen rect of a container, in the coordinate system `position: fixed` uses. */\nexport interface ContainerRect {\n top: number;\n left: number;\n /** Distance from the viewport's right edge — what CSS `right` expects for `position: fixed`. */\n right: number;\n height: number;\n}\n\n/**\n * Tracks the live on-screen rect of `anchorRef.current`'s parent element.\n *\n * Used to keep a `position: fixed` overlay (side panel) visually confined to\n * whatever container the consuming app actually placed the workspace into,\n * instead of defaulting to the full browser viewport. `position: fixed` is\n * required so the overlay never contributes scrollable overflow to any\n * ancestor (see the side-panel autofocus scroll-jump fix), but that means it\n * no longer inherits containment from a `position: relative` ancestor the way\n * `position: absolute` did — this hook restores that containment by measuring\n * it directly. For a full-viewport app the measured rect equals the viewport,\n * so this is a no-op change from the app's perspective.\n */\nexport function useContainerRect(anchorRef: RefObject<HTMLElement | null>): ContainerRect | null {\n const [rect, setRect] = useState<ContainerRect | null>(null);\n\n useLayoutEffect(() => {\n const container = anchorRef.current?.parentElement;\n if (!container) return;\n\n const measure = () => {\n const r = container.getBoundingClientRect();\n setRect({ top: r.top, left: r.left, right: window.innerWidth - r.right, height: r.height });\n };\n measure();\n\n const resizeObserver = new ResizeObserver(measure);\n resizeObserver.observe(container);\n window.addEventListener('resize', measure);\n\n return () => {\n resizeObserver.disconnect();\n window.removeEventListener('resize', measure);\n };\n }, [anchorRef]);\n\n return rect;\n}\n","import React, { useEffect, useRef } from 'react';\nimport { useFormContainer } from '../components/FormContainerContext';\nimport { useFormatMessage, usePredefinedMessages } from '../components/WindowManagerContext';\nimport { DialogIcon } from './dialogIcons';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Props for the {@link RddAlert} component.\n */\nexport interface RddAlertProps {\n /** Optional custom title text or localizable descriptor for the dialog container. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n title?: string | { id: string; defaultMessage?: string; values?: any } | (() => string);\n /** Main message text or localizable descriptor to display. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n message: string | { id: string; defaultMessage?: string; values?: any };\n /** Picks the built-in icon and its colour. Defaults to `'info'`. */\n alertType?: 'info' | 'warning' | 'success' | 'danger';\n /**\n * The icon left of the message. Omit it for the built-in icon of `alertType`, pass `null` for\n * none, or pass your own node. It is coloured by `alertType`.\n */\n icon?: React.ReactNode | null;\n /** Label of the button. Defaults to the `ok` predefined message. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n okLabel?: string | { id: string; defaultMessage?: string; values?: any };\n /**\n * Fired exactly once, however the dialog ends: the OK button, Enter, Escape, the backdrop, the ×\n * or the modal being closed by code.\n */\n onSettled?: () => void;\n}\n\n/**\n * RddAlert shows a message with a single OK button. Open it with `useModals().open` or\n * `useModals().alert()`.\n */\nexport const AlertForm: React.FC<RddAlertProps> = ({\n title,\n message,\n alertType = 'info',\n icon,\n okLabel,\n onSettled,\n}) => {\n const { requestClose, setTitle, onClose } = useFormContainer();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const okButtonRef = useRef<HTMLButtonElement>(null);\n\n const settledRef = useRef(false);\n const onSettledRef = useLatestRef(onSettled);\n const settle = () => {\n if (settledRef.current) return;\n settledRef.current = true;\n onSettledRef.current?.();\n };\n const settleRef = useLatestRef(settle);\n\n useEffect(() => onClose?.(() => settleRef.current()), [onClose, settleRef]);\n\n useEffect(() => {\n if (title) {\n const resolvedTitle = typeof title === 'string' ? title : typeof title === 'function' ? title() : formatMessage(title);\n setTitle(resolvedTitle);\n }\n }, [title, setTitle, formatMessage]);\n\n useEffect(() => {\n okButtonRef.current?.focus({ preventScroll: true });\n }, []);\n\n const resolvedMessage = typeof message === 'string' ? message : formatMessage(message);\n const resolvedOk = okLabel === undefined\n ? formatMessage(predefinedMessages.ok)\n : typeof okLabel === 'string' ? okLabel : formatMessage(okLabel);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n settle();\n requestClose({ force: true });\n };\n\n return (\n <form onSubmit={handleSubmit} className=\"rdd-confirmation-form-body\">\n <div className=\"rdd-dialog-content\">\n <DialogIcon icon={icon} type={alertType} />\n <div className=\"rdd-confirmation-message\">\n {resolvedMessage}\n </div>\n </div>\n\n <hr className=\"rdd-confirmation-divider\" />\n\n <div className=\"rdd-confirmation-actions\">\n <button\n type=\"submit\"\n className=\"rdd-btn rdd-btn-sm rdd-btn-primary\"\n ref={okButtonRef}\n data-rdd-alert-ok\n >\n {resolvedOk}\n </button>\n </div>\n </form>\n );\n};\n\nexport default AlertForm;\n","import React, {\n forwardRef,\n useImperativeHandle,\n useState,\n useRef,\n useEffect,\n useLayoutEffect,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { isComputedRtl } from '../utils/rtl';\nimport { enabledItems, moveMenuFocus } from '../utils/menuKeyboard';\nimport type { ContextMenuLabel, MessageFormatter, MenuItemAction } from './contextMenuTypes';\n\n// ─── Re-export shared primitives so callers don't need contextMenuTypes.ts ───\nexport type { ContextMenuLabel, MessageFormatter, MenuItemAction };\n\n// ─── Item type shapes (identical surface to former replace-react-contexify) ───\n\nexport interface ContextMenuCheckbox {\n /** Whether the checkbox column renders at all (default: true). */\n active?: boolean;\n /** Whether the item is interactive (default: true). Prefer top-level `disabled` on the item instead. */\n enabled?: boolean;\n /** Current checked state. */\n value: boolean;\n}\n\nexport interface ContextMenuSimpleItem {\n label: ContextMenuLabel;\n icon?: React.ReactNode;\n title?: ContextMenuLabel;\n checkbox?: ContextMenuCheckbox;\n action?: MenuItemAction;\n cyAction?: string;\n disabled?: boolean;\n}\n\nexport interface ContextMenuSeparator {\n separator: true;\n}\n\nexport interface ContextMenuSubMenu {\n label: ContextMenuLabel;\n title?: ContextMenuLabel;\n items?: ContextMenuItem[];\n}\n\nexport type ContextMenuItem = ContextMenuSimpleItem | ContextMenuSeparator | ContextMenuSubMenu;\n\n// ─── Imperative API ───────────────────────────────────────────────────────────\n\nexport interface ShowContextMenuOptions {\n event?: React.MouseEvent | React.TouchEvent | MouseEvent | TouchEvent;\n x?: number;\n y?: number;\n items: ContextMenuItem[];\n /**\n * The menu's direction. By default it is the direction of the element the menu was opened from\n * (the event's target); a workspace's `showContextMenu` passes its own direction for a menu\n * opened without an event. The menu is portaled to `<body>`, so it can't inherit either.\n */\n dir?: 'ltr' | 'rtl';\n /**\n * Where focus goes when the menu opens. `'menu'` (the default) focuses the menu itself, with no\n * item highlighted: ArrowDown then reaches the first item and ArrowUp the last. `'first-item'`\n * focuses the first enabled item, for a menu opened from the keyboard. When this is left out, a\n * keyboard `contextmenu` event (the ContextMenu key or Shift+F10, which report no pointer\n * position) opens on the first item and everything else, including a call with no event, on\n * the menu: the same view every time, whatever the user did before.\n */\n initialFocus?: 'menu' | 'first-item';\n}\n\nexport interface ContextMenuHandle {\n show(options: ShowContextMenuOptions): void;\n}\n\n// ─── Component props ──────────────────────────────────────────────────────────\n\nexport interface ContextMenuProps {\n theme?: string;\n animation?: string;\n formatMessageProvider?: MessageFormatter;\n onShow?: () => void;\n onHide?: () => void;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n style?: React.CSSProperties;\n}\n\n// ─── Adapter interface (strategy pattern) ────────────────────────────────────\n\nexport interface ContextMenuAdapter {\n Component: React.ForwardRefExoticComponent<\n ContextMenuProps & React.RefAttributes<ContextMenuHandle>\n >;\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────────\n\n/** A `contextmenu` event from the keyboard (ContextMenu key, Shift+F10): no pointer position. */\nfunction isKeyboardMenuEvent(event: ShowContextMenuOptions['event']): boolean {\n if (!event || 'touches' in event) return false;\n const mouse = event as MouseEvent;\n return mouse.clientX === 0 && mouse.clientY === 0;\n}\n\nfunction getCoords(\n event: ShowContextMenuOptions['event'],\n): { x: number; y: number } {\n if (!event) return { x: 0, y: 0 };\n if ('touches' in event && event.touches.length > 0) {\n return { x: event.touches[0].clientX, y: event.touches[0].clientY };\n }\n const mouse = event as MouseEvent;\n // The ContextMenu key and Shift+F10 fire `contextmenu` with no pointer position (0, 0): open\n // the menu at the focused element instead of the top-left corner of the page.\n if (mouse.clientX === 0 && mouse.clientY === 0 && mouse.target instanceof Element) {\n const r = mouse.target.getBoundingClientRect();\n if (r.width || r.height) return { x: r.left, y: r.bottom };\n }\n return { x: mouse.clientX, y: mouse.clientY };\n}\n\nfunction resolveLabel(label: ContextMenuLabel, fmt?: MessageFormatter): string {\n if (typeof label === 'string') return label;\n if (fmt) return fmt(label);\n return label.defaultMessage ?? label.id;\n}\n\nfunction isSeparator(item: ContextMenuItem): item is ContextMenuSeparator {\n return 'separator' in item;\n}\n\nfunction isSubMenu(item: ContextMenuItem): item is ContextMenuSubMenu {\n return !isSeparator(item) && 'items' in item;\n}\n\n// ─── Sub-menu panel (one-level deep) ─────────────────────────────────────────\n\n/** Where a submenu hangs from: the parent menu's physical edges, and the top of the item. */\ninterface SubMenuAnchor {\n menuLeft: number;\n menuRight: number;\n top: number;\n /** Reading direction at the item: the submenu prefers the reading-end side. */\n rtl: boolean;\n}\n\ninterface SubMenuPanelProps {\n items: ContextMenuItem[];\n /** Measures where to hang from. Called after layout and in event handlers, never in render. */\n getAnchor: () => SubMenuAnchor | null;\n /** Opened from the keyboard: focus its first item. */\n autoFocus: boolean;\n /** The key that returns to the parent item (ArrowLeft, or ArrowRight under RTL). */\n onBack: () => void;\n theme: string;\n /** The parent menu's direction: the submenu is portaled too, so it can't inherit it. */\n dir: 'ltr' | 'rtl';\n fmt?: MessageFormatter;\n onClose: () => void;\n onMouseEnter: () => void;\n onMouseLeave: () => void;\n}\n\nconst SubMenuPanel = forwardRef<HTMLDivElement, SubMenuPanelProps>(\n ({ items, getAnchor, autoFocus, onBack, theme, dir, fmt, onClose, onMouseEnter, onMouseLeave }, ref) => {\n // Placed after layout, once the panel's own width is known. It hangs off the parent menu's\n // reading-end edge (right in LTR, left in RTL) and flips to the other edge when that side\n // has no room — clamping it into the viewport instead is what laid it over the parent menu.\n useLayoutEffect(() => {\n const el = (ref as React.RefObject<HTMLDivElement>)?.current;\n const anchor = getAnchor();\n if (!el || !anchor) return;\n const PAD = 8;\n const GAP = 2;\n // Layout size, not getBoundingClientRect: the entry animation scales the panel, and a\n // scaled measurement placed a left-hanging submenu over its parent.\n const width = el.offsetWidth;\n const height = el.offsetHeight;\n const toRight = anchor.menuRight + GAP;\n const toLeft = anchor.menuLeft - GAP - width;\n const fitsRight = toRight + width <= window.innerWidth - PAD;\n const fitsLeft = toLeft >= PAD;\n let left: number;\n if (anchor.rtl) left = fitsLeft || !fitsRight ? toLeft : toRight;\n else left = fitsRight || !fitsLeft ? toRight : toLeft;\n left = Math.max(PAD, Math.min(left, window.innerWidth - width - PAD));\n const top = Math.max(PAD, Math.min(anchor.top, window.innerHeight - height - PAD));\n el.style.left = `${left}px`;\n el.style.top = `${top}px`;\n });\n\n useLayoutEffect(() => {\n if (autoFocus) enabledItems((ref as React.RefObject<HTMLDivElement>)?.current)[0]?.focus();\n }, [autoFocus, ref]);\n\n const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n const backKey = getAnchor()?.rtl ? 'ArrowRight' : 'ArrowLeft';\n if (e.key === backKey) { e.preventDefault(); e.stopPropagation(); onBack(); return; }\n if (e.key === 'Tab') { e.preventDefault(); e.stopPropagation(); onClose(); return; }\n if (moveMenuFocus(e.currentTarget, e.key)) { e.preventDefault(); e.stopPropagation(); }\n };\n\n return createPortal(\n <div\n ref={ref}\n className={`rdd-context-menu rdd-context-menu--${theme} rdd-context-menu--submenu`}\n dir={dir}\n // z-index from .rdd-context-menu--submenu (+8501) — see the main menu's note below.\n // Placed by the layout effect above before paint (its starting left/top are in the class).\n role=\"menu\"\n tabIndex={-1}\n onKeyDown={handleKeyDown}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n >\n {items.map((item, i) => {\n if (isSeparator(item)) {\n return <hr key={i} className=\"rdd-context-menu__separator\" role=\"separator\" />;\n }\n const simple = item as ContextMenuSimpleItem;\n const showChk = simple.checkbox && simple.checkbox.active !== false;\n const isChecked = showChk && simple.checkbox!.value;\n const isDisabled = simple.disabled === true || (showChk ? simple.checkbox!.enabled === false : false);\n return (\n <button\n key={i}\n type=\"button\"\n className={`rdd-context-menu__item${isDisabled ? ' rdd-context-menu__item--disabled' : ''}`}\n title={simple.title ? resolveLabel(simple.title, fmt) : undefined}\n disabled={isDisabled}\n data-cy-action={simple.cyAction}\n onClick={() => { if (!isDisabled) { simple.action?.(); onClose(); } }}\n role={showChk ? 'menuitemcheckbox' : 'menuitem'}\n aria-checked={showChk ? isChecked : undefined}\n >\n {simple.icon\n ? <span className=\"rdd-context-menu__icon\">{simple.icon}</span>\n : <span className=\"rdd-context-menu__icon\" aria-hidden=\"true\" />}\n <span className=\"rdd-context-menu__label\">{resolveLabel(simple.label, fmt)}</span>\n {showChk && (\n <span className={`rdd-context-menu__checkbox${isChecked ? ' rdd-context-menu__checkbox--checked' : ''}`} aria-hidden=\"true\">\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"0.75\" y=\"0.75\" width=\"10.5\" height=\"10.5\" rx=\"2\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n />\n {isChecked && (\n <path d=\"M2.5 6 L4.5 8.5 L9.5 3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n )}\n </svg>\n </span>\n )}\n </button>\n );\n })}\n </div>,\n document.body,\n );\n },\n);\n\nSubMenuPanel.displayName = 'ContextMenuSubMenuPanel';\n\n// ─── Main component ───────────────────────────────────────────────────────────\n\ninterface MenuState {\n visible: boolean;\n x: number;\n y: number;\n items: ContextMenuItem[];\n dir: 'ltr' | 'rtl';\n initialFocus: 'menu' | 'first-item';\n}\n\nconst CLOSED: MenuState = { visible: false, x: 0, y: 0, items: [], dir: 'ltr', initialFocus: 'menu' };\n\n/**\n * The menu is portaled to <body>, so it takes its direction from where it was opened: the event's\n * target, else the direction the caller passed (a workspace passes its own), else the page's.\n */\nfunction menuDirection(event: ShowContextMenuOptions['event'], dir: ShowContextMenuOptions['dir']): 'ltr' | 'rtl' {\n const target = event?.target;\n if (target instanceof Element) return isComputedRtl(target) ? 'rtl' : 'ltr';\n if (dir) return dir;\n return isComputedRtl(document.documentElement) ? 'rtl' : 'ltr';\n}\n\nexport const ContextMenu: React.ForwardRefExoticComponent<ContextMenuProps & React.RefAttributes<ContextMenuHandle>> = forwardRef<ContextMenuHandle, ContextMenuProps>(\n ({ theme = 'dark', formatMessageProvider, onShow, onHide, onOpenChange, className, style }, ref) => {\n const [menuState, setMenuState] = useState<MenuState>(CLOSED);\n const [submenuIndex, setSubmenuIndex] = useState<number | null>(null);\n // A submenu opened from the keyboard takes focus; one opened by hovering does not.\n const [submenuFocus, setSubmenuFocus] = useState(false);\n const menuRef = useRef<HTMLDivElement>(null);\n // Where focus was when the menu opened, so closing can hand it back (WAI-ARIA menu pattern).\n const openerRef = useRef<HTMLElement | null>(null);\n const restoreFocusRef = useRef(false);\n const submenuPanelRef = useRef<HTMLDivElement>(null);\n const itemRefs = useRef<Map<number, HTMLButtonElement | null>>(new Map());\n const timers = useRef<{\n open: ReturnType<typeof setTimeout> | null;\n close: ReturnType<typeof setTimeout> | null;\n }>({ open: null, close: null });\n\n const close = React.useCallback(() => {\n // Hand focus back to the opener only if it was inside the menu when it closed — an item's\n // action may itself have moved focus (opened a modal, say), and that must win.\n const active = document.activeElement;\n restoreFocusRef.current = !!active && (\n !!menuRef.current?.contains(active) || !!submenuPanelRef.current?.contains(active)\n );\n setMenuState(CLOSED);\n setSubmenuIndex(null);\n if (timers.current.open) clearTimeout(timers.current.open);\n if (timers.current.close) clearTimeout(timers.current.close);\n timers.current.open = null;\n timers.current.close = null;\n onHide?.();\n onOpenChange?.(false);\n }, [onHide, onOpenChange]);\n\n useImperativeHandle(ref, () => ({\n show({ event, x, y, items, dir, initialFocus }) {\n const coords = event ? getCoords(event) : { x: x ?? 0, y: y ?? 0 };\n openerRef.current = document.activeElement instanceof HTMLElement && document.activeElement !== document.body\n ? document.activeElement\n : null;\n itemRefs.current.clear();\n setMenuState({\n visible: true, x: coords.x, y: coords.y, items, dir: menuDirection(event, dir),\n initialFocus: initialFocus ?? (isKeyboardMenuEvent(event) ? 'first-item' : 'menu'),\n });\n setSubmenuIndex(null);\n setSubmenuFocus(false);\n onShow?.();\n onOpenChange?.(true);\n },\n }), [onShow, onOpenChange]);\n\n // Open: focus the menu itself (no item highlighted) or, for a keyboard-opened menu, its first\n // enabled item. Focusing an item is what made the browser's focus ring come and go with the\n // user's previous interaction. Close: return focus to the opener if the menu had it and\n // nothing else has taken it since.\n useLayoutEffect(() => {\n if (menuState.visible) {\n if (menuState.initialFocus === 'first-item') enabledItems(menuRef.current)[0]?.focus();\n else menuRef.current?.focus({ preventScroll: true });\n return;\n }\n if (!restoreFocusRef.current) return;\n restoreFocusRef.current = false;\n const opener = openerRef.current;\n const active = document.activeElement;\n if (opener?.isConnected && (!active || active === document.body)) opener.focus();\n }, [menuState.visible, menuState.items, menuState.initialFocus]);\n\n // Click-outside dismiss\n // Two listeners for full coverage:\n // pointerdown (capture) — fires before any canvas gesture handler; catches touch/stylus\n // click (bubble, window) — synthetic click survives stopPropagation on mousedown/pointerdown;\n // this is the reliable fallback for WebGL canvases (LuciadRIA, MapLibre, Three.js, etc.)\n useEffect(() => {\n if (!menuState.visible) return;\n const dismiss = (e: Event) => {\n // A click dispatched on `window` itself has no Node target, and `contains()` throws\n // for one. It is outside the menu by definition.\n if (!(e.target instanceof Node)) { close(); return; }\n if (menuRef.current?.contains(e.target as Node)) return;\n if (submenuPanelRef.current?.contains(e.target as Node)) return;\n close();\n };\n document.addEventListener('pointerdown', dismiss, { capture: true });\n window.addEventListener('click', dismiss);\n return () => {\n document.removeEventListener('pointerdown', dismiss, { capture: true });\n window.removeEventListener('click', dismiss);\n };\n }, [menuState.visible, close]);\n\n // Escape dismiss — a popup, so above any modal or drawer on the shared Escape stack.\n useEscapeLayer(menuState.visible, 'popup', close);\n\n // Viewport clamping for main menu\n useLayoutEffect(() => {\n if (!menuState.visible || !menuRef.current) return;\n const el = menuRef.current;\n const r = el.getBoundingClientRect();\n const PAD = 8;\n if (r.right > window.innerWidth - PAD) {\n el.style.left = `${Math.max(PAD, window.innerWidth - r.width - PAD)}px`;\n }\n if (r.bottom > window.innerHeight - PAD) {\n el.style.top = `${Math.max(PAD, window.innerHeight - r.height - PAD)}px`;\n }\n if (r.left < PAD) el.style.left = `${PAD}px`;\n if (r.top < PAD) el.style.top = `${PAD}px`;\n }, [menuState.visible]);\n\n if (!menuState.visible) return null;\n\n const fmt = formatMessageProvider;\n\n // Where the open sub-menu hangs from. The old computation took a distance from the right\n // edge under RTL and then used it as `left`, so the sub-menu landed far from its menu.\n const getSubmenuAnchor = (): SubMenuAnchor | null => {\n const itemEl = submenuIndex === null ? null : itemRefs.current.get(submenuIndex);\n const menuEl = menuRef.current;\n if (!itemEl || !menuEl) return null;\n const mr = menuEl.getBoundingClientRect();\n return { menuLeft: mr.left, menuRight: mr.right, top: itemEl.getBoundingClientRect().top, rtl: isComputedRtl(itemEl) };\n };\n const backToParentItem = () => {\n const parent = submenuIndex === null ? null : itemRefs.current.get(submenuIndex);\n setSubmenuIndex(null);\n setSubmenuFocus(false);\n parent?.focus();\n };\n\n function cancelOpenTimer() {\n if (timers.current.open) {\n clearTimeout(timers.current.open);\n timers.current.open = null;\n }\n }\n function cancelCloseTimer() {\n if (timers.current.close) {\n clearTimeout(timers.current.close);\n timers.current.close = null;\n }\n }\n\n function handleItemMouseEnter(index: number, item: ContextMenuItem) {\n cancelCloseTimer();\n // Switching away from a different open sub-menu\n if (submenuIndex !== null && submenuIndex !== index) {\n cancelOpenTimer();\n setSubmenuIndex(null);\n }\n if (isSubMenu(item) && item.items?.length) {\n cancelOpenTimer();\n timers.current.open = setTimeout(() => {\n // Opened by hovering: it must not take focus, even after a keyboard-opened submenu.\n setSubmenuFocus(false);\n setSubmenuIndex(index);\n }, 150);\n } else if (!isSubMenu(item)) {\n // Non-sub-menu item: close any open sub-menu after grace period\n cancelOpenTimer();\n if (submenuIndex !== null) {\n timers.current.close = setTimeout(() => setSubmenuIndex(null), 200);\n }\n }\n }\n\n const openSubmenuFromKeyboard = (index: number) => {\n cancelOpenTimer();\n cancelCloseTimer();\n setSubmenuFocus(true);\n setSubmenuIndex(index);\n };\n\n function handleMenuKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {\n if (e.key === 'Tab') { e.preventDefault(); close(); return; }\n const openKey = isComputedRtl(e.currentTarget) ? 'ArrowLeft' : 'ArrowRight';\n if (e.key === openKey) {\n const index = Number((document.activeElement as HTMLElement | null)?.dataset.menuIndex);\n const item = menuState.items[index];\n if (item && isSubMenu(item) && item.items?.length) { e.preventDefault(); openSubmenuFromKeyboard(index); }\n return;\n }\n if (moveMenuFocus(e.currentTarget, e.key)) {\n e.preventDefault();\n // Moving to another item closes an open submenu, as hovering another item does.\n if (submenuIndex !== null) setSubmenuIndex(null);\n }\n }\n\n function handleItemMouseLeave(item: ContextMenuItem) {\n cancelOpenTimer();\n if (isSubMenu(item) && item.items?.length) {\n timers.current.close = setTimeout(() => setSubmenuIndex(null), 200);\n }\n }\n\n return createPortal(\n <>\n <div\n ref={menuRef}\n className={`rdd-context-menu rdd-context-menu--${theme}${className ? ` ${className}` : ''}`}\n dir={menuState.dir}\n // No inline z-index: .rdd-context-menu's own `calc(var(--rdd-z-base, 1000) + 8500)`\n // owns it, so a WindowManagerProvider's zIndexBase actually shifts this menu (an\n // inline value here silently overrode it). Resolves to the same 9500 by default.\n style={{ left: menuState.x, top: menuState.y, ...style }}\n role=\"menu\"\n tabIndex={-1}\n aria-orientation=\"vertical\"\n onKeyDown={handleMenuKeyDown}\n >\n {menuState.items.map((item, i) => {\n if (isSeparator(item)) {\n return <hr key={i} className=\"rdd-context-menu__separator\" role=\"separator\" />;\n }\n\n if (isSubMenu(item)) {\n return (\n <button\n key={i}\n ref={el => { itemRefs.current.set(i, el); }}\n type=\"button\"\n className={`rdd-context-menu__item rdd-context-menu__item--has-submenu${submenuIndex === i ? ' rdd-context-menu__item--submenu-open' : ''}`}\n title={item.title ? resolveLabel(item.title, fmt) : undefined}\n data-menu-index={i}\n onMouseEnter={() => handleItemMouseEnter(i, item)}\n onMouseLeave={() => handleItemMouseLeave(item)}\n // Click, tap, Enter or Space. A keyboard click (detail 0) moves focus in.\n onClick={(e) => {\n if (!item.items?.length) return;\n cancelOpenTimer();\n cancelCloseTimer();\n setSubmenuFocus(e.detail === 0);\n setSubmenuIndex(submenuIndex === i && e.detail !== 0 ? null : i);\n }}\n role=\"menuitem\"\n aria-haspopup=\"true\"\n aria-expanded={submenuIndex === i}\n >\n <span className=\"rdd-context-menu__icon\" aria-hidden=\"true\" />\n <span className=\"rdd-context-menu__label\">{resolveLabel(item.label, fmt)}</span>\n <span className=\"rdd-context-menu__chevron\" aria-hidden=\"true\">›</span>\n </button>\n );\n }\n\n const simple = item as ContextMenuSimpleItem;\n const showChk = simple.checkbox && simple.checkbox.active !== false;\n const isChecked = showChk && simple.checkbox!.value;\n const isDisabled = simple.disabled === true || (showChk ? simple.checkbox!.enabled === false : false);\n\n return (\n <button\n key={i}\n ref={el => { itemRefs.current.set(i, el); }}\n data-menu-index={i}\n type=\"button\"\n className={`rdd-context-menu__item${isDisabled ? ' rdd-context-menu__item--disabled' : ''}`}\n title={simple.title ? resolveLabel(simple.title, fmt) : undefined}\n disabled={isDisabled}\n data-cy-action={simple.cyAction}\n onClick={() => { if (!isDisabled) { simple.action?.(); close(); } }}\n onMouseEnter={() => handleItemMouseEnter(i, item)}\n onMouseLeave={() => handleItemMouseLeave(item)}\n role={showChk ? 'menuitemcheckbox' : 'menuitem'}\n aria-checked={showChk ? isChecked : undefined}\n >\n {simple.icon\n ? <span className=\"rdd-context-menu__icon\">{simple.icon}</span>\n : <span className=\"rdd-context-menu__icon\" aria-hidden=\"true\" />}\n <span className=\"rdd-context-menu__label\">{resolveLabel(simple.label, fmt)}</span>\n {showChk && (\n <span className={`rdd-context-menu__checkbox${isChecked ? ' rdd-context-menu__checkbox--checked' : ''}`} aria-hidden=\"true\">\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"0.75\" y=\"0.75\" width=\"10.5\" height=\"10.5\" rx=\"2\"\n fill={isChecked ? 'currentColor' : 'none'}\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n />\n {isChecked && (\n <path d=\"M2.5 6 L4.5 8.5 L9.5 3.5\" stroke=\"white\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n )}\n </svg>\n </span>\n )}\n </button>\n );\n })}\n </div>\n\n {submenuIndex !== null && (() => {\n const sub = menuState.items[submenuIndex] as ContextMenuSubMenu;\n return (\n <SubMenuPanel\n ref={submenuPanelRef}\n items={sub.items ?? []}\n getAnchor={getSubmenuAnchor}\n autoFocus={submenuFocus}\n onBack={backToParentItem}\n theme={theme}\n dir={menuState.dir}\n fmt={fmt}\n onClose={close}\n onMouseEnter={() => cancelCloseTimer()}\n onMouseLeave={() => {\n timers.current.close = setTimeout(() => setSubmenuIndex(null), 200);\n }}\n />\n );\n })()}\n </>,\n document.body,\n );\n },\n);\n\nContextMenu.displayName = 'ContextMenu';\n\n// ─── Default adapter ──────────────────────────────────────────────────────────\n\nexport const DefaultContextMenuAdapter: ContextMenuAdapter = {\n Component: ContextMenu,\n};\n\n// ─── ContextMenuContext ────────────────────────────────────────────────────────\n// Decouples menu placement from WindowManager. Any component that renders\n// <ContextMenuProvider> makes showContextMenu available to all descendants,\n// regardless of where it sits relative to WindowManager in the tree.\n\ninterface ContextMenuContextValue {\n show: (options: ShowContextMenuOptions) => void;\n isOpen: boolean;\n}\n\nconst ContextMenuContext: React.Context<ContextMenuContextValue | null> = React.createContext<ContextMenuContextValue | null>(null);\n\nexport const ContextMenuProvider: React.FC<{\n adapter?: ContextMenuAdapter;\n children: React.ReactNode;\n} & ContextMenuProps> = ({ adapter = DefaultContextMenuAdapter, children, ...componentProps }) => {\n const menuRef = useRef<ContextMenuHandle>(null);\n const [isOpen, setIsOpen] = React.useState(false);\n const show = React.useCallback((opts: ShowContextMenuOptions) => {\n menuRef.current?.show(opts);\n }, []);\n return (\n <ContextMenuContext.Provider value={{ show, isOpen }}>\n {children}\n <adapter.Component\n ref={menuRef}\n {...componentProps}\n onShow={() => { setIsOpen(true); componentProps.onShow?.(); }}\n onHide={() => { setIsOpen(false); componentProps.onHide?.(); }}\n />\n </ContextMenuContext.Provider>\n );\n};\n\nexport function useShowContextMenu(): (options: ShowContextMenuOptions) => void {\n const ctx = React.useContext(ContextMenuContext);\n if (!ctx) throw new Error('useContextMenu must be used within <DockableDesktopProvider> or <RddContextMenu>');\n return ctx.show;\n}\n\n// Exported for the WindowManager.tsx bridge only — not re-exported from src/index.ts\nexport { ContextMenuContext };\n","export function isElementRtl(el: HTMLElement | null): boolean {\n if (!el) {\n if (typeof document !== 'undefined') {\n return (\n document.documentElement.dir?.toLowerCase() === 'rtl' ||\n document.body.dir?.toLowerCase() === 'rtl'\n );\n }\n return false;\n }\n\n // Check closest element with dir attribute\n const closestDirEl = el.closest('[dir]');\n if (closestDirEl) {\n return closestDirEl.getAttribute('dir')?.toLowerCase() === 'rtl';\n }\n\n // Fallback to document rules\n return (\n document.documentElement.dir?.toLowerCase() === 'rtl' ||\n document.body.dir?.toLowerCase() === 'rtl'\n );\n}\n\n/**\n * Whether `el` is laid out right-to-left, as the browser computes it — from a `dir` attribute on\n * any ancestor, the CSS `direction` property, or the workspace's own `setDirection`.\n *\n * Use this, not `document.documentElement.dir`, wherever a pointer delta (physical) is turned into\n * a size, side or index (logical): RTL is often set on `<body>` or a wrapper rather than `<html>`, and\n * the workspace can be RTL on an LTR page.\n */\nexport function isComputedRtl(el: Element | null | undefined): boolean {\n if (!el || typeof getComputedStyle === 'undefined') return false;\n return getComputedStyle(el).direction === 'rtl';\n}\n","/**\n * @file menuKeyboard.ts\n * @description Focus movement shared by the library's WAI-ARIA menus (the context menu and the\n * toolbar group flyout).\n */\n\n/** The enabled items of a menu element, in order. */\nexport const enabledItems = (menu: HTMLElement | null): HTMLElement[] =>\n menu ? Array.from(menu.querySelectorAll<HTMLElement>(':scope > [role^=\"menuitem\"]:not(:disabled)')) : [];\n\n/**\n * Up/Down/Home/End focus movement within one menu (WAI-ARIA menu pattern). Returns true when the\n * key was handled. Wraps around at either end; disabled items are skipped. From the menu element\n * itself (nothing highlighted), ArrowDown reaches the first item and ArrowUp the last.\n */\nexport function moveMenuFocus(menu: HTMLElement | null, key: string): boolean {\n const items = enabledItems(menu);\n if (items.length === 0) return false;\n const i = items.indexOf(document.activeElement as HTMLElement);\n let next: HTMLElement | undefined;\n if (key === 'ArrowDown') next = items[(i + 1) % items.length];\n // With the menu itself focused (i = -1, nothing highlighted yet) ArrowUp goes to the last item.\n else if (key === 'ArrowUp') next = items[i < 0 ? items.length - 1 : (i - 1 + items.length) % items.length];\n else if (key === 'Home') next = items[0];\n else if (key === 'End') next = items[items.length - 1];\n if (!next) return false;\n next.focus();\n return true;\n}\n","import React, { useContext, useState } from 'react';\nimport { WindowManagerProvider } from './WindowManagerContext';\nimport type { MessageFormatter, MessageDescriptor } from './WindowManagerContext';\nimport { PanelProvider } from './PanelProviderContext';\nimport { ToolbarProvider } from './ToolbarContext';\nimport { PanelContributionProvider } from './PanelContributionContext';\nimport { ContextMenuContext, ContextMenuProvider, DefaultContextMenuAdapter } from './ContextMenu';\nimport type { ContextMenuAdapter } from './ContextMenu';\nimport { WorkspaceClient } from '../WorkspaceClient';\nimport { WorkspaceInstanceContext } from './WorkspaceInstanceContext';\nimport type { Workspace } from '../api';\n\n/** Props for `<DockableDesktopProvider>`. */\nexport interface DockableDesktopProviderProps {\n children: React.ReactNode;\n /**\n * The workspace to render, from `createWorkspace()`. Omit it and the provider creates an empty\n * one of its own (register panels through `useWorkspace().registry`).\n */\n workspace?: Workspace<object>;\n /** Translates every built-in label. Overridden by the workspace's own `formatMessage`. */\n formatMessage?: MessageFormatter;\n /** Overrides any subset of the built-in message table. Overridden by the workspace's own `messages`. */\n messages?: Record<string, MessageDescriptor>;\n /** Initial layout direction, when the workspace doesn't set one. */\n dir?: 'ltr' | 'rtl';\n /** CSS class for the outer wrapper of every modal. */\n modalClass?: string;\n /** CSS class for the content area of every modal. */\n modalBodyClass?: string;\n /** CSS class for the outer wrapper of the side drawers. */\n sidePanelClass?: string;\n /** CSS class for the content area of the side drawers. */\n sidePanelBodyClass?: string;\n /** CSS class for the outer wrapper of floating windows. */\n windowClass?: string;\n /** CSS class for the content area of floating windows. */\n windowBodyClass?: string;\n /**\n * Starting z-index for floating windows and all of the library's chrome overlays, which shift\n * together via `--rdd-z-base`. @default 1000\n */\n zIndexBase?: number;\n /** Context menu implementation. Defaults to the built-in menu. */\n contextMenuAdapter?: ContextMenuAdapter;\n}\n\n/**\n * The one provider. Place it above everything from this library: `<RddDesktop>`, `<RddSidebar>`,\n * `<RddToolbar>`, `<RddSidePanels>`, `<RddModals>`.\n *\n * @example\n * ```tsx\n * const workspace = createWorkspace({ panels: { map: { component: MapPanel } } });\n *\n * <DockableDesktopProvider workspace={workspace}>\n * <RddSidebar tabs={tabs}>\n * <RddDesktop />\n * </RddSidebar>\n * <RddSidePanels />\n * <RddModals />\n * </DockableDesktopProvider>\n * ```\n */\nexport const DockableDesktopProvider: React.FC<DockableDesktopProviderProps> = (\n { contextMenuAdapter = DefaultContextMenuAdapter, workspace, messages, children, ...props }\n): React.ReactElement => {\n const existingCtxMenu = useContext(ContextMenuContext);\n const [ws] = useState(() => workspace ?? new WorkspaceClient<object>());\n\n const inner = (\n <WorkspaceInstanceContext.Provider value={ws}>\n <ToolbarProvider>\n <WindowManagerProvider client={ws} predefinedMessages={messages} {...props}>\n <PanelContributionProvider>\n <PanelProvider>\n {children}\n </PanelProvider>\n </PanelContributionProvider>\n </WindowManagerProvider>\n </ToolbarProvider>\n </WorkspaceInstanceContext.Provider>\n );\n\n if (existingCtxMenu !== null) return inner;\n\n return (\n <ContextMenuProvider\n adapter={contextMenuAdapter}\n formatMessageProvider={props.formatMessage}\n >\n {inner}\n </ContextMenuProvider>\n );\n};\n\n","/**\n * @file ToolbarContext.tsx\n * @description Toolbar state context — radio group selection and toggle modifier state.\n * Provided by DockableDesktopProvider; consumed via useToolbar() from anywhere in the tree.\n */\n\nimport React, { createContext, useContext, useMemo, useState } from 'react';\n\nexport interface ToolbarContextValue {\n /** Returns the active item id in a radio group, or null if none. */\n getActiveInGroup: (group: string) => string | null;\n /** Set the active item in a radio group (pass null to deselect all). */\n setActiveInGroup: (group: string, id: string | null) => void;\n /** Returns whether a toggle modifier is currently active. */\n isModifierActive: (id: string) => boolean;\n /** Explicitly set a toggle modifier's active state. */\n setModifierActive: (id: string, active: boolean) => void;\n /** Flip a toggle modifier between active and inactive. */\n toggleModifier: (id: string) => void;\n}\n\nconst ToolbarContext = createContext<ToolbarContextValue | null>(null);\n\nexport const ToolbarProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n const [radioGroups, setRadioGroups] = useState<Record<string, string | null>>({});\n const [modifiers, setModifiers] = useState<Record<string, boolean>>({});\n\n const value = useMemo<ToolbarContextValue>(() => ({\n getActiveInGroup: (group) => radioGroups[group] ?? null,\n setActiveInGroup: (group, id) => setRadioGroups(prev => ({ ...prev, [group]: id })),\n isModifierActive: (id) => modifiers[id] ?? false,\n setModifierActive: (id, active) => setModifiers(prev => ({ ...prev, [id]: active })),\n toggleModifier: (id) => setModifiers(prev => ({ ...prev, [id]: !prev[id] })),\n }), [radioGroups, modifiers]);\n\n return <ToolbarContext.Provider value={value}>{children}</ToolbarContext.Provider>;\n};\n\n/**\n * Returns toolbar state and control functions from anywhere inside\n * a `<DockableDesktopProvider>` tree.\n *\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n */\nexport function useToolbar(): ToolbarContextValue {\n const ctx = useContext(ToolbarContext);\n if (!ctx) throw new Error('useToolbar must be used within DockableDesktopProvider');\n return ctx;\n}\n","/**\n * @file PanelContributionContext.tsx\n * @description Lets any panel publish toolbar items and/or sidebar sections that\n * should only be surfaced while it is the globally active panel (`state.activePanelId`).\n * Optional, additive module — `DockableDesktopProvider` wires it up automatically.\n * Neither `<RddToolbar>` nor `<RddSidebar>` reads from this automatically; the app shell\n * merges `useActiveContribution()`'s result into its own `items`/`tabs` calls.\n */\n\nimport React, { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport type { ToolbarItem } from './Toolbar';\nimport type { SidebarTab } from './Sidebar';\nimport { usePanelId, useWindowManagerState } from './WindowManagerContext';\n\n/** A single named, labeled slot of content a panel contributes to the app's Sidebar while active. */\nexport interface PanelSidebarSection {\n id: string;\n label: string;\n icon?: React.ReactNode;\n content: React.ReactNode;\n}\n\n/**\n * What a panel publishes via `usePanelContribution()`. Both fields are optional and\n * independent — a panel may contribute only toolbar items, only sidebar sections,\n * both, or neither. The app decides what \"toolbar items\" and \"sidebar sections\" mean\n * for its own domain (map controls, document formatting, anything else).\n */\nexport interface PanelContribution {\n toolbarItems?: ToolbarItem[];\n sidebarSections?: PanelSidebarSection[];\n}\n\ntype Listener = () => void;\n\ninterface PanelContributionStore {\n publish(panelId: string, contribution: PanelContribution): () => void;\n get(panelId: string): PanelContribution | null;\n subscribe(listener: Listener): () => void;\n}\n\nfunction createPanelContributionStore(): PanelContributionStore {\n const contributions = new Map<string, PanelContribution>();\n const listeners = new Set<Listener>();\n const notify = () => listeners.forEach(l => l());\n\n return {\n publish(panelId, contribution) {\n contributions.set(panelId, contribution);\n notify();\n return () => {\n // Only clear if nothing else re-published for this id in the meantime.\n if (contributions.get(panelId) === contribution) {\n contributions.delete(panelId);\n notify();\n }\n };\n },\n get(panelId) {\n return contributions.get(panelId) ?? null;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\nconst PanelContributionContext = createContext<PanelContributionStore | null>(null);\n\n/**\n * Provider enabling `usePanelContribution()` / `useActiveContribution()`.\n * Mounted automatically by `DockableDesktopProvider` — only needed manually when\n * composing the internal provider directly without it.\n */\nexport const PanelContributionProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n const store = useMemo(() => createPanelContributionStore(), []);\n return <PanelContributionContext.Provider value={store}>{children}</PanelContributionContext.Provider>;\n};\n\n/**\n * Publish this panel's toolbar items and/or sidebar sections. Call on every render —\n * republishes automatically whenever `contribution` changes, and is cleared when the\n * panel unmounts. Memoize the object (and its array/callback contents, e.g. with\n * `useMemo`/`useCallback`) to avoid republishing on every unrelated re-render.\n *\n * Contributions are only ever surfaced while this panel is `state.activePanelId` —\n * see `useActiveContribution()`.\n *\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n * @example\n * function MapPanel() {\n * const [controller, setController] = useState<'pan' | 'draw' | 'measure'>('pan');\n * usePanelContribution({\n * toolbarItems: (['pan', 'draw', 'measure'] as const).map(id => ({\n * type: 'toggle', id, label: id, icon: icons[id],\n * active: controller === id, onToggle: () => setController(id),\n * })),\n * sidebarSections: [{ id: 'layers', label: 'Layers', content: <LayerList /> }],\n * });\n * // ...\n * }\n */\nexport function usePanelContribution(contribution: PanelContribution): void {\n const panelId = usePanelId();\n const store = useContext(PanelContributionContext);\n const cleanupRef = useRef<(() => void) | null>(null);\n\n if (!store) throw new Error('usePanelContribution must be used within <DockableDesktopProvider>');\n\n useLayoutEffect(() => {\n if (!store) return;\n cleanupRef.current?.();\n cleanupRef.current = store.publish(panelId, contribution);\n return () => {\n cleanupRef.current?.();\n cleanupRef.current = null;\n };\n }, [store, panelId, contribution]);\n}\n\n/**\n * Returns whatever the currently active panel (`state.activePanelId`) has published\n * via `usePanelContribution()`, or `null` if no panel is active or the active panel\n * hasn't contributed anything. Intended for the app shell to merge into its own\n * `<RddToolbar items={...}>` / `<RddSidebar tabs={...}>` calls.\n *\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n */\nexport function useActivePanelContribution(): PanelContribution | null {\n const activePanelId = useWindowManagerState(s => s.activePanelId);\n const store = useContext(PanelContributionContext);\n\n if (!store) throw new Error('useActiveContribution must be used within <DockableDesktopProvider>');\n\n const subscribe = useCallback(\n (onChange: Listener) => (store ? store.subscribe(onChange) : () => {}),\n [store]\n );\n const getSnapshot = () => (store && activePanelId ? store.get(activePanelId) : null);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * Converts a contributed sidebar section into a `SidebarTab` for `<RddSidebar tabs={...}>`.\n * `SidebarTab.icon` is optional but recommended unless the tab is `hidden`; supply\n * `fallbackIcon` for sections that omit one.\n * `eagerMount`/`preserveState` have no contribution-side equivalent — a contribution\n * only exists while its owning panel is mounted and active, so both are left unset.\n */\nexport function sidebarSectionToTab(section: PanelSidebarSection, fallbackIcon: React.ReactNode = null): SidebarTab {\n return {\n id: section.id,\n label: section.label,\n icon: section.icon ?? fallbackIcon,\n renderContent: () => section.content,\n };\n}\n\n/**\n * Convenience wrapper around `useActiveContribution()` for the common case:\n * append the active panel's contributed toolbar items (behind a separator) to a\n * static list. Returns `staticItems` unchanged when there's nothing to add.\n * For manual control (a different merge position, no separator, etc.), call\n * `useActiveContribution()` directly instead.\n */\nexport function useMergedToolbarItems(staticItems: ToolbarItem[]): ToolbarItem[] {\n const active = useActivePanelContribution();\n return active?.toolbarItems?.length\n ? [...staticItems, { type: 'separator' }, ...active.toolbarItems]\n : staticItems;\n}\n\n/**\n * Convenience wrapper around `useActiveContribution()` for the common case:\n * append the active panel's contributed sidebar sections (via `sectionToTab`)\n * to a static tab list, as dynamic tabs that appear only while their panel is active.\n * Returns `staticTabs` unchanged when there's nothing to add.\n */\nexport function useMergedSidebarTabs(staticTabs: SidebarTab[], fallbackIcon: React.ReactNode = null): SidebarTab[] {\n const active = useActivePanelContribution();\n return active?.sidebarSections?.length\n ? [...staticTabs, ...active.sidebarSections.map(section => sidebarSectionToTab(section, fallbackIcon))]\n : staticTabs;\n}\n","/**\n * @file WindowManager.tsx\n * @description Core component for react-dockable-desktop layout engine.\n * Renders the workspace desktop containing docked splits, tabbed panels, floated windows,\n * resize handles, context menus, and taskbar docks. Exposes lifecycle event listeners.\n */\n\nimport React, { useState, useRef, useEffect, useCallback, useContext } from 'react';\nimport { useIsClient } from '../utils/useIsClient';\nimport type { TabContentProps } from '../types';\nimport { forgetPanelDom } from './domPreservation';\nimport { usePanelHost } from './workspace/panelHost';\nimport { claimDocumentMirror, releaseDocumentMirror } from '../utils/documentMirror';\nimport { WindowStoreSyncContext, useWindowManagerState, useWindowManagerActionsInternal, useFormatMessage, formatLabel, usePredefinedMessages, useStyleClasses, useRegistry } from './WindowManagerContext';\nimport { DefaultContextMenuAdapter, ContextMenuContext } from './ContextMenu';\nimport type { ContextMenuHandle, ContextMenuAdapter } from './ContextMenu';\nimport { usePanelActions } from './PanelProviderContext';\nimport ConfirmationForm from '../forms/ConfirmationForm';\nimport { useColorScheme } from '../hooks/useColorScheme';\nimport { PanelMount } from './workspace/panelMount';\nimport { DragGhost } from './workspace/DragGhost';\nimport { WorkspaceGrid } from './workspace/WorkspaceGrid';\nimport { WorkspaceZones } from './workspace/WorkspaceZones';\nimport { FloatingWindows } from './workspace/FloatingWindows';\nimport { Taskbar, type HoveredMinimized } from './workspace/Taskbar';\nimport { useDragTargets } from './workspace/useDragTargets';\nimport { createTabDrag } from './workspace/tabDrag';\nimport { createWorkspaceMenus } from './workspace/workspaceMenus';\nimport { useWorkspaceSize } from './workspace/useWorkspaceSize';\nimport { createFloatingWindowDrag } from './workspace/floatingWindowDrag';\n\n\n\n// ==========================================\n// 5. WindowManager (Main Render Component)\n// ==========================================\n\n/** Controls when the minimized-panel taskbar is visible. */\nexport type TaskbarVisibility = 'always' | 'compact' | 'autohide';\n\n/** Props for `<RddDesktop>`. */\nexport interface RddDesktopProps {\n /** Built-in skin name or a custom skin key registered via CSS. @default 'vscode' */\n skin?: string;\n /** Fallback icon shown in panel tabs when no panel-specific icon is provided. */\n defaultPanelIcon?: React.ReactNode;\n /**\n * Controls taskbar visibility.\n * - `'always'` — permanent bar at the bottom\n * - `'compact'` — only visible when minimized panels exist\n * - `'autohide'` — overlay bar with 8 px peek strip (default)\n * @default 'autohide'\n */\n taskbarVisibility?: TaskbarVisibility;\n /** Enables the library's own transitions/animations (tab hover, dock preview, etc.). Never affects the consumer's own page. @default true */\n animations?: boolean;\n /**\n * What the workspace shows while no panel is docked: a welcome screen, a \"pick a file\" prompt.\n * It fills the empty group in place of the built-in message; the group stays a drop target, so a\n * floating window can still be docked into it. Floating windows still show over it. (7.8.0)\n */\n emptyWorkspace?: React.ReactNode;\n /**\n * Your own content for each tab in the grid: an icon, the title, a badge, a status dot (7.10.0).\n * It replaces the built-in icon, title and dirty marker; the tab itself (dragging, keyboard,\n * accessibility, its context menu, header actions and close button) stays the library's.\n * Called with the tab's `TabContentProps`; branch on `component` for a per-type look.\n */\n renderTabContent?: (tab: TabContentProps) => React.ReactNode;\n}\n\n/**\n * The desktop itself: the docked grid of tab groups, the floating windows, the taskbar of\n * minimized panels, and the drop targets while a panel is dragged. Render it inside\n * `<DockableDesktopProvider>`, in a container that gives it a size (`rdd-fill-viewport` fills the\n * page), and import `react-dockable-desktop/styles.css` once.\n *\n * Exported as `RddDesktop`.\n *\n * @example\n * ```tsx\n * <DockableDesktopProvider workspace={workspace}>\n * <div className=\"rdd-fill-viewport\">\n * <RddDesktop skin=\"vscode\" taskbarVisibility=\"autohide\" />\n * </div>\n * <RddModals />\n * </DockableDesktopProvider>\n * ```\n */\nexport const WindowManager: React.FC<RddDesktopProps> = ({ skin = 'vscode', defaultPanelIcon, taskbarVisibility = 'autohide', animations = true, emptyWorkspace, renderTabContent }) => {\n // The context menu comes from <DockableDesktopProvider contextMenuAdapter={…}>. This built-in\n // fallback only renders when no provider supplies one (the library's own tests).\n const contextMenuAdapter: ContextMenuAdapter = DefaultContextMenuAdapter;\n const state = useWindowManagerState();\n const panelHost = usePanelHost();\n const registry = useRegistry();\n const { restorePanel, minimizePanel, requestClosePanel, maximizePanel, updateFloatingPosition, focusPanel, floatPanel, setDraggedPanelId, dockPanelToGroup, movePanelOrder, dockPanelToWorkspaceEdge, setActivePanel, getPanelContextMenuItems, showContextMenu, registerContextMenuFn, isDropAllowed } = useWindowManagerActionsInternal();\n const { openModal } = usePanelActions();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n\n const handleRequestClose = React.useCallback((id: string) => {\n const panel = state.panels[id];\n return requestClosePanel(id, {\n onConfirm: (customOpts) => new Promise<boolean>((resolve) => {\n const opts = customOpts || panel?.dirtyOptions;\n const baseTitle = formatLabel(panel ? panel.title : messages.untitledPanel, formatMessage);\n openModal(\n ConfirmationForm,\n {\n title: opts?.title || messages.unsavedChangesTitle,\n message: opts?.message || {\n id: messages.unsavedChangesMessage.id,\n defaultMessage: messages.unsavedChangesMessage.defaultMessage,\n values: { title: baseTitle }\n },\n alert: opts?.alert,\n alertType: opts?.alertType || 'danger',\n useYesNoTitles: true,\n // Settles on every exit: Yes, No, Escape, the backdrop, the × or closeAll (7.7.0).\n onSettled: resolve,\n },\n { size: 'small' }\n );\n })\n });\n }, [requestClosePanel, state.panels, formatMessage, openModal, messages]);\n\n const { windowClass, windowBodyClass } = useStyleClasses();\n const ctxMenu = useContext(ContextMenuContext);\n const contextMenuRef = useRef<ContextMenuHandle>(null);\n\n useEffect(() => {\n if (ctxMenu !== null) {\n return registerContextMenuFn((opts) => ctxMenu.show(opts));\n } else {\n return registerContextMenuFn((opts) => contextMenuRef.current?.show(opts));\n }\n }, [ctxMenu, registerContextMenuFn]);\n\n const taskbarRef = useRef<HTMLDivElement | null>(null);\n const tooltipRef = useRef<HTMLDivElement | null>(null);\n const [taskbarExpanded, setTaskbarExpanded] = useState(false);\n const taskbarCollapseTimerRef = useRef<ReturnType<typeof setTimeout>>(null);\n // The pointer is on the taskbar: it must not slide away under it (a press there would be lost).\n const taskbarHoveredRef = useRef(false);\n const prevMinimizedLengthRef = useRef(state.minimized.length);\n\n const [hoveredMinimized, setHoveredMinimized] = useState<HoveredMinimized | null>(null);\n const minimizedTooltipTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);\n const lastTaskbarPointerTypeRef = useRef<string>('mouse');\n const [internalContextMenuOpen, setInternalContextMenuOpen] = useState(false);\n const isContextMenuOpen = ctxMenu !== null ? ctxMenu.isOpen : internalContextMenuOpen;\n\n useEffect(() => {\n return () => {\n // The timer pending at unmount is the one to clear, so the ref is read here on purpose.\n if (minimizedTooltipTimeoutRef.current) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n clearTimeout(minimizedTooltipTimeoutRef.current);\n }\n };\n }, []);\n\n useEffect(() => {\n if (hoveredMinimized) {\n const isStillMinimized = state.minimized.some(m => m.id === hoveredMinimized.id);\n if (!isStillMinimized) {\n // Cleared rather than derived: a stale preview kept in state would come back, with its old\n // position, if the same panel were minimized again.\n // eslint-disable-next-line react-hooks/set-state-in-effect\n setHoveredMinimized(null);\n }\n }\n }, [state.minimized, hoveredMinimized]);\n\n useEffect(() => {\n if (!hoveredMinimized?.fromTouch) return;\n const handler = (e: PointerEvent) => {\n if (e.pointerType !== 'touch') return;\n if (tooltipRef.current?.contains(e.target as Node)) return;\n setHoveredMinimized(null);\n };\n document.addEventListener('pointerdown', handler, { capture: true });\n return () => document.removeEventListener('pointerdown', handler, { capture: true });\n }, [hoveredMinimized?.fromTouch]);\n\n // Where a dragged panel would land; read by the drag handlers below and drawn by the zones.\n // Read live from the store, not from this render: drag handlers keep the deps of the render they\n // started in, before the dragged panel was set (7.9.0).\n const storeSync = useContext(WindowStoreSyncContext);\n const canInsertInto = (leafId: string) => {\n const dragged = storeSync?.getSnapshot().draggedPanelId ?? null;\n return dragged !== null && isDropAllowed(dragged, { kind: 'group', leafId, position: 'center' });\n };\n const targets = useDragTargets({ setDraggedPanelId, isRtl: state.isRtl, canInsertInto });\n const { activeDropZone, setActiveDropZone, dragPos, activeEdgeDrop, setActiveEdgeDrop, activeCornerAnchor, setActiveCornerAnchor, hoveredTab, setHoveredTab, handleTabHover, handleHoverDropZone } = targets;\n\n const { handleTabRightClick, handleMinimizedRightClick } = createWorkspaceMenus({\n state, registry, messages, formatMessage, handleRequestClose, setHoveredMinimized,\n actions: { floatPanel, minimizePanel, restorePanel, maximizePanel, getPanelContextMenuItems, showContextMenu, isDropAllowed },\n });\n\n const { handleTabDragStart } = createTabDrag({\n state, targets, handleTabRightClick,\n actions: { dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, floatPanel, setDraggedPanelId, isDropAllowed },\n });\n\n // Drop the preserved DOM of panels that are no longer open — this workspace's own only.\n useEffect(() => {\n const keys = Object.keys(state.panels);\n for (const cachedId of panelHost.ids()) {\n if (!keys.includes(cachedId)) {\n const el = panelHost.getElement(cachedId);\n panelHost.forget(cachedId);\n if (el) forgetPanelDom(el);\n }\n }\n }, [state.panels, panelHost]);\n\n // Safe window blur handler to cancel sticky dragging states when iframe/webview loses focus\n useEffect(() => {\n const handleWindowBlur = () => {\n if (state.draggedPanelId !== null) {\n setDraggedPanelId(null);\n setActiveDropZone(null);\n setHoveredTab(null);\n }\n };\n window.addEventListener('blur', handleWindowBlur);\n return () => {\n window.removeEventListener('blur', handleWindowBlur);\n };\n }, [state.draggedPanelId, setDraggedPanelId, setActiveDropZone, setHoveredTab]);\n\n const workspaceRef = useRef<HTMLDivElement | null>(null);\n const workspaceSize = useWorkspaceSize(workspaceRef);\n\n // Sync / Realignment Effect when actual workspace size changes\n useEffect(() => {\n const viewW = workspaceSize.width;\n const viewH = workspaceSize.height;\n\n state.floating.forEach(w => {\n const winW = typeof w.width === 'string' ? parseFloat(w.width) : w.width;\n const winH = typeof w.height === 'string' ? parseFloat(w.height) : w.height;\n const winX = typeof w.x === 'string' ? parseFloat(w.x) : w.x;\n const winY = typeof w.y === 'string' ? parseFloat(w.y) : w.y;\n\n let newWidth = winW;\n let newHeight = winH;\n let newX = winX;\n let newY = winY;\n let changed = false;\n\n // Clamp window size if it exceeds the new workspace size (applies whether anchored or free-floating)\n if (newWidth > viewW) {\n newWidth = Math.max(200, viewW - 20);\n changed = true;\n }\n if (newHeight > viewH) {\n newHeight = Math.max(150, viewH - 40);\n changed = true;\n }\n\n // Anchored windows are positioned entirely by `anchor` + `dir` at render time (see the\n // floating-window style callback below), so x/y don't affect their visual position —\n // only free-floating windows need off-screen bounds clamping here.\n if (!w.anchor) {\n const maxX = viewW - 100; // Keep at least 100px of titlebar visible\n if (newX > maxX) {\n newX = Math.max(0, maxX);\n changed = true;\n }\n const maxY = viewH - 40; // Keep titlebar clickable\n if (newY > maxY) {\n newY = Math.max(0, maxY);\n changed = true;\n }\n }\n\n if (changed) {\n updateFloatingPosition(w.id, {\n x: newX,\n y: newY,\n width: newWidth,\n height: newHeight\n });\n }\n });\n }, [workspaceSize, state.floating, updateFloatingPosition]);\n\n // Global Window Focus Event Delegation (Left-click/touch anywhere inside a window or grid panel focuses it)\n useEffect(() => {\n const handlePointerDownGlobal = (e: PointerEvent) => {\n // Only handle primary button (left-click or first touch point)\n if (e.button !== 0) return;\n\n const target = e.target as HTMLElement | null;\n if (!target || typeof target.closest !== 'function') return;\n\n // 1. Check if click is inside a floating window\n const windowEl = target.closest('.rdd-floating-window') as HTMLElement | null;\n if (windowEl) {\n const winId = windowEl.getAttribute('data-window-id');\n if (winId) {\n setActivePanel(winId);\n focusPanel(winId);\n }\n return;\n }\n\n // 2. Check if click is inside a grid split pane\n const panelEl = target.closest('.rdd-workspace-panel') as HTMLElement | null;\n if (panelEl) {\n const panelId = panelEl.getAttribute('data-active-panel-id');\n if (panelId) {\n setActivePanel(panelId);\n }\n }\n };\n\n document.addEventListener('pointerdown', handlePointerDownGlobal);\n return () => {\n document.removeEventListener('pointerdown', handlePointerDownGlobal);\n };\n }, [focusPanel, setActivePanel]);\n\n const { startDrag, startResize } = createFloatingWindowDrag({\n state, workspaceSize, targets,\n actions: { focusPanel, updateFloatingPosition, dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, setDraggedPanelId, isDropAllowed },\n });\n\n // horizontal scroll for minimized taskbar\n const scrollTaskbar = (direction: 'left' | 'right') => {\n if (taskbarRef.current) {\n const amount = direction === 'left' ? -150 : 150;\n taskbarRef.current.scrollBy({ left: amount, behavior: 'smooth' });\n }\n };\n\n // Every collapse goes through here: it replaces any pending timer (never leaves one behind to\n // fire later), and does nothing while the pointer is on the taskbar.\n const scheduleCollapseTaskbar = useCallback((delayMs: number) => {\n if (taskbarCollapseTimerRef.current) clearTimeout(taskbarCollapseTimerRef.current);\n taskbarCollapseTimerRef.current = setTimeout(() => {\n taskbarCollapseTimerRef.current = null;\n if (!taskbarHoveredRef.current) setTaskbarExpanded(false);\n }, delayMs);\n }, []);\n\n const expandTaskbar = useCallback(() => {\n taskbarHoveredRef.current = true;\n if (taskbarCollapseTimerRef.current) clearTimeout(taskbarCollapseTimerRef.current);\n setTaskbarExpanded(true);\n }, []);\n\n const leaveTaskbar = useCallback(() => {\n taskbarHoveredRef.current = false;\n scheduleCollapseTaskbar(400);\n }, [scheduleCollapseTaskbar]);\n\n useEffect(() => () => { if (taskbarCollapseTimerRef.current) clearTimeout(taskbarCollapseTimerRef.current); }, []);\n\n useEffect(() => {\n if (taskbarVisibility === 'autohide' && state.minimized.length > prevMinimizedLengthRef.current) {\n setTaskbarExpanded(true);\n scheduleCollapseTaskbar(2000);\n }\n // The autohide taskbar unmounts when nothing is minimized; a pointer that was on it then gets\n // no pointerleave, so forget it here.\n if (state.minimized.length === 0) taskbarHoveredRef.current = false;\n prevMinimizedLengthRef.current = state.minimized.length;\n }, [state.minimized.length, taskbarVisibility, scheduleCollapseTaskbar]);\n\n // Fetch the active color-scheme from documentElement to make sure nested variables resolve correctly\n const currentColorScheme = useColorScheme();\n const isClient = useIsClient();\n\n // Mirror the skin and the animations opt-out onto <html>, so what renders outside the workspace\n // element (RddToolbar, RddSidebar, portaled menus, toasts, flyouts) gets them too. Through the\n // document mirror, keyed by this workspace: with several on one page the newest wins, and unmounting\n // one hands <html> back to the others rather than clearing it. The claim and its release are\n // separate effects so a skin change updates the claim in place instead of re-stacking it.\n useEffect(() => {\n claimDocumentMirror(panelHost, { skin: skin || null, noAnimations: !animations });\n }, [panelHost, skin, animations]);\n useEffect(() => () => releaseDocumentMirror(panelHost, ['skin', 'noAnimations']), [panelHost]);\n\n return (\n <div\n className={`rdd-workspace${animations ? '' : ' rdd-no-animations'}`}\n data-rdd-skin={skin}\n data-color-scheme={currentColorScheme}\n dir={state.dir}\n // Focusable from script only: where keyboard focus goes when the last tab it was on closes.\n tabIndex={-1}\n >\n\n {/* 1. Main Workspace Viewport (Grids & Floating Panels) */}\n <div\n ref={workspaceRef}\n className={`rdd-workspace-viewport${state.draggedPanelId ? ' rdd-dragging-active' : ''}`}\n >\n <WorkspaceZones state={state} activeEdgeDrop={activeEdgeDrop} activeCornerAnchor={activeCornerAnchor} setActiveEdgeDrop={setActiveEdgeDrop} setActiveCornerAnchor={setActiveCornerAnchor} isDropAllowed={isDropAllowed} />\n\n {/* 1.1 Viewport Split Grid Layout */}\n <div className=\"rdd-workspace-grid-host\">\n {state.gridRoot ? (\n <WorkspaceGrid\n node={state.gridRoot}\n path={[]}\n onTabRightClick={handleTabRightClick}\n activeDropZone={activeDropZone}\n onHoverDropZone={handleHoverDropZone}\n onTabDragStart={handleTabDragStart}\n hoveredTab={hoveredTab}\n onTabHover={handleTabHover}\n defaultPanelIcon={defaultPanelIcon}\n onRequestClosePanel={handleRequestClose}\n emptyWorkspace={emptyWorkspace}\n renderTabContent={renderTabContent}\n />\n ) : (\n <div className=\"rdd-empty-workspace-grid\">\n {formatLabel(messages.emptyGrid, formatMessage)}\n </div>\n )}\n </div>\n\n <FloatingWindows\n state={state}\n registry={registry}\n windowClass={windowClass}\n windowBodyClass={windowBodyClass}\n defaultPanelIcon={defaultPanelIcon}\n messages={messages}\n formatMessage={formatMessage}\n setActivePanel={setActivePanel}\n focusPanel={focusPanel}\n maximizePanel={maximizePanel}\n minimizePanel={minimizePanel}\n getPanelContextMenuItems={getPanelContextMenuItems}\n showContextMenu={showContextMenu}\n handleRequestClose={handleRequestClose}\n startDrag={startDrag}\n startResize={startResize}\n />\n </div>\n\n {/* 2. macOS / Windows 11-style Taskbar Sibling Footer (Flex-shrinked at bottom) */}\n <Taskbar\n state={state}\n registry={registry}\n taskbarVisibility={taskbarVisibility}\n taskbarExpanded={taskbarExpanded}\n expandTaskbar={expandTaskbar}\n leaveTaskbar={leaveTaskbar}\n scrollTaskbar={scrollTaskbar}\n taskbarRef={taskbarRef}\n tooltipRef={tooltipRef}\n defaultPanelIcon={defaultPanelIcon}\n messages={messages}\n formatMessage={formatMessage}\n lastTaskbarPointerTypeRef={lastTaskbarPointerTypeRef}\n hoveredMinimized={hoveredMinimized}\n setHoveredMinimized={setHoveredMinimized}\n minimizedTooltipTimeoutRef={minimizedTooltipTimeoutRef}\n isContextMenuOpen={isContextMenuOpen}\n handleMinimizedRightClick={handleMinimizedRightClick}\n handleRequestClose={handleRequestClose}\n restorePanel={restorePanel}\n />\n\n {/* 3. Persistence Port: Portals rendering panels into off-screen elements. Client only:\n the server has no DOM to create them in, and panel bodies fill in after hydration. */}\n {isClient && Object.keys(state.panels).map((id) => <PanelMount key={id} panelId={id} />)}\n\n {/* 4. Context Menu — only rendered when no parent ContextMenuProvider is in the tree */}\n {ctxMenu === null && (\n <contextMenuAdapter.Component\n ref={contextMenuRef}\n theme=\"dark\"\n formatMessageProvider={formatMessage}\n onShow={() => setInternalContextMenuOpen(true)}\n onHide={() => setInternalContextMenuOpen(false)}\n />\n )}\n\n {/* 5. Dragging Tab Ghost Representation */}\n {state.draggedPanelId !== null && !state.floating.some(w => w.id === state.draggedPanelId) && (\n <DragGhost dragPos={dragPos}>\n 📄 {formatLabel(state.panels[state.draggedPanelId]?.title || messages.untitledPanel, formatMessage)}\n </DragGhost>\n )}\n\n\n\n </div>\n );\n};\n\nexport default WindowManager;\n","import { useSyncExternalStore } from 'react';\n\nconst subscribeNever = () => () => {};\nconst isClient = () => true;\nconst isServer = () => false;\n\n/**\n * False on the server and during hydration, true once mounted on the client — without a\n * hydration mismatch (`useSyncExternalStore` renders the server value while hydrating, then\n * re-renders with the client one). Gate anything that needs the DOM (portals, created elements)\n * behind it.\n */\nexport function useIsClient(): boolean {\n return useSyncExternalStore(subscribeNever, isClient, isServer);\n}\n","import { useSyncExternalStore } from 'react';\n\ntype ColorScheme = 'dark' | 'light';\n\nconst readScheme = (): ColorScheme =>\n document.documentElement.getAttribute('data-color-scheme') === 'light' ? 'light' : 'dark';\n\nconst subscribe = (onChange: () => void): (() => void) => {\n const observer = new MutationObserver(onChange);\n observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-color-scheme'] });\n return () => observer.disconnect();\n};\n\n// The server can't see the page's scheme. Dark is the library's default, so server-rendered\n// HTML says dark and hydration corrects it on the client — `useSyncExternalStore` renders the\n// server value during hydration and then the real one, without a mismatch.\nconst serverScheme = (): ColorScheme => 'dark';\n\n/**\n * Reactively reads the page's `data-color-scheme` attribute on `<html>` — the one the host\n * application sets to switch the library's scheme (the library itself never writes it) —\n * returning `'dark'` or `'light'` and re-rendering whenever it changes.\n *\n * Useful for panel content that needs to react to the same scheme the\n * workspace itself is using — e.g. swapping a map's tile layer or an\n * embedded editor's theme to match.\n *\n * Returns `'dark'` when rendered on the server.\n */\nexport function useColorScheme(): ColorScheme {\n return useSyncExternalStore(subscribe, readScheme, serverScheme);\n}\n","/**\n * @file panelMount.tsx\n * @description Where panels live: the slots that place a panel's preserved DOM (in a tab, a window, a taskbar preview), its lifecycle events and form container. The DOM, sizes and lifecycle handlers themselves belong to the workspace's own panel host (`panelHost.ts`).\n */\nimport React, { useRef, useState, useEffect, useLayoutEffect } from 'react';\nimport { createPortal } from 'react-dom';\nimport { restorePanelDom } from '../domPreservation';\nimport { useWindowManagerState, useWindowManagerActions, useFormatMessage, formatLabel, usePredefinedMessages, useRegistry } from '../WindowManagerContext';\nimport type { PanelInfo, MessageDescriptor, MessageFormatter, WorkspaceState } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport { FormContainerProvider } from '../FormContainerContext';\nimport type { FormContainerContract, ContainerType } from '../FormContainerContext';\nimport { usePanelHost } from './panelHost';\nimport { isShownInGrid } from '../../core/layoutTree';\n\n/** Whether a panel is on screen: floating, or the selected tab of its group (not minimized). */\nconst isPanelShown = (s: WorkspaceState, panelId: string): boolean => {\n const state = s.panels[panelId]?.state;\n if (state === 'floating') return true;\n if (state !== 'docked') return false;\n return isShownInGrid(s.gridRoot, panelId);\n};\n\n/**\n * Where a panel's element waits while no slot shows it. One per page, shared on purpose: every\n * workspace's elements are distinct, so parking them side by side in one hidden node is harmless.\n */\nexport const hiddenContainerId = 'preserved-dom-container';\n\nconst park = (el: HTMLElement): void => {\n let hiddenContainer = document.getElementById(hiddenContainerId);\n if (!hiddenContainer) {\n hiddenContainer = document.createElement('div');\n hiddenContainer.id = hiddenContainerId;\n hiddenContainer.style.display = 'none';\n document.body.appendChild(hiddenContainer);\n }\n hiddenContainer.appendChild(el);\n};\n\n\n// ==========================================\n// 3. Persistent DOM Container Host & Slot\n// ==========================================\n\nexport const renderPanelContent = (\n id: string,\n panel: PanelInfo,\n registry: PanelRegistry,\n messages: Record<MessageKey, MessageDescriptor>,\n formatMessage: MessageFormatter,\n): React.ReactNode => {\n const componentKey = panel.component;\n const registryEntry = registry.get(componentKey);\n if (!registryEntry) {\n console.warn(\n `[react-dockable-desktop] Panel \"${id}\" references component key \"${componentKey}\" ` +\n `which is not registered. Add it to the workspace's panels:\\n` +\n ` createWorkspace({ panels: { \"${componentKey}\": { component: YourComponent } } })`\n );\n return (\n <div className=\"rdd-unregistered-panel\">\n <h6 className=\"rdd-unregistered-panel__title\">⚠️ {formatLabel(messages.componentUnregistered, formatMessage)}</h6>\n <span className=\"rdd-unregistered-panel__key\">{formatLabel({ ...messages.componentKey, values: { key: componentKey } }, formatMessage)}</span>\n </div>\n );\n }\n const Component = registryEntry.Component;\n // Props spread first, panelId second — a caller-supplied prop of the same name can never\n // shadow the injected id. Matches ModalStackRenderer/SidePanelRenderer's spread order exactly.\n return <Component {...(panel.props ?? {})} panelId={id} />;\n};\n\nexport const PreservedDOMWrapper: React.FC<{ panelId: string }> = ({ panelId }) => {\n const panelHost = usePanelHost();\n const hostRef = useRef<HTMLDivElement | null>(null);\n // Only the active panel gets focus back after a move (see domPreservation.ts). A selector, so\n // this wrapper re-renders only when this panel's active flag flips.\n const isActive = useWindowManagerState(s => s.activePanelId === panelId);\n const isActiveRef = useRef(isActive);\n useLayoutEffect(() => { isActiveRef.current = isActive; });\n\n useEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n\n const cachedEl = panelHost.getOrCreateElement(panelId);\n host.appendChild(cachedEl);\n restorePanelDom(cachedEl, { refocus: isActiveRef.current });\n\n const resizeObserver = new ResizeObserver((entries) => {\n for (const entry of entries) {\n const { width, height } = entry.contentRect;\n if (width > 0 && height > 0) {\n panelHost.setDimensions(panelId, { width, height });\n const lifecycle = panelHost.getLifecycle(panelId);\n if (lifecycle) {\n lifecycle.onResize.forEach(h => h(width, height));\n }\n }\n }\n });\n resizeObserver.observe(host);\n\n return () => {\n resizeObserver.disconnect();\n park(cachedEl);\n };\n }, [panelId, panelHost]);\n\n return <div ref={hostRef} className=\"rdd-panel-dom-host\" />;\n};\n\nexport const PreviewDOMWrapper: React.FC<{ panelId: string }> = ({ panelId }) => {\n const panelHost = usePanelHost();\n const panel = useWindowManagerState(s => s.panels[panelId]);\n const registry = useRegistry();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const hostRef = useRef<HTMLDivElement | null>(null);\n\n const regEntry = panel ? registry.get(panel.component) : null;\n // A panel that unmounts while hidden has nothing to preview while minimized.\n const disableLivePreview = regEntry?.defaultOptions?.disableLivePreview || regEntry?.defaultOptions?.keepAlive === false || false;\n\n const lastSize = panelHost.getDimensions(panelId) || { width: 800, height: 500 };\n const origW = lastSize.width;\n const origH = lastSize.height;\n const maxW = 220;\n const maxH = 140;\n const scale = Math.min(maxW / origW, maxH / origH);\n\n useEffect(() => {\n if (disableLivePreview) return;\n\n const host = hostRef.current;\n if (!host) return;\n\n const cachedEl = panelHost.getElement(panelId);\n if (!cachedEl) return;\n\n host.appendChild(cachedEl);\n restorePanelDom(cachedEl, { refocus: false }); // a preview shows the panel's place; it never takes focus\n\n return () => park(cachedEl);\n }, [panelId, disableLivePreview, panelHost]);\n\n if (disableLivePreview) {\n const displayW = origW * scale;\n const displayH = origH * scale;\n const rawTitle = panel?.title || regEntry?.defaultOptions?.title || messages.untitledPanel;\n const title = formatLabel(rawTitle, formatMessage);\n const initialChar = (Array.from(title)[0] || 'P').toUpperCase();\n\n return (\n <div\n className=\"rdd-taskbar-item-preview-frame rdd-taskbar-item-preview-frame--empty\"\n style={{ width: `${displayW}px`, height: `${displayH}px` }}\n >\n <div className=\"rdd-taskbar-item-preview-initial\">\n {initialChar}\n </div>\n </div>\n );\n }\n\n return (\n <div\n className=\"rdd-taskbar-item-preview-frame\"\n style={{\n width: `${origW * scale}px`,\n height: `${origH * scale}px`,\n }}\n >\n <div\n ref={hostRef}\n className=\"rdd-taskbar-item-preview-host\"\n style={{\n width: `${origW}px`,\n height: `${origH}px`,\n transform: `scale(${scale})`,\n ['--rdd-preview-scale' as string]: scale\n }}\n />\n </div>\n );\n};\n\nexport const FormContainerProviderWrapper: React.FC<{ panelId: string; children: React.ReactNode }> = ({ panelId, children }) => {\n const panelHost = usePanelHost();\n const { requestClosePanel, setPanelDirty, registerCloseGuard, unregisterCloseGuard, registerStateProvider, unregisterStateProvider, updatePanelTitle, setPanelIcon, minimizePanel } = useWindowManagerActions();\n\n // ── minimize / restore ──────────────────────────────────────────────────\n const isMin = useWindowManagerState(s => s.minimized.some(m => m.id === panelId));\n const prevMinRef = useRef(isMin);\n\n useEffect(() => {\n const entry = panelHost.getLifecycle(panelId);\n if (!entry) return;\n\n if (isMin && !prevMinRef.current) {\n entry.onMinimize.forEach(h => h());\n } else if (!isMin && prevMinRef.current) {\n entry.onRestore.forEach(h => h());\n }\n prevMinRef.current = isMin;\n }, [isMin, panelId, panelHost]);\n\n // ── activate / deactivate ───────────────────────────────────────────────\n const isActive = useWindowManagerState(s => s.activePanelId === panelId);\n const prevActiveRef = useRef(isActive);\n\n useEffect(() => {\n const wasActive = prevActiveRef.current;\n prevActiveRef.current = isActive; // always sync the ref, even if no handler is registered yet\n const entry = panelHost.getLifecycle(panelId);\n if (!entry) return;\n\n if (isActive && !wasActive) {\n entry.onActivate.forEach(h => h());\n } else if (!isActive && wasActive) {\n entry.onDeactivate.forEach(h => h());\n }\n }, [isActive, panelId, panelHost]);\n\n // ── container-type change ───────────────────────────────────────────────\n const rawPanelState = useWindowManagerState(s => s.panels[panelId]?.state);\n const derivedContainerType: ContainerType =\n rawPanelState === 'floating' ? 'floating-window' : 'dockable-panel';\n const prevContainerTypeRef = useRef(derivedContainerType);\n\n useEffect(() => {\n if (rawPanelState === 'minimized') return; // minimize/restore is onMinimize's domain; intentionally skip ref update\n const prevType = prevContainerTypeRef.current;\n prevContainerTypeRef.current = derivedContainerType; // always sync, even if no handler registered yet\n const entry = panelHost.getLifecycle(panelId);\n if (!entry) return;\n\n if (derivedContainerType !== prevType) {\n entry.onContainerTypeChange.forEach(h => h(derivedContainerType));\n }\n }, [derivedContainerType, rawPanelState, panelId, panelHost]);\n\n // ── cleanup: fire onDeactivate (if active) then onClose ─────────────────\n useEffect(() => {\n return () => {\n const entry = panelHost.getLifecycle(panelId);\n if (entry) {\n if (prevActiveRef.current) entry.onDeactivate.forEach(h => h());\n entry.onClose.forEach(h => h());\n panelHost.deleteLifecycle(panelId);\n }\n };\n }, [panelId, panelHost]);\n\n // Capture the container type at mount so the static `containerType` field is\n // correct ('dockable-panel' or 'floating-window') rather than the default 'standalone'.\n const [initialContainerType] = useState<ContainerType>(derivedContainerType);\n\n const contract = React.useMemo<FormContainerContract>(() => ({\n requestClose: (options) => requestClosePanel(panelId, options),\n setDirty: (dirty, options) => setPanelDirty(panelId, dirty, options),\n onCloseRequested: (handler) => {\n registerCloseGuard(panelId, handler);\n return () => unregisterCloseGuard(panelId);\n },\n registerStateProvider: (getState) => {\n registerStateProvider(panelId, getState);\n return () => unregisterStateProvider(panelId);\n },\n setTitle: (title) => updatePanelTitle(panelId, title),\n setIcon: (icon) => setPanelIcon(panelId, icon ?? null),\n instanceId: panelId,\n containerType: initialContainerType,\n onClose: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onClose.add(handler);\n return () => reg.onClose.delete(handler);\n },\n onMinimize: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onMinimize.add(handler);\n return () => reg.onMinimize.delete(handler);\n },\n onRestore: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onRestore.add(handler);\n return () => reg.onRestore.delete(handler);\n },\n onResize: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onResize.add(handler);\n return () => reg.onResize.delete(handler);\n },\n requestMinimize: () => minimizePanel(panelId),\n getDimensions: () => panelHost.getDimensions(panelId) ?? null,\n onActivate: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onActivate.add(handler);\n return () => reg.onActivate.delete(handler);\n },\n onDeactivate: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onDeactivate.add(handler);\n return () => reg.onDeactivate.delete(handler);\n },\n onContainerTypeChange: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onContainerTypeChange.add(handler);\n return () => reg.onContainerTypeChange.delete(handler);\n },\n }), [panelId, panelHost, initialContainerType, requestClosePanel, setPanelDirty, registerCloseGuard, unregisterCloseGuard, registerStateProvider, unregisterStateProvider, updatePanelTitle, setPanelIcon, minimizePanel]);\n\n return (\n <FormContainerProvider value={contract}>\n {children}\n </FormContainerProvider>\n );\n};\n\n/**\n * One open panel's body, portaled into its preserved element (the slots then place that element in\n * a tab, a window or a preview). Memoised and given only the id: it reads its own entry and the\n * direction, so it re-renders when its panel changes, never because another panel did (7.7.2).\n */\nexport const PanelMount: React.FC<{ panelId: string }> = React.memo(({ panelId }) => {\n const panelHost = usePanelHost();\n const panel = useWindowManagerState(s => s.panels[panelId]);\n const dir = useWindowManagerState(s => s.dir);\n const registry = useRegistry();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n // keepAlive: false (7.8.0): only those panels ask whether they are shown, so the rest pay nothing.\n const keepAlive = (panel && registry.get(panel.component)?.defaultOptions?.keepAlive) !== false;\n const shown = useWindowManagerState(s => keepAlive || isPanelShown(s, panelId));\n if (!panel) return null;\n const typeClass = registry.get(panel.component)?.defaultOptions?.className;\n return createPortal(\n <FormContainerProviderWrapper panelId={panelId}>\n <div className={`rdd-panel-content${typeClass ? ` ${typeClass}` : ''}`} data-rdd-panel={panelId} dir={dir}>\n {shown && renderPanelContent(panelId, panel, registry, messages, formatMessage)}\n </div>\n </FormContainerProviderWrapper>,\n panelHost.getOrCreateElement(panelId),\n );\n});\nPanelMount.displayName = 'PanelMount';\n","/**\n * @file DragGhost.tsx\n * @description The tab that follows the pointer while a docked panel is dragged. It alone reads the pointer position, so a move re-renders it and nothing else.\n */\nimport React, { useSyncExternalStore } from 'react';\nimport type { DragPos } from './useDragTargets';\n\nexport const DragGhost: React.FC<{ dragPos: DragPos; children: React.ReactNode }> = ({ dragPos, children }) => {\n const pos = useSyncExternalStore(dragPos.subscribe, dragPos.get, dragPos.get);\n return (\n <div className=\"rdd-drag-ghost-tab\" style={{ left: pos.x + 12, top: pos.y + 12 }}>\n {children}\n </div>\n );\n};\n","/**\n * @file WorkspaceGrid.tsx\n * @description The split layout: a branch of the layout tree with its resizer bars, down to its leaf groups.\n */\nimport React from 'react';\nimport { isComputedRtl } from '../../utils/rtl';\nimport { useWindowManagerActions } from '../WindowManagerContext';\nimport type { LayoutNode, DropPosition } from '../../types';\nimport { startPointerDrag } from '../dragResize';\nimport { LeafGroup } from './LeafGroup';\nimport type { TabContentProps } from '../../types';\n\nexport interface WorkspaceGridProps {\n node: LayoutNode;\n path: number[];\n onTabRightClick: (id: string, e: React.MouseEvent) => void;\n activeDropZone: { leafId: string; position: DropPosition } | null;\n onHoverDropZone: (leafId: string, position: DropPosition | null) => void;\n onTabDragStart: (id: string, e: React.PointerEvent) => void;\n hoveredTab: { leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null;\n onTabHover: (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => void;\n defaultPanelIcon?: React.ReactNode;\n /** The app's empty-workspace view. Only the root grid receives it: nested grids are rendered without it. */\n emptyWorkspace?: React.ReactNode;\n /** The app's tab content, for every group (7.10.0). */\n renderTabContent?: (tab: TabContentProps) => React.ReactNode;\n onRequestClosePanel: (id: string) => Promise<void> | void;\n}\n\nexport const WorkspaceGrid: React.FC<WorkspaceGridProps> = ({ node, path, onTabRightClick, activeDropZone, onHoverDropZone, onTabDragStart, hoveredTab, onTabHover, defaultPanelIcon, onRequestClosePanel, emptyWorkspace, renderTabContent }) => {\n const { updateSplitSizes } = useWindowManagerActions();\n\n if (node.type === 'leaf') {\n return <LeafGroup leaf={node} onTabRightClick={onTabRightClick} activeDropZone={activeDropZone} onHoverDropZone={onHoverDropZone} onTabDragStart={onTabDragStart} hoveredTab={hoveredTab} onTabHover={onTabHover} defaultPanelIcon={defaultPanelIcon} onRequestClosePanel={onRequestClosePanel} emptyWorkspace={emptyWorkspace} renderTabContent={renderTabContent} />;\n }\n\n const isRow = node.orientation === 'horizontal';\n\n const handleResizerPointerDown = (idx: number, e: React.PointerEvent) => {\n e.preventDefault();\n const resizerEl = e.currentTarget as HTMLDivElement;\n const parentEl = resizerEl.parentElement;\n const parentSize = parentEl\n ? (isRow ? parentEl.clientWidth : parentEl.clientHeight)\n : (isRow ? 1000 : 800);\n const rtl = isComputedRtl(parentEl);\n\n startPointerDrag({\n element: resizerEl,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => [...node.sizes],\n activeClasses: [\n { el: resizerEl, classes: ['rdd-active'] },\n { el: document.body, classes: ['rdd-resizing-active', isRow ? 'rdd-resizing-col-active' : 'rdd-resizing-row-active'] },\n ],\n onMove: (dx, dy, startSizes) => {\n // A row reverses under RTL, so children[idx] is the pane to the divider's *right*: a\n // rightward drag must shrink it. Pointer deltas are physical; sizes are in child order.\n const sign = isRow && rtl ? -1 : 1;\n const deltaPercentage = (isRow ? sign * dx : dy) / parentSize;\n const newSizes = [...startSizes];\n newSizes[idx] += deltaPercentage;\n newSizes[idx + 1] -= deltaPercentage;\n if (newSizes[idx] > 0.1 && newSizes[idx + 1] > 0.1) {\n updateSplitSizes(path, newSizes);\n }\n },\n });\n };\n\n return (\n <div className={`rdd-split ${isRow ? 'rdd-split--row' : 'rdd-split--column'}`}>\n {node.children.map((child, idx) => {\n const size = node.sizes[idx] * 100;\n return (\n <React.Fragment key={idx}>\n <div className=\"rdd-split-child\" style={{ flexGrow: node.sizes[idx], flexBasis: `${size}%` }}>\n <WorkspaceGrid node={child} path={[...path, idx]} onTabRightClick={onTabRightClick} activeDropZone={activeDropZone} onHoverDropZone={onHoverDropZone} onTabDragStart={onTabDragStart} hoveredTab={hoveredTab} onTabHover={onTabHover} defaultPanelIcon={defaultPanelIcon} onRequestClosePanel={onRequestClosePanel} renderTabContent={renderTabContent} />\n </div>\n {idx < node.children.length - 1 && (\n <div\n onPointerDown={(e) => handleResizerPointerDown(idx, e)}\n className={`rdd-resizer-bar ${isRow ? 'rdd-resizer-bar--vertical' : 'rdd-resizer-bar--horizontal'}`}\n />\n )}\n </React.Fragment>\n );\n })}\n </div>\n );\n};\n","/**\n * Shared pointer-drag-resize primitives.\n *\n * Extracted from four previously-independent implementations (the workspace grid\n * split resizer, the sidebar drawer resizer, and two floating-window resize-handle\n * implementations) that had quietly drifted apart in exactly the kind of detail\n * (an inline-style property present in one and missing in the other) that once\n * caused a real, user-visible bug. This file is the single place that mechanic now\n * lives, so it can't drift again.\n */\n\n// ── Pointer-capture drag mechanics ──────────────────────────────────────────\n\nexport interface PointerDragConfig<TStart> {\n /** The element to capture the pointer on — normally the handle the user grabbed. */\n element: HTMLElement;\n pointerId: number;\n /** The pointerdown event's clientX/clientY, used as the delta origin. */\n startClientX: number;\n startClientY: number;\n /** Snapshot whatever state the caller needs at drag start (sizes, positions, ...). */\n captureStart: () => TStart;\n /** Called on every pointermove with the delta from the drag's start position. */\n onMove: (dx: number, dy: number, start: TStart) => void;\n /** Called once when the drag ends (pointerup or pointercancel). */\n onEnd?: (start: TStart) => void;\n /**\n * Called instead of `onEnd` when the drag is cut short: the window loses focus, or the pointer\n * capture is lost (the element was removed mid-drag). Without it, `onEnd` is called. (7.9.0)\n */\n onCancel?: (start: TStart) => void;\n /** Classes toggled on the given elements for the duration of the drag. */\n activeClasses?: Array<{ el: HTMLElement; classes: string[] }>;\n}\n\n/**\n * Starts a pointer-capture-based drag: captures the pointer on `element`, tracks\n * movement via listeners scoped to that element's own lifetime (not `window`), and\n * cleans up automatically on release or cancel, and (7.9.0) when the window loses focus\n * or the capture is lost, so a drag can never outlive its element or leave its classes behind.\n */\nexport function startPointerDrag<TStart>(config: PointerDragConfig<TStart>): void {\n const { element, pointerId, startClientX, startClientY, captureStart, onMove, onEnd, activeClasses } = config;\n\n element.setPointerCapture(pointerId);\n activeClasses?.forEach(({ el, classes }) => el.classList.add(...classes));\n const start = captureStart();\n\n const handleMove = (e: PointerEvent) => {\n onMove(e.clientX - startClientX, e.clientY - startClientY, start);\n };\n\n // Ends at most once: every listener is removed before the callback runs.\n const finish = (cancelled: boolean) => {\n activeClasses?.forEach(({ el, classes }) => el.classList.remove(...classes));\n element.removeEventListener('pointermove', handleMove);\n element.removeEventListener('pointerup', handleEnd);\n element.removeEventListener('pointercancel', handleEnd);\n doc.removeEventListener('lostpointercapture', handleLostCapture, true);\n view?.removeEventListener('blur', handleBlur);\n (cancelled && config.onCancel ? config.onCancel : onEnd)?.(start);\n };\n const handleEnd = () => finish(false);\n const handleBlur = () => finish(true);\n // Removing a capturing element fires lostpointercapture at the document, not the element, so\n // it is listened for there. A normal release ends the drag before the capture is let go.\n const handleLostCapture = (e: PointerEvent) => { if (e.pointerId === pointerId) finish(true); };\n\n const doc = element.ownerDocument;\n const view = doc.defaultView;\n element.addEventListener('pointermove', handleMove);\n element.addEventListener('pointerup', handleEnd);\n element.addEventListener('pointercancel', handleEnd);\n doc.addEventListener('lostpointercapture', handleLostCapture, true);\n view?.addEventListener('blur', handleBlur);\n}\n\n// ── 8-directional resize math ────────────────────────────────────────────────\n\nexport type ResizeDir = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';\n\nexport interface ResizeRect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nexport interface ResizeConstraints {\n minW: number;\n minH: number;\n /** Upper bound on width — only applies to eastward growth (dir includes 'e'). */\n maxW?: number;\n /** Upper bound on height — only applies to southward growth (dir includes 's'). */\n maxH?: number;\n /** Lower bound on the resulting x — only applies to westward growth (dir includes 'w'). */\n minX?: number;\n /** Lower bound on the resulting y — only applies to northward growth (dir includes 'n'). */\n minY?: number;\n}\n\n/**\n * Pure function computing the new rect for an 8-directional resize handle drag.\n *\n * `maxW`/`maxH` and `minX`/`minY` are independent, direction-scoped constraints\n * rather than one \"container bound\" — a resize toward the fixed edge (e/s) is\n * naturally bounded by a maximum dimension, while a resize toward the moving edge\n * (w/n) is naturally bounded by a minimum position, and the two calling sites this\n * was extracted from need different subsets of these (see workspace/floatingWindowDrag.ts's\n * `startResize`, which omits all four and lets a window grow unbounded and be\n * dragged fully off-screen, vs. panelOverlay/FloatingWidget.tsx's `handleResizePointerDown`, which\n * supplies all four to keep windows within their container).\n */\nexport function computeResizedRect(dir: ResizeDir, dx: number, dy: number, start: ResizeRect, constraints: ResizeConstraints): ResizeRect {\n const { minW, minH, maxW, maxH, minX, minY } = constraints;\n let { x, y, w, h } = start;\n\n if (dir.includes('e')) {\n w = Math.max(minW, Math.min(start.w + dx, maxW ?? Infinity));\n }\n if (dir.includes('w')) {\n const maxDx = start.w - minW; // largest rightward (shrinking) delta before hitting minW\n const minDx = minX != null ? -(start.x - minX) : -Infinity; // most negative (growing) delta before x hits minX\n const clampedDx = Math.max(minDx, Math.min(dx, maxDx));\n w = start.w - clampedDx;\n x = start.x + clampedDx;\n }\n if (dir.includes('s')) {\n h = Math.max(minH, Math.min(start.h + dy, maxH ?? Infinity));\n }\n if (dir.includes('n')) {\n const maxDy = start.h - minH;\n const minDy = minY != null ? -(start.y - minY) : -Infinity;\n const clampedDy = Math.max(minDy, Math.min(dy, maxDy));\n h = start.h - clampedDy;\n y = start.y + clampedDy;\n }\n\n return { x, y, w, h };\n}\n","/**\n * @file LeafGroup.tsx\n * @description A leaf group: its tab strip (keyboard, scroll, drag and drop) and the selected panel's body.\n */\nimport React, { useState, useRef, useEffect, useCallback } from 'react';\nimport { isComputedRtl } from '../../utils/rtl';\nimport { useWindowManagerState, useWindowManagerActionsInternal, useFormatMessage, formatLabel, usePredefinedMessages, useStyleClasses, useRegistry } from '../WindowManagerContext';\nimport type { LayoutLeafNode, DropPosition } from '../../types';\nimport { tabDropSide, isMenuKey, menuEventAt, refocusAfterTabClose, domIdPart } from './helpers';\nimport { DefaultGridIcon } from './icons';\nimport { PreservedDOMWrapper } from './panelMount';\nimport type { TabContentProps } from '../../types';\n\nexport interface LeafGroupProps {\n leaf: LayoutLeafNode;\n onTabRightClick: (id: string, e: React.MouseEvent) => void;\n activeDropZone: { leafId: string; position: DropPosition } | null;\n onHoverDropZone: (leafId: string, position: DropPosition | null) => void;\n onTabDragStart: (id: string, e: React.PointerEvent) => void;\n hoveredTab: { leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null;\n onTabHover: (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => void;\n defaultPanelIcon?: React.ReactNode;\n /** Set on the root group only: shown in place of the built-in message while it has no panels. */\n emptyWorkspace?: React.ReactNode;\n /** The app's tab content (7.10.0). */\n renderTabContent?: (tab: TabContentProps) => React.ReactNode;\n onRequestClosePanel: (id: string) => Promise<void> | void;\n}\n\nexport const LeafGroup: React.FC<LeafGroupProps> = ({ leaf, onTabRightClick, activeDropZone, onHoverDropZone, onTabDragStart, hoveredTab, onTabHover, defaultPanelIcon, onRequestClosePanel, emptyWorkspace, renderTabContent }) => {\n const state = useWindowManagerState();\n const registry = useRegistry();\n const { openPanel, closeLeafGroup, setActivePanel, isDropAllowed } = useWindowManagerActionsInternal();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const { windowClass, windowBodyClass } = useStyleClasses();\n\n const tabContainerRef = useRef<HTMLDivElement>(null);\n // Overflow tracked in reading order: `start` = tabs hidden before the first visible one, `end`\n // = after the last. Under RTL, scrollLeft runs from 0 down to negative values, so the physical\n // `scrollLeft > 0` test that used to be here never saw the start overflow and always the end.\n const [tabScroll, setTabScroll] = useState({ start: false, end: false, rtl: false });\n\n const updateTabScroll = useCallback(() => {\n const el = tabContainerRef.current;\n if (!el) return;\n const travelled = Math.abs(el.scrollLeft);\n const max = el.scrollWidth - el.clientWidth;\n const next = { start: travelled > 1, end: travelled < max - 1, rtl: isComputedRtl(el) };\n setTabScroll(prev => (prev.start === next.start && prev.end === next.end && prev.rtl === next.rtl ? prev : next));\n }, []);\n\n useEffect(() => {\n const el = tabContainerRef.current;\n if (!el) return;\n el.addEventListener('scroll', updateTabScroll, { passive: true });\n const ro = new ResizeObserver(updateTabScroll);\n ro.observe(el);\n updateTabScroll();\n return () => { el.removeEventListener('scroll', updateTabScroll); ro.disconnect(); };\n }, [updateTabScroll]);\n\n const scrollTabs = (toward: 'start' | 'end') => {\n // In reading order: toward the end is +x in LTR and −x in RTL.\n const forward = toward === 'end' ? 120 : -120;\n tabContainerRef.current?.scrollBy({ left: tabScroll.rtl ? -forward : forward, behavior: 'smooth' });\n };\n // The start button comes first in the DOM, so it sits on the physical left in LTR and on the\n // physical right in RTL. Class, glyph and label follow the physical side.\n const startSide = tabScroll.rtl ? 'right' : 'left';\n const endSide = tabScroll.rtl ? 'left' : 'right';\n const scrollGlyph = { left: '\\u2039', right: '\\u203A' } as const;\n const scrollLabel = { left: messages.scrollTabsLeft, right: messages.scrollTabsRight } as const;\n\n const selectTab = (id: string) => {\n openPanel(id, state.panels[id].component);\n setActivePanel(id);\n };\n\n // WAI-ARIA tabs pattern: one tab stop per group (the selected tab); the arrow keys move the\n // selection and focus along the strip — mirrored under RTL, where the strip runs right to left.\n const handleTabKeyDown = (e: React.KeyboardEvent<HTMLElement>, id: string, closable: boolean) => {\n if (isMenuKey(e)) {\n e.preventDefault();\n onTabRightClick(id, menuEventAt(e.currentTarget));\n return;\n }\n const ids = leaf.panels.filter(p => state.panels[p]);\n const i = ids.indexOf(id);\n const step = isComputedRtl(e.currentTarget) ? -1 : 1;\n let next: string | undefined;\n switch (e.key) {\n case 'ArrowRight': next = ids[(i + step + ids.length) % ids.length]; break;\n case 'ArrowLeft': next = ids[(i - step + ids.length) % ids.length]; break;\n case 'Home': next = ids[0]; break;\n case 'End': next = ids[ids.length - 1]; break;\n case 'Enter':\n case ' ':\n e.preventDefault();\n selectTab(id);\n return;\n case 'Delete': {\n if (!closable) return;\n e.preventDefault();\n const workspaceEl = e.currentTarget.closest<HTMLElement>('.rdd-workspace');\n void Promise.resolve(onRequestClosePanel(id)).then(() => requestAnimationFrame(() => {\n refocusAfterTabClose(id, tabContainerRef.current, workspaceEl);\n }));\n return;\n }\n default:\n return;\n }\n e.preventDefault();\n if (!next || next === id) return;\n selectTab(next);\n tabContainerRef.current\n ?.querySelector<HTMLElement>(`[data-tab-id=\"${next.replace(/[\"\\\\]/g, '\\\\$&')}\"]`)\n ?.focus();\n };\n const tabPanelId = `rdd-tabpanel-${domIdPart(leaf.id)}`;\n const tabIdFor = (panelId: string) => `rdd-tab-${domIdPart(panelId)}`;\n\n return (\n <div\n data-active-panel-id={leaf.activePanelId || ''}\n data-rdd-leaf={leaf.id}\n className={`rdd-workspace-panel ${windowClass ?? ''}`}\n >\n {/* Tab Headers */}\n <div className=\"rdd-workspace-tab-bar\">\n {tabScroll.start && (\n <button\n className={`rdd-tab-scroll-btn rdd-tab-scroll-btn-${startSide}`}\n onPointerDown={(e) => e.stopPropagation()}\n onClick={() => scrollTabs('start')}\n tabIndex={-1}\n aria-label={formatLabel(scrollLabel[startSide], formatMessage)}\n >{scrollGlyph[startSide]}</button>\n )}\n <div\n ref={tabContainerRef}\n className=\"rdd-tab-headers-container\"\n role=\"tablist\"\n aria-orientation=\"horizontal\"\n onPointerMove={(e) => {\n if (state.draggedPanelId && e.target === e.currentTarget) {\n onTabHover(leaf.id, 'EMPTY', leaf.panels.length, 'right');\n }\n }}\n onPointerLeave={(e) => {\n if (state.draggedPanelId && e.target === e.currentTarget) {\n onTabHover(leaf.id, '', -1, null);\n }\n }}\n >\n {leaf.panels.map((id, idx) => {\n const panel = state.panels[id];\n if (!panel) return null;\n const isSelected = leaf.activePanelId === id;\n const isGloballyActive = state.activePanelId === id;\n\n const registryEntry = registry.get(panel.component);\n const options = registryEntry?.defaultOptions;\n\n const isHovered = hoveredTab && hoveredTab.leafId === leaf.id && hoveredTab.panelId === id;\n const isLast = idx === leaf.panels.length - 1;\n const isHoveredEmpty = hoveredTab && hoveredTab.leafId === leaf.id && hoveredTab.panelId === 'EMPTY' && isLast;\n const sideClass = isHovered\n ? (hoveredTab.side === 'left' ? 'rdd-drag-hover-left' : 'rdd-drag-hover-right')\n : (isHoveredEmpty ? 'rdd-drag-hover-right' : '');\n\n const tabFocusClass = isSelected\n ? (isGloballyActive ? 'rdd-active rdd-workspace-tab-active-focused' : 'rdd-active rdd-workspace-tab-active-unfocused')\n : 'rdd-workspace-tab-inactive';\n\n return (\n <div\n key={id}\n id={tabIdFor(id)}\n role=\"tab\"\n aria-selected={isSelected}\n aria-controls={tabPanelId}\n aria-keyshortcuts={options?.canClose !== false ? 'Delete' : undefined}\n tabIndex={isSelected ? 0 : -1}\n onKeyDown={(e) => handleTabKeyDown(e, id, options?.canClose !== false)}\n data-tab-id={id}\n data-leaf-id={leaf.id}\n data-rdd-tab={id}\n data-tab-index={String(idx)}\n // State for app CSS (7.8.0): present when true, so `[data-rdd-dirty]` matches.\n data-rdd-selected={isSelected ? '' : undefined}\n data-rdd-focused={isGloballyActive ? '' : undefined}\n data-rdd-dirty={panel?.dirty ? '' : undefined}\n onClick={() => selectTab(id)}\n onPointerDown={(e) => {\n if (options?.canDrag !== false) {\n onTabDragStart(id, e);\n }\n }}\n onContextMenu={(e) => onTabRightClick(id, e)}\n onPointerMove={(e) => {\n if (state.draggedPanelId && e.pointerType !== 'touch') {\n onTabHover(leaf.id, id, idx, tabDropSide(e.currentTarget, e.clientX));\n }\n }}\n onPointerLeave={() => {\n if (state.draggedPanelId) {\n onTabHover(leaf.id, '', -1, null);\n }\n }}\n className={`rdd-workspace-tab ${tabFocusClass} ${sideClass}${options?.tabClassName ? ` ${options.tabClassName}` : ''}`}\n style={{ cursor: options?.canDrag === false ? 'default' : 'pointer' }}\n >\n <span className=\"rdd-text-truncate rdd-workspace-tab-title\">\n {(() => {\n const icon = panel.icon ?? (options?.icon || defaultPanelIcon || DefaultGridIcon);\n const title = formatLabel(panel.title, formatMessage);\n // The app's content replaces the icon, title and marker; the tab stays ours (7.10.0).\n if (renderTabContent) {\n return renderTabContent({ panelId: id, component: panel.component, title, icon, dirty: panel.dirty === true, selected: isSelected, focused: isGloballyActive });\n }\n return (\n <>\n <span className=\"rdd-workspace-tab-icon\">{icon}</span>\n <span>\n {title}\n {panel.dirty ? ' *' : ''}\n </span>\n </>\n );\n })()}\n </span>\n {options?.renderHeaderActions && (\n <span\n className=\"rdd-tab-header-actions\"\n onClick={(e) => e.stopPropagation()}\n onPointerDown={(e) => e.stopPropagation()}\n >\n {options.renderHeaderActions(id)}\n </span>\n )}\n {options?.canClose !== false && (\n <span\n onClick={(e) => {\n e.stopPropagation();\n onRequestClosePanel(id);\n }}\n title={formatLabel(messages.closeTab, formatMessage)}\n // Not a separate control: interactive content inside role=\"tab\" is not allowed.\n // Keyboard users close the focused tab with Delete.\n aria-hidden=\"true\"\n className={`rdd-close-tab-x${options?.renderHeaderActions ? '' : ' rdd-close-tab-x--end'}`}\n >\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </span>\n )}\n </div>\n );\n })}\n </div>\n {tabScroll.end && (\n <button\n className={`rdd-tab-scroll-btn rdd-tab-scroll-btn-${endSide}`}\n onPointerDown={(e) => e.stopPropagation()}\n onClick={() => scrollTabs('end')}\n tabIndex={-1}\n aria-label={formatLabel(scrollLabel[endSide], formatMessage)}\n >{scrollGlyph[endSide]}</button>\n )}\n\n {/* Empty group close button — only visible when keepOnEmpty keeps the group alive */}\n {leaf.panels.length === 0 && leaf.keepOnEmpty && leaf.canClose !== false && (\n <button\n type=\"button\"\n onClick={() => { void closeLeafGroup(leaf.id); }}\n className=\"rdd-close-tab-x rdd-header-close-empty-group\"\n title={formatLabel(messages.closeEmptyGroup, formatMessage)}\n aria-label={formatLabel(messages.closeEmptyGroup, formatMessage)}\n >\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" aria-hidden=\"true\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </button>\n )}\n </div>\n\n {/* Tab Content Display Area */}\n <div\n id={tabPanelId}\n role=\"tabpanel\"\n aria-labelledby={leaf.activePanelId ? tabIdFor(leaf.activePanelId) : undefined}\n className={`rdd-panel-body ${windowBodyClass ?? ''}`}\n >\n {leaf.activePanelId && state.panels[leaf.activePanelId] ? (\n <PreservedDOMWrapper key={leaf.activePanelId} panelId={leaf.activePanelId} />\n ) : emptyWorkspace !== undefined && leaf.panels.length === 0 ? (\n <div className=\"rdd-empty-workspace\">{emptyWorkspace}</div>\n ) : (\n <div className=\"rdd-empty-leaf-placeholder\">\n <span>{formatLabel(messages.emptyGroup, formatMessage)}</span>\n </div>\n )}\n\n {/* Drag overlay targets cross */}\n {state.draggedPanelId !== null && (() => {\n // State-driven, not :hover-driven — :hover never fires reliably in Safari\n // during an active drag, and doesn't exist at all on touch. activeDropZone\n // already tracks this for mouse, pen, and touch alike (see updateHoverFromPoint).\n const isActive = (pos: DropPosition) => activeDropZone?.leafId === leaf.id && activeDropZone.position === pos;\n // A target the rules forbid isn't offered at all (7.9.0). Zones are drawn by screen side;\n // the move flips left and right under RTL, and canDrop sees the side the move applies.\n const dragged = state.draggedPanelId;\n const applied = (pos: DropPosition): DropPosition =>\n state.isRtl && (pos === 'left' || pos === 'right') ? (pos === 'left' ? 'right' : 'left') : pos;\n const offer = (pos: DropPosition) => isDropAllowed(dragged, { kind: 'group', leafId: leaf.id, position: applied(pos) });\n return (\n <div className=\"rdd-dock-drop-zone-overlay\">\n <div className=\"rdd-dock-target-cross\">\n {/* Top target */}\n {offer('top') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"top\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'top')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-top${isActive('top') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▲\n </div>\n )}\n {/* Bottom target */}\n {offer('bottom') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"bottom\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'bottom')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-bottom${isActive('bottom') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▼\n </div>\n )}\n {/* Left target */}\n {offer('left') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"left\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'left')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-left${isActive('left') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ◀\n </div>\n )}\n {/* Right target */}\n {offer('right') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"right\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'right')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-right${isActive('right') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▶\n </div>\n )}\n {/* Center target */}\n {offer('center') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"center\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'center')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-center${isActive('center') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▣\n </div>\n )}\n </div>\n </div>\n );\n })()}\n\n {/* Visual preview highlight overlay */}\n {state.draggedPanelId !== null && activeDropZone !== null && activeDropZone.leafId === leaf.id && (\n <div\n className=\"rdd-dock-preview-highlight\"\n style={(() => {\n const pos = activeDropZone.position;\n const pct = `${state.splitRatio * 100}%`;\n const rem = `${(1 - state.splitRatio) * 100}%`;\n return {\n left: pos === 'right' ? rem : '0',\n top: pos === 'bottom' ? rem : '0',\n width: (pos === 'left' || pos === 'right') ? pct : '100%',\n height: (pos === 'top' || pos === 'bottom') ? pct : '100%',\n };\n })()}\n />\n )}\n </div>\n </div>\n );\n};\n","/**\n * @file helpers.ts\n * @description Small helpers of the workspace view: tree lookup, tab drop side, the keyboard's right-click, focus after a tab closes, DOM-safe ids.\n */\nimport React from 'react';\nimport { isComputedRtl } from '../../utils/rtl';\nimport type { LayoutNode, LayoutLeafNode } from '../../types';\n\nexport const findLeaf = (node: LayoutNode | null, leafId: string): LayoutLeafNode | null => {\n if (!node) return null;\n if (node.type === 'leaf') return node.id === leafId ? node : null;\n for (const child of node.children) {\n const found = findLeaf(child, leafId);\n if (found) return found;\n }\n return null;\n};\n\n// DOM Element Cache for preserving contexts (WebGL map, text area etc.)\n/**\n * Which side of a tab a dragged tab would drop on, in tab order: 'left' = before it, 'right' =\n * after it. The pointer's half is physical, but insertion (and the RTL-mirrored indicator CSS)\n * is logical — under RTL the physical left half means *after*.\n */\nexport const tabDropSide = (tabEl: Element, clientX: number): 'left' | 'right' => {\n const rect = tabEl.getBoundingClientRect();\n const onPhysicalLeft = clientX - rect.left < rect.width / 2;\n return onPhysicalLeft !== isComputedRtl(tabEl) ? 'left' : 'right';\n};\n\n/**\n * The keyboard's right-click: the ContextMenu key, or Shift+F10. Chrome on macOS sends no\n * `contextmenu` event for either, so the focused control handles them itself (preventing the\n * default, so a platform that does send one doesn't open the menu twice).\n */\nexport const isMenuKey = (e: React.KeyboardEvent): boolean => e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10');\n\n/** Events made by `menuEventAt`: their menu was opened from the keyboard, so it opens on its first item. */\nexport const keyboardMenuEvents: WeakSet<object> = new WeakSet<object>();\n\n/** A `contextmenu` event placed at an element, for opening that element's menu from the keyboard. */\nexport const menuEventAt = (el: Element): React.MouseEvent => {\n const r = el.getBoundingClientRect();\n const event = new MouseEvent('contextmenu', { clientX: r.left, clientY: r.bottom, cancelable: true });\n keyboardMenuEvents.add(event);\n return event as unknown as React.MouseEvent;\n};\n\n/**\n * The menu's initial focus for one of the library's own menus: the first item when it was opened\n * from the keyboard (the Menu key or Shift+F10 via `menuEventAt`, or Enter/Space on a button,\n * whose click has `detail` 0), else the default — the menu itself, nothing highlighted.\n */\nexport const initialFocusFor = (e: React.MouseEvent): 'first-item' | undefined =>\n keyboardMenuEvents.has(e) || (e.type === 'click' && e.detail === 0) ? 'first-item' : undefined;\n\n/**\n * After a tab closed from the keyboard, keep focus in the workspace instead of letting it drop to\n * <body>: the tab selected in its place, else the workspace's active tab, else the workspace.\n * Leaves focus alone if the close was refused, or if something else (a dialog) already moved it.\n */\nexport const refocusAfterTabClose = (id: string, strip: HTMLElement | null, workspaceEl: HTMLElement | null): void => {\n if (!workspaceEl?.isConnected) return;\n const esc = id.replace(/[\"\\\\]/g, '\\\\$&');\n if (workspaceEl.querySelector(`[data-tab-id=\"${esc}\"]`)) return;\n const active = document.activeElement;\n if (active && active !== document.body) return;\n const target = (strip?.isConnected ? strip.querySelector<HTMLElement>('[role=\"tab\"][aria-selected=\"true\"]') : null)\n ?? workspaceEl.querySelector<HTMLElement>('.rdd-workspace-tab-active-focused')\n ?? workspaceEl.querySelector<HTMLElement>('[role=\"tab\"][aria-selected=\"true\"]')\n ?? workspaceEl;\n target.focus();\n};\n\n/** A panel or group id made safe for an HTML `id` (used to link tabs to their tab panel). */\nexport const domIdPart = (raw: string): string => raw.replace(/[^A-Za-z0-9_-]/g, '_');\n\n/** A touch press held this long starts a drag (or opens a menu) instead of a tap. */\nexport const LONG_PRESS_MS = 300;\n/** Moving this far before then cancels the long press: the finger is scrolling, not pressing. */\nexport const CANCEL_MOVE_PX = 8;\n","/**\n * @file icons.tsx\n * @description Icons drawn by the workspace: the default panel icon and the context-menu item icons.\n */\n\n\nexport const DefaultGridIcon: React.ReactElement = (\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"3\" y=\"3\" width=\"7\" height=\"9\" rx=\"1\" />\n <rect x=\"14\" y=\"3\" width=\"7\" height=\"5\" rx=\"1\" />\n <rect x=\"14\" y=\"12\" width=\"7\" height=\"9\" rx=\"1\" />\n <rect x=\"3\" y=\"16\" width=\"7\" height=\"5\" rx=\"1\" />\n </svg>\n);\n\nexport const ContextMenuIcons: Record<'float' | 'minimize' | 'restore' | 'maximize' | 'close', React.ReactElement> = {\n // Two offset equal rects — Windows \"restore-down / new window\" language\n float: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"2\" y=\"8\" width=\"14\" height=\"14\" rx=\"1\"/>\n <rect x=\"8\" y=\"2\" width=\"14\" height=\"14\" rx=\"1\"/>\n </svg>\n </span>\n ),\n // Single horizontal dash — Windows minimize language\n minimize: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\">\n <line x1=\"4\" y1=\"18\" x2=\"20\" y2=\"18\"/>\n </svg>\n </span>\n ),\n // Single inset rect — restore to normal windowed state\n restore: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"1\"/>\n </svg>\n </span>\n ),\n // Near-full rect — maximize / fill workspace\n maximize: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"2\" y=\"2\" width=\"20\" height=\"20\" rx=\"1\"/>\n </svg>\n </span>\n ),\n // × — close\n close: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </span>\n ),\n};\n","/**\n * @file WorkspaceZones.tsx\n * @description The drop targets shown while a panel is dragged: the workspace edges, the corner anchors, and the preview of an edge drop.\n */\nimport React from 'react';\nimport type { SplitDirection, FloatAnchor, WorkspaceState, PanelDropTarget } from '../../types';\n\nexport interface WorkspaceZonesProps {\n state: WorkspaceState;\n activeEdgeDrop: SplitDirection | null;\n activeCornerAnchor: FloatAnchor | null;\n setActiveEdgeDrop: (val: SplitDirection | null) => void;\n setActiveCornerAnchor: (val: FloatAnchor | null) => void;\n /** Whether the dragged panel may go to a target; a forbidden one isn't offered (7.9.0). */\n isDropAllowed: (panelId: string, to: PanelDropTarget) => boolean;\n}\n\n/** The side an edge drop applies: edges are drawn by screen side, and the move flips them under RTL. */\nconst appliedSide = (side: SplitDirection, rtl: boolean): SplitDirection =>\n rtl && (side === 'left' || side === 'right') ? (side === 'left' ? 'right' : 'left') : side;\n\nexport const WorkspaceZones = ({ state, activeEdgeDrop, activeCornerAnchor, setActiveEdgeDrop, setActiveCornerAnchor, isDropAllowed }: WorkspaceZonesProps): React.ReactElement => {\n const dragged = state.draggedPanelId;\n const edge = (side: SplitDirection) => dragged !== null && isDropAllowed(dragged, { kind: 'edge', side: appliedSide(side, state.isRtl) });\n const cornerOffered = (anchor: FloatAnchor) => dragged !== null && isDropAllowed(dragged, { kind: 'float', anchor });\n return (\n <>\n {/* Workspace outer edge drop zone targets */}\n {state.draggedPanelId !== null && (\n <>\n {edge('left') && <div\n data-edge-trigger=\"left\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-left\"\n onPointerEnter={() => setActiveEdgeDrop('left')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n {edge('right') && <div\n data-edge-trigger=\"right\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-right\"\n onPointerEnter={() => setActiveEdgeDrop('right')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n {edge('top') && <div\n data-edge-trigger=\"top\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-top\"\n onPointerEnter={() => setActiveEdgeDrop('top')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n {edge('bottom') && <div\n data-edge-trigger=\"bottom\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-bottom\"\n onPointerEnter={() => setActiveEdgeDrop('bottom')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n </>\n )}\n\n {/* Corner anchor drop zones — appear during floating window drag */}\n {state.draggedPanelId !== null && (['top-left', 'top-right', 'bottom-left', 'bottom-right'] as FloatAnchor[]).filter(cornerOffered).map(corner => (\n <div\n key={corner}\n className={`rdd-corner-zone rdd-corner-zone--${corner}${activeCornerAnchor === corner ? ' rdd-corner-zone--hovered' : ''}`}\n onPointerEnter={() => { setActiveCornerAnchor(corner); setActiveEdgeDrop(null); }}\n onPointerLeave={() => setActiveCornerAnchor(null)}\n aria-hidden=\"true\"\n />\n ))}\n\n {/* Edge drop visual preview overlay */}\n {state.draggedPanelId !== null && activeEdgeDrop !== null && (\n <div\n className=\"rdd-workspace-edge-preview\"\n style={(() => {\n const pct = `${state.edgeSplitRatio * 100}%`;\n switch (activeEdgeDrop) {\n case 'left': return { left: 0, top: 0, bottom: 0, width: pct };\n case 'right': return { right: 0, top: 0, bottom: 0, width: pct };\n case 'top': return { top: 0, left: 0, right: 0, height: pct };\n case 'bottom': return { bottom: 0, left: 0, right: 0, height: pct };\n }\n })()}\n />\n )}\n </>\n );\n};\n","/**\n * @file FloatingWindows.tsx\n * @description The workspace's floating windows: title bar, body slot and resize handles, docked to a corner or free.\n */\nimport React from 'react';\nimport { formatLabel } from '../WindowManagerContext';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, InternalWindowActions } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport type { ResizeDir } from '../dragResize';\nimport { initialFocusFor } from './helpers';\nimport { DefaultGridIcon } from './icons';\nimport { PreservedDOMWrapper } from './panelMount';\n\nexport interface FloatingWindowsProps extends Pick<InternalWindowActions, 'setActivePanel' | 'focusPanel' | 'maximizePanel' | 'minimizePanel' | 'getPanelContextMenuItems' | 'showContextMenu'> {\n state: WorkspaceState;\n registry: PanelRegistry;\n windowClass?: string;\n windowBodyClass?: string;\n defaultPanelIcon?: React.ReactNode;\n messages: Record<MessageKey, MessageDescriptor>;\n formatMessage: MessageFormatter;\n handleRequestClose: (id: string) => unknown;\n startDrag: (id: string, e: React.PointerEvent) => void;\n startResize: (id: string, dir: ResizeDir, e: React.PointerEvent) => void;\n}\n\nexport const FloatingWindows = ({\n state, registry, windowClass, windowBodyClass, defaultPanelIcon, messages, formatMessage,\n setActivePanel, focusPanel, maximizePanel, minimizePanel, getPanelContextMenuItems, showContextMenu,\n handleRequestClose, startDrag, startResize,\n}: FloatingWindowsProps): React.ReactElement => (\n <>\n {state.floating.map(w => {\n const panel = state.panels[w.id];\n if (!panel) return null;\n\n const isMaximized = w.maximized;\n const isDragged = state.draggedPanelId === w.id;\n const isFocused = state.activePanelId === w.id;\n\n const registryEntry = registry.get(panel.component);\n const options = registryEntry?.defaultOptions;\n\n return (\n <div\n key={w.id}\n data-window-id={w.id}\n data-rdd-window={w.id}\n // State for app CSS (7.8.0): present when true.\n data-rdd-focused={isFocused ? '' : undefined}\n data-rdd-maximized={isMaximized ? '' : undefined}\n dir={state.dir}\n onPointerDownCapture={() => {\n setActivePanel(w.id);\n focusPanel(w.id);\n }}\n className={`rdd-floating-window ${isMaximized ? 'rdd-maximized' : ''} ${isFocused ? 'rdd-window-focused' : ''} ${windowClass ?? ''}`}\n style={(() => {\n const CORNER_INSET = 8;\n const CORNER_GAP = 8;\n const w_ = typeof w.width === 'number' ? `${w.width}px` : w.width;\n const h_ = typeof w.height === 'number' ? `${w.height}px` : w.height;\n if (isMaximized) {\n return { position: 'absolute' as const, left: 0, top: 0, width: '100%', height: '100%', zIndex: w.z, pointerEvents: isDragged ? 'none' as const : 'auto' as const };\n }\n if (w.anchor) {\n const stack = state.floating.filter(fw => fw.anchor === w.anchor && !fw.maximized);\n const idx = stack.findIndex(fw => fw.id === w.id);\n let stackOffset = CORNER_INSET;\n for (let i = 0; i < idx; i++) {\n const sh = typeof stack[i].height === 'number' ? stack[i].height as number : parseFloat(stack[i].height as string);\n stackOffset += sh + CORNER_GAP;\n }\n const isTop = w.anchor.startsWith('top');\n const isRight = w.anchor.endsWith('-right');\n return {\n position: 'absolute' as const,\n [isRight ? 'insetInlineEnd' : 'insetInlineStart']: CORNER_INSET,\n [isTop ? 'top' : 'bottom']: stackOffset,\n width: w_,\n height: h_,\n zIndex: w.z,\n transition: isDragged ? 'none' : 'top 0.2s ease, bottom 0.2s ease',\n pointerEvents: isDragged ? 'none' as const : 'auto' as const,\n };\n }\n return {\n position: 'absolute' as const,\n left: typeof w.x === 'number' ? `${w.x}px` : w.x,\n top: typeof w.y === 'number' ? `${w.y}px` : w.y,\n width: w_,\n height: h_,\n zIndex: w.z,\n pointerEvents: isDragged ? 'none' as const : 'auto' as const,\n };\n })()}\n >\n {/* The frame clips title bar and body to the rounded corners. It is a separate\n element so the resize handles (siblings below) can straddle the window edge:\n clipping on the window itself cut off their outer half, and the corners. */}\n <div className=\"rdd-floating-window-frame\">\n {/* Title Bar */}\n <div\n onDoubleClick={() => maximizePanel(w.id)}\n onPointerDown={(e) => {\n if (options?.canDrag !== false) {\n startDrag(w.id, e);\n }\n }}\n data-rdd-titlebar={w.id}\n className=\"rdd-floating-window-titlebar rdd-cursor-move\"\n style={{ cursor: isMaximized || options?.canDrag === false ? 'default' : 'move' }}\n >\n <span className=\"rdd-floating-window-title\">\n <span className=\"rdd-window-title-icon\">{panel.icon ?? (options?.icon || defaultPanelIcon || DefaultGridIcon)}</span>\n <span>\n {formatLabel(panel.title, formatMessage)}\n {panel.dirty ? ' *' : ''}\n </span>\n </span>\n <div className=\"rdd-titlebar-actions\" onPointerDown={(e) => e.stopPropagation()}>\n {options?.renderHeaderActions && (\n <div className=\"rdd-window-header-actions\">\n {options.renderHeaderActions(w.id)}\n </div>\n )}\n {getPanelContextMenuItems(w.id).length > 0 && (\n <button\n type=\"button\"\n className=\"rdd-custom-tab-btn rdd-btn-more-actions\"\n title={formatLabel(messages.moreActions, formatMessage)}\n aria-label={formatLabel(messages.moreActions, formatMessage)}\n onClick={(e) => {\n e.stopPropagation();\n const customItems = getPanelContextMenuItems(w.id);\n if (customItems.length === 0) return;\n showContextMenu({\n event: e,\n items: customItems,\n initialFocus: initialFocusFor(e),\n });\n }}\n >\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <circle cx=\"12\" cy=\"5\" r=\"2\"/>\n <circle cx=\"12\" cy=\"12\" r=\"2\"/>\n <circle cx=\"12\" cy=\"19\" r=\"2\"/>\n </svg>\n </button>\n )}\n <button\n type=\"button\"\n title={isMaximized\n ? formatLabel(messages.restoreSize, formatMessage)\n : formatLabel(messages.maximize, formatMessage)}\n onClick={() => maximizePanel(w.id)}\n className=\"rdd-custom-tab-btn rdd-btn-maximize-tab\"\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"1.5\"/>\n </svg>\n </button>\n {options?.canMinimize !== false && (\n <button\n type=\"button\"\n title={formatLabel(messages.minimize, formatMessage)}\n onClick={() => minimizePanel(w.id)}\n className=\"rdd-custom-tab-btn rdd-btn-minimize-tab\"\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"3\">\n <path d=\"M5 12h14\"/>\n </svg>\n </button>\n )}\n {options?.canClose !== false && (\n <button\n type=\"button\"\n title={formatLabel(messages.close, formatMessage)}\n onClick={() => handleRequestClose(w.id)}\n className=\"rdd-custom-tab-btn rdd-btn-close-tab\"\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"3\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </button>\n )}\n </div>\n </div>\n\n {/* Window Content */}\n <div className={`rdd-floating-window-body${windowBodyClass ? ` ${windowBodyClass}` : ''}`}>\n <PreservedDOMWrapper key={w.id} panelId={w.id} />\n </div>\n </div>\n\n {/* 8-direction resize handles */}\n {!isMaximized && (\n <>\n <div onPointerDown={(e) => startResize(w.id, 'n', e)} className=\"rdd-resize-handle rdd-resize-n\" />\n <div onPointerDown={(e) => startResize(w.id, 'ne', e)} className=\"rdd-resize-handle rdd-resize-ne\" />\n <div onPointerDown={(e) => startResize(w.id, 'e', e)} className=\"rdd-resize-handle rdd-resize-e\" />\n <div onPointerDown={(e) => startResize(w.id, 'se', e)} className=\"rdd-resize-handle rdd-resize-se\" />\n <div onPointerDown={(e) => startResize(w.id, 's', e)} className=\"rdd-resize-handle rdd-resize-s\" />\n <div onPointerDown={(e) => startResize(w.id, 'sw', e)} className=\"rdd-resize-handle rdd-resize-sw\" />\n <div onPointerDown={(e) => startResize(w.id, 'w', e)} className=\"rdd-resize-handle rdd-resize-w\" />\n <div onPointerDown={(e) => startResize(w.id, 'nw', e)} className=\"rdd-resize-handle rdd-resize-nw\" />\n </>\n )}\n </div>\n );\n })}\n </>\n);\n","/**\n * @file Taskbar.tsx\n * @description The taskbar of minimized panels: its items, the hover or long-press preview, scrolling and autohide.\n */\nimport React from 'react';\nimport { createPortal } from 'react-dom';\nimport { formatLabel } from '../WindowManagerContext';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, InternalWindowActions } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport { isMenuKey, menuEventAt, LONG_PRESS_MS, CANCEL_MOVE_PX } from './helpers';\nimport { DefaultGridIcon } from './icons';\nimport { PreviewDOMWrapper } from './panelMount';\nimport type { TaskbarVisibility } from '../WindowManager';\n\n/** The minimized panel whose preview is showing, and where its taskbar item is. */\nexport type HoveredMinimized = { id: string; rect: DOMRect; title: WorkspaceState['minimized'][number]['title']; component: string; fromTouch?: boolean };\n\nexport interface TaskbarProps extends Pick<InternalWindowActions, 'restorePanel'> {\n state: WorkspaceState;\n registry: PanelRegistry;\n taskbarVisibility: TaskbarVisibility;\n taskbarExpanded: boolean;\n expandTaskbar: () => void;\n leaveTaskbar: () => void;\n scrollTaskbar: (direction: 'left' | 'right') => void;\n taskbarRef: React.RefObject<HTMLDivElement | null>;\n /** This workspace's preview tooltip, so the touch dismissal never tests another workspace's. */\n tooltipRef: React.RefObject<HTMLDivElement | null>;\n defaultPanelIcon?: React.ReactNode;\n messages: Record<MessageKey, MessageDescriptor>;\n formatMessage: MessageFormatter;\n lastTaskbarPointerTypeRef: React.RefObject<string>;\n hoveredMinimized: HoveredMinimized | null;\n setHoveredMinimized: (v: HoveredMinimized | null) => void;\n minimizedTooltipTimeoutRef: React.RefObject<ReturnType<typeof setTimeout> | null>;\n isContextMenuOpen: boolean;\n handleMinimizedRightClick: (id: string, e: React.MouseEvent) => void;\n handleRequestClose: (id: string) => unknown;\n}\n\nexport const Taskbar = ({\n state, registry, taskbarVisibility, taskbarExpanded, expandTaskbar, leaveTaskbar, scrollTaskbar,\n taskbarRef, tooltipRef, defaultPanelIcon, messages, formatMessage, lastTaskbarPointerTypeRef, hoveredMinimized,\n setHoveredMinimized, minimizedTooltipTimeoutRef, isContextMenuOpen, handleMinimizedRightClick,\n handleRequestClose, restorePanel,\n}: TaskbarProps): React.ReactElement | null => {\n if (!((taskbarVisibility === 'always' || state.minimized.length > 0))) return null;\n return (\n <div\n className={[\n 'rdd-taskbar-footer-container',\n `rdd-taskbar-mode-${taskbarVisibility}`,\n taskbarVisibility === 'autohide' && taskbarExpanded ? 'rdd-taskbar-expanded' : '',\n ].filter(Boolean).join(' ')}\n onPointerEnter={taskbarVisibility === 'autohide' ? expandTaskbar : undefined}\n onPointerLeave={taskbarVisibility === 'autohide' ? leaveTaskbar : undefined}\n >\n {taskbarVisibility === 'autohide' && <div className=\"rdd-taskbar-peek-handle\" />}\n <button\n type=\"button\"\n onClick={() => scrollTaskbar('left')}\n className=\"rdd-taskbar-nav-btn\"\n aria-label={formatLabel(messages.scrollTaskbarLeft, formatMessage)}\n style={{ display: state.minimized.length > 4 ? 'block' : 'none' }}\n >\n ◀\n </button>\n\n <div\n ref={taskbarRef}\n className=\"rdd-taskbar-items-container\"\n >\n {state.minimized.map(m => {\n const regEntry = registry.get(m.component);\n const icon = state.panels[m.id]?.icon ?? (regEntry?.defaultOptions?.icon || defaultPanelIcon || DefaultGridIcon);\n\n return (\n <button\n type=\"button\"\n key={m.id}\n aria-label={formatLabel(m.title, formatMessage)}\n onClick={(e) => {\n // A touch tap is handled by the long-press logic in onPointerDown. A keyboard\n // click (Enter / Space) has detail 0 and always restores.\n if (e.detail !== 0 && lastTaskbarPointerTypeRef.current === 'touch') return;\n setHoveredMinimized(null);\n restorePanel(m.id);\n }}\n onContextMenu={(e) => handleMinimizedRightClick(m.id, e)}\n onKeyDown={(e) => {\n if (!isMenuKey(e)) return;\n e.preventDefault();\n handleMinimizedRightClick(m.id, menuEventAt(e.currentTarget));\n }}\n onPointerDown={(e) => {\n lastTaskbarPointerTypeRef.current = e.pointerType;\n if (e.pointerType !== 'touch') return;\n const el = e.currentTarget as HTMLElement;\n const startX = e.clientX;\n const startY = e.clientY;\n const pointerId = e.pointerId;\n let cancelled = false;\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', onShortTap);\n el.removeEventListener('pointercancel', cancel);\n };\n const onShortTap = () => {\n cancel();\n const rect = el.getBoundingClientRect();\n if (hoveredMinimized?.id === m.id) {\n restorePanel(m.id);\n setHoveredMinimized(null);\n } else {\n setHoveredMinimized({ id: m.id, rect, title: m.title, component: m.component, fromTouch: true });\n }\n };\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', onShortTap);\n el.removeEventListener('pointercancel', cancel);\n try { el.setPointerCapture(pointerId); } catch { return; }\n if (navigator.vibrate) navigator.vibrate(10);\n const onEnd = (me: PointerEvent) => {\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onEnd);\n handleMinimizedRightClick(m.id, me as unknown as React.MouseEvent);\n };\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onEnd);\n }, LONG_PRESS_MS);\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', onShortTap);\n el.addEventListener('pointercancel', cancel);\n }}\n onPointerEnter={(e) => {\n if (e.pointerType === 'touch') return;\n if (isContextMenuOpen) return;\n if (minimizedTooltipTimeoutRef.current) {\n clearTimeout(minimizedTooltipTimeoutRef.current);\n }\n const rect = e.currentTarget.getBoundingClientRect();\n const isInside = (\n e.clientX >= rect.left &&\n e.clientX <= rect.right &&\n e.clientY >= rect.top &&\n e.clientY <= rect.bottom\n );\n if (!isInside) return;\n setHoveredMinimized({ id: m.id, rect, title: m.title, component: m.component });\n }}\n onPointerLeave={(e) => {\n if (e.pointerType === 'touch') return;\n minimizedTooltipTimeoutRef.current = setTimeout(() => {\n setHoveredMinimized(null);\n }, 150);\n }}\n className=\"rdd-taskbar-glassmorphic-item\"\n data-rdd-taskbar-item={m.id}\n >\n <span className=\"rdd-taskbar-item-icon\" aria-hidden=\"true\">\n {icon}\n </span>\n </button>\n );\n })}\n </div>\n\n {hoveredMinimized && createPortal(\n <div\n ref={tooltipRef}\n className=\"rdd-taskbar-item-tooltip\"\n dir={state.dir}\n style={{\n left: `${hoveredMinimized.rect.left + hoveredMinimized.rect.width / 2}px`,\n top: `${hoveredMinimized.rect.top - 8}px`,\n }}\n onPointerEnter={() => {\n if (minimizedTooltipTimeoutRef.current) {\n clearTimeout(minimizedTooltipTimeoutRef.current);\n }\n }}\n onPointerLeave={(e) => {\n if (e.pointerType === 'touch') return;\n setHoveredMinimized(null);\n }}\n onClick={() => {\n restorePanel(hoveredMinimized.id);\n setHoveredMinimized(null);\n }}\n onContextMenu={(e) => handleMinimizedRightClick(hoveredMinimized.id, e)}\n onPointerDown={(e) => {\n if (e.pointerType !== 'touch') return;\n const tooltipId = hoveredMinimized.id;\n const el = e.currentTarget as HTMLElement;\n const startX = e.clientX;\n const startY = e.clientY;\n const pointerId = e.pointerId;\n let cancelled = false;\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n };\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n try { el.setPointerCapture(pointerId); } catch { return; }\n if (navigator.vibrate) navigator.vibrate(10);\n const onEnd = (me: PointerEvent) => {\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onEnd);\n handleMinimizedRightClick(tooltipId, me as unknown as React.MouseEvent);\n };\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onEnd);\n }, LONG_PRESS_MS);\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', cancel);\n el.addEventListener('pointercancel', cancel);\n }}\n >\n <div className=\"rdd-tooltip-header-row\">\n <span className=\"rdd-tooltip-title-text rdd-text-truncate\">\n {formatLabel(hoveredMinimized.title, formatMessage)}\n {state.panels[hoveredMinimized.id]?.dirty ? ' *' : ''}\n </span>\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n handleRequestClose(hoveredMinimized.id);\n setHoveredMinimized(null);\n }}\n title={formatLabel(messages.closePanel, formatMessage)}\n aria-label={formatLabel(messages.closePanel, formatMessage)}\n className=\"rdd-tooltip-close-x\"\n >\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" aria-hidden=\"true\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </button>\n </div>\n <PreviewDOMWrapper panelId={hoveredMinimized.id} />\n </div>,\n document.body\n )}\n\n <button\n type=\"button\"\n onClick={() => scrollTaskbar('right')}\n className=\"rdd-taskbar-nav-btn\"\n aria-label={formatLabel(messages.scrollTaskbarRight, formatMessage)}\n style={{ display: state.minimized.length > 4 ? 'block' : 'none' }}\n >\n ▶\n </button>\n </div>\n );\n};\n","/**\n * @file useDragTargets.ts\n * @description Where a dragged panel would land: the hovered drop zone, tab, workspace edge or corner, kept both as state (to render) and in refs (to read in pointer handlers), and the ghost position.\n */\nimport React, { useState, useRef } from 'react';\nimport type { SplitDirection, DropPosition, FloatAnchor, InternalWindowActions } from '../../types';\nimport { tabDropSide } from './helpers';\n\ntype DropZoneTarget = { leafId: string; position: DropPosition };\ntype Point = { x: number; y: number };\ntype TabTarget = { leafId: string; panelId: string; index: number; side: 'left' | 'right' };\n\n/**\n * The tab-drag ghost's position. Written on every pointer move and read only by the ghost, so it\n * lives outside React state: a move re-renders the ghost, not the desktop (7.7.2).\n */\nexport interface DragPos {\n get: () => Point;\n set: (v: Point) => void;\n subscribe: (cb: () => void) => () => void;\n}\n\nconst createDragPos = (): DragPos => {\n let pos: Point = { x: 0, y: 0 };\n const listeners = new Set<() => void>();\n return {\n get: () => pos,\n set: (v) => { pos = v; listeners.forEach(l => l()); },\n subscribe: (cb) => { listeners.add(cb); return () => { listeners.delete(cb); }; },\n };\n};\n\nconst sameDropZone = (a: DropZoneTarget | null, b: DropZoneTarget | null) =>\n a === b || (!!a && !!b && a.leafId === b.leafId && a.position === b.position);\nconst sameTab = (a: TabTarget | null, b: TabTarget | null) =>\n a === b || (!!a && !!b && a.leafId === b.leafId && a.panelId === b.panelId && a.index === b.index && a.side === b.side);\n\n/** What `useDragTargets` returns. */\nexport interface DragTargets {\n activeDropZone: DropZoneTarget | null;\n setActiveDropZone: (v: DropZoneTarget | null) => void;\n activeDropZoneRef: React.RefObject<DropZoneTarget | null>;\n dragPos: DragPos;\n setDragPos: (v: Point) => void;\n activeEdgeDrop: SplitDirection | null;\n activeEdgeDropRef: React.RefObject<SplitDirection | null>;\n setActiveEdgeDrop: (val: SplitDirection | null) => void;\n activeCornerAnchor: FloatAnchor | null;\n activeCornerAnchorRef: React.RefObject<FloatAnchor | null>;\n setActiveCornerAnchor: (val: FloatAnchor | null) => void;\n hoveredTab: TabTarget | null;\n setHoveredTab: (v: TabTarget | null) => void;\n hoveredTabRef: React.RefObject<TabTarget | null>;\n handleTabHover: (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => void;\n handleHoverDropZone: (leafId: string, position: DropPosition | null) => void;\n updateHoverFromPoint: (x: number, y: number) => void;\n clearDragState: () => void;\n flipRtl: (pos: DropPosition) => DropPosition;\n}\n\nexport function useDragTargets({ setDraggedPanelId, isRtl, canInsertInto }: {\n setDraggedPanelId: InternalWindowActions['setDraggedPanelId'];\n isRtl: boolean;\n /** Whether the dragged panel may be inserted among a group's tabs; a forbidden group's tabs are no target (7.9.0). */\n canInsertInto: (leafId: string) => boolean;\n}): DragTargets {\n const [activeDropZone, setActiveDropZone] = useState<{ leafId: string; position: DropPosition } | null>(null);\n const activeDropZoneRef = useRef<{ leafId: string; position: DropPosition } | null>(null);\n const [dragPos] = useState(createDragPos);\n const setDragPos = dragPos.set;\n\n const [activeEdgeDrop, setActiveEdgeDropState] = useState<SplitDirection | null>(null);\n const activeEdgeDropRef = useRef<SplitDirection | null>(null);\n const setActiveEdgeDrop = (val: SplitDirection | null) => {\n setActiveEdgeDropState(val);\n activeEdgeDropRef.current = val;\n };\n\n const [activeCornerAnchor, setActiveCornerAnchorState] = useState<FloatAnchor | null>(null);\n const activeCornerAnchorRef = useRef<FloatAnchor | null>(null);\n const setActiveCornerAnchor = (val: FloatAnchor | null) => {\n setActiveCornerAnchorState(val);\n activeCornerAnchorRef.current = val;\n };\n\n const [hoveredTab, setHoveredTab] = useState<{ leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null>(null);\n const hoveredTabRef = useRef<{ leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null>(null);\n\n const handleTabHover = (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => {\n const val = side && canInsertInto(leafId) ? { leafId, panelId, index, side } : null;\n setHoveredTab(val);\n hoveredTabRef.current = val;\n };\n\n const handleHoverDropZone = (leafId: string, position: DropPosition | null) => {\n const val = position ? { leafId, position } : null;\n setActiveDropZone(val);\n activeDropZoneRef.current = val;\n // A leaf's cross commonly overlaps the workspace edge/corner zones underneath it —\n // the more specific per-leaf target wins, matching the corner zone's own handler,\n // which already clears the edge the same way.\n if (val) {\n setActiveEdgeDrop(null);\n setActiveCornerAnchor(null);\n }\n };\n\n // Used during touch drag (pointer capture suppresses hover events on other elements)\n const updateHoverFromPoint = (x: number, y: number) => {\n const elements = document.elementsFromPoint(x, y);\n let foundDropZone = false;\n let foundEdge = false;\n let foundTab = false;\n\n for (const el of elements) {\n if (!(el instanceof HTMLElement)) continue;\n\n if (!foundDropZone && el.dataset.dropZone) {\n const leafId = el.dataset.leafId;\n if (leafId) {\n const val = { leafId, position: el.dataset.dropZone as DropPosition };\n setActiveDropZone(prev => sameDropZone(prev, val) ? prev : val);\n activeDropZoneRef.current = val;\n foundDropZone = true;\n }\n }\n\n // Tabs checked before edge triggers — precise tab intent beats the coarse edge zone\n if (!foundTab && el.dataset.tabId) {\n const leafId = el.dataset.leafId;\n const tabIdx = parseInt(el.dataset.tabIndex || '0', 10);\n if (leafId && canInsertInto(leafId)) {\n const val = { leafId, panelId: el.dataset.tabId, index: tabIdx, side: tabDropSide(el, x) };\n setHoveredTab(prev => sameTab(prev, val) ? prev : val);\n hoveredTabRef.current = val;\n foundTab = true;\n }\n }\n\n if (!foundEdge && el.dataset.edgeTrigger) {\n setActiveEdgeDrop(el.dataset.edgeTrigger as SplitDirection);\n foundEdge = true;\n }\n\n if (foundDropZone && foundEdge && foundTab) break;\n }\n\n if (!foundDropZone) { setActiveDropZone(null); activeDropZoneRef.current = null; }\n if (!foundEdge) setActiveEdgeDrop(null);\n if (!foundTab) { setHoveredTab(null); hoveredTabRef.current = null; }\n };\n\n\n const clearDragState = () => {\n setDraggedPanelId(null);\n setActiveDropZone(null);\n activeDropZoneRef.current = null;\n setHoveredTab(null);\n hoveredTabRef.current = null;\n setActiveEdgeDrop(null);\n setActiveCornerAnchor(null);\n };\n\n const flipRtl = (pos: DropPosition): DropPosition => {\n if (!isRtl) return pos;\n if (pos === 'left') return 'right';\n if (pos === 'right') return 'left';\n return pos;\n };\n\n return {\n activeDropZone, setActiveDropZone, activeDropZoneRef, dragPos, setDragPos,\n activeEdgeDrop, activeEdgeDropRef, setActiveEdgeDrop,\n activeCornerAnchor, activeCornerAnchorRef, setActiveCornerAnchor,\n hoveredTab, setHoveredTab, hoveredTabRef,\n handleTabHover, handleHoverDropZone, updateHoverFromPoint, clearDragState, flipRtl,\n };\n}\n","/**\n * @file tabDrag.ts\n * @description Dragging a tab: a mouse drag, or a touch long-press that drags on move and opens the menu on release; and the drop that docks, reorders or floats the panel.\n */\nimport React from 'react';\nimport type { SplitDirection, WorkspaceState, InternalWindowActions } from '../../types';\nimport { findLeaf, LONG_PRESS_MS, CANCEL_MOVE_PX } from './helpers';\nimport type { DragTargets } from './useDragTargets';\n\nexport interface TabDragDeps {\n state: WorkspaceState;\n targets: DragTargets;\n actions: Pick<InternalWindowActions, 'dockPanelToWorkspaceEdge' | 'movePanelOrder' | 'dockPanelToGroup' | 'floatPanel' | 'setDraggedPanelId' | 'isDropAllowed'>;\n handleTabRightClick: (id: string, e: React.MouseEvent) => void;\n}\n\nexport function createTabDrag(deps: TabDragDeps): { executeDrop: (id: string, me: PointerEvent) => void; handleTabDragStart: (id: string, e: React.PointerEvent) => void } {\n const { state, handleTabRightClick } = deps;\n const { activeDropZoneRef, hoveredTabRef, activeEdgeDropRef, activeCornerAnchorRef, setActiveCornerAnchor, clearDragState, flipRtl, setDragPos, updateHoverFromPoint } = deps.targets;\n const { dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, floatPanel, setDraggedPanelId, isDropAllowed } = deps.actions;\n\n const executeDrop = (id: string, me: PointerEvent) => {\n const dropZone = activeDropZoneRef.current;\n const targetTab = hoveredTabRef.current;\n const edgeDrop = activeEdgeDropRef.current;\n const cornerAnchor = activeCornerAnchorRef.current;\n\n // Each target was only offered if the rules allowed it (7.9.0); asking again here covers a rule\n // that changed mid-drag. A forbidden target, or nowhere when floating is forbidden, does nothing.\n if (edgeDrop) {\n const side = flipRtl(edgeDrop) as SplitDirection;\n if (isDropAllowed(id, { kind: 'edge', side })) dockPanelToWorkspaceEdge(id, side);\n } else if (targetTab) {\n if (!isDropAllowed(id, { kind: 'group', leafId: targetTab.leafId, position: 'center' })) { setActiveCornerAnchor(null); clearDragState(); return; }\n let targetIndex = targetTab.index;\n if (targetTab.side === 'right') targetIndex += 1;\n // DOM tab indices are pre-removal. movePanelOrder removes the panel before\n // inserting, shifting subsequent positions down by 1 in the same leaf.\n // Compensate when the dragged panel currently sits before the drop target.\n const targetLeaf = findLeaf(state.gridRoot, targetTab.leafId);\n if (targetLeaf) {\n const currentIdx = targetLeaf.panels.indexOf(id);\n if (currentIdx !== -1 && currentIdx < targetIndex) targetIndex -= 1;\n }\n movePanelOrder(id, targetTab.leafId, targetIndex);\n } else if (dropZone) {\n const position = flipRtl(dropZone.position);\n if (isDropAllowed(id, { kind: 'group', leafId: dropZone.leafId, position })) dockPanelToGroup(id, dropZone.leafId, position);\n } else if (cornerAnchor) {\n // The zone's name is already the anchor: the CSS mirrors the zones under RTL, and an anchor is\n // drawn mirrored too. Flipping it here as well sent the window to the opposite corner.\n if (isDropAllowed(id, { kind: 'float', anchor: cornerAnchor })) floatPanel(id, undefined, cornerAnchor);\n } else if (isDropAllowed(id, { kind: 'float', anchor: null })) {\n floatPanel(id, { x: me.clientX - 150, y: me.clientY - 15, width: 450, height: 350 });\n }\n setActiveCornerAnchor(null);\n clearDragState();\n };\n\n const handleTabDragStart = (id: string, e: React.PointerEvent) => {\n if (e.pointerType === 'mouse' && e.button !== 0) return;\n e.preventDefault();\n\n const el = e.currentTarget as HTMLElement;\n const startX = e.clientX;\n const startY = e.clientY;\n\n if (e.pointerType === 'touch') {\n const pointerId = e.pointerId;\n let cancelled = false;\n\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n };\n\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n\n try { el.setPointerCapture(pointerId); } catch { return; }\n el.classList.add('rdd-long-press-active');\n document.body.classList.add('rdd-dragging-active');\n if (navigator.vibrate) navigator.vibrate(10);\n\n // Long-press captured: move → drag, release → context menu\n let dragStarted = false;\n\n const onMove = (me: PointerEvent) => {\n if (!dragStarted) {\n dragStarted = true;\n setDraggedPanelId(id);\n }\n setDragPos({ x: me.clientX, y: me.clientY });\n updateHoverFromPoint(me.clientX, me.clientY);\n };\n\n const onEnd = (me: PointerEvent) => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n\n if (dragStarted) {\n executeDrop(id, me);\n } else {\n // Release without drag → context menu\n handleTabRightClick(id, me as unknown as React.MouseEvent);\n }\n };\n\n const onCancel = () => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) clearDragState();\n };\n\n el.addEventListener('pointermove', onMove);\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onCancel);\n // The window losing focus ends the drag, as a pointercancel would (7.4.1).\n window.addEventListener('blur', onCancel);\n }, LONG_PRESS_MS);\n\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', cancel);\n el.addEventListener('pointercancel', cancel);\n } else {\n // Mouse / pen: window-level listeners WITHOUT setPointerCapture so that\n // onPointerEnter/Leave on drop zones and edge triggers still fire normally.\n let dragStarted = false;\n\n const onMove = (me: PointerEvent) => {\n const dx = me.clientX - startX;\n const dy = me.clientY - startY;\n if (!dragStarted && (Math.abs(dx) > 5 || Math.abs(dy) > 5)) {\n dragStarted = true;\n setDraggedPanelId(id);\n }\n if (dragStarted) setDragPos({ x: me.clientX, y: me.clientY });\n };\n\n const onEnd = (me: PointerEvent) => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) executeDrop(id, me);\n };\n\n const onCancel = () => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) clearDragState();\n };\n\n document.body.classList.add('rdd-dragging-active');\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onEnd);\n window.addEventListener('pointercancel', onCancel);\n // The window losing focus (an alt-tab, an iframe taking it) ends the drag, as a\n // pointercancel would (7.4.1): the listeners, the hovered zone and the body class all go,\n // so the next click can't drop the panel into the zone it was over.\n window.addEventListener('blur', onCancel);\n }\n };\n\n return { executeDrop, handleTabDragStart };\n}\n","/**\n * @file workspaceMenus.ts\n * @description The workspace's own context menus: a tab's, and a minimized panel's on the taskbar.\n */\nimport React from 'react';\nimport { formatLabel } from '../WindowManagerContext';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, InternalWindowActions } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport { initialFocusFor } from './helpers';\nimport { ContextMenuIcons } from './icons';\nimport type { HoveredMinimized } from './Taskbar';\n\nexport interface WorkspaceMenusDeps {\n state: WorkspaceState;\n registry: PanelRegistry;\n messages: Record<MessageKey, MessageDescriptor>;\n formatMessage: MessageFormatter;\n handleRequestClose: (id: string) => unknown;\n setHoveredMinimized: (v: HoveredMinimized | null) => void;\n actions: Pick<InternalWindowActions, 'floatPanel' | 'minimizePanel' | 'restorePanel' | 'maximizePanel' | 'getPanelContextMenuItems' | 'showContextMenu' | 'isDropAllowed'>;\n}\n\nexport function createWorkspaceMenus(deps: WorkspaceMenusDeps): { handleTabRightClick: (id: string, e: React.MouseEvent) => void; handleMinimizedRightClick: (id: string, e: React.MouseEvent) => void } {\n const { state, registry, messages, formatMessage, handleRequestClose, setHoveredMinimized } = deps;\n const { floatPanel, minimizePanel, restorePanel, maximizePanel, getPanelContextMenuItems, showContextMenu, isDropAllowed } = deps.actions;\n\n const handleTabRightClick = (id: string, e: React.MouseEvent) => {\n e.preventDefault();\n const panel = state.panels[id];\n if (!panel) return;\n const registryEntry = registry.get(panel.component);\n const options = registryEntry?.defaultOptions;\n\n const items = [];\n // Floating it is a move the rules decide (7.9.0): canFloat, then the app's canDrop.\n if (options?.canDrag !== false && isDropAllowed(id, { kind: 'float', anchor: null })) {\n items.push({\n label: formatLabel(messages.floatWindow, formatMessage),\n icon: ContextMenuIcons.float,\n action: () => floatPanel(id)\n });\n }\n if (options?.canMinimize !== false) {\n items.push({\n label: formatLabel(messages.minimizePanel, formatMessage),\n icon: ContextMenuIcons.minimize,\n action: () => minimizePanel(id)\n });\n }\n if (items.length > 0 && options?.canClose !== false) {\n items.push({ separator: true as const });\n }\n if (options?.canClose !== false) {\n items.push({\n label: formatLabel(messages.closeTab, formatMessage),\n icon: ContextMenuIcons.close,\n action: () => handleRequestClose(id)\n });\n }\n\n if (items.length === 0) return;\n\n const custom = getPanelContextMenuItems(id);\n const finalItems = custom.length > 0 ? [...items, { separator: true as const }, ...custom] : items;\n\n showContextMenu({\n event: e,\n items: finalItems,\n initialFocus: initialFocusFor(e),\n });\n };\n\n const handleMinimizedRightClick = (id: string, e: React.MouseEvent) => {\n e.preventDefault();\n setHoveredMinimized(null);\n // Maximizing needs a floating window. A panel minimized from a group is floated on the way\n // back, which a `canDrag: false` panel refuses — so for it the item would do nothing.\n const panel = state.panels[id];\n // A panel that was floating only goes back to floating; one from a group is floated, which the\n // rules decide (7.9.0).\n const canMaximize = panel?.previousState === 'floating'\n || (registry.get(panel?.component ?? '')?.defaultOptions?.canDrag !== false && isDropAllowed(id, { kind: 'float', anchor: null }));\n showContextMenu({\n event: e,\n initialFocus: initialFocusFor(e),\n items: [\n {\n label: formatLabel(messages.restorePanel, formatMessage),\n icon: ContextMenuIcons.restore,\n action: () => restorePanel(id)\n },\n ...(canMaximize ? [{\n label: formatLabel(messages.maximizePanel, formatMessage),\n icon: ContextMenuIcons.maximize,\n action: () => maximizePanel(id)\n }] : []),\n { separator: true },\n {\n label: formatLabel(messages.closePanel, formatMessage),\n icon: ContextMenuIcons.close,\n action: () => handleRequestClose(id)\n }\n ]\n });\n };\n\n return { handleTabRightClick, handleMinimizedRightClick };\n}\n","/**\n * @file useWorkspaceSize.ts\n * @description The workspace's measured size, kept current by a ResizeObserver, with development warnings when the workspace has no height or is taller than the window.\n */\nimport React, { useState, useEffect } from 'react';\n\nexport function useWorkspaceSize(workspaceRef: React.RefObject<HTMLDivElement | null>): { width: number; height: number } {\n const [workspaceSize, setWorkspaceSize] = useState({ width: 1024, height: 768 });\n\n // Dynamically observe the workspace container bounds (accounts for sidebar expanding/collapsing and taskbar showing/hiding)\n useEffect(() => {\n const el = workspaceRef.current;\n if (!el) return;\n\n let heightWarnShown = false;\n let tallWarnShown = false;\n\n const observer = new ResizeObserver((entries) => {\n if (!entries || entries.length === 0) return;\n const rect = entries[0].contentRect;\n\n if (process.env.NODE_ENV === 'development' && rect.height < 10 && !heightWarnShown) {\n heightWarnShown = true;\n\n // Walk up the ancestor chain to find the highest zero-height element\n let culprit: Element = el;\n let cursor = el.parentElement;\n while (cursor && cursor !== document.documentElement) {\n if (cursor.getBoundingClientRect().height < 10) {\n culprit = cursor;\n } else {\n break;\n }\n cursor = cursor.parentElement;\n }\n\n const tag = culprit.tagName.toLowerCase();\n const id = culprit.id ? ` id=\"${culprit.id}\"` : '';\n const cls = culprit.className ? ` class=\"${culprit.className}\"` : '';\n const who = culprit === el\n ? 'the RddDesktop container itself'\n : `a wrapper element: <${tag}${id}${cls}>`;\n\n console.warn(\n `[react-dockable-desktop] Workspace height is 0px — the workspace will be invisible.\\n\\n` +\n `Zero height found at: ${who}\\n\\n` +\n `Root cause: in CSS, \"height: 100%\" only works when the parent has an explicit height.\\n` +\n `If any ancestor has height: auto (the default for <div>), the chain breaks and\\n` +\n `everything inside collapses to 0px.\\n\\n` +\n `Fix options:\\n` +\n ` 1. Use height: 100vh directly on the workspace wrapper:\\n` +\n ` <div style={{ height: '100vh', overflow: 'hidden' }}>\\n` +\n ` <RddDesktop />\\n` +\n ` </div>\\n\\n` +\n ` 2. Use CSS Grid/Flex and let the workspace fill remaining space:\\n` +\n ` .layout { display: flex; flex-direction: column; height: 100vh; }\\n` +\n ` .workspace { flex: 1; min-height: 0; }\\n\\n` +\n ` 3. For a workspace that fills the window, put className=\"rdd-fill-viewport\" on its wrapper.`\n );\n }\n\n // Without a height of its own, a workspace in a full-window app grows with its content and the\n // *page* scrolls instead of the panels. Until 7.0 the stylesheet hid that by fixing\n // html, body and #root to the viewport; it no longer styles the host page.\n if (process.env.NODE_ENV === 'development' && !tallWarnShown\n && rect.height > window.innerHeight + 1\n && document.documentElement.scrollHeight > window.innerHeight + 1) {\n tallWarnShown = true;\n console.warn(\n `[react-dockable-desktop] The workspace is taller than the window (${Math.round(rect.height)}px > ` +\n `${window.innerHeight}px), so the page scrolls instead of the panels.\\n\\n` +\n `For a workspace that fills the window, give its wrapper the rdd-fill-viewport class:\\n` +\n ` <div className=\"rdd-fill-viewport\"> … <RddDesktop /> … </div>\\n\\n` +\n `(Before 7.0 the stylesheet fixed html, body and #root to 100% height; it no longer styles the host page.)`\n );\n }\n\n setWorkspaceSize({\n width: Math.max(100, rect.width),\n height: Math.max(100, rect.height)\n });\n });\n\n observer.observe(el);\n return () => {\n observer.disconnect();\n };\n }, [workspaceRef]);\n\n return workspaceSize;\n}\n","/**\n * @file floatingWindowDrag.ts\n * @description Moving a floating window by its title bar (mouse, or touch long-press), dropping it on a dock target or corner, and resizing it from any of its eight handles.\n */\nimport React from 'react';\nimport type { SplitDirection, WorkspaceState, InternalWindowActions } from '../../types';\nimport { startPointerDrag, computeResizedRect } from '../dragResize';\nimport type { ResizeDir } from '../dragResize';\nimport { LONG_PRESS_MS, CANCEL_MOVE_PX } from './helpers';\nimport type { DragTargets } from './useDragTargets';\n\nexport interface FloatingWindowDragDeps {\n state: WorkspaceState;\n workspaceSize: { width: number; height: number };\n targets: DragTargets;\n actions: Pick<InternalWindowActions, 'focusPanel' | 'updateFloatingPosition' | 'dockPanelToWorkspaceEdge' | 'movePanelOrder' | 'dockPanelToGroup' | 'setDraggedPanelId' | 'isDropAllowed'>;\n}\n\nexport function createFloatingWindowDrag(deps: FloatingWindowDragDeps): { startDrag: (id: string, e: React.PointerEvent) => void; startResize: (id: string, dir: ResizeDir, e: React.PointerEvent) => void } {\n const { state, workspaceSize } = deps;\n const { activeDropZoneRef, hoveredTabRef, activeEdgeDropRef, activeCornerAnchorRef, setActiveCornerAnchor, clearDragState, flipRtl, updateHoverFromPoint } = deps.targets;\n const { focusPanel, updateFloatingPosition, dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, setDraggedPanelId, isDropAllowed } = deps.actions;\n\n // Floating Window dragging handler\n const startDrag = (id: string, e: React.PointerEvent) => {\n e.preventDefault();\n const floatingWin = state.floating.find(w => w.id === id);\n if (!floatingWin || floatingWin.maximized) return;\n focusPanel(id);\n\n const el = e.currentTarget as HTMLDivElement;\n const windowEl = el.closest('.rdd-floating-window') as HTMLDivElement | null;\n const startX = e.clientX;\n const startY = e.clientY;\n const startPosX = windowEl ? windowEl.offsetLeft : 0;\n const startPosY = windowEl ? windowEl.offsetTop : 0;\n\n const executeFWDrop = () => {\n const dropZone = activeDropZoneRef.current;\n const targetTab = hoveredTabRef.current;\n const edgeDrop = activeEdgeDropRef.current;\n const cornerAnchor = activeCornerAnchorRef.current;\n // Asked again at release, as in the tab drag (7.9.0); a forbidden target leaves it floating.\n if (cornerAnchor) {\n if (isDropAllowed(id, { kind: 'float', anchor: cornerAnchor })) updateFloatingPosition(id, { anchor: cornerAnchor }); // already the anchor — see the tab drop above\n } else if (edgeDrop) {\n const side = flipRtl(edgeDrop) as SplitDirection;\n if (isDropAllowed(id, { kind: 'edge', side })) dockPanelToWorkspaceEdge(id, side);\n } else if (targetTab) {\n let targetIndex = targetTab.index;\n if (targetTab.side === 'right') targetIndex += 1;\n if (isDropAllowed(id, { kind: 'group', leafId: targetTab.leafId, position: 'center' })) movePanelOrder(id, targetTab.leafId, targetIndex);\n } else if (dropZone) {\n const position = flipRtl(dropZone.position);\n if (isDropAllowed(id, { kind: 'group', leafId: dropZone.leafId, position })) dockPanelToGroup(id, dropZone.leafId, position);\n }\n setActiveCornerAnchor(null);\n clearDragState();\n };\n\n if (e.pointerType === 'touch') {\n const pointerId = e.pointerId;\n let cancelled = false;\n\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n };\n\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n\n try { el.setPointerCapture(pointerId); } catch { return; }\n el.classList.add('rdd-long-press-active');\n document.body.classList.add('rdd-dragging-active');\n setDraggedPanelId(id);\n\n const onMove = (me: PointerEvent) => {\n const dx = me.clientX - startX;\n const dy = me.clientY - startY;\n updateFloatingPosition(id, { x: startPosX + dx, y: startPosY + dy, anchor: null });\n updateHoverFromPoint(me.clientX, me.clientY);\n };\n\n const onEnd = () => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n executeFWDrop();\n };\n\n const onCancel = () => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n clearDragState();\n };\n\n el.addEventListener('pointermove', onMove);\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onCancel);\n // The window losing focus ends the drag, as a pointercancel would (7.4.1).\n window.addEventListener('blur', onCancel);\n }, LONG_PRESS_MS);\n\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', cancel);\n el.addEventListener('pointercancel', cancel);\n } else {\n // Mouse / pen: window-level listeners WITHOUT setPointerCapture so that\n // onPointerEnter/Leave on drop zones and edge triggers still fire normally.\n let dragStarted = false;\n\n const onMove = (me: PointerEvent) => {\n const dx = me.clientX - startX;\n const dy = me.clientY - startY;\n if (!dragStarted && (Math.abs(dx) > 5 || Math.abs(dy) > 5)) {\n dragStarted = true;\n setDraggedPanelId(id);\n }\n if (dragStarted) {\n updateFloatingPosition(id, { x: startPosX + dx, y: startPosY + dy, anchor: null });\n }\n };\n\n const onEnd = () => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) executeFWDrop();\n };\n\n const onCancel = () => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) clearDragState();\n };\n\n document.body.classList.add('rdd-dragging-active');\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onEnd);\n window.addEventListener('pointercancel', onCancel);\n // The window losing focus ends the drag, as a pointercancel would (7.4.1): the next click\n // can't dock the window into the zone it was over.\n window.addEventListener('blur', onCancel);\n }\n };\n\n // Floating Window resizing handler — supports 8 directions\n const startResize = (id: string, dir: ResizeDir, e: React.PointerEvent) => {\n e.preventDefault();\n e.stopPropagation();\n const floatingWin = state.floating.find(w => w.id === id);\n if (!floatingWin || floatingWin.maximized) return;\n focusPanel(id);\n\n const el = e.currentTarget as HTMLDivElement;\n const windowEl = el.closest('.rdd-floating-window') as HTMLDivElement | null;\n const startRect = {\n x: windowEl ? windowEl.offsetLeft : 0,\n y: windowEl ? windowEl.offsetTop : 0,\n w: windowEl ? windowEl.offsetWidth : 400,\n h: windowEl ? windowEl.offsetHeight : 300,\n };\n\n const viewW = workspaceSize.width;\n const viewH = workspaceSize.height;\n const parsedX = typeof floatingWin.x === 'string' ? parseFloat(floatingWin.x) : floatingWin.x;\n const parsedY = typeof floatingWin.y === 'string' ? parseFloat(floatingWin.y) : floatingWin.y;\n const parsedW = typeof floatingWin.width === 'string' ? parseFloat(floatingWin.width) : floatingWin.width;\n const parsedH = typeof floatingWin.height === 'string' ? parseFloat(floatingWin.height) : floatingWin.height;\n const isRightSnapped = dir === 'se' && Math.abs(parsedX + parsedW - viewW) < 4;\n const isBottomSnapped = dir === 'se' && Math.abs(parsedY + parsedH - viewH) < 4;\n\n startPointerDrag({\n element: el,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => startRect,\n activeClasses: [{ el: document.body, classes: ['rdd-resizing-active'] }],\n // No maxW/maxH/minX/minY: this window is intentionally allowed to grow\n // unbounded and be dragged fully off-screen, same as before this refactor.\n onMove: (dx, dy, start) => {\n const resized = computeResizedRect(dir, dx, dy, start, { minW: 200, minH: 150 });\n let { x: newX, y: newY, w: newW, h: newH } = resized;\n\n // Snap adjustments for SE corner when previously snapped to workspace edges\n if (isRightSnapped) {\n newX = viewW - newW;\n if (newX < 0) { newX = 0; newW = viewW; }\n }\n if (isBottomSnapped) {\n newY = viewH - newH;\n if (newY < 0) { newY = 0; newH = viewH; }\n }\n\n updateFloatingPosition(id, { x: newX, y: newY, width: newW, height: newH });\n },\n });\n };\n\n return { startDrag, startResize };\n}\n","import React, { useCallback, useRef, useState, useMemo } from 'react';\nimport { usePanelState, usePanelActions } from './PanelProviderContext';\nimport { FormContainerProvider, type FormContainerContract, type CloseOptions } from './FormContainerContext';\nimport type { OverlayInstance, ModalOptions, PanelTitle } from './PanelProviderContext';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport { useFormatMessage, formatLabel, useStyleClasses, usePredefinedMessages, useWindowManagerState } from './WindowManagerContext';\nimport ConfirmationForm from '../forms/ConfirmationForm';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Interface representing props for the internal {@link ModalRenderer} component.\n */\ninterface ModalRendererProps {\n /** The panel instance containing component structure, state, and option flags. */\n modal: OverlayInstance;\n /** The 0-based depth index of the modal within the active stack. */\n index: number;\n /** True if this modal is currently at the top of the stack. */\n}\n\n/**\n * ModalRenderer component renders a single modal window wrapped inside\n * the FormContainerProvider context, enabling subcomponents to request closes and set dirty states.\n */\nconst ModalRenderer: React.FC<ModalRendererProps> = ({ modal, index }) => {\n const { close, openModal, updateInstance, setDirty, onInstanceClose } = usePanelActions();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const dir = useWindowManagerState(s => s.dir);\n const { modalClass, modalBodyClass } = useStyleClasses();\n const closeHandlerRef = useRef<(() => boolean | Promise<boolean>) | null>(null);\n\n const { id, Component, props, options, dirty, dirtyOptions } = modal;\n const modalOptions = options as ModalOptions;\n\n const [icon, setIconState] = useState<React.ReactNode>(modalOptions.icon || null);\n\n const optionsRef = useLatestRef(modalOptions);\n\n const baseTitle = formatLabel(modalOptions.title, formatMessage);\n\n const handleClose = useCallback(async (options?: CloseOptions) => {\n if (options?.force) {\n close(id);\n return;\n }\n\n if (closeHandlerRef.current) {\n const canClose = await closeHandlerRef.current();\n if (!canClose) return;\n close(id);\n return;\n }\n\n if (dirty) {\n openModal(\n ConfirmationForm,\n {\n title: dirtyOptions?.title || predefinedMessages.unsavedChangesTitle,\n message: dirtyOptions?.message || {\n id: predefinedMessages.unsavedChangesMessage.id,\n defaultMessage: predefinedMessages.unsavedChangesMessage.defaultMessage,\n values: { title: baseTitle }\n },\n alert: dirtyOptions?.alert,\n alertType: dirtyOptions?.alertType || 'danger',\n useYesNoTitles: true,\n onOK: () => close(id),\n },\n { size: 'small' }\n );\n return;\n }\n\n close(id);\n }, [close, openModal, id, dirty, dirtyOptions, baseTitle, predefinedMessages]);\n\n const handleSetDirty = useCallback((dirty: boolean, options?: DirtyStateOptions) => setDirty(id, dirty, options), [setDirty, id]);\n const handleSetTitle = useCallback((title: PanelTitle) => updateInstance(id, { options: { ...optionsRef.current, title } }), [updateInstance, id, optionsRef]);\n const handleSetIcon = useCallback((newIcon: React.ReactNode) => setIconState(newIcon), []);\n const handleOnCloseRequested = useCallback((handler: () => boolean | Promise<boolean>) => {\n closeHandlerRef.current = handler;\n return () => { closeHandlerRef.current = null; };\n }, []);\n\n const handleOnClose = useCallback((handler: () => void) => onInstanceClose(id, handler), [onInstanceClose, id]);\n\n const contract: FormContainerContract = useMemo(() => ({\n requestClose: handleClose,\n setDirty: handleSetDirty,\n setTitle: handleSetTitle,\n setIcon: handleSetIcon,\n onCloseRequested: handleOnCloseRequested,\n containerType: 'modal',\n instanceId: id,\n onClose: handleOnClose,\n }), [handleClose, handleOnClose, handleSetDirty, handleSetTitle, handleSetIcon, handleOnCloseRequested, id]);\n\n const displayTitle = dirty ? `${baseTitle} *` : baseTitle;\n\n const sizeClass = modalOptions.size ? `rdd-modal-size-${modalOptions.size}` : 'rdd-modal-size-auto';\n const showCloseButton = modalOptions.closable !== false;\n\n const bodyPadding = modalOptions.bodyPadding;\n const bodyPaddingStyle = bodyPadding != null\n ? (typeof bodyPadding === 'number' ? `${bodyPadding}px` : bodyPadding)\n : undefined;\n\n // Every mounted modal takes its place on the shared Escape stack, where the most recently\n // opened one is on top. One that can't be closed still consumes the key, so Escape never\n // reaches a drawer behind it.\n useEscapeLayer(true, 'modal', () => {\n if (showCloseButton) handleClose();\n });\n\n // Reads the same --rdd-z-base a WindowManagerProvider's zIndexBase config mirrors\n // onto documentElement (falls back to 1000 so this also works standalone, with\n // no WindowManager mounted, matching the :root default in index.css).\n const modalZIndex = `calc(var(--rdd-z-base, 1000) + 9000 + ${index * 10})`;\n\n return (\n <div className=\"rdd-modal-overlay\" style={{ zIndex: modalZIndex }} dir={dir}>\n <div className=\"rdd-modal-curtain\" onClick={showCloseButton ? () => handleClose() : undefined} />\n <div className={`rdd-modal-window ${sizeClass} ${modalClass ?? ''}`}>\n <div className=\"rdd-modal-header\">\n {icon && <div className=\"rdd-modal-icon\">{icon}</div>}\n <h4 className=\"rdd-modal-title\">{displayTitle}</h4>\n {showCloseButton && (\n <button\n className=\"rdd-modal-close-button\"\n onClick={() => handleClose()}\n title={formatMessage(predefinedMessages.closeTooltip)}\n type=\"button\"\n >\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\" />\n </svg>\n </button>\n )}\n </div>\n <div\n className={`rdd-modal-body ${modalBodyClass ?? ''}`}\n style={bodyPaddingStyle != null ? { padding: bodyPaddingStyle } : undefined}\n >\n <FormContainerProvider value={contract}>\n <Component {...props} panelId={id} />\n </FormContainerProvider>\n </div>\n </div>\n </div>\n );\n};\n\n/**\n * Renders the modals opened through `useModals()`, stacked, topmost last. Mount one, inside\n * `<DockableDesktopProvider>`.\n */\nexport const ModalStackRenderer: React.FC = () => {\n const { modals } = usePanelState();\n\n if (modals.length === 0) return null;\n\n return (\n <>\n {modals.map((modal, index) => (\n <ModalRenderer\n key={modal.id}\n modal={modal}\n index={index}\n />\n ))}\n </>\n );\n};\n\nexport default ModalStackRenderer;\n","/**\n * @file Sidebar.tsx\n * @description Sidebar activity bar (strip) and resizable content drawer.\n * The strip and drawer are independently controllable via `visible` and\n * `stripVisible`. Drawer width is pixel-based and user-draggable using the\n * same pointer-capture interaction as the panel grid resizer.\n */\n\nimport React, {\n useState,\n useEffect,\n useRef,\n useCallback,\n useImperativeHandle,\n useContext,\n useMemo,\n createContext,\n forwardRef,\n memo,\n} from 'react';\nimport { startPointerDrag } from './dragResize';\nimport { isComputedRtl } from '../utils/rtl';\nimport { formatLabel, useFormatMessage, usePredefinedMessages, useOptionalWindowManagerState } from './WindowManagerContext';\n\n// ==========================================\n// Types\n// ==========================================\n\n/**\n * Per-tab configuration supplied by the consuming application.\n */\nexport interface SidebarTab {\n id: string;\n label: string;\n /** Required unless `hidden` is true — a hidden tab never renders a rail button, so it has no icon to show. */\n icon?: React.ReactNode;\n /**\n * Omit this tab's rail button entirely — no icon, no click target — while it\n * remains fully openable via `openTab()` / `useSidebar().openTab()` / a controlled\n * `activeTabId`. Use for menu-driven panels with no persistent icon (e.g. a\n * Google-Maps-style hamburger that opens content not otherwise pinned to the rail).\n * Default: false\n */\n hidden?: boolean;\n /**\n * Mount immediately when the Sidebar first renders, not on first user click.\n * Implies `preserveState: true`.\n * Default: false\n */\n eagerMount?: boolean;\n /**\n * Keep the component alive behind `display: none` when closed instead of\n * unmounting it. Use for panels with expensive local state.\n * Default: false\n */\n preserveState?: boolean;\n /**\n * Called to obtain the drawer content for this tab.\n * @param tabId - the id of this tab\n * @param onClose - call to collapse the sidebar drawer\n * @param onOpen - call to expand the drawer and select this tab\n */\n renderContent: (tabId: string, onClose: () => void, onOpen: () => void) => React.ReactNode;\n}\n\n/**\n * Simple case for `RddSidebarProps.headerAction`/`footerAction`: the library renders a\n * default-styled icon button (visually consistent with the regular tab buttons) and forwards\n * the click.\n */\nexport interface SidebarActionButton {\n /** Only needed when used inside a `SidebarRailEntry[]` array, for the React key. */\n id?: string;\n icon: React.ReactNode;\n /** Tooltip and aria-label — same convention as `SidebarTab.label`. */\n label: string;\n onClick: () => void;\n disabled?: boolean;\n}\n\n/**\n * Full-control case for `RddSidebarProps.headerAction`/`footerAction`: the consumer supplies their\n * own markup (a Material UI `IconButton`, a Bootstrap `Button`, a Tailwind-styled `<button>`, or\n * anything else) wholesale. The library renders exactly what this returns, unwrapped, so the\n * consumer's own hover/active/focus/ripple behavior and click handling are untouched.\n */\nexport interface SidebarCustomEntry {\n /** Only needed when used inside a `SidebarRailEntry[]` array, for the React key. */\n id?: string;\n render: () => React.ReactNode;\n}\n\n/**\n * A single, non-toggling action button shown above the tab strip (e.g. a hamburger menu).\n * Unlike `SidebarTab`, it never affects `activeTabId` or the drawer — the library only renders\n * it and forwards the click; what happens next (opening a side panel, a modal, anything else)\n * is entirely up to the consumer.\n */\nexport type SidebarHeaderAction = SidebarActionButton | SidebarCustomEntry;\n\n/**\n * A single entry inside `RddSidebarProps.headerAction`/`footerAction` when used as an array: either\n * a non-toggling action button/custom render (see `SidebarHeaderAction`), or a real `SidebarTab`\n * that behaves exactly like a main-list tab — it mounts, activates, and closes through the same\n * lifecycle, so e.g. a \"Settings\" entry pinned to the footer can expand like any other tab.\n */\nexport type SidebarRailEntry = SidebarTab | SidebarActionButton | SidebarCustomEntry;\n\nfunction isRailTab(entry: SidebarRailEntry): entry is SidebarTab {\n return 'renderContent' in entry;\n}\n\nfunction isRailCustom(entry: SidebarRailEntry): entry is SidebarCustomEntry {\n return 'render' in entry;\n}\n\nfunction toRailArray(value: SidebarRailEntry | SidebarRailEntry[] | undefined): SidebarRailEntry[] {\n if (value == null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nexport interface RddSidebarProps {\n /** Which side the activity bar and drawer appear on. Default: 'right' */\n position?: 'left' | 'right';\n tabs: SidebarTab[];\n /**\n * One or more non-toggling action buttons and/or real tabs shown above the tabs, in their\n * own `.rdd-sidebar-header-area` — independent of the tabs' own inter-item gap. Pass a single\n * `{ icon, label, onClick }`/`{ render }` object (the common case), or an array mixing action\n * buttons, custom renders, and `SidebarTab` entries — a tab entry here behaves exactly like a\n * main-list tab (mounts, activates, closes through the same lifecycle). Override\n * `--rdd-sidebar-header-area-padding-top`/`--rdd-sidebar-header-area-padding-bottom`\n * (both default `8px`) to control its spacing/effective height.\n */\n headerAction?: SidebarRailEntry | SidebarRailEntry[];\n /**\n * Mirror of `headerAction`, pinned to the bottom of the tab strip via its own\n * `.rdd-sidebar-footer-area` — e.g. a \"Settings\" tab that should always sit at the bottom\n * regardless of tab count. Override `--rdd-sidebar-footer-area-padding-top`/\n * `--rdd-sidebar-footer-area-padding-bottom` (both default `8px`) to control its spacing.\n */\n footerAction?: SidebarRailEntry | SidebarRailEntry[];\n /** Initial drawer width in pixels. Default: 280 */\n defaultWidth?: number;\n /** Minimum drawer width in pixels during drag-resize. Default: 150 */\n minWidth?: number;\n /** Maximum drawer width in pixels during drag-resize. Default: 600 */\n maxWidth?: number;\n /** Called during drag resize and on setWidth() with the new pixel width. */\n onWidthChange?: (px: number) => void;\n /** Controlled active tab id. Omit to use internal state. */\n activeTabId?: string | null;\n /** Called when the active tab changes. */\n onActiveTabChange?: (tabId: string | null) => void;\n /** Collapse the entire sidebar (strip + drawer). Default: true */\n visible?: boolean;\n /** Called when show/hide/toggle is invoked on the imperative handle. */\n onVisibilityChange?: (visible: boolean) => void;\n /** Collapse only the activity bar strip, leaving the drawer unaffected. Default: true */\n stripVisible?: boolean;\n /** Called when showStrip/hideStrip is invoked on the imperative handle. */\n onStripVisibilityChange?: (visible: boolean) => void;\n /**\n * Show an \"X\" close button in the expanded drawer's header, as an additional way to collapse\n * the sidebar (equivalent to clicking the active tab's own icon again). Opt-in. Default: false.\n * Has no effect once the default header is suppressed — via `hideDefaultHeader`, or simply by\n * passing `renderHeader` (either one is sufficient) — since the entire default header, this\n * button included, is skipped for every tab in that case.\n */\n showCloseButton?: boolean;\n /**\n * Suppress the library's own drawer header (title + `showCloseButton`'s close\n * button) for every tab, so `renderHeader` (or each tab's own `renderContent`)\n * can supply a header, border, and styling instead. Applies uniformly across\n * all tabs — there's no per-tab override. Passing `renderHeader` by itself has\n * the same suppressing effect even if this is left unset — the two conditions\n * are combined with OR, precisely so that supplying `renderHeader` alone is\n * never a silent no-op. The close mechanism is unaffected either way: the\n * `onClose` parameter passed to `renderContent`/`renderHeader`, or\n * `useSidebarTab().onClose` from anywhere in a tab's content tree.\n * Default: false\n */\n hideDefaultHeader?: boolean;\n /**\n * Custom header renderer used in place of the library's own drawer header.\n * Passing `renderHeader` is by itself sufficient to suppress the default\n * header, whether or not `hideDefaultHeader` is also set — the two props are\n * combined with OR. Called once for whichever tab is currently active, so\n * the same header markup (e.g. a hamburger icon, a search field, a close\n * button) is shared uniformly across every tab instead of being repeated\n * inside each tab's own `renderContent`. Omit `renderHeader` and set\n * `hideDefaultHeader: true` to render no header at all and let each tab's\n * `renderContent` supply its own instead.\n * @param tab - the currently active tab\n * @param onClose - call to collapse the sidebar drawer\n * @param onOpen - call to (re-)select this tab\n */\n renderHeader?: (tab: SidebarTab, onClose: () => void, onOpen: () => void) => React.ReactNode;\n /**\n * @internal Marks this instance as a secondary sidebar for context-broadcasting\n * purposes. Set automatically by `<RddSecondarySidebar>` — do not pass this directly.\n * Default: false\n */\n isSecondary?: boolean;\n /** Main workspace content rendered alongside the sidebar. */\n children?: React.ReactNode;\n}\n\n/**\n * Imperative handle exposed by `<RddSidebar ref={...}>`.\n */\nexport interface SidebarHandle {\n openTab: (tabId: string) => void;\n closeDrawer: () => void;\n getActiveTab: () => string | null;\n show: () => void;\n hide: () => void;\n toggle: () => void;\n showStrip: () => void;\n hideStrip: () => void;\n setWidth: (px: number) => void;\n getWidth: () => number;\n}\n\n/**\n * Value provided by `useSidebar()`. Available to any component inside the\n * `<RddSidebar>` React tree, including panels rendered via `{children}`.\n */\nexport interface SidebarContextValue {\n openTab: (tabId: string) => void;\n closeDrawer: () => void;\n getActiveTab: () => string | null;\n /** Which side this Sidebar instance is rendering on. */\n position: 'left' | 'right';\n /** True if this instance is a `<RddSecondarySidebar>`, false for a primary `<RddSidebar>`. */\n isSecondary: boolean;\n}\n\n/**\n * Value provided by `useSidebarTab()`. Available only to components rendered\n * inside a sidebar tab's `renderContent` tree.\n */\nexport interface SidebarTabContextValue {\n tabId: string;\n onOpen: () => void;\n onClose: () => void;\n openTab: (tabId: string) => void;\n}\n\n// ==========================================\n// Contexts\n// ==========================================\n\nconst SidebarContext = createContext<SidebarContextValue | null>(null);\nconst SidebarTabContext = createContext<SidebarTabContextValue | null>(null);\n\n// ==========================================\n// SidebarTabProvider (internal)\n// ==========================================\n\ninterface SidebarTabProviderProps {\n tabId: string;\n onClose: () => void;\n onOpen: () => void;\n setActiveTabId: (id: string | null) => void;\n children: React.ReactNode;\n}\n\nfunction SidebarTabProvider({ tabId, onClose, onOpen, setActiveTabId, children }: SidebarTabProviderProps) {\n const value = useMemo<SidebarTabContextValue>(() => ({\n tabId,\n onClose,\n onOpen,\n openTab: (otherId: string) => setActiveTabId(otherId),\n }), [tabId, onClose, onOpen, setActiveTabId]);\n\n return <SidebarTabContext.Provider value={value}>{children}</SidebarTabContext.Provider>;\n}\n\n// ==========================================\n// renderRailEntry (internal helper)\n// Shared by the header/footer areas only — dispatches a SidebarRailEntry to a tab button,\n// a default-styled action button, or a fully custom render. The main tabs-list keeps its own\n// inline JSX below since it only ever renders SidebarTab entries.\n// ==========================================\n\nfunction renderRailEntry(\n entry: SidebarRailEntry,\n index: number,\n activeTabId: string | null | undefined,\n onTabClick: (tabId: string) => void\n): React.ReactNode {\n if (isRailCustom(entry)) {\n return <React.Fragment key={entry.id ?? index}>{entry.render()}</React.Fragment>;\n }\n if (isRailTab(entry)) {\n if (entry.hidden) return null;\n const isActive = activeTabId === entry.id;\n return (\n <button\n key={entry.id}\n type=\"button\"\n onClick={() => onTabClick(entry.id)}\n data-rdd-sidebar-tab={entry.id}\n className={`rdd-sidebar-tab-btn${isActive ? ' rdd-active' : ''}`}\n title={entry.label}\n aria-pressed={isActive}\n >\n {entry.icon}\n </button>\n );\n }\n return (\n <button\n key={entry.id ?? index}\n type=\"button\"\n onClick={entry.onClick}\n disabled={entry.disabled}\n className=\"rdd-sidebar-tab-btn rdd-sidebar-header-action-btn\"\n title={entry.label}\n aria-label={entry.label}\n >\n {entry.icon}\n </button>\n );\n}\n\n// ==========================================\n// SidebarTabStrip (internal sub-component)\n// Re-renders only when tabs, selection, or strip visibility changes —\n// not on drawer width changes during drag.\n// ==========================================\n\ninterface SidebarTabStripProps {\n tabs: SidebarTab[];\n headerEntries: SidebarRailEntry[];\n footerEntries: SidebarRailEntry[];\n activeTabId: string | null | undefined;\n isVisible: boolean;\n position: 'left' | 'right';\n onTabClick: (tabId: string) => void;\n}\n\nconst SidebarTabStrip = memo(function SidebarTabStrip({\n tabs,\n headerEntries,\n footerEntries,\n activeTabId,\n isVisible,\n position,\n onTabClick,\n}: SidebarTabStripProps) {\n return (\n // Outer div drives the collapse transition via overflow:hidden.\n // The inner rdd-sidebar-tabs-strip must NOT have overflow:hidden so the active\n // tab's negative margin can extend into the drawer border without clipping.\n <div className={`rdd-sidebar-strip-wrap${isVisible ? '' : ' rdd-sidebar-strip-wrap--collapsed'}`}>\n <div\n className={`rdd-sidebar-tabs-strip rdd-${position}${headerEntries.length ? ' rdd-sidebar-tabs-strip--has-header-action' : ''}${footerEntries.length ? ' rdd-sidebar-tabs-strip--has-footer-action' : ''}`}\n >\n {headerEntries.length > 0 && (\n <div className=\"rdd-sidebar-header-area\">\n {headerEntries.map((entry, i) => renderRailEntry(entry, i, activeTabId, onTabClick))}\n </div>\n )}\n <div className=\"rdd-sidebar-tabs-list\">\n {tabs.map(tab => {\n if (tab.hidden) return null;\n const isActive = activeTabId === tab.id;\n return (\n <button\n key={tab.id}\n type=\"button\"\n onClick={() => onTabClick(tab.id)}\n data-rdd-sidebar-tab={tab.id}\n className={`rdd-sidebar-tab-btn${isActive ? ' rdd-active' : ''}`}\n title={tab.label}\n aria-pressed={isActive}\n >\n {tab.icon}\n </button>\n );\n })}\n </div>\n {footerEntries.length > 0 && (\n <div className=\"rdd-sidebar-footer-area\">\n {footerEntries.map((entry, i) => renderRailEntry(entry, i, activeTabId, onTabClick))}\n </div>\n )}\n </div>\n </div>\n );\n});\n\n// ==========================================\n// SidebarResizeHandle (internal sub-component)\n// Encapsulates all pointer-capture drag logic.\n// Identical interaction pattern to the panel grid resizer in workspace/WorkspaceGrid.tsx.\n// ==========================================\n\ninterface SidebarResizeHandleProps {\n position: 'left' | 'right';\n currentWidth: number;\n minWidth: number;\n maxWidth: number;\n onWidthChange: (newWidth: number) => void;\n onResizeStart: () => void;\n onResizeEnd: () => void;\n}\n\nfunction SidebarResizeHandle({\n position,\n currentWidth,\n minWidth,\n maxWidth,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n}: SidebarResizeHandleProps) {\n const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n e.preventDefault();\n const el = e.currentTarget;\n const activeClasses: Array<{ el: HTMLElement; classes: string[] }> = [\n { el, classes: ['rdd-active'] },\n { el: document.body, classes: ['rdd-resizing-active', 'rdd-resizing-col-active'] },\n ];\n // Suppress the drawer's CSS transition so drag feels instant — driven by this\n // instance's own isResizing state (see the drawer's style below), not a DOM\n // class + descendant selector, which would leak across a nested secondary\n // Sidebar's subtree since it's a literal DOM descendant of this one.\n onResizeStart();\n\n const onPhysicalRight = (position === 'right') !== isComputedRtl(el);\n\n startPointerDrag({\n element: el,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => currentWidth,\n activeClasses,\n onMove: (dx, _dy, startWidth) => {\n // The sign follows the drawer's physical edge, not the prop: the sidebar is a plain flex\n // row, so under RTL position=\"left\" renders on the right. A drawer on the physical right\n // widens when dragged left (negative dx).\n const newW = onPhysicalRight ? startWidth - dx : startWidth + dx;\n onWidthChange(Math.max(minWidth, Math.min(maxWidth, newW)));\n },\n onEnd: () => onResizeEnd(),\n });\n };\n\n return (\n <div\n className=\"rdd-resizer-bar rdd-resizer-bar--vertical\"\n onPointerDown={handlePointerDown}\n />\n );\n}\n\n// ==========================================\n// Sidebar (main component)\n// ==========================================\n\nexport const Sidebar: React.ForwardRefExoticComponent<RddSidebarProps & React.RefAttributes<SidebarHandle>> =\n forwardRef<SidebarHandle, RddSidebarProps>(function Sidebar(\n {\n position = 'right',\n tabs,\n headerAction,\n footerAction,\n defaultWidth,\n minWidth = 150,\n maxWidth = 600,\n onWidthChange,\n activeTabId: controlledActiveTabId,\n onActiveTabChange,\n visible,\n onVisibilityChange,\n stripVisible,\n onStripVisibilityChange,\n showCloseButton = false,\n hideDefaultHeader = false,\n renderHeader,\n isSecondary = false,\n children,\n },\n ref\n ) {\n const workspaceDir = useOptionalWindowManagerState(s => s.dir, undefined);\n const isControlled = controlledActiveTabId !== undefined;\n const formatMessage = useFormatMessage();\n const closeLabel = formatLabel(usePredefinedMessages().closeTooltip, formatMessage);\n\n const [width, setWidthState] = useState<number>(() => defaultWidth ?? 280);\n\n const setWidth = useCallback((px: number) => {\n setWidthState(px);\n onWidthChange?.(px);\n }, [onWidthChange]);\n\n // Suppresses the drawer's CSS transition during a resize drag — own state,\n // not a DOM class, so it can never leak into a nested secondary Sidebar's\n // drawer (see SidebarResizeHandle's onResizeStart/onResizeEnd below).\n const [isResizing, setIsResizing] = useState(false);\n\n // Internal active tab state (uncontrolled mode)\n const [internalActiveTabId, setInternalActiveTabId] = useState<string | null>(null);\n const activeTabId = isControlled ? controlledActiveTabId : internalActiveTabId;\n\n // Normalized header/footer rail entries, and the SidebarTab-shaped subset of each — a\n // header/footer tab (e.g. \"Settings\") must share the exact same lifecycle as a main tab.\n const normalizedHeaderEntries = useMemo(() => toRailArray(headerAction), [headerAction]);\n const normalizedFooterEntries = useMemo(() => toRailArray(footerAction), [footerAction]);\n const headerTabs = useMemo(() => normalizedHeaderEntries.filter(isRailTab), [normalizedHeaderEntries]);\n const footerTabs = useMemo(() => normalizedFooterEntries.filter(isRailTab), [normalizedFooterEntries]);\n const allTabs = useMemo(() => [...headerTabs, ...tabs, ...footerTabs], [headerTabs, tabs, footerTabs]);\n\n // Tracks which non-eager tabs have been mounted at least once (for lazy-mount / preserveState).\n // eagerMount tabs are folded in via effectiveMountedTabIds below, so no effect needed for them.\n const [mountedTabIds, setMountedTabIds] = useState<Set<string>>(() => new Set<string>());\n\n // Derives the full mounted set during render — no effect needed.\n // Includes: accumulated mountedTabIds + the currently active tab (handles controlled\n // prop changes where setActiveTabId is never called) + all eagerMount tabs.\n const effectiveMountedTabIds = useMemo(() => {\n const result = new Set(mountedTabIds);\n if (activeTabId) result.add(activeTabId);\n for (const tab of allTabs) {\n if (tab.eagerMount) result.add(tab.id);\n }\n return result;\n }, [mountedTabIds, activeTabId, allTabs]);\n\n // Stable refs for imperative handle\n const activeTabIdRef = useRef<string | null>(activeTabId ?? null);\n useEffect(() => { activeTabIdRef.current = activeTabId ?? null; }, [activeTabId]);\n\n const widthRef = useRef<number>(width);\n useEffect(() => { widthRef.current = width; }, [width]);\n\n const setActiveTabId = useCallback(\n (id: string | null) => {\n // Update mounted set in the same render batch as the tab switch — avoids setState-in-effect.\n if (id !== null) {\n setMountedTabIds(prev => {\n if (prev.has(id)) return prev;\n const next = new Set(prev);\n next.add(id);\n return next;\n });\n } else {\n // Drawer closing: evict transient tabs (non-eager, non-preserveState).\n setMountedTabIds(prev => {\n let changed = false;\n const next = new Set(prev);\n for (const tabId of prev) {\n const tab = allTabs.find(t => t.id === tabId);\n if (tab && !tab.eagerMount && !tab.preserveState) {\n next.delete(tabId);\n changed = true;\n }\n }\n return changed ? next : prev;\n });\n }\n if (isControlled) {\n onActiveTabChange?.(id);\n } else {\n setInternalActiveTabId(id);\n onActiveTabChange?.(id);\n }\n },\n [isControlled, onActiveTabChange, allTabs]\n );\n\n // If the active tab stops existing in `tabs`/`headerAction`/`footerAction` (its contributing\n // panel changed/closed, or the tab was otherwise removed), close the drawer rather than\n // leaving it open and empty with no tab button left to click closed — never silently fall\n // back to a different tab the user didn't choose.\n useEffect(() => {\n if (activeTabId != null && !allTabs.some(t => t.id === activeTabId)) {\n // Through setActiveTabId on purpose: it also tells a controlling parent (onActiveTabChange).\n // eslint-disable-next-line react-hooks/set-state-in-effect\n setActiveTabId(null);\n }\n }, [activeTabId, allTabs, setActiveTabId]);\n\n useImperativeHandle(ref, () => ({\n openTab: (tabId: string) => setActiveTabId(tabId),\n closeDrawer: () => setActiveTabId(null),\n getActiveTab: () => activeTabIdRef.current,\n show: () => onVisibilityChange?.(true),\n hide: () => onVisibilityChange?.(false),\n toggle: () => onVisibilityChange?.(visible === false ? true : false),\n showStrip: () => onStripVisibilityChange?.(true),\n hideStrip: () => onStripVisibilityChange?.(false),\n setWidth: (px: number) => setWidth(Math.max(minWidth, Math.min(maxWidth, px))),\n getWidth: () => widthRef.current,\n }), [setActiveTabId, visible, onVisibilityChange, onStripVisibilityChange, setWidth, minWidth, maxWidth]);\n\n const handleTabClick = useCallback((tabId: string) => {\n setActiveTabId(activeTabId === tabId ? null : tabId);\n }, [activeTabId, setActiveTabId]);\n\n const handleClose = useCallback(() => setActiveTabId(null), [setActiveTabId]);\n\n // `renderHeader` alone (no `hideDefaultHeader`) also suppresses the default\n // header — see the render condition below. Derived once here so both that\n // condition and the dev-warning effect stay in sync.\n const hasHeaderOverride = hideDefaultHeader || renderHeader != null;\n\n // Dev-only: showCloseButton renders nothing once the default header is\n // suppressed, since its close button is part of that (now-skipped) header.\n // Warns once per mounted Sidebar — closeButtonWarnedRef lives in component\n // scope (not inside the effect) so it survives re-renders; depending on the\n // derived boolean rather than `renderHeader` itself avoids re-running this\n // on every render, since `renderHeader` is typically passed as a fresh\n // inline arrow function each time.\n const closeButtonWarnedRef = useRef(false);\n useEffect(() => {\n if (process.env.NODE_ENV !== 'development') return;\n if (!showCloseButton || !hasHeaderOverride) return;\n if (closeButtonWarnedRef.current) return;\n closeButtonWarnedRef.current = true;\n console.warn(\n '[react-dockable-desktop] `showCloseButton` has no effect because the default header is ' +\n 'suppressed (`hideDefaultHeader` is set, or `renderHeader` was passed). The \"X\" close button ' +\n 'only renders as part of the library\\'s own default header, which is skipped in this case. ' +\n 'Add your own close control inside `renderHeader` (or `renderContent`), wired to its `onClose` ' +\n 'parameter or `useSidebarTab().onClose`.'\n );\n }, [showCloseButton, hasHeaderOverride]);\n\n // Stable context value for useSidebar() consumers\n const sidebarContextValue = useMemo<SidebarContextValue>(() => ({\n openTab: (tabId: string) => setActiveTabId(tabId),\n closeDrawer: () => setActiveTabId(null),\n getActiveTab: () => activeTabIdRef.current,\n position,\n isSecondary,\n }), [setActiveTabId, position, isSecondary]);\n\n // ---- Derived visibility flags ----\n const isSidebarVisible = visible !== false;\n const isStripVisible = isSidebarVisible && stripVisible !== false;\n const isDrawerOpen = isSidebarVisible && activeTabId != null;\n\n // ---- Drawer element (shared between left and right) ----\n const drawer = (\n <div\n className={`rdd-sidebar-content-drawer rdd-${position}`}\n style={{\n // flex-basis drives the visible width; width: 0px has no effect in flex context\n // when flex-basis is set — so we animate flex-basis, not width.\n flexBasis: isDrawerOpen ? `${width}px` : '0px',\n minWidth: isDrawerOpen ? `${minWidth}px` : '0px',\n maxWidth: isDrawerOpen ? `${maxWidth}px` : '0px',\n // Suppressed during a resize drag via this instance's own isResizing state.\n transition: isResizing\n ? 'none'\n : 'flex-basis 0.2s cubic-bezier(0.4, 0, 0.2, 1), min-width 0.2s cubic-bezier(0.4, 0, 0.2, 1), max-width 0.2s cubic-bezier(0.4, 0, 0.2, 1)',\n }}\n >\n {allTabs.map(tab => {\n const isMounted = effectiveMountedTabIds.has(tab.id);\n if (!isMounted) return null;\n\n const isCurrent = activeTabId === tab.id;\n const onOpen = () => setActiveTabId(tab.id);\n\n return (\n <div key={tab.id} className=\"rdd-sidebar-pane\" style={{ display: isCurrent ? 'flex' : 'none' }}>\n {/* Drawer header — tab label, plus an optional close button (showCloseButton) as\n an extra way to collapse the sidebar; clicking the active tab icon still works too.\n Suppressed for every tab when hideDefaultHeader is set, OR simply when renderHeader\n is passed (either alone is sufficient — see hasHeaderOverride above, which keeps\n this in sync with the dev-warning effect) — onClose/onOpen still flow to either\n one regardless. */}\n {hasHeaderOverride ? (\n renderHeader?.(tab, handleClose, onOpen)\n ) : (\n <div className=\"rdd-sidebar-drawer-header\">\n <span className=\"rdd-sidebar-header-title\">{tab.label}</span>\n {showCloseButton && (\n <button\n type=\"button\"\n className=\"rdd-sidebar-drawer-close-button\"\n onClick={handleClose}\n title={closeLabel}\n aria-label={closeLabel}\n >\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\" />\n </svg>\n </button>\n )}\n </div>\n )}\n\n {/* Drawer body — consumer-supplied content */}\n <div className=\"rdd-sidebar-drawer-body\">\n <SidebarTabProvider\n tabId={tab.id}\n onClose={handleClose}\n onOpen={onOpen}\n setActiveTabId={setActiveTabId}\n >\n {tab.renderContent(tab.id, handleClose, onOpen)}\n </SidebarTabProvider>\n </div>\n </div>\n );\n })}\n </div>\n );\n\n // ---- Resize handle (only interactive when drawer is open) ----\n const resizeHandle = isDrawerOpen ? (\n <SidebarResizeHandle\n position={position}\n currentWidth={width}\n minWidth={minWidth}\n maxWidth={maxWidth}\n onWidthChange={setWidth}\n onResizeStart={() => setIsResizing(true)}\n onResizeEnd={() => setIsResizing(false)}\n />\n ) : null;\n\n return (\n <SidebarContext.Provider value={sidebarContextValue}>\n {/* A sidebar is usually an ancestor of the workspace, so the workspace's own dir never\n reached it: setDirection('rtl') mirrored the desktop beside an unmirrored rail. It now\n follows the workspace into RTL; otherwise it inherits the page's direction, as before. */}\n <div className=\"rdd-sidebar-layout\" dir={workspaceDir === 'rtl' ? 'rtl' : undefined}>\n {position === 'left' && (\n <SidebarTabStrip\n tabs={tabs}\n headerEntries={normalizedHeaderEntries}\n footerEntries={normalizedFooterEntries}\n activeTabId={activeTabId}\n isVisible={isStripVisible}\n position={position}\n onTabClick={handleTabClick}\n />\n )}\n {position === 'left' && drawer}\n {position === 'left' && resizeHandle}\n\n {/* Workspace content — fills all remaining space */}\n <div className=\"rdd-sidebar-content\">\n {children}\n </div>\n\n {position === 'right' && resizeHandle}\n {position === 'right' && drawer}\n {position === 'right' && (\n <SidebarTabStrip\n tabs={tabs}\n headerEntries={normalizedHeaderEntries}\n footerEntries={normalizedFooterEntries}\n activeTabId={activeTabId}\n isVisible={isStripVisible}\n position={position}\n onTabClick={handleTabClick}\n />\n )}\n </div>\n </SidebarContext.Provider>\n );\n });\n\n// ==========================================\n// SecondarySidebar\n// ==========================================\n\n/**\n * Props for {@link RddSecondarySidebar} — identical to {@link RddSidebarProps} except\n * `position` (always the opposite of whatever primary `Sidebar` it's nested inside)\n * and `isSecondary` (always `true`) are not settable.\n */\nexport type RddSecondarySidebarProps = Omit<RddSidebarProps, 'position' | 'isSecondary'>;\n\n/**\n * A second, independent `Sidebar` instance for the opposite edge of the screen —\n * same component, same behavior, zero forked code. Must be rendered inside a\n * primary `Sidebar`'s `children`; automatically takes whichever side that primary\n * isn't using, so the side is never specified directly.\n *\n * @throws Error if rendered without an ancestor `Sidebar`, or nested inside another\n * `RddSecondarySidebar` — this library supports exactly one primary and one secondary,\n * nothing deeper.\n */\nexport const SecondarySidebar: React.ForwardRefExoticComponent<RddSecondarySidebarProps & React.RefAttributes<SidebarHandle>> =\n forwardRef<SidebarHandle, RddSecondarySidebarProps>(function SecondarySidebar(props, ref) {\n const primary = useContext(SidebarContext);\n if (!primary) {\n throw new Error('RddSecondarySidebar must be rendered inside a primary RddSidebar\\'s children');\n }\n if (primary.isSecondary) {\n throw new Error('RddSecondarySidebar cannot be nested inside another RddSecondarySidebar');\n }\n const opposite = primary.position === 'left' ? 'right' : 'left';\n return <Sidebar ref={ref} {...props} position={opposite} isSecondary />;\n });\n\n// ==========================================\n// Hooks\n// ==========================================\n\n/**\n * Returns sidebar control functions from anywhere inside a `<RddSidebar>` tree,\n * including floating panels rendered via `{children}`.\n *\n * @throws Error if used outside of an {@link RddSidebar}.\n */\nexport function useSidebar(): SidebarContextValue {\n const ctx = useContext(SidebarContext);\n if (!ctx) throw new Error('useSidebar must be used within <RddSidebar>');\n return ctx;\n}\n\n/**\n * Returns tab-specific control functions for components rendered inside a\n * sidebar tab's `renderContent` tree.\n *\n * @throws Error if used outside of an {@link RddSidebar} tab's `renderContent` tree.\n */\nexport function useSidebarTab(): SidebarTabContextValue {\n const ctx = useContext(SidebarTabContext);\n if (!ctx) throw new Error('useSidebarTab must be used within an RddSidebar tab\\'s renderContent');\n return ctx;\n}\n\n","/**\n * @file Toolbar.tsx\n * @description Vertical or horizontal toolbar strip hosting action buttons,\n * mutually-exclusive radio tool groups, independent toggle modifiers,\n * and collapsible sub-tool group flyouts.\n * State is library-wide via DockableDesktopProvider / ToolbarContext.\n */\n\nimport React, { forwardRef, useImperativeHandle, useState, useRef, useEffect, useLayoutEffect } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useToolbar } from './ToolbarContext';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { isComputedRtl } from '../utils/rtl';\nimport { enabledItems, moveMenuFocus } from '../utils/menuKeyboard';\nimport type { ToolbarContextValue } from './ToolbarContext';\n\n// ==========================================\n// Item type definitions\n// ==========================================\n\n/** A one-shot action button. */\nexport interface ToolbarActionItem {\n type: 'action';\n id: string;\n label: string;\n icon: React.ReactNode;\n onClick: () => void;\n disabled?: boolean;\n}\n\n/** A mutually-exclusive radio button within a named group. */\nexport interface ToolbarRadioItem {\n type: 'radio';\n id: string;\n group: string;\n label: string;\n icon: React.ReactNode;\n /** Keyboard shortcut hint — displayed in the group flyout; reserved for future custom tooltip. */\n shortcut?: string;\n /** Called when this item becomes active. */\n onActivate?: (id: string) => void;\n disabled?: boolean;\n}\n\n/**\n * An independent on/off toggle modifier (e.g. snap-to-grid).\n *\n * Supports both uncontrolled mode (omit `rdd-active` — state lives in\n * ToolbarContext, keyed by `id`) and controlled mode (provide `rdd-active` —\n * the caller is the single source of truth and must update the prop in\n * response to `onToggle`). Controlled mode is what lets independent\n * instances of the same panel type report independent active state\n * instead of colliding on a shared id.\n */\nexport interface ToolbarToggleItem {\n type: 'toggle';\n id: string;\n label: string;\n icon: React.ReactNode;\n /** Keyboard shortcut hint — reserved for future custom tooltip. */\n shortcut?: string;\n /**\n * Controlled active state. When provided (even as false), the component\n * reads this prop instead of ToolbarContext and does not update context\n * on click. Omit (undefined) for uncontrolled behaviour.\n */\n active?: boolean;\n /** Called after the toggle flips; receives the new active state. */\n onToggle?: (active: boolean) => void;\n disabled?: boolean;\n}\n\n/** A visual divider between button groups. */\nexport interface ToolbarSeparator {\n type: 'separator';\n}\n\n// ==========================================\n// Group item types (sub-tool flyout)\n// ==========================================\n\n/**\n * A single selectable sub-tool inside a group flyout.\n * All sub-items in the same ToolbarGroupItem share one radio group\n * keyed by the parent ToolbarGroupItem's `id`.\n */\nexport interface ToolbarGroupSubItem {\n id: string;\n label: string;\n icon: React.ReactNode;\n /** Keyboard shortcut displayed in the flyout panel. */\n shortcut?: string;\n disabled?: boolean;\n /** Called when this sub-item is selected. */\n onActivate?: (id: string) => void;\n}\n\n/** An entry inside a group flyout — either a sub-item or a separator. */\nexport type ToolbarGroupEntry = ToolbarGroupSubItem | { type: 'separator' };\n\n/**\n * A collapsed tool-family button that opens a flyout panel listing all\n * sub-tools. Only one sub-tool may be active at a time (radio semantics).\n * The parent button's icon morphs to show the currently active sub-tool.\n *\n * Supports both uncontrolled mode (omit activeItemId — state lives in\n * ToolbarContext) and controlled mode (provide activeItemId — the caller\n * is the single source of truth and must update the prop in response to\n * onActiveItemChange).\n */\nexport interface ToolbarGroupItem {\n type: 'group';\n /** Serves as both the button ID and the radio group key in ToolbarContext. */\n id: string;\n /** Tooltip / aria-label shown when no sub-item is active. */\n label: string;\n /** Icon shown when no sub-item is active. */\n defaultIcon: React.ReactNode;\n items: ToolbarGroupEntry[];\n disabled?: boolean;\n /**\n * Controlled active sub-item id. When provided (even as null), the\n * component reads this prop instead of ToolbarContext and fires\n * onActiveItemChange on click instead of updating context.\n * Omit (undefined) for uncontrolled behaviour.\n */\n activeItemId?: string | null;\n /**\n * Called when the user selects a sub-item in controlled mode.\n * The toolbar does not update itself — the caller must update activeItemId.\n */\n onActiveItemChange?: (id: string) => void;\n}\n\nexport type ToolbarItem =\n | ToolbarActionItem\n | ToolbarRadioItem\n | ToolbarToggleItem\n | ToolbarGroupItem\n | ToolbarSeparator;\n\n// ==========================================\n// Props and Handle\n// ==========================================\n\nexport interface RddToolbarProps {\n /** Side the strip is attached to. Controls strip orientation. Default: 'left' */\n position?: 'left' | 'right' | 'top' | 'bottom';\n /** Ordered list of items to render. */\n items: ToolbarItem[];\n /** Collapse the strip to zero width/height. State is preserved — no unmount. */\n visible?: boolean;\n /** Called when show/hide/toggle is invoked on the imperative handle. */\n onVisibilityChange?: (visible: boolean) => void;\n className?: string;\n style?: React.CSSProperties;\n}\n\nexport interface ToolbarHandle {\n show(): void;\n hide(): void;\n toggle(): void;\n}\n\n// ==========================================\n// ToolbarGroupButton — internal sub-component\n// Manages its own open/close state and renders the flyout via a portal\n// so it is never clipped by the strip's overflow:hidden.\n// ==========================================\n\ninterface ToolbarGroupButtonProps {\n item: ToolbarGroupItem;\n position: 'left' | 'right' | 'top' | 'bottom';\n toolbar: ToolbarContextValue;\n}\n\nfunction flyoutPosition(\n rect: DOMRect,\n position: 'left' | 'right' | 'top' | 'bottom',\n isRtl = false,\n gap = 8,\n): React.CSSProperties {\n switch (position) {\n case 'left':\n // RTL: flex-row reverses, so 'left' toolbar sits on the right → open leftward\n return isRtl\n ? { right: window.innerWidth - rect.left + gap, top: rect.top }\n : { left: rect.right + gap, top: rect.top };\n case 'right':\n // RTL: 'right' toolbar sits on the left → open rightward\n return isRtl\n ? { left: rect.right + gap, top: rect.top }\n : { right: window.innerWidth - rect.left + gap, top: rect.top };\n case 'top':\n return isRtl\n ? { top: rect.bottom + gap, right: window.innerWidth - rect.right }\n : { top: rect.bottom + gap, left: rect.left };\n case 'bottom':\n return isRtl\n ? { bottom: window.innerHeight - rect.top + gap, right: window.innerWidth - rect.right }\n : { bottom: window.innerHeight - rect.top + gap, left: rect.left };\n }\n}\n\nfunction ToolbarGroupButton({ item, position, toolbar }: ToolbarGroupButtonProps) {\n const [isOpen, setIsOpen] = useState(false);\n const [btnRect, setBtnRect] = useState<DOMRect | null>(null);\n const [btnRtl, setBtnRtl] = useState(false);\n const btnRef = useRef<HTMLButtonElement>(null);\n const flyoutRef = useRef<HTMLDivElement>(null);\n\n const isControlled = item.activeItemId !== undefined;\n const activeId = isControlled ? item.activeItemId : toolbar.getActiveInGroup(item.id);\n const activeSubItem = item.items.find(\n (e): e is ToolbarGroupSubItem => !('type' in e) && e.id === activeId,\n );\n const isActive = activeId !== null;\n const displayIcon = activeSubItem?.icon ?? item.defaultIcon;\n const displayLabel = activeSubItem?.label ?? item.label;\n\n const handleClick = () => {\n if (item.disabled) return;\n if (!isOpen && btnRef.current) {\n setBtnRect(btnRef.current.getBoundingClientRect());\n // The strip's own computed direction decides which side it sits on — RTL may be set on\n // <body> or a wrapper, not just <html>, and an LTR strip can sit on an RTL page.\n setBtnRtl(isComputedRtl(btnRef.current));\n }\n setIsOpen(prev => !prev);\n };\n\n // Clamp flyout to viewport after it renders (runs before paint to avoid jitter)\n useLayoutEffect(() => {\n if (!isOpen || !flyoutRef.current) return;\n const el = flyoutRef.current;\n const r = el.getBoundingClientRect();\n const PAD = 8;\n if (r.right > window.innerWidth - PAD) {\n el.style.left = `${Math.max(PAD, window.innerWidth - r.width - PAD)}px`;\n el.style.right = 'auto';\n }\n if (r.left < PAD) {\n el.style.left = `${PAD}px`;\n el.style.right = 'auto';\n }\n if (r.bottom > window.innerHeight - PAD) {\n el.style.top = `${Math.max(PAD, window.innerHeight - r.height - PAD)}px`;\n el.style.bottom = 'auto';\n }\n if (r.top < PAD) {\n el.style.top = `${PAD}px`;\n el.style.bottom = 'auto';\n }\n }, [isOpen]);\n\n // Close flyout on click-away (exclude clicks inside the button or flyout itself)\n useEffect(() => {\n if (!isOpen) return;\n const onMouseDown = (e: MouseEvent) => {\n const target = e.target as Node;\n if (btnRef.current?.contains(target)) return;\n if (flyoutRef.current?.contains(target)) return;\n setIsOpen(false);\n };\n document.addEventListener('mousedown', onMouseDown);\n return () => document.removeEventListener('mousedown', onMouseDown);\n }, [isOpen]);\n\n // Closing from inside the flyout (Escape, Tab, choosing an item) hands focus back to the\n // trigger, as the context menu does; a click elsewhere leaves focus where the click put it.\n const closeFlyout = () => {\n if (flyoutRef.current?.contains(document.activeElement)) btnRef.current?.focus();\n setIsOpen(false);\n };\n\n // Open: focus the chosen item, else the first (WAI-ARIA menu pattern).\n useLayoutEffect(() => {\n if (!isOpen) return;\n const items = enabledItems(flyoutRef.current);\n (items.find(el => el.getAttribute('aria-checked') === 'true') ?? items[0])?.focus();\n }, [isOpen]);\n\n const handleFlyoutKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n if (e.key === 'Tab') { e.preventDefault(); closeFlyout(); return; }\n if (moveMenuFocus(e.currentTarget, e.key)) e.preventDefault();\n };\n\n // Close flyout on Escape — a popup, so above any modal or drawer on the shared Escape stack.\n useEscapeLayer(isOpen, 'popup', closeFlyout);\n\n return (\n <>\n <button\n ref={btnRef}\n type=\"button\"\n className={`rdd-toolbar-btn rdd-toolbar-btn-group${isActive ? ' rdd-active' : ''}`}\n title={displayLabel}\n aria-label={displayLabel}\n aria-expanded={isOpen}\n aria-haspopup=\"menu\"\n disabled={item.disabled}\n onClick={handleClick}\n >\n {displayIcon}\n </button>\n\n {isOpen && btnRect && createPortal(\n <div\n ref={flyoutRef}\n className={`rdd-toolbar-group-flyout rdd-${position}`}\n style={flyoutPosition(btnRect, position, btnRtl)}\n role=\"menu\"\n // Portaled to <body>: carry the strip's direction, which it can't inherit there.\n dir={btnRtl ? 'rtl' : 'ltr'}\n onKeyDown={handleFlyoutKeyDown}\n >\n {item.items.map((entry, i) => {\n if ('type' in entry) {\n return <div key={`sep-${i}`} className=\"rdd-toolbar-group-flyout-sep\" role=\"separator\" />;\n }\n const isSubActive = activeId === entry.id;\n return (\n <button\n key={entry.id}\n type=\"button\"\n className={`rdd-toolbar-group-flyout-item${isSubActive ? ' rdd-active' : ''}`}\n disabled={entry.disabled}\n // One of a mutually exclusive set: a radio menu item. aria-pressed is not allowed\n // on menu items.\n role=\"menuitemradio\"\n aria-checked={isSubActive}\n onClick={() => {\n if (isControlled) {\n item.onActiveItemChange?.(entry.id);\n } else {\n toolbar.setActiveInGroup(item.id, entry.id);\n }\n entry.onActivate?.(entry.id);\n closeFlyout();\n }}\n >\n <span className=\"rdd-toolbar-group-flyout-icon\">{entry.icon}</span>\n <span className=\"rdd-toolbar-group-flyout-label\">{entry.label}</span>\n {entry.shortcut && (\n <span className=\"rdd-toolbar-group-flyout-shortcut\">{entry.shortcut}</span>\n )}\n </button>\n );\n })}\n </div>,\n document.body,\n )}\n </>\n );\n}\n\n// ==========================================\n// renderItem — pure helper outside component\n// ==========================================\n\nfunction renderItem(\n item: ToolbarItem,\n index: number,\n toolbar: ToolbarContextValue,\n position: 'left' | 'right' | 'top' | 'bottom',\n): React.ReactNode {\n switch (item.type) {\n case 'separator':\n return <div key={`sep-${index}`} className=\"rdd-toolbar-separator\" role=\"separator\" />;\n\n case 'action':\n return (\n <button\n key={item.id}\n type=\"button\"\n className=\"rdd-toolbar-btn rdd-toolbar-btn-action\"\n title={item.label}\n aria-label={item.label}\n disabled={item.disabled}\n onClick={item.onClick}\n >\n {item.icon}\n </button>\n );\n\n case 'radio': {\n const isActive = toolbar.getActiveInGroup(item.group) === item.id;\n return (\n <button\n key={item.id}\n type=\"button\"\n className={`rdd-toolbar-btn rdd-toolbar-btn-radio${isActive ? ' rdd-active' : ''}`}\n title={item.label}\n aria-label={item.label}\n aria-pressed={isActive}\n disabled={item.disabled}\n onClick={() => {\n toolbar.setActiveInGroup(item.group, item.id);\n item.onActivate?.(item.id);\n }}\n >\n {item.icon}\n </button>\n );\n }\n\n case 'toggle': {\n const controlled = item.active !== undefined;\n const isActive = controlled ? item.active! : toolbar.isModifierActive(item.id);\n return (\n <button\n key={item.id}\n type=\"button\"\n className={`rdd-toolbar-btn rdd-toolbar-btn-toggle${isActive ? ' rdd-active' : ''}`}\n title={item.label}\n aria-label={item.label}\n aria-pressed={isActive}\n disabled={item.disabled}\n onClick={() => {\n if (!controlled) toolbar.toggleModifier(item.id);\n item.onToggle?.(!isActive);\n }}\n >\n {item.icon}\n </button>\n );\n }\n\n case 'group':\n return (\n <ToolbarGroupButton\n key={item.id}\n item={item}\n position={position}\n toolbar={toolbar}\n />\n );\n }\n}\n\n// ==========================================\n// Component\n// ==========================================\n\nexport const Toolbar: React.ForwardRefExoticComponent<RddToolbarProps & React.RefAttributes<ToolbarHandle>> = forwardRef<ToolbarHandle, RddToolbarProps>(function Toolbar(\n { position = 'left', items, visible, onVisibilityChange, className, style },\n ref\n) {\n const toolbar = useToolbar();\n const isVertical = position === 'left' || position === 'right';\n\n useImperativeHandle(ref, () => ({\n show: () => onVisibilityChange?.(true),\n hide: () => onVisibilityChange?.(false),\n toggle: () => onVisibilityChange?.(visible === false ? true : false),\n }), [visible, onVisibilityChange]);\n\n // CSS owns the open-state dimensions (including the touch @media 56px override).\n // Inline style only forces 0px when collapsed so the transition animates correctly.\n const collapsed = visible === false;\n const collapseStyle: React.CSSProperties = !collapsed\n ? {}\n : isVertical\n ? { width: '0px' }\n : { height: '0px' };\n\n // A collapsed strip is still in the DOM, so its buttons stayed in the Tab order — keyboard focus\n // landed on controls nobody could see. `inert` takes the whole subtree out of focus and the\n // accessibility tree. Set through the DOM rather than as a JSX prop: only React 19 knows `inert`,\n // and this library supports React 18 as well.\n const stripRef = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n const strip = stripRef.current;\n if (!strip) return;\n if (collapsed) strip.setAttribute('inert', '');\n else strip.removeAttribute('inert');\n }, [collapsed]);\n\n return (\n <div\n ref={stripRef}\n className={`rdd-toolbar-strip rdd-${position}${collapsed ? ' rdd-collapsed' : ''}${className ? ` ${className}` : ''}`}\n role=\"toolbar\"\n aria-orientation={isVertical ? 'vertical' : 'horizontal'}\n aria-hidden={collapsed || undefined}\n style={{ ...collapseStyle, ...style }}\n >\n {items.map((item, i) => renderItem(item, i, toolbar, position))}\n </div>\n );\n});\n\n// ==========================================\n// Barrel re-exports from ToolbarContext\n// ==========================================\n\nexport { useToolbar, ToolbarProvider } from './ToolbarContext';\nexport type { ToolbarContextValue } from './ToolbarContext';\n","import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { useIsClient } from '../utils/useIsClient';\nimport { createPortal } from 'react-dom';\nimport { formatLabel, useFormatMessage, usePredefinedMessages, useOptionalWindowManagerState } from './WindowManagerContext';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n// ─── Public types ─────────────────────────────────────────────────────────────\n\n/** Visual type of a toast notification. Determines the icon and accent color. */\nexport type ToastType = 'info' | 'success' | 'warning' | 'error';\n\n/** Corner position of the `<RddToasts>` relative to the viewport. */\nexport type ToastPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\n/**\n * Per-notification options passed to `toast()`, `toast.info()`, etc.\n * All fields are optional and fall back to `<RddToasts>` defaults when unset.\n */\nexport interface ToastOptions {\n /** Visual type. Overridden by the `toast.info/success/warning/error` shorthands. @default 'info' */\n type?: ToastType;\n /** Auto-dismiss delay in ms. `0` = sticky (never auto-dismisses). @default from container */\n duration?: number;\n /** Explicit ID for dedup — calling `toast.*` with the same `id` updates the existing card in-place. */\n id?: string;\n /** Show the × close button on this notification. @default from container */\n closable?: boolean;\n /** Override the built-in type icon with arbitrary content. */\n icon?: React.ReactNode;\n /** Replace the string message with arbitrary JSX. */\n content?: React.ReactNode;\n /** Called when the notification is dismissed by timer, close button, or `toast.dismiss()`. */\n onClose?: () => void;\n}\n\n/**\n * Fully-resolved options passed to `ToastAdapter.show()` and `ToastAdapter.update()`.\n * All optional `ToastOptions` fields are resolved against the container defaults.\n */\nexport interface ResolvedToastOptions {\n id: string;\n type: ToastType;\n duration: number;\n closable: boolean;\n icon?: React.ReactNode;\n content?: React.ReactNode;\n onClose?: () => void;\n}\n\n/**\n * Props for `<RddToasts>`. Mount one instance at your app root, alongside `<RddModals>`.\n * @example\n * <RddToasts position=\"top-right\" progressBar />\n */\nexport interface RddToastsProps {\n /** Where notifications appear in the viewport. @default 'top-right' */\n position?: ToastPosition;\n /** Maximum number of notifications shown simultaneously. Extras are queued. @default 3 */\n maxVisible?: number;\n /** Default auto-dismiss delay in ms. `0` = all notifications sticky. @default 5000 */\n defaultDuration?: number;\n /** Show the × close button on all notifications unless overridden per-toast. @default true */\n defaultClosable?: boolean;\n /** Pause the auto-dismiss timer while the cursor is over a notification. @default true */\n pauseOnHover?: boolean;\n /** Entry/exit animation style. @default 'slide' */\n animation?: 'slide' | 'fade' | 'none';\n /** When `true`, newest notification appears at the top of the stack. @default false */\n newestOnTop?: boolean;\n /** Show a countdown progress bar at the bottom of each notification. @default false */\n progressBar?: boolean;\n /** Width of each notification card in pixels. @default 320 */\n width?: number;\n /** Delegate all `toast.*` calls to a custom renderer (Ant Design, MUI, Sonner, etc.). */\n adapter?: ToastAdapter;\n}\n\n/**\n * Message set for `toast.promise()`. Each field may be static content or a function\n * that receives the resolved/rejected value and returns renderable content.\n * @template T The resolved value type of the tracked promise.\n */\nexport interface ToastPromiseMessages<T> {\n /** Shown while the promise is pending. */\n pending: React.ReactNode;\n /** Shown on fulfillment. Pass a function to include the resolved value. */\n success: React.ReactNode | ((result: T) => React.ReactNode);\n /** Shown on rejection. Pass a function to include the error reason. */\n error: React.ReactNode | ((err: unknown) => React.ReactNode);\n}\n\n/**\n * Strategy interface for replacing the built-in toast renderer with an external library.\n * Pass an instance via `<RddToasts adapter={...} />` to redirect all `toast.*` calls\n * without changing any call sites in your application.\n * @see RddToastsProps.adapter\n */\nexport interface ToastAdapter {\n /** Called when a new notification is requested. */\n show(id: string, message: React.ReactNode, options: ResolvedToastOptions): void;\n /** Called when an existing notification is updated (e.g. after `toast.promise()` resolves). */\n update(id: string, message: React.ReactNode, options: Partial<ResolvedToastOptions>): void;\n /** Called to dismiss one notification (`id` provided) or all active notifications (no `id`). */\n dismiss(id?: string): void;\n /**\n * `null` means the adapter manages its own DOM and `<RddToasts>` renders nothing.\n * A component causes `<RddToasts>` to portal-render it with a `position` prop.\n */\n Container: React.ComponentType<{ position: ToastPosition }> | null;\n}\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ntype ToastEvent =\n | { kind: 'show'; id: string; message: React.ReactNode; rawOpts: ToastOptions & { id: string } }\n | { kind: 'update'; id: string; message: React.ReactNode; patch: Partial<ResolvedToastOptions> }\n | { kind: 'dismiss'; id?: string };\n\ninterface ActiveToast {\n id: string;\n message: React.ReactNode;\n options: ResolvedToastOptions;\n exiting: boolean;\n}\n\n// ─── ToastEmitter ─────────────────────────────────────────────────────────────\n\nclass ToastEmitter {\n private listeners = new Set<(e: ToastEvent) => void>();\n private counter = 0;\n\n subscribe(fn: (e: ToastEvent) => void) { this.listeners.add(fn); }\n unsubscribe(fn: (e: ToastEvent) => void) { this.listeners.delete(fn); }\n\n show(message: React.ReactNode, opts: ToastOptions = {}): string {\n const id = opts.id ?? `toast-${++this.counter}`;\n this.emit({ kind: 'show', id, message, rawOpts: { ...opts, id } });\n return id;\n }\n\n update(id: string, message: React.ReactNode, patch: Partial<ResolvedToastOptions>) {\n this.emit({ kind: 'update', id, message, patch });\n }\n\n dismiss(id?: string) { this.emit({ kind: 'dismiss', id }); }\n\n private emit(e: ToastEvent) { this.listeners.forEach(fn => fn(e)); }\n}\n\nconst emitter = new ToastEmitter();\n\n// ─── toast public API ─────────────────────────────────────────────────────────\n\n/**\n * Type of the `toast` singleton. Callable directly or via named shorthand methods.\n * Import this type to annotate variables or props that accept the `toast` object.\n * @example\n * function notify(fn: ToastFunction) { fn.success('Done!'); }\n */\nexport interface ToastFunction {\n /** Show a notification. `opts.type` defaults to `'info'`. Returns the notification ID. */\n (msg: React.ReactNode, opts?: ToastOptions): string;\n /** Show an info notification. Returns the notification ID. */\n info: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Show a success notification. Returns the notification ID. */\n success: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Show a warning notification. Returns the notification ID. */\n warning: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Show an error notification. Returns the notification ID. */\n error: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Dismiss a notification by ID, or all active notifications when called with no argument. */\n dismiss: (id?: string) => void;\n /**\n * Track a promise through pending → success/error states.\n * Shows a sticky pending notification immediately, then transitions it on settlement.\n * @template T The resolved value type of the promise.\n */\n promise: <T>(promise: Promise<T>, messages: ToastPromiseMessages<T>, opts?: ToastOptions) => Promise<T>;\n}\n\n/**\n * Imperative notification singleton. Call from anywhere — inside or outside React.\n * Mount `<RddToasts>` once at your app root to activate the renderer.\n * @example\n * toast.success('File saved.');\n * toast.error('Upload failed.', { duration: 0 }); // sticky\n * toast.promise(saveFile(), { pending: 'Saving…', success: 'Saved!', error: 'Failed.' });\n */\nexport const toast: ToastFunction = Object.assign(\n (msg: React.ReactNode, opts?: ToastOptions): string => emitter.show(msg, opts),\n {\n info: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'info' }),\n success: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'success' }),\n warning: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'warning' }),\n error: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'error' }),\n dismiss: (id?: string): void => emitter.dismiss(id),\n promise: <T,>(\n promise: Promise<T>,\n messages: ToastPromiseMessages<T>,\n opts?: ToastOptions\n ): Promise<T> => {\n const id = emitter.show(messages.pending, { ...opts, type: 'info', duration: 0 });\n promise.then(\n result => {\n const msg = typeof messages.success === 'function' ? messages.success(result) : messages.success;\n emitter.update(id, msg, { type: 'success', duration: opts?.duration ?? 5000 });\n },\n err => {\n const msg = typeof messages.error === 'function' ? messages.error(err) : messages.error;\n emitter.update(id, msg, { type: 'error', duration: opts?.duration ?? 5000 });\n }\n );\n return promise;\n },\n }\n);\n\n// ─── Icons ────────────────────────────────────────────────────────────────────\n\nconst InfoIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M8 5v.01M8 7.5v3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst SuccessIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5 8l2 2 4-4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"/>\n </svg>\n);\nconst WarningIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <path d=\"M8 2.5L14 13.5H2L8 2.5z\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinejoin=\"round\"/>\n <path d=\"M8 7v2.5M8 11.5v.01\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst ErrorIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5.5 5.5l5 5M10.5 5.5l-5 5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst CloseIcon = () => (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <path d=\"M4 4l8 8M12 4l-8 8\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\n\nconst DEFAULT_ICONS: Record<ToastType, React.ReactNode> = {\n info: <InfoIcon />,\n success: <SuccessIcon />,\n warning: <WarningIcon />,\n error: <ErrorIcon />,\n};\n\n// ─── ToastItem ────────────────────────────────────────────────────────────────\n\ninterface ToastItemProps {\n id: string;\n message: React.ReactNode;\n options: ResolvedToastOptions;\n exiting: boolean;\n isLeft: boolean;\n showProgress: boolean;\n pauseOnHover: boolean;\n animation: 'slide' | 'fade' | 'none';\n closeLabel: string;\n onDismiss: (id: string) => void;\n onExited: (id: string) => void;\n}\n\nfunction ToastItem({\n id, message, options, exiting, isLeft,\n showProgress, pauseOnHover, animation, closeLabel, onDismiss, onExited,\n}: ToastItemProps) {\n const divRef = useRef<HTMLDivElement>(null);\n const bodyRef = useRef<HTMLDivElement>(null);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const remainRef = useRef<number>(options.duration);\n const startRef = useRef<number>(0);\n const [paused, setPaused] = useState(false);\n\n const startEntry =\n animation === 'none' ? 'rdd-toast--visible' :\n animation === 'fade' ? 'rdd-toast--fade-entering' :\n isLeft ? 'rdd-toast--entering-left' :\n 'rdd-toast--entering';\n const [entryClass, setEntryClass] = useState(startEntry);\n\n // Keep max-height in sync with the card's true content height, so content that\n // grows after mount (e.g. toast.promise()'s pending -> error message) never gets\n // clipped by the overflow: hidden below. The card's own box is exactly what this\n // effect holds at a fixed height, so it never reports a resize on its own — the\n // ResizeObserver instead watches the unconstrained inner body (the only thing\n // that actually grows with its content) purely as a trigger, and reads the\n // outer card's scrollHeight (which reports the true, uncapped content height\n // even while a stale cap is still clipping it — offsetHeight/clientHeight would\n // just return that stale cap) to compute the new value. Frozen once exiting\n // starts: .rdd-toast--exiting's `max-height: 0 !important` below takes over\n // from there regardless of this inline value.\n useLayoutEffect(() => {\n const el = divRef.current;\n const body = bodyRef.current;\n if (!el || !body || exiting) return;\n\n const applyHeight = () => { el.style.maxHeight = `${el.scrollHeight}px`; };\n applyHeight();\n\n const observer = new ResizeObserver(applyHeight);\n observer.observe(body);\n return () => observer.disconnect();\n }, [exiting]);\n\n // Trigger entry transition on next frame\n useEffect(() => {\n if (animation === 'none') return;\n const raf = requestAnimationFrame(() => setEntryClass('rdd-toast--visible'));\n return () => cancelAnimationFrame(raf);\n }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n // Auto-dismiss timer\n const scheduleDismiss = useCallback((ms: number) => {\n if (ms <= 0) return;\n startRef.current = Date.now();\n timerRef.current = setTimeout(() => onDismiss(id), ms);\n }, [id, onDismiss]);\n\n useEffect(() => {\n if (timerRef.current) clearTimeout(timerRef.current);\n remainRef.current = options.duration;\n scheduleDismiss(options.duration);\n return () => { if (timerRef.current) clearTimeout(timerRef.current); };\n }, [options.duration, scheduleDismiss]);\n\n // Exit animation → call onExited after transition\n useEffect(() => {\n if (!exiting) return;\n const el = divRef.current;\n if (!el || animation === 'none') {\n onExited(id);\n return;\n }\n const handle = (e: TransitionEvent) => {\n if (e.propertyName === 'max-height') onExited(id);\n };\n el.addEventListener('transitionend', handle);\n const fallback = setTimeout(() => onExited(id), 520);\n return () => {\n el.removeEventListener('transitionend', handle);\n clearTimeout(fallback);\n };\n }, [exiting, id, onExited, animation]);\n\n const handleMouseEnter = () => {\n if (!pauseOnHover || options.duration === 0) return;\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n remainRef.current = Math.max(0, remainRef.current - (Date.now() - startRef.current));\n }\n setPaused(true);\n };\n\n const handleMouseLeave = () => {\n if (!pauseOnHover || options.duration === 0) return;\n setPaused(false);\n scheduleDismiss(remainRef.current);\n };\n\n const cls = [\n 'rdd-toast',\n options.type && `rdd-toast--${options.type}`,\n entryClass,\n exiting && 'rdd-toast--exiting',\n paused && 'rdd-toast--paused',\n ].filter(Boolean).join(' ');\n\n const icon = options.icon !== undefined ? options.icon : (options.type ? DEFAULT_ICONS[options.type] : null);\n\n return (\n <div\n ref={divRef}\n role=\"status\"\n aria-live=\"polite\"\n className={cls}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n {icon && icon}\n <div ref={bodyRef} className=\"rdd-toast__body\">\n {options.content !== undefined ? options.content : message}\n </div>\n {options.closable && (\n <button\n type=\"button\"\n className=\"rdd-toast__close\"\n onClick={() => onDismiss(id)}\n aria-label={closeLabel}\n >\n <CloseIcon />\n </button>\n )}\n {showProgress && options.duration > 0 && (\n <div\n className=\"rdd-toast__progress\"\n style={{ animationDuration: `${options.duration}ms` }}\n />\n )}\n </div>\n );\n}\n\n// ─── ToastContainer ───────────────────────────────────────────────────────────\n\n\nfunction resolveOpts(\n raw: ToastOptions & { id: string },\n defaultDuration: number,\n defaultClosable: boolean\n): ResolvedToastOptions {\n return {\n id: raw.id,\n type: raw.type ?? 'info',\n duration: raw.duration ?? defaultDuration,\n closable: raw.closable ?? defaultClosable,\n icon: raw.icon,\n content: raw.content,\n onClose: raw.onClose,\n };\n}\n\n/**\n * Portal-rendered notification host. Mount once at your app root, outside the workspace\n * container. All `toast.*` calls are routed here automatically via the internal event emitter.\n * @example\n * <RddToasts position=\"top-right\" progressBar />\n */\nexport function ToastContainer({\n position = 'top-right',\n maxVisible = 3,\n defaultDuration = 5000,\n defaultClosable = true,\n pauseOnHover = true,\n animation = 'slide',\n newestOnTop = false,\n progressBar = false,\n width = 320,\n adapter,\n}: RddToastsProps): React.ReactElement | null {\n const [toasts, setToasts] = useState<ActiveToast[]>([]);\n // Both hooks work without a provider (English defaults), so a ToastContainer mounted outside\n // the workspace still renders.\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const regionLabel = formatLabel(messages.notifications, formatMessage);\n // Toasts are portalled to <body>: they follow setDirection('rtl') like the workspace, and\n // otherwise inherit the page's direction, as before.\n const workspaceDir = useOptionalWindowManagerState(s => s.dir, undefined);\n // Portals need `document.body`, which doesn't exist on the server. Render nothing there, and\n // during hydration (the server snapshot); portal on the client after that. The server's output\n // and the hydrating render then agree — both empty — so there is nothing to reconcile.\n const mounted = useIsClient();\n const closeLabel = formatLabel(messages.closeNotification, formatMessage);\n const queueRef = useRef<Array<{ id: string; message: React.ReactNode; rawOpts: ToastOptions & { id: string } }>>([]);\n const toastsRef = useLatestRef<ActiveToast[]>(toasts);\n\n const handleDismiss = useCallback((id: string) => {\n setToasts(prev => prev.map(t => t.id === id ? { ...t, exiting: true } : t));\n toastsRef.current.find(t => t.id === id)?.options.onClose?.();\n }, [toastsRef]);\n\n const handleExited = useCallback((id: string) => {\n // Shift outside the updater (once) so the updater is pure and safe for StrictMode\n const promoted = queueRef.current.shift() ?? null;\n setToasts(prev => {\n const filtered = prev.filter(t => t.id !== id);\n if (!promoted) return filtered;\n const options = resolveOpts(promoted.rawOpts, defaultDuration, defaultClosable);\n return [...filtered, { id: promoted.id, message: promoted.message, options, exiting: false }];\n });\n }, [defaultDuration, defaultClosable]);\n\n // Subscribe to emitter (built-in path)\n useEffect(() => {\n if (adapter) return;\n\n const handle = (e: ToastEvent) => {\n if (e.kind === 'show') {\n // Resolve options once outside the updater so the updater stays pure\n const options = resolveOpts(e.rawOpts, defaultDuration, defaultClosable);\n const newEntry: ActiveToast = { id: e.id, message: e.message, options, exiting: false };\n const rawEntry = { id: e.id, message: e.message, rawOpts: e.rawOpts };\n\n setToasts(prev => {\n // Dedup check against actual prev (not stale ref) so batched calls are safe\n const existing = prev.find(t => t.id === e.id);\n if (existing) {\n return prev.map(t => t.id === e.id ? { ...t, message: e.message, options } : t);\n }\n // Count against actual prev so multiple synchronous toast() calls batch correctly\n const visible = prev.filter(t => !t.exiting).length;\n if (visible < maxVisible) {\n return [...prev, newEntry];\n }\n // Queue — guard prevents duplicate push when React calls updater twice (StrictMode)\n if (!queueRef.current.some(q => q.id === rawEntry.id)) {\n queueRef.current.push(rawEntry);\n }\n return prev;\n });\n } else if (e.kind === 'update') {\n setToasts(prev => prev.map(t => {\n if (t.id !== e.id) return t;\n const merged: ResolvedToastOptions = { ...t.options, ...e.patch, id: t.id };\n return { ...t, message: e.message, options: merged };\n }));\n queueRef.current = queueRef.current.map(q => {\n if (q.id !== e.id) return q;\n return { ...q, message: e.message, rawOpts: { ...q.rawOpts, ...e.patch } };\n });\n } else if (e.kind === 'dismiss') {\n if (e.id === undefined) {\n setToasts(prev => prev.map(t => ({ ...t, exiting: true })));\n queueRef.current = [];\n } else {\n const isActive = toastsRef.current.some(t => t.id === e.id);\n if (isActive) {\n handleDismiss(e.id);\n } else {\n queueRef.current = queueRef.current.filter(q => q.id !== e.id);\n }\n }\n }\n };\n\n emitter.subscribe(handle);\n return () => emitter.unsubscribe(handle);\n }, [adapter, maxVisible, defaultDuration, defaultClosable, handleDismiss, toastsRef]);\n\n // Subscribe to emitter (adapter path)\n useEffect(() => {\n if (!adapter) return;\n const handle = (e: ToastEvent) => {\n if (e.kind === 'show') {\n const opts = resolveOpts(e.rawOpts, defaultDuration, defaultClosable);\n adapter.show(e.id, e.message, opts);\n } else if (e.kind === 'update') {\n adapter.update(e.id, e.message, e.patch);\n } else if (e.kind === 'dismiss') {\n adapter.dismiss(e.id);\n }\n };\n emitter.subscribe(handle);\n return () => emitter.unsubscribe(handle);\n }, [adapter, defaultDuration, defaultClosable]);\n\n if (!mounted) return null;\n\n if (adapter) {\n if (!adapter.Container) return null;\n const AdapterContainer = adapter.Container;\n return createPortal(<AdapterContainer position={position} />, document.body);\n }\n\n const isLeft = position.endsWith('left');\n let dirMod = '';\n if (newestOnTop === true) dirMod = 'rdd-toast-container--newest-top';\n if (newestOnTop === false) dirMod = 'rdd-toast-container--newest-bottom';\n\n const cls = ['rdd-toast-container', `rdd-toast-container--${position}`, dirMod]\n .filter(Boolean).join(' ');\n\n return createPortal(\n // A named landmark. Each toast is its own role=\"status\" live region, so the container is not\n // one as well — nested live regions get announced twice.\n <div className={cls} style={{ width }} role=\"region\" aria-label={regionLabel} dir={workspaceDir === 'rtl' ? 'rtl' : undefined}>\n {toasts.map(t => (\n <ToastItem\n key={t.id}\n id={t.id}\n message={t.message}\n options={t.options}\n exiting={t.exiting}\n isLeft={isLeft}\n showProgress={progressBar}\n pauseOnHover={pauseOnHover}\n animation={animation}\n closeLabel={closeLabel}\n onDismiss={handleDismiss}\n onExited={handleExited}\n />\n ))}\n </div>,\n document.body\n );\n}\n","/**\n * @file PanelOverlayRoot.tsx\n * @description The Panel Overlay root: provides the overlay contexts and draws the corner drop zones.\n */\nimport React, { useState, useRef, useCallback, useMemo } from 'react';\nimport type { FloatAnchor } from '../WindowManagerContext';\nimport type { ManagedWidget, Stretch, ToolbarPosition } from './types';\nimport { PanelToolbarContext, PanelManagerContext, PanelOverlayContext } from './context';\nimport type { PanelOverlayCtx, PanelToolbarCtx, PanelManagerCtx } from './context';\nimport { bucketsFor, ANCHORS } from '../../core/stretch';\nimport { PanelFloatingWindow } from './FloatingWidget';\n\n// ─── PanelOverlayRoot ─────────────────────────────────────────────────────────\n\n/** Props for `<RddPanelOverlay>`. */\nexport interface RddPanelOverlayProps {\n children: React.ReactNode;\n className?: string;\n style?: React.CSSProperties;\n}\n\n/**\n * Context provider and layout root for the Panel Overlay system. Wrap your panel content\n * with this to enable `RddPanelToolbar`, `RddFloatingWidget`, and `useFloatingWidgets`.\n * @example\n * function MyPanel() {\n * return (\n * <RddPanelOverlay style={{ position: 'relative', width: '100%', height: '100%' }}>\n * <RddPanelToolbar position=\"top\">...</RddPanelToolbar>\n * <div className=\"my-panel-body\">content</div>\n * </RddPanelOverlay>\n * );\n * }\n */\nexport function PanelOverlayRoot({ children, className, style }: RddPanelOverlayProps): React.ReactElement {\n const [toolbarSizes, setToolbarSizes] = useState<Partial<Record<ToolbarPosition, number>>>({});\n const [zOrders, setZOrders] = useState<Record<string, number>>({});\n const [stacks, setStacks] = useState<Record<FloatAnchor, string[]>>({\n 'top-left': [], 'top-right': [], 'bottom-left': [], 'bottom-right': [],\n });\n const [dockedSizes, setDockedSizes] = useState<Record<string, number>>({});\n const [draggingId, setDraggingId] = useState<string | null>(null);\n const [hoveredZone, setHoveredZone] = useState<FloatAnchor | null>(null);\n const [topId, setTopId] = useState<string | null>(null);\n const [managedWindows, setManagedWindows] = useState<Map<string, ManagedWidget>>(() => new Map());\n const zCounterRef = useRef(100);\n const containerRef = useRef<HTMLDivElement>(null);\n\n const registerToolbar = useCallback((pos: ToolbarPosition, size: number): (() => void) => {\n setToolbarSizes(prev => ({ ...prev, [pos]: size }));\n return () => setToolbarSizes(prev => {\n const next = { ...prev };\n delete next[pos];\n return next;\n });\n }, []);\n\n const focusWindow = useCallback((id: string): void => {\n zCounterRef.current += 1;\n const z = zCounterRef.current;\n setZOrders(prev => ({ ...prev, [id]: z }));\n setTopId(id);\n }, []);\n\n const dockWindow = useCallback((id: string, anchor: FloatAnchor, stretch: Stretch | null = null): void => {\n const buckets = bucketsFor(anchor, stretch);\n setStacks(prev => {\n const next: Record<FloatAnchor, string[]> = {\n 'top-left': prev['top-left'].filter(x => x !== id),\n 'top-right': prev['top-right'].filter(x => x !== id),\n 'bottom-left': prev['bottom-left'].filter(x => x !== id),\n 'bottom-right': prev['bottom-right'].filter(x => x !== id),\n };\n for (const bucket of buckets) next[bucket] = [...next[bucket], id];\n // Re-registering identical membership would allocate fresh arrays on every placement effect\n // and churn every consumer of `stacks`, so bail out when nothing actually moved.\n const unchanged = ANCHORS.every(a =>\n next[a].length === prev[a].length && next[a].every((x, i) => x === prev[a][i]));\n return unchanged ? prev : next;\n });\n }, []);\n\n const undockWindow = useCallback((id: string): void => {\n setStacks(prev => ({\n 'top-left': prev['top-left'].filter(x => x !== id),\n 'top-right': prev['top-right'].filter(x => x !== id),\n 'bottom-left': prev['bottom-left'].filter(x => x !== id),\n 'bottom-right': prev['bottom-right'].filter(x => x !== id),\n }));\n }, []);\n\n const reportDockedSize = useCallback((id: string, size: number): void => {\n setDockedSizes(prev => {\n if (prev[id] === size) return prev;\n return { ...prev, [id]: size };\n });\n }, []);\n\n const openManaged = useCallback((id: string, config: ManagedWidget): void => {\n setManagedWindows(prev => {\n const next = new Map(prev);\n next.set(id, config);\n return next;\n });\n }, []);\n\n const closeManaged = useCallback((id: string): void => {\n setManagedWindows(prev => {\n const next = new Map(prev);\n next.delete(id);\n return next;\n });\n }, []);\n\n const closeAllManaged = useCallback((): void => {\n setManagedWindows(new Map());\n }, []);\n\n const managedWindowIds = useMemo(() => Array.from(managedWindows.keys()), [managedWindows]);\n\n const toolbarCtxValue = useMemo<PanelToolbarCtx>(() => ({\n registerToolbar,\n insetTop: toolbarSizes.top ?? 0,\n insetBottom: toolbarSizes.bottom ?? 0,\n }), [registerToolbar, toolbarSizes]);\n\n const managerCtxValue = useMemo<PanelManagerCtx>(() => ({\n managedWindowIds,\n openManaged,\n closeManaged,\n closeAllManaged,\n }), [managedWindowIds, openManaged, closeManaged, closeAllManaged]);\n\n const coreCtxValue = useMemo<PanelOverlayCtx>(() => ({\n topId,\n zOrders,\n focusWindow,\n containerRef: containerRef as React.RefObject<HTMLDivElement>,\n stacks,\n dockedSizes,\n dockWindow,\n undockWindow,\n reportDockedSize,\n draggingId,\n setDraggingId,\n hoveredZone,\n setHoveredZone,\n insetTop: toolbarSizes.top ?? 0,\n insetBottom: toolbarSizes.bottom ?? 0,\n insetInlineStart: toolbarSizes.left ?? 0,\n insetInlineEnd: toolbarSizes.right ?? 0,\n }), [topId, zOrders, focusWindow, stacks, dockedSizes, dockWindow, undockWindow,\n reportDockedSize, draggingId, hoveredZone, toolbarSizes]);\n\n return (\n <PanelToolbarContext.Provider value={toolbarCtxValue}>\n <PanelManagerContext.Provider value={managerCtxValue}>\n <PanelOverlayContext.Provider value={coreCtxValue}>\n <div\n ref={containerRef}\n className={`rdd-panel-overlay-root${draggingId !== null ? ' rdd-dragging-active' : ''}${className ? ' ' + className : ''}`}\n style={style}\n >\n {children}\n {draggingId !== null && <DropZoneOverlay hoveredZone={hoveredZone} />}\n {Array.from(managedWindows.entries()).map(([id, cfg]) => (\n <PanelFloatingWindow\n key={id}\n id={id}\n title={cfg.title}\n icon={cfg.icon}\n open={true}\n onClose={() => closeManaged(id)}\n defaultAnchor={cfg.anchor ?? 'top-right'}\n defaultWidth={cfg.width ?? 320}\n defaultHeight={cfg.height ?? 240}\n defaultStretch={cfg.stretch}\n >\n {cfg.content}\n </PanelFloatingWindow>\n ))}\n </div>\n </PanelOverlayContext.Provider>\n </PanelManagerContext.Provider>\n </PanelToolbarContext.Provider>\n );\n}\n\n// ─── Internal: DropZoneOverlay ────────────────────────────────────────────────\n\nfunction DropZoneOverlay({ hoveredZone }: { hoveredZone: FloatAnchor | null }): React.ReactElement {\n return (\n <>\n {ANCHORS.map(zone => (\n <div\n key={zone}\n className={`rdd-panel-float-dropzone rdd-panel-float-dropzone--${zone}${hoveredZone === zone ? ' rdd-panel-float-dropzone--hovered' : ''}`}\n aria-hidden=\"true\"\n />\n ))}\n </>\n );\n}\n","/**\n * @file context.ts\n * @description The Panel Overlay's internal React contexts, shared by the overlay root, the\n * toolbars and the floating widgets.\n */\nimport type React from 'react';\nimport { createContext } from 'react';\nimport type { FloatAnchor } from '../../types';\nimport type { ManagedWidget, Stretch, ToolbarPosition } from './types';\n\n// ─── Internal contexts ────────────────────────────────────────────────────────\n\nexport interface PanelToolbarCtx {\n registerToolbar(pos: ToolbarPosition, size: number): () => void;\n insetTop: number;\n insetBottom: number;\n}\nexport const PanelToolbarContext: React.Context<PanelToolbarCtx | null> = createContext<PanelToolbarCtx | null>(null);\n\nexport interface PanelManagerCtx {\n managedWindowIds: string[];\n openManaged(id: string, config: ManagedWidget): void;\n closeManaged(id: string): void;\n closeAllManaged(): void;\n}\nexport const PanelManagerContext: React.Context<PanelManagerCtx | null> = createContext<PanelManagerCtx | null>(null);\n\nexport interface PanelOverlayCtx {\n topId: string | null;\n zOrders: Record<string, number>;\n focusWindow(id: string): void;\n containerRef: React.RefObject<HTMLDivElement>;\n stacks: Record<FloatAnchor, string[]>;\n dockedSizes: Record<string, number>;\n dockWindow(id: string, anchor: FloatAnchor, stretch?: Stretch | null): void;\n undockWindow(id: string): void;\n reportDockedSize(id: string, size: number): void;\n draggingId: string | null;\n setDraggingId(id: string | null): void;\n hoveredZone: FloatAnchor | null;\n setHoveredZone(zone: FloatAnchor | null): void;\n /** Block-axis space claimed by `PanelToolbar`s on the top/bottom edges. */\n insetTop: number;\n insetBottom: number;\n /**\n * Inline-axis space claimed by `PanelToolbar`s on the `left`/`right` edges. Logical, matching\n * how `PanelToolbar` positions itself (`insetInlineStart`/`insetInlineEnd`), so `left` means\n * inline-start regardless of direction. `registerToolbar` has always recorded these; they simply\n * weren't surfaced, so nothing could keep clear of a side toolbar the way the block axis does.\n */\n insetInlineStart: number;\n insetInlineEnd: number;\n}\nexport const PanelOverlayContext: React.Context<PanelOverlayCtx | null> = createContext<PanelOverlayCtx | null>(null);\n","/**\n * @file stretch.ts\n * @description Pure helpers for a docked widget's stretched axes and corner stacking.\n */\nimport type { FloatAnchor } from '../types';\nimport type { Stretch } from '../components/panelOverlay/types';\n\nexport const stretchesInline = (s: Stretch | null): boolean => s === 'width' || s === 'both';\nexport const stretchesBlock = (s: Stretch | null): boolean => s === 'height' || s === 'both';\n\n/** Adds one axis to a stretch value, keeping whatever was already stretched. */\nexport const addAxis = (s: Stretch | null, axis: 'inline' | 'block'): Stretch => {\n if (axis === 'inline') return stretchesBlock(s) ? 'both' : 'width';\n return stretchesInline(s) ? 'both' : 'height';\n};\n\n/** Drops one axis from a stretch value, keeping the other. */\nexport const releaseAxis = (s: Stretch | null, axis: 'inline' | 'block'): Stretch | null => {\n if (axis === 'inline') return s === 'both' ? 'height' : stretchesInline(s) ? null : s;\n return s === 'both' ? 'width' : stretchesBlock(s) ? null : s;\n};\n\n/**\n * Which stack buckets a placement occupies.\n *\n * The four corner buckets are really a proxy for *\"do these overlap on the inline axis?\"* — two\n * widgets in the same corner overlap and so stack; widgets in opposite corners sit side by side and\n * don't. A full-width strip overlaps everything on its edge, so it belongs to **both** buckets of\n * that edge and pushes the widgets in each. (Computing real inline overlap was rejected: widths\n * change continuously during a resize drag, so widgets would reshuffle mid-gesture.)\n *\n * A block-stretched widget spans the very axis stacking uses to separate siblings, so it can't\n * participate at all and occupies no bucket — z-order decides any overlap.\n */\nexport const bucketsFor = (anchor: FloatAnchor, stretch: Stretch | null): FloatAnchor[] => {\n if (stretchesBlock(stretch)) return [];\n if (stretchesInline(stretch)) {\n return anchor.startsWith('top-')\n ? ['top-left', 'top-right']\n : ['bottom-left', 'bottom-right'];\n }\n return [anchor];\n};\n\n/** Replaces one half of a corner anchor, leaving the other axis alone. */\nexport const withInlineHalf = (a: FloatAnchor, half: 'left' | 'right'): FloatAnchor =>\n `${a.startsWith('top-') ? 'top' : 'bottom'}-${half}` as FloatAnchor;\nexport const withBlockHalf = (a: FloatAnchor, half: 'top' | 'bottom'): FloatAnchor =>\n `${half}-${a.endsWith('-right') ? 'right' : 'left'}` as FloatAnchor;\n\nexport const ANCHORS: readonly FloatAnchor[] = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];\n","/**\n * @file FloatingWidget.tsx\n * @description A floating widget inside a panel: docked to a corner or free, stretchable, resizable.\n */\nimport React, { useState, useContext, useRef, useLayoutEffect, useInsertionEffect, useCallback, useEffect } from 'react';\nimport { useOptionalWindowManagerState, formatLabel, useFormatMessage, usePredefinedMessages } from '../WindowManagerContext';\nimport type { FloatAnchor } from '../WindowManagerContext';\nimport type { PanelTitle } from '../PanelProviderContext';\nimport { flipZoneHorizontal } from '../anchorGeometry';\nimport { startPointerDrag, computeResizedRect } from '../dragResize';\nimport type { ResizeDir } from '../dragResize';\nimport type { PanelFloatPlacement, Stretch } from './types';\nimport { PanelOverlayContext } from './context';\nimport type { PanelOverlayCtx } from './context';\nimport { stretchesInline, stretchesBlock, addAxis, releaseAxis, bucketsFor, withInlineHalf, withBlockHalf } from '../../core/stretch';\nimport { getHoveredZone, MIN_W, MIN_H, DOCK_INSET, DOCK_GAP, SNAP_IN, SNAP_OUT } from '../../core/panelOverlayGeometry';\nimport { useLatestRef } from '../../utils/useLatestRef';\n\n// ─── PanelFloatingWindow ──────────────────────────────────────────────────────\n\n/** Props for `<RddFloatingWidget>`. */\nexport interface RddFloatingWidgetProps {\n /** Unique identifier within the panel overlay. Used for z-order and stack tracking. */\n id: string;\n /** Text shown in the window's header bar. Accepts a plain string or an i18n message descriptor. */\n title: PanelTitle;\n /** Optional icon shown to the left of the title in the header. */\n icon?: React.ReactNode;\n /** Whether the window is mounted and visible. Set to `false` to close/unmount it. */\n open: boolean;\n /** Called when the user clicks the × button. Set `open` to `false` in response. */\n onClose(): void;\n /** Corner of the panel to dock to on first render. @see FloatAnchor */\n defaultAnchor: FloatAnchor;\n /** Initial width in pixels. Ignored on an axis that starts stretched, and restored to when that\n * axis is later released. */\n defaultWidth: number;\n /** Initial height in pixels. Ignored on an axis that starts stretched, and restored to when that\n * axis is later released. */\n defaultHeight: number;\n /**\n * Which axes span the panel on first render. Uncontrolled: gestures update it from here.\n * @see Stretch\n */\n defaultStretch?: Stretch;\n /**\n * Controlled stretch state. When provided — **including as `null`** — the caller is the single\n * source of truth: gestures report through {@link RddFloatingWidgetProps.onPlacementChange}\n * instead of updating internally, and the caller must echo the new value back. Omit entirely\n * (`undefined`) for uncontrolled behaviour, matching `ToolbarToggleItem.active` and\n * `Sidebar.activeTabId`.\n */\n stretch?: Stretch | null;\n /**\n * Called whenever a gesture changes where the widget sits — a stretched axis released, a\n * re-dock, or a detach. Reports anchor and stretch **together**, because one gesture can change\n * both at once and reporting them separately would surface a state that is never valid.\n *\n * This is also the only way to persist placement: the library serialises nothing about inner\n * widgets, so store what you receive here and feed it back via `defaultAnchor`/`stretch`.\n */\n onPlacementChange?: (placement: PanelFloatPlacement) => void;\n /**\n * Whether this widget may span the panel at all. `false` disables resize-to-stretch snapping,\n * for content that only makes sense at a bounded size. Default `true`.\n */\n stretchable?: boolean;\n children?: React.ReactNode;\n}\n\n/**\n * A floating widget inside a panel — anchored within an `RddPanelOverlay`.\n *\n * Docks to any corner, drags free of it, and drops back onto one. Windows sharing a corner stack\n * along the block axis with animated offsets. An axis can also **span the panel** instead of\n * carrying a fixed size, so the window tracks the panel as it resizes — see\n * {@link RddFloatingWidgetProps.defaultStretch} and {@link Stretch}.\n *\n * Resize handles follow what is actually movable: a free-floating window is pinned by nothing and\n * offers all eight, while a docked one offers only its free edges — plus both ends of any spanning\n * axis, either of which releases it.\n *\n * @example\n * const [infoOpen, setInfoOpen] = useState(false);\n * <RddFloatingWidget\n * id=\"layer-info\" title=\"Layer Info\"\n * open={infoOpen} onClose={() => setInfoOpen(false)}\n * defaultAnchor=\"top-right\" defaultWidth={300} defaultHeight={200}\n * >\n * <LayerInfoContent />\n * </RddFloatingWidget>\n *\n * @example\n * // A full-width status strip along the bottom, tracking the panel's width.\n * // defaultHeight still applies; defaultWidth is what the inline axis returns to if released.\n * <RddFloatingWidget\n * id=\"timeline\" title=\"Timeline\"\n * open onClose={close}\n * defaultAnchor=\"bottom-left\" defaultStretch=\"width\"\n * defaultWidth={240} defaultHeight={120}\n * >\n * <TimelineContent />\n * </RddFloatingWidget>\n */\nexport function PanelFloatingWindow(props: RddFloatingWidgetProps): React.ReactElement | null {\n const ctx = useContext(PanelOverlayContext);\n if (!props.open) return null;\n return <FloatingWindowBody key={props.id} ctx={ctx} {...props} />;\n}\n\n// ─── Internal: FloatingWindowBody ─────────────────────────────────────────────\n\ninterface FloatingWindowBodyProps extends RddFloatingWidgetProps {\n ctx: PanelOverlayCtx | null;\n}\n\ntype WindowMode = 'docked' | 'free';\n\n\nfunction FloatingWindowBody({ id, title, icon, defaultAnchor, defaultWidth, defaultHeight, defaultStretch, stretch: stretchProp, onPlacementChange, stretchable = true, children, ctx, onClose }: FloatingWindowBodyProps): React.ReactElement {\n const isRtl = useOptionalWindowManagerState(s => s.isRtl, false);\n // Resolved here rather than at the call site, so a descriptor title re-resolves whenever the\n // formatter changes. Both hooks fall back to the message's own `defaultMessage` when there is no\n // provider, so an overlay used outside a WindowManager keeps working.\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const [mode, setMode] = useState<WindowMode>('docked');\n const [currentAnchor, setCurrentAnchor] = useState<FloatAnchor>(defaultAnchor);\n // `size` is deliberately left untouched while an axis is stretched — the render branch below\n // simply stops reading it, exactly as a maximized workspace window keeps its x/y/w/h. Releasing\n // the axis therefore restores the previous size with no snapshot and no bookkeeping.\n const [internalStretch, setInternalStretch] = useState<Stretch | null>(defaultStretch ?? null);\n // Controlled when the prop is present at all — `null` is a meaningful value (\"not stretched\"),\n // so only `undefined` means \"manage it yourself\".\n const isStretchControlled = stretchProp !== undefined;\n const stretch = isStretchControlled ? (stretchProp ?? null) : internalStretch;\n const [freePos, setFreePos] = useState<{ x: number; y: number } | null>(null);\n const [size, setSize] = useState({ w: defaultWidth, h: defaultHeight });\n const windowRef = useRef<HTMLDivElement>(null);\n\n // Refs to avoid stale closures in pointer handlers\n const modeRef = useLatestRef(mode);\n const freePosRef = useLatestRef(freePos);\n const sizeRef = useLatestRef(size);\n const stretchRef = useLatestRef(stretch);\n const currentAnchorRef = useLatestRef(currentAnchor);\n const onPlacementChangeRef = useLatestRef(onPlacementChange);\n /** Which axes would snap to stretched if the drag were released now — drives the visual cue. */\n const [snapArmed, setSnapArmed] = useState<{ inline: boolean; block: boolean }>({ inline: false, block: false });\n const snapArmedRef = useLatestRef(snapArmed);\n /** The block extent available to this widget depends on what it is stacked behind. */\n const stackOffsetRef = useRef(0);\n\n /**\n * The single write path for placement. Anchor is always internal; stretch is internal only when\n * uncontrolled. Either way the pair is reported once, so a listener never observes a half-applied\n * transition.\n */\n const applyPlacement = useCallback((anchor: FloatAnchor, next: Stretch | null): void => {\n setCurrentAnchor(anchor);\n if (!isStretchControlled) setInternalStretch(next);\n onPlacementChangeRef.current?.({ anchor, stretch: next });\n }, [isStretchControlled, onPlacementChangeRef]);\n\n const dragState = useRef<{ mouseX: number; mouseY: number; posX: number; posY: number; hasDragged: boolean } | null>(null);\n\n // Bucket membership depends on the whole placement (see bucketsFor), so this re-runs whenever\n // the anchor or a stretched axis changes — not only on mount. Free-floating widgets are in no\n // stack at all.\n useLayoutEffect(() => {\n if (mode !== 'docked') return;\n ctx?.dockWindow(id, currentAnchor, stretch);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mode, currentAnchor, stretch]);\n\n // Leave the stack on unmount (close). Closing resets to the defaults on the next open, since a\n // fresh mount means fresh state.\n useLayoutEffect(() => () => { ctx?.undockWindow(id); },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []);\n\n // Dev-only: a block-stretched widget spans the whole block axis, so it cannot stack with\n // anything — it will simply overlap siblings on its own inline side, with z-order deciding.\n // Warns once per widget, matching the warning conventions in Sidebar/WindowManager.\n const blockStretchWarnedRef = useRef(false);\n useEffect(() => {\n if (process.env.NODE_ENV !== 'development') return;\n if (blockStretchWarnedRef.current) return;\n if (mode !== 'docked' || !stretchesBlock(stretch) || !ctx) return;\n const half = currentAnchor.endsWith('-right') ? 'right' : 'left';\n const neighbours = ([`top-${half}`, `bottom-${half}`] as FloatAnchor[])\n .flatMap(bucket => ctx.stacks[bucket] ?? [])\n .filter(other => other !== id);\n if (neighbours.length === 0) return;\n blockStretchWarnedRef.current = true;\n console.warn(\n `[react-dockable-desktop] RddFloatingWidget \"${id}\" stretches the block axis ` +\n `(stretch: \"${stretch}\") while ${neighbours.length} other widget(s) are anchored to the ` +\n `same side (${neighbours.join(', ')}). A block-stretched widget spans the axis that stacking ` +\n `uses to separate siblings, so it cannot stack and will overlap them — z-order decides which ` +\n `is on top. Either give it a fixed height, or move the other widgets to the opposite side.`\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mode, stretch, currentAnchor, ctx?.stacks, id]);\n\n // Report height whenever size changes so stack peers can compute their offset.\n useEffect(() => {\n ctx?.reportDockedSize(id, size.h);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [size.h]);\n\n const zOrder = ctx?.zOrders[id] ?? 101;\n\n const isActive = !ctx || ctx.topId === id;\n\n const getContainerBounds = (): { cw: number; ch: number } => {\n const container = windowRef.current?.offsetParent as HTMLElement | null;\n return { cw: container?.clientWidth ?? 9999, ch: container?.clientHeight ?? 9999 };\n };\n\n /**\n * The band a docked widget is allowed to occupy, in physical pixels from the container's edges.\n *\n * The block axis keeps clear of top/bottom `PanelToolbar`s only; the inline axis also adds the\n * `DOCK_INSET` gutter, matching how a docked widget is already positioned (one inline inset of\n * `DOCK_INSET`, one block inset of the toolbar size). Growth previously stopped at the raw\n * container edge, so a docked widget could be resized straight over the toolbar on the far side —\n * which the library elsewhere treats as a bug (a 5.x fix stopped docked floats *positioning*\n * themselves over a toolbar; the resize path never got the same treatment).\n *\n * Inline is converted from logical to physical here because handle directions and measured rects\n * are physical, while `PanelToolbar` claims its space logically.\n */\n const dockedBand = (): { left: number; right: number; top: number; bottom: number } => {\n const logicalStart = ctx?.insetInlineStart ?? 0;\n const logicalEnd = ctx?.insetInlineEnd ?? 0;\n return {\n left: (isRtl ? logicalEnd : logicalStart) + DOCK_INSET,\n right: (isRtl ? logicalStart : logicalEnd) + DOCK_INSET,\n top: ctx?.insetTop ?? 0,\n bottom: ctx?.insetBottom ?? 0,\n };\n };\n\n const handleWindowPointerDown = (): void => {\n ctx?.focusWindow(id);\n };\n\n const handleHeaderPointerDown = (e: React.PointerEvent<HTMLDivElement>): void => {\n if (e.button !== 0) return;\n e.preventDefault();\n\n let startX: number;\n let startY: number;\n\n if (modeRef.current === 'docked') {\n // Snapshot the rendered position so that *if* this becomes a real drag, switching to free\n // positioning causes no visual jump. Undocking itself is deferred to the drag threshold\n // below — doing it here meant a plain click on the header silently tore the widget off its\n // anchor: it looked unchanged, but its stacked siblings reflowed to close the gap and it\n // stopped tracking the corner on every later panel resize.\n const el = windowRef.current;\n const container = ctx?.containerRef?.current;\n if (el && container) {\n const elRect = el.getBoundingClientRect();\n const cRect = container.getBoundingClientRect();\n startX = elRect.left - cRect.left;\n startY = elRect.top - cRect.top;\n } else {\n startX = DOCK_INSET;\n startY = ctx?.insetTop ?? 0;\n }\n } else {\n startX = freePosRef.current?.x ?? 0;\n startY = freePosRef.current?.y ?? 0;\n }\n\n dragState.current = { mouseX: e.clientX, mouseY: e.clientY, posX: startX, posY: startY, hasDragged: false };\n windowRef.current?.setPointerCapture(e.pointerId);\n };\n\n const handleResizePointerDown = (dir: ResizeDir) => (e: React.PointerEvent<HTMLDivElement>): void => {\n if (e.button !== 0) return;\n e.preventDefault();\n e.stopPropagation();\n // Snapshot current rendered position for offset-from-edge calculations\n let startX = 0, startY = 0;\n if (modeRef.current === 'free') {\n startX = freePosRef.current?.x ?? 0;\n startY = freePosRef.current?.y ?? 0;\n } else {\n const el = windowRef.current;\n const container = el?.offsetParent as HTMLElement | null;\n if (el && container) {\n const er = el.getBoundingClientRect();\n const cr = container.getBoundingClientRect();\n startX = er.left - cr.left;\n startY = er.top - cr.top;\n }\n }\n // For a stretched axis the stored size is stale by design (the render branch stops reading it),\n // so the drag has to start from the *measured* extent or the widget would jump.\n const measured = windowRef.current?.getBoundingClientRect();\n const startRect = {\n x: startX,\n y: startY,\n w: stretchesInline(stretchRef.current) && measured ? measured.width : sizeRef.current.w,\n h: stretchesBlock(stretchRef.current) && measured ? measured.height : sizeRef.current.h,\n };\n\n // Dragging an end of a stretched axis releases that axis: the edge under the pointer becomes\n // the moving one and the opposite end becomes the new pin, so it reads exactly like an ordinary\n // resize. Done once per drag; `released` guards against repeat moves before the re-render.\n const dragsInline = dir.includes('e') || dir.includes('w');\n const dragsBlock = dir.includes('n') || dir.includes('s');\n let released = false;\n let armed = { inline: false, block: false };\n const releaseIfNeeded = (): void => {\n if (released || modeRef.current !== 'docked') return;\n const st = stretchRef.current;\n const releasingInline = dragsInline && stretchesInline(st);\n const releasingBlock = dragsBlock && stretchesBlock(st);\n if (!releasingInline && !releasingBlock) return;\n released = true;\n\n let next = st;\n let nextAnchor = currentAnchorRef.current;\n if (releasingInline) {\n next = releaseAxis(next, 'inline');\n // Pin the end opposite the dragged edge. Handle dirs are physical, anchors are logical.\n const pinsPhysicalLeft = dir.includes('e');\n nextAnchor = withInlineHalf(nextAnchor, (pinsPhysicalLeft !== isRtl) ? 'left' : 'right');\n }\n if (releasingBlock) {\n next = releaseAxis(next, 'block');\n nextAnchor = withBlockHalf(nextAnchor, dir.includes('s') ? 'top' : 'bottom');\n }\n applyPlacement(nextAnchor, next);\n };\n\n startPointerDrag({\n element: e.currentTarget,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => startRect,\n activeClasses: [{ el: document.body, classes: ['rdd-resizing-active'] }],\n onMove: (dx, dy, start) => {\n // Re-measured every move, matching the original's live re-measurement —\n // the container can in principle change size during a drag.\n const { cw, ch } = getContainerBounds();\n // Docked widgets stop at the toolbar band; free-floating ones stay unconstrained beyond the\n // container itself, since \"free\" means free.\n const band = modeRef.current === 'docked'\n ? dockedBand()\n : { left: 0, right: 0, top: 0, bottom: 0 };\n const { x: newX, y: newY, w: newW, h: newH } = computeResizedRect(dir, dx, dy, start, {\n minW: MIN_W, minH: MIN_H,\n maxW: (cw - band.right) - start.x, maxH: (ch - band.bottom) - start.y,\n minX: band.left, minY: band.top,\n });\n releaseIfNeeded();\n\n // ── resize-to-stretch snapping ──\n // The clamps above already stop growth exactly where a stretched axis would sit, so an\n // armed drag is already visually at its target; the cue is an outline rather than a ghost.\n if (modeRef.current === 'docked' && stretchable) {\n const fullInline = cw - band.left - band.right;\n const fullBlock = ch - band.top - band.bottom - stackOffsetRef.current;\n const st = stretchRef.current;\n const nextArmed = { ...armed };\n if (dragsInline && !stretchesInline(st)) {\n if (newW >= fullInline - SNAP_IN) nextArmed.inline = true;\n else if (armed.inline && newW < fullInline - SNAP_OUT) nextArmed.inline = false;\n }\n if (dragsBlock && !stretchesBlock(st)) {\n if (newH >= fullBlock - SNAP_IN) nextArmed.block = true;\n else if (armed.block && newH < fullBlock - SNAP_OUT) nextArmed.block = false;\n }\n if (nextArmed.inline !== armed.inline || nextArmed.block !== armed.block) {\n armed = nextArmed;\n setSnapArmed(nextArmed);\n }\n }\n // Only write an axis that carries a size. A still-stretched axis must keep its stored\n // value, so releasing it later restores the size it had before stretching.\n const st = released ? releaseAxis(releaseAxis(stretchRef.current,\n dragsInline ? 'inline' : 'block'), dragsBlock ? 'block' : 'inline') : stretchRef.current;\n setSize(prev => ({\n w: stretchesInline(st) ? prev.w : newW,\n h: stretchesBlock(st) ? prev.h : newH,\n }));\n if (modeRef.current === 'free') {\n setFreePos({ x: newX, y: newY });\n }\n },\n onEnd: (start) => {\n if (!armed.inline && !armed.block) {\n if (snapArmedRef.current.inline || snapArmedRef.current.block) {\n setSnapArmed({ inline: false, block: false });\n }\n return;\n }\n // Restore the size the axis had *before* this drag: while an axis is stretched its stored\n // size is what releasing it later returns to, so it should be the size the user last chose\n // deliberately — not the full-bleed value the drag happened to pass through.\n setSize(prev => ({\n w: armed.inline ? start.w : prev.w,\n h: armed.block ? start.h : prev.h,\n }));\n let next = stretchRef.current;\n if (armed.inline) next = addAxis(next, 'inline');\n if (armed.block) next = addAxis(next, 'block');\n applyPlacement(currentAnchorRef.current, next);\n setSnapArmed({ inline: false, block: false });\n },\n });\n };\n\n const handleWindowPointerMove = (e: React.PointerEvent): void => {\n if (dragState.current) {\n const ds = dragState.current;\n if (!ds.hasDragged) {\n const dist = Math.abs(e.clientX - ds.mouseX) + Math.abs(e.clientY - ds.mouseY);\n if (dist < 4) return;\n ds.hasDragged = true;\n // This, not pointerdown, is the moment the widget leaves its anchor.\n if (modeRef.current === 'docked') {\n // A stretched axis carries no size, so free mode — which positions from an explicit box —\n // would otherwise snap back to whatever the size was before stretching. Materialise what\n // is actually on screen, then clear stretch: \"free\" and \"spanning the panel\" are\n // mutually exclusive.\n if (stretchRef.current) {\n const r = windowRef.current?.getBoundingClientRect();\n if (r) setSize({ w: Math.round(r.width), h: Math.round(r.height) });\n applyPlacement(currentAnchorRef.current, null);\n }\n ctx?.undockWindow(id);\n setMode('free');\n }\n document.body.classList.add('rdd-dragging-active');\n ctx?.setDraggingId(id);\n }\n const { cw, ch } = getContainerBounds();\n const newX = Math.max(0, Math.min(ds.posX + e.clientX - ds.mouseX, cw - sizeRef.current.w));\n const newY = Math.max(0, Math.min(ds.posY + e.clientY - ds.mouseY, ch - sizeRef.current.h));\n setFreePos({ x: newX, y: newY });\n\n const container = ctx?.containerRef?.current;\n if (container) {\n const rawZone = getHoveredZone(container, e.clientX, e.clientY);\n ctx?.setHoveredZone(rawZone && isRtl ? flipZoneHorizontal(rawZone) : rawZone);\n }\n }\n };\n\n const handleWindowPointerUp = (): void => {\n if (dragState.current?.hasDragged) {\n const zone = ctx?.hoveredZone;\n if (zone) {\n ctx?.dockWindow(id, zone, stretchRef.current);\n setMode('docked');\n setFreePos(null);\n applyPlacement(zone, stretchRef.current);\n }\n ctx?.setHoveredZone(null);\n ctx?.setDraggingId(null);\n }\n document.body.classList.remove('rdd-dragging-active');\n dragState.current = null;\n };\n\n const handleWindowPointerCancel = (): void => {\n if (dragState.current?.hasDragged) {\n ctx?.setHoveredZone(null);\n ctx?.setDraggingId(null);\n }\n document.body.classList.remove('rdd-dragging-active');\n dragState.current = null;\n };\n\n // ── Compute position style ─────────────────────────────────────────────────\n let windowStyle: React.CSSProperties;\n\n // This render's stack offset while docked, for the drag handlers (see stackOffsetRef). Left\n // null in free mode, where the ref keeps its last docked value, as before.\n let dockedStackOffset: number | null = null;\n if (mode === 'docked' && ctx) {\n // Offset is the largest offset across every bucket this widget occupies, so a strip spanning\n // an edge clears whatever is stacked in *both* of that edge's corners.\n const buckets = bucketsFor(currentAnchor, stretch);\n let stackOffset = 0;\n // A widget with no buckets (block-stretched) is never \"in\" a stack, so it must not be held\n // invisible by the not-yet-registered guard below.\n let registered = buckets.length === 0;\n for (const bucket of buckets) {\n const stack = ctx.stacks[bucket] ?? [];\n const idx = stack.indexOf(id);\n if (idx === -1) continue;\n registered = true;\n let offset = 0;\n for (let i = 0; i < idx; i++) {\n offset += (ctx.dockedSizes[stack[i]] ?? defaultHeight) + DOCK_GAP;\n }\n stackOffset = Math.max(stackOffset, offset);\n }\n dockedStackOffset = stackOffset;\n\n const band = dockedBand();\n\n windowStyle = {\n zIndex: zOrder,\n transition: 'top 0.2s ease, bottom 0.2s ease',\n // Hide until registered in stack (first layout effect hasn't run yet)\n opacity: registered ? undefined : 0,\n pointerEvents: registered ? undefined : 'none',\n };\n\n // Inline axis: one inset plus an explicit width, or both insets and no width at all. Setting\n // both ends is the whole mechanism — CSS then keeps the widget spanning the panel for free.\n if (stretchesInline(stretch)) {\n windowStyle.insetInlineStart = (ctx.insetInlineStart ?? 0) + DOCK_INSET;\n windowStyle.insetInlineEnd = (ctx.insetInlineEnd ?? 0) + DOCK_INSET;\n } else {\n windowStyle[currentAnchor.endsWith('-right') ? 'insetInlineEnd' : 'insetInlineStart'] = DOCK_INSET;\n windowStyle.width = size.w;\n }\n\n // Block axis: same idea. Note the block insets carry no DOCK_INSET gutter, matching how a\n // docked widget has always been positioned against a top/bottom toolbar (flush, not inset).\n if (stretchesBlock(stretch)) {\n windowStyle.top = band.top;\n windowStyle.bottom = band.bottom;\n } else if (currentAnchor.startsWith('top-')) {\n windowStyle.top = band.top + stackOffset;\n windowStyle.height = size.h;\n } else {\n windowStyle.bottom = band.bottom + stackOffset;\n windowStyle.height = size.h;\n }\n } else {\n windowStyle = {\n left: freePos?.x ?? 0,\n top: freePos?.y ?? 0,\n width: size.w,\n height: size.h,\n zIndex: zOrder,\n };\n }\n useInsertionEffect(() => {\n if (dockedStackOffset !== null) stackOffsetRef.current = dockedStackOffset;\n });\n\n // ── Which resize handles this window offers ────────────────────────────────\n // Free-floating: all eight, nothing is pinned.\n //\n // Docked: only the edges that can actually move. A docked window has one edge pinned per axis\n // (see the positioning block above — `top-*` pins `top`, `bottom-*` pins `bottom`, `*-left`\n // pins `insetInlineStart`, `*-right` pins `insetInlineEnd`), so dragging a handle on a pinned\n // side moves the *opposite* edge instead of the one under the cursor, and can't move it further\n // than that side's own inset before `computeResizedRect`'s bounds stop it — an inert stub with a\n // resize cursor on it. The handle set used to be hardcoded to the five non-northern directions\n // regardless of anchor, which made that harmless-looking for top anchors but left every\n // bottom-anchored window with no working vertical resize at all: `n` wasn't rendered, and `s`\n // was the stub.\n //\n // Restricting docked mode to free edges also means the existing resize bounds are already\n // correct for every direction that remains: `maxW`/`maxH` apply only to eastward/southward\n // growth (where the top-left origin genuinely is pinned), while `minX`/`minY` bound the moving\n // edge for westward/northward growth — so no change to the resize math is needed.\n const handleDirs: ResizeDir[] = React.useMemo(() => {\n if (mode === 'free') return ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'];\n\n // Block axis is direction-agnostic; the inline axis is not. The pin is a logical property\n // (`insetInlineEnd`) but the handle classes are physical (`.rdd-resize-e { right: -4px }`), so\n // which *physical* side is pinned depends on the window's own `dir`.\n const freeBlock: ResizeDir = currentAnchor.startsWith('top-') ? 's' : 'n';\n const pinsPhysicalRight = currentAnchor.endsWith('-right') !== isRtl;\n const freeInline: ResizeDir = pinsPhysicalRight ? 'w' : 'e';\n\n const inlineStretched = stretchesInline(stretch);\n const blockStretched = stretchesBlock(stretch);\n\n // A stretched axis has both ends pinned, but both are *releasable*: dragging either end moves\n // that edge and pins the opposite one, so the widget leaves stretch at the width the drag\n // produced. Hence handles on both ends — which is also what keeps the fully-stretched state\n // from being a dead end with nothing to grab.\n const dirs: ResizeDir[] = [];\n dirs.push(...(inlineStretched ? (['e', 'w'] as ResizeDir[]) : [freeInline]));\n dirs.push(...(blockStretched ? (['n', 's'] as ResizeDir[]) : [freeBlock]));\n // The corner belongs only to the all-pinned state; in a stretched state it would mix a resize\n // and a release into one gesture.\n if (!inlineStretched && !blockStretched) dirs.push(`${freeBlock}${freeInline}` as ResizeDir);\n return dirs;\n }, [mode, currentAnchor, isRtl, stretch]);\n\n const CloseIcon = (\n <svg width=\"8\" height=\"8\" viewBox=\"0 0 10 10\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\">\n <line x1=\"1\" y1=\"1\" x2=\"9\" y2=\"9\" />\n <line x1=\"9\" y1=\"1\" x2=\"1\" y2=\"9\" />\n </svg>\n );\n\n return (\n <div\n ref={windowRef}\n dir={isRtl ? 'rtl' : 'ltr'}\n data-rdd-widget={id}\n className={[\n 'rdd-panel-float',\n isActive ? 'rdd-panel-float--active' : '',\n snapArmed.inline || snapArmed.block ? 'rdd-panel-float--snapping' : '',\n ].filter(Boolean).join(' ')}\n style={windowStyle}\n onPointerDown={handleWindowPointerDown}\n onPointerMove={handleWindowPointerMove}\n onPointerUp={handleWindowPointerUp}\n onPointerCancel={handleWindowPointerCancel}\n >\n {/* Clips header and body to the rounded corners; the resize handles are its siblings so\n they can straddle the edge instead of being half clipped. */}\n <div className=\"rdd-panel-float__frame\">\n <div className=\"rdd-panel-float__header\" onPointerDown={handleHeaderPointerDown}>\n {icon && <span className=\"rdd-panel-float__icon\">{icon}</span>}\n <span className=\"rdd-panel-float__title\">{formatLabel(title, formatMessage)}</span>\n <button\n type=\"button\"\n className=\"rdd-panel-float__close\"\n onClick={onClose}\n onPointerDown={e => e.stopPropagation()}\n title={formatLabel(messages.closeTooltip, formatMessage)}\n aria-label={formatLabel(messages.closeTooltip, formatMessage)}\n >\n {CloseIcon}\n </button>\n </div>\n <div className=\"rdd-panel-float__body\">{children}</div>\n </div>\n {handleDirs.map(dir => (\n <div\n key={dir}\n className={`rdd-resize-handle rdd-resize-${dir}`}\n onPointerDown={handleResizePointerDown(dir)}\n />\n ))}\n </div>\n );\n}\n","import type { FloatAnchor } from '../types';\n\n/**\n * Mirrors a physical workspace corner to its horizontal opposite.\n *\n * Used only to translate a physically-hovered corner (raw pointer/screen\n * position, which CSS cannot reason about) into the logical `FloatAnchor`\n * value stored on a `FloatingWindow` under RTL. Render-time positioning\n * should use CSS logical properties (`insetInlineStart`/`insetInlineEnd`)\n * driven by the element's `dir` attribute instead of calling this.\n */\nexport function flipZoneHorizontal(zone: FloatAnchor): FloatAnchor {\n if (zone === 'top-left') return 'top-right';\n if (zone === 'top-right') return 'top-left';\n if (zone === 'bottom-left') return 'bottom-right';\n return 'bottom-left';\n}\n","/**\n * @file panelOverlayGeometry.ts\n * @description Pure geometry of the Panel Overlay: the corner drop zones and a floating widget's\n * size, dock and snap distances.\n */\nimport type { FloatAnchor } from '../types';\n\n// ─── Helper ───────────────────────────────────────────────────────────────────\n\nexport const DROP_ZONE_SIZE = 80;\n\nexport function getHoveredZone(container: HTMLElement, clientX: number, clientY: number): FloatAnchor | null {\n const rect = container.getBoundingClientRect();\n const x = clientX - rect.left;\n const y = clientY - rect.top;\n if (x < DROP_ZONE_SIZE && y < DROP_ZONE_SIZE) return 'top-left';\n if (x > rect.width - DROP_ZONE_SIZE && y < DROP_ZONE_SIZE) return 'top-right';\n if (x < DROP_ZONE_SIZE && y > rect.height - DROP_ZONE_SIZE) return 'bottom-left';\n if (x > rect.width - DROP_ZONE_SIZE && y > rect.height - DROP_ZONE_SIZE) return 'bottom-right';\n return null;\n}\n\nexport const MIN_W = 120;\nexport const MIN_H = 60;\nexport const DOCK_INSET = 8;\nexport const DOCK_GAP = 8;\n/**\n * Resize-to-stretch snapping. Asymmetric on purpose: arming within `SNAP_IN` of the full extent\n * but only disarming once the drag pulls back past the wider `SNAP_OUT`. Without that hysteresis,\n * releasing a stretched axis by dragging a few pixels inward would immediately re-arm and snap\n * straight back on release, which makes the gesture feel broken.\n */\nexport const SNAP_IN = 16;\nexport const SNAP_OUT = 40;\n","/**\n * @file PanelToolbar.tsx\n * @description A toolbar on a panel edge, and its buttons, toggles and layout primitives.\n */\nimport React, { useContext, useRef, useLayoutEffect } from 'react';\nimport type { ToolbarPosition } from './types';\nimport { PanelToolbarContext } from './context';\n\n// ─── PanelToolbar ─────────────────────────────────────────────────────────────\n\n/** Background style of a `PanelToolbar`. */\nexport type ToolbarVariant = 'transparent' | 'frosted' | 'solid';\n\n/** Visual style applied to `ToolbarButton` and `ToolbarToggle` components. */\nexport type ButtonVariant = 'ghost' | 'soft' | 'outlined' | 'filled';\n\n/** Props for `<RddPanelToolbar>`. */\nexport interface RddPanelToolbarProps {\n /** Edge of the panel overlay to attach to. @see ToolbarPosition */\n position: ToolbarPosition;\n /** Background style of the toolbar strip. @default 'transparent' */\n variant?: ToolbarVariant;\n /** Default button style inherited by `ToolbarButton` and `ToolbarToggle` children. @default 'ghost' */\n buttonVariant?: ButtonVariant;\n /** Button size in pixels for all buttons in this toolbar (sets `--rdd-panel-toolbar-btn-size`). The icon inside follows `--rdd-panel-toolbar-icon-size`. Falls back to the stylesheet when unset. */\n buttonSize?: number;\n style?: React.CSSProperties;\n className?: string;\n children?: React.ReactNode;\n}\n\n/**\n * Toolbar strip that attaches to any edge of an `RddPanelOverlay`.\n * Left/right toolbars inset automatically to avoid overlapping top/bottom toolbars.\n * RTL layouts are detected and handled automatically.\n * @example\n * <RddPanelToolbar position=\"top\" variant=\"frosted\">\n * <RddToolbarButton icon={<SaveIcon />} title=\"Save\" onClick={save} />\n * <RddToolbarToggle icon={<GridIcon />} title=\"Grid\" active={grid} onToggle={() => setGrid(v => !v)} />\n * </RddPanelToolbar>\n */\nexport function PanelToolbar({ position, variant = 'transparent', buttonVariant = 'ghost', buttonSize, style, className, children }: RddPanelToolbarProps): React.ReactElement {\n const ctx = useContext(PanelToolbarContext);\n const ref = useRef<HTMLDivElement>(null);\n const cleanupRef = useRef<(() => void) | null>(null);\n\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n if (!ctx) return;\n const measure = () => {\n const size = (position === 'top' || position === 'bottom') ? el.offsetHeight : el.offsetWidth;\n cleanupRef.current?.();\n cleanupRef.current = ctx.registerToolbar(position, size);\n };\n measure();\n // A one-shot measurement is correct for a live mount (already at final size), but during a\n // layout restore (loadLayout()/initialState) the panel's DOM isn't necessarily settled yet at\n // this exact instant — without re-measuring, a wrong size (often 0) is baked in permanently,\n // and every docked float ends up positioned at the toolbar's own y/x, covering it. This also\n // catches any later size change (button wrapping, a buttonSize/variant change, content change).\n const ro = new ResizeObserver(measure);\n ro.observe(el);\n return () => {\n ro.disconnect();\n cleanupRef.current?.();\n cleanupRef.current = null;\n };\n // ctx?.registerToolbar is a stable useCallback — depending on ctx directly\n // would re-run on every toolbarSizes update, causing an infinite loop.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [position, ctx?.registerToolbar]);\n\n const posStyle: React.CSSProperties = { position: 'absolute', zIndex: 5, pointerEvents: 'none', boxSizing: 'border-box' };\n\n if (position === 'top') {\n posStyle.top = 0; posStyle.left = 0; posStyle.right = 0;\n } else if (position === 'bottom') {\n posStyle.bottom = 0; posStyle.left = 0; posStyle.right = 0;\n } else if (position === 'left') {\n posStyle.insetInlineStart = 0;\n posStyle.top = ctx?.insetTop ?? 0;\n posStyle.bottom = ctx?.insetBottom ?? 0;\n } else {\n posStyle.insetInlineEnd = 0;\n posStyle.top = ctx?.insetTop ?? 0;\n posStyle.bottom = ctx?.insetBottom ?? 0;\n }\n\n const isSide = position === 'left' || position === 'right';\n const sideStyle: React.CSSProperties = isSide ? {\n ...(ctx?.insetTop ?? 0) > 0 ? { paddingTop: 0 } : {},\n ...(ctx?.insetBottom ?? 0) > 0 ? { paddingBottom: 0 } : {},\n } : {};\n\n const sizeStyle: React.CSSProperties = buttonSize != null\n ? { ['--rdd-panel-toolbar-btn-size' as string]: `${buttonSize}px` }\n : {};\n\n return (\n <div\n ref={ref}\n className={`rdd-panel-toolbar rdd-panel-toolbar--${position}${className ? ' ' + className : ''}`}\n data-variant={variant}\n data-btn-variant={buttonVariant}\n style={{ ...posStyle, ...sideStyle, ...sizeStyle, ...style }}\n >\n {children}\n </div>\n );\n}\n\n// ─── ToolbarButton ────────────────────────────────────────────────────────────\n\n/** Props for `<RddToolbarButton>`. */\nexport interface RddToolbarButtonProps {\n /** Button icon: an SVG, an icon component or an icon-font glyph. Pass no size: the library sizes it with `--rdd-panel-toolbar-icon-size`. */\n icon: React.ReactNode;\n /** Click handler. */\n onClick(): void;\n disabled?: boolean;\n /** Tooltip text and accessible `aria-label`. */\n title?: string;\n /** Visual style override. Falls back to the parent `PanelToolbar`'s `buttonVariant`. */\n variant?: ButtonVariant;\n}\n\n/** Icon button for use inside a `PanelToolbar`. */\nexport function ToolbarButton({ icon, onClick, disabled, title, variant }: RddToolbarButtonProps): React.ReactElement {\n return (\n <button\n type=\"button\"\n className=\"rdd-panel-toolbar-btn\"\n onClick={onClick}\n disabled={disabled}\n title={title}\n aria-label={title}\n {...(variant ? { 'data-variant': variant } : {})}\n >\n {icon}\n </button>\n );\n}\n\n// ─── ToolbarToggle ────────────────────────────────────────────────────────────\n\n/** Props for `<RddToolbarToggle>`. */\nexport interface RddToolbarToggleProps {\n /** Button icon: an SVG, an icon component or an icon-font glyph. Pass no size: the library sizes it with `--rdd-panel-toolbar-icon-size`. */\n icon: React.ReactNode;\n /** Whether the toggle is in the active/pressed state. Sets `aria-pressed` automatically. */\n active: boolean;\n /** Called when the button is clicked. Toggle `active` in response. */\n onToggle(): void;\n disabled?: boolean;\n /** Tooltip text and accessible `aria-label`. */\n title?: string;\n /** Visual style override. Falls back to the parent `PanelToolbar`'s `buttonVariant`. */\n variant?: ButtonVariant;\n}\n\n/** Two-state icon toggle button for use inside a `PanelToolbar`. Sets `aria-pressed` automatically. */\nexport function ToolbarToggle({ icon, active, onToggle, disabled, title, variant }: RddToolbarToggleProps): React.ReactElement {\n return (\n <button\n type=\"button\"\n className={`rdd-panel-toolbar-btn${active ? ' rdd-panel-toolbar-btn--active' : ''}`}\n onClick={onToggle}\n disabled={disabled}\n title={title}\n aria-label={title}\n aria-pressed={active}\n {...(variant ? { 'data-variant': variant } : {})}\n >\n {icon}\n </button>\n );\n}\n\n// ─── ToolbarSeparator ─────────────────────────────────────────────────────────\n\n/** Vertical (or horizontal) divider line between groups of toolbar items. */\nexport function ToolbarSeparator(): React.ReactElement {\n return <span className=\"rdd-panel-toolbar__sep\" aria-hidden=\"true\" />;\n}\n\n// ─── ToolbarSpacer ────────────────────────────────────────────────────────────\n\n/** Flex-grow spacer that pushes subsequent toolbar items to the far edge. */\nexport function ToolbarSpacer(): React.ReactElement {\n return <span className=\"rdd-panel-toolbar__spacer\" aria-hidden=\"true\" />;\n}\n\n// ─── ToolbarItem (custom control wrapper) ────────────────────────────────────\n\n/** Wrapper for a custom non-button control (e.g. a dropdown or input) inside a `PanelToolbar`. */\nexport function ToolbarItem({ children }: { children: React.ReactNode }): React.ReactElement {\n return <span className=\"rdd-panel-toolbar__item\">{children}</span>;\n}\n\n// ─── ToolbarCenter ────────────────────────────────────────────────────────────\n\n/** Centers its children within the toolbar using absolute positioning. */\nexport function ToolbarCenter({ children }: { children: React.ReactNode }): React.ReactElement {\n return <div className=\"rdd-panel-toolbar__center\">{children}</div>;\n}\n","/**\n * @file ToolbarSearch.tsx\n * @description The search field of a panel toolbar, with its results dropdown.\n */\nimport React, { useState, useRef, useMemo, useEffect } from 'react';\nimport { createPortal } from 'react-dom';\nimport { formatLabel, useFormatMessage, usePredefinedMessages } from '../WindowManagerContext';\n\n// ─── ToolbarSearchInput ───────────────────────────────────────────────────────\n\n/** A single result item returned by `RddToolbarSearchProps.onSearch`. */\nexport interface SearchResult {\n /** Unique identifier for this result — passed to `onSelect`. */\n id: string;\n /** Primary display text. */\n label: string;\n /** Optional secondary text shown below the label in the dropdown. */\n description?: string;\n /** Optional group header used to bucket results visually. */\n group?: string;\n /** Optional icon shown to the left of the label. */\n icon?: React.ReactNode;\n}\n\n/** Props for `<RddToolbarSearch>`. */\nexport interface RddToolbarSearchProps {\n /** Placeholder text shown in the expanded input field. @default the `searchPlaceholder` message ('Search…') */\n placeholder?: string;\n /**\n * Called with the current query and an `AbortSignal` each time the input changes (debounced).\n * Return `SearchResult[]` directly for synchronous sources, or `Promise<SearchResult[]>` for async.\n * Abort in-flight requests when the signal fires to prevent stale result races.\n */\n onSearch(query: string, signal: AbortSignal): Promise<SearchResult[]> | SearchResult[];\n /** Called when the user selects a result from the dropdown. */\n onSelect(result: SearchResult): void;\n}\n\n/**\n * Debounced async search field for use inside a `PanelToolbar`.\n * Renders as a compact icon button that expands into a text input on activation.\n * Results appear in a portal-rendered dropdown below the input.\n * @example\n * <ToolbarSearchInput\n * placeholder=\"Find layer…\"\n * onSearch={(q, signal) => fetchLayers(q, { signal })}\n * onSelect={result => workspace.focusLayer(result.id)}\n * />\n */\nexport function ToolbarSearchInput({ placeholder, onSearch, onSelect }: RddToolbarSearchProps): React.ReactElement {\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const searchLabel = formatLabel(messages.search, formatMessage);\n const closeSearchLabel = formatLabel(messages.closeSearch, formatMessage);\n const placeholderText = placeholder ?? formatLabel(messages.searchPlaceholder, formatMessage);\n const [expanded, setExpanded] = useState(false);\n const [query, setQuery] = useState('');\n const [results, setResults] = useState<SearchResult[]>([]);\n const [dropdownPos, setDropdownPos] = useState<{ top: number; left: number; width: number } | null>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const abortRef = useRef<AbortController | null>(null);\n const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Unmounting stops the search (7.4.1): a pending debounce would still call onSearch for a\n // toolbar that has gone, and a search in flight would never see its signal abort.\n useEffect(() => () => {\n abortRef.current?.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n }, []);\n\n const openSearch = (): void => {\n setExpanded(true);\n setTimeout(() => inputRef.current?.focus({ preventScroll: true }), 0);\n };\n\n const closeSearch = (): void => {\n setExpanded(false);\n setQuery('');\n setResults([]);\n setDropdownPos(null);\n abortRef.current?.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n };\n\n const handleQueryChange = (e: React.ChangeEvent<HTMLInputElement>): void => {\n const q = e.target.value;\n setQuery(q);\n abortRef.current?.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n if (!q.trim()) { setResults([]); setDropdownPos(null); return; }\n\n debounceRef.current = setTimeout(async () => {\n const ctrl = new AbortController();\n abortRef.current = ctrl;\n try {\n const res = await onSearch(q, ctrl.signal);\n if (!ctrl.signal.aborted) {\n setResults(res);\n const el = containerRef.current;\n if (el && res.length > 0) {\n const r = el.getBoundingClientRect();\n const dropW = Math.max(r.width, 240);\n let left = r.left;\n if (left + dropW > window.innerWidth - 8) left = window.innerWidth - dropW - 8;\n setDropdownPos({ top: r.bottom + 4, left, width: dropW });\n } else {\n setDropdownPos(null);\n }\n }\n } catch {\n // AbortError or user-thrown — ignore\n }\n }, 300);\n };\n\n const handleSelect = (result: SearchResult): void => {\n onSelect(result);\n closeSearch();\n };\n\n const handleBlur = (e: React.FocusEvent): void => {\n if (!containerRef.current?.contains(e.relatedTarget as Node)) {\n closeSearch();\n }\n };\n\n const handleKeyDown = (e: React.KeyboardEvent): void => {\n if (e.key === 'Escape') {\n // Claim the key so the drawer or modal holding this panel stays open (see escapeStack).\n e.preventDefault();\n closeSearch();\n }\n };\n\n const grouped = useMemo((): Record<string, SearchResult[]> => {\n const map: Record<string, SearchResult[]> = {};\n for (const r of results) {\n const g = r.group ?? '';\n if (!map[g]) map[g] = [];\n map[g].push(r);\n }\n return map;\n }, [results]);\n\n const SearchIcon = (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <circle cx=\"6.5\" cy=\"6.5\" r=\"4.5\" />\n <line x1=\"10\" y1=\"10\" x2=\"14\" y2=\"14\" />\n </svg>\n );\n\n if (!expanded) {\n return (\n <div ref={containerRef} className=\"rdd-panel-toolbar-search\">\n <button type=\"button\" className=\"rdd-panel-toolbar-btn\" onClick={openSearch} title={searchLabel} aria-label={searchLabel}>\n {SearchIcon}\n </button>\n </div>\n );\n }\n\n return (\n <div ref={containerRef} className=\"rdd-panel-toolbar-search rdd-panel-toolbar-search--open\" onBlur={handleBlur}>\n <button type=\"button\" className=\"rdd-panel-toolbar-btn\" onClick={closeSearch} aria-label={closeSearchLabel} title={closeSearchLabel}>\n {SearchIcon}\n </button>\n <input\n ref={inputRef}\n className=\"rdd-panel-toolbar-search__input\"\n type=\"text\"\n value={query}\n onChange={handleQueryChange}\n onKeyDown={handleKeyDown}\n placeholder={placeholderText}\n aria-label={searchLabel}\n autoComplete=\"off\"\n />\n {dropdownPos && results.length > 0 && createPortal(\n <div\n className=\"rdd-panel-toolbar-search__dropdown\"\n // z-index from .rdd-panel-toolbar-search__dropdown (+8502), not inline, so\n // zIndexBase shifts it too. Resolves to the same 9502 by default.\n style={{ top: dropdownPos.top, left: dropdownPos.left, width: dropdownPos.width }}\n onMouseDown={e => e.preventDefault()}\n >\n {Object.entries(grouped).map(([group, items]) => (\n <React.Fragment key={group || '__default__'}>\n {group && <div className=\"rdd-panel-toolbar-search__group\">{group}</div>}\n {items.map(item => (\n <button\n key={item.id}\n type=\"button\"\n className=\"rdd-panel-toolbar-search__item\"\n onClick={() => handleSelect(item)}\n >\n {item.icon && <span className=\"rdd-panel-toolbar-search__item-icon\">{item.icon}</span>}\n <span className=\"rdd-panel-toolbar-search__item-label\">{item.label}</span>\n {item.description && <span className=\"rdd-panel-toolbar-search__item-desc\">{item.description}</span>}\n </button>\n ))}\n </React.Fragment>\n ))}\n </div>,\n document.body,\n )}\n </div>\n );\n}\n","/**\n * @file useFloatingWidgets.tsx\n * @description The hooks that open floating widgets from code: one widget, or a set managed by id.\n */\nimport { useState, useContext, useCallback, useMemo } from 'react';\nimport type { ManagedWidget } from './types';\nimport { PanelManagerContext } from './context';\n\n// ─── usePanelFloatingWindow ───────────────────────────────────────────────────\n\n/** Return type of `usePanelFloatingWindow`. @see usePanelFloatingWindow */\nexport interface UsePanelFloatingWindowReturn {\n /** Whether the floating window is currently open. */\n isOpen: boolean;\n /** Open the floating window. */\n open(): void;\n /** Close the floating window. */\n close(): void;\n}\n\n/**\n * Manages the open/close boolean state for a single `RddFloatingWidget`.\n * Pass `isOpen` to `open`, `close` to `onClose` on the component directly.\n * @returns A stable `UsePanelFloatingWindowReturn` object.\n * @example\n * const info = usePanelFloatingWindow();\n * <RddFloatingWidget id=\"info\" open={info.isOpen} onClose={info.close} ... />\n */\nexport function usePanelFloatingWindow(): UsePanelFloatingWindowReturn {\n const [isOpen, setIsOpen] = useState(false);\n const open = useCallback((): void => { setIsOpen(true); }, []);\n const close = useCallback((): void => { setIsOpen(false); }, []);\n return { isOpen, open, close };\n}\n\n// ─── usePanelFloatingWindowManager ───────────────────────────────────────────\n\nconst EMPTY_IDS: string[] = [];\n\n/**\n * What `useFloatingWidgets()` returns.\n */\nexport interface FloatingWidgetsApi {\n /** Spawn or reconfigure a named window. Safe to call with an already-open ID to update config. */\n open(id: string, config: ManagedWidget): void;\n /** Close a named window by ID. No-op if the window is not open. */\n close(id: string): void;\n /** Close all managed windows. */\n closeAll(): void;\n /** Returns `true` if the named window is currently open. */\n isOpen(id: string): boolean;\n /** IDs of all currently open managed windows. Changes to this array trigger re-renders. */\n openIds: string[];\n}\n\n/**\n * Imperative hook for spawning N named floating windows at runtime from data or event handlers.\n * All widgets share z-ordering, drag, and corner-docking infrastructure of the `RddPanelOverlay`,\n * and accept the same placement options — including {@link ManagedWidget.stretch} to span an\n * axis of the panel.\n *\n * Must be called inside a **descendant** of `RddPanelOverlay`, not in the component that renders it.\n * @returns A stable `FloatingWidgetsApi`.\n * @example\n * const manager = useFloatingWidgets();\n * manager.open('feature-42', { title: 'Feature 42', content: <FeatureDetail id={42} />, anchor: 'top-right' });\n *\n * // A full-width strip along the bottom edge:\n * manager.open('timeline', { title: 'Timeline', content: <Timeline />, anchor: 'bottom-left', stretch: 'width', height: 120 });\n */\nexport function usePanelFloatingWindowManager(): FloatingWidgetsApi {\n const ctx = useContext(PanelManagerContext);\n const ids = ctx?.managedWindowIds ?? EMPTY_IDS;\n\n return useMemo(() => ({\n open: (id: string, config: ManagedWidget) => ctx?.openManaged(id, config),\n close: (id: string) => ctx?.closeManaged(id),\n closeAll: () => ctx?.closeAllManaged(),\n isOpen: (id: string) => ids.includes(id),\n openIds: ids,\n }), [ctx, ids]);\n}\n"],"mappings":"AAOA,OAAgB,cAAAA,GAAY,cAAAC,GAAY,aAAAC,GAAW,mBAAAC,GAAiB,WAAAC,GAAS,UAAAC,OAAc,QC+DpF,IAAMC,GAAN,KAAoB,CACjB,SAAW,IAAI,IAQvB,SACEC,EACAC,EACAC,EACM,CACN,KAAK,SAAS,IAAIF,EAAI,CACpB,UAAWC,EACX,eAAAC,CACF,CAAC,CACH,CAKA,IAAIF,EAA4C,CAC9C,OAAO,KAAK,SAAS,IAAIA,CAAE,CAC7B,CAKA,kBAA6B,CAC3B,OAAO,MAAM,KAAK,KAAK,SAAS,KAAK,CAAC,CACxC,CACF,EAGaG,G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C,GAAa,WAAAC,OAAe,QAiC3D,IAAMC,GAAsB,CAAC,EAiCtB,SAASC,IAAoD,CAClE,IAAMC,EAAMC,GAAWC,EAAmB,EACpCC,EAAMH,GAAK,kBAAoBF,GAErC,OAAOM,GAAQ,KAAO,CACpB,KAAM,CAACC,EAAYC,IAA0BN,GAAK,YAAYK,EAAIC,CAAM,EACxE,MAAQD,GAAeL,GAAK,aAAaK,CAAE,EAC3C,SAAU,IAAML,GAAK,gBAAgB,EACrC,OAASK,GAAeF,EAAI,SAASE,CAAE,EACvC,QAASF,CACX,GAAI,CAACH,EAAKG,CAAG,CAAC,CAChB","names":["forwardRef","useContext","useEffect","useLayoutEffect","useMemo","useRef","PanelRegistry","id","Component","defaultOptions","globalPanelRegistry","createContext","useContext","useState","useMemo","useEffect","useSyncExternalStore","createContext","useContext","useSyncExternalStore","defaultContract","FormContainerContext","FormContainerProvider","useFormContainer","usePanelSize","onResize","getDimensions","onStoreChange","createContext","useContext","records","isOnScreen","el","trackPanelDom","root","record","e","target","restorePanelDom","refocus","apply","top","left","focused","focusWasLost","forgetPanelDom","createPanelHost","elements","dimensions","lifecycle","id","el","trackPanelDom","size","entry","PanelHostContext","createContext","usePanelHost","host","useContext","FIELDS","stacks","apply","doc","stack","touched","root","pick","field","i","skin","noAnimations","zBase","claimDocumentMirror","owner","values","claim","c","releaseDocumentMirror","fields","index","released","defaultPredefinedMessages","defaultFormatMessage","msg","text","key","value","formatLabel","label","formatter","isValidElement","isSerializable","value","type","proto","shallowEqual","a","b","ka","k","sameTitle","sameDirtyOptions","keys","x","y","PanelEventBus","event","callback","cb","data","e","EMPTY_LEAF","isVisibleActiveTarget","id","scope","info","w","isLeafSelection","node","deriveActivePanelId","isCandidate","fromLeaves","child","found","selected","frontmost","resolveActivePanelId","next","preferId","repairLayoutTree","gridRoot","panels","repairs","seen","walk","kept","panelId","activePanelId","children","c","sizesOk","sizes","n","v","unchanged","i","sum","a","b","s","root","orphans","p","attach","ids","orphan","removePanelFromTree","idx","updatedLeaf","addPanelToLeaf","leafId","isLoneOccupant","hasLeaf","isShownInGrid","findLeafIdOf","findFirstLeafId","splitLeafInTree","position","splitRatio","newLeaf","orientation","DEFAULT_FLOAT_RECT","finiteGeometry","fw","repairs","out","k","v","parseLayoutPayload","input","parsed","geometryRepairs","floating","anchor","_sr","_sb","rest","panels","repaired","repairLayoutTree","gridRoot","scope","persisted","activePanelId","isVisibleActiveTarget","deriveActivePanelId","parseInitialState","json","payload","EMPTY_LEAF","createWorkspaceCore","config","registry","effectiveDir","effectiveZIndexBase","state","parseInitialState","listeners","setState","update","prev","next","listener","stateRef","getSnapshot","subscribeToState","cb","closeGuardsRef","stateProvidersRef","eventBusRef","PanelEventBus","topZ","floating","top","w","maxZRef","subscribe","event","callback","publish","data","getCascadedPosition","fav","currentFloating","x","y","width","height","isOverlapping","pos","wx","wy","attempts","viewW","viewH","focusPanel","id","panel","win","alreadyTop","selectActiveInTree","node","applyRestore","activate","nextMinimized","m","prevState","nextActive","entry","floatBack","favPos","cascaded","hasLeaf","addPanelToLeaf","targetLeafId","findFirstLeafId","applyFloat","rect","anchor","DEFAULT_FLOAT_RECT","cleanRoot","removePanelFromTree","otherWindows","resolveActivePanelId","applyDock","nextFloating","EMPTY_LEAF","leafId","openPanel","component","options","resolvedId","match","p","isNew","isRedirect","shouldFocus","serializable","isSerializable","explicitTarget","restored","dockTo","findLeafIdOf","exists","title","target","activePanelId","dockLeaf","newPanelInfo","nextPanels","share","splitLeafInTree","firstLeaf","closePanel","nextRoot","nextActivePanelId","deriveActivePanelId","registerCloseGuard","guard","unregisterCloseGuard","registerStateProvider","provider","unregisterStateProvider","setPanelDirty","dirty","sameDirtyOptions","updatePanelTitle","sameTitle","setPanelIcon","icon","requestClosePanel","minimizePanel","wasActive","lastFloatingRect","lastLeafId","findLeafForPanel","child","res","restorePanel","wasMinimized","floatPanel","willFloat","dockPanel","setDraggedPanelId","dockPanelToGroup","position","before","willMove","isLoneOccupant","newRoot","dockPanelToWorkspaceEdge","newLeaf","orientation","children","r","movePanelOrder","panelId","targetIndex","insertInLeaf","remaining","index","newPanels","closeLeafGroup","findLeaf","found","leaf","removeLeafFromTree","c","sizes","sum","a","b","s","removed","current","maximizePanel","updateSplitSizes","path","updateInTree","depth","idx","i","updateFloatingPosition","updates","isDropAllowed","to","e","saveLayout","currentPanels","excludedIds","includedPanels","info","dynamicValue","hasDynamicValue","effectiveProps","effectiveSerializable","_icon","saved","gridRoot","minimized","liveActive","isVisibleActiveTarget","payload","loadLayout","layoutJson","parseLayoutPayload","panels","was","titleOf","setActivePanel","setDirection","dir","isOpen","getOpenPanelIds","findPanelId","dedupeKey","customMenuGettersRef","showContextMenuFnRef","getItems","fn","defaults","useInsertionEffect","useRef","useLatestRef","value","ref","jsx","WindowActionsContext","createContext","WindowI18nContext","WindowStoreSyncContext","WindowPredefinedMessagesContext","defaultPredefinedMessages","StyleClassContext","useStyleClasses","useContext","RegistryContext","globalPanelRegistry","useRegistry","WindowManagerProvider","children","client","formatMessage","predefinedMessages","dirProp","modalClass","modalBodyClass","sidePanelClass","sidePanelBodyClass","windowClass","windowBodyClass","zIndexBaseProp","core","useState","c","createWorkspaceCore","registry","panelHost","createPanelHost","actions","effectiveFormatMessage","effectivePredefinedMessages","effectiveDir","effectiveZIndexBase","mergedMessages","useMemo","useEffect","claimDocumentMirror","releaseDocumentMirror","styleClasses","syncContextValue","defaultFormatMessage","PanelHostContext","noopSubscribe","_cb","outsideProvider","useWindowManagerState","selector","syncCtx","read","snap","useSyncExternalStore","useOptionalWindowManagerState","fallback","useWindowManagerActions","ctx","useWindowManagerActionsInternal","useFormatMessage","usePredefinedMessages","useContext","WindowPredefinedMessagesContext","usePanelId","useFormContainer","usePanelContextMenu","items","ctx","WindowActionsContext","panelId","register","itemsRef","useLatestRef","useEffect","WorkspaceClient","_WorkspaceClient","config","PanelRegistry","id","def","key","descriptor","createWorkspaceCore","fn","event","cb","args","a","component","dedupeKey","json","dir","path","sizes","updates","targetLeafId","position","panelId","targetIndex","leafId","options","guard","provider","dirty","title","icon","data","callback","d","createContext","WorkspaceInstanceContext","createContext","useContext","useState","useCallback","useMemo","useRef","jsx","idCounter","generateId","closeHandlers","changesNothing","current","updates","sameDirtyOptions","next","prev","keys","k","sameTitle","initialState","PanelStateContext","createContext","PanelActionsContext","PanelProvider","children","state","setState","useState","defaultModalTitle","usePredefinedMessages","stateRef","useLatestRef","closeListeners","useRef","onInstanceClose","useCallback","id","handler","listeners","notifyClosed","ids","handlers","h","registerCloseHandler","unregisterCloseHandler","openLeftPanel","Component","props","options","currentPanel","instance","s","openRightPanel","openModal","formTitle","modalOptions","close","m","closeAll","leftPanel","rightPanel","modals","closeAllModals","getInstance","updateInstance","target","setDirty","dirty","actions","useMemo","usePanelState","ctx","useContext","usePanelActions","useCallback","useRef","useEffect","useState","useMemo","useEffect","useRef","jsx","jsxs","QuestionIcon","InfoIcon","SuccessIcon","WarningIcon","DangerIcon","TYPE_ICONS","DialogIcon","icon","type","question","Builtin","jsx","jsxs","ConfirmationForm","title","message","alert","alertType","useYesNoTitles","onOK","onCancel","onSettled","icon","requestClose","setTitle","onClose","useFormContainer","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","confirmButtonRef","useRef","settledRef","onSettledRef","useLatestRef","settle","ok","settleRef","useEffect","resolvedTitle","resolvedMessage","cancelLabel","confirmLabel","handleSubmit","e","handleCancel","DialogIcon","ConfirmationForm_default","useEffect","useLayoutEffect","useRef","LAYER_RANK","entries","nextOrder","handleKeyDown","top","entry","higher","pushEscape","layer","onEscape","index","useEscapeLayer","active","onEscapeRef","useLayoutEffect","useState","useContainerRect","anchorRef","rect","setRect","container","measure","r","resizeObserver","Fragment","jsx","jsxs","SidePanelRendererItem","panel","position","defaultWidth","containerRect","close","openModal","updateInstance","setDirty","registerCloseHandler","unregisterCloseHandler","onInstanceClose","usePanelActions","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","dir","useWindowManagerState","s","sidePanelClass","sidePanelBodyClass","useStyleClasses","closeHandlerRef","useRef","id","Component","props","options","dirty","dirtyOptions","panelOptions","icon","setIconState","useState","optionsRef","useLatestRef","baseTitle","formatLabel","handleClose","useCallback","ConfirmationForm_default","canClose","useEffect","handleSetDirty","handleSetTitle","title","handleSetIcon","newIcon","handleOnCloseRequested","handler","handleOnClose","contract","useMemo","displayTitle","useEscapeLayer","width","widthStyle","bodyPadding","bodyPaddingStyle","FormContainerProvider","SidePanelAnchor","children","anchorRef","useContainerRect","SidePanelRenderer","leftPanel","rightPanel","usePanelState","LeftPanelRenderer","RightPanelRenderer","SidePanelRenderer_default","useEffect","useRef","jsx","jsxs","AlertForm","title","message","alertType","icon","okLabel","onSettled","requestClose","setTitle","onClose","useFormContainer","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","okButtonRef","useRef","settledRef","onSettledRef","useLatestRef","settle","settleRef","useEffect","resolvedTitle","resolvedMessage","resolvedOk","e","DialogIcon","AlertForm_default","React","forwardRef","useImperativeHandle","useState","useRef","useEffect","useLayoutEffect","createPortal","isElementRtl","el","closestDirEl","isComputedRtl","enabledItems","menu","moveMenuFocus","key","items","i","next","Fragment","jsx","jsxs","isKeyboardMenuEvent","event","mouse","getCoords","r","resolveLabel","label","fmt","isSeparator","item","isSubMenu","SubMenuPanel","forwardRef","items","getAnchor","autoFocus","onBack","theme","dir","onClose","onMouseEnter","onMouseLeave","ref","useLayoutEffect","el","anchor","PAD","GAP","width","height","toRight","toLeft","fitsRight","fitsLeft","left","top","enabledItems","handleKeyDown","e","backKey","moveMenuFocus","createPortal","i","simple","showChk","isChecked","isDisabled","CLOSED","menuDirection","target","isComputedRtl","ContextMenu","formatMessageProvider","onShow","onHide","onOpenChange","className","style","menuState","setMenuState","useState","submenuIndex","setSubmenuIndex","submenuFocus","setSubmenuFocus","menuRef","useRef","openerRef","restoreFocusRef","submenuPanelRef","itemRefs","timers","close","React","active","useImperativeHandle","x","y","initialFocus","coords","opener","useEffect","dismiss","useEscapeLayer","getSubmenuAnchor","itemEl","menuEl","mr","backToParentItem","parent","cancelOpenTimer","cancelCloseTimer","handleItemMouseEnter","index","openSubmenuFromKeyboard","handleMenuKeyDown","openKey","handleItemMouseLeave","sub","DefaultContextMenuAdapter","ContextMenuContext","ContextMenuProvider","adapter","children","componentProps","isOpen","setIsOpen","show","opts","useShowContextMenu","ctx","jsx","definePanels","panels","createWorkspace","config","messages","rest","WorkspaceClient","useWorkspace","ws","useContext","WorkspaceInstanceContext","usePanel","c","useFormContainer","id","state","useOptionalWindowManagerState","s","isActive","containerType","cRef","useRef","useLayoutEffect","mutators","useMemo","options","dirty","title","icon","usePanelEvents","events","ref","useEffect","offs","w","h","t","off","useBeforeClose","guard","useSaveState","getState","useModals","modals","usePanelState","a","usePanelActions","usePredefinedMessages","message","alert","alertType","yesNo","size","resolve","ConfirmationForm_default","okLabel","AlertForm_default","useSidePanels","leftPanel","rightPanel","RddSidePanels","side","defaultWidth","LeftPanelRenderer","RightPanelRenderer","SidePanelRenderer_default","RddContextMenu","forwardRef","children","adapter","menuProps","ContextMenuProvider","ContextMenu","useContext","useState","createContext","useContext","useMemo","useState","jsx","ToolbarContext","ToolbarProvider","children","radioGroups","setRadioGroups","modifiers","setModifiers","value","group","id","prev","active","useToolbar","ctx","createContext","useCallback","useContext","useLayoutEffect","useMemo","useRef","useSyncExternalStore","jsx","createPanelContributionStore","contributions","listeners","notify","l","panelId","contribution","listener","PanelContributionContext","createContext","PanelContributionProvider","children","store","useMemo","usePanelContribution","usePanelId","useContext","cleanupRef","useRef","useLayoutEffect","useActivePanelContribution","activePanelId","useWindowManagerState","s","subscribe","useCallback","onChange","getSnapshot","useSyncExternalStore","sidebarSectionToTab","section","fallbackIcon","useMergedToolbarItems","staticItems","active","useMergedSidebarTabs","staticTabs","jsx","DockableDesktopProvider","contextMenuAdapter","DefaultContextMenuAdapter","workspace","messages","children","props","existingCtxMenu","useContext","ContextMenuContext","ws","useState","WorkspaceClient","inner","WorkspaceInstanceContext","ToolbarProvider","WindowManagerProvider","PanelContributionProvider","PanelProvider","ContextMenuProvider","React","useState","useRef","useEffect","useCallback","useContext","useSyncExternalStore","subscribeNever","isClient","isServer","useIsClient","useSyncExternalStore","readScheme","subscribe","onChange","observer","serverScheme","useColorScheme","React","useRef","useState","useEffect","useLayoutEffect","createPortal","jsx","jsxs","isPanelShown","s","panelId","state","isShownInGrid","hiddenContainerId","park","el","hiddenContainer","renderPanelContent","id","panel","registry","messages","formatMessage","componentKey","registryEntry","formatLabel","Component","PreservedDOMWrapper","panelHost","usePanelHost","hostRef","useRef","isActive","useWindowManagerState","isActiveRef","useLayoutEffect","useEffect","host","cachedEl","restorePanelDom","resizeObserver","entries","entry","width","height","lifecycle","h","PreviewDOMWrapper","useRegistry","useFormatMessage","usePredefinedMessages","regEntry","disableLivePreview","lastSize","origW","origH","scale","displayW","displayH","rawTitle","title","initialChar","FormContainerProviderWrapper","children","requestClosePanel","setPanelDirty","registerCloseGuard","unregisterCloseGuard","registerStateProvider","unregisterStateProvider","updatePanelTitle","setPanelIcon","minimizePanel","useWindowManagerActions","isMin","m","prevMinRef","prevActiveRef","wasActive","rawPanelState","derivedContainerType","prevContainerTypeRef","prevType","initialContainerType","useState","contract","React","options","dirty","handler","getState","icon","reg","FormContainerProvider","PanelMount","dir","keepAlive","shown","typeClass","createPortal","useSyncExternalStore","jsx","DragGhost","dragPos","children","pos","React","startPointerDrag","config","element","pointerId","startClientX","startClientY","captureStart","onMove","onEnd","activeClasses","el","classes","start","handleMove","e","finish","cancelled","handleEnd","doc","handleLostCapture","view","handleBlur","computeResizedRect","dir","dx","dy","constraints","minW","minH","maxW","maxH","minX","minY","x","y","w","h","maxDx","minDx","clampedDx","maxDy","minDy","clampedDy","useState","useRef","useEffect","useCallback","findLeaf","node","leafId","child","found","tabDropSide","tabEl","clientX","rect","isComputedRtl","isMenuKey","keyboardMenuEvents","menuEventAt","el","r","event","initialFocusFor","refocusAfterTabClose","id","strip","workspaceEl","esc","active","domIdPart","raw","LONG_PRESS_MS","CANCEL_MOVE_PX","jsx","jsxs","DefaultGridIcon","ContextMenuIcons","Fragment","jsx","jsxs","LeafGroup","leaf","onTabRightClick","activeDropZone","onHoverDropZone","onTabDragStart","hoveredTab","onTabHover","defaultPanelIcon","onRequestClosePanel","emptyWorkspace","renderTabContent","state","useWindowManagerState","registry","useRegistry","openPanel","closeLeafGroup","setActivePanel","isDropAllowed","useWindowManagerActionsInternal","formatMessage","useFormatMessage","messages","usePredefinedMessages","windowClass","windowBodyClass","useStyleClasses","tabContainerRef","useRef","tabScroll","setTabScroll","useState","updateTabScroll","useCallback","el","travelled","max","next","isComputedRtl","prev","useEffect","ro","scrollTabs","toward","forward","startSide","endSide","scrollGlyph","scrollLabel","selectTab","id","handleTabKeyDown","e","closable","isMenuKey","menuEventAt","ids","p","i","step","workspaceEl","refocusAfterTabClose","tabPanelId","domIdPart","tabIdFor","panelId","formatLabel","idx","panel","isSelected","isGloballyActive","options","isHovered","isLast","isHoveredEmpty","sideClass","tabFocusClass","tabDropSide","icon","DefaultGridIcon","title","PreservedDOMWrapper","isActive","pos","dragged","applied","offer","pct","rem","jsx","jsxs","WorkspaceGrid","node","path","onTabRightClick","activeDropZone","onHoverDropZone","onTabDragStart","hoveredTab","onTabHover","defaultPanelIcon","onRequestClosePanel","emptyWorkspace","renderTabContent","updateSplitSizes","useWindowManagerActions","LeafGroup","isRow","handleResizerPointerDown","idx","e","resizerEl","parentEl","parentSize","rtl","isComputedRtl","startPointerDrag","dx","dy","startSizes","deltaPercentage","newSizes","child","size","React","Fragment","jsx","jsxs","appliedSide","side","rtl","WorkspaceZones","state","activeEdgeDrop","activeCornerAnchor","setActiveEdgeDrop","setActiveCornerAnchor","isDropAllowed","dragged","edge","cornerOffered","anchor","corner","pct","Fragment","jsx","jsxs","FloatingWindows","state","registry","windowClass","windowBodyClass","defaultPanelIcon","messages","formatMessage","setActivePanel","focusPanel","maximizePanel","minimizePanel","getPanelContextMenuItems","showContextMenu","handleRequestClose","startDrag","startResize","w","panel","isMaximized","isDragged","isFocused","options","w_","h_","stack","fw","idx","stackOffset","i","sh","isTop","e","DefaultGridIcon","formatLabel","customItems","initialFocusFor","PreservedDOMWrapper","createPortal","jsx","jsxs","Taskbar","state","registry","taskbarVisibility","taskbarExpanded","expandTaskbar","leaveTaskbar","scrollTaskbar","taskbarRef","tooltipRef","defaultPanelIcon","messages","formatMessage","lastTaskbarPointerTypeRef","hoveredMinimized","setHoveredMinimized","minimizedTooltipTimeoutRef","isContextMenuOpen","handleMinimizedRightClick","handleRequestClose","restorePanel","formatLabel","m","regEntry","icon","DefaultGridIcon","e","isMenuKey","menuEventAt","el","startX","startY","pointerId","cancelled","cancel","timer","onPreMove","onShortTap","rect","me","CANCEL_MOVE_PX","onEnd","LONG_PRESS_MS","createPortal","tooltipId","PreviewDOMWrapper","useState","useRef","createDragPos","pos","listeners","v","l","cb","sameDropZone","a","b","sameTab","useDragTargets","setDraggedPanelId","isRtl","canInsertInto","activeDropZone","setActiveDropZone","useState","activeDropZoneRef","useRef","dragPos","setDragPos","activeEdgeDrop","setActiveEdgeDropState","activeEdgeDropRef","setActiveEdgeDrop","val","activeCornerAnchor","setActiveCornerAnchorState","activeCornerAnchorRef","setActiveCornerAnchor","hoveredTab","setHoveredTab","hoveredTabRef","leafId","panelId","index","side","position","x","y","elements","foundDropZone","foundEdge","foundTab","el","prev","tabIdx","tabDropSide","createTabDrag","deps","state","handleTabRightClick","activeDropZoneRef","hoveredTabRef","activeEdgeDropRef","activeCornerAnchorRef","setActiveCornerAnchor","clearDragState","flipRtl","setDragPos","updateHoverFromPoint","dockPanelToWorkspaceEdge","movePanelOrder","dockPanelToGroup","floatPanel","setDraggedPanelId","isDropAllowed","executeDrop","id","me","dropZone","targetTab","edgeDrop","cornerAnchor","side","targetIndex","targetLeaf","findLeaf","currentIdx","position","e","el","startX","startY","pointerId","cancelled","cancel","timer","onPreMove","CANCEL_MOVE_PX","dragStarted","onMove","onEnd","onCancel","LONG_PRESS_MS","dx","dy","createWorkspaceMenus","deps","state","registry","messages","formatMessage","handleRequestClose","setHoveredMinimized","floatPanel","minimizePanel","restorePanel","maximizePanel","getPanelContextMenuItems","showContextMenu","isDropAllowed","id","e","panel","options","items","formatLabel","ContextMenuIcons","custom","finalItems","initialFocusFor","canMaximize","useState","useEffect","useWorkspaceSize","workspaceRef","workspaceSize","setWorkspaceSize","el","heightWarnShown","tallWarnShown","observer","entries","rect","culprit","cursor","tag","id","cls","who","createFloatingWindowDrag","deps","state","workspaceSize","activeDropZoneRef","hoveredTabRef","activeEdgeDropRef","activeCornerAnchorRef","setActiveCornerAnchor","clearDragState","flipRtl","updateHoverFromPoint","focusPanel","updateFloatingPosition","dockPanelToWorkspaceEdge","movePanelOrder","dockPanelToGroup","setDraggedPanelId","isDropAllowed","id","e","floatingWin","w","el","windowEl","startX","startY","startPosX","startPosY","executeFWDrop","dropZone","targetTab","edgeDrop","cornerAnchor","side","targetIndex","position","pointerId","cancelled","cancel","timer","onPreMove","me","CANCEL_MOVE_PX","onMove","dx","dy","onEnd","onCancel","LONG_PRESS_MS","dragStarted","dir","startRect","viewW","viewH","parsedX","parsedY","parsedW","parsedH","isRightSnapped","isBottomSnapped","startPointerDrag","start","resized","computeResizedRect","newX","newY","newW","newH","jsx","jsxs","WindowManager","skin","defaultPanelIcon","taskbarVisibility","animations","emptyWorkspace","renderTabContent","contextMenuAdapter","DefaultContextMenuAdapter","state","useWindowManagerState","panelHost","usePanelHost","registry","useRegistry","restorePanel","minimizePanel","requestClosePanel","maximizePanel","updateFloatingPosition","focusPanel","floatPanel","setDraggedPanelId","dockPanelToGroup","movePanelOrder","dockPanelToWorkspaceEdge","setActivePanel","getPanelContextMenuItems","showContextMenu","registerContextMenuFn","isDropAllowed","useWindowManagerActionsInternal","openModal","usePanelActions","formatMessage","useFormatMessage","messages","usePredefinedMessages","handleRequestClose","React","id","panel","customOpts","resolve","opts","baseTitle","formatLabel","ConfirmationForm_default","windowClass","windowBodyClass","useStyleClasses","ctxMenu","useContext","ContextMenuContext","contextMenuRef","useRef","useEffect","taskbarRef","tooltipRef","taskbarExpanded","setTaskbarExpanded","useState","taskbarCollapseTimerRef","taskbarHoveredRef","prevMinimizedLengthRef","hoveredMinimized","setHoveredMinimized","minimizedTooltipTimeoutRef","lastTaskbarPointerTypeRef","internalContextMenuOpen","setInternalContextMenuOpen","isContextMenuOpen","m","handler","e","storeSync","WindowStoreSyncContext","canInsertInto","leafId","dragged","targets","useDragTargets","activeDropZone","setActiveDropZone","dragPos","activeEdgeDrop","setActiveEdgeDrop","activeCornerAnchor","setActiveCornerAnchor","hoveredTab","setHoveredTab","handleTabHover","handleHoverDropZone","handleTabRightClick","handleMinimizedRightClick","createWorkspaceMenus","handleTabDragStart","createTabDrag","keys","cachedId","el","forgetPanelDom","handleWindowBlur","workspaceRef","workspaceSize","useWorkspaceSize","viewW","viewH","w","winW","winH","winX","winY","newWidth","newHeight","newX","newY","changed","maxX","maxY","handlePointerDownGlobal","target","windowEl","winId","panelEl","panelId","startDrag","startResize","createFloatingWindowDrag","scrollTaskbar","direction","amount","scheduleCollapseTaskbar","useCallback","delayMs","expandTaskbar","leaveTaskbar","currentColorScheme","useColorScheme","isClient","useIsClient","claimDocumentMirror","releaseDocumentMirror","WorkspaceZones","WorkspaceGrid","FloatingWindows","Taskbar","PanelMount","DragGhost","WindowManager_default","useCallback","useRef","useState","useMemo","Fragment","jsx","jsxs","ModalRenderer","modal","index","close","openModal","updateInstance","setDirty","onInstanceClose","usePanelActions","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","dir","useWindowManagerState","s","modalClass","modalBodyClass","useStyleClasses","closeHandlerRef","useRef","id","Component","props","options","dirty","dirtyOptions","modalOptions","icon","setIconState","useState","optionsRef","useLatestRef","baseTitle","formatLabel","handleClose","useCallback","ConfirmationForm_default","handleSetDirty","handleSetTitle","title","handleSetIcon","newIcon","handleOnCloseRequested","handler","handleOnClose","contract","useMemo","displayTitle","sizeClass","showCloseButton","bodyPadding","bodyPaddingStyle","useEscapeLayer","modalZIndex","FormContainerProvider","ModalStackRenderer","modals","usePanelState","ModalStackRenderer_default","React","useState","useEffect","useRef","useCallback","useImperativeHandle","useContext","useMemo","createContext","forwardRef","memo","jsx","jsxs","isRailTab","entry","isRailCustom","toRailArray","value","SidebarContext","createContext","SidebarTabContext","SidebarTabProvider","tabId","onClose","onOpen","setActiveTabId","children","useMemo","otherId","renderRailEntry","index","activeTabId","onTabClick","React","isActive","SidebarTabStrip","memo","tabs","headerEntries","footerEntries","isVisible","position","i","tab","SidebarResizeHandle","currentWidth","minWidth","maxWidth","onWidthChange","onResizeStart","onResizeEnd","e","el","activeClasses","onPhysicalRight","isComputedRtl","startPointerDrag","dx","_dy","startWidth","newW","Sidebar","forwardRef","headerAction","footerAction","defaultWidth","controlledActiveTabId","onActiveTabChange","visible","onVisibilityChange","stripVisible","onStripVisibilityChange","showCloseButton","hideDefaultHeader","renderHeader","isSecondary","ref","workspaceDir","useOptionalWindowManagerState","s","isControlled","formatMessage","useFormatMessage","closeLabel","formatLabel","usePredefinedMessages","width","setWidthState","useState","setWidth","useCallback","px","isResizing","setIsResizing","internalActiveTabId","setInternalActiveTabId","normalizedHeaderEntries","normalizedFooterEntries","headerTabs","footerTabs","allTabs","mountedTabIds","setMountedTabIds","effectiveMountedTabIds","result","activeTabIdRef","useRef","useEffect","widthRef","id","prev","next","changed","t","useImperativeHandle","handleTabClick","handleClose","hasHeaderOverride","closeButtonWarnedRef","sidebarContextValue","isSidebarVisible","isStripVisible","isDrawerOpen","drawer","isCurrent","resizeHandle","SecondarySidebar","props","primary","useContext","opposite","useSidebar","ctx","useSidebarTab","forwardRef","useImperativeHandle","useState","useRef","useEffect","useLayoutEffect","createPortal","Fragment","jsx","jsxs","flyoutPosition","rect","position","isRtl","gap","ToolbarGroupButton","item","toolbar","isOpen","setIsOpen","useState","btnRect","setBtnRect","btnRtl","setBtnRtl","btnRef","useRef","flyoutRef","isControlled","activeId","activeSubItem","e","isActive","displayIcon","displayLabel","handleClick","isComputedRtl","prev","useLayoutEffect","el","r","PAD","useEffect","onMouseDown","target","closeFlyout","items","enabledItems","handleFlyoutKeyDown","moveMenuFocus","useEscapeLayer","createPortal","entry","i","isSubActive","renderItem","index","controlled","Toolbar","forwardRef","visible","onVisibilityChange","className","style","ref","useToolbar","isVertical","useImperativeHandle","collapsed","collapseStyle","stripRef","strip","useCallback","useEffect","useLayoutEffect","useRef","useState","createPortal","jsx","jsxs","ToastEmitter","fn","message","opts","id","patch","e","emitter","toast","msg","promise","messages","result","err","InfoIcon","SuccessIcon","WarningIcon","ErrorIcon","CloseIcon","DEFAULT_ICONS","ToastItem","options","exiting","isLeft","showProgress","pauseOnHover","animation","closeLabel","onDismiss","onExited","divRef","useRef","bodyRef","timerRef","remainRef","startRef","paused","setPaused","useState","startEntry","entryClass","setEntryClass","useLayoutEffect","el","body","applyHeight","observer","useEffect","raf","scheduleDismiss","useCallback","ms","handle","fallback","handleMouseEnter","handleMouseLeave","cls","icon","resolveOpts","raw","defaultDuration","defaultClosable","ToastContainer","position","maxVisible","newestOnTop","progressBar","width","adapter","toasts","setToasts","formatMessage","useFormatMessage","usePredefinedMessages","regionLabel","formatLabel","workspaceDir","useOptionalWindowManagerState","s","mounted","useIsClient","queueRef","toastsRef","useLatestRef","handleDismiss","prev","t","handleExited","promoted","filtered","newEntry","rawEntry","q","merged","AdapterContainer","createPortal","dirMod","useState","useRef","useCallback","useMemo","createContext","PanelToolbarContext","PanelManagerContext","PanelOverlayContext","stretchesInline","s","stretchesBlock","addAxis","axis","releaseAxis","bucketsFor","anchor","stretch","withInlineHalf","a","half","withBlockHalf","ANCHORS","React","useState","useContext","useRef","useLayoutEffect","useInsertionEffect","useCallback","useEffect","flipZoneHorizontal","zone","getHoveredZone","container","clientX","clientY","rect","x","y","MIN_W","MIN_H","DOCK_INSET","DOCK_GAP","SNAP_IN","SNAP_OUT","jsx","jsxs","PanelFloatingWindow","props","ctx","useContext","PanelOverlayContext","FloatingWindowBody","id","title","icon","defaultAnchor","defaultWidth","defaultHeight","defaultStretch","stretchProp","onPlacementChange","stretchable","children","onClose","isRtl","useOptionalWindowManagerState","s","formatMessage","useFormatMessage","messages","usePredefinedMessages","mode","setMode","useState","currentAnchor","setCurrentAnchor","internalStretch","setInternalStretch","isStretchControlled","stretch","freePos","setFreePos","size","setSize","windowRef","useRef","modeRef","useLatestRef","freePosRef","sizeRef","stretchRef","currentAnchorRef","onPlacementChangeRef","snapArmed","setSnapArmed","snapArmedRef","stackOffsetRef","applyPlacement","useCallback","anchor","next","dragState","useLayoutEffect","blockStretchWarnedRef","useEffect","stretchesBlock","half","neighbours","bucket","other","zOrder","isActive","getContainerBounds","container","dockedBand","logicalStart","logicalEnd","DOCK_INSET","handleWindowPointerDown","handleHeaderPointerDown","e","startX","startY","el","elRect","cRect","handleResizePointerDown","dir","er","cr","measured","startRect","stretchesInline","dragsInline","dragsBlock","released","armed","releaseIfNeeded","st","releasingInline","releasingBlock","nextAnchor","releaseAxis","pinsPhysicalLeft","withInlineHalf","withBlockHalf","startPointerDrag","dx","dy","start","cw","ch","band","newX","newY","newW","newH","computeResizedRect","MIN_W","MIN_H","fullInline","fullBlock","nextArmed","SNAP_IN","SNAP_OUT","prev","addAxis","handleWindowPointerMove","ds","r","rawZone","getHoveredZone","flipZoneHorizontal","handleWindowPointerUp","zone","handleWindowPointerCancel","windowStyle","dockedStackOffset","buckets","bucketsFor","stackOffset","registered","stack","idx","offset","i","DOCK_GAP","useInsertionEffect","handleDirs","React","freeBlock","freeInline","inlineStretched","blockStretched","dirs","CloseIcon","formatLabel","Fragment","jsx","jsxs","PanelOverlayRoot","children","className","style","toolbarSizes","setToolbarSizes","useState","zOrders","setZOrders","stacks","setStacks","dockedSizes","setDockedSizes","draggingId","setDraggingId","hoveredZone","setHoveredZone","topId","setTopId","managedWindows","setManagedWindows","zCounterRef","useRef","containerRef","registerToolbar","useCallback","pos","size","prev","next","focusWindow","id","z","dockWindow","anchor","stretch","buckets","bucketsFor","x","bucket","ANCHORS","a","i","undockWindow","reportDockedSize","openManaged","config","closeManaged","closeAllManaged","managedWindowIds","useMemo","toolbarCtxValue","managerCtxValue","coreCtxValue","PanelToolbarContext","PanelManagerContext","PanelOverlayContext","DropZoneOverlay","cfg","PanelFloatingWindow","zone","useContext","useRef","useLayoutEffect","jsx","PanelToolbar","position","variant","buttonVariant","buttonSize","style","className","children","ctx","useContext","PanelToolbarContext","ref","useRef","cleanupRef","useLayoutEffect","el","measure","size","ro","posStyle","sideStyle","sizeStyle","ToolbarButton","icon","onClick","disabled","title","ToolbarToggle","active","onToggle","ToolbarSeparator","ToolbarSpacer","ToolbarItem","ToolbarCenter","React","useState","useRef","useMemo","useEffect","createPortal","jsx","jsxs","ToolbarSearchInput","placeholder","onSearch","onSelect","formatMessage","useFormatMessage","messages","usePredefinedMessages","searchLabel","formatLabel","closeSearchLabel","placeholderText","expanded","setExpanded","useState","query","setQuery","results","setResults","dropdownPos","setDropdownPos","containerRef","useRef","inputRef","abortRef","debounceRef","useEffect","openSearch","closeSearch","handleQueryChange","e","q","ctrl","res","el","r","dropW","left","handleSelect","result","handleBlur","handleKeyDown","grouped","useMemo","map","g","SearchIcon","createPortal","group","items","React","item","useState","useContext","useCallback","useMemo","EMPTY_IDS","usePanelFloatingWindowManager","ctx","useContext","PanelManagerContext","ids","useMemo","id","config"]}
|
|
1
|
+
{"version":3,"sources":["../src/api/index.tsx","../src/components/PanelRegistry.ts","../src/components/WindowManagerContext.tsx","../src/components/FormContainerContext.ts","../src/components/workspace/panelHost.ts","../src/components/domPreservation.ts","../src/components/domMove.ts","../src/utils/documentMirror.ts","../src/components/predefinedMessages.ts","../src/core/messages.ts","../src/components/serializable.ts","../src/components/sameUpdate.ts","../src/core/eventBus.ts","../src/core/layoutTree.ts","../src/core/panelOptions.ts","../src/core/serialize.ts","../src/core/workspaceCore.ts","../src/utils/useLatestRef.ts","../src/WorkspaceClient.ts","../src/components/WorkspaceInstanceContext.ts","../src/components/PanelProviderContext.tsx","../src/components/SidePanelRenderer.tsx","../src/forms/ConfirmationForm.tsx","../src/forms/dialogIcons.tsx","../src/utils/escapeStack.ts","../src/hooks/useContainerRect.ts","../src/forms/AlertForm.tsx","../src/components/ContextMenu.tsx","../src/utils/rtl.ts","../src/utils/menuKeyboard.ts","../src/components/DockableDesktopProvider.tsx","../src/components/ToolbarContext.tsx","../src/components/PanelContributionContext.tsx","../src/components/WindowManager.tsx","../src/utils/useIsClient.ts","../src/hooks/useColorScheme.ts","../src/components/workspace/panelMount.tsx","../src/components/workspace/DragGhost.tsx","../src/components/workspace/WorkspaceGrid.tsx","../src/components/dragResize.ts","../src/components/workspace/LeafGroup.tsx","../src/components/workspace/helpers.ts","../src/components/workspace/icons.tsx","../src/components/workspace/WorkspaceZones.tsx","../src/components/workspace/FloatingWindows.tsx","../src/components/workspace/Taskbar.tsx","../src/components/workspace/useDragTargets.ts","../src/components/workspace/tabDrag.ts","../src/components/workspace/workspaceMenus.ts","../src/components/workspace/useWorkspaceSize.ts","../src/components/workspace/floatingWindowDrag.ts","../src/components/ModalStackRenderer.tsx","../src/components/Sidebar.tsx","../src/components/Toolbar.tsx","../src/components/Toast.tsx","../src/components/panelOverlay/PanelOverlayRoot.tsx","../src/components/panelOverlay/context.ts","../src/core/stretch.ts","../src/core/panelOverlayGeometry.ts","../src/core/widgetPlacement.ts","../src/components/panelOverlay/FloatingWidget.tsx","../src/components/anchorGeometry.ts","../src/components/panelOverlay/useWidgetHosting.ts","../src/components/panelOverlay/widgetContext.ts","../src/components/panelOverlay/PanelToolbar.tsx","../src/components/panelOverlay/ToolbarSearch.tsx","../src/components/panelOverlay/useFloatingWidgets.tsx"],"sourcesContent":["/**\n * The 7.0 public API layer: `createWorkspace()`, the hooks a panel or an app component uses, and\n * the two components that replace several 6.x ones (`RddSidePanels`, `RddContextMenu`).\n *\n * Everything here is built on the library's internal modules; `src/index.ts` exports it together\n * with the internal components under their 7.0 names.\n */\nimport React, { forwardRef, useContext, useEffect, useLayoutEffect, useMemo, useRef } from 'react';\nimport { WorkspaceClient, type PanelDefinition, type WorkspaceClientConfig } from '../WorkspaceClient';\nimport type { OpenPanelOptions } from '../types';\nimport { WorkspaceInstanceContext } from '../components/WorkspaceInstanceContext';\nimport { useOptionalWindowManagerState, usePredefinedMessages, type MessageDescriptor, type PanelInfo } from '../components/WindowManagerContext';\nimport { useFormContainer, type CloseOptions, type ContainerType, type FormContainerContract } from '../components/FormContainerContext';\nimport type { DirtyStateOptions } from '../components/dirtyOptions';\nimport { usePanelActions, usePanelState, type OverlayInstance, type OverlayId, type ModalOptions, type SidePanelOptions } from '../components/PanelProviderContext';\nexport type { OverlayInstance, OverlayId };\nimport SidePanelRenderer, { LeftPanelRenderer, RightPanelRenderer } from '../components/SidePanelRenderer';\nimport ConfirmationForm, { type RddConfirmProps } from '../forms/ConfirmationForm';\nimport AlertForm, { type RddAlertProps } from '../forms/AlertForm';\nimport { ContextMenu, ContextMenuProvider, type ContextMenuAdapter, type ContextMenuHandle, type ContextMenuProps } from '../components/ContextMenu';\n\n// ─── Workspace ──────────────────────────────────────────────────────────────────\n\n/** Configuration for `createWorkspace()`. */\nexport interface WorkspaceConfig extends Omit<WorkspaceClientConfig, 'predefinedMessages'> {\n /** Overrides any subset of the built-in message table. */\n messages?: Record<string, MessageDescriptor>;\n}\n\n/**\n * A workspace: the layout, every action on it, the panel registry and the event bus. It is live\n * from the moment it is created — calls made before any `<DockableDesktopProvider>` mounts apply\n * immediately.\n */\n// An interface rather than an alias, so the API reference lists the members under this name.\nexport interface Workspace<TEvents extends object = Record<string, unknown>> extends WorkspaceClient<TEvents> {}\n\n/** The type-only mark {@link definePanels} puts on a map. No such value exists at runtime. */\ndeclare const panelsBrand: unique symbol;\n\n/** A panel map marked by {@link definePanels}, so `createWorkspace` types `openPanel` from it (7.10.0). */\nexport type PanelMap<TPanels extends Record<string, PanelDefinition> = Record<string, PanelDefinition>> = TPanels & { readonly [panelsBrand]: true };\n\n/** The props `openPanel` passes to a registered panel: its component's props, without `panelId`. */\nexport type PanelPropsOf<TDefinition> = TDefinition extends { component: React.ComponentType<infer P> } ? Omit<P, 'panelId'> : never;\n\n/**\n * Marks a panel map for typing (7.10.0). Returns it unchanged; a workspace created from it gets a\n * typed `openPanel`: only registered names, and `props` checked against that panel's component.\n *\n * @example\n * ```ts\n * const panels = definePanels({ map: { component: MapPanel }, chart: { component: ChartPanel } });\n * const workspace = createWorkspace({ panels });\n * workspace.openPanel('c1', 'chart', { props: { series: 3 } }); // checked against ChartPanel's props\n * ```\n */\nexport function definePanels<const TPanels extends Record<string, PanelDefinition>>(panels: TPanels): PanelMap<TPanels> {\n return panels as PanelMap<TPanels>;\n}\n\n/**\n * A workspace created from {@link definePanels}: the same object, with `openPanel` typed from the\n * registry. Pass it anywhere a {@link Workspace} goes. `useWorkspace()` stays untyped; keep this\n * one for typed calls.\n */\nexport interface TypedWorkspace<TPanels extends Record<string, PanelDefinition>, TEvents extends object = Record<string, unknown>> extends Workspace<TEvents> {\n /** `openPanel`, typed: a registered name, and that panel's props. */\n openPanel<K extends keyof TPanels & string>(id: string, component: K, options?: OpenPanelOptions<PanelPropsOf<TPanels[K]>>): void;\n}\n\n/**\n * Creates a workspace from a map marked by {@link definePanels} (7.10.0): `openPanel` takes only\n * the registered names, with `props` checked against each panel's component. To name the events\n * as well, pass both type arguments: `createWorkspace<typeof panels, AppEvents>({ panels })`.\n */\nexport function createWorkspace<TPanels extends Record<string, PanelDefinition>, TEvents extends object = Record<string, unknown>>(config: WorkspaceConfig & { panels: PanelMap<TPanels> }): TypedWorkspace<TPanels, TEvents>;\n/**\n * Creates a workspace. Pass it to `<DockableDesktopProvider workspace={…}>`.\n *\n * @example\n * ```ts\n * interface AppEvents { 'layer:select': { layerId: string } }\n * export const workspace = createWorkspace<AppEvents>({\n * panels: { map: { component: MapPanel } },\n * initialState: localStorage.getItem('layout'),\n * });\n * ```\n */\nexport function createWorkspace<TEvents extends object = Record<string, unknown>>(config?: WorkspaceConfig): Workspace<TEvents>;\nexport function createWorkspace(config: WorkspaceConfig = {}): Workspace {\n const { messages, ...rest } = config;\n return new WorkspaceClient({ ...rest, predefinedMessages: messages });\n}\n\n/**\n * The workspace of the nearest `<DockableDesktopProvider>`. A stable object: it never changes, so\n * a component that only calls actions never re-renders because of it.\n */\nexport function useWorkspace<TEvents extends object = Record<string, unknown>>(): Workspace<TEvents> {\n const ws = useContext(WorkspaceInstanceContext);\n if (!ws) throw new Error('useWorkspace must be used within <DockableDesktopProvider>');\n return ws as Workspace<TEvents>;\n}\n\n// ─── Panel side ─────────────────────────────────────────────────────────────────\n\n/** The state of a workspace panel: where it is. */\nexport type PanelState = PanelInfo['state'];\n\n/**\n * What a panel component knows about, and can do to, its own container. See {@link usePanel}.\n *\n * **Identity.** `id` and the five functions (`close`, `minimize`, `setDirty`, `setTitle`,\n * `setIcon`) never change identity for the panel's lifetime. The handle object itself changes\n * when `containerType`, `isActive`, `isMinimized` or `isFloating` does. So don't list the handle\n * in a dependency array: depend on the function you call, or on the values you write.\n */\nexport interface PanelHandle {\n /** This panel's instance id. */\n id: string;\n /** Where it is rendered. Updates live (a docked panel that is floated re-renders as `'floating-window'`). */\n containerType: ContainerType;\n /** A workspace panel that is the globally active one. Always false in a modal or drawer. */\n isActive: boolean;\n /** A workspace panel that is minimized to the taskbar. */\n isMinimized: boolean;\n /** A workspace panel shown as a floating window. */\n isFloating: boolean;\n /** Asks the container to close, honouring close guards and the dirty flag. */\n close: (options?: CloseOptions) => void;\n /** Minimizes a workspace panel. No effect in a modal or drawer. */\n minimize: () => void;\n /** Marks the panel as having unsaved changes. */\n setDirty: (dirty: boolean, options?: DirtyStateOptions) => void;\n /** Changes the title shown on the tab, window or modal. */\n setTitle: (title: string | MessageDescriptor | (() => string)) => void;\n /**\n * Changes the icon on the panel's tab, floating title bar and taskbar button, or in a modal's or\n * drawer's header. In a workspace panel, `null` goes back to the registration's\n * `defaultOptions.icon`. The icon is not saved by `saveLayout()`.\n */\n setIcon: (icon: React.ReactNode) => void;\n}\n\n/**\n * The panel's own container: its id, where it is, and what it can do. Works in docked panels,\n * floating windows, modals and side drawers.\n *\n * The functions on the handle are stable; the handle object is not (see {@link PanelHandle}).\n * To keep the tab title in step with a document:\n *\n * ```tsx\n * const { setTitle, setDirty } = usePanel();\n * useEffect(() => { setTitle(doc.title); setDirty(doc.dirty); }, [setTitle, setDirty, doc.title, doc.dirty]);\n * ```\n */\nexport function usePanel(): PanelHandle {\n const c = useFormContainer();\n const id = c.instanceId;\n // Select primitives only: a selector returning the whole panel record would give a new handle\n // on every write to the panel (title, dirty, props), including the panel's own writes.\n const state = useOptionalWindowManagerState(s => s.panels[id]?.state, undefined);\n const isActive = useOptionalWindowManagerState(s => s.activePanelId === id, false);\n const containerType: ContainerType = state\n ? (state === 'floating' ? 'floating-window' : 'dockable-panel')\n : (c.containerType ?? 'standalone');\n // A modal's or drawer's container object changes when its title or dirty flag does, so the\n // mutators read it through a ref and never change identity themselves.\n const cRef = useRef(c);\n useLayoutEffect(() => { cRef.current = c; });\n const mutators = useMemo(() => ({\n close: (options?: CloseOptions) => cRef.current.requestClose(options),\n minimize: () => cRef.current.requestMinimize?.(),\n setDirty: (dirty: boolean, options?: DirtyStateOptions) => cRef.current.setDirty(dirty, options),\n setTitle: (title: string | MessageDescriptor | (() => string)) => cRef.current.setTitle(title as Parameters<FormContainerContract['setTitle']>[0]),\n setIcon: (icon: React.ReactNode) => cRef.current.setIcon?.(icon),\n // New functions when the panel changes, so an effect that depends on them re-runs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [id]);\n return useMemo<PanelHandle>(() => ({\n id,\n containerType,\n isActive: !!state && isActive,\n isMinimized: state === 'minimized',\n isFloating: state === 'floating',\n ...mutators,\n }), [mutators, id, containerType, state, isActive]);\n}\n\n/** Lifecycle callbacks for {@link usePanelEvents}. Each is called at the moment it describes. */\nexport interface PanelEvents {\n onActivate?: () => void;\n onDeactivate?: () => void;\n onMinimize?: () => void;\n onRestore?: () => void;\n onClose?: () => void;\n onResize?: (width: number, height: number) => void;\n onContainerTypeChange?: (type: ContainerType) => void;\n}\n\n/**\n * Subscribes to the panel's lifecycle. Call it at the top level of the panel component; it always\n * calls the latest callbacks passed in and cleans up on unmount — no dependency array.\n */\nexport function usePanelEvents(events: PanelEvents): void {\n const c = useFormContainer();\n const ref = useRef(events);\n useLayoutEffect(() => { ref.current = events; });\n useEffect(() => {\n const offs = [\n c.onActivate?.(() => ref.current.onActivate?.()),\n c.onDeactivate?.(() => ref.current.onDeactivate?.()),\n c.onMinimize?.(() => ref.current.onMinimize?.()),\n c.onRestore?.(() => ref.current.onRestore?.()),\n c.onClose?.(() => ref.current.onClose?.()),\n c.onResize?.((w, h) => ref.current.onResize?.(w, h)),\n c.onContainerTypeChange?.((t) => ref.current.onContainerTypeChange?.(t)),\n ];\n return () => { offs.forEach(off => off?.()); };\n }, [c]);\n}\n\n/**\n * Registers a close guard: resolve `false` to keep the panel open (ask the user, save first, …).\n * Pass `null` to register none. Always calls the latest guard passed in.\n */\nexport function useBeforeClose(guard: (() => boolean | Promise<boolean>) | null): void {\n const c = useFormContainer();\n const ref = useRef(guard);\n useLayoutEffect(() => { ref.current = guard; });\n // Registered once; a null guard allows the close, so switching it off needs no re-registration.\n useEffect(() => c.onCloseRequested(() => (ref.current ? ref.current() : true)), [c]);\n}\n\n/**\n * Reports the panel's restorable state, pulled fresh on every `saveLayout()` and saved as the\n * panel's props. Pass `null` to report none. Always calls the latest function passed in.\n */\nexport function useSaveState(getState: (() => unknown) | null): void {\n const c = useFormContainer();\n const ref = useRef(getState);\n useLayoutEffect(() => { ref.current = getState; });\n // Registered once; reporting undefined (a null function) means \"use the panel's static props\".\n useEffect(() => c.registerStateProvider?.(() => ref.current?.()), [c]);\n}\n\n// ─── Overlays: modals and side drawers ──────────────────────────────────────────\n\ntype OverlayUpdate = Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>;\n\n/** Returned by {@link useModals}. */\nexport interface ModalsApi {\n /** Open modals, bottom to top. */\n stack: OverlayInstance[];\n /** The top modal, or null. */\n topmost: OverlayInstance | null;\n open: <P extends object>(component: React.ComponentType<P>, props: P, options?: ModalOptions) => OverlayId;\n close: (id: OverlayId) => void;\n closeAll: () => void;\n get: (id: OverlayId) => OverlayInstance | undefined;\n update: (id: OverlayId, updates: OverlayUpdate) => void;\n setDirty: (id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => void;\n /**\n * Opens an {@link RddConfirm} and resolves `true` when it is confirmed, `false` when it is\n * cancelled or dismissed (Escape, the backdrop, the ×, or a close by code).\n */\n confirm: (options: ConfirmOptions) => Promise<boolean>;\n /** Opens an {@link RddAlert} and resolves once it is acknowledged or dismissed. */\n alert: (options: AlertOptions) => Promise<void>;\n}\n\n/** Options of {@link ModalsApi.confirm}. The title defaults to the `modalTitle` message. */\nexport interface ConfirmOptions {\n message: RddConfirmProps['message'];\n title?: ModalOptions['title'];\n alert?: string;\n alertType?: RddConfirmProps['alertType'];\n icon?: React.ReactNode | null;\n /** Labels the buttons Yes and No instead of OK and Cancel. */\n yesNo?: boolean;\n /** Defaults to `'small'`. */\n size?: ModalOptions['size'];\n}\n\n/** Options of {@link ModalsApi.alert}. The title defaults to the `alertTitle` message. */\nexport interface AlertOptions {\n message: RddAlertProps['message'];\n title?: ModalOptions['title'];\n alertType?: RddAlertProps['alertType'];\n icon?: React.ReactNode | null;\n okLabel?: RddAlertProps['okLabel'];\n /** Defaults to `'small'`. */\n size?: ModalOptions['size'];\n}\n\n/** Returned by {@link useSidePanels}. */\nexport interface SidePanelsApi {\n left: OverlayInstance | null;\n right: OverlayInstance | null;\n openLeft: <P extends object>(component: React.ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n openRight: <P extends object>(component: React.ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n close: (id: OverlayId) => void;\n /** Closes both drawers. */\n closeAll: () => void;\n get: (id: OverlayId) => OverlayInstance | undefined;\n update: (id: OverlayId, updates: OverlayUpdate) => void;\n setDirty: (id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => void;\n}\n\n/** Opens and tracks modals. */\nexport function useModals(): ModalsApi {\n const { modals } = usePanelState();\n const a = usePanelActions();\n const messages = usePredefinedMessages();\n return useMemo<ModalsApi>(() => ({\n stack: modals,\n topmost: modals[modals.length - 1] ?? null,\n open: a.openModal,\n close: a.close,\n closeAll: a.closeAllModals,\n get: a.getInstance,\n update: a.updateInstance,\n setDirty: a.setDirty,\n confirm: ({ message, title, alert, alertType, icon, yesNo, size = 'small' }) => new Promise<boolean>(resolve => {\n a.openModal(ConfirmationForm, { message, alert, alertType, icon, useYesNoTitles: yesNo, onSettled: resolve },\n { title: title ?? messages.modalTitle, size });\n }),\n alert: ({ message, title, alertType, icon, okLabel, size = 'small' }) => new Promise<void>(resolve => {\n a.openModal(AlertForm, { message, alertType, icon, okLabel, onSettled: resolve },\n { title: title ?? messages.alertTitle, size });\n }),\n }), [modals, a, messages]);\n}\n\n/** Opens and tracks the left and right side drawers. */\nexport function useSidePanels(): SidePanelsApi {\n const { leftPanel, rightPanel } = usePanelState();\n const a = usePanelActions();\n return useMemo<SidePanelsApi>(() => ({\n left: leftPanel,\n right: rightPanel,\n openLeft: a.openLeftPanel,\n openRight: a.openRightPanel,\n close: a.close,\n closeAll: () => {\n if (leftPanel) a.close(leftPanel.id);\n if (rightPanel) a.close(rightPanel.id);\n },\n get: a.getInstance,\n update: a.updateInstance,\n setDirty: a.setDirty,\n }), [leftPanel, rightPanel, a]);\n}\n\n// ─── Components ─────────────────────────────────────────────────────────────────\n\n/** Props for {@link RddSidePanels}. */\nexport interface RddSidePanelsProps {\n /** Render only one side's drawer. Omit to render both. */\n side?: 'left' | 'right';\n /** Width used when an `openLeft`/`openRight` call doesn't give one. Number = px. @default 400 */\n defaultWidth?: number | string;\n}\n\n/** Renders the side drawers opened through {@link useSidePanels}. */\nexport function RddSidePanels({ side, defaultWidth }: RddSidePanelsProps): React.ReactElement {\n if (side === 'left') return <LeftPanelRenderer defaultWidth={defaultWidth} />;\n if (side === 'right') return <RightPanelRenderer defaultWidth={defaultWidth} />;\n return <SidePanelRenderer defaultWidth={defaultWidth} />;\n}\n\n/** Props for {@link RddContextMenu}. */\nexport type RddContextMenuProps = ContextMenuProps & {\n /** With children: the context-menu implementation for them. @default the built-in menu */\n adapter?: ContextMenuAdapter;\n /**\n * With children, `RddContextMenu` provides a context menu to them (`useContextMenu()` inside\n * shows it) — for a surface outside `<DockableDesktopProvider>`, or to override the menu for a\n * subtree. Without children, it is a single menu you drive through its `ref`.\n */\n children?: React.ReactNode;\n};\n\n/**\n * A context menu. Inside `<DockableDesktopProvider>` one is already provided — use\n * `useContextMenu()` or `showContextMenu()` and you need no `RddContextMenu` at all.\n */\nexport const RddContextMenu: React.ForwardRefExoticComponent<RddContextMenuProps & React.RefAttributes<ContextMenuHandle>> = forwardRef<ContextMenuHandle, RddContextMenuProps>(function RddContextMenu(\n { children, adapter, ...menuProps },\n ref,\n) {\n if (children !== undefined) {\n return <ContextMenuProvider adapter={adapter} {...menuProps}>{children}</ContextMenuProvider>;\n }\n return <ContextMenu ref={ref} {...menuProps} />;\n});\n","import type { ComponentType } from 'react';\nimport type { FloatAnchor } from '../types';\n\n/**\n * Represents a registered component configuration template inside the panel catalog registry.\n */\nexport interface PanelRegistryEntry {\n /** The React component type registered. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: a registry holds components with different props; unknown would reject them\n Component: ComponentType<any>;\n /** Default metadata settings configuration applied on instantiation. */\n defaultOptions?: {\n /** Tab and window headers text — plain string or i18n descriptor. */\n title?: string | { id: string; defaultMessage?: string; values?: Record<string, string | number> } | (() => string);\n /** Icon placed next to title tags. */\n icon?: React.ReactNode;\n /** Initial mounting state inside the desktop layout grid. */\n initialTarget?: 'floating' | 'docked' | 'tabbed';\n /** Custom default bounds applied when the container is floated. */\n favoritePosition?: { x: number | string; y: number | string; width: number | string; height: number | string };\n /** Enables/disables window drag interactions. */\n canDrag?: boolean;\n /**\n * `false`: the user can't make this panel floating. A tab drag can't end in a floating window\n * (dropped on nothing or on a corner, it stays where it was), and the \"Float\" and taskbar\n * \"Maximize\" menu items are hidden. A window the app floated itself can still be moved. The\n * app's own `floatPanel` always works. @default true (7.9.0)\n */\n canFloat?: boolean;\n /**\n * `false`: the user can't dock this panel. Dragging it offers no group, tab or edge targets\n * (corners still anchor a floating window), so it stays floating. The app's own docking calls\n * always work; give the type `initialTarget: 'floating'` so it opens floating. @default true (7.9.0)\n */\n canDock?: boolean;\n /** Enables/disables minimizing of the panel instance. */\n canMinimize?: boolean;\n /** Enables/disables closing actions for the tab/window. */\n canClose?: boolean;\n /** Corner of the workspace to anchor newly-opened floating windows to. */\n defaultAnchor?: FloatAnchor;\n /** Disables live WebGL rendering canvas thumbnails inside the taskbar hover popup previews. */\n disableLivePreview?: boolean;\n /** Custom header actions renderer, placing custom components in the window/tab titlebar. */\n renderHeaderActions?: (panelId: string) => React.ReactNode;\n /**\n * Class added to each panel of this type, on its own content element (`.rdd-panel-content`),\n * which moves with the panel between groups, windows and the taskbar preview. (7.8.0)\n */\n className?: string;\n /** Class added to the tab of each panel of this type. (7.8.0) */\n tabClassName?: string;\n /**\n * `false` unmounts the panel's component while it is hidden (an unselected tab, or minimized)\n * and mounts it afresh when it is shown, to free what a heavy, rarely shown panel holds. Its\n * own state is lost each time; its tab, title and lifecycle continue (`onClose` is not called),\n * and the taskbar shows a placeholder instead of a live preview. While it is unmounted, a\n * guard it registered with `useBeforeClose` is not active (its dirty flag still is), and\n * `saveLayout()` saves its open-time props. @default true: panels stay mounted and keep their\n * state, as they always have. (7.8.0)\n */\n keepAlive?: boolean;\n /**\n * Keep embedded documents and media alive when the panel moves (7.11.0): an `<iframe>` doesn't\n * reload when the panel is docked, floated, minimised or restored. The library then moves the\n * panel's element with `moveBefore()`, which keeps that state, in browsers that have it\n * (Chrome and Edge 133+, Firefox 144+); in the others (Safari) it moves as before and an iframe\n * reloads. Off by default. @default false\n */\n preserveEmbeds?: boolean;\n };\n}\n\n/**\n * Registry mapping catalog entries to allow programmatic panel instantiation\n * inside dynamic layout cells or floating windows.\n * Exported so `createWorkspace()` can create scoped, per-instance registries.\n */\nexport class PanelRegistry {\n private registry = new Map<string, PanelRegistryEntry>();\n\n /**\n * Register a new component to the panel catalog registry.\n * @param id - Unique string identifier.\n * @param Component - React component instance template.\n * @param defaultOptions - Custom default settings configuration.\n */\n register<P extends object>(\n id: string,\n Component: ComponentType<P>,\n defaultOptions?: PanelRegistryEntry['defaultOptions']\n ): void {\n this.registry.set(id, {\n Component: Component as PanelRegistryEntry['Component'],\n defaultOptions\n });\n }\n\n /**\n * Retrieve a registered panel configuration by identifier.\n */\n get(id: string): PanelRegistryEntry | undefined {\n return this.registry.get(id);\n }\n\n /**\n * Returns a list of all registered panel entry identifiers.\n */\n getRegisteredIds(): string[] {\n return Array.from(this.registry.keys());\n }\n}\n\n/** Global singleton instance of the Panel Registry. */\nexport const globalPanelRegistry: PanelRegistry = new PanelRegistry();\n","import React, { createContext, useContext, useState, useMemo, useEffect, useSyncExternalStore } from 'react';\nimport { useFormContainer } from './FormContainerContext';\nimport { globalPanelRegistry } from './PanelRegistry';\nimport { createPanelHost, PanelHostContext, type PanelHost } from './workspace/panelHost';\nimport { claimDocumentMirror, releaseDocumentMirror } from '../utils/documentMirror';\nimport type { PanelRegistry } from './PanelRegistry';\nimport { defaultPredefinedMessages } from './predefinedMessages';\nimport type { MessageKey } from './predefinedMessages';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport type { ContextMenuItem } from './ContextMenu';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, WorkspaceActions, InternalWindowActions, HostClasses, WindowManagerProviderProps, WorkspaceCore } from '../types';\nimport { defaultFormatMessage } from '../core/messages';\nimport { createWorkspaceCore } from '../core/workspaceCore';\nimport { useLatestRef } from '../utils/useLatestRef';\nexport type { MessageKey } from './predefinedMessages';\nexport { defaultPredefinedMessages } from './predefinedMessages';\nexport type { DirtyStateOptions };\n\n// Moved in 7.6.1; re-exported so every existing import of this module keeps working.\nexport type { MessageDescriptor, MessageFormatter, SplitOrientation, SplitDirection, DropPosition, DropTarget, PanelDrop, PanelDropTarget, TabContentProps, LayoutGridNode, LayoutLeafNode, LayoutNode, FloatAnchor, FloatingWindow, PanelInfo, PanelOwner, OpenPanelOptions, WorkspaceState, WorkspaceActions, InternalWindowActions, HostClasses, SerializedLayout, WindowManagerProviderProps, WorkspaceCoreConfig, WorkspaceCore } from '../types';\nexport { defaultFormatMessage, formatLabel } from '../core/messages';\nexport { createWorkspaceCore } from '../core/workspaceCore';\n\nconst WindowActionsContext = createContext<InternalWindowActions | null>(null);\nconst WindowI18nContext = createContext<MessageFormatter | null>(null);\n\ninterface WindowStoreSyncContextValue {\n getSnapshot: () => WorkspaceState;\n subscribeToState: (callback: () => void) => () => void;\n}\n/** @internal Snapshot + subscribe for selector hooks (`useWorkspaceState(selector)`, `usePanel`). */\nexport const WindowStoreSyncContext: React.Context<WindowStoreSyncContextValue | null> = createContext<WindowStoreSyncContextValue | null>(null);\n\nconst WindowPredefinedMessagesContext = createContext<Record<MessageKey, MessageDescriptor>>(defaultPredefinedMessages);\n\n\nconst StyleClassContext = createContext<HostClasses>({});\n\n/** Custom hook to read configured style class contexts. */\nexport const useStyleClasses = (): HostClasses => useContext(StyleClassContext);\n\nconst RegistryContext = createContext<PanelRegistry>(globalPanelRegistry);\n\n/**\n * React hook to read the scoped {@link PanelRegistry} for the current provider.\n * When the provider was given a workspace from `createWorkspace()`, this returns that workspace's\n * private registry. Otherwise it returns the global `globalPanelRegistry` singleton.\n *\n * @group Hooks\n * @returns The panel registry instance in scope.\n * @example\n * ```tsx\n * function MyComponent() {\n * const registry = useRegistry();\n * const entry = registry.get('map');\n * return entry ? <entry.Component panelId=\"preview\" /> : null;\n * }\n * ```\n */\nexport const useRegistry = (): PanelRegistry => useContext(RegistryContext);\n\n\nexport const WindowManagerProvider: React.FC<WindowManagerProviderProps> = ({\n children,\n client,\n formatMessage,\n predefinedMessages,\n dir: dirProp,\n modalClass,\n modalBodyClass,\n sidePanelClass,\n sidePanelBodyClass,\n windowClass,\n windowBodyClass,\n zIndexBase: zIndexBaseProp\n}) => {\n // The workspace store: the client's own, or one owned by this provider (then panels come from\n // the global globalPanelRegistry, as before). The store is live before this mounts; nothing connects.\n const [core] = useState<WorkspaceCore>(() => {\n const c = client\n ? client._core\n : createWorkspaceCore({ registry: globalPanelRegistry, dir: dirProp, zIndexBase: zIndexBaseProp });\n c.applyProviderDefaults({ dir: dirProp, zIndexBase: zIndexBaseProp });\n return c;\n });\n const registry = client?.registry ?? globalPanelRegistry;\n // This workspace's own panel DOM, sizes and lifecycle handlers — never shared with another provider.\n const [panelHost] = useState<PanelHost>(createPanelHost);\n const actions = core.actions;\n\n // Effective config: client config takes precedence over individual provider props\n const effectiveFormatMessage = client?.config.formatMessage ?? formatMessage;\n const effectivePredefinedMessages = client?.config.predefinedMessages ?? predefinedMessages;\n const effectiveDir = client?.config.dir ?? dirProp;\n const effectiveZIndexBase = client?.config.zIndexBase ?? zIndexBaseProp ?? 1000;\n\n const mergedMessages = useMemo(() => ({\n ...defaultPredefinedMessages,\n ...effectivePredefinedMessages\n }), [effectivePredefinedMessages]);\n\n // Mirror the z-index base onto document.documentElement as a CSS variable so the\n // library's portaled chrome (ContextMenu, Toast, Toolbar's flyout, ModalStackRenderer),\n // which renders outside this provider's own DOM subtree, shifts in lockstep with\n // the floating windows' z counter.\n // Through the document mirror, keyed by this workspace's panel host (as RddDesktop's skin is), so\n // two workspaces on one page don't strip each other's base on unmount.\n useEffect(() => {\n claimDocumentMirror(panelHost, { zBase: effectiveZIndexBase });\n }, [panelHost, effectiveZIndexBase]);\n useEffect(() => () => releaseDocumentMirror(panelHost, ['zBase']), [panelHost]);\n\n useEffect(() => {\n if (effectiveDir) actions.setDirection(effectiveDir);\n }, [effectiveDir, actions]);\n\n\n const styleClasses = useMemo(() => ({\n modalClass,\n modalBodyClass,\n sidePanelClass,\n sidePanelBodyClass,\n windowClass,\n windowBodyClass\n }), [modalClass, modalBodyClass, sidePanelClass, sidePanelBodyClass, windowClass, windowBodyClass]);\n\n useEffect(() => {\n if (process.env.NODE_ENV !== 'development') return;\n\n // Check 1: styles.css sentinel — catches the \"forgot to import\" case precisely\n try {\n const sentinel = getComputedStyle(document.documentElement)\n .getPropertyValue('--rdd-styles-loaded').trim();\n if (sentinel !== '1') {\n console.error(\n \"[react-dockable-desktop] styles.css is not imported.\\n\" +\n \"Add this to your entry file (main.tsx / index.tsx):\\n\" +\n \" import 'react-dockable-desktop/styles.css'\\n\" +\n \"Without it the workspace renders as a black screen with no console errors.\"\n );\n }\n } catch { /* getComputedStyle unavailable (SSR) */ }\n\n }, []);\n\n const syncContextValue = useMemo<WindowStoreSyncContextValue>(\n () => ({ getSnapshot: core.getSnapshot, subscribeToState: core.subscribeToState }),\n [core]\n );\n\n return (\n <StyleClassContext.Provider value={styleClasses}>\n <RegistryContext.Provider value={registry}>\n <WindowStoreSyncContext.Provider value={syncContextValue}>\n <WindowActionsContext.Provider value={actions}>\n <WindowI18nContext.Provider value={effectiveFormatMessage || defaultFormatMessage}>\n <WindowPredefinedMessagesContext.Provider value={mergedMessages}>\n <PanelHostContext.Provider value={panelHost}>\n {children}\n </PanelHostContext.Provider>\n </WindowPredefinedMessagesContext.Provider>\n </WindowI18nContext.Provider>\n </WindowActionsContext.Provider>\n </WindowStoreSyncContext.Provider>\n </RegistryContext.Provider>\n </StyleClassContext.Provider>\n );\n};\n\nconst noopSubscribe = (_cb: () => void): (() => void) => () => {};\nconst outsideProvider = (): never => { throw new Error('useWorkspaceState must be used within <DockableDesktopProvider>'); };\n\n/**\n * The live workspace state. The component re-renders whenever it changes — or, given a selector,\n * only when the selected value changes.\n *\n * For reads without a subscription, call the workspace's `isOpen()` or `getOpenPanelIds()`.\n *\n * The selector must return a value that stays the same while the state does — a primitive, or a\n * part of the state as it is (`s => s.panels[id]`). A selector that builds a new object or array\n * on each call (`s => ({ n: s.floating.length })`, `s => s.floating.map(...)`) is a new value\n * every time React asks, and React stops with \"Maximum update depth exceeded\". Select the parts\n * separately, or\n * derive the object with `useMemo` from what you selected.\n *\n * @returns The current workspace state, or the selector's result.\n * @throws Error if used outside `<DockableDesktopProvider>`.\n * @example\n * ```tsx\n * function PanelCount() {\n * const count = useWorkspaceState(s => Object.keys(s.panels).length);\n * return <span>{count} open</span>;\n * }\n * ```\n */\nexport function useWindowManagerState(): WorkspaceState;\nexport function useWindowManagerState<T>(selector: (state: WorkspaceState) => T): T;\nexport function useWindowManagerState<T>(selector?: (state: WorkspaceState) => T): WorkspaceState | T {\n // Straight from the store, with the selector inside the subscription: until 7.7.2 this also read\n // a context holding the whole state, so it re-rendered on every change whatever the selector\n // returned.\n const syncCtx = useContext(WindowStoreSyncContext);\n const read = (): WorkspaceState | T => {\n const snap = syncCtx!.getSnapshot();\n return selector ? selector(snap) : snap;\n };\n return useSyncExternalStore(syncCtx?.subscribeToState ?? noopSubscribe, syncCtx ? read : outsideProvider, syncCtx ? read : outsideProvider);\n}\n\n/**\n * @internal `useWorkspaceState(selector)` for components that may also render outside a provider\n * (sidebar, toasts, panel overlays, a panel used standalone): `fallback` there instead of throwing.\n */\nexport function useOptionalWindowManagerState<T>(selector: (state: WorkspaceState) => T, fallback: T): T {\n const syncCtx = useContext(WindowStoreSyncContext);\n const read = (): T => (syncCtx ? selector(syncCtx.getSnapshot()) : fallback);\n return useSyncExternalStore(syncCtx?.subscribeToState ?? noopSubscribe, read, read);\n}\n\n/**\n * React hook to retrieve all layout mutation actions.\n * Returns the public {@link WorkspaceActions} interface.\n *\n * @group Hooks\n * @returns The full set of workspace mutation methods.\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n * @example\n * ```tsx\n * function Toolbar() {\n * const actions = useWindowManagerActions();\n * return (\n * <button onClick={() => actions.openPanel('map-1', 'map')}>Open Map</button>\n * );\n * }\n * ```\n */\nexport const useWindowManagerActions = (): WorkspaceActions => {\n const ctx = useContext(WindowActionsContext);\n if (!ctx) throw new Error('useWorkspace must be used within <DockableDesktopProvider>');\n return ctx;\n};\n\n/**\n * @internal — used by WindowManager.tsx rendering components only.\n * Returns the full {@link InternalWindowActions} including `setActivePanel`.\n */\nexport const useWindowManagerActionsInternal = (): InternalWindowActions => {\n const ctx = useContext(WindowActionsContext);\n if (!ctx) throw new Error('react-dockable-desktop components must be used within <DockableDesktopProvider>');\n return ctx;\n};\n\n\n/** @internal {@link useWindowManagerActionsInternal}, or null outside a provider (a panel overlay used standalone). */\nexport const useOptionalWindowManagerActionsInternal = (): InternalWindowActions | null => useContext(WindowActionsContext);\n\n\n/**\n * React hook to retrieve the active i18n formatter.\n */\nexport const useFormatMessage = (): MessageFormatter => {\n const formatter = useContext(WindowI18nContext);\n return formatter || defaultFormatMessage;\n};\n\n\n/**\n * React hook providing pub-sub helper methods for inter-panel event messaging.\n */\nexport const usePanelContext = (): Pick<WorkspaceActions, 'publish' | 'subscribe'> => {\n const { publish, subscribe } = useWindowManagerActions();\n return { publish, subscribe };\n};\n\n/**\n * React hook to fetch the localizable predefined message map catalog.\n */\nexport const usePredefinedMessages = (): Record<MessageKey, MessageDescriptor> => {\n return useContext(WindowPredefinedMessagesContext);\n};\n\n/**\n * React hook to retrieve the panel instance ID for the component currently rendered inside\n * the dockable desktop. Works for docked, floating, modal, and side-panel containers.\n * Opt-in — components that don't need the ID require no changes.\n *\n * @group Hooks\n * @returns The unique panel instance ID string.\n * @example\n * ```tsx\n * function MyPanel() {\n * const panelId = usePanelId();\n * const { closePanel } = useWindowManagerActions();\n * return <button onClick={() => closePanel(panelId)}>Close</button>;\n * }\n * ```\n */\nexport const usePanelId = (): string => useFormContainer().instanceId;\n\n/**\n * React hook for injecting custom context menu items into a panel's context menu from inside the panel component.\n * Items are dynamic — the array is re-read each time the menu opens, so state-driven changes (enable/disable, add/remove) work automatically.\n * The hook knows which panel it is in — no id needed.\n *\n * @param items - Array of `ContextMenuItem` entries (simple items, separators, submenus).\n * @example\n * ```tsx\n * import { usePanelContextMenu } from 'dockable-windows';\n *\n * function MyPanel() {\n * const [dirty, setDirty] = useState(false);\n * usePanelContextMenu([\n * { label: 'Save', action: () => save() },\n * { label: 'Revert', action: () => revert() },\n * ]);\n * return <Editor onChange={() => setDirty(true)} />;\n * }\n * ```\n */\nexport function usePanelContextMenu(items: ContextMenuItem[]): void {\n const ctx = useContext(WindowActionsContext);\n const panelId = usePanelId();\n const register = ctx?.registerPanelContextMenu;\n const itemsRef = useLatestRef(items);\n\n useEffect(() => {\n if (!register || !panelId) return;\n return register(panelId, () => itemsRef.current);\n }, [panelId, register, itemsRef]);\n}\n","import { createContext, useContext, useSyncExternalStore, type Context, type Provider } from 'react';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport type { MessageDescriptor } from '../types';\n\n/**\n * Options used when requesting to close a container.\n */\nexport interface CloseOptions {\n /** If true, bypasses any dirty state warnings or custom close guards. */\n force?: boolean;\n}\n\n/** Represents the type of container context a panel/form is currently rendered inside. */\nexport type ContainerType =\n | 'left-panel'\n | 'right-panel'\n | 'modal'\n | 'dockable-panel' // panel currently docked in the grid\n | 'floating-window' // panel currently in a detached floating window\n | 'standalone';\n\n/**\n * Contract interface exposed by a container (like a tab, window, modal, or side-panel)\n * to its children forms, enabling them to control or listen to container events.\n */\nexport interface FormContainerContract {\n /** Request the container to close itself. Bypassed by default unless options.force is true. */\n requestClose: (options?: CloseOptions) => void;\n /** Mark the form's content as dirty (having unsaved changes), triggering alert dialogs on close. */\n setDirty: (dirty: boolean, options?: DirtyStateOptions) => void;\n /** Register a custom close guard handler. Returning false or a promise resolving to false blocks closing. */\n onCloseRequested: (handler: () => boolean | Promise<boolean>) => (() => void);\n /**\n * Registers a callback reporting this panel's *current* restorable state, pulled fresh by\n * `workspace.saveLayout()` every time it's called — for panels whose static open-time\n * props can't capture state accumulated after opening (scroll position, an in-progress edit, a\n * view-mode toggle). Only meaningful for docked/floating panels — left/right side panels and\n * modals already have a complete answer to this via `openLeftPanel`/`openRightPanel`/\n * `openModal`'s own `props` argument plus `updateInstance`, so this is `undefined` there.\n * The returned value must be synchronous — `saveLayout()` itself never returns a `Promise`.\n * Return `undefined` to fall back to the static `props` this panel was opened with.\n */\n registerStateProvider?: (getState: () => unknown) => (() => void);\n /** Change the display title of the containing tab or window dynamically. */\n setTitle: (title: string | MessageDescriptor | (() => string)) => void;\n /** Change the tab or window icon dynamically. */\n setIcon?: (icon: React.ReactNode) => void;\n /** The type of container the panel is mounted in. Reflects the state at mount time; subscribe to {@link onContainerTypeChange} for live updates. */\n containerType?: ContainerType;\n /** Unique identifier of the panel or window instance. */\n instanceId: string;\n /** Subscribe to the container's close event. Returns an unsubscribe function. */\n onClose?: (handler: () => void) => () => void;\n /** Subscribe to the container's minimize event. Returns an unsubscribe function. */\n onMinimize?: (handler: () => void) => () => void;\n /** Subscribe to the container's restore event. Returns an unsubscribe function. */\n onRestore?: (handler: () => void) => () => void;\n /** Subscribe to the container's window resize event, returning width and height. Returns an unsubscribe function. */\n onResize?: (handler: (width: number, height: number) => void) => () => void;\n /** Request the container to minimize itself to the taskbar. No-op if the container type does not support minimize. */\n requestMinimize?: () => void;\n /** Returns the current rendered dimensions of this panel, or `null` if the panel has not been laid out yet. */\n getDimensions?: () => { width: number; height: number } | null;\n /**\n * Subscribe to this panel becoming the globally active panel.\n * Fires when `activePanelId` transitions to this panel's id.\n * Returns an unsubscribe function.\n */\n onActivate?: (handler: () => void) => () => void;\n /**\n * Subscribe to this panel losing active status.\n * Fires when `activePanelId` transitions away from this panel's id,\n * and also fires if the panel is destroyed while it is active.\n * Returns an unsubscribe function.\n */\n onDeactivate?: (handler: () => void) => () => void;\n /**\n * Subscribe to changes in the panel's container type (e.g. docked ↔ floating).\n * Does not fire for minimize/restore cycles — use {@link onMinimize} / {@link onRestore} for those.\n * Returns an unsubscribe function.\n */\n onContainerTypeChange?: (handler: (type: ContainerType) => void) => () => void;\n}\n\nconst defaultContract: FormContainerContract = {\n requestClose: () => {\n console.warn('FormContainerContract: requestClose called but no container is present');\n },\n setDirty: () => {},\n onCloseRequested: () => () => {},\n registerStateProvider: () => () => {},\n setTitle: () => {},\n setIcon: () => {},\n containerType: 'standalone',\n instanceId: 'standalone',\n onClose: () => () => {},\n onMinimize: () => () => {},\n onRestore: () => () => {},\n onResize: () => () => {},\n requestMinimize: () => {},\n getDimensions: () => null,\n onActivate: () => () => {},\n onDeactivate: () => () => {},\n onContainerTypeChange: () => () => {},\n};\n\n/**\n * Context that supplies the {@link FormContainerContract} to panels inside the Window Manager.\n */\nexport const FormContainerContext: Context<FormContainerContract> = createContext<FormContainerContract>(defaultContract);\nexport const FormContainerProvider: Provider<FormContainerContract> = FormContainerContext.Provider;\n\n/**\n * React hook to retrieve the current {@link FormContainerContract} from context.\n * Enables sub-forms to trigger close/minimize requests, mark themselves dirty,\n * rename their tabs, query dimensions, or subscribe to lifecycle events\n * (resize, close, minimize, restore, activate, deactivate, container-type changes).\n */\nexport const useFormContainer = (): FormContainerContract => {\n return useContext(FormContainerContext);\n};\n\n/**\n * Reactive alternative to measuring the panel's container yourself.\n * Returns the panel's current `{ width, height }`, or `null` before it has been laid\n * out, and re-renders whenever the panel's rendered box changes — including resizes\n * caused by the workspace itself (a grid split being dragged, docking, floating, or\n * tab activation), not just resizes of an element the panel created.\n */\nexport const usePanelSize = (): { width: number; height: number } | null => {\n const { onResize, getDimensions } = useFormContainer();\n return useSyncExternalStore(\n (onStoreChange) => (onResize ? onResize(() => onStoreChange()) : () => {}),\n () => (getDimensions ? getDimensions() : null)\n );\n};\n","/**\n * @file panelHost.ts\n * @description Where one workspace keeps its panels' DOM, sizes and lifecycle handlers.\n *\n * One host per provider, never module-level. These used to be three module-level maps keyed by\n * panel id alone, so every workspace on the page shared them: each workspace's cleanup deleted the\n * other workspaces' cached elements (their panels remounted blank), and two workspaces with the same\n * panel id rendered into one element and fired each other's lifecycle handlers. vdd's `PanelDomCache`\n * and ndd's `PanelHost` are per desktop for the same reason.\n */\nimport { createContext, useContext, type Context } from 'react';\nimport { trackPanelDom } from '../domPreservation';\nimport { park as parkIn } from '../domMove';\nimport type { ContainerType } from '../FormContainerContext';\n\nexport interface PanelLifecycleRegistry {\n onClose: Set<() => void>;\n onMinimize: Set<() => void>;\n onRestore: Set<() => void>;\n onResize: Set<(w: number, h: number) => void>;\n onActivate: Set<() => void>;\n onDeactivate: Set<() => void>;\n onContainerTypeChange: Set<(type: ContainerType) => void>;\n}\n\nexport interface PanelHost {\n /** The panel's preserved element: created on first use, then moved between slots, never remounted. */\n getOrCreateElement(id: string): HTMLDivElement;\n /** The panel's element if it has one. */\n getElement(id: string): HTMLDivElement | undefined;\n /** Ids of the panels this host holds an element for. */\n ids(): string[];\n /** Drops a closed panel's element (and with it, its recorded scroll and focus). */\n forget(id: string): void;\n /**\n * Parks an element in the hidden store of this host's document, while no slot shows it. The\n * store is found or created in that document, not the global one, so a host bound to another\n * document (a pop-out window, later) parks there.\n */\n park(el: HTMLElement): void;\n /** The panel's last on-screen size, or undefined before it was first laid out. */\n getDimensions(id: string): { width: number; height: number } | undefined;\n setDimensions(id: string, size: { width: number; height: number }): void;\n getLifecycle(id: string): PanelLifecycleRegistry | undefined;\n getOrCreateLifecycle(id: string): PanelLifecycleRegistry;\n deleteLifecycle(id: string): void;\n /**\n * A hosted panel's content (7.11.0): the element of the managed widget it shows, registered by\n * the widget's overlay before it opens the panel and cleared after it removes it. The hosted\n * panel's slot only attaches it.\n */\n getHostedContent(id: string): HTMLElement | undefined;\n setHostedContent(id: string, el: HTMLElement | null): void;\n}\n\n/**\n * @param ownerDocument The document this host creates and parks its elements in. Defaults to the\n * global one, looked up on first use rather than here, so a provider can be created where there\n * is no DOM (server rendering) as long as no element is asked for. vdd's `PanelDomCache` takes\n * the same optional document.\n */\nexport function createPanelHost(ownerDocument?: Document): PanelHost {\n const doc = (): Document => ownerDocument ?? document;\n const elements = new Map<string, HTMLDivElement>();\n const dimensions = new Map<string, { width: number; height: number }>();\n const lifecycle = new Map<string, PanelLifecycleRegistry>();\n const hostedContent = new Map<string, HTMLElement>();\n\n return {\n getOrCreateElement(id) {\n let el = elements.get(id);\n if (!el) {\n el = doc().createElement('div');\n el.className = 'rdd-panel-dom';\n elements.set(id, el);\n trackPanelDom(el);\n }\n return el;\n },\n getElement: (id) => elements.get(id),\n ids: () => Array.from(elements.keys()),\n forget: (id) => { elements.delete(id); },\n // The hidden store is found or created in this host's document (see domMove.ts).\n park(el) { parkIn(el, doc()); },\n getDimensions: (id) => dimensions.get(id),\n setDimensions: (id, size) => { dimensions.set(id, size); },\n getLifecycle: (id) => lifecycle.get(id),\n getOrCreateLifecycle(id) {\n let entry = lifecycle.get(id);\n if (!entry) {\n entry = {\n onClose: new Set(),\n onMinimize: new Set(),\n onRestore: new Set(),\n onResize: new Set(),\n onActivate: new Set(),\n onDeactivate: new Set(),\n onContainerTypeChange: new Set(),\n };\n lifecycle.set(id, entry);\n }\n return entry;\n },\n deleteLifecycle: (id) => { lifecycle.delete(id); },\n getHostedContent: (id) => hostedContent.get(id),\n setHostedContent: (id, el) => { if (el) hostedContent.set(id, el); else hostedContent.delete(id); },\n };\n}\n\n/** @internal The nearest provider's panel host. */\nexport const PanelHostContext: Context<PanelHost | null> = createContext<PanelHost | null>(null);\n\n/** @internal The nearest provider's panel host, or null outside one (a panel overlay used standalone). */\nexport function useOptionalPanelHost(): PanelHost | null {\n return useContext(PanelHostContext);\n}\n\n/** @internal The nearest provider's panel host. Throws outside a provider, as the slots never render there. */\nexport function usePanelHost(): PanelHost {\n const host = useContext(PanelHostContext);\n if (!host) throw new Error('[react-dockable-desktop] panel slots must render inside <DockableDesktopProvider>');\n return host;\n}\n","/**\n * Scroll offsets and focus for panel DOM that is moved rather than remounted.\n *\n * A panel's element is never unmounted: it moves between slots — a tab group, a floating window,\n * the taskbar preview, the hidden parking container. React state survives that; browser state\n * does not. A detached or `display: none` subtree loses every scroll offset, and the focused\n * element inside it loses focus. So every tab switch, minimize/restore, float and dock used to\n * put a long list back at the top and drop the caret out of the field being typed in.\n *\n * Offsets and the focused element are recorded *continuously* while the panel is on screen: by\n * the time React runs an effect cleanup the element has already been detached, and reads 0.\n *\n * Keyed by the panel's cached element rather than its id: each workspace has its own elements, so two\n * workspaces on one page — even with the same panel ids — keep separate records, and a record goes\n * away with its element.\n */\n\ninterface PanelDomRecord {\n /** Last on-screen scroll offset of each scrolled element inside the panel. */\n scrolls: Map<Element, { top: number; left: number }>;\n /** The element inside the panel that last had focus. */\n focused: HTMLElement | null;\n}\n\nconst records = new WeakMap<HTMLElement, PanelDomRecord>();\n\n/** A detached or display:none element has no client rects; its scroll offsets read 0. */\nconst isOnScreen = (el: Element): boolean => el.isConnected && el.getClientRects().length > 0;\n\n/** Starts recording scroll offsets and focus inside a panel's cached element. Idempotent. */\nexport function trackPanelDom(root: HTMLElement): void {\n if (records.has(root)) return;\n const record: PanelDomRecord = { scrolls: new Map(), focused: null };\n records.set(root, record);\n\n root.addEventListener('scroll', (e) => {\n const target = e.target;\n // Defensive: an element being hidden or detached resets its offset to 0, and some browsers\n // report that as a scroll event. Chrome doesn't, so no test exercises this guard.\n if (!(target instanceof Element) || !isOnScreen(target)) return;\n record.scrolls.set(target, { top: target.scrollTop, left: target.scrollLeft });\n }, { capture: true, passive: true });\n\n root.addEventListener('focusin', (e) => {\n if (e.target instanceof HTMLElement) record.focused = e.target;\n });\n}\n\n/**\n * Re-applies a panel's recorded state after its element was attached to a new slot.\n *\n * Scroll offsets are always restored. Focus is restored only when `refocus` is true — the panel\n * is the active one — and focus was actually lost (it is on <body>), so a panel restored in the\n * background, or one the user has already moved away from, never takes focus.\n *\n * Runs now and once more on the next frame: content that lays out lazily (virtualised lists,\n * images) may not be tall enough to accept the offset on the first pass.\n */\nexport function restorePanelDom(root: HTMLElement, { refocus }: { refocus: boolean }): void {\n const record = records.get(root);\n if (!record) return;\n const apply = () => {\n record.scrolls.forEach(({ top, left }, el) => {\n if (!el.isConnected) { record.scrolls.delete(el); return; }\n if (el.scrollTop !== top) el.scrollTop = top;\n if (el.scrollLeft !== left) el.scrollLeft = left;\n });\n const focused = record.focused;\n const focusWasLost = document.activeElement === null || document.activeElement === document.body;\n if (refocus && focusWasLost && focused?.isConnected && isOnScreen(focused)) {\n // The element keeps its own selection range, so focusing it puts the caret back too.\n focused.focus({ preventScroll: true });\n }\n };\n apply();\n if (typeof requestAnimationFrame !== 'undefined') requestAnimationFrame(apply);\n}\n\n/** Drops a closed panel's records. */\nexport function forgetPanelDom(root: HTMLElement): void {\n records.delete(root);\n}\n","/**\n * @file domMove.ts\n * @description Moving a panel's or a widget's element between slots, keeping embedded state where\n * asked to (7.11.0, `preserveEmbeds`).\n *\n * An element moved with `appendChild` is removed and re-inserted: an `<iframe>` in it reloads.\n * `moveBefore()` (Chrome and Edge 133+, Firefox 144+) moves it without that, but only between two\n * places in the same document that are both connected. So an element that preserves its embeds is\n * moved with it when it can be, and parked in the document's hidden store, never detached, between\n * slots. Everything else moves exactly as before.\n */\n\nconst preserving = new WeakSet<Element>();\n\n/** Marks an element (a panel's, or a widget's content) as keeping its embeds alive, or not. */\nexport function setPreserveEmbeds(el: Element, on: boolean): void {\n if (on) preserving.add(el); else preserving.delete(el);\n}\n\n/** Whether an element keeps its embeds alive when it moves. */\nexport function preservesEmbeds(el: Element): boolean {\n return preserving.has(el);\n}\n\n/**\n * Moves `el` into `slot` once the slot is in the document. A slot inside a panel's element can\n * render before the workspace has attached that element; `moveBefore()` needs both ends\n * connected, so an element that keeps its embeds waits (where it is, still connected) rather than\n * fall back to a move that reloads them. Any other element moves at once, as before. Returns a\n * cancel function for the slot's cleanup.\n */\nexport function moveIntoWhenConnected(slot: Element, el: Element): () => void {\n if (!preserving.has(el) || slot.isConnected) { moveInto(slot, el); return () => {}; }\n let cancelled = false;\n let frames = 0;\n const frame = typeof requestAnimationFrame === 'undefined'\n ? (cb: () => void) => { setTimeout(cb, 16); }\n : (cb: () => void) => { requestAnimationFrame(cb); };\n const attempt = (): void => {\n if (cancelled) return;\n // A slot that never connects (it was left detached) still gets its element, after a while.\n if (slot.isConnected || ++frames > 60) { moveInto(slot, el); return; }\n frame(attempt);\n };\n frame(attempt);\n return () => { cancelled = true; };\n}\n\ntype WithMoveBefore = Element & { moveBefore?: (node: Node, child: Node | null) => void };\n\n/** Appends `el` to `parent`: with `moveBefore()` when the element asks for it and it applies. */\nexport function moveInto(parent: Element, el: Element): void {\n const p = parent as WithMoveBefore;\n if (preserving.has(el) && typeof p.moveBefore === 'function'\n && parent.isConnected && el.isConnected && parent.ownerDocument === el.ownerDocument) {\n try {\n p.moveBefore(el, null);\n return;\n } catch {\n // A move the browser refuses (a state it doesn't allow) falls back to a plain move.\n }\n }\n parent.appendChild(el);\n}\n\n/**\n * Where an element waits while no slot shows it: one hidden node per document, shared on purpose.\n * Every workspace's and overlay's elements are distinct, so parking them side by side is harmless.\n */\nconst HIDDEN_ID = 'preserved-dom-container';\n\n/** Parks an element in the hidden store of `doc` (created on first use). */\nexport function park(el: Element, doc: Document): void {\n let store = doc.getElementById(HIDDEN_ID);\n if (!store) {\n store = doc.createElement('div');\n store.id = HIDDEN_ID;\n store.style.display = 'none';\n doc.body.appendChild(store);\n }\n moveInto(store, el);\n}\n\n/**\n * Takes an element out of `slot` when a slot unmounts, unless it already moved elsewhere. One that\n * keeps its embeds is parked instead of detached, so its next move can still keep them.\n */\nexport function leaveSlot(slot: Element, el: Element): void {\n if (el.parentNode !== slot) return;\n if (preserving.has(el)) park(el, el.ownerDocument);\n else slot.removeChild(el);\n}\n","/**\n * What a workspace mirrors onto `<html>`: its skin, its animations opt-out and its stacking base.\n *\n * Chrome that renders outside the workspace element (the toolbar, the sidebar, portaled menus, toasts,\n * flyouts, modals) can only inherit these from the document, so they are written there. The document\n * is shared by every workspace on the page, which is why this module keeps state at module level, per\n * document — and why it is a stack of owners rather than a plain write: with two workspaces mounted,\n * each used to overwrite the other, and unmounting either one removed the values for the one still on\n * screen.\n *\n * Each field shows the most recently mounted owner that claims it. An owner releases only the fields\n * it claimed; releasing the last claim of a field removes it from `<html>`, as a single workspace\n * always did. A field nobody claims is never touched, so a value the page set itself survives.\n */\n\nexport interface DocumentMirrorValues {\n /** `data-rdd-skin`. `null` claims \"no skin attribute\". */\n skin?: string | null;\n /** The `rdd-no-animations` class. */\n noAnimations?: boolean;\n /** `--rdd-z-base`. */\n zBase?: number;\n}\n\ntype Field = keyof DocumentMirrorValues;\nconst FIELDS: readonly Field[] = ['skin', 'noAnimations', 'zBase'];\n\ninterface Claim { owner: object; values: DocumentMirrorValues }\n\nconst stacks = new WeakMap<Document, Claim[]>();\n\nfunction apply(doc: Document, stack: readonly Claim[], touched: readonly Field[]): void {\n const root = doc.documentElement;\n // The newest owner that claims a field decides it.\n const pick = <K extends Field>(field: K): { claimed: boolean; value?: DocumentMirrorValues[K] } => {\n for (let i = stack.length - 1; i >= 0; i--) {\n if (field in stack[i].values) return { claimed: true, value: stack[i].values[field] };\n }\n return { claimed: false };\n };\n\n if (touched.includes('skin')) {\n const skin = pick('skin');\n if (skin.claimed && skin.value) root.setAttribute('data-rdd-skin', skin.value);\n else root.removeAttribute('data-rdd-skin');\n }\n if (touched.includes('noAnimations')) {\n const noAnimations = pick('noAnimations');\n root.classList.toggle('rdd-no-animations', noAnimations.claimed && noAnimations.value === true);\n }\n if (touched.includes('zBase')) {\n const zBase = pick('zBase');\n if (zBase.claimed && zBase.value !== undefined) root.style.setProperty('--rdd-z-base', String(zBase.value));\n else root.style.removeProperty('--rdd-z-base');\n }\n}\n\n/**\n * Claims (or updates) `owner`'s values. A first claim puts the owner on top; an update keeps its\n * place, so changing one workspace's skin never lets it jump over a workspace mounted after it.\n */\nexport function claimDocumentMirror(owner: object, values: DocumentMirrorValues, doc: Document = document): void {\n const stack = stacks.get(doc) ?? [];\n stacks.set(doc, stack);\n const claim = stack.find(c => c.owner === owner);\n if (claim) Object.assign(claim.values, values);\n else stack.push({ owner, values: { ...values } });\n apply(doc, stack, Object.keys(values) as Field[]);\n}\n\n/** Releases `owner`'s claim on `fields`; the owner leaves the stack once it claims nothing. */\nexport function releaseDocumentMirror(owner: object, fields: readonly Field[] = FIELDS, doc: Document = document): void {\n const stack = stacks.get(doc);\n if (!stack) return;\n const index = stack.findIndex(c => c.owner === owner);\n if (index === -1) return;\n const claim = stack[index];\n const released = fields.filter(field => field in claim.values);\n for (const field of released) delete claim.values[field];\n if (Object.keys(claim.values).length === 0) stack.splice(index, 1);\n apply(doc, stack, released);\n}\n","/**\n * @file predefinedMessages.ts\n * @description Provides the default localizable message catalogs and translation keys\n * utilized by Dockable Desktop's context menus, headers, and tooltips.\n *\n * Each value's `id` is the react-intl message ID that the consumer should\n * define in their IntlProvider messages table. The `defaultMessage` is used\n * as a fallback when no external formatter is provided.\n *\n * Pass a partial or full override as `createWorkspace({ messages })` or\n * `<DockableDesktopProvider messages={…}>` to customise labels without replacing the whole table.\n */\nexport const defaultPredefinedMessages = {\n floatWindow: { id: 'dockable-desktop-floatWindow', defaultMessage: 'Float Window' },\n minimizePanel: { id: 'dockable-desktop-minimizePanel', defaultMessage: 'Minimize Panel' },\n closeTab: { id: 'dockable-desktop-closeTab', defaultMessage: 'Close Tab' },\n restorePanel: { id: 'dockable-desktop-restorePanel', defaultMessage: 'Restore Panel' },\n maximizePanel: { id: 'dockable-desktop-maximizePanel', defaultMessage: 'Maximize Panel' },\n closePanel: { id: 'dockable-desktop-closePanel', defaultMessage: 'Close Panel' },\n dockWindow: { id: 'dockable-desktop-dockWindow', defaultMessage: 'Dock Window' },\n minimize: { id: 'dockable-desktop-minimize', defaultMessage: 'Minimize' },\n maximize: { id: 'dockable-desktop-maximize', defaultMessage: 'Maximize' },\n restoreSize: { id: 'dockable-desktop-restoreSize', defaultMessage: 'Restore Size' },\n close: { id: 'dockable-desktop-close', defaultMessage: 'Close' },\n closeEmptyGroup: { id: 'dockable-desktop-closeEmptyGroup', defaultMessage: 'Close empty split group' },\n unsavedChangesTitle: { id: 'dockable-desktop-unsavedChangesTitle', defaultMessage: 'Unsaved Changes' },\n unsavedChangesMessage: { id: 'dockable-desktop-unsavedChangesMessage', defaultMessage: '\"{title}\" has unsaved changes. Do you want to discard your changes and close?' },\n discardChanges: { id: 'dockable-desktop-discardChanges', defaultMessage: 'Discard Changes' },\n cancel: { id: 'dockable-desktop-cancel', defaultMessage: 'Cancel' },\n yes: { id: 'dockable-desktop-yes', defaultMessage: 'Yes' },\n no: { id: 'dockable-desktop-no', defaultMessage: 'No' },\n ok: { id: 'dockable-desktop-ok', defaultMessage: 'OK' },\n closePanelTooltip: { id: 'dockable-desktop-closePanelTooltip', defaultMessage: 'Close panel' },\n closeTooltip: { id: 'dockable-desktop-closeTooltip', defaultMessage: 'Close' },\n // Accessible names and placeholders (6.4.0) — previously hard-coded in English.\n notifications: { id: 'dockable-desktop-notifications', defaultMessage: 'Notifications' },\n closeNotification: { id: 'dockable-desktop-closeNotification', defaultMessage: 'Close notification' },\n scrollTabsLeft: { id: 'dockable-desktop-scrollTabsLeft', defaultMessage: 'Scroll tabs left' },\n scrollTabsRight: { id: 'dockable-desktop-scrollTabsRight', defaultMessage: 'Scroll tabs right' },\n scrollTaskbarLeft: { id: 'dockable-desktop-scrollTaskbarLeft', defaultMessage: 'Scroll taskbar left' },\n scrollTaskbarRight: { id: 'dockable-desktop-scrollTaskbarRight', defaultMessage: 'Scroll taskbar right' },\n moreActions: { id: 'dockable-desktop-moreActions', defaultMessage: 'More actions' },\n search: { id: 'dockable-desktop-search', defaultMessage: 'Search' },\n closeSearch: { id: 'dockable-desktop-closeSearch', defaultMessage: 'Close search' },\n searchPlaceholder: { id: 'dockable-desktop-searchPlaceholder', defaultMessage: 'Search…' },\n modalTitle: { id: 'dockable-desktop-modalTitle', defaultMessage: 'Confirmation' },\n // Default title of useModals().alert() (7.7.0).\n alertTitle: { id: 'dockable-desktop-alertTitle', defaultMessage: 'Information' },\n emptyGroup: { id: 'dockable-desktop-emptyGroup', defaultMessage: 'Empty Workspace Section' },\n emptyGrid: { id: 'dockable-desktop-emptyGrid', defaultMessage: 'Grid Empty' },\n componentUnregistered: { id: 'dockable-desktop-componentUnregistered', defaultMessage: 'Component Unregistered' },\n componentKey: { id: 'dockable-desktop-componentKey', defaultMessage: 'Key: {key}' },\n untitledPanel: { id: 'dockable-desktop-untitledPanel', defaultMessage: 'Panel' },\n} as const;\n\n/**\n * Union of every key in `defaultMessages`.\n *\n * Import this type in your i18n message tables to get a compile-time\n * guarantee that all keys are present and no typos exist:\n *\n * import type { MessageKey } from 'react-dockable-desktop';\n *\n * const myMessages: Record<MessageKey, string> = { ... };\n */\nexport type MessageKey = keyof typeof defaultPredefinedMessages;\n","/**\n * @file messages.ts\n * @description Resolving a label — a string, a message descriptor or a thunk — to text.\n */\nimport type { MessageDescriptor, MessageFormatter } from '../types';\n\n/**\n * @internal The formatter used when the app passes none: the descriptor's `defaultMessage` (or its\n * id) with each `{key}` replaced by its value — every occurrence (7.4.1; it replaced only the first).\n */\nexport const defaultFormatMessage: MessageFormatter = (msg) => {\n let text = msg.defaultMessage || msg.id;\n if (msg.values) {\n for (const [key, value] of Object.entries(msg.values)) text = text.split(`{${key}}`).join(String(value));\n }\n return text;\n};\n\n/**\n * Helper to resolve dynamic label strings or localizable descriptor objects into text.\n */\nexport const formatLabel = (\n label: string | MessageDescriptor | (() => string) | undefined,\n formatter: MessageFormatter\n): string => {\n if (!label) return '';\n if (typeof label === 'string') return label;\n // A thunk (7.4.0) is called each time the label is rendered, so it follows the app's own locale.\n if (typeof label === 'function') return label();\n return formatter(label);\n};\n","import { isValidElement } from 'react';\n\n/**\n * Recursively checks whether a value can round-trip through `JSON.stringify`/`JSON.parse`\n * without silently losing information.\n *\n * Deliberately **not** a `JSON.stringify` try/catch — that call doesn't throw for the actual\n * failure case this guards against: a function-valued property is simply dropped by\n * `JSON.stringify`, not rejected. This walks the value tree instead, returning `false` as soon as\n * it finds a function, symbol, `undefined`, React element, or any non-plain object (a class\n * instance, `Map`, `Set`, `RegExp`, etc.).\n *\n * `Date` is treated as an explicit exception — serializable-enough, matching `JSON.stringify`'s\n * own behavior — even though it doesn't round-trip back to a `Date` instance on parse. That's a\n * smaller, more tolerable gotcha than a silently-vanishing function, so it's documented rather\n * than treated as a disqualifying case.\n *\n * Used to decide whether a docked/floating panel's `props` can be included in\n * the workspace's `saveLayout()` output — see {@link PanelInfo.serializable}.\n */\nexport function isSerializable(value: unknown): boolean {\n if (value === null) return true;\n if (value === undefined) return false;\n\n const type = typeof value;\n if (type === 'string' || type === 'number' || type === 'boolean') return true;\n if (type === 'function' || type === 'symbol' || type === 'bigint') return false;\n\n // type === 'object' from here on.\n if (value instanceof Date) return true;\n if (isValidElement(value)) return false;\n if (Array.isArray(value)) return value.every(isSerializable);\n\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return false; // class instance, Map, Set, RegExp, Error, etc.\n\n return Object.values(value as Record<string, unknown>).every(isSerializable);\n}\n","/**\n * @file sameUpdate.ts\n * @description Equality checks that let the title and dirty setters skip a write that changes\n * nothing, so a panel that writes the same value on every render doesn't re-render forever.\n */\nimport type { DirtyStateOptions } from './dirtyOptions';\n\ntype Title = string | { id: string; defaultMessage?: string; values?: Record<string, unknown> } | (() => string);\n\nfunction shallowEqual(a: object | undefined, b: object | undefined): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n const ka = Object.keys(a);\n if (ka.length !== Object.keys(b).length) return false;\n return ka.every(k => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k]);\n}\n\n/** A string title, or a message descriptor with the same id, default text and values. */\nexport function sameTitle(a: Title | undefined, b: Title | undefined): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;\n return a.id === b.id && a.defaultMessage === b.defaultMessage && shallowEqual(a.values, b.values);\n}\n\n/** Dirty options with the same title, message and alert. */\nexport function sameDirtyOptions(a: DirtyStateOptions | undefined, b: DirtyStateOptions | undefined): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof DirtyStateOptions>;\n for (const k of keys) {\n const x = a[k], y = b[k];\n if (k === 'title' || k === 'message' ? !sameTitle(x as Title | undefined, y as Title | undefined) : x !== y) return false;\n }\n return true;\n}\n","/**\n * @file eventBus.ts\n * @description The workspace's pub/sub event bus.\n */\n\n// Event Bus class for pub-sub communication between panels\nexport class PanelEventBus {\n private listeners: Record<string, ((data: unknown) => void)[]> = {};\n\n subscribe(event: string, callback: (data: unknown) => void): () => void {\n if (!this.listeners[event]) {\n this.listeners[event] = [];\n }\n this.listeners[event].push(callback);\n return () => {\n this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);\n };\n }\n\n publish(event: string, data: unknown): void {\n if (this.listeners[event]) {\n // One subscriber that throws must not stop delivery to the rest (7.4.1), nor the action\n // that published — loadLayout, a close — halfway through.\n for (const cb of this.listeners[event]) {\n try {\n cb(data);\n } catch (e) {\n console.error(`[react-dockable-desktop] A subscriber to \"${event}\" threw:`, e);\n }\n }\n }\n }\n}\n","/**\n * @file layoutTree.ts\n * @description Pure functions over the layout tree: which panel is visibly active, repairing a\n * loaded tree, and the tree edits the workspace actions are built from.\n */\nimport type { SplitOrientation, SplitDirection, LayoutLeafNode, LayoutNode, FloatingWindow, PanelInfo, SerializedLayout } from '../types';\n\nexport const EMPTY_LEAF: LayoutLeafNode = {\n type: 'leaf',\n id: 'group-default',\n panels: [],\n activePanelId: null,\n};\n\n/** The subset of a layout needed to reason about which panel is visibly active. */\nexport type ActiveTargetScope = Pick<SerializedLayout, 'gridRoot' | 'floating' | 'panels'>;\n\n/**\n * Whether `id` names a panel the user can actually see, and which may therefore be the globally\n * active one: the selected tab of some leaf, or a floating window. A minimized panel never\n * qualifies — it stays mounted (see the persistence port in `WindowManager.tsx`), so leaving it\n * active would keep routing `useActiveContribution()` to a panel that isn't on screen.\n *\n * Used both to validate a persisted `activePanelId` on load and to guard the one written by\n * `saveLayout`, so the two directions can't disagree about what \"active\" is allowed to mean.\n */\nexport function isVisibleActiveTarget(id: string, scope: ActiveTargetScope): boolean {\n const info = scope.panels[id];\n if (!info || info.state === 'minimized') return false;\n if (scope.floating.some(w => w.id === id)) return true;\n const isLeafSelection = (node: LayoutNode): boolean =>\n node.type === 'leaf'\n ? node.activePanelId === id\n : node.children.some(isLeafSelection);\n return scope.gridRoot ? isLeafSelection(scope.gridRoot) : false;\n}\n\n/**\n * Derives the globally active panel for a restored layout.\n *\n * Replaces the original `Object.keys(panels)[0]` seed, which picked the first key of a flat,\n * insertion-ordered record that knows nothing about tab order or docked/floating/minimized — so\n * unless the user happened to have the first-opened panel selected when they saved, the workspace\n * came back with one panel visible and a *different*, invisible one marked active. Every\n * `LayoutLeafNode` already persists its own `activePanelId`, so the answer was on disk all along.\n *\n * Order:\n * 1. The first leaf in document order whose own selected tab is a valid target.\n * 2. Otherwise the frontmost (highest `z`) floating window — matching `focusPanel`'s own\n * \"highest z is on top\" rule, and keeping float-only layouts from restoring with nothing\n * active at all.\n * 3. Otherwise `null`.\n *\n * Depth-first, not breadth-first: for a grid whose first child is itself a split, a level-by-level\n * walk reaches the *second* child's leaf before the first child's leaves and picks the wrong tab.\n * Mirrors `findFirstLeafId`'s traversal shape for exactly that reason.\n */\nexport function deriveActivePanelId(scope: ActiveTargetScope): string | null {\n const isCandidate = (id: string | null): boolean =>\n id !== null && !!scope.panels[id] && scope.panels[id].state !== 'minimized';\n\n const fromLeaves = (node: LayoutNode): string | null => {\n if (node.type === 'leaf') {\n return isCandidate(node.activePanelId) ? node.activePanelId : null;\n }\n for (const child of node.children) {\n const found = fromLeaves(child);\n if (found) return found;\n }\n return null;\n };\n\n const selected = scope.gridRoot ? fromLeaves(scope.gridRoot) : null;\n if (selected) return selected;\n\n let frontmost: FloatingWindow | null = null;\n for (const w of scope.floating) {\n if (!isCandidate(w.id)) continue;\n if (!frontmost || w.z > frontmost.z) frontmost = w;\n }\n return frontmost?.id ?? null;\n}\n\n/**\n * The globally active panel after a placement action (float / dock / move / close-group).\n *\n * Those actions change which tab a leaf shows without going through `focusPanel`, and each one\n * used to leave `activePanelId` wherever it was — often on a tab the move had just hidden, so the\n * visible tab rendered unfocused and `useActiveContribution()` kept serving the hidden\n * panel's controls. The moved panel is what the user just acted on, so it wins when it is\n * visible; otherwise the previous active panel is kept if it still is; otherwise it is derived.\n */\nexport function resolveActivePanelId(\n next: ActiveTargetScope & { activePanelId: string | null },\n preferId: string | null,\n): string | null {\n if (preferId && isVisibleActiveTarget(preferId, next)) return preferId;\n if (next.activePanelId && isVisibleActiveTarget(next.activePanelId, next)) return next.activePanelId;\n return deriveActivePanelId(next);\n}\n\n/**\n * Shared shape-check + migration for a parsed (but not yet validated) layout payload,\n * used by both `parseInitialState` (the `initialState`/`createWorkspace({ initialState })`\n * entry point) and `loadLayout` — previously these duplicated the check independently\n * and only one of them ran the stickyRight/stickyBottom migration, so a layout fed\n * through `initialState` silently skipped it. `version` is read but not yet branched on\n * — it's read here so a future migration has a version to gate on without needing\n * another ad hoc field-presence sniff like this one.\n *\n * Also resolves `activePanelId`, for the same reason the shape-check lives here: both entry\n * points need it and previously seeded it themselves, identically wrongly, in two places.\n */\n/**\n * Heal a saved layout that names the same panel twice, or names none of them.\n *\n * Until 6.3.1, dropping a lone docked panel onto its own group put that panel in two leaves,\n * and `saveLayout()` wrote the result out — so the duplicate came back on every reload, for\n * good. Repairing on read means a layout stored by an affected version loads clean with\n * nothing asked of the application. It changes only what is *read*: `saveLayout()`'s output\n * format is untouched.\n *\n * The repairs, in order: a leaf panel id the layout's `panels` doesn't have is dropped (7.4.1);\n * a panel id that appears in more than one leaf is kept in the first one only; a leaf emptied\n * by either keeps existing only if it asked to (`keepOnEmpty`); a branch left with one child\n * collapses into it, with sizes re-normalised; a branch whose sizes don't match its children,\n * or aren't finite positive numbers, gets even sizes (7.4.1); and a panel the layout says is\n * docked but that no leaf lists is appended to the first leaf, since \"open but in no group\"\n * renders nothing and cannot be reached.\n */\nexport function repairLayoutTree(\n gridRoot: LayoutNode,\n panels: Record<string, PanelInfo>\n): { gridRoot: LayoutNode; repairs: string[] } {\n const repairs: string[] = [];\n const seen = new Set<string>();\n\n const walk = (node: LayoutNode): LayoutNode | null => {\n if (node.type === 'leaf') {\n const kept = node.panels.filter(panelId => {\n if (!panels[panelId]) {\n repairs.push(`group \"${node.id}\" listed panel \"${panelId}\", which the layout doesn't have`);\n return false;\n }\n if (seen.has(panelId)) {\n repairs.push(`panel \"${panelId}\" was listed in more than one group`);\n return false;\n }\n seen.add(panelId);\n return true;\n });\n if (kept.length === node.panels.length) return node;\n if (kept.length === 0 && !node.keepOnEmpty) return null;\n const activePanelId = node.activePanelId && kept.includes(node.activePanelId)\n ? node.activePanelId\n : (kept[0] ?? null);\n return { ...node, panels: kept, activePanelId };\n }\n\n const children = node.children.map(walk).filter((c): c is LayoutNode => c !== null);\n // Identity, not count: a child can survive the walk and still have been repaired inside.\n // Comparing lengths alone returned the original branch and discarded those repairs.\n // Sizes that don't match the children, or aren't finite positive numbers, would give a child\n // `flex-basis: NaN%` (7.4.1): such a branch gets even sizes.\n const sizesOk = (sizes: unknown[], n: number) =>\n Array.isArray(sizes) && sizes.length === n && sizes.every(v => typeof v === 'number' && Number.isFinite(v) && v > 0);\n const unchanged = children.length === node.children.length && children.every((c, i) => c === node.children[i]);\n if (unchanged && sizesOk(node.sizes, children.length)) return node;\n if (children.length === 0) return null;\n if (children.length === 1) return children[0];\n if (unchanged) {\n repairs.push(`a split had sizes ${JSON.stringify(node.sizes)} for ${children.length} children`);\n return { ...node, sizes: children.map(() => 1 / children.length) };\n }\n const kept = Array.isArray(node.sizes) ? node.sizes.slice(0, children.length) : [];\n if (!sizesOk(kept, children.length)) return { ...node, children, sizes: children.map(() => 1 / children.length) };\n const sum = kept.reduce((a, b) => a + b, 0);\n return { ...node, children, sizes: kept.map(s => s / sum) };\n };\n\n let root = walk(gridRoot) || EMPTY_LEAF;\n\n const orphans = Object.values(panels).filter(p => p.state === 'docked' && !seen.has(p.id));\n if (orphans.length > 0) {\n const attach = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n const ids = orphans.map(p => p.id);\n return { ...node, panels: [...node.panels, ...ids], activePanelId: node.activePanelId ?? ids[0] };\n }\n return { ...node, children: [attach(node.children[0]), ...node.children.slice(1)] };\n };\n for (const orphan of orphans) {\n repairs.push(`panel \"${orphan.id}\" is docked but was in no group`);\n }\n root = attach(root);\n }\n\n return { gridRoot: root, repairs };\n}\n\n// Recursive helpers to manipulate layout tree\nexport const removePanelFromTree = (node: LayoutNode, id: string): LayoutNode | null => {\n if (node.type === 'leaf') {\n const idx = node.panels.indexOf(id);\n if (idx === -1) return node;\n const panels = node.panels.filter(p => p !== id);\n const activePanelId = node.activePanelId === id\n ? (panels[idx] || panels[idx - 1] || panels[0] || null)\n : node.activePanelId;\n const updatedLeaf = { ...node, panels, activePanelId };\n // Auto-remove this leaf when it becomes empty, unless keepOnEmpty is set\n if (panels.length === 0 && !node.keepOnEmpty) return null;\n return updatedLeaf;\n } else {\n const children = node.children\n .map(c => removePanelFromTree(c, id))\n .filter((c): c is LayoutNode => c !== null);\n\n if (children.length === 0) return null;\n if (children.length === 1) return children[0];\n\n // Re-normalize sizes\n const sizes = node.sizes.slice(0, children.length);\n const sum = sizes.reduce((a, b) => a + b, 0);\n return {\n ...node,\n children,\n sizes: sizes.map(s => s / sum)\n };\n }\n};\n\nexport const addPanelToLeaf = (node: LayoutNode, leafId: string, panelId: string): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.id === leafId) {\n const panels = node.panels.includes(panelId) ? node.panels : [...node.panels, panelId];\n return { ...node, panels, activePanelId: panelId };\n }\n return node;\n } else {\n return {\n ...node,\n children: node.children.map(c => addPanelToLeaf(c, leafId, panelId))\n };\n }\n};\n\n/**\n * Is `panelId` the only panel in `leafId`?\n *\n * The question every dock reducer has to ask *before* it removes anything. Removing a\n * panel deletes an emptied leaf, so a drop onto the dragged panel's own leaf destroys the\n * very target it names — and the placement that follows has nowhere to go. Dropping a lone\n * panel onto itself is a no-op by definition: the result would be the layout it already\n * has.\n */\nexport const isLoneOccupant = (node: LayoutNode, leafId: string, panelId: string): boolean => {\n if (node.type === 'leaf') {\n return node.id === leafId && node.panels.length === 1 && node.panels[0] === panelId;\n }\n return node.children.some(c => isLoneOccupant(c, leafId, panelId));\n};\n\n/** Does `leafId` name a leaf that is actually in the tree? */\nexport const hasLeaf = (node: LayoutNode, leafId: string): boolean =>\n node.type === 'leaf' ? node.id === leafId : node.children.some(c => hasLeaf(c, leafId));\n\n/** Whether a docked panel is the one shown in its group. */\nexport const isShownInGrid = (node: LayoutNode, panelId: string): boolean => {\n if (node.type === 'leaf') return node.panels.includes(panelId) && node.activePanelId === panelId;\n return node.children.some(c => isShownInGrid(c, panelId));\n};\n\n/** The id of the group (leaf) that holds `panelId` in the grid, or null if it is not docked. */\nexport const findLeafIdOf = (node: LayoutNode, panelId: string): string | null => {\n if (node.type === 'leaf') return node.panels.includes(panelId) ? node.id : null;\n for (const child of node.children) {\n const id = findLeafIdOf(child, panelId);\n if (id) return id;\n }\n return null;\n};\n\nexport const findFirstLeafId = (node: LayoutNode): string | null => {\n if (node.type === 'leaf') return node.id;\n for (const child of node.children) {\n const id = findFirstLeafId(child);\n if (id) return id;\n }\n return null;\n};\n\n// Helper to split a layout leaf node into a branch (for drag split targets)\nexport const splitLeafInTree = (\n node: LayoutNode,\n leafId: string,\n panelId: string,\n position: SplitDirection,\n splitRatio: number\n): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.id === leafId) {\n const newLeaf: LayoutLeafNode = {\n type: 'leaf',\n id: `group-split-${Date.now()}-${Math.floor(Math.random() * 1000)}`,\n panels: [panelId],\n activePanelId: panelId\n };\n const orientation: SplitOrientation = (position === 'left' || position === 'right') ? 'horizontal' : 'vertical';\n const children = (position === 'left' || position === 'top') ? [newLeaf, node] : [node, newLeaf];\n const sizes = (position === 'left' || position === 'top')\n ? [splitRatio, 1 - splitRatio]\n : [1 - splitRatio, splitRatio];\n return {\n type: 'branch',\n orientation,\n sizes,\n children\n };\n }\n return node;\n } else {\n return {\n ...node,\n children: node.children.map(c => splitLeafInTree(c, leafId, panelId, position, splitRatio))\n };\n }\n};\n","/**\n * @file panelOptions.ts\n * @description One place that answers \"what options does this open panel have\": its type's\n * registration, or, for a panel showing a widget moved out of its owner panel, the widget's own.\n */\nimport type { PanelRegistry, PanelRegistryEntry } from '../components/PanelRegistry';\nimport type { PanelInfo } from '../types';\n\n/** A panel type's options, as registered (`defaultOptions`). */\nexport type PanelTypeOptions = NonNullable<PanelRegistryEntry['defaultOptions']>;\n\n/**\n * The component key of a panel that shows a managed widget moved out of its owner panel (7.11.0).\n * Reserved: such a panel has no registration, and its content is the widget's, mounted by its owner.\n */\nexport const HOSTED_COMPONENT = 'rdd:widget';\n\n/** What a hosted panel can do whatever its widget says: close, minimise, be dragged; stay mounted. */\nconst HOSTED_BASE: PanelTypeOptions = { canDrag: true, canClose: true, canMinimize: true, keepAlive: true };\n\n/**\n * The options that apply to an open panel. For an ordinary panel, its type's registration; for a\n * hosted panel, the base above plus the widget's `canFloat` / `canDock` (both `false` unless the\n * widget allows them). `component` is the fallback for an id that is no longer in `state.panels`\n * (a minimized entry keeps its own copy).\n */\nexport function optionsFor(\n registry: PanelRegistry,\n panel: PanelInfo | undefined,\n component?: string,\n): PanelTypeOptions | undefined {\n if (panel?.owner) {\n return {\n ...HOSTED_BASE,\n canFloat: panel.owner.options?.canFloat ?? false,\n canDock: panel.owner.options?.canDock ?? false,\n };\n }\n const key = panel?.component ?? component;\n return key === undefined ? undefined : registry.get(key)?.defaultOptions;\n}\n","/**\n * @file serialize.ts\n * @description Reading a saved layout: parsing, migrating, and repairing it on load.\n */\nimport type { LayoutNode, FloatAnchor, PanelInfo, WorkspaceState, SerializedLayout } from '../types';\nimport { EMPTY_LEAF, isVisibleActiveTarget, deriveActivePanelId, repairLayoutTree, removePanelFromTree } from './layoutTree';\nimport { HOSTED_COMPONENT } from './panelOptions';\nimport type { ActiveTargetScope } from './layoutTree';\n\nexport type ParsedLayoutPayload = Pick<SerializedLayout, 'gridRoot' | 'floating' | 'minimized' | 'panels'> & {\n /** Resolved by `parseLayoutPayload` — the persisted value when still valid, else derived. */\n activePanelId: string | null;\n};\n\n/** The geometry a newly floated panel gets, and what a saved window's unusable geometry is repaired to. */\nexport const DEFAULT_FLOAT_RECT = { x: 300, y: 150, width: 450, height: 350 } as const;\n\n/**\n * A saved window's x/y/width/height, made finite (7.4.0). A NaN, Infinity or missing number would\n * otherwise reach the window's style — React logs \"`NaN` is an invalid value for the `left` css\n * style property\" at every start-up — so each is replaced by the default a new float gets, and the\n * repair is reported. A string (a CSS length) is kept as it is.\n */\nexport function finiteGeometry<T extends Record<string, unknown>>(fw: T, repairs: string[]): T {\n let out = fw;\n for (const k of ['x', 'y', 'width', 'height'] as const) {\n const v = fw[k];\n if (typeof v === 'string' || (typeof v === 'number' && Number.isFinite(v))) continue;\n out = { ...out, [k]: DEFAULT_FLOAT_RECT[k] } as T;\n repairs.push(`floating window \"${fw.id}\" had ${k} = ${String(v)}`);\n }\n return out;\n}\n\n/** A saved window as read from storage, before repair: possibly a pre-anchor layout (`stickyRight`/`stickyBottom`). */\ntype RawWindow = Record<string, unknown>;\n\nexport function parseLayoutPayload(input: unknown): ParsedLayoutPayload | null {\n const parsed = input as Partial<Record<'gridRoot' | 'floating' | 'minimized' | 'panels' | 'activePanelId', unknown>> | null;\n if (!parsed || !parsed.gridRoot || !Array.isArray(parsed.floating) || !Array.isArray(parsed.minimized) || !parsed.panels) {\n return null;\n }\n // const version = typeof parsed.version === 'number' ? parsed.version : 0; // reserved for future migrations\n const geometryRepairs: string[] = [];\n // Past the shape check the payload is trusted, as before; each window only gets its geometry\n // repaired and a pre-anchor layout converted.\n const floating = (parsed.floating as RawWindow[]).map(fw => finiteGeometry(fw, geometryRepairs)).map(fw => {\n if ('stickyRight' in fw || 'stickyBottom' in fw) {\n const anchor: FloatAnchor | null = fw.stickyRight && fw.stickyBottom ? 'bottom-right'\n : fw.stickyRight ? 'top-right'\n : fw.stickyBottom ? 'bottom-left'\n : null;\n const { stickyRight: _sr, stickyBottom: _sb, ...rest } = fw;\n return { ...rest, anchor };\n }\n return fw;\n }) as unknown as SerializedLayout['floating'];\n const panels = parsed.panels as Record<string, PanelInfo>;\n // Repair before anything reads the tree: activePanelId resolution below asks which panels\n // are visible, and a duplicated or orphaned panel would make that answer meaningless.\n const repaired = repairLayoutTree(parsed.gridRoot as LayoutNode, panels);\n if (repaired.repairs.length > 0 && process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] Repaired the saved layout on load: ${repaired.repairs.join('; ')}. ` +\n `(Layouts saved by versions before 6.3.1 can list a panel twice — dropping a lone docked ` +\n `panel onto its own group duplicated it.) The repair is applied every time it is read, so ` +\n `saving again from this session stores the corrected layout.`\n );\n }\n if (geometryRepairs.length > 0 && process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] Repaired the saved layout on load: ${geometryRepairs.join('; ')}. ` +\n `Each is replaced by the default a new floating window gets (${JSON.stringify(DEFAULT_FLOAT_RECT)}); ` +\n `saving again from this session stores the corrected layout.`\n );\n }\n const gridRoot = repaired.gridRoot;\n const scope: ActiveTargetScope = { gridRoot, floating, panels };\n\n // A persisted value wins when it still names a visible panel; anything stale (the panel was\n // closed, minimized, or pruned from this snapshot) falls back to deriving from the grid, which\n // is also the path every pre-`activePanelId` layout takes.\n const persisted = typeof parsed.activePanelId === 'string' ? parsed.activePanelId : null;\n let activePanelId: string | null = null;\n if (persisted !== null) {\n if (isVisibleActiveTarget(persisted, scope)) {\n activePanelId = persisted;\n } else if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] Ignoring the saved layout's activePanelId (\"${persisted}\") — ` +\n `it doesn't name a currently visible panel (it may have been closed, minimized, or ` +\n `excluded from the snapshot as non-serializable). Falling back to the selected tab of ` +\n `the first leaf in the grid.`\n );\n }\n }\n if (activePanelId === null) activePanelId = deriveActivePanelId(scope);\n\n return { gridRoot, floating, minimized: parsed.minimized as SerializedLayout['minimized'], panels, activePanelId };\n}\n\n/**\n * A parsed layout without hosted panels (7.11.0). A hosted panel shows a widget its owner panel\n * mounts; `saveLayout()` never writes one, so one in a layout came from a hand-made JSON and has no\n * content to show. It is dropped with every reference to it, and `owner` is stripped elsewhere.\n */\nexport function withoutHostedPanels(payload: ParsedLayoutPayload): ParsedLayoutPayload {\n const hosted = Object.values(payload.panels).filter(p => p.component === HOSTED_COMPONENT).map(p => p.id);\n if (hosted.length === 0) return payload;\n const panels = { ...payload.panels };\n let gridRoot: LayoutNode = payload.gridRoot;\n for (const id of hosted) {\n delete panels[id];\n gridRoot = removePanelFromTree(gridRoot, id) || EMPTY_LEAF;\n }\n const gone = new Set(hosted);\n const floating = payload.floating.filter(w => !gone.has(w.id));\n const minimized = payload.minimized.filter(m => !gone.has(m.id));\n const activePanelId = payload.activePanelId !== null && gone.has(payload.activePanelId)\n ? deriveActivePanelId({ gridRoot, floating, panels } as ActiveTargetScope)\n : payload.activePanelId;\n return { gridRoot, floating, minimized, panels, activePanelId };\n}\n\nexport function parseInitialState(json: string | null): Pick<WorkspaceState, 'gridRoot' | 'floating' | 'minimized' | 'panels' | 'activePanelId'> {\n if (json) {\n try {\n const payload = parseLayoutPayload(JSON.parse(json));\n if (payload) return withoutHostedPanels(payload);\n } catch {\n // fall through to empty canvas\n }\n }\n return { gridRoot: EMPTY_LEAF, floating: [], minimized: [], panels: {}, activePanelId: null };\n}\n","/**\n * @file workspaceCore.ts\n * @description The workspace store: the layout state, every action on it, and the event bus. It\n * has no React dependency; a provider only subscribes to it.\n */\nimport type React from 'react';\nimport type { DirtyStateOptions } from '../components/dirtyOptions';\nimport type { ContextMenuItem, ShowContextMenuOptions } from '../components/ContextMenu';\nimport { isSerializable } from '../components/serializable';\nimport { sameTitle, sameDirtyOptions } from '../components/sameUpdate';\nimport type { PanelDropTarget, MessageDescriptor, SplitOrientation, SplitDirection, DropPosition, LayoutLeafNode, LayoutNode, FloatAnchor, FloatingWindow, PanelInfo, PanelOwner, HostedPanelPlacement, OpenPanelOptions, WorkspaceState, InternalWindowActions, SerializedLayout, WorkspaceCoreConfig, WorkspaceCore } from '../types';\nimport { PanelEventBus } from './eventBus';\nimport { EMPTY_LEAF, isVisibleActiveTarget, deriveActivePanelId, resolveActivePanelId, removePanelFromTree, addPanelToLeaf, isLoneOccupant, hasLeaf, findFirstLeafId, findLeafIdOf, splitLeafInTree } from './layoutTree';\nimport { DEFAULT_FLOAT_RECT, parseLayoutPayload, parseInitialState, withoutHostedPanels } from './serialize';\nimport { optionsFor, HOSTED_COMPONENT } from './panelOptions';\n\n/**\n * @internal Builds a workspace store: the layout state, every action on it, and the event bus.\n * It has no React dependency — it exists (and accepts calls) before any provider mounts, and a\n * provider only subscribes to it. See `createWorkspace()` for the public face.\n */\nexport function createWorkspaceCore(config: WorkspaceCoreConfig): WorkspaceCore {\n const registry = config.registry;\n\n const effectiveDir = config.dir;\n const effectiveZIndexBase = config.zIndexBase ?? 1000;\n\n let state: WorkspaceState = (() => {\n const layout = parseInitialState(config.initialState ?? null);\n return {\n ...layout,\n draggedPanelId: null,\n dir: effectiveDir || 'ltr',\n isRtl: effectiveDir === 'rtl',\n splitRatio: Math.min(0.9, Math.max(0.1, config.defaultSplitRatio ?? 0.5)),\n edgeSplitRatio: Math.min(0.9, Math.max(0.1, config.defaultEdgeSplitRatio ?? 0.2)),\n };\n })();\n\n // The state lives here, outside React: actions apply immediately, before or after any provider\n // mounts, and the provider reads it through useSyncExternalStore.\n const listeners = new Set<() => void>();\n const setState = (update: WorkspaceState | ((prev: WorkspaceState) => WorkspaceState)): void => {\n const prev = state;\n const next = typeof update === 'function' ? update(prev) : update;\n if (next === prev) return;\n state = next;\n listeners.forEach(listener => listener());\n };\n // Read-only view kept under the old name, so every `stateRef.current` read sees live state.\n const stateRef = { get current(): WorkspaceState { return state; } };\n const getSnapshot = (): WorkspaceState => state;\n const subscribeToState = (cb: () => void): (() => void) => {\n listeners.add(cb);\n return () => { listeners.delete(cb); };\n };\n\n const closeGuardsRef: { current: Record<string, () => boolean | Promise<boolean>> } = { current: {} };\n const stateProvidersRef: { current: Record<string, () => unknown> } = { current: {} };\n /** Hosted panels' close handlers, by panel id: the widget's overlay registers them (7.11.0). */\n const hostedCloseHandlersRef = { current: new Map<string, () => void>() };\n /** ...and what to call just before a layout load drops one (it never keeps a hosted panel). */\n const hostedDropHandlersRef = { current: new Map<string, () => void>() };\n\n const eventBusRef = { current: new PanelEventBus() };\n // Seeded from the restored windows (7.4.1): starting at the base, a focused restored window was\n // given a z below the others and dropped behind them, and a new float opened beneath them.\n const topZ = (floating: FloatingWindow[]): number =>\n floating.reduce((top, w) => (Number.isFinite(w.z) && w.z > top ? w.z : top), effectiveZIndexBase);\n const maxZRef = { current: topZ(state.floating) };\n\n const subscribe: InternalWindowActions['subscribe'] = (event, callback) => {\n return eventBusRef.current.subscribe(event, callback);\n };\n\n const publish: InternalWindowActions['publish'] = (event, data) => {\n eventBusRef.current.publish(event, data);\n };\n\n // Helper: Find free cascading location for floating window\n const getCascadedPosition = (\n fav: { x: number | string; y: number | string; width: number | string; height: number | string },\n currentFloating: FloatingWindow[]\n ) => {\n let x = typeof fav.x === 'string' ? parseFloat(fav.x) : fav.x;\n let y = typeof fav.y === 'string' ? parseFloat(fav.y) : fav.y;\n let width = typeof fav.width === 'string' ? parseFloat(fav.width) : fav.width;\n let height = typeof fav.height === 'string' ? parseFloat(fav.height) : fav.height;\n\n // Fallbacks if parseFloat fails and returns NaN\n if (isNaN(x)) x = 300;\n if (isNaN(y)) y = 150;\n if (isNaN(width)) width = 450;\n if (isNaN(height)) height = 350;\n\n const isOverlapping = (pos: { x: number; y: number }) => {\n return currentFloating.some(w => {\n const wx = typeof w.x === 'string' ? parseFloat(w.x) : w.x;\n const wy = typeof w.y === 'string' ? parseFloat(w.y) : w.y;\n return !w.maximized && Math.abs(wx - pos.x) < 20 && Math.abs(wy - pos.y) < 20;\n });\n };\n\n let attempts = 0;\n while (isOverlapping({ x, y }) && attempts < 10) {\n x += 30;\n y += 30;\n attempts++;\n }\n\n // Capture safe viewport boundaries (min 1024x768 fallback if not measured or in headless environments)\n // (and on the server, where a workspace can already be opened into before anything mounts)\n const viewW = Math.max(100, (typeof window !== 'undefined' && window.innerWidth) || 1024);\n const viewH = Math.max(100, (typeof window !== 'undefined' && window.innerHeight) || 768);\n\n if (x + width > viewW || y + height > viewH) {\n x = 100 + (attempts % 5) * 30;\n y = 100 + (attempts % 5) * 30;\n }\n\n // Final safety clamp to make sure window title bar is always visible and clickable\n x = Math.max(0, Math.min(x, viewW - 100));\n y = Math.max(0, Math.min(y, viewH - 40));\n\n return { x, y, width, height };\n };\n\n const focusPanel = (id: string, options?: { restore?: boolean }) => {\n // Restoring brings it back and focuses it, with restorePanel's events (7.11.0).\n if (options?.restore && stateRef.current.panels[id]?.state === 'minimized') {\n restorePanel(id);\n return;\n }\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n if (panel.state === 'floating') {\n const win = prev.floating.find(w => w.id === id);\n if (!win) return prev;\n const alreadyTop = !prev.floating.some(w => w.z > win.z);\n if (alreadyTop && prev.activePanelId === id) return prev; // no-op — StrictMode safe\n if (!alreadyTop) maxZRef.current += 1;\n return {\n ...prev,\n floating: prev.floating.map(w =>\n w.id === id ? { ...w, z: alreadyTop ? win.z : maxZRef.current } : w\n ),\n activePanelId: id\n };\n } else if (panel.state === 'docked') {\n if (prev.activePanelId === id) return prev; // no-op\n const selectActiveInTree = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.panels.includes(id)) {\n return { ...node, activePanelId: id };\n }\n return node;\n } else {\n return { ...node, children: node.children.map(selectActiveInTree) };\n }\n };\n return {\n ...prev,\n gridRoot: selectActiveInTree(prev.gridRoot),\n activePanelId: id\n };\n }\n if (prev.activePanelId === id) return prev; // no-op for minimized\n return { ...prev, activePanelId: id };\n });\n };\n\n\n // State transitions shared by more than one action. Each takes the previous state and returns\n // the next one (or `prev` itself when there is nothing to do), so an action can chain them\n // inside a single `setState` — maximizing a minimized panel is restore, then float, then\n // maximize, and must not render the intermediate states.\n\n /** Brings a minimized panel back where it was: its old floating rect, or its old group. */\n const applyRestore = (prev: WorkspaceState, id: string, activate: boolean): WorkspaceState => {\n const panel = prev.panels[id];\n if (!panel || panel.state !== 'minimized') return prev;\n\n const nextMinimized = prev.minimized.filter(m => m.id !== id);\n const prevState = panel.previousState || 'docked';\n // A restored panel is, by definition, visible again — so unlike the minimize path there is\n // nothing to derive: it is itself the only correct candidate. Leaving activePanelId behind\n // reproduced the 6de3381 defect class in reverse (visible tab rendered unfocused, and every\n // contributed control stayed bound to whatever replaced this panel while it was minimized).\n const nextActive = activate ? id : prev.activePanelId;\n const options = optionsFor(registry, panel);\n\n const floatBack = (): WorkspaceState => {\n maxZRef.current += 1;\n const favPos = panel.lastFloatingRect || options?.favoritePosition || { x: 300, y: 150, width: 450, height: 350 };\n const cascaded = getCascadedPosition(favPos, prev.floating);\n return {\n ...prev,\n minimized: nextMinimized,\n floating: [\n ...prev.floating,\n {\n ...cascaded,\n id,\n z: maxZRef.current,\n anchor: panel.lastFloatingRect?.anchor ?? null\n }\n ],\n panels: { ...prev.panels, [id]: { ...panel, state: 'floating' } },\n activePanelId: nextActive\n };\n };\n\n if (prevState === 'floating') return floatBack();\n\n if (panel.lastLeafId && hasLeaf(prev.gridRoot, panel.lastLeafId)) {\n return {\n ...prev,\n minimized: nextMinimized,\n gridRoot: addPanelToLeaf(prev.gridRoot, panel.lastLeafId, id),\n panels: { ...prev.panels, [id]: { ...panel, state: 'docked' } },\n activePanelId: nextActive\n };\n }\n // Leaf group ceased to exist: float it instead if floatable!\n if (options?.canDrag !== false) return floatBack();\n\n // Leaf group ceased to exist but not floatable: dock into fallback leaf group\n const targetLeafId = findFirstLeafId(prev.gridRoot) || 'group-default';\n return {\n ...prev,\n minimized: nextMinimized,\n gridRoot: addPanelToLeaf(prev.gridRoot, targetLeafId, id),\n panels: { ...prev.panels, [id]: { ...panel, state: 'docked' } },\n activePanelId: nextActive\n };\n };\n\n /** Turns a docked panel into a floating window. Refused for `canDrag: false` panels. */\n const applyFloat = (\n prev: WorkspaceState,\n id: string,\n { rect, anchor, activate = true }: { rect?: { x: number; y: number; width: number; height: number }; anchor?: FloatAnchor | null; activate?: boolean } = {},\n ): WorkspaceState => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n const options = optionsFor(registry, panel);\n if (options?.canDrag === false) return prev;\n\n const favPos = rect || options?.favoritePosition || DEFAULT_FLOAT_RECT;\n const cleanRoot = removePanelFromTree(prev.gridRoot, id);\n // Floating an already-floating panel re-places it rather than adding a second window.\n const otherWindows = prev.floating.filter(w => w.id !== id);\n maxZRef.current += 1;\n const cascaded = getCascadedPosition(favPos, otherWindows);\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: cleanRoot || { type: 'leaf', id: 'group-default', panels: [], activePanelId: null },\n floating: [...otherWindows, { ...cascaded, id, z: maxZRef.current, anchor: anchor ?? null }],\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'floating' }\n }\n };\n return { ...next, activePanelId: resolveActivePanelId(next, activate ? id : null) };\n };\n\n /** Docks a panel into `targetLeafId`, or the first group when that id is missing. */\n const applyDock = (prev: WorkspaceState, id: string, targetLeafId?: string, activate = true): WorkspaceState => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n const nextFloating = prev.floating.filter(w => w.id !== id);\n const cleanRoot = removePanelFromTree(prev.gridRoot, id) || EMPTY_LEAF;\n // The caller asked for this panel to be docked, so an id that no longer names a group\n // falls back to the first one rather than docking it nowhere. Removing the panel can\n // itself delete the requested group, which is why this is checked against `cleanRoot`.\n const requested = targetLeafId && hasLeaf(cleanRoot, targetLeafId) ? targetLeafId : undefined;\n const leafId = requested || findFirstLeafId(cleanRoot) || EMPTY_LEAF.id;\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: addPanelToLeaf(cleanRoot, leafId, id),\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'docked' }\n }\n };\n return { ...next, activePanelId: resolveActivePanelId(next, activate ? id : null) };\n };\n\n const openPanel = <P extends object = Record<string, unknown>>(id: string, component: string, options?: OpenPanelOptions<P>) => {\n // Dedup redirect: resolve to an already-open panel of the same component/dedupeKey, if any,\n // before anything else runs — the caller's own `id`/`props` are ignored for this call in\n // that case, the same way re-opening an already-open exact `id` already focuses it instead\n // of duplicating it.\n let resolvedId = id;\n if (options?.dedupeKey !== undefined) {\n const match = Object.values(stateRef.current.panels).find(\n p => p.component === component && p.dedupeKey === options.dedupeKey\n );\n if (match) resolvedId = match.id;\n }\n const isNew = !(resolvedId in stateRef.current.panels);\n const isRedirect = resolvedId !== id;\n const shouldFocus = options?.focus !== false;\n const propsProvided = options?.props !== undefined;\n const serializable = propsProvided ? isSerializable(options.props) : true;\n\n // Re-opening a minimized panel is a restore, and must land where `restorePanel` would: its\n // old group or floating rect. This used to re-place it from the registry's initial target\n // (the first group, or the default floating position) and publish nothing, so an autosave\n // keyed on `layout:changed` missed it. An explicit `initialTarget` still wins.\n if (stateRef.current.panels[resolvedId]?.state === 'minimized') {\n const explicitTarget = options?.initialTarget;\n setState(prev => {\n const restored = applyRestore(prev, resolvedId, shouldFocus);\n const state = restored.panels[resolvedId]?.state;\n if (explicitTarget === 'floating' && state === 'docked') {\n return applyFloat(restored, resolvedId, { activate: shouldFocus });\n }\n if (explicitTarget && explicitTarget !== 'floating' && state === 'floating') {\n return applyDock(restored, resolvedId, undefined, shouldFocus);\n }\n return restored;\n });\n eventBusRef.current.publish('panel:restored', { id: resolvedId });\n eventBusRef.current.publish('layout:changed', {});\n return;\n }\n\n const dockTo = options?.dockTo;\n if (dockTo && isNew && process.env.NODE_ENV === 'development' && !findLeafIdOf(stateRef.current.gridRoot, dockTo.panel)) {\n console.warn(\n `[react-dockable-desktop] openPanel(\"${resolvedId}\") could not dock beside \"${dockTo.panel}\": ` +\n `that panel is not docked (not open, floating or minimized), so the new panel was placed as usual.`\n );\n }\n\n setState(prev => {\n const exists = prev.panels[resolvedId];\n const entry = registry.get(component);\n const title = options?.title || entry?.defaultOptions?.title || resolvedId;\n const target = options?.initialTarget || entry?.defaultOptions?.initialTarget || 'docked';\n const favPos = entry?.defaultOptions?.favoritePosition || { x: 300, y: 150, width: 450, height: 350 };\n const activePanelId = shouldFocus ? resolvedId : prev.activePanelId;\n\n // Case 1: Already exists (a minimized one was handled above, before this update)\n if (exists) {\n if (exists.state === 'minimized') {\n return applyRestore(prev, resolvedId, shouldFocus);\n } else if (exists.state === 'floating') {\n if (shouldFocus) focusPanel(resolvedId);\n return prev;\n } else {\n // Focus in tab group\n const selectActiveInTree = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.panels.includes(resolvedId)) {\n return { ...node, activePanelId: resolvedId };\n }\n return node;\n } else {\n return { ...node, children: node.children.map(selectActiveInTree) };\n }\n };\n return {\n ...prev,\n gridRoot: selectActiveInTree(prev.gridRoot),\n activePanelId\n };\n }\n }\n\n // Case 2: New panel. `dockTo` beside a docked panel wins over the target.\n const dockLeaf = dockTo ? findLeafIdOf(prev.gridRoot, dockTo.panel) : null;\n const targetState = dockLeaf ? 'docked' : (target === 'tabbed' ? 'docked' : target);\n const newPanelInfo: PanelInfo = {\n id: resolvedId,\n title,\n component,\n state: targetState,\n props: options?.props as Record<string, unknown> | undefined,\n serializable,\n dedupeKey: options?.dedupeKey,\n };\n const nextPanels = { ...prev.panels, [resolvedId]: newPanelInfo };\n\n if (dockTo && dockLeaf) {\n const share = Math.min(0.9, Math.max(0.1, dockTo.size ?? prev.splitRatio));\n return {\n ...prev,\n gridRoot: dockTo.position === 'center'\n ? addPanelToLeaf(prev.gridRoot, dockLeaf, resolvedId)\n : splitLeafInTree(prev.gridRoot, dockLeaf, resolvedId, dockTo.position, share),\n panels: nextPanels,\n activePanelId\n };\n }\n\n if (target === 'floating') {\n maxZRef.current += 1;\n const cascaded = getCascadedPosition(favPos, prev.floating);\n\n const anchor = options?.anchor ?? entry?.defaultOptions?.defaultAnchor ?? null;\n\n return {\n ...prev,\n floating: [...prev.floating, { ...cascaded, id: resolvedId, z: maxZRef.current, anchor }],\n panels: nextPanels,\n activePanelId\n };\n } else {\n const firstLeaf = findFirstLeafId(prev.gridRoot) || 'group-default';\n return {\n ...prev,\n gridRoot: addPanelToLeaf(prev.gridRoot, firstLeaf, resolvedId),\n panels: nextPanels,\n activePanelId\n };\n }\n });\n if (isNew) eventBusRef.current.publish('panel:opened', { id: resolvedId, component });\n if (isNew || isRedirect) eventBusRef.current.publish('layout:changed', {});\n };\n\n /** The state without panel `id`, wherever it was; its guard and state provider are dropped. */\n const withoutPanel = (prev: WorkspaceState, id: string): WorkspaceState => {\n delete closeGuardsRef.current[id];\n delete stateProvidersRef.current[id];\n\n const nextPanels = { ...prev.panels };\n delete nextPanels[id];\n\n const nextRoot = removePanelFromTree(prev.gridRoot, id)\n || { type: 'leaf' as const, id: 'group-default', panels: [], activePanelId: null };\n const nextFloating = prev.floating.filter(w => w.id !== id);\n\n // Closing the active panel used to leave `activePanelId` pointing at the panel just deleted.\n // `removePanelFromTree` has already promoted the next tab in its leaf, so re-deriving picks\n // whatever the user can now actually see.\n const nextActivePanelId = prev.activePanelId === id\n ? deriveActivePanelId({ gridRoot: nextRoot, floating: nextFloating, panels: nextPanels })\n : prev.activePanelId;\n\n return {\n ...prev,\n gridRoot: nextRoot,\n floating: nextFloating,\n minimized: prev.minimized.filter(m => m.id !== id),\n panels: nextPanels,\n activePanelId: nextActivePanelId\n };\n };\n\n const closePanel = (id: string) => {\n const panel = stateRef.current.panels[id];\n setState(prev => {\n const current = prev.panels[id];\n if (!current || optionsFor(registry, current)?.canClose === false) return prev;\n return withoutPanel(prev, id);\n });\n // Published whenever the panel existed, even if `canClose: false` refused it: unchanged.\n if (panel) {\n eventBusRef.current.publish('panel:closed', { id });\n eventBusRef.current.publish('layout:changed', {});\n // A hosted panel closed from the page (×, menu, the app's closePanel): its widget closes\n // too (7.11.0). A hosted panel can always close. The handler belongs to the widget's overlay.\n if (panel.owner) hostedCloseHandlersRef.current.get(id)?.();\n }\n };\n\n // ── Hosted panels (7.11.0): a managed widget moved out of its owner panel ──\n // They exist only at runtime: saveLayout skips them and loadLayout never creates one.\n\n const openHostedPanel = (id: string, owner: PanelOwner, title: PanelInfo['title'], at: HostedPanelPlacement): boolean => {\n const now = stateRef.current;\n if (id in now.panels) return false;\n const leaf = at.kind === 'dock' ? findLeafIdOf(now.gridRoot, at.dockTo.panel) : null;\n if (at.kind === 'dock' && !leaf) return false;\n const info: PanelInfo = { id, title, component: HOSTED_COMPONENT, state: at.kind === 'dock' ? 'docked' : 'floating', serializable: false, owner };\n if (at.kind === 'float') maxZRef.current += 1;\n const z = maxZRef.current;\n setState(prev => {\n if (id in prev.panels) return prev;\n const panels = { ...prev.panels, [id]: info };\n if (at.kind === 'float') {\n return { ...prev, panels, floating: [...prev.floating, { ...at.rect, id, z, anchor: null }], activePanelId: id };\n }\n const target = findLeafIdOf(prev.gridRoot, at.dockTo.panel);\n if (!target) return prev;\n const share = Math.min(0.9, Math.max(0.1, at.dockTo.size ?? prev.splitRatio));\n const gridRoot = at.dockTo.position === 'center'\n ? addPanelToLeaf(prev.gridRoot, target, id)\n : splitLeafInTree(prev.gridRoot, target, id, at.dockTo.position, share);\n return { ...prev, panels, gridRoot, activePanelId: id };\n });\n eventBusRef.current.publish('panel:opened', { id, component: HOSTED_COMPONENT });\n eventBusRef.current.publish('layout:changed', {});\n return true;\n };\n\n const removeHostedPanel = (id: string) => {\n if (!stateRef.current.panels[id]?.owner) return;\n setState(prev => (prev.panels[id]?.owner ? withoutPanel(prev, id) : prev));\n eventBusRef.current.publish('panel:closed', { id });\n eventBusRef.current.publish('layout:changed', {});\n };\n\n const setHostedOptions = (id: string, options: NonNullable<PanelOwner['options']>) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel?.owner) return prev;\n const was = panel.owner.options;\n if (was?.canFloat === options.canFloat && was?.canDock === options.canDock) return prev;\n return { ...prev, panels: { ...prev.panels, [id]: { ...panel, owner: { ...panel.owner, options } } } };\n });\n };\n\n const registerHostedCloseHandler = (id: string, onClose: () => void, onDrop?: () => void) => {\n hostedCloseHandlersRef.current.set(id, onClose);\n if (onDrop) hostedDropHandlersRef.current.set(id, onDrop);\n return () => {\n if (hostedCloseHandlersRef.current.get(id) === onClose) hostedCloseHandlersRef.current.delete(id);\n if (onDrop && hostedDropHandlersRef.current.get(id) === onDrop) hostedDropHandlersRef.current.delete(id);\n };\n };\n\n const registerCloseGuard = (id: string, guard: () => boolean | Promise<boolean>) => {\n closeGuardsRef.current[id] = guard;\n };\n\n const unregisterCloseGuard = (id: string) => {\n delete closeGuardsRef.current[id];\n };\n\n const registerStateProvider = (id: string, provider: () => unknown) => {\n stateProvidersRef.current[id] = provider;\n };\n\n const unregisterStateProvider = (id: string) => {\n delete stateProvidersRef.current[id];\n };\n\n const setPanelDirty = (id: string, dirty: boolean, options?: DirtyStateOptions) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n if (!!panel.dirty === dirty && sameDirtyOptions(panel.dirtyOptions, options)) return prev;\n return {\n ...prev,\n panels: {\n ...prev.panels,\n [id]: { ...panel, dirty, dirtyOptions: options }\n }\n };\n });\n };\n\n const updatePanelTitle = (id: string, title: string | MessageDescriptor | (() => string)) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n if (sameTitle(panel.title, title)) return prev;\n return {\n ...prev,\n panels: {\n ...prev.panels,\n [id]: { ...panel, title }\n }\n };\n });\n };\n\n const updatePanelProps = (id: string, props: Record<string, unknown> | ((prev: Record<string, unknown> | undefined) => Record<string, unknown>)) => {\n const panel = stateRef.current.panels[id];\n if (!panel || panel.owner) return; // a hosted panel has no props of its own\n const next = typeof props === 'function' ? props(panel.props) : props;\n setState(prev => {\n const p = prev.panels[id];\n if (!p) return prev;\n return { ...prev, panels: { ...prev.panels, [id]: { ...p, props: next, serializable: isSerializable(next) } } };\n });\n eventBusRef.current.publish('layout:changed', {});\n };\n\n const setPanelIcon = (id: string, icon: React.ReactNode | null) => {\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n const next = icon ?? undefined;\n if (panel.icon === next) return prev;\n return { ...prev, panels: { ...prev.panels, [id]: { ...panel, icon: next } } };\n });\n };\n\n const requestClosePanel = async (id: string, options?: { force?: boolean; onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }) => {\n if (options?.force) {\n closePanel(id);\n return;\n }\n\n // 1. Check custom close guard\n const guard = closeGuardsRef.current[id];\n if (guard) {\n const canClose = await guard();\n if (!canClose) return;\n }\n\n // 2. Check automatic dirty flag\n const panel = stateRef.current.panels[id];\n if (panel?.dirty) {\n if (options?.onConfirm) {\n const discard = await options.onConfirm(panel.dirtyOptions);\n if (!discard) return;\n } else {\n return;\n }\n }\n\n closePanel(id);\n };\n\n const minimizePanel = (id: string) => {\n const wasActive = stateRef.current.panels[id]?.state !== 'minimized' && id in stateRef.current.panels;\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel || panel.state === 'minimized') return prev;\n\n if (optionsFor(registry, panel)?.canMinimize === false) {\n return prev;\n }\n\n let lastFloatingRect: PanelInfo['lastFloatingRect'] = undefined;\n let lastLeafId: string | undefined = undefined;\n\n if (panel.state === 'floating') {\n const win = prev.floating.find(w => w.id === id);\n if (win) {\n lastFloatingRect = {\n x: Number(win.x),\n y: Number(win.y),\n width: Number(win.width),\n height: Number(win.height),\n anchor: win.anchor ?? null\n };\n }\n } else if (panel.state === 'docked') {\n const findLeafForPanel = (node: LayoutNode): string | null => {\n if (node.type === 'leaf') {\n return node.panels.includes(id) ? node.id : null;\n } else {\n for (const child of node.children) {\n const res = findLeafForPanel(child);\n if (res) return res;\n }\n return null;\n }\n };\n lastLeafId = findLeafForPanel(prev.gridRoot) ?? undefined;\n }\n\n const nextRoot = removePanelFromTree(prev.gridRoot, id)\n || { type: 'leaf' as const, id: 'group-default', panels: [], activePanelId: null };\n const nextFloating = prev.floating.filter(w => w.id !== id);\n const nextPanels: Record<string, PanelInfo> = {\n ...prev.panels,\n [id]: {\n ...panel,\n state: 'minimized',\n previousState: panel.state,\n lastFloatingRect,\n lastLeafId\n }\n };\n\n // A minimized panel is off screen but still mounted (see the persistence port in\n // WindowManager.tsx), so leaving it active kept `useActivePanelContribution()` — and every\n // contributed control — wired to a panel the user can't see. `deriveActivePanelId` skips\n // minimized panels, so this lands on whatever became visible in its place.\n const nextActivePanelId = prev.activePanelId === id\n ? deriveActivePanelId({ gridRoot: nextRoot, floating: nextFloating, panels: nextPanels })\n : prev.activePanelId;\n\n return {\n ...prev,\n gridRoot: nextRoot,\n floating: nextFloating,\n minimized: [...prev.minimized, { id, title: panel.title, component: panel.component }],\n panels: nextPanels,\n activePanelId: nextActivePanelId\n };\n });\n if (wasActive) {\n eventBusRef.current.publish('panel:minimized', { id });\n eventBusRef.current.publish('layout:changed', {});\n }\n };\n\n const restorePanel = (id: string, options?: { focus?: boolean }) => {\n const wasMinimized = stateRef.current.panels[id]?.state === 'minimized';\n const shouldFocus = options?.focus !== false;\n setState(prev => applyRestore(prev, id, shouldFocus));\n if (wasMinimized) {\n eventBusRef.current.publish('panel:restored', { id });\n eventBusRef.current.publish('layout:changed', {});\n }\n };\n\n const floatPanel = (id: string, rect?: { x: number; y: number; width: number; height: number }, anchor?: FloatAnchor | null) => {\n const panel = stateRef.current.panels[id];\n const willFloat = !!panel && optionsFor(registry, panel)?.canDrag !== false;\n setState(prev => applyFloat(prev, id, { rect, anchor }));\n if (willFloat) eventBusRef.current.publish('layout:changed', {});\n };\n\n const dockPanel = (id: string, targetLeafId?: string) => {\n const exists = id in stateRef.current.panels;\n setState(prev => applyDock(prev, id, targetLeafId));\n if (exists) eventBusRef.current.publish('layout:changed', {});\n };\n\n\n const setDraggedPanelId = (id: string | null) => {\n setState(prev => ({ ...prev, draggedPanelId: id }));\n };\n\n const dockPanelToGroup = (id: string, targetLeafId: string, position: DropPosition) => {\n const before = stateRef.current;\n const willMove = id in before.panels\n && hasLeaf(before.gridRoot, targetLeafId)\n && !isLoneOccupant(before.gridRoot, targetLeafId, id);\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n // Dropping a lone panel onto its own group asks for the layout it already has. Taking\n // it literally deletes the target leaf on the way in, and the split then ran against\n // the pre-removal tree, leaving the same panel in two leaves — one of them showing\n // nothing, since a panel's DOM can only live in one slot.\n if (isLoneOccupant(prev.gridRoot, targetLeafId, id)) return prev;\n\n // A group that is not in the tree cannot receive anything. Placing into it would strip\n // the panel from the layout and leave it \"open\" but in no group — visible nowhere, and\n // recoverable only by minimizing and restoring it.\n if (!hasLeaf(prev.gridRoot, targetLeafId)) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] dockPanelToGroup(\"${id}\", \"${targetLeafId}\") was ignored: ` +\n `no group with that id is in the layout. Emptying a group removes it, so an id held ` +\n `across a layout change can name a group that no longer exists.`\n );\n }\n return prev;\n }\n\n const nextFloating = prev.floating.filter(w => w.id !== id);\n // `null` from removePanelFromTree means the tree is now empty — not \"nothing was\n // removed\". Falling back to `prev.gridRoot` here is what put the panel in two leaves.\n const cleanRoot = removePanelFromTree(prev.gridRoot, id) || EMPTY_LEAF;\n\n let newRoot: LayoutNode;\n if (position === 'center') {\n newRoot = addPanelToLeaf(cleanRoot, targetLeafId, id);\n } else {\n newRoot = splitLeafInTree(cleanRoot, targetLeafId, id, position, prev.splitRatio);\n }\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: newRoot,\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'docked' }\n },\n draggedPanelId: null\n };\n return { ...next, activePanelId: resolveActivePanelId(next, id) };\n });\n if (willMove) eventBusRef.current.publish('layout:changed', {});\n };\n\n const dockPanelToWorkspaceEdge = (id: string, position: SplitDirection) => {\n const before = stateRef.current;\n const willMove = id in before.panels && removePanelFromTree(before.gridRoot, id) !== null;\n setState(prev => {\n const panel = prev.panels[id];\n if (!panel) return prev;\n\n const nextFloating = prev.floating.filter(w => w.id !== id);\n const cleanRoot = removePanelFromTree(prev.gridRoot, id);\n\n // The sole docked panel already fills the workspace, so docking it to an edge asks for\n // the layout it has. Acting on it duplicated the panel into the new edge leaf while the\n // old one still listed it, exactly as a drop on its own group did.\n if (cleanRoot === null) return prev;\n\n const newLeaf: LayoutLeafNode = {\n type: 'leaf',\n id: `group-edge-${Date.now()}-${Math.floor(Math.random() * 1000)}`,\n panels: [id],\n activePanelId: id\n };\n\n const orientation: SplitOrientation = (position === 'left' || position === 'right') ? 'horizontal' : 'vertical';\n const children = (position === 'left' || position === 'top')\n ? [newLeaf, cleanRoot]\n : [cleanRoot, newLeaf];\n\n const r = prev.edgeSplitRatio;\n const newRoot: LayoutNode = {\n type: 'branch',\n orientation,\n sizes: (position === 'left' || position === 'top') ? [r, 1 - r] : [1 - r, r],\n children\n };\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: newRoot,\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [id]: { ...panel, state: 'docked' }\n },\n draggedPanelId: null\n };\n return { ...next, activePanelId: resolveActivePanelId(next, id) };\n });\n if (willMove) eventBusRef.current.publish('layout:changed', {});\n };\n\n const movePanelOrder = (panelId: string, targetLeafId: string, targetIndex: number) => {\n const before = stateRef.current;\n const willMove = panelId in before.panels\n && hasLeaf(before.gridRoot, targetLeafId)\n && !isLoneOccupant(before.gridRoot, targetLeafId, panelId);\n setState(prev => {\n const panel = prev.panels[panelId];\n if (!panel) return prev;\n\n // A lone panel dropped on its own tab strip is already where it is being sent. Today\n // the reinsertion happens to cancel out; guarded so that stays true rather than\n // depending on it.\n if (isLoneOccupant(prev.gridRoot, targetLeafId, panelId)) return prev;\n\n if (!hasLeaf(prev.gridRoot, targetLeafId)) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] movePanelOrder(\"${panelId}\", \"${targetLeafId}\") was ignored: ` +\n `no group with that id is in the layout.`\n );\n }\n return prev;\n }\n\n // 1. Remove panel from its current group in the layout tree\n const cleanRoot = removePanelFromTree(prev.gridRoot, panelId);\n\n // 2. Insert panel at specific index in target leaf ID\n const insertInLeaf = (node: LayoutNode): LayoutNode => {\n if (node.type === 'leaf') {\n if (node.id === targetLeafId) {\n const remaining = node.panels.filter(p => p !== panelId);\n const index = Math.max(0, Math.min(targetIndex, remaining.length));\n const newPanels = [...remaining];\n newPanels.splice(index, 0, panelId);\n return {\n ...node,\n panels: newPanels,\n activePanelId: panelId\n };\n }\n return node;\n } else {\n return {\n ...node,\n children: node.children.map(insertInLeaf)\n };\n }\n };\n\n const newRoot = insertInLeaf(cleanRoot || EMPTY_LEAF);\n const nextFloating = prev.floating.filter(w => w.id !== panelId);\n\n const next: WorkspaceState = {\n ...prev,\n gridRoot: newRoot,\n floating: nextFloating,\n panels: {\n ...prev.panels,\n [panelId]: { ...panel, state: 'docked' }\n },\n draggedPanelId: null\n };\n return { ...next, activePanelId: resolveActivePanelId(next, panelId) };\n });\n if (willMove) eventBusRef.current.publish('layout:changed', {});\n };\n\n const closeLeafGroup = async (leafId: string, options?: { onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }) => {\n const findLeaf = (node: LayoutNode): LayoutLeafNode | null => {\n if (node.type === 'leaf') return node.id === leafId ? node : null;\n for (const child of node.children) {\n const found = findLeaf(child);\n if (found) return found;\n }\n return null;\n };\n\n const leaf = findLeaf(stateRef.current.gridRoot);\n if (!leaf || leaf.canClose === false) return;\n\n // Closing a group closes its tabs, each through the same guarded path as the tab's own ×:\n // a close guard can refuse, and a dirty panel is kept unless `onConfirm` agrees. Removing\n // the leaf outright used to leave its panels \"open\" but in no group — rendered nowhere.\n for (const panelId of [...leaf.panels]) {\n await requestClosePanel(panelId, { onConfirm: options?.onConfirm });\n }\n\n const removeLeafFromTree = (node: LayoutNode): LayoutNode | null => {\n if (node.type === 'leaf') {\n return node.id === leafId ? null : node;\n }\n const children = node.children\n .map(c => removeLeafFromTree(c))\n .filter((c): c is LayoutNode => c !== null);\n\n if (children.length === 0) return null;\n if (children.length === 1) return children[0];\n\n // Re-normalize sizes\n const sizes = node.sizes.slice(0, children.length);\n const sum = sizes.reduce((a, b) => a + b, 0);\n return {\n ...node,\n children,\n sizes: sizes.map(s => s / sum)\n };\n };\n\n // A panel that refused to close keeps its group. An emptied `keepOnEmpty` group is still in\n // the tree at this point, and is the one case left to remove here.\n // Each closed tab already published its own layout:changed; publish here only if this step\n // changed the layout too.\n let removed = false;\n setState(prev => {\n const current = findLeaf(prev.gridRoot);\n if (!current || current.panels.length > 0) return prev;\n removed = true;\n const next: WorkspaceState = {\n ...prev,\n gridRoot: removeLeafFromTree(prev.gridRoot) || { type: 'leaf', id: 'group-default', panels: [], activePanelId: null }\n };\n return { ...next, activePanelId: resolveActivePanelId(next, null) };\n });\n if (removed) eventBusRef.current.publish('layout:changed', {});\n };\n\n const maximizePanel = (id: string) => {\n const panel = stateRef.current.panels[id];\n if (!panel) return;\n\n if (panel.state === 'minimized') {\n // \"Maximize\" on a minimized panel (the taskbar menu offers it) is restore + maximize.\n // Only floating windows maximize, so a panel that comes back docked is floated first —\n // unless it can't be dragged, in which case it is just restored to its group. The\n // taskbar menu hides the item for that case.\n setState(prev => {\n const restored = applyRestore(prev, id, true);\n if (restored === prev) return prev;\n let next = restored;\n if (restored.panels[id]?.state === 'docked') {\n next = applyFloat(restored, id);\n if (next === restored) return restored;\n }\n return {\n ...next,\n floating: next.floating.map(w => w.id === id ? { ...w, maximized: true } : w),\n activePanelId: id\n };\n });\n eventBusRef.current.publish('panel:restored', { id });\n eventBusRef.current.publish('layout:changed', {});\n return;\n }\n\n if (panel.state === 'docked') {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[react-dockable-desktop] maximizePanel(\"${id}\") was ignored: only floating windows can ` +\n `be maximized. Float the panel first with floatPanel(\"${id}\").`\n );\n }\n return;\n }\n\n setState(prev => ({\n ...prev,\n floating: prev.floating.map(w => w.id === id ? { ...w, maximized: !w.maximized } : w)\n }));\n };\n\n const updateSplitSizes = (path: number[], sizes: number[]) => {\n const updateInTree = (node: LayoutNode, depth: number): LayoutNode => {\n if (node.type === 'leaf') return node;\n if (depth === path.length) {\n return { ...node, sizes };\n }\n const idx = path[depth];\n const children = node.children.map((c, i) => i === idx ? updateInTree(c, depth + 1) : c);\n return { ...node, children };\n };\n\n setState(prev => ({\n ...prev,\n gridRoot: updateInTree(prev.gridRoot, 0)\n }));\n };\n\n const updateFloatingPosition = (id: string, updates: Partial<Pick<FloatingWindow, 'x' | 'y' | 'width' | 'height' | 'anchor'>>) => {\n setState(prev => ({\n ...prev,\n floating: prev.floating.map(w => w.id === id ? { ...w, ...updates } : w)\n }));\n };\n\n // Docking rules (7.9.0): what the *user* may do. The type's own canFloat / canDock first, then\n // the app's canDrop. Never consulted by the app's own API calls.\n const isDropAllowed = (panelId: string, to: PanelDropTarget): boolean => {\n const panel = stateRef.current.panels[panelId];\n if (!panel) return false;\n const options = optionsFor(registry, panel);\n if (to.kind === 'float') {\n // Blocks *becoming* floating; a window that already floats may still change corner.\n if (options?.canFloat === false && panel.state !== 'floating') return false;\n } else if (options?.canDock === false) {\n return false;\n }\n if (!config.canDrop) return true;\n try {\n return config.canDrop({ panelId, component: panel.component, to }) !== false;\n } catch (e) {\n console.error('[react-dockable-desktop] canDrop threw; the move is allowed:', e);\n return true;\n }\n };\n\n const saveLayout = () => {\n const currentPanels = stateRef.current.panels;\n const excludedIds: string[] = [];\n // Hosted panels (7.11.0) are never saved and never reported as excluded: the owner panel\n // saves its widgets itself.\n const hostedIds: string[] = [];\n const includedPanels: Record<string, PanelInfo> = {};\n\n // A registered state provider (see registerStateProvider) is pulled fresh on every save —\n // a panel's serializability can flip over its lifetime, so this is never cached from open\n // time for provider-backed panels. Panels with no provider keep their static open-time\n // props/serializable classification unchanged.\n for (const [id, info] of Object.entries(currentPanels)) {\n if (info.owner || info.component === HOSTED_COMPONENT) { hostedIds.push(id); continue; }\n const provider = stateProvidersRef.current[id];\n const dynamicValue = provider?.();\n const hasDynamicValue = provider !== undefined && dynamicValue !== undefined;\n const effectiveProps = hasDynamicValue ? (dynamicValue as Record<string, unknown>) : info.props;\n const effectiveSerializable = hasDynamicValue ? isSerializable(dynamicValue) : info.serializable;\n\n if (effectiveSerializable) {\n // The runtime icon is a React element: never part of a saved layout.\n const { icon: _icon, ...saved } = info;\n // A function title (7.4.0) can't be saved; the restored panel takes its registered default.\n if (typeof saved.title === 'function') delete (saved as Partial<PanelInfo>).title;\n includedPanels[id] = hasDynamicValue ? { ...saved, props: effectiveProps, serializable: effectiveSerializable } : saved;\n } else {\n excludedIds.push(id);\n }\n }\n\n // Non-serializable panels are excluded from this saved snapshot — pruned from gridRoot/\n // floating/minimized too, so a restore never references a panel with no data to recreate it\n // meaningfully. This computes a derived copy for the JSON string only; none of this touches\n // stateRef/setState, so the live, on-screen workspace is completely unaffected — an excluded\n // panel keeps existing and working normally on screen, it simply won't be there after the\n // *next* loadLayout().\n let gridRoot = stateRef.current.gridRoot;\n let floating = stateRef.current.floating;\n let minimized = stateRef.current.minimized;\n for (const id of [...excludedIds, ...hostedIds]) {\n gridRoot = removePanelFromTree(gridRoot, id) || { type: 'leaf', id: 'group-default', panels: [], activePanelId: null };\n floating = floating.filter(w => w.id !== id);\n minimized = minimized.filter(m => m.id !== id);\n }\n\n if (excludedIds.length > 0) {\n eventBusRef.current.publish('layout:panels-excluded', {\n panels: excludedIds.map(id => ({ id, component: currentPanels[id].component }))\n });\n }\n\n // Validated against the *pruned* snapshot, not the live state: if the active panel was itself\n // excluded above, or is minimized, the field is omitted entirely rather than persisted as an id\n // this payload's own `panels` doesn't contain. A restore then derives it — see\n // `deriveActivePanelId`.\n const liveActive = stateRef.current.activePanelId;\n const activePanelId = liveActive !== null && isVisibleActiveTarget(liveActive, { gridRoot, floating, panels: includedPanels })\n ? liveActive\n : null;\n\n const payload: SerializedLayout = {\n version: 2, // v2: panels may carry `props`/`dedupeKey`; the payload may omit panels the\n // live workspace still has open (see the exclusion pass above).\n ...(activePanelId !== null ? { activePanelId } : {}),\n gridRoot,\n floating,\n minimized: minimized.map(m => (typeof m.title === 'function' ? { id: m.id, component: m.component } : m)) as SerializedLayout['minimized'],\n panels: includedPanels\n };\n return JSON.stringify(payload);\n };\n\n const loadLayout = (layoutJson: string): boolean => {\n try {\n const parsed = parseLayoutPayload(JSON.parse(layoutJson));\n if (!parsed) return false;\n const payload = withoutHostedPanels(parsed);\n // The live hosted panels are about to go: tell their owners first, while their content is still in place.\n for (const [id, panel] of Object.entries(stateRef.current.panels)) {\n if (panel.owner) hostedDropHandlersRef.current.get(id)?.();\n }\n maxZRef.current = Math.max(maxZRef.current, topZ(payload.floating));\n setState(prev => {\n // A panel that stays open keeps its runtime icon: the component that set it isn't\n // re-mounted, so it wouldn't set it again.\n const panels: Record<string, PanelInfo> = {};\n for (const [id, saved] of Object.entries(payload.panels)) {\n // A panel saved without a title — it had a function title, which a layout can't hold —\n // takes its registered default title, as a newly opened one would.\n const info = saved.title ? saved : { ...saved, title: registry.get(saved.component)?.defaultOptions?.title || id };\n // An `owner` can only come from a hand-made layout: a hosted panel is never saved.\n if ('owner' in info) delete (info as Partial<PanelInfo>).owner;\n const was = prev.panels[id];\n panels[id] = was?.icon !== undefined && was.component === info.component ? { ...info, icon: was.icon } : info;\n }\n const titleOf = (m: { id: string; title?: PanelInfo['title'] }) => m.title || panels[m.id]?.title || m.id;\n return {\n ...prev,\n gridRoot: payload.gridRoot,\n floating: payload.floating,\n minimized: payload.minimized.map(m => (m.title ? m : { ...m, title: titleOf(m) })),\n panels,\n draggedPanelId: null,\n activePanelId: payload.activePanelId\n };\n });\n return true;\n } catch (e) {\n console.error('Failed to parse layout configuration:', e);\n return false;\n }\n };\n\n const setActivePanel = (id: string | null) => {\n setState(prev => {\n if (prev.activePanelId === id) return prev;\n return { ...prev, activePanelId: id };\n });\n };\n\n const setDirection = (dir: 'ltr' | 'rtl') => {\n setState(prev => {\n if (prev.dir === dir) return prev;\n return { ...prev, dir, isRtl: dir === 'rtl' };\n });\n };\n\n const isOpen = (id: string) => id in stateRef.current.panels;\n\n const getOpenPanelIds = () => Object.keys(stateRef.current.panels);\n\n const findPanelId = (component: string, dedupeKey: string): string | null => {\n const match = Object.values(stateRef.current.panels).find(\n p => p.component === component && p.dedupeKey === dedupeKey\n );\n return match?.id ?? null;\n };\n\n const customMenuGettersRef: { current: Map<string, () => ContextMenuItem[]> } = { current: new Map() };\n\n const showContextMenuFnRef: { current: ((options: ShowContextMenuOptions) => void) | null } = { current: null };\n const registerContextMenuFn = (fn: (options: ShowContextMenuOptions) => void) => {\n showContextMenuFnRef.current = fn;\n return () => { showContextMenuFnRef.current = null; };\n };\n // The menu is portaled out of the workspace: tell it the workspace's direction, for a menu opened\n // without an event to take it from (the menu prefers the event's target when there is one).\n const showContextMenu = (options: ShowContextMenuOptions) => {\n showContextMenuFnRef.current?.({ dir: stateRef.current.dir, ...options });\n };\n\n const registerPanelContextMenu = (panelId: string, getItems: () => ContextMenuItem[]) => {\n customMenuGettersRef.current.set(panelId, getItems);\n return () => { customMenuGettersRef.current.delete(panelId); };\n };\n\n const getPanelContextMenuItems = (panelId: string): ContextMenuItem[] =>\n customMenuGettersRef.current.get(panelId)?.() ?? [];\n\n const actions: InternalWindowActions = {\n openPanel,\n closePanel,\n minimizePanel,\n restorePanel,\n floatPanel,\n dockPanel,\n maximizePanel,\n updateSplitSizes,\n updateFloatingPosition,\n isDropAllowed,\n focusPanel,\n updatePanelProps,\n isOpen,\n getOpenPanelIds,\n findPanelId,\n saveLayout,\n loadLayout,\n publish,\n subscribe,\n setDraggedPanelId,\n dockPanelToGroup,\n movePanelOrder,\n closeLeafGroup,\n registerCloseGuard,\n unregisterCloseGuard,\n registerStateProvider,\n unregisterStateProvider,\n setPanelDirty,\n updatePanelTitle,\n setPanelIcon,\n requestClosePanel,\n dockPanelToWorkspaceEdge,\n setActivePanel,\n openHostedPanel,\n removeHostedPanel,\n setHostedOptions,\n registerHostedCloseHandler,\n setDirection,\n registerPanelContextMenu,\n getPanelContextMenuItems,\n showContextMenu,\n registerContextMenuFn,\n };\n\n const applyProviderDefaults = (defaults: { dir?: 'ltr' | 'rtl'; zIndexBase?: number }): void => {\n if (config.dir === undefined && defaults.dir) setDirection(defaults.dir);\n if (config.zIndexBase === undefined && defaults.zIndexBase !== undefined && state.floating.length === 0) {\n maxZRef.current = defaults.zIndexBase;\n }\n };\n\n return { actions, getSnapshot, subscribeToState, applyProviderDefaults };\n}\n","import { useInsertionEffect, useRef, type RefObject } from 'react';\n\n/**\n * A ref that holds the latest `value`, for event handlers and effects to read without being\n * re-created. Never read it during render.\n *\n * It is updated in an insertion effect rather than during render (which the React Compiler rules\n * forbid, and which can publish a value from a render React then discards). Insertion effects run\n * before every layout effect of the commit, so even a child's effect, which runs before its\n * parent's, already sees this render's value.\n */\nexport function useLatestRef<T>(value: T): RefObject<T> {\n const ref = useRef(value);\n useInsertionEffect(() => { ref.current = value; });\n return ref;\n}\n","import type { ComponentType, ReactNode } from 'react';\nimport { PanelRegistry } from './components/PanelRegistry';\nimport type { PanelRegistryEntry } from './components/PanelRegistry';\nimport { createWorkspaceCore, type WorkspaceCore } from './components/WindowManagerContext';\nimport type {\n PanelDrop,\n WorkspaceActions,\n MessageFormatter,\n MessageDescriptor,\n DropPosition,\n SplitDirection,\n DirtyStateOptions,\n FloatingWindow,\n} from './components/WindowManagerContext';\nimport type { ShowContextMenuOptions } from './components/ContextMenu';\n\n/** Built-in lifecycle events always available on the workspace event bus. */\nexport interface BuiltInEvents {\n 'panel:opened': { id: string; component: string };\n 'panel:closed': { id: string };\n 'panel:minimized': { id: string };\n 'panel:restored': { id: string };\n /**\n * Fires whenever something `saveLayout()` would capture changes — open/close/minimize/restore,\n * float/dock/re-order/dock-to-edge, closing a group, maximizing a minimized panel, and an\n * `openPanel` `dedupeKey` redirect. Coalesces those into one signal for autosave-style\n * consumers, so they don't need to subscribe to separate events. Does **not** cover a\n * `registerStateProvider` callback's return value changing on its own — that's a pull, there's\n * no way to observe it changing without the panel separately notifying — nor split-ratio drags,\n * floating-window moves and resizes, or toggling a floating window's maximized state.\n */\n 'layout:changed': Record<string, never>;\n /**\n * Fires from inside `saveLayout()` itself, only when that specific call excluded at least one\n * panel (a panel whose current `props` — static or from a `registerStateProvider` — failed\n * {@link isSerializable}). A passive `PanelInfo.serializable` flag alone isn't enough for this:\n * nobody may be polling it at the exact moment a save happens and something silently drops out\n * (e.g. a floating window rendering data from a live class instance). This is deliberately just\n * a signal, not a UI opinion — decide for yourself whether that becomes a toast, a console\n * warning, or nothing.\n */\n 'layout:panels-excluded': { panels: { id: string; component: string }[] };\n}\n\n/** Per-panel definition supplied to `createWorkspace({ panels })`. */\nexport interface PanelDefinition {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: a registry holds components with different props; unknown would reject them\n component: ComponentType<any>;\n defaultOptions?: PanelRegistryEntry['defaultOptions'];\n}\n\n/** Configuration object accepted by `createWorkspace()`. */\nexport interface WorkspaceClientConfig {\n /**\n * Declarative panel catalog. Replaces imperative globalPanelRegistry.register() calls.\n * Keys are the component identifiers used in openPanel() and serialised layouts.\n */\n panels?: Record<string, PanelDefinition>;\n /**\n * Serialised layout produced by a previous saveLayout() call.\n * Pass null or omit to start with an empty canvas.\n *\n * Parsed synchronously before the first render. The restored `activePanelId` is the one the\n * snapshot recorded, or — for layouts saved before that was persisted — the selected tab of\n * the first leaf in the grid.\n */\n initialState?: string | null;\n /** Custom i18n formatter for all internal strings. */\n formatMessage?: MessageFormatter;\n /** Override any subset of the built-in predefined message catalog. */\n predefinedMessages?: Record<string, MessageDescriptor>;\n /** Initial layout direction. */\n dir?: 'ltr' | 'rtl';\n /**\n * Fraction of the target panel the new panel takes when dropped on a panel's\n * top/bottom/left/right cross target. Range 0.1–0.9. Default: 0.5.\n */\n defaultSplitRatio?: number;\n /**\n * Fraction of the workspace the new panel takes when dropped on the workspace\n * outer edge. Range 0.1–0.9. Default: 0.2.\n */\n defaultEdgeSplitRatio?: number;\n /**\n * Starting z-index for floating windows and the library's own chrome overlays\n * (context menu, toolbar flyout, modal stack, toast, workspace edge zones),\n * all of which shift together via `--rdd-z-base`. Set this above/below a host\n * app's own modal z-index range to control stacking against it. Default: 1000.\n */\n zIndexBase?: number;\n /**\n * Veto where users can move panels (7.9.0). Called for each place a dragged panel could go, and\n * for the built-in \"Float\" and \"Maximize\" menu items: return `false` and that target isn't\n * offered (its drop zone doesn't appear) and the move doesn't happen. It runs after the panel\n * type's own `canFloat` / `canDock`, and only for what the user does: the app's own calls\n * (`floatPanel`, `dockPanelToGroup`, `openPanel`) always work. Keep it fast and pure; it runs\n * while the pointer moves.\n *\n * @example\n * ```ts\n * createWorkspace({\n * panels,\n * // Nothing but tool panels in the left group.\n * canDrop: ({ component, to }) => !(to.kind === 'group' && to.leafId === 'tools' && component !== 'tool'),\n * });\n * ```\n */\n canDrop?: (drop: PanelDrop) => boolean;\n}\n\n/**\n * A workspace: the layout, every action on it, the panel registry and the event bus. Create one\n * with `createWorkspace()` outside the React tree and pass it to\n * `<DockableDesktopProvider workspace={…}>`; inside the tree, `useWorkspace()` returns it.\n *\n * Pattern: TanStack QueryClient / Redux store — configuration and imperative access live on the\n * workspace; rendering is delegated to the thin React provider.\n *\n * @remarks\n * The workspace is live from the moment it is created: calls made before any provider mounts\n * apply immediately, and a provider that mounts later shows the result.\n *\n * @example\n * const workspace = createWorkspace<MyEvents>({\n * panels: {\n * map: { component: MapPanel },\n * editor: { component: EditorPanel, defaultOptions: { title: 'Code Editor' } },\n * },\n * initialState: localStorage.getItem('layout'),\n * });\n *\n * <DockableDesktopProvider workspace={workspace}>\n * <RddDesktop />\n * </DockableDesktopProvider>\n *\n * // Imperative access from anywhere:\n * workspace.saveLayout();\n * workspace.openPanel('map-1', 'map');\n * workspace.focusPanel('map-1');\n */\n// `object`, not `Record<string, unknown>`: an event map declared as an `interface` (the form the\n// docs use) has no index signature and so never satisfied the Record constraint (TS2344).\nexport class WorkspaceClient<TUserEvents extends object = Record<string, unknown>> {\n /** Scoped panel registry — fully independent from the global singleton. */\n readonly registry: PanelRegistry;\n\n /** Serialised layout to restore on mount, or null to start with an empty canvas. */\n readonly initialState: string | null;\n\n /** Non-rendering configuration forwarded to the provider. */\n readonly config: Pick<WorkspaceClientConfig, 'formatMessage' | 'predefinedMessages' | 'dir' | 'defaultSplitRatio' | 'defaultEdgeSplitRatio' | 'zIndexBase'>;\n\n /** @internal The workspace store. Live from construction; a provider only subscribes to it. */\n readonly _core: WorkspaceCore;\n\n /** The store's actions, to which every method below forwards. */\n private get _actions(): WorkspaceActions { return this._core.actions; }\n\n constructor(config: WorkspaceClientConfig = {}) {\n this.registry = new PanelRegistry();\n this.initialState = config.initialState ?? null;\n this.config = {\n formatMessage: config.formatMessage,\n predefinedMessages: config.predefinedMessages,\n dir: config.dir,\n defaultSplitRatio: config.defaultSplitRatio,\n defaultEdgeSplitRatio: config.defaultEdgeSplitRatio,\n zIndexBase: config.zIndexBase,\n };\n\n if (config.panels) {\n for (const [id, def] of Object.entries(config.panels)) {\n this.registry.register(id, def.component, def.defaultOptions);\n }\n }\n\n // Every method is bound to this workspace, so `const { openPanel } = useWorkspace()` works —\n // destructuring a class instance's methods otherwise loses `this`.\n for (const key of Object.getOwnPropertyNames(WorkspaceClient.prototype) as Array<keyof this>) {\n const descriptor = Object.getOwnPropertyDescriptor(WorkspaceClient.prototype, key);\n if (key === 'constructor' || !descriptor || typeof descriptor.value !== 'function') continue;\n (this as Record<keyof this, unknown>)[key] = (descriptor.value as (...a: unknown[]) => unknown).bind(this);\n }\n\n this._core = createWorkspaceCore({\n registry: this.registry,\n initialState: this.initialState,\n dir: config.dir,\n zIndexBase: config.zIndexBase,\n defaultSplitRatio: config.defaultSplitRatio,\n defaultEdgeSplitRatio: config.defaultEdgeSplitRatio,\n canDrop: config.canDrop,\n });\n }\n\n private _dispatch(fn: (actions: WorkspaceActions) => void): void {\n fn(this._actions);\n }\n\n private _subscribeRaw(event: string, cb: (data: unknown) => void): () => void {\n return this._actions.subscribe(event, cb);\n }\n\n // ── Forwarding methods — mirrors the WorkspaceActions public interface ────────\n\n openPanel(...args: Parameters<WorkspaceActions['openPanel']>): void { this._actions.openPanel(...args); }\n\n closePanel(id: string): void { this._dispatch(a => a.closePanel(id)); }\n\n minimizePanel(id: string): void { this._dispatch(a => a.minimizePanel(id)); }\n\n restorePanel(...args: Parameters<WorkspaceActions['restorePanel']>): void {\n this._dispatch(a => a.restorePanel(...args));\n }\n\n floatPanel(...args: Parameters<WorkspaceActions['floatPanel']>): void {\n this._dispatch(a => a.floatPanel(...args));\n }\n\n dockPanel(...args: Parameters<WorkspaceActions['dockPanel']>): void {\n this._dispatch(a => a.dockPanel(...args));\n }\n\n maximizePanel(id: string): void { this._dispatch(a => a.maximizePanel(id)); }\n\n /**\n * Activates the given panel regardless of its current state.\n * For floating panels: raises z-index so the window appears on top.\n * For docked panels: selects the tab within its leaf group.\n * For minimized panels: makes it the active one, but leaves it minimized.\n */\n focusPanel(id: string): void;\n /**\n * As `focusPanel(id)`; with `restore: true`, a minimized panel is restored first, with\n * `restorePanel`'s events (7.11.0).\n * @example\n * ```ts\n * workspace.focusPanel('map-1', { restore: true }); // bring the map forward, wherever it is\n * ```\n */\n focusPanel(id: string, options: { restore?: boolean }): void;\n focusPanel(id: string, options?: { restore?: boolean }): void { this._core.actions.focusPanel(id, options); }\n\n /** Returns `true` if a panel with this ID is currently open. */\n isOpen(id: string): boolean { return this._actions.isOpen(id); }\n\n /** Returns the IDs of all currently open panels. */\n getOpenPanelIds(): string[] { return this._actions.getOpenPanelIds(); }\n\n /** Finds an already-open panel of the given component with a matching `dedupeKey` (set via\n * `openPanel`'s `dedupeKey` option). Returns `null` if none is open. */\n findPanelId(component: string, dedupeKey: string): string | null {\n return this._actions.findPanelId(component, dedupeKey);\n }\n\n saveLayout(): string { return this._actions.saveLayout(); }\n\n loadLayout(json: string): boolean { return this._actions.loadLayout(json); }\n\n setDirection(dir: 'ltr' | 'rtl'): void { this._dispatch(a => a.setDirection(dir)); }\n\n /** Updates the split-size fractions at the given grid path. */\n updateSplitSizes(path: number[], sizes: number[]): void {\n this._dispatch(a => a.updateSplitSizes(path, sizes));\n }\n\n /** Updates position/size/anchor of a floating panel. */\n updateFloatingPosition(id: string, updates: Partial<Pick<FloatingWindow, 'x' | 'y' | 'width' | 'height' | 'anchor'>>): void {\n this._dispatch(a => a.updateFloatingPosition(id, updates));\n }\n\n /** @internal Drives the drag-in-progress visual state; normally only the library's own drag UI calls this. */\n setDraggedPanelId(id: string | null): void { this._dispatch(a => a.setDraggedPanelId(id)); }\n\n /** Docks a panel into an existing leaf group at the given drop position. */\n dockPanelToGroup(id: string, targetLeafId: string, position: DropPosition): void {\n this._dispatch(a => a.dockPanelToGroup(id, targetLeafId, position));\n }\n\n /** Reorders a panel's tab within its leaf group. */\n movePanelOrder(panelId: string, targetLeafId: string, targetIndex: number): void {\n this._dispatch(a => a.movePanelOrder(panelId, targetLeafId, targetIndex));\n }\n\n /**\n * Closes a leaf group: each of its tabs is closed through the guarded close path, then the\n * group is removed once empty. A tab whose close guard refuses — or a dirty tab that\n * `onConfirm` doesn't approve — stays open, and so does its group.\n * Resolves once every close request has been settled.\n */\n closeLeafGroup(leafId: string, options?: { onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }): Promise<void> {\n return this._actions.closeLeafGroup(leafId, options);\n }\n\n /** Registers a guard that can veto closing the given panel. */\n registerCloseGuard(id: string, guard: () => boolean | Promise<boolean>): void {\n this._dispatch(a => a.registerCloseGuard(id, guard));\n }\n\n /** Removes a previously registered close guard. */\n unregisterCloseGuard(id: string): void { this._dispatch(a => a.unregisterCloseGuard(id)); }\n\n /** Registers a callback reporting a panel's current restorable state, pulled fresh on every\n * `saveLayout()` call — see {@link BuiltInEvents}'s `'layout:panels-excluded'` doc and\n * `FormContainerContract.registerStateProvider`. */\n registerStateProvider(id: string, provider: () => unknown): void {\n this._dispatch(a => a.registerStateProvider(id, provider));\n }\n\n /** Removes a previously registered state provider. */\n unregisterStateProvider(id: string): void { this._dispatch(a => a.unregisterStateProvider(id)); }\n\n /** Sets/clears a panel's dirty (unsaved changes) flag. */\n setPanelDirty(id: string, dirty: boolean, options?: DirtyStateOptions): void {\n this._dispatch(a => a.setPanelDirty(id, dirty, options));\n }\n\n /** Updates a panel's displayed title. */\n updatePanelTitle(id: string, title: string | MessageDescriptor | (() => string)): void {\n this._dispatch(a => a.updatePanelTitle(id, title));\n }\n\n /** Replaces an open panel's props, or derives them from the current ones (7.11.0). See {@link WorkspaceActions.updatePanelProps}. */\n updatePanelProps(...args: Parameters<WorkspaceActions['updatePanelProps']>): void {\n this._dispatch(a => a.updatePanelProps(...args));\n }\n\n /** Sets an open panel's tab/window/taskbar icon; `null` restores its registration's icon. Not saved by `saveLayout()`. */\n setPanelIcon(id: string, icon: ReactNode | null): void {\n this._dispatch(a => a.setPanelIcon(id, icon));\n }\n\n /**\n * Requests that a panel close, honoring any registered close guard and its dirty flag: a dirty\n * panel closes only if `onConfirm` resolves `true` (without `onConfirm` it stays open).\n * `force: true` skips both. Resolves once the close (or the refusal) has been decided.\n */\n requestClosePanel(id: string, options?: { force?: boolean; onConfirm?: (opts?: DirtyStateOptions) => Promise<boolean> }): Promise<void> {\n return this._actions.requestClosePanel(id, options);\n }\n\n /** Docks a panel to one of the workspace's outer edges. */\n dockPanelToWorkspaceEdge(id: string, position: SplitDirection): void {\n this._dispatch(a => a.dockPanelToWorkspaceEdge(id, position));\n }\n\n /** Shows a context menu using the app's configured ContextMenuAdapter. */\n showContextMenu(options: ShowContextMenuOptions): void { this._dispatch(a => a.showContextMenu(options)); }\n\n // ── Typed event bus ───────────────────────────────────────────────────────\n\n publish<K extends keyof (TUserEvents & BuiltInEvents)>(\n event: K,\n data: (TUserEvents & BuiltInEvents)[K]\n ): void {\n this._dispatch(a => a.publish(event as string, data));\n }\n\n subscribe<K extends keyof (TUserEvents & BuiltInEvents)>(\n event: K,\n callback: (data: (TUserEvents & BuiltInEvents)[K]) => void\n ): () => void {\n return this._subscribeRaw(event as string, callback as (data: unknown) => void);\n }\n\n // ── Lifecycle callbacks ───────────────────────────────────────────────────\n\n /** Subscribe to panel open events. Fires only for newly created panels. */\n onPanelOpen(callback: (id: string, component: string) => void): () => void {\n return this._subscribeRaw('panel:opened', data => {\n const d = data as BuiltInEvents['panel:opened'];\n callback(d.id, d.component);\n });\n }\n\n /** Subscribe to panel close events. */\n onPanelClose(callback: (id: string) => void): () => void {\n return this._subscribeRaw('panel:closed', data => {\n callback((data as BuiltInEvents['panel:closed']).id);\n });\n }\n\n /** Subscribe to panel minimize events. */\n onPanelMinimize(callback: (id: string) => void): () => void {\n return this._subscribeRaw('panel:minimized', data => {\n callback((data as BuiltInEvents['panel:minimized']).id);\n });\n }\n\n /** Subscribe to panel restore events. */\n onPanelRestore(callback: (id: string) => void): () => void {\n return this._subscribeRaw('panel:restored', data => {\n callback((data as BuiltInEvents['panel:restored']).id);\n });\n }\n\n /** Subscribe to the coalesced layout-change signal — see {@link BuiltInEvents}'s\n * `'layout:changed'` doc for exactly what it covers (and doesn't). */\n onLayoutChanged(callback: () => void): () => void {\n return this._subscribeRaw('layout:changed', () => callback());\n }\n\n /** Subscribe to notification that a `saveLayout()` call excluded one or more panels because\n * their current props weren't serializable — see {@link BuiltInEvents}'s\n * `'layout:panels-excluded'` doc. */\n onPanelsExcluded(callback: (panels: { id: string; component: string }[]) => void): () => void {\n return this._subscribeRaw('layout:panels-excluded', data => {\n callback((data as BuiltInEvents['layout:panels-excluded']).panels);\n });\n }\n}\n","import { createContext, type Context } from 'react';\nimport type { WorkspaceClient } from '../WorkspaceClient';\n\n/**\n * @internal The workspace object behind the nearest `<DockableDesktopProvider>`. `useWorkspace()`\n * reads it. Kept in its own module so the store (WindowManagerContext) and the workspace class\n * (WorkspaceClient) don't import each other at runtime.\n */\nexport const WorkspaceInstanceContext: Context<WorkspaceClient<object> | null> = createContext<WorkspaceClient<object> | null>(null);\n","import React, { createContext, useContext, useState, useCallback, useMemo, useRef } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport { usePredefinedMessages } from './WindowManagerContext';\nimport { sameTitle, sameDirtyOptions } from './sameUpdate';\nimport { useLatestRef } from '../utils/useLatestRef';\nexport type { DirtyStateOptions };\n\n/** Unique string identifier for panel/modal instances. */\nexport type OverlayId = string;\n\n/**\n * Descriptor object for localizable panel titles, supporting context translation systems.\n */\nexport interface PanelTitleDescriptor {\n /** The translation dictionary key. */\n id: string;\n /** Fallback string if translation key is missing. */\n defaultMessage?: string;\n /** Parameters to inject into the translated text string. */\n values?: Record<string, string | number>;\n}\n\n/**\n * A panel, window, drawer or modal title: a plain string, a localizable descriptor, or (7.4.0) a\n * function returning the text — called each time the title is rendered, so a title built with the\n * app's own translation function follows a language change. A function title is not saved in a\n * layout: a restored panel takes its registered default title.\n */\nexport type PanelTitle = string | PanelTitleDescriptor | (() => string);\n\n/** Configuration options applied when opening a SidePanel. */\nexport interface SidePanelOptions {\n /** Display title for the side-panel header. */\n title?: PanelTitle;\n /** Icon displayed next to the panel title. */\n icon?: React.ReactNode;\n /** Specific CSS width (e.g. 300, '40%') for the panel container. */\n width?: number | string;\n /**\n * CSS padding for the panel body content — a number (px) or any CSS value/shorthand\n * (e.g. `'10px 16px'`). Default: `0` (edge-to-edge) — pass `10` to restore the pre-v6.0.0\n * default, or any value your content needs.\n */\n bodyPadding?: number | string;\n}\n\n/** Configuration options applied when opening a Modal. */\nexport interface ModalOptions {\n /** Display title for the modal header. */\n title?: PanelTitle;\n /** Icon displayed in the modal title bar. */\n icon?: React.ReactNode;\n /** Size modifier affecting CSS max-width rules. */\n size?: 'small' | 'medium' | 'large' | 'fullscreen' | 'auto';\n /** If false, hides the modal backdrop exit click and header close button. */\n closable?: boolean;\n /**\n * CSS padding for the modal body content — a number (px) or any CSS value/shorthand\n * (e.g. `'10px 16px'`). Default: `0` (edge-to-edge) — pass `10` to restore the pre-v6.0.0\n * default, or any value your content needs.\n */\n bodyPadding?: number | string;\n}\n\n/**\n * Represents a rendered instance of a panel or modal in the layout.\n */\nexport interface OverlayInstance {\n /** Unique ID generated for this instance. */\n id: OverlayId;\n /** React Component to mount inside the panel. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: overlays of every component share this type; unknown would reject them\n Component: ComponentType<any>;\n /** Property props passed to the Component. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public: read back by callers through get()/stack\n props: Record<string, any>;\n /** The target rendering layout zone. */\n containerType: 'left-panel' | 'right-panel' | 'modal';\n /** Configuration metadata settings. */\n options: SidePanelOptions | ModalOptions;\n /** True if the form container has unsaved user edits. */\n dirty?: boolean;\n /** Custom warning options applied to the automatic unsaved changes modal. */\n dirtyOptions?: DirtyStateOptions;\n}\n\n/** Stores the active layout structures for floating overlays. */\nexport interface OverlayState {\n /** The currently open left drawer panel instance, or null. */\n leftPanel: OverlayInstance | null;\n /** The currently open right drawer panel instance, or null. */\n rightPanel: OverlayInstance | null;\n /** Stack containing all active floating modal instances. */\n modals: OverlayInstance[];\n}\n\n/** Exposes methods to trigger state actions on drawers and modals. */\nexport interface PanelActions {\n /** Mounts a panel in the left-side container drawer. */\n openLeftPanel: <P extends object>(Component: ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n /** Mounts a panel in the right-side container drawer. */\n openRightPanel: <P extends object>(Component: ComponentType<P>, props: P, options?: SidePanelOptions) => Promise<OverlayId | null>;\n /** Pushes a new modal component instance to the top of the stack. */\n openModal: <P extends object>(Component: ComponentType<P>, props: P, options?: ModalOptions) => OverlayId;\n /** Closes an instance by ID. */\n close: (id: OverlayId) => void;\n /** Closes all drawers and modals in a single action. */\n closeAll: () => void;\n /** Closes all open modals. */\n closeAllModals: () => void;\n /** Retrieves metadata for an active instance by ID. */\n getInstance: (id: OverlayId) => OverlayInstance | undefined;\n /** Updates the props, configuration options, or dirty flag of an active panel. */\n updateInstance: (id: OverlayId, updates: Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>) => void;\n /** Flags an instance as dirty (contains unsaved changes). */\n setDirty: (id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => void;\n /** Subscribes a custom close confirmation intercept handler. */\n registerCloseHandler: (id: OverlayId, handler: () => Promise<boolean>) => void;\n /** Unsubscribes close confirmation handler. */\n unregisterCloseHandler: (id: OverlayId) => void;\n /**\n * Subscribes to an instance being removed, by any path (`close`, `closeAll`, `closeAllModals`, or\n * a side panel being replaced). Fires once; returns an unsubscribe function.\n */\n onInstanceClose: (id: OverlayId, handler: () => void) => () => void;\n}\n\nlet idCounter = 0;\nconst generateId = (): OverlayId => `panel-${++idCounter}-${Date.now()}`;\n\nconst closeHandlers = new Map<OverlayId, () => Promise<boolean>>();\n\n/** True when applying `updates` to `current` would leave every field as it is. */\nfunction changesNothing(current: OverlayInstance, updates: Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>): boolean {\n if ('props' in updates && updates.props !== current.props) return false;\n if ('dirty' in updates && !!updates.dirty !== !!current.dirty) return false;\n if ('dirtyOptions' in updates && !sameDirtyOptions(updates.dirtyOptions, current.dirtyOptions)) return false;\n if ('options' in updates && updates.options !== current.options) {\n const next = updates.options as Record<string, unknown>, prev = current.options as Record<string, unknown>;\n const keys = new Set([...Object.keys(next), ...Object.keys(prev)]);\n for (const k of keys) {\n if (k === 'title' ? !sameTitle(next[k] as never, prev[k] as never) : next[k] !== prev[k]) return false;\n }\n }\n return true;\n}\n\nconst initialState: OverlayState = {\n leftPanel: null,\n rightPanel: null,\n modals: [],\n};\n\nconst PanelStateContext = createContext<OverlayState | null>(null);\nconst PanelActionsContext = createContext<PanelActions | null>(null);\n\n/**\n * PanelProvider component manages the state and action handlers\n * for drawers (left/right) and active stacked modal overlays.\n */\nexport const PanelProvider: React.FC<{ children: ReactNode }> = ({ children }) => {\n const [state, setState] = useState<OverlayState>(initialState);\n // A message descriptor, not a string: titles are formatted when rendered, so the default title\n // follows the app's formatter and `predefinedMessages` like every other label.\n const defaultModalTitle = usePredefinedMessages().modalTitle;\n\n const stateRef = useLatestRef(state);\n\n // Close listeners per instance. Fired from the actions that remove an instance, never from an\n // unmount, so StrictMode's simulated unmount can't fire them.\n const closeListeners = useRef(new Map<OverlayId, Set<() => void>>());\n\n const onInstanceClose = useCallback((id: OverlayId, handler: () => void) => {\n const listeners = closeListeners.current;\n if (!listeners.has(id)) listeners.set(id, new Set());\n listeners.get(id)!.add(handler);\n return () => { listeners.get(id)?.delete(handler); };\n }, []);\n\n const notifyClosed = useCallback((ids: (OverlayId | undefined)[]) => {\n for (const id of ids) {\n if (!id) continue;\n const handlers = closeListeners.current.get(id);\n closeListeners.current.delete(id);\n handlers?.forEach(h => h());\n }\n }, []);\n\n const registerCloseHandler = useCallback((id: OverlayId, handler: () => Promise<boolean>) => {\n closeHandlers.set(id, handler);\n }, []);\n\n const unregisterCloseHandler = useCallback((id: OverlayId) => {\n closeHandlers.delete(id);\n }, []);\n\n const openLeftPanel = useCallback(\n async <P extends object>(\n Component: ComponentType<P>,\n props: P,\n options: SidePanelOptions = {}\n ): Promise<OverlayId | null> => {\n const currentPanel = stateRef.current.leftPanel;\n if (currentPanel) {\n const handler = closeHandlers.get(currentPanel.id);\n if (handler) {\n const canClose = await handler();\n if (!canClose) return null;\n }\n }\n\n const id = generateId();\n const instance: OverlayInstance = {\n id,\n Component: Component as OverlayInstance['Component'],\n props: props as OverlayInstance['props'],\n containerType: 'left-panel',\n options,\n };\n setState(s => ({ ...s, leftPanel: instance }));\n notifyClosed([currentPanel?.id]);\n return id;\n },\n [notifyClosed, stateRef]\n );\n\n const openRightPanel = useCallback(\n async <P extends object>(\n Component: ComponentType<P>,\n props: P,\n options: SidePanelOptions = {}\n ): Promise<OverlayId | null> => {\n const currentPanel = stateRef.current.rightPanel;\n if (currentPanel) {\n const handler = closeHandlers.get(currentPanel.id);\n if (handler) {\n const canClose = await handler();\n if (!canClose) return null;\n }\n }\n\n const id = generateId();\n const instance: OverlayInstance = {\n id,\n Component: Component as OverlayInstance['Component'],\n props: props as OverlayInstance['props'],\n containerType: 'right-panel',\n options,\n };\n setState(s => ({ ...s, rightPanel: instance }));\n notifyClosed([currentPanel?.id]);\n return id;\n },\n [notifyClosed, stateRef]\n );\n\n const openModal = useCallback(\n <P extends object>(\n Component: ComponentType<P>,\n props: P,\n options: ModalOptions = {}\n ): OverlayId => {\n const id = generateId();\n const formTitle = (props as { title?: PanelTitle }).title;\n \n const modalOptions: ModalOptions = {\n ...options,\n title: options.title || formTitle || defaultModalTitle,\n };\n\n const instance: OverlayInstance = {\n id,\n Component: Component as OverlayInstance['Component'],\n props: props as OverlayInstance['props'],\n containerType: 'modal',\n options: modalOptions,\n };\n setState(s => ({ ...s, modals: [...s.modals, instance] }));\n return id;\n },\n [defaultModalTitle]\n );\n\n const close = useCallback((id: OverlayId) => {\n setState(s => ({\n leftPanel: s.leftPanel?.id === id ? null : s.leftPanel,\n rightPanel: s.rightPanel?.id === id ? null : s.rightPanel,\n modals: s.modals.filter(m => m.id !== id),\n }));\n notifyClosed([id]);\n }, [notifyClosed]);\n\n const closeAll = useCallback(() => {\n const { leftPanel, rightPanel, modals } = stateRef.current;\n setState(initialState);\n notifyClosed([leftPanel?.id, rightPanel?.id, ...modals.map(m => m.id)]);\n }, [notifyClosed, stateRef]);\n\n const closeAllModals = useCallback(() => {\n const { modals } = stateRef.current;\n setState(s => ({ ...s, modals: [] }));\n notifyClosed(modals.map(m => m.id));\n }, [notifyClosed, stateRef]);\n\n const getInstance = useCallback(\n (id: OverlayId): OverlayInstance | undefined => {\n if (state.leftPanel?.id === id) return state.leftPanel;\n if (state.rightPanel?.id === id) return state.rightPanel;\n return state.modals.find(m => m.id === id);\n },\n [state]\n );\n\n const updateInstance = useCallback(\n (\n id: OverlayId,\n updates: Partial<Pick<OverlayInstance, 'props' | 'options' | 'dirty' | 'dirtyOptions'>>\n ) => {\n setState(s => {\n const target = s.leftPanel?.id === id ? s.leftPanel : s.rightPanel?.id === id ? s.rightPanel : s.modals.find(m => m.id === id);\n if (!target || changesNothing(target, updates)) return s;\n return {\n leftPanel: s.leftPanel?.id === id ? { ...s.leftPanel, ...updates } : s.leftPanel,\n rightPanel: s.rightPanel?.id === id ? { ...s.rightPanel, ...updates } : s.rightPanel,\n modals: s.modals.map(m => m.id === id ? { ...m, ...updates } : m),\n };\n });\n },\n []\n );\n\n const setDirty = useCallback((id: OverlayId, dirty: boolean, options?: DirtyStateOptions) => {\n updateInstance(id, { dirty, dirtyOptions: options });\n }, [updateInstance]);\n\n const actions = useMemo<PanelActions>(\n () => ({\n openLeftPanel,\n openRightPanel,\n openModal,\n close,\n closeAll,\n closeAllModals,\n getInstance,\n updateInstance,\n setDirty,\n registerCloseHandler,\n unregisterCloseHandler,\n onInstanceClose,\n }),\n [\n openLeftPanel,\n openRightPanel,\n openModal,\n close,\n closeAll,\n closeAllModals,\n getInstance,\n updateInstance,\n setDirty,\n registerCloseHandler,\n unregisterCloseHandler,\n onInstanceClose,\n ]\n );\n\n return (\n <PanelStateContext.Provider value={state}>\n <PanelActionsContext.Provider value={actions}>\n {children}\n </PanelActionsContext.Provider>\n </PanelStateContext.Provider>\n );\n};\n\n/**\n * React hook to retrieve the active floating/drawer panels state.\n * @throws Error if used outside of a {@link PanelProvider}.\n */\nexport const usePanelState = (): OverlayState => {\n const ctx = useContext(PanelStateContext);\n if (!ctx) throw new Error('useModals / useSidePanels must be used within <DockableDesktopProvider>');\n return ctx;\n};\n\n/**\n * React hook to retrieve actions enabling drawer toggles and modal push actions.\n * @throws Error if used outside of a {@link PanelProvider}.\n */\nexport const usePanelActions = (): PanelActions => {\n const ctx = useContext(PanelActionsContext);\n if (!ctx) throw new Error('useModals / useSidePanels must be used within <DockableDesktopProvider>');\n return ctx;\n};\n","import React, { useCallback, useRef, useEffect, useState, useMemo } from 'react';\nimport { usePanelState, usePanelActions } from './PanelProviderContext';\nimport { FormContainerProvider, type FormContainerContract, type CloseOptions } from './FormContainerContext';\nimport type { OverlayInstance, SidePanelOptions, PanelTitle } from './PanelProviderContext';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport { useFormatMessage, formatLabel, useStyleClasses, usePredefinedMessages, useWindowManagerState } from './WindowManagerContext';\nimport ConfirmationForm from '../forms/ConfirmationForm';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { useContainerRect, type ContainerRect } from '../hooks/useContainerRect';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Props for the internal {@link SidePanelRendererItem} component.\n */\ninterface SidePanelRendererItemProps {\n /** The panel instance containing metadata, component type, and rendering state. */\n panel: OverlayInstance;\n /** Floating anchor edge side for the drawer panel. */\n position: 'left' | 'right';\n /** Default width applied if no panel override configuration is provided. */\n defaultWidth?: number | string;\n /** On-screen rect of the app's own container, or null to default to the full viewport. */\n containerRect: ContainerRect | null;\n}\n\n/**\n * SidePanelRendererItem component renders an individual left or right drawer panel instance\n * wrapped inside the FormContainerProvider context. Handles dirty state verification before close.\n */\nconst SidePanelRendererItem: React.FC<SidePanelRendererItemProps> = ({ panel, position, defaultWidth, containerRect }) => {\n const { close, openModal, updateInstance, setDirty, registerCloseHandler, unregisterCloseHandler, onInstanceClose } = usePanelActions();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const dir = useWindowManagerState(s => s.dir);\n const { sidePanelClass, sidePanelBodyClass } = useStyleClasses();\n const closeHandlerRef = useRef<(() => boolean | Promise<boolean>) | null>(null);\n\n const { id, Component, props, options, dirty, dirtyOptions } = panel;\n const panelOptions = options as SidePanelOptions;\n const [icon, setIconState] = useState<React.ReactNode>(panelOptions.icon || null);\n\n const optionsRef = useLatestRef(panelOptions);\n\n const baseTitle = formatLabel(panelOptions.title, formatMessage);\n\n const handleClose = useCallback(async (options?: CloseOptions) => {\n if (options?.force) {\n close(id);\n return;\n }\n\n if (closeHandlerRef.current) {\n const canClose = await closeHandlerRef.current();\n if (!canClose) return;\n close(id);\n return;\n }\n\n if (dirty) {\n openModal(\n ConfirmationForm,\n {\n title: dirtyOptions?.title || predefinedMessages.unsavedChangesTitle,\n message: dirtyOptions?.message || {\n id: predefinedMessages.unsavedChangesMessage.id,\n defaultMessage: predefinedMessages.unsavedChangesMessage.defaultMessage,\n values: { title: baseTitle }\n },\n alert: dirtyOptions?.alert,\n alertType: dirtyOptions?.alertType || 'danger',\n useYesNoTitles: true,\n onOK: () => close(id),\n },\n { size: 'small' }\n );\n return;\n }\n\n close(id);\n }, [close, openModal, id, dirty, dirtyOptions, baseTitle, predefinedMessages]);\n\n const canClose = useCallback(async (): Promise<boolean> => {\n if (closeHandlerRef.current) {\n return await closeHandlerRef.current();\n }\n return !dirty;\n }, [dirty]);\n\n useEffect(() => {\n registerCloseHandler(id, canClose);\n return () => unregisterCloseHandler(id);\n }, [id, canClose, registerCloseHandler, unregisterCloseHandler]);\n\n const handleSetDirty = useCallback((dirty: boolean, options?: DirtyStateOptions) => setDirty(id, dirty, options), [setDirty, id]);\n const handleSetTitle = useCallback((title: PanelTitle) => updateInstance(id, { options: { ...optionsRef.current, title } }), [updateInstance, id, optionsRef]);\n const handleSetIcon = useCallback((newIcon: React.ReactNode) => setIconState(newIcon), []);\n const handleOnCloseRequested = useCallback((handler: () => boolean | Promise<boolean>) => {\n closeHandlerRef.current = handler;\n return () => { closeHandlerRef.current = null; };\n }, []);\n\n const handleOnClose = useCallback((handler: () => void) => onInstanceClose(id, handler), [onInstanceClose, id]);\n\n const contract: FormContainerContract = useMemo(() => ({\n requestClose: handleClose,\n setDirty: handleSetDirty,\n setTitle: handleSetTitle,\n setIcon: handleSetIcon,\n onCloseRequested: handleOnCloseRequested,\n containerType: position === 'left' ? 'left-panel' : 'right-panel',\n instanceId: id,\n onClose: handleOnClose,\n }), [handleClose, handleOnClose, handleSetDirty, handleSetTitle, handleSetIcon, handleOnCloseRequested, position, id]);\n\n const displayTitle = dirty ? `${baseTitle} *` : baseTitle;\n\n // Modals sit above drawers on the shared Escape stack, so an open modal answers first; of\n // two open drawers, the one opened last does.\n useEscapeLayer(true, 'drawer', handleClose);\n\n const width = panelOptions.width || defaultWidth || 400;\n const widthStyle = typeof width === 'number' ? `${width}px` : width;\n\n const bodyPadding = panelOptions.bodyPadding;\n const bodyPaddingStyle = bodyPadding != null\n ? (typeof bodyPadding === 'number' ? `${bodyPadding}px` : bodyPadding)\n : undefined;\n\n return (\n <div\n className={`rdd-side-panel rdd-side-panel-${position} rdd-side-panel-visible ${sidePanelClass ?? ''}`}\n style={{\n width: widthStyle,\n ...(containerRect ? {\n top: containerRect.top,\n height: containerRect.height,\n bottom: 'auto',\n ...(position === 'right' ? { right: containerRect.right } : { left: containerRect.left }),\n } : {}),\n }}\n dir={dir}\n >\n <div className=\"rdd-side-panel-window\">\n <div className=\"rdd-side-panel-header\">\n {icon && <div className=\"rdd-side-panel-icon\">{icon}</div>}\n <h4 className=\"rdd-side-panel-title\">{displayTitle}</h4>\n <button\n className=\"rdd-side-panel-close-button\"\n onClick={() => handleClose()}\n title={formatMessage(predefinedMessages.closeTooltip)}\n type=\"button\"\n >\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\" />\n </svg>\n </button>\n </div>\n <div\n className={`rdd-side-panel-body ${sidePanelBodyClass ?? ''}`}\n style={bodyPaddingStyle != null ? { padding: bodyPaddingStyle } : undefined}\n >\n <FormContainerProvider value={contract}>\n <Component {...props} panelId={id} />\n </FormContainerProvider>\n </div>\n </div>\n </div>\n );\n};\n\nexport interface SidePanelRendererProps {\n /**\n * Default panel width applied when openLeftPanel/openRightPanel do not specify one.\n * Accepts a number (treated as px) or any CSS width string (e.g. '40vw').\n * Falls back to 400px if omitted.\n */\n defaultWidth?: number | string;\n}\n\n/**\n * Renders an always-present, zero-footprint anchor (`display: contents` — no box\n * of its own, no layout/visual effect) so its parent element — the container the\n * consuming app actually placed the workspace into — can be measured via\n * {@link useContainerRect}, independent of whether any panel is currently open.\n */\nconst SidePanelAnchor: React.FC<{ children: (containerRect: ContainerRect | null) => React.ReactNode }> = ({ children }) => {\n const anchorRef = useRef<HTMLDivElement>(null);\n const containerRect = useContainerRect(anchorRef);\n return <div ref={anchorRef} className=\"rdd-side-panel-anchor\">{children(containerRect)}</div>;\n};\n\n/**\n * Renders both side drawers when open. Public as `<RddSidePanels>`.\n */\nexport const SidePanelRenderer: React.FC<SidePanelRendererProps> = ({ defaultWidth }) => {\n const { leftPanel, rightPanel } = usePanelState();\n return (\n <SidePanelAnchor>\n {(containerRect) => (\n <>\n {leftPanel && <SidePanelRendererItem key={leftPanel.id} panel={leftPanel} position=\"left\" defaultWidth={defaultWidth} containerRect={containerRect} />}\n {rightPanel && <SidePanelRendererItem key={rightPanel.id} panel={rightPanel} position=\"right\" defaultWidth={defaultWidth} containerRect={containerRect} />}\n </>\n )}\n </SidePanelAnchor>\n );\n};\n\n/**\n * LeftPanelRenderer component renders ONLY the left side drawer if it is currently active.\n */\nexport const LeftPanelRenderer: React.FC<SidePanelRendererProps> = ({ defaultWidth }) => {\n const { leftPanel } = usePanelState();\n return (\n <SidePanelAnchor>\n {(containerRect) => leftPanel ? <SidePanelRendererItem key={leftPanel.id} panel={leftPanel} position=\"left\" defaultWidth={defaultWidth} containerRect={containerRect} /> : null}\n </SidePanelAnchor>\n );\n};\n\n/**\n * RightPanelRenderer component renders ONLY the right side drawer if it is currently active.\n */\nexport const RightPanelRenderer: React.FC<SidePanelRendererProps> = ({ defaultWidth }) => {\n const { rightPanel } = usePanelState();\n return (\n <SidePanelAnchor>\n {(containerRect) => rightPanel ? <SidePanelRendererItem key={rightPanel.id} panel={rightPanel} position=\"right\" defaultWidth={defaultWidth} containerRect={containerRect} /> : null}\n </SidePanelAnchor>\n );\n};\n\nexport default SidePanelRenderer;\n","import React, { useEffect, useRef } from 'react';\nimport { useFormContainer } from '../components/FormContainerContext';\nimport { useFormatMessage, usePredefinedMessages } from '../components/WindowManagerContext';\nimport { DialogIcon } from './dialogIcons';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Props for the {@link RddConfirm} component.\n */\nexport interface RddConfirmProps {\n /** Optional custom title text or localizable descriptor for the dialog container. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n title?: string | { id: string; defaultMessage?: string; values?: any } | (() => string);\n /** Main message text or localizable descriptor to display. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n message: string | { id: string; defaultMessage?: string; values?: any };\n /** Optional auxiliary top alert notification text. */\n alert?: string;\n /** Type style classification for the alert notice banner. */\n alertType?: 'info' | 'warning' | 'success' | 'danger';\n /** If true, changes action button labels to 'Yes' and 'No' instead of 'OK' and 'Cancel'. */\n useYesNoTitles?: boolean;\n /** Callback fired when the user selects the confirm button. */\n onOK?: () => void;\n /** Callback fired when the user selects the cancel button. */\n onCancel?: () => void;\n /**\n * Fired exactly once, however the dialog ends: `true` for the confirm button (or Enter),\n * `false` for the cancel button, Escape, the backdrop, the × or the modal being closed by code.\n */\n onSettled?: (ok: boolean) => void;\n /**\n * The icon left of the message. Omit it for the built-in question icon, pass `null` for none,\n * or pass your own node. It is coloured by `alertType`.\n */\n icon?: React.ReactNode | null;\n}\n\n/**\n * RddConfirm component renders a standard dialog content layout,\n * allowing users to confirm actions or abort them. Exposes action callbacks.\n */\nexport const ConfirmationForm: React.FC<RddConfirmProps> = ({\n title,\n message,\n alert,\n alertType = 'info',\n useYesNoTitles = false,\n onOK,\n onCancel,\n onSettled,\n icon,\n}) => {\n const { requestClose, setTitle, onClose } = useFormContainer();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const confirmButtonRef = useRef<HTMLButtonElement>(null);\n\n // Settle once. The container reports every close, so Escape, the backdrop, the × and a close by\n // code settle as \"not confirmed\"; after a button the guard swallows that report.\n const settledRef = useRef(false);\n const onSettledRef = useLatestRef(onSettled);\n const settle = (ok: boolean) => {\n if (settledRef.current) return;\n settledRef.current = true;\n onSettledRef.current?.(ok);\n };\n const settleRef = useLatestRef(settle);\n\n useEffect(() => onClose?.(() => settleRef.current(false)), [onClose, settleRef]);\n\n useEffect(() => {\n if (title) {\n const resolvedTitle = typeof title === 'string' ? title : typeof title === 'function' ? title() : formatMessage(title);\n setTitle(resolvedTitle);\n }\n }, [title, setTitle, formatMessage]);\n\n useEffect(() => {\n confirmButtonRef.current?.focus({ preventScroll: true });\n }, []);\n\n const resolvedMessage = typeof message === 'string' ? message : formatMessage(message);\n\n const cancelLabel = useYesNoTitles\n ? formatMessage(predefinedMessages.no)\n : formatMessage(predefinedMessages.cancel);\n\n const confirmLabel = useYesNoTitles\n ? formatMessage(predefinedMessages.yes)\n : formatMessage(predefinedMessages.ok);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n settle(true);\n onOK?.();\n requestClose();\n };\n\n const handleCancel = () => {\n settle(false);\n onCancel?.();\n requestClose();\n };\n\n return (\n <form onSubmit={handleSubmit} className=\"rdd-confirmation-form-body\">\n {alert && (\n <div className={`rdd-confirmation-alert rdd-confirmation-alert-${alertType}`}>\n <span>ℹ️</span>\n <span>{alert}</span>\n </div>\n )}\n\n <div className=\"rdd-dialog-content\">\n <DialogIcon icon={icon} type={alertType} question />\n <div className=\"rdd-confirmation-message\">\n {resolvedMessage}\n </div>\n </div>\n\n <hr className=\"rdd-confirmation-divider\" />\n\n <div className=\"rdd-confirmation-actions\">\n <button\n type=\"button\"\n className=\"rdd-btn rdd-btn-sm rdd-btn-outline\"\n onClick={handleCancel}\n data-rdd-confirm-cancel\n >\n {cancelLabel}\n </button>\n <button\n type=\"submit\"\n className=\"rdd-btn rdd-btn-sm rdd-btn-primary\"\n ref={confirmButtonRef}\n data-rdd-confirm-ok\n >\n {confirmLabel}\n </button>\n </div>\n </form>\n );\n};\n\nexport default ConfirmationForm;\n","import React from 'react';\n\n/** The four alert types the confirmation and alert dialogs take. */\nexport type DialogAlertType = 'info' | 'warning' | 'success' | 'danger';\n\n// Built-in dialog icons, drawn in currentColor so the `rdd-dialog-icon-{type}` class colours them.\n// Same 16-unit grid and stroke as the toast icons.\n\nconst QuestionIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M6.25 6.25a1.75 1.75 0 1 1 2.6 1.53c-.5.28-.85.7-.85 1.27v.2M8 11.25v.01\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"/>\n </svg>\n);\nconst InfoIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M8 5v.01M8 7.5v3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst SuccessIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5 8l2 2 4-4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"/>\n </svg>\n);\nconst WarningIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <path d=\"M8 2.5L14 13.5H2L8 2.5z\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinejoin=\"round\"/>\n <path d=\"M8 7v2.5M8 11.5v.01\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst DangerIcon = () => (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5.5 5.5l5 5M10.5 5.5l-5 5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\n\nconst TYPE_ICONS: Record<DialogAlertType, React.FC> = {\n info: InfoIcon,\n success: SuccessIcon,\n warning: WarningIcon,\n danger: DangerIcon,\n};\n\n/**\n * The icon slot left of a dialog's message. `icon` undefined draws the built-in icon (`question`\n * for a confirmation, the type's icon for an alert), `null` draws nothing, anything else is drawn\n * in its place.\n */\nexport const DialogIcon: React.FC<{ icon: React.ReactNode | undefined; type: DialogAlertType; question?: boolean }> = ({ icon, type, question }) => {\n if (icon === null) return null;\n const Builtin = question ? QuestionIcon : TYPE_ICONS[type];\n return (\n <div className={`rdd-dialog-icon rdd-dialog-icon-${type}`} data-rdd-dialog-icon={icon === undefined ? 'default' : 'custom'}>\n {icon === undefined ? <Builtin /> : icon}\n </div>\n );\n};\n","import { useEffect, useLayoutEffect, useRef } from 'react';\n\n/**\n * One Escape closes one overlay: the one on top.\n *\n * Every overlay used to add its own `keydown` listener to `document`. `stopPropagation()` does\n * not stop the other listeners on the same node, so a single key press closed a context menu\n * *and* the modal under it, or both side drawers at once. Overlays now register here instead,\n * and one shared listener hands each Escape to the topmost registration only.\n *\n * \"Topmost\" is by layer first — popups (context menu, toolbar flyout) above modals, modals above\n * drawers, matching how they are stacked on screen — then by registration order within a layer.\n *\n * The listener is on `document` in the bubble phase, so it runs after React's own handlers\n * (which are attached to the root container). A control that handles Escape itself — the panel\n * search box, or an app's own widget — claims it with `preventDefault()`, and the overlay stays.\n */\nexport type EscapeLayer = 'drawer' | 'modal' | 'popup';\n\nconst LAYER_RANK: Record<EscapeLayer, number> = { drawer: 1, modal: 2, popup: 3 };\n\ninterface EscapeEntry {\n layer: EscapeLayer;\n order: number;\n onEscape: () => void;\n}\n\nconst entries: EscapeEntry[] = [];\nlet nextOrder = 0;\n\nfunction handleKeyDown(e: KeyboardEvent): void {\n if (e.key !== 'Escape' || e.defaultPrevented || entries.length === 0) return;\n let top = entries[0];\n for (const entry of entries) {\n const higher = LAYER_RANK[entry.layer] - LAYER_RANK[top.layer];\n if (higher > 0 || (higher === 0 && entry.order > top.order)) top = entry;\n }\n e.preventDefault();\n top.onEscape();\n}\n\n/**\n * Registers an overlay for Escape. Returns the function that unregisters it.\n * `onEscape` may do nothing (a modal that can't be closed) — the key is still consumed, so it\n * doesn't fall through to whatever is underneath.\n */\nexport function pushEscape(layer: EscapeLayer, onEscape: () => void): () => void {\n const entry: EscapeEntry = { layer, order: nextOrder++, onEscape };\n entries.push(entry);\n if (entries.length === 1) document.addEventListener('keydown', handleKeyDown);\n return () => {\n const index = entries.indexOf(entry);\n if (index === -1) return;\n entries.splice(index, 1);\n if (entries.length === 0) document.removeEventListener('keydown', handleKeyDown);\n };\n}\n\n/**\n * Registers an overlay for Escape while `active` is true.\n *\n * The overlay's place in the stack is fixed when it becomes active; `onEscape` is read through a\n * ref, so a new callback identity on re-render does not move it to the top.\n */\nexport function useEscapeLayer(active: boolean, layer: EscapeLayer, onEscape: () => void): void {\n const onEscapeRef = useRef(onEscape);\n useLayoutEffect(() => {\n onEscapeRef.current = onEscape;\n });\n useEffect(() => {\n if (!active) return;\n return pushEscape(layer, () => onEscapeRef.current());\n }, [active, layer]);\n}\n","import { useLayoutEffect, useState, type RefObject } from 'react';\n\n/** On-screen rect of a container, in the coordinate system `position: fixed` uses. */\nexport interface ContainerRect {\n top: number;\n left: number;\n /** Distance from the viewport's right edge — what CSS `right` expects for `position: fixed`. */\n right: number;\n height: number;\n}\n\n/**\n * Tracks the live on-screen rect of `anchorRef.current`'s parent element.\n *\n * Used to keep a `position: fixed` overlay (side panel) visually confined to\n * whatever container the consuming app actually placed the workspace into,\n * instead of defaulting to the full browser viewport. `position: fixed` is\n * required so the overlay never contributes scrollable overflow to any\n * ancestor (see the side-panel autofocus scroll-jump fix), but that means it\n * no longer inherits containment from a `position: relative` ancestor the way\n * `position: absolute` did — this hook restores that containment by measuring\n * it directly. For a full-viewport app the measured rect equals the viewport,\n * so this is a no-op change from the app's perspective.\n */\nexport function useContainerRect(anchorRef: RefObject<HTMLElement | null>): ContainerRect | null {\n const [rect, setRect] = useState<ContainerRect | null>(null);\n\n useLayoutEffect(() => {\n const container = anchorRef.current?.parentElement;\n if (!container) return;\n\n const measure = () => {\n const r = container.getBoundingClientRect();\n setRect({ top: r.top, left: r.left, right: window.innerWidth - r.right, height: r.height });\n };\n measure();\n\n const resizeObserver = new ResizeObserver(measure);\n resizeObserver.observe(container);\n window.addEventListener('resize', measure);\n\n return () => {\n resizeObserver.disconnect();\n window.removeEventListener('resize', measure);\n };\n }, [anchorRef]);\n\n return rect;\n}\n","import React, { useEffect, useRef } from 'react';\nimport { useFormContainer } from '../components/FormContainerContext';\nimport { useFormatMessage, usePredefinedMessages } from '../components/WindowManagerContext';\nimport { DialogIcon } from './dialogIcons';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Props for the {@link RddAlert} component.\n */\nexport interface RddAlertProps {\n /** Optional custom title text or localizable descriptor for the dialog container. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n title?: string | { id: string; defaultMessage?: string; values?: any } | (() => string);\n /** Main message text or localizable descriptor to display. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n message: string | { id: string; defaultMessage?: string; values?: any };\n /** Picks the built-in icon and its colour. Defaults to `'info'`. */\n alertType?: 'info' | 'warning' | 'success' | 'danger';\n /**\n * The icon left of the message. Omit it for the built-in icon of `alertType`, pass `null` for\n * none, or pass your own node. It is coloured by `alertType`.\n */\n icon?: React.ReactNode | null;\n /** Label of the button. Defaults to the `ok` predefined message. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public input; narrowed with the title type in 8.0.0\n okLabel?: string | { id: string; defaultMessage?: string; values?: any };\n /**\n * Fired exactly once, however the dialog ends: the OK button, Enter, Escape, the backdrop, the ×\n * or the modal being closed by code.\n */\n onSettled?: () => void;\n}\n\n/**\n * RddAlert shows a message with a single OK button. Open it with `useModals().open` or\n * `useModals().alert()`.\n */\nexport const AlertForm: React.FC<RddAlertProps> = ({\n title,\n message,\n alertType = 'info',\n icon,\n okLabel,\n onSettled,\n}) => {\n const { requestClose, setTitle, onClose } = useFormContainer();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const okButtonRef = useRef<HTMLButtonElement>(null);\n\n const settledRef = useRef(false);\n const onSettledRef = useLatestRef(onSettled);\n const settle = () => {\n if (settledRef.current) return;\n settledRef.current = true;\n onSettledRef.current?.();\n };\n const settleRef = useLatestRef(settle);\n\n useEffect(() => onClose?.(() => settleRef.current()), [onClose, settleRef]);\n\n useEffect(() => {\n if (title) {\n const resolvedTitle = typeof title === 'string' ? title : typeof title === 'function' ? title() : formatMessage(title);\n setTitle(resolvedTitle);\n }\n }, [title, setTitle, formatMessage]);\n\n useEffect(() => {\n okButtonRef.current?.focus({ preventScroll: true });\n }, []);\n\n const resolvedMessage = typeof message === 'string' ? message : formatMessage(message);\n const resolvedOk = okLabel === undefined\n ? formatMessage(predefinedMessages.ok)\n : typeof okLabel === 'string' ? okLabel : formatMessage(okLabel);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n settle();\n requestClose({ force: true });\n };\n\n return (\n <form onSubmit={handleSubmit} className=\"rdd-confirmation-form-body\">\n <div className=\"rdd-dialog-content\">\n <DialogIcon icon={icon} type={alertType} />\n <div className=\"rdd-confirmation-message\">\n {resolvedMessage}\n </div>\n </div>\n\n <hr className=\"rdd-confirmation-divider\" />\n\n <div className=\"rdd-confirmation-actions\">\n <button\n type=\"submit\"\n className=\"rdd-btn rdd-btn-sm rdd-btn-primary\"\n ref={okButtonRef}\n data-rdd-alert-ok\n >\n {resolvedOk}\n </button>\n </div>\n </form>\n );\n};\n\nexport default AlertForm;\n","import React, {\n forwardRef,\n useImperativeHandle,\n useState,\n useRef,\n useEffect,\n useLayoutEffect,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { isComputedRtl } from '../utils/rtl';\nimport { enabledItems, moveMenuFocus } from '../utils/menuKeyboard';\nimport type { ContextMenuLabel, MessageFormatter, MenuItemAction } from './contextMenuTypes';\n\n// ─── Re-export shared primitives so callers don't need contextMenuTypes.ts ───\nexport type { ContextMenuLabel, MessageFormatter, MenuItemAction };\n\n// ─── Item type shapes (identical surface to former replace-react-contexify) ───\n\nexport interface ContextMenuCheckbox {\n /** Whether the checkbox column renders at all (default: true). */\n active?: boolean;\n /** Whether the item is interactive (default: true). Prefer top-level `disabled` on the item instead. */\n enabled?: boolean;\n /** Current checked state. */\n value: boolean;\n}\n\nexport interface ContextMenuSimpleItem {\n label: ContextMenuLabel;\n icon?: React.ReactNode;\n title?: ContextMenuLabel;\n checkbox?: ContextMenuCheckbox;\n action?: MenuItemAction;\n cyAction?: string;\n disabled?: boolean;\n}\n\nexport interface ContextMenuSeparator {\n separator: true;\n}\n\nexport interface ContextMenuSubMenu {\n label: ContextMenuLabel;\n title?: ContextMenuLabel;\n items?: ContextMenuItem[];\n}\n\nexport type ContextMenuItem = ContextMenuSimpleItem | ContextMenuSeparator | ContextMenuSubMenu;\n\n// ─── Imperative API ───────────────────────────────────────────────────────────\n\nexport interface ShowContextMenuOptions {\n event?: React.MouseEvent | React.TouchEvent | MouseEvent | TouchEvent;\n x?: number;\n y?: number;\n items: ContextMenuItem[];\n /**\n * The menu's direction. By default it is the direction of the element the menu was opened from\n * (the event's target); a workspace's `showContextMenu` passes its own direction for a menu\n * opened without an event. The menu is portaled to `<body>`, so it can't inherit either.\n */\n dir?: 'ltr' | 'rtl';\n /**\n * Where focus goes when the menu opens. `'menu'` (the default) focuses the menu itself, with no\n * item highlighted: ArrowDown then reaches the first item and ArrowUp the last. `'first-item'`\n * focuses the first enabled item, for a menu opened from the keyboard. When this is left out, a\n * keyboard `contextmenu` event (the ContextMenu key or Shift+F10, which report no pointer\n * position) opens on the first item and everything else, including a call with no event, on\n * the menu: the same view every time, whatever the user did before.\n */\n initialFocus?: 'menu' | 'first-item';\n}\n\nexport interface ContextMenuHandle {\n show(options: ShowContextMenuOptions): void;\n}\n\n// ─── Component props ──────────────────────────────────────────────────────────\n\nexport interface ContextMenuProps {\n theme?: string;\n animation?: string;\n formatMessageProvider?: MessageFormatter;\n onShow?: () => void;\n onHide?: () => void;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n style?: React.CSSProperties;\n}\n\n// ─── Adapter interface (strategy pattern) ────────────────────────────────────\n\nexport interface ContextMenuAdapter {\n Component: React.ForwardRefExoticComponent<\n ContextMenuProps & React.RefAttributes<ContextMenuHandle>\n >;\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────────\n\n/** A `contextmenu` event from the keyboard (ContextMenu key, Shift+F10): no pointer position. */\nfunction isKeyboardMenuEvent(event: ShowContextMenuOptions['event']): boolean {\n if (!event || 'touches' in event) return false;\n const mouse = event as MouseEvent;\n return mouse.clientX === 0 && mouse.clientY === 0;\n}\n\nfunction getCoords(\n event: ShowContextMenuOptions['event'],\n): { x: number; y: number } {\n if (!event) return { x: 0, y: 0 };\n if ('touches' in event && event.touches.length > 0) {\n return { x: event.touches[0].clientX, y: event.touches[0].clientY };\n }\n const mouse = event as MouseEvent;\n // The ContextMenu key and Shift+F10 fire `contextmenu` with no pointer position (0, 0): open\n // the menu at the focused element instead of the top-left corner of the page.\n if (mouse.clientX === 0 && mouse.clientY === 0 && mouse.target instanceof Element) {\n const r = mouse.target.getBoundingClientRect();\n if (r.width || r.height) return { x: r.left, y: r.bottom };\n }\n return { x: mouse.clientX, y: mouse.clientY };\n}\n\nfunction resolveLabel(label: ContextMenuLabel, fmt?: MessageFormatter): string {\n if (typeof label === 'string') return label;\n if (fmt) return fmt(label);\n return label.defaultMessage ?? label.id;\n}\n\nfunction isSeparator(item: ContextMenuItem): item is ContextMenuSeparator {\n return 'separator' in item;\n}\n\nfunction isSubMenu(item: ContextMenuItem): item is ContextMenuSubMenu {\n return !isSeparator(item) && 'items' in item;\n}\n\n// ─── Sub-menu panel (one-level deep) ─────────────────────────────────────────\n\n/** Where a submenu hangs from: the parent menu's physical edges, and the top of the item. */\ninterface SubMenuAnchor {\n menuLeft: number;\n menuRight: number;\n top: number;\n /** Reading direction at the item: the submenu prefers the reading-end side. */\n rtl: boolean;\n}\n\ninterface SubMenuPanelProps {\n items: ContextMenuItem[];\n /** Measures where to hang from. Called after layout and in event handlers, never in render. */\n getAnchor: () => SubMenuAnchor | null;\n /** Opened from the keyboard: focus its first item. */\n autoFocus: boolean;\n /** The key that returns to the parent item (ArrowLeft, or ArrowRight under RTL). */\n onBack: () => void;\n theme: string;\n /** The parent menu's direction: the submenu is portaled too, so it can't inherit it. */\n dir: 'ltr' | 'rtl';\n fmt?: MessageFormatter;\n onClose: () => void;\n onMouseEnter: () => void;\n onMouseLeave: () => void;\n}\n\nconst SubMenuPanel = forwardRef<HTMLDivElement, SubMenuPanelProps>(\n ({ items, getAnchor, autoFocus, onBack, theme, dir, fmt, onClose, onMouseEnter, onMouseLeave }, ref) => {\n // Placed after layout, once the panel's own width is known. It hangs off the parent menu's\n // reading-end edge (right in LTR, left in RTL) and flips to the other edge when that side\n // has no room — clamping it into the viewport instead is what laid it over the parent menu.\n useLayoutEffect(() => {\n const el = (ref as React.RefObject<HTMLDivElement>)?.current;\n const anchor = getAnchor();\n if (!el || !anchor) return;\n const PAD = 8;\n const GAP = 2;\n // Layout size, not getBoundingClientRect: the entry animation scales the panel, and a\n // scaled measurement placed a left-hanging submenu over its parent.\n const width = el.offsetWidth;\n const height = el.offsetHeight;\n const toRight = anchor.menuRight + GAP;\n const toLeft = anchor.menuLeft - GAP - width;\n const fitsRight = toRight + width <= window.innerWidth - PAD;\n const fitsLeft = toLeft >= PAD;\n let left: number;\n if (anchor.rtl) left = fitsLeft || !fitsRight ? toLeft : toRight;\n else left = fitsRight || !fitsLeft ? toRight : toLeft;\n left = Math.max(PAD, Math.min(left, window.innerWidth - width - PAD));\n const top = Math.max(PAD, Math.min(anchor.top, window.innerHeight - height - PAD));\n el.style.left = `${left}px`;\n el.style.top = `${top}px`;\n });\n\n useLayoutEffect(() => {\n if (autoFocus) enabledItems((ref as React.RefObject<HTMLDivElement>)?.current)[0]?.focus();\n }, [autoFocus, ref]);\n\n const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n const backKey = getAnchor()?.rtl ? 'ArrowRight' : 'ArrowLeft';\n if (e.key === backKey) { e.preventDefault(); e.stopPropagation(); onBack(); return; }\n if (e.key === 'Tab') { e.preventDefault(); e.stopPropagation(); onClose(); return; }\n if (moveMenuFocus(e.currentTarget, e.key)) { e.preventDefault(); e.stopPropagation(); }\n };\n\n return createPortal(\n <div\n ref={ref}\n className={`rdd-context-menu rdd-context-menu--${theme} rdd-context-menu--submenu`}\n dir={dir}\n // z-index from .rdd-context-menu--submenu (+8501) — see the main menu's note below.\n // Placed by the layout effect above before paint (its starting left/top are in the class).\n role=\"menu\"\n tabIndex={-1}\n onKeyDown={handleKeyDown}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n >\n {items.map((item, i) => {\n if (isSeparator(item)) {\n return <hr key={i} className=\"rdd-context-menu__separator\" role=\"separator\" />;\n }\n const simple = item as ContextMenuSimpleItem;\n const showChk = simple.checkbox && simple.checkbox.active !== false;\n const isChecked = showChk && simple.checkbox!.value;\n const isDisabled = simple.disabled === true || (showChk ? simple.checkbox!.enabled === false : false);\n return (\n <button\n key={i}\n type=\"button\"\n className={`rdd-context-menu__item${isDisabled ? ' rdd-context-menu__item--disabled' : ''}`}\n title={simple.title ? resolveLabel(simple.title, fmt) : undefined}\n disabled={isDisabled}\n data-cy-action={simple.cyAction}\n onClick={() => { if (!isDisabled) { simple.action?.(); onClose(); } }}\n role={showChk ? 'menuitemcheckbox' : 'menuitem'}\n aria-checked={showChk ? isChecked : undefined}\n >\n {simple.icon\n ? <span className=\"rdd-context-menu__icon\">{simple.icon}</span>\n : <span className=\"rdd-context-menu__icon\" aria-hidden=\"true\" />}\n <span className=\"rdd-context-menu__label\">{resolveLabel(simple.label, fmt)}</span>\n {showChk && (\n <span className={`rdd-context-menu__checkbox${isChecked ? ' rdd-context-menu__checkbox--checked' : ''}`} aria-hidden=\"true\">\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"0.75\" y=\"0.75\" width=\"10.5\" height=\"10.5\" rx=\"2\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n />\n {isChecked && (\n <path d=\"M2.5 6 L4.5 8.5 L9.5 3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n )}\n </svg>\n </span>\n )}\n </button>\n );\n })}\n </div>,\n document.body,\n );\n },\n);\n\nSubMenuPanel.displayName = 'ContextMenuSubMenuPanel';\n\n// ─── Main component ───────────────────────────────────────────────────────────\n\ninterface MenuState {\n visible: boolean;\n x: number;\n y: number;\n items: ContextMenuItem[];\n dir: 'ltr' | 'rtl';\n initialFocus: 'menu' | 'first-item';\n}\n\nconst CLOSED: MenuState = { visible: false, x: 0, y: 0, items: [], dir: 'ltr', initialFocus: 'menu' };\n\n/**\n * The menu is portaled to <body>, so it takes its direction from where it was opened: the event's\n * target, else the direction the caller passed (a workspace passes its own), else the page's.\n */\nfunction menuDirection(event: ShowContextMenuOptions['event'], dir: ShowContextMenuOptions['dir']): 'ltr' | 'rtl' {\n const target = event?.target;\n if (target instanceof Element) return isComputedRtl(target) ? 'rtl' : 'ltr';\n if (dir) return dir;\n return isComputedRtl(document.documentElement) ? 'rtl' : 'ltr';\n}\n\nexport const ContextMenu: React.ForwardRefExoticComponent<ContextMenuProps & React.RefAttributes<ContextMenuHandle>> = forwardRef<ContextMenuHandle, ContextMenuProps>(\n ({ theme = 'dark', formatMessageProvider, onShow, onHide, onOpenChange, className, style }, ref) => {\n const [menuState, setMenuState] = useState<MenuState>(CLOSED);\n const [submenuIndex, setSubmenuIndex] = useState<number | null>(null);\n // A submenu opened from the keyboard takes focus; one opened by hovering does not.\n const [submenuFocus, setSubmenuFocus] = useState(false);\n const menuRef = useRef<HTMLDivElement>(null);\n // Where focus was when the menu opened, so closing can hand it back (WAI-ARIA menu pattern).\n const openerRef = useRef<HTMLElement | null>(null);\n const restoreFocusRef = useRef(false);\n const submenuPanelRef = useRef<HTMLDivElement>(null);\n const itemRefs = useRef<Map<number, HTMLButtonElement | null>>(new Map());\n const timers = useRef<{\n open: ReturnType<typeof setTimeout> | null;\n close: ReturnType<typeof setTimeout> | null;\n }>({ open: null, close: null });\n\n const close = React.useCallback(() => {\n // Hand focus back to the opener only if it was inside the menu when it closed — an item's\n // action may itself have moved focus (opened a modal, say), and that must win.\n const active = document.activeElement;\n restoreFocusRef.current = !!active && (\n !!menuRef.current?.contains(active) || !!submenuPanelRef.current?.contains(active)\n );\n setMenuState(CLOSED);\n setSubmenuIndex(null);\n if (timers.current.open) clearTimeout(timers.current.open);\n if (timers.current.close) clearTimeout(timers.current.close);\n timers.current.open = null;\n timers.current.close = null;\n onHide?.();\n onOpenChange?.(false);\n }, [onHide, onOpenChange]);\n\n useImperativeHandle(ref, () => ({\n show({ event, x, y, items, dir, initialFocus }) {\n const coords = event ? getCoords(event) : { x: x ?? 0, y: y ?? 0 };\n openerRef.current = document.activeElement instanceof HTMLElement && document.activeElement !== document.body\n ? document.activeElement\n : null;\n itemRefs.current.clear();\n setMenuState({\n visible: true, x: coords.x, y: coords.y, items, dir: menuDirection(event, dir),\n initialFocus: initialFocus ?? (isKeyboardMenuEvent(event) ? 'first-item' : 'menu'),\n });\n setSubmenuIndex(null);\n setSubmenuFocus(false);\n onShow?.();\n onOpenChange?.(true);\n },\n }), [onShow, onOpenChange]);\n\n // Open: focus the menu itself (no item highlighted) or, for a keyboard-opened menu, its first\n // enabled item. Focusing an item is what made the browser's focus ring come and go with the\n // user's previous interaction. Close: return focus to the opener if the menu had it and\n // nothing else has taken it since.\n useLayoutEffect(() => {\n if (menuState.visible) {\n if (menuState.initialFocus === 'first-item') enabledItems(menuRef.current)[0]?.focus();\n else menuRef.current?.focus({ preventScroll: true });\n return;\n }\n if (!restoreFocusRef.current) return;\n restoreFocusRef.current = false;\n const opener = openerRef.current;\n const active = document.activeElement;\n if (opener?.isConnected && (!active || active === document.body)) opener.focus();\n }, [menuState.visible, menuState.items, menuState.initialFocus]);\n\n // Click-outside dismiss\n // Two listeners for full coverage:\n // pointerdown (capture) — fires before any canvas gesture handler; catches touch/stylus\n // click (bubble, window) — synthetic click survives stopPropagation on mousedown/pointerdown;\n // this is the reliable fallback for WebGL canvases (LuciadRIA, MapLibre, Three.js, etc.)\n useEffect(() => {\n if (!menuState.visible) return;\n const dismiss = (e: Event) => {\n // A click dispatched on `window` itself has no Node target, and `contains()` throws\n // for one. It is outside the menu by definition.\n if (!(e.target instanceof Node)) { close(); return; }\n if (menuRef.current?.contains(e.target as Node)) return;\n if (submenuPanelRef.current?.contains(e.target as Node)) return;\n close();\n };\n document.addEventListener('pointerdown', dismiss, { capture: true });\n window.addEventListener('click', dismiss);\n return () => {\n document.removeEventListener('pointerdown', dismiss, { capture: true });\n window.removeEventListener('click', dismiss);\n };\n }, [menuState.visible, close]);\n\n // Escape dismiss — a popup, so above any modal or drawer on the shared Escape stack.\n useEscapeLayer(menuState.visible, 'popup', close);\n\n // Viewport clamping for main menu\n useLayoutEffect(() => {\n if (!menuState.visible || !menuRef.current) return;\n const el = menuRef.current;\n const r = el.getBoundingClientRect();\n const PAD = 8;\n if (r.right > window.innerWidth - PAD) {\n el.style.left = `${Math.max(PAD, window.innerWidth - r.width - PAD)}px`;\n }\n if (r.bottom > window.innerHeight - PAD) {\n el.style.top = `${Math.max(PAD, window.innerHeight - r.height - PAD)}px`;\n }\n if (r.left < PAD) el.style.left = `${PAD}px`;\n if (r.top < PAD) el.style.top = `${PAD}px`;\n }, [menuState.visible]);\n\n if (!menuState.visible) return null;\n\n const fmt = formatMessageProvider;\n\n // Where the open sub-menu hangs from. The old computation took a distance from the right\n // edge under RTL and then used it as `left`, so the sub-menu landed far from its menu.\n const getSubmenuAnchor = (): SubMenuAnchor | null => {\n const itemEl = submenuIndex === null ? null : itemRefs.current.get(submenuIndex);\n const menuEl = menuRef.current;\n if (!itemEl || !menuEl) return null;\n const mr = menuEl.getBoundingClientRect();\n return { menuLeft: mr.left, menuRight: mr.right, top: itemEl.getBoundingClientRect().top, rtl: isComputedRtl(itemEl) };\n };\n const backToParentItem = () => {\n const parent = submenuIndex === null ? null : itemRefs.current.get(submenuIndex);\n setSubmenuIndex(null);\n setSubmenuFocus(false);\n parent?.focus();\n };\n\n function cancelOpenTimer() {\n if (timers.current.open) {\n clearTimeout(timers.current.open);\n timers.current.open = null;\n }\n }\n function cancelCloseTimer() {\n if (timers.current.close) {\n clearTimeout(timers.current.close);\n timers.current.close = null;\n }\n }\n\n function handleItemMouseEnter(index: number, item: ContextMenuItem) {\n cancelCloseTimer();\n // Switching away from a different open sub-menu\n if (submenuIndex !== null && submenuIndex !== index) {\n cancelOpenTimer();\n setSubmenuIndex(null);\n }\n if (isSubMenu(item) && item.items?.length) {\n cancelOpenTimer();\n timers.current.open = setTimeout(() => {\n // Opened by hovering: it must not take focus, even after a keyboard-opened submenu.\n setSubmenuFocus(false);\n setSubmenuIndex(index);\n }, 150);\n } else if (!isSubMenu(item)) {\n // Non-sub-menu item: close any open sub-menu after grace period\n cancelOpenTimer();\n if (submenuIndex !== null) {\n timers.current.close = setTimeout(() => setSubmenuIndex(null), 200);\n }\n }\n }\n\n const openSubmenuFromKeyboard = (index: number) => {\n cancelOpenTimer();\n cancelCloseTimer();\n setSubmenuFocus(true);\n setSubmenuIndex(index);\n };\n\n function handleMenuKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {\n if (e.key === 'Tab') { e.preventDefault(); close(); return; }\n const openKey = isComputedRtl(e.currentTarget) ? 'ArrowLeft' : 'ArrowRight';\n if (e.key === openKey) {\n const index = Number((document.activeElement as HTMLElement | null)?.dataset.menuIndex);\n const item = menuState.items[index];\n if (item && isSubMenu(item) && item.items?.length) { e.preventDefault(); openSubmenuFromKeyboard(index); }\n return;\n }\n if (moveMenuFocus(e.currentTarget, e.key)) {\n e.preventDefault();\n // Moving to another item closes an open submenu, as hovering another item does.\n if (submenuIndex !== null) setSubmenuIndex(null);\n }\n }\n\n function handleItemMouseLeave(item: ContextMenuItem) {\n cancelOpenTimer();\n if (isSubMenu(item) && item.items?.length) {\n timers.current.close = setTimeout(() => setSubmenuIndex(null), 200);\n }\n }\n\n return createPortal(\n <>\n <div\n ref={menuRef}\n className={`rdd-context-menu rdd-context-menu--${theme}${className ? ` ${className}` : ''}`}\n dir={menuState.dir}\n // No inline z-index: .rdd-context-menu's own `calc(var(--rdd-z-base, 1000) + 8500)`\n // owns it, so a WindowManagerProvider's zIndexBase actually shifts this menu (an\n // inline value here silently overrode it). Resolves to the same 9500 by default.\n style={{ left: menuState.x, top: menuState.y, ...style }}\n role=\"menu\"\n tabIndex={-1}\n aria-orientation=\"vertical\"\n onKeyDown={handleMenuKeyDown}\n >\n {menuState.items.map((item, i) => {\n if (isSeparator(item)) {\n return <hr key={i} className=\"rdd-context-menu__separator\" role=\"separator\" />;\n }\n\n if (isSubMenu(item)) {\n return (\n <button\n key={i}\n ref={el => { itemRefs.current.set(i, el); }}\n type=\"button\"\n className={`rdd-context-menu__item rdd-context-menu__item--has-submenu${submenuIndex === i ? ' rdd-context-menu__item--submenu-open' : ''}`}\n title={item.title ? resolveLabel(item.title, fmt) : undefined}\n data-menu-index={i}\n onMouseEnter={() => handleItemMouseEnter(i, item)}\n onMouseLeave={() => handleItemMouseLeave(item)}\n // Click, tap, Enter or Space. A keyboard click (detail 0) moves focus in.\n onClick={(e) => {\n if (!item.items?.length) return;\n cancelOpenTimer();\n cancelCloseTimer();\n setSubmenuFocus(e.detail === 0);\n setSubmenuIndex(submenuIndex === i && e.detail !== 0 ? null : i);\n }}\n role=\"menuitem\"\n aria-haspopup=\"true\"\n aria-expanded={submenuIndex === i}\n >\n <span className=\"rdd-context-menu__icon\" aria-hidden=\"true\" />\n <span className=\"rdd-context-menu__label\">{resolveLabel(item.label, fmt)}</span>\n <span className=\"rdd-context-menu__chevron\" aria-hidden=\"true\">›</span>\n </button>\n );\n }\n\n const simple = item as ContextMenuSimpleItem;\n const showChk = simple.checkbox && simple.checkbox.active !== false;\n const isChecked = showChk && simple.checkbox!.value;\n const isDisabled = simple.disabled === true || (showChk ? simple.checkbox!.enabled === false : false);\n\n return (\n <button\n key={i}\n ref={el => { itemRefs.current.set(i, el); }}\n data-menu-index={i}\n type=\"button\"\n className={`rdd-context-menu__item${isDisabled ? ' rdd-context-menu__item--disabled' : ''}`}\n title={simple.title ? resolveLabel(simple.title, fmt) : undefined}\n disabled={isDisabled}\n data-cy-action={simple.cyAction}\n onClick={() => { if (!isDisabled) { simple.action?.(); close(); } }}\n onMouseEnter={() => handleItemMouseEnter(i, item)}\n onMouseLeave={() => handleItemMouseLeave(item)}\n role={showChk ? 'menuitemcheckbox' : 'menuitem'}\n aria-checked={showChk ? isChecked : undefined}\n >\n {simple.icon\n ? <span className=\"rdd-context-menu__icon\">{simple.icon}</span>\n : <span className=\"rdd-context-menu__icon\" aria-hidden=\"true\" />}\n <span className=\"rdd-context-menu__label\">{resolveLabel(simple.label, fmt)}</span>\n {showChk && (\n <span className={`rdd-context-menu__checkbox${isChecked ? ' rdd-context-menu__checkbox--checked' : ''}`} aria-hidden=\"true\">\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"0.75\" y=\"0.75\" width=\"10.5\" height=\"10.5\" rx=\"2\"\n fill={isChecked ? 'currentColor' : 'none'}\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n />\n {isChecked && (\n <path d=\"M2.5 6 L4.5 8.5 L9.5 3.5\" stroke=\"white\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n )}\n </svg>\n </span>\n )}\n </button>\n );\n })}\n </div>\n\n {submenuIndex !== null && (() => {\n const sub = menuState.items[submenuIndex] as ContextMenuSubMenu;\n return (\n <SubMenuPanel\n ref={submenuPanelRef}\n items={sub.items ?? []}\n getAnchor={getSubmenuAnchor}\n autoFocus={submenuFocus}\n onBack={backToParentItem}\n theme={theme}\n dir={menuState.dir}\n fmt={fmt}\n onClose={close}\n onMouseEnter={() => cancelCloseTimer()}\n onMouseLeave={() => {\n timers.current.close = setTimeout(() => setSubmenuIndex(null), 200);\n }}\n />\n );\n })()}\n </>,\n document.body,\n );\n },\n);\n\nContextMenu.displayName = 'ContextMenu';\n\n// ─── Default adapter ──────────────────────────────────────────────────────────\n\nexport const DefaultContextMenuAdapter: ContextMenuAdapter = {\n Component: ContextMenu,\n};\n\n// ─── ContextMenuContext ────────────────────────────────────────────────────────\n// Decouples menu placement from WindowManager. Any component that renders\n// <ContextMenuProvider> makes showContextMenu available to all descendants,\n// regardless of where it sits relative to WindowManager in the tree.\n\ninterface ContextMenuContextValue {\n show: (options: ShowContextMenuOptions) => void;\n isOpen: boolean;\n}\n\nconst ContextMenuContext: React.Context<ContextMenuContextValue | null> = React.createContext<ContextMenuContextValue | null>(null);\n\nexport const ContextMenuProvider: React.FC<{\n adapter?: ContextMenuAdapter;\n children: React.ReactNode;\n} & ContextMenuProps> = ({ adapter = DefaultContextMenuAdapter, children, ...componentProps }) => {\n const menuRef = useRef<ContextMenuHandle>(null);\n const [isOpen, setIsOpen] = React.useState(false);\n const show = React.useCallback((opts: ShowContextMenuOptions) => {\n menuRef.current?.show(opts);\n }, []);\n return (\n <ContextMenuContext.Provider value={{ show, isOpen }}>\n {children}\n <adapter.Component\n ref={menuRef}\n {...componentProps}\n onShow={() => { setIsOpen(true); componentProps.onShow?.(); }}\n onHide={() => { setIsOpen(false); componentProps.onHide?.(); }}\n />\n </ContextMenuContext.Provider>\n );\n};\n\nexport function useShowContextMenu(): (options: ShowContextMenuOptions) => void {\n const ctx = React.useContext(ContextMenuContext);\n if (!ctx) throw new Error('useContextMenu must be used within <DockableDesktopProvider> or <RddContextMenu>');\n return ctx.show;\n}\n\n// Exported for the WindowManager.tsx bridge only — not re-exported from src/index.ts\nexport { ContextMenuContext };\n","export function isElementRtl(el: HTMLElement | null): boolean {\n if (!el) {\n if (typeof document !== 'undefined') {\n return (\n document.documentElement.dir?.toLowerCase() === 'rtl' ||\n document.body.dir?.toLowerCase() === 'rtl'\n );\n }\n return false;\n }\n\n // Check closest element with dir attribute\n const closestDirEl = el.closest('[dir]');\n if (closestDirEl) {\n return closestDirEl.getAttribute('dir')?.toLowerCase() === 'rtl';\n }\n\n // Fallback to document rules\n return (\n document.documentElement.dir?.toLowerCase() === 'rtl' ||\n document.body.dir?.toLowerCase() === 'rtl'\n );\n}\n\n/**\n * Whether `el` is laid out right-to-left, as the browser computes it — from a `dir` attribute on\n * any ancestor, the CSS `direction` property, or the workspace's own `setDirection`.\n *\n * Use this, not `document.documentElement.dir`, wherever a pointer delta (physical) is turned into\n * a size, side or index (logical): RTL is often set on `<body>` or a wrapper rather than `<html>`, and\n * the workspace can be RTL on an LTR page.\n */\nexport function isComputedRtl(el: Element | null | undefined): boolean {\n if (!el || typeof getComputedStyle === 'undefined') return false;\n return getComputedStyle(el).direction === 'rtl';\n}\n","/**\n * @file menuKeyboard.ts\n * @description Focus movement shared by the library's WAI-ARIA menus (the context menu and the\n * toolbar group flyout).\n */\n\n/** The enabled items of a menu element, in order. */\nexport const enabledItems = (menu: HTMLElement | null): HTMLElement[] =>\n menu ? Array.from(menu.querySelectorAll<HTMLElement>(':scope > [role^=\"menuitem\"]:not(:disabled)')) : [];\n\n/**\n * Up/Down/Home/End focus movement within one menu (WAI-ARIA menu pattern). Returns true when the\n * key was handled. Wraps around at either end; disabled items are skipped. From the menu element\n * itself (nothing highlighted), ArrowDown reaches the first item and ArrowUp the last.\n */\nexport function moveMenuFocus(menu: HTMLElement | null, key: string): boolean {\n const items = enabledItems(menu);\n if (items.length === 0) return false;\n const i = items.indexOf(document.activeElement as HTMLElement);\n let next: HTMLElement | undefined;\n if (key === 'ArrowDown') next = items[(i + 1) % items.length];\n // With the menu itself focused (i = -1, nothing highlighted yet) ArrowUp goes to the last item.\n else if (key === 'ArrowUp') next = items[i < 0 ? items.length - 1 : (i - 1 + items.length) % items.length];\n else if (key === 'Home') next = items[0];\n else if (key === 'End') next = items[items.length - 1];\n if (!next) return false;\n next.focus();\n return true;\n}\n","import React, { useContext, useState } from 'react';\nimport { WindowManagerProvider } from './WindowManagerContext';\nimport type { MessageFormatter, MessageDescriptor } from './WindowManagerContext';\nimport { PanelProvider } from './PanelProviderContext';\nimport { ToolbarProvider } from './ToolbarContext';\nimport { PanelContributionProvider } from './PanelContributionContext';\nimport { ContextMenuContext, ContextMenuProvider, DefaultContextMenuAdapter } from './ContextMenu';\nimport type { ContextMenuAdapter } from './ContextMenu';\nimport { WorkspaceClient } from '../WorkspaceClient';\nimport { WorkspaceInstanceContext } from './WorkspaceInstanceContext';\nimport type { Workspace } from '../api';\n\n/** Props for `<DockableDesktopProvider>`. */\nexport interface DockableDesktopProviderProps {\n children: React.ReactNode;\n /**\n * The workspace to render, from `createWorkspace()`. Omit it and the provider creates an empty\n * one of its own (register panels through `useWorkspace().registry`).\n */\n workspace?: Workspace<object>;\n /** Translates every built-in label. Overridden by the workspace's own `formatMessage`. */\n formatMessage?: MessageFormatter;\n /** Overrides any subset of the built-in message table. Overridden by the workspace's own `messages`. */\n messages?: Record<string, MessageDescriptor>;\n /** Initial layout direction, when the workspace doesn't set one. */\n dir?: 'ltr' | 'rtl';\n /** CSS class for the outer wrapper of every modal. */\n modalClass?: string;\n /** CSS class for the content area of every modal. */\n modalBodyClass?: string;\n /** CSS class for the outer wrapper of the side drawers. */\n sidePanelClass?: string;\n /** CSS class for the content area of the side drawers. */\n sidePanelBodyClass?: string;\n /** CSS class for the outer wrapper of floating windows. */\n windowClass?: string;\n /** CSS class for the content area of floating windows. */\n windowBodyClass?: string;\n /**\n * Starting z-index for floating windows and all of the library's chrome overlays, which shift\n * together via `--rdd-z-base`. @default 1000\n */\n zIndexBase?: number;\n /** Context menu implementation. Defaults to the built-in menu. */\n contextMenuAdapter?: ContextMenuAdapter;\n}\n\n/**\n * The one provider. Place it above everything from this library: `<RddDesktop>`, `<RddSidebar>`,\n * `<RddToolbar>`, `<RddSidePanels>`, `<RddModals>`.\n *\n * @example\n * ```tsx\n * const workspace = createWorkspace({ panels: { map: { component: MapPanel } } });\n *\n * <DockableDesktopProvider workspace={workspace}>\n * <RddSidebar tabs={tabs}>\n * <RddDesktop />\n * </RddSidebar>\n * <RddSidePanels />\n * <RddModals />\n * </DockableDesktopProvider>\n * ```\n */\nexport const DockableDesktopProvider: React.FC<DockableDesktopProviderProps> = (\n { contextMenuAdapter = DefaultContextMenuAdapter, workspace, messages, children, ...props }\n): React.ReactElement => {\n const existingCtxMenu = useContext(ContextMenuContext);\n const [ws] = useState(() => workspace ?? new WorkspaceClient<object>());\n\n const inner = (\n <WorkspaceInstanceContext.Provider value={ws}>\n <ToolbarProvider>\n <WindowManagerProvider client={ws} predefinedMessages={messages} {...props}>\n <PanelContributionProvider>\n <PanelProvider>\n {children}\n </PanelProvider>\n </PanelContributionProvider>\n </WindowManagerProvider>\n </ToolbarProvider>\n </WorkspaceInstanceContext.Provider>\n );\n\n if (existingCtxMenu !== null) return inner;\n\n return (\n <ContextMenuProvider\n adapter={contextMenuAdapter}\n formatMessageProvider={props.formatMessage}\n >\n {inner}\n </ContextMenuProvider>\n );\n};\n\n","/**\n * @file ToolbarContext.tsx\n * @description Toolbar state context — radio group selection and toggle modifier state.\n * Provided by DockableDesktopProvider; consumed via useToolbar() from anywhere in the tree.\n */\n\nimport React, { createContext, useContext, useMemo, useState } from 'react';\n\nexport interface ToolbarContextValue {\n /** Returns the active item id in a radio group, or null if none. */\n getActiveInGroup: (group: string) => string | null;\n /** Set the active item in a radio group (pass null to deselect all). */\n setActiveInGroup: (group: string, id: string | null) => void;\n /** Returns whether a toggle modifier is currently active. */\n isModifierActive: (id: string) => boolean;\n /** Explicitly set a toggle modifier's active state. */\n setModifierActive: (id: string, active: boolean) => void;\n /** Flip a toggle modifier between active and inactive. */\n toggleModifier: (id: string) => void;\n}\n\nconst ToolbarContext = createContext<ToolbarContextValue | null>(null);\n\nexport const ToolbarProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n const [radioGroups, setRadioGroups] = useState<Record<string, string | null>>({});\n const [modifiers, setModifiers] = useState<Record<string, boolean>>({});\n\n const value = useMemo<ToolbarContextValue>(() => ({\n getActiveInGroup: (group) => radioGroups[group] ?? null,\n setActiveInGroup: (group, id) => setRadioGroups(prev => ({ ...prev, [group]: id })),\n isModifierActive: (id) => modifiers[id] ?? false,\n setModifierActive: (id, active) => setModifiers(prev => ({ ...prev, [id]: active })),\n toggleModifier: (id) => setModifiers(prev => ({ ...prev, [id]: !prev[id] })),\n }), [radioGroups, modifiers]);\n\n return <ToolbarContext.Provider value={value}>{children}</ToolbarContext.Provider>;\n};\n\n/**\n * Returns toolbar state and control functions from anywhere inside\n * a `<DockableDesktopProvider>` tree.\n *\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n */\nexport function useToolbar(): ToolbarContextValue {\n const ctx = useContext(ToolbarContext);\n if (!ctx) throw new Error('useToolbar must be used within DockableDesktopProvider');\n return ctx;\n}\n","/**\n * @file PanelContributionContext.tsx\n * @description Lets any panel publish toolbar items and/or sidebar sections that\n * should only be surfaced while it is the globally active panel (`state.activePanelId`).\n * Optional, additive module — `DockableDesktopProvider` wires it up automatically.\n * Neither `<RddToolbar>` nor `<RddSidebar>` reads from this automatically; the app shell\n * merges `useActiveContribution()`'s result into its own `items`/`tabs` calls.\n */\n\nimport React, { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport type { ToolbarItem } from './Toolbar';\nimport type { SidebarTab } from './Sidebar';\nimport { usePanelId, useWindowManagerState } from './WindowManagerContext';\n\n/** A single named, labeled slot of content a panel contributes to the app's Sidebar while active. */\nexport interface PanelSidebarSection {\n id: string;\n label: string;\n icon?: React.ReactNode;\n content: React.ReactNode;\n}\n\n/**\n * What a panel publishes via `usePanelContribution()`. Both fields are optional and\n * independent — a panel may contribute only toolbar items, only sidebar sections,\n * both, or neither. The app decides what \"toolbar items\" and \"sidebar sections\" mean\n * for its own domain (map controls, document formatting, anything else).\n */\nexport interface PanelContribution {\n toolbarItems?: ToolbarItem[];\n sidebarSections?: PanelSidebarSection[];\n}\n\ntype Listener = () => void;\n\ninterface PanelContributionStore {\n publish(panelId: string, contribution: PanelContribution): () => void;\n get(panelId: string): PanelContribution | null;\n subscribe(listener: Listener): () => void;\n}\n\nfunction createPanelContributionStore(): PanelContributionStore {\n const contributions = new Map<string, PanelContribution>();\n const listeners = new Set<Listener>();\n const notify = () => listeners.forEach(l => l());\n\n return {\n publish(panelId, contribution) {\n contributions.set(panelId, contribution);\n notify();\n return () => {\n // Only clear if nothing else re-published for this id in the meantime.\n if (contributions.get(panelId) === contribution) {\n contributions.delete(panelId);\n notify();\n }\n };\n },\n get(panelId) {\n return contributions.get(panelId) ?? null;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\nconst PanelContributionContext = createContext<PanelContributionStore | null>(null);\n\n/**\n * Provider enabling `usePanelContribution()` / `useActiveContribution()`.\n * Mounted automatically by `DockableDesktopProvider` — only needed manually when\n * composing the internal provider directly without it.\n */\nexport const PanelContributionProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n const store = useMemo(() => createPanelContributionStore(), []);\n return <PanelContributionContext.Provider value={store}>{children}</PanelContributionContext.Provider>;\n};\n\n/**\n * Publish this panel's toolbar items and/or sidebar sections. Call on every render —\n * republishes automatically whenever `contribution` changes, and is cleared when the\n * panel unmounts. Memoize the object (and its array/callback contents, e.g. with\n * `useMemo`/`useCallback`) to avoid republishing on every unrelated re-render.\n *\n * Contributions are only ever surfaced while this panel is `state.activePanelId` —\n * see `useActiveContribution()`.\n *\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n * @example\n * function MapPanel() {\n * const [controller, setController] = useState<'pan' | 'draw' | 'measure'>('pan');\n * usePanelContribution({\n * toolbarItems: (['pan', 'draw', 'measure'] as const).map(id => ({\n * type: 'toggle', id, label: id, icon: icons[id],\n * active: controller === id, onToggle: () => setController(id),\n * })),\n * sidebarSections: [{ id: 'layers', label: 'Layers', content: <LayerList /> }],\n * });\n * // ...\n * }\n */\nexport function usePanelContribution(contribution: PanelContribution): void {\n const panelId = usePanelId();\n const store = useContext(PanelContributionContext);\n const cleanupRef = useRef<(() => void) | null>(null);\n\n if (!store) throw new Error('usePanelContribution must be used within <DockableDesktopProvider>');\n\n useLayoutEffect(() => {\n if (!store) return;\n cleanupRef.current?.();\n cleanupRef.current = store.publish(panelId, contribution);\n return () => {\n cleanupRef.current?.();\n cleanupRef.current = null;\n };\n }, [store, panelId, contribution]);\n}\n\n/**\n * Returns whatever the currently active panel (`state.activePanelId`) has published\n * via `usePanelContribution()`, or `null` if no panel is active or the active panel\n * hasn't contributed anything. Intended for the app shell to merge into its own\n * `<RddToolbar items={...}>` / `<RddSidebar tabs={...}>` calls.\n *\n * @throws Error if used outside of a {@link DockableDesktopProvider}.\n */\nexport function useActivePanelContribution(): PanelContribution | null {\n const activePanelId = useWindowManagerState(s => s.activePanelId);\n const store = useContext(PanelContributionContext);\n\n if (!store) throw new Error('useActiveContribution must be used within <DockableDesktopProvider>');\n\n const subscribe = useCallback(\n (onChange: Listener) => (store ? store.subscribe(onChange) : () => {}),\n [store]\n );\n const getSnapshot = () => (store && activePanelId ? store.get(activePanelId) : null);\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * Converts a contributed sidebar section into a `SidebarTab` for `<RddSidebar tabs={...}>`.\n * `SidebarTab.icon` is optional but recommended unless the tab is `hidden`; supply\n * `fallbackIcon` for sections that omit one.\n * `eagerMount`/`preserveState` have no contribution-side equivalent — a contribution\n * only exists while its owning panel is mounted and active, so both are left unset.\n */\nexport function sidebarSectionToTab(section: PanelSidebarSection, fallbackIcon: React.ReactNode = null): SidebarTab {\n return {\n id: section.id,\n label: section.label,\n icon: section.icon ?? fallbackIcon,\n renderContent: () => section.content,\n };\n}\n\n/**\n * Convenience wrapper around `useActiveContribution()` for the common case:\n * append the active panel's contributed toolbar items (behind a separator) to a\n * static list. Returns `staticItems` unchanged when there's nothing to add.\n * For manual control (a different merge position, no separator, etc.), call\n * `useActiveContribution()` directly instead.\n */\nexport function useMergedToolbarItems(staticItems: ToolbarItem[]): ToolbarItem[] {\n const active = useActivePanelContribution();\n return active?.toolbarItems?.length\n ? [...staticItems, { type: 'separator' }, ...active.toolbarItems]\n : staticItems;\n}\n\n/**\n * Convenience wrapper around `useActiveContribution()` for the common case:\n * append the active panel's contributed sidebar sections (via `sectionToTab`)\n * to a static tab list, as dynamic tabs that appear only while their panel is active.\n * Returns `staticTabs` unchanged when there's nothing to add.\n */\nexport function useMergedSidebarTabs(staticTabs: SidebarTab[], fallbackIcon: React.ReactNode = null): SidebarTab[] {\n const active = useActivePanelContribution();\n return active?.sidebarSections?.length\n ? [...staticTabs, ...active.sidebarSections.map(section => sidebarSectionToTab(section, fallbackIcon))]\n : staticTabs;\n}\n","/**\n * @file WindowManager.tsx\n * @description Core component for react-dockable-desktop layout engine.\n * Renders the workspace desktop containing docked splits, tabbed panels, floated windows,\n * resize handles, context menus, and taskbar docks. Exposes lifecycle event listeners.\n */\n\nimport React, { useState, useRef, useEffect, useCallback, useContext } from 'react';\nimport { useIsClient } from '../utils/useIsClient';\nimport type { TabContentProps } from '../types';\nimport { forgetPanelDom } from './domPreservation';\nimport { usePanelHost } from './workspace/panelHost';\nimport { claimDocumentMirror, releaseDocumentMirror } from '../utils/documentMirror';\nimport { WindowStoreSyncContext, useWindowManagerState, useWindowManagerActionsInternal, useFormatMessage, formatLabel, usePredefinedMessages, useStyleClasses, useRegistry } from './WindowManagerContext';\nimport { DefaultContextMenuAdapter, ContextMenuContext } from './ContextMenu';\nimport type { ContextMenuHandle, ContextMenuAdapter } from './ContextMenu';\nimport { usePanelActions } from './PanelProviderContext';\nimport ConfirmationForm from '../forms/ConfirmationForm';\nimport { useColorScheme } from '../hooks/useColorScheme';\nimport { PanelMount } from './workspace/panelMount';\nimport { DragGhost } from './workspace/DragGhost';\nimport { WorkspaceGrid } from './workspace/WorkspaceGrid';\nimport { WorkspaceZones } from './workspace/WorkspaceZones';\nimport { FloatingWindows } from './workspace/FloatingWindows';\nimport { Taskbar, type HoveredMinimized } from './workspace/Taskbar';\nimport { useDragTargets } from './workspace/useDragTargets';\nimport { createTabDrag } from './workspace/tabDrag';\nimport { createWorkspaceMenus } from './workspace/workspaceMenus';\nimport { useWorkspaceSize } from './workspace/useWorkspaceSize';\nimport { createFloatingWindowDrag } from './workspace/floatingWindowDrag';\n\n\n\n// ==========================================\n// 5. WindowManager (Main Render Component)\n// ==========================================\n\n/** Controls when the minimized-panel taskbar is visible. */\nexport type TaskbarVisibility = 'always' | 'compact' | 'autohide';\n\n/** Props for `<RddDesktop>`. */\nexport interface RddDesktopProps {\n /** Built-in skin name or a custom skin key registered via CSS. @default 'vscode' */\n skin?: string;\n /** Fallback icon shown in panel tabs when no panel-specific icon is provided. */\n defaultPanelIcon?: React.ReactNode;\n /**\n * Controls taskbar visibility.\n * - `'always'` — permanent bar at the bottom\n * - `'compact'` — only visible when minimized panels exist\n * - `'autohide'` — overlay bar with 8 px peek strip (default)\n * @default 'autohide'\n */\n taskbarVisibility?: TaskbarVisibility;\n /** Enables the library's own transitions/animations (tab hover, dock preview, etc.). Never affects the consumer's own page. @default true */\n animations?: boolean;\n /**\n * What the workspace shows while no panel is docked: a welcome screen, a \"pick a file\" prompt.\n * It fills the empty group in place of the built-in message; the group stays a drop target, so a\n * floating window can still be docked into it. Floating windows still show over it. (7.8.0)\n */\n emptyWorkspace?: React.ReactNode;\n /**\n * Your own content for each tab in the grid: an icon, the title, a badge, a status dot (7.10.0).\n * It replaces the built-in icon, title and dirty marker; the tab itself (dragging, keyboard,\n * accessibility, its context menu, header actions and close button) stays the library's.\n * Called with the tab's `TabContentProps`; branch on `component` for a per-type look.\n */\n renderTabContent?: (tab: TabContentProps) => React.ReactNode;\n}\n\n/**\n * The desktop itself: the docked grid of tab groups, the floating windows, the taskbar of\n * minimized panels, and the drop targets while a panel is dragged. Render it inside\n * `<DockableDesktopProvider>`, in a container that gives it a size (`rdd-fill-viewport` fills the\n * page), and import `react-dockable-desktop/styles.css` once.\n *\n * Exported as `RddDesktop`.\n *\n * @example\n * ```tsx\n * <DockableDesktopProvider workspace={workspace}>\n * <div className=\"rdd-fill-viewport\">\n * <RddDesktop skin=\"vscode\" taskbarVisibility=\"autohide\" />\n * </div>\n * <RddModals />\n * </DockableDesktopProvider>\n * ```\n */\nexport const WindowManager: React.FC<RddDesktopProps> = ({ skin = 'vscode', defaultPanelIcon, taskbarVisibility = 'autohide', animations = true, emptyWorkspace, renderTabContent }) => {\n // The context menu comes from <DockableDesktopProvider contextMenuAdapter={…}>. This built-in\n // fallback only renders when no provider supplies one (the library's own tests).\n const contextMenuAdapter: ContextMenuAdapter = DefaultContextMenuAdapter;\n const state = useWindowManagerState();\n const panelHost = usePanelHost();\n const registry = useRegistry();\n const { restorePanel, minimizePanel, requestClosePanel, maximizePanel, updateFloatingPosition, focusPanel, floatPanel, setDraggedPanelId, dockPanelToGroup, movePanelOrder, dockPanelToWorkspaceEdge, setActivePanel, getPanelContextMenuItems, showContextMenu, registerContextMenuFn, isDropAllowed } = useWindowManagerActionsInternal();\n const { openModal } = usePanelActions();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n\n const handleRequestClose = React.useCallback((id: string) => {\n const panel = state.panels[id];\n return requestClosePanel(id, {\n onConfirm: (customOpts) => new Promise<boolean>((resolve) => {\n const opts = customOpts || panel?.dirtyOptions;\n const baseTitle = formatLabel(panel ? panel.title : messages.untitledPanel, formatMessage);\n openModal(\n ConfirmationForm,\n {\n title: opts?.title || messages.unsavedChangesTitle,\n message: opts?.message || {\n id: messages.unsavedChangesMessage.id,\n defaultMessage: messages.unsavedChangesMessage.defaultMessage,\n values: { title: baseTitle }\n },\n alert: opts?.alert,\n alertType: opts?.alertType || 'danger',\n useYesNoTitles: true,\n // Settles on every exit: Yes, No, Escape, the backdrop, the × or closeAll (7.7.0).\n onSettled: resolve,\n },\n { size: 'small' }\n );\n })\n });\n }, [requestClosePanel, state.panels, formatMessage, openModal, messages]);\n\n const { windowClass, windowBodyClass } = useStyleClasses();\n const ctxMenu = useContext(ContextMenuContext);\n const contextMenuRef = useRef<ContextMenuHandle>(null);\n\n useEffect(() => {\n if (ctxMenu !== null) {\n return registerContextMenuFn((opts) => ctxMenu.show(opts));\n } else {\n return registerContextMenuFn((opts) => contextMenuRef.current?.show(opts));\n }\n }, [ctxMenu, registerContextMenuFn]);\n\n const taskbarRef = useRef<HTMLDivElement | null>(null);\n const tooltipRef = useRef<HTMLDivElement | null>(null);\n const [taskbarExpanded, setTaskbarExpanded] = useState(false);\n const taskbarCollapseTimerRef = useRef<ReturnType<typeof setTimeout>>(null);\n // The pointer is on the taskbar: it must not slide away under it (a press there would be lost).\n const taskbarHoveredRef = useRef(false);\n const prevMinimizedLengthRef = useRef(state.minimized.length);\n\n const [hoveredMinimized, setHoveredMinimized] = useState<HoveredMinimized | null>(null);\n const minimizedTooltipTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);\n const lastTaskbarPointerTypeRef = useRef<string>('mouse');\n const [internalContextMenuOpen, setInternalContextMenuOpen] = useState(false);\n const isContextMenuOpen = ctxMenu !== null ? ctxMenu.isOpen : internalContextMenuOpen;\n\n useEffect(() => {\n return () => {\n // The timer pending at unmount is the one to clear, so the ref is read here on purpose.\n if (minimizedTooltipTimeoutRef.current) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n clearTimeout(minimizedTooltipTimeoutRef.current);\n }\n };\n }, []);\n\n useEffect(() => {\n if (hoveredMinimized) {\n const isStillMinimized = state.minimized.some(m => m.id === hoveredMinimized.id);\n if (!isStillMinimized) {\n // Cleared rather than derived: a stale preview kept in state would come back, with its old\n // position, if the same panel were minimized again.\n // eslint-disable-next-line react-hooks/set-state-in-effect\n setHoveredMinimized(null);\n }\n }\n }, [state.minimized, hoveredMinimized]);\n\n useEffect(() => {\n if (!hoveredMinimized?.fromTouch) return;\n const handler = (e: PointerEvent) => {\n if (e.pointerType !== 'touch') return;\n if (tooltipRef.current?.contains(e.target as Node)) return;\n setHoveredMinimized(null);\n };\n document.addEventListener('pointerdown', handler, { capture: true });\n return () => document.removeEventListener('pointerdown', handler, { capture: true });\n }, [hoveredMinimized?.fromTouch]);\n\n // Where a dragged panel would land; read by the drag handlers below and drawn by the zones.\n // Read live from the store, not from this render: drag handlers keep the deps of the render they\n // started in, before the dragged panel was set (7.9.0).\n const storeSync = useContext(WindowStoreSyncContext);\n const canInsertInto = (leafId: string) => {\n const dragged = storeSync?.getSnapshot().draggedPanelId ?? null;\n return dragged !== null && isDropAllowed(dragged, { kind: 'group', leafId, position: 'center' });\n };\n const targets = useDragTargets({ setDraggedPanelId, isRtl: state.isRtl, canInsertInto });\n const { activeDropZone, setActiveDropZone, dragPos, activeEdgeDrop, setActiveEdgeDrop, activeCornerAnchor, setActiveCornerAnchor, hoveredTab, setHoveredTab, handleTabHover, handleHoverDropZone } = targets;\n\n const { handleTabRightClick, handleMinimizedRightClick } = createWorkspaceMenus({\n state, registry, messages, formatMessage, handleRequestClose, setHoveredMinimized,\n actions: { floatPanel, minimizePanel, restorePanel, maximizePanel, getPanelContextMenuItems, showContextMenu, isDropAllowed },\n });\n\n const { handleTabDragStart } = createTabDrag({\n state, targets, handleTabRightClick,\n actions: { dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, floatPanel, setDraggedPanelId, isDropAllowed },\n });\n\n // Drop the preserved DOM of panels that are no longer open — this workspace's own only.\n useEffect(() => {\n const keys = Object.keys(state.panels);\n for (const cachedId of panelHost.ids()) {\n if (!keys.includes(cachedId)) {\n const el = panelHost.getElement(cachedId);\n panelHost.forget(cachedId);\n if (el) forgetPanelDom(el);\n }\n }\n }, [state.panels, panelHost]);\n\n // Safe window blur handler to cancel sticky dragging states when iframe/webview loses focus\n useEffect(() => {\n const handleWindowBlur = () => {\n if (state.draggedPanelId !== null) {\n setDraggedPanelId(null);\n setActiveDropZone(null);\n setHoveredTab(null);\n }\n };\n window.addEventListener('blur', handleWindowBlur);\n return () => {\n window.removeEventListener('blur', handleWindowBlur);\n };\n }, [state.draggedPanelId, setDraggedPanelId, setActiveDropZone, setHoveredTab]);\n\n const workspaceRef = useRef<HTMLDivElement | null>(null);\n const workspaceSize = useWorkspaceSize(workspaceRef);\n\n // Sync / Realignment Effect when actual workspace size changes\n useEffect(() => {\n const viewW = workspaceSize.width;\n const viewH = workspaceSize.height;\n\n state.floating.forEach(w => {\n const winW = typeof w.width === 'string' ? parseFloat(w.width) : w.width;\n const winH = typeof w.height === 'string' ? parseFloat(w.height) : w.height;\n const winX = typeof w.x === 'string' ? parseFloat(w.x) : w.x;\n const winY = typeof w.y === 'string' ? parseFloat(w.y) : w.y;\n\n let newWidth = winW;\n let newHeight = winH;\n let newX = winX;\n let newY = winY;\n let changed = false;\n\n // Clamp window size if it exceeds the new workspace size (applies whether anchored or free-floating)\n if (newWidth > viewW) {\n newWidth = Math.max(200, viewW - 20);\n changed = true;\n }\n if (newHeight > viewH) {\n newHeight = Math.max(150, viewH - 40);\n changed = true;\n }\n\n // Anchored windows are positioned entirely by `anchor` + `dir` at render time (see the\n // floating-window style callback below), so x/y don't affect their visual position —\n // only free-floating windows need off-screen bounds clamping here.\n if (!w.anchor) {\n const maxX = viewW - 100; // Keep at least 100px of titlebar visible\n if (newX > maxX) {\n newX = Math.max(0, maxX);\n changed = true;\n }\n const maxY = viewH - 40; // Keep titlebar clickable\n if (newY > maxY) {\n newY = Math.max(0, maxY);\n changed = true;\n }\n }\n\n if (changed) {\n updateFloatingPosition(w.id, {\n x: newX,\n y: newY,\n width: newWidth,\n height: newHeight\n });\n }\n });\n }, [workspaceSize, state.floating, updateFloatingPosition]);\n\n // Global Window Focus Event Delegation (Left-click/touch anywhere inside a window or grid panel focuses it)\n useEffect(() => {\n const handlePointerDownGlobal = (e: PointerEvent) => {\n // Only handle primary button (left-click or first touch point)\n if (e.button !== 0) return;\n\n const target = e.target as HTMLElement | null;\n if (!target || typeof target.closest !== 'function') return;\n\n // 1. Check if click is inside a floating window\n const windowEl = target.closest('.rdd-floating-window') as HTMLElement | null;\n if (windowEl) {\n const winId = windowEl.getAttribute('data-window-id');\n if (winId) {\n setActivePanel(winId);\n focusPanel(winId);\n }\n return;\n }\n\n // 2. Check if click is inside a grid split pane\n const panelEl = target.closest('.rdd-workspace-panel') as HTMLElement | null;\n if (panelEl) {\n const panelId = panelEl.getAttribute('data-active-panel-id');\n if (panelId) {\n setActivePanel(panelId);\n }\n }\n };\n\n document.addEventListener('pointerdown', handlePointerDownGlobal);\n return () => {\n document.removeEventListener('pointerdown', handlePointerDownGlobal);\n };\n }, [focusPanel, setActivePanel]);\n\n const { startDrag, startResize } = createFloatingWindowDrag({\n state, workspaceSize, targets,\n actions: { focusPanel, updateFloatingPosition, dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, setDraggedPanelId, isDropAllowed },\n });\n\n // horizontal scroll for minimized taskbar\n const scrollTaskbar = (direction: 'left' | 'right') => {\n if (taskbarRef.current) {\n const amount = direction === 'left' ? -150 : 150;\n taskbarRef.current.scrollBy({ left: amount, behavior: 'smooth' });\n }\n };\n\n // Every collapse goes through here: it replaces any pending timer (never leaves one behind to\n // fire later), and does nothing while the pointer is on the taskbar.\n const scheduleCollapseTaskbar = useCallback((delayMs: number) => {\n if (taskbarCollapseTimerRef.current) clearTimeout(taskbarCollapseTimerRef.current);\n taskbarCollapseTimerRef.current = setTimeout(() => {\n taskbarCollapseTimerRef.current = null;\n if (!taskbarHoveredRef.current) setTaskbarExpanded(false);\n }, delayMs);\n }, []);\n\n const expandTaskbar = useCallback(() => {\n taskbarHoveredRef.current = true;\n if (taskbarCollapseTimerRef.current) clearTimeout(taskbarCollapseTimerRef.current);\n setTaskbarExpanded(true);\n }, []);\n\n const leaveTaskbar = useCallback(() => {\n taskbarHoveredRef.current = false;\n scheduleCollapseTaskbar(400);\n }, [scheduleCollapseTaskbar]);\n\n useEffect(() => () => { if (taskbarCollapseTimerRef.current) clearTimeout(taskbarCollapseTimerRef.current); }, []);\n\n useEffect(() => {\n if (taskbarVisibility === 'autohide' && state.minimized.length > prevMinimizedLengthRef.current) {\n setTaskbarExpanded(true);\n scheduleCollapseTaskbar(2000);\n }\n // The autohide taskbar unmounts when nothing is minimized; a pointer that was on it then gets\n // no pointerleave, so forget it here.\n if (state.minimized.length === 0) taskbarHoveredRef.current = false;\n prevMinimizedLengthRef.current = state.minimized.length;\n }, [state.minimized.length, taskbarVisibility, scheduleCollapseTaskbar]);\n\n // Fetch the active color-scheme from documentElement to make sure nested variables resolve correctly\n const currentColorScheme = useColorScheme();\n const isClient = useIsClient();\n\n // Mirror the skin and the animations opt-out onto <html>, so what renders outside the workspace\n // element (RddToolbar, RddSidebar, portaled menus, toasts, flyouts) gets them too. Through the\n // document mirror, keyed by this workspace: with several on one page the newest wins, and unmounting\n // one hands <html> back to the others rather than clearing it. The claim and its release are\n // separate effects so a skin change updates the claim in place instead of re-stacking it.\n useEffect(() => {\n claimDocumentMirror(panelHost, { skin: skin || null, noAnimations: !animations });\n }, [panelHost, skin, animations]);\n useEffect(() => () => releaseDocumentMirror(panelHost, ['skin', 'noAnimations']), [panelHost]);\n\n return (\n <div\n className={`rdd-workspace${animations ? '' : ' rdd-no-animations'}`}\n data-rdd-skin={skin}\n data-color-scheme={currentColorScheme}\n dir={state.dir}\n // Focusable from script only: where keyboard focus goes when the last tab it was on closes.\n tabIndex={-1}\n >\n\n {/* 1. Main Workspace Viewport (Grids & Floating Panels) */}\n <div\n ref={workspaceRef}\n className={`rdd-workspace-viewport${state.draggedPanelId ? ' rdd-dragging-active' : ''}`}\n >\n <WorkspaceZones state={state} activeEdgeDrop={activeEdgeDrop} activeCornerAnchor={activeCornerAnchor} setActiveEdgeDrop={setActiveEdgeDrop} setActiveCornerAnchor={setActiveCornerAnchor} isDropAllowed={isDropAllowed} />\n\n {/* 1.1 Viewport Split Grid Layout */}\n <div className=\"rdd-workspace-grid-host\">\n {state.gridRoot ? (\n <WorkspaceGrid\n node={state.gridRoot}\n path={[]}\n onTabRightClick={handleTabRightClick}\n activeDropZone={activeDropZone}\n onHoverDropZone={handleHoverDropZone}\n onTabDragStart={handleTabDragStart}\n hoveredTab={hoveredTab}\n onTabHover={handleTabHover}\n defaultPanelIcon={defaultPanelIcon}\n onRequestClosePanel={handleRequestClose}\n emptyWorkspace={emptyWorkspace}\n renderTabContent={renderTabContent}\n />\n ) : (\n <div className=\"rdd-empty-workspace-grid\">\n {formatLabel(messages.emptyGrid, formatMessage)}\n </div>\n )}\n </div>\n\n <FloatingWindows\n state={state}\n registry={registry}\n windowClass={windowClass}\n windowBodyClass={windowBodyClass}\n defaultPanelIcon={defaultPanelIcon}\n messages={messages}\n formatMessage={formatMessage}\n setActivePanel={setActivePanel}\n focusPanel={focusPanel}\n maximizePanel={maximizePanel}\n minimizePanel={minimizePanel}\n getPanelContextMenuItems={getPanelContextMenuItems}\n showContextMenu={showContextMenu}\n handleRequestClose={handleRequestClose}\n startDrag={startDrag}\n startResize={startResize}\n />\n </div>\n\n {/* 2. macOS / Windows 11-style Taskbar Sibling Footer (Flex-shrinked at bottom) */}\n <Taskbar\n state={state}\n registry={registry}\n taskbarVisibility={taskbarVisibility}\n taskbarExpanded={taskbarExpanded}\n expandTaskbar={expandTaskbar}\n leaveTaskbar={leaveTaskbar}\n scrollTaskbar={scrollTaskbar}\n taskbarRef={taskbarRef}\n tooltipRef={tooltipRef}\n defaultPanelIcon={defaultPanelIcon}\n messages={messages}\n formatMessage={formatMessage}\n lastTaskbarPointerTypeRef={lastTaskbarPointerTypeRef}\n hoveredMinimized={hoveredMinimized}\n setHoveredMinimized={setHoveredMinimized}\n minimizedTooltipTimeoutRef={minimizedTooltipTimeoutRef}\n isContextMenuOpen={isContextMenuOpen}\n handleMinimizedRightClick={handleMinimizedRightClick}\n handleRequestClose={handleRequestClose}\n restorePanel={restorePanel}\n />\n\n {/* 3. Persistence Port: Portals rendering panels into off-screen elements. Client only:\n the server has no DOM to create them in, and panel bodies fill in after hydration. */}\n {isClient && Object.keys(state.panels).map((id) => <PanelMount key={id} panelId={id} />)}\n\n {/* 4. Context Menu — only rendered when no parent ContextMenuProvider is in the tree */}\n {ctxMenu === null && (\n <contextMenuAdapter.Component\n ref={contextMenuRef}\n theme=\"dark\"\n formatMessageProvider={formatMessage}\n onShow={() => setInternalContextMenuOpen(true)}\n onHide={() => setInternalContextMenuOpen(false)}\n />\n )}\n\n {/* 5. Dragging Tab Ghost Representation */}\n {state.draggedPanelId !== null && !state.floating.some(w => w.id === state.draggedPanelId) && (\n <DragGhost dragPos={dragPos}>\n 📄 {formatLabel(state.panels[state.draggedPanelId]?.title || messages.untitledPanel, formatMessage)}\n </DragGhost>\n )}\n\n\n\n </div>\n );\n};\n\nexport default WindowManager;\n","import { useSyncExternalStore } from 'react';\n\nconst subscribeNever = () => () => {};\nconst isClient = () => true;\nconst isServer = () => false;\n\n/**\n * False on the server and during hydration, true once mounted on the client — without a\n * hydration mismatch (`useSyncExternalStore` renders the server value while hydrating, then\n * re-renders with the client one). Gate anything that needs the DOM (portals, created elements)\n * behind it.\n */\nexport function useIsClient(): boolean {\n return useSyncExternalStore(subscribeNever, isClient, isServer);\n}\n","import { useSyncExternalStore } from 'react';\n\ntype ColorScheme = 'dark' | 'light';\n\nconst readScheme = (): ColorScheme =>\n document.documentElement.getAttribute('data-color-scheme') === 'light' ? 'light' : 'dark';\n\nconst subscribe = (onChange: () => void): (() => void) => {\n const observer = new MutationObserver(onChange);\n observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-color-scheme'] });\n return () => observer.disconnect();\n};\n\n// The server can't see the page's scheme. Dark is the library's default, so server-rendered\n// HTML says dark and hydration corrects it on the client — `useSyncExternalStore` renders the\n// server value during hydration and then the real one, without a mismatch.\nconst serverScheme = (): ColorScheme => 'dark';\n\n/**\n * Reactively reads the page's `data-color-scheme` attribute on `<html>` — the one the host\n * application sets to switch the library's scheme (the library itself never writes it) —\n * returning `'dark'` or `'light'` and re-rendering whenever it changes.\n *\n * Useful for panel content that needs to react to the same scheme the\n * workspace itself is using — e.g. swapping a map's tile layer or an\n * embedded editor's theme to match.\n *\n * Returns `'dark'` when rendered on the server.\n */\nexport function useColorScheme(): ColorScheme {\n return useSyncExternalStore(subscribe, readScheme, serverScheme);\n}\n","/**\n * @file panelMount.tsx\n * @description Where panels live: the slots that place a panel's preserved DOM (in a tab, a window, a taskbar preview), its lifecycle events and form container. The DOM, sizes and lifecycle handlers themselves belong to the workspace's own panel host (`panelHost.ts`).\n */\nimport React, { useRef, useState, useEffect, useLayoutEffect } from 'react';\nimport { createPortal } from 'react-dom';\nimport { restorePanelDom } from '../domPreservation';\nimport { useWindowManagerState, useWindowManagerActions, useFormatMessage, formatLabel, usePredefinedMessages, useRegistry } from '../WindowManagerContext';\nimport type { PanelInfo, MessageDescriptor, MessageFormatter, WorkspaceState } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport { FormContainerProvider } from '../FormContainerContext';\nimport type { FormContainerContract, ContainerType } from '../FormContainerContext';\nimport { usePanelHost } from './panelHost';\nimport { isShownInGrid } from '../../core/layoutTree';\nimport { optionsFor } from '../../core/panelOptions';\nimport { moveInto, moveIntoWhenConnected, leaveSlot, setPreserveEmbeds, preservesEmbeds } from '../domMove';\nimport type { PanelHost } from './panelHost';\n\n/**\n * For an element that keeps its embeds (`preserveEmbeds`, 7.11.0): parks it before React removes\n * this slot's node. The slot's own cleanup is a passive effect, which runs after the node, with the\n * element still in it, has been removed: that detaches the element, and an iframe in it reloads.\n * A layout cleanup runs before. Any other element is left to the passive cleanup, as before.\n */\nfunction useParkBeforeRemoval(hostRef: React.RefObject<HTMLDivElement | null>, panelId: string, panelHost: PanelHost): void {\n useLayoutEffect(() => {\n const host = hostRef.current;\n return () => {\n const el = panelHost.getElement(panelId);\n if (host && el && el.parentNode === host && preservesEmbeds(el)) panelHost.park(el);\n };\n }, [hostRef, panelId, panelHost]);\n}\n\n/** Whether a panel is on screen: floating, or the selected tab of its group (not minimized). */\nconst isPanelShown = (s: WorkspaceState, panelId: string): boolean => {\n const state = s.panels[panelId]?.state;\n if (state === 'floating') return true;\n if (state !== 'docked') return false;\n return isShownInGrid(s.gridRoot, panelId);\n};\n\n\n\n// ==========================================\n// 3. Persistent DOM Container Host & Slot\n// ==========================================\n\nexport const renderPanelContent = (\n id: string,\n panel: PanelInfo,\n registry: PanelRegistry,\n messages: Record<MessageKey, MessageDescriptor>,\n formatMessage: MessageFormatter,\n): React.ReactNode => {\n const componentKey = panel.component;\n const registryEntry = registry.get(componentKey);\n if (!registryEntry) {\n console.warn(\n `[react-dockable-desktop] Panel \"${id}\" references component key \"${componentKey}\" ` +\n `which is not registered. Add it to the workspace's panels:\\n` +\n ` createWorkspace({ panels: { \"${componentKey}\": { component: YourComponent } } })`\n );\n return (\n <div className=\"rdd-unregistered-panel\">\n <h6 className=\"rdd-unregistered-panel__title\">⚠️ {formatLabel(messages.componentUnregistered, formatMessage)}</h6>\n <span className=\"rdd-unregistered-panel__key\">{formatLabel({ ...messages.componentKey, values: { key: componentKey } }, formatMessage)}</span>\n </div>\n );\n }\n const Component = registryEntry.Component;\n // Props spread first, panelId second — a caller-supplied prop of the same name can never\n // shadow the injected id. Matches ModalStackRenderer/SidePanelRenderer's spread order exactly.\n return <Component {...(panel.props ?? {})} panelId={id} />;\n};\n\n/**\n * A hosted panel's body (7.11.0): it shows the content element of the managed widget it hosts.\n * The content is rendered once, by the widget's overlay in its owner panel, so nothing here mounts\n * it; this only attaches the element, and takes it back out on unmount unless it has already gone\n * somewhere else (back into its panel).\n */\nconst HostedWidgetSlot: React.FC<{ panelId: string }> = ({ panelId }) => {\n const panelHost = usePanelHost();\n const slotRef = useRef<HTMLDivElement | null>(null);\n // Read here, not only in the effect: a widget closed and re-opened out of its panel in one tick\n // gets a new element under the same panel id, and React keeps this slot mounted. The panel's\n // entry is new then, so this re-renders and the effect attaches the new element.\n const el = panelHost.getHostedContent(panelId);\n useLayoutEffect(() => {\n const slot = slotRef.current;\n if (!slot || !el) return;\n // This slot is inside the hosted panel's own element, which the workspace may not have attached\n // yet: an element that keeps its embeds waits for it (see domMove.ts).\n const cancel = moveIntoWhenConnected(slot, el);\n restorePanelDom(el, { refocus: false });\n return () => { cancel(); leaveSlot(slot, el); };\n }, [el]);\n return <div ref={slotRef} className=\"rdd-hosted-widget\" />;\n};\n\nexport const PreservedDOMWrapper: React.FC<{ panelId: string }> = ({ panelId }) => {\n const panelHost = usePanelHost();\n const registry = useRegistry();\n const preserve = useWindowManagerState(s => optionsFor(registry, s.panels[panelId])?.preserveEmbeds === true);\n const hostRef = useRef<HTMLDivElement | null>(null);\n // Only the active panel gets focus back after a move (see domPreservation.ts). A selector, so\n // this wrapper re-renders only when this panel's active flag flips.\n const isActive = useWindowManagerState(s => s.activePanelId === panelId);\n const isActiveRef = useRef(isActive);\n useLayoutEffect(() => { isActiveRef.current = isActive; });\n\n useEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n\n const cachedEl = panelHost.getOrCreateElement(panelId);\n // Only ever switched on here: a widget that keeps its embeds also marks its owner's element.\n if (preserve) setPreserveEmbeds(cachedEl, true);\n moveInto(host, cachedEl);\n restorePanelDom(cachedEl, { refocus: isActiveRef.current });\n\n const resizeObserver = new ResizeObserver((entries) => {\n for (const entry of entries) {\n const { width, height } = entry.contentRect;\n if (width > 0 && height > 0) {\n panelHost.setDimensions(panelId, { width, height });\n const lifecycle = panelHost.getLifecycle(panelId);\n if (lifecycle) {\n lifecycle.onResize.forEach(h => h(width, height));\n }\n }\n }\n });\n resizeObserver.observe(host);\n\n return () => {\n resizeObserver.disconnect();\n panelHost.park(cachedEl);\n };\n }, [panelId, panelHost, preserve]);\n useParkBeforeRemoval(hostRef, panelId, panelHost);\n\n return <div ref={hostRef} className=\"rdd-panel-dom-host\" />;\n};\n\nexport const PreviewDOMWrapper: React.FC<{ panelId: string }> = ({ panelId }) => {\n const panelHost = usePanelHost();\n const panel = useWindowManagerState(s => s.panels[panelId]);\n const registry = useRegistry();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const hostRef = useRef<HTMLDivElement | null>(null);\n\n const options = optionsFor(registry, panel);\n // A panel that unmounts while hidden has nothing to preview while minimized.\n const disableLivePreview = options?.disableLivePreview || options?.keepAlive === false || false;\n\n const lastSize = panelHost.getDimensions(panelId) || { width: 800, height: 500 };\n const origW = lastSize.width;\n const origH = lastSize.height;\n const maxW = 220;\n const maxH = 140;\n const scale = Math.min(maxW / origW, maxH / origH);\n\n useEffect(() => {\n if (disableLivePreview) return;\n\n const host = hostRef.current;\n if (!host) return;\n\n const cachedEl = panelHost.getElement(panelId);\n if (!cachedEl) return;\n\n moveInto(host, cachedEl);\n restorePanelDom(cachedEl, { refocus: false }); // a preview shows the panel's place; it never takes focus\n\n return () => panelHost.park(cachedEl);\n }, [panelId, disableLivePreview, panelHost]);\n useParkBeforeRemoval(hostRef, panelId, panelHost);\n\n if (disableLivePreview) {\n const displayW = origW * scale;\n const displayH = origH * scale;\n const rawTitle = panel?.title || options?.title || messages.untitledPanel;\n const title = formatLabel(rawTitle, formatMessage);\n const initialChar = (Array.from(title)[0] || 'P').toUpperCase();\n\n return (\n <div\n className=\"rdd-taskbar-item-preview-frame rdd-taskbar-item-preview-frame--empty\"\n style={{ width: `${displayW}px`, height: `${displayH}px` }}\n >\n <div className=\"rdd-taskbar-item-preview-initial\">\n {initialChar}\n </div>\n </div>\n );\n }\n\n return (\n <div\n className=\"rdd-taskbar-item-preview-frame\"\n style={{\n width: `${origW * scale}px`,\n height: `${origH * scale}px`,\n }}\n >\n <div\n ref={hostRef}\n className=\"rdd-taskbar-item-preview-host\"\n style={{\n width: `${origW}px`,\n height: `${origH}px`,\n transform: `scale(${scale})`,\n ['--rdd-preview-scale' as string]: scale\n }}\n />\n </div>\n );\n};\n\nexport const FormContainerProviderWrapper: React.FC<{ panelId: string; children: React.ReactNode }> = ({ panelId, children }) => {\n const panelHost = usePanelHost();\n const { requestClosePanel, setPanelDirty, registerCloseGuard, unregisterCloseGuard, registerStateProvider, unregisterStateProvider, updatePanelTitle, setPanelIcon, minimizePanel } = useWindowManagerActions();\n\n // ── minimize / restore ──────────────────────────────────────────────────\n const isMin = useWindowManagerState(s => s.minimized.some(m => m.id === panelId));\n const prevMinRef = useRef(isMin);\n\n useEffect(() => {\n const entry = panelHost.getLifecycle(panelId);\n if (!entry) return;\n\n if (isMin && !prevMinRef.current) {\n entry.onMinimize.forEach(h => h());\n } else if (!isMin && prevMinRef.current) {\n entry.onRestore.forEach(h => h());\n }\n prevMinRef.current = isMin;\n }, [isMin, panelId, panelHost]);\n\n // ── activate / deactivate ───────────────────────────────────────────────\n const isActive = useWindowManagerState(s => s.activePanelId === panelId);\n const prevActiveRef = useRef(isActive);\n\n useEffect(() => {\n const wasActive = prevActiveRef.current;\n prevActiveRef.current = isActive; // always sync the ref, even if no handler is registered yet\n const entry = panelHost.getLifecycle(panelId);\n if (!entry) return;\n\n if (isActive && !wasActive) {\n entry.onActivate.forEach(h => h());\n } else if (!isActive && wasActive) {\n entry.onDeactivate.forEach(h => h());\n }\n }, [isActive, panelId, panelHost]);\n\n // ── container-type change ───────────────────────────────────────────────\n const rawPanelState = useWindowManagerState(s => s.panels[panelId]?.state);\n const derivedContainerType: ContainerType =\n rawPanelState === 'floating' ? 'floating-window' : 'dockable-panel';\n const prevContainerTypeRef = useRef(derivedContainerType);\n\n useEffect(() => {\n if (rawPanelState === 'minimized') return; // minimize/restore is onMinimize's domain; intentionally skip ref update\n const prevType = prevContainerTypeRef.current;\n prevContainerTypeRef.current = derivedContainerType; // always sync, even if no handler registered yet\n const entry = panelHost.getLifecycle(panelId);\n if (!entry) return;\n\n if (derivedContainerType !== prevType) {\n entry.onContainerTypeChange.forEach(h => h(derivedContainerType));\n }\n }, [derivedContainerType, rawPanelState, panelId, panelHost]);\n\n // ── cleanup: fire onDeactivate (if active) then onClose ─────────────────\n useEffect(() => {\n return () => {\n const entry = panelHost.getLifecycle(panelId);\n if (entry) {\n if (prevActiveRef.current) entry.onDeactivate.forEach(h => h());\n entry.onClose.forEach(h => h());\n panelHost.deleteLifecycle(panelId);\n }\n };\n }, [panelId, panelHost]);\n\n // Capture the container type at mount so the static `containerType` field is\n // correct ('dockable-panel' or 'floating-window') rather than the default 'standalone'.\n const [initialContainerType] = useState<ContainerType>(derivedContainerType);\n\n const contract = React.useMemo<FormContainerContract>(() => ({\n requestClose: (options) => requestClosePanel(panelId, options),\n setDirty: (dirty, options) => setPanelDirty(panelId, dirty, options),\n onCloseRequested: (handler) => {\n registerCloseGuard(panelId, handler);\n return () => unregisterCloseGuard(panelId);\n },\n registerStateProvider: (getState) => {\n registerStateProvider(panelId, getState);\n return () => unregisterStateProvider(panelId);\n },\n setTitle: (title) => updatePanelTitle(panelId, title),\n setIcon: (icon) => setPanelIcon(panelId, icon ?? null),\n instanceId: panelId,\n containerType: initialContainerType,\n onClose: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onClose.add(handler);\n return () => reg.onClose.delete(handler);\n },\n onMinimize: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onMinimize.add(handler);\n return () => reg.onMinimize.delete(handler);\n },\n onRestore: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onRestore.add(handler);\n return () => reg.onRestore.delete(handler);\n },\n onResize: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onResize.add(handler);\n return () => reg.onResize.delete(handler);\n },\n requestMinimize: () => minimizePanel(panelId),\n getDimensions: () => panelHost.getDimensions(panelId) ?? null,\n onActivate: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onActivate.add(handler);\n return () => reg.onActivate.delete(handler);\n },\n onDeactivate: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onDeactivate.add(handler);\n return () => reg.onDeactivate.delete(handler);\n },\n onContainerTypeChange: (handler) => {\n const reg = panelHost.getOrCreateLifecycle(panelId);\n reg.onContainerTypeChange.add(handler);\n return () => reg.onContainerTypeChange.delete(handler);\n },\n }), [panelId, panelHost, initialContainerType, requestClosePanel, setPanelDirty, registerCloseGuard, unregisterCloseGuard, registerStateProvider, unregisterStateProvider, updatePanelTitle, setPanelIcon, minimizePanel]);\n\n return (\n <FormContainerProvider value={contract}>\n {children}\n </FormContainerProvider>\n );\n};\n\n/**\n * One open panel's body, portaled into its preserved element (the slots then place that element in\n * a tab, a window or a preview). Memoised and given only the id: it reads its own entry and the\n * direction, so it re-renders when its panel changes, never because another panel did (7.7.2).\n */\nexport const PanelMount: React.FC<{ panelId: string }> = React.memo(({ panelId }) => {\n const panelHost = usePanelHost();\n const panel = useWindowManagerState(s => s.panels[panelId]);\n const dir = useWindowManagerState(s => s.dir);\n const registry = useRegistry();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n // keepAlive: false (7.8.0): only those panels ask whether they are shown, so the rest pay nothing.\n const keepAlive = (panel && optionsFor(registry, panel)?.keepAlive) !== false;\n const shown = useWindowManagerState(s => keepAlive || isPanelShown(s, panelId));\n if (!panel) return null;\n const typeClass = optionsFor(registry, panel)?.className;\n return createPortal(\n <FormContainerProviderWrapper panelId={panelId}>\n <div className={`rdd-panel-content${typeClass ? ` ${typeClass}` : ''}`} data-rdd-panel={panelId} dir={dir}>\n {shown && (panel.owner\n ? <HostedWidgetSlot panelId={panelId} />\n : renderPanelContent(panelId, panel, registry, messages, formatMessage))}\n </div>\n </FormContainerProviderWrapper>,\n panelHost.getOrCreateElement(panelId),\n );\n});\nPanelMount.displayName = 'PanelMount';\n","/**\n * @file DragGhost.tsx\n * @description The tab that follows the pointer while a docked panel is dragged. It alone reads the pointer position, so a move re-renders it and nothing else.\n */\nimport React, { useSyncExternalStore } from 'react';\nimport type { DragPos } from './useDragTargets';\n\nexport const DragGhost: React.FC<{ dragPos: DragPos; children: React.ReactNode }> = ({ dragPos, children }) => {\n const pos = useSyncExternalStore(dragPos.subscribe, dragPos.get, dragPos.get);\n return (\n <div className=\"rdd-drag-ghost-tab\" style={{ left: pos.x + 12, top: pos.y + 12 }}>\n {children}\n </div>\n );\n};\n","/**\n * @file WorkspaceGrid.tsx\n * @description The split layout: a branch of the layout tree with its resizer bars, down to its leaf groups.\n */\nimport React from 'react';\nimport { isComputedRtl } from '../../utils/rtl';\nimport { useWindowManagerActions } from '../WindowManagerContext';\nimport type { LayoutNode, DropPosition } from '../../types';\nimport { startPointerDrag } from '../dragResize';\nimport { LeafGroup } from './LeafGroup';\nimport type { TabContentProps } from '../../types';\n\nexport interface WorkspaceGridProps {\n node: LayoutNode;\n path: number[];\n onTabRightClick: (id: string, e: React.MouseEvent) => void;\n activeDropZone: { leafId: string; position: DropPosition } | null;\n onHoverDropZone: (leafId: string, position: DropPosition | null) => void;\n onTabDragStart: (id: string, e: React.PointerEvent) => void;\n hoveredTab: { leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null;\n onTabHover: (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => void;\n defaultPanelIcon?: React.ReactNode;\n /** The app's empty-workspace view. Only the root grid receives it: nested grids are rendered without it. */\n emptyWorkspace?: React.ReactNode;\n /** The app's tab content, for every group (7.10.0). */\n renderTabContent?: (tab: TabContentProps) => React.ReactNode;\n onRequestClosePanel: (id: string) => Promise<void> | void;\n}\n\nexport const WorkspaceGrid: React.FC<WorkspaceGridProps> = ({ node, path, onTabRightClick, activeDropZone, onHoverDropZone, onTabDragStart, hoveredTab, onTabHover, defaultPanelIcon, onRequestClosePanel, emptyWorkspace, renderTabContent }) => {\n const { updateSplitSizes } = useWindowManagerActions();\n\n if (node.type === 'leaf') {\n return <LeafGroup leaf={node} onTabRightClick={onTabRightClick} activeDropZone={activeDropZone} onHoverDropZone={onHoverDropZone} onTabDragStart={onTabDragStart} hoveredTab={hoveredTab} onTabHover={onTabHover} defaultPanelIcon={defaultPanelIcon} onRequestClosePanel={onRequestClosePanel} emptyWorkspace={emptyWorkspace} renderTabContent={renderTabContent} />;\n }\n\n const isRow = node.orientation === 'horizontal';\n\n const handleResizerPointerDown = (idx: number, e: React.PointerEvent) => {\n e.preventDefault();\n const resizerEl = e.currentTarget as HTMLDivElement;\n const parentEl = resizerEl.parentElement;\n const parentSize = parentEl\n ? (isRow ? parentEl.clientWidth : parentEl.clientHeight)\n : (isRow ? 1000 : 800);\n const rtl = isComputedRtl(parentEl);\n\n startPointerDrag({\n element: resizerEl,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => [...node.sizes],\n activeClasses: [\n { el: resizerEl, classes: ['rdd-active'] },\n { el: document.body, classes: ['rdd-resizing-active', isRow ? 'rdd-resizing-col-active' : 'rdd-resizing-row-active'] },\n ],\n onMove: (dx, dy, startSizes) => {\n // A row reverses under RTL, so children[idx] is the pane to the divider's *right*: a\n // rightward drag must shrink it. Pointer deltas are physical; sizes are in child order.\n const sign = isRow && rtl ? -1 : 1;\n const deltaPercentage = (isRow ? sign * dx : dy) / parentSize;\n const newSizes = [...startSizes];\n newSizes[idx] += deltaPercentage;\n newSizes[idx + 1] -= deltaPercentage;\n if (newSizes[idx] > 0.1 && newSizes[idx + 1] > 0.1) {\n updateSplitSizes(path, newSizes);\n }\n },\n });\n };\n\n return (\n <div className={`rdd-split ${isRow ? 'rdd-split--row' : 'rdd-split--column'}`}>\n {node.children.map((child, idx) => {\n const size = node.sizes[idx] * 100;\n return (\n <React.Fragment key={idx}>\n <div className=\"rdd-split-child\" style={{ flexGrow: node.sizes[idx], flexBasis: `${size}%` }}>\n <WorkspaceGrid node={child} path={[...path, idx]} onTabRightClick={onTabRightClick} activeDropZone={activeDropZone} onHoverDropZone={onHoverDropZone} onTabDragStart={onTabDragStart} hoveredTab={hoveredTab} onTabHover={onTabHover} defaultPanelIcon={defaultPanelIcon} onRequestClosePanel={onRequestClosePanel} renderTabContent={renderTabContent} />\n </div>\n {idx < node.children.length - 1 && (\n <div\n onPointerDown={(e) => handleResizerPointerDown(idx, e)}\n className={`rdd-resizer-bar ${isRow ? 'rdd-resizer-bar--vertical' : 'rdd-resizer-bar--horizontal'}`}\n />\n )}\n </React.Fragment>\n );\n })}\n </div>\n );\n};\n","/**\n * Shared pointer-drag-resize primitives.\n *\n * Extracted from four previously-independent implementations (the workspace grid\n * split resizer, the sidebar drawer resizer, and two floating-window resize-handle\n * implementations) that had quietly drifted apart in exactly the kind of detail\n * (an inline-style property present in one and missing in the other) that once\n * caused a real, user-visible bug. This file is the single place that mechanic now\n * lives, so it can't drift again.\n */\n\n// ── Pointer-capture drag mechanics ──────────────────────────────────────────\n\nexport interface PointerDragConfig<TStart> {\n /** The element to capture the pointer on — normally the handle the user grabbed. */\n element: HTMLElement;\n pointerId: number;\n /** The pointerdown event's clientX/clientY, used as the delta origin. */\n startClientX: number;\n startClientY: number;\n /** Snapshot whatever state the caller needs at drag start (sizes, positions, ...). */\n captureStart: () => TStart;\n /** Called on every pointermove with the delta from the drag's start position. */\n onMove: (dx: number, dy: number, start: TStart) => void;\n /** Called once when the drag ends (pointerup or pointercancel). */\n onEnd?: (start: TStart) => void;\n /**\n * Called instead of `onEnd` when the drag is cut short: the window loses focus, or the pointer\n * capture is lost (the element was removed mid-drag). Without it, `onEnd` is called. (7.9.0)\n */\n onCancel?: (start: TStart) => void;\n /** Classes toggled on the given elements for the duration of the drag. */\n activeClasses?: Array<{ el: HTMLElement; classes: string[] }>;\n}\n\n/**\n * Starts a pointer-capture-based drag: captures the pointer on `element`, tracks\n * movement via listeners scoped to that element's own lifetime (not `window`), and\n * cleans up automatically on release or cancel, and (7.9.0) when the window loses focus\n * or the capture is lost, so a drag can never outlive its element or leave its classes behind.\n */\nexport function startPointerDrag<TStart>(config: PointerDragConfig<TStart>): void {\n const { element, pointerId, startClientX, startClientY, captureStart, onMove, onEnd, activeClasses } = config;\n\n element.setPointerCapture(pointerId);\n activeClasses?.forEach(({ el, classes }) => el.classList.add(...classes));\n const start = captureStart();\n\n const handleMove = (e: PointerEvent) => {\n onMove(e.clientX - startClientX, e.clientY - startClientY, start);\n };\n\n // Ends at most once: every listener is removed before the callback runs.\n const finish = (cancelled: boolean) => {\n activeClasses?.forEach(({ el, classes }) => el.classList.remove(...classes));\n element.removeEventListener('pointermove', handleMove);\n element.removeEventListener('pointerup', handleEnd);\n element.removeEventListener('pointercancel', handleEnd);\n doc.removeEventListener('lostpointercapture', handleLostCapture, true);\n view?.removeEventListener('blur', handleBlur);\n (cancelled && config.onCancel ? config.onCancel : onEnd)?.(start);\n };\n const handleEnd = () => finish(false);\n const handleBlur = () => finish(true);\n // Removing a capturing element fires lostpointercapture at the document, not the element, so\n // it is listened for there. A normal release ends the drag before the capture is let go.\n const handleLostCapture = (e: PointerEvent) => { if (e.pointerId === pointerId) finish(true); };\n\n const doc = element.ownerDocument;\n const view = doc.defaultView;\n element.addEventListener('pointermove', handleMove);\n element.addEventListener('pointerup', handleEnd);\n element.addEventListener('pointercancel', handleEnd);\n doc.addEventListener('lostpointercapture', handleLostCapture, true);\n view?.addEventListener('blur', handleBlur);\n}\n\n// ── 8-directional resize math ────────────────────────────────────────────────\n\nexport type ResizeDir = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';\n\nexport interface ResizeRect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nexport interface ResizeConstraints {\n minW: number;\n minH: number;\n /** Upper bound on width — only applies to eastward growth (dir includes 'e'). */\n maxW?: number;\n /** Upper bound on height — only applies to southward growth (dir includes 's'). */\n maxH?: number;\n /** Lower bound on the resulting x — only applies to westward growth (dir includes 'w'). */\n minX?: number;\n /** Lower bound on the resulting y — only applies to northward growth (dir includes 'n'). */\n minY?: number;\n}\n\n/**\n * Pure function computing the new rect for an 8-directional resize handle drag.\n *\n * `maxW`/`maxH` and `minX`/`minY` are independent, direction-scoped constraints\n * rather than one \"container bound\" — a resize toward the fixed edge (e/s) is\n * naturally bounded by a maximum dimension, while a resize toward the moving edge\n * (w/n) is naturally bounded by a minimum position, and the two calling sites this\n * was extracted from need different subsets of these (see workspace/floatingWindowDrag.ts's\n * `startResize`, which omits all four and lets a window grow unbounded and be\n * dragged fully off-screen, vs. panelOverlay/FloatingWidget.tsx's `handleResizePointerDown`, which\n * supplies all four to keep windows within their container).\n */\nexport function computeResizedRect(dir: ResizeDir, dx: number, dy: number, start: ResizeRect, constraints: ResizeConstraints): ResizeRect {\n const { minW, minH, maxW, maxH, minX, minY } = constraints;\n let { x, y, w, h } = start;\n\n if (dir.includes('e')) {\n w = Math.max(minW, Math.min(start.w + dx, maxW ?? Infinity));\n }\n if (dir.includes('w')) {\n const maxDx = start.w - minW; // largest rightward (shrinking) delta before hitting minW\n const minDx = minX != null ? -(start.x - minX) : -Infinity; // most negative (growing) delta before x hits minX\n const clampedDx = Math.max(minDx, Math.min(dx, maxDx));\n w = start.w - clampedDx;\n x = start.x + clampedDx;\n }\n if (dir.includes('s')) {\n h = Math.max(minH, Math.min(start.h + dy, maxH ?? Infinity));\n }\n if (dir.includes('n')) {\n const maxDy = start.h - minH;\n const minDy = minY != null ? -(start.y - minY) : -Infinity;\n const clampedDy = Math.max(minDy, Math.min(dy, maxDy));\n h = start.h - clampedDy;\n y = start.y + clampedDy;\n }\n\n return { x, y, w, h };\n}\n","/**\n * @file LeafGroup.tsx\n * @description A leaf group: its tab strip (keyboard, scroll, drag and drop) and the selected panel's body.\n */\nimport React, { useState, useRef, useEffect, useCallback } from 'react';\nimport { isComputedRtl } from '../../utils/rtl';\nimport { useWindowManagerState, useWindowManagerActionsInternal, useFormatMessage, formatLabel, usePredefinedMessages, useStyleClasses, useRegistry } from '../WindowManagerContext';\nimport type { LayoutLeafNode, DropPosition } from '../../types';\nimport { tabDropSide, isMenuKey, menuEventAt, refocusAfterTabClose, domIdPart } from './helpers';\nimport { DefaultGridIcon } from './icons';\nimport { PreservedDOMWrapper } from './panelMount';\nimport type { TabContentProps } from '../../types';\nimport { optionsFor } from '../../core/panelOptions';\n\nexport interface LeafGroupProps {\n leaf: LayoutLeafNode;\n onTabRightClick: (id: string, e: React.MouseEvent) => void;\n activeDropZone: { leafId: string; position: DropPosition } | null;\n onHoverDropZone: (leafId: string, position: DropPosition | null) => void;\n onTabDragStart: (id: string, e: React.PointerEvent) => void;\n hoveredTab: { leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null;\n onTabHover: (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => void;\n defaultPanelIcon?: React.ReactNode;\n /** Set on the root group only: shown in place of the built-in message while it has no panels. */\n emptyWorkspace?: React.ReactNode;\n /** The app's tab content (7.10.0). */\n renderTabContent?: (tab: TabContentProps) => React.ReactNode;\n onRequestClosePanel: (id: string) => Promise<void> | void;\n}\n\nexport const LeafGroup: React.FC<LeafGroupProps> = ({ leaf, onTabRightClick, activeDropZone, onHoverDropZone, onTabDragStart, hoveredTab, onTabHover, defaultPanelIcon, onRequestClosePanel, emptyWorkspace, renderTabContent }) => {\n const state = useWindowManagerState();\n const registry = useRegistry();\n const { openPanel, closeLeafGroup, setActivePanel, isDropAllowed } = useWindowManagerActionsInternal();\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const { windowClass, windowBodyClass } = useStyleClasses();\n\n const tabContainerRef = useRef<HTMLDivElement>(null);\n // Overflow tracked in reading order: `start` = tabs hidden before the first visible one, `end`\n // = after the last. Under RTL, scrollLeft runs from 0 down to negative values, so the physical\n // `scrollLeft > 0` test that used to be here never saw the start overflow and always the end.\n const [tabScroll, setTabScroll] = useState({ start: false, end: false, rtl: false });\n\n const updateTabScroll = useCallback(() => {\n const el = tabContainerRef.current;\n if (!el) return;\n const travelled = Math.abs(el.scrollLeft);\n const max = el.scrollWidth - el.clientWidth;\n const next = { start: travelled > 1, end: travelled < max - 1, rtl: isComputedRtl(el) };\n setTabScroll(prev => (prev.start === next.start && prev.end === next.end && prev.rtl === next.rtl ? prev : next));\n }, []);\n\n useEffect(() => {\n const el = tabContainerRef.current;\n if (!el) return;\n el.addEventListener('scroll', updateTabScroll, { passive: true });\n const ro = new ResizeObserver(updateTabScroll);\n ro.observe(el);\n updateTabScroll();\n return () => { el.removeEventListener('scroll', updateTabScroll); ro.disconnect(); };\n }, [updateTabScroll]);\n\n const scrollTabs = (toward: 'start' | 'end') => {\n // In reading order: toward the end is +x in LTR and −x in RTL.\n const forward = toward === 'end' ? 120 : -120;\n tabContainerRef.current?.scrollBy({ left: tabScroll.rtl ? -forward : forward, behavior: 'smooth' });\n };\n // The start button comes first in the DOM, so it sits on the physical left in LTR and on the\n // physical right in RTL. Class, glyph and label follow the physical side.\n const startSide = tabScroll.rtl ? 'right' : 'left';\n const endSide = tabScroll.rtl ? 'left' : 'right';\n const scrollGlyph = { left: '\\u2039', right: '\\u203A' } as const;\n const scrollLabel = { left: messages.scrollTabsLeft, right: messages.scrollTabsRight } as const;\n\n const selectTab = (id: string) => {\n openPanel(id, state.panels[id].component);\n setActivePanel(id);\n };\n\n // WAI-ARIA tabs pattern: one tab stop per group (the selected tab); the arrow keys move the\n // selection and focus along the strip — mirrored under RTL, where the strip runs right to left.\n const handleTabKeyDown = (e: React.KeyboardEvent<HTMLElement>, id: string, closable: boolean) => {\n if (isMenuKey(e)) {\n e.preventDefault();\n onTabRightClick(id, menuEventAt(e.currentTarget));\n return;\n }\n const ids = leaf.panels.filter(p => state.panels[p]);\n const i = ids.indexOf(id);\n const step = isComputedRtl(e.currentTarget) ? -1 : 1;\n let next: string | undefined;\n switch (e.key) {\n case 'ArrowRight': next = ids[(i + step + ids.length) % ids.length]; break;\n case 'ArrowLeft': next = ids[(i - step + ids.length) % ids.length]; break;\n case 'Home': next = ids[0]; break;\n case 'End': next = ids[ids.length - 1]; break;\n case 'Enter':\n case ' ':\n e.preventDefault();\n selectTab(id);\n return;\n case 'Delete': {\n if (!closable) return;\n e.preventDefault();\n const workspaceEl = e.currentTarget.closest<HTMLElement>('.rdd-workspace');\n void Promise.resolve(onRequestClosePanel(id)).then(() => requestAnimationFrame(() => {\n refocusAfterTabClose(id, tabContainerRef.current, workspaceEl);\n }));\n return;\n }\n default:\n return;\n }\n e.preventDefault();\n if (!next || next === id) return;\n selectTab(next);\n tabContainerRef.current\n ?.querySelector<HTMLElement>(`[data-tab-id=\"${next.replace(/[\"\\\\]/g, '\\\\$&')}\"]`)\n ?.focus();\n };\n const tabPanelId = `rdd-tabpanel-${domIdPart(leaf.id)}`;\n const tabIdFor = (panelId: string) => `rdd-tab-${domIdPart(panelId)}`;\n\n return (\n <div\n data-active-panel-id={leaf.activePanelId || ''}\n data-rdd-leaf={leaf.id}\n className={`rdd-workspace-panel ${windowClass ?? ''}`}\n >\n {/* Tab Headers */}\n <div className=\"rdd-workspace-tab-bar\">\n {tabScroll.start && (\n <button\n className={`rdd-tab-scroll-btn rdd-tab-scroll-btn-${startSide}`}\n onPointerDown={(e) => e.stopPropagation()}\n onClick={() => scrollTabs('start')}\n tabIndex={-1}\n aria-label={formatLabel(scrollLabel[startSide], formatMessage)}\n >{scrollGlyph[startSide]}</button>\n )}\n <div\n ref={tabContainerRef}\n className=\"rdd-tab-headers-container\"\n role=\"tablist\"\n aria-orientation=\"horizontal\"\n onPointerMove={(e) => {\n if (state.draggedPanelId && e.target === e.currentTarget) {\n onTabHover(leaf.id, 'EMPTY', leaf.panels.length, 'right');\n }\n }}\n onPointerLeave={(e) => {\n if (state.draggedPanelId && e.target === e.currentTarget) {\n onTabHover(leaf.id, '', -1, null);\n }\n }}\n >\n {leaf.panels.map((id, idx) => {\n const panel = state.panels[id];\n if (!panel) return null;\n const isSelected = leaf.activePanelId === id;\n const isGloballyActive = state.activePanelId === id;\n\n const options = optionsFor(registry, panel);\n\n const isHovered = hoveredTab && hoveredTab.leafId === leaf.id && hoveredTab.panelId === id;\n const isLast = idx === leaf.panels.length - 1;\n const isHoveredEmpty = hoveredTab && hoveredTab.leafId === leaf.id && hoveredTab.panelId === 'EMPTY' && isLast;\n const sideClass = isHovered\n ? (hoveredTab.side === 'left' ? 'rdd-drag-hover-left' : 'rdd-drag-hover-right')\n : (isHoveredEmpty ? 'rdd-drag-hover-right' : '');\n\n const tabFocusClass = isSelected\n ? (isGloballyActive ? 'rdd-active rdd-workspace-tab-active-focused' : 'rdd-active rdd-workspace-tab-active-unfocused')\n : 'rdd-workspace-tab-inactive';\n\n return (\n <div\n key={id}\n id={tabIdFor(id)}\n role=\"tab\"\n aria-selected={isSelected}\n aria-controls={tabPanelId}\n aria-keyshortcuts={options?.canClose !== false ? 'Delete' : undefined}\n tabIndex={isSelected ? 0 : -1}\n onKeyDown={(e) => handleTabKeyDown(e, id, options?.canClose !== false)}\n data-tab-id={id}\n data-leaf-id={leaf.id}\n data-rdd-tab={id}\n data-tab-index={String(idx)}\n // State for app CSS (7.8.0): present when true, so `[data-rdd-dirty]` matches.\n data-rdd-selected={isSelected ? '' : undefined}\n data-rdd-focused={isGloballyActive ? '' : undefined}\n data-rdd-dirty={panel?.dirty ? '' : undefined}\n onClick={() => selectTab(id)}\n onPointerDown={(e) => {\n if (options?.canDrag !== false) {\n onTabDragStart(id, e);\n }\n }}\n onContextMenu={(e) => onTabRightClick(id, e)}\n onPointerMove={(e) => {\n if (state.draggedPanelId && e.pointerType !== 'touch') {\n onTabHover(leaf.id, id, idx, tabDropSide(e.currentTarget, e.clientX));\n }\n }}\n onPointerLeave={() => {\n if (state.draggedPanelId) {\n onTabHover(leaf.id, '', -1, null);\n }\n }}\n className={`rdd-workspace-tab ${tabFocusClass} ${sideClass}${options?.tabClassName ? ` ${options.tabClassName}` : ''}`}\n style={{ cursor: options?.canDrag === false ? 'default' : 'pointer' }}\n >\n <span className=\"rdd-text-truncate rdd-workspace-tab-title\">\n {(() => {\n const icon = panel.icon ?? (options?.icon || defaultPanelIcon || DefaultGridIcon);\n const title = formatLabel(panel.title, formatMessage);\n // The app's content replaces the icon, title and marker; the tab stays ours (7.10.0).\n if (renderTabContent) {\n return renderTabContent({ panelId: id, component: panel.component, title, icon, dirty: panel.dirty === true, selected: isSelected, focused: isGloballyActive });\n }\n return (\n <>\n <span className=\"rdd-workspace-tab-icon\">{icon}</span>\n <span>\n {title}\n {panel.dirty ? ' *' : ''}\n </span>\n </>\n );\n })()}\n </span>\n {options?.renderHeaderActions && (\n <span\n className=\"rdd-tab-header-actions\"\n onClick={(e) => e.stopPropagation()}\n onPointerDown={(e) => e.stopPropagation()}\n >\n {options.renderHeaderActions(id)}\n </span>\n )}\n {options?.canClose !== false && (\n <span\n onClick={(e) => {\n e.stopPropagation();\n onRequestClosePanel(id);\n }}\n title={formatLabel(messages.closeTab, formatMessage)}\n // Not a separate control: interactive content inside role=\"tab\" is not allowed.\n // Keyboard users close the focused tab with Delete.\n aria-hidden=\"true\"\n className={`rdd-close-tab-x${options?.renderHeaderActions ? '' : ' rdd-close-tab-x--end'}`}\n >\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </span>\n )}\n </div>\n );\n })}\n </div>\n {tabScroll.end && (\n <button\n className={`rdd-tab-scroll-btn rdd-tab-scroll-btn-${endSide}`}\n onPointerDown={(e) => e.stopPropagation()}\n onClick={() => scrollTabs('end')}\n tabIndex={-1}\n aria-label={formatLabel(scrollLabel[endSide], formatMessage)}\n >{scrollGlyph[endSide]}</button>\n )}\n\n {/* Empty group close button — only visible when keepOnEmpty keeps the group alive */}\n {leaf.panels.length === 0 && leaf.keepOnEmpty && leaf.canClose !== false && (\n <button\n type=\"button\"\n onClick={() => { void closeLeafGroup(leaf.id); }}\n className=\"rdd-close-tab-x rdd-header-close-empty-group\"\n title={formatLabel(messages.closeEmptyGroup, formatMessage)}\n aria-label={formatLabel(messages.closeEmptyGroup, formatMessage)}\n >\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" aria-hidden=\"true\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </button>\n )}\n </div>\n\n {/* Tab Content Display Area */}\n <div\n id={tabPanelId}\n role=\"tabpanel\"\n aria-labelledby={leaf.activePanelId ? tabIdFor(leaf.activePanelId) : undefined}\n className={`rdd-panel-body ${windowBodyClass ?? ''}`}\n >\n {leaf.activePanelId && state.panels[leaf.activePanelId] ? (\n <PreservedDOMWrapper key={leaf.activePanelId} panelId={leaf.activePanelId} />\n ) : emptyWorkspace !== undefined && leaf.panels.length === 0 ? (\n <div className=\"rdd-empty-workspace\">{emptyWorkspace}</div>\n ) : (\n <div className=\"rdd-empty-leaf-placeholder\">\n <span>{formatLabel(messages.emptyGroup, formatMessage)}</span>\n </div>\n )}\n\n {/* Drag overlay targets cross */}\n {state.draggedPanelId !== null && (() => {\n // State-driven, not :hover-driven — :hover never fires reliably in Safari\n // during an active drag, and doesn't exist at all on touch. activeDropZone\n // already tracks this for mouse, pen, and touch alike (see updateHoverFromPoint).\n const isActive = (pos: DropPosition) => activeDropZone?.leafId === leaf.id && activeDropZone.position === pos;\n // A target the rules forbid isn't offered at all (7.9.0). Zones are drawn by screen side;\n // the move flips left and right under RTL, and canDrop sees the side the move applies.\n const dragged = state.draggedPanelId;\n const applied = (pos: DropPosition): DropPosition =>\n state.isRtl && (pos === 'left' || pos === 'right') ? (pos === 'left' ? 'right' : 'left') : pos;\n const offer = (pos: DropPosition) => isDropAllowed(dragged, { kind: 'group', leafId: leaf.id, position: applied(pos) });\n return (\n <div className=\"rdd-dock-drop-zone-overlay\">\n <div className=\"rdd-dock-target-cross\">\n {/* Top target */}\n {offer('top') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"top\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'top')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-top${isActive('top') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▲\n </div>\n )}\n {/* Bottom target */}\n {offer('bottom') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"bottom\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'bottom')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-bottom${isActive('bottom') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▼\n </div>\n )}\n {/* Left target */}\n {offer('left') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"left\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'left')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-left${isActive('left') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ◀\n </div>\n )}\n {/* Right target */}\n {offer('right') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"right\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'right')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-right${isActive('right') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▶\n </div>\n )}\n {/* Center target */}\n {offer('center') && (\n <div\n data-leaf-id={leaf.id}\n data-drop-zone=\"center\"\n onPointerEnter={() => onHoverDropZone(leaf.id, 'center')}\n onPointerLeave={() => onHoverDropZone(leaf.id, null)}\n className={`rdd-dock-target-box rdd-dock-target-center${isActive('center') ? ' rdd-dock-target-box--active' : ''}`}\n >\n ▣\n </div>\n )}\n </div>\n </div>\n );\n })()}\n\n {/* Visual preview highlight overlay */}\n {state.draggedPanelId !== null && activeDropZone !== null && activeDropZone.leafId === leaf.id && (\n <div\n className=\"rdd-dock-preview-highlight\"\n style={(() => {\n const pos = activeDropZone.position;\n const pct = `${state.splitRatio * 100}%`;\n const rem = `${(1 - state.splitRatio) * 100}%`;\n return {\n left: pos === 'right' ? rem : '0',\n top: pos === 'bottom' ? rem : '0',\n width: (pos === 'left' || pos === 'right') ? pct : '100%',\n height: (pos === 'top' || pos === 'bottom') ? pct : '100%',\n };\n })()}\n />\n )}\n </div>\n </div>\n );\n};\n","/**\n * @file helpers.ts\n * @description Small helpers of the workspace view: tree lookup, tab drop side, the keyboard's right-click, focus after a tab closes, DOM-safe ids.\n */\nimport React from 'react';\nimport { isComputedRtl } from '../../utils/rtl';\nimport type { LayoutNode, LayoutLeafNode } from '../../types';\n\nexport const findLeaf = (node: LayoutNode | null, leafId: string): LayoutLeafNode | null => {\n if (!node) return null;\n if (node.type === 'leaf') return node.id === leafId ? node : null;\n for (const child of node.children) {\n const found = findLeaf(child, leafId);\n if (found) return found;\n }\n return null;\n};\n\n// DOM Element Cache for preserving contexts (WebGL map, text area etc.)\n/**\n * Which side of a tab a dragged tab would drop on, in tab order: 'left' = before it, 'right' =\n * after it. The pointer's half is physical, but insertion (and the RTL-mirrored indicator CSS)\n * is logical — under RTL the physical left half means *after*.\n */\nexport const tabDropSide = (tabEl: Element, clientX: number): 'left' | 'right' => {\n const rect = tabEl.getBoundingClientRect();\n const onPhysicalLeft = clientX - rect.left < rect.width / 2;\n return onPhysicalLeft !== isComputedRtl(tabEl) ? 'left' : 'right';\n};\n\n/**\n * The keyboard's right-click: the ContextMenu key, or Shift+F10. Chrome on macOS sends no\n * `contextmenu` event for either, so the focused control handles them itself (preventing the\n * default, so a platform that does send one doesn't open the menu twice).\n */\nexport const isMenuKey = (e: React.KeyboardEvent): boolean => e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10');\n\n/** Events made by `menuEventAt`: their menu was opened from the keyboard, so it opens on its first item. */\nexport const keyboardMenuEvents: WeakSet<object> = new WeakSet<object>();\n\n/** A `contextmenu` event placed at an element, for opening that element's menu from the keyboard. */\nexport const menuEventAt = (el: Element): React.MouseEvent => {\n const r = el.getBoundingClientRect();\n const event = new MouseEvent('contextmenu', { clientX: r.left, clientY: r.bottom, cancelable: true });\n keyboardMenuEvents.add(event);\n return event as unknown as React.MouseEvent;\n};\n\n/**\n * The menu's initial focus for one of the library's own menus: the first item when it was opened\n * from the keyboard (the Menu key or Shift+F10 via `menuEventAt`, or Enter/Space on a button,\n * whose click has `detail` 0), else the default — the menu itself, nothing highlighted.\n */\nexport const initialFocusFor = (e: React.MouseEvent): 'first-item' | undefined =>\n keyboardMenuEvents.has(e) || (e.type === 'click' && e.detail === 0) ? 'first-item' : undefined;\n\n/**\n * After a tab closed from the keyboard, keep focus in the workspace instead of letting it drop to\n * <body>: the tab selected in its place, else the workspace's active tab, else the workspace.\n * Leaves focus alone if the close was refused, or if something else (a dialog) already moved it.\n */\nexport const refocusAfterTabClose = (id: string, strip: HTMLElement | null, workspaceEl: HTMLElement | null): void => {\n if (!workspaceEl?.isConnected) return;\n const esc = id.replace(/[\"\\\\]/g, '\\\\$&');\n if (workspaceEl.querySelector(`[data-tab-id=\"${esc}\"]`)) return;\n const active = document.activeElement;\n if (active && active !== document.body) return;\n const target = (strip?.isConnected ? strip.querySelector<HTMLElement>('[role=\"tab\"][aria-selected=\"true\"]') : null)\n ?? workspaceEl.querySelector<HTMLElement>('.rdd-workspace-tab-active-focused')\n ?? workspaceEl.querySelector<HTMLElement>('[role=\"tab\"][aria-selected=\"true\"]')\n ?? workspaceEl;\n target.focus();\n};\n\n/** A panel or group id made safe for an HTML `id` (used to link tabs to their tab panel). */\nexport const domIdPart = (raw: string): string => raw.replace(/[^A-Za-z0-9_-]/g, '_');\n\n/** A touch press held this long starts a drag (or opens a menu) instead of a tap. */\nexport const LONG_PRESS_MS = 300;\n/** Moving this far before then cancels the long press: the finger is scrolling, not pressing. */\nexport const CANCEL_MOVE_PX = 8;\n","/**\n * @file icons.tsx\n * @description Icons drawn by the workspace: the default panel icon and the context-menu item icons.\n */\n\n\nexport const DefaultGridIcon: React.ReactElement = (\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"3\" y=\"3\" width=\"7\" height=\"9\" rx=\"1\" />\n <rect x=\"14\" y=\"3\" width=\"7\" height=\"5\" rx=\"1\" />\n <rect x=\"14\" y=\"12\" width=\"7\" height=\"9\" rx=\"1\" />\n <rect x=\"3\" y=\"16\" width=\"7\" height=\"5\" rx=\"1\" />\n </svg>\n);\n\nexport const ContextMenuIcons: Record<'float' | 'minimize' | 'restore' | 'maximize' | 'close', React.ReactElement> = {\n // Two offset equal rects — Windows \"restore-down / new window\" language\n float: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"2\" y=\"8\" width=\"14\" height=\"14\" rx=\"1\"/>\n <rect x=\"8\" y=\"2\" width=\"14\" height=\"14\" rx=\"1\"/>\n </svg>\n </span>\n ),\n // Single horizontal dash — Windows minimize language\n minimize: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\">\n <line x1=\"4\" y1=\"18\" x2=\"20\" y2=\"18\"/>\n </svg>\n </span>\n ),\n // Single inset rect — restore to normal windowed state\n restore: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"1\"/>\n </svg>\n </span>\n ),\n // Near-full rect — maximize / fill workspace\n maximize: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"2\" y=\"2\" width=\"20\" height=\"20\" rx=\"1\"/>\n </svg>\n </span>\n ),\n // × — close\n close: (\n <span className=\"rdd-menu-icon\">\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </span>\n ),\n};\n","/**\n * @file WorkspaceZones.tsx\n * @description The drop targets shown while a panel is dragged: the workspace edges, the corner anchors, and the preview of an edge drop.\n */\nimport React from 'react';\nimport type { SplitDirection, FloatAnchor, WorkspaceState, PanelDropTarget } from '../../types';\n\nexport interface WorkspaceZonesProps {\n state: WorkspaceState;\n activeEdgeDrop: SplitDirection | null;\n activeCornerAnchor: FloatAnchor | null;\n setActiveEdgeDrop: (val: SplitDirection | null) => void;\n setActiveCornerAnchor: (val: FloatAnchor | null) => void;\n /** Whether the dragged panel may go to a target; a forbidden one isn't offered (7.9.0). */\n isDropAllowed: (panelId: string, to: PanelDropTarget) => boolean;\n}\n\n/** The side an edge drop applies: edges are drawn by screen side, and the move flips them under RTL. */\nconst appliedSide = (side: SplitDirection, rtl: boolean): SplitDirection =>\n rtl && (side === 'left' || side === 'right') ? (side === 'left' ? 'right' : 'left') : side;\n\nexport const WorkspaceZones = ({ state, activeEdgeDrop, activeCornerAnchor, setActiveEdgeDrop, setActiveCornerAnchor, isDropAllowed }: WorkspaceZonesProps): React.ReactElement => {\n const dragged = state.draggedPanelId;\n const edge = (side: SplitDirection) => dragged !== null && isDropAllowed(dragged, { kind: 'edge', side: appliedSide(side, state.isRtl) });\n const cornerOffered = (anchor: FloatAnchor) => dragged !== null && isDropAllowed(dragged, { kind: 'float', anchor });\n return (\n <>\n {/* Workspace outer edge drop zone targets */}\n {state.draggedPanelId !== null && (\n <>\n {edge('left') && <div\n data-edge-trigger=\"left\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-left\"\n onPointerEnter={() => setActiveEdgeDrop('left')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n {edge('right') && <div\n data-edge-trigger=\"right\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-right\"\n onPointerEnter={() => setActiveEdgeDrop('right')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n {edge('top') && <div\n data-edge-trigger=\"top\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-top\"\n onPointerEnter={() => setActiveEdgeDrop('top')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n {edge('bottom') && <div\n data-edge-trigger=\"bottom\"\n className=\"rdd-workspace-edge-trigger rdd-edge-trigger-bottom\"\n onPointerEnter={() => setActiveEdgeDrop('bottom')}\n onPointerLeave={() => setActiveEdgeDrop(null)}\n />}\n </>\n )}\n\n {/* Corner anchor drop zones — appear during floating window drag */}\n {state.draggedPanelId !== null && (['top-left', 'top-right', 'bottom-left', 'bottom-right'] as FloatAnchor[]).filter(cornerOffered).map(corner => (\n <div\n key={corner}\n className={`rdd-corner-zone rdd-corner-zone--${corner}${activeCornerAnchor === corner ? ' rdd-corner-zone--hovered' : ''}`}\n onPointerEnter={() => { setActiveCornerAnchor(corner); setActiveEdgeDrop(null); }}\n onPointerLeave={() => setActiveCornerAnchor(null)}\n aria-hidden=\"true\"\n />\n ))}\n\n {/* Edge drop visual preview overlay */}\n {state.draggedPanelId !== null && activeEdgeDrop !== null && (\n <div\n className=\"rdd-workspace-edge-preview\"\n style={(() => {\n const pct = `${state.edgeSplitRatio * 100}%`;\n switch (activeEdgeDrop) {\n case 'left': return { left: 0, top: 0, bottom: 0, width: pct };\n case 'right': return { right: 0, top: 0, bottom: 0, width: pct };\n case 'top': return { top: 0, left: 0, right: 0, height: pct };\n case 'bottom': return { bottom: 0, left: 0, right: 0, height: pct };\n }\n })()}\n />\n )}\n </>\n );\n};\n","/**\n * @file FloatingWindows.tsx\n * @description The workspace's floating windows: title bar, body slot and resize handles, docked to a corner or free.\n */\nimport React from 'react';\nimport { formatLabel } from '../WindowManagerContext';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, InternalWindowActions } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport type { ResizeDir } from '../dragResize';\nimport { initialFocusFor } from './helpers';\nimport { DefaultGridIcon, ContextMenuIcons } from './icons';\nimport { PreservedDOMWrapper } from './panelMount';\nimport { optionsFor } from '../../core/panelOptions';\n\nexport interface FloatingWindowsProps extends Pick<InternalWindowActions, 'setActivePanel' | 'focusPanel' | 'maximizePanel' | 'minimizePanel' | 'getPanelContextMenuItems' | 'showContextMenu'> {\n state: WorkspaceState;\n registry: PanelRegistry;\n windowClass?: string;\n windowBodyClass?: string;\n defaultPanelIcon?: React.ReactNode;\n messages: Record<MessageKey, MessageDescriptor>;\n formatMessage: MessageFormatter;\n handleRequestClose: (id: string) => unknown;\n startDrag: (id: string, e: React.PointerEvent) => void;\n startResize: (id: string, dir: ResizeDir, e: React.PointerEvent) => void;\n}\n\nexport const FloatingWindows = ({\n state, registry, windowClass, windowBodyClass, defaultPanelIcon, messages, formatMessage,\n setActivePanel, focusPanel, maximizePanel, minimizePanel, getPanelContextMenuItems, showContextMenu,\n handleRequestClose, startDrag, startResize,\n}: FloatingWindowsProps): React.ReactElement => (\n <>\n {state.floating.map(w => {\n const panel = state.panels[w.id];\n if (!panel) return null;\n\n const isMaximized = w.maximized;\n const isDragged = state.draggedPanelId === w.id;\n const isFocused = state.activePanelId === w.id;\n\n const options = optionsFor(registry, panel);\n\n return (\n <div\n key={w.id}\n data-window-id={w.id}\n data-rdd-window={w.id}\n // State for app CSS (7.8.0): present when true.\n data-rdd-focused={isFocused ? '' : undefined}\n data-rdd-maximized={isMaximized ? '' : undefined}\n dir={state.dir}\n onPointerDownCapture={() => {\n setActivePanel(w.id);\n focusPanel(w.id);\n }}\n className={`rdd-floating-window ${isMaximized ? 'rdd-maximized' : ''} ${isFocused ? 'rdd-window-focused' : ''} ${windowClass ?? ''}`}\n style={(() => {\n const CORNER_INSET = 8;\n const CORNER_GAP = 8;\n const w_ = typeof w.width === 'number' ? `${w.width}px` : w.width;\n const h_ = typeof w.height === 'number' ? `${w.height}px` : w.height;\n if (isMaximized) {\n return { position: 'absolute' as const, left: 0, top: 0, width: '100%', height: '100%', zIndex: w.z, pointerEvents: isDragged ? 'none' as const : 'auto' as const };\n }\n if (w.anchor) {\n const stack = state.floating.filter(fw => fw.anchor === w.anchor && !fw.maximized);\n const idx = stack.findIndex(fw => fw.id === w.id);\n let stackOffset = CORNER_INSET;\n for (let i = 0; i < idx; i++) {\n const sh = typeof stack[i].height === 'number' ? stack[i].height as number : parseFloat(stack[i].height as string);\n stackOffset += sh + CORNER_GAP;\n }\n const isTop = w.anchor.startsWith('top');\n const isRight = w.anchor.endsWith('-right');\n return {\n position: 'absolute' as const,\n [isRight ? 'insetInlineEnd' : 'insetInlineStart']: CORNER_INSET,\n [isTop ? 'top' : 'bottom']: stackOffset,\n width: w_,\n height: h_,\n zIndex: w.z,\n transition: isDragged ? 'none' : 'top 0.2s ease, bottom 0.2s ease',\n pointerEvents: isDragged ? 'none' as const : 'auto' as const,\n };\n }\n return {\n position: 'absolute' as const,\n left: typeof w.x === 'number' ? `${w.x}px` : w.x,\n top: typeof w.y === 'number' ? `${w.y}px` : w.y,\n width: w_,\n height: h_,\n zIndex: w.z,\n pointerEvents: isDragged ? 'none' as const : 'auto' as const,\n };\n })()}\n >\n {/* The frame clips title bar and body to the rounded corners. It is a separate\n element so the resize handles (siblings below) can straddle the window edge:\n clipping on the window itself cut off their outer half, and the corners. */}\n <div className=\"rdd-floating-window-frame\">\n {/* Title Bar */}\n <div\n onDoubleClick={() => maximizePanel(w.id)}\n onPointerDown={(e) => {\n if (options?.canDrag !== false) {\n startDrag(w.id, e);\n }\n }}\n data-rdd-titlebar={w.id}\n className=\"rdd-floating-window-titlebar rdd-cursor-move\"\n style={{ cursor: isMaximized || options?.canDrag === false ? 'default' : 'move' }}\n >\n <span className=\"rdd-floating-window-title\">\n <span className=\"rdd-window-title-icon\">{panel.icon ?? (options?.icon || defaultPanelIcon || DefaultGridIcon)}</span>\n <span>\n {formatLabel(panel.title, formatMessage)}\n {panel.dirty ? ' *' : ''}\n </span>\n </span>\n <div className=\"rdd-titlebar-actions\" onPointerDown={(e) => e.stopPropagation()}>\n {options?.renderHeaderActions && (\n <div className=\"rdd-window-header-actions\">\n {options.renderHeaderActions(w.id)}\n </div>\n )}\n {getPanelContextMenuItems(w.id).length > 0 && (\n <button\n type=\"button\"\n className=\"rdd-custom-tab-btn rdd-btn-more-actions\"\n title={formatLabel(messages.moreActions, formatMessage)}\n aria-label={formatLabel(messages.moreActions, formatMessage)}\n onClick={(e) => {\n e.stopPropagation();\n const customItems = getPanelContextMenuItems(w.id);\n if (customItems.length === 0) return;\n // A hosted panel's menu is its widget's titleMenu, then the built-in Close (7.11.0).\n const closeItem = panel.owner && options?.canClose !== false\n ? [{ separator: true as const }, { label: formatLabel(messages.closePanel, formatMessage), icon: ContextMenuIcons.close, action: () => handleRequestClose(w.id) }]\n : [];\n showContextMenu({\n event: e,\n items: [...customItems, ...closeItem],\n initialFocus: initialFocusFor(e),\n });\n }}\n >\n <svg className=\"rdd-svg-icon\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <circle cx=\"12\" cy=\"5\" r=\"2\"/>\n <circle cx=\"12\" cy=\"12\" r=\"2\"/>\n <circle cx=\"12\" cy=\"19\" r=\"2\"/>\n </svg>\n </button>\n )}\n <button\n type=\"button\"\n title={isMaximized\n ? formatLabel(messages.restoreSize, formatMessage)\n : formatLabel(messages.maximize, formatMessage)}\n onClick={() => maximizePanel(w.id)}\n className=\"rdd-custom-tab-btn rdd-btn-maximize-tab\"\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"1.5\"/>\n </svg>\n </button>\n {options?.canMinimize !== false && (\n <button\n type=\"button\"\n title={formatLabel(messages.minimize, formatMessage)}\n onClick={() => minimizePanel(w.id)}\n className=\"rdd-custom-tab-btn rdd-btn-minimize-tab\"\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"3\">\n <path d=\"M5 12h14\"/>\n </svg>\n </button>\n )}\n {options?.canClose !== false && (\n <button\n type=\"button\"\n title={formatLabel(messages.close, formatMessage)}\n onClick={() => handleRequestClose(w.id)}\n className=\"rdd-custom-tab-btn rdd-btn-close-tab\"\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"3\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </button>\n )}\n </div>\n </div>\n\n {/* Window Content */}\n <div className={`rdd-floating-window-body${windowBodyClass ? ` ${windowBodyClass}` : ''}`}>\n <PreservedDOMWrapper key={w.id} panelId={w.id} />\n </div>\n </div>\n\n {/* 8-direction resize handles */}\n {!isMaximized && (\n <>\n <div onPointerDown={(e) => startResize(w.id, 'n', e)} className=\"rdd-resize-handle rdd-resize-n\" />\n <div onPointerDown={(e) => startResize(w.id, 'ne', e)} className=\"rdd-resize-handle rdd-resize-ne\" />\n <div onPointerDown={(e) => startResize(w.id, 'e', e)} className=\"rdd-resize-handle rdd-resize-e\" />\n <div onPointerDown={(e) => startResize(w.id, 'se', e)} className=\"rdd-resize-handle rdd-resize-se\" />\n <div onPointerDown={(e) => startResize(w.id, 's', e)} className=\"rdd-resize-handle rdd-resize-s\" />\n <div onPointerDown={(e) => startResize(w.id, 'sw', e)} className=\"rdd-resize-handle rdd-resize-sw\" />\n <div onPointerDown={(e) => startResize(w.id, 'w', e)} className=\"rdd-resize-handle rdd-resize-w\" />\n <div onPointerDown={(e) => startResize(w.id, 'nw', e)} className=\"rdd-resize-handle rdd-resize-nw\" />\n </>\n )}\n </div>\n );\n })}\n </>\n);\n","/**\n * @file Taskbar.tsx\n * @description The taskbar of minimized panels: its items, the hover or long-press preview, scrolling and autohide.\n */\nimport React from 'react';\nimport { createPortal } from 'react-dom';\nimport { formatLabel } from '../WindowManagerContext';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, InternalWindowActions } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport { isMenuKey, menuEventAt, LONG_PRESS_MS, CANCEL_MOVE_PX } from './helpers';\nimport { DefaultGridIcon } from './icons';\nimport { PreviewDOMWrapper } from './panelMount';\nimport type { TaskbarVisibility } from '../WindowManager';\nimport { optionsFor } from '../../core/panelOptions';\n\n/** The minimized panel whose preview is showing, and where its taskbar item is. */\nexport type HoveredMinimized = { id: string; rect: DOMRect; title: WorkspaceState['minimized'][number]['title']; component: string; fromTouch?: boolean };\n\nexport interface TaskbarProps extends Pick<InternalWindowActions, 'restorePanel'> {\n state: WorkspaceState;\n registry: PanelRegistry;\n taskbarVisibility: TaskbarVisibility;\n taskbarExpanded: boolean;\n expandTaskbar: () => void;\n leaveTaskbar: () => void;\n scrollTaskbar: (direction: 'left' | 'right') => void;\n taskbarRef: React.RefObject<HTMLDivElement | null>;\n /** This workspace's preview tooltip, so the touch dismissal never tests another workspace's. */\n tooltipRef: React.RefObject<HTMLDivElement | null>;\n defaultPanelIcon?: React.ReactNode;\n messages: Record<MessageKey, MessageDescriptor>;\n formatMessage: MessageFormatter;\n lastTaskbarPointerTypeRef: React.RefObject<string>;\n hoveredMinimized: HoveredMinimized | null;\n setHoveredMinimized: (v: HoveredMinimized | null) => void;\n minimizedTooltipTimeoutRef: React.RefObject<ReturnType<typeof setTimeout> | null>;\n isContextMenuOpen: boolean;\n handleMinimizedRightClick: (id: string, e: React.MouseEvent) => void;\n handleRequestClose: (id: string) => unknown;\n}\n\nexport const Taskbar = ({\n state, registry, taskbarVisibility, taskbarExpanded, expandTaskbar, leaveTaskbar, scrollTaskbar,\n taskbarRef, tooltipRef, defaultPanelIcon, messages, formatMessage, lastTaskbarPointerTypeRef, hoveredMinimized,\n setHoveredMinimized, minimizedTooltipTimeoutRef, isContextMenuOpen, handleMinimizedRightClick,\n handleRequestClose, restorePanel,\n}: TaskbarProps): React.ReactElement | null => {\n if (!((taskbarVisibility === 'always' || state.minimized.length > 0))) return null;\n return (\n <div\n className={[\n 'rdd-taskbar-footer-container',\n `rdd-taskbar-mode-${taskbarVisibility}`,\n taskbarVisibility === 'autohide' && taskbarExpanded ? 'rdd-taskbar-expanded' : '',\n ].filter(Boolean).join(' ')}\n onPointerEnter={taskbarVisibility === 'autohide' ? expandTaskbar : undefined}\n onPointerLeave={taskbarVisibility === 'autohide' ? leaveTaskbar : undefined}\n >\n {taskbarVisibility === 'autohide' && <div className=\"rdd-taskbar-peek-handle\" />}\n <button\n type=\"button\"\n onClick={() => scrollTaskbar('left')}\n className=\"rdd-taskbar-nav-btn\"\n aria-label={formatLabel(messages.scrollTaskbarLeft, formatMessage)}\n style={{ display: state.minimized.length > 4 ? 'block' : 'none' }}\n >\n ◀\n </button>\n\n <div\n ref={taskbarRef}\n className=\"rdd-taskbar-items-container\"\n >\n {state.minimized.map(m => {\n const options = optionsFor(registry, state.panels[m.id], m.component);\n const icon = state.panels[m.id]?.icon ?? (options?.icon || defaultPanelIcon || DefaultGridIcon);\n\n return (\n <button\n type=\"button\"\n key={m.id}\n aria-label={formatLabel(m.title, formatMessage)}\n onClick={(e) => {\n // A touch tap is handled by the long-press logic in onPointerDown. A keyboard\n // click (Enter / Space) has detail 0 and always restores.\n if (e.detail !== 0 && lastTaskbarPointerTypeRef.current === 'touch') return;\n setHoveredMinimized(null);\n restorePanel(m.id);\n }}\n onContextMenu={(e) => handleMinimizedRightClick(m.id, e)}\n onKeyDown={(e) => {\n if (!isMenuKey(e)) return;\n e.preventDefault();\n handleMinimizedRightClick(m.id, menuEventAt(e.currentTarget));\n }}\n onPointerDown={(e) => {\n lastTaskbarPointerTypeRef.current = e.pointerType;\n if (e.pointerType !== 'touch') return;\n const el = e.currentTarget as HTMLElement;\n const startX = e.clientX;\n const startY = e.clientY;\n const pointerId = e.pointerId;\n let cancelled = false;\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', onShortTap);\n el.removeEventListener('pointercancel', cancel);\n };\n const onShortTap = () => {\n cancel();\n const rect = el.getBoundingClientRect();\n if (hoveredMinimized?.id === m.id) {\n restorePanel(m.id);\n setHoveredMinimized(null);\n } else {\n setHoveredMinimized({ id: m.id, rect, title: m.title, component: m.component, fromTouch: true });\n }\n };\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', onShortTap);\n el.removeEventListener('pointercancel', cancel);\n try { el.setPointerCapture(pointerId); } catch { return; }\n if (navigator.vibrate) navigator.vibrate(10);\n const onEnd = (me: PointerEvent) => {\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onEnd);\n handleMinimizedRightClick(m.id, me as unknown as React.MouseEvent);\n };\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onEnd);\n }, LONG_PRESS_MS);\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', onShortTap);\n el.addEventListener('pointercancel', cancel);\n }}\n onPointerEnter={(e) => {\n if (e.pointerType === 'touch') return;\n if (isContextMenuOpen) return;\n if (minimizedTooltipTimeoutRef.current) {\n clearTimeout(minimizedTooltipTimeoutRef.current);\n }\n const rect = e.currentTarget.getBoundingClientRect();\n const isInside = (\n e.clientX >= rect.left &&\n e.clientX <= rect.right &&\n e.clientY >= rect.top &&\n e.clientY <= rect.bottom\n );\n if (!isInside) return;\n setHoveredMinimized({ id: m.id, rect, title: m.title, component: m.component });\n }}\n onPointerLeave={(e) => {\n if (e.pointerType === 'touch') return;\n minimizedTooltipTimeoutRef.current = setTimeout(() => {\n setHoveredMinimized(null);\n }, 150);\n }}\n className=\"rdd-taskbar-glassmorphic-item\"\n data-rdd-taskbar-item={m.id}\n >\n <span className=\"rdd-taskbar-item-icon\" aria-hidden=\"true\">\n {icon}\n </span>\n </button>\n );\n })}\n </div>\n\n {hoveredMinimized && createPortal(\n <div\n ref={tooltipRef}\n className=\"rdd-taskbar-item-tooltip\"\n dir={state.dir}\n style={{\n left: `${hoveredMinimized.rect.left + hoveredMinimized.rect.width / 2}px`,\n top: `${hoveredMinimized.rect.top - 8}px`,\n }}\n onPointerEnter={() => {\n if (minimizedTooltipTimeoutRef.current) {\n clearTimeout(minimizedTooltipTimeoutRef.current);\n }\n }}\n onPointerLeave={(e) => {\n if (e.pointerType === 'touch') return;\n setHoveredMinimized(null);\n }}\n onClick={() => {\n restorePanel(hoveredMinimized.id);\n setHoveredMinimized(null);\n }}\n onContextMenu={(e) => handleMinimizedRightClick(hoveredMinimized.id, e)}\n onPointerDown={(e) => {\n if (e.pointerType !== 'touch') return;\n const tooltipId = hoveredMinimized.id;\n const el = e.currentTarget as HTMLElement;\n const startX = e.clientX;\n const startY = e.clientY;\n const pointerId = e.pointerId;\n let cancelled = false;\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n };\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n try { el.setPointerCapture(pointerId); } catch { return; }\n if (navigator.vibrate) navigator.vibrate(10);\n const onEnd = (me: PointerEvent) => {\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onEnd);\n handleMinimizedRightClick(tooltipId, me as unknown as React.MouseEvent);\n };\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onEnd);\n }, LONG_PRESS_MS);\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', cancel);\n el.addEventListener('pointercancel', cancel);\n }}\n >\n <div className=\"rdd-tooltip-header-row\">\n <span className=\"rdd-tooltip-title-text rdd-text-truncate\">\n {formatLabel(hoveredMinimized.title, formatMessage)}\n {state.panels[hoveredMinimized.id]?.dirty ? ' *' : ''}\n </span>\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n handleRequestClose(hoveredMinimized.id);\n setHoveredMinimized(null);\n }}\n title={formatLabel(messages.closePanel, formatMessage)}\n aria-label={formatLabel(messages.closePanel, formatMessage)}\n className=\"rdd-tooltip-close-x\"\n >\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" aria-hidden=\"true\">\n <path d=\"M18 6L6 18M6 6l12 12\"/>\n </svg>\n </button>\n </div>\n <PreviewDOMWrapper panelId={hoveredMinimized.id} />\n </div>,\n document.body\n )}\n\n <button\n type=\"button\"\n onClick={() => scrollTaskbar('right')}\n className=\"rdd-taskbar-nav-btn\"\n aria-label={formatLabel(messages.scrollTaskbarRight, formatMessage)}\n style={{ display: state.minimized.length > 4 ? 'block' : 'none' }}\n >\n ▶\n </button>\n </div>\n );\n};\n","/**\n * @file useDragTargets.ts\n * @description Where a dragged panel would land: the hovered drop zone, tab, workspace edge or corner, kept both as state (to render) and in refs (to read in pointer handlers), and the ghost position.\n */\nimport React, { useState, useRef } from 'react';\nimport type { SplitDirection, DropPosition, FloatAnchor, InternalWindowActions } from '../../types';\nimport { tabDropSide } from './helpers';\n\ntype DropZoneTarget = { leafId: string; position: DropPosition };\ntype Point = { x: number; y: number };\ntype TabTarget = { leafId: string; panelId: string; index: number; side: 'left' | 'right' };\n\n/**\n * The tab-drag ghost's position. Written on every pointer move and read only by the ghost, so it\n * lives outside React state: a move re-renders the ghost, not the desktop (7.7.2).\n */\nexport interface DragPos {\n get: () => Point;\n set: (v: Point) => void;\n subscribe: (cb: () => void) => () => void;\n}\n\nconst createDragPos = (): DragPos => {\n let pos: Point = { x: 0, y: 0 };\n const listeners = new Set<() => void>();\n return {\n get: () => pos,\n set: (v) => { pos = v; listeners.forEach(l => l()); },\n subscribe: (cb) => { listeners.add(cb); return () => { listeners.delete(cb); }; },\n };\n};\n\nconst sameDropZone = (a: DropZoneTarget | null, b: DropZoneTarget | null) =>\n a === b || (!!a && !!b && a.leafId === b.leafId && a.position === b.position);\nconst sameTab = (a: TabTarget | null, b: TabTarget | null) =>\n a === b || (!!a && !!b && a.leafId === b.leafId && a.panelId === b.panelId && a.index === b.index && a.side === b.side);\n\n/** What `useDragTargets` returns. */\nexport interface DragTargets {\n activeDropZone: DropZoneTarget | null;\n setActiveDropZone: (v: DropZoneTarget | null) => void;\n activeDropZoneRef: React.RefObject<DropZoneTarget | null>;\n dragPos: DragPos;\n setDragPos: (v: Point) => void;\n activeEdgeDrop: SplitDirection | null;\n activeEdgeDropRef: React.RefObject<SplitDirection | null>;\n setActiveEdgeDrop: (val: SplitDirection | null) => void;\n activeCornerAnchor: FloatAnchor | null;\n activeCornerAnchorRef: React.RefObject<FloatAnchor | null>;\n setActiveCornerAnchor: (val: FloatAnchor | null) => void;\n hoveredTab: TabTarget | null;\n setHoveredTab: (v: TabTarget | null) => void;\n hoveredTabRef: React.RefObject<TabTarget | null>;\n handleTabHover: (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => void;\n handleHoverDropZone: (leafId: string, position: DropPosition | null) => void;\n updateHoverFromPoint: (x: number, y: number) => void;\n clearDragState: () => void;\n flipRtl: (pos: DropPosition) => DropPosition;\n}\n\nexport function useDragTargets({ setDraggedPanelId, isRtl, canInsertInto }: {\n setDraggedPanelId: InternalWindowActions['setDraggedPanelId'];\n isRtl: boolean;\n /** Whether the dragged panel may be inserted among a group's tabs; a forbidden group's tabs are no target (7.9.0). */\n canInsertInto: (leafId: string) => boolean;\n}): DragTargets {\n const [activeDropZone, setActiveDropZone] = useState<{ leafId: string; position: DropPosition } | null>(null);\n const activeDropZoneRef = useRef<{ leafId: string; position: DropPosition } | null>(null);\n const [dragPos] = useState(createDragPos);\n const setDragPos = dragPos.set;\n\n const [activeEdgeDrop, setActiveEdgeDropState] = useState<SplitDirection | null>(null);\n const activeEdgeDropRef = useRef<SplitDirection | null>(null);\n const setActiveEdgeDrop = (val: SplitDirection | null) => {\n setActiveEdgeDropState(val);\n activeEdgeDropRef.current = val;\n };\n\n const [activeCornerAnchor, setActiveCornerAnchorState] = useState<FloatAnchor | null>(null);\n const activeCornerAnchorRef = useRef<FloatAnchor | null>(null);\n const setActiveCornerAnchor = (val: FloatAnchor | null) => {\n setActiveCornerAnchorState(val);\n activeCornerAnchorRef.current = val;\n };\n\n const [hoveredTab, setHoveredTab] = useState<{ leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null>(null);\n const hoveredTabRef = useRef<{ leafId: string; panelId: string; index: number; side: 'left' | 'right' } | null>(null);\n\n const handleTabHover = (leafId: string, panelId: string, index: number, side: 'left' | 'right' | null) => {\n const val = side && canInsertInto(leafId) ? { leafId, panelId, index, side } : null;\n setHoveredTab(val);\n hoveredTabRef.current = val;\n };\n\n const handleHoverDropZone = (leafId: string, position: DropPosition | null) => {\n const val = position ? { leafId, position } : null;\n setActiveDropZone(val);\n activeDropZoneRef.current = val;\n // A leaf's cross commonly overlaps the workspace edge/corner zones underneath it —\n // the more specific per-leaf target wins, matching the corner zone's own handler,\n // which already clears the edge the same way.\n if (val) {\n setActiveEdgeDrop(null);\n setActiveCornerAnchor(null);\n }\n };\n\n // Used during touch drag (pointer capture suppresses hover events on other elements)\n const updateHoverFromPoint = (x: number, y: number) => {\n const elements = document.elementsFromPoint(x, y);\n let foundDropZone = false;\n let foundEdge = false;\n let foundTab = false;\n\n for (const el of elements) {\n if (!(el instanceof HTMLElement)) continue;\n\n if (!foundDropZone && el.dataset.dropZone) {\n const leafId = el.dataset.leafId;\n if (leafId) {\n const val = { leafId, position: el.dataset.dropZone as DropPosition };\n setActiveDropZone(prev => sameDropZone(prev, val) ? prev : val);\n activeDropZoneRef.current = val;\n foundDropZone = true;\n }\n }\n\n // Tabs checked before edge triggers — precise tab intent beats the coarse edge zone\n if (!foundTab && el.dataset.tabId) {\n const leafId = el.dataset.leafId;\n const tabIdx = parseInt(el.dataset.tabIndex || '0', 10);\n if (leafId && canInsertInto(leafId)) {\n const val = { leafId, panelId: el.dataset.tabId, index: tabIdx, side: tabDropSide(el, x) };\n setHoveredTab(prev => sameTab(prev, val) ? prev : val);\n hoveredTabRef.current = val;\n foundTab = true;\n }\n }\n\n if (!foundEdge && el.dataset.edgeTrigger) {\n setActiveEdgeDrop(el.dataset.edgeTrigger as SplitDirection);\n foundEdge = true;\n }\n\n if (foundDropZone && foundEdge && foundTab) break;\n }\n\n if (!foundDropZone) { setActiveDropZone(null); activeDropZoneRef.current = null; }\n if (!foundEdge) setActiveEdgeDrop(null);\n if (!foundTab) { setHoveredTab(null); hoveredTabRef.current = null; }\n };\n\n\n const clearDragState = () => {\n setDraggedPanelId(null);\n setActiveDropZone(null);\n activeDropZoneRef.current = null;\n setHoveredTab(null);\n hoveredTabRef.current = null;\n setActiveEdgeDrop(null);\n setActiveCornerAnchor(null);\n };\n\n const flipRtl = (pos: DropPosition): DropPosition => {\n if (!isRtl) return pos;\n if (pos === 'left') return 'right';\n if (pos === 'right') return 'left';\n return pos;\n };\n\n return {\n activeDropZone, setActiveDropZone, activeDropZoneRef, dragPos, setDragPos,\n activeEdgeDrop, activeEdgeDropRef, setActiveEdgeDrop,\n activeCornerAnchor, activeCornerAnchorRef, setActiveCornerAnchor,\n hoveredTab, setHoveredTab, hoveredTabRef,\n handleTabHover, handleHoverDropZone, updateHoverFromPoint, clearDragState, flipRtl,\n };\n}\n","/**\n * @file tabDrag.ts\n * @description Dragging a tab: a mouse drag, or a touch long-press that drags on move and opens the menu on release; and the drop that docks, reorders or floats the panel.\n */\nimport React from 'react';\nimport type { SplitDirection, WorkspaceState, InternalWindowActions } from '../../types';\nimport { findLeaf, LONG_PRESS_MS, CANCEL_MOVE_PX } from './helpers';\nimport type { DragTargets } from './useDragTargets';\n\nexport interface TabDragDeps {\n state: WorkspaceState;\n targets: DragTargets;\n actions: Pick<InternalWindowActions, 'dockPanelToWorkspaceEdge' | 'movePanelOrder' | 'dockPanelToGroup' | 'floatPanel' | 'setDraggedPanelId' | 'isDropAllowed'>;\n handleTabRightClick: (id: string, e: React.MouseEvent) => void;\n}\n\nexport function createTabDrag(deps: TabDragDeps): { executeDrop: (id: string, me: PointerEvent) => void; handleTabDragStart: (id: string, e: React.PointerEvent) => void } {\n const { state, handleTabRightClick } = deps;\n const { activeDropZoneRef, hoveredTabRef, activeEdgeDropRef, activeCornerAnchorRef, setActiveCornerAnchor, clearDragState, flipRtl, setDragPos, updateHoverFromPoint } = deps.targets;\n const { dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, floatPanel, setDraggedPanelId, isDropAllowed } = deps.actions;\n\n const executeDrop = (id: string, me: PointerEvent) => {\n const dropZone = activeDropZoneRef.current;\n const targetTab = hoveredTabRef.current;\n const edgeDrop = activeEdgeDropRef.current;\n const cornerAnchor = activeCornerAnchorRef.current;\n\n // Each target was only offered if the rules allowed it (7.9.0); asking again here covers a rule\n // that changed mid-drag. A forbidden target, or nowhere when floating is forbidden, does nothing.\n if (edgeDrop) {\n const side = flipRtl(edgeDrop) as SplitDirection;\n if (isDropAllowed(id, { kind: 'edge', side })) dockPanelToWorkspaceEdge(id, side);\n } else if (targetTab) {\n if (!isDropAllowed(id, { kind: 'group', leafId: targetTab.leafId, position: 'center' })) { setActiveCornerAnchor(null); clearDragState(); return; }\n let targetIndex = targetTab.index;\n if (targetTab.side === 'right') targetIndex += 1;\n // DOM tab indices are pre-removal. movePanelOrder removes the panel before\n // inserting, shifting subsequent positions down by 1 in the same leaf.\n // Compensate when the dragged panel currently sits before the drop target.\n const targetLeaf = findLeaf(state.gridRoot, targetTab.leafId);\n if (targetLeaf) {\n const currentIdx = targetLeaf.panels.indexOf(id);\n if (currentIdx !== -1 && currentIdx < targetIndex) targetIndex -= 1;\n }\n movePanelOrder(id, targetTab.leafId, targetIndex);\n } else if (dropZone) {\n const position = flipRtl(dropZone.position);\n if (isDropAllowed(id, { kind: 'group', leafId: dropZone.leafId, position })) dockPanelToGroup(id, dropZone.leafId, position);\n } else if (cornerAnchor) {\n // The zone's name is already the anchor: the CSS mirrors the zones under RTL, and an anchor is\n // drawn mirrored too. Flipping it here as well sent the window to the opposite corner.\n if (isDropAllowed(id, { kind: 'float', anchor: cornerAnchor })) floatPanel(id, undefined, cornerAnchor);\n } else if (isDropAllowed(id, { kind: 'float', anchor: null })) {\n floatPanel(id, { x: me.clientX - 150, y: me.clientY - 15, width: 450, height: 350 });\n }\n setActiveCornerAnchor(null);\n clearDragState();\n };\n\n const handleTabDragStart = (id: string, e: React.PointerEvent) => {\n if (e.pointerType === 'mouse' && e.button !== 0) return;\n e.preventDefault();\n\n const el = e.currentTarget as HTMLElement;\n const startX = e.clientX;\n const startY = e.clientY;\n\n if (e.pointerType === 'touch') {\n const pointerId = e.pointerId;\n let cancelled = false;\n\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n };\n\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n\n try { el.setPointerCapture(pointerId); } catch { return; }\n el.classList.add('rdd-long-press-active');\n document.body.classList.add('rdd-dragging-active');\n if (navigator.vibrate) navigator.vibrate(10);\n\n // Long-press captured: move → drag, release → context menu\n let dragStarted = false;\n\n const onMove = (me: PointerEvent) => {\n if (!dragStarted) {\n dragStarted = true;\n setDraggedPanelId(id);\n }\n setDragPos({ x: me.clientX, y: me.clientY });\n updateHoverFromPoint(me.clientX, me.clientY);\n };\n\n const onEnd = (me: PointerEvent) => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n\n if (dragStarted) {\n executeDrop(id, me);\n } else {\n // Release without drag → context menu\n handleTabRightClick(id, me as unknown as React.MouseEvent);\n }\n };\n\n const onCancel = () => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) clearDragState();\n };\n\n el.addEventListener('pointermove', onMove);\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onCancel);\n // The window losing focus ends the drag, as a pointercancel would (7.4.1).\n window.addEventListener('blur', onCancel);\n }, LONG_PRESS_MS);\n\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', cancel);\n el.addEventListener('pointercancel', cancel);\n } else {\n // Mouse / pen: window-level listeners WITHOUT setPointerCapture so that\n // onPointerEnter/Leave on drop zones and edge triggers still fire normally.\n let dragStarted = false;\n\n const onMove = (me: PointerEvent) => {\n const dx = me.clientX - startX;\n const dy = me.clientY - startY;\n if (!dragStarted && (Math.abs(dx) > 5 || Math.abs(dy) > 5)) {\n dragStarted = true;\n setDraggedPanelId(id);\n }\n if (dragStarted) setDragPos({ x: me.clientX, y: me.clientY });\n };\n\n const onEnd = (me: PointerEvent) => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) executeDrop(id, me);\n };\n\n const onCancel = () => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) clearDragState();\n };\n\n document.body.classList.add('rdd-dragging-active');\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onEnd);\n window.addEventListener('pointercancel', onCancel);\n // The window losing focus (an alt-tab, an iframe taking it) ends the drag, as a\n // pointercancel would (7.4.1): the listeners, the hovered zone and the body class all go,\n // so the next click can't drop the panel into the zone it was over.\n window.addEventListener('blur', onCancel);\n }\n };\n\n return { executeDrop, handleTabDragStart };\n}\n","/**\n * @file workspaceMenus.ts\n * @description The workspace's own context menus: a tab's, and a minimized panel's on the taskbar.\n */\nimport React from 'react';\nimport { formatLabel } from '../WindowManagerContext';\nimport type { MessageDescriptor, MessageFormatter, WorkspaceState, InternalWindowActions } from '../../types';\nimport type { MessageKey } from '../predefinedMessages';\nimport type { PanelRegistry } from '../PanelRegistry';\nimport { initialFocusFor } from './helpers';\nimport { ContextMenuIcons } from './icons';\nimport type { HoveredMinimized } from './Taskbar';\nimport { optionsFor } from '../../core/panelOptions';\n\nexport interface WorkspaceMenusDeps {\n state: WorkspaceState;\n registry: PanelRegistry;\n messages: Record<MessageKey, MessageDescriptor>;\n formatMessage: MessageFormatter;\n handleRequestClose: (id: string) => unknown;\n setHoveredMinimized: (v: HoveredMinimized | null) => void;\n actions: Pick<InternalWindowActions, 'floatPanel' | 'minimizePanel' | 'restorePanel' | 'maximizePanel' | 'getPanelContextMenuItems' | 'showContextMenu' | 'isDropAllowed'>;\n}\n\nexport function createWorkspaceMenus(deps: WorkspaceMenusDeps): { handleTabRightClick: (id: string, e: React.MouseEvent) => void; handleMinimizedRightClick: (id: string, e: React.MouseEvent) => void } {\n const { state, registry, messages, formatMessage, handleRequestClose, setHoveredMinimized } = deps;\n const { floatPanel, minimizePanel, restorePanel, maximizePanel, getPanelContextMenuItems, showContextMenu, isDropAllowed } = deps.actions;\n\n const handleTabRightClick = (id: string, e: React.MouseEvent) => {\n e.preventDefault();\n const panel = state.panels[id];\n if (!panel) return;\n const options = optionsFor(registry, panel);\n\n const items = [];\n // A hosted panel (a widget out of its panel, 7.11.0) has no built-in Float: the widget's own\n // titleMenu items, which lead its menu below, are what move it.\n const hosted = !!panel.owner;\n // Floating it is a move the rules decide (7.9.0): canFloat, then the app's canDrop.\n if (!hosted && options?.canDrag !== false && isDropAllowed(id, { kind: 'float', anchor: null })) {\n items.push({\n label: formatLabel(messages.floatWindow, formatMessage),\n icon: ContextMenuIcons.float,\n action: () => floatPanel(id)\n });\n }\n if (options?.canMinimize !== false) {\n items.push({\n label: formatLabel(messages.minimizePanel, formatMessage),\n icon: ContextMenuIcons.minimize,\n action: () => minimizePanel(id)\n });\n }\n if (items.length > 0 && options?.canClose !== false) {\n items.push({ separator: true as const });\n }\n if (options?.canClose !== false) {\n items.push({\n label: formatLabel(messages.closeTab, formatMessage),\n icon: ContextMenuIcons.close,\n action: () => handleRequestClose(id)\n });\n }\n\n if (items.length === 0) return;\n\n const custom = getPanelContextMenuItems(id);\n const finalItems = custom.length === 0 ? items\n : hosted ? [...custom, { separator: true as const }, ...items]\n : [...items, { separator: true as const }, ...custom];\n\n showContextMenu({\n event: e,\n items: finalItems,\n initialFocus: initialFocusFor(e),\n });\n };\n\n const handleMinimizedRightClick = (id: string, e: React.MouseEvent) => {\n e.preventDefault();\n setHoveredMinimized(null);\n // Maximizing needs a floating window. A panel minimized from a group is floated on the way\n // back, which a `canDrag: false` panel refuses — so for it the item would do nothing.\n const panel = state.panels[id];\n // A panel that was floating only goes back to floating; one from a group is floated, which the\n // rules decide (7.9.0).\n const canMaximize = panel?.previousState === 'floating'\n || (optionsFor(registry, panel)?.canDrag !== false && isDropAllowed(id, { kind: 'float', anchor: null }));\n showContextMenu({\n event: e,\n initialFocus: initialFocusFor(e),\n items: [\n {\n label: formatLabel(messages.restorePanel, formatMessage),\n icon: ContextMenuIcons.restore,\n action: () => restorePanel(id)\n },\n ...(canMaximize ? [{\n label: formatLabel(messages.maximizePanel, formatMessage),\n icon: ContextMenuIcons.maximize,\n action: () => maximizePanel(id)\n }] : []),\n { separator: true },\n {\n label: formatLabel(messages.closePanel, formatMessage),\n icon: ContextMenuIcons.close,\n action: () => handleRequestClose(id)\n }\n ]\n });\n };\n\n return { handleTabRightClick, handleMinimizedRightClick };\n}\n","/**\n * @file useWorkspaceSize.ts\n * @description The workspace's measured size, kept current by a ResizeObserver, with development warnings when the workspace has no height or is taller than the window.\n */\nimport React, { useState, useEffect } from 'react';\n\nexport function useWorkspaceSize(workspaceRef: React.RefObject<HTMLDivElement | null>): { width: number; height: number } {\n const [workspaceSize, setWorkspaceSize] = useState({ width: 1024, height: 768 });\n\n // Dynamically observe the workspace container bounds (accounts for sidebar expanding/collapsing and taskbar showing/hiding)\n useEffect(() => {\n const el = workspaceRef.current;\n if (!el) return;\n\n let heightWarnShown = false;\n let tallWarnShown = false;\n\n const observer = new ResizeObserver((entries) => {\n if (!entries || entries.length === 0) return;\n const rect = entries[0].contentRect;\n\n if (process.env.NODE_ENV === 'development' && rect.height < 10 && !heightWarnShown) {\n heightWarnShown = true;\n\n // Walk up the ancestor chain to find the highest zero-height element\n let culprit: Element = el;\n let cursor = el.parentElement;\n while (cursor && cursor !== document.documentElement) {\n if (cursor.getBoundingClientRect().height < 10) {\n culprit = cursor;\n } else {\n break;\n }\n cursor = cursor.parentElement;\n }\n\n const tag = culprit.tagName.toLowerCase();\n const id = culprit.id ? ` id=\"${culprit.id}\"` : '';\n const cls = culprit.className ? ` class=\"${culprit.className}\"` : '';\n const who = culprit === el\n ? 'the RddDesktop container itself'\n : `a wrapper element: <${tag}${id}${cls}>`;\n\n console.warn(\n `[react-dockable-desktop] Workspace height is 0px — the workspace will be invisible.\\n\\n` +\n `Zero height found at: ${who}\\n\\n` +\n `Root cause: in CSS, \"height: 100%\" only works when the parent has an explicit height.\\n` +\n `If any ancestor has height: auto (the default for <div>), the chain breaks and\\n` +\n `everything inside collapses to 0px.\\n\\n` +\n `Fix options:\\n` +\n ` 1. Use height: 100vh directly on the workspace wrapper:\\n` +\n ` <div style={{ height: '100vh', overflow: 'hidden' }}>\\n` +\n ` <RddDesktop />\\n` +\n ` </div>\\n\\n` +\n ` 2. Use CSS Grid/Flex and let the workspace fill remaining space:\\n` +\n ` .layout { display: flex; flex-direction: column; height: 100vh; }\\n` +\n ` .workspace { flex: 1; min-height: 0; }\\n\\n` +\n ` 3. For a workspace that fills the window, put className=\"rdd-fill-viewport\" on its wrapper.`\n );\n }\n\n // Without a height of its own, a workspace in a full-window app grows with its content and the\n // *page* scrolls instead of the panels. Until 7.0 the stylesheet hid that by fixing\n // html, body and #root to the viewport; it no longer styles the host page.\n if (process.env.NODE_ENV === 'development' && !tallWarnShown\n && rect.height > window.innerHeight + 1\n && document.documentElement.scrollHeight > window.innerHeight + 1) {\n tallWarnShown = true;\n console.warn(\n `[react-dockable-desktop] The workspace is taller than the window (${Math.round(rect.height)}px > ` +\n `${window.innerHeight}px), so the page scrolls instead of the panels.\\n\\n` +\n `For a workspace that fills the window, give its wrapper the rdd-fill-viewport class:\\n` +\n ` <div className=\"rdd-fill-viewport\"> … <RddDesktop /> … </div>\\n\\n` +\n `(Before 7.0 the stylesheet fixed html, body and #root to 100% height; it no longer styles the host page.)`\n );\n }\n\n setWorkspaceSize({\n width: Math.max(100, rect.width),\n height: Math.max(100, rect.height)\n });\n });\n\n observer.observe(el);\n return () => {\n observer.disconnect();\n };\n }, [workspaceRef]);\n\n return workspaceSize;\n}\n","/**\n * @file floatingWindowDrag.ts\n * @description Moving a floating window by its title bar (mouse, or touch long-press), dropping it on a dock target or corner, and resizing it from any of its eight handles.\n */\nimport React from 'react';\nimport type { SplitDirection, WorkspaceState, InternalWindowActions } from '../../types';\nimport { startPointerDrag, computeResizedRect } from '../dragResize';\nimport type { ResizeDir } from '../dragResize';\nimport { LONG_PRESS_MS, CANCEL_MOVE_PX } from './helpers';\nimport type { DragTargets } from './useDragTargets';\n\nexport interface FloatingWindowDragDeps {\n state: WorkspaceState;\n workspaceSize: { width: number; height: number };\n targets: DragTargets;\n actions: Pick<InternalWindowActions, 'focusPanel' | 'updateFloatingPosition' | 'dockPanelToWorkspaceEdge' | 'movePanelOrder' | 'dockPanelToGroup' | 'setDraggedPanelId' | 'isDropAllowed'>;\n}\n\nexport function createFloatingWindowDrag(deps: FloatingWindowDragDeps): { startDrag: (id: string, e: React.PointerEvent) => void; startResize: (id: string, dir: ResizeDir, e: React.PointerEvent) => void } {\n const { state, workspaceSize } = deps;\n const { activeDropZoneRef, hoveredTabRef, activeEdgeDropRef, activeCornerAnchorRef, setActiveCornerAnchor, clearDragState, flipRtl, updateHoverFromPoint } = deps.targets;\n const { focusPanel, updateFloatingPosition, dockPanelToWorkspaceEdge, movePanelOrder, dockPanelToGroup, setDraggedPanelId, isDropAllowed } = deps.actions;\n\n // Floating Window dragging handler\n const startDrag = (id: string, e: React.PointerEvent) => {\n e.preventDefault();\n const floatingWin = state.floating.find(w => w.id === id);\n if (!floatingWin || floatingWin.maximized) return;\n focusPanel(id);\n\n const el = e.currentTarget as HTMLDivElement;\n const windowEl = el.closest('.rdd-floating-window') as HTMLDivElement | null;\n const startX = e.clientX;\n const startY = e.clientY;\n const startPosX = windowEl ? windowEl.offsetLeft : 0;\n const startPosY = windowEl ? windowEl.offsetTop : 0;\n\n const executeFWDrop = () => {\n const dropZone = activeDropZoneRef.current;\n const targetTab = hoveredTabRef.current;\n const edgeDrop = activeEdgeDropRef.current;\n const cornerAnchor = activeCornerAnchorRef.current;\n // Asked again at release, as in the tab drag (7.9.0); a forbidden target leaves it floating.\n if (cornerAnchor) {\n if (isDropAllowed(id, { kind: 'float', anchor: cornerAnchor })) updateFloatingPosition(id, { anchor: cornerAnchor }); // already the anchor — see the tab drop above\n } else if (edgeDrop) {\n const side = flipRtl(edgeDrop) as SplitDirection;\n if (isDropAllowed(id, { kind: 'edge', side })) dockPanelToWorkspaceEdge(id, side);\n } else if (targetTab) {\n let targetIndex = targetTab.index;\n if (targetTab.side === 'right') targetIndex += 1;\n if (isDropAllowed(id, { kind: 'group', leafId: targetTab.leafId, position: 'center' })) movePanelOrder(id, targetTab.leafId, targetIndex);\n } else if (dropZone) {\n const position = flipRtl(dropZone.position);\n if (isDropAllowed(id, { kind: 'group', leafId: dropZone.leafId, position })) dockPanelToGroup(id, dropZone.leafId, position);\n }\n setActiveCornerAnchor(null);\n clearDragState();\n };\n\n if (e.pointerType === 'touch') {\n const pointerId = e.pointerId;\n let cancelled = false;\n\n const cancel = () => {\n cancelled = true;\n clearTimeout(timer);\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n };\n\n const onPreMove = (me: PointerEvent) => {\n if (Math.hypot(me.clientX - startX, me.clientY - startY) > CANCEL_MOVE_PX) cancel();\n };\n\n const timer = setTimeout(() => {\n if (cancelled) return;\n el.removeEventListener('pointermove', onPreMove);\n el.removeEventListener('pointerup', cancel);\n el.removeEventListener('pointercancel', cancel);\n\n try { el.setPointerCapture(pointerId); } catch { return; }\n el.classList.add('rdd-long-press-active');\n document.body.classList.add('rdd-dragging-active');\n setDraggedPanelId(id);\n\n const onMove = (me: PointerEvent) => {\n const dx = me.clientX - startX;\n const dy = me.clientY - startY;\n updateFloatingPosition(id, { x: startPosX + dx, y: startPosY + dy, anchor: null });\n updateHoverFromPoint(me.clientX, me.clientY);\n };\n\n const onEnd = () => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n executeFWDrop();\n };\n\n const onCancel = () => {\n el.classList.remove('rdd-long-press-active');\n document.body.classList.remove('rdd-dragging-active');\n el.removeEventListener('pointermove', onMove);\n el.removeEventListener('pointerup', onEnd);\n el.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n clearDragState();\n };\n\n el.addEventListener('pointermove', onMove);\n el.addEventListener('pointerup', onEnd);\n el.addEventListener('pointercancel', onCancel);\n // The window losing focus ends the drag, as a pointercancel would (7.4.1).\n window.addEventListener('blur', onCancel);\n }, LONG_PRESS_MS);\n\n el.addEventListener('pointermove', onPreMove);\n el.addEventListener('pointerup', cancel);\n el.addEventListener('pointercancel', cancel);\n } else {\n // Mouse / pen: window-level listeners WITHOUT setPointerCapture so that\n // onPointerEnter/Leave on drop zones and edge triggers still fire normally.\n let dragStarted = false;\n\n const onMove = (me: PointerEvent) => {\n const dx = me.clientX - startX;\n const dy = me.clientY - startY;\n if (!dragStarted && (Math.abs(dx) > 5 || Math.abs(dy) > 5)) {\n dragStarted = true;\n setDraggedPanelId(id);\n }\n if (dragStarted) {\n updateFloatingPosition(id, { x: startPosX + dx, y: startPosY + dy, anchor: null });\n }\n };\n\n const onEnd = () => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) executeFWDrop();\n };\n\n const onCancel = () => {\n document.body.classList.remove('rdd-dragging-active');\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onEnd);\n window.removeEventListener('pointercancel', onCancel);\n window.removeEventListener('blur', onCancel);\n if (dragStarted) clearDragState();\n };\n\n document.body.classList.add('rdd-dragging-active');\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onEnd);\n window.addEventListener('pointercancel', onCancel);\n // The window losing focus ends the drag, as a pointercancel would (7.4.1): the next click\n // can't dock the window into the zone it was over.\n window.addEventListener('blur', onCancel);\n }\n };\n\n // Floating Window resizing handler — supports 8 directions\n const startResize = (id: string, dir: ResizeDir, e: React.PointerEvent) => {\n e.preventDefault();\n e.stopPropagation();\n const floatingWin = state.floating.find(w => w.id === id);\n if (!floatingWin || floatingWin.maximized) return;\n focusPanel(id);\n\n const el = e.currentTarget as HTMLDivElement;\n const windowEl = el.closest('.rdd-floating-window') as HTMLDivElement | null;\n const startRect = {\n x: windowEl ? windowEl.offsetLeft : 0,\n y: windowEl ? windowEl.offsetTop : 0,\n w: windowEl ? windowEl.offsetWidth : 400,\n h: windowEl ? windowEl.offsetHeight : 300,\n };\n\n const viewW = workspaceSize.width;\n const viewH = workspaceSize.height;\n const parsedX = typeof floatingWin.x === 'string' ? parseFloat(floatingWin.x) : floatingWin.x;\n const parsedY = typeof floatingWin.y === 'string' ? parseFloat(floatingWin.y) : floatingWin.y;\n const parsedW = typeof floatingWin.width === 'string' ? parseFloat(floatingWin.width) : floatingWin.width;\n const parsedH = typeof floatingWin.height === 'string' ? parseFloat(floatingWin.height) : floatingWin.height;\n const isRightSnapped = dir === 'se' && Math.abs(parsedX + parsedW - viewW) < 4;\n const isBottomSnapped = dir === 'se' && Math.abs(parsedY + parsedH - viewH) < 4;\n\n startPointerDrag({\n element: el,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => startRect,\n activeClasses: [{ el: document.body, classes: ['rdd-resizing-active'] }],\n // No maxW/maxH/minX/minY: this window is intentionally allowed to grow\n // unbounded and be dragged fully off-screen, same as before this refactor.\n onMove: (dx, dy, start) => {\n const resized = computeResizedRect(dir, dx, dy, start, { minW: 200, minH: 150 });\n let { x: newX, y: newY, w: newW, h: newH } = resized;\n\n // Snap adjustments for SE corner when previously snapped to workspace edges\n if (isRightSnapped) {\n newX = viewW - newW;\n if (newX < 0) { newX = 0; newW = viewW; }\n }\n if (isBottomSnapped) {\n newY = viewH - newH;\n if (newY < 0) { newY = 0; newH = viewH; }\n }\n\n updateFloatingPosition(id, { x: newX, y: newY, width: newW, height: newH });\n },\n });\n };\n\n return { startDrag, startResize };\n}\n","import React, { useCallback, useRef, useState, useMemo } from 'react';\nimport { usePanelState, usePanelActions } from './PanelProviderContext';\nimport { FormContainerProvider, type FormContainerContract, type CloseOptions } from './FormContainerContext';\nimport type { OverlayInstance, ModalOptions, PanelTitle } from './PanelProviderContext';\nimport type { DirtyStateOptions } from './dirtyOptions';\nimport { useFormatMessage, formatLabel, useStyleClasses, usePredefinedMessages, useWindowManagerState } from './WindowManagerContext';\nimport ConfirmationForm from '../forms/ConfirmationForm';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n/**\n * Interface representing props for the internal {@link ModalRenderer} component.\n */\ninterface ModalRendererProps {\n /** The panel instance containing component structure, state, and option flags. */\n modal: OverlayInstance;\n /** The 0-based depth index of the modal within the active stack. */\n index: number;\n /** True if this modal is currently at the top of the stack. */\n}\n\n/**\n * ModalRenderer component renders a single modal window wrapped inside\n * the FormContainerProvider context, enabling subcomponents to request closes and set dirty states.\n */\nconst ModalRenderer: React.FC<ModalRendererProps> = ({ modal, index }) => {\n const { close, openModal, updateInstance, setDirty, onInstanceClose } = usePanelActions();\n const formatMessage = useFormatMessage();\n const predefinedMessages = usePredefinedMessages();\n const dir = useWindowManagerState(s => s.dir);\n const { modalClass, modalBodyClass } = useStyleClasses();\n const closeHandlerRef = useRef<(() => boolean | Promise<boolean>) | null>(null);\n\n const { id, Component, props, options, dirty, dirtyOptions } = modal;\n const modalOptions = options as ModalOptions;\n\n const [icon, setIconState] = useState<React.ReactNode>(modalOptions.icon || null);\n\n const optionsRef = useLatestRef(modalOptions);\n\n const baseTitle = formatLabel(modalOptions.title, formatMessage);\n\n const handleClose = useCallback(async (options?: CloseOptions) => {\n if (options?.force) {\n close(id);\n return;\n }\n\n if (closeHandlerRef.current) {\n const canClose = await closeHandlerRef.current();\n if (!canClose) return;\n close(id);\n return;\n }\n\n if (dirty) {\n openModal(\n ConfirmationForm,\n {\n title: dirtyOptions?.title || predefinedMessages.unsavedChangesTitle,\n message: dirtyOptions?.message || {\n id: predefinedMessages.unsavedChangesMessage.id,\n defaultMessage: predefinedMessages.unsavedChangesMessage.defaultMessage,\n values: { title: baseTitle }\n },\n alert: dirtyOptions?.alert,\n alertType: dirtyOptions?.alertType || 'danger',\n useYesNoTitles: true,\n onOK: () => close(id),\n },\n { size: 'small' }\n );\n return;\n }\n\n close(id);\n }, [close, openModal, id, dirty, dirtyOptions, baseTitle, predefinedMessages]);\n\n const handleSetDirty = useCallback((dirty: boolean, options?: DirtyStateOptions) => setDirty(id, dirty, options), [setDirty, id]);\n const handleSetTitle = useCallback((title: PanelTitle) => updateInstance(id, { options: { ...optionsRef.current, title } }), [updateInstance, id, optionsRef]);\n const handleSetIcon = useCallback((newIcon: React.ReactNode) => setIconState(newIcon), []);\n const handleOnCloseRequested = useCallback((handler: () => boolean | Promise<boolean>) => {\n closeHandlerRef.current = handler;\n return () => { closeHandlerRef.current = null; };\n }, []);\n\n const handleOnClose = useCallback((handler: () => void) => onInstanceClose(id, handler), [onInstanceClose, id]);\n\n const contract: FormContainerContract = useMemo(() => ({\n requestClose: handleClose,\n setDirty: handleSetDirty,\n setTitle: handleSetTitle,\n setIcon: handleSetIcon,\n onCloseRequested: handleOnCloseRequested,\n containerType: 'modal',\n instanceId: id,\n onClose: handleOnClose,\n }), [handleClose, handleOnClose, handleSetDirty, handleSetTitle, handleSetIcon, handleOnCloseRequested, id]);\n\n const displayTitle = dirty ? `${baseTitle} *` : baseTitle;\n\n const sizeClass = modalOptions.size ? `rdd-modal-size-${modalOptions.size}` : 'rdd-modal-size-auto';\n const showCloseButton = modalOptions.closable !== false;\n\n const bodyPadding = modalOptions.bodyPadding;\n const bodyPaddingStyle = bodyPadding != null\n ? (typeof bodyPadding === 'number' ? `${bodyPadding}px` : bodyPadding)\n : undefined;\n\n // Every mounted modal takes its place on the shared Escape stack, where the most recently\n // opened one is on top. One that can't be closed still consumes the key, so Escape never\n // reaches a drawer behind it.\n useEscapeLayer(true, 'modal', () => {\n if (showCloseButton) handleClose();\n });\n\n // Reads the same --rdd-z-base a WindowManagerProvider's zIndexBase config mirrors\n // onto documentElement (falls back to 1000 so this also works standalone, with\n // no WindowManager mounted, matching the :root default in index.css).\n const modalZIndex = `calc(var(--rdd-z-base, 1000) + 9000 + ${index * 10})`;\n\n return (\n <div className=\"rdd-modal-overlay\" style={{ zIndex: modalZIndex }} dir={dir}>\n <div className=\"rdd-modal-curtain\" onClick={showCloseButton ? () => handleClose() : undefined} />\n <div className={`rdd-modal-window ${sizeClass} ${modalClass ?? ''}`}>\n <div className=\"rdd-modal-header\">\n {icon && <div className=\"rdd-modal-icon\">{icon}</div>}\n <h4 className=\"rdd-modal-title\">{displayTitle}</h4>\n {showCloseButton && (\n <button\n className=\"rdd-modal-close-button\"\n onClick={() => handleClose()}\n title={formatMessage(predefinedMessages.closeTooltip)}\n type=\"button\"\n >\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\" />\n </svg>\n </button>\n )}\n </div>\n <div\n className={`rdd-modal-body ${modalBodyClass ?? ''}`}\n style={bodyPaddingStyle != null ? { padding: bodyPaddingStyle } : undefined}\n >\n <FormContainerProvider value={contract}>\n <Component {...props} panelId={id} />\n </FormContainerProvider>\n </div>\n </div>\n </div>\n );\n};\n\n/**\n * Renders the modals opened through `useModals()`, stacked, topmost last. Mount one, inside\n * `<DockableDesktopProvider>`.\n */\nexport const ModalStackRenderer: React.FC = () => {\n const { modals } = usePanelState();\n\n if (modals.length === 0) return null;\n\n return (\n <>\n {modals.map((modal, index) => (\n <ModalRenderer\n key={modal.id}\n modal={modal}\n index={index}\n />\n ))}\n </>\n );\n};\n\nexport default ModalStackRenderer;\n","/**\n * @file Sidebar.tsx\n * @description Sidebar activity bar (strip) and resizable content drawer.\n * The strip and drawer are independently controllable via `visible` and\n * `stripVisible`. Drawer width is pixel-based and user-draggable using the\n * same pointer-capture interaction as the panel grid resizer.\n */\n\nimport React, {\n useState,\n useEffect,\n useRef,\n useCallback,\n useImperativeHandle,\n useContext,\n useMemo,\n createContext,\n forwardRef,\n memo,\n} from 'react';\nimport { startPointerDrag } from './dragResize';\nimport { isComputedRtl } from '../utils/rtl';\nimport { formatLabel, useFormatMessage, usePredefinedMessages, useOptionalWindowManagerState } from './WindowManagerContext';\n\n// ==========================================\n// Types\n// ==========================================\n\n/**\n * Per-tab configuration supplied by the consuming application.\n */\nexport interface SidebarTab {\n id: string;\n label: string;\n /** Required unless `hidden` is true — a hidden tab never renders a rail button, so it has no icon to show. */\n icon?: React.ReactNode;\n /**\n * Omit this tab's rail button entirely — no icon, no click target — while it\n * remains fully openable via `openTab()` / `useSidebar().openTab()` / a controlled\n * `activeTabId`. Use for menu-driven panels with no persistent icon (e.g. a\n * Google-Maps-style hamburger that opens content not otherwise pinned to the rail).\n * Default: false\n */\n hidden?: boolean;\n /**\n * Mount immediately when the Sidebar first renders, not on first user click.\n * Implies `preserveState: true`.\n * Default: false\n */\n eagerMount?: boolean;\n /**\n * Keep the component alive behind `display: none` when closed instead of\n * unmounting it. Use for panels with expensive local state.\n * Default: false\n */\n preserveState?: boolean;\n /**\n * Called to obtain the drawer content for this tab.\n * @param tabId - the id of this tab\n * @param onClose - call to collapse the sidebar drawer\n * @param onOpen - call to expand the drawer and select this tab\n */\n renderContent: (tabId: string, onClose: () => void, onOpen: () => void) => React.ReactNode;\n}\n\n/**\n * Simple case for `RddSidebarProps.headerAction`/`footerAction`: the library renders a\n * default-styled icon button (visually consistent with the regular tab buttons) and forwards\n * the click.\n */\nexport interface SidebarActionButton {\n /** Only needed when used inside a `SidebarRailEntry[]` array, for the React key. */\n id?: string;\n icon: React.ReactNode;\n /** Tooltip and aria-label — same convention as `SidebarTab.label`. */\n label: string;\n onClick: () => void;\n disabled?: boolean;\n}\n\n/**\n * Full-control case for `RddSidebarProps.headerAction`/`footerAction`: the consumer supplies their\n * own markup (a Material UI `IconButton`, a Bootstrap `Button`, a Tailwind-styled `<button>`, or\n * anything else) wholesale. The library renders exactly what this returns, unwrapped, so the\n * consumer's own hover/active/focus/ripple behavior and click handling are untouched.\n */\nexport interface SidebarCustomEntry {\n /** Only needed when used inside a `SidebarRailEntry[]` array, for the React key. */\n id?: string;\n render: () => React.ReactNode;\n}\n\n/**\n * A single, non-toggling action button shown above the tab strip (e.g. a hamburger menu).\n * Unlike `SidebarTab`, it never affects `activeTabId` or the drawer — the library only renders\n * it and forwards the click; what happens next (opening a side panel, a modal, anything else)\n * is entirely up to the consumer.\n */\nexport type SidebarHeaderAction = SidebarActionButton | SidebarCustomEntry;\n\n/**\n * A single entry inside `RddSidebarProps.headerAction`/`footerAction` when used as an array: either\n * a non-toggling action button/custom render (see `SidebarHeaderAction`), or a real `SidebarTab`\n * that behaves exactly like a main-list tab — it mounts, activates, and closes through the same\n * lifecycle, so e.g. a \"Settings\" entry pinned to the footer can expand like any other tab.\n */\nexport type SidebarRailEntry = SidebarTab | SidebarActionButton | SidebarCustomEntry;\n\nfunction isRailTab(entry: SidebarRailEntry): entry is SidebarTab {\n return 'renderContent' in entry;\n}\n\nfunction isRailCustom(entry: SidebarRailEntry): entry is SidebarCustomEntry {\n return 'render' in entry;\n}\n\nfunction toRailArray(value: SidebarRailEntry | SidebarRailEntry[] | undefined): SidebarRailEntry[] {\n if (value == null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nexport interface RddSidebarProps {\n /** Which side the activity bar and drawer appear on. Default: 'right' */\n position?: 'left' | 'right';\n tabs: SidebarTab[];\n /**\n * One or more non-toggling action buttons and/or real tabs shown above the tabs, in their\n * own `.rdd-sidebar-header-area` — independent of the tabs' own inter-item gap. Pass a single\n * `{ icon, label, onClick }`/`{ render }` object (the common case), or an array mixing action\n * buttons, custom renders, and `SidebarTab` entries — a tab entry here behaves exactly like a\n * main-list tab (mounts, activates, closes through the same lifecycle). Override\n * `--rdd-sidebar-header-area-padding-top`/`--rdd-sidebar-header-area-padding-bottom`\n * (both default `8px`) to control its spacing/effective height.\n */\n headerAction?: SidebarRailEntry | SidebarRailEntry[];\n /**\n * Mirror of `headerAction`, pinned to the bottom of the tab strip via its own\n * `.rdd-sidebar-footer-area` — e.g. a \"Settings\" tab that should always sit at the bottom\n * regardless of tab count. Override `--rdd-sidebar-footer-area-padding-top`/\n * `--rdd-sidebar-footer-area-padding-bottom` (both default `8px`) to control its spacing.\n */\n footerAction?: SidebarRailEntry | SidebarRailEntry[];\n /** Initial drawer width in pixels. Default: 280 */\n defaultWidth?: number;\n /** Minimum drawer width in pixels during drag-resize. Default: 150 */\n minWidth?: number;\n /** Maximum drawer width in pixels during drag-resize. Default: 600 */\n maxWidth?: number;\n /** Called during drag resize and on setWidth() with the new pixel width. */\n onWidthChange?: (px: number) => void;\n /** Controlled active tab id. Omit to use internal state. */\n activeTabId?: string | null;\n /** Called when the active tab changes. */\n onActiveTabChange?: (tabId: string | null) => void;\n /** Collapse the entire sidebar (strip + drawer). Default: true */\n visible?: boolean;\n /** Called when show/hide/toggle is invoked on the imperative handle. */\n onVisibilityChange?: (visible: boolean) => void;\n /** Collapse only the activity bar strip, leaving the drawer unaffected. Default: true */\n stripVisible?: boolean;\n /** Called when showStrip/hideStrip is invoked on the imperative handle. */\n onStripVisibilityChange?: (visible: boolean) => void;\n /**\n * Show an \"X\" close button in the expanded drawer's header, as an additional way to collapse\n * the sidebar (equivalent to clicking the active tab's own icon again). Opt-in. Default: false.\n * Has no effect once the default header is suppressed — via `hideDefaultHeader`, or simply by\n * passing `renderHeader` (either one is sufficient) — since the entire default header, this\n * button included, is skipped for every tab in that case.\n */\n showCloseButton?: boolean;\n /**\n * Suppress the library's own drawer header (title + `showCloseButton`'s close\n * button) for every tab, so `renderHeader` (or each tab's own `renderContent`)\n * can supply a header, border, and styling instead. Applies uniformly across\n * all tabs — there's no per-tab override. Passing `renderHeader` by itself has\n * the same suppressing effect even if this is left unset — the two conditions\n * are combined with OR, precisely so that supplying `renderHeader` alone is\n * never a silent no-op. The close mechanism is unaffected either way: the\n * `onClose` parameter passed to `renderContent`/`renderHeader`, or\n * `useSidebarTab().onClose` from anywhere in a tab's content tree.\n * Default: false\n */\n hideDefaultHeader?: boolean;\n /**\n * Custom header renderer used in place of the library's own drawer header.\n * Passing `renderHeader` is by itself sufficient to suppress the default\n * header, whether or not `hideDefaultHeader` is also set — the two props are\n * combined with OR. Called once for whichever tab is currently active, so\n * the same header markup (e.g. a hamburger icon, a search field, a close\n * button) is shared uniformly across every tab instead of being repeated\n * inside each tab's own `renderContent`. Omit `renderHeader` and set\n * `hideDefaultHeader: true` to render no header at all and let each tab's\n * `renderContent` supply its own instead.\n * @param tab - the currently active tab\n * @param onClose - call to collapse the sidebar drawer\n * @param onOpen - call to (re-)select this tab\n */\n renderHeader?: (tab: SidebarTab, onClose: () => void, onOpen: () => void) => React.ReactNode;\n /**\n * @internal Marks this instance as a secondary sidebar for context-broadcasting\n * purposes. Set automatically by `<RddSecondarySidebar>` — do not pass this directly.\n * Default: false\n */\n isSecondary?: boolean;\n /** Main workspace content rendered alongside the sidebar. */\n children?: React.ReactNode;\n}\n\n/**\n * Imperative handle exposed by `<RddSidebar ref={...}>`.\n */\nexport interface SidebarHandle {\n openTab: (tabId: string) => void;\n closeDrawer: () => void;\n getActiveTab: () => string | null;\n show: () => void;\n hide: () => void;\n toggle: () => void;\n showStrip: () => void;\n hideStrip: () => void;\n setWidth: (px: number) => void;\n getWidth: () => number;\n}\n\n/**\n * Value provided by `useSidebar()`. Available to any component inside the\n * `<RddSidebar>` React tree, including panels rendered via `{children}`.\n */\nexport interface SidebarContextValue {\n openTab: (tabId: string) => void;\n closeDrawer: () => void;\n getActiveTab: () => string | null;\n /** Which side this Sidebar instance is rendering on. */\n position: 'left' | 'right';\n /** True if this instance is a `<RddSecondarySidebar>`, false for a primary `<RddSidebar>`. */\n isSecondary: boolean;\n}\n\n/**\n * Value provided by `useSidebarTab()`. Available only to components rendered\n * inside a sidebar tab's `renderContent` tree.\n */\nexport interface SidebarTabContextValue {\n tabId: string;\n onOpen: () => void;\n onClose: () => void;\n openTab: (tabId: string) => void;\n}\n\n// ==========================================\n// Contexts\n// ==========================================\n\nconst SidebarContext = createContext<SidebarContextValue | null>(null);\nconst SidebarTabContext = createContext<SidebarTabContextValue | null>(null);\n\n// ==========================================\n// SidebarTabProvider (internal)\n// ==========================================\n\ninterface SidebarTabProviderProps {\n tabId: string;\n onClose: () => void;\n onOpen: () => void;\n setActiveTabId: (id: string | null) => void;\n children: React.ReactNode;\n}\n\nfunction SidebarTabProvider({ tabId, onClose, onOpen, setActiveTabId, children }: SidebarTabProviderProps) {\n const value = useMemo<SidebarTabContextValue>(() => ({\n tabId,\n onClose,\n onOpen,\n openTab: (otherId: string) => setActiveTabId(otherId),\n }), [tabId, onClose, onOpen, setActiveTabId]);\n\n return <SidebarTabContext.Provider value={value}>{children}</SidebarTabContext.Provider>;\n}\n\n// ==========================================\n// renderRailEntry (internal helper)\n// Shared by the header/footer areas only — dispatches a SidebarRailEntry to a tab button,\n// a default-styled action button, or a fully custom render. The main tabs-list keeps its own\n// inline JSX below since it only ever renders SidebarTab entries.\n// ==========================================\n\nfunction renderRailEntry(\n entry: SidebarRailEntry,\n index: number,\n activeTabId: string | null | undefined,\n onTabClick: (tabId: string) => void\n): React.ReactNode {\n if (isRailCustom(entry)) {\n return <React.Fragment key={entry.id ?? index}>{entry.render()}</React.Fragment>;\n }\n if (isRailTab(entry)) {\n if (entry.hidden) return null;\n const isActive = activeTabId === entry.id;\n return (\n <button\n key={entry.id}\n type=\"button\"\n onClick={() => onTabClick(entry.id)}\n data-rdd-sidebar-tab={entry.id}\n className={`rdd-sidebar-tab-btn${isActive ? ' rdd-active' : ''}`}\n title={entry.label}\n aria-pressed={isActive}\n >\n {entry.icon}\n </button>\n );\n }\n return (\n <button\n key={entry.id ?? index}\n type=\"button\"\n onClick={entry.onClick}\n disabled={entry.disabled}\n className=\"rdd-sidebar-tab-btn rdd-sidebar-header-action-btn\"\n title={entry.label}\n aria-label={entry.label}\n >\n {entry.icon}\n </button>\n );\n}\n\n// ==========================================\n// SidebarTabStrip (internal sub-component)\n// Re-renders only when tabs, selection, or strip visibility changes —\n// not on drawer width changes during drag.\n// ==========================================\n\ninterface SidebarTabStripProps {\n tabs: SidebarTab[];\n headerEntries: SidebarRailEntry[];\n footerEntries: SidebarRailEntry[];\n activeTabId: string | null | undefined;\n isVisible: boolean;\n position: 'left' | 'right';\n onTabClick: (tabId: string) => void;\n}\n\nconst SidebarTabStrip = memo(function SidebarTabStrip({\n tabs,\n headerEntries,\n footerEntries,\n activeTabId,\n isVisible,\n position,\n onTabClick,\n}: SidebarTabStripProps) {\n return (\n // Outer div drives the collapse transition via overflow:hidden.\n // The inner rdd-sidebar-tabs-strip must NOT have overflow:hidden so the active\n // tab's negative margin can extend into the drawer border without clipping.\n <div className={`rdd-sidebar-strip-wrap${isVisible ? '' : ' rdd-sidebar-strip-wrap--collapsed'}`}>\n <div\n className={`rdd-sidebar-tabs-strip rdd-${position}${headerEntries.length ? ' rdd-sidebar-tabs-strip--has-header-action' : ''}${footerEntries.length ? ' rdd-sidebar-tabs-strip--has-footer-action' : ''}`}\n >\n {headerEntries.length > 0 && (\n <div className=\"rdd-sidebar-header-area\">\n {headerEntries.map((entry, i) => renderRailEntry(entry, i, activeTabId, onTabClick))}\n </div>\n )}\n <div className=\"rdd-sidebar-tabs-list\">\n {tabs.map(tab => {\n if (tab.hidden) return null;\n const isActive = activeTabId === tab.id;\n return (\n <button\n key={tab.id}\n type=\"button\"\n onClick={() => onTabClick(tab.id)}\n data-rdd-sidebar-tab={tab.id}\n className={`rdd-sidebar-tab-btn${isActive ? ' rdd-active' : ''}`}\n title={tab.label}\n aria-pressed={isActive}\n >\n {tab.icon}\n </button>\n );\n })}\n </div>\n {footerEntries.length > 0 && (\n <div className=\"rdd-sidebar-footer-area\">\n {footerEntries.map((entry, i) => renderRailEntry(entry, i, activeTabId, onTabClick))}\n </div>\n )}\n </div>\n </div>\n );\n});\n\n// ==========================================\n// SidebarResizeHandle (internal sub-component)\n// Encapsulates all pointer-capture drag logic.\n// Identical interaction pattern to the panel grid resizer in workspace/WorkspaceGrid.tsx.\n// ==========================================\n\ninterface SidebarResizeHandleProps {\n position: 'left' | 'right';\n currentWidth: number;\n minWidth: number;\n maxWidth: number;\n onWidthChange: (newWidth: number) => void;\n onResizeStart: () => void;\n onResizeEnd: () => void;\n}\n\nfunction SidebarResizeHandle({\n position,\n currentWidth,\n minWidth,\n maxWidth,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n}: SidebarResizeHandleProps) {\n const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n e.preventDefault();\n const el = e.currentTarget;\n const activeClasses: Array<{ el: HTMLElement; classes: string[] }> = [\n { el, classes: ['rdd-active'] },\n { el: document.body, classes: ['rdd-resizing-active', 'rdd-resizing-col-active'] },\n ];\n // Suppress the drawer's CSS transition so drag feels instant — driven by this\n // instance's own isResizing state (see the drawer's style below), not a DOM\n // class + descendant selector, which would leak across a nested secondary\n // Sidebar's subtree since it's a literal DOM descendant of this one.\n onResizeStart();\n\n const onPhysicalRight = (position === 'right') !== isComputedRtl(el);\n\n startPointerDrag({\n element: el,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => currentWidth,\n activeClasses,\n onMove: (dx, _dy, startWidth) => {\n // The sign follows the drawer's physical edge, not the prop: the sidebar is a plain flex\n // row, so under RTL position=\"left\" renders on the right. A drawer on the physical right\n // widens when dragged left (negative dx).\n const newW = onPhysicalRight ? startWidth - dx : startWidth + dx;\n onWidthChange(Math.max(minWidth, Math.min(maxWidth, newW)));\n },\n onEnd: () => onResizeEnd(),\n });\n };\n\n return (\n <div\n className=\"rdd-resizer-bar rdd-resizer-bar--vertical\"\n onPointerDown={handlePointerDown}\n />\n );\n}\n\n// ==========================================\n// Sidebar (main component)\n// ==========================================\n\nexport const Sidebar: React.ForwardRefExoticComponent<RddSidebarProps & React.RefAttributes<SidebarHandle>> =\n forwardRef<SidebarHandle, RddSidebarProps>(function Sidebar(\n {\n position = 'right',\n tabs,\n headerAction,\n footerAction,\n defaultWidth,\n minWidth = 150,\n maxWidth = 600,\n onWidthChange,\n activeTabId: controlledActiveTabId,\n onActiveTabChange,\n visible,\n onVisibilityChange,\n stripVisible,\n onStripVisibilityChange,\n showCloseButton = false,\n hideDefaultHeader = false,\n renderHeader,\n isSecondary = false,\n children,\n },\n ref\n ) {\n const workspaceDir = useOptionalWindowManagerState(s => s.dir, undefined);\n const isControlled = controlledActiveTabId !== undefined;\n const formatMessage = useFormatMessage();\n const closeLabel = formatLabel(usePredefinedMessages().closeTooltip, formatMessage);\n\n const [width, setWidthState] = useState<number>(() => defaultWidth ?? 280);\n\n const setWidth = useCallback((px: number) => {\n setWidthState(px);\n onWidthChange?.(px);\n }, [onWidthChange]);\n\n // Suppresses the drawer's CSS transition during a resize drag — own state,\n // not a DOM class, so it can never leak into a nested secondary Sidebar's\n // drawer (see SidebarResizeHandle's onResizeStart/onResizeEnd below).\n const [isResizing, setIsResizing] = useState(false);\n\n // Internal active tab state (uncontrolled mode)\n const [internalActiveTabId, setInternalActiveTabId] = useState<string | null>(null);\n const activeTabId = isControlled ? controlledActiveTabId : internalActiveTabId;\n\n // Normalized header/footer rail entries, and the SidebarTab-shaped subset of each — a\n // header/footer tab (e.g. \"Settings\") must share the exact same lifecycle as a main tab.\n const normalizedHeaderEntries = useMemo(() => toRailArray(headerAction), [headerAction]);\n const normalizedFooterEntries = useMemo(() => toRailArray(footerAction), [footerAction]);\n const headerTabs = useMemo(() => normalizedHeaderEntries.filter(isRailTab), [normalizedHeaderEntries]);\n const footerTabs = useMemo(() => normalizedFooterEntries.filter(isRailTab), [normalizedFooterEntries]);\n const allTabs = useMemo(() => [...headerTabs, ...tabs, ...footerTabs], [headerTabs, tabs, footerTabs]);\n\n // Tracks which non-eager tabs have been mounted at least once (for lazy-mount / preserveState).\n // eagerMount tabs are folded in via effectiveMountedTabIds below, so no effect needed for them.\n const [mountedTabIds, setMountedTabIds] = useState<Set<string>>(() => new Set<string>());\n\n // Derives the full mounted set during render — no effect needed.\n // Includes: accumulated mountedTabIds + the currently active tab (handles controlled\n // prop changes where setActiveTabId is never called) + all eagerMount tabs.\n const effectiveMountedTabIds = useMemo(() => {\n const result = new Set(mountedTabIds);\n if (activeTabId) result.add(activeTabId);\n for (const tab of allTabs) {\n if (tab.eagerMount) result.add(tab.id);\n }\n return result;\n }, [mountedTabIds, activeTabId, allTabs]);\n\n // Stable refs for imperative handle\n const activeTabIdRef = useRef<string | null>(activeTabId ?? null);\n useEffect(() => { activeTabIdRef.current = activeTabId ?? null; }, [activeTabId]);\n\n const widthRef = useRef<number>(width);\n useEffect(() => { widthRef.current = width; }, [width]);\n\n const setActiveTabId = useCallback(\n (id: string | null) => {\n // Update mounted set in the same render batch as the tab switch — avoids setState-in-effect.\n if (id !== null) {\n setMountedTabIds(prev => {\n if (prev.has(id)) return prev;\n const next = new Set(prev);\n next.add(id);\n return next;\n });\n } else {\n // Drawer closing: evict transient tabs (non-eager, non-preserveState).\n setMountedTabIds(prev => {\n let changed = false;\n const next = new Set(prev);\n for (const tabId of prev) {\n const tab = allTabs.find(t => t.id === tabId);\n if (tab && !tab.eagerMount && !tab.preserveState) {\n next.delete(tabId);\n changed = true;\n }\n }\n return changed ? next : prev;\n });\n }\n if (isControlled) {\n onActiveTabChange?.(id);\n } else {\n setInternalActiveTabId(id);\n onActiveTabChange?.(id);\n }\n },\n [isControlled, onActiveTabChange, allTabs]\n );\n\n // If the active tab stops existing in `tabs`/`headerAction`/`footerAction` (its contributing\n // panel changed/closed, or the tab was otherwise removed), close the drawer rather than\n // leaving it open and empty with no tab button left to click closed — never silently fall\n // back to a different tab the user didn't choose.\n useEffect(() => {\n if (activeTabId != null && !allTabs.some(t => t.id === activeTabId)) {\n // Through setActiveTabId on purpose: it also tells a controlling parent (onActiveTabChange).\n // eslint-disable-next-line react-hooks/set-state-in-effect\n setActiveTabId(null);\n }\n }, [activeTabId, allTabs, setActiveTabId]);\n\n useImperativeHandle(ref, () => ({\n openTab: (tabId: string) => setActiveTabId(tabId),\n closeDrawer: () => setActiveTabId(null),\n getActiveTab: () => activeTabIdRef.current,\n show: () => onVisibilityChange?.(true),\n hide: () => onVisibilityChange?.(false),\n toggle: () => onVisibilityChange?.(visible === false ? true : false),\n showStrip: () => onStripVisibilityChange?.(true),\n hideStrip: () => onStripVisibilityChange?.(false),\n setWidth: (px: number) => setWidth(Math.max(minWidth, Math.min(maxWidth, px))),\n getWidth: () => widthRef.current,\n }), [setActiveTabId, visible, onVisibilityChange, onStripVisibilityChange, setWidth, minWidth, maxWidth]);\n\n const handleTabClick = useCallback((tabId: string) => {\n setActiveTabId(activeTabId === tabId ? null : tabId);\n }, [activeTabId, setActiveTabId]);\n\n const handleClose = useCallback(() => setActiveTabId(null), [setActiveTabId]);\n\n // `renderHeader` alone (no `hideDefaultHeader`) also suppresses the default\n // header — see the render condition below. Derived once here so both that\n // condition and the dev-warning effect stay in sync.\n const hasHeaderOverride = hideDefaultHeader || renderHeader != null;\n\n // Dev-only: showCloseButton renders nothing once the default header is\n // suppressed, since its close button is part of that (now-skipped) header.\n // Warns once per mounted Sidebar — closeButtonWarnedRef lives in component\n // scope (not inside the effect) so it survives re-renders; depending on the\n // derived boolean rather than `renderHeader` itself avoids re-running this\n // on every render, since `renderHeader` is typically passed as a fresh\n // inline arrow function each time.\n const closeButtonWarnedRef = useRef(false);\n useEffect(() => {\n if (process.env.NODE_ENV !== 'development') return;\n if (!showCloseButton || !hasHeaderOverride) return;\n if (closeButtonWarnedRef.current) return;\n closeButtonWarnedRef.current = true;\n console.warn(\n '[react-dockable-desktop] `showCloseButton` has no effect because the default header is ' +\n 'suppressed (`hideDefaultHeader` is set, or `renderHeader` was passed). The \"X\" close button ' +\n 'only renders as part of the library\\'s own default header, which is skipped in this case. ' +\n 'Add your own close control inside `renderHeader` (or `renderContent`), wired to its `onClose` ' +\n 'parameter or `useSidebarTab().onClose`.'\n );\n }, [showCloseButton, hasHeaderOverride]);\n\n // Stable context value for useSidebar() consumers\n const sidebarContextValue = useMemo<SidebarContextValue>(() => ({\n openTab: (tabId: string) => setActiveTabId(tabId),\n closeDrawer: () => setActiveTabId(null),\n getActiveTab: () => activeTabIdRef.current,\n position,\n isSecondary,\n }), [setActiveTabId, position, isSecondary]);\n\n // ---- Derived visibility flags ----\n const isSidebarVisible = visible !== false;\n const isStripVisible = isSidebarVisible && stripVisible !== false;\n const isDrawerOpen = isSidebarVisible && activeTabId != null;\n\n // ---- Drawer element (shared between left and right) ----\n const drawer = (\n <div\n className={`rdd-sidebar-content-drawer rdd-${position}`}\n style={{\n // flex-basis drives the visible width; width: 0px has no effect in flex context\n // when flex-basis is set — so we animate flex-basis, not width.\n flexBasis: isDrawerOpen ? `${width}px` : '0px',\n minWidth: isDrawerOpen ? `${minWidth}px` : '0px',\n maxWidth: isDrawerOpen ? `${maxWidth}px` : '0px',\n // Suppressed during a resize drag via this instance's own isResizing state.\n transition: isResizing\n ? 'none'\n : 'flex-basis 0.2s cubic-bezier(0.4, 0, 0.2, 1), min-width 0.2s cubic-bezier(0.4, 0, 0.2, 1), max-width 0.2s cubic-bezier(0.4, 0, 0.2, 1)',\n }}\n >\n {allTabs.map(tab => {\n const isMounted = effectiveMountedTabIds.has(tab.id);\n if (!isMounted) return null;\n\n const isCurrent = activeTabId === tab.id;\n const onOpen = () => setActiveTabId(tab.id);\n\n return (\n <div key={tab.id} className=\"rdd-sidebar-pane\" style={{ display: isCurrent ? 'flex' : 'none' }}>\n {/* Drawer header — tab label, plus an optional close button (showCloseButton) as\n an extra way to collapse the sidebar; clicking the active tab icon still works too.\n Suppressed for every tab when hideDefaultHeader is set, OR simply when renderHeader\n is passed (either alone is sufficient — see hasHeaderOverride above, which keeps\n this in sync with the dev-warning effect) — onClose/onOpen still flow to either\n one regardless. */}\n {hasHeaderOverride ? (\n renderHeader?.(tab, handleClose, onOpen)\n ) : (\n <div className=\"rdd-sidebar-drawer-header\">\n <span className=\"rdd-sidebar-header-title\">{tab.label}</span>\n {showCloseButton && (\n <button\n type=\"button\"\n className=\"rdd-sidebar-drawer-close-button\"\n onClick={handleClose}\n title={closeLabel}\n aria-label={closeLabel}\n >\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\">\n <path d=\"M18 6L6 18M6 6l12 12\" />\n </svg>\n </button>\n )}\n </div>\n )}\n\n {/* Drawer body — consumer-supplied content */}\n <div className=\"rdd-sidebar-drawer-body\">\n <SidebarTabProvider\n tabId={tab.id}\n onClose={handleClose}\n onOpen={onOpen}\n setActiveTabId={setActiveTabId}\n >\n {tab.renderContent(tab.id, handleClose, onOpen)}\n </SidebarTabProvider>\n </div>\n </div>\n );\n })}\n </div>\n );\n\n // ---- Resize handle (only interactive when drawer is open) ----\n const resizeHandle = isDrawerOpen ? (\n <SidebarResizeHandle\n position={position}\n currentWidth={width}\n minWidth={minWidth}\n maxWidth={maxWidth}\n onWidthChange={setWidth}\n onResizeStart={() => setIsResizing(true)}\n onResizeEnd={() => setIsResizing(false)}\n />\n ) : null;\n\n return (\n <SidebarContext.Provider value={sidebarContextValue}>\n {/* A sidebar is usually an ancestor of the workspace, so the workspace's own dir never\n reached it: setDirection('rtl') mirrored the desktop beside an unmirrored rail. It now\n follows the workspace into RTL; otherwise it inherits the page's direction, as before. */}\n <div className=\"rdd-sidebar-layout\" dir={workspaceDir === 'rtl' ? 'rtl' : undefined}>\n {position === 'left' && (\n <SidebarTabStrip\n tabs={tabs}\n headerEntries={normalizedHeaderEntries}\n footerEntries={normalizedFooterEntries}\n activeTabId={activeTabId}\n isVisible={isStripVisible}\n position={position}\n onTabClick={handleTabClick}\n />\n )}\n {position === 'left' && drawer}\n {position === 'left' && resizeHandle}\n\n {/* Workspace content — fills all remaining space */}\n <div className=\"rdd-sidebar-content\">\n {children}\n </div>\n\n {position === 'right' && resizeHandle}\n {position === 'right' && drawer}\n {position === 'right' && (\n <SidebarTabStrip\n tabs={tabs}\n headerEntries={normalizedHeaderEntries}\n footerEntries={normalizedFooterEntries}\n activeTabId={activeTabId}\n isVisible={isStripVisible}\n position={position}\n onTabClick={handleTabClick}\n />\n )}\n </div>\n </SidebarContext.Provider>\n );\n });\n\n// ==========================================\n// SecondarySidebar\n// ==========================================\n\n/**\n * Props for {@link RddSecondarySidebar} — identical to {@link RddSidebarProps} except\n * `position` (always the opposite of whatever primary `Sidebar` it's nested inside)\n * and `isSecondary` (always `true`) are not settable.\n */\nexport type RddSecondarySidebarProps = Omit<RddSidebarProps, 'position' | 'isSecondary'>;\n\n/**\n * A second, independent `Sidebar` instance for the opposite edge of the screen —\n * same component, same behavior, zero forked code. Must be rendered inside a\n * primary `Sidebar`'s `children`; automatically takes whichever side that primary\n * isn't using, so the side is never specified directly.\n *\n * @throws Error if rendered without an ancestor `Sidebar`, or nested inside another\n * `RddSecondarySidebar` — this library supports exactly one primary and one secondary,\n * nothing deeper.\n */\nexport const SecondarySidebar: React.ForwardRefExoticComponent<RddSecondarySidebarProps & React.RefAttributes<SidebarHandle>> =\n forwardRef<SidebarHandle, RddSecondarySidebarProps>(function SecondarySidebar(props, ref) {\n const primary = useContext(SidebarContext);\n if (!primary) {\n throw new Error('RddSecondarySidebar must be rendered inside a primary RddSidebar\\'s children');\n }\n if (primary.isSecondary) {\n throw new Error('RddSecondarySidebar cannot be nested inside another RddSecondarySidebar');\n }\n const opposite = primary.position === 'left' ? 'right' : 'left';\n return <Sidebar ref={ref} {...props} position={opposite} isSecondary />;\n });\n\n// ==========================================\n// Hooks\n// ==========================================\n\n/**\n * Returns sidebar control functions from anywhere inside a `<RddSidebar>` tree,\n * including floating panels rendered via `{children}`.\n *\n * @throws Error if used outside of an {@link RddSidebar}.\n */\nexport function useSidebar(): SidebarContextValue {\n const ctx = useContext(SidebarContext);\n if (!ctx) throw new Error('useSidebar must be used within <RddSidebar>');\n return ctx;\n}\n\n/**\n * Returns tab-specific control functions for components rendered inside a\n * sidebar tab's `renderContent` tree.\n *\n * @throws Error if used outside of an {@link RddSidebar} tab's `renderContent` tree.\n */\nexport function useSidebarTab(): SidebarTabContextValue {\n const ctx = useContext(SidebarTabContext);\n if (!ctx) throw new Error('useSidebarTab must be used within an RddSidebar tab\\'s renderContent');\n return ctx;\n}\n\n","/**\n * @file Toolbar.tsx\n * @description Vertical or horizontal toolbar strip hosting action buttons,\n * mutually-exclusive radio tool groups, independent toggle modifiers,\n * and collapsible sub-tool group flyouts.\n * State is library-wide via DockableDesktopProvider / ToolbarContext.\n */\n\nimport React, { forwardRef, useImperativeHandle, useState, useRef, useEffect, useLayoutEffect } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useToolbar } from './ToolbarContext';\nimport { useEscapeLayer } from '../utils/escapeStack';\nimport { isComputedRtl } from '../utils/rtl';\nimport { enabledItems, moveMenuFocus } from '../utils/menuKeyboard';\nimport type { ToolbarContextValue } from './ToolbarContext';\n\n// ==========================================\n// Item type definitions\n// ==========================================\n\n/** A one-shot action button. */\nexport interface ToolbarActionItem {\n type: 'action';\n id: string;\n label: string;\n icon: React.ReactNode;\n onClick: () => void;\n disabled?: boolean;\n}\n\n/** A mutually-exclusive radio button within a named group. */\nexport interface ToolbarRadioItem {\n type: 'radio';\n id: string;\n group: string;\n label: string;\n icon: React.ReactNode;\n /** Keyboard shortcut hint — displayed in the group flyout; reserved for future custom tooltip. */\n shortcut?: string;\n /** Called when this item becomes active. */\n onActivate?: (id: string) => void;\n disabled?: boolean;\n}\n\n/**\n * An independent on/off toggle modifier (e.g. snap-to-grid).\n *\n * Supports both uncontrolled mode (omit `rdd-active` — state lives in\n * ToolbarContext, keyed by `id`) and controlled mode (provide `rdd-active` —\n * the caller is the single source of truth and must update the prop in\n * response to `onToggle`). Controlled mode is what lets independent\n * instances of the same panel type report independent active state\n * instead of colliding on a shared id.\n */\nexport interface ToolbarToggleItem {\n type: 'toggle';\n id: string;\n label: string;\n icon: React.ReactNode;\n /** Keyboard shortcut hint — reserved for future custom tooltip. */\n shortcut?: string;\n /**\n * Controlled active state. When provided (even as false), the component\n * reads this prop instead of ToolbarContext and does not update context\n * on click. Omit (undefined) for uncontrolled behaviour.\n */\n active?: boolean;\n /** Called after the toggle flips; receives the new active state. */\n onToggle?: (active: boolean) => void;\n disabled?: boolean;\n}\n\n/** A visual divider between button groups. */\nexport interface ToolbarSeparator {\n type: 'separator';\n}\n\n// ==========================================\n// Group item types (sub-tool flyout)\n// ==========================================\n\n/**\n * A single selectable sub-tool inside a group flyout.\n * All sub-items in the same ToolbarGroupItem share one radio group\n * keyed by the parent ToolbarGroupItem's `id`.\n */\nexport interface ToolbarGroupSubItem {\n id: string;\n label: string;\n icon: React.ReactNode;\n /** Keyboard shortcut displayed in the flyout panel. */\n shortcut?: string;\n disabled?: boolean;\n /** Called when this sub-item is selected. */\n onActivate?: (id: string) => void;\n}\n\n/** An entry inside a group flyout — either a sub-item or a separator. */\nexport type ToolbarGroupEntry = ToolbarGroupSubItem | { type: 'separator' };\n\n/**\n * A collapsed tool-family button that opens a flyout panel listing all\n * sub-tools. Only one sub-tool may be active at a time (radio semantics).\n * The parent button's icon morphs to show the currently active sub-tool.\n *\n * Supports both uncontrolled mode (omit activeItemId — state lives in\n * ToolbarContext) and controlled mode (provide activeItemId — the caller\n * is the single source of truth and must update the prop in response to\n * onActiveItemChange).\n */\nexport interface ToolbarGroupItem {\n type: 'group';\n /** Serves as both the button ID and the radio group key in ToolbarContext. */\n id: string;\n /** Tooltip / aria-label shown when no sub-item is active. */\n label: string;\n /** Icon shown when no sub-item is active. */\n defaultIcon: React.ReactNode;\n items: ToolbarGroupEntry[];\n disabled?: boolean;\n /**\n * Controlled active sub-item id. When provided (even as null), the\n * component reads this prop instead of ToolbarContext and fires\n * onActiveItemChange on click instead of updating context.\n * Omit (undefined) for uncontrolled behaviour.\n */\n activeItemId?: string | null;\n /**\n * Called when the user selects a sub-item in controlled mode.\n * The toolbar does not update itself — the caller must update activeItemId.\n */\n onActiveItemChange?: (id: string) => void;\n}\n\nexport type ToolbarItem =\n | ToolbarActionItem\n | ToolbarRadioItem\n | ToolbarToggleItem\n | ToolbarGroupItem\n | ToolbarSeparator;\n\n// ==========================================\n// Props and Handle\n// ==========================================\n\nexport interface RddToolbarProps {\n /** Side the strip is attached to. Controls strip orientation. Default: 'left' */\n position?: 'left' | 'right' | 'top' | 'bottom';\n /** Ordered list of items to render. */\n items: ToolbarItem[];\n /** Collapse the strip to zero width/height. State is preserved — no unmount. */\n visible?: boolean;\n /** Called when show/hide/toggle is invoked on the imperative handle. */\n onVisibilityChange?: (visible: boolean) => void;\n className?: string;\n style?: React.CSSProperties;\n}\n\nexport interface ToolbarHandle {\n show(): void;\n hide(): void;\n toggle(): void;\n}\n\n// ==========================================\n// ToolbarGroupButton — internal sub-component\n// Manages its own open/close state and renders the flyout via a portal\n// so it is never clipped by the strip's overflow:hidden.\n// ==========================================\n\ninterface ToolbarGroupButtonProps {\n item: ToolbarGroupItem;\n position: 'left' | 'right' | 'top' | 'bottom';\n toolbar: ToolbarContextValue;\n}\n\nfunction flyoutPosition(\n rect: DOMRect,\n position: 'left' | 'right' | 'top' | 'bottom',\n isRtl = false,\n gap = 8,\n): React.CSSProperties {\n switch (position) {\n case 'left':\n // RTL: flex-row reverses, so 'left' toolbar sits on the right → open leftward\n return isRtl\n ? { right: window.innerWidth - rect.left + gap, top: rect.top }\n : { left: rect.right + gap, top: rect.top };\n case 'right':\n // RTL: 'right' toolbar sits on the left → open rightward\n return isRtl\n ? { left: rect.right + gap, top: rect.top }\n : { right: window.innerWidth - rect.left + gap, top: rect.top };\n case 'top':\n return isRtl\n ? { top: rect.bottom + gap, right: window.innerWidth - rect.right }\n : { top: rect.bottom + gap, left: rect.left };\n case 'bottom':\n return isRtl\n ? { bottom: window.innerHeight - rect.top + gap, right: window.innerWidth - rect.right }\n : { bottom: window.innerHeight - rect.top + gap, left: rect.left };\n }\n}\n\nfunction ToolbarGroupButton({ item, position, toolbar }: ToolbarGroupButtonProps) {\n const [isOpen, setIsOpen] = useState(false);\n const [btnRect, setBtnRect] = useState<DOMRect | null>(null);\n const [btnRtl, setBtnRtl] = useState(false);\n const btnRef = useRef<HTMLButtonElement>(null);\n const flyoutRef = useRef<HTMLDivElement>(null);\n\n const isControlled = item.activeItemId !== undefined;\n const activeId = isControlled ? item.activeItemId : toolbar.getActiveInGroup(item.id);\n const activeSubItem = item.items.find(\n (e): e is ToolbarGroupSubItem => !('type' in e) && e.id === activeId,\n );\n const isActive = activeId !== null;\n const displayIcon = activeSubItem?.icon ?? item.defaultIcon;\n const displayLabel = activeSubItem?.label ?? item.label;\n\n const handleClick = () => {\n if (item.disabled) return;\n if (!isOpen && btnRef.current) {\n setBtnRect(btnRef.current.getBoundingClientRect());\n // The strip's own computed direction decides which side it sits on — RTL may be set on\n // <body> or a wrapper, not just <html>, and an LTR strip can sit on an RTL page.\n setBtnRtl(isComputedRtl(btnRef.current));\n }\n setIsOpen(prev => !prev);\n };\n\n // Clamp flyout to viewport after it renders (runs before paint to avoid jitter)\n useLayoutEffect(() => {\n if (!isOpen || !flyoutRef.current) return;\n const el = flyoutRef.current;\n const r = el.getBoundingClientRect();\n const PAD = 8;\n if (r.right > window.innerWidth - PAD) {\n el.style.left = `${Math.max(PAD, window.innerWidth - r.width - PAD)}px`;\n el.style.right = 'auto';\n }\n if (r.left < PAD) {\n el.style.left = `${PAD}px`;\n el.style.right = 'auto';\n }\n if (r.bottom > window.innerHeight - PAD) {\n el.style.top = `${Math.max(PAD, window.innerHeight - r.height - PAD)}px`;\n el.style.bottom = 'auto';\n }\n if (r.top < PAD) {\n el.style.top = `${PAD}px`;\n el.style.bottom = 'auto';\n }\n }, [isOpen]);\n\n // Close flyout on click-away (exclude clicks inside the button or flyout itself)\n useEffect(() => {\n if (!isOpen) return;\n const onMouseDown = (e: MouseEvent) => {\n const target = e.target as Node;\n if (btnRef.current?.contains(target)) return;\n if (flyoutRef.current?.contains(target)) return;\n setIsOpen(false);\n };\n document.addEventListener('mousedown', onMouseDown);\n return () => document.removeEventListener('mousedown', onMouseDown);\n }, [isOpen]);\n\n // Closing from inside the flyout (Escape, Tab, choosing an item) hands focus back to the\n // trigger, as the context menu does; a click elsewhere leaves focus where the click put it.\n const closeFlyout = () => {\n if (flyoutRef.current?.contains(document.activeElement)) btnRef.current?.focus();\n setIsOpen(false);\n };\n\n // Open: focus the chosen item, else the first (WAI-ARIA menu pattern).\n useLayoutEffect(() => {\n if (!isOpen) return;\n const items = enabledItems(flyoutRef.current);\n (items.find(el => el.getAttribute('aria-checked') === 'true') ?? items[0])?.focus();\n }, [isOpen]);\n\n const handleFlyoutKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n if (e.key === 'Tab') { e.preventDefault(); closeFlyout(); return; }\n if (moveMenuFocus(e.currentTarget, e.key)) e.preventDefault();\n };\n\n // Close flyout on Escape — a popup, so above any modal or drawer on the shared Escape stack.\n useEscapeLayer(isOpen, 'popup', closeFlyout);\n\n return (\n <>\n <button\n ref={btnRef}\n type=\"button\"\n className={`rdd-toolbar-btn rdd-toolbar-btn-group${isActive ? ' rdd-active' : ''}`}\n title={displayLabel}\n aria-label={displayLabel}\n aria-expanded={isOpen}\n aria-haspopup=\"menu\"\n disabled={item.disabled}\n onClick={handleClick}\n >\n {displayIcon}\n </button>\n\n {isOpen && btnRect && createPortal(\n <div\n ref={flyoutRef}\n className={`rdd-toolbar-group-flyout rdd-${position}`}\n style={flyoutPosition(btnRect, position, btnRtl)}\n role=\"menu\"\n // Portaled to <body>: carry the strip's direction, which it can't inherit there.\n dir={btnRtl ? 'rtl' : 'ltr'}\n onKeyDown={handleFlyoutKeyDown}\n >\n {item.items.map((entry, i) => {\n if ('type' in entry) {\n return <div key={`sep-${i}`} className=\"rdd-toolbar-group-flyout-sep\" role=\"separator\" />;\n }\n const isSubActive = activeId === entry.id;\n return (\n <button\n key={entry.id}\n type=\"button\"\n className={`rdd-toolbar-group-flyout-item${isSubActive ? ' rdd-active' : ''}`}\n disabled={entry.disabled}\n // One of a mutually exclusive set: a radio menu item. aria-pressed is not allowed\n // on menu items.\n role=\"menuitemradio\"\n aria-checked={isSubActive}\n onClick={() => {\n if (isControlled) {\n item.onActiveItemChange?.(entry.id);\n } else {\n toolbar.setActiveInGroup(item.id, entry.id);\n }\n entry.onActivate?.(entry.id);\n closeFlyout();\n }}\n >\n <span className=\"rdd-toolbar-group-flyout-icon\">{entry.icon}</span>\n <span className=\"rdd-toolbar-group-flyout-label\">{entry.label}</span>\n {entry.shortcut && (\n <span className=\"rdd-toolbar-group-flyout-shortcut\">{entry.shortcut}</span>\n )}\n </button>\n );\n })}\n </div>,\n document.body,\n )}\n </>\n );\n}\n\n// ==========================================\n// renderItem — pure helper outside component\n// ==========================================\n\nfunction renderItem(\n item: ToolbarItem,\n index: number,\n toolbar: ToolbarContextValue,\n position: 'left' | 'right' | 'top' | 'bottom',\n): React.ReactNode {\n switch (item.type) {\n case 'separator':\n return <div key={`sep-${index}`} className=\"rdd-toolbar-separator\" role=\"separator\" />;\n\n case 'action':\n return (\n <button\n key={item.id}\n type=\"button\"\n className=\"rdd-toolbar-btn rdd-toolbar-btn-action\"\n title={item.label}\n aria-label={item.label}\n disabled={item.disabled}\n onClick={item.onClick}\n >\n {item.icon}\n </button>\n );\n\n case 'radio': {\n const isActive = toolbar.getActiveInGroup(item.group) === item.id;\n return (\n <button\n key={item.id}\n type=\"button\"\n className={`rdd-toolbar-btn rdd-toolbar-btn-radio${isActive ? ' rdd-active' : ''}`}\n title={item.label}\n aria-label={item.label}\n aria-pressed={isActive}\n disabled={item.disabled}\n onClick={() => {\n toolbar.setActiveInGroup(item.group, item.id);\n item.onActivate?.(item.id);\n }}\n >\n {item.icon}\n </button>\n );\n }\n\n case 'toggle': {\n const controlled = item.active !== undefined;\n const isActive = controlled ? item.active! : toolbar.isModifierActive(item.id);\n return (\n <button\n key={item.id}\n type=\"button\"\n className={`rdd-toolbar-btn rdd-toolbar-btn-toggle${isActive ? ' rdd-active' : ''}`}\n title={item.label}\n aria-label={item.label}\n aria-pressed={isActive}\n disabled={item.disabled}\n onClick={() => {\n if (!controlled) toolbar.toggleModifier(item.id);\n item.onToggle?.(!isActive);\n }}\n >\n {item.icon}\n </button>\n );\n }\n\n case 'group':\n return (\n <ToolbarGroupButton\n key={item.id}\n item={item}\n position={position}\n toolbar={toolbar}\n />\n );\n }\n}\n\n// ==========================================\n// Component\n// ==========================================\n\nexport const Toolbar: React.ForwardRefExoticComponent<RddToolbarProps & React.RefAttributes<ToolbarHandle>> = forwardRef<ToolbarHandle, RddToolbarProps>(function Toolbar(\n { position = 'left', items, visible, onVisibilityChange, className, style },\n ref\n) {\n const toolbar = useToolbar();\n const isVertical = position === 'left' || position === 'right';\n\n useImperativeHandle(ref, () => ({\n show: () => onVisibilityChange?.(true),\n hide: () => onVisibilityChange?.(false),\n toggle: () => onVisibilityChange?.(visible === false ? true : false),\n }), [visible, onVisibilityChange]);\n\n // CSS owns the open-state dimensions (including the touch @media 56px override).\n // Inline style only forces 0px when collapsed so the transition animates correctly.\n const collapsed = visible === false;\n const collapseStyle: React.CSSProperties = !collapsed\n ? {}\n : isVertical\n ? { width: '0px' }\n : { height: '0px' };\n\n // A collapsed strip is still in the DOM, so its buttons stayed in the Tab order — keyboard focus\n // landed on controls nobody could see. `inert` takes the whole subtree out of focus and the\n // accessibility tree. Set through the DOM rather than as a JSX prop: only React 19 knows `inert`,\n // and this library supports React 18 as well.\n const stripRef = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n const strip = stripRef.current;\n if (!strip) return;\n if (collapsed) strip.setAttribute('inert', '');\n else strip.removeAttribute('inert');\n }, [collapsed]);\n\n return (\n <div\n ref={stripRef}\n className={`rdd-toolbar-strip rdd-${position}${collapsed ? ' rdd-collapsed' : ''}${className ? ` ${className}` : ''}`}\n role=\"toolbar\"\n aria-orientation={isVertical ? 'vertical' : 'horizontal'}\n aria-hidden={collapsed || undefined}\n style={{ ...collapseStyle, ...style }}\n >\n {items.map((item, i) => renderItem(item, i, toolbar, position))}\n </div>\n );\n});\n\n// ==========================================\n// Barrel re-exports from ToolbarContext\n// ==========================================\n\nexport { useToolbar, ToolbarProvider } from './ToolbarContext';\nexport type { ToolbarContextValue } from './ToolbarContext';\n","import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { useIsClient } from '../utils/useIsClient';\nimport { createPortal } from 'react-dom';\nimport { formatLabel, useFormatMessage, usePredefinedMessages, useOptionalWindowManagerState } from './WindowManagerContext';\nimport { useLatestRef } from '../utils/useLatestRef';\n\n// ─── Public types ─────────────────────────────────────────────────────────────\n\n/** Visual type of a toast notification. Determines the icon and accent color. */\nexport type ToastType = 'info' | 'success' | 'warning' | 'error';\n\n/** Corner position of the `<RddToasts>` relative to the viewport. */\nexport type ToastPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\n/**\n * Per-notification options passed to `toast()`, `toast.info()`, etc.\n * All fields are optional and fall back to `<RddToasts>` defaults when unset.\n */\nexport interface ToastOptions {\n /** Visual type. Overridden by the `toast.info/success/warning/error` shorthands. @default 'info' */\n type?: ToastType;\n /** Auto-dismiss delay in ms. `0` = sticky (never auto-dismisses). @default from container */\n duration?: number;\n /** Explicit ID for dedup — calling `toast.*` with the same `id` updates the existing card in-place. */\n id?: string;\n /** Show the × close button on this notification. @default from container */\n closable?: boolean;\n /** Override the built-in type icon with arbitrary content. */\n icon?: React.ReactNode;\n /** Replace the string message with arbitrary JSX. */\n content?: React.ReactNode;\n /** Called when the notification is dismissed by timer, close button, or `toast.dismiss()`. */\n onClose?: () => void;\n}\n\n/**\n * Fully-resolved options passed to `ToastAdapter.show()` and `ToastAdapter.update()`.\n * All optional `ToastOptions` fields are resolved against the container defaults.\n */\nexport interface ResolvedToastOptions {\n id: string;\n type: ToastType;\n duration: number;\n closable: boolean;\n icon?: React.ReactNode;\n content?: React.ReactNode;\n onClose?: () => void;\n}\n\n/**\n * Props for `<RddToasts>`. Mount one instance at your app root, alongside `<RddModals>`.\n * @example\n * <RddToasts position=\"top-right\" progressBar />\n */\nexport interface RddToastsProps {\n /** Where notifications appear in the viewport. @default 'top-right' */\n position?: ToastPosition;\n /** Maximum number of notifications shown simultaneously. Extras are queued. @default 3 */\n maxVisible?: number;\n /** Default auto-dismiss delay in ms. `0` = all notifications sticky. @default 5000 */\n defaultDuration?: number;\n /** Show the × close button on all notifications unless overridden per-toast. @default true */\n defaultClosable?: boolean;\n /** Pause the auto-dismiss timer while the cursor is over a notification. @default true */\n pauseOnHover?: boolean;\n /** Entry/exit animation style. @default 'slide' */\n animation?: 'slide' | 'fade' | 'none';\n /** When `true`, newest notification appears at the top of the stack. @default false */\n newestOnTop?: boolean;\n /** Show a countdown progress bar at the bottom of each notification. @default false */\n progressBar?: boolean;\n /** Width of each notification card in pixels. @default 320 */\n width?: number;\n /** Delegate all `toast.*` calls to a custom renderer (Ant Design, MUI, Sonner, etc.). */\n adapter?: ToastAdapter;\n}\n\n/**\n * Message set for `toast.promise()`. Each field may be static content or a function\n * that receives the resolved/rejected value and returns renderable content.\n * @template T The resolved value type of the tracked promise.\n */\nexport interface ToastPromiseMessages<T> {\n /** Shown while the promise is pending. */\n pending: React.ReactNode;\n /** Shown on fulfillment. Pass a function to include the resolved value. */\n success: React.ReactNode | ((result: T) => React.ReactNode);\n /** Shown on rejection. Pass a function to include the error reason. */\n error: React.ReactNode | ((err: unknown) => React.ReactNode);\n}\n\n/**\n * Strategy interface for replacing the built-in toast renderer with an external library.\n * Pass an instance via `<RddToasts adapter={...} />` to redirect all `toast.*` calls\n * without changing any call sites in your application.\n * @see RddToastsProps.adapter\n */\nexport interface ToastAdapter {\n /** Called when a new notification is requested. */\n show(id: string, message: React.ReactNode, options: ResolvedToastOptions): void;\n /** Called when an existing notification is updated (e.g. after `toast.promise()` resolves). */\n update(id: string, message: React.ReactNode, options: Partial<ResolvedToastOptions>): void;\n /** Called to dismiss one notification (`id` provided) or all active notifications (no `id`). */\n dismiss(id?: string): void;\n /**\n * `null` means the adapter manages its own DOM and `<RddToasts>` renders nothing.\n * A component causes `<RddToasts>` to portal-render it with a `position` prop.\n */\n Container: React.ComponentType<{ position: ToastPosition }> | null;\n}\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ntype ToastEvent =\n | { kind: 'show'; id: string; message: React.ReactNode; rawOpts: ToastOptions & { id: string } }\n | { kind: 'update'; id: string; message: React.ReactNode; patch: Partial<ResolvedToastOptions> }\n | { kind: 'dismiss'; id?: string };\n\ninterface ActiveToast {\n id: string;\n message: React.ReactNode;\n options: ResolvedToastOptions;\n exiting: boolean;\n}\n\n// ─── ToastEmitter ─────────────────────────────────────────────────────────────\n\nclass ToastEmitter {\n private listeners = new Set<(e: ToastEvent) => void>();\n private counter = 0;\n\n subscribe(fn: (e: ToastEvent) => void) { this.listeners.add(fn); }\n unsubscribe(fn: (e: ToastEvent) => void) { this.listeners.delete(fn); }\n\n show(message: React.ReactNode, opts: ToastOptions = {}): string {\n const id = opts.id ?? `toast-${++this.counter}`;\n this.emit({ kind: 'show', id, message, rawOpts: { ...opts, id } });\n return id;\n }\n\n update(id: string, message: React.ReactNode, patch: Partial<ResolvedToastOptions>) {\n this.emit({ kind: 'update', id, message, patch });\n }\n\n dismiss(id?: string) { this.emit({ kind: 'dismiss', id }); }\n\n private emit(e: ToastEvent) { this.listeners.forEach(fn => fn(e)); }\n}\n\nconst emitter = new ToastEmitter();\n\n// ─── toast public API ─────────────────────────────────────────────────────────\n\n/**\n * Type of the `toast` singleton. Callable directly or via named shorthand methods.\n * Import this type to annotate variables or props that accept the `toast` object.\n * @example\n * function notify(fn: ToastFunction) { fn.success('Done!'); }\n */\nexport interface ToastFunction {\n /** Show a notification. `opts.type` defaults to `'info'`. Returns the notification ID. */\n (msg: React.ReactNode, opts?: ToastOptions): string;\n /** Show an info notification. Returns the notification ID. */\n info: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Show a success notification. Returns the notification ID. */\n success: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Show a warning notification. Returns the notification ID. */\n warning: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Show an error notification. Returns the notification ID. */\n error: (msg: React.ReactNode, opts?: ToastOptions) => string;\n /** Dismiss a notification by ID, or all active notifications when called with no argument. */\n dismiss: (id?: string) => void;\n /**\n * Track a promise through pending → success/error states.\n * Shows a sticky pending notification immediately, then transitions it on settlement.\n * @template T The resolved value type of the promise.\n */\n promise: <T>(promise: Promise<T>, messages: ToastPromiseMessages<T>, opts?: ToastOptions) => Promise<T>;\n}\n\n/**\n * Imperative notification singleton. Call from anywhere — inside or outside React.\n * Mount `<RddToasts>` once at your app root to activate the renderer.\n * @example\n * toast.success('File saved.');\n * toast.error('Upload failed.', { duration: 0 }); // sticky\n * toast.promise(saveFile(), { pending: 'Saving…', success: 'Saved!', error: 'Failed.' });\n */\nexport const toast: ToastFunction = Object.assign(\n (msg: React.ReactNode, opts?: ToastOptions): string => emitter.show(msg, opts),\n {\n info: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'info' }),\n success: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'success' }),\n warning: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'warning' }),\n error: (msg: React.ReactNode, opts?: ToastOptions): string =>\n emitter.show(msg, { ...opts, type: 'error' }),\n dismiss: (id?: string): void => emitter.dismiss(id),\n promise: <T,>(\n promise: Promise<T>,\n messages: ToastPromiseMessages<T>,\n opts?: ToastOptions\n ): Promise<T> => {\n const id = emitter.show(messages.pending, { ...opts, type: 'info', duration: 0 });\n promise.then(\n result => {\n const msg = typeof messages.success === 'function' ? messages.success(result) : messages.success;\n emitter.update(id, msg, { type: 'success', duration: opts?.duration ?? 5000 });\n },\n err => {\n const msg = typeof messages.error === 'function' ? messages.error(err) : messages.error;\n emitter.update(id, msg, { type: 'error', duration: opts?.duration ?? 5000 });\n }\n );\n return promise;\n },\n }\n);\n\n// ─── Icons ────────────────────────────────────────────────────────────────────\n\nconst InfoIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M8 5v.01M8 7.5v3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst SuccessIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5 8l2 2 4-4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"/>\n </svg>\n);\nconst WarningIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <path d=\"M8 2.5L14 13.5H2L8 2.5z\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinejoin=\"round\"/>\n <path d=\"M8 7v2.5M8 11.5v.01\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst ErrorIcon = () => (\n <svg className=\"rdd-toast__icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"7\" stroke=\"currentColor\" strokeWidth=\"1.5\"/>\n <path d=\"M5.5 5.5l5 5M10.5 5.5l-5 5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\nconst CloseIcon = () => (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <path d=\"M4 4l8 8M12 4l-8 8\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\"/>\n </svg>\n);\n\nconst DEFAULT_ICONS: Record<ToastType, React.ReactNode> = {\n info: <InfoIcon />,\n success: <SuccessIcon />,\n warning: <WarningIcon />,\n error: <ErrorIcon />,\n};\n\n// ─── ToastItem ────────────────────────────────────────────────────────────────\n\ninterface ToastItemProps {\n id: string;\n message: React.ReactNode;\n options: ResolvedToastOptions;\n exiting: boolean;\n isLeft: boolean;\n showProgress: boolean;\n pauseOnHover: boolean;\n animation: 'slide' | 'fade' | 'none';\n closeLabel: string;\n onDismiss: (id: string) => void;\n onExited: (id: string) => void;\n}\n\nfunction ToastItem({\n id, message, options, exiting, isLeft,\n showProgress, pauseOnHover, animation, closeLabel, onDismiss, onExited,\n}: ToastItemProps) {\n const divRef = useRef<HTMLDivElement>(null);\n const bodyRef = useRef<HTMLDivElement>(null);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const remainRef = useRef<number>(options.duration);\n const startRef = useRef<number>(0);\n const [paused, setPaused] = useState(false);\n\n const startEntry =\n animation === 'none' ? 'rdd-toast--visible' :\n animation === 'fade' ? 'rdd-toast--fade-entering' :\n isLeft ? 'rdd-toast--entering-left' :\n 'rdd-toast--entering';\n const [entryClass, setEntryClass] = useState(startEntry);\n\n // Keep max-height in sync with the card's true content height, so content that\n // grows after mount (e.g. toast.promise()'s pending -> error message) never gets\n // clipped by the overflow: hidden below. The card's own box is exactly what this\n // effect holds at a fixed height, so it never reports a resize on its own — the\n // ResizeObserver instead watches the unconstrained inner body (the only thing\n // that actually grows with its content) purely as a trigger, and reads the\n // outer card's scrollHeight (which reports the true, uncapped content height\n // even while a stale cap is still clipping it — offsetHeight/clientHeight would\n // just return that stale cap) to compute the new value. Frozen once exiting\n // starts: .rdd-toast--exiting's `max-height: 0 !important` below takes over\n // from there regardless of this inline value.\n useLayoutEffect(() => {\n const el = divRef.current;\n const body = bodyRef.current;\n if (!el || !body || exiting) return;\n\n const applyHeight = () => { el.style.maxHeight = `${el.scrollHeight}px`; };\n applyHeight();\n\n const observer = new ResizeObserver(applyHeight);\n observer.observe(body);\n return () => observer.disconnect();\n }, [exiting]);\n\n // Trigger entry transition on next frame\n useEffect(() => {\n if (animation === 'none') return;\n const raf = requestAnimationFrame(() => setEntryClass('rdd-toast--visible'));\n return () => cancelAnimationFrame(raf);\n }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n // Auto-dismiss timer\n const scheduleDismiss = useCallback((ms: number) => {\n if (ms <= 0) return;\n startRef.current = Date.now();\n timerRef.current = setTimeout(() => onDismiss(id), ms);\n }, [id, onDismiss]);\n\n useEffect(() => {\n if (timerRef.current) clearTimeout(timerRef.current);\n remainRef.current = options.duration;\n scheduleDismiss(options.duration);\n return () => { if (timerRef.current) clearTimeout(timerRef.current); };\n }, [options.duration, scheduleDismiss]);\n\n // Exit animation → call onExited after transition\n useEffect(() => {\n if (!exiting) return;\n const el = divRef.current;\n if (!el || animation === 'none') {\n onExited(id);\n return;\n }\n const handle = (e: TransitionEvent) => {\n if (e.propertyName === 'max-height') onExited(id);\n };\n el.addEventListener('transitionend', handle);\n const fallback = setTimeout(() => onExited(id), 520);\n return () => {\n el.removeEventListener('transitionend', handle);\n clearTimeout(fallback);\n };\n }, [exiting, id, onExited, animation]);\n\n const handleMouseEnter = () => {\n if (!pauseOnHover || options.duration === 0) return;\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n remainRef.current = Math.max(0, remainRef.current - (Date.now() - startRef.current));\n }\n setPaused(true);\n };\n\n const handleMouseLeave = () => {\n if (!pauseOnHover || options.duration === 0) return;\n setPaused(false);\n scheduleDismiss(remainRef.current);\n };\n\n const cls = [\n 'rdd-toast',\n options.type && `rdd-toast--${options.type}`,\n entryClass,\n exiting && 'rdd-toast--exiting',\n paused && 'rdd-toast--paused',\n ].filter(Boolean).join(' ');\n\n const icon = options.icon !== undefined ? options.icon : (options.type ? DEFAULT_ICONS[options.type] : null);\n\n return (\n <div\n ref={divRef}\n role=\"status\"\n aria-live=\"polite\"\n className={cls}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n {icon && icon}\n <div ref={bodyRef} className=\"rdd-toast__body\">\n {options.content !== undefined ? options.content : message}\n </div>\n {options.closable && (\n <button\n type=\"button\"\n className=\"rdd-toast__close\"\n onClick={() => onDismiss(id)}\n aria-label={closeLabel}\n >\n <CloseIcon />\n </button>\n )}\n {showProgress && options.duration > 0 && (\n <div\n className=\"rdd-toast__progress\"\n style={{ animationDuration: `${options.duration}ms` }}\n />\n )}\n </div>\n );\n}\n\n// ─── ToastContainer ───────────────────────────────────────────────────────────\n\n\nfunction resolveOpts(\n raw: ToastOptions & { id: string },\n defaultDuration: number,\n defaultClosable: boolean\n): ResolvedToastOptions {\n return {\n id: raw.id,\n type: raw.type ?? 'info',\n duration: raw.duration ?? defaultDuration,\n closable: raw.closable ?? defaultClosable,\n icon: raw.icon,\n content: raw.content,\n onClose: raw.onClose,\n };\n}\n\n/**\n * Portal-rendered notification host. Mount once at your app root, outside the workspace\n * container. All `toast.*` calls are routed here automatically via the internal event emitter.\n * @example\n * <RddToasts position=\"top-right\" progressBar />\n */\nexport function ToastContainer({\n position = 'top-right',\n maxVisible = 3,\n defaultDuration = 5000,\n defaultClosable = true,\n pauseOnHover = true,\n animation = 'slide',\n newestOnTop = false,\n progressBar = false,\n width = 320,\n adapter,\n}: RddToastsProps): React.ReactElement | null {\n const [toasts, setToasts] = useState<ActiveToast[]>([]);\n // Both hooks work without a provider (English defaults), so a ToastContainer mounted outside\n // the workspace still renders.\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const regionLabel = formatLabel(messages.notifications, formatMessage);\n // Toasts are portalled to <body>: they follow setDirection('rtl') like the workspace, and\n // otherwise inherit the page's direction, as before.\n const workspaceDir = useOptionalWindowManagerState(s => s.dir, undefined);\n // Portals need `document.body`, which doesn't exist on the server. Render nothing there, and\n // during hydration (the server snapshot); portal on the client after that. The server's output\n // and the hydrating render then agree — both empty — so there is nothing to reconcile.\n const mounted = useIsClient();\n const closeLabel = formatLabel(messages.closeNotification, formatMessage);\n const queueRef = useRef<Array<{ id: string; message: React.ReactNode; rawOpts: ToastOptions & { id: string } }>>([]);\n const toastsRef = useLatestRef<ActiveToast[]>(toasts);\n\n const handleDismiss = useCallback((id: string) => {\n setToasts(prev => prev.map(t => t.id === id ? { ...t, exiting: true } : t));\n toastsRef.current.find(t => t.id === id)?.options.onClose?.();\n }, [toastsRef]);\n\n const handleExited = useCallback((id: string) => {\n // Shift outside the updater (once) so the updater is pure and safe for StrictMode\n const promoted = queueRef.current.shift() ?? null;\n setToasts(prev => {\n const filtered = prev.filter(t => t.id !== id);\n if (!promoted) return filtered;\n const options = resolveOpts(promoted.rawOpts, defaultDuration, defaultClosable);\n return [...filtered, { id: promoted.id, message: promoted.message, options, exiting: false }];\n });\n }, [defaultDuration, defaultClosable]);\n\n // Subscribe to emitter (built-in path)\n useEffect(() => {\n if (adapter) return;\n\n const handle = (e: ToastEvent) => {\n if (e.kind === 'show') {\n // Resolve options once outside the updater so the updater stays pure\n const options = resolveOpts(e.rawOpts, defaultDuration, defaultClosable);\n const newEntry: ActiveToast = { id: e.id, message: e.message, options, exiting: false };\n const rawEntry = { id: e.id, message: e.message, rawOpts: e.rawOpts };\n\n setToasts(prev => {\n // Dedup check against actual prev (not stale ref) so batched calls are safe\n const existing = prev.find(t => t.id === e.id);\n if (existing) {\n return prev.map(t => t.id === e.id ? { ...t, message: e.message, options } : t);\n }\n // Count against actual prev so multiple synchronous toast() calls batch correctly\n const visible = prev.filter(t => !t.exiting).length;\n if (visible < maxVisible) {\n return [...prev, newEntry];\n }\n // Queue — guard prevents duplicate push when React calls updater twice (StrictMode)\n if (!queueRef.current.some(q => q.id === rawEntry.id)) {\n queueRef.current.push(rawEntry);\n }\n return prev;\n });\n } else if (e.kind === 'update') {\n setToasts(prev => prev.map(t => {\n if (t.id !== e.id) return t;\n const merged: ResolvedToastOptions = { ...t.options, ...e.patch, id: t.id };\n return { ...t, message: e.message, options: merged };\n }));\n queueRef.current = queueRef.current.map(q => {\n if (q.id !== e.id) return q;\n return { ...q, message: e.message, rawOpts: { ...q.rawOpts, ...e.patch } };\n });\n } else if (e.kind === 'dismiss') {\n if (e.id === undefined) {\n setToasts(prev => prev.map(t => ({ ...t, exiting: true })));\n queueRef.current = [];\n } else {\n const isActive = toastsRef.current.some(t => t.id === e.id);\n if (isActive) {\n handleDismiss(e.id);\n } else {\n queueRef.current = queueRef.current.filter(q => q.id !== e.id);\n }\n }\n }\n };\n\n emitter.subscribe(handle);\n return () => emitter.unsubscribe(handle);\n }, [adapter, maxVisible, defaultDuration, defaultClosable, handleDismiss, toastsRef]);\n\n // Subscribe to emitter (adapter path)\n useEffect(() => {\n if (!adapter) return;\n const handle = (e: ToastEvent) => {\n if (e.kind === 'show') {\n const opts = resolveOpts(e.rawOpts, defaultDuration, defaultClosable);\n adapter.show(e.id, e.message, opts);\n } else if (e.kind === 'update') {\n adapter.update(e.id, e.message, e.patch);\n } else if (e.kind === 'dismiss') {\n adapter.dismiss(e.id);\n }\n };\n emitter.subscribe(handle);\n return () => emitter.unsubscribe(handle);\n }, [adapter, defaultDuration, defaultClosable]);\n\n if (!mounted) return null;\n\n if (adapter) {\n if (!adapter.Container) return null;\n const AdapterContainer = adapter.Container;\n return createPortal(<AdapterContainer position={position} />, document.body);\n }\n\n const isLeft = position.endsWith('left');\n let dirMod = '';\n if (newestOnTop === true) dirMod = 'rdd-toast-container--newest-top';\n if (newestOnTop === false) dirMod = 'rdd-toast-container--newest-bottom';\n\n const cls = ['rdd-toast-container', `rdd-toast-container--${position}`, dirMod]\n .filter(Boolean).join(' ');\n\n return createPortal(\n // A named landmark. Each toast is its own role=\"status\" live region, so the container is not\n // one as well — nested live regions get announced twice.\n <div className={cls} style={{ width }} role=\"region\" aria-label={regionLabel} dir={workspaceDir === 'rtl' ? 'rtl' : undefined}>\n {toasts.map(t => (\n <ToastItem\n key={t.id}\n id={t.id}\n message={t.message}\n options={t.options}\n exiting={t.exiting}\n isLeft={isLeft}\n showProgress={progressBar}\n pauseOnHover={pauseOnHover}\n animation={animation}\n closeLabel={closeLabel}\n onDismiss={handleDismiss}\n onExited={handleExited}\n />\n ))}\n </div>,\n document.body\n );\n}\n","/**\n * @file PanelOverlayRoot.tsx\n * @description The Panel Overlay root: provides the overlay contexts and draws the corner drop zones.\n */\nimport React, { useState, useRef, useCallback, useMemo, useEffect, useLayoutEffect, useContext } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { FloatAnchor } from '../WindowManagerContext';\nimport type { ManagedWidget, Stretch, ToolbarPosition } from './types';\nimport { PanelToolbarContext, PanelManagerContext, PanelOverlayContext } from './context';\nimport type { PanelOverlayCtx, PanelToolbarCtx, PanelManagerCtx, ManagedPlacement } from './context';\nimport { forgetPanelDom } from '../domPreservation';\nimport { setPreserveEmbeds } from '../domMove';\nimport { toPanelForm, fromPanelForm, parsePlacement } from '../../core/widgetPlacement';\nimport type { PanelBox, PanelForm, OutTarget } from '../../core/widgetPlacement';\nimport type { WidgetPlacement, WidgetTarget } from './types';\nimport { useOptionalWindowManagerState } from '../WindowManagerContext';\nimport { bucketsFor, ANCHORS } from '../../core/stretch';\nimport { ManagedFloatingWindow } from './FloatingWidget';\nimport { useWidgetHosting, useWidgetContainer } from './useWidgetHosting';\nimport type { WidgetHosting } from './useWidgetHosting';\nimport { WidgetContext } from './widgetContext';\nimport type { WidgetHandle } from './widgetContext';\nimport { ContextMenuContext } from '../ContextMenu';\nimport { initialFocusFor } from '../workspace/helpers';\n\n/** Where a managed widget starts: its config's corner, stretch and size, docked. */\nconst seedPlacement = (config: ManagedWidget): ManagedPlacement => ({\n anchor: config.anchor ?? 'top-right',\n stretch: config.stretch ?? null,\n mode: 'docked',\n freePos: null,\n size: { w: config.width ?? 320, h: config.height ?? 240 },\n});\n\n/** A saved out-of-panel target as a move; a floating rect is clamped into the workspace as it is now. */\nfunction targetOf(out: OutTarget, root: HTMLElement | null): WidgetTarget {\n if (out.at === 'tabbed') return { to: 'tabbed' };\n if (out.at === 'docked') return { to: 'docked', position: out.position, ...(out.size !== undefined ? { size: out.size } : {}) };\n const viewport = root?.closest('.rdd-workspace-viewport') as HTMLElement | null | undefined;\n const vw = viewport?.clientWidth ?? 0;\n const vh = viewport?.clientHeight ?? 0;\n const r = out.rect;\n if (vw <= 0 || vh <= 0) return { to: 'floating', rect: r };\n const width = Math.min(r.width, vw);\n const height = Math.min(r.height, vh);\n return { to: 'floating', rect: { x: Math.min(r.x, vw - width), y: Math.min(r.y, vh - height), width, height } };\n}\n\n// ─── PanelOverlayRoot ─────────────────────────────────────────────────────────\n\n/** Props for `<RddPanelOverlay>`. */\nexport interface RddPanelOverlayProps {\n children: React.ReactNode;\n className?: string;\n style?: React.CSSProperties;\n}\n\n/**\n * Context provider and layout root for the Panel Overlay system. Wrap your panel content\n * with this to enable `RddPanelToolbar`, `RddFloatingWidget`, and `useFloatingWidgets`.\n * @example\n * function MyPanel() {\n * return (\n * <RddPanelOverlay style={{ position: 'relative', width: '100%', height: '100%' }}>\n * <RddPanelToolbar position=\"top\">...</RddPanelToolbar>\n * <div className=\"my-panel-body\">content</div>\n * </RddPanelOverlay>\n * );\n * }\n */\nexport function PanelOverlayRoot({ children, className, style }: RddPanelOverlayProps): React.ReactElement {\n const [toolbarSizes, setToolbarSizes] = useState<Partial<Record<ToolbarPosition, number>>>({});\n const [zOrders, setZOrders] = useState<Record<string, number>>({});\n const [stacks, setStacks] = useState<Record<FloatAnchor, string[]>>({\n 'top-left': [], 'top-right': [], 'bottom-left': [], 'bottom-right': [],\n });\n const [dockedSizes, setDockedSizes] = useState<Record<string, number>>({});\n const [draggingId, setDraggingId] = useState<string | null>(null);\n const [hoveredZone, setHoveredZone] = useState<FloatAnchor | null>(null);\n const [topId, setTopId] = useState<string | null>(null);\n const [managedWindows, setManagedWindows] = useState<Map<string, ManagedWidget>>(() => new Map());\n // Where each managed widget sits and how big it is, owned here rather than inside its frame, so\n // the overlay always knows and the frame can unmount (vdd's and ndd's overlay stores keep the\n // same record). Seeded once per open from the config, then updated by gestures; closing drops\n // it, so close-then-open is the reset.\n const [managedPlacements, setManagedPlacements] = useState<Record<string, ManagedPlacement>>({});\n // Each managed widget's content element, `div.rdd-panel-float__content`. The content is rendered\n // into it once, for the widget's whole life, and the element is what moves: so its state, and\n // the DOM state of what it holds, survive whatever happens to the frame.\n // A stable Map, written only by open and close, never during render.\n const [contentEls] = useState(() => new Map<string, HTMLDivElement>());\n // The configs again, for code that must read them synchronously (moving a widget out).\n const configsRef = useRef(new Map<string, ManagedWidget>());\n const zCounterRef = useRef(100);\n const containerRef = useRef<HTMLDivElement>(null);\n // Set below; the hosting hook needs it before it exists (a user's close of a hosted panel).\n const closeWidgetRef = useRef<(id: string) => void>(() => {});\n const hosting = useWidgetHosting({ contentEls, configs: configsRef, containerRef, closeWidget: closeWidgetRef });\n const { release: releaseHosted, refresh: refreshHosted } = hosting;\n // move() and outTarget() change identity each render; open and placement() call the latest.\n const hostingRef = useRef(hosting);\n useEffect(() => { hostingRef.current = hosting; });\n const isRtl = useOptionalWindowManagerState(s => s.isRtl, false);\n const isRtlRef = useRef(isRtl);\n useEffect(() => { isRtlRef.current = isRtl; });\n // The store again, for placement(), which is called between renders.\n const placementsRef = useRef(managedPlacements);\n useEffect(() => { placementsRef.current = managedPlacements; });\n // Restored free positions waiting for the panel to have a size (a hidden panel measures 0×0).\n const pendingRef = useRef(new Map<string, PanelForm>());\n const [pendingCount, setPendingCount] = useState(0);\n /** The panel's size and direction now, or null while it has none. */\n const boxNow = (): PanelBox | null => {\n const el = containerRef.current;\n return el && el.clientWidth > 0 && el.clientHeight > 0\n ? { width: el.clientWidth, height: el.clientHeight, rtl: isRtlRef.current } : null;\n };\n // The context menu the title icon opens; none outside a provider, and then the icon stays decorative.\n const contextMenu = useContext(ContextMenuContext);\n\n const registerToolbar = useCallback((pos: ToolbarPosition, size: number): (() => void) => {\n setToolbarSizes(prev => ({ ...prev, [pos]: size }));\n return () => setToolbarSizes(prev => {\n const next = { ...prev };\n delete next[pos];\n return next;\n });\n }, []);\n\n const focusWindow = useCallback((id: string): void => {\n zCounterRef.current += 1;\n const z = zCounterRef.current;\n setZOrders(prev => ({ ...prev, [id]: z }));\n setTopId(id);\n }, []);\n\n const dockWindow = useCallback((id: string, anchor: FloatAnchor, stretch: Stretch | null = null): void => {\n const buckets = bucketsFor(anchor, stretch);\n setStacks(prev => {\n const next: Record<FloatAnchor, string[]> = {\n 'top-left': prev['top-left'].filter(x => x !== id),\n 'top-right': prev['top-right'].filter(x => x !== id),\n 'bottom-left': prev['bottom-left'].filter(x => x !== id),\n 'bottom-right': prev['bottom-right'].filter(x => x !== id),\n };\n for (const bucket of buckets) next[bucket] = [...next[bucket], id];\n // Re-registering identical membership would allocate fresh arrays on every placement effect\n // and churn every consumer of `stacks`, so bail out when nothing actually moved.\n const unchanged = ANCHORS.every(a =>\n next[a].length === prev[a].length && next[a].every((x, i) => x === prev[a][i]));\n return unchanged ? prev : next;\n });\n }, []);\n\n const undockWindow = useCallback((id: string): void => {\n setStacks(prev => ({\n 'top-left': prev['top-left'].filter(x => x !== id),\n 'top-right': prev['top-right'].filter(x => x !== id),\n 'bottom-left': prev['bottom-left'].filter(x => x !== id),\n 'bottom-right': prev['bottom-right'].filter(x => x !== id),\n }));\n }, []);\n\n const reportDockedSize = useCallback((id: string, size: number): void => {\n setDockedSizes(prev => {\n if (prev[id] === size) return prev;\n return { ...prev, [id]: size };\n });\n }, []);\n\n const openManaged = useCallback((id: string, config: ManagedWidget): void => {\n if (!contentEls.has(id)) {\n const el = (containerRef.current?.ownerDocument ?? document).createElement('div');\n el.className = 'rdd-panel-float__content';\n // The content is portalled into this element, so React events in it don't reach the frame:\n // bring the widget to the front natively, as a pointerdown anywhere in the frame does.\n el.addEventListener('pointerdown', () => focusWindow(id));\n contentEls.set(id, el);\n }\n const reopened = configsRef.current.has(id);\n configsRef.current.set(id, config);\n setPreserveEmbeds(contentEls.get(id)!, config.preserveEmbeds === true);\n if (config.preserveEmbeds) hostingRef.current.preserveOwner();\n if (reopened) refreshHosted(id, config);\n setManagedWindows(prev => {\n const next = new Map(prev);\n next.set(id, config);\n return next;\n });\n if (reopened) return; // a re-open of a live id refreshes its config, but leaves it where it is\n // A saved placement, read and applied to the panel as it is now; else the config's own.\n const saved = config.placement !== undefined ? parsePlacement(config.placement) : null;\n let seed = seedPlacement(config);\n if (saved?.home) {\n const { state, deferred } = fromPanelForm(saved.home, boxNow());\n seed = state;\n if (deferred) { pendingRef.current.set(id, saved.home); setPendingCount(c => c + 1); }\n }\n setManagedPlacements(prev => (id in prev ? prev : { ...prev, [id]: seed }));\n // Out of the panel, as saved. A refusal leaves it in the panel.\n if (saved?.out) hostingRef.current.move(id, targetOf(saved.out, containerRef.current));\n }, [contentEls, focusWindow, refreshHosted]);\n\n /** Drops a closed widget's content element; its content unmounts with the portal. */\n const forgetContentEl = useCallback((id: string): void => {\n const el = contentEls.get(id);\n if (!el) return;\n contentEls.delete(id);\n forgetPanelDom(el);\n el.remove();\n }, [contentEls]);\n\n const closeManaged = useCallback((id: string): void => {\n pendingRef.current.delete(id);\n releaseHosted(id);\n configsRef.current.delete(id);\n setManagedWindows(prev => {\n const next = new Map(prev);\n next.delete(id);\n return next;\n });\n setManagedPlacements(prev => {\n if (!(id in prev)) return prev;\n const next = { ...prev };\n delete next[id];\n return next;\n });\n forgetContentEl(id);\n }, [forgetContentEl, releaseHosted]);\n useEffect(() => { closeWidgetRef.current = closeManaged; });\n\n const closeAllManaged = useCallback((): void => {\n pendingRef.current.clear();\n Array.from(configsRef.current.keys()).forEach(releaseHosted);\n configsRef.current.clear();\n setManagedWindows(new Map());\n setManagedPlacements({});\n Array.from(contentEls.keys()).forEach(forgetContentEl);\n }, [contentEls, forgetContentEl, releaseHosted]);\n\n /**\n * A gesture's report. Ignored for a widget that is no longer open: a gesture can land after a\n * close, and writing then would leave a placement that the next open would wrongly reuse.\n */\n const updateManagedPlacement = useCallback(\n (id: string, patch: (prev: ManagedPlacement) => Partial<ManagedPlacement>): void => {\n setManagedPlacements(prev => (id in prev ? { ...prev, [id]: { ...prev[id], ...patch(prev[id]) } } : prev));\n }, []);\n\n /** Where a widget is, as JSON to save: see `WidgetPlacement`. */\n const placementOf = useCallback((id: string): WidgetPlacement | null => {\n if (!configsRef.current.has(id)) return null;\n const pending = pendingRef.current.get(id);\n const current = placementsRef.current[id];\n const home = pending ?? (current ? toPanelForm(current, boxNow()) : null);\n if (!home) return null;\n const out = hostingRef.current.outTarget(id);\n return (out ? { v: 1, home, ...out } : home) as unknown as WidgetPlacement;\n }, []);\n\n // Apply restored free positions once the panel has a size.\n useEffect(() => {\n if (pendingCount === 0) return;\n const apply = (): void => {\n const box = boxNow();\n if (!box || pendingRef.current.size === 0) return;\n for (const [id, form] of pendingRef.current) {\n const { state } = fromPanelForm(form, box);\n updateManagedPlacement(id, () => state);\n }\n pendingRef.current.clear();\n setPendingCount(0);\n };\n apply();\n const el = containerRef.current;\n if (!el || typeof ResizeObserver === 'undefined') return;\n const ro = new ResizeObserver(apply);\n ro.observe(el);\n return () => ro.disconnect();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingCount]);\n\n const managedWindowIds = useMemo(() => Array.from(managedWindows.keys()), [managedWindows]);\n\n const toolbarCtxValue = useMemo<PanelToolbarCtx>(() => ({\n registerToolbar,\n insetTop: toolbarSizes.top ?? 0,\n insetBottom: toolbarSizes.bottom ?? 0,\n }), [registerToolbar, toolbarSizes]);\n\n const managerCtxValue = useMemo<PanelManagerCtx>(() => ({\n managedWindowIds,\n openManaged,\n closeManaged,\n closeAllManaged,\n moveManaged: hosting.move,\n locationOf: hosting.location,\n placementOf,\n }), [managedWindowIds, openManaged, closeManaged, closeAllManaged, hosting.move, hosting.location, placementOf]);\n\n const coreCtxValue = useMemo<PanelOverlayCtx>(() => ({\n topId,\n zOrders,\n focusWindow,\n containerRef: containerRef as React.RefObject<HTMLDivElement>,\n stacks,\n dockedSizes,\n dockWindow,\n undockWindow,\n reportDockedSize,\n draggingId,\n setDraggingId,\n hoveredZone,\n setHoveredZone,\n insetTop: toolbarSizes.top ?? 0,\n insetBottom: toolbarSizes.bottom ?? 0,\n insetInlineStart: toolbarSizes.left ?? 0,\n insetInlineEnd: toolbarSizes.right ?? 0,\n }), [topId, zOrders, focusWindow, stacks, dockedSizes, dockWindow, undockWindow,\n reportDockedSize, draggingId, hoveredZone, toolbarSizes]);\n\n return (\n <PanelToolbarContext.Provider value={toolbarCtxValue}>\n <PanelManagerContext.Provider value={managerCtxValue}>\n <PanelOverlayContext.Provider value={coreCtxValue}>\n <div\n ref={containerRef}\n className={`rdd-panel-overlay-root${draggingId !== null ? ' rdd-dragging-active' : ''}${className ? ' ' + className : ''}`}\n style={style}\n >\n {children}\n {draggingId !== null && <DropZoneOverlay hoveredZone={hoveredZone} />}\n {Array.from(managedWindows.entries()).map(([id, cfg]) => {\n const placement = managedPlacements[id] ?? seedPlacement(cfg);\n const el = contentEls.get(id);\n if (!el) return null; // openManaged always sets it first; defensive only\n return (\n <React.Fragment key={id}>\n {createPortal(<WidgetScope id={id} hosting={hosting}>{cfg.content}</WidgetScope>, el)}\n {/* Out of the panel, a hosted panel shows the content and there is no frame. */}\n {!(id in hosting.hostedIds) && <ManagedFloatingWindow\n id={id}\n title={cfg.title}\n icon={cfg.icon}\n open={true}\n onClose={() => closeManaged(id)}\n controlled={{ placement, update: patch => updateManagedPlacement(id, patch) }}\n contentEl={el}\n onTitleMenu={cfg.titleMenu && contextMenu ? (e) => {\n const items = hosting.menuItems(id);\n if (items.length > 0) contextMenu.show({ event: e, items, initialFocus: initialFocusFor(e) });\n } : undefined}\n />}\n </React.Fragment>\n );\n })}\n </div>\n </PanelOverlayContext.Provider>\n </PanelManagerContext.Provider>\n </PanelToolbarContext.Provider>\n );\n}\n\n// ─── Internal: WidgetScope ────────────────────────────────────────────────────\n\n/**\n * Provides `useWidget()` to one managed widget's content, and calls its `onMoved` callbacks\n * whenever its element has landed in another container.\n */\nfunction WidgetScope({ id, hosting, children }: { id: string; hosting: WidgetHosting; children: React.ReactNode }): React.ReactElement {\n const { location, key } = useWidgetContainer(hosting.hostedIds[id], hosting.ownerPanelId ?? '');\n const { listen, settled, ownerPanelId } = hosting;\n const lastKey = useRef(key);\n useLayoutEffect(() => {\n if (lastKey.current === key) return;\n lastKey.current = key;\n settled(id);\n }, [key, id, settled]);\n const handle = useMemo<WidgetHandle>(() => ({\n id,\n ownerPanelId,\n location,\n onWillMove: cb => listen(id, 'will', cb),\n onMoved: cb => listen(id, 'moved', cb),\n }), [id, ownerPanelId, location, listen]);\n return <WidgetContext.Provider value={handle}>{children}</WidgetContext.Provider>;\n}\n\n// ─── Internal: DropZoneOverlay ────────────────────────────────────────────────\n\nfunction DropZoneOverlay({ hoveredZone }: { hoveredZone: FloatAnchor | null }): React.ReactElement {\n return (\n <>\n {ANCHORS.map(zone => (\n <div\n key={zone}\n className={`rdd-panel-float-dropzone rdd-panel-float-dropzone--${zone}${hoveredZone === zone ? ' rdd-panel-float-dropzone--hovered' : ''}`}\n aria-hidden=\"true\"\n />\n ))}\n </>\n );\n}\n","/**\n * @file context.ts\n * @description The Panel Overlay's internal React contexts, shared by the overlay root, the\n * toolbars and the floating widgets.\n */\nimport type React from 'react';\nimport { createContext } from 'react';\nimport type { FloatAnchor } from '../../types';\nimport type { ManagedWidget, MoveResult, PanelFloatPlacement, Stretch, ToolbarPosition, WidgetLocation, WidgetPlacement, WidgetTarget } from './types';\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\n/**\n * Everything about where a managed widget sits and how big it is: the public anchor and stretch,\n * plus whether it is docked or free, its free position and its size. Kept in the overlay's store\n * (`PanelOverlayRoot`), not in the frame, so it survives the frame unmounting: from 7.11 a widget\n * moved out of its panel has no frame, and coming back must find it where it was.\n */\nexport interface ManagedPlacement extends PanelFloatPlacement {\n mode: 'docked' | 'free';\n freePos: { x: number; y: number } | null;\n size: { w: number; h: number };\n}\n\n/** How a frame reads and writes a placement it doesn't own. `update` merges what it returns. */\nexport interface ControlledPlacement {\n placement: ManagedPlacement;\n update(patch: (prev: ManagedPlacement) => Partial<ManagedPlacement>): void;\n}\n\n// ─── Internal contexts ────────────────────────────────────────────────────────\n\nexport interface PanelToolbarCtx {\n registerToolbar(pos: ToolbarPosition, size: number): () => void;\n insetTop: number;\n insetBottom: number;\n}\nexport const PanelToolbarContext: React.Context<PanelToolbarCtx | null> = createContext<PanelToolbarCtx | null>(null);\n\nexport interface PanelManagerCtx {\n managedWindowIds: string[];\n openManaged(id: string, config: ManagedWidget): void;\n closeManaged(id: string): void;\n closeAllManaged(): void;\n moveManaged(id: string, to: WidgetTarget): MoveResult;\n locationOf(id: string): WidgetLocation | null;\n placementOf(id: string): WidgetPlacement | null;\n}\nexport const PanelManagerContext: React.Context<PanelManagerCtx | null> = createContext<PanelManagerCtx | null>(null);\n\nexport interface PanelOverlayCtx {\n topId: string | null;\n zOrders: Record<string, number>;\n focusWindow(id: string): void;\n containerRef: React.RefObject<HTMLDivElement>;\n stacks: Record<FloatAnchor, string[]>;\n dockedSizes: Record<string, number>;\n dockWindow(id: string, anchor: FloatAnchor, stretch?: Stretch | null): void;\n undockWindow(id: string): void;\n reportDockedSize(id: string, size: number): void;\n draggingId: string | null;\n setDraggingId(id: string | null): void;\n hoveredZone: FloatAnchor | null;\n setHoveredZone(zone: FloatAnchor | null): void;\n /** Block-axis space claimed by `PanelToolbar`s on the top/bottom edges. */\n insetTop: number;\n insetBottom: number;\n /**\n * Inline-axis space claimed by `PanelToolbar`s on the `left`/`right` edges. Logical, matching\n * how `PanelToolbar` positions itself (`insetInlineStart`/`insetInlineEnd`), so `left` means\n * inline-start regardless of direction. `registerToolbar` has always recorded these; they simply\n * weren't surfaced, so nothing could keep clear of a side toolbar the way the block axis does.\n */\n insetInlineStart: number;\n insetInlineEnd: number;\n}\nexport const PanelOverlayContext: React.Context<PanelOverlayCtx | null> = createContext<PanelOverlayCtx | null>(null);\n","/**\n * @file stretch.ts\n * @description Pure helpers for a docked widget's stretched axes and corner stacking.\n */\nimport type { FloatAnchor } from '../types';\nimport type { Stretch } from '../components/panelOverlay/types';\n\nexport const stretchesInline = (s: Stretch | null): boolean => s === 'width' || s === 'both';\nexport const stretchesBlock = (s: Stretch | null): boolean => s === 'height' || s === 'both';\n\n/** Adds one axis to a stretch value, keeping whatever was already stretched. */\nexport const addAxis = (s: Stretch | null, axis: 'inline' | 'block'): Stretch => {\n if (axis === 'inline') return stretchesBlock(s) ? 'both' : 'width';\n return stretchesInline(s) ? 'both' : 'height';\n};\n\n/** Drops one axis from a stretch value, keeping the other. */\nexport const releaseAxis = (s: Stretch | null, axis: 'inline' | 'block'): Stretch | null => {\n if (axis === 'inline') return s === 'both' ? 'height' : stretchesInline(s) ? null : s;\n return s === 'both' ? 'width' : stretchesBlock(s) ? null : s;\n};\n\n/**\n * Which stack buckets a placement occupies.\n *\n * The four corner buckets are really a proxy for *\"do these overlap on the inline axis?\"* — two\n * widgets in the same corner overlap and so stack; widgets in opposite corners sit side by side and\n * don't. A full-width strip overlaps everything on its edge, so it belongs to **both** buckets of\n * that edge and pushes the widgets in each. (Computing real inline overlap was rejected: widths\n * change continuously during a resize drag, so widgets would reshuffle mid-gesture.)\n *\n * A block-stretched widget spans the very axis stacking uses to separate siblings, so it can't\n * participate at all and occupies no bucket — z-order decides any overlap.\n */\nexport const bucketsFor = (anchor: FloatAnchor, stretch: Stretch | null): FloatAnchor[] => {\n if (stretchesBlock(stretch)) return [];\n if (stretchesInline(stretch)) {\n return anchor.startsWith('top-')\n ? ['top-left', 'top-right']\n : ['bottom-left', 'bottom-right'];\n }\n return [anchor];\n};\n\n/** Replaces one half of a corner anchor, leaving the other axis alone. */\nexport const withInlineHalf = (a: FloatAnchor, half: 'left' | 'right'): FloatAnchor =>\n `${a.startsWith('top-') ? 'top' : 'bottom'}-${half}` as FloatAnchor;\nexport const withBlockHalf = (a: FloatAnchor, half: 'top' | 'bottom'): FloatAnchor =>\n `${half}-${a.endsWith('-right') ? 'right' : 'left'}` as FloatAnchor;\n\nexport const ANCHORS: readonly FloatAnchor[] = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];\n","/**\n * @file panelOverlayGeometry.ts\n * @description Pure geometry of the Panel Overlay: the corner drop zones and a floating widget's\n * size, dock and snap distances.\n */\nimport type { FloatAnchor } from '../types';\n\n// ─── Helper ───────────────────────────────────────────────────────────────────\n\nexport const DROP_ZONE_SIZE = 80;\n\nexport function getHoveredZone(container: HTMLElement, clientX: number, clientY: number): FloatAnchor | null {\n const rect = container.getBoundingClientRect();\n const x = clientX - rect.left;\n const y = clientY - rect.top;\n if (x < DROP_ZONE_SIZE && y < DROP_ZONE_SIZE) return 'top-left';\n if (x > rect.width - DROP_ZONE_SIZE && y < DROP_ZONE_SIZE) return 'top-right';\n if (x < DROP_ZONE_SIZE && y > rect.height - DROP_ZONE_SIZE) return 'bottom-left';\n if (x > rect.width - DROP_ZONE_SIZE && y > rect.height - DROP_ZONE_SIZE) return 'bottom-right';\n return null;\n}\n\nexport const MIN_W = 120;\nexport const MIN_H = 60;\nexport const DOCK_INSET = 8;\nexport const DOCK_GAP = 8;\n/**\n * Resize-to-stretch snapping. Asymmetric on purpose: arming within `SNAP_IN` of the full extent\n * but only disarming once the drag pulls back past the wider `SNAP_OUT`. Without that hysteresis,\n * releasing a stretched axis by dragging a few pixels inward would immediately re-arm and snap\n * straight back on release, which makes the gesture feel broken.\n */\nexport const SNAP_IN = 16;\nexport const SNAP_OUT = 40;\n","/**\n * @file widgetPlacement.ts\n * @description A managed widget's saved placement (7.11.0): building it, reading it back, and\n * applying it to a panel of whatever size the panel has now. Pure; the overlay calls these.\n *\n * The value is opaque to apps (`WidgetPlacement = { v: 1 } & Record<string, unknown>`) and\n * identical in vdd and ndd, so a saved value moves between the libraries. Inside:\n * - in the panel: `{ v: 1, at: 'panel', anchor, stretch, mode, offset?, width, height }`. A free\n * position is an offset from the panel corner the widget was nearest, measured from the\n * inline-start or inline-end edge, so it stays put on a bigger or smaller panel and mirrors in RTL;\n * - out of it: `{ v: 1, at: 'docked' | 'tabbed' | 'floating', home, position?, size?, rect? }`, where\n * `home` is the panel form, where going back returns it.\n */\nimport type { FloatAnchor } from '../types';\nimport { ANCHORS } from './stretch';\nimport { MIN_W, MIN_H } from './panelOverlayGeometry';\n\ntype Stretch = 'width' | 'height' | 'both';\n\n/** Where a widget sits inside its panel, as the overlay's store holds it. */\nexport interface PanelPlacementState {\n anchor: FloatAnchor;\n stretch: Stretch | null;\n mode: 'docked' | 'free';\n freePos: { x: number; y: number } | null;\n size: { w: number; h: number };\n}\n\n/** The panel form of a saved placement. */\nexport interface PanelForm {\n v: 1;\n at: 'panel';\n anchor: FloatAnchor;\n stretch: Stretch | null;\n mode: 'docked' | 'free';\n offset?: { corner: FloatAnchor; inline: number; block: number };\n width: number;\n height: number;\n}\n\n/** Where outside the panel, as saved. */\nexport type OutTarget =\n | { at: 'docked'; position: 'left' | 'right' | 'top' | 'bottom'; size?: number }\n | { at: 'tabbed' }\n | { at: 'floating'; rect: { x: number; y: number; width: number; height: number } };\n\n/** The panel's size and direction: what a free position is measured against. */\nexport interface PanelBox { width: number; height: number; rtl: boolean }\n\nconst STRETCHES: readonly (Stretch | null)[] = [null, 'width', 'height', 'both'];\nconst POSITIONS = ['left', 'right', 'top', 'bottom'] as const;\nconst isNum = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n);\nconst isObj = (o: unknown): o is Record<string, unknown> => typeof o === 'object' && o !== null && !Array.isArray(o);\nconst clamp = (n: number, lo: number, hi: number): number => Math.min(Math.max(n, lo), Math.max(lo, hi));\nconst isAnchor = (a: unknown): a is FloatAnchor => ANCHORS.includes(a as FloatAnchor);\n\n/** The panel form of where a widget is in its panel. A free one needs the panel's box. */\nexport function toPanelForm(p: PanelPlacementState, box: PanelBox | null): PanelForm {\n const form: PanelForm = { v: 1, at: 'panel', anchor: p.anchor, stretch: p.stretch, mode: p.mode, width: p.size.w, height: p.size.h };\n if (p.mode === 'free' && p.freePos) {\n if (!box || box.width <= 0 || box.height <= 0) {\n // No box to measure against: keep the position as an offset from the top-left start.\n form.offset = { corner: 'top-left', inline: p.freePos.x, block: p.freePos.y };\n return form;\n }\n const { x, y } = p.freePos;\n const leftGap = x;\n const rightGap = box.width - x - p.size.w;\n const startGap = box.rtl ? rightGap : leftGap;\n const endGap = box.rtl ? leftGap : rightGap;\n const topGap = y;\n const bottomGap = box.height - y - p.size.h;\n const block = topGap <= bottomGap ? 'top' : 'bottom';\n const inline = startGap <= endGap ? 'left' : 'right'; // anchors are logical: 'left' is inline-start\n form.offset = {\n corner: `${block}-${inline}` as FloatAnchor,\n inline: Math.max(0, Math.round(inline === 'left' ? startGap : endGap)),\n block: Math.max(0, Math.round(block === 'top' ? topGap : bottomGap)),\n };\n }\n return form;\n}\n\n/**\n * A saved panel form back into store state, for a panel of this box, clamped into it. With no box\n * yet (a hidden panel measures 0×0) a free position can't be placed: `null` for `freePos` with\n * `deferred: true`, and the caller applies it again once the panel has a size.\n */\nexport function fromPanelForm(form: PanelForm, box: PanelBox | null): { state: PanelPlacementState; deferred: boolean } {\n const hasBox = !!box && box.width > 0 && box.height > 0;\n const w = hasBox ? clamp(form.width, MIN_W, box!.width) : Math.max(MIN_W, form.width);\n const h = hasBox ? clamp(form.height, MIN_H, box!.height) : Math.max(MIN_H, form.height);\n const base: PanelPlacementState = { anchor: form.anchor, stretch: form.stretch, mode: form.mode, freePos: null, size: { w, h } };\n if (form.mode !== 'free') return { state: base, deferred: false };\n // A free widget carries no stretch.\n base.stretch = null;\n if (!hasBox) return { state: { ...base, mode: 'docked' }, deferred: true };\n const o = form.offset ?? { corner: 'top-left' as FloatAnchor, inline: 0, block: 0 };\n const fromStart = o.corner.endsWith('-left');\n const startX = fromStart ? o.inline : box!.width - w - o.inline; // distance from inline-start\n const x = box!.rtl ? box!.width - w - startX : startX; // physical left\n const y = o.corner.startsWith('top-') ? o.block : box!.height - h - o.block;\n return {\n state: { ...base, freePos: { x: Math.round(clamp(x, 0, box!.width - w)), y: Math.round(clamp(y, 0, box!.height - h)) } },\n deferred: false,\n };\n}\n\nfunction parsePanelForm(raw: unknown): PanelForm | null {\n if (!isObj(raw) || raw.v !== 1) return null;\n if (!isAnchor(raw.anchor) || !STRETCHES.includes(raw.stretch as Stretch | null)) return null;\n if (raw.mode !== 'docked' && raw.mode !== 'free') return null;\n if (!isNum(raw.width) || !isNum(raw.height) || raw.width <= 0 || raw.height <= 0) return null;\n const form: PanelForm = { v: 1, at: 'panel', anchor: raw.anchor, stretch: raw.stretch as Stretch | null, mode: raw.mode, width: raw.width, height: raw.height };\n const o = raw.offset;\n if (isObj(o) && isAnchor(o.corner) && isNum(o.inline) && isNum(o.block)) {\n form.offset = { corner: o.corner, inline: Math.max(0, o.inline), block: Math.max(0, o.block) };\n }\n return form;\n}\n\n/**\n * Reads a value an app gave back. `home` is the panel form (or `null` when it is unusable: the\n * config's defaults apply); `out` is where to move it after opening, when the value says so and\n * that part is valid. An unknown `v`, or anything that isn't such a value, gives both `null`.\n */\nexport function parsePlacement(raw: unknown): { home: PanelForm | null; out: OutTarget | null } {\n if (!isObj(raw) || raw.v !== 1) return { home: null, out: null };\n if (raw.at === 'panel' || raw.at === undefined) return { home: parsePanelForm(raw), out: null };\n const home = parsePanelForm(raw.home);\n if (raw.at === 'tabbed') return { home, out: { at: 'tabbed' } };\n if (raw.at === 'docked' && POSITIONS.includes(raw.position as typeof POSITIONS[number])) {\n const size = isNum(raw.size) ? clamp(raw.size, 0.1, 0.9) : undefined;\n return { home, out: { at: 'docked', position: raw.position as typeof POSITIONS[number], ...(size !== undefined ? { size } : {}) } };\n }\n const r = raw.rect;\n if (raw.at === 'floating' && isObj(r) && isNum(r.x) && isNum(r.y) && isNum(r.width) && isNum(r.height) && r.width > 0 && r.height > 0) {\n return { home, out: { at: 'floating', rect: { x: Math.max(0, r.x), y: Math.max(0, r.y), width: Math.max(MIN_W, r.width), height: Math.max(MIN_H, r.height) } } };\n }\n return { home, out: null };\n}\n","/**\n * @file FloatingWidget.tsx\n * @description A floating widget inside a panel: docked to a corner or free, stretchable, resizable.\n */\nimport React, { useState, useContext, useRef, useLayoutEffect, useInsertionEffect, useCallback, useEffect } from 'react';\nimport { useOptionalWindowManagerState, formatLabel, useFormatMessage, usePredefinedMessages } from '../WindowManagerContext';\nimport type { FloatAnchor } from '../WindowManagerContext';\nimport type { PanelTitle } from '../PanelProviderContext';\nimport { flipZoneHorizontal } from '../anchorGeometry';\nimport { startPointerDrag, computeResizedRect } from '../dragResize';\nimport type { ResizeDir } from '../dragResize';\nimport type { PanelFloatPlacement, Stretch } from './types';\nimport { PanelOverlayContext } from './context';\nimport type { PanelOverlayCtx, ManagedPlacement, ControlledPlacement } from './context';\nimport { stretchesInline, stretchesBlock, addAxis, releaseAxis, bucketsFor, withInlineHalf, withBlockHalf } from '../../core/stretch';\nimport { getHoveredZone, MIN_W, MIN_H, DOCK_INSET, DOCK_GAP, SNAP_IN, SNAP_OUT } from '../../core/panelOverlayGeometry';\nimport { useLatestRef } from '../../utils/useLatestRef';\nimport { trackPanelDom, restorePanelDom } from '../domPreservation';\nimport { moveIntoWhenConnected, leaveSlot } from '../domMove';\n\n// ─── PanelFloatingWindow ──────────────────────────────────────────────────────\n\n/** Props for `<RddFloatingWidget>`. */\nexport interface RddFloatingWidgetProps {\n /** Unique identifier within the panel overlay. Used for z-order and stack tracking. */\n id: string;\n /** Text shown in the window's header bar. Accepts a plain string or an i18n message descriptor. */\n title: PanelTitle;\n /** Optional icon shown to the left of the title in the header. */\n icon?: React.ReactNode;\n /** Whether the window is mounted and visible. Set to `false` to close/unmount it. */\n open: boolean;\n /** Called when the user clicks the × button. Set `open` to `false` in response. */\n onClose(): void;\n /** Corner of the panel to dock to on first render. @see FloatAnchor */\n defaultAnchor: FloatAnchor;\n /** Initial width in pixels. Ignored on an axis that starts stretched, and restored to when that\n * axis is later released. */\n defaultWidth: number;\n /** Initial height in pixels. Ignored on an axis that starts stretched, and restored to when that\n * axis is later released. */\n defaultHeight: number;\n /**\n * Which axes span the panel on first render. Uncontrolled: gestures update it from here.\n * @see Stretch\n */\n defaultStretch?: Stretch;\n /**\n * Controlled stretch state. When provided — **including as `null`** — the caller is the single\n * source of truth: gestures report through {@link RddFloatingWidgetProps.onPlacementChange}\n * instead of updating internally, and the caller must echo the new value back. Omit entirely\n * (`undefined`) for uncontrolled behaviour, matching `ToolbarToggleItem.active` and\n * `Sidebar.activeTabId`.\n */\n stretch?: Stretch | null;\n /**\n * Called whenever a gesture changes where the widget sits — a stretched axis released, a\n * re-dock, or a detach. Reports anchor and stretch **together**, because one gesture can change\n * both at once and reporting them separately would surface a state that is never valid.\n *\n * This is also the only way to persist placement: the library serialises nothing about inner\n * widgets, so store what you receive here and feed it back via `defaultAnchor`/`stretch`.\n */\n onPlacementChange?: (placement: PanelFloatPlacement) => void;\n /**\n * Whether this widget may span the panel at all. `false` disables resize-to-stretch snapping,\n * for content that only makes sense at a bounded size. Default `true`.\n */\n stretchable?: boolean;\n children?: React.ReactNode;\n}\n\n/**\n * A floating widget inside a panel — anchored within an `RddPanelOverlay`.\n *\n * Docks to any corner, drags free of it, and drops back onto one. Windows sharing a corner stack\n * along the block axis with animated offsets. An axis can also **span the panel** instead of\n * carrying a fixed size, so the window tracks the panel as it resizes — see\n * {@link RddFloatingWidgetProps.defaultStretch} and {@link Stretch}.\n *\n * Resize handles follow what is actually movable: a free-floating window is pinned by nothing and\n * offers all eight, while a docked one offers only its free edges — plus both ends of any spanning\n * axis, either of which releases it.\n *\n * @example\n * const [infoOpen, setInfoOpen] = useState(false);\n * <RddFloatingWidget\n * id=\"layer-info\" title=\"Layer Info\"\n * open={infoOpen} onClose={() => setInfoOpen(false)}\n * defaultAnchor=\"top-right\" defaultWidth={300} defaultHeight={200}\n * >\n * <LayerInfoContent />\n * </RddFloatingWidget>\n *\n * @example\n * // A full-width status strip along the bottom, tracking the panel's width.\n * // defaultHeight still applies; defaultWidth is what the inline axis returns to if released.\n * <RddFloatingWidget\n * id=\"timeline\" title=\"Timeline\"\n * open onClose={close}\n * defaultAnchor=\"bottom-left\" defaultStretch=\"width\"\n * defaultWidth={240} defaultHeight={120}\n * >\n * <TimelineContent />\n * </RddFloatingWidget>\n */\nexport function PanelFloatingWindow(props: RddFloatingWidgetProps): React.ReactElement | null {\n const ctx = useContext(PanelOverlayContext);\n if (!props.open) return null;\n // The internal props are set last, so no stray prop on the public component can turn them on.\n return <FloatingWindowBody key={props.id} ctx={ctx} {...props} controlled={undefined} contentEl={undefined} onTitleMenu={undefined} />;\n}\n\n/**\n * @internal A managed widget (`useFloatingWidgets().open()`). Its whole placement (anchor,\n * stretch, docked or free, position, size) is owned by the overlay's store (`PanelOverlayRoot`),\n * as in vdd and ndd, so it survives this frame unmounting. Its content is rendered once by the\n * overlay into `contentEl`, which the frame only shows. Not exported from the package.\n */\nexport function ManagedFloatingWindow(\n props: Omit<RddFloatingWidgetProps, 'defaultAnchor' | 'defaultWidth' | 'defaultHeight' | 'children'>\n & { controlled: ControlledPlacement; contentEl: HTMLElement; onTitleMenu: ((e: React.MouseEvent) => void) | undefined },\n): React.ReactElement | null {\n const ctx = useContext(PanelOverlayContext);\n if (!props.open) return null;\n const { placement } = props.controlled;\n return (\n <FloatingWindowBody\n key={props.id} ctx={ctx} {...props}\n defaultAnchor={placement.anchor} defaultWidth={placement.size.w} defaultHeight={placement.size.h}\n />\n );\n}\n\n// ─── Internal: FloatingWindowBody ─────────────────────────────────────────────\n\ninterface FloatingWindowBodyProps extends RddFloatingWidgetProps {\n ctx: PanelOverlayCtx | null;\n /** The overlay's placement, used only by `ManagedFloatingWindow`. `undefined` keeps it internal. */\n controlled: ControlledPlacement | undefined;\n /** Content the overlay renders elsewhere; the body shows this element instead of `children`. */\n contentEl: HTMLElement | undefined;\n /** A managed widget's `titleMenu`: when set, the title icon is a button that opens it. */\n onTitleMenu: ((e: React.MouseEvent) => void) | undefined;\n}\n\ntype WindowMode = ManagedPlacement['mode'];\ntype FieldSetter<T> = (next: T | ((prev: T) => T)) => void;\n\n/**\n * One field of the placement: the frame's own state, or the overlay's when `controlled`. The\n * setter takes a value or an updater, like `useState`'s, so the drag code reads the same either way.\n */\nfunction usePlacementField<K extends keyof ManagedPlacement>(\n controlled: ControlledPlacement | undefined, key: K, initial: ManagedPlacement[K],\n): [ManagedPlacement[K], FieldSetter<ManagedPlacement[K]>] {\n const [internal, setInternal] = useState<ManagedPlacement[K]>(initial);\n const updateRef = useLatestRef(controlled?.update);\n const isControlled = controlled !== undefined;\n const set = useCallback<FieldSetter<ManagedPlacement[K]>>((next) => {\n if (!isControlled) { setInternal(next); return; }\n // None of the fields is a function, so a function here is always an updater.\n updateRef.current?.(prev => ({\n [key]: typeof next === 'function' ? (next as (p: ManagedPlacement[K]) => ManagedPlacement[K])(prev[key]) : next,\n }) as Partial<ManagedPlacement>);\n }, [isControlled, key, updateRef]);\n return [isControlled ? controlled.placement[key] : internal, set];\n}\n\n\nfunction FloatingWindowBody({ id, title, icon, defaultAnchor, defaultWidth, defaultHeight, defaultStretch, stretch: stretchProp, onPlacementChange, stretchable = true, children, ctx, onClose, controlled, contentEl, onTitleMenu }: FloatingWindowBodyProps): React.ReactElement {\n const isRtl = useOptionalWindowManagerState(s => s.isRtl, false);\n // Resolved here rather than at the call site, so a descriptor title re-resolves whenever the\n // formatter changes. Both hooks fall back to the message's own `defaultMessage` when there is no\n // provider, so an overlay used outside a WindowManager keeps working.\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n // Each field is the frame's own state, except for a managed widget, whose overlay owns them all.\n const [mode, setMode] = usePlacementField(controlled, 'mode', 'docked' as WindowMode);\n const [currentAnchor, setAnchor] = usePlacementField(controlled, 'anchor', defaultAnchor);\n // `size` is deliberately left untouched while an axis is stretched — the render branch below\n // simply stops reading it, exactly as a maximized workspace window keeps its x/y/w/h. Releasing\n // the axis therefore restores the previous size with no snapshot and no bookkeeping.\n const [ownStretch, setOwnStretch] = usePlacementField(controlled, 'stretch', defaultStretch ?? null);\n // Controlled by the caller when the prop is present at all — `null` is a meaningful value (\"not\n // stretched\"), so only `undefined` means \"manage it yourself\". Never for a managed widget.\n const isStretchControlled = stretchProp !== undefined && controlled === undefined;\n const stretch = isStretchControlled ? (stretchProp ?? null) : ownStretch;\n const [freePos, setFreePos] = usePlacementField(controlled, 'freePos', null);\n const [size, setSize] = usePlacementField(controlled, 'size', { w: defaultWidth, h: defaultHeight });\n const windowRef = useRef<HTMLDivElement>(null);\n\n // Refs to avoid stale closures in pointer handlers\n const modeRef = useLatestRef(mode);\n const freePosRef = useLatestRef(freePos);\n const sizeRef = useLatestRef(size);\n const stretchRef = useLatestRef(stretch);\n const currentAnchorRef = useLatestRef(currentAnchor);\n const onPlacementChangeRef = useLatestRef(onPlacementChange);\n /** Which axes would snap to stretched if the drag were released now — drives the visual cue. */\n const [snapArmed, setSnapArmed] = useState<{ inline: boolean; block: boolean }>({ inline: false, block: false });\n const snapArmedRef = useLatestRef(snapArmed);\n /** The block extent available to this widget depends on what it is stacked behind. */\n const stackOffsetRef = useRef(0);\n\n /**\n * The single write path for anchor and stretch. Stretch is written here only when the caller\n * doesn't control it. Either way the pair is reported once, so a listener never observes a\n * half-applied transition.\n */\n const applyPlacement = useCallback((anchor: FloatAnchor, next: Stretch | null): void => {\n setAnchor(anchor);\n if (!isStretchControlled) setOwnStretch(next);\n onPlacementChangeRef.current?.({ anchor, stretch: next });\n }, [setAnchor, setOwnStretch, isStretchControlled, onPlacementChangeRef]);\n\n const dragState = useRef<{ mouseX: number; mouseY: number; posX: number; posY: number; hasDragged: boolean } | null>(null);\n\n // Bucket membership depends on the whole placement (see bucketsFor), so this re-runs whenever\n // the anchor or a stretched axis changes — not only on mount. Free-floating widgets are in no\n // stack at all.\n useLayoutEffect(() => {\n if (mode !== 'docked') return;\n ctx?.dockWindow(id, currentAnchor, stretch);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mode, currentAnchor, stretch]);\n\n // Leave the stack on unmount (close). Closing resets to the defaults on the next open, since a\n // fresh mount means fresh state.\n useLayoutEffect(() => () => { ctx?.undockWindow(id); },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []);\n\n // Dev-only: a block-stretched widget spans the whole block axis, so it cannot stack with\n // anything — it will simply overlap siblings on its own inline side, with z-order deciding.\n // Warns once per widget, matching the warning conventions in Sidebar/WindowManager.\n const blockStretchWarnedRef = useRef(false);\n useEffect(() => {\n if (process.env.NODE_ENV !== 'development') return;\n if (blockStretchWarnedRef.current) return;\n if (mode !== 'docked' || !stretchesBlock(stretch) || !ctx) return;\n const half = currentAnchor.endsWith('-right') ? 'right' : 'left';\n const neighbours = ([`top-${half}`, `bottom-${half}`] as FloatAnchor[])\n .flatMap(bucket => ctx.stacks[bucket] ?? [])\n .filter(other => other !== id);\n if (neighbours.length === 0) return;\n blockStretchWarnedRef.current = true;\n console.warn(\n `[react-dockable-desktop] RddFloatingWidget \"${id}\" stretches the block axis ` +\n `(stretch: \"${stretch}\") while ${neighbours.length} other widget(s) are anchored to the ` +\n `same side (${neighbours.join(', ')}). A block-stretched widget spans the axis that stacking ` +\n `uses to separate siblings, so it cannot stack and will overlap them — z-order decides which ` +\n `is on top. Either give it a fixed height, or move the other widgets to the opposite side.`\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mode, stretch, currentAnchor, ctx?.stacks, id]);\n\n // Report height whenever size changes so stack peers can compute their offset.\n useEffect(() => {\n ctx?.reportDockedSize(id, size.h);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [size.h]);\n\n const zOrder = ctx?.zOrders[id] ?? 101;\n\n const isActive = !ctx || ctx.topId === id;\n\n const getContainerBounds = (): { cw: number; ch: number } => {\n const container = windowRef.current?.offsetParent as HTMLElement | null;\n return { cw: container?.clientWidth ?? 9999, ch: container?.clientHeight ?? 9999 };\n };\n\n /**\n * The band a docked widget is allowed to occupy, in physical pixels from the container's edges.\n *\n * The block axis keeps clear of top/bottom `PanelToolbar`s only; the inline axis also adds the\n * `DOCK_INSET` gutter, matching how a docked widget is already positioned (one inline inset of\n * `DOCK_INSET`, one block inset of the toolbar size). Growth previously stopped at the raw\n * container edge, so a docked widget could be resized straight over the toolbar on the far side —\n * which the library elsewhere treats as a bug (a 5.x fix stopped docked floats *positioning*\n * themselves over a toolbar; the resize path never got the same treatment).\n *\n * Inline is converted from logical to physical here because handle directions and measured rects\n * are physical, while `PanelToolbar` claims its space logically.\n */\n const dockedBand = (): { left: number; right: number; top: number; bottom: number } => {\n const logicalStart = ctx?.insetInlineStart ?? 0;\n const logicalEnd = ctx?.insetInlineEnd ?? 0;\n return {\n left: (isRtl ? logicalEnd : logicalStart) + DOCK_INSET,\n right: (isRtl ? logicalStart : logicalEnd) + DOCK_INSET,\n top: ctx?.insetTop ?? 0,\n bottom: ctx?.insetBottom ?? 0,\n };\n };\n\n const handleWindowPointerDown = (): void => {\n ctx?.focusWindow(id);\n };\n\n const handleHeaderPointerDown = (e: React.PointerEvent<HTMLDivElement>): void => {\n if (e.button !== 0) return;\n e.preventDefault();\n\n let startX: number;\n let startY: number;\n\n if (modeRef.current === 'docked') {\n // Snapshot the rendered position so that *if* this becomes a real drag, switching to free\n // positioning causes no visual jump. Undocking itself is deferred to the drag threshold\n // below — doing it here meant a plain click on the header silently tore the widget off its\n // anchor: it looked unchanged, but its stacked siblings reflowed to close the gap and it\n // stopped tracking the corner on every later panel resize.\n const el = windowRef.current;\n const container = ctx?.containerRef?.current;\n if (el && container) {\n const elRect = el.getBoundingClientRect();\n const cRect = container.getBoundingClientRect();\n startX = elRect.left - cRect.left;\n startY = elRect.top - cRect.top;\n } else {\n startX = DOCK_INSET;\n startY = ctx?.insetTop ?? 0;\n }\n } else {\n startX = freePosRef.current?.x ?? 0;\n startY = freePosRef.current?.y ?? 0;\n }\n\n dragState.current = { mouseX: e.clientX, mouseY: e.clientY, posX: startX, posY: startY, hasDragged: false };\n windowRef.current?.setPointerCapture(e.pointerId);\n };\n\n const handleResizePointerDown = (dir: ResizeDir) => (e: React.PointerEvent<HTMLDivElement>): void => {\n if (e.button !== 0) return;\n e.preventDefault();\n e.stopPropagation();\n // Snapshot current rendered position for offset-from-edge calculations\n let startX = 0, startY = 0;\n if (modeRef.current === 'free') {\n startX = freePosRef.current?.x ?? 0;\n startY = freePosRef.current?.y ?? 0;\n } else {\n const el = windowRef.current;\n const container = el?.offsetParent as HTMLElement | null;\n if (el && container) {\n const er = el.getBoundingClientRect();\n const cr = container.getBoundingClientRect();\n startX = er.left - cr.left;\n startY = er.top - cr.top;\n }\n }\n // For a stretched axis the stored size is stale by design (the render branch stops reading it),\n // so the drag has to start from the *measured* extent or the widget would jump.\n const measured = windowRef.current?.getBoundingClientRect();\n const startRect = {\n x: startX,\n y: startY,\n w: stretchesInline(stretchRef.current) && measured ? measured.width : sizeRef.current.w,\n h: stretchesBlock(stretchRef.current) && measured ? measured.height : sizeRef.current.h,\n };\n\n // Dragging an end of a stretched axis releases that axis: the edge under the pointer becomes\n // the moving one and the opposite end becomes the new pin, so it reads exactly like an ordinary\n // resize. Done once per drag; `released` guards against repeat moves before the re-render.\n const dragsInline = dir.includes('e') || dir.includes('w');\n const dragsBlock = dir.includes('n') || dir.includes('s');\n let released = false;\n let armed = { inline: false, block: false };\n const releaseIfNeeded = (): void => {\n if (released || modeRef.current !== 'docked') return;\n const st = stretchRef.current;\n const releasingInline = dragsInline && stretchesInline(st);\n const releasingBlock = dragsBlock && stretchesBlock(st);\n if (!releasingInline && !releasingBlock) return;\n released = true;\n\n let next = st;\n let nextAnchor = currentAnchorRef.current;\n if (releasingInline) {\n next = releaseAxis(next, 'inline');\n // Pin the end opposite the dragged edge. Handle dirs are physical, anchors are logical.\n const pinsPhysicalLeft = dir.includes('e');\n nextAnchor = withInlineHalf(nextAnchor, (pinsPhysicalLeft !== isRtl) ? 'left' : 'right');\n }\n if (releasingBlock) {\n next = releaseAxis(next, 'block');\n nextAnchor = withBlockHalf(nextAnchor, dir.includes('s') ? 'top' : 'bottom');\n }\n applyPlacement(nextAnchor, next);\n };\n\n startPointerDrag({\n element: e.currentTarget,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n startClientY: e.clientY,\n captureStart: () => startRect,\n activeClasses: [{ el: document.body, classes: ['rdd-resizing-active'] }],\n onMove: (dx, dy, start) => {\n // Re-measured every move, matching the original's live re-measurement —\n // the container can in principle change size during a drag.\n const { cw, ch } = getContainerBounds();\n // Docked widgets stop at the toolbar band; free-floating ones stay unconstrained beyond the\n // container itself, since \"free\" means free.\n const band = modeRef.current === 'docked'\n ? dockedBand()\n : { left: 0, right: 0, top: 0, bottom: 0 };\n const { x: newX, y: newY, w: newW, h: newH } = computeResizedRect(dir, dx, dy, start, {\n minW: MIN_W, minH: MIN_H,\n maxW: (cw - band.right) - start.x, maxH: (ch - band.bottom) - start.y,\n minX: band.left, minY: band.top,\n });\n releaseIfNeeded();\n\n // ── resize-to-stretch snapping ──\n // The clamps above already stop growth exactly where a stretched axis would sit, so an\n // armed drag is already visually at its target; the cue is an outline rather than a ghost.\n if (modeRef.current === 'docked' && stretchable) {\n const fullInline = cw - band.left - band.right;\n const fullBlock = ch - band.top - band.bottom - stackOffsetRef.current;\n const st = stretchRef.current;\n const nextArmed = { ...armed };\n if (dragsInline && !stretchesInline(st)) {\n if (newW >= fullInline - SNAP_IN) nextArmed.inline = true;\n else if (armed.inline && newW < fullInline - SNAP_OUT) nextArmed.inline = false;\n }\n if (dragsBlock && !stretchesBlock(st)) {\n if (newH >= fullBlock - SNAP_IN) nextArmed.block = true;\n else if (armed.block && newH < fullBlock - SNAP_OUT) nextArmed.block = false;\n }\n if (nextArmed.inline !== armed.inline || nextArmed.block !== armed.block) {\n armed = nextArmed;\n setSnapArmed(nextArmed);\n }\n }\n // Only write an axis that carries a size. A still-stretched axis must keep its stored\n // value, so releasing it later restores the size it had before stretching.\n const st = released ? releaseAxis(releaseAxis(stretchRef.current,\n dragsInline ? 'inline' : 'block'), dragsBlock ? 'block' : 'inline') : stretchRef.current;\n setSize(prev => ({\n w: stretchesInline(st) ? prev.w : newW,\n h: stretchesBlock(st) ? prev.h : newH,\n }));\n if (modeRef.current === 'free') {\n setFreePos({ x: newX, y: newY });\n }\n },\n onEnd: (start) => {\n if (!armed.inline && !armed.block) {\n if (snapArmedRef.current.inline || snapArmedRef.current.block) {\n setSnapArmed({ inline: false, block: false });\n }\n return;\n }\n // Restore the size the axis had *before* this drag: while an axis is stretched its stored\n // size is what releasing it later returns to, so it should be the size the user last chose\n // deliberately — not the full-bleed value the drag happened to pass through.\n setSize(prev => ({\n w: armed.inline ? start.w : prev.w,\n h: armed.block ? start.h : prev.h,\n }));\n let next = stretchRef.current;\n if (armed.inline) next = addAxis(next, 'inline');\n if (armed.block) next = addAxis(next, 'block');\n applyPlacement(currentAnchorRef.current, next);\n setSnapArmed({ inline: false, block: false });\n },\n });\n };\n\n const handleWindowPointerMove = (e: React.PointerEvent): void => {\n if (dragState.current) {\n const ds = dragState.current;\n if (!ds.hasDragged) {\n const dist = Math.abs(e.clientX - ds.mouseX) + Math.abs(e.clientY - ds.mouseY);\n if (dist < 4) return;\n ds.hasDragged = true;\n // This, not pointerdown, is the moment the widget leaves its anchor.\n if (modeRef.current === 'docked') {\n // A stretched axis carries no size, so free mode — which positions from an explicit box —\n // would otherwise snap back to whatever the size was before stretching. Materialise what\n // is actually on screen, then clear stretch: \"free\" and \"spanning the panel\" are\n // mutually exclusive.\n if (stretchRef.current) {\n const r = windowRef.current?.getBoundingClientRect();\n if (r) setSize({ w: Math.round(r.width), h: Math.round(r.height) });\n applyPlacement(currentAnchorRef.current, null);\n }\n ctx?.undockWindow(id);\n setMode('free');\n }\n document.body.classList.add('rdd-dragging-active');\n ctx?.setDraggingId(id);\n }\n const { cw, ch } = getContainerBounds();\n const newX = Math.max(0, Math.min(ds.posX + e.clientX - ds.mouseX, cw - sizeRef.current.w));\n const newY = Math.max(0, Math.min(ds.posY + e.clientY - ds.mouseY, ch - sizeRef.current.h));\n setFreePos({ x: newX, y: newY });\n\n const container = ctx?.containerRef?.current;\n if (container) {\n const rawZone = getHoveredZone(container, e.clientX, e.clientY);\n ctx?.setHoveredZone(rawZone && isRtl ? flipZoneHorizontal(rawZone) : rawZone);\n }\n }\n };\n\n const handleWindowPointerUp = (): void => {\n if (dragState.current?.hasDragged) {\n const zone = ctx?.hoveredZone;\n if (zone) {\n ctx?.dockWindow(id, zone, stretchRef.current);\n setMode('docked');\n setFreePos(null);\n applyPlacement(zone, stretchRef.current);\n }\n ctx?.setHoveredZone(null);\n ctx?.setDraggingId(null);\n }\n document.body.classList.remove('rdd-dragging-active');\n dragState.current = null;\n };\n\n const handleWindowPointerCancel = (): void => {\n if (dragState.current?.hasDragged) {\n ctx?.setHoveredZone(null);\n ctx?.setDraggingId(null);\n }\n document.body.classList.remove('rdd-dragging-active');\n dragState.current = null;\n };\n\n // ── Compute position style ─────────────────────────────────────────────────\n let windowStyle: React.CSSProperties;\n\n // This render's stack offset while docked, for the drag handlers (see stackOffsetRef). Left\n // null in free mode, where the ref keeps its last docked value, as before.\n let dockedStackOffset: number | null = null;\n if (mode === 'docked' && ctx) {\n // Offset is the largest offset across every bucket this widget occupies, so a strip spanning\n // an edge clears whatever is stacked in *both* of that edge's corners.\n const buckets = bucketsFor(currentAnchor, stretch);\n let stackOffset = 0;\n // A widget with no buckets (block-stretched) is never \"in\" a stack, so it must not be held\n // invisible by the not-yet-registered guard below.\n let registered = buckets.length === 0;\n for (const bucket of buckets) {\n const stack = ctx.stacks[bucket] ?? [];\n const idx = stack.indexOf(id);\n if (idx === -1) continue;\n registered = true;\n let offset = 0;\n for (let i = 0; i < idx; i++) {\n offset += (ctx.dockedSizes[stack[i]] ?? defaultHeight) + DOCK_GAP;\n }\n stackOffset = Math.max(stackOffset, offset);\n }\n dockedStackOffset = stackOffset;\n\n const band = dockedBand();\n\n windowStyle = {\n zIndex: zOrder,\n transition: 'top 0.2s ease, bottom 0.2s ease',\n // Hide until registered in stack (first layout effect hasn't run yet)\n opacity: registered ? undefined : 0,\n pointerEvents: registered ? undefined : 'none',\n };\n\n // Inline axis: one inset plus an explicit width, or both insets and no width at all. Setting\n // both ends is the whole mechanism — CSS then keeps the widget spanning the panel for free.\n if (stretchesInline(stretch)) {\n windowStyle.insetInlineStart = (ctx.insetInlineStart ?? 0) + DOCK_INSET;\n windowStyle.insetInlineEnd = (ctx.insetInlineEnd ?? 0) + DOCK_INSET;\n } else {\n windowStyle[currentAnchor.endsWith('-right') ? 'insetInlineEnd' : 'insetInlineStart'] = DOCK_INSET;\n windowStyle.width = size.w;\n }\n\n // Block axis: same idea. Note the block insets carry no DOCK_INSET gutter, matching how a\n // docked widget has always been positioned against a top/bottom toolbar (flush, not inset).\n if (stretchesBlock(stretch)) {\n windowStyle.top = band.top;\n windowStyle.bottom = band.bottom;\n } else if (currentAnchor.startsWith('top-')) {\n windowStyle.top = band.top + stackOffset;\n windowStyle.height = size.h;\n } else {\n windowStyle.bottom = band.bottom + stackOffset;\n windowStyle.height = size.h;\n }\n } else {\n windowStyle = {\n left: freePos?.x ?? 0,\n top: freePos?.y ?? 0,\n width: size.w,\n height: size.h,\n zIndex: zOrder,\n };\n }\n useInsertionEffect(() => {\n if (dockedStackOffset !== null) stackOffsetRef.current = dockedStackOffset;\n });\n\n // ── Which resize handles this window offers ────────────────────────────────\n // Free-floating: all eight, nothing is pinned.\n //\n // Docked: only the edges that can actually move. A docked window has one edge pinned per axis\n // (see the positioning block above — `top-*` pins `top`, `bottom-*` pins `bottom`, `*-left`\n // pins `insetInlineStart`, `*-right` pins `insetInlineEnd`), so dragging a handle on a pinned\n // side moves the *opposite* edge instead of the one under the cursor, and can't move it further\n // than that side's own inset before `computeResizedRect`'s bounds stop it — an inert stub with a\n // resize cursor on it. The handle set used to be hardcoded to the five non-northern directions\n // regardless of anchor, which made that harmless-looking for top anchors but left every\n // bottom-anchored window with no working vertical resize at all: `n` wasn't rendered, and `s`\n // was the stub.\n //\n // Restricting docked mode to free edges also means the existing resize bounds are already\n // correct for every direction that remains: `maxW`/`maxH` apply only to eastward/southward\n // growth (where the top-left origin genuinely is pinned), while `minX`/`minY` bound the moving\n // edge for westward/northward growth — so no change to the resize math is needed.\n const handleDirs: ResizeDir[] = React.useMemo(() => {\n if (mode === 'free') return ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'];\n\n // Block axis is direction-agnostic; the inline axis is not. The pin is a logical property\n // (`insetInlineEnd`) but the handle classes are physical (`.rdd-resize-e { right: -4px }`), so\n // which *physical* side is pinned depends on the window's own `dir`.\n const freeBlock: ResizeDir = currentAnchor.startsWith('top-') ? 's' : 'n';\n const pinsPhysicalRight = currentAnchor.endsWith('-right') !== isRtl;\n const freeInline: ResizeDir = pinsPhysicalRight ? 'w' : 'e';\n\n const inlineStretched = stretchesInline(stretch);\n const blockStretched = stretchesBlock(stretch);\n\n // A stretched axis has both ends pinned, but both are *releasable*: dragging either end moves\n // that edge and pins the opposite one, so the widget leaves stretch at the width the drag\n // produced. Hence handles on both ends — which is also what keeps the fully-stretched state\n // from being a dead end with nothing to grab.\n const dirs: ResizeDir[] = [];\n dirs.push(...(inlineStretched ? (['e', 'w'] as ResizeDir[]) : [freeInline]));\n dirs.push(...(blockStretched ? (['n', 's'] as ResizeDir[]) : [freeBlock]));\n // The corner belongs only to the all-pinned state; in a stretched state it would mix a resize\n // and a release into one gesture.\n if (!inlineStretched && !blockStretched) dirs.push(`${freeBlock}${freeInline}` as ResizeDir);\n return dirs;\n }, [mode, currentAnchor, isRtl, stretch]);\n\n const CloseIcon = (\n <svg width=\"8\" height=\"8\" viewBox=\"0 0 10 10\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\">\n <line x1=\"1\" y1=\"1\" x2=\"9\" y2=\"9\" />\n <line x1=\"9\" y1=\"1\" x2=\"1\" y2=\"9\" />\n </svg>\n );\n\n return (\n <div\n ref={windowRef}\n dir={isRtl ? 'rtl' : 'ltr'}\n data-rdd-widget={id}\n className={[\n 'rdd-panel-float',\n isActive ? 'rdd-panel-float--active' : '',\n snapArmed.inline || snapArmed.block ? 'rdd-panel-float--snapping' : '',\n ].filter(Boolean).join(' ')}\n style={windowStyle}\n onPointerDown={handleWindowPointerDown}\n onPointerMove={handleWindowPointerMove}\n onPointerUp={handleWindowPointerUp}\n onPointerCancel={handleWindowPointerCancel}\n >\n {/* Clips header and body to the rounded corners; the resize handles are its siblings so\n they can straddle the edge instead of being half clipped. */}\n <div className=\"rdd-panel-float__frame\">\n <div className=\"rdd-panel-float__header\" onPointerDown={handleHeaderPointerDown}>\n {onTitleMenu ? (\n <button\n type=\"button\"\n className=\"rdd-panel-float__icon rdd-panel-float__menu\"\n // Not a drag: the header starts one on pointerdown, as the close button also prevents.\n onPointerDown={e => e.stopPropagation()}\n // Stopped, as the workspace's own menu buttons do: the menu closes on a document click.\n onClick={e => { e.stopPropagation(); onTitleMenu(e); }}\n title={formatLabel(messages.moreActions, formatMessage)}\n aria-label={formatLabel(messages.moreActions, formatMessage)}\n aria-haspopup=\"menu\"\n >\n {icon ?? MenuIcon}\n </button>\n ) : icon && <span className=\"rdd-panel-float__icon\">{icon}</span>}\n <span className=\"rdd-panel-float__title\">{formatLabel(title, formatMessage)}</span>\n <button\n type=\"button\"\n className=\"rdd-panel-float__close\"\n onClick={onClose}\n onPointerDown={e => e.stopPropagation()}\n title={formatLabel(messages.closeTooltip, formatMessage)}\n aria-label={formatLabel(messages.closeTooltip, formatMessage)}\n >\n {CloseIcon}\n </button>\n </div>\n {contentEl\n ? <WidgetContentSlot el={contentEl} />\n : <div className=\"rdd-panel-float__body\">{children}</div>}\n </div>\n {handleDirs.map(dir => (\n <div\n key={dir}\n className={`rdd-resize-handle rdd-resize-${dir}`}\n onPointerDown={handleResizePointerDown(dir)}\n />\n ))}\n </div>\n );\n}\n\n/** The title button's glyph for a widget with a titleMenu and no icon of its own. */\nconst MenuIcon = (\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\">\n <circle cx=\"12\" cy=\"5\" r=\"2\" /><circle cx=\"12\" cy=\"12\" r=\"2\" /><circle cx=\"12\" cy=\"19\" r=\"2\" />\n </svg>\n);\n\n// ─── Internal: WidgetContentSlot ──────────────────────────────────────────────\n\n/**\n * The body of a managed widget's frame. The content lives in `el`, rendered once by the overlay\n * for the widget's whole life; this only attaches it, and puts back the scroll offsets a detached\n * element loses (the same records workspace panels use).\n */\nfunction WidgetContentSlot({ el }: { el: HTMLElement }): React.ReactElement {\n const bodyRef = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n const body = bodyRef.current;\n if (!body) return;\n trackPanelDom(el);\n // A widget that keeps its embeds waits for this frame to be in the document (see domMove.ts).\n const cancel = el.parentNode !== body ? moveIntoWhenConnected(body, el) : () => {};\n restorePanelDom(el, { refocus: false });\n // Taken back out on unmount, so the element is never left inside a frame React has removed\n // (parked instead, for a widget that keeps its embeds).\n return () => { cancel(); leaveSlot(body, el); };\n }, [el]);\n return <div ref={bodyRef} className=\"rdd-panel-float__body\" />;\n}\n","import type { FloatAnchor } from '../types';\n\n/**\n * Mirrors a physical workspace corner to its horizontal opposite.\n *\n * Used only to translate a physically-hovered corner (raw pointer/screen\n * position, which CSS cannot reason about) into the logical `FloatAnchor`\n * value stored on a `FloatingWindow` under RTL. Render-time positioning\n * should use CSS logical properties (`insetInlineStart`/`insetInlineEnd`)\n * driven by the element's `dir` attribute instead of calling this.\n */\nexport function flipZoneHorizontal(zone: FloatAnchor): FloatAnchor {\n if (zone === 'top-left') return 'top-right';\n if (zone === 'top-right') return 'top-left';\n if (zone === 'bottom-left') return 'bottom-right';\n return 'bottom-left';\n}\n","/**\n * @file useWidgetHosting.ts\n * @description Moving a panel overlay's managed widgets out of their owner panel and back (7.11.0).\n *\n * A widget out of its panel is shown by a hosted panel: a workspace panel of the reserved kind\n * `'rdd:widget'`, owned by this overlay, whose body attaches the widget's content element. The\n * content itself stays rendered here, in the owner panel's tree, so nothing remounts and it keeps\n * its owner's contexts. This overlay owns its hosted panels: it opens and removes them, closes the\n * widget when the user closes one, and removes them all when it unmounts (the owner closed).\n */\nimport { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport type React from 'react';\nimport { FormContainerContext } from '../FormContainerContext';\nimport { WindowStoreSyncContext, useOptionalWindowManagerActionsInternal, useOptionalWindowManagerState, useRegistry } from '../WindowManagerContext';\nimport { useOptionalPanelHost } from '../workspace/panelHost';\nimport { optionsFor } from '../../core/panelOptions';\nimport { findLeafIdOf } from '../../core/layoutTree';\nimport type { HostedPanelPlacement, PanelInfo, WorkspaceState } from '../../types';\nimport type { ContextMenuItem } from '../ContextMenu';\nimport type { OutTarget } from '../../core/widgetPlacement';\nimport { setPreserveEmbeds } from '../domMove';\nimport type { ManagedWidget, MoveResult, WidgetLocation, WidgetTarget } from './types';\n\ninterface HostingDeps {\n /** Each open widget's content element. */\n contentEls: Map<string, HTMLDivElement>;\n /** Each open widget's config, kept current by open and close. */\n configs: { current: Map<string, ManagedWidget> };\n /** The overlay root, to find a widget's frame on screen. */\n containerRef: React.RefObject<HTMLDivElement | null>;\n /** Closes a widget for real: the user closed its hosted panel. */\n closeWidget: { current: (id: string) => void };\n}\n\nexport interface WidgetHosting {\n /** Widget id → its hosted panel's id, for the widgets that are out of the panel. */\n hostedIds: Record<string, string>;\n move(id: string, to: WidgetTarget): MoveResult;\n location(id: string): WidgetLocation | null;\n /** Removes a widget's hosted panel, if it has one, without closing anything: for close(). */\n release(id: string): void;\n /** Re-applies a re-opened widget's title, icon and capabilities to its hosted panel. */\n refresh(id: string, config: ManagedWidget): void;\n /** The widget's `titleMenu` items for where it is now; empty without one. */\n menuItems(id: string): ContextMenuItem[];\n /** The owner panel's id, or null when the overlay isn't in a workspace panel. */\n ownerPanelId: string | null;\n /**\n * A widget that keeps its embeds is inside its owner panel's element, which moves whenever the\n * grid changes around it (as it does when a hosted panel docks beside it): that element must\n * move with moveBefore() too, so this marks it, for the rest of its life.\n */\n preserveOwner(): void;\n /** Where a widget out of its panel is, as a saved placement's target; null in the panel. */\n outTarget(id: string): OutTarget | null;\n /** Subscribes to a widget's `onWillMove` / `onMoved`. */\n listen(id: string, kind: 'will' | 'moved', cb: () => void): () => void;\n /** The widget is in its new container: calls `onMoved` once it has a size. */\n settled(id: string): void;\n}\n\n/**\n * Which container a widget is in, as a string that changes exactly when the element moves: its\n * location plus, in the grid, the group. Reactive; `hostedId` is undefined while in the panel.\n */\nexport function useWidgetContainer(hostedId: string | undefined, ownerId: string): { location: WidgetLocation; key: string } {\n const key = useOptionalWindowManagerState((st: WorkspaceState) => containerKey(st, hostedId, ownerId), 'panel');\n return { location: key.split('|')[0] as WidgetLocation, key };\n}\n\nfunction containerKey(st: WorkspaceState, hostedId: string | undefined, ownerId: string): string {\n const panel = hostedId ? st.panels[hostedId] : undefined;\n if (!hostedId || !panel) return 'panel';\n if (panel.state === 'floating') return 'floating';\n if (panel.state === 'minimized') return 'minimized';\n const leaf = findLeafIdOf(st.gridRoot, hostedId);\n return `${leaf === findLeafIdOf(st.gridRoot, ownerId) ? 'tabbed' : 'docked'}|${leaf ?? ''}`;\n}\n\n/** A widget's own capabilities, as its hosted panel's options. */\nconst capabilities = (config: ManagedWidget): { canFloat: boolean; canDock: boolean } =>\n ({ canFloat: config.canFloat ?? false, canDock: config.canDock ?? false });\n\nconst NO_HOSTED: Record<string, string> = {};\n\nexport function useWidgetHosting({ contentEls, configs, containerRef, closeWidget }: HostingDeps): WidgetHosting {\n const actions = useOptionalWindowManagerActionsInternal();\n const sync = useContext(WindowStoreSyncContext);\n const panelHost = useOptionalPanelHost();\n const registry = useRegistry();\n const ownerId = useContext(FormContainerContext).instanceId;\n const [hostedIds, setHostedIds] = useState<Record<string, string>>(NO_HOSTED);\n // The same record, read synchronously by move() and the cleanup; with each one's close-handler unregister.\n // `target` is the last move's target, for placement(): what the grid alone can't say (which side, how big).\n const hostedRef = useRef(new Map<string, { panelId: string; unregister: () => void; target: WidgetTarget }>());\n // Each widget's onWillMove / onMoved callbacks, and the container each hosted one was last seen in.\n const listenersRef = useRef(new Map<string, { will: Set<() => void>; moved: Set<() => void> }>());\n const lastKeyRef = useRef(new Map<string, string>());\n const fire = (id: string, kind: 'will' | 'moved'): void => {\n listenersRef.current.get(id)?.[kind].forEach(cb => cb());\n };\n // The hosted panels' menu getters are registered once, so they call the latest functions.\n const latestRef = useRef<{ menuItems: (id: string) => ContextMenuItem[] }>({ menuItems: () => [] });\n\n const setHosted = (id: string, panelId: string | null): void => {\n setHostedIds(prev => {\n if (panelId === null) {\n if (!(id in prev)) return prev;\n const next = { ...prev };\n delete next[id];\n return next;\n }\n return prev[id] === panelId ? prev : { ...prev, [id]: panelId };\n });\n };\n\n /** Forgets a widget's hosted panel; removes it from the workspace unless it is already gone. */\n const detach = useCallback((id: string, remove: boolean): void => {\n const entry = hostedRef.current.get(id);\n if (!entry) return;\n hostedRef.current.delete(id);\n lastKeyRef.current.delete(id);\n entry.unregister();\n if (remove) actions?.removeHostedPanel(entry.panelId);\n panelHost?.setHostedContent(entry.panelId, null);\n setHosted(id, null);\n }, [actions, panelHost]);\n\n /** Where the widget's frame is on screen, in workspace pixels: where `'floating'` opens by default. */\n const frameRect = (id: string, config: ManagedWidget): { x: number; y: number; width: number; height: number } => {\n const root = containerRef.current;\n const frame = root\n ? Array.from(root.querySelectorAll<HTMLElement>('[data-rdd-widget]')).find(el => el.getAttribute('data-rdd-widget') === id)\n : undefined;\n const viewport = root?.closest('.rdd-workspace-viewport');\n const f = frame?.getBoundingClientRect();\n const v = viewport?.getBoundingClientRect();\n return {\n x: f && v ? Math.round(f.left - v.left) : 0,\n y: f && v ? Math.round(f.top - v.top) : 0,\n width: f && f.width > 0 ? Math.round(f.width) : (config.width ?? 320),\n height: f && f.height > 0 ? Math.round(f.height) : (config.height ?? 240),\n };\n };\n\n const move = (id: string, to: WidgetTarget): MoveResult => {\n const config = configs.current.get(id);\n const el = contentEls.get(id);\n if (!config || !el) return { ok: false, reason: 'not-open' };\n const current = hostedRef.current.get(id);\n if (to.to === 'panel') {\n if (current) fire(id, 'will');\n detach(id, true);\n return { ok: true };\n }\n const s = sync?.getSnapshot();\n const owner = s?.panels[ownerId];\n // An overlay in a modal, a drawer or outside any provider has no workspace panel to move beside.\n if (!actions || !panelHost || !owner || owner.owner) return { ok: false, reason: 'no-workspace' };\n if (optionsFor(registry, owner)?.keepAlive === false) return { ok: false, reason: 'owner-not-kept-alive' };\n if (to.to !== 'floating' && owner.state !== 'docked') return { ok: false, reason: 'owner-not-docked' };\n\n const at: HostedPanelPlacement = to.to === 'floating'\n ? { kind: 'float', rect: to.rect ?? frameRect(id, config) }\n : to.to === 'tabbed'\n ? { kind: 'dock', dockTo: { panel: ownerId, position: 'center' } }\n : { kind: 'dock', dockTo: { panel: ownerId, position: to.position, ...(to.size !== undefined ? { size: to.size } : {}) } };\n fire(id, 'will');\n // Already out: the hosted panel is replaced rather than moved, so every target takes one path.\n // Its content stays rendered here throughout; only the element moves.\n if (current) detach(id, true);\n const panelId = `${ownerId}/${id}`;\n panelHost.setHostedContent(panelId, el);\n // Its hosted panel's element moves the content wherever the user takes it: it keeps embeds too.\n if (config.preserveEmbeds) setPreserveEmbeds(panelHost.getOrCreateElement(panelId), true);\n const opened = actions.openHostedPanel(panelId, { panelId: ownerId, widgetId: id, options: capabilities(config) }, config.title as PanelInfo['title'], at);\n if (!opened) {\n panelHost.setHostedContent(panelId, null);\n return { ok: false, reason: 'owner-not-docked' };\n }\n if (config.icon !== undefined) actions.setPanelIcon(panelId, config.icon);\n // An in-page close of the hosted panel closes the widget (D17); going back is move({ to: 'panel' }).\n const unregisterClose = actions.registerHostedCloseHandler(panelId, () => {\n detach(id, false);\n closeWidget.current(id);\n }, () => fire(id, 'will')); // a layout load is about to drop it: the reconcile below sends it home\n // The app's titleMenu items lead the hosted panel's own menus.\n const unregisterMenu = actions.registerPanelContextMenu(panelId, () => latestRef.current.menuItems(id));\n const unregister = (): void => { unregisterClose(); unregisterMenu(); };\n hostedRef.current.set(id, { panelId, unregister, target: to.to === 'floating' ? { to: 'floating', rect: at.kind === 'float' ? at.rect : undefined } : to });\n if (sync) lastKeyRef.current.set(id, containerKey(sync.getSnapshot(), panelId, ownerId));\n setHosted(id, panelId);\n return { ok: true };\n };\n\n const location = (id: string): WidgetLocation | null => {\n if (!configs.current.has(id)) return null;\n const entry = hostedRef.current.get(id);\n const s = sync?.getSnapshot();\n if (!entry || !s) return 'panel';\n return containerKey(s, entry.panelId, ownerId).split('|')[0] as WidgetLocation;\n };\n\n const release = useCallback((id: string): void => detach(id, true), [detach]);\n\n const refresh = (id: string, config: ManagedWidget): void => {\n const entry = hostedRef.current.get(id);\n if (!entry || !actions) return;\n actions.updatePanelTitle(entry.panelId, config.title as PanelInfo['title']);\n actions.setPanelIcon(entry.panelId, config.icon ?? null);\n actions.setHostedOptions(entry.panelId, capabilities(config));\n };\n\n const menuItems = (id: string): ContextMenuItem[] => {\n const config = configs.current.get(id);\n if (!config?.titleMenu) return [];\n return config.titleMenu({\n id,\n location: location(id) ?? 'panel',\n ...capabilities(config),\n move: to => move(id, to),\n close: () => closeWidget.current(id),\n });\n };\n useEffect(() => { latestRef.current = { menuItems }; });\n\n const listen = useCallback((id: string, kind: 'will' | 'moved', cb: () => void): (() => void) => {\n let entry = listenersRef.current.get(id);\n if (!entry) { entry = { will: new Set(), moved: new Set() }; listenersRef.current.set(id, entry); }\n entry[kind].add(cb);\n return () => { entry[kind].delete(cb); };\n }, []);\n\n /** onMoved, once: on the element's first size in its new container, else after two frames. */\n const settled = useCallback((id: string): void => {\n const el = contentEls.get(id);\n if (!el) return;\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n observer?.disconnect();\n fire(id, 'moved');\n };\n const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(entries => {\n if (entries.some(e => e.contentRect.width > 0 && e.contentRect.height > 0)) finish();\n });\n observer?.observe(el);\n const frame = typeof requestAnimationFrame === 'undefined'\n ? (cb: () => void) => setTimeout(cb, 16)\n : requestAnimationFrame;\n frame(() => frame(finish));\n }, [contentEls]);\n\n const ownerPanelId = sync && sync.getSnapshot().panels[ownerId] ? ownerId : null;\n\n const preserveOwner = (): void => {\n const el = panelHost?.getElement(ownerId);\n if (el) setPreserveEmbeds(el, true);\n };\n\n const outTarget = (id: string): OutTarget | null => {\n const entry = hostedRef.current.get(id);\n const s = sync?.getSnapshot();\n if (!entry || !s?.panels[entry.panelId]) return null;\n const where = containerKey(s, entry.panelId, ownerId).split('|')[0];\n const win = s.floating.find(w => w.id === entry.panelId);\n if (where === 'floating' && win) {\n const n = (v: number | string) => (typeof v === 'number' ? v : parseFloat(v) || 0);\n return { at: 'floating', rect: { x: n(win.x), y: n(win.y), width: n(win.width), height: n(win.height) } };\n }\n if (where === 'tabbed') return { at: 'tabbed' };\n const t = entry.target;\n if (where === 'docked') {\n // The side and size it was docked with; a user's drag elsewhere in the grid keeps them.\n return t.to === 'docked' ? { at: 'docked', position: t.position, ...(t.size !== undefined ? { size: t.size } : {}) } : { at: 'docked', position: 'bottom' };\n }\n // Minimised: where it was before.\n if (t.to === 'floating' && t.rect) return { at: 'floating', rect: t.rect };\n if (t.to === 'docked') return { at: 'docked', position: t.position, ...(t.size !== undefined ? { size: t.size } : {}) };\n return { at: 'tabbed' };\n };\n\n // A hosted panel that left the workspace without this overlay asking (only loadLayout can do\n // that: it never keeps one) sends its widget back into the panel.\n const alive = useOptionalWindowManagerState(\n (st: WorkspaceState) => Object.values(hostedIds).filter(h => h in st.panels).join('\\n'), '');\n useEffect(() => {\n const present = new Set(alive.split('\\n'));\n for (const [id, panelId] of Object.entries(hostedIds)) {\n if (present.has(panelId) || !hostedRef.current.has(id)) continue;\n detach(id, false);\n }\n }, [alive, hostedIds, detach]);\n\n // The user moving a hosted panel (a drag to another group, floating, docking, minimising,\n // restoring): the store notifies synchronously, before React moves any DOM, so this is still\n // \"before the element moves\". The overlay's own moves are fired by move() itself.\n useEffect(() => {\n if (!sync) return;\n return sync.subscribeToState(() => {\n const st = sync.getSnapshot();\n for (const [id, entry] of hostedRef.current) {\n if (!(entry.panelId in st.panels)) continue; // gone: a close, or the reconcile above\n const key = containerKey(st, entry.panelId, ownerId);\n // Floating: remember its window, so a later minimise still knows where it was.\n const win = key === 'floating' ? st.floating.find(w => w.id === entry.panelId) : undefined;\n if (win && typeof win.x === 'number' && typeof win.y === 'number' && typeof win.width === 'number' && typeof win.height === 'number') {\n entry.target = { to: 'floating', rect: { x: win.x, y: win.y, width: win.width, height: win.height } };\n }\n const last = lastKeyRef.current.get(id);\n lastKeyRef.current.set(id, key);\n if (last !== undefined && last !== key) fire(id, 'will');\n }\n });\n }, [sync, ownerId]);\n\n // The owner closed, or its overlay unmounted: its widgets go with it, and so do their hosted panels.\n const detachRef = useRef(detach);\n useEffect(() => { detachRef.current = detach; });\n useEffect(() => () => {\n for (const id of Array.from(hostedRef.current.keys())) detachRef.current(id, true);\n }, []);\n\n // Fresh functions each render are fine: callers reach them through the manager context's memo.\n return useMemo(() => ({ hostedIds, move, location, release, refresh, menuItems, ownerPanelId, listen, settled, outTarget, preserveOwner }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [hostedIds, actions, sync, panelHost, registry, ownerId, release, ownerPanelId, listen, settled]);\n}\n","/**\n * @file widgetContext.ts\n * @description `useWidget()`: what a managed widget's own content knows about the widget (7.11.0).\n */\nimport { createContext, useContext, type Context } from 'react';\nimport type { WidgetLocation } from './types';\n\n/**\n * What `useWidget()` returns inside a managed widget's content (7.11.0).\n *\n * `usePanel()` there is still the **owner** panel, so content bound to its owner (a table bound to\n * its map) keeps working wherever the widget is. This is the widget's own side.\n */\nexport interface WidgetHandle {\n /** The widget's id, as given to `useFloatingWidgets().open()`. */\n id: string;\n /** The workspace panel that owns it, or `null` when its overlay isn't in one. */\n ownerPanelId: string | null;\n /** Where it is shown now. A component that reads it re-renders when it changes. */\n location: WidgetLocation;\n /**\n * Called just before the widget's content element moves to another container: into or out of\n * its panel, between docked, tabbed and floating, minimised or restored. Save what a move would\n * disturb here, such as a map's view. Returns the unsubscribe function.\n */\n onWillMove(cb: () => void): () => void;\n /**\n * Called once the element is in its new container and has its new size (or, with no size, as\n * when minimised, on the next frames). Restore what you saved in `onWillMove` here. Returns the\n * unsubscribe function.\n */\n onMoved(cb: () => void): () => void;\n}\n\n/** @internal */\nexport const WidgetContext: Context<WidgetHandle | null> = createContext<WidgetHandle | null>(null);\n\n/**\n * The managed widget this component is rendered in, or `null` outside one (7.11.0).\n * @example\n * function TableWidget() {\n * const widget = useWidget();\n * useEffect(() => widget?.onMoved(() => grid.current?.resize()), [widget]);\n * return <Grid ref={grid} compact={widget?.location === 'panel'} />;\n * }\n */\nexport function useWidget(): WidgetHandle | null {\n return useContext(WidgetContext);\n}\n","/**\n * @file PanelToolbar.tsx\n * @description A toolbar on a panel edge, and its buttons, toggles and layout primitives.\n */\nimport React, { useContext, useRef, useLayoutEffect } from 'react';\nimport type { ToolbarPosition } from './types';\nimport { PanelToolbarContext } from './context';\n\n// ─── PanelToolbar ─────────────────────────────────────────────────────────────\n\n/** Background style of a `PanelToolbar`. */\nexport type ToolbarVariant = 'transparent' | 'frosted' | 'solid';\n\n/** Visual style applied to `ToolbarButton` and `ToolbarToggle` components. */\nexport type ButtonVariant = 'ghost' | 'soft' | 'outlined' | 'filled';\n\n/** Props for `<RddPanelToolbar>`. */\nexport interface RddPanelToolbarProps {\n /** Edge of the panel overlay to attach to. @see ToolbarPosition */\n position: ToolbarPosition;\n /** Background style of the toolbar strip. @default 'transparent' */\n variant?: ToolbarVariant;\n /** Default button style inherited by `ToolbarButton` and `ToolbarToggle` children. @default 'ghost' */\n buttonVariant?: ButtonVariant;\n /** Button size in pixels for all buttons in this toolbar (sets `--rdd-panel-toolbar-btn-size`). The icon inside follows `--rdd-panel-toolbar-icon-size`. Falls back to the stylesheet when unset. */\n buttonSize?: number;\n style?: React.CSSProperties;\n className?: string;\n children?: React.ReactNode;\n}\n\n/**\n * Toolbar strip that attaches to any edge of an `RddPanelOverlay`.\n * Left/right toolbars inset automatically to avoid overlapping top/bottom toolbars.\n * RTL layouts are detected and handled automatically.\n * @example\n * <RddPanelToolbar position=\"top\" variant=\"frosted\">\n * <RddToolbarButton icon={<SaveIcon />} title=\"Save\" onClick={save} />\n * <RddToolbarToggle icon={<GridIcon />} title=\"Grid\" active={grid} onToggle={() => setGrid(v => !v)} />\n * </RddPanelToolbar>\n */\nexport function PanelToolbar({ position, variant = 'transparent', buttonVariant = 'ghost', buttonSize, style, className, children }: RddPanelToolbarProps): React.ReactElement {\n const ctx = useContext(PanelToolbarContext);\n const ref = useRef<HTMLDivElement>(null);\n const cleanupRef = useRef<(() => void) | null>(null);\n\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n if (!ctx) return;\n const measure = () => {\n const size = (position === 'top' || position === 'bottom') ? el.offsetHeight : el.offsetWidth;\n cleanupRef.current?.();\n cleanupRef.current = ctx.registerToolbar(position, size);\n };\n measure();\n // A one-shot measurement is correct for a live mount (already at final size), but during a\n // layout restore (loadLayout()/initialState) the panel's DOM isn't necessarily settled yet at\n // this exact instant — without re-measuring, a wrong size (often 0) is baked in permanently,\n // and every docked float ends up positioned at the toolbar's own y/x, covering it. This also\n // catches any later size change (button wrapping, a buttonSize/variant change, content change).\n const ro = new ResizeObserver(measure);\n ro.observe(el);\n return () => {\n ro.disconnect();\n cleanupRef.current?.();\n cleanupRef.current = null;\n };\n // ctx?.registerToolbar is a stable useCallback — depending on ctx directly\n // would re-run on every toolbarSizes update, causing an infinite loop.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [position, ctx?.registerToolbar]);\n\n const posStyle: React.CSSProperties = { position: 'absolute', zIndex: 5, pointerEvents: 'none', boxSizing: 'border-box' };\n\n if (position === 'top') {\n posStyle.top = 0; posStyle.left = 0; posStyle.right = 0;\n } else if (position === 'bottom') {\n posStyle.bottom = 0; posStyle.left = 0; posStyle.right = 0;\n } else if (position === 'left') {\n posStyle.insetInlineStart = 0;\n posStyle.top = ctx?.insetTop ?? 0;\n posStyle.bottom = ctx?.insetBottom ?? 0;\n } else {\n posStyle.insetInlineEnd = 0;\n posStyle.top = ctx?.insetTop ?? 0;\n posStyle.bottom = ctx?.insetBottom ?? 0;\n }\n\n const isSide = position === 'left' || position === 'right';\n const sideStyle: React.CSSProperties = isSide ? {\n ...(ctx?.insetTop ?? 0) > 0 ? { paddingTop: 0 } : {},\n ...(ctx?.insetBottom ?? 0) > 0 ? { paddingBottom: 0 } : {},\n } : {};\n\n const sizeStyle: React.CSSProperties = buttonSize != null\n ? { ['--rdd-panel-toolbar-btn-size' as string]: `${buttonSize}px` }\n : {};\n\n return (\n <div\n ref={ref}\n className={`rdd-panel-toolbar rdd-panel-toolbar--${position}${className ? ' ' + className : ''}`}\n data-variant={variant}\n data-btn-variant={buttonVariant}\n style={{ ...posStyle, ...sideStyle, ...sizeStyle, ...style }}\n >\n {children}\n </div>\n );\n}\n\n// ─── ToolbarButton ────────────────────────────────────────────────────────────\n\n/** Props for `<RddToolbarButton>`. */\nexport interface RddToolbarButtonProps {\n /** Button icon: an SVG, an icon component or an icon-font glyph. Pass no size: the library sizes it with `--rdd-panel-toolbar-icon-size`. */\n icon: React.ReactNode;\n /** Click handler. */\n onClick(): void;\n disabled?: boolean;\n /** Tooltip text and accessible `aria-label`. */\n title?: string;\n /** Visual style override. Falls back to the parent `PanelToolbar`'s `buttonVariant`. */\n variant?: ButtonVariant;\n}\n\n/** Icon button for use inside a `PanelToolbar`. */\nexport function ToolbarButton({ icon, onClick, disabled, title, variant }: RddToolbarButtonProps): React.ReactElement {\n return (\n <button\n type=\"button\"\n className=\"rdd-panel-toolbar-btn\"\n onClick={onClick}\n disabled={disabled}\n title={title}\n aria-label={title}\n {...(variant ? { 'data-variant': variant } : {})}\n >\n {icon}\n </button>\n );\n}\n\n// ─── ToolbarToggle ────────────────────────────────────────────────────────────\n\n/** Props for `<RddToolbarToggle>`. */\nexport interface RddToolbarToggleProps {\n /** Button icon: an SVG, an icon component or an icon-font glyph. Pass no size: the library sizes it with `--rdd-panel-toolbar-icon-size`. */\n icon: React.ReactNode;\n /** Whether the toggle is in the active/pressed state. Sets `aria-pressed` automatically. */\n active: boolean;\n /** Called when the button is clicked. Toggle `active` in response. */\n onToggle(): void;\n disabled?: boolean;\n /** Tooltip text and accessible `aria-label`. */\n title?: string;\n /** Visual style override. Falls back to the parent `PanelToolbar`'s `buttonVariant`. */\n variant?: ButtonVariant;\n}\n\n/** Two-state icon toggle button for use inside a `PanelToolbar`. Sets `aria-pressed` automatically. */\nexport function ToolbarToggle({ icon, active, onToggle, disabled, title, variant }: RddToolbarToggleProps): React.ReactElement {\n return (\n <button\n type=\"button\"\n className={`rdd-panel-toolbar-btn${active ? ' rdd-panel-toolbar-btn--active' : ''}`}\n onClick={onToggle}\n disabled={disabled}\n title={title}\n aria-label={title}\n aria-pressed={active}\n {...(variant ? { 'data-variant': variant } : {})}\n >\n {icon}\n </button>\n );\n}\n\n// ─── ToolbarSeparator ─────────────────────────────────────────────────────────\n\n/** Vertical (or horizontal) divider line between groups of toolbar items. */\nexport function ToolbarSeparator(): React.ReactElement {\n return <span className=\"rdd-panel-toolbar__sep\" aria-hidden=\"true\" />;\n}\n\n// ─── ToolbarSpacer ────────────────────────────────────────────────────────────\n\n/** Flex-grow spacer that pushes subsequent toolbar items to the far edge. */\nexport function ToolbarSpacer(): React.ReactElement {\n return <span className=\"rdd-panel-toolbar__spacer\" aria-hidden=\"true\" />;\n}\n\n// ─── ToolbarItem (custom control wrapper) ────────────────────────────────────\n\n/** Wrapper for a custom non-button control (e.g. a dropdown or input) inside a `PanelToolbar`. */\nexport function ToolbarItem({ children }: { children: React.ReactNode }): React.ReactElement {\n return <span className=\"rdd-panel-toolbar__item\">{children}</span>;\n}\n\n// ─── ToolbarCenter ────────────────────────────────────────────────────────────\n\n/** Centers its children within the toolbar using absolute positioning. */\nexport function ToolbarCenter({ children }: { children: React.ReactNode }): React.ReactElement {\n return <div className=\"rdd-panel-toolbar__center\">{children}</div>;\n}\n","/**\n * @file ToolbarSearch.tsx\n * @description The search field of a panel toolbar, with its results dropdown.\n */\nimport React, { useState, useRef, useMemo, useEffect } from 'react';\nimport { createPortal } from 'react-dom';\nimport { formatLabel, useFormatMessage, usePredefinedMessages } from '../WindowManagerContext';\n\n// ─── ToolbarSearchInput ───────────────────────────────────────────────────────\n\n/** A single result item returned by `RddToolbarSearchProps.onSearch`. */\nexport interface SearchResult {\n /** Unique identifier for this result — passed to `onSelect`. */\n id: string;\n /** Primary display text. */\n label: string;\n /** Optional secondary text shown below the label in the dropdown. */\n description?: string;\n /** Optional group header used to bucket results visually. */\n group?: string;\n /** Optional icon shown to the left of the label. */\n icon?: React.ReactNode;\n}\n\n/** Props for `<RddToolbarSearch>`. */\nexport interface RddToolbarSearchProps {\n /** Placeholder text shown in the expanded input field. @default the `searchPlaceholder` message ('Search…') */\n placeholder?: string;\n /**\n * Called with the current query and an `AbortSignal` each time the input changes (debounced).\n * Return `SearchResult[]` directly for synchronous sources, or `Promise<SearchResult[]>` for async.\n * Abort in-flight requests when the signal fires to prevent stale result races.\n */\n onSearch(query: string, signal: AbortSignal): Promise<SearchResult[]> | SearchResult[];\n /** Called when the user selects a result from the dropdown. */\n onSelect(result: SearchResult): void;\n}\n\n/**\n * Debounced async search field for use inside a `PanelToolbar`.\n * Renders as a compact icon button that expands into a text input on activation.\n * Results appear in a portal-rendered dropdown below the input.\n * @example\n * <ToolbarSearchInput\n * placeholder=\"Find layer…\"\n * onSearch={(q, signal) => fetchLayers(q, { signal })}\n * onSelect={result => workspace.focusLayer(result.id)}\n * />\n */\nexport function ToolbarSearchInput({ placeholder, onSearch, onSelect }: RddToolbarSearchProps): React.ReactElement {\n const formatMessage = useFormatMessage();\n const messages = usePredefinedMessages();\n const searchLabel = formatLabel(messages.search, formatMessage);\n const closeSearchLabel = formatLabel(messages.closeSearch, formatMessage);\n const placeholderText = placeholder ?? formatLabel(messages.searchPlaceholder, formatMessage);\n const [expanded, setExpanded] = useState(false);\n const [query, setQuery] = useState('');\n const [results, setResults] = useState<SearchResult[]>([]);\n const [dropdownPos, setDropdownPos] = useState<{ top: number; left: number; width: number } | null>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const abortRef = useRef<AbortController | null>(null);\n const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Unmounting stops the search (7.4.1): a pending debounce would still call onSearch for a\n // toolbar that has gone, and a search in flight would never see its signal abort.\n useEffect(() => () => {\n abortRef.current?.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n }, []);\n\n const openSearch = (): void => {\n setExpanded(true);\n setTimeout(() => inputRef.current?.focus({ preventScroll: true }), 0);\n };\n\n const closeSearch = (): void => {\n setExpanded(false);\n setQuery('');\n setResults([]);\n setDropdownPos(null);\n abortRef.current?.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n };\n\n const handleQueryChange = (e: React.ChangeEvent<HTMLInputElement>): void => {\n const q = e.target.value;\n setQuery(q);\n abortRef.current?.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n if (!q.trim()) { setResults([]); setDropdownPos(null); return; }\n\n debounceRef.current = setTimeout(async () => {\n const ctrl = new AbortController();\n abortRef.current = ctrl;\n try {\n const res = await onSearch(q, ctrl.signal);\n if (!ctrl.signal.aborted) {\n setResults(res);\n const el = containerRef.current;\n if (el && res.length > 0) {\n const r = el.getBoundingClientRect();\n const dropW = Math.max(r.width, 240);\n let left = r.left;\n if (left + dropW > window.innerWidth - 8) left = window.innerWidth - dropW - 8;\n setDropdownPos({ top: r.bottom + 4, left, width: dropW });\n } else {\n setDropdownPos(null);\n }\n }\n } catch {\n // AbortError or user-thrown — ignore\n }\n }, 300);\n };\n\n const handleSelect = (result: SearchResult): void => {\n onSelect(result);\n closeSearch();\n };\n\n const handleBlur = (e: React.FocusEvent): void => {\n if (!containerRef.current?.contains(e.relatedTarget as Node)) {\n closeSearch();\n }\n };\n\n const handleKeyDown = (e: React.KeyboardEvent): void => {\n if (e.key === 'Escape') {\n // Claim the key so the drawer or modal holding this panel stays open (see escapeStack).\n e.preventDefault();\n closeSearch();\n }\n };\n\n const grouped = useMemo((): Record<string, SearchResult[]> => {\n const map: Record<string, SearchResult[]> = {};\n for (const r of results) {\n const g = r.group ?? '';\n if (!map[g]) map[g] = [];\n map[g].push(r);\n }\n return map;\n }, [results]);\n\n const SearchIcon = (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <circle cx=\"6.5\" cy=\"6.5\" r=\"4.5\" />\n <line x1=\"10\" y1=\"10\" x2=\"14\" y2=\"14\" />\n </svg>\n );\n\n if (!expanded) {\n return (\n <div ref={containerRef} className=\"rdd-panel-toolbar-search\">\n <button type=\"button\" className=\"rdd-panel-toolbar-btn\" onClick={openSearch} title={searchLabel} aria-label={searchLabel}>\n {SearchIcon}\n </button>\n </div>\n );\n }\n\n return (\n <div ref={containerRef} className=\"rdd-panel-toolbar-search rdd-panel-toolbar-search--open\" onBlur={handleBlur}>\n <button type=\"button\" className=\"rdd-panel-toolbar-btn\" onClick={closeSearch} aria-label={closeSearchLabel} title={closeSearchLabel}>\n {SearchIcon}\n </button>\n <input\n ref={inputRef}\n className=\"rdd-panel-toolbar-search__input\"\n type=\"text\"\n value={query}\n onChange={handleQueryChange}\n onKeyDown={handleKeyDown}\n placeholder={placeholderText}\n aria-label={searchLabel}\n autoComplete=\"off\"\n />\n {dropdownPos && results.length > 0 && createPortal(\n <div\n className=\"rdd-panel-toolbar-search__dropdown\"\n // z-index from .rdd-panel-toolbar-search__dropdown (+8502), not inline, so\n // zIndexBase shifts it too. Resolves to the same 9502 by default.\n style={{ top: dropdownPos.top, left: dropdownPos.left, width: dropdownPos.width }}\n onMouseDown={e => e.preventDefault()}\n >\n {Object.entries(grouped).map(([group, items]) => (\n <React.Fragment key={group || '__default__'}>\n {group && <div className=\"rdd-panel-toolbar-search__group\">{group}</div>}\n {items.map(item => (\n <button\n key={item.id}\n type=\"button\"\n className=\"rdd-panel-toolbar-search__item\"\n onClick={() => handleSelect(item)}\n >\n {item.icon && <span className=\"rdd-panel-toolbar-search__item-icon\">{item.icon}</span>}\n <span className=\"rdd-panel-toolbar-search__item-label\">{item.label}</span>\n {item.description && <span className=\"rdd-panel-toolbar-search__item-desc\">{item.description}</span>}\n </button>\n ))}\n </React.Fragment>\n ))}\n </div>,\n document.body,\n )}\n </div>\n );\n}\n","/**\n * @file useFloatingWidgets.tsx\n * @description The hooks that open floating widgets from code: one widget, or a set managed by id.\n */\nimport { useState, useContext, useCallback, useMemo } from 'react';\nimport type { ManagedWidget, MoveResult, WidgetLocation, WidgetPlacement, WidgetTarget } from './types';\nimport { PanelManagerContext } from './context';\n\n// ─── usePanelFloatingWindow ───────────────────────────────────────────────────\n\n/** Return type of `usePanelFloatingWindow`. @see usePanelFloatingWindow */\nexport interface UsePanelFloatingWindowReturn {\n /** Whether the floating window is currently open. */\n isOpen: boolean;\n /** Open the floating window. */\n open(): void;\n /** Close the floating window. */\n close(): void;\n}\n\n/**\n * Manages the open/close boolean state for a single `RddFloatingWidget`.\n * Pass `isOpen` to `open`, `close` to `onClose` on the component directly.\n * @returns A stable `UsePanelFloatingWindowReturn` object.\n * @example\n * const info = usePanelFloatingWindow();\n * <RddFloatingWidget id=\"info\" open={info.isOpen} onClose={info.close} ... />\n */\nexport function usePanelFloatingWindow(): UsePanelFloatingWindowReturn {\n const [isOpen, setIsOpen] = useState(false);\n const open = useCallback((): void => { setIsOpen(true); }, []);\n const close = useCallback((): void => { setIsOpen(false); }, []);\n return { isOpen, open, close };\n}\n\n// ─── usePanelFloatingWindowManager ───────────────────────────────────────────\n\nconst EMPTY_IDS: string[] = [];\n\n/**\n * What `useFloatingWidgets()` returns.\n */\nexport interface FloatingWidgetsApi {\n /** Spawn or reconfigure a named window. Safe to call with an already-open ID to update config. */\n open(id: string, config: ManagedWidget): void;\n /** Close a named window by ID. No-op if the window is not open. */\n close(id: string): void;\n /** Close all managed windows. */\n closeAll(): void;\n /** Returns `true` if the named window is currently open. */\n isOpen(id: string): boolean;\n /** IDs of all currently open managed windows, wherever they are shown. Changes to this array trigger re-renders. */\n openIds: string[];\n /**\n * Moves a widget out of its panel or back (7.11.0), without remounting its content: docked\n * beside its owner panel, a tab in the owner's group, a floating window, or back into the panel\n * where it last was. Out of the panel it is a workspace panel of its own, which the user can\n * move, minimise and close like any other; closing it closes the widget. It never goes into a\n * saved layout. Returns a result rather than throwing; a refusal changes nothing.\n * @example\n * const widgets = useFloatingWidgets();\n * widgets.move('table', { to: 'docked', position: 'bottom', size: 0.35 });\n * widgets.move('table', { to: 'panel' });\n */\n move(id: string, to: WidgetTarget): MoveResult;\n /**\n * Where a widget is shown (7.11.0), or `null` if it isn't open. Read when called; it doesn't\n * re-render anything by itself.\n */\n location(id: string): WidgetLocation | null;\n /**\n * Where a widget is, as plain JSON to save with the rest of your panel's state (7.11.0): in the\n * panel (corner, stretch, free position, size) or out of it (docked, tabbed or floating, and where\n * it goes back to). Give it back to `open(id, { placement })` after a reload. `null` if it isn't open.\n * @example\n * const saved = widgets.placement('table'); // store it\n * widgets.open('table', { ...config, placement: saved }); // later: it opens where it was\n */\n placement(id: string): WidgetPlacement | null;\n}\n\n/**\n * Imperative hook for spawning N named floating windows at runtime from data or event handlers.\n * All widgets share z-ordering, drag, and corner-docking infrastructure of the `RddPanelOverlay`,\n * and accept the same placement options — including {@link ManagedWidget.stretch} to span an\n * axis of the panel.\n *\n * Must be called inside a **descendant** of `RddPanelOverlay`, not in the component that renders it.\n * @returns A stable `FloatingWidgetsApi`.\n * @example\n * const manager = useFloatingWidgets();\n * manager.open('feature-42', { title: 'Feature 42', content: <FeatureDetail id={42} />, anchor: 'top-right' });\n *\n * // A full-width strip along the bottom edge:\n * manager.open('timeline', { title: 'Timeline', content: <Timeline />, anchor: 'bottom-left', stretch: 'width', height: 120 });\n */\nexport function usePanelFloatingWindowManager(): FloatingWidgetsApi {\n const ctx = useContext(PanelManagerContext);\n const ids = ctx?.managedWindowIds ?? EMPTY_IDS;\n\n return useMemo(() => ({\n open: (id: string, config: ManagedWidget) => ctx?.openManaged(id, config),\n close: (id: string) => ctx?.closeManaged(id),\n closeAll: () => ctx?.closeAllManaged(),\n isOpen: (id: string) => ids.includes(id),\n openIds: ids,\n move: (id: string, to: WidgetTarget): MoveResult => ctx ? ctx.moveManaged(id, to) : { ok: false, reason: 'not-open' },\n location: (id: string): WidgetLocation | null => ctx ? ctx.locationOf(id) : null,\n placement: (id: string): WidgetPlacement | null => ctx ? ctx.placementOf(id) : null,\n }), [ctx, ids]);\n}\n"],"mappings":"AAOA,OAAgB,cAAAA,GAAY,cAAAC,GAAY,aAAAC,GAAW,mBAAAC,GAAiB,WAAAC,GAAS,UAAAC,OAAc,QCuEpF,IAAMC,GAAN,KAAoB,CACjB,SAAW,IAAI,IAQvB,SACEC,EACAC,EACAC,EACM,CACN,KAAK,SAAS,IAAIF,EAAI,CACpB,UAAWC,EACX,eAAAC,CACF,CAAC,CACH,CAKA,IAAIF,EAA4C,CAC9C,OAAO,KAAK,SAAS,IAAIA,CAAE,CAC7B,CAKA,kBAA6B,CAC3B,OAAO,M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KAAM,CAACE,EAAYE,IAAiCP,EAAMA,EAAI,YAAYK,EAAIE,CAAE,EAAI,CAAE,GAAI,GAAO,OAAQ,UAAW,EACpH,SAAWF,GAAsCL,EAAMA,EAAI,WAAWK,CAAE,EAAI,KAC5E,UAAYA,GAAuCL,EAAMA,EAAI,YAAYK,CAAE,EAAI,IACjF,GAAI,CAACL,EAAKG,CAAG,CAAC,CAChB","names":["forwardRef","useContext","useEffect","useLayoutEffect","useMemo","useRef","PanelRegistry","id","Component","defaultOptions","globalPanelRegistry","createContext","useContext","useState","useMemo","useEffect","useSyncExternalStore","createContext","useContext","useSyncExternalStore","defaultContract","FormContainerContext","FormContainerProvider","useFormContainer","usePanelSize","onResize","getDimensions","onStoreChange","createContext","useContext","records","isOnScreen","el","trackPanelDom","root","record","e","target","restorePanelDom","refocus","apply","top","left","focused","focusWasLost","forgetPanelDom","preserving","setPreserveEmbeds","el","on","preservesEmbeds","moveIntoWhenConnected","slot","moveInto","cancelled","frames","frame","cb","attempt","parent","p","HIDDEN_ID","park","doc","store","leaveSlot","createPanelHost","ownerDocument","doc","elements","dimensions","lifecycle","hostedContent","id","el","trackPanelDom","park","size","entry","PanelHostContext","createContext","useOptionalPanelHost","useContext","usePanelHost","host","FIELDS","stacks","apply","doc","stack","touched","root","pick","field","i","skin","noAnimations","zBase","claimDocumentMirror","owner","values","claim","c","releaseDocumentMirror","fields","index","released","defaultPredefinedMessages","defaultFormatMessage","msg","text","key","value","formatLabel","label","formatter","isValidElement","isSerializable","value","type","proto","shallowEqual","a","b","ka","k","sameTitle","sameDirtyOptions","keys","x","y","PanelEventBus","event","callback","cb","data","e","EMPTY_LEAF","isVisibleActiveTarget","id","scope","info","w","isLeafSelection","node","deriveActivePanelId","isCandidate","fromLeaves","child","found","selected","frontmost","resolveActivePanelId","next","preferId","repairLayoutTree","gridRoot","panels","repairs","seen","walk","kept","panelId","activePanelId","children","c","sizesOk","sizes","n","v","unchanged","i","sum","a","s","root","orphans","p","attach","ids","orphan","removePanelFromTree","idx","updatedLeaf","b","addPanelToLeaf","leafId","isLoneOccupant","hasLeaf","isShownInGrid","findLeafIdOf","findFirstLeafId","splitLeafInTree","position","splitRatio","newLeaf","orientation","HOSTED_COMPONENT","HOSTED_BASE","optionsFor","registry","panel","component","key","DEFAULT_FLOAT_RECT","finiteGeometry","fw","repairs","out","k","v","parseLayoutPayload","input","parsed","geometryRepairs","floating","anchor","_sr","_sb","rest","panels","repaired","repairLayoutTree","gridRoot","scope","persisted","activePanelId","isVisibleActiveTarget","deriveActivePanelId","withoutHostedPanels","payload","hosted","p","HOSTED_COMPONENT","id","removePanelFromTree","EMPTY_LEAF","gone","w","minimized","m","parseInitialState","json","createWorkspaceCore","config","registry","effectiveDir","effectiveZIndexBase","state","parseInitialState","listeners","setState","update","prev","next","listener","stateRef","getSnapshot","subscribeToState","cb","closeGuardsRef","stateProvidersRef","hostedCloseHandlersRef","hostedDropHandlersRef","eventBusRef","PanelEventBus","topZ","floating","top","w","maxZRef","subscribe","event","callback","publish","data","getCascadedPosition","fav","currentFloating","x","y","width","height","isOverlapping","pos","wx","wy","attempts","viewW","viewH","focusPanel","id","options","restorePanel","panel","win","alreadyTop","selectActiveInTree","node","applyRestore","activate","nextMinimized","m","prevState","nextActive","optionsFor","floatBack","favPos","cascaded","hasLeaf","addPanelToLeaf","targetLeafId","findFirstLeafId","applyFloat","rect","anchor","DEFAULT_FLOAT_RECT","cleanRoot","removePanelFromTree","otherWindows","resolveActivePanelId","applyDock","nextFloating","EMPTY_LEAF","leafId","openPanel","component","resolvedId","match","p","isNew","isRedirect","shouldFocus","serializable","isSerializable","explicitTarget","restored","dockTo","findLeafIdOf","exists","entry","title","target","activePanelId","dockLeaf","newPanelInfo","nextPanels","share","splitLeafInTree","firstLeaf","withoutPanel","nextRoot","nextActivePanelId","deriveActivePanelId","closePanel","current","openHostedPanel","owner","at","now","leaf","info","HOSTED_COMPONENT","z","panels","gridRoot","removeHostedPanel","setHostedOptions","was","registerHostedCloseHandler","onClose","onDrop","registerCloseGuard","guard","unregisterCloseGuard","registerStateProvider","provider","unregisterStateProvider","setPanelDirty","dirty","sameDirtyOptions","updatePanelTitle","sameTitle","updatePanelProps","props","setPanelIcon","icon","requestClosePanel","minimizePanel","wasActive","lastFloatingRect","lastLeafId","findLeafForPanel","child","res","wasMinimized","floatPanel","willFloat","dockPanel","setDraggedPanelId","dockPanelToGroup","position","before","willMove","isLoneOccupant","newRoot","dockPanelToWorkspaceEdge","newLeaf","orientation","children","r","movePanelOrder","panelId","targetIndex","insertInLeaf","remaining","index","newPanels","closeLeafGroup","findLeaf","found","removeLeafFromTree","c","sizes","sum","a","b","s","removed","maximizePanel","updateSplitSizes","path","updateInTree","depth","idx","i","updateFloatingPosition","updates","isDropAllowed","to","e","saveLayout","currentPanels","excludedIds","hostedIds","includedPanels","dynamicValue","hasDynamicValue","effectiveProps","effectiveSerializable","_icon","saved","minimized","liveActive","isVisibleActiveTarget","payload","loadLayout","layoutJson","parsed","parseLayoutPayload","withoutHostedPanels","titleOf","setActivePanel","setDirection","dir","isOpen","getOpenPanelIds","findPanelId","dedupeKey","customMenuGettersRef","showContextMenuFnRef","getItems","fn","defaults","useInsertionEffect","useRef","useLatestRef","value","ref","jsx","WindowActionsContext","createContext","WindowI18nContext","WindowStoreSyncContext","WindowPredefinedMessagesContext","defaultPredefinedMessages","StyleClassContext","useStyleClasses","useContext","RegistryContext","globalPanelRegistry","useRegistry","WindowManagerProvider","children","client","formatMessage","predefinedMessages","dirProp","modalClass","modalBodyClass","sidePanelClass","sidePanelBodyClass","windowClass","windowBodyClass","zIndexBaseProp","core","useState","c","createWorkspaceCore","registry","panelHost","createPanelHost","actions","effectiveFormatMessage","effectivePredefinedMessages","effectiveDir","effectiveZIndexBase","mergedMessages","useMemo","useEffect","claimDocumentMirror","releaseDocumentMirror","styleClasses","syncContextValue","defaultFormatMessage","PanelHostContext","noopSubscribe","_cb","outsideProvider","useWindowManagerState","selector","syncCtx","read","snap","useSyncExternalStore","useOptionalWindowManagerState","fallback","useWindowManagerActions","ctx","useWindowManagerActionsInternal","useOptionalWindowManagerActionsInternal","useFormatMessage","usePredefinedMessages","useContext","WindowPredefinedMessagesContext","usePanelId","useFormContainer","usePanelContextMenu","items","ctx","WindowActionsContext","panelId","register","itemsRef","useLatestRef","useEffect","WorkspaceClient","_WorkspaceClient","config","PanelRegistry","id","def","key","descriptor","createWorkspaceCore","fn","event","cb","args","a","options","component","dedupeKey","json","dir","path","sizes","updates","targetLeafId","position","panelId","targetIndex","leafId","guard","provider","dirty","title","icon","data","callback","d","createContext","WorkspaceInstanceContext","createContext","useContext","useState","useCallback","useMemo","useRef","jsx","idCounter","generateId","closeHandlers","changesNothing","current","updates","sameDirtyOptions","next","prev","keys","k","sameTitle","initialState","PanelStateContext","createContext","PanelActionsContext","PanelProvider","children","state","setState","useState","defaultModalTitle","usePredefinedMessages","stateRef","useLatestRef","closeListeners","useRef","onInstanceClose","useCallback","id","handler","listeners","notifyClosed","ids","handlers","h","registerCloseHandler","unregisterCloseHandler","openLeftPanel","Component","props","options","currentPanel","instance","s","openRightPanel","openModal","formTitle","modalOptions","close","m","closeAll","leftPanel","rightPanel","modals","closeAllModals","getInstance","updateInstance","target","setDirty","dirty","actions","useMemo","usePanelState","ctx","useContext","usePanelActions","useCallback","useRef","useEffect","useState","useMemo","useEffect","useRef","jsx","jsxs","QuestionIcon","InfoIcon","SuccessIcon","WarningIcon","DangerIcon","TYPE_ICONS","DialogIcon","icon","type","question","Builtin","jsx","jsxs","ConfirmationForm","title","message","alert","alertType","useYesNoTitles","onOK","onCancel","onSettled","icon","requestClose","setTitle","onClose","useFormContainer","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","confirmButtonRef","useRef","settledRef","onSettledRef","useLatestRef","settle","ok","settleRef","useEffect","resolvedTitle","resolvedMessage","cancelLabel","confirmLabel","handleSubmit","e","handleCancel","DialogIcon","ConfirmationForm_default","useEffect","useLayoutEffect","useRef","LAYER_RANK","entries","nextOrder","handleKeyDown","top","entry","higher","pushEscape","layer","onEscape","index","useEscapeLayer","active","onEscapeRef","useLayoutEffect","useState","useContainerRect","anchorRef","rect","setRect","container","measure","r","resizeObserver","Fragment","jsx","jsxs","SidePanelRendererItem","panel","position","defaultWidth","containerRect","close","openModal","updateInstance","setDirty","registerCloseHandler","unregisterCloseHandler","onInstanceClose","usePanelActions","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","dir","useWindowManagerState","s","sidePanelClass","sidePanelBodyClass","useStyleClasses","closeHandlerRef","useRef","id","Component","props","options","dirty","dirtyOptions","panelOptions","icon","setIconState","useState","optionsRef","useLatestRef","baseTitle","formatLabel","handleClose","useCallback","ConfirmationForm_default","canClose","useEffect","handleSetDirty","handleSetTitle","title","handleSetIcon","newIcon","handleOnCloseRequested","handler","handleOnClose","contract","useMemo","displayTitle","useEscapeLayer","width","widthStyle","bodyPadding","bodyPaddingStyle","FormContainerProvider","SidePanelAnchor","children","anchorRef","useContainerRect","SidePanelRenderer","leftPanel","rightPanel","usePanelState","LeftPanelRenderer","RightPanelRenderer","SidePanelRenderer_default","useEffect","useRef","jsx","jsxs","AlertForm","title","message","alertType","icon","okLabel","onSettled","requestClose","setTitle","onClose","useFormContainer","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","okButtonRef","useRef","settledRef","onSettledRef","useLatestRef","settle","settleRef","useEffect","resolvedTitle","resolvedMessage","resolvedOk","e","DialogIcon","AlertForm_default","React","forwardRef","useImperativeHandle","useState","useRef","useEffect","useLayoutEffect","createPortal","isElementRtl","el","closestDirEl","isComputedRtl","enabledItems","menu","moveMenuFocus","key","items","i","next","Fragment","jsx","jsxs","isKeyboardMenuEvent","event","mouse","getCoords","r","resolveLabel","label","fmt","isSeparator","item","isSubMenu","SubMenuPanel","forwardRef","items","getAnchor","autoFocus","onBack","theme","dir","onClose","onMouseEnter","onMouseLeave","ref","useLayoutEffect","el","anchor","PAD","GAP","width","height","toRight","toLeft","fitsRight","fitsLeft","left","top","enabledItems","handleKeyDown","e","backKey","moveMenuFocus","createPortal","i","simple","showChk","isChecked","isDisabled","CLOSED","menuDirection","target","isComputedRtl","ContextMenu","formatMessageProvider","onShow","onHide","onOpenChange","className","style","menuState","setMenuState","useState","submenuIndex","setSubmenuIndex","submenuFocus","setSubmenuFocus","menuRef","useRef","openerRef","restoreFocusRef","submenuPanelRef","itemRefs","timers","close","React","active","useImperativeHandle","x","y","initialFocus","coords","opener","useEffect","dismiss","useEscapeLayer","getSubmenuAnchor","itemEl","menuEl","mr","backToParentItem","parent","cancelOpenTimer","cancelCloseTimer","handleItemMouseEnter","index","openSubmenuFromKeyboard","handleMenuKeyDown","openKey","handleItemMouseLeave","sub","DefaultContextMenuAdapter","ContextMenuContext","ContextMenuProvider","adapter","children","componentProps","isOpen","setIsOpen","show","opts","useShowContextMenu","ctx","jsx","definePanels","panels","createWorkspace","config","messages","rest","WorkspaceClient","useWorkspace","ws","useContext","WorkspaceInstanceContext","usePanel","c","useFormContainer","id","state","useOptionalWindowManagerState","s","isActive","containerType","cRef","useRef","useLayoutEffect","mutators","useMemo","options","dirty","title","icon","usePanelEvents","events","ref","useEffect","offs","w","h","t","off","useBeforeClose","guard","useSaveState","getState","useModals","modals","usePanelState","a","usePanelActions","usePredefinedMessages","message","alert","alertType","yesNo","size","resolve","ConfirmationForm_default","okLabel","AlertForm_default","useSidePanels","leftPanel","rightPanel","RddSidePanels","side","defaultWidth","LeftPanelRenderer","RightPanelRenderer","SidePanelRenderer_default","RddContextMenu","forwardRef","children","adapter","menuProps","ContextMenuProvider","ContextMenu","useContext","useState","createContext","useContext","useMemo","useState","jsx","ToolbarContext","ToolbarProvider","children","radioGroups","setRadioGroups","modifiers","setModifiers","value","group","id","prev","active","useToolbar","ctx","createContext","useCallback","useContext","useLayoutEffect","useMemo","useRef","useSyncExternalStore","jsx","createPanelContributionStore","contributions","listeners","notify","l","panelId","contribution","listener","PanelContributionContext","createContext","PanelContributionProvider","children","store","useMemo","usePanelContribution","usePanelId","useContext","cleanupRef","useRef","useLayoutEffect","useActivePanelContribution","activePanelId","useWindowManagerState","s","subscribe","useCallback","onChange","getSnapshot","useSyncExternalStore","sidebarSectionToTab","section","fallbackIcon","useMergedToolbarItems","staticItems","active","useMergedSidebarTabs","staticTabs","jsx","DockableDesktopProvider","contextMenuAdapter","DefaultContextMenuAdapter","workspace","messages","children","props","existingCtxMenu","useContext","ContextMenuContext","ws","useState","WorkspaceClient","inner","WorkspaceInstanceContext","ToolbarProvider","WindowManagerProvider","PanelContributionProvider","PanelProvider","ContextMenuProvider","React","useState","useRef","useEffect","useCallback","useContext","useSyncExternalStore","subscribeNever","isClient","isServer","useIsClient","useSyncExternalStore","readScheme","subscribe","onChange","observer","serverScheme","useColorScheme","React","useRef","useState","useEffect","useLayoutEffect","createPortal","jsx","jsxs","useParkBeforeRemoval","hostRef","panelId","panelHost","useLayoutEffect","host","el","preservesEmbeds","isPanelShown","s","state","isShownInGrid","renderPanelContent","id","panel","registry","messages","formatMessage","componentKey","registryEntry","formatLabel","Component","HostedWidgetSlot","usePanelHost","slotRef","useRef","slot","cancel","moveIntoWhenConnected","restorePanelDom","leaveSlot","PreservedDOMWrapper","useRegistry","preserve","useWindowManagerState","optionsFor","isActive","isActiveRef","useEffect","cachedEl","setPreserveEmbeds","moveInto","resizeObserver","entries","entry","width","height","lifecycle","h","PreviewDOMWrapper","useFormatMessage","usePredefinedMessages","options","disableLivePreview","lastSize","origW","origH","scale","displayW","displayH","rawTitle","title","initialChar","FormContainerProviderWrapper","children","requestClosePanel","setPanelDirty","registerCloseGuard","unregisterCloseGuard","registerStateProvider","unregisterStateProvider","updatePanelTitle","setPanelIcon","minimizePanel","useWindowManagerActions","isMin","m","prevMinRef","prevActiveRef","wasActive","rawPanelState","derivedContainerType","prevContainerTypeRef","prevType","initialContainerType","useState","contract","React","dirty","handler","getState","icon","reg","FormContainerProvider","PanelMount","dir","keepAlive","shown","typeClass","createPortal","useSyncExternalStore","jsx","DragGhost","dragPos","children","pos","React","startPointerDrag","config","element","pointerId","startClientX","startClientY","captureStart","onMove","onEnd","activeClasses","el","classes","start","handleMove","e","finish","cancelled","handleEnd","doc","handleLostCapture","view","handleBlur","computeResizedRect","dir","dx","dy","constraints","minW","minH","maxW","maxH","minX","minY","x","y","w","h","maxDx","minDx","clampedDx","maxDy","minDy","clampedDy","useState","useRef","useEffect","useCallback","findLeaf","node","leafId","child","found","tabDropSide","tabEl","clientX","rect","isComputedRtl","isMenuKey","keyboardMenuEvents","menuEventAt","el","r","event","initialFocusFor","refocusAfterTabClose","id","strip","workspaceEl","esc","active","domIdPart","raw","LONG_PRESS_MS","CANCEL_MOVE_PX","jsx","jsxs","DefaultGridIcon","ContextMenuIcons","Fragment","jsx","jsxs","LeafGroup","leaf","onTabRightClick","activeDropZone","onHoverDropZone","onTabDragStart","hoveredTab","onTabHover","defaultPanelIcon","onRequestClosePanel","emptyWorkspace","renderTabContent","state","useWindowManagerState","registry","useRegistry","openPanel","closeLeafGroup","setActivePanel","isDropAllowed","useWindowManagerActionsInternal","formatMessage","useFormatMessage","messages","usePredefinedMessages","windowClass","windowBodyClass","useStyleClasses","tabContainerRef","useRef","tabScroll","setTabScroll","useState","updateTabScroll","useCallback","el","travelled","max","next","isComputedRtl","prev","useEffect","ro","scrollTabs","toward","forward","startSide","endSide","scrollGlyph","scrollLabel","selectTab","id","handleTabKeyDown","e","closable","isMenuKey","menuEventAt","ids","p","i","step","workspaceEl","refocusAfterTabClose","tabPanelId","domIdPart","tabIdFor","panelId","formatLabel","idx","panel","isSelected","isGloballyActive","options","optionsFor","isHovered","isLast","isHoveredEmpty","sideClass","tabFocusClass","tabDropSide","icon","DefaultGridIcon","title","PreservedDOMWrapper","isActive","pos","dragged","applied","offer","pct","rem","jsx","jsxs","WorkspaceGrid","node","path","onTabRightClick","activeDropZone","onHoverDropZone","onTabDragStart","hoveredTab","onTabHover","defaultPanelIcon","onRequestClosePanel","emptyWorkspace","renderTabContent","updateSplitSizes","useWindowManagerActions","LeafGroup","isRow","handleResizerPointerDown","idx","e","resizerEl","parentEl","parentSize","rtl","isComputedRtl","startPointerDrag","dx","dy","startSizes","deltaPercentage","newSizes","child","size","React","Fragment","jsx","jsxs","appliedSide","side","rtl","WorkspaceZones","state","activeEdgeDrop","activeCornerAnchor","setActiveEdgeDrop","setActiveCornerAnchor","isDropAllowed","dragged","edge","cornerOffered","anchor","corner","pct","Fragment","jsx","jsxs","FloatingWindows","state","registry","windowClass","windowBodyClass","defaultPanelIcon","messages","formatMessage","setActivePanel","focusPanel","maximizePanel","minimizePanel","getPanelContextMenuItems","showContextMenu","handleRequestClose","startDrag","startResize","w","panel","isMaximized","isDragged","isFocused","options","optionsFor","w_","h_","stack","fw","idx","stackOffset","i","sh","isTop","e","DefaultGridIcon","formatLabel","customItems","closeItem","ContextMenuIcons","initialFocusFor","PreservedDOMWrapper","createPortal","jsx","jsxs","Taskbar","state","registry","taskbarVisibility","taskbarExpanded","expandTaskbar","leaveTaskbar","scrollTaskbar","taskbarRef","tooltipRef","defaultPanelIcon","messages","formatMessage","lastTaskbarPointerTypeRef","hoveredMinimized","setHoveredMinimized","minimizedTooltipTimeoutRef","isContextMenuOpen","handleMinimizedRightClick","handleRequestClose","restorePanel","formatLabel","m","options","optionsFor","icon","DefaultGridIcon","e","isMenuKey","menuEventAt","el","startX","startY","pointerId","cancelled","cancel","timer","onPreMove","onShortTap","rect","me","CANCEL_MOVE_PX","onEnd","LONG_PRESS_MS","createPortal","tooltipId","PreviewDOMWrapper","useState","useRef","createDragPos","pos","listeners","v","l","cb","sameDropZone","a","b","sameTab","useDragTargets","setDraggedPanelId","isRtl","canInsertInto","activeDropZone","setActiveDropZone","useState","activeDropZoneRef","useRef","dragPos","setDragPos","activeEdgeDrop","setActiveEdgeDropState","activeEdgeDropRef","setActiveEdgeDrop","val","activeCornerAnchor","setActiveCornerAnchorState","activeCornerAnchorRef","setActiveCornerAnchor","hoveredTab","setHoveredTab","hoveredTabRef","leafId","panelId","index","side","position","x","y","elements","foundDropZone","foundEdge","foundTab","el","prev","tabIdx","tabDropSide","createTabDrag","deps","state","handleTabRightClick","activeDropZoneRef","hoveredTabRef","activeEdgeDropRef","activeCornerAnchorRef","setActiveCornerAnchor","clearDragState","flipRtl","setDragPos","updateHoverFromPoint","dockPanelToWorkspaceEdge","movePanelOrder","dockPanelToGroup","floatPanel","setDraggedPanelId","isDropAllowed","executeDrop","id","me","dropZone","targetTab","edgeDrop","cornerAnchor","side","targetIndex","targetLeaf","findLeaf","currentIdx","position","e","el","startX","startY","pointerId","cancelled","cancel","timer","onPreMove","CANCEL_MOVE_PX","dragStarted","onMove","onEnd","onCancel","LONG_PRESS_MS","dx","dy","createWorkspaceMenus","deps","state","registry","messages","formatMessage","handleRequestClose","setHoveredMinimized","floatPanel","minimizePanel","restorePanel","maximizePanel","getPanelContextMenuItems","showContextMenu","isDropAllowed","id","e","panel","options","optionsFor","items","hosted","formatLabel","ContextMenuIcons","custom","finalItems","initialFocusFor","canMaximize","useState","useEffect","useWorkspaceSize","workspaceRef","workspaceSize","setWorkspaceSize","el","heightWarnShown","tallWarnShown","observer","entries","rect","culprit","cursor","tag","id","cls","who","createFloatingWindowDrag","deps","state","workspaceSize","activeDropZoneRef","hoveredTabRef","activeEdgeDropRef","activeCornerAnchorRef","setActiveCornerAnchor","clearDragState","flipRtl","updateHoverFromPoint","focusPanel","updateFloatingPosition","dockPanelToWorkspaceEdge","movePanelOrder","dockPanelToGroup","setDraggedPanelId","isDropAllowed","id","e","floatingWin","w","el","windowEl","startX","startY","startPosX","startPosY","executeFWDrop","dropZone","targetTab","edgeDrop","cornerAnchor","side","targetIndex","position","pointerId","cancelled","cancel","timer","onPreMove","me","CANCEL_MOVE_PX","onMove","dx","dy","onEnd","onCancel","LONG_PRESS_MS","dragStarted","dir","startRect","viewW","viewH","parsedX","parsedY","parsedW","parsedH","isRightSnapped","isBottomSnapped","startPointerDrag","start","resized","computeResizedRect","newX","newY","newW","newH","jsx","jsxs","WindowManager","skin","defaultPanelIcon","taskbarVisibility","animations","emptyWorkspace","renderTabContent","contextMenuAdapter","DefaultContextMenuAdapter","state","useWindowManagerState","panelHost","usePanelHost","registry","useRegistry","restorePanel","minimizePanel","requestClosePanel","maximizePanel","updateFloatingPosition","focusPanel","floatPanel","setDraggedPanelId","dockPanelToGroup","movePanelOrder","dockPanelToWorkspaceEdge","setActivePanel","getPanelContextMenuItems","showContextMenu","registerContextMenuFn","isDropAllowed","useWindowManagerActionsInternal","openModal","usePanelActions","formatMessage","useFormatMessage","messages","usePredefinedMessages","handleRequestClose","React","id","panel","customOpts","resolve","opts","baseTitle","formatLabel","ConfirmationForm_default","windowClass","windowBodyClass","useStyleClasses","ctxMenu","useContext","ContextMenuContext","contextMenuRef","useRef","useEffect","taskbarRef","tooltipRef","taskbarExpanded","setTaskbarExpanded","useState","taskbarCollapseTimerRef","taskbarHoveredRef","prevMinimizedLengthRef","hoveredMinimized","setHoveredMinimized","minimizedTooltipTimeoutRef","lastTaskbarPointerTypeRef","internalContextMenuOpen","setInternalContextMenuOpen","isContextMenuOpen","m","handler","e","storeSync","WindowStoreSyncContext","canInsertInto","leafId","dragged","targets","useDragTargets","activeDropZone","setActiveDropZone","dragPos","activeEdgeDrop","setActiveEdgeDrop","activeCornerAnchor","setActiveCornerAnchor","hoveredTab","setHoveredTab","handleTabHover","handleHoverDropZone","handleTabRightClick","handleMinimizedRightClick","createWorkspaceMenus","handleTabDragStart","createTabDrag","keys","cachedId","el","forgetPanelDom","handleWindowBlur","workspaceRef","workspaceSize","useWorkspaceSize","viewW","viewH","w","winW","winH","winX","winY","newWidth","newHeight","newX","newY","changed","maxX","maxY","handlePointerDownGlobal","target","windowEl","winId","panelEl","panelId","startDrag","startResize","createFloatingWindowDrag","scrollTaskbar","direction","amount","scheduleCollapseTaskbar","useCallback","delayMs","expandTaskbar","leaveTaskbar","currentColorScheme","useColorScheme","isClient","useIsClient","claimDocumentMirror","releaseDocumentMirror","WorkspaceZones","WorkspaceGrid","FloatingWindows","Taskbar","PanelMount","DragGhost","WindowManager_default","useCallback","useRef","useState","useMemo","Fragment","jsx","jsxs","ModalRenderer","modal","index","close","openModal","updateInstance","setDirty","onInstanceClose","usePanelActions","formatMessage","useFormatMessage","predefinedMessages","usePredefinedMessages","dir","useWindowManagerState","s","modalClass","modalBodyClass","useStyleClasses","closeHandlerRef","useRef","id","Component","props","options","dirty","dirtyOptions","modalOptions","icon","setIconState","useState","optionsRef","useLatestRef","baseTitle","formatLabel","handleClose","useCallback","ConfirmationForm_default","handleSetDirty","handleSetTitle","title","handleSetIcon","newIcon","handleOnCloseRequested","handler","handleOnClose","contract","useMemo","displayTitle","sizeClass","showCloseButton","bodyPadding","bodyPaddingStyle","useEscapeLayer","modalZIndex","FormContainerProvider","ModalStackRenderer","modals","usePanelState","ModalStackRenderer_default","React","useState","useEffect","useRef","useCallback","useImperativeHandle","useContext","useMemo","createContext","forwardRef","memo","jsx","jsxs","isRailTab","entry","isRailCustom","toRailArray","value","SidebarContext","createContext","SidebarTabContext","SidebarTabProvider","tabId","onClose","onOpen","setActiveTabId","children","useMemo","otherId","renderRailEntry","index","activeTabId","onTabClick","React","isActive","SidebarTabStrip","memo","tabs","headerEntries","footerEntries","isVisible","position","i","tab","SidebarResizeHandle","currentWidth","minWidth","maxWidth","onWidthChange","onResizeStart","onResizeEnd","e","el","activeClasses","onPhysicalRight","isComputedRtl","startPointerDrag","dx","_dy","startWidth","newW","Sidebar","forwardRef","headerAction","footerAction","defaultWidth","controlledActiveTabId","onActiveTabChange","visible","onVisibilityChange","stripVisible","onStripVisibilityChange","showCloseButton","hideDefaultHeader","renderHeader","isSecondary","ref","workspaceDir","useOptionalWindowManagerState","s","isControlled","formatMessage","useFormatMessage","closeLabel","formatLabel","usePredefinedMessages","width","setWidthState","useState","setWidth","useCallback","px","isResizing","setIsResizing","internalActiveTabId","setInternalActiveTabId","normalizedHeaderEntries","normalizedFooterEntries","headerTabs","footerTabs","allTabs","mountedTabIds","setMountedTabIds","effectiveMountedTabIds","result","activeTabIdRef","useRef","useEffect","widthRef","id","prev","next","changed","t","useImperativeHandle","handleTabClick","handleClose","hasHeaderOverride","closeButtonWarnedRef","sidebarContextValue","isSidebarVisible","isStripVisible","isDrawerOpen","drawer","isCurrent","resizeHandle","SecondarySidebar","props","primary","useContext","opposite","useSidebar","ctx","useSidebarTab","forwardRef","useImperativeHandle","useState","useRef","useEffect","useLayoutEffect","createPortal","Fragment","jsx","jsxs","flyoutPosition","rect","position","isRtl","gap","ToolbarGroupButton","item","toolbar","isOpen","setIsOpen","useState","btnRect","setBtnRect","btnRtl","setBtnRtl","btnRef","useRef","flyoutRef","isControlled","activeId","activeSubItem","e","isActive","displayIcon","displayLabel","handleClick","isComputedRtl","prev","useLayoutEffect","el","r","PAD","useEffect","onMouseDown","target","closeFlyout","items","enabledItems","handleFlyoutKeyDown","moveMenuFocus","useEscapeLayer","createPortal","entry","i","isSubActive","renderItem","index","controlled","Toolbar","forwardRef","visible","onVisibilityChange","className","style","ref","useToolbar","isVertical","useImperativeHandle","collapsed","collapseStyle","stripRef","strip","useCallback","useEffect","useLayoutEffect","useRef","useState","createPortal","jsx","jsxs","ToastEmitter","fn","message","opts","id","patch","e","emitter","toast","msg","promise","messages","result","err","InfoIcon","SuccessIcon","WarningIcon","ErrorIcon","CloseIcon","DEFAULT_ICONS","ToastItem","options","exiting","isLeft","showProgress","pauseOnHover","animation","closeLabel","onDismiss","onExited","divRef","useRef","bodyRef","timerRef","remainRef","startRef","paused","setPaused","useState","startEntry","entryClass","setEntryClass","useLayoutEffect","el","body","applyHeight","observer","useEffect","raf","scheduleDismiss","useCallback","ms","handle","fallback","handleMouseEnter","handleMouseLeave","cls","icon","resolveOpts","raw","defaultDuration","defaultClosable","ToastContainer","position","maxVisible","newestOnTop","progressBar","width","adapter","toasts","setToasts","formatMessage","useFormatMessage","usePredefinedMessages","regionLabel","formatLabel","workspaceDir","useOptionalWindowManagerState","s","mounted","useIsClient","queueRef","toastsRef","useLatestRef","handleDismiss","prev","t","handleExited","promoted","filtered","newEntry","rawEntry","q","merged","AdapterContainer","createPortal","dirMod","React","useState","useRef","useCallback","useMemo","useEffect","useLayoutEffect","useContext","createPortal","createContext","PanelToolbarContext","PanelManagerContext","PanelOverlayContext","stretchesInline","s","stretchesBlock","addAxis","axis","releaseAxis","bucketsFor","anchor","stretch","withInlineHalf","a","half","withBlockHalf","ANCHORS","getHoveredZone","container","clientX","clientY","rect","x","y","MIN_W","MIN_H","DOCK_INSET","DOCK_GAP","SNAP_IN","SNAP_OUT","STRETCHES","POSITIONS","isNum","n","isObj","o","clamp","lo","hi","isAnchor","a","ANCHORS","toPanelForm","p","box","form","x","y","leftGap","rightGap","startGap","endGap","topGap","bottomGap","block","inline","fromPanelForm","hasBox","w","MIN_W","h","MIN_H","base","startX","parsePanelForm","raw","parsePlacement","home","size","r","React","useState","useContext","useRef","useLayoutEffect","useInsertionEffect","useCallback","useEffect","flipZoneHorizontal","zone","jsx","jsxs","PanelFloatingWindow","props","ctx","useContext","PanelOverlayContext","FloatingWindowBody","ManagedFloatingWindow","placement","usePlacementField","controlled","key","initial","internal","setInternal","useState","updateRef","useLatestRef","isControlled","set","useCallback","next","prev","id","title","icon","defaultAnchor","defaultWidth","defaultHeight","defaultStretch","stretchProp","onPlacementChange","stretchable","children","onClose","contentEl","onTitleMenu","isRtl","useOptionalWindowManagerState","s","formatMessage","useFormatMessage","messages","usePredefinedMessages","mode","setMode","currentAnchor","setAnchor","ownStretch","setOwnStretch","isStretchControlled","stretch","freePos","setFreePos","size","setSize","windowRef","useRef","modeRef","freePosRef","sizeRef","stretchRef","currentAnchorRef","onPlacementChangeRef","snapArmed","setSnapArmed","snapArmedRef","stackOffsetRef","applyPlacement","anchor","dragState","useLayoutEffect","blockStretchWarnedRef","useEffect","stretchesBlock","half","neighbours","bucket","other","zOrder","isActive","getContainerBounds","container","dockedBand","logicalStart","logicalEnd","DOCK_INSET","handleWindowPointerDown","handleHeaderPointerDown","e","startX","startY","el","elRect","cRect","handleResizePointerDown","dir","er","cr","measured","startRect","stretchesInline","dragsInline","dragsBlock","released","armed","releaseIfNeeded","st","releasingInline","releasingBlock","nextAnchor","releaseAxis","pinsPhysicalLeft","withInlineHalf","withBlockHalf","startPointerDrag","dx","dy","start","cw","ch","band","newX","newY","newW","newH","computeResizedRect","MIN_W","MIN_H","fullInline","fullBlock","nextArmed","SNAP_IN","SNAP_OUT","addAxis","handleWindowPointerMove","ds","r","rawZone","getHoveredZone","flipZoneHorizontal","handleWindowPointerUp","zone","handleWindowPointerCancel","windowStyle","dockedStackOffset","buckets","bucketsFor","stackOffset","registered","stack","idx","offset","i","DOCK_GAP","useInsertionEffect","handleDirs","React","freeBlock","freeInline","inlineStretched","blockStretched","dirs","CloseIcon","formatLabel","MenuIcon","WidgetContentSlot","bodyRef","body","trackPanelDom","cancel","moveIntoWhenConnected","restorePanelDom","leaveSlot","useCallback","useContext","useEffect","useMemo","useRef","useState","useWidgetContainer","hostedId","ownerId","key","useOptionalWindowManagerState","st","containerKey","panel","leaf","findLeafIdOf","capabilities","config","NO_HOSTED","useWidgetHosting","contentEls","configs","containerRef","closeWidget","actions","useOptionalWindowManagerActionsInternal","sync","useContext","WindowStoreSyncContext","panelHost","useOptionalPanelHost","registry","useRegistry","FormContainerContext","hostedIds","setHostedIds","useState","hostedRef","useRef","listenersRef","lastKeyRef","fire","id","kind","cb","latestRef","setHosted","panelId","prev","next","detach","useCallback","remove","entry","frameRect","root","frame","el","viewport","f","v","move","to","current","owner","optionsFor","at","setPreserveEmbeds","unregisterClose","unregisterMenu","unregister","location","s","release","refresh","menuItems","useEffect","listen","settled","done","finish","observer","entries","e","ownerPanelId","preserveOwner","outTarget","where","win","w","n","t","alive","h","present","last","detachRef","useMemo","createContext","useContext","WidgetContext","useWidget","Fragment","jsx","jsxs","seedPlacement","config","targetOf","out","root","viewport","vw","vh","r","width","height","PanelOverlayRoot","children","className","style","toolbarSizes","setToolbarSizes","useState","zOrders","setZOrders","stacks","setStacks","dockedSizes","setDockedSizes","draggingId","setDraggingId","hoveredZone","setHoveredZone","topId","setTopId","managedWindows","setManagedWindows","managedPlacements","setManagedPlacements","contentEls","configsRef","useRef","zCounterRef","containerRef","closeWidgetRef","hosting","useWidgetHosting","releaseHosted","refreshHosted","hostingRef","useEffect","isRtl","useOptionalWindowManagerState","s","isRtlRef","placementsRef","pendingRef","pendingCount","setPendingCount","boxNow","el","contextMenu","useContext","ContextMenuContext","registerToolbar","useCallback","pos","size","prev","next","focusWindow","id","z","dockWindow","anchor","stretch","buckets","bucketsFor","x","bucket","ANCHORS","a","i","undockWindow","reportDockedSize","openManaged","reopened","setPreserveEmbeds","saved","parsePlacement","seed","state","deferred","fromPanelForm","c","forgetContentEl","forgetPanelDom","closeManaged","closeAllManaged","updateManagedPlacement","patch","placementOf","pending","current","home","toPanelForm","apply","box","form","ro","managedWindowIds","useMemo","toolbarCtxValue","managerCtxValue","coreCtxValue","PanelToolbarContext","PanelManagerContext","PanelOverlayContext","DropZoneOverlay","cfg","placement","React","createPortal","WidgetScope","ManagedFloatingWindow","e","items","initialFocusFor","location","key","useWidgetContainer","listen","settled","ownerPanelId","lastKey","useLayoutEffect","handle","cb","WidgetContext","zone","useContext","useRef","useLayoutEffect","jsx","PanelToolbar","position","variant","buttonVariant","buttonSize","style","className","children","ctx","useContext","PanelToolbarContext","ref","useRef","cleanupRef","useLayoutEffect","el","measure","size","ro","posStyle","sideStyle","sizeStyle","ToolbarButton","icon","onClick","disabled","title","ToolbarToggle","active","onToggle","ToolbarSeparator","ToolbarSpacer","ToolbarItem","ToolbarCenter","React","useState","useRef","useMemo","useEffect","createPortal","jsx","jsxs","ToolbarSearchInput","placeholder","onSearch","onSelect","formatMessage","useFormatMessage","messages","usePredefinedMessages","searchLabel","formatLabel","closeSearchLabel","placeholderText","expanded","setExpanded","useState","query","setQuery","results","setResults","dropdownPos","setDropdownPos","containerRef","useRef","inputRef","abortRef","debounceRef","useEffect","openSearch","closeSearch","handleQueryChange","e","q","ctrl","res","el","r","dropW","left","handleSelect","result","handleBlur","handleKeyDown","grouped","useMemo","map","g","SearchIcon","createPortal","group","items","React","item","useState","useContext","useCallback","useMemo","EMPTY_IDS","usePanelFloatingWindowManager","ctx","useContext","PanelManagerContext","ids","useMemo","id","config","to"]}
|