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
75 changed files with 1875 additions and 284 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",
+61 -20
View File
@@ -1,14 +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,
@@ -34,7 +39,6 @@ import {
ResizableViewport,
SceneAnnotation,
HeaderNavigation,
HeaderProfile,
HeaderWorkspace,
Icon,
IconButton,
@@ -121,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" },
@@ -147,7 +152,7 @@ const materialDefaults: Record<NodedcTheme, MaterialDraft> = {
panelOpacity: 100,
fieldHex: "#2a2a2c",
fieldOpacity: 100,
nestedHex: "#0b0b0d",
nestedHex: "#0d0d0f",
},
light: {
panelHex: "#ffffff",
@@ -225,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: "Контент",
@@ -245,6 +250,9 @@ 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: "Активность",
@@ -262,6 +270,7 @@ const iconLabels: Record<IconName, string> = {
close: "Закрыть",
copy: "Копировать",
database: "База данных",
pin: "Закрепить",
download: "Скачать",
edit: "Редактировать",
eye: "Показать",
@@ -275,6 +284,8 @@ const iconLabels: Record<IconName, string> = {
image: "Изображение",
inbox: "Уведомления",
info: "Информация",
"info-plain": "Информация без окружности",
"fit-view": "Вписать модель",
key: "Ключ",
layers: "Слои",
list: "Список задач",
@@ -333,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 },
@@ -386,7 +397,7 @@ 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);
@@ -396,6 +407,7 @@ export function CatalogApp() {
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);
@@ -407,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);
@@ -547,6 +560,7 @@ export function CatalogApp() {
applyNodedcTheme(document.documentElement, {
theme,
appearance: missionAppearance ? "mission" : "default",
edges: flatEdges ? "flat" : "default",
accent,
material: {
panel: panelMaterial,
@@ -556,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);
@@ -1342,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} />
@@ -1390,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">
@@ -1406,7 +1422,7 @@ export function CatalogApp() {
</FieldFrame>
<FieldFrame label="Engine / split select">
<Select
variant="split"
variant="split" shape="pill"
label="Тип связи"
value={connectionType}
options={[
@@ -1464,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">
@@ -1500,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="Получение сведений" />
@@ -1516,6 +1548,8 @@ export function CatalogApp() {
<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>
@@ -1583,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
@@ -1714,6 +1748,11 @@ export function CatalogApp() {
<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" />
<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>Прозрачная плашка над сценой</h2>
@@ -1776,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">
@@ -2148,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}
@@ -2161,7 +2201,6 @@ export function CatalogApp() {
{ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" },
]}
/>
</HeaderProfile>
}
/>
}
@@ -2324,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,
@@ -2337,7 +2376,7 @@ export function CatalogApp() {
) : null}
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
<Tree label="Пример дерева объектов" selected={treeSelected} onSelect={setTreeSelected} onVisibilityChange={(_,visible)=>setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/>
<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}
@@ -2348,12 +2387,14 @@ export function CatalogApp() {
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="Создать модуль"
headerActionsPlacement="before-close"
headerActions={<IconButton label="Очистить форму" onClick={() => {setCreateModuleName("");setCreateModuleSlug("");}}><Icon name="trash"/></IconButton>}
subtitle="Свободное окно · шапка: перемещение · края: размер"
size="sm"
onClose={() => setCreateModuleOpen(false)}
+8 -6
View File
@@ -1,13 +1,15 @@
import {useState} from 'react';
import {Button,Description,EditorDockLayout,EditorWorkspace,type EditorDockState} from '@nodedc/ui-react';
export function EditorDockExample(){
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 <><Button onClick={()=>{setOpen({objects:true,materials:true});setEditing(true);}}>Открыть редактор сцены</Button><div style={{height:480}}>
<EditorWorkspace editing={editing} title="Редактор сцены" subtitle="Общая оконная система" onBack={()=>setEditing(false)}>
<EditorDockLayout value={layout} onChange={setLayout} enabled={editing} primary={<div style={{display:'grid',height:'100%',placeContent:'center'}}><Description>Закреплённая сцена</Description><Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button></div>}
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:'Материалы',open:open.materials,onClose:()=>setOpen(v=>({...v,materials: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.
+77 -4
View File
@@ -8,7 +8,8 @@
- `default` — обычная карточка/панель;
- `strong` — dropdown, modal и поверхность над сложным фоном;
- `soft` — вложенная или вторичная область.
- `soft` — утопленная вторичная область / canvas, не подложка формы;
- `group` — нейтральная группа как SettingsCard, для самостоятельного элемента коллекции.
`radius="pill"` задаёт каноническую капсульную геометрию через `--nodedc-radius-circle`. Она предназначена, в частности, для компактных вертикальных и горизонтальных реек из круглых действий: верхняя и нижняя части поверхности повторяют круг кнопок без прямых торцевых пролётов. Consumer не воспроизводит этот радиус локальным CSS.
@@ -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 действий.
@@ -356,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 владеет:
- заголовками разделов;
@@ -494,6 +513,8 @@ The first optional Hold action controls the existing persisted `autoHide` settin
### 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.
@@ -519,3 +540,55 @@ Exact `RangeControl` editors synchronize external controlled-value changes while
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.
+35
View File
@@ -29,3 +29,38 @@ Explanatory paragraphs use `Description`, the same contract as `SettingsCard.des
пояснения вне карточки также используют `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.
+20
View File
@@ -151,3 +151,23 @@ Turning the free mode off returns the same contents to the normal centered size
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.
+7 -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 && npm run test:window-geometry && npm run test:editor-dock",
"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",
@@ -45,7 +45,12 @@
"test:analysis-controls": "node --test scripts/analysis-controls.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: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;
}
+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"
+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) {
+157 -43
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;
}
@@ -693,7 +711,7 @@ textarea.nodedc-field__control {
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;
}
@@ -1020,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:
@@ -1431,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) {
@@ -1458,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;
}
@@ -1703,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;
}
@@ -1711,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;
}
@@ -1847,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;
@@ -1855,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;
}
@@ -2008,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;
}
@@ -2047,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;
@@ -3151,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;
}
@@ -3549,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 {
@@ -3637,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;
@@ -3734,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);
}
@@ -3914,6 +3945,7 @@ textarea.nodedc-field__control {
overflow: auto;
}
.nodedc-header__profile-button,
.nodedc-user-profile-menu__trigger-label {
display: none;
}
@@ -4003,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%); } }
@@ -4096,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;
}
@@ -4131,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;
}
@@ -4238,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;
}
@@ -4350,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) {
@@ -4376,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); }
@@ -4530,14 +4547,19 @@ textarea.nodedc-field__control {
.nodedc-editor-workspace__body {position:relative;flex:1;min-height:0;min-width:0;overflow:hidden;}
.nodedc-editor-dock {position:absolute;inset:0;overflow:auto;overscroll-behavior:contain;isolation:isolate;}
.nodedc-editor-dock__canvas {position:relative;width:100%;height:100%;}
.nodedc-editor-dock__primary {position:absolute;overflow:hidden;min-width:0;min-height:0;}
.nodedc-editor-dock__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;}
@@ -4565,7 +4587,7 @@ 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)); }
@@ -4662,3 +4684,95 @@ textarea.nodedc-field__control {
.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"> {}
+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;
+7 -6
View File
@@ -7,6 +7,7 @@ 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;
@@ -38,7 +39,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
const required=dockMinimum(visibleTree,minimums),area={...bounds,width:Math.max(bounds.width,required.width),height:Math.max(bounds.height,required.height)};
const constrained=constrainDockTree(visibleTree,area,minimums)!;
const rects=dockRects(constrained,area);
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds);
const 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();},[]);
@@ -56,8 +57,8 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
const p=point(e),dx=p.x-g.x,dy=p.y-g.y;
if(!g.moved&&Math.hypot(dx,dy)<6)return;
g.moved=true;
const b=latest.current.bounds;
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b);
const 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();
@@ -84,7 +85,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
else if(position)setKeyboard({id,target:{activeId:id,overId:keyboard.target?.overId??primaryId,position,scope:e.shiftKey||!keyboard.target?'workspace':keyboard.target.scope}});
else return;
}else if(e.key==='Enter'||e.key===' '){setKeyboard({id,target:null});activate(id);}
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds)}});}
else 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();
};
@@ -97,11 +98,11 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
return <div ref={viewport} className={cn('nodedc-editor-dock',className)} data-editing={enabled||undefined} data-dragging={!!drag||undefined}>
<div ref={host} className="nodedc-editor-dock__canvas" style={{minWidth:required.width,minHeight:required.height}}>
<EditorSplits tree={constrained} bounds={area} minimums={minimums} onResize={(path,ratio)=>onChange({...value,tree:mergeEditorDockRatios(value.tree,resizeDockSplit(constrained,path,ratio))})}/>
<div className="nodedc-editor-dock__primary" data-editor-primary={primaryId} style={rects[primaryId]}>{primary}</div>
<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-active={order.at(-1)===tool.id||undefined}
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)}>
+12 -8
View File
@@ -1,12 +1,15 @@
import {useEffect,useId,useLayoutEffect,useRef,useState,type ReactNode} from 'react';
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}
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}:EditorWorkspaceProps){
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]);
@@ -16,7 +19,7 @@ export function EditorWorkspace({editing,title,subtitle,onBack,children,classNam
if(host.parentElement!==target){if(target.moveBefore&&host.isConnected)target.moveBefore(host,null);else target.append(host);}
host.dataset.editing=String(editing);
if(editing)host.querySelector<HTMLElement>('[data-editor-back]')?.focus({preventScroll:true});
else {setExpanded(false);if(opener.current?.isConnected)opener.current.focus({preventScroll:true});}
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(
@@ -25,10 +28,11 @@ export function EditorWorkspace({editing,title,subtitle,onBack,children,classNam
{editing&&<header className="nodedc-window__head nodedc-editor-workspace__head">
<div className="nodedc-window__titles"><h1 id={titleId} className="nodedc-window__title">{title}</h1>{subtitle&&<p className="nodedc-window__subtitle">{subtitle}</p>}</div>
<div className="nodedc-window__actions">
<IconButton data-editor-back label="Вернуться из редактора сцены" onClick={onBack}><Icon name="chevron-left"/></IconButton>
<IconButton label={expanded?'Восстановить окно редактора':'Развернуть окно редактора'} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton>
<IconButton label="Завершить редактирование сцены" aria-pressed onClick={onBack}><Icon name="edit"/></IconButton>
<IconButton label="Закрыть редактор сцены" onClick={onBack}><Icon name="close"/></IconButton>
{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>
@@ -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>
);
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { createGlassMaterialVariables, type GlassMaterialSettings } from "@noded
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";
+27 -2
View File
@@ -1,5 +1,9 @@
import {
MousePointer2,
Pipette,
createLucideIcon,
Glasses,
Cuboid,
Move,
CirclePlus,
Box,
@@ -47,6 +51,8 @@ import {
PanelTop,
Pencil,
Play,
Pin,
Power,
Plus,
Minus,
RefreshCw,
@@ -68,10 +74,26 @@ 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,
@@ -94,6 +116,7 @@ const icons = {
close: X,
copy: Copy,
database: Database,
pin: Pin,
download: Download,
edit: Pencil,
eye: Eye,
@@ -107,6 +130,7 @@ const icons = {
image: Image,
inbox: Inbox,
info: Info,
"info-plain": InformationPlain,
key: KeyRound,
layers: Layers,
list: ListChecks,
@@ -118,6 +142,7 @@ const icons = {
panel: PanelTop,
plan: Map,
play: Play,
power: Power,
plus: Plus,
minus: Minus,
profile: UserCircle,
+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)}
+44
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,
@@ -155,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">
@@ -277,7 +295,27 @@ function hsvToHex({ h, s, v }: Hsv): string {
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;
@@ -302,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}
@@ -354,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
@@ -371,6 +414,7 @@ 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"
{...props}
+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>;
}
+35 -12
View File
@@ -1,27 +1,49 @@
import {useLayoutEffect,useRef,useState,type CSSProperties} from 'react';
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 TreeProps {nodes:TreeNode[];selected:string|null;onSelect:(id:string)=>void;onVisibilityChange?:(id:string,visible:boolean)=>void;label:string;query?:string;revealKey?:number}
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,onSelect,onVisibilityChange,label,query='',revealKey}:TreeProps){
const [collapsed,setCollapsed]=useState<Set<string>>(()=>new Set());
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.has(node.id);rows.push({node,depth,open});if(open)flatten(node.children??[],depth+1);}};flatten(nodes);
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;};
useLayoutEffect(()=>{if(selected){setFocus(selected);setCollapsed(old=>{if(![...ancestors].some(id=>old.has(id)))return old;const next=new Set(old);for(const id of ancestors)next.delete(id);return next;});}},[selected,revealKey]);
useLayoutEffect(()=>{if(selected)reveal(selected);},[selected,revealKey,query,collapsed]);
const toggle=(id:string)=>setCollapsed(old=>{const next=new Set(old);if(next.has(id))next.delete(id);else next.add(id);return next;});
const select=(id:string)=>{setFocus(id);onSelect(id);elements.current.get(id)?.focus({preventScroll:true});reveal(id);};
return <div ref={host} className="nodedc-tree" role="tree" aria-label={label}>
{rows.map(({node,depth,open},position)=><div key={node.id} ref={element=>{if(element)elements.current.set(node.id,element);else elements.current.delete(node.id);}} role="treeitem" aria-level={depth+1} aria-selected={selected===node.id} aria-expanded={node.children?.length?open:undefined} tabIndex={(focus??selected??rows[0]?.node.id)===node.id?0:-1} className="nodedc-tree__row" style={{'--tree-depth':depth} as CSSProperties} title={node.label} onFocus={()=>setFocus(node.id)} onClick={()=>select(node.id)} onDoubleClick={()=>node.children?.length&&toggle(node.id)} onKeyDown={event=>{
// 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;
@@ -32,11 +54,12 @@ export function Tree({nodes,selected,onSelect,onVisibilityChange,label,query='',
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.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>
)}
+25 -8
View File
@@ -1,4 +1,5 @@
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
@@ -11,6 +12,7 @@ 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";
@@ -37,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;
@@ -64,6 +68,7 @@ export function Window({
children,
footer,
headerActions,
headerActionsPlacement = "before-move",
size = "md",
placement = "center",
closeLabel = "Закрыть",
@@ -82,6 +87,9 @@ export function Window({
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);
@@ -100,10 +108,10 @@ export function Window({
const isFloating = floating && allowFloating && placement === "center";
const freeGeometry = isFloating || (resizable && placement === "end");
const canDrag = draggable || freeGeometry;
const shouldLockBodyScroll = !isFloating && (lockBodyScroll ?? placement === "center");
const shouldTrapFocus = !isFloating && (trapFocus ?? placement === "center");
const modeRef = useRef({ shouldTrapFocus, isFloating });
modeRef.current = { shouldTrapFocus, isFloating };
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(() => {
@@ -116,7 +124,15 @@ export function Window({
});
const handleKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
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();
@@ -227,7 +243,7 @@ export function Window({
return createPortal(
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} data-floating={isFloating || undefined} 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)}
@@ -273,7 +289,7 @@ 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) {
@@ -282,6 +298,7 @@ export function Window({
}
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>
@@ -298,7 +315,7 @@ export function Window({
{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(' ');
}
+5 -1
View File
@@ -48,9 +48,13 @@ export {KeyButton, type KeyButtonProps} from './KeyButton.js';
export type {DockMinimum, DockMinimums} from "@nodedc/ui-core";
export {Tree,type TreeNode,type TreeProps} from "./Tree.js";
export {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);
}
+7 -6
View File
@@ -3,15 +3,16 @@ export type WindowRect = { left: number; top: number; width: number; height: num
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): WindowRect {
const width = clamp(rect.width, Math.min(320, bounds.width - 16), Math.max(1, bounds.width - 16));
const height = clamp(rect.height, Math.min(200, bounds.height - 16), Math.max(1, bounds.height - 16));
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): WindowRect {
const r = fitWindow(rect, bounds), right = r.left + r.width, bottom = r.top + r.height;
const minWidth = Math.min(320, bounds.width - 16), minHeight = Math.min(200, bounds.height - 16);
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;
+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."
}
]
+158 -28
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,7 +105,8 @@
"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. Scene overlays reuse V4 blur and tint with independent translucent density.",
"anatomy": [
@@ -109,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.",
"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."
"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."
]
},
{
@@ -157,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."
]
},
{
@@ -285,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."
]
},
{
@@ -305,12 +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.",
"HEX text keeps incomplete drafts; valid six-digit colors apply live, invalid drafts revert on blur/Escape, Enter commits; external undo updates the field."
"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."
]
},
{
@@ -332,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",
@@ -382,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."
]
},
{
@@ -396,7 +428,9 @@
],
"domPackage": "@nodedc/ui-dom",
"domExports": [
"createModalController"
"createModalController",
"createModalSizeController",
"fitModalSize"
],
"domContract": [
"nodedc-overlay",
@@ -412,9 +446,12 @@
"backdrop close policy",
"modal-only body scroll lock",
"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"
"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.",
@@ -427,7 +464,8 @@
"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."
"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."
]
},
{
@@ -465,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."
]
},
{
@@ -509,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",
@@ -661,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."
]
},
{
@@ -741,7 +782,8 @@
"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.",
"ApplicationPanel allowFullscreen exposes an owned full-window context; the whole panel and its header move atomically, preserving the renderer and body-portaled inspectors."
"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."
]
},
{
@@ -775,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",
@@ -923,7 +967,8 @@
"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."
]
},
{
@@ -1095,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."
]
},
{
@@ -1110,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.",
@@ -1188,7 +1236,8 @@
"summary": "Secondary explanatory copy matching SettingsCard descriptions.",
"rules": [
"Use the same inherited family, regular 400 weight, small font token, muted text token and 1.4 line height for explanatory paragraphs. Do not restyle per feature.",
"Use role=status for explanatory pending/result copy. SettingsCard applies the same contract to unclassed body paragraphs as a fallback, without changing headings or controls."
"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."
]
},
{
@@ -1224,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",
@@ -1239,7 +1289,8 @@
"exports": [
"Tree",
"TreeNode",
"TreeProps"
"TreeProps",
"TreeSelectionGesture"
],
"domContract": [
"nodedc-tree",
@@ -1247,14 +1298,19 @@
],
"summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.",
"behavior": [
"selection expands ancestors and scrolls only the tree container",
"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"
"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."
"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."
]
},
{
@@ -1343,7 +1399,9 @@
"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",
@@ -1357,7 +1415,79 @@
"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."
"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."
]
}
]
+10 -2
View File
@@ -32,7 +32,9 @@
"panel",
"apps",
"layers",
"move"
"move",
"power",
"pipette"
]
},
{
@@ -53,6 +55,7 @@
"sliders",
"search",
"orthographic",
"fit-view",
"perspective"
]
},
@@ -78,7 +81,10 @@
"curve",
"undo",
"redo",
"add-point"
"add-point",
"ruler",
"section",
"isolate"
]
},
{
@@ -93,6 +99,7 @@
"check",
"alert",
"info",
"info-plain",
"activity",
"lock",
"key",
@@ -115,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%"/);
});
+18
View File
@@ -54,3 +54,21 @@ test('repeated dock and float transitions retain unique tools and tile the full
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/);
}
});
+1 -1
View File
@@ -31,7 +31,7 @@ test('legacy card paragraphs and live descriptions share small muted typography,
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-font-size-sm)','line-height: 1.4'])assert.ok(copy.body.includes(declaration),declaration);
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": []
}
+12
View File
@@ -15,3 +15,15 @@ test('viewport shrink retains reachable header and fits small screens',()=>{
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);
});