feat(scene-editor): add persistent dockable tool workspaces

This commit is contained in:
Codex
2026-11-04 00:39:39 +03:00
parent ecf53ce974
commit 972944e6f2
27 changed files with 1020 additions and 67 deletions
+51 -4
View File
@@ -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.
+22
View File
@@ -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.