Files
NODEDC_DESIGN_GUIDELINE/docs/WINDOWS_AND_LAYERS.md
T

162 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Окна, dropdown и слои
## Зачем отдельный контракт
В NODE.DC повторяется одна механика: пользователь нажимает trigger, открывается окно или floating surface, взаимодействует и закрывает его. Если каждое приложение реализует outside click, Escape, portal и z-index отдельно, одинаковые окна начинают вести себя по-разному.
## Layer scale
- base: `0`;
- panel: `100`;
- header: `400`;
- overlay/window: `800`;
- dropdown/popover: `900`;
- toast: `950`.
Произвольные значения вроде `30030` допускаются только во временном legacy adapter. Новый код использует scale.
## Dropdown/popover
Обязательное поведение:
1. trigger сообщает `aria-expanded`;
2. surface переносится в body;
3. координаты рассчитываются как fixed;
4. горизонтальная позиция ограничивается viewport;
5. при недостатке места surface меняет bottom/top placement;
6. scroll/resize пересчитывают позицию;
7. trigger, полностью ушедший за viewport, закрывает surface;
8. outside pointer и Escape закрывают surface;
9. после Escape фокус возвращается на trigger;
10. открытие другого корневого dropdown закрывает предыдущий; вложенные меню сохраняют предков, а Escape закрывает только самый глубокий слой.
Inline absolute dropdown внутри card/sidebar/sticky container является дефектом.
## Modal window
Обязательное поведение:
1. window рендерится в body;
2. при открытии запоминается текущий focus;
3. focus переносится на первый интерактивный элемент или dialog;
4. Tab не выходит за пределы dialog;
5. Escape закрывает окно, если операция не блокирует закрытие;
6. backdrop закрывает окно только при клике именно на backdrop;
7. body scroll блокируется;
8. после закрытия focus возвращается на предыдущий trigger.
## Карта modal-паттернов
| Тип | Источник | Каноническая реализация |
| --- | --- | --- |
| Form/create/save | Launcher, CMS, BIM | `Window` + Field/Select + footer actions |
| Destructive confirmation | Launcher, Engine, BIM | `ConfirmationModal` |
| Workflow access sharing | новый Engine | `ShareAccessModal` |
| Resource link sharing | BIM Viewer | `ShareLinkModal` / `createShareLinkController` |
| Context actions | BIM measurement/object | `Window size="sm"` + application-owned actions |
| Expandable detail | BIM comment workspace | `Window` или `ApplicationPanel`, domain content остаётся в BIM |
| Large data/history | BIM version history | `Window size="lg"`, data table остаётся domain composition |
Новый тип появляется только если отличается поведением слоя или имеет устойчивую независимую anatomy. Разная таблица, форма или текст внутри Window не создают новую modal-систему.
## Side window / inspector
Side window использует ту же механику, но placement `end` и ограниченную ширину. Это канон для:
- настроек окружения;
- инспектора агентной ноды;
- будущих detail/settings panels;
- CMS/SEO side editors, если они не требуют отдельного полноэкранного workflow.
По умолчанию это modeless-слой: он не затемняет страницу, не перехватывает клики по основной области, не закрывается по backdrop, не блокирует body scroll и не удерживает Tab внутри панели. Escape и кнопка закрытия остаются доступны. Если конкретный workflow должен быть modal, это задаётся явно, а не получается случайно из placement.
### ApplicationSidePanel: отдельная push-колонка
Когда settings/detail принадлежат всему Application и должны физически
уменьшать рабочую область, используется `ApplicationSidePanel` внутри
`ApplicationShell.endPanel`. На desktop панель имеет ту же ширину, surface,
радиус и тень, что `AdminNavigationPanel`, входит справа налево и сдвигает
content/stage на panel width + page gap. Она не является `Window`, не получает
backdrop и не входит в stack bounded-окон сцены.
Открытие панели контролирует action в header владельца, закрытие — тот же
action или обязательный close action самой панели. Клик по рабочей области не
закрывает её неявно. На mobile отдельная колонка становится полноширинным
верхним panel-layer, потому что сохранять две узкие колонки там невозможно.
## Workspace window
`WorkspaceWindow` отличается от modal и side inspector границей слоя: это inline modeless-окно, ограниченное конкретной рабочей сценой приложения.
Обязательное поведение:
1. окно рендерится внутри bounds-контейнера без portal;
2. приложение контролирует rectangle, maximized-state, visibility, active-state и z-order;
3. drag доступен за header мышью, touch/pen pointer и стрелками клавиатуры;
4. resize выполняется нижней правой ручкой pointer-ом или стрелками клавиатуры;
5. move и resize всегда ограничены текущими размерами workspace;
6. `ResizeObserver` повторно ограничивает rectangle после изменения layout;
7. maximize заполняет только workspace, а restore возвращает сохранённый приложением rectangle;
8. close сообщает intent приложению и не создаёт внутренний store;
9. родительский bounds-контейнер использует `position: relative` и `overflow: hidden`.
Workspace window используется для вспомогательных камер, инструментов и сопоставляемых представлений внутри stage. Оно не заменяет modal `Window`, viewport-level Inspector или `ApplicationPanel`.
Если Inspector принадлежит конкретной bounded-сцене и должен конкурировать по
z-order с её карточками и инструментами, он является содержимым
`WorkspaceWindow`, а не application-level side panel. Текущий Map Page
разделяет уровни явно: активный сектор, окна bindings и карточка объекта входят
в один bounded stack; настройки карты живут в `ApplicationSidePanel`; короткие
настройки слоёв открываются из нижнего toolbar через `Dropdown` в том же
map-glass дизайне, что Objects.
## Управление состоянием
Библиотека не создаёт глобальный store окон. Приложение владеет тем, какое окно открыто и какие данные в нём загружены. Библиотека владеет одинаковым поведением самого слоя.
Stack workspace-окон остаётся контролируемым приложением: оно передаёт active-state и `zIndex`, а компонент отвечает только за одинаковую геометрию и взаимодействие. Глобальный stack viewport-level modeless-окон остаётся отдельным будущим контрактом.
## Контекстные действия заголовка
`Window.headerActions` и `FeatureSettingsWindow.headerActions` принимают канонические `IconButton`. Обновление содержимого находится рядом с закрытием; сохранение и отмена формы остаются в footer. Слот входит в focus trap окна, а клики по действиям не начинают перетаскивание. Pending/disabled задаёт владелец данных; закрытие остаётся доступным.
На узком экране центрированное окно учитывает padding своего overlay с обеих сторон. В `FeatureSettingsWindow` меню занимает высоту содержимого, а оставшаяся высота отдана прокручиваемой форме. Проверочный пример «Настройки модуля» находится в живом каталоге окон; проверять в том числе на ширине 390 px.
FeatureSettingsWindow owns two independent scrollports. Its outer body is overflow-hidden; both navigation and content are min-height:0, overflow:auto, keyboard-focusable and overscroll-contained. Long left menus never move the right body. At narrow widths navigation remains capped and the content receives the remaining height.
Selecting a different settings section resets only its content scroll to the top; navigation keeps its position.
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.
When an EditorWorkspace detaches from a Window, the owning overlay is suspended
without unmounting its children. Its backdrop and focus trap are inactive until
the editor returns. Escape/Tab belong to the focused dialog, so nested settings
close without also closing the battery/detail window.
Portal typography is self-contained: Window text base is md/13 px, its title is title/18 px, and explanatory/status paragraphs use Description/sm/12 px. This stays identical in centered and floating modes and is independent of the host body size.