feat(scene-editor): add persistent dockable tool workspaces
This commit is contained in:
@@ -72,3 +72,6 @@
|
||||
--nodedc-font-weight-medium: 620;
|
||||
--nodedc-font-weight-strong: 760;
|
||||
}
|
||||
|
||||
/* Readable V4 telemetry over moving scene imagery; independent of modal opacity. */
|
||||
:root { --nodedc-scene-glass-opacity: .52; --nodedc-scene-glass-blur: 18px; }
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import {decodeDockTree,dockIds,dockPosition,pruneDockTree,type DockTree,type DockRect,type DockMove} from './dockTree.js';
|
||||
|
||||
/** The primary view is permanent. Tools can leave the split tree without losing their identity. */
|
||||
export interface EditorDockState {tree:DockTree;floating:Record<string,DockRect>}
|
||||
export function decodeEditorDock(raw:unknown,primary:string,tools:readonly string[]):EditorDockState|null {
|
||||
if(!raw||typeof raw!=='object')return null;
|
||||
const value=raw as Partial<EditorDockState>,allowed=[primary,...tools];
|
||||
let tree=pruneDockTree(decodeDockTree(value.tree),allowed);
|
||||
if(!dockIds(tree).includes(primary))tree=tree?{axis:'x',ratio:70,first:{id:primary},second:tree}:{id:primary};
|
||||
const floating:Record<string,DockRect>={};
|
||||
for(const id of tools){const r=value.floating?.[id];if(!r||!['left','top','width','height'].every(k=>Number.isFinite(r[k as keyof DockRect]))||r.width<=0||r.height<=0)continue;
|
||||
floating[id]={left:Math.max(-16384,Math.min(16384,r.left)),top:Math.max(-16384,Math.min(16384,r.top)),width:Math.min(16384,r.width),height:Math.min(16384,r.height)};
|
||||
}
|
||||
return {tree:tree!,floating};
|
||||
}
|
||||
|
||||
/** Inserts an absent/floating tool, or moves an existing tool. Never swaps the primary view. */
|
||||
export function dockEditorTool(state:EditorDockState,primary:string,move:DockMove|null,id:string,rect:DockRect):EditorDockState {
|
||||
if(id===primary)return state;
|
||||
const remaining=pruneDockTree(state.tree,dockIds(state.tree).filter(v=>v!==id))??{id:primary};
|
||||
const floating={...state.floating,[id]:rect};
|
||||
if(!move||move.position==='center'||(move.scope!=='workspace'&&!dockIds(remaining).includes(move.overId)))return {tree:remaining,floating};
|
||||
const before=move.position==='left'||move.position==='top',axis=move.position==='left'||move.position==='right'?'x':'y';
|
||||
const wrap=(node:DockTree,ratio:number):DockTree=>({axis,ratio:before?ratio:100-ratio,first:before?{id}:node,second:before?node:{id}});
|
||||
const insert=(node:DockTree):DockTree=>'id' in node?(node.id===move.overId?wrap(node,50):node):{...node,first:insert(node.first),second:insert(node.second)};
|
||||
return {tree:move.scope==='workspace'?wrap(remaining,axis==='x'?25:28):insert(remaining),floating};
|
||||
}
|
||||
|
||||
/** Outer edge has priority; broad magnets fill the gap between a tool and the viewport. */
|
||||
export function editorDockTarget(bounds:DockRect,rects:Record<string,DockRect>,primary:string,id:string,x:number,y:number):DockMove|null {
|
||||
if(!dockPosition(bounds,x,y))return null;
|
||||
const edges:[DockMove['position'],number][]=[['left',x-bounds.left],['right',bounds.left+bounds.width-x],['top',y-bounds.top],['bottom',bounds.top+bounds.height-y]];
|
||||
const nearest=edges.slice().sort((a,b)=>a[1]-b[1])[0];
|
||||
if(nearest[1]<=24)return {activeId:id,overId:primary,position:nearest[0],scope:'workspace'};
|
||||
for(const [target,r] of Object.entries(rects)){
|
||||
if(target===id||target===primary||!dockPosition(r,x,y))continue;
|
||||
const distances:[DockMove['position'],number][]=[['left',(x-r.left)/r.width],['right',(r.left+r.width-x)/r.width],['top',(y-r.top)/r.height],['bottom',(r.top+r.height-y)/r.height]];
|
||||
return {activeId:id,overId:target,position:distances.sort((a,b)=>a[1]-b[1])[0][0],scope:'panel'};
|
||||
}
|
||||
const magnets=edges.map(([position,distance])=>[position,distance/Math.min(position==='left'||position==='right'?160:96,(position==='left'||position==='right'?bounds.width:bounds.height)*.16)] as const).sort((a,b)=>a[1]-b[1]);
|
||||
return magnets[0][1]<=1?{activeId:id,overId:primary,position:magnets[0][0],scope:'workspace'}:null;
|
||||
}
|
||||
|
||||
/** Resize visible splits while retaining the positions of temporarily closed tools. */
|
||||
export function mergeEditorDockRatios(full:DockTree,visible:DockTree):DockTree {
|
||||
const ids=dockIds(visible),ratios=new Map<string,number>();
|
||||
const key=(node:DockTree)=>dockIds(node).sort().join('\0');
|
||||
const collect=(node:DockTree)=>{if('id' in node)return;ratios.set(key(node),node.ratio);collect(node.first);collect(node.second);};collect(visible);
|
||||
const merge=(node:DockTree):DockTree=>{
|
||||
if('id' in node)return node;
|
||||
const a=pruneDockTree(node.first,ids),b=pruneDockTree(node.second,ids),shown=pruneDockTree(node,ids);
|
||||
return {...node,ratio:a&&b&&shown?(ratios.get(key(shown))??node.ratio):node.ratio,first:merge(node.first),second:merge(node.second)};
|
||||
};return merge(full);
|
||||
}
|
||||
@@ -29,12 +29,16 @@ function clamp(value: number, min: number, max: number) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
export function createGlassMaterialVariables(settings: GlassMaterialSettings): Record<string, string> {
|
||||
export function createGlassMaterialVariables(settings: GlassMaterialSettings, context: "floating" | "scene" = "floating"): Record<string, string> {
|
||||
const tintHex = normalizeHex(settings.tintHex);
|
||||
const red = Number.parseInt(tintHex.slice(1, 3), 16);
|
||||
const green = Number.parseInt(tintHex.slice(3, 5), 16);
|
||||
const blue = Number.parseInt(tintHex.slice(5, 7), 16);
|
||||
return {
|
||||
...(context === "scene" ? {
|
||||
"--nodedc-scene-glass-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
|
||||
"--nodedc-scene-glass-blur": `${clamp(settings.blur, 0, 120)}px`,
|
||||
} : {}),
|
||||
"--nodedc-modal-glass-tint-rgb": `${red} ${green} ${blue}`,
|
||||
"--nodedc-modal-glass-tint-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
|
||||
"--nodedc-blur-modal": `${clamp(settings.blur, 0, 120)}px`,
|
||||
|
||||
@@ -12,3 +12,4 @@ export {dockMinimum, constrainDockTree, type DockMinimum, type DockMinimums} fro
|
||||
export {preferDockSizes} from "./dockTree.js";
|
||||
|
||||
export * from "./menuAim.js";
|
||||
export * from "./editorDock.js";
|
||||
|
||||
+116
-1
@@ -1565,7 +1565,8 @@ textarea.nodedc-field__control {
|
||||
height: calc(100vh - var(--nodedc-app-header-height));
|
||||
min-height: 0;
|
||||
margin-top: var(--nodedc-app-header-height);
|
||||
overflow: hidden;
|
||||
/* Translated inactive stages must not become a focus-scroll destination. */
|
||||
overflow: clip;
|
||||
}
|
||||
|
||||
.nodedc-app-shell__stage {
|
||||
@@ -4519,6 +4520,29 @@ textarea.nodedc-field__control {
|
||||
/* Content minimums govern resizing; an undersized viewport scrolls the canvas. */
|
||||
.nodedc-dock-layout {overflow:auto; overscroll-behavior:contain;}
|
||||
.nodedc-dock-layout__canvas {position:relative; height:100%; width:100%;}
|
||||
|
||||
/* Shared editor workspace: its header is outside the docking bounds. */
|
||||
.nodedc-editor-workspace__slot,.nodedc-editor-workspace__host,.nodedc-editor-workspace {position:relative;width:100%;height:100%;min-width:0;min-height:0;}
|
||||
.nodedc-editor-workspace {display:flex;flex-direction:column;}
|
||||
.nodedc-editor-workspace__host[data-editing="true"] {position:fixed;inset:var(--nodedc-space-4);width:auto;height:auto;z-index:calc(var(--nodedc-layer-overlay) - 1);background:var(--nodedc-app-panel-surface);border-radius:var(--nodedc-radius-panel);box-shadow:var(--nodedc-modal-shadow);overflow:hidden;}
|
||||
.nodedc-editor-workspace__host[data-editing="true"][data-expanded="true"] {inset:0;border-radius:0;}
|
||||
.nodedc-editor-workspace__head {flex:none;}
|
||||
.nodedc-editor-workspace__body {position:relative;flex:1;min-height:0;min-width:0;overflow:hidden;}
|
||||
.nodedc-editor-dock {position:absolute;inset:0;overflow:auto;overscroll-behavior:contain;isolation:isolate;}
|
||||
.nodedc-editor-dock__canvas {position:relative;width:100%;height:100%;}
|
||||
.nodedc-editor-dock__primary {position:absolute;overflow:hidden;min-width:0;min-height:0;}
|
||||
.nodedc-editor-dock__tool {position:absolute;display:flex;flex-direction:column;box-sizing:border-box;min-width:0;min-height:0;}
|
||||
.nodedc-editor-dock__tool[hidden] {display:none;}
|
||||
.nodedc-editor-dock__tool:not([data-floating]) {border-radius:0;box-shadow:none;}
|
||||
.nodedc-editor-dock__tool::before {display:none;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head {flex:none;cursor:grab;touch-action:none;user-select:none;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head:active {cursor:grabbing;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head:focus-visible {outline:2px solid var(--nodedc-text-primary);outline-offset:-3px;}
|
||||
.nodedc-editor-dock__body {flex:1;min-height:0;min-width:0;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;padding:0 var(--nodedc-space-3) var(--nodedc-space-3);}
|
||||
.nodedc-editor-dock__tool .nodedc-inspector {width:100%;max-width:none;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__footer {flex:none;}
|
||||
.nodedc-editor-dock__shield {position:absolute;inset:0;z-index:30;cursor:grabbing;}
|
||||
.nodedc-editor-dock__preview {z-index:50;pointer-events:none;}
|
||||
.nodedc-comparison-table[data-density="compact"] table {min-width:calc(7.5rem + (var(--nodedc-comparison-columns) - 1) * 5.5rem); table-layout:fixed; line-height:1.25;}
|
||||
.nodedc-comparison-table[data-density="compact"] col:first-child {width:7.5rem;}
|
||||
.nodedc-comparison-table[data-density="compact"] th, .nodedc-comparison-table[data-density="compact"] td {padding:3px var(--nodedc-space-1);}
|
||||
@@ -4547,3 +4571,94 @@ textarea.nodedc-field__control {
|
||||
.nodedc-navigation-cube g.is-hovered polygon, .nodedc-navigation-cube g:focus-visible polygon { fill: var(--cube-hover, var(--nodedc-control-selected-bg, #eee)); }
|
||||
.nodedc-navigation-cube g.is-hovered text, .nodedc-navigation-cube g:focus-visible text { fill: var(--cube-hover-text, var(--nodedc-control-selected-text, #161616)); }
|
||||
.nodedc-navigation-cube g[aria-disabled="true"] { opacity: .45; cursor: default; }
|
||||
|
||||
.nodedc-window__resize:is([data-edge="n"], [data-edge="s"]) { cursor: ns-resize; }
|
||||
.nodedc-window__resize:is([data-edge="e"], [data-edge="w"]) { cursor: ew-resize; }
|
||||
.nodedc-window__resize:is([data-edge="ne"], [data-edge="sw"]) { cursor: nesw-resize; }
|
||||
.nodedc-window__resize:is([data-edge="nw"], [data-edge="se"]) { cursor: nwse-resize; }
|
||||
.nodedc-window[data-floating="true"] > .nodedc-window__head { cursor: move; }
|
||||
|
||||
/* Modeless mode retains the same mounted window and form. */
|
||||
.nodedc-overlay[data-floating="true"] {
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
pointer-events: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
.nodedc-window[data-floating="true"] { pointer-events: auto; }
|
||||
.nodedc-window[data-floating="true"] > .nodedc-window__head { touch-action: none; user-select: none; }
|
||||
.nodedc-window__resize { position: absolute; z-index: 3; touch-action: none; }
|
||||
.nodedc-window__resize[data-edge="n"] { top: 0; left: 12px; right: 12px; height: 6px; }
|
||||
.nodedc-window__resize[data-edge="s"] { bottom: 0; left: 12px; right: 12px; height: 6px; }
|
||||
.nodedc-window__resize[data-edge="e"] { right: 0; top: 12px; bottom: 12px; width: 6px; }
|
||||
.nodedc-window__resize[data-edge="w"] { left: 0; top: 12px; bottom: 12px; width: 6px; }
|
||||
.nodedc-window__resize[data-edge="ne"] { top: 0; right: 0; width: 12px; height: 12px; }
|
||||
.nodedc-window__resize[data-edge="nw"] { top: 0; left: 0; width: 12px; height: 12px; }
|
||||
.nodedc-window__resize[data-edge="se"] { bottom: 0; right: 0; width: 12px; height: 12px; }
|
||||
.nodedc-window__resize[data-edge="sw"] { bottom: 0; left: 0; width: 12px; height: 12px; }
|
||||
/* An inspector in a settings window follows the available content width. */
|
||||
.nodedc-window__body .nodedc-inspector,
|
||||
.nodedc-window__body .nodedc-control-row { width: 100%; min-width: 0; }
|
||||
|
||||
|
||||
.nodedc-feature-settings-window > .nodedc-window__body { container: nodedc-settings / inline-size; }
|
||||
@container nodedc-settings (max-width: 42rem) {
|
||||
.nodedc-feature-settings { grid-template-columns:minmax(0,1fr); grid-template-rows:auto minmax(0,1fr); }
|
||||
.nodedc-feature-settings__navigation { max-height:10rem; }
|
||||
}
|
||||
|
||||
/* Compact outliner: rows, indentation and selection; no nested card surfaces. */
|
||||
.nodedc-tree { overflow:auto; min-height:0; overscroll-behavior:contain; font-size:var(--nodedc-font-size-sm); }
|
||||
.nodedc-tree__row { display:flex; align-items:center; gap:6px; min-height:28px; padding:2px 6px 2px calc(4px + var(--tree-depth) * 14px); box-sizing:border-box; cursor:default; user-select:none; color:var(--nodedc-text-secondary); }
|
||||
.nodedc-tree__row:hover { background:rgb(var(--nodedc-accent-rgb) / .06); }
|
||||
.nodedc-tree__row[aria-selected="true"] { background:rgb(var(--nodedc-accent-rgb) / .14); color:var(--nodedc-text-primary); }
|
||||
.nodedc-tree__row:focus-visible { outline:2px solid var(--nodedc-accent); outline-offset:-2px; }
|
||||
.nodedc-tree__row > svg { flex:0 0 auto; }
|
||||
.nodedc-tree__branch { display:flex; flex:0 0 16px; }
|
||||
.nodedc-tree__label { flex:1; min-width:0; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
|
||||
.nodedc-tree button { appearance:none; border:0; padding:2px; background:transparent; color:inherit; display:flex; align-items:center; justify-content:center; width:20px; height:22px; cursor:pointer; }
|
||||
.nodedc-tree button:focus-visible { outline:2px solid var(--nodedc-accent); }
|
||||
.nodedc-tree__visibility { flex:0 0 20px; opacity:.6; }
|
||||
.nodedc-tree__visibility:hover { opacity:1; }
|
||||
.nodedc-window[data-resizable="true"] { display:flex; flex-direction:column; }
|
||||
.nodedc-window[data-resizable="true"] > .nodedc-window__body { flex:1; min-height:0; }
|
||||
|
||||
.nodedc-glass-material[data-radius="panel"] { border-radius:var(--nodedc-radius-panel); }
|
||||
.nodedc-glass-material[data-radius="card"] { border-radius:var(--nodedc-radius-card); }
|
||||
.nodedc-glass-material[data-radius="pill"] { border-radius:var(--nodedc-radius-circle); }
|
||||
.nodedc-glass-material[data-glass-context="scene"] {
|
||||
background:rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
|
||||
backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
-webkit-backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
box-shadow:var(--nodedc-glass-panel-shadow);
|
||||
}
|
||||
.nodedc-resizable-viewport { position:relative; min-width:0; isolation:isolate; }
|
||||
.nodedc-resizable-viewport__grip {
|
||||
position:absolute; z-index:4; bottom:0; width:28px; height:28px;
|
||||
color:var(--nodedc-text-secondary); cursor:ns-resize; touch-action:none; user-select:none;
|
||||
border-radius:var(--nodedc-radius-sm);
|
||||
}
|
||||
.nodedc-resizable-viewport__grip[data-corner="end"] { right:0; }
|
||||
.nodedc-resizable-viewport__grip[data-corner="start"] { left:0; transform:scaleX(-1); }
|
||||
.nodedc-resizable-viewport__grip::before, .nodedc-resizable-viewport__grip::after {
|
||||
content:""; position:absolute; right:5px; bottom:5px;
|
||||
border-right:1px solid currentColor; border-bottom:1px solid currentColor;
|
||||
}
|
||||
.nodedc-resizable-viewport__grip::before { width:12px; height:12px; }
|
||||
.nodedc-resizable-viewport__grip::after { width:6px; height:6px; }
|
||||
.nodedc-resizable-viewport__grip:hover { color:var(--nodedc-text-primary); background:var(--nodedc-glass-control-hover); }
|
||||
.nodedc-resizable-viewport__grip:focus-visible { outline:2px solid rgb(var(--nodedc-accent-rgb)); outline-offset:-3px; }
|
||||
.nodedc-panel-viewport-anchor, .nodedc-panel-viewport-anchor > div, .nodedc-panel-viewport { height:100%; min-height:0; }
|
||||
.nodedc-panel-viewport[data-fullscreen="true"] { position:fixed; inset:var(--nodedc-space-3); height:auto; z-index:calc(var(--nodedc-layer-overlay) - 1); }
|
||||
.nodedc-panel-viewport[data-fullscreen="true"] > .nodedc-application-panel { animation:none; }
|
||||
|
||||
.nodedc-resizable-viewport[data-resize-indicator="hidden"] .nodedc-resizable-viewport__grip::before,
|
||||
.nodedc-resizable-viewport[data-resize-indicator="hidden"] .nodedc-resizable-viewport__grip::after { display:none; }
|
||||
.nodedc-resizable-viewport[data-resize-indicator="hidden"] .nodedc-resizable-viewport__grip:hover { background:transparent; }
|
||||
.nodedc-scene-annotation.nodedc-button { min-width:0; padding:var(--nodedc-space-1); background:transparent; text-shadow:0 1px 4px rgb(0 0 0 / .85); }
|
||||
.nodedc-scene-annotation .nodedc-button__content { display:grid; gap:0; text-align:center; font-variant-numeric:tabular-nums; }
|
||||
.nodedc-scene-annotation:hover, .nodedc-scene-annotation[aria-pressed="true"] { background:var(--nodedc-glass-control-hover); }
|
||||
.nodedc-scene-annotation[aria-pressed="true"] { box-shadow:var(--nodedc-glass-control-shadow); }
|
||||
|
||||
.nodedc-scene-annotation.nodedc-button[hidden] { display:none; }
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import {createContext, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
|
||||
const FullscreenContext = createContext<{fullscreen:boolean; setFullscreen:(value:boolean)=>void} | null>(null);
|
||||
/** Shared full-window presentation. Portaled inspectors remain above the panel. */
|
||||
export const useApplicationPanelFullscreen = () => useContext(FullscreenContext);
|
||||
export function ApplicationPanelFullscreen({children}: {children:ReactNode}) {
|
||||
const [fullscreen,setFullscreen] = useState(false);
|
||||
const [mount] = useState(() => typeof document === "undefined" ? null : document.createElement("div"));
|
||||
const anchor = useRef<HTMLDivElement>(null);
|
||||
const value = useMemo(() => ({fullscreen,setFullscreen}), [fullscreen]);
|
||||
useLayoutEffect(() => {
|
||||
if (!mount || !anchor.current) return;
|
||||
anchor.current.append(mount);
|
||||
return () => mount.remove();
|
||||
}, [mount]);
|
||||
useLayoutEffect(() => {
|
||||
if (!mount || !anchor.current) return;
|
||||
const target = (fullscreen ? document.body : anchor.current) as HTMLElement & {moveBefore?:(node:Node, before:Node|null)=>void};
|
||||
if (mount.parentElement !== target) {
|
||||
if (target.moveBefore) target.moveBefore(mount, null); else target.append(mount);
|
||||
}
|
||||
}, [fullscreen,mount]);
|
||||
const content = <FullscreenContext.Provider value={value}><div className="nodedc-panel-viewport nodedc-ui-root" data-fullscreen={fullscreen || undefined}>{children}</div></FullscreenContext.Provider>;
|
||||
return mount ? <><div ref={anchor} className="nodedc-panel-viewport-anchor"/>{createPortal(content,mount)}</> : content;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
import {ApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
|
||||
export interface ApplicationShellProps extends Omit<HTMLAttributes<HTMLDivElement>, "content"> {
|
||||
@@ -52,6 +53,8 @@ export interface ApplicationPanelProps extends Omit<HTMLAttributes<HTMLElement>,
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
expanded?: boolean;
|
||||
/** Enables full-window presentation requested by an owned viewer through context. */
|
||||
allowFullscreen?: boolean;
|
||||
expandLabel?: string;
|
||||
closeLabel?: string;
|
||||
onExpandedChange?: (expanded: boolean) => void;
|
||||
@@ -76,6 +79,7 @@ export function ApplicationPanel({
|
||||
title,
|
||||
description,
|
||||
expanded = false,
|
||||
allowFullscreen = false,
|
||||
expandLabel = "Развернуть окно",
|
||||
closeLabel = "Закрыть окно",
|
||||
onExpandedChange,
|
||||
@@ -86,7 +90,7 @@ export function ApplicationPanel({
|
||||
className,
|
||||
...props
|
||||
}: ApplicationPanelProps) {
|
||||
return (
|
||||
const panel = (
|
||||
<section className={cn("nodedc-application-panel", className)} data-expanded={expanded ? "true" : undefined} {...props}>
|
||||
<header className="nodedc-application-panel__head">
|
||||
<div className="nodedc-application-panel__titles">
|
||||
@@ -131,4 +135,5 @@ export function ApplicationPanel({
|
||||
<div className="nodedc-application-panel__body">{children}</div>
|
||||
</section>
|
||||
);
|
||||
return allowFullscreen ? <ApplicationPanelFullscreen>{panel}</ApplicationPanelFullscreen> : panel;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { ReactNode } from "react";
|
||||
import {createContext, useContext, useEffect, useRef, useState, type ReactNode} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
DragOverlay,
|
||||
PointerSensor,
|
||||
useDraggable,
|
||||
useDroppable,
|
||||
@@ -36,6 +38,8 @@ export interface DragDropResult {
|
||||
overData?: NodedcDragData;
|
||||
activeRect?: DragRect;
|
||||
overRect?: DragRect;
|
||||
/** Client coordinates of the pointer, for exact canvas/object drop targets. */
|
||||
pointer?: {x:number;y:number};
|
||||
}
|
||||
|
||||
const copyRect = (rect: DragRect | null | undefined): DragRect | undefined => rect ? ({
|
||||
@@ -70,9 +74,15 @@ export function DragHandle({ label = "Перетащить", listeners, attribut
|
||||
);
|
||||
}
|
||||
|
||||
export function DragDropRoot({ children, onDragEnd }: { children: ReactNode; onDragEnd: (result: DragDropResult) => void }) {
|
||||
const DragOverlayContext=createContext(false);
|
||||
export function DragDropRoot({ children, onDragEnd, renderOverlay }: { children: ReactNode; onDragEnd: (result: DragDropResult) => void; renderOverlay?:(item:{id:string;data?:NodedcDragData})=>ReactNode }) {
|
||||
const [active,setActive]=useState<{id:string;data?:NodedcDragData}|null>(null);
|
||||
const dragging=useRef(false),pointer=useRef<{x:number;y:number}|undefined>(undefined);
|
||||
useEffect(()=>{const track=(event:PointerEvent)=>{if(dragging.current)pointer.current={x:event.clientX,y:event.clientY};};window.addEventListener('pointermove',track,true);window.addEventListener('pointerup',track,true);return()=>{window.removeEventListener('pointermove',track,true);window.removeEventListener('pointerup',track,true);};},[]);
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
setActive(null);dragging.current=false;
|
||||
const origin=event.activatorEvent as PointerEvent;
|
||||
onDragEnd({
|
||||
activeId: String(event.active.id),
|
||||
overId: event.over ? String(event.over.id) : null,
|
||||
@@ -80,25 +90,27 @@ export function DragDropRoot({ children, onDragEnd }: { children: ReactNode; onD
|
||||
overData: event.over?.data.current as NodedcDragData | undefined,
|
||||
activeRect: copyRect(event.active.rect.current.translated),
|
||||
overRect: copyRect(event.over?.rect),
|
||||
pointer: pointer.current??(typeof origin.clientX==='number'?{x:origin.clientX+event.delta.x,y:origin.clientY+event.delta.y}:undefined),
|
||||
});
|
||||
};
|
||||
return <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>{children}</DndContext>;
|
||||
return <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={event=>{dragging.current=true;pointer.current=undefined;setActive({id:String(event.active.id),data:event.active.data.current});}} onDragCancel={()=>{dragging.current=false;setActive(null);}} onDragEnd={handleDragEnd}><DragOverlayContext.Provider value={!!renderOverlay}>{children}</DragOverlayContext.Provider>{renderOverlay&&typeof document!=='undefined'&&createPortal(<DragOverlay dropAnimation={null} style={{pointerEvents:"none"}}>{active?renderOverlay(active):null}</DragOverlay>,document.fullscreenElement??document.body)}</DndContext>;
|
||||
}
|
||||
|
||||
export function DraggableItem({ id, data, className, children }: {
|
||||
id: string;
|
||||
data?: NodedcDragData;
|
||||
className?: string;
|
||||
children: (state: { handle: ReactNode; isDragging: boolean }) => ReactNode;
|
||||
children: (state: { handle: ReactNode; isDragging: boolean; activator: {attributes:ReturnType<typeof useDraggable>["attributes"];listeners:ReturnType<typeof useDraggable>["listeners"]} }) => ReactNode;
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id, data });
|
||||
const overlay=useContext(DragOverlayContext);
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
className={cn(className, isDragging && "is-dragging")}
|
||||
style={{ transform: CSS.Translate.toString(transform), opacity: isDragging ? 0.65 : undefined }}
|
||||
style={{ transform: overlay?undefined:CSS.Translate.toString(transform), opacity: isDragging ? 0.65 : undefined }}
|
||||
>
|
||||
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging })}
|
||||
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging, activator:{attributes,listeners} })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import {useEffect,useLayoutEffect,useRef,useState,type KeyboardEvent,type PointerEvent,type ReactNode} from 'react';
|
||||
import {constrainDockTree,dockIds,dockMinimum,dockRects,dockEditorTool,editorDockTarget,mergeEditorDockRatios,pruneDockTree,resizeDockSplit,type DockMinimum,type DockMove,type DockRect,type DockTree,type EditorDockState} from '@nodedc/ui-core';
|
||||
import {IconButton} from './Button.js';
|
||||
import {Icon} from './Icon.js';
|
||||
import {SplitPane} from './SplitPane.js';
|
||||
import {InspectorSelectPolicyContext} from './InspectorContext.js';
|
||||
import {LoadingContext} from './LoadingContext.js';
|
||||
import {fitWindow,resizeWindow,windowResizeEdges,type ResizeEdge} from './windowGeometry.js';
|
||||
import {cn} from './cn.js';
|
||||
|
||||
export interface EditorDockTool {
|
||||
id:string;title:ReactNode;label:string;open:boolean;onClose:()=>void;content:ReactNode;
|
||||
subtitle?:ReactNode;actions?:ReactNode;footer?:ReactNode;className?:string;
|
||||
minimumSize?:DockMinimum;initialRect?:DockRect;activationKey?:string|number;
|
||||
}
|
||||
export interface EditorDockLayoutProps {
|
||||
value:EditorDockState;onChange:(value:EditorDockState)=>void;
|
||||
primary:ReactNode;primaryId?:string;primaryMinimum?:DockMinimum;
|
||||
tools:EditorDockTool[];enabled?:boolean;className?:string;
|
||||
}
|
||||
type Gesture={id:string;pointer:number;x:number;y:number;rect:DockRect;edge?:ResizeEdge;moved:boolean;current:DockRect;target:DockMove|null};
|
||||
const actionNames={left:'Слева',right:'Справа',top:'Сверху',bottom:'Снизу',center:'Рядом'};
|
||||
/** A locked primary renderer, docked tools and floating tools share stable sibling hosts. */
|
||||
export function EditorDockLayout({value,onChange,primary,primaryId='viewport',primaryMinimum={width:320,height:240},tools,enabled=true,className}:EditorDockLayoutProps){
|
||||
const host=useRef<HTMLDivElement>(null),viewport=useRef<HTMLDivElement>(null);
|
||||
const [bounds,setBounds]=useState<DockRect>({left:0,top:0,width:1,height:1});
|
||||
const [drag,setDrag]=useState<Gesture|null>(null),gesture=useRef<Gesture|null>(null);
|
||||
const [order,setOrder]=useState<string[]>([]),[keyboard,setKeyboard]=useState<{id:string;target:DockMove|null}|null>(null);
|
||||
const previousTools=useRef(new Map<string,{open:boolean;key?:string|number}>());
|
||||
useEffect(()=>{
|
||||
const raised=tools.filter(t=>t.open&&(!previousTools.current.get(t.id)?.open||previousTools.current.get(t.id)?.key!==t.activationKey)).map(t=>t.id);
|
||||
previousTools.current=new Map(tools.map(t=>[t.id,{open:t.open,key:t.activationKey}]));
|
||||
if(enabled&&raised.length)setOrder(v=>[...v.filter(id=>!raised.includes(id)),...raised]);
|
||||
});
|
||||
const visible=[primaryId,...tools.filter(t=>enabled&&t.open).map(t=>t.id)];
|
||||
const minimums={...Object.fromEntries(tools.map(t=>[t.id,t.minimumSize??{width:280,height:180}])),[primaryId]:primaryMinimum};
|
||||
const visibleTree=pruneDockTree(value.tree,visible)??{id:primaryId};
|
||||
const required=dockMinimum(visibleTree,minimums),area={...bounds,width:Math.max(bounds.width,required.width),height:Math.max(bounds.height,required.height)};
|
||||
const constrained=constrainDockTree(visibleTree,area,minimums)!;
|
||||
const rects=dockRects(constrained,area);
|
||||
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds);
|
||||
const latest=useRef({value,onChange,rects,bounds,enabled,tools});latest.current={value,onChange,rects,bounds,enabled,tools};
|
||||
const activate=(id:string)=>setOrder(v=>[...v.filter(x=>x!==id),id]);
|
||||
useLayoutEffect(()=>{const v=viewport.current!;const measure=()=>setBounds({left:0,top:0,width:v.clientWidth,height:v.clientHeight});measure();const ro=new ResizeObserver(measure);ro.observe(v);return()=>ro.disconnect();},[]);
|
||||
const point=(e:{clientX:number;clientY:number})=>{const r=host.current!.getBoundingClientRect();return {x:e.clientX-r.left,y:e.clientY-r.top};};
|
||||
const begin=(id:string,e:PointerEvent<HTMLElement>,edge?:ResizeEdge)=>{
|
||||
if(!enabled||e.button!==0||gesture.current||(!edge&&(e.target as HTMLElement).closest('button,input,select,textarea,a,[role=slider]')))return;
|
||||
const p=point(e),docked=rects[id],saved=floatingRect(id);
|
||||
const rect=docked?{...saved,left:p.x-Math.min(saved.width-24,Math.max(24,p.x-docked.left)),top:p.y-Math.min(48,p.y-docked.top)}:saved;
|
||||
gesture.current={id,pointer:e.pointerId,x:p.x,y:p.y,rect,edge,moved:false,current:rect,target:null};
|
||||
e.currentTarget.setPointerCapture(e.pointerId);e.currentTarget.focus();activate(id);setKeyboard(null);e.preventDefault();e.stopPropagation();
|
||||
};
|
||||
useEffect(()=>{
|
||||
const move=(e:globalThis.PointerEvent)=>{
|
||||
const g=gesture.current;if(!g||e.pointerId!==g.pointer)return;
|
||||
const p=point(e),dx=p.x-g.x,dy=p.y-g.y;
|
||||
if(!g.moved&&Math.hypot(dx,dy)<6)return;
|
||||
g.moved=true;
|
||||
const b=latest.current.bounds;
|
||||
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b);
|
||||
const visibleBounds={...b,left:viewport.current?.scrollLeft??0,top:viewport.current?.scrollTop??0};
|
||||
g.target=g.edge?null:editorDockTarget(visibleBounds,latest.current.rects,primaryId,g.id,p.x,p.y);
|
||||
setDrag({...g});e.preventDefault();
|
||||
};
|
||||
const finish=(e:globalThis.PointerEvent)=>{
|
||||
const g=gesture.current;if(!g||g.pointer!==e.pointerId)return;
|
||||
if(e.type==='pointerup'&&g.moved){const v=latest.current;v.onChange(g.edge?{...v.value,floating:{...v.value.floating,[g.id]:g.current}}:dockEditorTool(v.value,primaryId,g.target,g.id,g.current));}
|
||||
gesture.current=null;setDrag(null);
|
||||
};
|
||||
const cancel=(e:globalThis.KeyboardEvent)=>{if(e.key==='Escape'&&gesture.current){gesture.current=null;setDrag(null);e.preventDefault();e.stopPropagation();}};
|
||||
const blur=()=>{gesture.current=null;setDrag(null);};
|
||||
window.addEventListener('pointermove',move,{passive:false});window.addEventListener('pointerup',finish);window.addEventListener('pointercancel',finish);window.addEventListener('keydown',cancel,true);window.addEventListener('blur',blur);
|
||||
return()=>{window.removeEventListener('pointermove',move);window.removeEventListener('pointerup',finish);window.removeEventListener('pointercancel',finish);window.removeEventListener('keydown',cancel,true);window.removeEventListener('blur',blur);};
|
||||
},[primaryId]);
|
||||
useEffect(()=>{if(!enabled||!tools.some(t=>t.open&&t.id===(gesture.current?.id??keyboard?.id))){gesture.current=null;setDrag(null);setKeyboard(null);}},[enabled,tools.map(t=>`${t.id}:${t.open}`).join('|')]);
|
||||
const key=(id:string,e:KeyboardEvent<HTMLElement>)=>{
|
||||
if(e.target!==e.currentTarget)return;
|
||||
const positions={ArrowLeft:'left',ArrowRight:'right',ArrowUp:'top',ArrowDown:'bottom'} as const,position=positions[e.key as keyof typeof positions];
|
||||
if(keyboard?.id===id){
|
||||
if(e.key==='Escape')setKeyboard(null);
|
||||
else if(e.key==='Enter'||e.key===' '){onChange(dockEditorTool(value,primaryId,keyboard.target,id,floatingRect(id)));setKeyboard(null);}
|
||||
else if(e.key==='Home')setKeyboard({id,target:null});
|
||||
else if(e.key==='Tab'){const candidates=Object.keys(rects).filter(x=>x!==id&&x!==primaryId);if(candidates.length){const index=candidates.indexOf(keyboard.target?.overId??'');setKeyboard({id,target:{activeId:id,overId:candidates[(index+(e.shiftKey?-1:1)+candidates.length)%candidates.length],position:keyboard.target?.position??'right',scope:'panel'}});}}
|
||||
else if(position)setKeyboard({id,target:{activeId:id,overId:keyboard.target?.overId??primaryId,position,scope:e.shiftKey||!keyboard.target?'workspace':keyboard.target.scope}});
|
||||
else return;
|
||||
}else if(e.key==='Enter'||e.key===' '){setKeyboard({id,target:null});activate(id);}
|
||||
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds)}});}
|
||||
else return;
|
||||
e.preventDefault();e.stopPropagation();
|
||||
};
|
||||
const target=drag?.target??keyboard?.target,active=drag?.id??keyboard?.id;
|
||||
const projected=target&&active?dockEditorTool(value,primaryId,target,active,drag?.current??floatingRect(active)):null;
|
||||
const previewTree=projected?pruneDockTree(projected.tree,visible):null,previewMinimum=dockMinimum(previewTree,minimums);
|
||||
const previewArea={...bounds,width:Math.max(bounds.width,previewMinimum.width),height:Math.max(bounds.height,previewMinimum.height)};
|
||||
const preview=active&&previewTree?dockRects(constrainDockTree(previewTree,previewArea,minimums),previewArea)[active]:null;
|
||||
const announcement=active?`${target?`${actionNames[target.position]} · ${target.scope==='workspace'?'вся область':tools.find(t=>t.id===target.overId)?.label}`:'Свободное окно'}. Стрелки — край, Shift+стрелки — вся область, Tab — панель, Home — свободно, Enter — применить, Escape — отменить.`:'';
|
||||
return <div ref={viewport} className={cn('nodedc-editor-dock',className)} data-editing={enabled||undefined} data-dragging={!!drag||undefined}>
|
||||
<div ref={host} className="nodedc-editor-dock__canvas" style={{minWidth:required.width,minHeight:required.height}}>
|
||||
<EditorSplits tree={constrained} bounds={area} minimums={minimums} onResize={(path,ratio)=>onChange({...value,tree:mergeEditorDockRatios(value.tree,resizeDockSplit(constrained,path,ratio))})}/>
|
||||
<div className="nodedc-editor-dock__primary" data-editor-primary={primaryId} style={rects[primaryId]}>{primary}</div>
|
||||
{tools.map(tool=>{
|
||||
const moving=drag?.id===tool.id,free=!rects[tool.id]||moving;
|
||||
const rect=moving?drag.current:rects[tool.id]??floatingRect(tool.id);
|
||||
return <div key={tool.id} className={cn('nodedc-editor-dock__tool nodedc-glass-material nodedc-ui-root',tool.className)} data-editor-tool={tool.id} data-floating={free||undefined} data-active={order.at(-1)===tool.id||undefined}
|
||||
role="region" aria-label={tool.label} hidden={!enabled||!tool.open} style={{...rect,zIndex:moving?40:free?10+Math.max(0,order.indexOf(tool.id)):1}}
|
||||
onPointerDownCapture={()=>activate(tool.id)} onFocusCapture={()=>activate(tool.id)}>
|
||||
<header className="nodedc-window__head" tabIndex={0} aria-label={`Переместить · ${tool.label}`} aria-roledescription="Перемещаемая панель" onPointerDown={e=>begin(tool.id,e)} onKeyDown={e=>key(tool.id,e)}>
|
||||
<div className="nodedc-window__titles"><h2 className="nodedc-window__title">{tool.title}</h2>{tool.subtitle&&<p className="nodedc-window__subtitle">{tool.subtitle}</p>}</div>
|
||||
<div className="nodedc-window__actions">{tool.actions}<IconButton label={`Закрыть · ${tool.label}`} onClick={tool.onClose}><Icon name="close"/></IconButton></div>
|
||||
</header>
|
||||
<InspectorSelectPolicyContext.Provider value={false}><LoadingContext.Provider value={null}>
|
||||
<div className="nodedc-window__body nodedc-editor-dock__body">{tool.content}</div>
|
||||
{tool.footer&&<footer className="nodedc-window__footer">{tool.footer}</footer>}
|
||||
</LoadingContext.Provider></InspectorSelectPolicyContext.Provider>
|
||||
{free&&windowResizeEdges.map(edge=><div key={edge} className="nodedc-window__resize" data-edge={edge} aria-hidden="true" onPointerDown={e=>begin(tool.id,e,edge)}/>)}
|
||||
</div>;
|
||||
})}
|
||||
{drag&&<div className="nodedc-editor-dock__shield"/>}
|
||||
{preview&&<div className="nodedc-dock-layout__preview nodedc-editor-dock__preview" style={preview} aria-hidden="true"><span>{target&&actionNames[target.position]}</span></div>}
|
||||
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{announcement}</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
function EditorSplits({tree,bounds,minimums,onResize,path=''}:{tree:DockTree;bounds:DockMinimum;minimums:Record<string,DockMinimum>;onResize:(path:string,ratio:number)=>void;path?:string}){
|
||||
if('id' in tree)return null;
|
||||
const k=tree.axis==='x'?'width':'height',span=bounds[k];
|
||||
return <SplitPane className="nodedc-dock-layout__split" separatorAppearance="invisible" orientation={tree.axis==='x'?'vertical':'horizontal'} primarySize={tree.ratio}
|
||||
minPrimarySize={span?dockMinimum(tree.first,minimums)[k]/span*100:0} minSecondarySize={span?dockMinimum(tree.second,minimums)[k]/span*100:0} onPrimarySizeChange={ratio=>onResize(path,ratio)} separatorLabel="Изменить размеры панелей редактора"
|
||||
primary={<EditorSplits tree={tree.first} bounds={{...bounds,[k]:span*tree.ratio/100}} minimums={minimums} onResize={onResize} path={path+'0'}/>}
|
||||
secondary={<EditorSplits tree={tree.second} bounds={{...bounds,[k]:span*(1-tree.ratio/100)}} minimums={minimums} onResize={onResize} path={path+'1'}/>}/>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {useEffect,useId,useLayoutEffect,useRef,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {IconButton} from './Button.js';
|
||||
import {Icon} from './Icon.js';
|
||||
import {cn} from './cn.js';
|
||||
|
||||
export interface EditorWorkspaceProps {editing:boolean;title:ReactNode;subtitle?:ReactNode;onBack:()=>void;children:ReactNode;className?:string}
|
||||
/** One mounted renderer moves between its original slot and a modeless editor window. */
|
||||
export function EditorWorkspace({editing,title,subtitle,onBack,children,className}:EditorWorkspaceProps){
|
||||
const inline=useRef<HTMLDivElement>(null),[host]=useState(()=>document.createElement('div'));
|
||||
const [expanded,setExpanded]=useState(false),opener=useRef<HTMLElement|null>(null),titleId=useId();
|
||||
useLayoutEffect(()=>{host.className='nodedc-editor-workspace__host';inline.current!.append(host);return()=>host.remove();},[host]);
|
||||
useLayoutEffect(()=>{
|
||||
const target=(editing?(document.fullscreenElement??document.body):inline.current!) as HTMLElement&{moveBefore?:(node:Node,before:Node|null)=>void};
|
||||
if(editing)opener.current=document.activeElement instanceof HTMLElement?document.activeElement:null;
|
||||
if(host.parentElement!==target){if(target.moveBefore&&host.isConnected)target.moveBefore(host,null);else target.append(host);}
|
||||
host.dataset.editing=String(editing);
|
||||
if(editing)host.querySelector<HTMLElement>('[data-editor-back]')?.focus({preventScroll:true});
|
||||
else {setExpanded(false);if(opener.current?.isConnected)opener.current.focus({preventScroll:true});}
|
||||
},[editing,host]);
|
||||
useEffect(()=>{host.dataset.expanded=String(expanded);},[expanded,host]);
|
||||
return <div ref={inline} className={cn('nodedc-editor-workspace__slot',className)}>{createPortal(
|
||||
<div className="nodedc-editor-workspace nodedc-ui-root" data-editing={editing||undefined} role={editing?'dialog':undefined} aria-modal={editing?'false':undefined} aria-labelledby={editing?titleId:undefined}
|
||||
onKeyDown={event=>{if(!editing||event.key!=='Escape'||event.defaultPrevented)return;const dialog=(event.target as HTMLElement).closest('[role=dialog]');if(dialog!==event.currentTarget)return;event.preventDefault();event.stopPropagation();if(expanded)setExpanded(false);else onBack();}}>
|
||||
{editing&&<header className="nodedc-window__head nodedc-editor-workspace__head">
|
||||
<div className="nodedc-window__titles"><h1 id={titleId} className="nodedc-window__title">{title}</h1>{subtitle&&<p className="nodedc-window__subtitle">{subtitle}</p>}</div>
|
||||
<div className="nodedc-window__actions">
|
||||
<IconButton data-editor-back label="Вернуться из редактора сцены" onClick={onBack}><Icon name="chevron-left"/></IconButton>
|
||||
<IconButton label={expanded?'Восстановить окно редактора':'Развернуть окно редактора'} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton>
|
||||
<IconButton label="Завершить редактирование сцены" aria-pressed onClick={onBack}><Icon name="edit"/></IconButton>
|
||||
<IconButton label="Закрыть редактор сцены" onClick={onBack}><Icon name="close"/></IconButton>
|
||||
</div>
|
||||
</header>}
|
||||
<div className="nodedc-editor-workspace__body">{children}</div>
|
||||
</div>,host)}</div>;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { createGlassMaterialVariables, type GlassMaterialSettings } from "@nodedc/ui-core";
|
||||
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export type GlassTone = "default" | "strong" | "soft";
|
||||
@@ -37,11 +38,17 @@ export function GlassSurface({
|
||||
|
||||
export interface GlassMaterialSurfaceProps extends HTMLAttributes<HTMLDivElement> {
|
||||
children: ReactNode;
|
||||
/** Scene telemetry uses the translucent V4 material, independent of modal density. */
|
||||
context?: "floating" | "scene";
|
||||
radius?: GlassRadius;
|
||||
/** Per-instance appearance; never changes the global theme or other surfaces. */
|
||||
material?: GlassMaterialSettings;
|
||||
radiusPx?: number;
|
||||
}
|
||||
|
||||
/** Canonical modal/Inspector material. General application panels must not use it. */
|
||||
export function GlassMaterialSurface({ children, className, ...props }: GlassMaterialSurfaceProps) {
|
||||
return <div className={cn("nodedc-glass-material", className)} {...props}>{children}</div>;
|
||||
/** Canonical floating/scene-overlay material. Ordinary application panels stay matte. */
|
||||
export function GlassMaterialSurface({ children, className, context = "floating", radius = "modal", material, radiusPx, style, ...props }: GlassMaterialSurfaceProps) {
|
||||
return <div className={cn("nodedc-glass-material", className)} data-glass-context={context} data-radius={radius} style={{ ...material && createGlassMaterialVariables(material, context), ...Number.isFinite(radiusPx) && {borderRadius: Math.max(0, Math.min(120, radiusPx!))}, ...style } as CSSProperties} {...props}>{children}</div>;
|
||||
}
|
||||
|
||||
export interface MapGlassSurfaceProps extends HTMLAttributes<HTMLDivElement> {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
MousePointer2,
|
||||
Move,
|
||||
CirclePlus,
|
||||
Box,
|
||||
Scan,
|
||||
@@ -47,6 +48,7 @@ import {
|
||||
Pencil,
|
||||
Play,
|
||||
Plus,
|
||||
Minus,
|
||||
RefreshCw,
|
||||
RotateCw,
|
||||
Save,
|
||||
@@ -71,6 +73,7 @@ const icons = {
|
||||
perspective: Box,
|
||||
orthographic: Scan,
|
||||
select: MousePointer2,
|
||||
move: Move,
|
||||
pen: PenTool,
|
||||
rectangle: RectangleHorizontal,
|
||||
curve: Spline,
|
||||
@@ -116,6 +119,7 @@ const icons = {
|
||||
plan: Map,
|
||||
play: Play,
|
||||
plus: Plus,
|
||||
minus: Minus,
|
||||
profile: UserCircle,
|
||||
refresh: RefreshCw,
|
||||
"rotate-clockwise": RotateCw,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {useRef, type HTMLAttributes, type ReactNode} from "react";
|
||||
import {cn} from "./cn.js";
|
||||
|
||||
export interface ResizableViewportProps extends Omit<HTMLAttributes<HTMLDivElement>, "children" | "onChange"> {
|
||||
children: ReactNode;
|
||||
height: number;
|
||||
minHeight?: number;
|
||||
maxHeight?: number;
|
||||
onHeightChange: (height: number) => void;
|
||||
onHeightCommit?: (height: number) => void;
|
||||
resizeLabel?: string;
|
||||
resizeIndicator?: boolean;
|
||||
}
|
||||
/** In-flow viewer with height-only corner grips. Persistence belongs to its owner. */
|
||||
export function ResizableViewport({children, height, minHeight = 360, maxHeight = 2160, onHeightChange, onHeightCommit, resizeLabel = "Высота 3D-окна", resizeIndicator = true, className, style, ...props}: ResizableViewportProps) {
|
||||
const drag = useRef<{id:number; y:number; height:number; current:number} | null>(null);
|
||||
const fit = (value:number) => Math.round(Math.max(minHeight, Math.min(maxHeight, value)));
|
||||
const current = fit(height);
|
||||
return <div {...props} data-resize-indicator={resizeIndicator ? undefined : "hidden"} className={cn("nodedc-resizable-viewport", className)} style={{...style, height:current}}>
|
||||
{children}
|
||||
{(["start", "end"] as const).map(corner => <div key={corner} className="nodedc-resizable-viewport__grip" data-corner={corner}
|
||||
role="separator" aria-orientation="horizontal" tabIndex={0} aria-label={`${resizeLabel} · ${corner === "start" ? "левый угол" : "правый угол"}`}
|
||||
aria-valuenow={current} aria-valuemin={minHeight} aria-valuemax={maxHeight} aria-valuetext={`${current} px`}
|
||||
onPointerDown={event => {
|
||||
if (event.button !== 0 || drag.current) return;
|
||||
event.preventDefault(); event.stopPropagation(); event.currentTarget.setPointerCapture(event.pointerId);
|
||||
drag.current = {id:event.pointerId, y:event.clientY, height:current, current};
|
||||
}}
|
||||
onPointerMove={event => {
|
||||
const gesture = drag.current;
|
||||
if (!gesture || event.pointerId !== gesture.id) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
gesture.current = fit(gesture.height + event.clientY - gesture.y); onHeightChange(gesture.current);
|
||||
}}
|
||||
onPointerUp={event => {
|
||||
const gesture = drag.current; if (!gesture || event.pointerId !== gesture.id) return;
|
||||
event.stopPropagation(); drag.current = null; event.currentTarget.releasePointerCapture(event.pointerId); onHeightCommit?.(gesture.current);
|
||||
}}
|
||||
onLostPointerCapture={() => {const gesture = drag.current; drag.current = null; if (gesture) onHeightCommit?.(gesture.current);}}
|
||||
onKeyDown={event => {
|
||||
const step = event.shiftKey ? 50 : 10;
|
||||
const next = event.key === "ArrowUp" ? current - step : event.key === "ArrowDown" ? current + step : event.key === "Home" ? minHeight : event.key === "End" ? maxHeight : null;
|
||||
if (next === null) return;
|
||||
event.preventDefault(); event.stopPropagation(); const value = fit(next); onHeightChange(value); onHeightCommit?.(value);
|
||||
}}/>) }
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {forwardRef} from "react";
|
||||
import {Button,type ButtonProps} from "./Button.js";
|
||||
import {cn} from "./cn.js";
|
||||
/** Screen-projected data anchored to a real scene object; coordinates belong to the renderer. */
|
||||
export const SceneAnnotation=forwardRef<HTMLButtonElement,ButtonProps>(function SceneAnnotation({className,...props},ref){
|
||||
return <Button {...props} ref={ref} variant="ghost" size="dense" className={cn("nodedc-scene-annotation",className)}/>;
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import {useLayoutEffect,useRef,useState,type CSSProperties} from 'react';
|
||||
import {Icon,type IconName} from './Icon.js';
|
||||
|
||||
export interface TreeNode {id:string;label:string;children?:TreeNode[];icon?:IconName;visible?:boolean}
|
||||
export interface TreeProps {nodes:TreeNode[];selected:string|null;onSelect:(id:string)=>void;onVisibilityChange?:(id:string,visible:boolean)=>void;label:string;query?:string;revealKey?:number}
|
||||
|
||||
/** Compact outliner. Selection reveals ancestors without scrolling its host page. */
|
||||
export function Tree({nodes,selected,onSelect,onVisibilityChange,label,query='',revealKey}:TreeProps){
|
||||
const [collapsed,setCollapsed]=useState<Set<string>>(()=>new Set());
|
||||
const [focus,setFocus]=useState<string|null>(null);
|
||||
const host=useRef<HTMLDivElement>(null),elements=useRef(new Map<string,HTMLDivElement>());
|
||||
const parents=new Map<string,string>(),index=new Map<string,TreeNode>();
|
||||
const visit=(items:TreeNode[],parent?:string)=>{for(const item of items){index.set(item.id,item);if(parent)parents.set(item.id,parent);visit(item.children??[],item.id);}};visit(nodes);
|
||||
const ancestors=new Set<string>();let parent=selected?parents.get(selected):undefined;while(parent){ancestors.add(parent);parent=parents.get(parent);}
|
||||
const matches=(item:TreeNode):boolean=>!query||item.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())||!!item.children?.some(matches);
|
||||
const rows:{node:TreeNode;depth:number;open:boolean}[]=[];
|
||||
const flatten=(items:TreeNode[],depth=0)=>{for(const node of items){if(!matches(node))continue;const open=!!query||!collapsed.has(node.id);rows.push({node,depth,open});if(open)flatten(node.children??[],depth+1);}};flatten(nodes);
|
||||
const reveal=(id:string)=>{const target=elements.current.get(id),container=host.current;if(!target||!container)return;const row=target.getBoundingClientRect(),box=container.getBoundingClientRect();if(row.top<box.top)container.scrollTop-=box.top-row.top;else if(row.bottom>box.bottom)container.scrollTop+=row.bottom-box.bottom;};
|
||||
useLayoutEffect(()=>{if(selected){setFocus(selected);setCollapsed(old=>{if(![...ancestors].some(id=>old.has(id)))return old;const next=new Set(old);for(const id of ancestors)next.delete(id);return next;});}},[selected,revealKey]);
|
||||
useLayoutEffect(()=>{if(selected)reveal(selected);},[selected,revealKey,query,collapsed]);
|
||||
const toggle=(id:string)=>setCollapsed(old=>{const next=new Set(old);if(next.has(id))next.delete(id);else next.add(id);return next;});
|
||||
const select=(id:string)=>{setFocus(id);onSelect(id);elements.current.get(id)?.focus({preventScroll:true});reveal(id);};
|
||||
return <div ref={host} className="nodedc-tree" role="tree" aria-label={label}>
|
||||
{rows.map(({node,depth,open},position)=><div key={node.id} ref={element=>{if(element)elements.current.set(node.id,element);else elements.current.delete(node.id);}} role="treeitem" aria-level={depth+1} aria-selected={selected===node.id} aria-expanded={node.children?.length?open:undefined} tabIndex={(focus??selected??rows[0]?.node.id)===node.id?0:-1} className="nodedc-tree__row" style={{'--tree-depth':depth} as CSSProperties} title={node.label} onFocus={()=>setFocus(node.id)} onClick={()=>select(node.id)} onDoubleClick={()=>node.children?.length&&toggle(node.id)} onKeyDown={event=>{
|
||||
if(event.target!==event.currentTarget)return;
|
||||
let next:string|undefined;
|
||||
if(event.key==='ArrowDown')next=rows[Math.min(rows.length-1,position+1)]?.node.id;
|
||||
else if(event.key==='ArrowUp')next=rows[Math.max(0,position-1)]?.node.id;
|
||||
else if(event.key==='Home')next=rows[0]?.node.id;
|
||||
else if(event.key==='End')next=rows.at(-1)?.node.id;
|
||||
else if(event.key==='ArrowRight'){if(node.children?.length){if(!open)toggle(node.id);else next=node.children[0].id;}}
|
||||
else if(event.key==='ArrowLeft'){if(open&&node.children?.length)toggle(node.id);else next=parents.get(node.id);}
|
||||
else if(event.key==='Enter'||event.key===' ')next=node.id;
|
||||
else return;
|
||||
event.preventDefault();event.stopPropagation();if(next)select(next);
|
||||
}}>
|
||||
<span className="nodedc-tree__branch">{node.children?.length?<button type="button" tabIndex={-1} aria-label={`${open?'Свернуть':'Развернуть'} ${node.label}`} onClick={event=>{event.stopPropagation();toggle(node.id);}}><Icon name={open?'chevron-down':'chevron-right'} size={14}/></button>:null}</span>
|
||||
<Icon name={node.icon??(node.children?.length?'folder':'layers')} size={14}/>
|
||||
<span className="nodedc-tree__label">{node.label}</span>
|
||||
{onVisibilityChange&&node.visible!==undefined&&<button type="button" className="nodedc-tree__visibility" tabIndex={focus===node.id?0:-1} aria-label={`${node.visible?'Скрыть':'Показать'} ${node.label}`} aria-pressed={node.visible} onClick={event=>{event.stopPropagation();onVisibilityChange(node.id,!node.visible);}}><Icon name={node.visible?'eye':'eye-off'} size={14}/></button>}
|
||||
</div>)}
|
||||
</div>;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type HTMLAttributes,
|
||||
@@ -12,6 +13,8 @@ import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { LoadingContext } from "./LoadingContext.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { IconButton } from "./Button.js";
|
||||
import { fitWindow, resizeWindow, windowResizeEdges, type WindowRect, type ResizeEdge } from "./windowGeometry.js";
|
||||
|
||||
const focusableSelector = [
|
||||
"a[href]",
|
||||
@@ -24,6 +27,7 @@ const focusableSelector = [
|
||||
|
||||
export type WindowSize = "sm" | "md" | "lg";
|
||||
export type WindowPlacement = "center" | "end";
|
||||
export type { WindowRect } from "./windowGeometry.js";
|
||||
|
||||
export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title"> {
|
||||
open: boolean;
|
||||
@@ -41,6 +45,15 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
|
||||
lockBodyScroll?: boolean;
|
||||
trapFocus?: boolean;
|
||||
draggable?: boolean;
|
||||
/** Resize a modeless inspector using the same eight edges as floating windows. */
|
||||
resizable?: boolean;
|
||||
initialRect?: WindowRect;
|
||||
/** Application-owned geometry, restored on open and on external undo/import. */
|
||||
rect?: WindowRect;
|
||||
/** One commit after a drag/resize, or a keyboard geometry step. */
|
||||
onRectCommit?: (rect: WindowRect) => void;
|
||||
/** Centered windows can become modeless without remounting their contents. */
|
||||
allowFloating?: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -59,6 +72,11 @@ export function Window({
|
||||
lockBodyScroll,
|
||||
trapFocus,
|
||||
draggable = false,
|
||||
resizable = false,
|
||||
initialRect,
|
||||
rect,
|
||||
onRectCommit,
|
||||
allowFloating = true,
|
||||
onClose,
|
||||
className,
|
||||
style,
|
||||
@@ -70,29 +88,42 @@ export function Window({
|
||||
const onCloseRef = useRef(onClose);
|
||||
const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number } | null>(null);
|
||||
const [dragPosition, setDragPosition] = useState<{ left: number; top: number } | null>(null);
|
||||
const shouldLockBodyScroll = lockBodyScroll ?? placement === "center";
|
||||
const shouldTrapFocus = trapFocus ?? placement === "center";
|
||||
const [floating, setFloating] = useState(false);
|
||||
const [floatingRect, setFloatingRect] = useState<WindowRect | null>(null);
|
||||
const rectRef = useRef<WindowRect | null>(null);
|
||||
const initialRectRef = useRef<WindowRect | null>(null);
|
||||
const commitRef = useRef(onRectCommit);
|
||||
commitRef.current = onRectCommit;
|
||||
const changeRect = (next: WindowRect | null) => { rectRef.current = next; setFloatingRect(next); };
|
||||
const gestureChanged = useRef(false);
|
||||
const resizeRef = useRef<{ pointerId: number; x: number; y: number; rect: WindowRect; edge: ResizeEdge } | null>(null);
|
||||
const isFloating = floating && allowFloating && placement === "center";
|
||||
const freeGeometry = isFloating || (resizable && placement === "end");
|
||||
const canDrag = draggable || freeGeometry;
|
||||
const shouldLockBodyScroll = !isFloating && (lockBodyScroll ?? placement === "center");
|
||||
const shouldTrapFocus = !isFloating && (trapFocus ?? placement === "center");
|
||||
const modeRef = useRef({ shouldTrapFocus, isFloating });
|
||||
modeRef.current = { shouldTrapFocus, isFloating };
|
||||
onCloseRef.current = onClose;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || typeof document === "undefined") return;
|
||||
const previousActiveElement = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
if (shouldLockBodyScroll) document.body.style.overflow = "hidden";
|
||||
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
const firstFocusable = dialogRef.current?.querySelector<HTMLElement>(focusableSelector);
|
||||
const firstFocusable = Array.from(dialogRef.current?.querySelectorAll<HTMLElement>(focusableSelector) ?? []).find(element => element.getClientRects().length > 0);
|
||||
(firstFocusable ?? dialogRef.current)?.focus();
|
||||
});
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape" && closeOnEscape) {
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.key === "Escape" && closeOnEscape && (!modeRef.current.isFloating || dialogRef.current?.contains(document.activeElement))) {
|
||||
event.preventDefault();
|
||||
onCloseRef.current();
|
||||
return;
|
||||
}
|
||||
if (event.key !== "Tab" || !shouldTrapFocus || !dialogRef.current) return;
|
||||
const focusable = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(focusableSelector));
|
||||
if (event.key !== "Tab" || !modeRef.current.shouldTrapFocus || !dialogRef.current) return;
|
||||
const focusable = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(focusableSelector)).filter(element => element.getClientRects().length > 0);
|
||||
if (focusable.length === 0) {
|
||||
event.preventDefault();
|
||||
dialogRef.current.focus();
|
||||
@@ -113,28 +144,61 @@ export function Window({
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
if (shouldLockBodyScroll) document.body.style.overflow = previousOverflow;
|
||||
previousActiveElement?.focus();
|
||||
if (!modeRef.current.isFloating || document.activeElement === document.body || dialogRef.current?.contains(document.activeElement)) previousActiveElement?.focus();
|
||||
};
|
||||
}, [closeOnEscape, open, shouldLockBodyScroll, shouldTrapFocus]);
|
||||
}, [closeOnEscape, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setDragPosition(null);
|
||||
if (!open || !shouldLockBodyScroll) return;
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
return () => { document.body.style.overflow = previousOverflow; };
|
||||
}, [open, shouldLockBodyScroll]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (open && freeGeometry && !dragRef.current && !resizeRef.current) {
|
||||
// The modal move toggle already restores its local rectangle. An
|
||||
// uncontrolled floating window must retain it when toggled twice.
|
||||
if (placement === "center" && !onRectCommit && !rect && rectRef.current) return;
|
||||
const bounds=dialogRef.current?.getBoundingClientRect();
|
||||
if(bounds){
|
||||
initialRectRef.current ??= initialRect??{left:bounds.left,top:bounds.top,width:bounds.width,height:bounds.height};
|
||||
changeRect(fitWindow(rect??initialRectRef.current,{width:window.innerWidth,height:window.innerHeight}));
|
||||
}
|
||||
}
|
||||
},[open,freeGeometry,rect?.left,rect?.top,rect?.width,rect?.height]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) { setDragPosition(null); setFloating(false); changeRect(null); initialRectRef.current = null; dragRef.current = null; resizeRef.current = null; }
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!draggable || !open) return;
|
||||
if (!canDrag || !open) return;
|
||||
const handlePointerMove = (event: globalThis.PointerEvent) => {
|
||||
const resizing = resizeRef.current;
|
||||
if (resizing && event.pointerId === resizing.pointerId) {
|
||||
gestureChanged.current = true;
|
||||
changeRect(resizeWindow(resizing.rect, resizing.edge, event.clientX - resizing.x, event.clientY - resizing.y, { width: window.innerWidth, height: window.innerHeight }));
|
||||
return;
|
||||
}
|
||||
const drag = dragRef.current;
|
||||
const dialog = dialogRef.current;
|
||||
if (!drag || !dialog || event.pointerId !== drag.pointerId) return;
|
||||
const bounds = dialog.getBoundingClientRect();
|
||||
if (freeGeometry) {
|
||||
gestureChanged.current = true;
|
||||
changeRect(fitWindow({ left: event.clientX - drag.offsetX, top: event.clientY - drag.offsetY, width: bounds.width, height: bounds.height }, { width: window.innerWidth, height: window.innerHeight }));
|
||||
return;
|
||||
}
|
||||
const left = Math.max(8, Math.min(window.innerWidth - bounds.width - 8, event.clientX - drag.offsetX));
|
||||
const top = Math.max(76, Math.min(window.innerHeight - bounds.height - 8, event.clientY - drag.offsetY));
|
||||
setDragPosition({ left, top });
|
||||
};
|
||||
const handlePointerUp = (event: globalThis.PointerEvent) => {
|
||||
const owned = dragRef.current?.pointerId === event.pointerId || resizeRef.current?.pointerId === event.pointerId;
|
||||
if (dragRef.current?.pointerId === event.pointerId) dragRef.current = null;
|
||||
if (resizeRef.current?.pointerId === event.pointerId) resizeRef.current = null;
|
||||
if (owned && gestureChanged.current && rectRef.current) { gestureChanged.current = false; commitRef.current?.({...rectRef.current}); }
|
||||
};
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
@@ -144,11 +208,18 @@ export function Window({
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
};
|
||||
}, [draggable, open]);
|
||||
}, [canDrag, freeGeometry, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!freeGeometry || !open) return;
|
||||
const fit = () => { if(rectRef.current) changeRect(fitWindow(rect ?? rectRef.current, { width: window.innerWidth, height: window.innerHeight })); };
|
||||
window.addEventListener("resize", fit);
|
||||
return () => window.removeEventListener("resize", fit);
|
||||
}, [freeGeometry, open, rect]);
|
||||
|
||||
if (!open || typeof document === "undefined") return null;
|
||||
|
||||
const allowBackdropClose = closeOnBackdrop ?? placement === "center";
|
||||
const allowBackdropClose = !isFloating && (closeOnBackdrop ?? placement === "center");
|
||||
|
||||
const handleBackdropPointerDown = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (allowBackdropClose && event.target === event.currentTarget) onClose();
|
||||
@@ -156,29 +227,44 @@ export function Window({
|
||||
|
||||
return createPortal(
|
||||
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
|
||||
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} onPointerDown={handleBackdropPointerDown}>
|
||||
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} data-floating={isFloating || undefined} onPointerDown={handleBackdropPointerDown}>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
className={cn("nodedc-window nodedc-glass-material nodedc-material-rim", className)}
|
||||
data-material="glass-v4"
|
||||
data-size={size === "md" ? undefined : size}
|
||||
data-placement={placement}
|
||||
data-draggable={draggable ? "true" : undefined}
|
||||
data-draggable={canDrag ? "true" : undefined}
|
||||
data-resizable={freeGeometry || undefined}
|
||||
data-floating={isFloating || undefined}
|
||||
role="dialog"
|
||||
aria-modal={placement === "center" ? "true" : undefined}
|
||||
aria-modal={placement === "center" && !isFloating ? "true" : undefined}
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={subtitle ? descriptionId : undefined}
|
||||
tabIndex={-1}
|
||||
style={dragPosition ? { ...style, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : style}
|
||||
style={freeGeometry && floatingRect ? { ...style, position: "fixed", ...floatingRect, right: "auto", bottom: "auto", maxWidth: "none", maxHeight: "none" } : dragPosition ? { ...style, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : style}
|
||||
{...props}
|
||||
>
|
||||
<header
|
||||
className="nodedc-window__head"
|
||||
tabIndex={freeGeometry ? 0 : undefined}
|
||||
aria-label={freeGeometry ? "Перемещение окна: стрелки; изменение размера: Shift и стрелки" : undefined}
|
||||
onKeyDown={(event) => {
|
||||
if (!freeGeometry || !floatingRect || event.target !== event.currentTarget || !event.key.startsWith("Arrow")) return;
|
||||
event.preventDefault();
|
||||
const dx = event.key === "ArrowLeft" ? -10 : event.key === "ArrowRight" ? 10 : 0;
|
||||
const dy = event.key === "ArrowUp" ? -10 : event.key === "ArrowDown" ? 10 : 0;
|
||||
const bounds = { width: window.innerWidth, height: window.innerHeight };
|
||||
const next = event.shiftKey ? resizeWindow(floatingRect, "se", dx, dy, bounds) : fitWindow({ ...floatingRect, left: floatingRect.left + dx, top: floatingRect.top + dy }, bounds);
|
||||
changeRect(next); commitRef.current?.(next);
|
||||
}}
|
||||
onPointerDown={(event) => {
|
||||
if (!draggable || event.button !== 0 || (event.target as HTMLElement).closest("button, input, select, textarea, a")) return;
|
||||
if (!canDrag || event.button !== 0 || (event.target as HTMLElement).closest("button, input, select, textarea, a")) return;
|
||||
const bounds = dialogRef.current?.getBoundingClientRect();
|
||||
if (!bounds) return;
|
||||
dragRef.current = { pointerId: event.pointerId, offsetX: event.clientX - bounds.left, offsetY: event.clientY - bounds.top };
|
||||
gestureChanged.current = false;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
event.preventDefault();
|
||||
}}
|
||||
>
|
||||
@@ -188,11 +274,26 @@ export function Window({
|
||||
</div>
|
||||
<div className="nodedc-window__actions">
|
||||
{headerActions}
|
||||
{allowFloating && placement === "center" && <IconButton label={isFloating ? "Вернуть модальный режим" : "Свободное окно"} aria-pressed={isFloating} onClick={() => {
|
||||
dragRef.current = null; resizeRef.current = null;
|
||||
if (!isFloating) {
|
||||
const rect = dialogRef.current?.getBoundingClientRect();
|
||||
if (rect) changeRect(fitWindow(rectRef.current ?? { left: rect.left, top: rect.top, width: rect.width, height: rect.height }, { width: window.innerWidth, height: window.innerHeight }));
|
||||
}
|
||||
setFloating(!isFloating);
|
||||
}}><Icon name="move" /></IconButton>}
|
||||
<button type="button" className="nodedc-window__close" aria-label={closeLabel} onClick={onClose}>
|
||||
<Icon name="close" size={16} strokeWidth={1.6} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
{freeGeometry && windowResizeEdges.map(edge => <div key={edge} className="nodedc-window__resize" data-edge={edge} aria-hidden="true" onPointerDown={event => {
|
||||
if (event.button !== 0 || !floatingRect) return;
|
||||
resizeRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, rect: floatingRect, edge };
|
||||
gestureChanged.current = false;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
}} />)}
|
||||
<div className="nodedc-window__body">{children}</div>
|
||||
{footer ? <footer className="nodedc-window__footer">{footer}</footer> : null}
|
||||
</div>
|
||||
|
||||
@@ -14,7 +14,10 @@ export * from "./ConfirmationModal.js";
|
||||
export * from "./Dropdown.js";
|
||||
export * from "./DragDrop.js";
|
||||
export * from "./DockLayout.js";
|
||||
export {decodeDockTree, dockIds, balancedDockTree, reconcileDockTree, pruneDockTree, moveDockPanel, resizeDockSplit, dockRects, dockPosition, type DockTree, type DockMove, type DockRect, type DockPosition} from "@nodedc/ui-core";
|
||||
export * from "./EditorDockLayout.js";
|
||||
export * from "./EditorWorkspace.js";
|
||||
export {decodeEditorDock,dockEditorTool,editorDockTarget,mergeEditorDockRatios,type EditorDockState} from "@nodedc/ui-core";
|
||||
export {decodeDockTree, dockIds, balancedDockTree, reconcileDockTree, pruneDockTree, moveDockPanel, resizeDockSplit, dockRects, dockPosition, dockMoveAtPoint, type DockTree, type DockMove, type DockRect, type DockPosition} from "@nodedc/ui-core";
|
||||
export * from "./Field.js";
|
||||
export * from "./FeatureSettingsWindow.js";
|
||||
export * from "./Glass.js";
|
||||
@@ -44,3 +47,10 @@ export * from "./LandingStage.js";
|
||||
export {KeyButton, type KeyButtonProps} from './KeyButton.js';
|
||||
|
||||
export type {DockMinimum, DockMinimums} from "@nodedc/ui-core";
|
||||
|
||||
export {Tree,type TreeNode,type TreeProps} from "./Tree.js";
|
||||
|
||||
export * from "./ResizableViewport.js";
|
||||
export {useApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
|
||||
|
||||
export {SceneAnnotation} from "./SceneAnnotation.js";
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Viewport-local geometry shared by pointer and keyboard window manipulation. */
|
||||
export type WindowRect = { left: number; top: number; width: number; height: number };
|
||||
export type ResizeEdge = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
|
||||
export const windowResizeEdges: ResizeEdge[] = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];
|
||||
type Bounds = { width: number; height: number };
|
||||
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value));
|
||||
export function fitWindow(rect: WindowRect, bounds: Bounds): WindowRect {
|
||||
const width = clamp(rect.width, Math.min(320, bounds.width - 16), Math.max(1, bounds.width - 16));
|
||||
const height = clamp(rect.height, Math.min(200, bounds.height - 16), Math.max(1, bounds.height - 16));
|
||||
return { width, height, left: clamp(rect.left, 8, Math.max(8, bounds.width - width - 8)), top: clamp(rect.top, 8, Math.max(8, bounds.height - height - 8)) };
|
||||
}
|
||||
export function resizeWindow(rect: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds): WindowRect {
|
||||
const r = fitWindow(rect, bounds), right = r.left + r.width, bottom = r.top + r.height;
|
||||
const minWidth = Math.min(320, bounds.width - 16), minHeight = Math.min(200, bounds.height - 16);
|
||||
const left = edge.includes('w') ? clamp(r.left + dx, 8, right - minWidth) : r.left;
|
||||
const top = edge.includes('n') ? clamp(r.top + dy, 8, bottom - minHeight) : r.top;
|
||||
const endX = edge.includes('e') ? clamp(right + dx, left + minWidth, bounds.width - 8) : right;
|
||||
const endY = edge.includes('s') ? clamp(bottom + dy, top + minHeight, bounds.height - 8) : bottom;
|
||||
return { left, top, width: endX - left, height: endY - top };
|
||||
}
|
||||
Reference in New Issue
Block a user