From 972944e6f234eaaa24cd73543f9f1eef871f24c8 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 4 Nov 2026 00:39:39 +0300 Subject: [PATCH] feat(scene-editor): add persistent dockable tool workspaces --- apps/catalog/src/CatalogApp.tsx | 38 +++- apps/catalog/src/EditorDockExample.tsx | 13 ++ docs/COMPONENTS.md | 55 +++++- docs/WINDOWS_AND_LAYERS.md | 22 +++ package.json | 6 +- packages/tokens/tokens.css | 3 + packages/ui-core/src/editorDock.ts | 54 ++++++ packages/ui-core/src/glass.ts | 6 +- packages/ui-core/src/index.ts | 1 + packages/ui-core/styles.css | 117 ++++++++++- .../src/ApplicationPanelFullscreen.tsx | 26 +++ packages/ui-react/src/ApplicationShell.tsx | 7 +- packages/ui-react/src/DragDrop.tsx | 24 ++- packages/ui-react/src/EditorDockLayout.tsx | 131 +++++++++++++ packages/ui-react/src/EditorWorkspace.tsx | 36 ++++ packages/ui-react/src/Glass.tsx | 15 +- packages/ui-react/src/Icon.tsx | 4 + packages/ui-react/src/ResizableViewport.tsx | 47 +++++ packages/ui-react/src/SceneAnnotation.tsx | 7 + packages/ui-react/src/Tree.tsx | 43 +++++ packages/ui-react/src/Window.tsx | 141 ++++++++++++-- packages/ui-react/src/index.ts | 12 +- packages/ui-react/src/windowGeometry.ts | 20 ++ registry/components.json | 182 ++++++++++++++++-- registry/icons.json | 4 +- scripts/editor-dock.test.mjs | 56 ++++++ scripts/window-geometry.test.mjs | 17 ++ 27 files changed, 1020 insertions(+), 67 deletions(-) create mode 100644 apps/catalog/src/EditorDockExample.tsx create mode 100644 packages/ui-core/src/editorDock.ts create mode 100644 packages/ui-react/src/ApplicationPanelFullscreen.tsx create mode 100644 packages/ui-react/src/EditorDockLayout.tsx create mode 100644 packages/ui-react/src/EditorWorkspace.tsx create mode 100644 packages/ui-react/src/ResizableViewport.tsx create mode 100644 packages/ui-react/src/SceneAnnotation.tsx create mode 100644 packages/ui-react/src/Tree.tsx create mode 100644 packages/ui-react/src/windowGeometry.ts create mode 100644 scripts/editor-dock.test.mjs create mode 100644 scripts/window-geometry.test.mjs diff --git a/apps/catalog/src/CatalogApp.tsx b/apps/catalog/src/CatalogApp.tsx index e1583fb..f0c9d38 100644 --- a/apps/catalog/src/CatalogApp.tsx +++ b/apps/catalog/src/CatalogApp.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; import { applyGlassMaterial, applyNodedcTheme, defaultGlassMaterial, type GlassMaterialSettings, type NodedcTheme, type RgbTuple } from "@nodedc/ui-core"; import { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTemplateDefinition } from "@nodedc/page-patterns"; +import {EditorDockExample} from './EditorDockExample'; import { ActivityIndicator, LoadingRegion, @@ -30,6 +31,8 @@ import { FeatureSettingsWindow, GlassSurface, GlassMaterialSurface, + ResizableViewport, + SceneAnnotation, HeaderNavigation, HeaderProfile, HeaderWorkspace, @@ -41,6 +44,7 @@ import { RangeControl, ResourceRow, ResourceList, + Tree, SegmentedControl, SegmentedGroup, SegmentedButton, @@ -241,6 +245,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [ ]; const iconLabels: Record = { + move: "Свободное окно", "add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить", activity: "Активность", alert: "Предупреждение", @@ -282,6 +287,7 @@ const iconLabels: Record = { play: "Воспроизвести", target: "Таргеты", plus: "Добавить", + minus: "Уменьшить", profile: "Профиль", refresh: "Обновить", "rotate-clockwise": "Повернуть по часовой стрелке", @@ -386,8 +392,13 @@ export function CatalogApp() { const [fillOpacity, setFillOpacity] = useState(100); const [strokeColor, setStrokeColor] = useState("#2b2b36"); const [strokeOpacity, setStrokeOpacity] = useState(100); + const [treeDemoOpen,setTreeDemoOpen]=useState(false); + const [treeDemoRect,setTreeDemoRect]=useState({left:32,top:96,width:380,height:480}); + const [treeSelected,setTreeSelected]=useState('cells'); + const [treeVisible,setTreeVisible]=useState(true); const [inspectorOpen, setInspectorOpen] = useState(false); const workspaceWindowDemoRef = useRef(null); + const [sceneDemoHeight, setSceneDemoHeight] = useState(480); const [workspaceWindowDemoOpen, setWorkspaceWindowDemoOpen] = useState(true); const [workspaceWindowDemoMaximized, setWorkspaceWindowDemoMaximized] = useState(false); const [workspaceWindowDemoRect, setWorkspaceWindowDemoRect] = useState({ x: 24, y: 24, width: 340, height: 230 }); @@ -1307,6 +1318,7 @@ export function CatalogApp() { onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)} /> + HEX можно очистить и набрать заново; Enter применяет, Escape возвращает текущий цвет. `${value}px`} onChange={(value) => { @@ -1499,6 +1511,8 @@ export function CatalogApp() {
  • } title="Подключённая камера" description="Индикатор перед названием" statusPlacement="leading" status={} actions={ setProjectName("Подключённая камера")}>} />
  • } title="Подготовка камеры" metadata="Проверка потоков" progress={{label:"Подготовка камеры",value:0.8}} aria-busy="true" actions={} />
  • + + {}}>{({activator})=>} @@ -1585,12 +1599,13 @@ export function CatalogApp() {

    Граница изменяет контролируемую долю панелей; клавиши и pointer используют одни ограничения, а resize контейнера не сбрасывает выбранное соотношение.

    - +
    {id}}/>
    -

    Центр — обмен, край — разделение. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой.

    +

    Центр окна — обмен, край окна — разделение, внешний край всей области — на всю сторону. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой; Shift + стрелки выбирают край всей области.

    +
    {sidePanelDemoOpen ? ( @@ -1696,16 +1711,17 @@ export function CatalogApp() { case "glass": return (
    -
    +
    - + CANONICAL GLASS -

    Модальное окно и Inspector

    +

    Прозрачная плашка над сценой

    + 014,15 В

    Фон остаётся различимым, но текст и контролы сохраняют контраст. Этот материал не применяется к обычным панелям приложения.

    -
    +
    setGlassMaterial((current) => ({ ...current, tintHex }))} /> @@ -1918,7 +1934,7 @@ export function CatalogApp() { title="Состав страниц" description="Перетащите готовую страницу справа в конфигурацию приложения. Свободного canvas и произвольных компонентов нет." > - { + {data?.type==='page-template'?getPageTemplate(String(data.templateId))?.title:'Страница'}} onDragEnd={({ activeData, activeId, activeRect, overData, overId, overRect }) => { if (!overId) return; if (activeData?.type === "page-template" && (overId === "application-pages" || overData?.type === "application-page")) { const horizontalOverlap = activeRect && overRect @@ -2320,10 +2336,14 @@ export function CatalogApp() { /> ) : null} + setTreeDemoOpen(false)}> + setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/> + setInspectorOpen(false)} @@ -2334,7 +2354,7 @@ export function CatalogApp() { setCreateModuleOpen(false)} footer={ @@ -2435,7 +2455,7 @@ export function CatalogApp() { headerActions={ setProjectName('Обновлено')}>} onClose={() => setFeatureSettingsDemoOpen(false)}> {featureSettingsDemoSection === 'general' ? setProjectName(event.target.value)} /> - : Текст в теле использует тот же стиль.({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/>} + : Текст в теле использует тот же стиль.

    Пояснение прежнего потребителя без класса — тот же компактный стиль.

    Ожидаем ответ устройства…({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/>
    } ({tree:{axis:'y',ratio:70,first:{axis:'x',ratio:25,first:{id:'objects'},second:{id:'viewport'}},second:{id:'materials'}},floating:{}}); + return <>
    + setEditing(false)}> + Закреплённая сцена
    } + tools={[{id:'objects',title:'Объекты',label:'Объекты',open:open.objects,onClose:()=>setOpen(v=>({...v,objects:false})),content:Сцена → Модель → Детали}, + {id:'materials',title:'Материалы',label:'Материалы',open:open.materials,onClose:()=>setOpen(v=>({...v,materials:false})),content:Перетащите шапку к краю, рядом с другим инструментом или в центр сцены.}]}/> + +
    ; +} diff --git a/docs/COMPONENTS.md b/docs/COMPONENTS.md index df864e6..1f2e552 100644 --- a/docs/COMPONENTS.md +++ b/docs/COMPONENTS.md @@ -4,7 +4,7 @@ ## GlassSurface -Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал с blur и rim используется только у floating-слоёв: modal `Window` и portal-dropdown/select. +Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал используется у floating-слоёв и явно выбранных информационных плашек над 3D-сценой. - `default` — обычная карточка/панель; - `strong` — dropdown, modal и поверхность над сложным фоном; @@ -14,7 +14,7 @@ Material rim допустим только как часть floating glass. Жёсткая цветная рамка, случайный browser outline или debug border не являются rim. -`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют только modal `Window` и modeless draggable Inspector; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную. +`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют modal `Window`, modeless draggable Inspector и информационные плашки над 3D через `context="scene"`; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную. ## Button и IconButton @@ -270,6 +270,8 @@ setup-команды, сохранение, API и права принадлеж Точные состояния и размеры зафиксированы в `docs/APPLICATION_TEMPLATE.md`. +Внешняя область stage использует `overflow: clip`: скрытый сдвинутый stage не должен создавать горизонтальную прокрутку всего приложения при смене фокуса или работе с плавающим окном. Прокрутка предметного содержимого остаётся внутри соответствующей панели. + ## MediaSourceField Общий компонент Launcher/CMS для медиа-поля: file control, имя файла, URL input, переключатель `HD / URL`, круглое превью, path/hint/error. Один контракт применяется и для stage-видео, и для изображений/логотипов; тип файла, подписи и preview задаёт consumer. Публичный API контролируемый. @@ -328,6 +330,8 @@ variant="panel"`: accordion сохраняет свой layout-state, а его `DragHandle`, `DragDropRoot`, `DraggableItem`, `DropZone`, `SortableScope`, `SortableItem` и `SortableList` образуют общий React-контракт переноса и сортировки. Он перенесён из рабочего Engine-паттерна: drag начинается только за шесть точек и только после движения на `6 px`, поэтому обычный клик по строке не конфликтует с навигацией. +`DragDropRoot.renderOverlay` включает portal-превью переноса поверх прокручиваемого списка. Исходная строка остаётся на месте. Escape/отмена снимают превью без назначения. `DragDropResult.pointer` содержит client-координаты отпускания для точного picking внутри canvas; проверка объекта остаётся у renderer. Существующие потребители без renderOverlay сохраняют прежнее поведение. + Sortable-строки ограничены вертикальной осью: горизонтальное движение указателя не сдвигает navigation или composition layout. `DragDropRoot` возвращает реальные active/over rectangles, поэтому consumer может принять перенос только после достаточного перекрытия destination. Module Foundry использует порог `20%` ширины переносимой строки: короткое движение, движение влево или касание границы не создаёт page instance. В Module Foundry исходная строка Page Template остаётся в Page Library после переноса. Каждый подтверждённый drop создаёт новый page instance с уникальным id; состав приложения и левая навигация читают один массив страниц и потому всегда перестраиваются синхронно. Удаление instance выполняется стандартным `ConfirmationModal`, а не мгновенным действием крестика. @@ -419,13 +423,19 @@ React `Window` (including `FeatureSettingsWindow`) and `Dropdown` (including Sel `DockLayout` and `DockHandle` compose stable viewport hosts over a serializable `DockTree`. Drop at the center to exchange views; the left/right/top/bottom zones split that destination. +The outer 24 CSS pixels of the visible workspace dock across its whole side, including +when the pointer is over the source panel. The remaining tree keeps its relative layout. +This zone is capped at 8% per axis on small surfaces; it takes precedence over panel zones. +The preview labels the scope as «Вся область». Outside drops still cancel. +`DockMove.scope="workspace"` selects this operation; omitted/`panel` retains local docking. +The serialized `DockTree` is unchanged. `dockMoveAtPoint` resolves both hit-test scopes. Removing the source collapses its old empty branch. The contour uses the resulting tree, so it previews the actual final position, even when the destination expands after removal. Any number of available panels can be composed with nested horizontal and vertical splits. `focusedId` expands a view without reparenting media; the application persists `tree`. -There is no permanent outline. Outside/self drops and Escape leave the tree unchanged. +There is no permanent outline. Outside drops, local self drops and Escape leave the tree unchanged. Keyboard: Enter/Space on the grip, Tab/Shift+Tab to choose a destination, arrows for edges, -Home for center, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing. +Home for center, Shift+arrows for a whole-workspace edge, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing. The pure tree types, geometry and operations are exported by `@nodedc/ui-core`; React re-exports them for view consumers. Domain adapters import the framework-neutral package. @@ -437,6 +447,11 @@ The pure tree types, geometry and operations are exported by `@nodedc/ui-core`; `Description` is the shared explanatory paragraph. It matches `SettingsCard.description`: inherited family, small font token (12px), regular 400, muted text token, line-height 1.4. Use it for help below values, not a local paragraph override. +Use `Description role="status"` for explanatory pending/result copy. Unclassed +paragraphs in a `SettingsCard` body inherit this same contract as a compatibility +safeguard, even inside layout groups. New consumers must use `Description`. +This safeguard does not restyle headings, controls or explicitly styled data. + ## ComparisonTable `ComparisonTable` accepts a heading, entity columns and labelled rows. Semantic headers, a 9rem minimum per column and horizontal overflow preserve 1–N comparisons in narrow panels. The keyboard scrollport contains wheel overscroll; no borders or cards per entity. Data freshness stays application-owned. @@ -472,3 +487,35 @@ menu choices use the neutral primary Button state as well as `aria-pressed`. The first optional Hold action controls the existing persisted `autoHide` setting. Disabling autohide cancels any pending hide timer. Dropdown observes outside pointerdown in capture phase; viewport Toolbar consumes background dismissal before canvas editing tools, while other controls retain their normal actions. Nested menus and trigger clicks retain lineage behavior. Catalog includes the Hold action. - `NavigationCube`: [orientation cube](NAVIGATION_CUBE.md), controlled face/edge/corner navigation. + +### Window free mode + +`Window` and composed `FeatureSettingsWindow` expose the move toggle by default for centered placement. It removes the backdrop and enables bounded header drag and border/corner resize without remounting the form. Return restores canonical modal geometry. Use arrow keys on the floating header to move; Shift+arrows resize. `allowFloating={false}` is available for workflows that explicitly require a fixed modal. Inspectors stretch within window content. See WINDOWS_AND_LAYERS.md for focus, portal and lifetime rules. + +### Tree · compact outliner + +`Tree` accepts stable `TreeNode` IDs, a selected ID and `onSelect`, optional query and visibility callback. Rows stay on one line with ellipsis. Selection reveals ancestors and scrolls only the tree, avoiding page/camera jumps. Arrow keys, Home/End, Enter/Space support navigation. Use the canonical `Window resizable initialRect` for a movable object outliner. + +`Window` end inspectors can opt into `resizable`; the same eight-edge geometry and header Shift+arrow keyboard sizing are used. Existing windows keep their defaults. `DraggableItem` also exposes `activator.attributes` and `activator.listeners` to attach directly to a tile button; separate handles remain the default for existing consumers. + +## Scene overlays and viewport height + +`GlassMaterialSurface context="scene" radius="panel"` reuses V4 tint, blur/saturation/brightness with independent scene opacity (52%) and blur (18 px). Mission appearance cannot turn it into the 97%-opaque modal. Use only over rendered imagery, keep telemetry hit areas interactive for page scrolling and leave empty overlay space transparent to scene input. No decorative rim is added in Mission appearance. + +`ResizableViewport` owns two visible bottom grips, controlled `height`, `minHeight`, `maxHeight`, `onHeightChange` and `onHeightCommit`. Drag uses pointer capture; keyboard Up/Down moves 10 px, Shift 50 px, Home/End selects limits. Owner persists on commit per view. The viewer remains in document flow, so heights larger than the available area scroll normally. Grip strokes are structural resize indicators; focus is canonical. + +`ApplicationPanel allowFullscreen` makes `useApplicationPanelFullscreen()` available to owned viewer actions. Fullscreen moves the whole panel including its one header above the app stage. Canvas identity is preserved by atomic DOM move; modeless inspectors remain above it. Restore/back/close leaves no detached panel. This is application full-window presentation, not browser fullscreen, so body portals remain usable. + +`ResizableViewport resizeIndicator={false}` hides the resize strokes and hover surface. Only the pointer cursor changes; keyboard focus remains accessible. Pointer capture does not force focus, avoiding a focus ring after mouse drag. + +`SceneAnnotation` is a transparent canonical ghost button for projected scene data. Renderer supplies screen coordinates, culls offscreen/hidden objects and owns identity; click, Enter and Space activate the same selected state. Use stacked object name/value and never fabricate sensor fields. + +ColorField keeps a local HEX draft so deletion and replacement work with strict controlled values. Six hexadecimal digits (optional #) apply live; blur/Enter normalize valid input or revert incomplete input. Escape cancels the draft. External value changes, including undo, synchronize the displayed text. + +`GlassMaterialSurface` accepts `material: GlassMaterialSettings` and optional `radiusPx` for operator-customizable overlays. Variables are scoped to that instance; scene tint opacity and blur use the scene context, without mutating modal or global appearance. + +Exact `RangeControl` editors synchronize external controlled-value changes while focused, so undo/redo is visible immediately and subsequent blur cannot reapply an obsolete draft. + +Window: `rect` / `onRectCommit` — восстановление и фиксация геометрии инструментов; см. WINDOWS_AND_LAYERS.md. Иконка `minus` дополняет `plus` для управления масштабом содержимого. + +`EditorDockLayout` / `EditorWorkspace`: переносимый редактор с закреплённым основным видом, четырьмя зонами стыковки, разделителями и отрываемыми панелями. Управляемый `EditorDockState` хранится в документе приложения. Шапка редактора не участвует в стыковке; возврат восстанавливает исходный вид. Контракт, keyboard и минимумы — в WINDOWS_AND_LAYERS.md. diff --git a/docs/WINDOWS_AND_LAYERS.md b/docs/WINDOWS_AND_LAYERS.md index f94fee8..141df52 100644 --- a/docs/WINDOWS_AND_LAYERS.md +++ b/docs/WINDOWS_AND_LAYERS.md @@ -129,3 +129,25 @@ Selecting a different settings section resets only its content scroll to the top Docked content declares minimumSize for both axes. The divider stops at the recursive content boundary; a small overall viewport scrolls the layout canvas. `DockLayout.panels[].preferredSize` задаёт начальный компактный размер. Продукт передаёт его только для новой раскладки без сохранённой геометрии; первый resize/dock сохраняет пользовательскую геометрию. Минимумы продолжают действовать при всех последующих размерах. + +## Free-window mode for centered windows + +A centered `Window` exposes the semantic `move` icon beside close (`allowFloating`, true by default). The toggle retains the mounted contents and captures their current dimensions. In floating mode the backdrop has no dimming or blur and passes interaction to the background; body scrolling and focus trapping are released. Drag the header or resize from any of the eight invisible border regions. No hover handles or decorative resize marks are drawn. Edges and corners expose their directional resize cursor; the movable header uses the move cursor. Keyboard users focus the header and use arrows to move or Shift+arrows to resize. Geometry is clamped on manipulation and viewport resize. + +Turning the free mode off returns the same contents to the normal centered size and modal semantics. Turning it on again during the same opening restores the floating rectangle. Closing clears it. Portal ownership remains the active fullscreen element or body. Nested dialogs keep their own modal behavior. Inspector controls inside windows stretch to available width. + +## Сохранённая геометрия инструментов + +`Window.rect: WindowRect` и `onRectCommit` позволяют приложению хранить геометрию в своём документе. Для `placement="end" resizable` размеры и координаты восстанавливаются при открытии и при внешнем undo/import. Перетаскивание и resize обновляются локально; callback вызывается один раз при завершении жеста. Клавиатурный шаг тоже фиксируется. Автоматическое вписывание в уменьшенный экран не перезаписывает сохранённый прямоугольник. Без `rect` остаётся прежнее поведение `initialRect`. Пример дерева объектов в каталоге сохраняет прямоугольник между открытиями. + +Действия уменьшения/увеличения содержимого палитр используют канонические `IconButton` с иконками `minus` / `plus` в `headerActions`, рядом с закрытием. Их прикладной масштаб хранится вместе с документом. + +## Scene editor workspace and detachable tools + +`EditorWorkspace` opens the same mounted content in a separate modeless editing window, then returns it to the original inline slot. Back, close and finishing editing share `onBack`; fullscreen is local to this editing window. The fixed header is not a docking target. The application retains its original view height, layout and camera document. The renderer host is moved atomically with `moveBefore` when available; canvas-based renderers remain mounted with the append fallback too. + +`EditorDockLayout` receives `value: EditorDockState`, `onChange`, a locked `primary`, and typed `tools`. Tool descriptors supply title, open/close, content, actions, footer, minimum size and optional initial floating rectangle. The primary cannot detach. Each tool keeps its DOM host when docked, floating or temporarily hidden. The split tree, floating rectangles and any application-owned palette scale belong to the scene document, not a global library store. + +Drag a tool header to any of four outer edges to create a full-side area; drop over another tool to split beside it. Drop in the primary center to detach. An exact destination preview is shown only during placement. A 24 px outer zone wins over panel targets; broader magnets reach 160 px horizontally / 96 px vertically, capped at 16% of the workspace. The center of a tool chooses its nearest side, never swaps it with the primary. Split minima protect content; small viewports scroll the bounded layout. Invisible floating edges resize, and only the cursor changes. + +Header Enter/Space begins keyboard docking, arrows choose an edge, Shift+arrows choose the whole workspace, Tab selects a tool, Home selects floating, Enter commits and Escape cancels. Floating headers also accept arrows to move and Shift+arrows to resize. Pointer cancellation and Escape restore the uncommitted layout. Automatic viewport fitting does not overwrite stored rectangles. The living catalog includes the same workspace with a fixed scene, outliner and material palette. diff --git a/package.json b/package.json index 7c61e66..4cf2517 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "build": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react && npm run build --workspace @nodedc/ui-catalog", "build:packages": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react", - "check": "npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces", + "check": "npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock", "dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog", "serve": "node server/catalog-server.mjs", "validate:registry": "node scripts/validate-registry.mjs", @@ -43,7 +43,9 @@ "test:split-pane": "node --test scripts/split-pane-contract.test.mjs", "test:dock-layout": "node --test scripts/dock-layout.test.mjs", "test:analysis-controls": "node --test scripts/analysis-controls.test.mjs", - "test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs" + "test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs", + "test:window-geometry": "node --test scripts/window-geometry.test.mjs", + "test:editor-dock": "node --test scripts/editor-dock.test.mjs" }, "engines": { "node": ">=20" diff --git a/packages/tokens/tokens.css b/packages/tokens/tokens.css index b1702df..1987c0a 100644 --- a/packages/tokens/tokens.css +++ b/packages/tokens/tokens.css @@ -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; } diff --git a/packages/ui-core/src/editorDock.ts b/packages/ui-core/src/editorDock.ts new file mode 100644 index 0000000..f4669ba --- /dev/null +++ b/packages/ui-core/src/editorDock.ts @@ -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} +export function decodeEditorDock(raw:unknown,primary:string,tools:readonly string[]):EditorDockState|null { + if(!raw||typeof raw!=='object')return null; + const value=raw as Partial,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={}; + 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,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(); + 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); +} diff --git a/packages/ui-core/src/glass.ts b/packages/ui-core/src/glass.ts index a3ccac8..d593425 100644 --- a/packages/ui-core/src/glass.ts +++ b/packages/ui-core/src/glass.ts @@ -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 { +export function createGlassMaterialVariables(settings: GlassMaterialSettings, context: "floating" | "scene" = "floating"): Record { 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`, diff --git a/packages/ui-core/src/index.ts b/packages/ui-core/src/index.ts index c600062..217eca0 100644 --- a/packages/ui-core/src/index.ts +++ b/packages/ui-core/src/index.ts @@ -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"; diff --git a/packages/ui-core/styles.css b/packages/ui-core/styles.css index 7dcbee2..963675f 100644 --- a/packages/ui-core/styles.css +++ b/packages/ui-core/styles.css @@ -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; } diff --git a/packages/ui-react/src/ApplicationPanelFullscreen.tsx b/packages/ui-react/src/ApplicationPanelFullscreen.tsx new file mode 100644 index 0000000..619b3d3 --- /dev/null +++ b/packages/ui-react/src/ApplicationPanelFullscreen.tsx @@ -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(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 =
    {children}
    ; + return mount ? <>
    {createPortal(content,mount)} : content; +} diff --git a/packages/ui-react/src/ApplicationShell.tsx b/packages/ui-react/src/ApplicationShell.tsx index b0454c7..f8ad783 100644 --- a/packages/ui-react/src/ApplicationShell.tsx +++ b/packages/ui-react/src/ApplicationShell.tsx @@ -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, "content"> { @@ -52,6 +53,8 @@ export interface ApplicationPanelProps extends Omit, 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 = (
    @@ -131,4 +135,5 @@ export function ApplicationPanel({
    {children}
    ); + return allowFullscreen ? {panel} : panel; } diff --git a/packages/ui-react/src/DragDrop.tsx b/packages/ui-react/src/DragDrop.tsx index 363b71e..220b444 100644 --- a/packages/ui-react/src/DragDrop.tsx +++ b/packages/ui-react/src/DragDrop.tsx @@ -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 {children}; + return {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}>{children}{renderOverlay&&typeof document!=='undefined'&&createPortal({active?renderOverlay(active):null},document.fullscreenElement??document.body)}; } 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["attributes"];listeners:ReturnType["listeners"]} }) => ReactNode; }) { const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id, data }); + const overlay=useContext(DragOverlayContext); return (
    - {children({ handle: , isDragging })} + {children({ handle: , isDragging, activator:{attributes,listeners} })}
    ); } diff --git a/packages/ui-react/src/EditorDockLayout.tsx b/packages/ui-react/src/EditorDockLayout.tsx new file mode 100644 index 0000000..0b26fcb --- /dev/null +++ b/packages/ui-react/src/EditorDockLayout.tsx @@ -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(null),viewport=useRef(null); + const [bounds,setBounds]=useState({left:0,top:0,width:1,height:1}); + const [drag,setDrag]=useState(null),gesture=useRef(null); + const [order,setOrder]=useState([]),[keyboard,setKeyboard]=useState<{id:string;target:DockMove|null}|null>(null); + const previousTools=useRef(new Map()); + 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,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)=>{ + 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
    +
    + onChange({...value,tree:mergeEditorDockRatios(value.tree,resizeDockSplit(constrained,path,ratio))})}/> +
    {primary}
    + {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 ; +} +function EditorSplits({tree,bounds,minimums,onResize,path=''}:{tree:DockTree;bounds:DockMinimum;minimums:Record;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 onResize(path,ratio)} separatorLabel="Изменить размеры панелей редактора" + primary={} + secondary={}/>; +} diff --git a/packages/ui-react/src/EditorWorkspace.tsx b/packages/ui-react/src/EditorWorkspace.tsx new file mode 100644 index 0000000..fd725d2 --- /dev/null +++ b/packages/ui-react/src/EditorWorkspace.tsx @@ -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(null),[host]=useState(()=>document.createElement('div')); + const [expanded,setExpanded]=useState(false),opener=useRef(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('[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
    {createPortal( +
    {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&&
    +

    {title}

    {subtitle&&

    {subtitle}

    }
    +
    + + setExpanded(v=>!v)}> + + +
    +
    } +
    {children}
    +
    ,host)}
    ; +} diff --git a/packages/ui-react/src/Glass.tsx b/packages/ui-react/src/Glass.tsx index cee0d3c..758fd98 100644 --- a/packages/ui-react/src/Glass.tsx +++ b/packages/ui-react/src/Glass.tsx @@ -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 { 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
    {children}
    ; +/** 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
    {children}
    ; } export interface MapGlassSurfaceProps extends HTMLAttributes { diff --git a/packages/ui-react/src/Icon.tsx b/packages/ui-react/src/Icon.tsx index b6d10c4..f83dbb8 100644 --- a/packages/ui-react/src/Icon.tsx +++ b/packages/ui-react/src/Icon.tsx @@ -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, diff --git a/packages/ui-react/src/ResizableViewport.tsx b/packages/ui-react/src/ResizableViewport.tsx new file mode 100644 index 0000000..6fa577c --- /dev/null +++ b/packages/ui-react/src/ResizableViewport.tsx @@ -0,0 +1,47 @@ +import {useRef, type HTMLAttributes, type ReactNode} from "react"; +import {cn} from "./cn.js"; + +export interface ResizableViewportProps extends Omit, "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
    + {children} + {(["start", "end"] as const).map(corner =>
    { + 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); + }}/>) } +
    ; +} diff --git a/packages/ui-react/src/SceneAnnotation.tsx b/packages/ui-react/src/SceneAnnotation.tsx new file mode 100644 index 0000000..33ba59d --- /dev/null +++ b/packages/ui-react/src/SceneAnnotation.tsx @@ -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(function SceneAnnotation({className,...props},ref){ + return :null} + + {node.label} + {onVisibilityChange&&node.visible!==undefined&&} +
    )} +
    ; +} diff --git a/packages/ui-react/src/Window.tsx b/packages/ui-react/src/Window.tsx index 0d3bf5f..f4d25d6 100644 --- a/packages/ui-react/src/Window.tsx +++ b/packages/ui-react/src/Window.tsx @@ -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, "title"> { open: boolean; @@ -41,6 +45,15 @@ export interface WindowProps extends Omit, "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(null); + const rectRef = useRef(null); + const initialRectRef = useRef(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(focusableSelector); + const firstFocusable = Array.from(dialogRef.current?.querySelectorAll(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(focusableSelector)); + if (event.key !== "Tab" || !modeRef.current.shouldTrapFocus || !dialogRef.current) return; + const focusable = Array.from(dialogRef.current.querySelectorAll(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) => { if (allowBackdropClose && event.target === event.currentTarget) onClose(); @@ -156,29 +227,44 @@ export function Window({ return createPortal( -
    +
    { + 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({
    {headerActions} + {allowFloating && placement === "center" && { + 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); + }}>}
    + {freeGeometry && windowResizeEdges.map(edge => diff --git a/packages/ui-react/src/index.ts b/packages/ui-react/src/index.ts index 0b7bc3a..ada6bd0 100644 --- a/packages/ui-react/src/index.ts +++ b/packages/ui-react/src/index.ts @@ -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"; diff --git a/packages/ui-react/src/windowGeometry.ts b/packages/ui-react/src/windowGeometry.ts new file mode 100644 index 0000000..0b046dd --- /dev/null +++ b/packages/ui-react/src/windowGeometry.ts @@ -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 }; +} diff --git a/registry/components.json b/registry/components.json index 2ba1bfb..333da1f 100644 --- a/registry/components.json +++ b/registry/components.json @@ -85,7 +85,7 @@ "nodedc-map-glass", "nodedc-material-rim" ], - "summary": "Matte application surfaces, the Engine V4 modal material and the light translucent surface used over Cesium imagery.", + "summary": "Matte application surfaces, the Engine V4 modal material and the light translucent surface used over Cesium imagery. Scene overlays reuse V4 blur and tint with independent translucent density.", "anatomy": [ "theme-provided surface", "modal tint", @@ -98,7 +98,8 @@ "default", "strong", "soft", - "map" + "map", + "scene" ], "radiusVariants": [ "card", @@ -112,7 +113,7 @@ "Compact rails of canonical round actions use the pill radius; consumers do not recreate it with a local border radius.", "A material rim is a glass highlight, not a hard product-colored border.", "Nested surfaces must use a softer tone to avoid card-inside-card noise.", - "GlassyMaterialSurface is restricted to modal Windows and the draggable Inspector.", + "GlassMaterialSurface supports modal/Inspector floating material and explicit context=scene telemetry overlays over rendered imagery; ordinary panels remain matte. Optional material and radiusPx apply appearance to one instance without changing the global theme.", "MapGlassSurface is restricted to overlays over Cesium/map imagery and must match the map Toolbar translucency." ] }, @@ -308,7 +309,8 @@ ], "rules": [ "Do not expose a browser-native color dialog as the product runtime UI.", - "The palette owns choice geometry; the consumer owns color validation, persistence and domain reaction." + "The palette owns choice geometry; the consumer owns color validation, persistence and domain reaction.", + "HEX text keeps incomplete drafts; valid six-digit colors apply live, invalid drafts revert on blur/Escape, Enter commits; external undo updates the field." ] }, { @@ -389,7 +391,8 @@ "package": "@nodedc/ui-react", "exports": [ "Window", - "WindowFooterActions" + "WindowFooterActions", + "WindowRect" ], "domPackage": "@nodedc/ui-dom", "domExports": [ @@ -399,7 +402,7 @@ "nodedc-overlay", "nodedc-window" ], - "summary": "Canonical controlled window for modal and right-side panel presentations, with optional headerActions beside close.", + "summary": "Canonical controlled window with a move toggle between centered modal and draggable, resizable modeless presentation.", "behavior": [ "portal to active fullscreen element or body", "focus entry", @@ -408,7 +411,8 @@ "Escape close", "backdrop close policy", "modal-only body scroll lock", - "optional bounded dragging for modeless inspectors" + "optional bounded dragging for modeless inspectors", + "move toggle: preserve mounted contents and current size; remove dimming, backdrop close, scroll lock and focus trap; header drag and eight invisible resize regions" ], "rules": [ "WindowFooterActions aligns modal actions to the trailing edge, including a footer with only one action group; actions wrap within narrow windows.", @@ -418,7 +422,12 @@ "A right-side inspector is modeless by default: no dimming, no backdrop blur, no backdrop close, no focus trap and no body scroll lock.", "A draggable inspector moves by its header and remains clamped to the viewport.", "Closing a modeless inspector is never gated by autosave; preserve the draft, close immediately and report persistence failure through ToastStack.", - "Operational copy inside Window uses component typography tokens; browser-default paragraph or heading sizes are forbidden." + "Operational copy inside Window uses component typography tokens; browser-default paragraph or heading sizes are forbidden.", + "Centered windows expose the move toggle by default; allowFloating opts a workflow out. Returning to modal restores canonical centered geometry; closing clears floating geometry.", + "Floating header supports arrow-key movement and Shift+arrow resizing. Bounds stay inside the viewport. Resize affordances have no hover decoration.", + "Inspectors inside a Window use its full available content width.", + "End inspectors opt into resizable with an optional initialRect; existing eight edge geometry and keyboard resize are shared with floating windows.", + "Application-owned rect restores modeless window geometry on reopen and external undo/import. onRectCommit reports one completed drag/resize or keyboard step; viewport fitting never overwrites saved geometry." ] }, { @@ -696,7 +705,8 @@ "exports": [ "ApplicationShell", "ApplicationPanel", - "useApplicationWorkspace" + "useApplicationWorkspace", + "useApplicationPanelFullscreen" ], "domPackage": "@nodedc/ui-dom", "domExports": [ @@ -722,14 +732,16 @@ "expanded content replaces stage", "global utility actions remain in the panel header across sections", "mobile panels use the available viewport sequentially", - "independent content scrolling" + "independent content scrolling", + "the outer stage boundary clips overflow without becoming a focus-scroll container" ], "rules": [ "The bottom Launcher service rail is product-specific and is not part of the general application template.", "Desktop page gap is 20 px and navigation width follows the Launcher 332–352 px range.", "Applications supply routes, profile data, stage media and panel content without changing shell geometry.", "Light panels use the SEO white surface and shadow tokens rather than a dark shell with inverted text.", - "A layout-level save action belongs to ApplicationPanel.utilityActions and is never duplicated inside individual content cards." + "A layout-level save action belongs to ApplicationPanel.utilityActions and is never duplicated inside individual content cards.", + "ApplicationPanel allowFullscreen exposes an owned full-window context; the whole panel and its header move atomically, preserving the renderer and body-portaled inspectors." ] }, { @@ -909,6 +921,7 @@ "The card owns grouping geometry but not product form schemas.", "Use align=center for compact result or empty messages: center the content on both axes and omit an empty body. The default start layout remains unchanged.", "Section and empty-state titles use the compact md token; descriptions use sm. Page/window title sizes and browser heading defaults are forbidden inside cards.", + "Unclassed paragraphs in the body, including nested layout groups, share Description typography as a compatibility safeguard. New explanatory copy must use Description; headings and controls retain their own typography.", "Use Switch for compact visibility/enable states; use Checker for the Engine inspector treatment.", "Switch keeps its track width beside wrapped labels. The checked thumb uses on-accent contrast; the unchecked track follows theme text instead of a fixed white tint." ] @@ -992,7 +1005,8 @@ "moveDockPanel", "resizeDockSplit", "dockRects", - "dockPosition" + "dockPosition", + "dockMoveAtPoint" ], "domContract": [ "nodedc-dock-layout", @@ -1006,10 +1020,11 @@ "empty source branches collapse", "6 px handle activation", "pointer-position hit testing", - "outside and self drops cancel", + "outside and local self drops cancel", "keyboard docking", "resizable splits", - "focus preserves media hosts" + "focus preserves media hosts", + "four outer workspace edges wrap the remaining layout" ], "rules": [ "Applications persist the serializable tree and own panel content.", @@ -1018,7 +1033,8 @@ "Space or Enter starts keyboard docking, Tab chooses the destination, arrows choose an edge, Home chooses swap, Enter commits and Escape cancels.", "Only the active drag paints a destination contour; no permanent decorative panel outlines.", "Panel minimumSize propagates through split ancestors, constrains pointer/keyboard resize and expands a scrollable canvas below the viewport limit; never clips content to satisfy a ratio.", - "preferredSize applies only to an unsaved default layout; minimumSize always constrains nested splits and scroll canvas." + "preferredSize applies only to an unsaved default layout; minimumSize always constrains nested splits and scroll canvas.", + "The outer visible-workspace zone is 24 CSS px, capped at 8% per axis; it wins over local panel zones, including over the source. Shift+arrows select the same workspace edges. Preview and commit both apply panel minimum sizes; existing DockTree persistence is unchanged." ] }, { @@ -1051,7 +1067,10 @@ "A transfer is accepted only when the dragged surface overlaps the destination by at least the consumer-defined threshold; Module Foundry uses 20 percent.", "Consumers own domain mutations while the package owns sensors, transforms, accessible drag attributes and geometry.", "Repeated page-template drops create distinct application page instances instead of consuming the source template.", - "A reordered application page array is the single source of truth for both composition and navigation order." + "A reordered application page array is the single source of truth for both composition and navigation order.", + "Optional renderOverlay portals the drag preview above scroll clipping without moving source layout; cancellation clears it.", + "Pointer drops report client coordinates for consumer-owned canvas hit testing; dropping on empty space never implies an object target.", + "DraggableItem exposes activator attributes/listeners for whole-tile dragging without a separate handle; the same activation threshold distinguishes clicks from drags." ] }, { @@ -1168,7 +1187,8 @@ ], "summary": "Secondary explanatory copy matching SettingsCard descriptions.", "rules": [ - "Use the same inherited family, regular 400 weight, small font token, muted text token and 1.4 line height for explanatory paragraphs. Do not restyle per feature." + "Use the same inherited family, regular 400 weight, small font token, muted text token and 1.4 line height for explanatory paragraphs. Do not restyle per feature.", + "Use role=status for explanatory pending/result copy. SettingsCard applies the same contract to unclassed body paragraphs as a fallback, without changing headings or controls." ] }, { @@ -1211,6 +1231,134 @@ "Labels rotate and foreshorten in the face plane; they never billboard" ], "documentation": "../docs/NAVIGATION_CUBE.md" + }, + { + "id": "tree", + "status": "baseline", + "package": "@nodedc/ui-react", + "exports": [ + "Tree", + "TreeNode", + "TreeProps" + ], + "domContract": [ + "nodedc-tree", + "nodedc-tree__row" + ], + "summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.", + "behavior": [ + "selection expands ancestors and scrolls only the tree container", + "Arrow/Home/End navigation, disclosure and optional visibility actions", + "long names ellipsize without growing row height", + "filter retains matching ancestors" + ], + "rules": [ + "Use for object hierarchies; no nested ResourceRow cards.", + "Host owns model identity and visibility; the tree owns navigation presentation." + ] + }, + { + "id": "resizable-viewport", + "status": "baseline", + "package": "@nodedc/ui-react", + "exports": [ + "ResizableViewport", + "ResizableViewportProps" + ], + "domContract": [ + "nodedc-resizable-viewport", + "nodedc-resizable-viewport__grip" + ], + "summary": "In-flow viewer with controlled height and two accessible bottom corner grips.", + "anatomy": [ + "content", + "bottom-left grip", + "bottom-right grip" + ], + "variants": [ + "height-only", + "hidden-indicator" + ], + "states": [ + "idle", + "hover", + "focus", + "resizing" + ], + "rules": [ + "The owner persists height per view; the component never writes application storage.", + "Pointer capture isolates resizing from scene navigation. Up/Down resize, Shift accelerates, Home/End use limits.", + "Only the viewport height changes; the page and browser retain their dimensions.", + "resizeIndicator=false hides both glyphs and hover surfaces. Pointer resizing shows only the cursor; keyboard focus remains visible." + ] + }, + { + "id": "scene-annotation", + "status": "baseline", + "package": "@nodedc/ui-react", + "exports": [ + "SceneAnnotation" + ], + "domContract": [ + "nodedc-scene-annotation" + ], + "summary": "Transparent interactive data label projected onto a real scene object.", + "anatomy": [ + "canonical ghost button", + "stacked label and data" + ], + "states": [ + "idle", + "hover", + "selected", + "keyboard-focus" + ], + "rules": [ + "Renderer owns projection and offscreen/hidden-object clipping; the label does not infer measurements.", + "Use canonical button keyboard and focus semantics, transparent resting surface, compact numeric typography." + ] + }, + { + "id": "editor-dock-layout", + "status": "baseline", + "package": "@nodedc/ui-react", + "exports": [ + "EditorDockLayout", + "EditorDockLayoutProps", + "EditorDockTool", + "EditorDockState", + "EditorWorkspace", + "EditorWorkspaceProps", + "decodeEditorDock", + "dockEditorTool", + "editorDockTarget", + "mergeEditorDockRatios" + ], + "domContract": [ + "nodedc-editor-dock", + "nodedc-editor-dock__tool", + "nodedc-editor-workspace" + ], + "summary": "Fixed primary scene with detachable docked tools and a separate editor window that restores the original view.", + "behavior": [ + "four outer magnetic edges", + "nested adjacent tool splits", + "drag header to detach over primary", + "invisible resize regions", + "controlled JSON layout", + "stable mounted renderer", + "keyboard docking and cancellation", + "fixed header outside docking bounds" + ], + "rules": [ + "Applications own scene content, visibility and persisted layout; tools share one generic docking implementation.", + "Primary content cannot detach or swap with a tool. Dropping in the primary center makes a tool floating.", + "Outer 24 px has priority; additional magnets extend to 160 px horizontally and 96 px vertically, capped at 16% of the host.", + "Header Enter/Space starts keyboard docking; arrows select edges, Shift+arrows the whole workspace, Tab cycles tools, Home floats, Escape cancels. Floating headers also support arrows and Shift+arrows for move/resize.", + "Hidden tools retain their docking placement and remembered floating rectangle. Viewport clamps never overwrite preferred geometry.", + "EditorWorkspace keeps one mounted portal host, moves it atomically when supported, and restores its original slot on return. It never changes the source-view layout.", + "The fixed editor header is outside docking bounds. Back, edit completion and close return to the original view." + ] } ] } diff --git a/registry/icons.json b/registry/icons.json index ebe99f9..93378a0 100644 --- a/registry/icons.json +++ b/registry/icons.json @@ -25,12 +25,14 @@ "names": [ "close", "plus", + "minus", "expand", "minimize", "refresh", "panel", "apps", - "layers" + "layers", + "move" ] }, { diff --git a/scripts/editor-dock.test.mjs b/scripts/editor-dock.test.mjs new file mode 100644 index 0000000..49c4a52 --- /dev/null +++ b/scripts/editor-dock.test.mjs @@ -0,0 +1,56 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {dockIds,dockRects,pruneDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js'; +import {decodeEditorDock,dockEditorTool,editorDockTarget,mergeEditorDockRatios} from '../packages/ui-core/dist/editorDock.js'; +const bounds={left:0,top:0,width:1400,height:900},rect={left:400,top:200,width:360,height:400}; +const start={tree:{id:'viewport'},floating:{}}; +test('floating tools can dock to every side; primary survives every detach',()=>{ + for(const position of ['left','right','top','bottom']){ + const dock=dockEditorTool(start,'viewport',{activeId:'tree',overId:'viewport',position,scope:'workspace'},'tree',rect); + assert.deepEqual(dockIds(dock.tree).sort(),['tree','viewport']); + const r=dockRects(dock.tree,bounds);assert.equal(position==='left'?r.tree.left===0:position==='right'?r.tree.left>r.viewport.left:position==='top'?r.tree.top===0:r.tree.top>r.viewport.top,true); + const free=dockEditorTool(dock,'viewport',null,'tree',rect);assert.deepEqual(free.tree,start.tree);assert.deepEqual(free.floating.tree,rect); + assert.equal(dockEditorTool(dock,'viewport',null,'viewport',rect),dock); + } +}); +test('adjacent bottom tools fill one row; detaching collapses only their empty branch',()=>{ + const a=dockEditorTool(start,'viewport',{activeId:'palette',overId:'viewport',position:'bottom',scope:'workspace'},'palette',rect); + const b=dockEditorTool(a,'viewport',{activeId:'tree',overId:'palette',position:'right'},'tree',rect),r=dockRects(b.tree,bounds); + assert.equal(r.tree.top,r.palette.top);assert.equal(r.tree.height,r.palette.height);assert.equal(r.viewport.width,1400); + assert.deepEqual(dockEditorTool(b,'viewport',null,'tree',rect).tree,a.tree); +}); +test('primary center floats, broad edge magnets and panel targets use pointer location',()=>{ + const r={viewport:bounds,palette:{left:0,top:700,width:1400,height:200}}; + assert.equal(editorDockTarget(bounds,r,'viewport','tree',700,400),null); + assert.equal(editorDockTarget(bounds,r,'viewport','tree',100,400).position,'left'); + assert.equal(editorDockTarget(bounds,r,'viewport','tree',700,40).position,'top'); + assert.equal(editorDockTarget(bounds,r,'viewport','tree',1300,800).overId,'palette'); + assert.equal(editorDockTarget(bounds,r,'viewport','tree',700,899).scope,'workspace'); + assert.equal(editorDockTarget(bounds,r,'viewport','tree',100,-1),null); +}); +test('closed tool retains placement when a visible split resizes',()=>{ + const full={axis:'x',ratio:25,first:{id:'objects'},second:{axis:'y',ratio:70,first:{id:'viewport'},second:{id:'palette'}}}; + const visible=pruneDockTree(full,['viewport','palette']); + const next=mergeEditorDockRatios(full,resizeDockSplit(visible,'',62)); + assert.equal(next.ratio,25);assert.equal(next.second.ratio,62);assert.deepEqual(next.first,full.first); +}); +test('outer magnets follow the visible viewport when minimum-size canvas is scrolled',()=>{ + const b={left:112,top:40,width:768,height:580},r={viewport:{left:280,top:0,width:320,height:400},objects:{left:0,top:0,width:280,height:580},material:{left:600,top:0,width:280,height:580}}; + assert.equal(editorDockTarget(b,r,'viewport','objects',879,300).position,'right'); + assert.equal(editorDockTarget(b,r,'viewport','objects',400,41).position,'top'); + assert.equal(editorDockTarget(b,r,'viewport','objects',100,300),null); +}); +test('untrusted layout excludes unknown identities and primary floating geometry',()=>{ + const value=decodeEditorDock({tree:{axis:'x',ratio:Infinity,first:{id:'bad'},second:{id:'objects'}},floating:{viewport:rect,objects:{...rect,width:NaN},palette:rect}},'viewport',['objects','palette']); + assert.deepEqual(value.tree,{id:'viewport'});assert.deepEqual(value.floating,{palette:rect}); + assert.deepEqual(decodeEditorDock(JSON.parse(JSON.stringify(value)),'viewport',['objects','palette']),value); +}); +test('repeated dock and float transitions retain unique tools and tile the full workspace',()=>{ + let state=start; + for(let round=0;round<4;round++)for(const id of ['objects','palette','material','environment'])for(const position of ['left','right','top','bottom']){ + state=dockEditorTool(state,'viewport',{activeId:id,overId:'viewport',position,scope:'workspace'},id,rect); + const ids=dockIds(state.tree);assert.equal(new Set(ids).size,ids.length);assert.ok(ids.includes('viewport')); + const boxes=Object.values(dockRects(state.tree,bounds));assert.ok(Math.abs(boxes.reduce((n,r)=>n+r.width*r.height,0)-bounds.width*bounds.height)<1e-6); + const free=dockEditorTool(state,'viewport',null,id,rect);assert.ok(!dockIds(free.tree).includes(id));assert.deepEqual(free.floating[id],rect); + } +}); diff --git a/scripts/window-geometry.test.mjs b/scripts/window-geometry.test.mjs new file mode 100644 index 0000000..cbed7fa --- /dev/null +++ b/scripts/window-geometry.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {fitWindow,resizeWindow,windowResizeEdges} from '../packages/ui-react/dist/windowGeometry.js'; +const bounds={width:1200,height:800}, r={left:200,top:100,width:600,height:400}; +test('all resize edges preserve the opposite anchor and remain within the viewport',()=>{ + for(const edge of windowResizeEdges) for(const dx of [-2000,-25,25,2000]) for(const dy of [-2000,-25,25,2000]){ + const v=resizeWindow(r,edge,dx,dy,bounds); + assert.ok(v.width>=320&&v.height>=200);assert.ok(v.left>=8&&v.top>=8&&v.left+v.width<=1192&&v.top+v.height<=792); + if(edge.includes('w'))assert.equal(v.left+v.width,r.left+r.width);else assert.equal(v.left,r.left); + if(edge.includes('n'))assert.equal(v.top+v.height,r.top+r.height);else assert.equal(v.top,r.top); + } +}); +test('viewport shrink retains reachable header and fits small screens',()=>{ + const v=fitWindow({...r,left:1100,top:750},{width:280,height:180}); + assert.deepEqual(v,{left:8,top:8,width:264,height:164}); + assert.deepEqual(fitWindow(r,bounds),r); +});