128 lines
9.6 KiB
TypeScript
128 lines
9.6 KiB
TypeScript
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<HTMLDivElement>) => 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 <div ref={setNodeRef} className="nodedc-dock-layout__handle" onKeyDown={event => onKey(id, event)}>
|
|
<DragHandle label={`Переместить · ${label}`} attributes={{...attributes, "aria-disabled": disabled}} listeners={listeners}/>
|
|
</div>;
|
|
}
|
|
|
|
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<HTMLDivElement>(null), viewport = useRef<HTMLDivElement>(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<string[]>([]);
|
|
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<DockRect>({left: 0, top: 0, width: 0, height: 0});
|
|
const [active, setActive] = useState<string | null>(null), [target, setTarget] = useState<DockMove | null>(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<HTMLDivElement>) => {
|
|
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 <DndContext sensors={sensors} autoScroll={false}
|
|
onDragStart={event => {setActive(String(event.active.id)); setKeyboard(false);}}
|
|
onDragMove={event => setTarget(locate(event))}
|
|
onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
|
|
<DockContext.Provider value={{disabled, onKey}}>
|
|
<div ref={viewport} className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
|
|
<div ref={host} className="nodedc-dock-layout__canvas" style={{minWidth:minimum.width, minHeight:minimum.height}}>
|
|
<DockSlots tree={constrained} bounds={canvas} minimums={minimums} onResize={(path, ratio) => {if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/>
|
|
{hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel => <div key={panel.id} className="nodedc-dock-layout__panel" data-dock-id={panel.id}
|
|
data-dock-source={active === panel.id ? "true" : undefined} style={rects[panel.id] ?? {display: "none"}}>{renderPanel(panel.id)}</div>)}
|
|
{active ? <div className="nodedc-dock-layout__overlay" aria-hidden="true">
|
|
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} data-dock-scope={target!.scope ?? "panel"} style={preview}><span>{action} · {label}</span></div> : null}
|
|
</div> : null}
|
|
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край окна, Shift+стрелки — край всей области, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
|
|
</div>
|
|
</div>
|
|
{children}
|
|
</DockContext.Provider>
|
|
</DndContext>;
|
|
}
|
|
|
|
function DockSlots({tree, bounds, minimums, onResize, path = ""}: {tree: DockTree | null; bounds: DockMinimum; minimums: Record<string,DockMinimum>; 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 <SplitPane className="nodedc-dock-layout__split" separatorAppearance="invisible" orientation={tree.axis === "x" ? "vertical" : "horizontal"}
|
|
primarySize={tree.ratio} minPrimarySize={span ? dockMinimum(tree.first,minimums)[key]/span*100 : 0} minSecondarySize={span ? dockMinimum(tree.second,minimums)[key]/span*100 : 0} onPrimarySizeChange={ratio => onResize(path, ratio)} separatorLabel="Изменить размеры окон"
|
|
primary={<DockSlots tree={tree.first} bounds={{...bounds,[key]:span*tree.ratio/100}} minimums={minimums} onResize={onResize} path={path + "0"}/>}
|
|
secondary={<DockSlots tree={tree.second} bounds={{...bounds,[key]:span*(1-tree.ratio/100)}} minimums={minimums} onResize={onResize} path={path + "1"}/>}/>;
|
|
}
|