feat(scene-editor): add persistent dockable tool workspaces
This commit is contained in:
@@ -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