import {createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode} from "react"; import {DndContext, PointerSensor, useDraggable, useSensor, useSensors, type DragMoveEvent} from "@dnd-kit/core"; import {DragHandle} from "./DragDrop.js"; import {SplitPane} from "./SplitPane.js"; import {cn} from "./cn.js"; import {dockIds, dockMoveAtPoint, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core"; const DockContext = createContext<{disabled: boolean; onKey: (id: string, event: KeyboardEvent) => void}>({disabled: true, onKey: () => {}}); /** The shared six-dot grip supports pointer dragging and keyboard docking. */ export function DockHandle({id, label}: {id: string; label: string}) { const {disabled, onKey} = useContext(DockContext); const {attributes, listeners, setNodeRef} = useDraggable({id, disabled}); return
onKey(id, event)}>
; } export interface DockLayoutProps { tree: DockTree | null; onTreeChange: (tree: DockTree) => void; panels: {id: string; label: string; minimumSize?: DockMinimum; preferredSize?: DockMinimum}[]; renderPanel: (id: string) => ReactNode; focusedId?: string | null; className?: string; children?: ReactNode; } /** Media stay in stable sibling hosts; only geometry changes, including focus. */ export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId, className, children}: DockLayoutProps) { const host = useRef(null), viewport = useRef(null); // React must not reorder these DOM siblings: moving an iframe node reloads // its browsing context even when its key and portal content are unchanged. const hostOrder = useRef([]); const available = new Set(panels.map(panel => panel.id)); hostOrder.current = hostOrder.current.filter(id => available.has(id)); for (const panel of panels) if (!hostOrder.current.includes(panel.id)) hostOrder.current.push(panel.id); const [bounds, setBounds] = useState({left: 0, top: 0, width: 0, height: 0}); const [active, setActive] = useState(null), [target, setTarget] = useState(null); const [keyboard, setKeyboard] = useState(false); const sensors = useSensors(useSensor(PointerSensor, {activationConstraint: {distance: 6}})); const ids = panels.map(panel => panel.id), visibleTree = pruneDockTree(tree, focusedId ? [focusedId] : ids); const minimums = Object.fromEntries(panels.filter(p => p.minimumSize).map(p => [p.id, p.minimumSize!])); const minimum = dockMinimum(visibleTree, minimums); const canvas = {...bounds, width: Math.max(bounds.width, minimum.width), height: Math.max(bounds.height, minimum.height)}; const preferred = Object.fromEntries(panels.filter(p => p.preferredSize).map(p => [p.id,p.preferredSize!])); const constrained = constrainDockTree(preferDockSizes(visibleTree,canvas,preferred), canvas, minimums); const rects = dockRects(constrained, canvas); const disabled = !!focusedId || ids.length < 2; const reset = () => {setActive(null); setTarget(null); setKeyboard(false);}; useLayoutEffect(() => { const element = host.current!; const measure = () => {const r = element.getBoundingClientRect(); setBounds({left: 0, top: 0, width: r.width, height: r.height});}; measure(); const observer = new ResizeObserver(measure); observer.observe(element); return () => observer.disconnect(); }, []); useEffect(() => {if (disabled || (active && !ids.includes(active))) reset();}, [disabled, panels.map(p => p.id).join("\0")]); // Block iframe hit-testing only during a drag so pointer motion stays in the document. const locate = (event: DragMoveEvent): DockMove | null => { const start = event.activatorEvent as PointerEvent, box = host.current!.getBoundingClientRect(); const x = start.clientX + event.delta.x - box.left, y = start.clientY + event.delta.y - box.top; const view = viewport.current!, screen = view.getBoundingClientRect(); const visible = {left: screen.left + view.clientLeft - box.left, top: screen.top + view.clientTop - box.top, width: view.clientWidth, height: view.clientHeight}; return dockMoveAtPoint(visible, rects, String(event.active.id), x, y); }; // Preview and commit use the same content limits, including a newly enlarged canvas. const projectMove = (move: DockMove | null) => { const next = move && moveDockPanel(constrained, move), required = dockMinimum(next, minimums); const area = {...bounds, width: Math.max(bounds.width, required.width), height: Math.max(bounds.height, required.height)}; return {tree: constrainDockTree(next, area, minimums), area}; }; const commit = (move: DockMove | null) => { const next = projectMove(move).tree; if (next) onTreeChange(next); reset(); }; const onKey = (id: string, event: KeyboardEvent) => { if (disabled) return; if (!keyboard) { if (event.key !== " " && event.key !== "Enter") return; const overId = ids.find(value => value !== id)!; setActive(id); setTarget({activeId: id, overId, position: "center"}); setKeyboard(true); } else if (event.key === "Escape") reset(); else if (event.key === "Enter" || event.key === " ") commit(target); else if (event.key === "Tab") { const candidates = dockIds(visibleTree).filter(value => value !== active), index = candidates.indexOf(target?.overId ?? ""); setTarget({activeId: active!, overId: candidates[(index + (event.shiftKey ? -1 : 1) + candidates.length) % candidates.length], position: target?.position ?? "center"}); } else { const positions = {ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const; const position = positions[event.key as keyof typeof positions]; if (!position || !target) return; setTarget({...target, position, scope: event.shiftKey && position !== "center" ? "workspace" : "panel"}); } event.preventDefault(); event.stopPropagation(); }; const projected = projectMove(target); const preview = target ? dockRects(projected.tree, projected.area)[target.activeId] : null; const action = target ? ({center: "Поменять местами", left: "Слева", right: "Справа", top: "Сверху", bottom: "Снизу"})[target.position] : "Выберите окно и край"; const label = target?.scope === "workspace" ? "Вся область" : target ? panels.find(panel => panel.id === target.overId)?.label : ""; return {setActive(String(event.active.id)); setKeyboard(false);}} onDragMove={event => setTarget(locate(event))} onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
{if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/> {hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel =>
{renderPanel(panel.id)}
)} {active ? : null}
{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край окна, Shift+стрелки — край всей области, Home — обмен, Enter — применить, Escape — отменить.` : ""}
{children}
; } function DockSlots({tree, bounds, minimums, onResize, path = ""}: {tree: DockTree | null; bounds: DockMinimum; minimums: Record; onResize: (path: string, ratio: number) => void; path?: string}) { if (!tree || "id" in tree) return null; const key = tree.axis === "x" ? "width" : "height", span = bounds[key]; return onResize(path, ratio)} separatorLabel="Изменить размеры окон" primary={} secondary={}/>; }