Author SHA1 Message Date
Codex d0648014f5 feat(ui): add thin horizontal single-value range rail 2026-11-15 15:26:33 +03:00
Codex 4390d1350d Apply scene glass to detached editor tools 2026-11-15 13:32:35 +03:00
Codex fea966a3f0 fix(ui): separate tree visibility from disclosure and preserve scroll 2026-11-15 12:33:42 +03:00
Codex 8b49296efa fix(ui): keep invisible dock separators clear during pointer resize 2026-11-15 11:36:29 +03:00
Codex 70d5d8b385 fix(ui): remove decorative palette rim 2026-11-14 23:51:55 +03:00
Codex cb49932706 fix(ui): keep editor headers and footers outside scroll overflow 2026-11-14 23:45:03 +03:00
Codex 5f93defabf fix(ui): constrain editor tools and add screen color sampling 2026-11-14 23:37:36 +03:00
Codex d7885fe098 Support controlled multi-selection and visible ranges in Tree 2026-11-14 23:05:56 +03:00
Codex d8ed37e09d Unify viewport glass and professional BIM controls 2026-11-14 22:53:01 +03:00
Codex 9a00d0bb06 Round only exterior corners of docked editor panes 2026-11-14 22:37:52 +03:00
Codex 616ec9160a fix(ui): preserve focused dock action contrast 2026-11-14 22:12:41 +03:00
Codex 1cc360f99a fix(ui): keep information menus closed after Escape 2026-11-14 22:09:08 +03:00
Codex 31ed774529 fix(ui): keep tree information menus within viewport bounds 2026-11-14 22:01:43 +03:00
Codex 6f2f9644fe feat(ui): extend shared tree actions and BIM tool menus 2026-11-14 21:55:07 +03:00
Codex 91a5ebe8da Keep dock headings legible under keyboard focus 2026-11-14 21:42:58 +03:00
Codex ce1b707348 Reuse scene editor workspace for detachable viewers 2026-11-14 21:05:12 +03:00
Codex 64908711a4 Merge remote-tracking branch 'origin/main' 2026-11-14 20:45:56 +03:00
Codex 3d4c4aaa08 Standardize Glass V4 on individual viewport controls and overlays 2026-11-14 20:30:32 +03:00
DCCONSTRUCTIONS 541fb2a2c3 Document CMS path bar adoption and server GUI preferences 2026-11-13 18:13:07 +03:00
DCCONSTRUCTIONS 1326ec6cc9 Add shared Finder-style path bar for DOM media browsers 2026-11-13 18:03:15 +03:00
DCCONSTRUCTIONS 1ec17b3098 Add reusable centered DOM modal resizing with preference adapter 2026-11-13 17:52:26 +03:00
Codex 661ca2afd2 merge: preserve compact typography alongside shared Mission theme updates 2026-11-11 23:55:19 +03:00
Codex 59411f4937 feat(ui): add accessible tooltips and enforce compact operational typography 2026-11-11 23:53:26 +03:00
Codex 601ca62e9a feat(ui): support storage settings, pinned copies and contextual window actions 2026-11-10 01:04:24 +03:00
DCCONSTRUCTIONS 633b0db7b3 docs(ui): reconcile current CMS and Device adoption 2026-11-06 00:16:35 +03:00
DCCONSTRUCTIONS 189bb70377 fix(ui): match Mission Core form grouping without recessed canvases 2026-11-05 16:00:16 +03:00
DCCONSTRUCTIONS 3750a94200 Establish Mission Core as the shared theme foundation 2026-11-05 13:46:35 +03:00
DCCONSTRUCTIONS 06cb8ad4cd fix(ui): keep canonical profile clear of mobile header controls 2026-11-05 13:18:56 +03:00
DCCONSTRUCTIONS 55fa5fa6bc fix(ui): make the shared three-part profile the canonical header 2026-11-05 13:02:56 +03:00
DCCONSTRUCTIONS fdc93a3136 fix(ui): compose canonical three-part profile header 2026-11-05 12:51:53 +03:00
DCCONSTRUCTIONS 8addef187b feat(ui): add flat surfaces and compact profile/site controls 2026-11-05 12:33:25 +03:00
DCCONSTRUCTIONS 4904fbe1f7 docs: record DC CMS package adoption and adapter ownership 2026-11-05 12:07:32 +03:00
Codex be929f9d8e feat(ui): standardize inspector spacing and compact level geometry 2026-11-04 18:18:10 +03:00
Codex 8ff33a6a17 feat(ui): add measured level buttons and suspend modal hosts during scene editing 2026-11-04 17:13:43 +03:00
Codex bbbfa8912f feat(icons): add confirmed computer power action 2026-11-04 01:01:28 +03:00
Codex 972944e6f2 feat(scene-editor): add persistent dockable tool workspaces 2026-11-04 00:39:39 +03:00
Codex ecf53ce974 feat(docking): support outer workspace edge targets 2026-11-04 00:39:39 +03:00
Codex ac65b1167f fix(controls): preserve editable color values and settings typography 2026-11-04 00:39:39 +03:00
87 changed files with 2991 additions and 314 deletions
+7
View File
@@ -12,6 +12,8 @@ Before adding UI to a NODE.DC application:
Canonical source limits:
- Mission Core is the owner-approved dark-theme reference (2026-11-05). Its audited palette and shared operator presentation are maintained here; apps consume `missionDarkTheme`, not copied CSS.
- Launcher/Hub, CMS and SEO are the reference product family for application shell, headers, windows and common controls.
- From Engine, only the redesigned environment settings, shared glass controls and NDC agent inspector are approved reference sources.
- Legacy Engine inspectors and legacy Engine plates are explicitly non-canonical.
@@ -37,3 +39,8 @@ All subagent work in this repository follows
deploy, install dependencies or expand their own scope.
- Do not invent per-agent token measurements. Report measured usage only when the
product exposes it; otherwise report model, task, state, turns and outcome.
## Enforced compact typography
Operational values/section headings use md (13 px), explanatory/status/error copy uses Description/sm (12 px). Only canonical window/page title roles use title (18 px). Do not add browser-default paragraphs, local larger sizes, font shorthand or inline fontSize. Typography checks are mandatory build gates; never extend the frozen compact legacy baseline or generalize scene/display exceptions to satisfy a feature. Run the typography contract tests and verify computed sizes in centered/floating and narrow windows. See Design Guideline docs/OPERATIONAL_TYPOGRAPHY.md.
+2 -1
View File
@@ -6,7 +6,8 @@
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "tsc -b && vite build",
"typecheck": "tsc -b --pretty false"
"typecheck": "tsc -b --pretty false",
"prebuild": "node --test ../../scripts/operational-typography.test.mjs"
},
"dependencies": {
"@nodedc/page-patterns": "0.1.0",
+89 -28
View File
@@ -1,13 +1,19 @@
import { OperationalTypographyDemo } from "./OperationalTypographyDemo";
import { ModalSizeExample } from './ModalSizeExample';
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 {MissionThemeExample} from './MissionThemeExample';
import {EditorDockExample} from './EditorDockExample';
import {
ActivityIndicator,
Tooltip,
LoadingRegion,
Description,
ComparisonTable,
StatusBadge,
ProgressBar,
LevelButton,
ProgressButton,
LayerStackIndicator,
AdminNavigationPanel,
@@ -30,8 +36,9 @@ import {
FeatureSettingsWindow,
GlassSurface,
GlassMaterialSurface,
ResizableViewport,
SceneAnnotation,
HeaderNavigation,
HeaderProfile,
HeaderWorkspace,
Icon,
IconButton,
@@ -41,6 +48,7 @@ import {
RangeControl,
ResourceRow,
ResourceList,
Tree,
SegmentedControl,
SegmentedGroup,
SegmentedButton,
@@ -117,7 +125,8 @@ const designProfileDocumentPath = (reference: { id: string; version: string; sta
);
const accents: Array<{ label: string; value: RgbTuple; hex: string }> = [
{ label: "NODE.DC", value: [255, 47, 146], hex: "#ff2f92" },
{ label: "Mission Core", value: [247, 248, 244], hex: "#f7f8f4" },
{ label: "Rose", value: [255, 47, 146], hex: "#ff2f92" },
{ label: "Rose", value: [255, 62, 108], hex: "#ff3e6c" },
{ label: "Blush", value: [255, 108, 175], hex: "#ff6caf" },
{ label: "Magenta", value: [215, 70, 255], hex: "#d746ff" },
@@ -143,7 +152,7 @@ const materialDefaults: Record<NodedcTheme, MaterialDraft> = {
panelOpacity: 100,
fieldHex: "#2a2a2c",
fieldOpacity: 100,
nestedHex: "#0b0b0d",
nestedHex: "#0d0d0f",
},
light: {
panelHex: "#ffffff",
@@ -221,17 +230,17 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
{
title: "Редактирование",
note: "Launcher / SEO",
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "orthographic", "perspective", "select", "pen", "rectangle", "curve", "undo", "redo"],
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "ruler", "section", "isolate", "orthographic", "perspective", "fit-view", "select", "pen", "rectangle", "curve", "undo", "redo"],
},
{
title: "Состояние и доступ",
note: "Вся платформа",
icons: ["check", "alert", "info", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
icons: ["check", "alert", "info", "info-plain", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
},
{
title: "Сущности",
note: "Общий словарь",
icons: ["profile", "users", "building", "globe", "target", "database", "network", "inbox", "mail"],
icons: ["profile", "users", "building", "globe", "target", "database", "pin", "network", "inbox", "mail"],
},
{
title: "Контент",
@@ -241,6 +250,10 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
];
const iconLabels: Record<IconName, string> = {
pipette: "Пипетка",
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
power: "Питание",
move: "Свободное окно",
"add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить",
activity: "Активность",
alert: "Предупреждение",
@@ -257,6 +270,7 @@ const iconLabels: Record<IconName, string> = {
close: "Закрыть",
copy: "Копировать",
database: "База данных",
pin: "Закрепить",
download: "Скачать",
edit: "Редактировать",
eye: "Показать",
@@ -270,6 +284,8 @@ const iconLabels: Record<IconName, string> = {
image: "Изображение",
inbox: "Уведомления",
info: "Информация",
"info-plain": "Информация без окружности",
"fit-view": "Вписать модель",
key: "Ключ",
layers: "Слои",
list: "Список задач",
@@ -282,6 +298,7 @@ const iconLabels: Record<IconName, string> = {
play: "Воспроизвести",
target: "Таргеты",
plus: "Добавить",
minus: "Уменьшить",
profile: "Профиль",
refresh: "Обновить",
"rotate-clockwise": "Повернуть по часовой стрелке",
@@ -327,7 +344,7 @@ function Preview({ title, note, children, className }: {
export function CatalogApp() {
const [theme, setTheme] = useState<NodedcTheme>("dark");
const [accentHex, setAccentHex] = useState("#ff2f92");
const [accentHex, setAccentHex] = useState("#f7f8f4");
const [materialByTheme, setMaterialByTheme] = useState<Record<NodedcTheme, MaterialDraft>>(() => ({
dark: { ...materialDefaults.dark },
light: { ...materialDefaults.light },
@@ -380,14 +397,20 @@ export function CatalogApp() {
const [glowDistance, setGlowDistance] = useState(105);
const [usePortColors, setUsePortColors] = useState(false);
const [connectionType, setConnectionType] = useState("spline");
const [lightColor, setLightColor] = useState("#ff2f92");
const [lightColor, setLightColor] = useState("#f7f8f4");
const [connectionColor, setConnectionColor] = useState("#404040");
const [fillColor, setFillColor] = useState("#ff6caf");
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<string|null>('cells');
const [treeVisible,setTreeVisible]=useState(true);
const [treeSelectedIds,setTreeSelectedIds]=useState<string[]>(['cells']);
const [inspectorOpen, setInspectorOpen] = useState(false);
const workspaceWindowDemoRef = useRef<HTMLDivElement>(null);
const [sceneDemoHeight, setSceneDemoHeight] = useState(480);
const [workspaceWindowDemoOpen, setWorkspaceWindowDemoOpen] = useState(true);
const [workspaceWindowDemoMaximized, setWorkspaceWindowDemoMaximized] = useState(false);
const [workspaceWindowDemoRect, setWorkspaceWindowDemoRect] = useState<WorkspaceWindowRect>({ x: 24, y: 24, width: 340, height: 230 });
@@ -396,7 +419,8 @@ export function CatalogApp() {
const [splitPaneDemoSize, setSplitPaneDemoSize] = useState(50);
const [sidePanelDemoOpen, setSidePanelDemoOpen] = useState(true);
const [createModalOpen, setCreateModalOpen] = useState(false);
const [missionAppearance, setMissionAppearance] = useState(false);
const [missionAppearance, setMissionAppearance] = useState(true);
const [flatEdges, setFlatEdges] = useState(true);
const [featureSettingsDemoOpen, setFeatureSettingsDemoOpen] = useState(false);
const [featureSettingsDemoSection, setFeatureSettingsDemoSection] = useState('general');
const [confirmOpen, setConfirmOpen] = useState(false);
@@ -536,6 +560,7 @@ export function CatalogApp() {
applyNodedcTheme(document.documentElement, {
theme,
appearance: missionAppearance ? "mission" : "default",
edges: flatEdges ? "flat" : "default",
accent,
material: {
panel: panelMaterial,
@@ -545,7 +570,7 @@ export function CatalogApp() {
},
});
document.documentElement.style.setProperty("--nodedc-canvas-soft", material.nestedHex);
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme, missionAppearance]);
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme, missionAppearance, flatEdges]);
useEffect(() => {
applyGlassMaterial(document.documentElement, glassMaterial);
@@ -1307,6 +1332,7 @@ export function CatalogApp() {
onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)}
/>
<ControlRow label="Фон"><ColorField value={toolbarBg} onChange={setToolbarBg} /></ControlRow>
<Description>HEX можно очистить и набрать заново; Enter применяет, Escape возвращает текущий цвет.</Description>
<ControlRow label="Border"><ColorField value={toolbarBorder} onChange={setToolbarBorder} /></ControlRow>
<ControlRow label="Outline"><ColorField value={toolbarOutline} onChange={setToolbarOutline} /></ControlRow>
<RangeControl label="Минимальный размер" value={toolbarMinSize} min={18} max={42} formatValue={(value) => `${value}px`} onChange={(value) => {
@@ -1330,6 +1356,7 @@ export function CatalogApp() {
<>
<ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow>
<RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} />
<RangeControl variant="rail" label="Тонкая горизонтальная шкала" value={brightness} min={0} max={100} formatValue={v=>`${v}%`} onChange={setBrightness}/>
<div style={{ height: 180 }} title="Тонкая шкала: две границы двигаются независимо; без центрального текста"><RangeControl orientation="vertical" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
<div style={{ height: 180, display: 'flex', justifyContent: 'flex-end' }} title="Шкала справа: границы слева; фокус подчёркивает выбранную границу"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} exactValueBounds={{ min: 0 }} formatValue={(value) => `${value}%`} onChange={setGlowDistance} />
@@ -1378,7 +1405,8 @@ export function CatalogApp() {
case "controls":
return (
<div className="catalog-grid">
<Preview title="Navigation cube" note="faces / edges / corners"><NavigationCube edgeOpacity={cubeEdgeOpacity} size={cubeSize} quaternion={[.28,-.36,.12,.88]} onSelect={setCubeDirection}/><RangeControl label="Размер 3D-куба" value={cubeSize} min={48} max={160} step={1} onChange={setCubeSize} formatValue={v=>`${v} px`}/><RangeControl label="Прозрачность линий куба" value={1-cubeEdgeOpacity} min={0} max={1} step={.05} onChange={v=>setCubeEdgeOpacity(1-v)} formatValue={v=>`${Math.round(v*100)}%`}/><p>{cubeDirection.join(" · ")}</p></Preview>
<Preview title="Mission Core" note="canonical foundation / nested fields / portal" className="catalog-preview--wide"><MissionThemeExample/></Preview>
<Preview title="Navigation cube" note="faces / edges / corners"><NavigationCube faceOpacity={.65} edgeOpacity={cubeEdgeOpacity} size={cubeSize} quaternion={[.28,-.36,.12,.88]} onSelect={setCubeDirection}/><RangeControl label="Размер 3D-куба" value={cubeSize} min={48} max={160} step={1} onChange={setCubeSize} formatValue={v=>`${v} px`}/><RangeControl label="Прозрачность линий куба" value={1-cubeEdgeOpacity} min={0} max={1} step={.05} onChange={v=>setCubeEdgeOpacity(1-v)} formatValue={v=>`${Math.round(v*100)}%`}/><p>{cubeDirection.join(" · ")}</p></Preview>
<Preview title="Selection" note="integrated / split / inline">
<div className="catalog-form">
<FieldFrame label="Hub / integrated select" labelPlacement="below">
@@ -1394,7 +1422,7 @@ export function CatalogApp() {
</FieldFrame>
<FieldFrame label="Engine / split select">
<Select
variant="split"
variant="split" shape="pill"
label="Тип связи"
value={connectionType}
options={[
@@ -1452,6 +1480,13 @@ export function CatalogApp() {
<KeyButton label="Клавиша S недоступна" disabled>S</KeyButton>
</div>
</Preview>
<Preview title="Подсказки" note="hover / focus / touch" className="catalog-preview--compact">
<div className="catalog-inline catalog-inline--wrap">
<Tooltip content="Короткое пояснение. Escape закрывает только подсказку."><Button>Подробнее</Button></Tooltip>
<Tooltip focusable label="Текущий уровень" content="Доступно мышью, клавиатурой и касанием."><StatusBadge tone="neutral">Нормальный уровень</StatusBadge></Tooltip>
<Tooltip disabled content="Эта подсказка отключена"><Button disabled>Недоступно</Button></Tooltip>
</div>
</Preview>
<Preview title="Активность" note="default / compact" className="catalog-preview--compact">
<div className="catalog-inline catalog-inline--wrap">
<span className="catalog-inline">
@@ -1488,6 +1523,15 @@ export function CatalogApp() {
<SegmentedControl selectionMode="multiple" label="Слои сцены" value={previewLayers} onChange={setPreviewLayers}
items={[{value:"source",label:"Источник"},{value:"geometry",label:"Геометрия"},{value:"unavailable",label:"Недоступно",disabled:true}]} />
</Preview>
<Preview title="Уровень ресурса" note="измерение / последние данные / неизвестно">
<LevelButton label="Заряд аккумулятора" value={.82} levelTone="success" onClick={()=>setProjectName("Аккумулятор · 82%")}/>
<LevelButton label="Заряд аккумулятора" value={.17} levelTone="warning" freshness="stale"/>
<LevelButton label="Заряд аккумулятора" value={null} freshness="unknown" disabled/>
<LevelButton label="Белая заливка" value={.82} fillColor="#ffffff"/>
<LevelButton label="Чёрная заливка" value={.82} fillColor="#000000"/>
<LevelButton label="Минимальный индикатор" value={1} valueText="100%" fillColor="#ffffff" geometry={{width:32,height:12,radius:4}}/>
<LevelButton label="Широкий индикатор" value={.82} geometry={{width:160,height:24,radius:8}}/>
</Preview>
<Preview title="Линейный прогресс" note="измеренный / неизвестный / завершённый">
<ProgressBar label="Подготовка" value={0.6} valueText="Три этапа из пяти" />
<ProgressBar label="Получение сведений" />
@@ -1499,9 +1543,13 @@ export function CatalogApp() {
<li><ResourceRow icon={<Icon name="camera" />} title="Подключённая камера" description="Индикатор перед названием" statusPlacement="leading" status={<StatusBadge variant="indicator" tone="success" aria-label="Подключено" title="Подключено" />} actions={<IconButton label="Просмотреть камеру" onClick={() => setProjectName("Подключённая камера")}><Icon name="eye" /></IconButton>} /></li>
<li><ResourceRow icon={<Icon name="camera" />} title="Подготовка камеры" metadata="Проверка потоков" progress={{label:"Подготовка камеры",value:0.8}} aria-busy="true" actions={<IconButton label="Просмотр недоступен" disabled><Icon name="eye" /></IconButton>} /></li>
</ResourceList>
<Button onClick={()=>setTreeDemoOpen(true)}>Дерево объектов · изменяемый размер</Button>
<DragDropRoot onDragEnd={()=>{}}><DraggableItem id="whole-material-tile">{({activator})=><Button {...activator.attributes} {...activator.listeners}>Перенос за всю плитку</Button>}</DraggableItem></DragDropRoot>
<SettingsCard title="Устройства не обнаружены" description="Подключите устройство, чтобы оно появилось в списке." />
<SettingsCard align="center" role="status" title="Настройки применены" description="Проверьте подключение устройства." />
</Preview>
<Preview title="Операционная типографика" note="единый размер во всех состояниях"><OperationalTypographyDemo /></Preview>
<Preview title="Размер DOM-окна" note="геометрия с сохранением в приложении"><ModalSizeExample /></Preview>
<Preview title="Главная и окружение" note="единые компоненты · сохранение в памяти каталога">
<EnvironmentCatalogDemo />
</Preview>
@@ -1569,7 +1617,7 @@ export function CatalogApp() {
</div>
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
</Preview>
<Preview title="Split pane" note="pointer / keyboard / controlled" className="catalog-preview--wide catalog-split-pane-preview">
<Preview title="Split pane" note="pointer resize: invisible / keyboard focus: visible" className="catalog-preview--wide catalog-split-pane-preview">
<Switch label="Скрыть линию разделителя" checked={splitPaneInvisible} onChange={setSplitPaneInvisible} />
<div className="catalog-split-pane-demo">
<SplitPane
@@ -1585,12 +1633,13 @@ export function CatalogApp() {
</div>
<p className="catalog-preview__explanation">Граница изменяет контролируемую долю панелей; клавиши и pointer используют одни ограничения, а resize контейнера не сбрасывает выбранное соотношение.</p>
</Preview>
<Preview title="Dock layout" note="center swap / four edges / keyboard" className="catalog-preview--wide">
<Preview title="Dock layout" note="center swap / panel edges / workspace edges / keyboard" className="catalog-preview--wide">
<div style={{height:420}}><DockLayout tree={dockDemoTree} onTreeChange={setDockDemoTree}
panels={[{id:'camera',label:'Камера'},{id:'depth',label:'Глубина'},{id:'map',label:'Карта'},{id:'scene',label:'Сцена',minimumSize:{width:320,height:280}}]}
renderPanel={id=><GlassSurface tone="soft" radius="panel" style={{height:'100%'}}><DockHandle id={id} label={id}/><strong>{id}</strong></GlassSurface>}/></div>
<p>Центр — обмен, край — разделение. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой.</p>
<p>Центр окна — обмен, край окна — разделение, внешний край всей области — на всю сторону. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой; Shift + стрелки выбирают край всей области.</p>
</Preview>
<Preview title="Scene editor docking" note="fixed primary / detachable tools / return" className="catalog-preview--wide"><EditorDockExample/></Preview>
<Preview title="Application side panel" note="end / push / controlled" className="catalog-preview--wide catalog-side-panel-preview">
<div className="catalog-side-panel-demo">
{sidePanelDemoOpen ? (
@@ -1696,16 +1745,22 @@ export function CatalogApp() {
case "glass":
return (
<div className="catalog-glass-lab">
<section className="catalog-glass-stage">
<ResizableViewport className="catalog-glass-stage" resizeIndicator={false} height={sceneDemoHeight} minHeight={360} maxHeight={900} onHeightChange={setSceneDemoHeight}>
<video key={stageMediaSrc} autoPlay muted loop playsInline aria-hidden="true"><source src={stageMediaSrc} type="video/mp4" /></video>
<div className="catalog-glass-stage__shade" />
<GlassMaterialSurface className="catalog-glass-stage__sample">
<div className="catalog-viewport-actions nodedc-viewport-controls">
<IconButton label="Приблизить пример" onClick={()=>setSceneDemoHeight(value=>Math.min(900,value+40))}><Icon name="plus"/></IconButton>
<IconButton label="Отдалить пример" onClick={()=>setSceneDemoHeight(value=>Math.max(360,value-40))}><Icon name="minus"/></IconButton>
<IconButton label="Вернуть размер примера" onClick={()=>setSceneDemoHeight(480)}><Icon name="select"/></IconButton>
</div>
<GlassMaterialSurface context="scene" radius="panel" material={glassMaterial} radiusPx={24} className="catalog-glass-stage__sample">
<span>CANONICAL GLASS</span>
<h2>Модальное окно и Inspector</h2>
<h2>Прозрачная плашка над сценой</h2>
<SceneAnnotation aria-label="Ячейка 01 · 4,15 В"><span>01</span><strong>4,15 В</strong></SceneAnnotation>
<p>Фон остаётся различимым, но текст и контролы сохраняют контраст. Этот материал не применяется к обычным панелям приложения.</p>
<div className="catalog-inline"><TextField label="Пример поля" name="organization" autoComplete="organization" defaultValue="NODE.DC" description="Автозаполнение сохраняет материал поля и клавиатурный фокус текущей темы." /><Button variant="primary" shape="pill">Применить</Button></div>
</GlassMaterialSurface>
</section>
</ResizableViewport>
<SettingsCard eyebrow="ENGINE / GLASS V4" title="Параметры материала" description="Общий token-контракт ui-core; изменения сразу видны на preview, модалках и Inspector.">
<div className="catalog-glass-controls">
<ControlRow label="Цвет тонировки"><ColorField value={glassMaterial.tintHex} onChange={(tintHex) => setGlassMaterial((current) => ({ ...current, tintHex }))} /></ControlRow>
@@ -1760,7 +1815,7 @@ export function CatalogApp() {
<p className="catalog-preview__explanation">Destructive-цвет появляется только у подтверждения.</p>
<Button variant="danger" shape="pill" icon={<Icon name="trash" />} onClick={() => setConfirmOpen(true)}>Проверить удаление</Button>
</Preview>
<Preview title="Настройки модуля" note="адаптивное меню и форма" className="catalog-modal-preview"><Switch label="Визуальный профиль Mission Core" checked={missionAppearance} onChange={setMissionAppearance} />
<Preview title="Настройки модуля" note="адаптивное меню и форма" className="catalog-modal-preview"><Switch label="Без декоративных обводок" checked={flatEdges} onChange={setFlatEdges} /><Switch label="Визуальный профиль Mission Core" checked={missionAppearance} onChange={setMissionAppearance} />
<Button icon={<Icon name="settings" />} onClick={() => setFeatureSettingsDemoOpen(true)}>Открыть настройки модуля</Button>
</Preview>
<Preview title="Workflow sharing" note="ENGINE / access" className="catalog-modal-preview">
@@ -1918,7 +1973,7 @@ export function CatalogApp() {
title="Состав страниц"
description="Перетащите готовую страницу справа в конфигурацию приложения. Свободного canvas и произвольных компонентов нет."
>
<DragDropRoot onDragEnd={({ activeData, activeId, activeRect, overData, overId, overRect }) => {
<DragDropRoot renderOverlay={({data})=><GlassSurface padding="sm"><span>{data?.type==='page-template'?getPageTemplate(String(data.templateId))?.title:'Страница'}</span></GlassSurface>} 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
@@ -2132,10 +2187,11 @@ export function CatalogApp() {
/>
</>
}
// The shared profile owns its responsive label; consumers do not size it.
right={
<HeaderProfile>
<IconButton label="Уведомления"><Icon name="inbox" size={20} strokeWidth={1.7} /></IconButton>
<UserProfileMenu
triggerLabel="Профиль"
triggerIcon="inbox"
displayName={sessionProfile?.user?.displayName || "Профиль"}
subtitle={sessionProfile?.user?.email || "NODE.DC Foundry"}
avatarUrl={sessionProfile?.user?.avatarUrl || undefined}
@@ -2145,7 +2201,6 @@ export function CatalogApp() {
{ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" },
]}
/>
</HeaderProfile>
}
/>
}
@@ -2308,7 +2363,7 @@ export function CatalogApp() {
maxSize={toolbarMaxSize}
lensCount={toolbarLensCount}
autoHide={toolbarAutoHide}
hideDelay={toolbarHideDelay} gap={toolbarGap}
hideDelay={toolbarHideDelay} gap={toolbarGap} menuWidth={320}
items={[{id:"hold",label:toolbarAutoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!toolbarAutoHide,onSelect:()=>setToolbarAutoHide(v=>!v)}, ...(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
id,
label: item.title,
@@ -2320,21 +2375,27 @@ export function CatalogApp() {
/>
) : null}
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
<Tree defaultExpandedDepth={2} renderActions={node=><Dropdown width={320} trigger={({setTriggerRef,show,open})=><IconButton ref={setTriggerRef} label={`Информация: ${node.label}`} aria-expanded={open} onMouseEnter={show} onClick={show}><Icon name="info-plain" size={14}/></IconButton>}><Description>{node.label}</Description></Dropdown>} label="Пример дерева объектов: стрелка раскрывает, глазик меняет видимость без прокрутки" selected={treeSelected} selectedIds={treeSelectedIds} onSelect={(id,gesture)=>{setTreeSelected(id);setTreeSelectedIds(old=>gesture.shiftKey?gesture.rangeIds:gesture.metaKey?(old.includes(id)?old.filter(key=>key!==id):[...old,id]):gesture.ctrlKey?[...new Set([...old,id])]:[id]);}} onVisibilityChange={(_,visible)=>setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/>
</Window>
<Window
open={inspectorOpen}
title="Настройки окружения"
subtitle="ENGINE / draggable inspector"
resizable
placement="end"
draggable
onClose={() => setInspectorOpen(false)}
>
<Inspector sections={environmentSections} defaultOpen={["application-material"]} />
<Inspector header={<Description>Поля и секции разделены единым шагом 12 px.</Description>} footer={<Button variant="primary" tone="neutral" onClick={()=>setInspectorOpen(false)}>Готово</Button>} sections={environmentSections} defaultOpen={["application-material"]} />
</Window>
<Window
open={createModuleOpen}
title="Создать модуль"
subtitle="APPLICATION / DRAFT"
headerActionsPlacement="before-close"
headerActions={<IconButton label="Очистить форму" onClick={() => {setCreateModuleName("");setCreateModuleSlug("");}}><Icon name="trash"/></IconButton>}
subtitle="Свободное окно · шапка: перемещение · края: размер"
size="sm"
onClose={() => setCreateModuleOpen(false)}
footer={
@@ -2435,7 +2496,7 @@ export function CatalogApp() {
headerActions={<IconButton label="Обновить настройки примера" onClick={() => setProjectName('Обновлено')}><Icon name="refresh" /></IconButton>}
onClose={() => setFeatureSettingsDemoOpen(false)}>
{featureSettingsDemoSection === 'general' ? <SettingsCard title="Основное"><TextField label="Название модуля" value={projectName} onChange={(event) => setProjectName(event.target.value)} /></SettingsCard>
: <SettingsCard title="Сведения" description="Общее пояснение к данным."><Description>Текст в теле использует тот же стиль.</Description><ComparisonTable density="compact" label="Сравнение устройств" heading="Устройство" columns={Array.from({length:4},(_,i)=>({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/><LoadingRegion aggregate loading label="Загрузка сведений"><LoadingRegion loading label="Вложенный запрос A"/><LoadingRegion loading label="Вложенный запрос B"/></LoadingRegion></SettingsCard>}
: <SettingsCard title="Сведения" description="Общее пояснение к данным."><Description>Текст в теле использует тот же стиль.</Description><div><p>Пояснение прежнего потребителя без класса — тот же компактный стиль.</p></div><Description role="status">Ожидаем ответ устройства…</Description><ComparisonTable density="compact" label="Сравнение устройств" heading="Устройство" columns={Array.from({length:4},(_,i)=>({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/><LoadingRegion aggregate loading label="Загрузка сведений"><LoadingRegion loading label="Вложенный запрос A"/><LoadingRegion loading label="Вложенный запрос B"/></LoadingRegion></SettingsCard>}
</FeatureSettingsWindow>
<Window
+15
View File
@@ -0,0 +1,15 @@
import {useState} from 'react';
import {Button,Window,Description,ColorField,ControlRow,Inspector,EditorDockLayout,EditorWorkspace,type EditorDockState} from '@nodedc/ui-react';
export function EditorDockExample({inWindow=false}:{inWindow?:boolean}){
const [color,setColor]=useState('#292929');
const [modal,setModal]=useState(false),[purpose,setPurpose]=useState<'edit'|'view'>('edit');
const [editing,setEditing]=useState(false),[open,setOpen]=useState({objects:true,materials:true});
const [layout,setLayout]=useState<EditorDockState>({tree:{axis:'y',ratio:70,first:{axis:'x',ratio:25,first:{id:'objects'},second:{id:'viewport'}},second:{id:'materials'}},floating:{}});
return <>{!inWindow&&<><Button onClick={()=>setModal(true)}>Сцена в модальном окне</Button><Window open={modal} title="Просмотр сцены" onClose={()=>setModal(false)}><EditorDockExample inWindow/></Window></>}<Button onClick={()=>{setPurpose('edit');setOpen({objects:true,materials:true});setEditing(true);}}>Открыть редактор сцены</Button><Button onClick={()=>{setPurpose('view');setEditing(true);}}>Отдельное окно просмотра</Button><div style={{height:480}}>
<EditorWorkspace editing={editing} purpose={purpose} title={purpose==='view'?'Просмотр сцены':'Редактор сцены'} subtitle="Общая оконная система" onBack={()=>setEditing(false)} headerActions={purpose==='view'?<Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button>:undefined}>
<EditorDockLayout value={layout} onChange={setLayout} enabled={editing} primary={<div style={{display:'grid',height:'100%',placeContent:'center'}}><Description>Закреплённая сцена · откреплённые инструменты используют scene Glass V4</Description><Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button></div>}
tools={[{id:'objects',title:'Объекты',label:'Объекты',open:open.objects,onClose:()=>setOpen(v=>({...v,objects:false})),content:<Description>Сцена → Модель → Детали</Description>},
{id:'materials',title:'Материалы',label:'Материалы',minimumSize:{width:380,height:280},footer:<Button width="full" onClick={()=>setColor('#292929')}>Сбросить настройки</Button>,open:open.materials,onClose:()=>setOpen(v=>({...v,materials:false})),content:<Inspector sections={[{id:"color",label:"Цвет без обводки и пипетка",content:<ControlRow label="Цвет"><ColorField label="Цвет материала" value={color} onChange={setColor}/></ControlRow>}]} defaultOpen={["color"]} header={<Description>Минимум 380 × 280. Пипетка берёт цвет с экрана после нажатия; Escape отменяет выбор. Нижняя кнопка не прокручивается.</Description>}/>}]}/>
</EditorWorkspace>
</div></>;
}
+2 -1
View File
@@ -15,13 +15,14 @@ export function EnvironmentCatalogDemo() {
useEffect(() => () => urls.current.forEach(url => URL.revokeObjectURL(url)), []);
return <>
<div className="catalog-environment-actions">
<UserProfileMenu displayName="DC" subtitle="Каталог компонентов" triggerLabel={null}
<UserProfileMenu variant="default" displayName="DC" subtitle="Каталог компонентов" triggerLabel={null}
actions={[{ id: "settings", label: "Настройки", icon: "settings", onSelect: () => setOpen(true) }]} />
<Button variant="primary" tone="neutral" onClick={() => setOpen(true)}>Настройки окружения</Button>
<Button variant="primary" tone="neutral" disabled>Неактивное действие</Button>
</div>
<div className="catalog-environment-stage"><LandingStage page={settings.pages.home} /></div>
<EnvironmentSettingsWindow open={open} onClose={() => setOpen(false)} productName="Продукт"
additionalSections={[{ id: "storage", label: "Хранилище", icon: "database", content: <p>Настройки хранения продукта используют общий каркас окна.</p> }]}
surfaces={[{ id: "home", home: true, description: "Главная страница продукта", actions: [] }]}
settings={settings} state="ready" error={null}
onSave={async draft => { const next = { ...draft, revision: draft.revision + 1 }; setSettings(next); return next; }}
+28
View File
@@ -0,0 +1,28 @@
import {useState} from 'react';
import {Button, Description, FeatureSettingsWindow, GlassSurface, Select, SettingsCard, StatusBadge, Switch, TextAreaField, TextField} from '@nodedc/ui-react';
/** Living acceptance fixture. All materials and control states come from the library. */
export function MissionThemeExample() {
const [open,setOpen]=useState(false);
const [name,setName]=useState('Mission Core');
const [enabled,setEnabled]=useState(true);
const [mode,setMode]=useState('review');
const fields=<div className="catalog-theme-fields">
<TextField label="Название" value={name} onChange={event=>setName(event.target.value)}/>
<TextAreaField label="Описание" defaultValue="Панель, группа и поле сохраняют собственные поверхности."/>
<Select label="Режим" value={mode} options={[{value:'review',label:'Просмотр'},{value:'edit',label:'Редактирование'}]} onChange={setMode}/>
<TextField label="Недоступное поле" value="Только чтение" disabled/>
</div>;
return <SettingsCard title="Фундамент Mission Core" description="Единая тёмная тема: поверхности, поля, действия и окна." actions={<Switch label="Включено" checked={enabled} onChange={setEnabled}/>}>
{fields}
<GlassSurface tone="group" padding="md" materialRim={false}>
<TextField label="Элемент коллекции" defaultValue="Дополнительная ссылка"/>
</GlassSurface>
<StatusBadge tone="success">Сохранено</StatusBadge>
<Button variant="primary" onClick={()=>setOpen(true)}>Открыть настройки</Button>
<Description>Поля лежат прямо в SettingsCard; самостоятельный элемент коллекции использует тот же серый материал через GlassSurface tone="group".</Description>
<FeatureSettingsWindow open={open} onClose={()=>setOpen(false)} title="Настройки темы" identity={{title:'Профиль',subtitle:'Mission Core',avatarLabel:'DC'}} sections={[{id:'appearance',label:'Оформление',group:'Общие'}]} activeSection="appearance" onSectionChange={()=>{}}>
<SettingsCard title="Форма в окне" description="Тот же материал полей в портальном окне.">{fields}</SettingsCard>
</FeatureSettingsWindow>
</SettingsCard>;
}
+25
View File
@@ -0,0 +1,25 @@
import { createPortal } from 'react-dom';
import { useEffect, useRef } from 'react';
import { createModalController, createModalSizeController, renderPathBar } from '@nodedc/ui-dom';
import { renderToStaticMarkup } from 'react-dom/server';
import '@nodedc/ui-dom/styles.css';
import { Button, Description, Icon } from '@nodedc/ui-react';
export function ModalSizeExample() {
const overlay = useRef<HTMLDivElement>(null), dialog = useRef<HTMLDivElement>(null);
const modal = useRef<ReturnType<typeof createModalController> | null>(null);
const path = useRef<HTMLDivElement>(null);
const saved = useRef({ width: 800, height: 500 });
useEffect(() => {
renderPathBar(path.current!, [{label:'Файлы',path:'',kind:'folder'},{label:'Изображения',path:'images',kind:'folder'},{label:'example.png',path:'images/example.png',kind:'file',current:true}], {onNavigate: () => {}, icon: kind => { const span=document.createElement('span'); span.innerHTML=renderToStaticMarkup(<Icon name={kind}/>); return span.firstElementChild!; }});
const size = createModalSizeController({ dialog: dialog.current!, initialSize: saved.current, onSizeCommit: value => { saved.current = value; } });
modal.current = createModalController({ overlay: overlay.current!, dialog: dialog.current!, onOpenChange: open => { if (open) size.refresh(); } });
return () => { modal.current?.destroy(); size.destroy(); };
}, []);
return <><Button onClick={() => modal.current?.open()}>Окно с сохранением размера</Button>
{createPortal(<div ref={overlay} hidden><div ref={dialog} className="nodedc-glass" aria-labelledby="modal-size-example-title">
<header className="nodedc-window__head"><h2 id="modal-size-example-title" className="nodedc-window__title">Размер модального окна</h2></header>
<div className="nodedc-window__body"><Description>Перетаскивание за края и углы. Для клавиатуры: фокус на шапке, Shift + стрелки. Повторное открытие сохраняет размер; уменьшение экрана не меняет предпочтение.</Description><div ref={path}/></div>
<footer className="nodedc-window__footer"><Button onClick={() => modal.current?.close()}>Закрыть</Button></footer>
</div></div>, document.body)}</>;
}
@@ -0,0 +1,20 @@
import { useState } from "react";
import { Button, Description, SettingsCard, Window, WindowFooterActions } from "@nodedc/ui-react";
/** Catalog-only sample: verify host-size independence and centered/floating status copy. */
export function OperationalTypographyDemo() {
const [open, setOpen] = useState(false);
return <>
<SettingsCard title="Компактная типографика" description="Значения и секции — 13 px, пояснения — 12 px, заголовок окна — 18 px.">
<h3>Подключение</h3>
<div>192.168.1.1</div>
<Description>Нет сведений о подключении.</Description>
<Description role="alert">Не удалось получить ответ устройства.</Description>
<Button onClick={() => setOpen(true)}>Проверить типографику окна</Button>
</SettingsCard>
<Window open={open} size="sm" title="Состояние подключения" onClose={() => setOpen(false)}
footer={<WindowFooterActions><Button onClick={() => setOpen(false)}>Понятно</Button></WindowFooterActions>}>
<Description role="status">Связь прервалась после приёма команды. Проверьте, выключился ли борт.</Description>
</Window>
</>;
}
+3
View File
@@ -2304,3 +2304,6 @@ textarea {
grid-template-columns: 1fr;
}
}
.catalog-theme-fields { display: grid; gap: var(--nodedc-space-4); }
.catalog-viewport-actions {position:absolute;top:var(--nodedc-space-3);right:var(--nodedc-space-3);display:flex;gap:var(--nodedc-space-2);padding:var(--nodedc-space-2);}
+76 -3
View File
@@ -2,7 +2,7 @@
## Текущее состояние
Первый этап не меняет существующие приложения. Репозиторий фиксирует baseline и создаёт пакетный контракт. Это позволяет продолжать текущую разработку без одномоментной переделки Engine, Ops, BIM, CMS, SEO и Launcher.
Пакетный контракт действует: CMS использует общие tokens, ui-core, ui-dom и ui-react, включая принятую тему Mission Core; Device Core использует общую шапку. Точные consumer pins и границы приведены ниже. Остальные приложения переводятся по отдельным проверенным этапам; наличие общего компонента не означает автоматическую миграцию всех consumer.
## Рекомендуемый порядок
@@ -27,7 +27,7 @@
### 3. CMS и SEO
Используют те же компоненты и механику окон. CMS подключает DOM-layer, SEO — React-layer. Первым общим admin pattern подключается `MediaSourceField`/`createMediaSourceController`; storage API остаётся в приложении. Цветовые различия оформляются theme overrides.
Используют те же компоненты и механику окон. CMS уже подключает DOM-layer и контролируемые React islands; целевой слой SEO — React. Общий admin pattern `MediaSourceField`/`createMediaSourceController`; storage API остаётся в приложении. Цветовые сочетания определяются библиотечным theme preset, без локальных копий палитры.
### 4. Engine
@@ -62,7 +62,8 @@
| --- | --- | --- | --- |
| Launcher/Hub | React/local shared | React | header, button, dropdown, window |
| SEO | React/local overrides | React | theme, window, field, select |
| CMS | Vanilla DOM | DOM | theme, header, modal, select |
| CMS | Пакеты + тонкий DOM/React adapter | Подключено, domain UI остаётся в CMS | Mission theme, shell/header, forms, modal, controls |
| Device Core | Общий UserProfileMenu, pin 06cb8ad | Шапка подключена, формы без изменений | responsive profile, menu, avatar |
| Engine | React/mixed generations | React | new inspector and environment settings only |
| Ops | React/Plane packages | React | floating behavior and modal primitives |
| BIM Viewer | Vanilla JS | DOM | tokens, glass select, settings surfaces |
@@ -87,3 +88,75 @@ The component contract and catalog example are in `ENVIRONMENT_SETTINGS.md`.
## Mission Core loading (2026-09-08)
Core и Node используют общий sensor-ui/X4 frontend с Button.loading, IconButton.loading и LoadingRegion из Design Guideline. SDK/network semantics остаются в consumer, геометрия ожидания принадлежит DG. Этот локальный кандидат передаётся через source manifest с hashes вместе с Node installer; public npm release не публиковался, исходники компонентов в приложение не копируются.
## DC CMS package adoption (2026-11-05)
DC_CMS now consumes the immutable npm distributions of tokens, ui-core, ui-dom
and ui-react, pinned to a canonical source SHA plus package hashes in the
consumer's `ui/design-system.lock.json`. Its build renders AppHeader,
ApplicationShell, AdminNavigationPanel, ApplicationPanel and control templates
from exports. Select, Switch, RangeControl, ProgressBar, StatusBadge and Dropdown
run directly as controlled React islands. Core CSS and tokens are bundled once.
The thin compatibility adapter is `DC_CMS/ui/src/design-system.mjs`: it retains
native CMS form/model bindings and listeners, adopts generated field/card/button
anatomy, uses ui-dom modal/workspace controllers and connects MediaSourceField's
DOM contract to the existing CMS file manager. Folder columns, editable block
collections and knowledge content remain domain UI. No package source is copied
or maintained as a local component fork. Remove this adapter as those domain
renderers move to direct component composition. CMS CI rejects stale generated
assets; the existing Git-to-canonical-runner deployment foundation is unchanged.
CMS visual follow-up, 2026-11-05: flat theme edges, neutral white default accent,
UserProfileMenu with a session avatar and inbox glyph, FeatureSettingsWindow,
ColorField, pill-shaped split Select, and the canonical six-dot DragHandle.
UI preferences belong to authenticated per-user server metadata; site content and deployment
credentials stay in the existing CMS model. Immutable npm snapshots retain
package semver and are identified by source commit plus archive SHA-256.
CMS uses `UserProfileMenu`: profile label, menu icon, avatar.
The menu opens settings; the application does not add a fourth action.
Device Core and CMS share the complete `UserProfileMenu` header, not local copies.
The reference composition is the existing rounded profile group in Launcher/Hub
and Engine (`EnginePlatformHeader.tsx` / `TopBar.tsx`); its reusable geometry is
already in AppHeader, HeaderProfileButton, IconButton and HeaderAvatar. The owner
confirmed the order profile → inbox → avatar and settings inside the middle
icon's menu on 2026-11-05. No application CSS overrides are needed.
Device Core retains session identity, profile URL, permissions and logout actions.
### 2026-11-05 — Mission dark foundation → CMS
Owner selected the running local Mission Core as the canonical dark reference.
Source audit: b0332fa, styles/base.css and main.tsx; uncommitted simulation changes excluded.
The complete Mission/flat preset now lives in tokens + ui-core, exported for React and DOM consumers.
CMS consumes the immutable packages and retains only domain layout/event adapters.
Nested forms use SettingsCard with a transparent layout grid and opaque fields; collection entries use GlassSurface group. The soft canvas is not a form-group material; no CMS palette.
Mission Core itself remains on its existing local package state; its duplicated base overrides are recorded migration debt, not silently updated.
### CMS form composition correction — 2026-11-05
Mission Core environment settings were verified in the running app: SettingsCard
uses the neutral group material, its form grid is transparent, fields are opaque.
CMS removes the extra field-grid surface and the card around the full list of
content cards. Collection entries and native JSON disclosures adopt the shared
GlassSurface group material. No local palette, field colors or business logic
are introduced. The prior soft-canvas composition is superseded in THEMING and
the living catalog; soft itself remains available for recessed non-form areas.
## CMS: размеры модальных окон
CMS подключает `createModalSizeController` из immutable ui-dom package, без копии resize-кода. Тонкий адаптер связывает `media-library` с серверным пользовательским GUI JSON; оформление и размеры записываются через аутентифицированный API. Медиатека остаётся привязанной к сайту, геометрия — к пользователю.
## CMS: строка пути файлов
CMS подключает `renderPathBar` и его stylesheet из ui-dom, source `1326ec6`,
immutable archive `nodedc-ui-dom-0.7.0-modal.2.tgz`. Адаптер передаёт пути
выбранного сайта, стандартный Icon и callback перехода в папку. Общий компонент
владеет компактной строкой Finder, разделителями и нейтральными иконками.
Сетка файлов, поиск и фильтрация по нескольким типам остаются доменной логикой
CMS; переключатели используют общий IconButton. Проверены выбор глубокого
пути, переход в каталог, dark/light и узкое окно 390 px.
+128 -8
View File
@@ -4,17 +4,18 @@
## GlassSurface
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал с blur и rim используется только у floating-слоёв: modal `Window` и portal-dropdown/select.
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал используется у floating-слоёв и явно выбранных информационных плашек над 3D-сценой.
- `default` — обычная карточка/панель;
- `strong` — dropdown, modal и поверхность над сложным фоном;
- `soft` — вложенная или вторичная область.
- `soft` — утопленная вторичная область / canvas, не подложка формы;
- `group` — нейтральная группа как SettingsCard, для самостоятельного элемента коллекции.
`radius="pill"` задаёт каноническую капсульную геометрию через `--nodedc-radius-circle`. Она предназначена, в частности, для компактных вертикальных и горизонтальных реек из круглых действий: верхняя и нижняя части поверхности повторяют круг кнопок без прямых торцевых пролётов. Consumer не воспроизводит этот радиус локальным CSS.
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
@@ -57,6 +58,8 @@ FieldFrame объединяет label, control, hint и description. `labelPlace
## RangeControl
`RangeControl variant="rail"` — горизонтальный односторонний вариант тонкой шкалы среза: та же толщина `0.2 × --nodedc-control-height`, заполнение слева и текущее `formatValue` над шкалой. Общей подложки, стекла, рамки и тени нет; прозрачная область захвата не ниже 24 px. Native range сохраняет стрелки, Home/End, доступное имя и disabled; focus-visible подчёркивает значение. Точный ввод остаётся у обычного варианта `field`. Позиционирование в viewport и время показа задаёт приложение.
Вертикальная шкала занимает `0.2 × --nodedc-control-height` (9.2 px при 46 px), вдвое тоньше предыдущей. Прозрачная область захвата не уже 24 px.
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. `min/max` задают только рабочий диапазон перетаскивания; ручной ввод по умолчанию принимает любое конечное число и не меняет геометрию ползунка. Опциональный `exactValueBounds` независимо задаёт жёсткие границы ручного ввода: например, `{ min: 0 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком.
@@ -77,9 +80,9 @@ Engine/BIM-геометрия color field: круглый swatch и HEX-знач
## Dropdown
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. It does not change the material. Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. The same scope now supplies scene Glass V4 to control backgrounds (owner revision 2026-11-14). Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
For opaque controls directly above imagery, `nodedc-scene-controls` adds the same geometry plus a common opaque field surface. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
`nodedc-scene-controls` is the compatibility alias for the same geometry and scene Glass V4 material. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
Dropdown владеет floating-layer поведением:
@@ -132,6 +135,8 @@ Modeless Inspector закрывается независимо от резуль
Для modeless Inspector доступен `draggable`: окно двигается за header, не блокирует приложение и ограничивается viewport. Modal-окна не становятся draggable автоматически.
DOM: `createModalSizeController({dialog, initialSize, minimum, onSizeCommit})` дополняет `createModalController` изменением размера за восемь краёв/углов. Шапка получает клавиатурный resize через Shift + стрелки. `setSize` восстанавливает сохранённый размер, `refresh` подгоняет окно после открытия. Подгонка под экран и pointercancel не записывают новое предпочтение. Контроллер не меняет modal/focus contract; приложение хранит размер отдельно для текущего пользователя. Живой пример: «Размер DOM-окна».
## WorkspaceWindow
`WorkspaceWindow` — modeless-окно внутри рабочей сцены приложения. Оно рендерится непосредственно в переданном workspace, не использует portal и не может перекрыть шапку, навигацию или соседние панели за пределами этого workspace.
@@ -182,6 +187,8 @@ ConfirmationModal оборачивает Window и защищает async-confir
## SplitPane
Невидимый разделитель остаётся прозрачным при наведении и pointer-resize, даже после ввода в текстовом поле. Клавиатурное изменение размера сохраняет видимый focus cue.
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
@@ -228,7 +235,14 @@ Pill navigation для верхней панели и компактного п
## UserProfileMenu
Каноническая выпадашка профиля для правой группы `AppHeader`. Она использует
Каноническая правая группа `AppHeader`: «Профиль» → inbox → аватар.
`UserProfileMenu` владеет всей группой, включая `HeaderProfile`; приложение
передаёт только identity и действия. Настройки находятся в меню, отдельной
шестерёнки после аватара нет. Нельзя добавлять внешнюю обёртку или локальные
отступы. Все три элемента открывают меню; Escape возвращает фокус на вызвавшую кнопку.
На узком экране подпись скрывается по общей адаптивной механике; иконка и аватар остаются доступны.
Она использует
общий portal `Dropdown`, показывает identity cover с аватаром, именем и
подписью и принимает список application-owned действий.
@@ -270,6 +284,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 +344,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`, а не мгновенным действием крестика.
@@ -352,6 +370,11 @@ Sortable-строки ограничены вертикальной осью: г
Единая accordion-панель для settings и definition controls. Источник — только новый Environment Settings и NDC Agent Inspector.
Inspector принимает `header` для полей перед секциями и `footer` для действий после них.
Поля header и соседние секции разделяет `--nodedc-space-3` (12 px); footer
центрирует действия. Вложенные Inspector сохраняют тот же шаг. Это общий контракт,
а не локальные margin-правки потребителя. Вариант `panel` сохраняет компактные строки.
Inspector владеет:
- заголовками разделов;
@@ -419,13 +442,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 +466,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 +506,89 @@ 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
Visibility is independent of disclosure. Data/eye updates never re-open selected ancestors or scroll to an old selection. Disclosure uses its arrow (or ArrowLeft/ArrowRight), preserves the scroll position, and does not expand on row double-click. Only a new external selected ID/revealKey requests automatic reveal; asynchronous nodes can complete that pending request.
`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.
Размер поясняющего текста `Description` можно задать через
`--nodedc-description-font-size`; по умолчанию используется `--nodedc-font-size-sm`.
Window header actions default to before the move toggle. `headerActionsPlacement="before-close"` places supplied canonical IconButtons between move and close, preserving DOM/Tab order. Deletion confirmation remains application-owned content in the same mounted Window.
## Tooltip
Нейтральная подсказка с `content`, `children`, необязательными `label`, `focusable`, `disabled` и `placement`. Оборачивает триггер; `focusable` делает читаемую графику доступной клавиатуре, обычная кнопка сохраняет собственный фокус. Hover, focus и touch показывают один общий portal над окном; Escape закрывает подсказку, не родительское окно. Можно перевести курсор в подсказку. Позиция пересчитывается при scroll/resize, с общим clamp/flip. Не содержит действий: для меню используется Dropdown. Нет рамки, акцентных цветов или анимации при reduced motion.
Принят для запрошенных владельцем пояснений шкал сигнала,10.11.2026; приложение владеет диапазонами и текстом, общий компонент — формой и взаимодействием.
Window, WorkspaceWindow, ApplicationPanel and AdminPanel establish an independent compact md text base, including portals. Native semantic headings inside operational surfaces use md unless an explicit canonical title rule applies. Use Description for result/error/pending paragraphs. The living catalog includes a typography example with values, nested headings and a status dialog. See OPERATIONAL_TYPOGRAPHY.md and the exported build-time `@nodedc/ui-core/typography` contract.
## Flat surface profile and profile trigger
The shared theme supports `edges: "flat"` for borderless surfaces, including portal windows. Keyboard focus changes the fill and foreground instead of adding an outline. The living catalog exposes this alongside the Mission appearance switch. `UserProfileMenu` composes the canonical profile label, independent inbox/menu button and avatar. CMS puts settings inside that menu. No additional settings button or HeaderProfile wrapper is needed; spacing comes from existing HeaderProfileButton and IconButton geometry.
`Select variant="split" shape="pill"` aligns a compact workspace/site selector with adjacent round actions, preserving the shared dimensions and keyboard behavior.
## Mission Core theme foundation
`missionDarkTheme` и `missionLightTheme` — общий профиль из `@nodedc/ui-core` / `@nodedc/ui-dom`. `applyNodedcTheme` по умолчанию выбирает Mission и flat. Полный контракт цветов и композиции вложенных форм находится в [THEMING.md](THEMING.md). SettingsCard использует семантическую поверхность группы; поля расположены непосредственно в его body, как в Mission Core. GlassSurface tone="group" использует тот же материал для элементов коллекций. tone="soft" не применяется к формам. Ни CMS, ни другой потребитель не повторяет палитру локально. Living catalog содержит форму и её портальную версию.
## Viewport UI — правило владельца 14.11.2026
Все элементы интерфейса с подложкой внутри viewport используют общий Glass V4: карты, BIM, LAS/облака точек, 3DGS, PlayCanvas, камеры и replay. Поиск, отдельные кнопки прозрачного action rail, информационные плашки и меню относятся к этому правилу независимо от движка. Обычные панели вне viewport остаются matte. См. [контракт, применение и проверку](VIEWPORT_UI.md).
## PathBar (DOM)
`renderPathBar(target, items, {icon, onNavigate})` — компактная строка пути в стиле Finder: нейтральные иконки папок, текст и разделители `›`, без pill-кнопок. Подключается `@nodedc/ui-dom/styles.css`. Папки — клавиатурно доступные кнопки; конечный файл — текст с `aria-current`. Длинный путь прокручивается по горизонтали. Consumer передаёт пути и существующий Icon, хранение и навигация остаются в приложении. Живой пример: «Размер DOM-окна».
Toolbar `menuWidth` controls inspector menu width (default 220 px, bounded 180–600 px); Dropdown retains viewport clamping. Tree `renderActions(node)` supports per-item information menus without duplicating the outliner. `defaultExpandedDepth` limits initial expansion; selecting an item still reveals and scrolls to its ancestors. BIM uses canonical `ruler` (dimension line), `section` (model/plane), and `isolate` (temporary visibility) glyphs.
Open Dropdown surfaces observe content size changes and recompute their viewport bounds, including asynchronous property/volume results. Information triggers open on hover or explicit pointer/keyboard activation with `show`. Do not open on focus alone: Escape restores trigger focus and must keep the menu closed.
EditorDockLayout rounds only the external corners of its complete tiled area using the shared panel radius. A left stack has a rounded top-left on its first pane and bottom-left on its last; a bottom row has only the outer lower corners. Internal joins remain square. Corners recompute after docking, closing, resizing or restoring panels. Floating tools retain all four window corners. The primary viewport follows the same outside-edge rule.
Viewport-scoped Toolbar buttons use the same scene Glass V4 material as the top viewport controls, preserving pressed, disabled and keyboard states. Its rail remains transparent. Compact Tree information actions use `info-plain` at 14 px beside the existing eye.
Tree supports optional controlled `selectedIds` for multi-selection. Its selection callback includes keyboard modifiers and the Shift range across displayed rows only. Consumers own set semantics and geometry identities; existing single-selection callers remain unchanged. Pointer and keyboard selection share the same path. Visibility and information actions do not alter the selection. The living Tree example demonstrates Shift range, Ctrl add and Command toggle.
ColorField screen sampling (owner direction, 2026-11-14): the shared palette includes a Pipette action. In secure browsers supporting EyeDropper, click “Цвет с экрана”, then any screen pixel, including another application or desktop. Escape cancels without a change. Sampling never starts on pointer leave, never captures a screenshot, and is aborted when the control closes, disables or unmounts. Unsupported browsers expose “Системная палитра”; desktop sampling there depends on the native browser/OS picker. Palette/HEX remain usable regardless. This explicit fallback is the approved exception to the old no-native-dialog rule.
Floating EditorDockLayout tools honor minimumSize on restore, all eight resize edges and keyboard resize. If the available viewport is smaller, they fit that viewport; Inspector fields stack below a 330px content width instead of clipping. Tool footer is separate from the scrolling body; a Button width="full" is the canonical adaptive bottom action. The catalog's scene editor example demonstrates minimum size, a ColorField and fixed reset footer.
EditorDockLayout: every floating or actively detached tool uses context="scene" Glass V4 (shared scene tint/blur); docking removes that context and retains tiled surface/corner rules. Applies to hierarchy, layers, settings and any other editor tool. No application tint/blur overrides.
+13
View File
@@ -17,3 +17,16 @@ The application validates URLs/media bytes, persists uploads and document revisi
Mission Core passes all existing page definitions and its current operator-environment API. Mission Core Node passes home only and authenticated local presentation storage. Device control never depends on this document. The catalog EnvironmentCatalogDemo exercises the same exported components with an explicitly in-memory save/upload adapter; it is not a persistence service.
Validate the source migration, TypeScript builds, playlist functions, neutral enabled/disabled DOM contract, dark/light and multiple accents, modal Escape, media order/timing and both consumer persistence adapters. Long-running or physical device acceptance remains application-owned.
## Product sections (2026-11-08)
`additionalSections` accepts `{ id, label, icon, group?, content, footer? }`.
Use unique IDs other than `environment`. Content and footer are product-owned;
the shared shell retains navigation, focus, dragging, Escape and geometry.
Environment drafts remain intact when switching sections. Each section owns its
loading/error/saving states. No product API is called by the shared library.
Mission Core uses this extension for the owner-requested Storage section.
The canonical `pin` icon is the Lucide Pin glyph. Pair it with IconButton and
`aria-pressed` for pinned state; use a busy/disabled state during preparation.
An absent local copy and an unpinned copy are separate states.
+3
View File
@@ -59,3 +59,6 @@
## Владение
У дизайн-системы должен быть явный code owner. Product team может предлагать компоненты, но общий API и theme contract проходят отдельное review, потому что изменение распространяется на все будущие приложения.
Typography is a build gate, not a recommendation. See `OPERATIONAL_TYPOGRAPHY.md`: operational values/sections 13 px, descriptions/status/error copy 12 px, canonical window/page titles 18 px. Browser defaults, new local sizes and inline font overrides fail validation. The frozen compact legacy list cannot be expanded for new UI; exceptions require an explicit owner decision.
+6
View File
@@ -49,3 +49,9 @@ hover, focus, disabled и pending принадлежат кнопке. `activity
Раскрытие строки вниз: `chevron-down` в закрытом состоянии, `chevron-up` в открытом; кнопка сообщает `aria-expanded` и `aria-controls`.
`rotate-clockwise` — поворот изображения по часовой стрелке. Применение: независимая ориентация объективов Insta360 в Центре наблюдения Mission Core, по запросу владельца 09.10.2026. Шаг задаёт приложение; подпись кнопки сообщает угол. Состояния и геометрия принадлежат каноническому `IconButton`.
`power` — штатное выключение компьютера. Запрошено владельцем Mission Core 04.11.2026 для шапки окна «Бортовой компьютер». Используется в стандартном `IconButton` с доступной подписью; недоступность и выполняемое действие блокируют кнопку. Нажатие открывает `ConfirmationModal`; сам glyph не запускает выключение. Живой каталог получает иконку из `registry/icons.json`.
BIM controls use `ruler` (dimension line with extension lines/arrows), `section` (model intersected by a plane), `isolate` (temporary visibility/glasses), `perspective`/`orthographic` (projection cubes), and `fit-view` (frame extents). `info-plain` is an unframed i for compact tree actions next to the visibility eye; use 14 px for both glyphs. They share the canonical stroke and accessible control behavior.
Semantic references: [Revit measurement](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-Model/files/GUID-65EA44EC-C777-4C97-8718-5783C3A80B0A.htm), [temporary hide/isolate](https://help.autodesk.com/cloudhelp/2014/ENU/Revit-LT/files/GUID-A5E51D5E-8E18-4834-8A2F-8B4E3E6379A1.htm), [section box](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-GetStarted/files/GUID-C9EA51CB-3214-4BD8-AD55-3BEB1CCD15B6.htm). Glyphs are original monochrome NODE.DC vectors; this does not claim copied Autodesk artwork or full Section Box functionality.
+28
View File
@@ -0,0 +1,28 @@
# LevelButton
Measured resource level inside the standard pill Button. Initial consumer: Mission
Core battery state in the observatory header. Width is 2.5 canonical controls;
height, focus, keyboard, disabled and hover grammar remain Button-owned.
`value` is a fraction in [0,1]; unknown/NaN has no fill and displays an em dash.
`valueText` supplies the visible value; `label` names the resource. `freshness`
is live, stale or unknown. Stale retains the reading, neutralises fill and adds
accessible last-reading text. No animation, no fabricated progress, no nested
interactive elements. `levelTone` uses semantic tokens, never a local palette.
Click opens domain details supplied by the consumer. The consumer decides which
physical resource is selected; it must not average unrelated batteries or treat
a stale number as fresh. Catalog includes normal, stale and unavailable states.
An explicit operator-selected `fillColor` (#RRGGBB) overrides semantic tint.
The measured fraction clips a solid fill and a second, aria-hidden copy of its
label. WCAG luminance chooses black/white text independently over the filled
part, while the unfilled part keeps the normal theme text. Unknown has no fill;
stale retains the chosen colour and its accessible stale label. Colour-range
configuration belongs to the domain profile, not the visual component.
`geometry={{width, height, radius}}` задаёт операторские размеры с минимумом
32 × 12 px. Ниже 64 × 24 текст и padding уменьшаются пропорционально
ограничивающему размеру; длинная подпись также учитывается. Оба слоя текста
наследуют одинаковые размеры. Без geometry сохраняется прежний размер Button.
Внешний отступ от соседних действий остаётся ответственностью композиции шапки.
+2
View File
@@ -11,3 +11,5 @@ Visible hit regions have native tooltips, hover, keyboard focus, Enter/Space act
Presentation props: `size` in CSS pixels (default 66), `face`, `text`, `edge`, `hover`, `hoverText`, `opacity`. Consumer preferences may persist these; omitted colors inherit theme tokens. Core exposes these under viewport settings → 3D-куб.
Face labels use the projected face-local right/up basis, including foreshortening and rotation; they never billboard towards the screen. `edgeOpacity` (0–1, default 1) independently controls structural grid/edge strokes without fading faces or labels.
`faceOpacity` (0–1, default 1) controls polygon fill only. It is independent of `edgeOpacity`, text and the legacy overall `opacity`; a transparent face remains a navigation target.
+42
View File
@@ -22,3 +22,45 @@ Checker, круг, pill или кнопку. Это знак результат
Лампочка состояния устройства отдельно использует StatusBadge indicator.
Explanatory paragraphs use `Description`, the same contract as `SettingsCard.description`: inherited font family, regular 400, `--nodedc-font-size-sm`, `--nodedc-text-muted`, line-height 1.4 and zero paragraph margins. Applications must not create feature-specific equivalents.
Защита компонента: обычный `p` без класса внутри тела `SettingsCard` получает
тот же стиль описания, включая вложенные группы. Это страховка для прежних
потребителей, а не замена `Description` в новом коде. Статусы ожидания и
пояснения вне карточки также используют `Description` с `role="status"`, если
нужно объявление для скринридера. Заголовки, значения полей и кнопки сохраняют
собственную типографику; глобальный стиль для всех `p` страницы не вводится.
## Обязательная проверка сборки — 10.11.2026
Операционный UI имеет собственный базовый `md` (13 px), в том числе портальные
`Window`, `WorkspaceWindow`, `ApplicationPanel` и `AdminPanel`. Размер body
внешнего приложения не является контрактом. Корневой размер `html` не меняется:
rem и пользовательское масштабирование остаются доступными. Семантические
h1–h6 внутри этих поверхностей по умолчанию используют md, а явные канонические
заголовки страницы/окна — title (18 px). Значения и заголовки секций — md;
пояснения, ошибки, ожидание и результат команды — `Description` / sm (12 px).
Правило исполняется модулем `@nodedc/ui-core/typography` и обязательным
`npm run test:typography` Design Guideline. Mission Core запускает
`check:typography` перед сборкой Control Station и Node UI, а также в полном
наборе unit-тестов. Проверяется исходный код всех экранов, общих пакетов и
frontend-плагинов, а не только последний изменённый компонент.
Проверка запрещает новые локальные размеры вместо токенов, lg/title для данных,
увеличивающие calc/clamp/em, font shorthand, inline fontSize и обычные p без
явного класса. Сохранившиеся компактные значения старого UI (не более 13 px)
зафиксированы по файлу, селектору и значению в `typography-policy.json`;
добавлять туда новый UI запрещено. При изменении такого правила его переводят
на токен, запись удаляют. Список не допускает крупных значений даже при ошибочном
добавлении. Исключения перечислены отдельно с причиной и точным выражением:
существующая обложка LandingStage, подписи в координатах SVG и управляемый
пользователем масштаб сцены. Они не разрешают увеличивать текст рабочих панелей.
Начальный размер значений батареи — 13 px; сохранённый пользователем масштаб
3D-сцены не перезаписывается.
Изменение шкалы токенов, списка ролей или исключений требует явного решения
владельца продукта и обновления живого каталога. Нельзя ослаблять проверку ради
одного экрана, закрывать проблему локальным font-size или менять масштаб html.
При приёмке проверяют computed font-size в обычном и плавающем окне, на узкой
ширине, а также ожидание, ошибку, пустое состояние и результат команды.
+3
View File
@@ -13,3 +13,6 @@ aria-valuenow отсутствует. `label` обязателен; `valueText`
ResourceRow.progress занимает свободное место между текстом и actions, скрывает
status, на узком экране переносится ниже текста. Готовность не вычисляется
компонентом. Каталог содержит завершённый, определённый и неизвестный прогресс.
Размер полосы задаётся опциональным `--nodedc-progress-height`; по умолчанию
используется `--nodedc-space-2`. Плотность не меняет поведение и ARIA-состояния.
+66 -62
View File
@@ -1,78 +1,82 @@
# Темы и цвет приложения
## Основное правило
## Один фундамент
NODE.DC-приложения отличаются цветовой схемой, а не набором заново нарисованных компонентов. Тема задаёт значения CSS custom properties. Компоненты сохраняют геометрию, состояния и поведение.
С 2026-11-05 основа тёмной темы — проверенный локальный Mission Core
(`b0332fa`, `apps/control-station/src/styles/base.css`, работающий интерфейс
`127.0.0.1:8000`). Цвета находятся только в `@nodedc/tokens/themes.css`,
геометрия и состояния — в `@nodedc/ui-core`, компоненты — в `@nodedc/ui-react`.
Приложение выбирает тему, а не повторяет цвета, селекторы или устройство компонентов.
## Что меняет тема
```ts
import {applyNodedcTheme, missionDarkTheme} from '@nodedc/ui-core';
applyNodedcTheme(document.documentElement, missionDarkTheme);
```
- canvas/background;
- основной и вторичный текст;
- accent и автоматически вычисляемый on-accent;
- цвет непрозрачных application surfaces;
- field/control surfaces;
- overlay;
- тени controls и modal material;
- semantic success/warning/danger tones при необходимости.
Те же exports доступны из `@nodedc/ui-dom`. `applyNodedcTheme(root)` по умолчанию
выбирает `dark / mission / flat`. `missionLightTheme` сохраняет общую геометрию
и даёт светлую тему. Установка на `document.documentElement` обязательна для
приложения с порталами: меню и модальные окна получают тот же профиль.
## Что тема не меняет
## Роли поверхностей
- высоту контролов;
- радиусы по классам компонентов;
- положение логотипа;
- механику окна и dropdown;
- DOM anatomy;
- keyboard behavior;
- расположение footer actions;
- API React/DOM компонентов.
| Роль | Тёмная тема | Компонент |
| --- | --- | --- |
| Фон приложения | `#050506` | ApplicationShell |
| Рабочая сцена | `#08090b` | доменный viewport, token `--nodedc-stage` |
| Панель | `#151517` | ApplicationPanel, AdminNavigationPanel |
| Группа | нейтральный слой `110 110 110 / .07` | SettingsCard |
| Элемент коллекции | нейтральный слой `110 110 110 / .07` | GlassSurface tone="group" |
| Утопленная вторичная область | `#0d0d0f` | GlassSurface tone="soft", вне форм |
| Поле | `#2a2a2c`, непрозрачное | TextField, TextAreaField, Select, MediaSourceField |
| Модальное окно | `15 15 17 / .97` | FeatureSettingsWindow, Window |
| Выпадающее меню | `15 15 17 / .98` | Dropdown, Select portal |
| Основное действие | `247 248 244 / .96`; тёмный текст | Button |
## Presets
ApplicationPanel → SettingsCard → поля — композиция, проверенная в работающих
настройках Mission Core. Сетка полей прозрачная, без отдельной подложки и отступов.
Самостоятельный элемент коллекции может использовать GlassSurface tone="group":
тот же нейтральный материал SettingsCard, а не почти чёрный canvas-soft.
Не добавлять карточку вокруг списка карточек или вокруг каждого поля; максимум
два уровня групп сохраняют отличие непрозрачного поля от подложки.
В baseline включены `dark` и `light`. Это не два отдельных продукта, а примеры одного контракта:
Исправление 2026-11-05: прежний пример с tone="soft" ошибочно переносил цвет
вторичного canvas в формы. Значение soft сохранено для его исходной роли;
приложения исправляют композицию, а не перекрашивают canvas локальным CSS.
- dark соответствует текущей основной семье Launcher/Hub/CMS;
- light воспроизводит SEO-поверхности: `#ececec` canvas, белые панели и поля, тёмный текст, чёрные primary actions и мягкую тень у белых secondary controls;
- конкретный продукт может поверх preset задать свой accent и surface variables.
Основной/вторичный/приглушённый/недоступный текст использует оттенок
`247 248 244` с непрозрачностью `.96 / .72 / .48 / .34`. Состояния hover,
active, focus, disabled задаёт библиотека; приложения не переопределяют их.
Hover поля использует собственный непрозрачный материал, а не полупрозрачную
заливку кнопки: поле не исчезает при наведении.
Декоративные рамки и контуры отсутствуют. Клавиатурный фокус остаётся видимым
через контрастную заливку. Success/warning/danger сохраняют смысловые цвета
индикаторов; цвет акцента не подменяет состояние ошибки.
## Accent
## Акцент и настройки
Accent задаётся RGB tuple. On-accent вычисляется по luminance и не должен вручную прописываться белым или чёрным в отдельном компоненте.
Базовый акцент тёмной темы — `247 248 244`, светлой — `24 25 28`.
Пользовательский `accent` остаётся допустимой настройкой активных контролов.
`on-accent` вычисляется библиотекой по яркости. Нейтральное основное действие
остаётся нейтральным. Возврат к теме вызывает `clearNodedcAccent(root)`, затем
`applyNodedcTheme`; удалять пользовательское значение без явного сброса нельзя.
Материалы можно исследовать в каталоге; приложения не должны хранить собственный
набор цветов для восстановления стандартной темы.
Default accent текущего NODE.DC shell — `#ff2f92`. `ColorField` открывает единый portal-picker с saturation/value plane, hue slider, HEX и быстрыми цветами — системный `input[type=color]` не является runtime UI. Изменение accent сразу меняет Environment Settings, active actions, range fill, media file action и theme-aware window states без создания новой темы или fork компонентов. Blur, gloss и material rim не наследуются application panels: это материал только для floating modal и portal-dropdown/select.
В светлой теме canvas — `#ececec`, панели и поля — белые, группы и вложенные
области — `#f4f4f4`. Белое поле различимо внутри группы.
Map-glass остаётся отдельным светлым полупрозрачным материалом над изображением;
он не заменяет обычную тему форм, панелей и портальных окон.
Semantic status не обязан совпадать с accent. Например, ошибка остаётся danger, даже если приложение использует красный брендовый accent.
## Проверка и совместимость
## Область применения
Living catalog: Controls → Mission Core. Проверяются вложенная форма, текст,
select, textarea, disabled, переключатель, статус и то же содержимое в портальном
окне; дополнительно проверяются клавиатура и обе темы. CMS использует этот же
профиль и immutable npm-пакеты, не копию исходников компонентов.
Тема может быть установлена:
- на корневом `html/body` для всего приложения;
- на контейнере embedded-модуля;
- на catalog preview для сравнения схем.
Portal-компоненты рендерятся в `document.body`, поэтому приложение должно либо задавать тему на `document.documentElement`, либо передавать согласованные переменные на body. Локальная тема глубоко внутри React subtree не сможет автоматически охватить portal без отдельного theme portal root.
Map-glass overlays являются отдельной, независимой от application theme
поверхностью поверх imagery. Их светлые translucent controls используют
`--nodedc-map-glass-text`, а непрозрачное светлое поле поиска обязано брать
тёмный foreground из `--nodedc-map-field-text` и placeholder из
`--nodedc-map-field-text-muted`. Светлый field не наследует белый текст
map-glass родителя. `ApplicationSidePanel`, напротив, находится вне imagery и
всегда наследует обычные theme-aware application panel/text tokens; при смене
dark/light она меняется синхронно с `AdminNavigationPanel`.
## Совместимость
Существующие `--nodedc-*` имена сохранены намеренно. Это уменьшает стоимость будущего подключения Launcher, Engine, Task Manager и BIM Viewer.
## Mission Core operator appearance
`applyNodedcTheme(document.documentElement, { theme, accent, appearance: "mission" })`
selects the shared visual profile qualified against Mission Core on 2026-09-30.
It covers body portals, dark modal/floating fills, plain avatar surfaces,
neutral actions and semantic dot statuses. `default` remains compatible with
other consumers. Light theme retains its legible light surfaces. Reapplying
`default` removes the profile through the data attribute, without CSS cleanup.
Feature settings use the same geometry, focus, scrolling and responsive behavior.
Application code owns section names and icons; tracker/VPS sections follow the
text-only Mission equipment menu. Environment settings may retain their icons.
`appearance: "default", edges: "default"` оставлены для явной совместимости
со старой презентацией компонентов. Новые потребители используют Mission.
Эта ревизия не меняет локальный Mission Core и его незакоммиченные эксперименты.
Его прежние локальные CSS-дубли зафиксированы как миграционный долг: перенос
зависимости требует отдельной проверки приложения, а не незаметной замены пакетов.
+19
View File
@@ -0,0 +1,19 @@
# Интерфейс внутри viewport
Правило владельца от 14.11.2026. Любая подложка интерфейса поверх изображения viewport — общий **Glass V4**, тот же материал, что информационные плашки аппаратов. Правило одинаково для MapLibre/Cesium, IFC/BIM, point cloud/LAS, 3DGS, PlayCanvas, камер и replay; новые движки не создают новый материал.
## Применение
- Поиск, панели действий, легенды, статусы и плавающие плашки: `GlassMaterialSurface context="scene"`. `radius="panel"` для текста/поиска. У рейки круглых действий фон получают сами кнопки; общий контейнер остаётся прозрачным, без общей капсулы (уточнение владельца 14.11). На существующий семантический overlay разрешён DOM-контракт `className="nodedc-viewport-surface" data-glass-context="scene"`; позиционирование и радиус остаются у композиции.
- `nodedc-viewport-controls` и совместимый `nodedc-scene-controls` сохраняют масштаб 0.7 и задают Glass V4 кнопкам, select и segmented. Нельзя оборачивать этим scope весь renderer ради изменения размеров текста.
- Стекло меняет фон, а не opacity всей кнопки: иконки/текст сохраняют контраст. Общие scene tokens задают плотность 52% и blur 18px, отдельно от модальных окон. Настройки материала через публичный `material` contract; приложения не копируют blur/tint CSS.
- Открытые Dropdown/Select/Window используют canonical floating Glass V4, в том числе при fullscreen portal. Hover, pressed, disabled, focus и видимость меню сохраняются. Активная кнопка может использовать существующую контрастную заливку: это состояние общего контрола.
- Canvas, video, геометрия, текстуры/цвета модели, карта и содержимое изображения не покрываются стеклом. Полноэкранный пустой renderer/background не является плашкой. Обычный список, каталог и настройки за пределами viewport остаются matte.
## Эталон и проверка
Живой каталог → Glassy material: общий материал плашки и компактная панель управления над тем же фоном. Проверять на тёмном и светлом изображении, без наведения и при hover/focus, узком размере и fullscreen. Для BIM и центра наблюдения отдельно проверять реальные action rails; изменение CSS не является доказательством связи с устройством или работоспособности renderer.
Миграция начинается с BIM-карты/viewer и Центра наблюдения. Общий action scope охватывает существующие scene/map/replay controls; оставшиеся собственные подложки переводятся на тот же surface contract. Не создавать глобальную непрозрачную плашку вокруг всех viewports.
Уточнение 15.11.2026: все откреплённые панели `EditorDockLayout` (иерархия, слои, настройки и другие инструменты) автоматически получают `data-glass-context="scene"`. Материал действует уже во время отрыва/перетаскивания и после восстановления плавающего положения. Повторная стыковка возвращает материал и наружные углы tiled-панелей. Приложение не задаёт свои tint/blur/opacity.
+42
View File
@@ -129,3 +129,45 @@ 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.
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.
`EditorWorkspace purpose="view"` reuses the same stable host and docking grammar for viewers. Back/close return the mounted view to its inline slot; no edit-completion action is shown. Optional `headerActions` keeps application actions in the fixed window header. The default `purpose="edit"` preserves existing editors. The living docking example demonstrates both purposes.
Dock tool headings inherit the focused drag-header foreground, including title and subtitle, so the canonical inverted keyboard-focus fill retains readable text.
Keyboard-focused dock headers keep their action/close glyphs on the inherited contrast color, as well as title/subtitle.
Tool minimumSize governs floating and docked geometry alike, including restored JSON, pointer and keyboard resize. Screen bounds take priority when smaller. Put fixed bottom actions in EditorDockTool.footer; never append them to scrollable inspector content.
The primary scene owns an isolated stacking context so its toolbars stay behind floating tools. A tool outer shell clips without scrolling; only its body scrolls, keeping header/footer fixed even when a field receives focus.
ColorField spectrum has no decorative perimeter stroke; retain its visible sampling marker and keyboard focus. UserProfileMenu variant=header owns its HeaderProfile surface; consumers must not wrap it in another HeaderProfile.
+9 -2
View File
@@ -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 test:typography && 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 && npm run test:flat-theme && npm run test:mission-theme && npm run test:modal-size",
"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,14 @@
"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",
"test:typography": "node --test scripts/operational-typography.test.mjs",
"prebuild": "npm run test:typography",
"test:flat-theme": "node --test scripts/flat-theme.test.mjs",
"test:mission-theme": "node --test scripts/mission-theme.test.mjs",
"test:modal-size": "node --test scripts/modal-size.test.mjs"
},
"engines": {
"node": ">=20"
+31 -5
View File
@@ -1,4 +1,5 @@
:root {
--nodedc-field-hover-bg: color-mix(in srgb, var(--nodedc-field-bg) 94%, var(--nodedc-text-primary));
--nodedc-neutral-action-bg: rgba(247, 248, 244, 0.96);
--nodedc-neutral-action-hover: #fff;
--nodedc-neutral-action-color: rgba(8, 8, 10, 0.96);
@@ -9,14 +10,16 @@
:root,
[data-nodedc-theme="dark"] {
color-scheme: dark;
--nodedc-accent-rgb: 255 47 146;
--nodedc-on-accent-rgb: 11 17 23;
--nodedc-accent-rgb: 247 248 244;
--nodedc-on-accent-rgb: 8 8 10;
--nodedc-danger-rgb: 255 116 116;
--nodedc-warning-rgb: 255 209 102;
--nodedc-success-rgb: 181 255 90;
--nodedc-canvas: #050506;
--nodedc-canvas-soft: #0b0b0d;
--nodedc-canvas-soft: #0d0d0f;
--nodedc-stage: #08090b;
--nodedc-surface-group: rgba(110, 110, 110, 0.07);
--nodedc-text-primary: rgba(247, 248, 244, 0.96);
--nodedc-text-secondary: rgba(247, 248, 244, 0.72);
--nodedc-text-muted: rgba(247, 248, 244, 0.48);
@@ -82,14 +85,16 @@
[data-nodedc-theme="light"] {
color-scheme: light;
--nodedc-accent-rgb: 255 47 146;
--nodedc-on-accent-rgb: 11 17 23;
--nodedc-accent-rgb: 24 25 28;
--nodedc-on-accent-rgb: 247 248 244;
--nodedc-danger-rgb: 205 47 67;
--nodedc-warning-rgb: 173 111 0;
--nodedc-success-rgb: 46 125 76;
--nodedc-canvas: #ececec;
--nodedc-canvas-soft: #f4f4f4;
--nodedc-stage: #ececec;
--nodedc-surface-group: #f4f4f4;
--nodedc-text-primary: rgba(18, 20, 22, 0.96);
--nodedc-text-secondary: rgba(18, 20, 22, 0.7);
--nodedc-text-muted: rgba(18, 20, 22, 0.48);
@@ -152,3 +157,24 @@
--nodedc-modal-shadow: 0 24px 72px rgb(0 0 0 / var(--nodedc-modal-glass-shadow-light-opacity)), inset 0 1px 0 rgba(255, 255, 255, 0.8);
--nodedc-floating-surface: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(255, 255, 255, 0.72)), rgba(255, 255, 255, 0.94);
}
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] {
--nodedc-modal-surface: rgb(15 15 17 / .97);
--nodedc-floating-surface: rgb(15 15 17 / .98);
--nodedc-primary-action-bg: rgb(247 248 244 / .96);
--nodedc-primary-action-hover: rgb(255 255 255);
--nodedc-primary-action-color: rgb(8 8 10 / .96);
--nodedc-primary-action-shadow: none;
--nodedc-focus-surface: rgb(255 255 255 / .09);
}
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] {
--nodedc-modal-surface: rgb(247 248 250 / .97);
--nodedc-floating-surface: rgb(247 248 250 / .98);
--nodedc-primary-action-bg: rgb(24 25 28 / .96);
--nodedc-primary-action-hover: rgb(8 8 10);
--nodedc-primary-action-color: rgb(247 248 244);
--nodedc-primary-action-shadow: none;
}
+3
View File
@@ -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; }
+6 -3
View File
@@ -4,7 +4,8 @@
"type": "module",
"files": [
"dist",
"styles.css"
"styles.css",
"typography.mjs"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -13,11 +14,13 @@
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./styles.css": "./styles.css"
"./styles.css": "./styles.css",
"./typography": "./typography.mjs"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit"
"typecheck": "tsc -p tsconfig.json --noEmit",
"prebuild": "node --test ../../scripts/operational-typography.test.mjs"
},
"dependencies": {
"@nodedc/tokens": "0.6.0"
+31 -2
View File
@@ -2,7 +2,8 @@
export type DockTree = { id: string } | { axis: "x" | "y"; ratio: number; first: DockTree; second: DockTree };
export type DockPosition = "center" | "left" | "right" | "top" | "bottom";
export interface DockRect { left: number; top: number; width: number; height: number }
export interface DockMove { activeId: string; overId: string; position: DockPosition }
/** Workspace moves ignore overId and wrap the remaining layout at its outer edge. */
export interface DockMove { activeId: string; overId: string; position: DockPosition; scope?: "panel" | "workspace" }
export function dockIds(tree: DockTree | null): string[] {
return !tree ? [] : "id" in tree ? [tree.id] : [...dockIds(tree.first), ...dockIds(tree.second)];
@@ -47,7 +48,15 @@ export function reconcileDockTree(tree: DockTree | null, ids: readonly string[])
export function moveDockPanel(tree: DockTree | null, move: DockMove): DockTree | null {
const { activeId, overId, position } = move, ids = dockIds(tree);
if (!tree || activeId === overId || !ids.includes(activeId) || !ids.includes(overId)) return tree;
if (!tree || !ids.includes(activeId)) return tree;
if (move.scope === "workspace") {
if (position === "center" || ids.length < 2) return tree;
const remaining = pruneDockTree(tree, ids.filter(id => id !== activeId))!;
const before = position === "left" || position === "top";
return {axis: position === "left" || position === "right" ? "x" : "y", ratio: 50,
first: before ? {id: activeId} : remaining, second: before ? remaining : {id: activeId}};
}
if (activeId === overId || !ids.includes(overId)) return tree;
const swap = (node: DockTree): DockTree => "id" in node
? { id: node.id === activeId ? overId : node.id === overId ? activeId : node.id }
: { ...node, first: swap(node.first), second: swap(node.second) };
@@ -89,6 +98,26 @@ export function dockPosition(rect: DockRect, x: number, y: number): DockPosition
}
/** Outer 24 CSS px take priority over the existing per-panel zones.
* bounds is the visible workspace, expressed in the same coordinates as rects.
*/
export function dockMoveAtPoint(bounds: DockRect, rects: Readonly<Record<string, DockRect>>, activeId: string, x: number, y: number): DockMove | null {
if (![x, y, bounds.left, bounds.top, bounds.width, bounds.height].every(Number.isFinite)
|| !dockPosition(bounds, x, y) || !(activeId in rects) || Object.keys(rects).length < 2) return null;
const zoneX = Math.min(24, bounds.width * .08), zoneY = Math.min(24, bounds.height * .08);
const edges: [Exclude<DockPosition, "center">, number][] = [
["left", (x - bounds.left) / zoneX], ["right", (bounds.left + bounds.width - x) / zoneX],
["top", (y - bounds.top) / zoneY], ["bottom", (bounds.top + bounds.height - y) / zoneY],
];
const nearest = edges.sort((a, b) => a[1] - b[1])[0];
if (nearest[1] <= 1) return {activeId, overId: activeId, position: nearest[0], scope: "workspace"};
for (const [id, rect] of Object.entries(rects)) {
const position = dockPosition(rect, x, y);
if (position && id !== activeId) return {activeId, overId: id, position};
}
return null;
}
export interface DockMinimum { width: number; height: number }
export type DockMinimums = Readonly<Record<string, DockMinimum>>;
/** Propagate content limits through every ancestor, not only the nearest split. */
+54
View File
@@ -0,0 +1,54 @@
import {decodeDockTree,dockIds,dockPosition,pruneDockTree,type DockTree,type DockRect,type DockMove} from './dockTree.js';
/** The primary view is permanent. Tools can leave the split tree without losing their identity. */
export interface EditorDockState {tree:DockTree;floating:Record<string,DockRect>}
export function decodeEditorDock(raw:unknown,primary:string,tools:readonly string[]):EditorDockState|null {
if(!raw||typeof raw!=='object')return null;
const value=raw as Partial<EditorDockState>,allowed=[primary,...tools];
let tree=pruneDockTree(decodeDockTree(value.tree),allowed);
if(!dockIds(tree).includes(primary))tree=tree?{axis:'x',ratio:70,first:{id:primary},second:tree}:{id:primary};
const floating:Record<string,DockRect>={};
for(const id of tools){const r=value.floating?.[id];if(!r||!['left','top','width','height'].every(k=>Number.isFinite(r[k as keyof DockRect]))||r.width<=0||r.height<=0)continue;
floating[id]={left:Math.max(-16384,Math.min(16384,r.left)),top:Math.max(-16384,Math.min(16384,r.top)),width:Math.min(16384,r.width),height:Math.min(16384,r.height)};
}
return {tree:tree!,floating};
}
/** Inserts an absent/floating tool, or moves an existing tool. Never swaps the primary view. */
export function dockEditorTool(state:EditorDockState,primary:string,move:DockMove|null,id:string,rect:DockRect):EditorDockState {
if(id===primary)return state;
const remaining=pruneDockTree(state.tree,dockIds(state.tree).filter(v=>v!==id))??{id:primary};
const floating={...state.floating,[id]:rect};
if(!move||move.position==='center'||(move.scope!=='workspace'&&!dockIds(remaining).includes(move.overId)))return {tree:remaining,floating};
const before=move.position==='left'||move.position==='top',axis=move.position==='left'||move.position==='right'?'x':'y';
const wrap=(node:DockTree,ratio:number):DockTree=>({axis,ratio:before?ratio:100-ratio,first:before?{id}:node,second:before?node:{id}});
const insert=(node:DockTree):DockTree=>'id' in node?(node.id===move.overId?wrap(node,50):node):{...node,first:insert(node.first),second:insert(node.second)};
return {tree:move.scope==='workspace'?wrap(remaining,axis==='x'?25:28):insert(remaining),floating};
}
/** Outer edge has priority; broad magnets fill the gap between a tool and the viewport. */
export function editorDockTarget(bounds:DockRect,rects:Record<string,DockRect>,primary:string,id:string,x:number,y:number):DockMove|null {
if(!dockPosition(bounds,x,y))return null;
const edges:[DockMove['position'],number][]=[['left',x-bounds.left],['right',bounds.left+bounds.width-x],['top',y-bounds.top],['bottom',bounds.top+bounds.height-y]];
const nearest=edges.slice().sort((a,b)=>a[1]-b[1])[0];
if(nearest[1]<=24)return {activeId:id,overId:primary,position:nearest[0],scope:'workspace'};
for(const [target,r] of Object.entries(rects)){
if(target===id||target===primary||!dockPosition(r,x,y))continue;
const distances:[DockMove['position'],number][]=[['left',(x-r.left)/r.width],['right',(r.left+r.width-x)/r.width],['top',(y-r.top)/r.height],['bottom',(r.top+r.height-y)/r.height]];
return {activeId:id,overId:target,position:distances.sort((a,b)=>a[1]-b[1])[0][0],scope:'panel'};
}
const magnets=edges.map(([position,distance])=>[position,distance/Math.min(position==='left'||position==='right'?160:96,(position==='left'||position==='right'?bounds.width:bounds.height)*.16)] as const).sort((a,b)=>a[1]-b[1]);
return magnets[0][1]<=1?{activeId:id,overId:primary,position:magnets[0][0],scope:'workspace'}:null;
}
/** Resize visible splits while retaining the positions of temporarily closed tools. */
export function mergeEditorDockRatios(full:DockTree,visible:DockTree):DockTree {
const ids=dockIds(visible),ratios=new Map<string,number>();
const key=(node:DockTree)=>dockIds(node).sort().join('\0');
const collect=(node:DockTree)=>{if('id' in node)return;ratios.set(key(node),node.ratio);collect(node.first);collect(node.second);};collect(visible);
const merge=(node:DockTree):DockTree=>{
if('id' in node)return node;
const a=pruneDockTree(node.first,ids),b=pruneDockTree(node.second,ids),shown=pruneDockTree(node,ids);
return {...node,ratio:a&&b&&shown?(ratios.get(key(shown))??node.ratio):node.ratio,first:merge(node.first),second:merge(node.second)};
};return merge(full);
}
+5 -1
View File
@@ -29,12 +29,16 @@ function clamp(value: number, min: number, max: number) {
return Math.max(min, Math.min(max, value));
}
export function createGlassMaterialVariables(settings: GlassMaterialSettings): Record<string, string> {
export function createGlassMaterialVariables(settings: GlassMaterialSettings, context: "floating" | "scene" = "floating"): Record<string, string> {
const tintHex = normalizeHex(settings.tintHex);
const red = Number.parseInt(tintHex.slice(1, 3), 16);
const green = Number.parseInt(tintHex.slice(3, 5), 16);
const blue = Number.parseInt(tintHex.slice(5, 7), 16);
return {
...(context === "scene" ? {
"--nodedc-scene-glass-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
"--nodedc-scene-glass-blur": `${clamp(settings.blur, 0, 120)}px`,
} : {}),
"--nodedc-modal-glass-tint-rgb": `${red} ${green} ${blue}`,
"--nodedc-modal-glass-tint-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
"--nodedc-blur-modal": `${clamp(settings.blur, 0, 120)}px`,
+1
View File
@@ -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";
+14 -2
View File
@@ -15,12 +15,23 @@ export interface NodedcMaterial {
export interface ApplyThemeOptions {
theme?: NodedcTheme;
/** Operator UI qualified against Mission Core; opt-in across portals. */
/** Mission Core is the canonical foundation. `default` is legacy compatibility. */
appearance?: "default" | "mission";
/** Flat surfaces remove decorative edges; keyboard focus uses a contrasting fill. */
edges?: "default" | "flat";
accent?: RgbTuple;
material?: NodedcMaterial;
}
/** Complete shared foundation; colors live exclusively in @nodedc/tokens/themes.css. */
export const missionDarkTheme = Object.freeze({
theme: "dark", appearance: "mission", edges: "flat",
} as const satisfies ApplyThemeOptions);
export const missionLightTheme = Object.freeze({
theme: "light", appearance: "mission", edges: "flat",
} as const satisfies ApplyThemeOptions);
function formatRgb([red, green, blue]: RgbTuple): string {
return `${red} ${green} ${blue}`;
}
@@ -31,10 +42,11 @@ function clampOpacity(value: number): number {
export function applyNodedcTheme(
target: HTMLElement,
{ theme = "dark", accent, material, appearance = "default" }: ApplyThemeOptions = {},
{ theme = "dark", accent, material, appearance = "mission", edges = "flat" }: ApplyThemeOptions = {},
): void {
target.dataset.nodedcTheme = theme;
target.dataset.nodedcAppearance = appearance;
target.dataset.nodedcEdges = edges;
target.dataset.nodedcUi = "true";
if (accent) {
+276 -45
View File
@@ -1,7 +1,7 @@
@import "@nodedc/tokens/tokens.css";
@import "@nodedc/tokens/themes.css";
:where([data-nodedc-ui], .nodedc-ui-root) {
:where([data-nodedc-ui], .nodedc-ui-root, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) {
color: var(--nodedc-text-primary);
font-family: var(--nodedc-font-family);
font-synthesis: none;
@@ -9,6 +9,18 @@
-webkit-font-smoothing: antialiased;
}
/* Theme attributes may live on html. Set the text base on body instead, so
rem tokens and user zoom never get multiplied by the operational base. */
:where([data-nodedc-ui]:not(html), .nodedc-ui-root:not(html), html[data-nodedc-ui] > body, html.nodedc-ui-root > body, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) {
font-size: var(--nodedc-font-size-md);
}
/* Semantic headings inside operational surfaces do not inherit browser h1–h6 scaling.
Explicit canonical window/page titles retain their title token. */
:where([data-nodedc-ui], .nodedc-ui-root, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) :where(h1, h2, h3, h4, h5, h6) {
font-size: var(--nodedc-font-size-md);
}
:where([data-nodedc-ui], .nodedc-ui-root) *,
:where([data-nodedc-ui], .nodedc-ui-root) *::before,
:where([data-nodedc-ui], .nodedc-ui-root) *::after {
@@ -65,6 +77,12 @@
box-shadow: var(--nodedc-glass-control-shadow);
}
/* Form collections share SettingsCard's neutral group, not the recessed canvas. */
.nodedc-glass[data-tone="group"] {
background: var(--nodedc-surface-group);
box-shadow: none;
}
.nodedc-glass[data-radius="panel"] {
border-radius: var(--nodedc-radius-panel);
}
@@ -422,7 +440,7 @@
}
.nodedc-field__control:hover:not(:disabled) {
background: var(--nodedc-glass-control-hover);
background: var(--nodedc-field-hover-bg);
}
.nodedc-field__control:focus-visible {
@@ -647,7 +665,7 @@ textarea.nodedc-field__control {
min-width: 0;
gap: 1rem;
border-radius: var(--nodedc-radius-card);
background: var(--nodedc-glass-control-bg);
background: var(--nodedc-surface-group);
padding: 1rem;
}
@@ -674,7 +692,8 @@ textarea.nodedc-field__control {
.nodedc-settings-card__titles h2,
.nodedc-description,
.nodedc-settings-card__titles p {
.nodedc-settings-card__titles p,
.nodedc-settings-card__body :where(p:not([class])) {
font-family: inherit;
font-weight: 400;
margin: 0;
@@ -687,11 +706,12 @@ textarea.nodedc-field__control {
}
.nodedc-description,
.nodedc-settings-card__titles p {
.nodedc-settings-card__titles p,
.nodedc-settings-card__body :where(p:not([class])) {
font-family: inherit;
font-weight: 400;
color: var(--nodedc-text-muted);
font-size: var(--nodedc-font-size-sm);
font-size: var(--nodedc-description-font-size, var(--nodedc-font-size-sm));
line-height: 1.4;
}
@@ -1018,7 +1038,7 @@ textarea.nodedc-field__control {
position: relative;
aspect-ratio: 1.5 / 1;
overflow: hidden;
border: 1px solid var(--nodedc-glass-outline);
border: 0;
border-radius: var(--nodedc-radius-control);
outline: 0;
background:
@@ -1429,7 +1449,7 @@ textarea.nodedc-field__control {
.nodedc-user-profile-card__cover strong {
margin-top: 0.25rem;
font-size: 0.92rem;
font-size: var(--nodedc-font-size-md);
}
.nodedc-user-profile-card__cover > span:not(.nodedc-header__avatar) {
@@ -1456,7 +1476,7 @@ textarea.nodedc-field__control {
text-align: left;
text-decoration: none;
font: inherit;
font-size: 0.82rem;
font-size: var(--nodedc-font-size-md);
font-weight: 700;
cursor: pointer;
}
@@ -1563,7 +1583,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 {
@@ -1700,7 +1721,7 @@ textarea.nodedc-field__control {
}
.nodedc-application-panel__titles h1 {
font-size: 1.15rem;
font-size: var(--nodedc-font-size-title);
font-weight: 780;
line-height: 1.15;
}
@@ -1708,7 +1729,7 @@ textarea.nodedc-field__control {
.nodedc-application-panel__titles p {
max-width: 42rem;
color: var(--nodedc-text-muted);
font-size: 0.75rem;
font-size: var(--nodedc-font-size-sm);
line-height: 1.35;
}
@@ -1844,7 +1865,7 @@ textarea.nodedc-field__control {
.nodedc-admin-panel__head p {
color: var(--nodedc-text-muted);
font-size: 0.68rem;
font-size: var(--nodedc-font-size-sm);
font-weight: 850;
letter-spacing: 0.04em;
text-transform: uppercase;
@@ -1852,7 +1873,7 @@ textarea.nodedc-field__control {
.nodedc-admin-panel__head h2 {
margin-top: 0.55rem;
font-size: 1.15rem;
font-size: var(--nodedc-font-size-title);
font-weight: 780;
line-height: 1.1;
}
@@ -2005,7 +2026,7 @@ textarea.nodedc-field__control {
}
.nodedc-admin-context__body strong {
font-size: 0.92rem;
font-size: var(--nodedc-font-size-md);
font-weight: 800;
}
@@ -2044,7 +2065,7 @@ textarea.nodedc-field__control {
color: var(--nodedc-text-secondary);
padding: 5px 0.9rem 5px calc(5px + 2.92rem + 0.86rem);
font: inherit;
font-size: 0.91rem;
font-size: var(--nodedc-font-size-md);
font-weight: 570;
text-align: left;
opacity: 0.66;
@@ -3148,7 +3169,9 @@ textarea.nodedc-field__control {
}
/* Keep the full hit area and keyboard focus cue without a visible divider. */
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator:not(:focus-visible)::before {
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator:not(:focus-visible)::before,
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator[data-pointer-focus]::before,
.nodedc-split-pane[data-separator-appearance="invisible"][data-dragging="true"] > .nodedc-split-pane__separator::before {
background: transparent;
box-shadow: none;
}
@@ -3546,20 +3569,29 @@ textarea.nodedc-field__control {
}
.nodedc-inspector {
container-type: inline-size;
container-name: nodedc-inspector;
display: grid;
min-width: 0;
grid-template-columns: minmax(0, 1fr);
width: min(var(--nodedc-inspector-inner-width), 100%);
gap: 1px;
gap: var(--nodedc-space-3);
}
.nodedc-inspector__header { display: grid; min-width: 0; gap: var(--nodedc-space-3); }
.nodedc-inspector__footer { display: flex; justify-content: center; align-items: center; flex-wrap: wrap; gap: var(--nodedc-space-3); }
.nodedc-inspector__group {
display: grid;
gap: 1px;
min-width: 0;
grid-template-columns: minmax(0, 1fr);
gap: var(--nodedc-space-3);
}
.nodedc-inspector__section {
display: grid;
min-width: 0;
gap: 1px;
gap: 0;
}
.nodedc-inspector__section-trigger {
@@ -3634,6 +3666,8 @@ textarea.nodedc-field__control {
.nodedc-inspector__section-content {
display: grid;
min-width: 0;
grid-template-columns: minmax(0, 1fr);
gap: var(--nodedc-space-3);
padding: var(--nodedc-space-3) 0 var(--nodedc-space-2);
animation: nodedc-section-in var(--nodedc-duration-fast) ease;
@@ -3731,7 +3765,7 @@ textarea.nodedc-field__control {
display: grid;
width: min(var(--nodedc-inspector-inner-width), 100%);
min-height: var(--nodedc-control-height);
grid-template-columns: var(--nodedc-inspector-label-width) var(--nodedc-inspector-control-width);
grid-template-columns: minmax(0, 1fr) minmax(0, var(--nodedc-inspector-control-width));
align-items: center;
gap: var(--nodedc-inspector-control-gap);
}
@@ -3911,6 +3945,7 @@ textarea.nodedc-field__control {
overflow: auto;
}
.nodedc-header__profile-button,
.nodedc-user-profile-menu__trigger-label {
display: none;
}
@@ -4000,7 +4035,7 @@ textarea.nodedc-field__control {
[data-nodedc-theme="light"] :is(.nodedc-header__brand, .nodedc-header__workspace)[data-monochrome="true"] img { filter: brightness(0); }
/* Owner-admitted linear progress in the shared resource row. */
.nodedc-progress-bar { min-width: 3rem; height: var(--nodedc-space-2); overflow: hidden; border-radius: var(--nodedc-radius-circle); background: var(--nodedc-glass-control-bg); }
.nodedc-progress-bar { min-width: 3rem; height: var(--nodedc-progress-height, var(--nodedc-space-2)); overflow: hidden; border-radius: var(--nodedc-radius-circle); background: var(--nodedc-glass-control-bg); }
.nodedc-progress-bar__fill { display: block; width: 100%; height: 100%; background: var(--nodedc-text-secondary); border-radius: inherit; transform: scaleX(var(--nodedc-progress-fraction)); transform-origin: left; transition: transform var(--nodedc-duration-normal) var(--nodedc-ease-standard); }
.nodedc-progress-bar[data-indeterminate] > .nodedc-progress-bar__fill { width: 35%; animation: nodedc-progress-travel 1.5s ease-in-out infinite alternate; }
@keyframes nodedc-progress-travel { from { transform: translateX(-100%); } to { transform: translateX(285%); } }
@@ -4093,7 +4128,7 @@ textarea.nodedc-field__control {
max-width: 34rem;
margin: 0;
color: var(--nodedc-text-secondary);
font-size: clamp(0.8rem, 1vw, 1rem);
font-size: var(--nodedc-font-size-sm);
line-height: 1.6;
}
@@ -4128,7 +4163,7 @@ textarea.nodedc-field__control {
.nodedc-landing-stage__status p {
margin: 0.15rem 0 0;
color: var(--nodedc-text-muted);
font-size: 0.66rem;
font-size: var(--nodedc-font-size-sm);
line-height: 1.45;
}
@@ -4235,7 +4270,7 @@ textarea.nodedc-field__control {
.nodedc-environment-media-playlist__error {
margin: 0;
color: var(--nodedc-text-muted);
font-size: var(--nodedc-font-size-xs);
font-size: var(--nodedc-font-size-sm);
line-height: 1.4;
}
@@ -4347,7 +4382,7 @@ textarea.nodedc-field__control {
}
@media (max-height: 720px) and (min-width: 761px) {
.nodedc-landing-stage__copy p {
font-size: 0.76rem;
font-size: var(--nodedc-font-size-sm);
}
}
@media (max-height: 720px) and (min-width: 761px) {
@@ -4373,26 +4408,11 @@ textarea.nodedc-field__control {
.nodedc-key-button:disabled { opacity:.4; cursor:not-allowed; }
.nodedc-key-button:focus-visible { outline:2px solid rgb(var(--nodedc-accent-rgb)); outline-offset:3px; }
/* Shared operator appearance, qualified against Mission Core 2026-09-30.
/* Canonical operator appearance, audited against Mission Core 2026-11-05.
Set on documentElement so modal and dropdown portals share the same profile. */
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] {
--nodedc-modal-surface: rgb(15 15 17 / .97);
--nodedc-floating-surface: rgb(15 15 17 / .98);
--nodedc-primary-action-bg: rgb(247 248 244 / .96);
--nodedc-primary-action-hover: rgb(255 255 255);
--nodedc-primary-action-color: rgb(8 8 10 / .96);
--nodedc-primary-action-shadow: none;
--nodedc-focus-surface: rgb(255 255 255 / .09);
}
[data-nodedc-appearance="mission"] .nodedc-glass-material::before { display: none; }
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] {
--nodedc-modal-surface: rgb(247 248 250 / .97);
--nodedc-floating-surface: rgb(247 248 250 / .98);
--nodedc-primary-action-bg: rgb(24 25 28 / .96);
--nodedc-primary-action-hover: rgb(8 8 10);
--nodedc-primary-action-color: rgb(247 248 244);
--nodedc-primary-action-shadow: none;
}
[data-nodedc-appearance="mission"] .nodedc-header__avatar { background: rgb(226 226 226); }
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] .nodedc-feature-settings__section[data-active="true"] { background: rgb(247 248 244 / .14); }
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] .nodedc-feature-settings__section[data-active="true"] { background: rgb(8 8 10 / .09); }
@@ -4517,6 +4537,34 @@ 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;isolation:isolate;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 :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="top-left"] {border-top-left-radius:var(--nodedc-radius-panel);}
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="top-right"] {border-top-right-radius:var(--nodedc-radius-panel);}
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="bottom-right"] {border-bottom-right-radius:var(--nodedc-radius-panel);}
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="bottom-left"] {border-bottom-left-radius:var(--nodedc-radius-panel);}
.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__tool>.nodedc-window__head:focus-visible :is(.nodedc-window__title,.nodedc-window__subtitle,.nodedc-window__actions,.nodedc-window__close,.nodedc-icon-button) {color:inherit;}
.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);}
@@ -4539,9 +4587,192 @@ textarea.nodedc-field__control {
/* Structural cube edges communicate face/edge/corner hit zones. */
.nodedc-navigation-cube { width: 66px; height: 66px; overflow: visible; user-select: none; }
.nodedc-navigation-cube polygon { fill: var(--cube-face, var(--nodedc-surface-raised, #292929)); stroke: var(--cube-edge, var(--nodedc-text-muted, #888)); stroke-width: .55; stroke-opacity: var(--cube-edge-opacity, 1); }
.nodedc-navigation-cube polygon { fill: var(--cube-face, var(--nodedc-surface-raised, #292929)); stroke: var(--cube-edge, var(--nodedc-text-muted, #888)); stroke-width: .55; stroke-opacity: var(--cube-edge-opacity, 1); fill-opacity:var(--cube-face-opacity,1); }
.nodedc-navigation-cube text { fill: var(--cube-text, var(--nodedc-text-primary, #eee)); font: 600 9px var(--nodedc-font-family); pointer-events: none; }
.nodedc-navigation-cube g { cursor: pointer; }
.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; }
/* A measured resource capsule; its containing row never owns a surface. */
.nodedc-level-button.nodedc-button{min-width:calc(var(--nodedc-control-height) * 2.5);font-variant-numeric:tabular-nums;--nodedc-level-color:var(--nodedc-text-secondary)}
.nodedc-level-button[data-level-tone="success"]{--nodedc-level-color:rgb(var(--nodedc-success-rgb))}
.nodedc-level-button[data-level-tone="warning"]{--nodedc-level-color:rgb(var(--nodedc-warning-rgb))}
.nodedc-level-button[data-level-tone="danger"]{--nodedc-level-color:rgb(var(--nodedc-danger-rgb))}
.nodedc-level-button[data-freshness="stale"],.nodedc-level-button[data-freshness="unknown"]{--nodedc-level-color:var(--nodedc-text-secondary)}
.nodedc-level-button.nodedc-button,.nodedc-level-button.nodedc-button:hover{background-image:linear-gradient(90deg,color-mix(in srgb,var(--nodedc-level-color) 26%,transparent) var(--nodedc-level-percent),transparent var(--nodedc-level-percent))}
.nodedc-level-button[data-custom-fill].nodedc-button{position:relative;overflow:hidden;background-image:none}
.nodedc-level-button__fill{position:absolute;inset:0;display:grid;place-items:center;pointer-events:none;background:var(--nodedc-level-custom);color:var(--nodedc-level-ink);clip-path:inset(0 calc(100% - var(--nodedc-level-percent)) 0 0)}
.nodedc-tooltip-anchor { display: inline-flex; min-width: 0; }
.nodedc-tooltip-anchor[tabindex] { border-radius: var(--nodedc-radius-control-compact); }
.nodedc-tooltip-anchor[tabindex]:focus-visible { outline: 2px solid var(--nodedc-text-primary); outline-offset: 3px; }
.nodedc-tooltip {
position: fixed; z-index: var(--nodedc-layer-popover); box-sizing: border-box;
width: max-content; max-width: min(280px, calc(100vw - 16px)); overflow: auto;
padding: var(--nodedc-space-3) var(--nodedc-space-4);
border-radius: var(--nodedc-radius-control-compact);
background: var(--nodedc-floating-surface); color: var(--nodedc-text-primary);
box-shadow: var(--nodedc-glass-dropdown-shadow); font-family: var(--nodedc-font-family);
font-size: var(--nodedc-font-size-sm); font-weight: var(--nodedc-font-weight-regular); line-height: 1.4;
animation: nodedc-tooltip-in var(--nodedc-duration-fast) var(--nodedc-ease-standard);
}
@keyframes nodedc-tooltip-in { from { opacity: 0; } to { opacity: 1; } }
@media (prefers-reduced-motion: reduce) { .nodedc-tooltip { animation: none; } }
/* Opt-in flat material. Applies at the document root, including portal layers.
Focus remains visible through a high-contrast fill instead of a contour. */
[data-nodedc-edges="flat"] {
--nodedc-glass-outline: transparent;
--nodedc-glass-control-shadow: none;
--nodedc-panel-action-border: transparent;
--nodedc-panel-action-border-hover: transparent;
--nodedc-panel-action-shadow: none;
}
[data-nodedc-edges="flat"] .nodedc-material-rim::after,
[data-nodedc-edges="flat"] .nodedc-glass-material::before { display: none; }
[data-nodedc-edges="flat"] :is(.nodedc-admin-panel__nav-item, .nodedc-application-panel__action, .nodedc-admin-panel__close, .nodedc-media-source-button, .nodedc-media-preview, .nodedc-color-field__swatch) {
border: 0;
box-shadow: none;
}
[data-nodedc-edges="flat"] :is(button, input, textarea, [tabindex]):focus-visible {
outline: 0;
box-shadow: none;
background-color: var(--nodedc-text-primary);
color: var(--nodedc-canvas);
}
[data-nodedc-edges="flat"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon {
background: var(--nodedc-canvas);
color: var(--nodedc-text-primary);
}
.nodedc-select[data-shape="pill"] :is(.nodedc-select__value,.nodedc-select__toggle) { border-radius: var(--nodedc-radius-circle); }
/* Owner canon 2026-11-14: all viewport-backed UI shares scene Glass V4.
Geometry, disabled opacity, pressed selection and keyboard focus are retained.
The DOM surface class is for existing semantic overlays, never the renderer. */
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar__button:not([data-active="true"]),
.nodedc-viewport-surface[data-glass-context="scene"],
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-icon-button:not([aria-pressed="true"]), .nodedc-button:is([data-variant="secondary"], [data-variant="ghost"]):not([aria-pressed="true"]), .nodedc-select__toggle, .nodedc-segmented, .nodedc-workspace-window__action:not([aria-pressed="true"])) {
background: rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
color: var(--nodedc-text-primary);
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));
}
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar__button:hover:not(:disabled):not([data-active="true"]),
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-icon-button, .nodedc-button:is([data-variant="secondary"], [data-variant="ghost"]), .nodedc-workspace-window__action):hover:not(:disabled):not([aria-pressed="true"]) {
background: color-mix(in srgb, var(--nodedc-text-primary) 12%, rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity)));
}
.nodedc-tree__actions {display:flex;flex:none;align-items:center;}
.nodedc-tree__actions .nodedc-icon-button {flex:0 0 24px;width:24px;height:24px;min-width:24px;padding:0;}
/* A backdrop root on the transparent rail would prevent button glass sampling the scene. */
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar {will-change:transform;}
/* Floating inspectors may be narrower than the browser; respond to their own width. */
@container nodedc-inspector (max-width: 329px) {
.nodedc-control-row { grid-template-columns: minmax(0, 1fr); gap: var(--nodedc-space-2); }
}
.nodedc-editor-dock__tool.nodedc-glass-material { overflow: clip; }
/* Same thin scale as the vertical section rail, with one horizontal boundary. */
.nodedc-range-rail { display: flex; flex-direction: column; gap: var(--nodedc-space-2); width: 100%; padding-block: var(--nodedc-space-2); }
.nodedc-range-rail__value { text-align: center; color: var(--nodedc-text-primary); font-size: var(--nodedc-font-size-md); line-height: var(--nodedc-line-height-normal); font-weight: var(--nodedc-font-weight-medium); font-variant-numeric: tabular-nums; pointer-events: none; }
.nodedc-range[data-variant="rail"] { height: calc(var(--nodedc-control-height) * 0.2); overflow: visible; border: 0; outline: 0; box-shadow: none; }
.nodedc-range[data-variant="rail"] input[type="range"] { top: 50%; height: max(100%, 24px); transform: translateY(-50%); }
.nodedc-range-rail:has(input:focus-visible) .nodedc-range-rail__value { text-decoration: underline; text-underline-offset: 2px; }
.nodedc-range-rail[data-disabled] { opacity: var(--nodedc-disabled-opacity, 0.5); }
+46
View File
@@ -0,0 +1,46 @@
/** Build-time typography contract. CSS parsers/TypeScript are supplied by the consumer. */
export const operationalFontSizes = Object.freeze({xs: 11, sm: 12, md: 13, dense: 7.2});
export const titleFontSize = 18;
export function declarationKey({file, selector, property, value}) {
return [file, selector.replace(/\s+/g,' ').trim(), property, value].join(' | ');
}
export function typographyViolation(declaration, policy={}) {
const {property,value}=declaration,key=declarationKey(declaration);
if(property.startsWith('--nodedc-font-size-'))return 'Do not redefine canonical size tokens in a consumer';
if(property!=='font-size'&&property!=='font'&&!/font-size$/.test(property))return null;
if(property==='font-size'&&/(^|[,\s])(?:html|:root)(?=$|[,\s])/.test(declaration.selector))return 'Do not resize html/rem to make operational UI smaller';
if(policy.exceptions?.some(e=>e.key===key&&e.reason))return null;
if(property==='font-size'&&declaration.selector.split(',').some(s=>/(?:^|[\s>+~])p$|\.nodedc-description$/.test(s.trim()))&&value!=='var(--nodedc-font-size-sm)')return 'Explanatory paragraphs use sm/12px; do not restyle Description per feature';
if(property==='font')return value==='inherit'?null:'Use inherited typography; font shorthand can reintroduce browser/large sizes';
if(/^var\(--nodedc-font-size-(xs|sm|md|dense)\)$/.test(value))return null;
if(value==='var(--nodedc-font-size-title)'&&policy.titles?.includes(declaration.selector))return null;
// Existing compact custom geometry is frozen by exact declaration, never an open size allowance.
if(policy.compactLegacy?.includes(key)){
const literal=/^([\d.]+)(px|rem)$/.exec(value);
if(literal&&Number(literal[1])*(literal[2]==='rem'?16:1)<=13)return null;
}
return 'Use xs/sm/md tokens (11/12/13 px); title is reserved for canonical page/window titles';
}
export function auditStyles(postcss, text, file, policy) {
const violations=[];
postcss.parse(text,{from:file}).walkDecls(d=>{
const declaration={file,selector:d.parent.selector||d.parent.name||'',property:d.prop,value:d.value};
const reason=typographyViolation(declaration,policy);
if(reason)violations.push(`${file}:${d.source.start.line}: ${d.parent.selector}: ${d.prop}: ${d.value}: ${reason}`);
});
return violations;
}
export function auditMarkup(ts,text,file,{allowBareParagraphs=false,inlineExceptions=[]}={}) {
const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,file.endsWith('tsx')?ts.ScriptKind.TSX:ts.ScriptKind.TS),violations=[];
function report(n,reason){const fragment=n.getText(source);if(!inlineExceptions.some(e=>e.file===file&&e.fragment===fragment&&e.reason))violations.push(`${file}:${source.getLineAndCharacterOfPosition(n.getStart(source)).line+1}: ${reason}`);}
function visit(n){
if(ts.isJsxOpeningElement(n)||ts.isJsxSelfClosingElement(n)){
if(!allowBareParagraphs&&n.tagName.getText(source)==='p'&&!n.attributes.properties.some(p=>ts.isJsxAttribute(p)&&p.name.text==='className'))report(n,'Use Description for explanatory/status copy, or an explicitly styled data paragraph');
for(const a of n.attributes.properties)if(ts.isJsxAttribute(a)&&/^(fontSize|style)$/.test(a.name.text)&&a.initializer){
if(a.name.text==='fontSize'||(ts.isStringLiteral(a.initializer)&&/font(?:-size)?\s*:/.test(a.initializer.text)))report(a,'Inline typography bypasses the shared contract');
}
}
if(ts.isPropertyAssignment(n)&&(/^(fontSize|font|--nodedc-font-size-.+)$/.test(n.name.getText(source).replace(/['"]/g,''))))report(n,'Inline typography bypasses the shared contract');
ts.forEachChild(n,visit);
}visit(source);return violations;
}
+4 -2
View File
@@ -3,7 +3,8 @@
"version": "0.7.0",
"type": "module",
"files": [
"dist"
"dist",
"styles.css"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -11,7 +12,8 @@
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"./styles.css": "./styles.css"
},
"scripts": {
"build": "tsc -p tsconfig.json",
+3 -1
View File
@@ -1,8 +1,10 @@
export { applyNodedcTheme, clearNodedcAccent, createAccentVariables, readableTextRgb } from "@nodedc/ui-core";
export { applyNodedcTheme, missionDarkTheme, missionLightTheme, clearNodedcAccent, createAccentVariables, readableTextRgb } from "@nodedc/ui-core";
export * from "./applicationWorkspace.js";
export * from "./floating.js";
export * from "./mediaSource.js";
export * from "./modal.js";
export * from "./modalSize.js";
export * from "./pathBar.js";
export * from "./select.js";
export * from "./shareLink.js";
export * from "./toolbar.js";
+69
View File
@@ -0,0 +1,69 @@
export type ModalSize = { width: number; height: number };
export function fitModalSize(size: ModalSize, viewport: ModalSize, minimum: ModalSize = { width: 320, height: 200 }): ModalSize {
const fit = (value: number, available: number, min: number) => Math.max(Math.min(min, Math.max(1, available - 32)), Math.min(value, Math.max(1, available - 32)));
return { width: fit(size.width, viewport.width, minimum.width), height: fit(size.height, viewport.height, minimum.height) };
}
/** Resize a centered DOM modal without changing its focus/layer controller.
* Persistence belongs to the consumer; only completed user gestures commit.
*/
export function createModalSizeController({ dialog, initialSize, minimum, onSizeCommit }: {
dialog: HTMLElement; initialSize: ModalSize; minimum?: ModalSize; onSizeCommit?: (size: ModalSize) => void;
}) {
const head = dialog.querySelector<HTMLElement>('.nodedc-window__head');
const previous = { width: dialog.style.width, height: dialog.style.height, maxHeight: dialog.style.maxHeight, tab: head?.getAttribute('tabindex'), title: head?.getAttribute('title') };
let desired = { ...initialSize };
let gesture: { id: number; x: number; y: number; edge: string; size: ModalSize; before: ModalSize } | null = null;
const viewport = () => ({ width: window.innerWidth, height: window.innerHeight });
const visible = () => dialog.getClientRects().length > 0;
const apply = (size = desired) => {
const fitted = fitModalSize(size, viewport(), minimum);
dialog.style.width = `${fitted.width}px`;
dialog.style.height = `${fitted.height}px`;
dialog.style.maxHeight = 'calc(100dvh - 2rem)';
return fitted;
};
const handles = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map(edge => {
const handle = document.createElement('div');
handle.className = 'nodedc-window__resize'; handle.dataset.edge = edge; handle.setAttribute('aria-hidden', 'true');
handle.addEventListener('pointerdown', event => {
if (event.button !== 0 || gesture) return;
const rect = dialog.getBoundingClientRect();
gesture = { id: event.pointerId, x: event.clientX, y: event.clientY, edge, size: { width: rect.width, height: rect.height }, before: desired };
handle.setPointerCapture(event.pointerId); event.preventDefault();
});
dialog.append(handle); return handle;
});
const move = (event: PointerEvent) => {
if (!gesture || event.pointerId !== gesture.id) return;
const { size, edge, x, y } = gesture;
desired = apply({ width: size.width + (event.clientX - x) * (edge.includes('e') ? 2 : edge.includes('w') ? -2 : 0), height: size.height + (event.clientY - y) * (edge.includes('s') ? 2 : edge.includes('n') ? -2 : 0) });
event.preventDefault();
};
const end = (event: PointerEvent) => {
if (!gesture || event.pointerId !== gesture.id) return;
const before = gesture.before; gesture = null;
if (event.type === 'pointercancel') { desired = before; apply(); return; }
if (desired.width !== before.width || desired.height !== before.height) onSizeCommit?.({ ...desired });
};
const key = (event: KeyboardEvent) => {
if (event.target !== head || !event.shiftKey || !event.key.startsWith('Arrow')) return;
event.preventDefault();
const size = fitModalSize(desired, viewport(), minimum);
desired = apply({ width: size.width + (event.key === 'ArrowRight' ? 20 : event.key === 'ArrowLeft' ? -20 : 0), height: size.height + (event.key === 'ArrowDown' ? 20 : event.key === 'ArrowUp' ? -20 : 0) });
onSizeCommit?.({ ...desired });
};
const refresh = () => { if (visible() && !gesture) apply(); };
if (head) { head.tabIndex = 0; head.title = 'Размер окна: Shift + стрелки. Мышью — за край или угол.'; head.addEventListener('keydown', key); }
window.addEventListener('pointermove', move); window.addEventListener('pointerup', end); window.addEventListener('pointercancel', end); window.addEventListener('resize', refresh);
apply();
return {
refresh,
setSize(size: ModalSize) { if (!gesture) { desired = { ...size }; apply(); } },
destroy() {
window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', end); window.removeEventListener('pointercancel', end); window.removeEventListener('resize', refresh);
head?.removeEventListener('keydown', key); handles.forEach(handle => handle.remove());
for (const name of ['width', 'height', 'maxHeight'] as const) dialog.style[name] = previous[name];
if (head) for (const [name, value] of [['tabindex', previous.tab], ['title', previous.title]]) { if (value == null) head.removeAttribute(name!); else head.setAttribute(name!, value); }
},
};
}
+19
View File
@@ -0,0 +1,19 @@
export type PathBarItem = { label: string; path: string; kind: 'folder' | 'file'; current?: boolean };
/** Compact Finder-style path row. Navigation and icon source belong to the app. */
export function renderPathBar(target: HTMLElement, items: PathBarItem[], options: { onNavigate: (path: string) => void; icon: (kind: 'folder' | 'file') => Node }) {
target.classList.add('nodedc-path-bar');
target.setAttribute('role', 'navigation'); target.setAttribute('aria-label', 'Путь к файлу');
const nodes: Node[] = [];
items.forEach((item, index) => {
if (index) { const separator = document.createElement('span'); separator.className = 'nodedc-path-bar__separator'; separator.textContent = '›'; separator.setAttribute('aria-hidden', 'true'); nodes.push(separator); }
const part = document.createElement(item.kind === 'folder' ? 'button' : 'span');
part.className = 'nodedc-path-bar__item'; part.title = item.path || item.label;
if (item.current) part.setAttribute('aria-current', 'location');
const icon = document.createElement('span'); icon.className = 'nodedc-path-bar__icon'; icon.setAttribute('aria-hidden', 'true'); icon.append(options.icon(item.kind));
const text = document.createElement('span'); text.textContent = item.label;
part.append(icon, text);
if (part instanceof HTMLButtonElement) { part.type = 'button'; part.addEventListener('click', () => options.onNavigate(item.path)); }
nodes.push(part);
});
target.replaceChildren(...nodes);
}
+31
View File
@@ -0,0 +1,31 @@
.nodedc-path-bar {
display: flex;
align-items: center;
gap: var(--nodedc-space-1);
overflow-x: auto;
flex: none;
padding: var(--nodedc-space-2) var(--nodedc-space-3);
color: var(--nodedc-text-secondary);
font-size: var(--nodedc-font-size-sm);
background: var(--nodedc-surface-group);
}
.nodedc-path-bar__item {
display: inline-flex;
align-items: center;
gap: var(--nodedc-space-1);
flex: none;
white-space: nowrap;
padding: 0;
background: transparent;
border: 0;
color: inherit;
font-family: inherit;
font-size: var(--nodedc-font-size-sm);
line-height: 1.5;
}
button.nodedc-path-bar__item { cursor: pointer; }
button.nodedc-path-bar__item:hover { color: var(--nodedc-text-primary); }
button.nodedc-path-bar__item:focus-visible { outline: 2px solid var(--nodedc-text-primary); outline-offset: 2px; }
.nodedc-path-bar__icon { display: inline-flex; color: var(--nodedc-text-primary); }
.nodedc-path-bar__icon svg { width: 14px; height: 14px; }
.nodedc-path-bar__separator { flex: none; color: var(--nodedc-text-muted); }
+4 -3
View File
@@ -1,4 +1,4 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
import type { ButtonHTMLAttributes, ReactNode, Ref } from "react";
export interface AppHeaderProps {
brand: ReactNode;
@@ -74,10 +74,11 @@ export function HeaderNavigation<T extends string>({ label, value, items, onChan
export interface HeaderProfileProps {
children: ReactNode;
ref?: Ref<HTMLDivElement>;
}
export function HeaderProfile({ children }: HeaderProfileProps) {
return <div className="nodedc-header__profile">{children}</div>;
export function HeaderProfile({ children, ref }: HeaderProfileProps) {
return <div ref={ref} className="nodedc-header__profile">{children}</div>;
}
export interface HeaderProfileButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className" | "style"> {}
@@ -0,0 +1,26 @@
import {createContext, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode} from "react";
import {createPortal} from "react-dom";
const FullscreenContext = createContext<{fullscreen:boolean; setFullscreen:(value:boolean)=>void} | null>(null);
/** Shared full-window presentation. Portaled inspectors remain above the panel. */
export const useApplicationPanelFullscreen = () => useContext(FullscreenContext);
export function ApplicationPanelFullscreen({children}: {children:ReactNode}) {
const [fullscreen,setFullscreen] = useState(false);
const [mount] = useState(() => typeof document === "undefined" ? null : document.createElement("div"));
const anchor = useRef<HTMLDivElement>(null);
const value = useMemo(() => ({fullscreen,setFullscreen}), [fullscreen]);
useLayoutEffect(() => {
if (!mount || !anchor.current) return;
anchor.current.append(mount);
return () => mount.remove();
}, [mount]);
useLayoutEffect(() => {
if (!mount || !anchor.current) return;
const target = (fullscreen ? document.body : anchor.current) as HTMLElement & {moveBefore?:(node:Node, before:Node|null)=>void};
if (mount.parentElement !== target) {
if (target.moveBefore) target.moveBefore(mount, null); else target.append(mount);
}
}, [fullscreen,mount]);
const content = <FullscreenContext.Provider value={value}><div className="nodedc-panel-viewport nodedc-ui-root" data-fullscreen={fullscreen || undefined}>{children}</div></FullscreenContext.Provider>;
return mount ? <><div ref={anchor} className="nodedc-panel-viewport-anchor"/>{createPortal(content,mount)}</> : content;
}
+6 -1
View File
@@ -1,5 +1,6 @@
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "./cn.js";
import {ApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
import { Icon, type IconName } from "./Icon.js";
export interface ApplicationShellProps extends Omit<HTMLAttributes<HTMLDivElement>, "content"> {
@@ -52,6 +53,8 @@ export interface ApplicationPanelProps extends Omit<HTMLAttributes<HTMLElement>,
title: ReactNode;
description?: ReactNode;
expanded?: boolean;
/** Enables full-window presentation requested by an owned viewer through context. */
allowFullscreen?: boolean;
expandLabel?: string;
closeLabel?: string;
onExpandedChange?: (expanded: boolean) => void;
@@ -76,6 +79,7 @@ export function ApplicationPanel({
title,
description,
expanded = false,
allowFullscreen = false,
expandLabel = "Развернуть окно",
closeLabel = "Закрыть окно",
onExpandedChange,
@@ -86,7 +90,7 @@ export function ApplicationPanel({
className,
...props
}: ApplicationPanelProps) {
return (
const panel = (
<section className={cn("nodedc-application-panel", className)} data-expanded={expanded ? "true" : undefined} {...props}>
<header className="nodedc-application-panel__head">
<div className="nodedc-application-panel__titles">
@@ -131,4 +135,5 @@ export function ApplicationPanel({
<div className="nodedc-application-panel__body">{children}</div>
</section>
);
return allowFullscreen ? <ApplicationPanelFullscreen>{panel}</ApplicationPanelFullscreen> : panel;
}
+22 -15
View File
@@ -3,7 +3,7 @@ import {DndContext, PointerSensor, useDraggable, useSensor, useSensors, type Dra
import {DragHandle} from "./DragDrop.js";
import {SplitPane} from "./SplitPane.js";
import {cn} from "./cn.js";
import {dockIds, dockPosition, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
import {dockIds, dockMoveAtPoint, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
const DockContext = createContext<{disabled: boolean; onKey: (id: string, event: KeyboardEvent<HTMLDivElement>) => void}>({disabled: true, onKey: () => {}});
/** The shared six-dot grip supports pointer dragging and keyboard docking. */
@@ -27,7 +27,7 @@ export interface DockLayoutProps {
/** Media stay in stable sibling hosts; only geometry changes, including focus. */
export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId, className, children}: DockLayoutProps) {
const host = useRef<HTMLDivElement>(null);
const host = useRef<HTMLDivElement>(null), viewport = useRef<HTMLDivElement>(null);
// React must not reorder these DOM siblings: moving an iframe node reloads
// its browsing context even when its key and portal content are unchanged.
const hostOrder = useRef<string[]>([]);
@@ -57,14 +57,19 @@ export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId,
const locate = (event: DragMoveEvent): DockMove | null => {
const start = event.activatorEvent as PointerEvent, box = host.current!.getBoundingClientRect();
const x = start.clientX + event.delta.x - box.left, y = start.clientY + event.delta.y - box.top;
for (const [id, rect] of Object.entries(rects)) {
const position = dockPosition(rect, x, y);
if (position && id !== String(event.active.id)) return {activeId: String(event.active.id), overId: id, position};
}
return null;
const view = viewport.current!, screen = view.getBoundingClientRect();
const visible = {left: screen.left + view.clientLeft - box.left, top: screen.top + view.clientTop - box.top,
width: view.clientWidth, height: view.clientHeight};
return dockMoveAtPoint(visible, rects, String(event.active.id), x, y);
};
// Preview and commit use the same content limits, including a newly enlarged canvas.
const projectMove = (move: DockMove | null) => {
const next = move && moveDockPanel(constrained, move), required = dockMinimum(next, minimums);
const area = {...bounds, width: Math.max(bounds.width, required.width), height: Math.max(bounds.height, required.height)};
return {tree: constrainDockTree(next, area, minimums), area};
};
const commit = (move: DockMove | null) => {
const next = move && moveDockPanel(constrained, move);
const next = projectMove(move).tree;
if (next) onTreeChange(next);
reset();
};
@@ -80,29 +85,31 @@ export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId,
const candidates = dockIds(visibleTree).filter(value => value !== active), index = candidates.indexOf(target?.overId ?? "");
setTarget({activeId: active!, overId: candidates[(index + (event.shiftKey ? -1 : 1) + candidates.length) % candidates.length], position: target?.position ?? "center"});
} else {
const position = ({ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const)[event.key as "ArrowLeft"];
const positions = {ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const;
const position = positions[event.key as keyof typeof positions];
if (!position || !target) return;
setTarget({...target, position});
setTarget({...target, position, scope: event.shiftKey && position !== "center" ? "workspace" : "panel"});
}
event.preventDefault(); event.stopPropagation();
};
const preview = target ? dockRects(moveDockPanel(constrained, target), canvas)[target.activeId] : null;
const projected = projectMove(target);
const preview = target ? dockRects(projected.tree, projected.area)[target.activeId] : null;
const action = target ? ({center: "Поменять местами", left: "Слева", right: "Справа", top: "Сверху", bottom: "Снизу"})[target.position] : "Выберите окно и край";
const label = target ? panels.find(panel => panel.id === target.overId)?.label : "";
const label = target?.scope === "workspace" ? "Вся область" : target ? panels.find(panel => panel.id === target.overId)?.label : "";
return <DndContext sensors={sensors} autoScroll={false}
onDragStart={event => {setActive(String(event.active.id)); setKeyboard(false);}}
onDragMove={event => setTarget(locate(event))}
onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
<DockContext.Provider value={{disabled, onKey}}>
<div className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
<div ref={viewport} className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
<div ref={host} className="nodedc-dock-layout__canvas" style={{minWidth:minimum.width, minHeight:minimum.height}}>
<DockSlots tree={constrained} bounds={canvas} minimums={minimums} onResize={(path, ratio) => {if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/>
{hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel => <div key={panel.id} className="nodedc-dock-layout__panel" data-dock-id={panel.id}
data-dock-source={active === panel.id ? "true" : undefined} style={rects[panel.id] ?? {display: "none"}}>{renderPanel(panel.id)}</div>)}
{active ? <div className="nodedc-dock-layout__overlay" aria-hidden="true">
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} style={preview}><span>{action} · {label}</span></div> : null}
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} data-dock-scope={target!.scope ?? "panel"} style={preview}><span>{action} · {label}</span></div> : null}
</div> : null}
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край окна, Shift+стрелки — край всей области, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
</div>
</div>
{children}
+18 -6
View File
@@ -1,7 +1,9 @@
import type { ReactNode } from "react";
import {createContext, useContext, useEffect, useRef, useState, type ReactNode} from "react";
import {createPortal} from "react-dom";
import {
closestCenter,
DndContext,
DragOverlay,
PointerSensor,
useDraggable,
useDroppable,
@@ -36,6 +38,8 @@ export interface DragDropResult {
overData?: NodedcDragData;
activeRect?: DragRect;
overRect?: DragRect;
/** Client coordinates of the pointer, for exact canvas/object drop targets. */
pointer?: {x:number;y:number};
}
const copyRect = (rect: DragRect | null | undefined): DragRect | undefined => rect ? ({
@@ -70,9 +74,15 @@ export function DragHandle({ label = "Перетащить", listeners, attribut
);
}
export function DragDropRoot({ children, onDragEnd }: { children: ReactNode; onDragEnd: (result: DragDropResult) => void }) {
const DragOverlayContext=createContext(false);
export function DragDropRoot({ children, onDragEnd, renderOverlay }: { children: ReactNode; onDragEnd: (result: DragDropResult) => void; renderOverlay?:(item:{id:string;data?:NodedcDragData})=>ReactNode }) {
const [active,setActive]=useState<{id:string;data?:NodedcDragData}|null>(null);
const dragging=useRef(false),pointer=useRef<{x:number;y:number}|undefined>(undefined);
useEffect(()=>{const track=(event:PointerEvent)=>{if(dragging.current)pointer.current={x:event.clientX,y:event.clientY};};window.addEventListener('pointermove',track,true);window.addEventListener('pointerup',track,true);return()=>{window.removeEventListener('pointermove',track,true);window.removeEventListener('pointerup',track,true);};},[]);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
const handleDragEnd = (event: DragEndEvent) => {
setActive(null);dragging.current=false;
const origin=event.activatorEvent as PointerEvent;
onDragEnd({
activeId: String(event.active.id),
overId: event.over ? String(event.over.id) : null,
@@ -80,25 +90,27 @@ export function DragDropRoot({ children, onDragEnd }: { children: ReactNode; onD
overData: event.over?.data.current as NodedcDragData | undefined,
activeRect: copyRect(event.active.rect.current.translated),
overRect: copyRect(event.over?.rect),
pointer: pointer.current??(typeof origin.clientX==='number'?{x:origin.clientX+event.delta.x,y:origin.clientY+event.delta.y}:undefined),
});
};
return <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>{children}</DndContext>;
return <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={event=>{dragging.current=true;pointer.current=undefined;setActive({id:String(event.active.id),data:event.active.data.current});}} onDragCancel={()=>{dragging.current=false;setActive(null);}} onDragEnd={handleDragEnd}><DragOverlayContext.Provider value={!!renderOverlay}>{children}</DragOverlayContext.Provider>{renderOverlay&&typeof document!=='undefined'&&createPortal(<DragOverlay dropAnimation={null} style={{pointerEvents:"none"}}>{active?renderOverlay(active):null}</DragOverlay>,document.fullscreenElement??document.body)}</DndContext>;
}
export function DraggableItem({ id, data, className, children }: {
id: string;
data?: NodedcDragData;
className?: string;
children: (state: { handle: ReactNode; isDragging: boolean }) => ReactNode;
children: (state: { handle: ReactNode; isDragging: boolean; activator: {attributes:ReturnType<typeof useDraggable>["attributes"];listeners:ReturnType<typeof useDraggable>["listeners"]} }) => ReactNode;
}) {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id, data });
const overlay=useContext(DragOverlayContext);
return (
<div
ref={setNodeRef}
className={cn(className, isDragging && "is-dragging")}
style={{ transform: CSS.Translate.toString(transform), opacity: isDragging ? 0.65 : undefined }}
style={{ transform: overlay?undefined:CSS.Translate.toString(transform), opacity: isDragging ? 0.65 : undefined }}
>
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging })}
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging, activator:{attributes,listeners} })}
</div>
);
}
+7
View File
@@ -126,6 +126,13 @@ export function Dropdown({
updatePosition();
}, [isOpen, updatePosition]);
useEffect(() => {
if (!isOpen || !surfaceRef.current) return;
const observer = new ResizeObserver(updatePosition);
observer.observe(surfaceRef.current);
return () => observer.disconnect();
}, [isOpen, updatePosition]);
useEffect(() => {
if (!isOpen || !getAnchorRect) return;
let frame:number;
+132
View File
@@ -0,0 +1,132 @@
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';
import {editorDockCorners} from './editorDockCorners.js';
export interface EditorDockTool {
id:string;title:ReactNode;label:string;open:boolean;onClose:()=>void;content:ReactNode;
subtitle?:ReactNode;actions?:ReactNode;footer?:ReactNode;className?:string;
minimumSize?:DockMinimum;initialRect?:DockRect;activationKey?:string|number;
}
export interface EditorDockLayoutProps {
value:EditorDockState;onChange:(value:EditorDockState)=>void;
primary:ReactNode;primaryId?:string;primaryMinimum?:DockMinimum;
tools:EditorDockTool[];enabled?:boolean;className?:string;
}
type Gesture={id:string;pointer:number;x:number;y:number;rect:DockRect;edge?:ResizeEdge;moved:boolean;current:DockRect;target:DockMove|null};
const actionNames={left:'Слева',right:'Справа',top:'Сверху',bottom:'Снизу',center:'Рядом'};
/** A locked primary renderer, docked tools and floating tools share stable sibling hosts. */
export function EditorDockLayout({value,onChange,primary,primaryId='viewport',primaryMinimum={width:320,height:240},tools,enabled=true,className}:EditorDockLayoutProps){
const host=useRef<HTMLDivElement>(null),viewport=useRef<HTMLDivElement>(null);
const [bounds,setBounds]=useState<DockRect>({left:0,top:0,width:1,height:1});
const [drag,setDrag]=useState<Gesture|null>(null),gesture=useRef<Gesture|null>(null);
const [order,setOrder]=useState<string[]>([]),[keyboard,setKeyboard]=useState<{id:string;target:DockMove|null}|null>(null);
const previousTools=useRef(new Map<string,{open:boolean;key?:string|number}>());
useEffect(()=>{
const raised=tools.filter(t=>t.open&&(!previousTools.current.get(t.id)?.open||previousTools.current.get(t.id)?.key!==t.activationKey)).map(t=>t.id);
previousTools.current=new Map(tools.map(t=>[t.id,{open:t.open,key:t.activationKey}]));
if(enabled&&raised.length)setOrder(v=>[...v.filter(id=>!raised.includes(id)),...raised]);
});
const visible=[primaryId,...tools.filter(t=>enabled&&t.open).map(t=>t.id)];
const minimums={...Object.fromEntries(tools.map(t=>[t.id,t.minimumSize??{width:280,height:180}])),[primaryId]:primaryMinimum};
const visibleTree=pruneDockTree(value.tree,visible)??{id:primaryId};
const required=dockMinimum(visibleTree,minimums),area={...bounds,width:Math.max(bounds.width,required.width),height:Math.max(bounds.height,required.height)};
const constrained=constrainDockTree(visibleTree,area,minimums)!;
const rects=dockRects(constrained,area);
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds,tools.find(t=>t.id===id)?.minimumSize);
const latest=useRef({value,onChange,rects,bounds,enabled,tools});latest.current={value,onChange,rects,bounds,enabled,tools};
const activate=(id:string)=>setOrder(v=>[...v.filter(x=>x!==id),id]);
useLayoutEffect(()=>{const v=viewport.current!;const measure=()=>setBounds({left:0,top:0,width:v.clientWidth,height:v.clientHeight});measure();const ro=new ResizeObserver(measure);ro.observe(v);return()=>ro.disconnect();},[]);
const point=(e:{clientX:number;clientY:number})=>{const r=host.current!.getBoundingClientRect();return {x:e.clientX-r.left,y:e.clientY-r.top};};
const begin=(id:string,e:PointerEvent<HTMLElement>,edge?:ResizeEdge)=>{
if(!enabled||e.button!==0||gesture.current||(!edge&&(e.target as HTMLElement).closest('button,input,select,textarea,a,[role=slider]')))return;
const p=point(e),docked=rects[id],saved=floatingRect(id);
const rect=docked?{...saved,left:p.x-Math.min(saved.width-24,Math.max(24,p.x-docked.left)),top:p.y-Math.min(48,p.y-docked.top)}:saved;
gesture.current={id,pointer:e.pointerId,x:p.x,y:p.y,rect,edge,moved:false,current:rect,target:null};
e.currentTarget.setPointerCapture(e.pointerId);e.currentTarget.focus();activate(id);setKeyboard(null);e.preventDefault();e.stopPropagation();
};
useEffect(()=>{
const move=(e:globalThis.PointerEvent)=>{
const g=gesture.current;if(!g||e.pointerId!==g.pointer)return;
const p=point(e),dx=p.x-g.x,dy=p.y-g.y;
if(!g.moved&&Math.hypot(dx,dy)<6)return;
g.moved=true;
const b=latest.current.bounds,minimum=latest.current.tools.find(t=>t.id===g.id)?.minimumSize;
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b,minimum):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b,minimum);
const visibleBounds={...b,left:viewport.current?.scrollLeft??0,top:viewport.current?.scrollTop??0};
g.target=g.edge?null:editorDockTarget(visibleBounds,latest.current.rects,primaryId,g.id,p.x,p.y);
setDrag({...g});e.preventDefault();
};
const finish=(e:globalThis.PointerEvent)=>{
const g=gesture.current;if(!g||g.pointer!==e.pointerId)return;
if(e.type==='pointerup'&&g.moved){const v=latest.current;v.onChange(g.edge?{...v.value,floating:{...v.value.floating,[g.id]:g.current}}:dockEditorTool(v.value,primaryId,g.target,g.id,g.current));}
gesture.current=null;setDrag(null);
};
const cancel=(e:globalThis.KeyboardEvent)=>{if(e.key==='Escape'&&gesture.current){gesture.current=null;setDrag(null);e.preventDefault();e.stopPropagation();}};
const blur=()=>{gesture.current=null;setDrag(null);};
window.addEventListener('pointermove',move,{passive:false});window.addEventListener('pointerup',finish);window.addEventListener('pointercancel',finish);window.addEventListener('keydown',cancel,true);window.addEventListener('blur',blur);
return()=>{window.removeEventListener('pointermove',move);window.removeEventListener('pointerup',finish);window.removeEventListener('pointercancel',finish);window.removeEventListener('keydown',cancel,true);window.removeEventListener('blur',blur);};
},[primaryId]);
useEffect(()=>{if(!enabled||!tools.some(t=>t.open&&t.id===(gesture.current?.id??keyboard?.id))){gesture.current=null;setDrag(null);setKeyboard(null);}},[enabled,tools.map(t=>`${t.id}:${t.open}`).join('|')]);
const key=(id:string,e:KeyboardEvent<HTMLElement>)=>{
if(e.target!==e.currentTarget)return;
const positions={ArrowLeft:'left',ArrowRight:'right',ArrowUp:'top',ArrowDown:'bottom'} as const,position=positions[e.key as keyof typeof positions];
if(keyboard?.id===id){
if(e.key==='Escape')setKeyboard(null);
else if(e.key==='Enter'||e.key===' '){onChange(dockEditorTool(value,primaryId,keyboard.target,id,floatingRect(id)));setKeyboard(null);}
else if(e.key==='Home')setKeyboard({id,target:null});
else if(e.key==='Tab'){const candidates=Object.keys(rects).filter(x=>x!==id&&x!==primaryId);if(candidates.length){const index=candidates.indexOf(keyboard.target?.overId??'');setKeyboard({id,target:{activeId:id,overId:candidates[(index+(e.shiftKey?-1:1)+candidates.length)%candidates.length],position:keyboard.target?.position??'right',scope:'panel'}});}}
else if(position)setKeyboard({id,target:{activeId:id,overId:keyboard.target?.overId??primaryId,position,scope:e.shiftKey||!keyboard.target?'workspace':keyboard.target.scope}});
else return;
}else if(e.key==='Enter'||e.key===' '){setKeyboard({id,target:null});activate(id);}
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds,tools.find(t=>t.id===id)?.minimumSize):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds,tools.find(t=>t.id===id)?.minimumSize)}});}
else return;
e.preventDefault();e.stopPropagation();
};
const target=drag?.target??keyboard?.target,active=drag?.id??keyboard?.id;
const projected=target&&active?dockEditorTool(value,primaryId,target,active,drag?.current??floatingRect(active)):null;
const previewTree=projected?pruneDockTree(projected.tree,visible):null,previewMinimum=dockMinimum(previewTree,minimums);
const previewArea={...bounds,width:Math.max(bounds.width,previewMinimum.width),height:Math.max(bounds.height,previewMinimum.height)};
const preview=active&&previewTree?dockRects(constrainDockTree(previewTree,previewArea,minimums),previewArea)[active]:null;
const announcement=active?`${target?`${actionNames[target.position]} · ${target.scope==='workspace'?'вся область':tools.find(t=>t.id===target.overId)?.label}`:'Свободное окно'}. Стрелки — край, Shift+стрелки — вся область, Tab — панель, Home — свободно, Enter — применить, Escape — отменить.`:'';
return <div ref={viewport} className={cn('nodedc-editor-dock',className)} data-editing={enabled||undefined} data-dragging={!!drag||undefined}>
<div ref={host} className="nodedc-editor-dock__canvas" style={{minWidth:required.width,minHeight:required.height}}>
<EditorSplits tree={constrained} bounds={area} minimums={minimums} onResize={(path,ratio)=>onChange({...value,tree:mergeEditorDockRatios(value.tree,resizeDockSplit(constrained,path,ratio))})}/>
<div className="nodedc-editor-dock__primary" data-editor-primary={primaryId} data-dock-corners={editorDockCorners(rects[primaryId],area)} style={rects[primaryId]}>{primary}</div>
{tools.map(tool=>{
const moving=drag?.id===tool.id,free=!rects[tool.id]||moving;
const rect=moving?drag.current:rects[tool.id]??floatingRect(tool.id);
return <div key={tool.id} className={cn('nodedc-editor-dock__tool nodedc-glass-material nodedc-ui-root',tool.className)} data-editor-tool={tool.id} data-floating={free||undefined} data-glass-context={free?'scene':undefined} data-dock-corners={free?undefined:editorDockCorners(rect,area)} data-active={order.at(-1)===tool.id||undefined}
role="region" aria-label={tool.label} hidden={!enabled||!tool.open} style={{...rect,zIndex:moving?40:free?10+Math.max(0,order.indexOf(tool.id)):1}}
onPointerDownCapture={()=>activate(tool.id)} onFocusCapture={()=>activate(tool.id)}>
<header className="nodedc-window__head" tabIndex={0} aria-label={`Переместить · ${tool.label}`} aria-roledescription="Перемещаемая панель" onPointerDown={e=>begin(tool.id,e)} onKeyDown={e=>key(tool.id,e)}>
<div className="nodedc-window__titles"><h2 className="nodedc-window__title">{tool.title}</h2>{tool.subtitle&&<p className="nodedc-window__subtitle">{tool.subtitle}</p>}</div>
<div className="nodedc-window__actions">{tool.actions}<IconButton label={`Закрыть · ${tool.label}`} onClick={tool.onClose}><Icon name="close"/></IconButton></div>
</header>
<InspectorSelectPolicyContext.Provider value={false}><LoadingContext.Provider value={null}>
<div className="nodedc-window__body nodedc-editor-dock__body">{tool.content}</div>
{tool.footer&&<footer className="nodedc-window__footer">{tool.footer}</footer>}
</LoadingContext.Provider></InspectorSelectPolicyContext.Provider>
{free&&windowResizeEdges.map(edge=><div key={edge} className="nodedc-window__resize" data-edge={edge} aria-hidden="true" onPointerDown={e=>begin(tool.id,e,edge)}/>)}
</div>;
})}
{drag&&<div className="nodedc-editor-dock__shield"/>}
{preview&&<div className="nodedc-dock-layout__preview nodedc-editor-dock__preview" style={preview} aria-hidden="true"><span>{target&&actionNames[target.position]}</span></div>}
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{announcement}</div>
</div>
</div>;
}
function EditorSplits({tree,bounds,minimums,onResize,path=''}:{tree:DockTree;bounds:DockMinimum;minimums:Record<string,DockMinimum>;onResize:(path:string,ratio:number)=>void;path?:string}){
if('id' in tree)return null;
const k=tree.axis==='x'?'width':'height',span=bounds[k];
return <SplitPane className="nodedc-dock-layout__split" separatorAppearance="invisible" orientation={tree.axis==='x'?'vertical':'horizontal'} primarySize={tree.ratio}
minPrimarySize={span?dockMinimum(tree.first,minimums)[k]/span*100:0} minSecondarySize={span?dockMinimum(tree.second,minimums)[k]/span*100:0} onPrimarySizeChange={ratio=>onResize(path,ratio)} separatorLabel="Изменить размеры панелей редактора"
primary={<EditorSplits tree={tree.first} bounds={{...bounds,[k]:span*tree.ratio/100}} minimums={minimums} onResize={onResize} path={path+'0'}/>}
secondary={<EditorSplits tree={tree.second} bounds={{...bounds,[k]:span*(1-tree.ratio/100)}} minimums={minimums} onResize={onResize} path={path+'1'}/>}/>;
}
+40
View File
@@ -0,0 +1,40 @@
import {useContext,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 {WindowSuspensionContext} from './WindowSuspensionContext.js';
import {cn} from './cn.js';
export interface EditorWorkspaceProps {editing:boolean;title:ReactNode;subtitle?:ReactNode;onBack:()=>void;children:ReactNode;className?:string;purpose?:'edit'|'view';headerActions?:ReactNode}
/** One mounted renderer moves between its original slot and a modeless editor window. */
export function EditorWorkspace({editing,title,subtitle,onBack,children,className,purpose='edit',headerActions}:EditorWorkspaceProps){
const suspend=useContext(WindowSuspensionContext);
useLayoutEffect(()=>{if(editing)return suspend?.();},[editing,suspend]);
const inline=useRef<HTMLDivElement>(null),[host]=useState(()=>document.createElement('div'));
const [expanded,setExpanded]=useState(false),opener=useRef<HTMLElement|null>(null),titleId=useId();
useLayoutEffect(()=>{host.className='nodedc-editor-workspace__host';inline.current!.append(host);return()=>host.remove();},[host]);
useLayoutEffect(()=>{
const target=(editing?(document.fullscreenElement??document.body):inline.current!) as HTMLElement&{moveBefore?:(node:Node,before:Node|null)=>void};
if(editing)opener.current=document.activeElement instanceof HTMLElement?document.activeElement:null;
if(host.parentElement!==target){if(target.moveBefore&&host.isConnected)target.moveBefore(host,null);else target.append(host);}
host.dataset.editing=String(editing);
if(editing)host.querySelector<HTMLElement>('[data-editor-back]')?.focus({preventScroll:true});
else {setExpanded(false);const frame=requestAnimationFrame(()=>{if(opener.current?.isConnected)opener.current.focus({preventScroll:true});});return()=>cancelAnimationFrame(frame);}
},[editing,host]);
useEffect(()=>{host.dataset.expanded=String(expanded);},[expanded,host]);
return <div ref={inline} className={cn('nodedc-editor-workspace__slot',className)}>{createPortal(
<div className="nodedc-editor-workspace nodedc-ui-root" data-editing={editing||undefined} role={editing?'dialog':undefined} aria-modal={editing?'false':undefined} aria-labelledby={editing?titleId:undefined}
onKeyDown={event=>{if(!editing||event.key!=='Escape'||event.defaultPrevented)return;const dialog=(event.target as HTMLElement).closest('[role=dialog]');if(dialog!==event.currentTarget)return;event.preventDefault();event.stopPropagation();if(expanded)setExpanded(false);else onBack();}}>
{editing&&<header className="nodedc-window__head nodedc-editor-workspace__head">
<div className="nodedc-window__titles"><h1 id={titleId} className="nodedc-window__title">{title}</h1>{subtitle&&<p className="nodedc-window__subtitle">{subtitle}</p>}</div>
<div className="nodedc-window__actions">
{headerActions}
<IconButton data-editor-back label={purpose==='view'?'Вернуть просмотр в рабочую область':'Вернуться из редактора сцены'} onClick={onBack}><Icon name="chevron-left"/></IconButton>
<IconButton label={expanded?(purpose==='view'?'Восстановить окно просмотра':'Восстановить окно редактора'):(purpose==='view'?'Развернуть окно просмотра':'Развернуть окно редактора')} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton>
{purpose==='edit'&&<IconButton label="Завершить редактирование сцены" aria-pressed onClick={onBack}><Icon name="edit"/></IconButton>}
<IconButton label={purpose==='view'?'Закрыть отдельное окно просмотра':'Закрыть редактор сцены'} onClick={onBack}><Icon name="close"/></IconButton>
</div>
</header>}
<div className="nodedc-editor-workspace__body">{children}</div>
</div>,host)}</div>;
}
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import {
Button,
FeatureSettingsWindow,
@@ -18,9 +18,12 @@ import {
type EnvironmentSurface,
type UploadedEnvironmentMedia,
} from "@nodedc/ui-core";
import type { FeatureSettingsSection } from "./FeatureSettingsWindow.js";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor.js";
export interface EnvironmentSettingsWindowProps {
/** Product-owned sections reuse this shell; each owns its content and save lifecycle. */
additionalSections?: readonly (FeatureSettingsSection & { content: ReactNode; footer?: ReactNode })[];
productName: string;
surfaces: readonly EnvironmentSurface[];
initialSurfaceId?: string;
@@ -70,6 +73,7 @@ function patchBackground(
export function EnvironmentSettingsWindow({
productName,
additionalSections = [],
surfaces,
initialSurfaceId,
open,
@@ -80,6 +84,8 @@ export function EnvironmentSettingsWindow({
onSave,
onUpload,
}: EnvironmentSettingsWindowProps) {
const [activeSection, setActiveSection] = useState("environment");
const extension = additionalSections.find(section => section.id === activeSection);
const [draft, setDraft] = useState(() => cloneEnvironmentSettings(settings));
const [surfaceId, setSurfaceId] = useState(initialSurfaceId ?? surfaces[0]?.id ?? "home");
const [uploading, setUploading] = useState(false);
@@ -196,11 +202,12 @@ export function EnvironmentSettingsWindow({
group: productName.toUpperCase(),
icon: "settings",
},
...additionalSections,
]}
activeSection="environment"
onSectionChange={() => undefined}
activeSection={extension ? activeSection : "environment"}
onSectionChange={setActiveSection}
onClose={onClose}
footer={(
footer={extension ? extension.footer : (
<WindowFooterActions>
<Button
variant="secondary"
@@ -223,7 +230,7 @@ export function EnvironmentSettingsWindow({
</WindowFooterActions>
)}
>
<div className="nodedc-environment-settings">
{extension ? extension.content : <div className="nodedc-environment-settings">
<SettingsCard
eyebrow="ОКРУЖЕНИЕ"
title="Основные элементы управления"
@@ -349,7 +356,7 @@ export function EnvironmentSettingsWindow({
/>
</div>
</SettingsCard>
</div>
</div>}
</FeatureSettingsWindow>
);
}
+12 -5
View File
@@ -1,7 +1,8 @@
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";
export type GlassTone = "default" | "strong" | "soft" | "group";
export type GlassRadius = "card" | "panel" | "modal" | "pill";
export type GlassPadding = "none" | "sm" | "md" | "lg";
@@ -37,11 +38,17 @@ export function GlassSurface({
export interface GlassMaterialSurfaceProps extends HTMLAttributes<HTMLDivElement> {
children: ReactNode;
/** Scene telemetry uses the translucent V4 material, independent of modal density. */
context?: "floating" | "scene";
radius?: GlassRadius;
/** Per-instance appearance; never changes the global theme or other surfaces. */
material?: GlassMaterialSettings;
radiusPx?: number;
}
/** Canonical modal/Inspector material. General application panels must not use it. */
export function GlassMaterialSurface({ children, className, ...props }: GlassMaterialSurfaceProps) {
return <div className={cn("nodedc-glass-material", className)} {...props}>{children}</div>;
/** Canonical floating/scene-overlay material. Ordinary application panels stay matte. */
export function GlassMaterialSurface({ children, className, context = "floating", radius = "modal", material, radiusPx, style, ...props }: GlassMaterialSurfaceProps) {
return <div className={cn("nodedc-glass-material", className)} data-glass-context={context} data-radius={radius} style={{ ...material && createGlassMaterialVariables(material, context), ...Number.isFinite(radiusPx) && {borderRadius: Math.max(0, Math.min(120, radiusPx!))}, ...style } as CSSProperties} {...props}>{children}</div>;
}
export interface MapGlassSurfaceProps extends HTMLAttributes<HTMLDivElement> {
+31 -2
View File
@@ -1,5 +1,10 @@
import {
MousePointer2,
Pipette,
createLucideIcon,
Glasses,
Cuboid,
Move,
CirclePlus,
Box,
Scan,
@@ -46,7 +51,10 @@ import {
PanelTop,
Pencil,
Play,
Pin,
Power,
Plus,
Minus,
RefreshCw,
RotateCw,
Save,
@@ -66,11 +74,28 @@ import {
type LucideProps,
} from "lucide-react";
// CAD vocabulary: dimension line, cutting plane and unframed information glyph.
const DimensionLine = createLucideIcon('DimensionLine', [
['path', {d:'M4 5v14M20 5v14M4 12h16M8 9l-4 3 4 3M16 9l4 3-4 3',key:'dimension'}],
]);
const SectionPlane = createLucideIcon('SectionPlane', [
['path', {d:'m5 7 7-4 7 4v10l-7 4-7-4V7m0 0 7 4 7-4M12 11v10',key:'model'}],
['path', {d:'m2 12 10-5 10 5-10 5-10-5Z',key:'plane'}],
]);
const InformationPlain = createLucideIcon('InformationPlain', [
['path', {d:'M12 4h.01M10 9h2v11M9 20h6',key:'information'}],
]);
const icons = {
pipette: Pipette,
"add-point": CirclePlus,
perspective: Box,
orthographic: Scan,
ruler: DimensionLine,
section: SectionPlane,
isolate: Glasses,
perspective: Cuboid,
orthographic: Box,
"fit-view": Scan,
select: MousePointer2,
move: Move,
pen: PenTool,
rectangle: RectangleHorizontal,
curve: Spline,
@@ -91,6 +116,7 @@ const icons = {
close: X,
copy: Copy,
database: Database,
pin: Pin,
download: Download,
edit: Pencil,
eye: Eye,
@@ -104,6 +130,7 @@ const icons = {
image: Image,
inbox: Inbox,
info: Info,
"info-plain": InformationPlain,
key: KeyRound,
layers: Layers,
list: ListChecks,
@@ -115,7 +142,9 @@ const icons = {
panel: PanelTop,
plan: Map,
play: Play,
power: Power,
plus: Plus,
minus: Minus,
profile: UserCircle,
refresh: RefreshCw,
"rotate-clockwise": RotateCw,
+7
View File
@@ -19,6 +19,9 @@ export interface InspectorSectionSpec {
export interface InspectorProps {
sections: InspectorSectionSpec[];
/** Spaced form fields above sections and centered actions below them. */
header?: ReactNode;
footer?: ReactNode;
defaultOpen?: string[];
openSections?: string[];
activeId?: string;
@@ -31,6 +34,8 @@ export interface InspectorProps {
export function Inspector({
sections,
header,
footer,
defaultOpen = [],
openSections,
activeId,
@@ -70,6 +75,7 @@ export function Inspector({
return (
<InspectorSelectPolicyContext.Provider value>
<div className={cn("nodedc-inspector", className)} data-variant={variant === "default" ? undefined : variant}>
{header ? <div className="nodedc-inspector__header">{header}</div> : null}
{groups.map((group, groupIndex) => (
<div className="nodedc-inspector__group" key={`${group.label ?? "root"}-${groupIndex}`}>
{group.sections.map((section) => {
@@ -107,6 +113,7 @@ export function Inspector({
})}
</div>
))}
{footer ? <div className="nodedc-inspector__footer">{footer}</div> : null}
</div>
</InspectorSelectPolicyContext.Provider>
);
+30
View File
@@ -0,0 +1,30 @@
import {levelButtonGeometry,type LevelButtonGeometry} from './levelButtonGeometry.js';
export type {LevelButtonGeometry} from './levelButtonGeometry.js';
import type {CSSProperties} from 'react';
import {Button,type ButtonProps} from './Button.js';
import {cn} from './cn.js';
export interface LevelButtonProps extends Omit<ButtonProps,'children'|'shape'|'value'> {
label:string;
/** Optional operator geometry; text and padding shrink together below 64 × 24. */
geometry?:LevelButtonGeometry;
/** Measured fraction. Missing is unknown, never zero or animated progress. */
value?:number|null;
valueText?:string;
freshness?:'live'|'stale'|'unknown';
levelTone?:'neutral'|'success'|'warning'|'danger';
/** Explicit operator-selected fill; labels retain contrast over both parts. */
fillColor?:string;
}
/** Compact measured resource level which opens details, with native button semantics. */
export function LevelButton({label,value,valueText,freshness='live',levelTone='neutral',fillColor,geometry,className,style,...props}:LevelButtonProps){
const fraction=typeof value==='number'&&Number.isFinite(value)?Math.max(0,Math.min(1,value)):null;
const custom=typeof fillColor==='string'&&/^#[0-9a-f]{6}$/i.test(fillColor)?fillColor:null;
const channels=custom?.slice(1).match(/../g)?.map(v=>{const c=parseInt(v,16)/255;return c<=.04045?c/12.92:((c+.055)/1.055)**2.4;});
const ink=channels&&(.2126*channels[0]+.7152*channels[1]+.0722*channels[2])>.179?'#000000':'#ffffff';
const text=valueText??(fraction===null?'—':`${Math.round(fraction*100)}%`);
return <Button {...props} shape="pill" className={cn('nodedc-level-button',className)}
aria-label={`${label}: ${text}${freshness==='stale'?' · последние показания':''}`}
data-level-tone={levelTone} data-freshness={freshness} data-custom-fill={custom?true:undefined}
style={{...style,...levelButtonGeometry(geometry,text.length),'--nodedc-level-percent':`${(fraction??0)*100}%`,...(custom?{'--nodedc-level-custom':custom,'--nodedc-level-ink':ink}:{})} as CSSProperties}><span aria-hidden="true">{text}</span>{custom&&fraction!==null&&<span aria-hidden="true" className="nodedc-level-button__fill">{text}</span>}</Button>;
}
+3 -3
View File
@@ -4,7 +4,7 @@ export interface NavigationCubeProps {
/** Camera world quaternion, Y up. Directions point from target toward camera. */
quaternion: readonly [number,number,number,number];
onSelect: (direction:CubeDirection)=>void;
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number;
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number; faceOpacity?:number;
disabled?:boolean;
label?:string;
}
@@ -42,9 +42,9 @@ export function cubeRegions(quaternion:NavigationCubeProps["quaternion"]) {
});
}
/** BIM-style face / edge / corner navigation, independent of the scene engine. */
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1}:NavigationCubeProps) {
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1,faceOpacity=1}:NavigationCubeProps) {
const [hover,setHover]=useState<string|null>(null);
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-face-opacity":faceOpacity,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
{cubeRegions(quaternion).map(r=><g key={r.id} role="button" aria-label={`Ракурс: ${r.label}`} aria-disabled={disabled}
tabIndex={disabled?-1:0} className={hover===r.label?"is-hovered":""}
onPointerEnter={()=>setHover(r.label)} onPointerLeave={()=>setHover(null)}
+68 -4
View File
@@ -3,10 +3,16 @@ import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBa
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
import { cn } from "./cn.js";
import { Dropdown } from "./Dropdown.js";
import { Button } from "./Button.js";
import { Icon } from "./Icon.js";
import { Description } from "./Description.js";
import { screenColorPicker } from "./screenColorPicker.js";
export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> {
label: string;
orientation?: "horizontal" | "vertical";
/** Thin horizontal single-value rail; no containing surface or exact editor. */
variant?: "field" | "rail";
value: number;
min: number;
max: number;
@@ -69,6 +75,7 @@ export function RangeControl(props: RangeControlProps | RangeBandControlProps) {
function SingleRangeControl({
label,
orientation = "horizontal",
variant = "field",
value,
min,
max,
@@ -102,6 +109,10 @@ function SingleRangeControl({
"--nodedc-range-editor-characters": editorCharacters,
} as CSSProperties;
// External undo/redo owns the controlled value even while the exact editor is focused.
// Otherwise its next blur would commit an obsolete draft over the restored value.
useLayoutEffect(() => setDraft(editableNumber(value)), [value]);
useEffect(() => {
if (!editing) setDraft(editableNumber(value));
}, [editing, value]);
@@ -151,6 +162,17 @@ function SingleRangeControl({
}
};
if (orientation === "horizontal" && variant === "rail") return (
<div className={cn("nodedc-range-rail", className)} data-disabled={disabled || undefined}>
<span className="nodedc-range-rail__value" aria-hidden="true">{displayValue}</span>
<div ref={rootRef} className="nodedc-range" style={style} data-variant="rail">
<input ref={rangeRef} {...props} type="range" value={value} min={min} max={safeMax} step={step}
disabled={disabled} tabIndex={tabIndex} aria-label={label} aria-orientation="horizontal"
aria-valuetext={displayValue} onChange={event => onChange(Number(event.target.value))}/>
</div>
</div>
);
if (orientation === "vertical") return (
<div className="nodedc-range-scale" data-limit-side={limitSide} style={style}>
<div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical">
@@ -271,7 +293,29 @@ function hsvToHex({ h, s, v }: Hsv): string {
return `#${base.map((channel) => Math.round((channel + offset) * 255).toString(16).padStart(2, "0")).join("")}`;
}
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, ...props }: ColorFieldProps) {
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, onBlur, onKeyDown, ...props }: ColorFieldProps) {
const [draft, setDraft] = useState(value);
const [paletteOpen, setPaletteOpen] = useState(false), [picking, setPicking] = useState(false), [pickError, setPickError] = useState(false);
const nativePicker = useRef<HTMLInputElement>(null), sampling = useRef<AbortController | null>(null);
const screenPicker = screenColorPicker();
useEffect(() => () => { sampling.current?.abort(); }, []);
useEffect(() => { if (disabled || !paletteOpen) { sampling.current?.abort(); sampling.current = null; setPicking(false); } }, [disabled, paletteOpen]);
useEffect(() => setDraft(value), [value]);
const sampleScreen = async () => {
if (disabled || sampling.current) return;
setPickError(false);
if (!screenPicker) { nativePicker.current?.click(); return; }
const controller = new AbortController(); sampling.current = controller; setPicking(true);
try {
// open() executes synchronously in this trusted click before the first await.
const result = await new screenPicker().open({ signal: controller.signal });
if (!controller.signal.aborted && parseHexColor(result.sRGBHex)) { setDraft(result.sRGBHex.toLowerCase()); onChange(result.sRGBHex.toLowerCase()); }
} catch (error) {
if (!controller.signal.aborted && !(error instanceof Error && error.name === 'AbortError')) setPickError(true);
} finally {
if (!controller.signal.aborted) { setPicking(false); sampling.current = null; }
}
};
const validColor = hexToHsv(value);
const [hsv, setHsv] = useState<Hsv>(() => validColor ?? { h: 330, s: 82, v: 100 });
const style = { "--nodedc-color-value": validColor ? hsvToHex(validColor) : hsvToHex(hsv) } as CSSProperties;
@@ -283,6 +327,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
const commit = (next: Hsv) => {
const normalized = { h: clamp(next.h, 0, 360), s: clamp(next.s, 0, 100), v: clamp(next.v, 0, 100) };
setHsv(normalized);
setDraft(hsvToHex(normalized));
onChange(hsvToHex(normalized));
};
@@ -295,6 +340,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
<div className={cn("nodedc-color-field", className)} style={style}>
<Dropdown
className="nodedc-color-field__dropdown"
onOpenChange={setPaletteOpen}
placement="bottom-start"
minWidth={296}
width={296}
@@ -347,6 +393,10 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
<span>Оттенок</span>
<input type="range" min={0} max={360} value={Math.round(hsv.h)} aria-label={`${label}: оттенок`} disabled={disabled} onChange={(event) => commit({ ...hsv, h: Number(event.target.value) })} />
</label>
<Button width="full" icon={<Icon name="pipette"/>} disabled={disabled} loading={picking} onClick={() => void sampleScreen()} title={screenPicker ? 'Выбрать цвет в любой точке экрана; Escape — отменить' : 'В этом браузере выбор цвета с экрана доступен через системную палитру, если она поддерживает пипетку'}>
{screenPicker ? 'Цвет с экрана' : 'Системная палитра'}
</Button>
{pickError && <Description role="status">Не удалось включить пипетку. Повторите попытку.</Description>}
<div className="nodedc-color-palette__presets" aria-label="Быстрые цвета">
{palettePresets.map((preset) => (
<button
@@ -364,14 +414,28 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
</div>
</div>
</Dropdown>
<input ref={nativePicker} type="color" hidden tabIndex={-1} aria-hidden="true" disabled={disabled} value={validColor ? hsvToHex(validColor) : '#000000'} onChange={event => { setDraft(event.target.value); onChange(event.target.value); }}/>
<input
className="nodedc-color-field__text"
value={value}
{...props}
value={draft}
aria-label={`${label}: HEX`}
disabled={disabled}
spellCheck={false}
onChange={(event) => onChange(event.target.value)}
{...props}
onChange={(event) => {
const text = event.target.value;
setDraft(text);
if (parseHexColor(text)) onChange(`#${text.trim().replace(/^#/, "").toLowerCase()}`);
}}
onBlur={(event) => {
setDraft(parseHexColor(draft) ? `#${draft.trim().replace(/^#/, "").toLowerCase()}` : value);
onBlur?.(event);
}}
onKeyDown={(event) => {
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setDraft(value); }
if (event.key === "Enter") { event.preventDefault(); event.currentTarget.blur(); }
onKeyDown?.(event);
}}
/>
</div>
);
@@ -0,0 +1,47 @@
import {useRef, type HTMLAttributes, type ReactNode} from "react";
import {cn} from "./cn.js";
export interface ResizableViewportProps extends Omit<HTMLAttributes<HTMLDivElement>, "children" | "onChange"> {
children: ReactNode;
height: number;
minHeight?: number;
maxHeight?: number;
onHeightChange: (height: number) => void;
onHeightCommit?: (height: number) => void;
resizeLabel?: string;
resizeIndicator?: boolean;
}
/** In-flow viewer with height-only corner grips. Persistence belongs to its owner. */
export function ResizableViewport({children, height, minHeight = 360, maxHeight = 2160, onHeightChange, onHeightCommit, resizeLabel = "Высота 3D-окна", resizeIndicator = true, className, style, ...props}: ResizableViewportProps) {
const drag = useRef<{id:number; y:number; height:number; current:number} | null>(null);
const fit = (value:number) => Math.round(Math.max(minHeight, Math.min(maxHeight, value)));
const current = fit(height);
return <div {...props} data-resize-indicator={resizeIndicator ? undefined : "hidden"} className={cn("nodedc-resizable-viewport", className)} style={{...style, height:current}}>
{children}
{(["start", "end"] as const).map(corner => <div key={corner} className="nodedc-resizable-viewport__grip" data-corner={corner}
role="separator" aria-orientation="horizontal" tabIndex={0} aria-label={`${resizeLabel} · ${corner === "start" ? "левый угол" : "правый угол"}`}
aria-valuenow={current} aria-valuemin={minHeight} aria-valuemax={maxHeight} aria-valuetext={`${current} px`}
onPointerDown={event => {
if (event.button !== 0 || drag.current) return;
event.preventDefault(); event.stopPropagation(); event.currentTarget.setPointerCapture(event.pointerId);
drag.current = {id:event.pointerId, y:event.clientY, height:current, current};
}}
onPointerMove={event => {
const gesture = drag.current;
if (!gesture || event.pointerId !== gesture.id) return;
event.preventDefault(); event.stopPropagation();
gesture.current = fit(gesture.height + event.clientY - gesture.y); onHeightChange(gesture.current);
}}
onPointerUp={event => {
const gesture = drag.current; if (!gesture || event.pointerId !== gesture.id) return;
event.stopPropagation(); drag.current = null; event.currentTarget.releasePointerCapture(event.pointerId); onHeightCommit?.(gesture.current);
}}
onLostPointerCapture={() => {const gesture = drag.current; drag.current = null; if (gesture) onHeightCommit?.(gesture.current);}}
onKeyDown={event => {
const step = event.shiftKey ? 50 : 10;
const next = event.key === "ArrowUp" ? current - step : event.key === "ArrowDown" ? current + step : event.key === "Home" ? minHeight : event.key === "End" ? maxHeight : null;
if (next === null) return;
event.preventDefault(); event.stopPropagation(); const value = fit(next); onHeightChange(value); onHeightCommit?.(value);
}}/>) }
</div>;
}
@@ -0,0 +1,7 @@
import {forwardRef} from "react";
import {Button,type ButtonProps} from "./Button.js";
import {cn} from "./cn.js";
/** Screen-projected data anchored to a real scene object; coordinates belong to the renderer. */
export const SceneAnnotation=forwardRef<HTMLButtonElement,ButtonProps>(function SceneAnnotation({className,...props},ref){
return <Button {...props} ref={ref} variant="ghost" size="dense" className={cn("nodedc-scene-annotation",className)}/>;
});
+4 -1
View File
@@ -29,6 +29,8 @@ export interface SelectProps<T extends string> {
menuWidth?: number | "anchor";
disabled?: boolean;
variant?: SelectVariant;
/** Split site/workspace selectors can align with adjacent circular actions. */
shape?: "default" | "pill";
className?: string;
triggerClassName?: string;
menuClassName?: string;
@@ -47,6 +49,7 @@ export function Select<T extends string>({
menuWidth = "anchor",
disabled = false,
variant = "integrated",
shape = "default",
className,
triggerClassName,
menuClassName,
@@ -88,7 +91,7 @@ export function Select<T extends string>({
};
if (resolvedVariant === "split") {
return (
<div className={cn("nodedc-select", triggerClassName)} data-disabled={disabled ? "true" : undefined}>
<div className={cn("nodedc-select", triggerClassName)} data-shape={shape === "pill" ? "pill" : undefined} data-disabled={disabled ? "true" : undefined}>
<div ref={setAnchorRef} className="nodedc-select__control">
<div className="nodedc-select__value">
{selected?.icon ? <span className="nodedc-select__value-icon">{selected.icon}</span> : null}
+6 -1
View File
@@ -57,6 +57,7 @@ export function SplitPane({
const rootRef = useRef<HTMLDivElement>(null);
const activePointerIdRef = useRef<number | null>(null);
const [dragging, setDragging] = useState(false);
const [pointerFocus, setPointerFocus] = useState(false);
const limits = normalizedLimits(minPrimarySize, minSecondarySize);
const size = clamp(Number.isFinite(primarySize) ? primarySize : 50, limits.minimum, limits.maximum);
const keyboardIncrement = Number.isFinite(step) && step > 0 ? step : 2;
@@ -74,6 +75,7 @@ export function SplitPane({
};
const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
setPointerFocus(false);
const multiplier = event.shiftKey ? 5 : 1;
const decrement = orientation === "vertical" ? "ArrowLeft" : "ArrowUp";
const increment = orientation === "vertical" ? "ArrowRight" : "ArrowDown";
@@ -119,10 +121,13 @@ export function SplitPane({
aria-valuemax={Math.round(limits.maximum)}
aria-valuenow={Math.round(size)}
aria-valuetext={`${Math.round(size)}% / ${Math.round(100 - size)}%`}
data-pointer-focus={pointerFocus || undefined}
onBlur={() => setPointerFocus(false)}
onKeyDown={handleKeyDown}
onPointerDown={(event) => {
if (event.button !== 0) return;
event.currentTarget.focus();
setPointerFocus(true);
event.currentTarget.focus({ preventScroll: true });
activePointerIdRef.current = event.pointerId;
event.currentTarget.setPointerCapture(event.pointerId);
setDragging(true);
+4 -1
View File
@@ -38,6 +38,8 @@ export interface ToolbarProps<T extends string = string> {
hideDelay?: number;
gap?: number;
label?: string;
/** Dropdown width; placement still clamps to the visible viewport. */
menuWidth?: number;
className?: string;
/** Render inside a positioned viewport; edge reveal follows that viewport. */
container?: HTMLElement;
@@ -66,6 +68,7 @@ export function Toolbar<T extends string = string>({
hideDelay = NODEDC_TOOLBAR_DEFAULTS.hideDelay,
gap = NODEDC_TOOLBAR_DEFAULTS.gap,
label = "Панель инструментов",
menuWidth = 220,
className,
container,
}: ToolbarProps<T>) {
@@ -392,7 +395,7 @@ export function Toolbar<T extends string = string>({
if(placement==="left")return {...b.toJSON(),left:t.left,right:t.left+pad,width:pad};
if(placement==="bottom")return {...b.toJSON(),top:t.bottom-pad,bottom:t.bottom,height:pad};
return {...b.toJSON(),top:t.top,bottom:t.top+pad,height:pad};
}} width={220} trigger={button} onPointerDownOutside={event=>{
}} width={Number.isFinite(menuWidth)?Math.max(180,Math.min(600,menuWidth)):220} trigger={button} onPointerDownOutside={event=>{
const target=event.target as Element;
// Dismiss a menu before a viewport tool can turn this same click into an edit.
if(container?.contains(target)&&!target.closest('button,input,select,textarea,a,[role="button"],[role="tab"]')){
+69
View File
@@ -0,0 +1,69 @@
import {cloneElement,isValidElement,useCallback,useEffect,useId,useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode,type ReactElement} from 'react';
import {createPortal} from 'react-dom';
import {computeFloatingPosition,type FloatingPlacement} from '@nodedc/ui-core';
import {cn} from './cn.js';
export interface TooltipProps {
children:ReactNode;
content:ReactNode;
label?:string;
/** Use for a read-only graphic; buttons already supply their own focus target. */
focusable?:boolean;
disabled?:boolean;
placement?:FloatingPlacement;
className?:string;
}
/** Non-interactive explanation; selection/actions belong to Dropdown. */
export function Tooltip({children,content,label,focusable=false,disabled=false,placement='top-start',className}:TooltipProps){
const id=`tooltip-${useId().replaceAll(':','')}`;
const anchor=useRef<HTMLSpanElement>(null),surface=useRef<HTMLDivElement>(null);
const timer=useRef<ReturnType<typeof setTimeout>|undefined>(undefined);
const [open,setOpen]=useState(false),[style,setStyle]=useState<CSSProperties>({visibility:'hidden'});
const clear=useCallback(()=>{clearTimeout(timer.current);},[]);
const close=useCallback(()=>{clear();setOpen(false);},[clear]);
const show=useCallback(()=>{clear();if(!disabled)setOpen(true);},[clear,disabled]);
const leave=()=>{
clear();
if(anchor.current?.contains(document.activeElement))return;
timer.current=setTimeout(close,140);
};
useEffect(()=>()=>clear(),[clear]);
useEffect(()=>{if(disabled)close();},[disabled,close]);
useLayoutEffect(()=>{
if(!open)return;
const position=()=>{
if(!anchor.current||!surface.current)return;
const rect=anchor.current.getBoundingClientRect(),size=surface.current.getBoundingClientRect();
if(rect.bottom<=0||rect.top>=window.innerHeight||rect.right<=0||rect.left>=window.innerWidth){close();return;}
const p=computeFloatingPosition({anchor:rect,surfaceWidth:size.width,surfaceHeight:size.height,placement,offset:8});
setStyle({left:p.left,top:p.top,maxHeight:p.maxHeight,visibility:'visible'});
};
position();
const observer=new ResizeObserver(position);
if(anchor.current)observer.observe(anchor.current);
if(surface.current)observer.observe(surface.current);
window.addEventListener('resize',position);window.addEventListener('scroll',position,true);
document.addEventListener('fullscreenchange',close);
return()=>{observer.disconnect();window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true);document.removeEventListener('fullscreenchange',close);};
},[open,placement,close]);
useEffect(()=>{
if(!open)return;
const key=(e:KeyboardEvent)=>{if(e.key==='Escape'){close();e.preventDefault();e.stopImmediatePropagation();}};
const outside=(e:PointerEvent)=>{if(e.target instanceof Node&&!anchor.current?.contains(e.target)&&!surface.current?.contains(e.target))close();};
const other=(e:Event)=>{if((e as CustomEvent<string>).detail!==id)close();};
document.addEventListener('keydown',key,true);document.addEventListener('pointerdown',outside,true);
window.addEventListener('nodedc-tooltip-open',other);
window.dispatchEvent(new CustomEvent('nodedc-tooltip-open',{detail:id}));
return()=>{document.removeEventListener('keydown',key,true);document.removeEventListener('pointerdown',outside,true);window.removeEventListener('nodedc-tooltip-open',other);};
},[open,id,close]);
return <span ref={anchor} className={cn('nodedc-tooltip-anchor',className)}
tabIndex={focusable&&!disabled?0:undefined} role={focusable?'img':undefined} aria-label={label}
aria-describedby={open?id:undefined} onPointerEnter={e=>{if(e.pointerType!=='touch')show();}}
onPointerLeave={leave} onFocus={show} onBlur={e=>{if(!e.currentTarget.contains(e.relatedTarget)&&!e.currentTarget.matches(':hover'))close();}}
onPointerDown={e=>{if(e.pointerType==='touch'){if(open)close();else show();}}}>
{focusable||!isValidElement(children)?children:cloneElement(children as ReactElement<{'aria-describedby'?:string}>,{'aria-describedby':[children.props && (children.props as {'aria-describedby'?:string})['aria-describedby'],open?id:undefined].filter(Boolean).join(' ')||undefined})}
{open&&typeof document!=='undefined'&&createPortal(<div ref={surface} id={id} role="tooltip"
className="nodedc-tooltip" style={style} onPointerEnter={clear} onPointerLeave={leave}>{content}</div>,document.fullscreenElement??document.body)}
</span>;
}
+66
View File
@@ -0,0 +1,66 @@
import {useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode} from 'react';
import {treeSelectionRange} from './treeSelectionRange.js';
import {Icon,type IconName} from './Icon.js';
export interface TreeNode {id:string;label:string;children?:TreeNode[];icon?:IconName;visible?:boolean}
export interface TreeSelectionGesture {ctrlKey:boolean;metaKey:boolean;shiftKey:boolean;rangeIds:string[]}
export interface TreeProps {nodes:TreeNode[];selected:string|null;selectedIds?:readonly string[];onSelect:(id:string,gesture:TreeSelectionGesture)=>void;onVisibilityChange?:(id:string,visible:boolean)=>void;label:string;query?:string;revealKey?:number;defaultExpandedDepth?:number;renderActions?:(node:TreeNode)=>ReactNode}
/** Compact outliner. Selection reveals ancestors without scrolling its host page. */
export function Tree({nodes,selected,selectedIds,onSelect,onVisibilityChange,label,query='',revealKey,defaultExpandedDepth=Infinity,renderActions}:TreeProps){
const [collapsed,setCollapsed]=useState<Map<string,boolean>>(()=>new Map());
const [focus,setFocus]=useState<string|null>(null);
const anchor=useRef<string|null>(null);
const lastReveal=useRef<{selected:string;key:number|undefined}|null>(null),pendingReveal=useRef<string|null>(null);
const disclosureScroll=useRef<number|null>(null);
const host=useRef<HTMLDivElement>(null),elements=useRef(new Map<string,HTMLDivElement>());
const parents=new Map<string,string>(),index=new Map<string,TreeNode>();
const visit=(items:TreeNode[],parent?:string)=>{for(const item of items){index.set(item.id,item);if(parent)parents.set(item.id,parent);visit(item.children??[],item.id);}};visit(nodes);
const ancestors=new Set<string>();let parent=selected?parents.get(selected):undefined;while(parent){ancestors.add(parent);parent=parents.get(parent);}
const matches=(item:TreeNode):boolean=>!query||item.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())||!!item.children?.some(matches);
const rows:{node:TreeNode;depth:number;open:boolean}[]=[];
const flatten=(items:TreeNode[],depth=0)=>{for(const node of items){if(!matches(node))continue;const open=!!query||!(collapsed.get(node.id)??depth>=defaultExpandedDepth);rows.push({node,depth,open});if(open)flatten(node.children??[],depth+1);}};flatten(nodes);
const reveal=(id:string)=>{const target=elements.current.get(id),container=host.current;if(!target||!container)return;const row=target.getBoundingClientRect(),box=container.getBoundingClientRect();if(row.top<box.top)container.scrollTop-=box.top-row.top;else if(row.bottom>box.bottom)container.scrollTop+=row.bottom-box.bottom;};
// Data/visibility refreshes are not a new selection. An unresolved external
// selection may wait for async nodes, but a manual disclosure always wins.
useLayoutEffect(()=>{
if(!selected){lastReveal.current=null;pendingReveal.current=null;return;}
if(lastReveal.current?.selected===selected&&lastReveal.current.key===revealKey)return;
if(!index.has(selected))return;
lastReveal.current={selected,key:revealKey};pendingReveal.current=selected;setFocus(selected);
setCollapsed(old=>{if([...ancestors].every(id=>old.get(id)===false))return old;const next=new Map(old);for(const id of ancestors)next.set(id,false);return next;});
},[selected,revealKey,nodes]);
useLayoutEffect(()=>{
if(disclosureScroll.current!==null){if(host.current)host.current.scrollTop=disclosureScroll.current;disclosureScroll.current=null;return;}
const id=pendingReveal.current;if(id&&elements.current.has(id)){reveal(id);pendingReveal.current=null;}
},[selected,revealKey,nodes,query,collapsed]);
const toggle=(id:string)=>{
pendingReveal.current=null;disclosureScroll.current=host.current?.scrollTop??null;
setCollapsed(old=>{const next=new Map(old);const depth=rows.find(row=>row.node.id===id)?.depth??0;next.set(id,!(old.get(id)??depth>=defaultExpandedDepth));return next;});
};
const select=(id:string,event:{ctrlKey:boolean;metaKey:boolean;shiftKey:boolean})=>{setFocus(id);
const rangeIds=event.shiftKey&&selectedIds?treeSelectionRange(rows.map(row=>row.node.id),anchor.current,id):[id];
if(!event.shiftKey)anchor.current=id;
onSelect(id,{ctrlKey:event.ctrlKey,metaKey:event.metaKey,shiftKey:event.shiftKey,rangeIds});elements.current.get(id)?.focus({preventScroll:true});reveal(id);};
return <div ref={host} className="nodedc-tree" role="tree" aria-label={label} aria-multiselectable={selectedIds?true:undefined}>
{rows.map(({node,depth,open},position)=><div key={node.id} ref={element=>{if(element)elements.current.set(node.id,element);else elements.current.delete(node.id);}} role="treeitem" aria-level={depth+1} aria-selected={selectedIds?selectedIds.includes(node.id):selected===node.id} aria-expanded={node.children?.length?open:undefined} tabIndex={(focus??selected??rows[0]?.node.id)===node.id?0:-1} className="nodedc-tree__row" style={{'--tree-depth':depth} as CSSProperties} title={node.label} onFocus={()=>setFocus(node.id)} onClick={event=>select(node.id,event)} onKeyDown={event=>{
if(event.target!==event.currentTarget)return;
let next:string|undefined;
if(event.key==='ArrowDown')next=rows[Math.min(rows.length-1,position+1)]?.node.id;
else if(event.key==='ArrowUp')next=rows[Math.max(0,position-1)]?.node.id;
else if(event.key==='Home')next=rows[0]?.node.id;
else if(event.key==='End')next=rows.at(-1)?.node.id;
else if(event.key==='ArrowRight'){if(node.children?.length){if(!open)toggle(node.id);else next=node.children[0].id;}}
else if(event.key==='ArrowLeft'){if(open&&node.children?.length)toggle(node.id);else next=parents.get(node.id);}
else if(event.key==='Enter'||event.key===' ')next=node.id;
else return;
event.preventDefault();event.stopPropagation();if(next)select(next,event);
}}>
<span className="nodedc-tree__branch">{node.children?.length?<button type="button" tabIndex={-1} aria-label={`${open?'Свернуть':'Развернуть'} ${node.label}`} onClick={event=>{event.stopPropagation();toggle(node.id);}}><Icon name={open?'chevron-down':'chevron-right'} size={14}/></button>:null}</span>
<Icon name={node.icon??(node.children?.length?'folder':'layers')} size={14}/>
<span className="nodedc-tree__label">{node.label}</span>
{renderActions&&<span className="nodedc-tree__actions" onClick={event=>event.stopPropagation()} onDoubleClick={event=>event.stopPropagation()}>{renderActions(node)}</span>}
{onVisibilityChange&&node.visible!==undefined&&<button type="button" className="nodedc-tree__visibility" tabIndex={focus===node.id?0:-1} aria-label={`${node.visible?'Скрыть':'Показать'} ${node.label}`} aria-pressed={node.visible} onClick={event=>{event.stopPropagation();onVisibilityChange(node.id,!node.visible);}}><Icon name={node.visible?'eye':'eye-off'} size={14}/></button>}
</div>)}
</div>;
}
+28 -2
View File
@@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { Dropdown } from "./Dropdown.js";
import { HeaderAvatar } from "./AppHeader.js";
import { HeaderAvatar, HeaderProfile, HeaderProfileButton } from "./AppHeader.js";
import { IconButton } from "./Button.js";
import { Icon, type IconName } from "./Icon.js";
export interface UserProfileMenuAction {
@@ -15,19 +16,25 @@ export interface UserProfileMenuAction {
export interface UserProfileMenuProps {
displayName: string;
/** Header is canonical. "default" retains the legacy compact trigger outside headers. */
variant?: "default" | "header";
subtitle?: string;
avatarUrl?: string;
coverImageUrl?: string;
triggerLabel?: ReactNode;
/** Optional status glyph between the label and avatar. */
triggerIcon?: IconName;
actions: readonly UserProfileMenuAction[];
}
export function UserProfileMenu({
displayName,
variant = "header",
subtitle,
avatarUrl,
coverImageUrl,
triggerLabel,
triggerIcon,
actions,
}: UserProfileMenuProps) {
const label = displayName || "NODE.DC";
@@ -37,7 +44,25 @@ export function UserProfileMenu({
width={296}
offset={10}
surfaceClassName="nodedc-user-profile-menu"
trigger={({ open, toggle, setTriggerRef, surfaceId }) => (
trigger={({ open, toggle, setTriggerRef, setAnchorRef, surfaceId }) => variant === "header" ? (
<HeaderProfile ref={setAnchorRef}>
<HeaderProfileButton aria-haspopup="menu" aria-expanded={open} aria-controls={surfaceId} onClick={(event) => { setTriggerRef(event.currentTarget); toggle(); }}>
{triggerLabel ?? "Профиль"}
</HeaderProfileButton>
<IconButton
ref={setTriggerRef}
label={`Меню пользователя ${label}`}
aria-haspopup="menu"
aria-expanded={open}
aria-controls={surfaceId}
onClick={(event) => { setTriggerRef(event.currentTarget); toggle(); }}
><Icon name={triggerIcon ?? "inbox"} size={20} strokeWidth={1.7} /></IconButton>
<button type="button" className="nodedc-user-profile-menu__trigger" aria-label={`Профиль ${label}`} aria-haspopup="menu" aria-expanded={open} aria-controls={surfaceId}
onClick={(event) => { setTriggerRef(event.currentTarget); toggle(); }}>
<HeaderAvatar label={label} imageUrl={avatarUrl} />
</button>
</HeaderProfile>
) : (
<button
ref={setTriggerRef}
type="button"
@@ -49,6 +74,7 @@ export function UserProfileMenu({
onClick={toggle}
>
{triggerLabel === null ? null : <span className="nodedc-user-profile-menu__trigger-label">{triggerLabel ?? label}</span>}
{triggerIcon ? <Icon name={triggerIcon} size={18} /> : null}
<HeaderAvatar label={label} imageUrl={avatarUrl} />
</button>
)}
+140 -22
View File
@@ -1,6 +1,8 @@
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
type HTMLAttributes,
@@ -10,8 +12,11 @@ import {
import { createPortal } from "react-dom";
import { InspectorSelectPolicyContext } from "./InspectorContext.js";
import { LoadingContext } from "./LoadingContext.js";
import { WindowSuspensionContext } from "./WindowSuspensionContext.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 +29,7 @@ const focusableSelector = [
export type WindowSize = "sm" | "md" | "lg";
export type WindowPlacement = "center" | "end";
export type { WindowRect } from "./windowGeometry.js";
export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title"> {
open: boolean;
@@ -33,6 +39,8 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
footer?: ReactNode;
/** Context actions beside close, using canonical IconButton controls. */
headerActions?: ReactNode;
/** Keep contextual actions immediately before close when requested. */
headerActionsPlacement?: "before-move" | "before-close";
size?: WindowSize;
placement?: WindowPlacement;
closeLabel?: string;
@@ -41,6 +49,15 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
lockBodyScroll?: boolean;
trapFocus?: boolean;
draggable?: boolean;
/** Resize a modeless inspector using the same eight edges as floating windows. */
resizable?: boolean;
initialRect?: WindowRect;
/** Application-owned geometry, restored on open and on external undo/import. */
rect?: WindowRect;
/** One commit after a drag/resize, or a keyboard geometry step. */
onRectCommit?: (rect: WindowRect) => void;
/** Centered windows can become modeless without remounting their contents. */
allowFloating?: boolean;
onClose: () => void;
}
@@ -51,6 +68,7 @@ export function Window({
children,
footer,
headerActions,
headerActionsPlacement = "before-move",
size = "md",
placement = "center",
closeLabel = "Закрыть",
@@ -59,40 +77,69 @@ export function Window({
lockBodyScroll,
trapFocus,
draggable = false,
resizable = false,
initialRect,
rect,
onRectCommit,
allowFloating = true,
onClose,
className,
style,
...props
}: WindowProps) {
const [suspensions, setSuspensions] = useState(0);
const suspend = useCallback(() => {setSuspensions(value => value + 1); return () => setSuspensions(value => Math.max(0, value - 1));}, []);
const suspended = suspensions > 0;
const titleId = useId();
const descriptionId = useId();
const dialogRef = useRef<HTMLDivElement>(null);
const onCloseRef = useRef(onClose);
const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number } | null>(null);
const [dragPosition, setDragPosition] = useState<{ left: number; top: number } | null>(null);
const shouldLockBodyScroll = lockBodyScroll ?? placement === "center";
const shouldTrapFocus = trapFocus ?? placement === "center";
const [floating, setFloating] = useState(false);
const [floatingRect, setFloatingRect] = useState<WindowRect | null>(null);
const rectRef = useRef<WindowRect | null>(null);
const initialRectRef = useRef<WindowRect | null>(null);
const commitRef = useRef(onRectCommit);
commitRef.current = onRectCommit;
const changeRect = (next: WindowRect | null) => { rectRef.current = next; setFloatingRect(next); };
const gestureChanged = useRef(false);
const resizeRef = useRef<{ pointerId: number; x: number; y: number; rect: WindowRect; edge: ResizeEdge } | null>(null);
const isFloating = floating && allowFloating && placement === "center";
const freeGeometry = isFloating || (resizable && placement === "end");
const canDrag = draggable || freeGeometry;
const shouldLockBodyScroll = !suspended && !isFloating && (lockBodyScroll ?? placement === "center");
const shouldTrapFocus = !suspended && !isFloating && (trapFocus ?? placement === "center");
const modeRef = useRef({ shouldTrapFocus, isFloating, suspended });
modeRef.current = { shouldTrapFocus, isFloating, suspended };
onCloseRef.current = onClose;
useEffect(() => {
if (!open || typeof document === "undefined") return;
const previousActiveElement = document.activeElement instanceof HTMLElement ? document.activeElement : null;
const previousOverflow = document.body.style.overflow;
if (shouldLockBodyScroll) document.body.style.overflow = "hidden";
const frame = window.requestAnimationFrame(() => {
const firstFocusable = dialogRef.current?.querySelector<HTMLElement>(focusableSelector);
const firstFocusable = Array.from(dialogRef.current?.querySelectorAll<HTMLElement>(focusableSelector) ?? []).find(element => element.getClientRects().length > 0);
(firstFocusable ?? dialogRef.current)?.focus();
});
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape" && closeOnEscape) {
if (event.defaultPrevented || modeRef.current.suspended) return;
// Portalled child dialogs own their Escape/Tab keys. A parent listener
// can run first, so event.defaultPrevented alone cannot guard nesting.
const focusedDialog = document.activeElement?.closest('[role="dialog"]');
if (focusedDialog && focusedDialog !== dialogRef.current) return;
if (!focusedDialog) {
const topModal = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"][aria-modal="true"]')).filter(dialog => dialog.getClientRects().length > 0).at(-1);
if (topModal && topModal !== dialogRef.current) return;
}
if (event.key === "Escape" && closeOnEscape && (!modeRef.current.isFloating || dialogRef.current?.contains(document.activeElement))) {
event.preventDefault();
onCloseRef.current();
return;
}
if (event.key !== "Tab" || !shouldTrapFocus || !dialogRef.current) return;
const focusable = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(focusableSelector));
if (event.key !== "Tab" || !modeRef.current.shouldTrapFocus || !dialogRef.current) return;
const focusable = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(focusableSelector)).filter(element => element.getClientRects().length > 0);
if (focusable.length === 0) {
event.preventDefault();
dialogRef.current.focus();
@@ -113,28 +160,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 +224,18 @@ export function Window({
window.removeEventListener("pointerup", handlePointerUp);
window.removeEventListener("pointercancel", handlePointerUp);
};
}, [draggable, open]);
}, [canDrag, freeGeometry, open]);
useEffect(() => {
if (!freeGeometry || !open) return;
const fit = () => { if(rectRef.current) changeRect(fitWindow(rect ?? rectRef.current, { width: window.innerWidth, height: window.innerHeight })); };
window.addEventListener("resize", fit);
return () => window.removeEventListener("resize", fit);
}, [freeGeometry, open, rect]);
if (!open || typeof document === "undefined") return null;
const allowBackdropClose = closeOnBackdrop ?? placement === "center";
const allowBackdropClose = !isFloating && (closeOnBackdrop ?? placement === "center");
const handleBackdropPointerDown = (event: PointerEvent<HTMLDivElement>) => {
if (allowBackdropClose && event.target === event.currentTarget) onClose();
@@ -156,29 +243,44 @@ export function Window({
return createPortal(
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} onPointerDown={handleBackdropPointerDown}>
<WindowSuspensionContext.Provider value={suspend}><div className="nodedc-overlay nodedc-ui-root" style={suspended ? {display:"none"} : undefined} data-placement={placement} data-floating={isFloating || undefined} onPointerDown={handleBackdropPointerDown}>
<div
ref={dialogRef}
className={cn("nodedc-window nodedc-glass-material nodedc-material-rim", className)}
data-material="glass-v4"
data-size={size === "md" ? undefined : size}
data-placement={placement}
data-draggable={draggable ? "true" : undefined}
data-draggable={canDrag ? "true" : undefined}
data-resizable={freeGeometry || undefined}
data-floating={isFloating || undefined}
role="dialog"
aria-modal={placement === "center" ? "true" : undefined}
aria-modal={placement === "center" && !isFloating ? "true" : undefined}
aria-labelledby={titleId}
aria-describedby={subtitle ? descriptionId : undefined}
tabIndex={-1}
style={dragPosition ? { ...style, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : style}
style={freeGeometry && floatingRect ? { ...style, position: "fixed", ...floatingRect, right: "auto", bottom: "auto", maxWidth: "none", maxHeight: "none" } : dragPosition ? { ...style, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : style}
{...props}
>
<header
className="nodedc-window__head"
tabIndex={freeGeometry ? 0 : undefined}
aria-label={freeGeometry ? "Перемещение окна: стрелки; изменение размера: Shift и стрелки" : undefined}
onKeyDown={(event) => {
if (!freeGeometry || !floatingRect || event.target !== event.currentTarget || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const dx = event.key === "ArrowLeft" ? -10 : event.key === "ArrowRight" ? 10 : 0;
const dy = event.key === "ArrowUp" ? -10 : event.key === "ArrowDown" ? 10 : 0;
const bounds = { width: window.innerWidth, height: window.innerHeight };
const next = event.shiftKey ? resizeWindow(floatingRect, "se", dx, dy, bounds) : fitWindow({ ...floatingRect, left: floatingRect.left + dx, top: floatingRect.top + dy }, bounds);
changeRect(next); commitRef.current?.(next);
}}
onPointerDown={(event) => {
if (!draggable || event.button !== 0 || (event.target as HTMLElement).closest("button, input, select, textarea, a")) return;
if (!canDrag || event.button !== 0 || (event.target as HTMLElement).closest("button, input, select, textarea, a")) return;
const bounds = dialogRef.current?.getBoundingClientRect();
if (!bounds) return;
dragRef.current = { pointerId: event.pointerId, offsetX: event.clientX - bounds.left, offsetY: event.clientY - bounds.top };
gestureChanged.current = false;
event.currentTarget.setPointerCapture(event.pointerId);
event.preventDefault();
}}
>
@@ -187,17 +289,33 @@ export function Window({
{subtitle ? <p id={descriptionId} className="nodedc-window__subtitle">{subtitle}</p> : null}
</div>
<div className="nodedc-window__actions">
{headerActions}
{headerActionsPlacement === "before-move" && headerActions}
{allowFloating && placement === "center" && <IconButton label={isFloating ? "Вернуть модальный режим" : "Свободное окно"} aria-pressed={isFloating} onClick={() => {
dragRef.current = null; resizeRef.current = null;
if (!isFloating) {
const rect = dialogRef.current?.getBoundingClientRect();
if (rect) changeRect(fitWindow(rectRef.current ?? { left: rect.left, top: rect.top, width: rect.width, height: rect.height }, { width: window.innerWidth, height: window.innerHeight }));
}
setFloating(!isFloating);
}}><Icon name="move" /></IconButton>}
{headerActionsPlacement === "before-close" && headerActions}
<button type="button" className="nodedc-window__close" aria-label={closeLabel} onClick={onClose}>
<Icon name="close" size={16} strokeWidth={1.6} />
</button>
</div>
</header>
{freeGeometry && windowResizeEdges.map(edge => <div key={edge} className="nodedc-window__resize" data-edge={edge} aria-hidden="true" onPointerDown={event => {
if (event.button !== 0 || !floatingRect) return;
resizeRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, rect: floatingRect, edge };
gestureChanged.current = false;
event.currentTarget.setPointerCapture(event.pointerId);
event.preventDefault(); event.stopPropagation();
}} />)}
<div className="nodedc-window__body">{children}</div>
{footer ? <footer className="nodedc-window__footer">{footer}</footer> : null}
</div>
</div>
</InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
</WindowSuspensionContext.Provider></InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
document.fullscreenElement ?? document.body,
);
}
@@ -0,0 +1,3 @@
import {createContext} from 'react';
/** A detached editor hides its owning window without unmounting its contents. */
export const WindowSuspensionContext=createContext<null|(()=>()=>void)>(null);
@@ -0,0 +1,8 @@
import type {DockRect} from '@nodedc/ui-core';
/** Only corners on both outer edges are rounded; all internal seams stay square. */
export function editorDockCorners(rect:DockRect,area:DockRect):string {
const same=(a:number,b:number)=>Math.abs(a-b)<.01;
const left=same(rect.left,area.left),top=same(rect.top,area.top);
const right=same(rect.left+rect.width,area.left+area.width),bottom=same(rect.top+rect.height,area.top+area.height);
return [top&&left?'top-left':'',top&&right?'top-right':'',bottom&&right?'bottom-right':'',bottom&&left?'bottom-left':''].filter(Boolean).join(' ');
}
+15 -1
View File
@@ -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,14 @@ 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,type TreeSelectionGesture} from "./Tree.js";
export * from "./ResizableViewport.js";
export {useApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
export {SceneAnnotation} from "./SceneAnnotation.js";
export {LevelButton,type LevelButtonProps} from "./LevelButton.js";
export {Tooltip,type TooltipProps} from "./Tooltip.js";
@@ -0,0 +1,10 @@
import type {CSSProperties} from 'react';
export type LevelButtonGeometry={width:number;height:number;radius?:number};
/** Keep type and padding proportional when the operator chooses a tiny indicator. */
export function levelButtonGeometry(value:LevelButtonGeometry|undefined,characters:number):CSSProperties{
if(!value)return {};
const bounded=(n:number|undefined,fallback:number,min:number,max:number)=>typeof n==='number'&&Number.isFinite(n)?Math.max(min,Math.min(max,n)):fallback;
const width=bounded(value.width,115,32,4096),height=bounded(value.height,46,12,1024),radius=bounded(value.radius,999,0,4096);
const scale=Math.min(1,height/24,width/Math.max(64,(characters+2)*8));
return {width,minWidth:width,height,minHeight:height,borderRadius:radius,flexShrink:0,fontSize:`calc(var(--nodedc-font-size-md) * ${scale})`,lineHeight:1,padding:`calc(0.25rem * ${scale}) calc(var(--nodedc-space-2) * ${scale})`};
}
@@ -0,0 +1,5 @@
/** Screen sampling requires a secure context and an explicit trusted click. No screenshots are retained. */
export type ScreenColorPicker = new () => { open(options: { signal: AbortSignal }): Promise<{ sRGBHex: string }> };
export function screenColorPicker(): ScreenColorPicker | undefined {
return (globalThis as typeof globalThis & { EyeDropper?: ScreenColorPicker }).EyeDropper;
}
@@ -0,0 +1,5 @@
/** Range follows displayed rows only; folded/filtered-out branches cannot leak in. */
export function treeSelectionRange(rows:readonly string[],anchor:string|null,target:string):string[]{
const a=rows.indexOf(anchor??target),b=rows.indexOf(target);
return a<0||b<0?[target]:rows.slice(Math.min(a,b),Math.max(a,b)+1);
}
+21
View File
@@ -0,0 +1,21 @@
/** 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 defaultMinimum: Bounds = { width: 320, height: 200 };
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value));
export function fitWindow(rect: WindowRect, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
const width = clamp(rect.width, Math.max(1, Math.min(minimum.width, bounds.width - 16)), Math.max(1, bounds.width - 16));
const height = clamp(rect.height, Math.max(1, Math.min(minimum.height, 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, minimum: Bounds = defaultMinimum): WindowRect {
const r = fitWindow(rect, bounds, minimum), right = r.left + r.width, bottom = r.top + r.height;
const minWidth = Math.max(1, Math.min(minimum.width, bounds.width - 16)), minHeight = Math.max(1, Math.min(minimum.height, 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 };
}
+121 -34
View File
@@ -6,90 +6,177 @@
"id": "calendar-popover",
"classification": "planned-primitive",
"priority": "P1",
"referenceSources": ["launcher", "task-manager"],
"referenceSources": [
"launcher",
"task-manager"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["dropdown", "button", "field"],
"requiredBehavior": ["portal", "locale-aware labels", "single date", "date range", "keyboard navigation"],
"dependsOn": [
"dropdown",
"button",
"field"
],
"requiredBehavior": [
"portal",
"locale-aware labels",
"single date",
"date range",
"keyboard navigation"
],
"reasonNotBaseline": "Current Launcher and Task Manager implementations must be reconciled before one API is declared canonical."
},
{
"id": "profile-menu",
"classification": "planned-pattern",
"priority": "P1",
"referenceSources": ["launcher", "task-manager"],
"referenceSources": [
"launcher",
"task-manager"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["dropdown", "button", "status-badge"],
"requiredBehavior": ["avatar trigger", "identity summary", "role/workspace switch", "logout action"],
"dependsOn": [
"dropdown",
"button",
"status-badge"
],
"requiredBehavior": [
"avatar trigger",
"identity summary",
"role/workspace switch",
"logout action"
],
"reasonNotBaseline": "Identity and role data contracts differ between Hub and Ops and must remain application-owned."
},
{
"id": "action-dropdown",
"classification": "planned-pattern",
"priority": "P1",
"referenceSources": ["task-manager", "launcher"],
"referenceSources": [
"task-manager",
"launcher"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["dropdown"],
"requiredBehavior": ["commands", "disabled rows", "danger row", "optional groups", "keyboard navigation"],
"dependsOn": [
"dropdown"
],
"requiredBehavior": [
"commands",
"disabled rows",
"danger row",
"optional groups",
"keyboard navigation"
],
"reasonNotBaseline": "Floating behavior is stable; command-row API still needs validation against Ops consumers."
},
{
"id": "data-table",
"classification": "planned-pattern",
"priority": "P1",
"referenceSources": ["launcher", "task-manager"],
"referenceSources": [
"launcher",
"task-manager"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["button", "select", "status-badge", "field"],
"requiredBehavior": ["toolbar", "responsive overflow", "row actions", "editable cells", "loading", "empty state"],
"dependsOn": [
"button",
"select",
"status-badge",
"field"
],
"requiredBehavior": [
"toolbar",
"responsive overflow",
"row actions",
"editable cells",
"loading",
"empty state"
],
"reasonNotBaseline": "The library should own presentation and interaction slots, not adopt Launcher entity schemas or Plane table models."
},
{
"id": "avatar-stack",
"classification": "planned-primitive",
"priority": "P1",
"referenceSources": ["engine", "task-manager"],
"referenceSources": [
"engine",
"task-manager"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["dropdown"],
"requiredBehavior": ["overflow count", "presence", "picker mode", "fallback initials"],
"dependsOn": [
"dropdown"
],
"requiredBehavior": [
"overflow count",
"presence",
"picker mode",
"fallback initials"
],
"reasonNotBaseline": "Engine picker behavior and Task Manager presence semantics must not be coupled accidentally."
},
{
"id": "service-rail-card",
"classification": "product-pattern",
"priority": "P2",
"referenceSources": ["launcher"],
"referenceSources": [
"launcher"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["glass-surface", "status-badge", "button"],
"requiredBehavior": ["ambient media", "access status", "selected state", "open/request action"],
"dependsOn": [
"glass-surface",
"status-badge",
"button"
],
"requiredBehavior": [
"ambient media",
"access status",
"selected state",
"open/request action"
],
"reasonNotBaseline": "Likely reusable for product catalogs, but current contract is tightly connected to Launcher service data."
},
{
"id": "work-item-card",
"classification": "product-pattern",
"priority": "P2",
"referenceSources": ["task-manager"],
"referenceSources": [
"task-manager"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["glass-surface", "avatar-stack", "status-badge", "action-dropdown"],
"requiredBehavior": ["selected state", "drag state", "assignees", "dates", "quick actions"],
"dependsOn": [
"glass-surface",
"avatar-stack",
"status-badge",
"action-dropdown"
],
"requiredBehavior": [
"selected state",
"drag state",
"assignees",
"dates",
"quick actions"
],
"reasonNotBaseline": "The visual pattern is mature, but task-domain fields must be separated from the reusable card shell."
},
{
"id": "tooltip",
"classification": "missing-primitive",
"priority": "P2",
"referenceSources": ["launcher", "task-manager", "engine"],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["dropdown"],
"requiredBehavior": ["hover", "focus", "delay", "viewport placement"],
"reasonNotBaseline": "Needs a small dedicated accessibility contract rather than reuse of an application tooltip."
},
{
"id": "empty-loading-error",
"classification": "planned-pattern",
"priority": "P2",
"referenceSources": ["launcher", "seo", "task-manager"],
"referenceSources": [
"launcher",
"seo",
"task-manager"
],
"expectedPackage": "@nodedc/ui-react",
"dependsOn": ["button", "status-badge"],
"requiredBehavior": ["empty message", "retry", "loading progress", "fatal error"],
"dependsOn": [
"button",
"status-badge"
],
"requiredBehavior": [
"empty message",
"retry",
"loading progress",
"fatal error"
],
"reasonNotBaseline": "Copy and domain actions vary; the layout contract still needs examples from all product families."
}
]
+313 -35
View File
@@ -1,6 +1,28 @@
{
"schemaVersion": "1.0.0",
"components": [
{
"id": "mission-theme",
"status": "baseline",
"package": "@nodedc/ui-core",
"exports": [
"applyNodedcTheme",
"missionDarkTheme",
"missionLightTheme"
],
"domContract": [
"data-nodedc-theme",
"data-nodedc-appearance",
"data-nodedc-edges"
],
"summary": "Canonical Mission Core theme foundation shared by React, DOM and body portals.",
"rules": [
"Colors belong to tokens/themes.css; applications select a preset and may provide an explicit user accent.",
"ApplicationPanel → SettingsCard → fields matches Mission Core forms. Collection entries may use GlassSurface tone=group; never wrap field grids in recessed soft surfaces or add a card around a list of cards.",
"No decorative outlines; keyboard focus, disabled states and semantic error/success indicators remain visible."
],
"documentation": "../docs/THEMING.md"
},
{
"id": "progress-button",
"status": "baseline",
@@ -83,9 +105,10 @@
"nodedc-glass",
"nodedc-glass-material",
"nodedc-map-glass",
"nodedc-material-rim"
"nodedc-material-rim",
"nodedc-viewport-surface"
],
"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 +121,8 @@
"default",
"strong",
"soft",
"map"
"map",
"scene"
],
"radiusVariants": [
"card",
@@ -108,12 +132,14 @@
],
"rules": [
"Geometry is invariant across application themes.",
"Opt-in appearance=mission applies the qualified Mission Core operator surfaces, avatars and dot statuses across portals without changing geometry.",
"The default Mission Core foundation supplies surfaces, avatars and dot statuses across portals without changing geometry.",
"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.",
"MapGlassSurface is restricted to overlays over Cesium/map imagery and must match the map Toolbar translucency."
"Form collections use tone=group, the same neutral material as SettingsCard. tone=soft is a recessed secondary canvas, never a form-grid background.",
"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.",
"Theme edges=flat removes decorative rims and active outlines across portals; keyboard focus uses contrasting fill without changing geometry.",
"Owner 2026-11-14: all backed UI inside every map/3D/camera/replay viewport uses scene Glass V4, independent of renderer. Use GlassMaterialSurface context=scene or nodedc-viewport-surface for an existing semantic overlay. Never tint the renderer itself. See docs/VIEWPORT_UI.md."
]
},
{
@@ -156,7 +182,9 @@
"Destructive actions remain neutral until confirmation unless danger is the principal message.",
"loading displays one centered indicator inside the initiating action, disables repeat activation and preserves dimensions and accessible name. Never place its spinner beside or below the action group.",
"Primary tone=neutral is white when enabled and gray when disabled in every theme/accent; use it for accent-independent operator actions without local CSS overrides.",
"nodedc-viewport-controls is the shared geometry context for every viewer toolbar: 0.7 times standard controls, including icons, fonts and rims. It normalizes legacy compact/dense variants, never compounds in nested groups, and excludes portaled menus/settings and scene content."
"nodedc-viewport-controls is the shared geometry context for every viewer toolbar: 0.7 times standard controls, including icons, fonts and rims. It normalizes legacy compact/dense variants, never compounds in nested groups, and excludes portaled menus/settings and scene content.",
"Viewport action scopes apply scene Glass V4 to normal backgrounds; selected/disabled/hover and focus semantics are preserved. No local nearly transparent substitutes.",
"Viewport round action rails keep their group container transparent: glass belongs to each circle, not a shared capsule."
]
},
{
@@ -284,7 +312,8 @@
"The browser places the caret at the clicked character, preserves native drag or keyboard selection, and replaces the selected substring on typing without pointer-state interception.",
"Editor foreground and caret switch automatically between theme text and on-accent tokens according to the actual fill edge beneath the value area.",
"The editor has no separate background box and keeps focus across parent window rerenders and pointer leave.",
"Editor keyboard events do not bubble into enclosing Window shortcuts."
"Editor keyboard events do not bubble into enclosing Window shortcuts.",
"variant=rail is the single-value horizontal counterpart of the thin vertical section scale: 0.2 control-height shaft, minimum 24 px transparent target, value above, native arrows/Home/End, disabled and value underline focus. No enclosing surface, glass, outline, shadow or exact-value editor. Consumer owns placement and visibility timing."
]
},
{
@@ -304,11 +333,14 @@
"hue slider",
"quick colors",
"portal palette",
"keyboard spectrum adjustment"
"keyboard spectrum adjustment",
"explicit screen eyedropper with cancellation; system palette fallback when EyeDropper is unavailable"
],
"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.",
"The themed palette remains primary. Screen sampling starts only on a trusted button click, never pointer leave; unsupported browsers expose an explicit system-palette fallback. No screenshots are captured or stored. Escape, closing or unmount cancels sampling without applying a color.",
"Spectrum has no decorative perimeter border; sampling marker and keyboard focus remain visible."
]
},
{
@@ -330,6 +362,7 @@
"behavior": [
"portal to active fullscreen element or document body",
"viewport clamp",
"content resize repositions an open dropdown within viewport bounds",
"vertical flip",
"capture-phase outside pointer close before scene tool interception",
"optional outside-pointer consumer for editing viewports",
@@ -380,7 +413,8 @@
"Split is the Engine form: a separate value surface and a 46 px toggle separated by an 8 px gap.",
"Inline is a compact label-only toolbar trigger without a persistent surface or chevron; its menu and keyboard behavior remain canonical.",
"Integrated Select is forbidden inside Inspector; use InspectorSelectField so the visible label is above a full-width split control.",
"The portal menu preserves its source-family row geometry instead of inheriting card radii."
"The portal menu preserves its source-family row geometry instead of inheriting card radii.",
"Split Select accepts shape=pill to align its separate toggle with circular workspace actions."
]
},
{
@@ -389,17 +423,20 @@
"package": "@nodedc/ui-react",
"exports": [
"Window",
"WindowFooterActions"
"WindowFooterActions",
"WindowRect"
],
"domPackage": "@nodedc/ui-dom",
"domExports": [
"createModalController"
"createModalController",
"createModalSizeController",
"fitModalSize"
],
"domContract": [
"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,9 +445,13 @@
"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",
"Escape and Tab belong to the focused or topmost visible modal; parent windows do not dismiss behind nested settings.",
"DOM modal resizing shares eight canonical edge handles, centered viewport bounds and keyboard Shift+arrow control; onSizeCommit runs only for completed user changes."
],
"rules": [
"headerActionsPlacement=before-close places context actions between the move toggle and close in both visual and keyboard order; the default preserves existing consumers.",
"WindowFooterActions aligns modal actions to the trailing edge, including a footer with only one action group; actions wrap within narrow windows.",
"Centered windows at narrow widths subtract both overlay gutters from their maximum width and height.",
"Open state belongs to the application; focus/layer behavior belongs to the component.",
@@ -418,7 +459,13 @@
"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.",
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions."
]
},
{
@@ -456,7 +503,8 @@
"Rectangle, maximized state, visibility, activation and z-order are controlled by the application.",
"resizeIndicator=false hides only the corner glyph; pointer hit area, cursor and keyboard resizing remain available.",
"Use WorkspaceWindow for auxiliary views inside a stage; modal workflows and viewport inspectors continue to use Window.",
"Dragging and resizing remain clamped when the workspace changes size, including when it becomes smaller than the requested minimum."
"Dragging and resizing remain clamped when the workspace changes size, including when it becomes smaller than the requested minimum.",
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions."
]
},
{
@@ -500,7 +548,7 @@
"behavior": [
"controlled percentage",
"optional resizable separator",
"line or invisible separator appearance with retained keyboard focus",
"line or invisible separator appearance with retained keyboard focus; pointer resize never paints the invisible divider",
"pointer capture drag",
"Arrow/Home/End keyboard sizing",
"ARIA separator range",
@@ -652,12 +700,14 @@
"profile identity card",
"theme-independent cover",
"action links and callbacks",
"outside pointer and Escape close"
"outside pointer and Escape close",
"responsive profile label hides with the shared mobile header layout"
],
"rules": [
"The component owns menu geometry and profile presentation; the application owns settings, profile and logout actions.",
"Use the existing Dropdown engine so the menu is never clipped by the fixed application header.",
"Do not embed product permissions or sharing rules in the visual menu."
"Do not embed product permissions or sharing rules in the visual menu.",
"The default header composes HeaderProfileButton, an independent menu IconButton and HeaderAvatar using the existing header geometry. Application settings belong inside this menu; do not add an adjacent settings button or another HeaderProfile wrapper."
]
},
{
@@ -696,7 +746,8 @@
"exports": [
"ApplicationShell",
"ApplicationPanel",
"useApplicationWorkspace"
"useApplicationWorkspace",
"useApplicationPanelFullscreen"
],
"domPackage": "@nodedc/ui-dom",
"domExports": [
@@ -722,14 +773,17 @@
"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.",
"ApplicationPanel establishes md/13px operational typography independent of the host; its page title alone uses title/18px. Semantic section headings remain md; explanatory copy uses Description/sm."
]
},
{
@@ -763,6 +817,8 @@
"viewport container scope with local edge reveal",
"native tooltips with keyboard shortcut hints",
"optional canonical dropdown for toolbar item menus",
"viewport-scoped buttons share scene Glass V4; the rail stays transparent",
"bounded menuWidth for rich inspectors; default remains 220 px",
"theme-independent geometry",
"menus outside maximum magnified icon envelope",
"bounded triangle intent corridor before sibling menu activation",
@@ -909,8 +965,10 @@
"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."
"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.",
"Fields sit directly in the card body, as in Mission Core. Layout grids are transparent; use at most one additional neutral group for a collection entry, not a card around the entire form."
]
},
{
@@ -992,7 +1050,8 @@
"moveDockPanel",
"resizeDockSplit",
"dockRects",
"dockPosition"
"dockPosition",
"dockMoveAtPoint"
],
"domContract": [
"nodedc-dock-layout",
@@ -1006,10 +1065,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 +1078,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 +1112,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."
]
},
{
@@ -1076,7 +1140,9 @@
"Inspector selection fields use InspectorSelectField only: a stacked visible label and the 276/8/46 px split control; integrated pills are prohibited.",
"The panel variant reuses AdminNavigationPanel pill, icon and theme tokens while retaining the same controlled accordion state and domain-owned content.",
"A section action is a sibling IconButton before the disclosure chevron, never nested in the trigger. It does not toggle the section. Panel chevrons point down when collapsed and up when expanded.",
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts."
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts.",
"Default sections and optional header fields use the canonical 12 px spacing token; footer actions are centered with the same gap. Nested Inspectors retain this rhythm; the panel variant retains its compact row geometry.",
"Inspector responds to its own container width: fields stack below 330px and intrinsic tracks must not clip content."
]
},
{
@@ -1091,14 +1157,15 @@
"nodedc-environment-settings",
"nodedc-environment-media-playlist"
],
"summary": "Shared avatar Settings → Environment composition for product/home copy, quick actions and image/video playlists.",
"summary": "Shared avatar Settings composition with Environment editing and optional consumer-owned settings sections.",
"behavior": [
"product-configured page list",
"draft/reset/save",
"upload adapter",
"ordered media playlist",
"image timing",
"parent save/upload disabled state"
"parent save/upload disabled state",
"additionalSections extends shared navigation with consumer-owned content and footer while preserving the Environment draft"
],
"rules": [
"Reuse FeatureSettingsWindow and existing form primitives; never fork an application-specific settings form.",
@@ -1168,7 +1235,9 @@
],
"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.",
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions."
]
},
{
@@ -1204,6 +1273,7 @@
],
"summary": "Renderer-independent BIM-style orientation cube; six faces, twelve edges, eight corners.",
"behavior": [
"independent faceOpacity, edgeOpacity and text colors; overall opacity remains compatible",
"Tracks camera quaternion; never changes projection implicitly",
"Visible regions support hover, focus, Enter/Space and disabled state",
"Consumer owns camera navigation and coordinate conversion",
@@ -1211,6 +1281,214 @@
"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",
"TreeSelectionGesture"
],
"domContract": [
"nodedc-tree",
"nodedc-tree__row"
],
"summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.",
"behavior": [
"new external selection expands ancestors and scrolls only the tree container",
"visibility/data refresh keeps disclosure state; arrow disclosure keeps scroll position; row double-click does not expand",
"Arrow/Home/End navigation, disclosure and optional visibility actions",
"long names ellipsize without growing row height",
"filter retains matching ancestors",
"optional renderActions slot composes canonical controls without selecting the row",
"defaultExpandedDepth limits initial expansion; external selection reveals ancestors"
],
"rules": [
"Use for object hierarchies; no nested ResourceRow cards.",
"Host owns model identity and visibility; the tree owns navigation presentation.",
"Compact information uses info-plain at 14px beside the independent visibility eye.",
"Optional controlled selectedIds and modifier/range callback support multiple selection; Shift ranges use displayed rows only. Existing single-selection consumers remain compatible."
]
},
{
"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",
"only exterior workspace corners are rounded; adjoining pane seams remain square and update after dock, resize or close",
"drag header to detach over primary",
"floating and dragged tools use canonical scene Glass V4; docking restores tiled surface context",
"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.",
"When opened inside Window, the editor suspends that overlay, backdrop and focus trap without unmounting; returning restores the same window.",
"EditorWorkspace purpose=view uses the same mounted host, return/fullscreen behavior and optional fixed headerActions; purpose=edit remains the compatible default.",
"Tool minimumSize applies to floating restore, pointer and keyboard resize as well as docked splits; small screens clamp to available space. Footer remains outside the body scroller."
]
},
{
"id": "level-button",
"status": "baseline",
"package": "@nodedc/ui-react",
"exports": [
"LevelButton",
"LevelButtonProps",
"LevelButtonGeometry"
],
"domContract": [
"nodedc-level-button"
],
"summary": "Compact measured resource level inside a canonical pill button opening details.",
"rules": [
"Consumer supplies a measured fraction and freshness; unknown is not zero.",
"Stale retains the last number and accessible stale text; explicit user fill colours are retained.",
"Keyboard, focus, disabled and pointer behavior come from Button. Explicit fillColor uses contrast-correct text on the filled portion.",
"Optional geometry sets width, height and radius with a 32 × 12 px minimum. At small dimensions the text and padding shrink proportionally; both contrast layers share the same type geometry. Consumer owns header-group offset."
],
"documentation": "../docs/LEVEL_BUTTON.md"
},
{
"id": "tooltip",
"status": "baseline",
"package": "@nodedc/ui-react",
"exports": [
"Tooltip",
"TooltipProps"
],
"domContract": [
"nodedc-tooltip-anchor",
"nodedc-tooltip"
],
"summary": "Neutral non-interactive explanation on hover, focus or touch.",
"behavior": [
"portal to active fullscreen element or body",
"shared viewport clamp and flip",
"hoverable content and focus persistence",
"Escape dismisses tooltip without closing its parent",
"one tooltip at a time",
"scroll/resize reposition",
"reduced-motion fade disabled"
],
"rules": [
"Use focusable for read-only graphics; action triggers own their focus.",
"Content is descriptive, never a menu or interactive form.",
"No new app-local tooltip geometry or layer management."
]
},
{
"id": "path-bar",
"status": "baseline",
"package": "@nodedc/ui-dom",
"exports": [
"renderPathBar",
"PathBarItem"
],
"domContract": [
"nodedc-path-bar"
],
"summary": "Compact Finder-style path navigation with neutral folder icons, separators and native folder buttons.",
"behavior": [
"Application supplies items, icon factory and navigation callback.",
"Current location uses aria-current; long paths scroll without wrapping."
],
"rules": [
"Use ui-dom/styles.css, theme tokens and textContent labels; no application-local breadcrumb pills."
]
}
]
}
+12 -2
View File
@@ -25,12 +25,16 @@
"names": [
"close",
"plus",
"minus",
"expand",
"minimize",
"refresh",
"panel",
"apps",
"layers"
"layers",
"move",
"power",
"pipette"
]
},
{
@@ -51,6 +55,7 @@
"sliders",
"search",
"orthographic",
"fit-view",
"perspective"
]
},
@@ -76,7 +81,10 @@
"curve",
"undo",
"redo",
"add-point"
"add-point",
"ruler",
"section",
"isolate"
]
},
{
@@ -91,6 +99,7 @@
"check",
"alert",
"info",
"info-plain",
"activity",
"lock",
"key",
@@ -113,6 +122,7 @@
"building",
"globe",
"database",
"pin",
"network",
"inbox",
"mail"
+20 -3
View File
@@ -56,7 +56,8 @@
"mapTemplate": "../docs/MAP_TEMPLATE.md",
"icons": "../docs/ICONS.md",
"consumption": "../docs/CONSUMPTION.md",
"environmentSettings": "../docs/ENVIRONMENT_SETTINGS.md"
"environmentSettings": "../docs/ENVIRONMENT_SETTINGS.md",
"viewportUi": "../docs/VIEWPORT_UI.md"
},
"applicationManifestSchema": "schemas/application-manifest-v0.1.schema.json",
"designProfileSchema": "schemas/design-profile-v0.1.schema.json",
@@ -66,7 +67,23 @@
"mapSubjectDetailProfileRegistry": "map-subject-detail-profiles.json",
"operatingRule": "Check this registry before creating a NODE.DC interface element. Reuse or extend the canonical export instead of creating an application-local copy.",
"appearanceProfiles": {
"default": "Existing theme/material behavior",
"mission": "Opt-in operator appearance, qualified against live Mission Core 2026-09-30; shared modal/floating surfaces, neutral avatars and dot statuses"
"default": "Explicit legacy component presentation; no application-local overrides.",
"mission": "Canonical Mission Core foundation, audited on 2026-11-05: complete dark palette, surface hierarchy, neutral actions, portal materials, semantic dots and flat edges. Default for new applications."
},
"surfaceEdgeProfiles": {
"default": "Existing surface edges",
"flat": "No decorative borders or rims; contrasting keyboard focus fill"
},
"themePresets": {
"missionDarkTheme": {
"theme": "dark",
"appearance": "mission",
"edges": "flat"
},
"missionLightTheme": {
"theme": "light",
"appearance": "mission",
"edges": "flat"
}
}
}
+15
View File
@@ -108,6 +108,21 @@
"docs/ARCHITECTURE.md"
],
"policy": "architecture-context"
},
{
"id": "mission-core",
"repository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE.git",
"auditedRevision": "b0332fa",
"role": "Owner-approved canonical dark theme and shared operator presentation, 2026-11-05; source and running canonical localhost:8000 audited.",
"approvedPaths": [
"apps/control-station/src/styles/base.css",
"apps/control-station/src/main.tsx"
],
"policy": "reference",
"excludedPaths": [
"domain scene renderers",
"uncommitted simulation work"
]
}
]
}
+16
View File
@@ -47,3 +47,19 @@ test("viewport controls share one scale without scaling nested controls twice",
assert.match(styles, /\.nodedc-segmented\) :is\([^}]+zoom: 1;/);
assert.ok(JSON.parse(registrySource).components.find(c=>c.id==='button').domContract.includes('nodedc-viewport-controls'));
});
import { LevelButton } from "../packages/ui-react/dist/index.js";
import { levelButtonGeometry } from "../packages/ui-react/dist/levelButtonGeometry.js";
test("compact level indicators fit both contrast layers with proportional text and padding", () => {
const tiny=levelButtonGeometry({width:32,height:12,radius:4},4);
const normal=levelButtonGeometry({width:64,height:24,radius:8},4);
assert.equal(tiny.fontSize,'calc(var(--nodedc-font-size-md) * 0.5)');
assert.equal(tiny.padding,'calc(0.25rem * 0.5) calc(var(--nodedc-space-2) * 0.5)');
assert.equal(normal.fontSize,'calc(var(--nodedc-font-size-md) * 1)');
assert.equal(levelButtonGeometry({width:-1,height:NaN},4).width,32);
assert.equal(levelButtonGeometry({width:-1,height:NaN},4).height,46);
const markup=renderToStaticMarkup(createElement(LevelButton,{value:1,label:'Battery',fillColor:'#ffffff',geometry:{width:32,height:12,radius:4}}));
assert.match(markup,/width:32px/);assert.match(markup,/height:12px/);
assert.match(markup,/nodedc-level-button__fill/);
assert.match(markup,/100/);assert.match(markup,/aria-label="Battery: 100%"/);
});
+56 -1
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {preferDockSizes,dockMinimum,constrainDockTree,balancedDockTree,decodeDockTree,dockIds,dockPosition,dockRects,moveDockPanel,pruneDockTree,reconcileDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js';
import {dockMoveAtPoint,preferDockSizes,dockMinimum,constrainDockTree,balancedDockTree,decodeDockTree,dockIds,dockPosition,dockRects,moveDockPanel,pruneDockTree,reconcileDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js';
const bounds={left:0,top:0,width:1200,height:800};
const initial=balancedDockTree(['a','b','c']);
const rects=tree=>dockRects(tree,bounds);
@@ -79,3 +79,58 @@ test('new compact panel uses its preferred size without changing saved ratios',(
assert.ok(Math.abs(r.telemetry.width-320)<1e-8);assert.ok(Math.abs(r.telemetry.height-280)<1e-8);
assert.deepEqual(preferDockSizes(t,bounds,{}),t);
});
test('workspace edges span the whole side and preserve the remaining nested tree',()=>{
const original={axis:'x',ratio:35,first:{axis:'y',ratio:30,first:{id:'map'},second:{id:'rover'}},second:{axis:'y',ratio:60,first:{id:'camera'},second:{id:'telemetry'}}};
const snapshot=JSON.stringify(original),remaining=pruneDockTree(original,['map','rover','telemetry']);
for(const position of ['left','right','top','bottom']){
const moved=moveDockPanel(original,{activeId:'camera',overId:'camera',position,scope:'workspace'});
const before=position==='left'||position==='top';
assert.deepEqual(before?moved.second:moved.first,remaining);
const r=rects(moved).camera;
assert.deepEqual(r,position==='left'?{left:0,top:0,width:600,height:800}:
position==='right'?{left:600,top:0,width:600,height:800}:
position==='top'?{left:0,top:0,width:1200,height:400}:{left:0,top:400,width:1200,height:400});
assert.deepEqual(dockIds(moved).sort(),['camera','map','rover','telemetry']);
assert.deepEqual(decodeDockTree(JSON.parse(JSON.stringify(moved))),moved);
}
assert.equal(JSON.stringify(original),snapshot);
assert.equal(moveDockPanel(original,{activeId:'camera',overId:'map',position:'center',scope:'workspace'}),original);
assert.equal(moveDockPanel({id:'camera'},{activeId:'camera',overId:'camera',position:'top',scope:'workspace'}).id,'camera');
});
test('outer workspace zones win over source and panel edges; local docking remains reachable',()=>{
const r=rects(initial);
for(const [x,y,position] of [[10,300,'left'],[1190,300,'right'],[800,10,'top'],[800,790,'bottom']]){
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',x,y),{activeId:'a',overId:'a',position,scope:'workspace'});
}
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',620,400),{activeId:'a',overId:'c',position:'left'});
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',900,50),{activeId:'a',overId:'c',position:'top'});
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',900,400),{activeId:'a',overId:'c',position:'center'});
assert.equal(dockMoveAtPoint(bounds,r,'a',300,200),null);
for(const [x,y] of [[-1,300],[1201,300],[500,-1],[500,801],[NaN,100],[100,Infinity]])assert.equal(dockMoveAtPoint(bounds,r,'a',x,y),null);
assert.equal(dockMoveAtPoint(bounds,r,'missing',10,300),null);
assert.equal(dockMoveAtPoint(bounds,{a:bounds},'a',10,300),null);
assert.equal(dockMoveAtPoint(bounds,r,'a',5,15).position,'left');
assert.equal(dockMoveAtPoint(bounds,r,'a',15,5).position,'top');
});
test('visible viewport coordinates retain workspace docking while the canvas is scrolled',()=>{
const visible={left:300,top:120,width:500,height:400};
const target=dockMoveAtPoint(visible,rects(initial),'a',795,300);
assert.equal(target.scope,'workspace');assert.equal(target.position,'right');
assert.equal(dockMoveAtPoint(visible,rects(initial),'a',810,300),null);
});
test('workspace moves respect content minima and serialize a stable final geometry',()=>{
const sizes={a:{width:300,height:250},b:{width:480,height:350},c:{width:250,height:200}};
for(const position of ['left','right','top','bottom']){
const moved=moveDockPanel(initial,{activeId:'a',overId:'a',position,scope:'workspace'}),minimum=dockMinimum(moved,sizes);
const area={left:0,top:0,width:Math.max(700,minimum.width),height:Math.max(500,minimum.height)};
const final=constrainDockTree(moved,area,sizes),r=dockRects(final,area);
for(const id of ['a','b','c']){assert.ok(r[id].width>=sizes[id].width-1e-8);assert.ok(r[id].height>=sizes[id].height-1e-8);}
assert.deepEqual(dockRects(constrainDockTree(final,area,sizes),area),r);
assert.ok(Math.abs(Object.values(r).reduce((s,v)=>s+v.width*v.height,0)-area.width*area.height)<1e-6);
}
});
+74
View File
@@ -0,0 +1,74 @@
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);
}
});
import {editorDockCorners} from '../packages/ui-react/dist/editorDockCorners.js';
test('left stacked panels round only the outer top and bottom; close restores both corners',()=>{
const tree={axis:'x',ratio:25,first:{axis:'y',ratio:50,first:{id:'a'},second:{id:'b'}},second:{id:'viewport'}};
const r=dockRects(tree,bounds);
assert.equal(editorDockCorners(r.a,bounds),'top-left');assert.equal(editorDockCorners(r.b,bounds),'bottom-left');
assert.equal(editorDockCorners(r.viewport,bounds),'top-right bottom-right');
const remaining=dockRects(pruneDockTree(tree,['a','viewport']),bounds);
assert.equal(editorDockCorners(remaining.a,bounds),'top-left bottom-left');
});
test('top and bottom rows retain square seams at every size and canvas origin',()=>{
for(const position of ['top','bottom'])for(const area of [bounds,{left:80,top:45,width:713.5,height:528.3}]){
const first=dockEditorTool(start,'viewport',{activeId:'a',overId:'viewport',position,scope:'workspace'},'a',rect);
const split=dockEditorTool(first,'viewport',{activeId:'b',overId:'a',position:'right',scope:'panel'},'b',rect);
const r=dockRects(split.tree,area);
assert.equal(editorDockCorners(r.a,area),position+'-left');assert.equal(editorDockCorners(r.b,area),position+'-right');
}
});
+21
View File
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createElement as h} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {applyNodedcTheme} from '../packages/ui-core/dist/index.js';
import {UserProfileMenu} from '../packages/ui-react/dist/index.js';
test('flat profile can be switched back and keeps legible white accent in both themes',()=>{
const values=new Map(); const element={dataset:{},style:{setProperty:(k,v)=>values.set(k,v)}};
for(const theme of ['dark','light']) {
applyNodedcTheme(element,{theme,edges:'flat',accent:[255,255,255]});
assert.equal(element.dataset.nodedcEdges,'flat'); assert.equal(element.dataset.nodedcTheme,theme);
assert.equal(values.get('--nodedc-on-accent-rgb'),'11 17 23');
}
applyNodedcTheme(element,{theme:'dark',appearance:'default',edges:'default'}); assert.equal(element.dataset.nodedcEdges,'default');
});
test('profile glyph stays between label and real session avatar',()=>{
const markup=renderToStaticMarkup(h(UserProfileMenu,{displayName:'Operator',triggerLabel:'Профиль',triggerIcon:'inbox',avatarUrl:'/avatar.png',actions:[]}));
assert.ok(markup.indexOf('Профиль')<markup.indexOf('<svg'));
assert.ok(markup.indexOf('<svg')<markup.indexOf('class="nodedc-header__avatar"'));
assert.match(markup,/src="\/avatar.png"/); assert.match(markup,/Меню пользователя Operator/);
});
@@ -59,3 +59,12 @@ test("Foundry Inspector screens consume the semantic selection field", async ()
assert.equal((catalog.match(/<InspectorSelectField/g) ?? []).length, 2);
assert.match(coreStyles, /\.nodedc-inspector \.nodedc-control-row:has\(\.nodedc-select-anchor\)/);
});
test("Inspector owns form header and centered action footer around its sections",async()=>{
const markup=renderToStaticMarkup(createElement(Inspector,{header:'Form fields',footer:'Action',sections:[{id:'surface',label:'Surface',content:'Controls'},{id:'textures',label:'Textures',content:'Slots'}]}));
assert.ok(markup.indexOf('nodedc-inspector__header')<markup.indexOf('nodedc-inspector__group'));
assert.ok(markup.indexOf('nodedc-inspector__footer')>markup.lastIndexOf('nodedc-inspector__section'));
const css=await readFile(new URL('../packages/ui-core/styles.css',import.meta.url),'utf8');
assert.match(css,/\.nodedc-inspector__group\s*\{[^}]*gap: var\(--nodedc-space-3\)/);
assert.match(css,/\.nodedc-inspector__footer\s*\{[^}]*justify-content: center/);
});
+23
View File
@@ -0,0 +1,23 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {applyNodedcTheme, clearNodedcAccent, missionDarkTheme, missionLightTheme} from '../packages/ui-core/dist/index.js';
import * as dom from '../packages/ui-dom/dist/index.js';
test('React-independent and DOM consumers use one full preset, including portals at document root',()=>{
const values=new Map();
const root={dataset:{},style:{setProperty:(k,v)=>values.set(k,v),removeProperty:k=>values.delete(k)}};
assert.equal(dom.missionDarkTheme,missionDarkTheme);
assert.ok(Object.isFrozen(missionDarkTheme));
applyNodedcTheme(root);
assert.deepEqual(root.dataset,{nodedcTheme:'dark',nodedcAppearance:'mission',nodedcEdges:'flat',nodedcUi:'true'});
applyNodedcTheme(root,{...missionDarkTheme,accent:[255,255,255]});
assert.equal(values.get('--nodedc-on-accent-rgb'),'11 17 23');
clearNodedcAccent(root);
applyNodedcTheme(root,missionLightTheme);
assert.equal(root.dataset.nodedcTheme,'light');
assert.equal(root.dataset.nodedcAppearance,'mission');
assert.equal(values.size,0,'return to preset must not retain a previous custom accent');
applyNodedcTheme(root,{appearance:'default',edges:'default'});
assert.equal(root.dataset.nodedcAppearance,'default');
assert.equal(root.dataset.nodedcEdges,'default');
});
+40
View File
@@ -0,0 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { fitModalSize, createModalSizeController } from '../packages/ui-dom/dist/modalSize.js';
test('modal dimensions fit narrow and desktop screens without mutating preference', () => {
const requested = { width: 1600, height: 900 };
assert.deepEqual(fitModalSize(requested, { width: 375, height: 667 }), { width: 343, height: 635 });
assert.deepEqual(fitModalSize(requested, { width: 1920, height: 1080 }), requested);
assert.deepEqual(requested, { width: 1600, height: 900 });
});
test('only completed gestures commit; viewport fitting and cancellation preserve preference', () => {
class Element extends EventTarget {
style = { width: '', height: '', maxHeight: '' }; dataset = {}; attributes = new Map(); children = [];
setAttribute(k,v) { this.attributes.set(k,v); } getAttribute(k) { return this.attributes.get(k) ?? null; } removeAttribute(k) { this.attributes.delete(k); }
append(value) { this.children.push(value); } remove() {} setPointerCapture() {}
getClientRects() { return [1]; } getBoundingClientRect() { return { width: parseFloat(this.style.width), height: parseFloat(this.style.height) }; }
querySelector() { return head; }
}
const head = new Element(), dialog = new Element(), commits = [];
const oldWindow = globalThis.window, oldDocument = globalThis.document;
globalThis.window = Object.assign(new EventTarget(), { innerWidth: 1600, innerHeight: 1000 });
globalThis.document = { createElement: () => new Element() };
const dispatch = (target, type, values) => target.dispatchEvent(Object.assign(new Event(type, { cancelable: true }), values));
try {
const controller = createModalSizeController({ dialog, initialSize: { width: 800, height: 500 }, onSizeCommit: s => commits.push(s) });
const edge = dialog.children.find(node => node.dataset.edge === 'se');
dispatch(edge, 'pointerdown', {button: 0, pointerId: 1, clientX: 500, clientY: 500});
dispatch(window, 'pointermove', {pointerId: 1, clientX: 650, clientY: 600});
assert.equal(commits.length, 0);
dispatch(window, 'pointerup', {pointerId: 1});
assert.deepEqual(commits, [{width: 1100, height: 700}]);
window.innerWidth = 500; window.innerHeight = 400; window.dispatchEvent(new Event('resize'));
assert.equal(dialog.style.width, '468px'); assert.equal(commits.length, 1);
window.innerWidth = 1600; window.innerHeight = 1000; window.dispatchEvent(new Event('resize'));
assert.equal(dialog.style.width, '1100px');
dispatch(edge, 'pointerdown', {button: 0, pointerId: 2, clientX: 500, clientY: 500});
dispatch(window, 'pointermove', {pointerId: 2, clientX: 650, clientY: 600});
dispatch(window, 'pointercancel', {pointerId: 2}); assert.equal(dialog.style.width, '1100px'); assert.equal(commits.length, 1);
controller.destroy(); assert.equal(dialog.style.width, '');
} finally { globalThis.window = oldWindow; globalThis.document = oldDocument; }
});
+41
View File
@@ -0,0 +1,41 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import postcss from 'postcss';
import {readFileSync,readdirSync} from 'node:fs';
import {fileURLToPath} from 'node:url';
import path from 'node:path';
import {auditStyles,typographyViolation,operationalFontSizes,titleFontSize} from '../packages/ui-core/typography.mjs';
const root=fileURLToPath(new URL('../',import.meta.url));
const policy=JSON.parse(readFileSync(new URL('./typography-policy.json',import.meta.url),'utf8'));
function walk(dir){return readdirSync(dir,{withFileTypes:true}).flatMap(e=>['dist','node_modules','tokens'].includes(e.name)?[]:e.isDirectory()?walk(path.join(dir,e.name)):[path.join(dir,e.name)]);}
test('all shared CSS uses compact operational roles and canonical title exceptions',()=>{
const violations=[];for(const file of walk(path.join(root,'packages')).filter(f=>f.endsWith('.css')))violations.push(...auditStyles(postcss,readFileSync(file,'utf8'),path.relative(root,file),policy));assert.deepEqual(violations,[]);
});
test('UI roots and portaled windows establish their own 13px typography, independent of host body',()=>{
const css=postcss.parse(readFileSync(path.join(root,'packages/ui-core/styles.css'),'utf8'));
for(const scope of ['.nodedc-ui-root','.nodedc-window','.nodedc-workspace-window','.nodedc-application-panel','.nodedc-admin-panel']){
let base=false,headings=false;css.walkRules(rule=>{if(rule.selector.includes(scope)){if(!rule.selector.includes(' :where(')&&rule.nodes.some(d=>d.prop==='font-size'&&d.value==='var(--nodedc-font-size-md)'))base=true;if(rule.selector.includes(':where(h1, h2, h3, h4, h5, h6)')&&rule.nodes.some(d=>d.prop==='font-size'&&d.value==='var(--nodedc-font-size-md)'))headings=true;}});assert.ok(base,scope+' independent base');assert.ok(headings,scope+' semantic heading reset');
}
});
test('token values cannot silently make all operational consumers larger',()=>{
const css=postcss.parse(readFileSync(path.join(root,'packages/tokens/tokens.css'),'utf8'));
for(const [role,px] of Object.entries({...operationalFontSizes,title:titleFontSize})){
const values=[];css.walkDecls('--nodedc-font-size-'+role,d=>values.push(d.value));assert.ok(values.length,role);for(const value of values)assert.equal(parseFloat(value)*16,px,role);
}
});
test('title role never grants large typography to a data field or nested card',()=>{
assert.equal(typographyViolation({file:'example.css',selector:'.nodedc-window__title',property:'font-size',value:'var(--nodedc-font-size-title)'},policy),null);
for(const selector of ['.value','.settings-card h2','.nodedc-window__body'])assert.ok(typographyViolation({file:'example.css',selector,property:'font-size',value:'var(--nodedc-font-size-title)'},policy));
assert.ok(typographyViolation({file:'example.css',selector:'.value',property:'font-size',value:'16px'},{compactLegacy:['example.css | .value | font-size | 16px']}));
});
test('theme attributes on html cannot shrink the rem coordinate system',()=>{
const css=postcss.parse(readFileSync(path.join(root,'packages/ui-core/styles.css'),'utf8'));
css.walkRules(rule=>{
if(rule.nodes.some(d=>d.prop==='font-size')&&rule.selector.startsWith(':where([data-nodedc-ui]')&&!rule.selector.includes(' :where(')){
assert.ok(rule.selector.includes('[data-nodedc-ui]:not(html)'));
assert.ok(rule.selector.includes('.nodedc-ui-root:not(html)'));
assert.ok(rule.selector.includes('html[data-nodedc-ui] > body'));
}
});
});
+12
View File
@@ -117,3 +117,15 @@ test("both boundaries move, clamp independently, separate after coincidence and
assert.deepEqual(move([0, 10], 1, 7.3, 0, 10, .5), [0, 7.5]);
assert.deepEqual(move([0, 9], 1, 10.1, 0, 10.1, 3), [0, 10.1]);
});
test("horizontal thin rail has one native boundary and a formatted value, without field chrome", () => {
for(const disabled of [false,true]){
const markup=renderToStaticMarkup(createElement(RangeControl,{variant:"rail",label:"Скорость",value:5,min:.1,max:100,step:.1,disabled,formatValue:n=>`${n} м/с`,onChange(){}}));
assert.equal((markup.match(/type="range"/g)||[]).length,1);
assert.match(markup,/aria-label="Скорость" aria-orientation="horizontal"/);
assert.match(markup,/aria-valuetext="5 м\/с"/);
assert.match(markup,/nodedc-range-rail__value/);
assert.equal(markup.includes('disabled=""'),disabled);
assert.doesNotMatch(markup,/nodedc-range__label|nodedc-range__editor|nodedc-glass/);
}
});
+13
View File
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {readFile} from 'node:fs/promises';
import {createElement as h} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {LoadingRegion,Description,SettingsCard,ComparisonTable} from '../packages/ui-react/dist/index.js';
@@ -23,3 +24,15 @@ test('SettingsCard and standalone explanatory paragraphs use one typography comp
assert.match(renderToStaticMarkup(h(Description,null,'help')),/class="nodedc-description"/);
assert.match(renderToStaticMarkup(h(SettingsCard,{title:'Settings',description:'help'})),/<p class="nodedc-description">help/);
});
test('legacy card paragraphs and live descriptions share small muted typography, without targeting controls',async()=>{
const css=await readFile(new URL('../packages/ui-core/styles.css',import.meta.url),'utf8');
const blocks=[...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map(([,selectors,body])=>({selectors,body}));
const copy=blocks.find(b=>b.selectors.includes('.nodedc-description')&&b.body.includes('font-size:'));
assert.ok(copy);
assert.match(copy.selectors,/\.nodedc-settings-card__titles p/);
assert.match(copy.selectors,/\.nodedc-settings-card__body :where\(p:not\(\[class\]\)\)/);
for(const declaration of ['font-family: inherit','font-weight: 400','color: var(--nodedc-text-muted)','font-size: var(--nodedc-description-font-size, var(--nodedc-font-size-sm))','line-height: 1.4'])assert.ok(copy.body.includes(declaration),declaration);
assert.doesNotMatch(copy.selectors,/h[1-6]|button|input|select/);
const markup=renderToStaticMarkup(h(Description,{role:'status','aria-live':'polite'},'Waiting for device'));
assert.match(markup,/role="status"/);assert.match(markup,/aria-live="polite"/);assert.match(markup,/class="nodedc-description"/);
});
+29
View File
@@ -0,0 +1,29 @@
const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),assert=require('node:assert/strict');
// Supply jsdom through the QA NODE_PATH when it is not installed locally.
const root=process.env.DG_ROOT||path.resolve(__dirname,'..');
const {JSDOM}=require('jsdom'),React=require(root+'/node_modules/react'),{act}=React,{createRoot}=require(root+'/node_modules/react-dom/client');
const dom=new JSDOM('<div id="app"></div>',{pretendToBeVisual:true});
for(const name of ['window','document','HTMLElement','Element','Node','Event','MouseEvent','KeyboardEvent'])global[name]=dom.window[name];global.IS_REACT_ACT_ENVIRONMENT=true;
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'nodedc-tree-check-'));
require(root+'/node_modules/esbuild').buildSync({entryPoints:[root+'/packages/ui-react/src/Tree.tsx'],outfile:scratch+'/tree.cjs',bundle:true,platform:'node',format:'cjs',external:['react','react/*'],jsx:'automatic'});
const {Tree}=require(scratch+'/tree.cjs');
HTMLElement.prototype.getBoundingClientRect=function(){
const host=this.closest('[role=tree]');if(this===host)return{top:0,bottom:140,left:0,right:400,width:400,height:140};
const i=host?[...host.querySelectorAll('[role=treeitem]')].indexOf(this):0,top=i*28-(host?.scrollTop||0);return{top,bottom:top+28,left:0,right:400,width:400,height:28};
};
let visible=true,selected='leaf99',revision=0,selectedCalls=0,available=true;
const nodes=()=>[{id:'root',label:'Root',visible,children:available?Array.from({length:100},(_,i)=>({id:'leaf'+i,label:'Leaf '+i})):[]}];
const ui=createRoot(document.getElementById('app'));
const render=()=>act(async()=>ui.render(React.createElement(Tree,{nodes:nodes(),selected,revealKey:revision,label:'Tree test',defaultExpandedDepth:1,onSelect:()=>selectedCalls++,onVisibilityChange:(_,v)=>{visible=v;}})));
const button=label=>[...document.querySelectorAll('button')].find(b=>b.getAttribute('aria-label')===label);
const send=(target,type='click',props={})=>act(async()=>target.dispatchEvent(new MouseEvent(type,{bubbles:true,...props})));
(async()=>{
await render();const host=document.querySelector('[role=tree]');assert(host.scrollTop>0,'external leaf selection reveals the leaf');
await send(button('Свернуть Root'));host.scrollTop=0;assert.equal(document.querySelectorAll('[role=treeitem]').length,1);
await send(button('Скрыть Root'));await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,1,'visibility refresh cannot re-open selected ancestors');assert.equal(host.scrollTop,0);assert.equal(selectedCalls,0);
await send(button('Развернуть Root'));assert.equal(document.querySelectorAll('[role=treeitem]').length,101);assert.equal(host.scrollTop,0,'disclosure must not reveal old selected leaf');
await send(button('Свернуть Root'));await send(document.querySelector('[role=treeitem]'),'dblclick');assert.equal(document.querySelectorAll('[role=treeitem]').length,1,'only disclosure, not row double-click, expands');
revision++;await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,101);assert(host.scrollTop>0,'explicit external reveal still works');
selected='later';available=false;await render();selected='leaf99';await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,1);available=true;await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,101);assert(host.scrollTop>0,'pending selection is revealed when async children arrive');
await act(async()=>ui.unmount());console.log('PASS: 6 Tree DOM scenarios — visibility/disclosure independence, no disclosure scroll jump, eye does not select, row double-click does not expand, explicit reveal, async reveal.');
})().catch(e=>{console.error(e);process.exitCode=1;}).finally(()=>{fs.rmSync(scratch,{recursive:true,force:true});dom.window.close();});
+10
View File
@@ -0,0 +1,10 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {treeSelectionRange} from '../packages/ui-react/dist/treeSelectionRange.js';
test('tree ranges include endpoints in both directions and only visible rows',()=>{
const visible=['project','group','first','last','other'];
assert.deepEqual(treeSelectionRange(visible,'first','last'),['first','last']);
assert.deepEqual(treeSelectionRange(visible,'last','first'),['first','last']);
assert.deepEqual(treeSelectionRange(visible,'filtered-out','last'),['last']);
assert.deepEqual(treeSelectionRange(visible,null,'first'),['first']);
});
+59
View File
@@ -0,0 +1,59 @@
{
"compactLegacy": [
"packages/ui-core/styles.css | .nodedc-admin-context__body small | font-size | 0.72rem",
"packages/ui-core/styles.css | .nodedc-admin-panel__group-label | font-size | 0.68rem",
"packages/ui-core/styles.css | .nodedc-application-panel__titles span | font-size | 0.68rem",
"packages/ui-core/styles.css | .nodedc-application-side-panel__description | font-size | 0.72rem",
"packages/ui-core/styles.css | .nodedc-environment-settings__quick-actions span | font-size | 0.68rem",
"packages/ui-core/styles.css | .nodedc-environment-settings__surface > span | font-size | 0.74rem",
"packages/ui-core/styles.css | .nodedc-feature-settings__group | font-size | 0.66rem",
"packages/ui-core/styles.css | .nodedc-header__avatar | font-size | 0.72rem",
"packages/ui-core/styles.css | .nodedc-landing-stage__footer | font-size | 0.57rem",
"packages/ui-core/styles.css | .nodedc-media-field__kind | font-size | 0.62rem",
"packages/ui-core/styles.css | .nodedc-media-file__button | font-size | 0.78rem",
"packages/ui-core/styles.css | .nodedc-media-file__name | font-size | 0.78rem",
"packages/ui-core/styles.css | .nodedc-media-source-button | font-size | 0.68rem",
"packages/ui-core/styles.css | .nodedc-media-url | font-size | 0.78rem",
"packages/ui-core/styles.css | .nodedc-settings-card__titles > span | font-size | 0.66rem",
"packages/ui-core/styles.css | .nodedc-share-access__avatar | font-size | 0.68rem",
"packages/ui-core/styles.css | .nodedc-share-access__summary-avatar | font-size | 0.62rem",
"packages/ui-core/styles.css | .nodedc-share-access__summary-count | font-size | 0.68rem",
"packages/ui-core/styles.css | .nodedc-user-profile-card__cover > span:not(.nodedc-header__avatar) | font-size | 0.78rem"
],
"titles": [
".nodedc-application-panel__titles h1",
".nodedc-admin-panel__head h2",
".nodedc-window__title"
],
"exceptions": [
{
"key": "packages/ui-core/styles.css | .nodedc-description, .nodedc-settings-card__titles p, .nodedc-settings-card__body :where(p:not([class])) | font-size | var(--nodedc-description-font-size, var(--nodedc-font-size-sm))",
"reason": "Canonical Description fallback, compact sm token."
},
{
"key": "packages/ui-core/styles.css | .nodedc-range-scale__limit | font-size | calc(var(--nodedc-font-size-xs) * 0.9)",
"reason": "Existing compact viewport label multiplier below sm/xs."
},
{
"key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(3rem, 7vw, 7.6rem)",
"reason": "Cover display heading only; never an operational value or message."
},
{
"key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(2.7rem, 7vw, 5.6rem)",
"reason": "Cover display heading only; never an operational value or message."
},
{
"key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(2.8rem, 14vw, 5rem)",
"reason": "Cover display heading only; never an operational value or message."
},
{
"key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(2.7rem, 6vw, 5rem)",
"reason": "Cover display heading only; never an operational value or message."
},
{
"key": "packages/ui-core/styles.css | .nodedc-navigation-cube text | font | 600 9px var(--nodedc-font-family)",
"reason": "SVG viewBox coordinate text, not a CSS-screen text size."
}
],
"inlineExceptions": []
}
+29
View File
@@ -0,0 +1,29 @@
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);
});
test('custom tool minimum applies to restored geometry and every resize edge',()=>{
const minimum={width:380,height:280};
const restored=fitWindow({...r,width:320,height:200},bounds,minimum);
assert.equal(restored.width,380);assert.equal(restored.height,280);
for(const edge of windowResizeEdges)for(const delta of [-3000,3000]){
const resized=resizeWindow(r,edge,delta,delta,bounds,minimum);
assert.ok(resized.width>=380&&resized.height>=280);
}
assert.deepEqual(fitWindow(r,{width:280,height:180},minimum),{left:8,top:8,width:264,height:164});
const tiny=fitWindow(r,{width:10,height:10},minimum);assert.equal(tiny.width,1);assert.equal(tiny.height,1);
});