Author SHA1 Message Date
Codex cb534dbe39 feat(ui): add docking, viewport controls and composed settings
Add shared dock layouts, navigation cube, range bands, progress actions and comparison surfaces. Extend toolbar menus and loading composition, and align tokens, registry entries, documentation and the living catalog.
2026-10-29 09:38:25 +03:00
Codex a6e6c8f2d9 Add shared Mission Core operator appearance profile 2026-09-30 22:42:27 +03:00
Codex 2d23a0262e docs(ui): record narrow modal gutter contract 2026-09-30 21:34:29 +03:00
Codex 2ee34ac912 fix(ui): contain narrow settings windows within overlay bounds 2026-09-30 21:33:30 +03:00
Codex 77091fda98 feat(ui): support window header actions and disclosure collapse icon 2026-09-30 20:51:17 +03:00
Codex 1b63366d2e feat(ui): add command terminal icon and align window footer actions 2026-09-28 18:43:06 +03:00
Codex 9aa6f949b0 feat(ui): support invisible resizable split separators 2026-09-25 19:13:39 +03:00
Codex a5a73c8753 feat(ui): add momentary keyboard control surface 2026-09-25 16:35:14 +03:00
Codex 8dd9190573 feat(ui): add spatial clipping scale and compact record actions 2026-09-21 08:45:10 +03:00
Codex 67025ee209 fix(ui): add layer icon and preserve switch contrast 2026-09-10 22:11:39 +03:00
Codex 8c53f73ee5 Standardize action and region loading states
Keep progress inside the initiating Button/IconButton or centered within a
LoadingRegion without changing layout or unmounting live content. Document
ownership and completion/error behavior in the registry and living catalog.

Validation: qualified NET02 DG build/typecheck/registry/loading tests;
existing browser geometry, theme and error lifecycle acceptance. All eleven
committed files match the qualified source artifact byte for byte.
2026-09-10 09:19:12 +03:00
Codex b10fd5d645 Extract shared home and environment settings for product reuse 2026-09-07 22:54:17 +03:00
Codex 26a1bf72a2 Keep browser autofill within canonical field colors 2026-09-07 21:06:00 +03:00
Codex 5b882bc3d9 Support centered SettingsCard result messages 2026-09-07 13:43:23 +03:00
Codex 1bdfc6c240 docs(ui): keep viewport tools within their controlled split pane 2026-09-06 01:34:41 +03:00
Codex 70ce00f2d0 docs(ui): define compact feedback and nonblocking inspector close 2026-09-06 01:34:15 +03:00
Codex 999864e5b0 feat(ui): support leading resource status indicators 2026-09-06 01:17:37 +03:00
Codex 3adeb33b1b fix(ui): standardize compact operational headings and empty states 2026-09-06 00:41:48 +03:00
Codex be6463fd59 fix(catalog): import the status indicator specimen 2026-09-06 00:01:06 +03:00
Codex 47d4f19d99 feat(ui): support a single status indicator without duplicate glyphs 2026-09-05 23:59:49 +03:00
Codex 17e150b1c7 feat(ui): add measured linear progress to resource rows 2026-09-05 23:19:36 +03:00
Codex 8a79dfe84d feat(ui): share resource rows and refine Node shell behavior 2026-09-05 17:25:27 +03:00
Codex d51d8bb7f6 feat(ui): добавить плотные контролы для viewer 2026-08-30 13:28:20 +03:00
Codex c8f4916423 feat(ui): canonicalize exact range editing 2026-08-28 11:41:21 +03:00
Codex 6e7255ecdb feat(ui): stabilize laboratory viewer primitives 2026-08-24 22:31:35 +03:00
Codex c7e136cc14 feat(icons): add visibility controls 2026-08-22 11:24:07 +03:00
Codex 51cb426c6b refactor: move Device Manager app to Device Core repository 2026-08-21 12:23:21 +03:00
Codex 8f38c76f79 fix(device-manager): align shell with NODE.DC UX canon 2026-08-13 11:51:08 +03:00
Codex 2fa1951f51 feat(device-manager): add safe B2 service ping command 2026-08-13 11:38:26 +03:00
Codex 19f0d97e23 feat(device-manager): add full device profile workspace 2026-08-13 11:38:26 +03:00
Codex bbb50e06b4 feat(ui): add activity indicator governance 2026-08-13 11:38:26 +03:00
Codex d6c62da470 feat(device-manager): add safe device enrollment 2026-08-13 11:37:36 +03:00
Codex a3385e83c4 fix(device-manager): keep auth redirects alive 2026-08-13 11:37:36 +03:00
Codex 9fa81fde9a test(device-manager): prove production file-token startup 2026-08-13 11:37:36 +03:00
Codex 117bfe0c3a feat(device-manager): trust Hub owner scopes 2026-08-13 11:37:36 +03:00
Codex 1c5246afe8 feat(device-manager): add control and audit workspaces 2026-08-13 11:37:36 +03:00
Codex 4116f5ba95 feat(device-manager): add standalone project workspace 2026-08-13 11:37:36 +03:00
91 changed files with 5654 additions and 312 deletions
+213 -17
View File
@@ -2,21 +2,32 @@ import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties,
import { applyGlassMaterial, applyNodedcTheme, defaultGlassMaterial, type GlassMaterialSettings, type NodedcTheme, type RgbTuple } from "@nodedc/ui-core"; 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 { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTemplateDefinition } from "@nodedc/page-patterns";
import { import {
ActivityIndicator,
LoadingRegion,
Description,
ComparisonTable,
StatusBadge,
ProgressBar,
ProgressButton,
LayerStackIndicator,
AdminNavigationPanel, AdminNavigationPanel,
AppHeader, AppHeader,
ApplicationPanel, ApplicationPanel,
ApplicationShell, ApplicationShell,
ApplicationSidePanel, ApplicationSidePanel,
Button, Button,
KeyButton,
Checker, Checker,
ColorField, ColorField,
ConfirmationModal, ConfirmationModal,
ControlRow, ControlRow,
Dropdown, Dropdown,
DragDropRoot, DragDropRoot,
DockLayout, DockHandle, balancedDockTree, type DockTree,
DraggableItem, DraggableItem,
DropZone, DropZone,
FieldFrame, FieldFrame,
FeatureSettingsWindow,
GlassSurface, GlassSurface,
GlassMaterialSurface, GlassMaterialSurface,
HeaderNavigation, HeaderNavigation,
@@ -28,10 +39,15 @@ import {
InspectorSelectField, InspectorSelectField,
MediaSourceField, MediaSourceField,
RangeControl, RangeControl,
ResourceRow,
ResourceList,
SegmentedControl, SegmentedControl,
SegmentedGroup,
SegmentedButton,
Select, Select,
ShareAccessModal, ShareAccessModal,
ShareLinkModal, ShareLinkModal,
SplitPane,
SortableItem, SortableItem,
SortableScope, SortableScope,
SettingsCard, SettingsCard,
@@ -41,6 +57,7 @@ import {
ToastCard, ToastCard,
ToastStack, ToastStack,
Toolbar, Toolbar,
NavigationCube,
UserProfileMenu, UserProfileMenu,
useApplicationWorkspace, useApplicationWorkspace,
Window, Window,
@@ -76,6 +93,7 @@ import {
type StoredLayout, type StoredLayout,
} from "./designProfile.js"; } from "./designProfile.js";
import { FoundrySettingsModal } from "./FoundrySettingsModal.js"; import { FoundrySettingsModal } from "./FoundrySettingsModal.js";
import { EnvironmentCatalogDemo } from "./EnvironmentCatalogDemo.js";
type CatalogSection = "controls" | "media" | "glass" | "status" | "modals" | "icons"; type CatalogSection = "controls" | "media" | "glass" | "status" | "modals" | "icons";
type StudioContext = "visual" | "pages" | "applications"; type StudioContext = "visual" | "pages" | "applications";
@@ -193,7 +211,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
{ {
title: "Окно и слой", title: "Окно и слой",
note: "Launcher / Hub", note: "Launcher / Hub",
icons: ["close", "plus", "expand", "minimize", "refresh", "panel", "apps"], icons: ["close", "plus", "expand", "minimize", "refresh", "panel", "apps", "layers"],
}, },
{ {
title: "Навигация", title: "Навигация",
@@ -203,12 +221,12 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
{ {
title: "Редактирование", title: "Редактирование",
note: "Launcher / SEO", note: "Launcher / SEO",
icons: ["save", "edit", "trash", "copy", "upload", "download", "external"], icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "orthographic", "perspective", "select", "pen", "rectangle", "curve", "undo", "redo"],
}, },
{ {
title: "Состояние и доступ", title: "Состояние и доступ",
note: "Вся платформа", note: "Вся платформа",
icons: ["check", "alert", "activity", "lock", "key", "shield", "circle"], icons: ["check", "alert", "info", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
}, },
{ {
title: "Сущности", title: "Сущности",
@@ -218,17 +236,20 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
{ {
title: "Контент", title: "Контент",
note: "SEO / BIM / Engine", note: "SEO / BIM / Engine",
icons: ["image", "video", "file", "folder", "clipboard", "settings"], icons: ["camera", "plan", "play", "stop", "image", "video", "file", "folder", "clipboard", "settings", "terminal"],
}, },
]; ];
const iconLabels: Record<IconName, string> = { const iconLabels: Record<IconName, string> = {
"add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить",
activity: "Активность", activity: "Активность",
alert: "Предупреждение", alert: "Предупреждение",
apps: "Приложения", apps: "Приложения",
building: "Компания", building: "Компания",
camera: "Камера",
check: "Готово", check: "Готово",
"chevron-down": "Раскрыть", "chevron-down": "Раскрыть",
"chevron-up": "Свернуть",
"chevron-left": "Назад", "chevron-left": "Назад",
"chevron-right": "Вперёд", "chevron-right": "Вперёд",
circle: "Маркер", circle: "Маркер",
@@ -238,6 +259,8 @@ const iconLabels: Record<IconName, string> = {
database: "База данных", database: "База данных",
download: "Скачать", download: "Скачать",
edit: "Редактировать", edit: "Редактировать",
eye: "Показать",
"eye-off": "Скрыть",
expand: "Развернуть", expand: "Развернуть",
external: "Открыть снаружи", external: "Открыть снаружи",
file: "Файл", file: "Файл",
@@ -246,22 +269,29 @@ const iconLabels: Record<IconName, string> = {
grid: "Обзор", grid: "Обзор",
image: "Изображение", image: "Изображение",
inbox: "Уведомления", inbox: "Уведомления",
info: "Информация",
key: "Ключ", key: "Ключ",
layers: "Слои",
list: "Список задач", list: "Список задач",
lock: "Закрыто", lock: "Закрыто",
mail: "Приглашение", mail: "Приглашение",
minimize: "Свернуть", minimize: "Свернуть",
network: "Связи", network: "Связи",
panel: "Панель", panel: "Панель",
plan: "План",
play: "Воспроизвести",
target: "Таргеты", target: "Таргеты",
plus: "Добавить", plus: "Добавить",
profile: "Профиль", profile: "Профиль",
refresh: "Обновить", refresh: "Обновить",
"rotate-clockwise": "Повернуть по часовой стрелке",
save: "Сохранить", save: "Сохранить",
search: "Поиск", search: "Поиск",
settings: "Настройки", settings: "Настройки",
shield: "Доступ", shield: "Доступ",
sliders: "Параметры", sliders: "Параметры",
stop: "Остановить",
terminal: "Консоль команд",
trash: "Удалить", trash: "Удалить",
upload: "Загрузить", upload: "Загрузить",
users: "Участники", users: "Участники",
@@ -328,6 +358,7 @@ export function CatalogApp() {
const [createModuleDescription, setCreateModuleDescription] = useState(""); const [createModuleDescription, setCreateModuleDescription] = useState("");
const [deleteModuleOpen, setDeleteModuleOpen] = useState(false); const [deleteModuleOpen, setDeleteModuleOpen] = useState(false);
const [pageRemovalId, setPageRemovalId] = useState<string | null>(null); const [pageRemovalId, setPageRemovalId] = useState<string | null>(null);
const [previewLayers, setPreviewLayers] = useState<string[]>(["source"]);
const [applicationMode, setApplicationMode] = useState<"edit" | "preview">("edit"); const [applicationMode, setApplicationMode] = useState<"edit" | "preview">("edit");
const [designProfileSaveOpen, setDesignProfileSaveOpen] = useState(false); const [designProfileSaveOpen, setDesignProfileSaveOpen] = useState(false);
const [designProfileSaveMode, setDesignProfileSaveMode] = useState<"save" | "save-as">("save"); const [designProfileSaveMode, setDesignProfileSaveMode] = useState<"save" | "save-as">("save");
@@ -345,6 +376,7 @@ export function CatalogApp() {
const activePageTemplateId = pageTemplateIdFromView(activeView); const activePageTemplateId = pageTemplateIdFromView(activeView);
const [selectedStatus, setSelectedStatus] = useState<(typeof selectOptions)[number]["value"]>("active"); const [selectedStatus, setSelectedStatus] = useState<(typeof selectOptions)[number]["value"]>("active");
const [brightness, setBrightness] = useState(49); const [brightness, setBrightness] = useState(49);
const [sliceBand, setSliceBand] = useState<[number, number]>([-1.2, 51.5]);
const [glowDistance, setGlowDistance] = useState(105); const [glowDistance, setGlowDistance] = useState(105);
const [usePortColors, setUsePortColors] = useState(false); const [usePortColors, setUsePortColors] = useState(false);
const [connectionType, setConnectionType] = useState("spline"); const [connectionType, setConnectionType] = useState("spline");
@@ -359,8 +391,14 @@ export function CatalogApp() {
const [workspaceWindowDemoOpen, setWorkspaceWindowDemoOpen] = useState(true); const [workspaceWindowDemoOpen, setWorkspaceWindowDemoOpen] = useState(true);
const [workspaceWindowDemoMaximized, setWorkspaceWindowDemoMaximized] = useState(false); const [workspaceWindowDemoMaximized, setWorkspaceWindowDemoMaximized] = useState(false);
const [workspaceWindowDemoRect, setWorkspaceWindowDemoRect] = useState<WorkspaceWindowRect>({ x: 24, y: 24, width: 340, height: 230 }); const [workspaceWindowDemoRect, setWorkspaceWindowDemoRect] = useState<WorkspaceWindowRect>({ x: 24, y: 24, width: 340, height: 230 });
const [dockDemoTree, setDockDemoTree] = useState<DockTree | null>(() => balancedDockTree(["camera", "depth", "map", "scene"]));
const [splitPaneInvisible, setSplitPaneInvisible] = useState(false);
const [splitPaneDemoSize, setSplitPaneDemoSize] = useState(50);
const [sidePanelDemoOpen, setSidePanelDemoOpen] = useState(true); const [sidePanelDemoOpen, setSidePanelDemoOpen] = useState(true);
const [createModalOpen, setCreateModalOpen] = useState(false); const [createModalOpen, setCreateModalOpen] = useState(false);
const [missionAppearance, setMissionAppearance] = useState(false);
const [featureSettingsDemoOpen, setFeatureSettingsDemoOpen] = useState(false);
const [featureSettingsDemoSection, setFeatureSettingsDemoSection] = useState('general');
const [confirmOpen, setConfirmOpen] = useState(false); const [confirmOpen, setConfirmOpen] = useState(false);
const [shareAccessOpen, setShareAccessOpen] = useState(false); const [shareAccessOpen, setShareAccessOpen] = useState(false);
const [shareLinkOpen, setShareLinkOpen] = useState(false); const [shareLinkOpen, setShareLinkOpen] = useState(false);
@@ -399,6 +437,9 @@ export function CatalogApp() {
icon512: "/favicon/icon-512.png", icon512: "/favicon/icon-512.png",
}); });
const pendingFaviconIcoRef = useRef<Blob | null>(null); const pendingFaviconIcoRef = useRef<Blob | null>(null);
const [cubeSize,setCubeSize]=useState(66);
const [cubeEdgeOpacity,setCubeEdgeOpacity]=useState(1);
const [cubeDirection,setCubeDirection]=useState<number[]>([0,0,1]);
const [toolbarPlacement, setToolbarPlacement] = useState<ToolbarPlacement>("bottom"); const [toolbarPlacement, setToolbarPlacement] = useState<ToolbarPlacement>("bottom");
const [toolbarBg, setToolbarBg] = useState("#111115"); const [toolbarBg, setToolbarBg] = useState("#111115");
const [toolbarBorder, setToolbarBorder] = useState("#111117"); const [toolbarBorder, setToolbarBorder] = useState("#111117");
@@ -407,6 +448,8 @@ export function CatalogApp() {
const [toolbarMaxSize, setToolbarMaxSize] = useState(87); const [toolbarMaxSize, setToolbarMaxSize] = useState(87);
const [toolbarLensCount, setToolbarLensCount] = useState(5); const [toolbarLensCount, setToolbarLensCount] = useState(5);
const [toolbarAutoHide, setToolbarAutoHide] = useState(false); const [toolbarAutoHide, setToolbarAutoHide] = useState(false);
const [toolbarHideDelay,setToolbarHideDelay]=useState(5000);
const [toolbarGap,setToolbarGap]=useState(10);
const [shareEmail, setShareEmail] = useState(""); const [shareEmail, setShareEmail] = useState("");
const [shareRole, setShareRole] = useState<ShareRole>("editor"); const [shareRole, setShareRole] = useState<ShareRole>("editor");
const [shareMessage, setShareMessage] = useState(""); const [shareMessage, setShareMessage] = useState("");
@@ -470,6 +513,8 @@ export function CatalogApp() {
if (typeof stored.toolbar?.minSize === "number") setToolbarMinSize(stored.toolbar.minSize); if (typeof stored.toolbar?.minSize === "number") setToolbarMinSize(stored.toolbar.minSize);
if (typeof stored.toolbar?.maxSize === "number") setToolbarMaxSize(stored.toolbar.maxSize); if (typeof stored.toolbar?.maxSize === "number") setToolbarMaxSize(stored.toolbar.maxSize);
if (typeof stored.toolbar?.lensCount === "number") setToolbarLensCount(stored.toolbar.lensCount); if (typeof stored.toolbar?.lensCount === "number") setToolbarLensCount(stored.toolbar.lensCount);
if (typeof stored.toolbar?.hideDelay === "number") setToolbarHideDelay(stored.toolbar.hideDelay);
if (typeof stored.toolbar?.gap === "number") setToolbarGap(stored.toolbar.gap);
if (typeof stored.toolbar?.autoHide === "boolean") setToolbarAutoHide(stored.toolbar.autoHide); if (typeof stored.toolbar?.autoHide === "boolean") setToolbarAutoHide(stored.toolbar.autoHide);
}, []); }, []);
@@ -490,6 +535,7 @@ export function CatalogApp() {
useEffect(() => { useEffect(() => {
applyNodedcTheme(document.documentElement, { applyNodedcTheme(document.documentElement, {
theme, theme,
appearance: missionAppearance ? "mission" : "default",
accent, accent,
material: { material: {
panel: panelMaterial, panel: panelMaterial,
@@ -499,7 +545,7 @@ export function CatalogApp() {
}, },
}); });
document.documentElement.style.setProperty("--nodedc-canvas-soft", material.nestedHex); document.documentElement.style.setProperty("--nodedc-canvas-soft", material.nestedHex);
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme]); }, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme, missionAppearance]);
useEffect(() => { useEffect(() => {
applyGlassMaterial(document.documentElement, glassMaterial); applyGlassMaterial(document.documentElement, glassMaterial);
@@ -570,13 +616,15 @@ export function CatalogApp() {
} }
const toolbar = stored.toolbar; const toolbar = stored.toolbar;
if (toolbar) { if (toolbar) {
if (toolbar.placement === "left" || toolbar.placement === "right" || toolbar.placement === "bottom") setToolbarPlacement(toolbar.placement); if (toolbar.placement === "left" || toolbar.placement === "right" || toolbar.placement === "bottom" || toolbar.placement === "top") setToolbarPlacement(toolbar.placement);
if (toolbar.background) setToolbarBg(toolbar.background); if (toolbar.background) setToolbarBg(toolbar.background);
if (toolbar.border) setToolbarBorder(toolbar.border); if (toolbar.border) setToolbarBorder(toolbar.border);
if (toolbar.outline) setToolbarOutline(toolbar.outline); if (toolbar.outline) setToolbarOutline(toolbar.outline);
if (typeof toolbar.minSize === "number") setToolbarMinSize(toolbar.minSize); if (typeof toolbar.minSize === "number") setToolbarMinSize(toolbar.minSize);
if (typeof toolbar.maxSize === "number") setToolbarMaxSize(toolbar.maxSize); if (typeof toolbar.maxSize === "number") setToolbarMaxSize(toolbar.maxSize);
if (typeof toolbar.lensCount === "number") setToolbarLensCount(toolbar.lensCount); if (typeof toolbar.lensCount === "number") setToolbarLensCount(toolbar.lensCount);
if (typeof toolbar.hideDelay === "number") setToolbarHideDelay(toolbar.hideDelay);
if (typeof toolbar.gap === "number") setToolbarGap(toolbar.gap);
if (typeof toolbar.autoHide === "boolean") setToolbarAutoHide(toolbar.autoHide); if (typeof toolbar.autoHide === "boolean") setToolbarAutoHide(toolbar.autoHide);
} }
setLayoutSaveState("saved"); setLayoutSaveState("saved");
@@ -1045,6 +1093,7 @@ export function CatalogApp() {
maxSize: toolbarMaxSize, maxSize: toolbarMaxSize,
lensCount: toolbarLensCount, lensCount: toolbarLensCount,
autoHide: toolbarAutoHide, autoHide: toolbarAutoHide,
hideDelay:toolbarHideDelay,gap:toolbarGap,
}, },
}; };
const response = await fetch("/api/layout", { const response = await fetch("/api/layout", {
@@ -1253,6 +1302,7 @@ export function CatalogApp() {
{ value: "left", label: "Слева" }, { value: "left", label: "Слева" },
{ value: "right", label: "Справа" }, { value: "right", label: "Справа" },
{ value: "bottom", label: "Снизу" }, { value: "bottom", label: "Снизу" },
{ value: "top", label: "Сверху" },
]} ]}
onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)} onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)}
/> />
@@ -1267,6 +1317,8 @@ export function CatalogApp() {
<RangeControl label="Максимальный размер" value={toolbarMaxSize} min={28} max={88} formatValue={(value) => `${value}px`} onChange={(value) => setToolbarMaxSize(Math.max(toolbarMinSize, Math.round(value)))} /> <RangeControl label="Максимальный размер" value={toolbarMaxSize} min={28} max={88} formatValue={(value) => `${value}px`} onChange={(value) => setToolbarMaxSize(Math.max(toolbarMinSize, Math.round(value)))} />
<RangeControl label="Линза" value={toolbarLensCount} min={1} max={13} step={2} formatValue={(value) => `${value} иконок`} onChange={(value) => setToolbarLensCount(Math.round(value) % 2 === 0 ? Math.round(value) + 1 : Math.round(value))} /> <RangeControl label="Линза" value={toolbarLensCount} min={1} max={13} step={2} formatValue={(value) => `${value} иконок`} onChange={(value) => setToolbarLensCount(Math.round(value) % 2 === 0 ? Math.round(value) + 1 : Math.round(value))} />
<Checker checked={toolbarAutoHide} label="Автоскрытие" onChange={setToolbarAutoHide} /> <Checker checked={toolbarAutoHide} label="Автоскрытие" onChange={setToolbarAutoHide} />
<RangeControl label="Задержка скрытия" value={toolbarHideDelay} min={0} max={15000} step={250} formatValue={v=>`${v/1000} с`} onChange={setToolbarHideDelay}/>
<RangeControl label="Расстояние между кнопками" value={toolbarGap} min={0} max={24} step={1} formatValue={v=>`${v} px`} onChange={setToolbarGap}/>
</> </>
), ),
}, },
@@ -1278,7 +1330,9 @@ export function CatalogApp() {
<> <>
<ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow> <ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow>
<RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} /> <RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} />
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} formatValue={(value) => `${value}%`} onChange={setGlowDistance} /> <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} />
</> </>
), ),
}, },
@@ -1324,11 +1378,20 @@ export function CatalogApp() {
case "controls": case "controls":
return ( return (
<div className="catalog-grid"> <div className="catalog-grid">
<Preview title="Selection" note="integrated / split"> <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="Selection" note="integrated / split / inline">
<div className="catalog-form"> <div className="catalog-form">
<FieldFrame label="Hub / integrated select"> <FieldFrame label="Hub / integrated select" labelPlacement="below">
<Select label="Статус" value={selectedStatus} options={[...selectOptions]} searchable onChange={setSelectedStatus} /> <Select label="Статус" value={selectedStatus} options={[...selectOptions]} searchable onChange={setSelectedStatus} />
</FieldFrame> </FieldFrame>
<FieldFrame label="Select / независимое действие строки">
<Select label="Записи" value={selectedStatus} searchable onChange={setSelectedStatus}
options={selectOptions.map(option => ({ ...option, action: {
label: `Удалить ${option.label}`, icon: <Icon name="trash" />, tone: 'danger' as const,
disabled: option.value === 'active',
onAction: () => setConfirmOpen(true),
} }))} />
</FieldFrame>
<FieldFrame label="Engine / split select"> <FieldFrame label="Engine / split select">
<Select <Select
variant="split" variant="split"
@@ -1342,6 +1405,19 @@ export function CatalogApp() {
onChange={setConnectionType} onChange={setConnectionType}
/> />
</FieldFrame> </FieldFrame>
<FieldFrame label="Toolbar / inline select">
<Select
variant="inline"
label="Скорость воспроизведения"
value="1"
options={[
{ value: "0.5", label: "0,5×" },
{ value: "1", label: "1×" },
{ value: "2", label: "2×" },
]}
onChange={() => undefined}
/>
</FieldFrame>
<Dropdown <Dropdown
trigger={({ open, toggle, setTriggerRef, surfaceId }) => ( trigger={({ open, toggle, setTriggerRef, surfaceId }) => (
<Button ref={setTriggerRef} aria-expanded={open} aria-controls={surfaceId} icon={<Icon name="chevron-down" />} onClick={toggle}>Действия</Button> <Button ref={setTriggerRef} aria-expanded={open} aria-controls={surfaceId} icon={<Icon name="chevron-down" />} onClick={toggle}>Действия</Button>
@@ -1349,6 +1425,7 @@ export function CatalogApp() {
> >
{({ close }) => ( {({ close }) => (
<> <>
<Select label="Вложенный выбор статуса" value={selectedStatus} options={[...selectOptions]} onChange={setSelectedStatus} />
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="edit" /><span className="nodedc-dropdown-option__label">Переименовать</span></button> <button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="edit" /><span className="nodedc-dropdown-option__label">Переименовать</span></button>
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="copy" /><span className="nodedc-dropdown-option__label">Дублировать</span></button> <button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="copy" /><span className="nodedc-dropdown-option__label">Дублировать</span></button>
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="folder" /><span className="nodedc-dropdown-option__label">Архивировать</span></button> <button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="folder" /><span className="nodedc-dropdown-option__label">Архивировать</span></button>
@@ -1370,16 +1447,89 @@ export function CatalogApp() {
<Button variant="ghost" icon={<Icon name="external" />}>Открыть</Button> <Button variant="ghost" icon={<Icon name="external" />}>Открыть</Button>
<Button variant="danger" icon={<Icon name="trash" />}>Удалить</Button> <Button variant="danger" icon={<Icon name="trash" />}>Удалить</Button>
<IconButton label="Добавить"><Icon name="plus" /></IconButton> <IconButton label="Добавить"><Icon name="plus" /></IconButton>
<KeyButton label="Клавиша W">W</KeyButton>
<KeyButton label="Клавиша A нажата" pressed>A</KeyButton>
<KeyButton label="Клавиша S недоступна" disabled>S</KeyButton>
</div> </div>
</Preview> </Preview>
<Preview title="Оконные действия" note="круг `46 px`" className="catalog-preview--compact"> <Preview title="Активность" note="default / compact" className="catalog-preview--compact">
<div className="catalog-window-actions-demo"> <div className="catalog-inline catalog-inline--wrap">
<span className="catalog-inline">
<ActivityIndicator label="Загружаем данные" />
<span>Загружаем данные</span>
</span>
<Button loading>Подключить</Button>
<IconButton label="Обновить" loading><Icon name="refresh" /></IconButton>
</div>
<p className="catalog-preview__explanation">При reduced motion кольцо остаётся видимым без вращения; процесс и его завершение принадлежат приложению.</p>
</Preview>
<Preview title="Загрузка содержимого" note="в центре собственной области">
<LoadingRegion loading label="Ожидаем содержимое" />
</Preview>
<Preview title="Лампы состояния" note="один индикатор без дублирующего значка"><StatusBadge variant="indicator" tone="success" aria-label="Готово" title="Готово" /><StatusBadge variant="indicator" aria-label="Недоступно" title="Недоступно" /><StatusBadge tone="danger" pulse>Требуется внимание</StatusBadge></Preview>
<Preview title="Прогресс действия" note="idle / pending / disabled">
<div className="catalog-inline catalog-inline--wrap">
<ProgressButton label="Проанализировать" icon={<Icon name="layers" />} />
<ProgressButton label="Проанализировать" icon={<LayerStackIndicator />} progress={{label:"Анализ поверхности · 29 / 96",value:29/96}} />
<ProgressButton label="Проанализировать" icon={<LayerStackIndicator />} progress={{label:"Подготовка данных"}} />
<ProgressButton label="Проанализировать" disabled icon={<Icon name="layers" />} />
</div>
</Preview>
<Preview title="Независимые слои" note="multiple / empty / all">
<SegmentedGroup label="Слои и память">
<SegmentedButton active={previewLayers.includes("gaussian")} aria-pressed={previewLayers.includes("gaussian")}
onClick={()=>setPreviewLayers(current=>current.includes("gaussian")?current.filter(v=>v!=="gaussian"):[...current,"gaussian"])}>Gaussian</SegmentedButton>
<SegmentedButton disabled>Недоступный слой</SegmentedButton>
<Dropdown surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><SegmentedButton
ref={setTriggerRef} active={open} aria-expanded={open} aria-haspopup="dialog" aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
<p>Накопленные проезды этой локации.</p>
</Dropdown>
</SegmentedGroup>
<SegmentedControl selectionMode="multiple" label="Слои сцены" value={previewLayers} onChange={setPreviewLayers}
items={[{value:"source",label:"Источник"},{value:"geometry",label:"Геометрия"},{value:"unavailable",label:"Недоступно",disabled:true}]} />
</Preview>
<Preview title="Линейный прогресс" note="измеренный / неизвестный / завершённый">
<ProgressBar label="Подготовка" value={0.6} valueText="Три этапа из пяти" />
<ProgressBar label="Получение сведений" />
<ProgressBar label="Завершено" value={1} />
</Preview>
<Preview title="Строки ресурсов" note="Mission Core / общий список">
<ResourceList aria-label="Пример списка ресурсов">
<li><ResourceRow icon={<Icon name="file" />} title="Сохранённый результат" metadata="Сегодня · доступен для просмотра" actions={<IconButton label="Просмотреть пример" onClick={() => setProjectName("Сохранённый результат")}><Icon name="eye" /></IconButton>} /></li>
<li><ResourceRow icon={<Icon name="camera" />} title="Подключённая камера" description="Индикатор перед названием" statusPlacement="leading" status={<StatusBadge variant="indicator" tone="success" aria-label="Подключено" title="Подключено" />} actions={<IconButton label="Просмотреть камеру" onClick={() => setProjectName("Подключённая камера")}><Icon name="eye" /></IconButton>} /></li>
<li><ResourceRow icon={<Icon name="camera" />} title="Подготовка камеры" metadata="Проверка потоков" progress={{label:"Подготовка камеры",value:0.8}} aria-busy="true" actions={<IconButton label="Просмотр недоступен" disabled><Icon name="eye" /></IconButton>} /></li>
</ResourceList>
<SettingsCard title="Устройства не обнаружены" description="Подключите устройство, чтобы оно появилось в списке." />
<SettingsCard align="center" role="status" title="Настройки применены" description="Проверьте подключение устройства." />
</Preview>
<Preview title="Главная и окружение" note="единые компоненты · сохранение в памяти каталога">
<EnvironmentCatalogDemo />
</Preview>
<Preview title="Действия поверх сцены" note="круг `32.2 px` · единый viewport-канон 70%" className="catalog-preview--compact">
<div className="catalog-window-actions-demo nodedc-scene-controls">
<SegmentedControl label="Инструмент сцены" value={applicationMode} items={[{value:"edit",label:"Обзор"},{value:"preview",label:"Точки"}]} onChange={setApplicationMode}/>
<Button shape="pill" icon={<Icon name="refresh" />}>Обновить источник</Button> <Button shape="pill" icon={<Icon name="refresh" />}>Обновить источник</Button>
<Select label="Статус примера сцены" value={selectedStatus} options={[...selectOptions]} onChange={setSelectedStatus} />
<IconButton label="Добавить"><Icon name="plus" /></IconButton> <IconButton label="Добавить"><Icon name="plus" /></IconButton>
<IconButton label="Развернуть"><Icon name="expand" /></IconButton> <IconButton label="Развернуть"><Icon name="expand" /></IconButton>
<IconButton label="Закрыть"><Icon name="close" /></IconButton> <IconButton label="Закрыть"><Icon name="close" /></IconButton>
</div> </div>
</Preview> </Preview>
<Preview title="Вертикальная рейка" note="glass pill / круг `46 px`" className="catalog-preview--compact">
<GlassSurface
className="catalog-icon-rail-demo"
tone="strong"
radius="pill"
padding="sm"
materialRim={false}
role="toolbar"
aria-label="Режимы просмотра"
>
<IconButton label="Камера" aria-pressed="true"><Icon name="camera" /></IconButton>
<IconButton label="3D"><span aria-hidden="true">3D</span></IconButton>
<IconButton label="План"><Icon name="plan" /></IconButton>
</GlassSurface>
</Preview>
<Preview title="Workspace window" note="inline / bounded / controlled" className="catalog-preview--wide catalog-workspace-window-preview"> <Preview title="Workspace window" note="inline / bounded / controlled" className="catalog-preview--wide catalog-workspace-window-preview">
<div ref={workspaceWindowDemoRef} className="catalog-workspace-window-demo"> <div ref={workspaceWindowDemoRef} className="catalog-workspace-window-demo">
{workspaceWindowDemoOpen ? ( {workspaceWindowDemoOpen ? (
@@ -1394,6 +1544,7 @@ export function CatalogApp() {
setWorkspaceWindowDemoOpen(false); setWorkspaceWindowDemoOpen(false);
setWorkspaceWindowDemoMaximized(false); setWorkspaceWindowDemoMaximized(false);
}} }}
resizeIndicator={false}
title="Визуальный канал" title="Визуальный канал"
subtitle="WORKSPACE / AUXILIARY VIEW" subtitle="WORKSPACE / AUXILIARY VIEW"
status="LIVE" status="LIVE"
@@ -1418,6 +1569,28 @@ export function CatalogApp() {
</div> </div>
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p> <p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
</Preview> </Preview>
<Preview title="Split pane" note="pointer / keyboard / controlled" className="catalog-preview--wide catalog-split-pane-preview">
<Switch label="Скрыть линию разделителя" checked={splitPaneInvisible} onChange={setSplitPaneInvisible} />
<div className="catalog-split-pane-demo">
<SplitPane
primarySize={splitPaneDemoSize}
separatorAppearance={splitPaneInvisible ? "invisible" : "line"}
onPrimarySizeChange={setSplitPaneDemoSize}
minPrimarySize={25}
minSecondarySize={25}
separatorLabel="Изменить ширину синхронных представлений"
primary={<div className="catalog-split-pane-demo__panel"><Icon name="video" /><strong>Видео</strong></div>}
secondary={<div className="catalog-split-pane-demo__panel"><Icon name="grid" /><strong>Пространственная сцена</strong></div>}
/>
</div>
<p className="catalog-preview__explanation">Граница изменяет контролируемую долю панелей; клавиши и pointer используют одни ограничения, а resize контейнера не сбрасывает выбранное соотношение.</p>
</Preview>
<Preview title="Dock layout" note="center swap / four edges / keyboard" className="catalog-preview--wide">
<div style={{height:420}}><DockLayout tree={dockDemoTree} onTreeChange={setDockDemoTree}
panels={[{id:'camera',label:'Камера'},{id:'depth',label:'Глубина'},{id:'map',label:'Карта'},{id:'scene',label:'Сцена',minimumSize:{width:320,height:280}}]}
renderPanel={id=><GlassSurface tone="soft" radius="panel" style={{height:'100%'}}><DockHandle id={id} label={id}/><strong>{id}</strong></GlassSurface>}/></div>
<p>Центр — обмен, край — разделение. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой.</p>
</Preview>
<Preview title="Application side panel" note="end / push / controlled" className="catalog-preview--wide catalog-side-panel-preview"> <Preview title="Application side panel" note="end / push / controlled" className="catalog-preview--wide catalog-side-panel-preview">
<div className="catalog-side-panel-demo"> <div className="catalog-side-panel-demo">
{sidePanelDemoOpen ? ( {sidePanelDemoOpen ? (
@@ -1427,7 +1600,7 @@ export function CatalogApp() {
description="Theme-aware application panel" description="Theme-aware application panel"
onClose={() => setSidePanelDemoOpen(false)} onClose={() => setSidePanelDemoOpen(false)}
> >
<Inspector variant="panel" sections={environmentSections.slice(0, 3)} defaultOpen={[environmentSections[0]?.id ?? ""]} singleOpen /> <Inspector variant="panel" sections={environmentSections.slice(0, 3).map(section=>({...section,action:{label:`Действие секции ${section.label}`,icon:<Icon name="edit"/>,onAction:()=>setInspectorOpen(true)}}))} defaultOpen={[environmentSections[0]?.id ?? ""]} singleOpen />
</ApplicationSidePanel> </ApplicationSidePanel>
) : ( ) : (
<Button shape="pill" icon={<Icon name="panel" />} onClick={() => setSidePanelDemoOpen(true)}>Открыть правую панель</Button> <Button shape="pill" icon={<Icon name="panel" />} onClick={() => setSidePanelDemoOpen(true)}>Открыть правую панель</Button>
@@ -1450,6 +1623,10 @@ export function CatalogApp() {
description="MP4 или URL становятся частью единого server-side layout вместе с темой, материалом и Toolbar." description="MP4 или URL становятся частью единого server-side layout вместе с темой, материалом и Toolbar."
actions={<Switch checked={mediaVisible} label="Показать" onChange={setMediaVisible} />} actions={<Switch checked={mediaVisible} label="Показать" onChange={setMediaVisible} />}
> >
<div style={{"--nodedc-accent-rgb":"247 248 244","--nodedc-on-accent-rgb":"8 8 10"} as CSSProperties}>
<Switch checked={mediaVisible} label="Белый акцент · видимость" onChange={setMediaVisible} />
<Switch checked={false} label="Выключено" disabled onChange={()=>{}} />
</div>
<MediaSourceField <MediaSourceField
label="Видео / картинка" label="Видео / картинка"
source={mediaSource} source={mediaSource}
@@ -1526,7 +1703,7 @@ export function CatalogApp() {
<span>CANONICAL GLASS</span> <span>CANONICAL GLASS</span>
<h2>Модальное окно и Inspector</h2> <h2>Модальное окно и Inspector</h2>
<p>Фон остаётся различимым, но текст и контролы сохраняют контраст. Этот материал не применяется к обычным панелям приложения.</p> <p>Фон остаётся различимым, но текст и контролы сохраняют контраст. Этот материал не применяется к обычным панелям приложения.</p>
<div className="catalog-inline"><TextField label="Пример поля" defaultValue="NODE.DC" /><Button variant="primary" shape="pill">Применить</Button></div> <div className="catalog-inline"><TextField label="Пример поля" name="organization" autoComplete="organization" defaultValue="NODE.DC" description="Автозаполнение сохраняет материал поля и клавиатурный фокус текущей темы." /><Button variant="primary" shape="pill">Применить</Button></div>
</GlassMaterialSurface> </GlassMaterialSurface>
</section> </section>
<SettingsCard eyebrow="ENGINE / GLASS V4" title="Параметры материала" description="Общий token-контракт ui-core; изменения сразу видны на preview, модалках и Inspector."> <SettingsCard eyebrow="ENGINE / GLASS V4" title="Параметры материала" description="Общий token-контракт ui-core; изменения сразу видны на preview, модалках и Inspector.">
@@ -1583,6 +1760,9 @@ export function CatalogApp() {
<p className="catalog-preview__explanation">Destructive-цвет появляется только у подтверждения.</p> <p className="catalog-preview__explanation">Destructive-цвет появляется только у подтверждения.</p>
<Button variant="danger" shape="pill" icon={<Icon name="trash" />} onClick={() => setConfirmOpen(true)}>Проверить удаление</Button> <Button variant="danger" shape="pill" icon={<Icon name="trash" />} onClick={() => setConfirmOpen(true)}>Проверить удаление</Button>
</Preview> </Preview>
<Preview title="Настройки модуля" note="адаптивное меню и форма" className="catalog-modal-preview"><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"> <Preview title="Workflow sharing" note="ENGINE / access" className="catalog-modal-preview">
<p className="catalog-preview__explanation">Участники, роли, приглашение и immutable-владелец.</p> <p className="catalog-preview__explanation">Участники, роли, приглашение и immutable-владелец.</p>
<Button variant="primary" shape="pill" icon={<Icon name="users" />} onClick={() => setShareAccessOpen(true)}>Поделиться графом</Button> <Button variant="primary" shape="pill" icon={<Icon name="users" />} onClick={() => setShareAccessOpen(true)}>Поделиться графом</Button>
@@ -1621,6 +1801,8 @@ export function CatalogApp() {
<div className="catalog-icon-catalog"> <div className="catalog-icon-catalog">
<Preview title="Размеры и поверхности" note="glyph 16 px" className="catalog-preview--wide"> <Preview title="Размеры и поверхности" note="glyph 16 px" className="catalog-preview--wide">
<div className="catalog-window-actions-demo"> <div className="catalog-window-actions-demo">
<IconButton label="Камера включена" aria-pressed="true"><Icon name="camera" /></IconButton>
<IconButton label="План"><Icon name="plan" /></IconButton>
<IconButton label="Добавить"><Icon name="plus" /></IconButton> <IconButton label="Добавить"><Icon name="plus" /></IconButton>
<IconButton label="Обновить"><Icon name="refresh" /></IconButton> <IconButton label="Обновить"><Icon name="refresh" /></IconButton>
<IconButton label="Развернуть"><Icon name="expand" /></IconButton> <IconButton label="Развернуть"><Icon name="expand" /></IconButton>
@@ -1925,6 +2107,7 @@ export function CatalogApp() {
endPanel={<div ref={setMapSettingsPanelHost} className="catalog-map-settings-panel-host" />} endPanel={<div ref={setMapSettingsPanelHost} className="catalog-map-settings-panel-host" />}
header={ header={
<AppHeader <AppHeader
brandMonochrome
brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />} brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />}
brandHref="/" brandHref="/"
center={ center={
@@ -2115,7 +2298,7 @@ export function CatalogApp() {
/> />
{guidelineOpen && studioContext === "visual" ? ( {guidelineOpen && studioContext === "visual" ? (
<Toolbar<CatalogSection> <Toolbar<CatalogSection | "hold">
placement={toolbarPlacement} placement={toolbarPlacement}
background={toolbarBg} background={toolbarBg}
border={toolbarBorder} border={toolbarBorder}
@@ -2125,13 +2308,15 @@ export function CatalogApp() {
maxSize={toolbarMaxSize} maxSize={toolbarMaxSize}
lensCount={toolbarLensCount} lensCount={toolbarLensCount}
autoHide={toolbarAutoHide} autoHide={toolbarAutoHide}
items={(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({ hideDelay={toolbarHideDelay} gap={toolbarGap}
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, id,
label: item.title, label: item.title,
shortcut: id === "icons" ? "I" : undefined,
icon: item.icon, icon: item.icon,
active: activeSection === id, active: activeSection === id,
onSelect: openSection, onSelect: () => openSection(id),
}))} }))]}
/> />
) : null} ) : null}
@@ -2243,8 +2428,19 @@ export function CatalogApp() {
<FoundrySettingsModal open={foundrySettingsOpen} isAdmin={isFoundryAdmin} onClose={() => setFoundrySettingsOpen(false)} /> <FoundrySettingsModal open={foundrySettingsOpen} isAdmin={isFoundryAdmin} onClose={() => setFoundrySettingsOpen(false)} />
<FeatureSettingsWindow open={featureSettingsDemoOpen} title="Настройки модуля" subtitle="Настройки и меню доступны также в полноэкранном просмотре"
identity={{ title: 'Модуль', subtitle: 'Пример общего компонента', avatarLabel: 'DC' }}
sections={[{ id: 'general', label: 'Основное', icon: 'settings' }, ...Array.from({length:16}, (_,i)=>({id:`details-${i}`,label:`Раздел ${i+1}`,group:'Сведения'}))]}
activeSection={featureSettingsDemoSection} onSectionChange={setFeatureSettingsDemoSection}
headerActions={<IconButton label="Обновить настройки примера" onClick={() => setProjectName('Обновлено')}><Icon name="refresh" /></IconButton>}
onClose={() => setFeatureSettingsDemoOpen(false)}>
{featureSettingsDemoSection === 'general' ? <SettingsCard title="Основное"><TextField label="Название модуля" value={projectName} onChange={(event) => setProjectName(event.target.value)} /></SettingsCard>
: <SettingsCard title="Сведения" description="Общее пояснение к данным."><Description>Текст в теле использует тот же стиль.</Description><ComparisonTable density="compact" label="Сравнение устройств" heading="Устройство" columns={Array.from({length:4},(_,i)=>({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/><LoadingRegion aggregate loading label="Загрузка сведений"><LoadingRegion loading label="Вложенный запрос A"/><LoadingRegion loading label="Вложенный запрос B"/></LoadingRegion></SettingsCard>}
</FeatureSettingsWindow>
<Window <Window
open={createModalOpen} open={createModalOpen}
headerActions={<IconButton label="Обновить пример" onClick={() => setProjectName("Обновлено")}><Icon name="refresh" /></IconButton>}
title="Создать проект" title="Создать проект"
subtitle="Адаптивная форма" subtitle="Адаптивная форма"
size="sm" size="sm"
@@ -0,0 +1,33 @@
import { useEffect, useRef, useState } from "react";
import type { EnvironmentSettings } from "@nodedc/ui-core";
import { Button, EnvironmentSettingsWindow, LandingStage, UserProfileMenu } from "@nodedc/ui-react";
const initial: EnvironmentSettings = { revision: 0, pages: { home: {
headerLabel: "Продукт", eyebrow: "NODE.DC / ГЛАВНАЯ", title: "Главная продукта",
description: "Общая композиция страницы и настроек окружения.", primaryWorkspaceId: null, secondaryWorkspaceId: null,
background: { enabled: false, imageDurationSeconds: 10, items: [] },
} } };
export function EnvironmentCatalogDemo() {
const [open, setOpen] = useState(false);
const [settings, setSettings] = useState(initial);
const urls = useRef<string[]>([]);
useEffect(() => () => urls.current.forEach(url => URL.revokeObjectURL(url)), []);
return <>
<div className="catalog-environment-actions">
<UserProfileMenu 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="Продукт"
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; }}
onUpload={async (_surface, _item, file) => {
const url = URL.createObjectURL(file); urls.current.push(url);
return { url, fileName: file.name, mediaKind: file.type.startsWith("video/") ? "video" : "image" };
}} />
</>;
}
+2
View File
@@ -61,6 +61,8 @@ export interface StoredLayout {
maxSize?: number; maxSize?: number;
lensCount?: number; lensCount?: number;
autoHide?: boolean; autoHide?: boolean;
hideDelay?: number;
gap?: number;
}; };
/** Design fragments are keyed by a registered Page Library type/version. */ /** Design fragments are keyed by a registered Page Library type/version. */
pageTypes?: Record<string, DesignProfilePageFragment>; pageTypes?: Record<string, DesignProfilePageFragment>;
+38
View File
@@ -1,3 +1,6 @@
.catalog-environment-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.catalog-environment-stage { display: grid; width: 100%; min-height: 480px; }
:root { :root {
background: var(--nodedc-canvas); background: var(--nodedc-canvas);
} }
@@ -1678,6 +1681,33 @@ textarea {
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
} }
.catalog-split-pane-preview .catalog-preview__body {
align-content: stretch;
}
.catalog-split-pane-demo {
min-height: 18rem;
overflow: hidden;
border-radius: var(--nodedc-radius-card);
background: var(--nodedc-nested-surface);
}
.catalog-split-pane-demo__panel {
display: grid;
width: 100%;
height: 100%;
place-content: center;
justify-items: center;
gap: 0.5rem;
background: color-mix(in srgb, var(--nodedc-canvas) 82%, transparent);
color: var(--nodedc-text-secondary);
}
.catalog-split-pane-demo__panel strong {
color: var(--nodedc-text-primary);
font-size: 0.82rem;
}
.catalog-side-panel-preview .catalog-preview__body { .catalog-side-panel-preview .catalog-preview__body {
align-content: stretch; align-content: stretch;
} }
@@ -1754,6 +1784,14 @@ textarea {
flex-wrap: wrap; flex-wrap: wrap;
} }
.catalog-icon-rail-demo {
display: flex;
width: max-content;
flex-direction: column;
align-items: center;
gap: var(--nodedc-space-2);
}
.catalog-form { .catalog-form {
display: grid; display: grid;
gap: 0.75rem; gap: 0.75rem;
+13
View File
@@ -74,3 +74,16 @@
- не поддерживать отдельную тему путём fork компонента; - не поддерживать отдельную тему путём fork компонента;
- не использовать legacy Engine inspector как промежуточный канон; - не использовать legacy Engine inspector как промежуточный канон;
- не удалять production local component до проверки package replacement. - не удалять production local component до проверки package replacement.
# Mission Core and onboard Home (R17)
Mission Core and Mission Core Node consume `EnvironmentSettingsWindow`,
`EnvironmentMediaPlaylistEditor`, `EnvironmentBackgroundMedia` and `LandingStage`
from `@nodedc/ui-react`. The former Control Station files are thin API/product
registry adapters or compatibility re-exports. They own no copied form markup or
presentation CSS. Node supplies Home only; Core retains all existing pages and
its wire/storage schema. Both use the existing `UserProfileMenu` avatar dropdown.
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 не публиковался, исходники компонентов в приложение не копируются.
+4
View File
@@ -44,3 +44,7 @@ Modal остаётся portal-слоем. Его тело прокручивае
- предметное содержимое content window. - предметное содержимое content window.
Shell владеет геометрией, слоями, переходами и breakpoint-поведением. См. готовый путь подключения в `docs/CONSUMPTION.md`. Shell владеет геометрией, слоями, переходами и breakpoint-поведением. См. готовый путь подключения в `docs/CONSUMPTION.md`.
На узком экране скрывается именно действие `data-action="expand"`.
Порядок utility actions не является признаком типа действия: плюс и обновление
остаются доступны, даже когда стоят первыми в шапке. Исправлено при QA Node 0.3.
+191 -6
View File
@@ -10,6 +10,8 @@
- `strong` — dropdown, modal и поверхность над сложным фоном; - `strong` — dropdown, modal и поверхность над сложным фоном;
- `soft` — вложенная или вторичная область. - `soft` — вложенная или вторичная область.
`radius="pill"` задаёт каноническую капсульную геометрию через `--nodedc-radius-circle`. Она предназначена, в частности, для компактных вертикальных и горизонтальных реек из круглых действий: верхняя и нижняя части поверхности повторяют круг кнопок без прямых торцевых пролётов. Consumer не воспроизводит этот радиус локальным CSS.
Material rim допустим только как часть floating glass. Жёсткая цветная рамка, случайный browser outline или debug border не являются rim. Material rim допустим только как часть floating glass. Жёсткая цветная рамка, случайный browser outline или debug border не являются rim.
`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют только modal `Window` и modeless draggable Inspector; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную. `GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют только modal `Window` и modeless draggable Inspector; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную.
@@ -25,9 +27,25 @@ Button используется для всех текстовых действ
Icon-only action по умолчанию круглый. Квадратная кнопка с маленьким радиусом допустима только как кнопка закрытия окна или плотный инструмент, где это зафиксировано контрактом. Icon-only action по умолчанию круглый. Квадратная кнопка с маленьким радиусом допустима только как кнопка закрытия окна или плотный инструмент, где это зафиксировано контрактом.
`size="dense"` — каноническая плотность для текстовых layer/mode-действий внутри визуализатора. Она уменьшает площадь и подпись контрола, но не меняет hover, active, disabled и focus-состояния. В шапках приложения и обычных формах эта плотность не используется.
Переключаемый IconButton передаёт контролируемое состояние через `aria-pressed`. Активная поверхность и контраст принадлежат дизайн-системе; размер круга и glyph при переключении не меняются.
`loading` в `Button` и `IconButton` помещает индикатор по центру нажатой кнопки, сохраняет её размеры и accessible name, выставляет `aria-busy` и блокирует повторное нажатие. Подробный контракт — [состояния загрузки](LOADING_STATES.md).
## LoadingRegion
`LoadingRegion loading={pending} label="Получаем данные"` центрирует ожидание внутри области содержимого, сохраняя её детей смонтированными. Приложение резервирует размер визуализатора и снимает loading после первого пригодного содержимого, ошибки или timeout. Командный spinner принадлежит кнопке и сюда не дублируется.
## ActivityIndicator
`ActivityIndicator` — общий индикатор неопределённого по длительности процесса. `default` используется внутри `LoadingRegion` или явного inline-статуса, `compact` — внутри `Button.loading`/`IconButton.loading` либо фиксированного слота строки ресурса. Владелец операции по-прежнему задаёт видимый текст pending-состояния и `aria-busy`; индикатор не хранит таймер и не определяет завершение операции.
Без `label` индикатор декоративный и скрыт от accessibility tree. `label` включает `role="status"` только когда сам индикатор должен объявить процесс. При `prefers-reduced-motion: reduce` кольцо остаётся видимым, но не вращается.
## Field ## Field
FieldFrame объединяет label, control, hint и description. TextField/TextAreaField реализуют стандартные текстовые поля. FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
Приложение не должно вручную собирать label и input, если подходит Field. Ошибка и validation state будут расширением этого контракта, а не локальным классом приложения. Приложение не должно вручную собирать label и input, если подходит Field. Ошибка и validation state будут расширением этого контракта, а не локальным классом приложения.
@@ -39,7 +57,17 @@ FieldFrame объединяет label, control, hint и description. TextField/T
## RangeControl ## RangeControl
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. Drag всегда принадлежит невидимому native range и продолжается под областью значения. Над числом постоянно смонтирован один прозрачный native text input: клик включает редактирование без замены DOM-узла, браузер ставит каретку в фактическое место клика, а drag-selection остаётся нативным. Поле не получает собственной подложки, select-all или второго focus-ring. Enter/blur применяют значение с clamp/step-нормализацией, Escape отменяет ввод; события редактора не всплывают в оконные shortcuts. Оконный focus-manager выполняет начальный autofocus только при открытии и не отбирает фокус при последующих ререндерах. Вертикальная шкала занимает `0.2 × --nodedc-control-height` (9.2 px при 46 px), вдвое тоньше предыдущей. Прозрачная область захвата не уже 24 px.
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. `min/max` задают только рабочий диапазон перетаскивания; ручной ввод по умолчанию принимает любое конечное число и не меняет геометрию ползунка. Опциональный `exactValueBounds` независимо задаёт жёсткие границы ручного ввода: например, `{ min: 0 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком.
Drag всегда принадлежит невидимому native range и продолжается под областью значения. Над числом постоянно смонтирован один прозрачный native text input: фокус включает редактирование без замены DOM-узла и без pointer-state mutation, браузер ставит каретку в фактическое место клика, а drag/keyboard-selection и замена выделенного текста остаются полностью нативными. Поле не получает собственной подложки, select-all или второго focus-ring. Цвет текста и каретки автоматически выбирается между theme text и `on-accent` по фактической границе заливки под областью значения, поэтому светлая заливка получает тёмный контраст без application-local цвета. Enter/blur применяют значение с exact-bound/step-нормализацией, Escape отменяет ввод; события редактора не всплывают в оконные shortcuts. Оконный focus-manager выполняет начальный autofocus только при открытии и не отбирает фокус при последующих ререндерах.
`RangeControl orientation="vertical"` показывает текущую верхнюю границу среза у края заливки и нижнюю сохранённую границу `min` внизу. `formatLimit` форматирует эти числа без единиц по умолчанию. Центральная надпись отсутствует; имя и `formatValue(value)` остаются доступны screen reader. Верхняя подпись следует значению, ограничена высотой шкалы и не перекрывает нижнюю у минимума. `limitSide="left"` зеркалит подписи для шкалы справа от сцены.
Для двухстороннего среза передайте `value={[lower, upper]}` и `onChange={(band) => …}`. Обе границы независимы; заливка показывает оставшийся между ними слой. Drag выбирает ближайшую границу и удерживает её до отпускания. Границы не пересекаются; совпавшие можно снова развести движением вниз/вверх. Два native range доступны отдельно с клавиатуры и screen reader (`lowerLabel`/`upperLabel`). Подписи следуют обеим границам и разводятся у совпадения; центрального текста нет. Home/End возвращают выбранную границу к допустимому краю. Домен отдельно отключает нижнее/верхнее отсечение на соответствующем краю. Скалярный режим сохраняет совместимость.
В скалярном режиме заливка растёт снизу. Drag, стрелки и Home/End работают нативно. Фокус подчёркивает движущееся значение; контур, border и тень не добавляются. Домен определяет диапазон и отключение среза у верхнего края.
## ColorField ## ColorField
@@ -49,6 +77,10 @@ Engine/BIM-геометрия color field: круглый swatch и HEX-знач
## Dropdown ## 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.
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.
Dropdown владеет floating-layer поведением: Dropdown владеет floating-layer поведением:
- рендерится в `document.body`; - рендерится в `document.body`;
@@ -61,7 +93,7 @@ Dropdown владеет floating-layer поведением:
- закрывается, когда trigger полностью уходит за границы viewport; - закрывается, когда trigger полностью уходит за границы viewport;
- закрывается по outside pointer и Escape; - закрывается по outside pointer и Escape;
- после Escape возвращает фокус на реальную trigger-кнопку, не закрывая родительское окно; - после Escape возвращает фокус на реальную trigger-кнопку, не закрывая родительское окно;
- закрывает другой открытый dropdown. - закрывает другой корневой dropdown; вложенный Select сохраняет родительское меню, выбор закрывает только Select, Escape закрывает самый глубокий слой.
Содержимое меню передаётся приложением. Selection, action menu и filter menu используют один engine. Содержимое меню передаётся приложением. Selection, action menu и filter menu используют один engine.
@@ -69,15 +101,20 @@ Dropdown владеет floating-layer поведением:
## Select ## Select
Select добавляет к Dropdown контролируемое значение, options и необязательный поиск. У него две канонические формы: Select добавляет к Dropdown контролируемое значение, options и необязательный поиск. У него три канонические формы:
- `integrated` — единая pill-поверхность Hub/Launcher: label слева, chevron строго у правого края; - `integrated` — единая pill-поверхность Hub/Launcher: label слева, chevron строго у правого края;
- `split` — форма Engine с отдельной областью значения и отдельной кнопкой раскрытия `46 px`, между ними зазор `8 px`. - `split` — форма Engine с отдельной областью значения и отдельной кнопкой раскрытия `46 px`, между ними зазор `8 px`;
- `inline` — компактный toolbar-trigger: только текущее значение без постоянной подложки и chevron; всё значение открывает обычное portal-меню.
Native select не используется как видимый runtime UI. Меню рендерится через portal; у Engine-варианта меню имеет радиус `20 px`, а строки — `14 px` и высоту `42 px`. Native select не используется как видимый runtime UI. Меню рендерится через portal; у Engine-варианта меню имеет радиус `20 px`, а строки — `14 px` и высоту `42 px`.
Внутри `Inspector` форма `integrated` запрещена. Selection-поле собирается только через `InspectorSelectField`: видимая подпись находится сверху, а полноширинный control всегда использует `split`. Компонент намеренно не принимает `layout` и `variant`, поэтому consumer не может вернуть Inspector к Hub/Launcher pill-форме. Внутри `Inspector` форма `integrated` запрещена. Selection-поле собирается только через `InspectorSelectField`: видимая подпись находится сверху, а полноширинный control всегда использует `split`. Компонент намеренно не принимает `layout` и `variant`, поэтому consumer не может вернуть Inspector к Hub/Launcher pill-форме.
`SelectOption.action` добавляет независимое действие справа от строки (`label`, `icon`, `disabled`, `onAction`), например корзину. Это соседний канонический `IconButton`, не вложенная кнопка. Действие закрывает меню, не выбирает строку и не вызывает `onChange`; подтверждение и запрос принадлежат приложению. Меню с действиями использует dialog-семантику и отдельные доступные кнопки выбора/действия; обычный Select сохраняет listbox. Состояние `option.disabled` не блокирует независимое действие — для него предусмотрен `action.disabled`.
Действие строки повторяет принятый образец каталога сессий Mission Core: прозрачная колонка нажатия `2.35rem`, иконка `15 px`, приглушённый цвет, без круглой подложки, скругления или тени. Опциональный `tone="danger"` меняет цвет при наведении и клавиатурном фокусе, но не окрашивает корзину постоянно. Доступный focus-индикатор общего IconButton сохраняется.
## Window ## Window
Window — единая механика открытия modal и правой panel: Window — единая механика открытия modal и правой panel:
@@ -89,6 +126,10 @@ Window — единая механика открытия modal и правой
Содержание, сохранение и запросы принадлежат приложению. Содержание, сохранение и запросы принадлежат приложению.
`WindowFooterActions` размещает группу действий справа, в том числе когда это единственная группа в footer. На узком экране действия переносятся внутри окна. Вспомогательный текст footer может оставаться слева.
Modeless Inspector закрывается независимо от результата автосохранения. Приложение сначала закрывает controlled `Window`, затем завершает сохранение асинхронно; сбой сообщает через компактный `ToastStack` с tone `error`, сохраняя draft текущего просмотра. Нельзя удерживать окно открытым, выводить внутри него browser-default `p`/heading или увеличивать текст ошибки до title-размера.
Для modeless Inspector доступен `draggable`: окно двигается за header, не блокирует приложение и ограничивается viewport. Modal-окна не становятся draggable автоматически. Для modeless Inspector доступен `draggable`: окно двигается за header, не блокирует приложение и ограничивается viewport. Modal-окна не становятся draggable автоматически.
## WorkspaceWindow ## WorkspaceWindow
@@ -139,6 +180,18 @@ Enter при отсутствии совпадения разрешает оди
ConfirmationModal оборачивает Window и защищает async-confirm от повторного запуска. До завершения операции закрытие можно заблокировать. ConfirmationModal оборачивает Window и защищает async-confirm от повторного запуска. До завершения операции закрытие можно заблокировать.
## SplitPane
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
Вертикальная граница меняется мышью или клавишами `←/→`, горизонтальная — `↑/↓`; `Home/End` переходят к разрешённым границам, а `Shift` ускоряет клавиатурный шаг. Доля сохраняется при resize контейнера. Минимальные проценты обеих панелей применяются одинаково к pointer и keyboard interaction.
Разделитель является структурной границей между двумя рабочими представлениями и не создаёт декоративную рамку вокруг контента. При `resizable={false}` панели сохраняют ту же стабильную DOM-композицию, а separator полностью отсутствует в визуальном слое и accessibility tree; это позволяет приложению сворачивать одну из панелей без remount тяжёлого renderer.
При `separatorAppearance="invisible"` линия скрыта в покое, при наведении и перетаскивании. Зона захвата, курсор, клавиатурное изменение размера и индикатор клавиатурного фокуса сохраняются.
## ShareAccessModal ## ShareAccessModal
Workflow-sharing modal из нового Engine: заголовок ресурса, compact avatar stack, список участников, редактирование ролей, удаление доступа, email и роль нового участника. Компонент сохраняет Engine-геометрию `600 px` и controls `46 px`, но не импортирует ACL API. Consumer передаёт members, permissions и callbacks. Workflow-sharing modal из нового Engine: заголовок ресурса, compact avatar stack, список участников, редактирование ролей, удаление доступа, email и роль нового участника. Компонент сохраняет Engine-геометрию `600 px` и controls `46 px`, но не импортирует ACL API. Consumer передаёт members, permissions и callbacks.
@@ -151,8 +204,14 @@ Read-only link/copy окно из BIM Viewer. React-компонент испо
## SegmentedControl ## SegmentedControl
`SegmentedGroup` + `SegmentedButton` собирают переключатели и триггер `Dropdown` в одной капсуле. `active` задаёт оформление; `aria-pressed` передаётся только переключателю, а `aria-expanded`/`aria-haspopup` — меню. Ref кнопки передаётся в `Dropdown.setTriggerRef`, поэтому сохраняются позиционирование и возврат фокуса. Геометрия, состояния и темы совпадают с `SegmentedControl`.
`selectionMode="multiple"` принимает массив `value` и возвращает массив в `onChange`. Это независимые кнопки `aria-pressed` в одной капсуле: допустимы ноль, один или все включённые сегменты. Обычный режим остаётся одиночным.
Pill navigation для верхней панели и компактного переключения режимов. Active segment использует активную поверхность темы; это не обязательно основной accent приложения. Pill navigation для верхней панели и компактного переключения режимов. Active segment использует активную поверхность темы; это не обязательно основной accent приложения.
`size="dense"` применяется только в насыщенной панели слоёв или режимов непосредственно над viewer. Шапка приложения сохраняет default-геометрию; consumer не воспроизводит dense-отступы или шрифт локальным CSS.
## AppHeader ## AppHeader
Трёхосевая верхняя панель: Трёхосевая верхняя панель:
@@ -205,6 +264,10 @@ setup-команды, сохранение, API и права принадлеж
Постоянные действия всего рабочего окна передаются через `ApplicationPanel.utilityActions` и всегда находятся в правой части шапки перед expand/close. Сохранение общего layout или настроек приложения — одно такое действие для всего окна; оно не дублируется внутри отдельных карточек и секций. Постоянные действия всего рабочего окна передаются через `ApplicationPanel.utilityActions` и всегда находятся в правой части шапки перед expand/close. Сохранение общего layout или настроек приложения — одно такое действие для всего окна; оно не дублируется внутри отдельных карточек и секций.
Переключение режима выбранного объекта может передать `pressed` в utility action: состояние получает `aria-pressed` и общую активную поверхность. Например, `info` открывает обзор текущей сохранённой сессии Mission Core.
Если заголовок и действия не помещаются в одну строку, шапка переносит действия на следующую строку с выравниванием вправо. Кнопки не обрезаются, заголовок сохраняет читаемую ширину. Состав действий одинаков в обычном и развёрнутом окне.
Точные состояния и размеры зафиксированы в `docs/APPLICATION_TEMPLATE.md`. Точные состояния и размеры зафиксированы в `docs/APPLICATION_TEMPLATE.md`.
## MediaSourceField ## MediaSourceField
@@ -217,6 +280,22 @@ setup-команды, сохранение, API и права принадлеж
`SettingsCard` фиксирует нейтральную структуру админской группы: eyebrow/title/description/actions/body. `Switch` покрывает компактное включение/видимость внутри таких групп. Данные секции, сохранение и права остаются в consumer. `SettingsCard` фиксирует нейтральную структуру админской группы: eyebrow/title/description/actions/body. `Switch` покрывает компактное включение/видимость внутри таких групп. Данные секции, сохранение и права остаются в consumer.
Промежуточный loading-контейнер не должен обнулять вертикальный ритм тела
карточки. Если `LoadingRegion` оборачивает несколько полей, consumer передаёт
ему свою stack-компоновку с gap из spacing tokens. Связанные действия размещаются
в flex-группе с token gap и переносом, а не соседними кнопками без интервала.
Это применяется также к условно появляющимся фильтрам и действиям импорта/экспорта.
Бегунок включённого `Switch` использует `--nodedc-on-accent-rgb`, поэтому
сохраняет контраст с белым, цветным и тёмным акцентом. Выключенный track
наследует тон темы от text-primary. Длина track не сжимается при переносе
подписи; положение бегунка остаётся дополнительным признаком состояния.
Для компактных сообщений о результате и пустых состояний `SettingsCard align="center"`
центрирует содержимое по горизонтали и вертикали. Пустой body не создаёт
асимметричный нижний отступ. Обычные группы настроек сохраняют `align="start"`;
вариант не задаёт высоту и не меняет токены темы.
## AdminNavigationPanel ## AdminNavigationPanel
Левая выезжающая панель Hub/Launcher. Библиотека владеет оболочкой `352 px`, радиусом `21.6 px`, внутренними отступами, full-bleed context/navigation pills, круглыми icon surfaces и анимацией появления. Приложение передаёт workspace/company, маршруты, active id и footer identity. Левая выезжающая панель Hub/Launcher. Библиотека владеет оболочкой `352 px`, радиусом `21.6 px`, внутренними отступами, full-bleed context/navigation pills, круглыми icon surfaces и анимацией появления. Приложение передаёт workspace/company, маршруты, active id и footer identity.
@@ -263,9 +342,11 @@ Sortable-строки ограничены вертикальной осью: г
Статус использует semantic tone: neutral, success, warning, danger или accent. Бизнес-статус приложения маппится на tone в самом приложении. Статус использует semantic tone: neutral, success, warning, danger или accent. Бизнес-статус приложения маппится на tone в самом приложении.
`pulse` добавляет пульсацию только лампы, не текста и не фона. Подходит для потери подтверждения или другого состояния, требующего внимания. При `prefers-reduced-motion: reduce` лампа остаётся постоянной. Текст статуса обязателен рядом с отдельным индикатором или в самом badge.
## ToastStack ## ToastStack
`ToastCard` и `ToastStack` фиксируют Tasker-derived bottom-right уведомления для `success`, `error`, `warning`, `info` и `loading`. Приложение владеет текстом и состоянием операции; стек владеет portal, геометрией, aria-live и таймерами. Loading не закрывается автоматически и обновляется тем же id после завершения операции. Toast не используется вместо modal confirmation. `ToastCard` и `ToastStack` фиксируют Tasker-derived bottom-right уведомления для `success`, `error`, `warning`, `info` и `loading`. Приложение владеет текстом и состоянием операции; стек владеет portal, геометрией, aria-live и таймерами. Обычный terminal toast по умолчанию живёт `10 000 ms`; каждый стабильный `id` получает собственный таймер, поэтому добавление соседнего уведомления не продлевает уже показанное. Loading не закрывается автоматически и обновляется тем же id после завершения операции; после перехода в terminal tone для него запускается обычный независимый таймер. Toast не используется вместо modal confirmation.
## Environment Controls: Inspector и ControlRow ## Environment Controls: Inspector и ControlRow
@@ -287,3 +368,107 @@ Inspector владеет:
Для Engine Environment Settings desktop-контракт точный: окно `390 px`, рабочая колонка `330 px`, строка `154 + 14 + 162 px`, высота контрола `46 px`, section header `50 px` с радиусом `12 px`. Accent-filled section headers и полноширинные range/checker/select сохраняют геометрию исходника. Для Engine Environment Settings desktop-контракт точный: окно `390 px`, рабочая колонка `330 px`, строка `154 + 14 + 162 px`, высота контрола `46 px`, section header `50 px` с радиусом `12 px`. Accent-filled section headers и полноширинные range/checker/select сохраняют геометрию исходника.
Engine продолжает владеть определениями полей, типами нод и сохранением значений. В живом catalog эти collapsible sections находятся в `Guideline → Контролы`; отдельной product-вкладки Inspector нет. Engine продолжает владеть определениями полей, типами нод и сохранением значений. В живом catalog эти collapsible sections находятся в `Guideline → Контролы`; отдельной product-вкладки Inspector нет.
## ResourceRow и ResourceList
Общие компактные строки ресурсов, выделенные из Mission Core AI Inference.
Контракт, состояния и происхождение: [RESOURCE_ROW.md](RESOURCE_ROW.md).
Светлый одноцветный знак шапки явно помечается `AppHeader.brandMonochrome` и
`HeaderWorkspace.monochrome`: общая тема обеспечивает контраст на светлом фоне.
По умолчанию флаг выключен; цветные изображения и аватары не меняются.
## ProgressBar
Линейная полоса выполнения: `label`, измеренная доля `value` 0…1 или
неопределённая продолжительность без `value`, доступный `valueText`.
В `ResourceRow` передаётся через `progress` и заменяет статус между
наименованием и кнопками. Процент принадлежит приложению, анимация его не выдумывает.
См. [контракт](PROGRESS_BAR.md).
StatusBadge `variant="indicator"` отображает только одну лампу состояния.
Передавайте `aria-label` и `title`; дополнительный текст и значки скрываются.
## EnvironmentSettingsWindow и EnvironmentMediaPlaylistEditor
Единый редактор окружения перенесён из принятой композиции Mission Core. Принимает страницы, quick-action варианты, документ, состояние, upload/save adapters и название продукта. Использует тот же FeatureSettingsWindow, поля, переключатели, медиаконтент и перестановку; новое приложение передаёт данные, а не копирует форму. Для бортового приложения передаётся только home. Контракты и пример: [ENVIRONMENT_SETTINGS.md](ENVIRONMENT_SETTINGS.md).
## LandingStage и EnvironmentBackgroundMedia
Общая главная: надзаголовок, заголовок, описание, быстрые действия, фон и необязательные status/footer slots. Изображения меняются по таймеру, видео — после завершения; ошибочные источники пропускаются. Пустой фон однотонный, без декоративного круга. Состояние страниц и хранение принадлежат приложению.
Для primary Button `tone="neutral"` фиксирует белый enabled и серый disabled, независимо от темы и акцента; keyboard focus остаётся видимым. MediaSourceField принимает `disabled` и блокирует все операции выбора источника, пока родитель сохраняет документ или загружает файл.
## KeyButton
Контурная клавиша удержания с контролируемым pressed-состоянием. [Контракт](KEY_BUTTON.md).
`Window` и `FeatureSettingsWindow`: `headerActions` размещает обновление и другие контекстные IconButton рядом с закрытием; footer предназначен для завершения формы.
### Fullscreen portal ownership
React `Window` (including `FeatureSettingsWindow`) and `Dropdown` (including Select and ColorField) mount into the active native fullscreen element, falling back to document.body. Menu geometry remains viewport-fixed. Consumers must let an open dialog/menu handle Escape before restoring the fullscreen viewer.
### Scene window and accordion actions
`WorkspaceWindow resizeIndicator={false}` скрывает только видимый уголок. Размер по-прежнему меняется перетаскиванием правого нижнего угла или стрелками при фокусе на ручке; фокус остаётся видимым.
`InspectorSectionSpec.action` задаёт `{label, icon, disabled?, onAction}`. Это отдельная от раскрывающего заголовка кнопка: её нажатие не раскрывает секцию. В варианте `panel` она стоит левее стрелки; стрелка смотрит вниз в закрытом состоянии и вверх в открытом.
## DockLayout
`DockLayout` and `DockHandle` compose stable viewport hosts over a serializable `DockTree`.
Drop at the center to exchange views; the left/right/top/bottom zones split that destination.
Removing the source collapses its old empty branch. The contour uses the resulting tree,
so it previews the actual final position, even when the destination expands after removal.
Any number of available panels can be composed with nested horizontal and vertical splits.
`focusedId` expands a view without reparenting media; the application persists `tree`.
There is no permanent outline. Outside/self drops and Escape leave the tree unchanged.
Keyboard: Enter/Space on the grip, Tab/Shift+Tab to choose a destination, arrows for edges,
Home for center, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing.
The pure tree types, geometry and operations are exported by `@nodedc/ui-core`; React re-exports them for view consumers. Domain adapters import the framework-neutral package.
## ProgressButton
Фаза и полоса выполнения внутри инициирующей кнопки. `LayerStackIndicator` анимирует канонический значок layers. [API и состояния](PROGRESS_BUTTON.md).
## Description
`Description` is the shared explanatory paragraph. It matches `SettingsCard.description`: inherited family, small font token (12px), regular 400, muted text token, line-height 1.4. Use it for help below values, not a local paragraph override.
## ComparisonTable
`ComparisonTable` accepts a heading, entity columns and labelled rows. Semantic headers, a 9rem minimum per column and horizontal overflow preserve 1–N comparisons in narrow panels. The keyboard scrollport contains wheel overscroll; no borders or cards per entity. Data freshness stays application-owned.
DockLayout panels accept minimumSize in CSS pixels. Recursive minimums apply to
all ancestor splits and keyboard/pointer resizing. Below the whole-layout limit,
the canvas scrolls instead of shrinking or overlapping panel contents.
ComparisonTable density="compact" reduces 31px rows to21px (about32%). Its label
column has a120px minimum, each data column88px, and available width is shared by
data columns. Hosts provide matching content limits; typography stays12px.
### Toolbar in scene editors
Pass `container` and portal the shared `Toolbar` into a positioned viewport to keep it and its autohide reveal edge inside that viewport (including fullscreen). Omission retains window scope. Item `shortcut` adds a native tooltip and `aria-keyshortcuts`; the owning editor implements the scoped key binding. Focus reveals a hidden dock. Editing icons `select`, `pen`, `rectangle`, `curve`, `undo`, and `redo` use the shared Lucide adapter and catalog.
Toolbar item `menu` composes the canonical `Dropdown`, anchored to the tool button. Supply content or a function receiving `close`; menu controls remain canonical buttons, checkers or selects.
### Toolbar menus and settings
Toolbar supports left/right/top/bottom, minimum/maximum size, lens count, gap,
material colors, autohide and `hideDelay` in milliseconds (0–15000). Applications
persist these props in their existing preferences. A viewport `container` owns
its reveal edges. Item menus open inward beyond the maximum magnified button
extent; the shared Dropdown reserves that envelope throughout spring motion.
Once a menu is open, hovering another menu trigger changes it. A 300 ms bounded
pointer-intent triangle protects diagonal travel to the current menu. Clicking
or keyboard activation remains immediate. Open menus suspend autohide. Selected
menu choices use the neutral primary Button state as well as `aria-pressed`.
### Toolbar: Hold and scene dismissal (2026-10-21)
The first optional Hold action controls the existing persisted `autoHide` setting. Disabling autohide cancels any pending hide timer. Dropdown observes outside pointerdown in capture phase; viewport Toolbar consumes background dismissal before canvas editing tools, while other controls retain their normal actions. Nested menus and trigger clicks retain lineage behavior. Catalog includes the Hold action.
- `NavigationCube`: [orientation cube](NAVIGATION_CUBE.md), controlled face/edge/corner navigation.
+19
View File
@@ -0,0 +1,19 @@
# Shared environment and home
The owner-approved Mission Core settings anatomy is now canonical, not a screenshot to reproduce. Consumers use UserProfileMenu for the avatar dropdown, EnvironmentSettingsWindow for the settings composition, EnvironmentMediaPlaylistEditor for the list and LandingStage/EnvironmentBackgroundMedia for the home. All geometry and responsive styles live in ui-core.
The neutral primary Button tone comes from shared tokens, stays white when enabled and gray when disabled across dark/light and accent changes. It does not alter other applications' default primary theme.
## Consumer contract
Pass productName, a nonempty stable surfaces list, optional initialSurfaceId, a revision/pages document and save/upload adapters. Each surface references one present page and declares its available quick actions. Workspace IDs are opaque application-owned identifiers. The library owns only draft/form/list/playback behavior; it never imports Mission Core's registry or calls product APIs. Shared data shapes/list functions are exported by ui-core so nonvisual application contracts do not depend on React.
Settings uses the existing FeatureSettingsWindow/Window focus and Escape behavior. A busy parent disables editing and save; failed saves retain the draft. Each playlist has up to 24 items. Images use the configured delay; a video advances on ended, with one video looping. Failed media is skipped. List display reverses playback order to keep newly added media at the top, as in the accepted source UI.
The application validates URLs/media bytes, persists uploads and document revisions, handles authentication and rejects stale saves. An upload response provides URL, fileName and mediaKind. A file URL belongs to the storage adapter; an external source must use HTTP(S). No media defaults to an invented graphic. The product may supply status/footer slots without forking the stage.
## Adoption and validation
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.
+6 -1
View File
@@ -29,6 +29,12 @@
Допустимы density variants, если они имеют устойчивое назначение (`default`, `compact`) и тестируются как часть API. Допустимы density variants, если они имеют устойчивое назначение (`default`, `compact`) и тестируются как часть API.
## Типографика и операционные сообщения
Продуктовый интерфейс использует только типографические токены. Browser-default размеры у `h1`–`h6`, `p`, `strong` и form controls не являются допустимым стилем. `--nodedc-font-size-title` разрешён только для заголовка страницы или окна; названия конфигураций, статусы, ошибки, подписи полей и сообщения внутри рабочей сцены используют `md`, `sm`, `xs` или готовую типографику канонического компонента.
Ошибка сохранения или запроса не рендерится свободным текстовым блоком поверх рабочей сцены. Приложение использует семантический error-state канонического поля либо `ToastStack`, который владеет размером текста, цветом, положением и закрытием. Ошибка автосохранения modeless-инспектора не блокирует закрытие окна: draft остаётся в текущем просмотре, окно закрывается сразу, а сбой показывается неблокирующим error toast.
## Deprecated ## Deprecated
Перед удалением export: Перед удалением export:
@@ -53,4 +59,3 @@
## Владение ## Владение
У дизайн-системы должен быть явный code owner. Product team может предлагать компоненты, но общий API и theme contract проходят отдельное review, потому что изменение распространяется на все будущие приложения. У дизайн-системы должен быть явный code owner. Product team может предлагать компоненты, но общий API и theme contract проходят отдельное review, потому что изменение распространяется на все будущие приложения.
+25 -4
View File
@@ -1,5 +1,7 @@
# Иконки # Иконки
`info` — информация о выбранном объекте или записи. Иконка используется в стандартном круглом `IconButton`, с доступной подписью и `aria-pressed` для переключаемого обзора. Продуктовое применение: обзор сохранённой сессии Mission Core; одобрено владельцем 2026-09-11.
Канонический набор собран по реально используемым действиям Launcher/Hub, SEO, BIM Viewer и разрешённым новым участкам Engine. Полные vendor-наборы не являются частью дизайн-системы: наличие SVG в Font Awesome или export в Lucide не делает иконку канонической. Канонический набор собран по реально используемым действиям Launcher/Hub, SEO, BIM Viewer и разрешённым новым участкам Engine. Полные vendor-наборы не являются частью дизайн-системы: наличие SVG в Font Awesome или export в Lucide не делает иконку канонической.
## Геометрия ## Геометрия
@@ -16,15 +18,34 @@
| Группа | Канонические имена | | Группа | Канонические имена |
| --- | --- | | --- | --- |
| Окно и слой | `close`, `plus`, `expand`, `minimize`, `refresh`, `panel`, `apps` | | Окно и слой | `close`, `plus`, `expand`, `minimize`, `refresh`, `panel`, `apps`, `layers` |
| Навигация | `chevron-left`, `chevron-right`, `chevron-down`, `grid`, `list`, `sliders`, `search` | | Навигация | `chevron-left`, `chevron-right`, `chevron-down`, `grid`, `list`, `sliders`, `search` |
| Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external` | | Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external`, `rotate-clockwise` |
| Состояние и доступ | `check`, `alert`, `activity`, `lock`, `key`, `shield`, `circle` | | Состояние и доступ | `check`, `alert`, `activity`, `lock`, `key`, `shield`, `circle`, `eye`, `eye-off` |
| Сущности | `profile`, `users`, `building`, `globe`, `database`, `network`, `inbox`, `mail` | | Сущности | `profile`, `users`, `building`, `globe`, `database`, `network`, `inbox`, `mail` |
| Контент | `image`, `video`, `file`, `folder`, `clipboard`, `settings` | | Контент | `camera`, `plan`, `play`, `stop`, `image`, `video`, `file`, `folder`, `clipboard`, `settings`, `terminal` |
Живая таблица с названиями, поверхностями и размерами находится в разделе `Guideline → Иконки`. Машинный список — в `registry/icons.json`. Живая таблица с названиями, поверхностями и размерами находится в разделе `Guideline → Иконки`. Машинный список — в `registry/icons.json`.
## Правило расширения ## Правило расширения
Новая иконка добавляется только после подтверждённого применения в продукте. Нужно выбрать семантическое имя, добавить export в `Icon`, запись в registry и specimen в каталоге. Локальный импорт иконки только ради немного другой формы запрещён. Новая иконка добавляется только после подтверждённого применения в продукте. Нужно выбрать семантическое имя, добавить export в `Icon`, запись в registry и specimen в каталоге. Локальный импорт иконки только ради немного другой формы запрещён.
`camera` обозначает оптический канал, а `plan` — пространственное представление сверху. Оба glyph контурные и используют общую stroke-геометрию набора.
`layers` открывает управление видимостью слоёв карты или визуального источника.
Применение подтверждено владельцем Mission Core 10.09.2026: кнопка слоёв в
заголовке карты Центра наблюдения. `settings` остаётся общей конфигурацией.
Кнопка наследует обычные hover, focus, disabled и active-состояния `IconButton`.
`play` и `stop` — компактные полнотелые транспортные glyph: залитый треугольник запуска и залитый квадрат остановки/паузы. Видимая текстовая подпись не требуется, но action обязан сохранить доступный `aria-label`.
`terminal` — контурный знак `>_` для входа в консоль и журнал команд.
Применение подтверждено владельцем Mission Core 28.09.2026 для ARNavi B2.
Это действие использует обычный `IconButton` с доступной подписью; состояния
hover, focus, disabled и pending принадлежат кнопке. `activity` остаётся
обозначением телеметрии и состояния, а не отправки команд.
Раскрытие строки вниз: `chevron-down` в закрытом состоянии, `chevron-up` в открытом; кнопка сообщает `aria-expanded` и `aria-controls`.
`rotate-clockwise` — поворот изображения по часовой стрелке. Применение: независимая ориентация объективов Insta360 в Центре наблюдения Mission Core, по запросу владельца 09.10.2026. Шаг задаёт приложение; подпись кнопки сообщает угол. Состояния и геометрия принадлежат каноническому `IconButton`.
+15
View File
@@ -0,0 +1,15 @@
# KeyButton
Owner-approved momentary keyboard/pointer visualization (Mission Core, 2026-09-25).
Outlined square key surface; pressed is white with black text in every theme.
This explicit outline identifies a key, not a decorative panel border.
`label` is the complete accessible action; children are the short key legend.
`pressed` is controlled and never toggled by the component. Native button keyboard
semantics, disabled behavior and focus indicator are retained. Consumers own
pointer capture and release, keyboard scope, blur/cancel/unmount handling and
any domain command lease. A displayed pressed key is not an acknowledgement
from equipment. Disabled always renders released. No global listeners exist.
Catalog includes idle, pressed, disabled and focusable surfaces. Use only for
momentary key input, not ordinary actions (Button) or mode choice (SegmentedControl).
+36
View File
@@ -0,0 +1,36 @@
# Состояния загрузки
Общий контракт для Mission Core, Mission Core Node и других NODE.DC consumers. Кольцо рисует ActivityIndicator; место и семантику определяют Button.loading, IconButton.loading или LoadingRegion. Локальные absolute-спиннеры и свободные ActivityIndicator под группой действий запрещены.
| Причина ожидания | Компонент и место | Завершение |
|---|---|---|
| Нажата команда | loading только у инициирующей Button/IconButton, по центру внутри её прежних границ | Подтверждение результата, ошибка или timeout команды |
| Начальная загрузка содержимого | LoadingRegion вокруг конкретной области, по центру её границ | Первое пригодное содержимое, ошибка или timeout |
| Подключение видео | LoadingRegion вокруг смонтированного video/canvas, включая расширенный вид | Первый декодированный кадр; одного ICE connected недостаточно |
| Фоновое обновление с доступным содержимым | loading у явной кнопки обновления; без overlay при автоматическом polling | Ответ запроса или ошибка |
| Измеряемая многошаговая подготовка | Существующий ProgressBar/ResourceRow.progress и статусы этапов | Результат этапа/операции |
| Ошибка, offline, отсутствие свежих кадров | Конечный статус и разрешённое действие повторения | Не оставлять бесконечный spinner |
Приложение хранит pending по device ID, session и конкретному action key. Блокировка соседних несовместимых действий не делает их загружающимися. Для одной команды показывается один индикатор; последующее получение содержимого — отдельный этап. Элемент управления сохраняет размеры, надпись для screen reader и свой порядок в layout; spinner не добавляет строку и не сдвигает соседей. Повторная активация pending-кнопки блокируется native disabled.
LoadingRegion не размонтирует video/canvas и не присваивает область страницы целиком. Визуализатор задаёт собственную стабильную высоту/aspect ratio; индикатор центрируется относительно этой области и автоматически следует её normal/expanded размеру. Компонент не блокирует управление сам: consumer отключает только конфликтующие действия. Закрытие просмотра остаётся доступным.
Владелец операции задаёт начало и конец ожидания. Компоненты не запускают запросы, не выдумывают проценты, не повторяют операции и не скрывают ошибки по таймеру. Reduced motion сохраняет статическое кольцо. Button сохраняет accessible name и aria-busy; LoadingRegion имеет один status с label, декоративное кольцо скрыто от accessibility tree.
```tsx
<Button loading={pending === 'save'} onClick={save}>Сохранить</Button>
<IconButton label="Обновить" loading={pending === 'refresh'} onClick={refresh}><Icon name="refresh" /></IconButton>
<LoadingRegion loading={connecting || awaitingFirstFrame} label="Ожидаем изображение">
<video autoPlay muted playsInline />
</LoadingRegion>
```
Living catalog показывает action, icon-action и content loading. Изменение согласовано владельцем08.09.2026 для обоих Mission Core consumers. Локальный кандидат включается в hash-bound Ubuntu source artifact; внешний package release в рамках этой задачи не публикуется.
## Проверка кандидата 08.09.2026
N09: typecheck, registry validation, четыре loading contract tests и production catalog build прошли. В браузере проверены light/dark и два accent colors: loading не меняет размер Button/IconButton, кольцо сохраняет нейтральный цвет, content status центрируется вместе с подписью. В Mission Core проверены pending read-only action, video first frame, normal/expanded/Escape и terminal error: mounted video сохраняется, после кадра или ошибки лишних индикаторов нет. Тот же shared frontend включён в установленный Node0.8.18; отдельная визуальная проверка native Node shell остаётся задачей consumer acceptance.
### Composed content
Use `<LoadingRegion aggregate loading={ownPending} label="Loading equipment">` around a composed surface. Descendant `LoadingRegion`s register pending state without drawing another indicator. All visible nested initial requests share exactly one surface indicator. A terminal error or unmount releases the lease; background refresh with usable data must not register. Independent modal Windows reset the scope. Button operations retain their own progress. Do not aggregate unrelated observation panes.
+13
View File
@@ -0,0 +1,13 @@
# NavigationCube
Owner-requested on 2026-10-21 for semantic editing. Reference: BIM Viewer `frontend/dcViewer.js` NavCube, size 100; Xeokit renderer coupling is replaced by a controlled SVG adapter, with no extra GPU context.
`quaternion` is camera-to-world, Y up; `onSelect([x,y,z])` points from target to camera. Six face centres, twelve edge directions and eight corner directions. Adjacent face regions share the same direction. The consumer preserves framing, projection and semantic data. The cube reflects free camera rotation. Projection is a separate explicit control. Top is +Y, front is +Z, right is +X; domain adapters convert coordinate conventions.
Visible hit regions have native tooltips, hover, keyboard focus, Enter/Space activation and disabled state. Face/edge strokes are structural. Tokens own colors. No motion or GPU loop in the component. Catalog controls section demonstrates the cube.
`add-point` is a centered circled plus, distinct from whole-element `plus`. Projection icons: `orthographic`, `perspective`.
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.
+24
View File
@@ -0,0 +1,24 @@
# Компактная операционная типографика
Уточнение владельца 06.09.2026 для Mission Core / Node, обязательное для
общих компонентов NODE.DC. Повторяющиеся сообщения и подписи не оформляются
крупными заголовками. Этот документ зарегистрирован в registry/registry.json.
- Заголовок страницы или окна: только предусмотренный шаблоном title-токен.
- Заголовок секции, SettingsCard, короткое сообщение пустого списка: md
(0.8125rem / 13 px при стандартном корневом размере), без увеличения через h2.
- Описание, пояснение, сведения о состоянии: sm (0.75rem / 12 px).
- Технические метаданные: xs либо типографика ResourceRow.
- Browser-default h1–h6/p/strong и локальные крупные размеры запрещены.
- Размер не умножается из-за вложенности карточек, ошибки или отсутствия данных.
SettingsCard и nodedc-empty-state закрепляют эти размеры в ui-core. Текст
«Устройства не обнаружены» не является заголовком нового раздела. В живом
каталоге рядом со строками ресурсов есть пример пустого списка.
В завершённом этапе настройки окружения status-слот ResourceRow содержит
только Icon check с доступным названием. Галочка не оборачивается в StatusBadge,
Checker, круг, pill или кнопку. Это знак результата, а не интерактивный контрол.
Лампочка состояния устройства отдельно использует StatusBadge indicator.
Explanatory paragraphs use `Description`, the same contract as `SettingsCard.description`: inherited font family, regular 400, `--nodedc-font-size-sm`, `--nodedc-text-muted`, line-height 1.4 and zero paragraph margins. Applications must not create feature-specific equivalents.
+15
View File
@@ -0,0 +1,15 @@
# ProgressBar
Владелец Mission Core 05.09.2026 явно запросил горизонтальную заполняющуюся
полосу вместо кружка и точки в строке подготовки устройства. Общий компонент
добавлен в Design Guideline до подключения в Node/Core.
`value` — завершённая доля 0…1; NaN/Infinity трактуются как неизвестная величина,
выход за границы ограничивается. Без value используется движущийся сегмент,
aria-valuenow отсутствует. `label` обязателен; `valueText` описывает текущий этап.
Нет интерактивности и focus. Темы используют существующие семантические токены.
При reduced motion движение выключено, видимый сегмент сохраняется.
ResourceRow.progress занимает свободное место между текстом и actions, скрывает
status, на узком экране переносится ниже текста. Готовность не вычисляется
компонентом. Каталог содержит завершённый, определённый и неизвестный прогресс.
+22
View File
@@ -0,0 +1,22 @@
# ProgressButton
Принят владельцем Mission Core 10.10.2026: этап чуть выше центра кнопки,
заполняющаяся полоса ниже, слева слои последовательно опускаются и проседают.
`label` — стабильное имя действия; `progress?: { label, value?, valueText? }`
— текущая фаза с измеренной долей 0…1. Без доли полоса неопределённая.
При наличии progress кнопка блокирует повторный запуск, сохраняет читаемость
и сообщает aria-busy. После ошибки consumer убирает progress, возвращая запуск;
ошибка передаётся обычным каналом приложения. `disabled` отдельно закрывает
действие без объявления несуществующей активности. Управление, отмена и жизненный
цикл остаются у приложения. Высота стандартного Button не меняется.
ProgressBar расположен визуально внутри кнопки, но в DOM является соседним
элементом: его доступная семантика не теряется внутри нативного button.
Текущее описание связано через aria-describedby; role=status сообщает фазу.
Tab/Enter/Space работают как у Button; pending исключает повторную активацию.
`LayerStackIndicator` использует существующий `Icon name="layers"`, без нового
знака или зависимости. Анимация не вычисляет процент. При reduced motion
оставляет неподвижный знак; статус и измеренная полоса остаются доступны.
Каталог показывает idle, disabled, определённый и неопределённый progress.
+34
View File
@@ -0,0 +1,34 @@
# ResourceRow и ResourceList
Владелец 2026-09-05 запросил перенос существующих длинных строк Mission Core
AI Inference в Node с повторным использованием Design Guideline. Источник:
ObservatoryWorkspace / observatory-evidence-card. Это выделение существующего
оформления в общий компонент, без лабораторной модели данных.
`ResourceList` содержит обычные `li`; внутри — `ResourceRow` с обязательным
`title`, опциональными `icon`, `description`, `metadata`, `status`, `actions`.
Слоты действий принимают канонические Button/IconButton. Клик по всей строке
не назначается: самостоятельные действия имеют свои доступные подписи и focus.
Геометрия источника сохранена: минимум 4.25rem, отступы .7/.85rem, значок
2.15rem, компактный радиус и существующие токены поверхности/типографики.
Длинное название переносится; метаданные сокращаются визуально, полный текст
можно передать через title. На узком экране статус и действия переходят ниже.
Состояния поставляет consumer: нормальное, пустой список, загрузка, ошибка,
недоступное действие. Pending отмечается aria-busy и ActivityIndicator;
disabled и keyboard/focus остаются у общего контрола. Строка не объявляет
объект доступным или подключённым самостоятельно.
Пример находится в живом каталоге, раздел «Контролы → Строки ресурсов».
Для длительных операций с линейной индикацией используйте `progress`
(ProgressBar: label, value, valueText). Он заменяет status, оставляет действия
справа и занимает промежуток после названия.
`statusPlacement="leading"` размещает компактный индикатор после иконки и
перед всем текстовым блоком, с выравниванием по вертикальному центру строки.
По умолчанию остаётся `trailing` перед действиями. Статус не дублируется;
во время `progress` он скрыт в любом положении. Для одной лампы используйте
StatusBadge variant="indicator" с aria-label и title. Это согласованное
06.09.2026 расположение индикатора устройств Mission Core / Node.
+12
View File
@@ -64,3 +64,15 @@ dark/light она меняется синхронно с `AdminNavigationPanel`.
## Совместимость ## Совместимость
Существующие `--nodedc-*` имена сохранены намеренно. Это уменьшает стоимость будущего подключения Launcher, Engine, Task Manager и BIM Viewer. Существующие `--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.
+15 -1
View File
@@ -28,7 +28,7 @@
7. trigger, полностью ушедший за viewport, закрывает surface; 7. trigger, полностью ушедший за viewport, закрывает surface;
8. outside pointer и Escape закрывают surface; 8. outside pointer и Escape закрывают surface;
9. после Escape фокус возвращается на trigger; 9. после Escape фокус возвращается на trigger;
10. открытие другого dropdown закрывает предыдущий. 10. открытие другого корневого dropdown закрывает предыдущий; вложенные меню сохраняют предков, а Escape закрывает только самый глубокий слой.
Inline absolute dropdown внутри card/sidebar/sticky container является дефектом. Inline absolute dropdown внутри card/sidebar/sticky container является дефектом.
@@ -115,3 +115,17 @@ map-glass дизайне, что Objects.
Библиотека не создаёт глобальный store окон. Приложение владеет тем, какое окно открыто и какие данные в нём загружены. Библиотека владеет одинаковым поведением самого слоя. Библиотека не создаёт глобальный store окон. Приложение владеет тем, какое окно открыто и какие данные в нём загружены. Библиотека владеет одинаковым поведением самого слоя.
Stack workspace-окон остаётся контролируемым приложением: оно передаёт active-state и `zIndex`, а компонент отвечает только за одинаковую геометрию и взаимодействие. Глобальный stack viewport-level modeless-окон остаётся отдельным будущим контрактом. Stack workspace-окон остаётся контролируемым приложением: оно передаёт active-state и `zIndex`, а компонент отвечает только за одинаковую геометрию и взаимодействие. Глобальный stack viewport-level modeless-окон остаётся отдельным будущим контрактом.
## Контекстные действия заголовка
`Window.headerActions` и `FeatureSettingsWindow.headerActions` принимают канонические `IconButton`. Обновление содержимого находится рядом с закрытием; сохранение и отмена формы остаются в footer. Слот входит в focus trap окна, а клики по действиям не начинают перетаскивание. Pending/disabled задаёт владелец данных; закрытие остаётся доступным.
На узком экране центрированное окно учитывает padding своего overlay с обеих сторон. В `FeatureSettingsWindow` меню занимает высоту содержимого, а оставшаяся высота отдана прокручиваемой форме. Проверочный пример «Настройки модуля» находится в живом каталоге окон; проверять в том числе на ширине 390 px.
FeatureSettingsWindow owns two independent scrollports. Its outer body is overflow-hidden; both navigation and content are min-height:0, overflow:auto, keyboard-focusable and overscroll-contained. Long left menus never move the right body. At narrow widths navigation remains capped and the content receives the remaining height.
Selecting a different settings section resets only its content scroll to the top; navigation keeps its position.
Docked content declares minimumSize for both axes. The divider stops at the recursive content boundary; a small overall viewport scrolls the layout canvas.
`DockLayout.panels[].preferredSize` задаёт начальный компактный размер. Продукт передаёт его только для новой раскладки без сохранённой геометрии; первый resize/dock сохраняет пользовательскую геометрию. Минимумы продолжают действовать при всех последующих размерах.
+13 -3
View File
@@ -11,10 +11,11 @@
"scripts": { "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": "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", "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:floating-position && npm run test:inspector-select && npm run test:range-control && 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", "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",
"dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog", "dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog",
"serve": "node server/catalog-server.mjs", "serve": "node server/catalog-server.mjs",
"validate:registry": "node scripts/validate-registry.mjs", "validate:registry": "node scripts/validate-registry.mjs",
"test:environment-settings": "node --test scripts/environment-settings.test.mjs",
"test:platform-settings": "node scripts/smoke-platform-settings.mjs", "test:platform-settings": "node scripts/smoke-platform-settings.mjs",
"test:data-product-runtime": "node scripts/smoke-data-product-runtime.mjs", "test:data-product-runtime": "node scripts/smoke-data-product-runtime.mjs",
"test:data-product-consumer": "node --test server/foundry-data-product-consumer.test.mjs", "test:data-product-consumer": "node --test server/foundry-data-product-consumer.test.mjs",
@@ -31,9 +32,18 @@
"test:map-subject-card": "node --test scripts/map-subject-card.test.mjs", "test:map-subject-card": "node --test scripts/map-subject-card.test.mjs",
"test:map-subject-detail-profile": "node --test server/map-subject-detail-profile.test.mjs server/map-live-data-slot.test.mjs", "test:map-subject-detail-profile": "node --test server/map-subject-detail-profile.test.mjs server/map-live-data-slot.test.mjs",
"test:map-cache-contract": "node --test scripts/map-cache-resource-contract.test.mjs", "test:map-cache-contract": "node --test scripts/map-cache-resource-contract.test.mjs",
"test:spark-governance": "node --test scripts/spark-governance-contract.test.mjs",
"test:activity-indicator": "node --test scripts/activity-indicator-contract.test.mjs",
"test:control-density": "node --test scripts/control-density-contract.test.mjs",
"test:icon-contract": "node --test scripts/icon-contract.test.mjs",
"test:toast-contract": "node --test scripts/toast-contract.test.mjs",
"test:floating-position": "node --test scripts/floating-position-contract.test.mjs", "test:floating-position": "node --test scripts/floating-position-contract.test.mjs",
"test:inspector-select": "node --test scripts/inspector-select-contract.test.mjs", "test:inspector-select": "node --test scripts/inspector-select-contract.test.mjs scripts/select-actions-contract.test.mjs",
"test:range-control": "node --test scripts/range-control-contract.test.mjs" "test:range-control": "node --test scripts/range-control-contract.test.mjs",
"test:split-pane": "node --test scripts/split-pane-contract.test.mjs",
"test:dock-layout": "node --test scripts/dock-layout.test.mjs",
"test:analysis-controls": "node --test scripts/analysis-controls.test.mjs",
"test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
+8
View File
@@ -1,3 +1,11 @@
:root {
--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);
--nodedc-neutral-action-disabled-bg: #757575;
--nodedc-neutral-action-disabled-color: #242424;
}
:root, :root,
[data-nodedc-theme="dark"] { [data-nodedc-theme="dark"] {
color-scheme: dark; color-scheme: dark;
+3
View File
@@ -9,7 +9,9 @@
--nodedc-radius-circle: 999px; --nodedc-radius-circle: 999px;
--nodedc-control-height: 2.875rem; --nodedc-control-height: 2.875rem;
--nodedc-viewport-control-scale: 0.7;
--nodedc-control-height-compact: 2.375rem; --nodedc-control-height-compact: 2.375rem;
--nodedc-control-height-dense: 1.875rem;
--nodedc-icon-button-size: 2.875rem; --nodedc-icon-button-size: 2.875rem;
--nodedc-header-row-height: 3rem; --nodedc-header-row-height: 3rem;
--nodedc-header-pill-height: 3.45rem; --nodedc-header-pill-height: 3.45rem;
@@ -61,6 +63,7 @@
--nodedc-font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; --nodedc-font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
--nodedc-font-size-xs: 0.6875rem; --nodedc-font-size-xs: 0.6875rem;
--nodedc-font-size-dense: 0.45rem;
--nodedc-font-size-sm: 0.75rem; --nodedc-font-size-sm: 0.75rem;
--nodedc-font-size-md: 0.8125rem; --nodedc-font-size-md: 0.8125rem;
--nodedc-font-size-lg: 1rem; --nodedc-font-size-lg: 1rem;
+128
View File
@@ -0,0 +1,128 @@
/** Serializable split tree. Content identity is independent of its position. */
export type DockTree = { id: string } | { axis: "x" | "y"; ratio: number; first: DockTree; second: DockTree };
export type DockPosition = "center" | "left" | "right" | "top" | "bottom";
export interface DockRect { left: number; top: number; width: number; height: number }
export interface DockMove { activeId: string; overId: string; position: DockPosition }
export function dockIds(tree: DockTree | null): string[] {
return !tree ? [] : "id" in tree ? [tree.id] : [...dockIds(tree.first), ...dockIds(tree.second)];
}
export function decodeDockTree(raw: unknown): DockTree | null {
const seen = new Set<string>();
const read = (value: unknown, depth: number): DockTree | null => {
if (!value || typeof value !== "object" || depth > 128 || seen.size > 128) return null;
const v = value as Record<string, unknown>;
if (typeof v.id === "string" && v.id.length > 0 && v.id.length < 512) {
if (seen.has(v.id)) return null;
seen.add(v.id); return { id: v.id };
}
if ((v.axis !== "x" && v.axis !== "y") || typeof v.ratio !== "number" || !Number.isFinite(v.ratio)) return null;
const first = read(v.first, depth + 1), second = read(v.second, depth + 1);
return first && second ? { axis: v.axis, ratio: Math.max(10, Math.min(90, v.ratio)), first, second } : first ?? second;
};
return read(raw, 0);
}
export function pruneDockTree(tree: DockTree | null, ids: readonly string[]): DockTree | null {
if (!tree) return null;
if ("id" in tree) return ids.includes(tree.id) ? tree : null;
const first = pruneDockTree(tree.first, ids), second = pruneDockTree(tree.second, ids);
return first && second ? { ...tree, first, second } : first ?? second;
}
export function balancedDockTree(ids: readonly string[], axis: "x" | "y" = "x"): DockTree | null {
if (!ids.length) return null;
if (ids.length === 1) return { id: ids[0] };
const mid = Math.ceil(ids.length / 2);
return { axis, ratio: 50, first: balancedDockTree(ids.slice(0, mid), axis === "x" ? "y" : "x")!,
second: balancedDockTree(ids.slice(mid), axis === "x" ? "y" : "x")! };
}
export function reconcileDockTree(tree: DockTree | null, ids: readonly string[]): DockTree | null {
const kept = pruneDockTree(tree, ids), present = dockIds(kept), missing = ids.filter(id => !present.includes(id));
if (!kept) return balancedDockTree(missing);
return missing.length ? { axis: "x", ratio: 50, first: kept, second: balancedDockTree(missing)! } : kept;
}
export function moveDockPanel(tree: DockTree | null, move: DockMove): DockTree | null {
const { activeId, overId, position } = move, ids = dockIds(tree);
if (!tree || activeId === overId || !ids.includes(activeId) || !ids.includes(overId)) return tree;
const swap = (node: DockTree): DockTree => "id" in node
? { id: node.id === activeId ? overId : node.id === overId ? activeId : node.id }
: { ...node, first: swap(node.first), second: swap(node.second) };
if (position === "center") return swap(tree);
const remaining = pruneDockTree(tree, ids.filter(id => id !== activeId))!;
const insert = (node: DockTree): DockTree => {
if (!("id" in node)) return { ...node, first: insert(node.first), second: insert(node.second) };
if (node.id !== overId) return node;
const before = position === "left" || position === "top";
return { axis: position === "left" || position === "right" ? "x" : "y", ratio: 50,
first: before ? { id: activeId } : node, second: before ? node : { id: activeId } };
};
return insert(remaining);
}
export function resizeDockSplit(tree: DockTree, path: string, ratio: number): DockTree {
if ("id" in tree || !Number.isFinite(ratio)) return tree;
if (!path) return { ...tree, ratio: Math.max(10, Math.min(90, ratio)) };
const side = path[0] === "0" ? "first" : "second";
return { ...tree, [side]: resizeDockSplit(tree[side], path.slice(1), ratio) };
}
export function dockRects(tree: DockTree | null, bounds: DockRect): Record<string, DockRect> {
if (!tree) return {};
if ("id" in tree) return { [tree.id]: bounds };
const fraction = tree.ratio / 100;
const first = tree.axis === "x" ? { ...bounds, width: bounds.width * fraction } : { ...bounds, height: bounds.height * fraction };
const second = tree.axis === "x" ? { ...bounds, left: bounds.left + first.width, width: bounds.width - first.width }
: { ...bounds, top: bounds.top + first.height, height: bounds.height - first.height };
return { ...dockRects(tree.first, first), ...dockRects(tree.second, second) };
}
export function dockPosition(rect: DockRect, x: number, y: number): DockPosition | null {
if (rect.width <= 0 || rect.height <= 0 || x < rect.left || y < rect.top || x > rect.left + rect.width || y > rect.top + rect.height) return null;
const u = (x - rect.left) / rect.width, v = (y - rect.top) / rect.height;
const distances: [DockPosition, number][] = [["left", u], ["right", 1 - u], ["top", v], ["bottom", 1 - v]];
const nearest = distances.sort((a, b) => a[1] - b[1])[0];
return nearest[1] <= .23 ? nearest[0] : "center";
}
export interface DockMinimum { width: number; height: number }
export type DockMinimums = Readonly<Record<string, DockMinimum>>;
/** Propagate content limits through every ancestor, not only the nearest split. */
export function dockMinimum(tree: DockTree | null, minimums: DockMinimums = {}): DockMinimum {
if (!tree) return {width: 0, height: 0};
if ("id" in tree) {
const value = minimums[tree.id];
const valid = (v: number | undefined, fallback: number) => typeof v === "number" && Number.isFinite(v) ? Math.max(0, v) : fallback;
return {width: valid(value?.width, 160), height: valid(value?.height, 120)};
}
const a = dockMinimum(tree.first, minimums), b = dockMinimum(tree.second, minimums);
return tree.axis === "x" ? {width: a.width + b.width, height: Math.max(a.height, b.height)}
: {width: Math.max(a.width, b.width), height: a.height + b.height};
}
/** Host expands to the recursive minimum when the whole viewport is too small. */
export function constrainDockTree(tree: DockTree | null, bounds: DockMinimum, minimums: DockMinimums = {}): DockTree | null {
if (!tree || "id" in tree) return tree;
const required = dockMinimum(tree, minimums), size = {width: Math.max(bounds.width, required.width), height: Math.max(bounds.height, required.height)};
const a = dockMinimum(tree.first, minimums), b = dockMinimum(tree.second, minimums), key = tree.axis === "x" ? "width" : "height";
const available = size[key];
const cut = Math.max(a[key], Math.min(available - b[key], available * tree.ratio / 100));
const ratio=available>0?cut/available*100:50;
return {...tree, ratio:Math.abs(ratio-tree.ratio)<1e-9?tree.ratio:ratio,
first: constrainDockTree(tree.first, {...size, [key]: cut}, minimums)!,
second: constrainDockTree(tree.second, {...size, [key]: available - cut}, minimums)!};
}
/** Initial preferred sizes apply only until the product persists a user layout. */
export function preferDockSizes(tree:DockTree|null,bounds:DockMinimum,preferred:DockMinimums):DockTree|null {
if(!tree||'id' in tree)return tree;
const a=dockIds(tree.first).some(id=>id in preferred),b=dockIds(tree.second).some(id=>id in preferred);
const key=tree.axis==='x'?'width':'height';
let ratio=tree.ratio;
if(a!==b){const wanted=dockMinimum(a?tree.first:tree.second,preferred)[key];ratio=(a?wanted:bounds[key]-wanted)/bounds[key]*100;}
ratio=Math.max(1,Math.min(99,Number.isFinite(ratio)?ratio:50));
return {...tree,ratio,first:preferDockSizes(tree.first,{...bounds,[key]:bounds[key]*ratio/100},preferred)!,second:preferDockSizes(tree.second,{...bounds,[key]:bounds[key]*(1-ratio/100)},preferred)!};
}
+84
View File
@@ -0,0 +1,84 @@
export type EnvironmentMediaKind = "image" | "video";
export type EnvironmentMediaSource = "file" | "url";
export interface EnvironmentMediaItem {
id: string;
source: EnvironmentMediaSource;
url: string | null;
mediaKind: EnvironmentMediaKind | null;
fileName: string | null;
}
export interface EnvironmentBackground {
enabled: boolean;
imageDurationSeconds: number;
items: EnvironmentMediaItem[];
}
export interface EnvironmentPage {
headerLabel: string;
eyebrow: string;
title: string;
description: string;
primaryWorkspaceId: string | null;
secondaryWorkspaceId: string | null;
background: EnvironmentBackground;
}
export interface EnvironmentSettings { revision: number; pages: Record<string, EnvironmentPage> }
export interface UploadedEnvironmentMedia { url: string; fileName: string; mediaKind: EnvironmentMediaKind }
export interface EnvironmentAction { id: string; label: string; description?: string }
export interface EnvironmentSurface { id: string; home?: boolean; description?: string; actions: readonly EnvironmentAction[] }
export const defaultEnvironmentImageDurationSeconds = 10;
export const maxEnvironmentMediaItems = 24;
export function createEnvironmentMediaItem(): EnvironmentMediaItem {
return {
id: `media-${crypto.randomUUID()}`,
source: "file",
url: null,
mediaKind: null,
fileName: null,
};
}
export function appendEnvironmentMediaItem(
background: EnvironmentBackground,
item: EnvironmentMediaItem = createEnvironmentMediaItem(),
): EnvironmentBackground {
if (
background.items.length >= maxEnvironmentMediaItems
|| background.items.some((candidate) => candidate.id === item.id)
) {
return background;
}
return {
...background,
enabled: background.items.length === 0 ? true : background.enabled,
items: [...background.items, item],
};
}
export function removeEnvironmentMediaItem(
background: EnvironmentBackground,
itemId: string,
): EnvironmentBackground {
const items = background.items.filter((item) => item.id !== itemId);
if (items.length === background.items.length) return background;
return {
...background,
enabled: items.length > 0 && background.enabled,
items,
};
}
export function inferEnvironmentMediaKind(url: string): EnvironmentMediaKind {
return /\.(mp4|webm|mov)(?:[?#].*)?$/i.test(url) ? "video" : "image";
}
export function cloneEnvironmentSettings(settings: EnvironmentSettings): EnvironmentSettings {
return { ...settings, pages: Object.fromEntries(Object.entries(settings.pages).map(([id, page]) => [id, {
...page, background: { ...page.background, items: page.background.items.map(item => ({ ...item })) },
}])) };
}
+22 -3
View File
@@ -1,4 +1,4 @@
export type FloatingPlacement = "bottom-start" | "bottom-end" | "top-start" | "top-end"; export type FloatingPlacement = "bottom-start" | "bottom-end" | "top-start" | "top-end" | "left-start" | "right-start";
export interface RectLike { export interface RectLike {
top: number; top: number;
@@ -15,6 +15,7 @@ export interface FloatingPositionOptions {
surfaceHeight: number; surfaceHeight: number;
placement?: FloatingPlacement; placement?: FloatingPlacement;
offset?: number; offset?: number;
flip?: boolean;
viewportWidth?: number; viewportWidth?: number;
viewportHeight?: number; viewportHeight?: number;
viewportPadding?: number; viewportPadding?: number;
@@ -24,6 +25,7 @@ export interface FloatingPosition {
top: number; top: number;
left: number; left: number;
maxHeight: number; maxHeight: number;
maxWidth?: number;
resolvedPlacement: FloatingPlacement; resolvedPlacement: FloatingPlacement;
} }
@@ -33,6 +35,7 @@ export function computeFloatingPosition({
surfaceHeight, surfaceHeight,
placement = "bottom-start", placement = "bottom-start",
offset = 8, offset = 8,
flip = true,
viewportWidth = typeof window === "undefined" ? 1920 : window.innerWidth, viewportWidth = typeof window === "undefined" ? 1920 : window.innerWidth,
viewportHeight = typeof window === "undefined" ? 1080 : window.innerHeight, viewportHeight = typeof window === "undefined" ? 1080 : window.innerHeight,
viewportPadding = 8, viewportPadding = 8,
@@ -41,6 +44,22 @@ export function computeFloatingPosition({
0, 0,
viewportHeight - viewportPadding * 2, viewportHeight - viewportPadding * 2,
); );
if (placement.startsWith("left") || placement.startsWith("right")) {
const roomLeft = Math.max(0, anchor.left - offset - viewportPadding);
const roomRight = Math.max(0, viewportWidth - anchor.right - offset - viewportPadding);
const leftRequested = placement.startsWith("left");
const switched = flip && (leftRequested ? surfaceWidth > roomLeft && roomRight > roomLeft : surfaceWidth > roomRight && roomLeft > roomRight);
const toLeft = switched ? !leftRequested : leftRequested;
const maxWidth = toLeft ? roomLeft : roomRight;
const actualWidth = Math.min(surfaceWidth, maxWidth);
const visibleHeight = Math.min(surfaceHeight, viewportAvailableHeight);
return {
left: toLeft ? anchor.left - offset - actualWidth : anchor.right + offset,
top: Math.max(viewportPadding, Math.min(anchor.top, viewportHeight - viewportPadding - visibleHeight)),
maxHeight: viewportAvailableHeight, maxWidth,
resolvedPlacement: toLeft ? "left-start" : "right-start",
};
}
const roomBelow = Math.min( const roomBelow = Math.min(
viewportAvailableHeight, viewportAvailableHeight,
Math.max(0, viewportHeight - anchor.bottom - offset - viewportPadding), Math.max(0, viewportHeight - anchor.bottom - offset - viewportPadding),
@@ -50,9 +69,9 @@ export function computeFloatingPosition({
Math.max(0, anchor.top - offset - viewportPadding), Math.max(0, anchor.top - offset - viewportPadding),
); );
const requestedTop = placement.startsWith("top"); const requestedTop = placement.startsWith("top");
const shouldFlip = requestedTop const shouldFlip = flip && (requestedTop
? surfaceHeight > roomAbove && roomBelow > roomAbove ? surfaceHeight > roomAbove && roomBelow > roomAbove
: surfaceHeight > roomBelow && roomAbove > roomBelow; : surfaceHeight > roomBelow && roomAbove > roomBelow);
const resolvedPlacement = shouldFlip const resolvedPlacement = shouldFlip
? (`${requestedTop ? "bottom" : "top"}-${placement.endsWith("end") ? "end" : "start"}` as FloatingPlacement) ? (`${requestedTop ? "bottom" : "top"}-${placement.endsWith("end") ? "end" : "start"}` as FloatingPlacement)
: placement; : placement;
+9
View File
@@ -3,3 +3,12 @@ export * from "./floating.js";
export * from "./glass.js"; export * from "./glass.js";
export * from "./theme.js"; export * from "./theme.js";
export * from "./toolbar.js"; export * from "./toolbar.js";
export * from "./environment.js";
export * from "./dockTree.js";
export {dockMinimum, constrainDockTree, type DockMinimum, type DockMinimums} from "./dockTree.js";
export {preferDockSizes} from "./dockTree.js";
export * from "./menuAim.js";
+14
View File
@@ -0,0 +1,14 @@
import type { RectLike } from "./floating.js";
export type MenuPoint = {x:number;y:number};
/** Delay sibling activation only while the pointer advances through the corridor to the open menu. */
export function movingToMenu(origin:MenuPoint, previous:MenuPoint, current:MenuPoint, surface:RectLike):boolean {
const horizontal = origin.x < surface.left || origin.x > surface.right;
const edge = horizontal ? (origin.x < surface.left ? surface.left : surface.right) : (origin.y < surface.top ? surface.top : surface.bottom);
const a = horizontal ? {x:edge,y:surface.top-6} : {x:surface.left-6,y:edge};
const b = horizontal ? {x:edge,y:surface.bottom+6} : {x:surface.right+6,y:edge};
const cross=(p:MenuPoint,q:MenuPoint,v:MenuPoint)=>(q.x-p.x)*(v.y-p.y)-(q.y-p.y)*(v.x-p.x);
const signs=[cross(origin,a,current),cross(a,b,current),cross(b,origin,current)];
const inside=signs.every(v=>v>=-0.01)||signs.every(v=>v<=0.01);
const axis=horizontal?"x":"y";
return inside && Math.abs(current[axis]-edge)<Math.abs(previous[axis]-edge)-0.1;
}
+4 -1
View File
@@ -15,6 +15,8 @@ export interface NodedcMaterial {
export interface ApplyThemeOptions { export interface ApplyThemeOptions {
theme?: NodedcTheme; theme?: NodedcTheme;
/** Operator UI qualified against Mission Core; opt-in across portals. */
appearance?: "default" | "mission";
accent?: RgbTuple; accent?: RgbTuple;
material?: NodedcMaterial; material?: NodedcMaterial;
} }
@@ -29,9 +31,10 @@ function clampOpacity(value: number): number {
export function applyNodedcTheme( export function applyNodedcTheme(
target: HTMLElement, target: HTMLElement,
{ theme = "dark", accent, material }: ApplyThemeOptions = {}, { theme = "dark", accent, material, appearance = "default" }: ApplyThemeOptions = {},
): void { ): void {
target.dataset.nodedcTheme = theme; target.dataset.nodedcTheme = theme;
target.dataset.nodedcAppearance = appearance;
target.dataset.nodedcUi = "true"; target.dataset.nodedcUi = "true";
if (accent) { if (accent) {
+1 -1
View File
@@ -1,4 +1,4 @@
export type ToolbarPlacement = "left" | "right" | "bottom"; export type ToolbarPlacement = "left" | "right" | "top" | "bottom";
export interface ToolbarSettings { export interface ToolbarSettings {
minSize: number; minSize: number;
File diff suppressed because it is too large Load Diff
+5 -3
View File
@@ -17,6 +17,8 @@ export interface ToolbarControllerOptions {
maxSize?: number; maxSize?: number;
lensCount?: number; lensCount?: number;
autoHide?: boolean; autoHide?: boolean;
hideDelay?: number;
gap?: number;
} }
export interface ToolbarController { export interface ToolbarController {
@@ -112,7 +114,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
}; };
const updateMagnification = (coordinate: number) => { const updateMagnification = (coordinate: number) => {
const vertical = options.placement !== "bottom"; const vertical = options.placement !== "bottom" && options.placement !== "top";
const toolbarRect = toolbar.getBoundingClientRect(); const toolbarRect = toolbar.getBoundingClientRect();
const entries = buttons const entries = buttons
.map((button) => ({ .map((button) => ({
@@ -148,7 +150,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
hideTimer = window.setTimeout(() => { hideTimer = window.setTimeout(() => {
hideTimer = null; hideTimer = null;
if (!hovering) hide(); if (!hovering) hide();
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay); }, Math.max(0,Math.min(15000,options.hideDelay ?? NODEDC_TOOLBAR_DEFAULTS.hideDelay)));
}; };
const applyOptions = () => { const applyOptions = () => {
@@ -208,7 +210,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
? event.clientX >= window.innerWidth - threshold ? event.clientX >= window.innerWidth - threshold
: options.placement === "bottom" : options.placement === "bottom"
? event.clientY >= window.innerHeight - threshold ? event.clientY >= window.innerHeight - threshold
: event.clientX <= threshold; : options.placement === "top" ? event.clientY <= threshold : event.clientX <= threshold;
if (nearEdge) show(); if (nearEdge) show();
else if (visible && !hovering) scheduleHide(); else if (visible && !hovering) scheduleHide();
}; };
@@ -0,0 +1,32 @@
import type { HTMLAttributes } from "react";
import { cn } from "./cn.js";
export type ActivityIndicatorSize = "default" | "compact";
export interface ActivityIndicatorProps extends Omit<
HTMLAttributes<HTMLSpanElement>,
"aria-hidden" | "aria-label" | "children" | "role"
> {
size?: ActivityIndicatorSize;
label?: string;
}
export function ActivityIndicator({
size = "default",
label,
className,
...props
}: ActivityIndicatorProps) {
const accessibleLabel = label?.trim() || undefined;
return (
<span
{...props}
className={cn("nodedc-activity-indicator", className)}
data-size={size === "default" ? undefined : size}
role={accessibleLabel ? "status" : undefined}
aria-label={accessibleLabel}
aria-hidden={accessibleLabel ? undefined : "true"}
/>
);
}
+8 -4
View File
@@ -4,6 +4,8 @@ export interface AppHeaderProps {
brand: ReactNode; brand: ReactNode;
brandHref?: string; brandHref?: string;
brandLabel?: string; brandLabel?: string;
/** Opt in only for a light, single-color mark, never a full-color image. */
brandMonochrome?: boolean;
left?: ReactNode; left?: ReactNode;
center?: ReactNode; center?: ReactNode;
right?: ReactNode; right?: ReactNode;
@@ -13,14 +15,15 @@ export function AppHeader({
brand, brand,
brandHref, brandHref,
brandLabel = "NODE.DC", brandLabel = "NODE.DC",
brandMonochrome = false,
left, left,
center, center,
right, right,
}: AppHeaderProps) { }: AppHeaderProps) {
const brandNode = brandHref ? ( const brandNode = brandHref ? (
<a className="nodedc-header__brand" href={brandHref} aria-label={brandLabel}>{brand}</a> <a className="nodedc-header__brand" data-monochrome={brandMonochrome || undefined} href={brandHref} aria-label={brandLabel}>{brand}</a>
) : ( ) : (
<span className="nodedc-header__brand" aria-label={brandLabel}>{brand}</span> <span className="nodedc-header__brand" data-monochrome={brandMonochrome || undefined} aria-label={brandLabel}>{brand}</span>
); );
return ( return (
@@ -100,11 +103,12 @@ export interface HeaderWorkspaceProps {
label: string; label: string;
imageUrl?: string; imageUrl?: string;
kind?: "mark" | "avatar"; kind?: "mark" | "avatar";
monochrome?: boolean;
} }
export function HeaderWorkspace({ label, imageUrl, kind = "mark" }: HeaderWorkspaceProps) { export function HeaderWorkspace({ label, imageUrl, kind = "mark", monochrome = false }: HeaderWorkspaceProps) {
return ( return (
<span className="nodedc-header__workspace" data-kind={kind} title={label}> <span className="nodedc-header__workspace" data-kind={kind} data-monochrome={monochrome || undefined} title={label}>
{imageUrl ? <img src={imageUrl} alt="" /> : label.slice(0, 2).toUpperCase()} {imageUrl ? <img src={imageUrl} alt="" /> : label.slice(0, 2).toUpperCase()}
</span> </span>
); );
@@ -68,6 +68,7 @@ export interface ApplicationPanelUtilityAction {
icon: IconName; icon: IconName;
onClick: () => void; onClick: () => void;
disabled?: boolean; disabled?: boolean;
pressed?: boolean;
} }
export function ApplicationPanel({ export function ApplicationPanel({
@@ -102,6 +103,8 @@ export function ApplicationPanel({
className="nodedc-application-panel__action" className="nodedc-application-panel__action"
data-action="utility" data-action="utility"
aria-label={action.label} aria-label={action.label}
aria-pressed={action.pressed}
data-active={action.pressed ? "true" : undefined}
disabled={action.disabled} disabled={action.disabled}
onClick={action.onClick} onClick={action.onClick}
> >
+23 -1
View File
@@ -1,22 +1,28 @@
import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from "react"; import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from "react";
import { createAccentVariables, type RgbTuple } from "@nodedc/ui-core"; import { createAccentVariables, type RgbTuple } from "@nodedc/ui-core";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import { ActivityIndicator } from "./ActivityIndicator.js";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "danger" | "accent"; export type ButtonVariant = "primary" | "secondary" | "ghost" | "danger" | "accent";
export type ButtonSize = "default" | "compact"; export type ButtonSize = "default" | "compact" | "dense";
export type ButtonShape = "default" | "pill" | "rounded"; export type ButtonShape = "default" | "pill" | "rounded";
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> { export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant; variant?: ButtonVariant;
/** Neutral primary actions remain white/gray independently of the product accent. */
tone?: "theme" | "neutral";
size?: ButtonSize; size?: ButtonSize;
width?: "auto" | "full"; width?: "auto" | "full";
shape?: ButtonShape; shape?: ButtonShape;
accent?: RgbTuple; accent?: RgbTuple;
icon?: ReactNode; icon?: ReactNode;
/** Pending state belongs to this action; dimensions and accessible name stay unchanged. */
loading?: boolean;
} }
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button({ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button({
variant = "secondary", variant = "secondary",
tone = "theme",
size = "default", size = "default",
width = "auto", width = "auto",
shape = "default", shape = "default",
@@ -26,6 +32,8 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
children, children,
style, style,
type = "button", type = "button",
loading = false,
disabled,
...props ...props
}, ref) { }, ref) {
const accentStyle = accent ? createAccentVariables(accent) : undefined; const accentStyle = accent ? createAccentVariables(accent) : undefined;
@@ -35,14 +43,21 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
type={type} type={type}
className={cn("nodedc-button", className)} className={cn("nodedc-button", className)}
data-variant={variant} data-variant={variant}
data-tone={tone === "theme" ? undefined : tone}
data-size={size === "default" ? undefined : size} data-size={size === "default" ? undefined : size}
data-width={width === "auto" ? undefined : width} data-width={width === "auto" ? undefined : width}
data-shape={shape === "default" ? undefined : shape} data-shape={shape === "default" ? undefined : shape}
style={accentStyle ? { ...accentStyle, ...style } : style} style={accentStyle ? { ...accentStyle, ...style } : style}
{...props} {...props}
disabled={disabled || loading}
aria-busy={loading || props["aria-busy"]}
data-loading={loading || undefined}
> >
<span className="nodedc-button__content">
{icon ? <span className="nodedc-button__icon" aria-hidden="true">{icon}</span> : null} {icon ? <span className="nodedc-button__icon" aria-hidden="true">{icon}</span> : null}
{children} {children}
</span>
{loading ? <span className="nodedc-action-loading" aria-hidden="true"><ActivityIndicator size="compact" /></span> : null}
</button> </button>
); );
}); });
@@ -50,6 +65,7 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
export interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> { export interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
label: string; label: string;
shape?: "circle" | "rounded"; shape?: "circle" | "rounded";
loading?: boolean;
} }
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton({ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton({
@@ -58,6 +74,8 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
className, className,
children, children,
type = "button", type = "button",
loading = false,
disabled,
...props ...props
}, ref) { }, ref) {
return ( return (
@@ -69,8 +87,12 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
aria-label={label} aria-label={label}
title={label} title={label}
{...props} {...props}
disabled={disabled || loading}
aria-busy={loading || props["aria-busy"]}
data-loading={loading || undefined}
> >
{children} {children}
{loading ? <span className="nodedc-action-loading" aria-hidden="true"><ActivityIndicator size="compact" /></span> : null}
</button> </button>
); );
}); });
+19
View File
@@ -0,0 +1,19 @@
import type { ReactNode, CSSProperties } from "react";
export interface ComparisonTableProps {
density?: "default" | "compact";
label: string;
heading: ReactNode;
columns: readonly { id: string; label: ReactNode }[];
rows: readonly { id: string; label: ReactNode; cells: readonly ReactNode[] }[];
}
/** One label column, one non-collapsing column per entity. Scrolls as a unit. */
export function ComparisonTable({ density = "default", label, heading, columns, rows }: ComparisonTableProps) {
return <div className="nodedc-comparison-table" data-density={density} role="region" aria-label={label} tabIndex={0}
style={{ "--nodedc-comparison-columns": columns.length + 1 } as CSSProperties}>
<table aria-label={label}>
<colgroup><col/>{columns.map(column => <col key={column.id}/>)}</colgroup>
<thead><tr><th scope="col">{heading}</th>{columns.map(column => <th key={column.id} scope="col">{column.label}</th>)}</tr></thead>
<tbody>{rows.map(row => <tr key={row.id}><th scope="row">{row.label}</th>{columns.map((column, index) => <td key={column.id}>{row.cells[index] ?? "—"}</td>)}</tr>)}</tbody>
</table>
</div>;
}
+6
View File
@@ -0,0 +1,6 @@
import type { HTMLAttributes } from "react";
import { cn } from "./cn.js";
/** Secondary explanatory copy; identical inside and outside SettingsCard headers. */
export function Description({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {
return <p {...props} className={cn("nodedc-description", className)} />;
}
+120
View File
@@ -0,0 +1,120 @@
import {createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode} from "react";
import {DndContext, PointerSensor, useDraggable, useSensor, useSensors, type DragMoveEvent} from "@dnd-kit/core";
import {DragHandle} from "./DragDrop.js";
import {SplitPane} from "./SplitPane.js";
import {cn} from "./cn.js";
import {dockIds, dockPosition, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
const DockContext = createContext<{disabled: boolean; onKey: (id: string, event: KeyboardEvent<HTMLDivElement>) => void}>({disabled: true, onKey: () => {}});
/** The shared six-dot grip supports pointer dragging and keyboard docking. */
export function DockHandle({id, label}: {id: string; label: string}) {
const {disabled, onKey} = useContext(DockContext);
const {attributes, listeners, setNodeRef} = useDraggable({id, disabled});
return <div ref={setNodeRef} className="nodedc-dock-layout__handle" onKeyDown={event => onKey(id, event)}>
<DragHandle label={`Переместить · ${label}`} attributes={{...attributes, "aria-disabled": disabled}} listeners={listeners}/>
</div>;
}
export interface DockLayoutProps {
tree: DockTree | null;
onTreeChange: (tree: DockTree) => void;
panels: {id: string; label: string; minimumSize?: DockMinimum; preferredSize?: DockMinimum}[];
renderPanel: (id: string) => ReactNode;
focusedId?: string | null;
className?: string;
children?: ReactNode;
}
/** Media stay in stable sibling hosts; only geometry changes, including focus. */
export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId, className, children}: DockLayoutProps) {
const host = useRef<HTMLDivElement>(null);
// React must not reorder these DOM siblings: moving an iframe node reloads
// its browsing context even when its key and portal content are unchanged.
const hostOrder = useRef<string[]>([]);
const available = new Set(panels.map(panel => panel.id));
hostOrder.current = hostOrder.current.filter(id => available.has(id));
for (const panel of panels) if (!hostOrder.current.includes(panel.id)) hostOrder.current.push(panel.id);
const [bounds, setBounds] = useState<DockRect>({left: 0, top: 0, width: 0, height: 0});
const [active, setActive] = useState<string | null>(null), [target, setTarget] = useState<DockMove | null>(null);
const [keyboard, setKeyboard] = useState(false);
const sensors = useSensors(useSensor(PointerSensor, {activationConstraint: {distance: 6}}));
const ids = panels.map(panel => panel.id), visibleTree = pruneDockTree(tree, focusedId ? [focusedId] : ids);
const minimums = Object.fromEntries(panels.filter(p => p.minimumSize).map(p => [p.id, p.minimumSize!]));
const minimum = dockMinimum(visibleTree, minimums);
const canvas = {...bounds, width: Math.max(bounds.width, minimum.width), height: Math.max(bounds.height, minimum.height)};
const preferred = Object.fromEntries(panels.filter(p => p.preferredSize).map(p => [p.id,p.preferredSize!]));
const constrained = constrainDockTree(preferDockSizes(visibleTree,canvas,preferred), canvas, minimums);
const rects = dockRects(constrained, canvas);
const disabled = !!focusedId || ids.length < 2;
const reset = () => {setActive(null); setTarget(null); setKeyboard(false);};
useLayoutEffect(() => {
const element = host.current!;
const measure = () => {const r = element.getBoundingClientRect(); setBounds({left: 0, top: 0, width: r.width, height: r.height});};
measure(); const observer = new ResizeObserver(measure); observer.observe(element); return () => observer.disconnect();
}, []);
useEffect(() => {if (disabled || (active && !ids.includes(active))) reset();}, [disabled, panels.map(p => p.id).join("\0")]);
// Block iframe hit-testing only during a drag so pointer motion stays in the document.
const locate = (event: DragMoveEvent): DockMove | null => {
const start = event.activatorEvent as PointerEvent, box = host.current!.getBoundingClientRect();
const x = start.clientX + event.delta.x - box.left, y = start.clientY + event.delta.y - box.top;
for (const [id, rect] of Object.entries(rects)) {
const position = dockPosition(rect, x, y);
if (position && id !== String(event.active.id)) return {activeId: String(event.active.id), overId: id, position};
}
return null;
};
const commit = (move: DockMove | null) => {
const next = move && moveDockPanel(constrained, move);
if (next) onTreeChange(next);
reset();
};
const onKey = (id: string, event: KeyboardEvent<HTMLDivElement>) => {
if (disabled) return;
if (!keyboard) {
if (event.key !== " " && event.key !== "Enter") return;
const overId = ids.find(value => value !== id)!;
setActive(id); setTarget({activeId: id, overId, position: "center"}); setKeyboard(true);
} else if (event.key === "Escape") reset();
else if (event.key === "Enter" || event.key === " ") commit(target);
else if (event.key === "Tab") {
const candidates = dockIds(visibleTree).filter(value => value !== active), index = candidates.indexOf(target?.overId ?? "");
setTarget({activeId: active!, overId: candidates[(index + (event.shiftKey ? -1 : 1) + candidates.length) % candidates.length], position: target?.position ?? "center"});
} else {
const position = ({ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const)[event.key as "ArrowLeft"];
if (!position || !target) return;
setTarget({...target, position});
}
event.preventDefault(); event.stopPropagation();
};
const preview = target ? dockRects(moveDockPanel(constrained, target), canvas)[target.activeId] : null;
const action = target ? ({center: "Поменять местами", left: "Слева", right: "Справа", top: "Сверху", bottom: "Снизу"})[target.position] : "Выберите окно и край";
const label = target ? panels.find(panel => panel.id === target.overId)?.label : "";
return <DndContext sensors={sensors} autoScroll={false}
onDragStart={event => {setActive(String(event.active.id)); setKeyboard(false);}}
onDragMove={event => setTarget(locate(event))}
onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
<DockContext.Provider value={{disabled, onKey}}>
<div className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
<div ref={host} className="nodedc-dock-layout__canvas" style={{minWidth:minimum.width, minHeight:minimum.height}}>
<DockSlots tree={constrained} bounds={canvas} minimums={minimums} onResize={(path, ratio) => {if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/>
{hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel => <div key={panel.id} className="nodedc-dock-layout__panel" data-dock-id={panel.id}
data-dock-source={active === panel.id ? "true" : undefined} style={rects[panel.id] ?? {display: "none"}}>{renderPanel(panel.id)}</div>)}
{active ? <div className="nodedc-dock-layout__overlay" aria-hidden="true">
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} style={preview}><span>{action} · {label}</span></div> : null}
</div> : null}
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
</div>
</div>
{children}
</DockContext.Provider>
</DndContext>;
}
function DockSlots({tree, bounds, minimums, onResize, path = ""}: {tree: DockTree | null; bounds: DockMinimum; minimums: Record<string,DockMinimum>; onResize: (path: string, ratio: number) => void; path?: string}) {
if (!tree || "id" in tree) return null;
const key = tree.axis === "x" ? "width" : "height", span = bounds[key];
return <SplitPane className="nodedc-dock-layout__split" separatorAppearance="invisible" orientation={tree.axis === "x" ? "vertical" : "horizontal"}
primarySize={tree.ratio} minPrimarySize={span ? dockMinimum(tree.first,minimums)[key]/span*100 : 0} minSecondarySize={span ? dockMinimum(tree.second,minimums)[key]/span*100 : 0} onPrimarySizeChange={ratio => onResize(path, ratio)} separatorLabel="Изменить размеры окон"
primary={<DockSlots tree={tree.first} bounds={{...bounds,[key]:span*tree.ratio/100}} minimums={minimums} onResize={onResize} path={path + "0"}/>}
secondary={<DockSlots tree={tree.second} bounds={{...bounds,[key]:span*(1-tree.ratio/100)}} minimums={minimums} onResize={onResize} path={path + "1"}/>}/>;
}
+50 -16
View File
@@ -1,4 +1,7 @@
import { import {
createContext,
useContext,
useMemo,
useCallback, useCallback,
useEffect, useEffect,
useId, useId,
@@ -9,9 +12,12 @@ import {
type ReactNode, type ReactNode,
} from "react"; } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { computeFloatingPosition, type FloatingPlacement } from "@nodedc/ui-core"; import { computeFloatingPosition, type FloatingPlacement, type RectLike } from "@nodedc/ui-core";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
const DropdownLineage = createContext<readonly string[]>([]);
const openDropdowns = new Map<string, readonly string[]>();
export interface DropdownTriggerApi { export interface DropdownTriggerApi {
open: boolean; open: boolean;
show: () => void; show: () => void;
@@ -34,6 +40,11 @@ export interface DropdownProps {
surfaceClassName?: string; surfaceClassName?: string;
surfaceRole?: "menu" | "listbox" | "dialog"; surfaceRole?: "menu" | "listbox" | "dialog";
onOpenChange?: (open: boolean) => void; onOpenChange?: (open: boolean) => void;
/** Animated controls may reserve their maximum extent as a stable anchor. */
getAnchorRect?: () => RectLike | null;
flip?: boolean;
/** Capture-phase dismissal may consume a scene gesture before its tools run. */
onPointerDownOutside?: (event: PointerEvent) => void;
} }
export function Dropdown({ export function Dropdown({
@@ -48,8 +59,13 @@ export function Dropdown({
surfaceClassName, surfaceClassName,
surfaceRole = "menu", surfaceRole = "menu",
onOpenChange, onOpenChange,
getAnchorRect,
flip = true,
onPointerDownOutside,
}: DropdownProps) { }: DropdownProps) {
const instanceId = useId(); const instanceId = useId();
const ancestors = useContext(DropdownLineage);
const lineage = useMemo(() => [...ancestors, instanceId], [ancestors, instanceId]);
const surfaceId = `${instanceId.replaceAll(":", "")}-surface`; const surfaceId = `${instanceId.replaceAll(":", "")}-surface`;
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null); const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null);
@@ -72,7 +88,7 @@ export function Dropdown({
const updatePosition = useCallback(() => { const updatePosition = useCallback(() => {
const anchorNode = anchorElement ?? triggerElement; const anchorNode = anchorElement ?? triggerElement;
if (!anchorNode || !surfaceRef.current) return; if (!anchorNode || !surfaceRef.current) return;
const anchor = anchorNode.getBoundingClientRect(); const anchor = getAnchorRect?.() ?? anchorNode.getBoundingClientRect();
const anchorVisible = ( const anchorVisible = (
anchor.bottom > 0 anchor.bottom > 0
&& anchor.top < window.innerHeight && anchor.top < window.innerHeight
@@ -93,58 +109,73 @@ export function Dropdown({
surfaceWidth, surfaceWidth,
surfaceHeight, surfaceHeight,
placement, placement,
offset, offset, flip,
}); });
setSurfaceStyle({ const next:CSSProperties = {
top: position.top, top: position.top,
left: position.left, left: position.left,
width: surfaceWidth, width: Math.min(surfaceWidth, position.maxWidth ?? surfaceWidth),
maxHeight: position.maxHeight, maxHeight: position.maxHeight,
visibility: "visible", visibility: "visible",
}); };
}, [anchorElement, close, minWidth, offset, placement, triggerElement, width]); setSurfaceStyle(old => Object.keys(next).every(key => old[key as keyof CSSProperties] === next[key as keyof CSSProperties]) ? old : next);
}, [anchorElement, close, minWidth, offset, placement, triggerElement, width, getAnchorRect, flip]);
useLayoutEffect(() => { useLayoutEffect(() => {
if (!isOpen) return; if (!isOpen) return;
updatePosition(); updatePosition();
}, [isOpen, updatePosition]); }, [isOpen, updatePosition]);
useEffect(() => {
if (!isOpen || !getAnchorRect) return;
let frame:number;
const tick=()=>{updatePosition();frame=requestAnimationFrame(tick);};
frame=requestAnimationFrame(tick);
return()=>cancelAnimationFrame(frame);
},[isOpen,getAnchorRect,updatePosition]);
useEffect(() => { useEffect(() => {
if (!isOpen) return; if (!isOpen) return;
const handlePointerDown = (event: PointerEvent) => { const handlePointerDown = (event: PointerEvent) => {
const target = event.target; const target = event.target;
if (!(target instanceof Node)) return; if (!(target instanceof Node)) return;
if (anchorElement?.contains(target) || triggerElement?.contains(target) || surfaceRef.current?.contains(target)) return; if (anchorElement?.contains(target) || triggerElement?.contains(target) || surfaceRef.current?.contains(target)) return;
const surface = (target instanceof Element ? target : target.parentElement)?.closest('[data-dropdown-lineage]');
if (surface?.getAttribute('data-dropdown-lineage')?.split(' ').includes(instanceId)) return;
close(); close();
onPointerDownOutside?.(event);
}; };
const handleKeyDown = (event: KeyboardEvent) => { const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") { if (event.key === "Escape" && !event.defaultPrevented) {
if ([...openDropdowns].some(([id, parents]) => id !== instanceId && parents.includes(instanceId))) return;
close(); close();
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopImmediatePropagation();
triggerElement?.focus(); triggerElement?.focus();
} }
}; };
const handleOtherOpen = (event: Event) => { const handleOtherOpen = (event: Event) => {
const detail = (event as CustomEvent<{ id?: string }>).detail; const detail = (event as CustomEvent<{ id?: string; lineage?: readonly string[] }>).detail;
if (detail.id !== instanceId) close(); if (detail.id !== instanceId && !detail.lineage?.includes(instanceId)) close();
}; };
const handleViewportChange = () => updatePosition(); const handleViewportChange = () => updatePosition();
window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId } })); openDropdowns.set(instanceId, lineage);
document.addEventListener("pointerdown", handlePointerDown); window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId, lineage } }));
document.addEventListener("pointerdown", handlePointerDown, true);
document.addEventListener("keydown", handleKeyDown, true); document.addEventListener("keydown", handleKeyDown, true);
window.addEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener); window.addEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
window.addEventListener("resize", handleViewportChange); window.addEventListener("resize", handleViewportChange);
window.addEventListener("scroll", handleViewportChange, true); window.addEventListener("scroll", handleViewportChange, true);
return () => { return () => {
document.removeEventListener("pointerdown", handlePointerDown); openDropdowns.delete(instanceId);
document.removeEventListener("pointerdown", handlePointerDown, true);
document.removeEventListener("keydown", handleKeyDown, true); document.removeEventListener("keydown", handleKeyDown, true);
window.removeEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener); window.removeEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
window.removeEventListener("resize", handleViewportChange); window.removeEventListener("resize", handleViewportChange);
window.removeEventListener("scroll", handleViewportChange, true); window.removeEventListener("scroll", handleViewportChange, true);
}; };
}, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition]); }, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition, lineage, onPointerDownOutside]);
return ( return (
<span className={cn("nodedc-dropdown-anchor", className)}> <span className={cn("nodedc-dropdown-anchor", className)}>
@@ -154,13 +185,16 @@ export function Dropdown({
<div <div
ref={surfaceRef} ref={surfaceRef}
id={surfaceId} id={surfaceId}
data-dropdown-lineage={lineage.join(' ')}
className={cn("nodedc-dropdown-surface", surfaceClassName)} className={cn("nodedc-dropdown-surface", surfaceClassName)}
role={surfaceRole} role={surfaceRole}
style={surfaceStyle} style={surfaceStyle}
> >
<DropdownLineage.Provider value={lineage}>
{typeof children === "function" ? children({ close }) : children} {typeof children === "function" ? children({ close }) : children}
</DropdownLineage.Provider>
</div>, </div>,
document.body, document.fullscreenElement ?? document.body,
) )
: null} : null}
</span> </span>
@@ -0,0 +1,92 @@
import { useEffect, useMemo, useState } from "react";
import type {
EnvironmentBackground,
EnvironmentMediaItem,
} from "@nodedc/ui-core";
type ReadyEnvironmentMediaItem = EnvironmentMediaItem & {
url: string;
mediaKind: "image" | "video";
};
function isReadyMediaItem(
item: EnvironmentMediaItem,
): item is ReadyEnvironmentMediaItem {
return Boolean(item.url && item.mediaKind);
}
export function EnvironmentBackgroundMedia({
background,
}: {
background: EnvironmentBackground;
}) {
const items = useMemo(
() => background.items.filter(isReadyMediaItem),
[background.items],
);
const playlistIdentity = items.map((item) => `${item.id}:${item.url}`).join("|");
const [activeIndex, setActiveIndex] = useState(0);
const [failedIds, setFailedIds] = useState<Set<string>>(new Set());
const playableItems = items.filter((item) => !failedIds.has(item.id));
const activeItem = playableItems[activeIndex] ?? playableItems[0] ?? null;
useEffect(() => {
setActiveIndex(0);
setFailedIds(new Set());
}, [playlistIdentity]);
useEffect(() => {
if (
!background.enabled
|| !activeItem
|| activeItem.mediaKind !== "image"
|| playableItems.length < 2
) {
return;
}
const timer = window.setTimeout(() => {
setActiveIndex((current) => (current + 1) % playableItems.length);
}, background.imageDurationSeconds * 1_000);
return () => window.clearTimeout(timer);
}, [
activeItem,
background.enabled,
background.imageDurationSeconds,
playableItems.length,
]);
if (!background.enabled || !activeItem) return null;
return (
<div className="nodedc-landing-stage__media" aria-hidden="true">
{activeItem.mediaKind === "video" ? (
<video
key={activeItem.url}
src={activeItem.url}
autoPlay
muted
loop={playableItems.length === 1}
playsInline
onEnded={() => setActiveIndex((current) => (
(current + 1) % playableItems.length
))}
onError={() => {
setFailedIds((current) => new Set(current).add(activeItem.id));
setActiveIndex(0);
}}
/>
) : (
<img
key={activeItem.url}
src={activeItem.url}
alt=""
onError={() => {
setFailedIds((current) => new Set(current).add(activeItem.id));
setActiveIndex(0);
}}
/>
)}
</div>
);
}
@@ -0,0 +1,251 @@
import { useEffect, useMemo, useRef, useState } from "react";
import {
Icon,
IconButton,
MediaSourceField,
RangeControl,
SortableList,
} from "./index.js";
import {
appendEnvironmentMediaItem,
inferEnvironmentMediaKind,
maxEnvironmentMediaItems,
removeEnvironmentMediaItem,
type EnvironmentBackground,
type EnvironmentMediaItem,
type UploadedEnvironmentMedia,
} from "@nodedc/ui-core";
export interface EnvironmentMediaPlaylistEditorProps {
surfaceId: string;
background: EnvironmentBackground;
disabled: boolean;
error: string | null;
onChange: (background: EnvironmentBackground) => void;
onBusyChange: (busy: boolean) => void;
onUpload: (
surfaceId: string,
itemId: string,
file: File,
) => Promise<UploadedEnvironmentMedia>;
}
const acceptedEnvironmentMedia = [
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"image/avif",
"video/mp4",
"video/webm",
"video/quicktime",
".png",
".jpg",
".jpeg",
".gif",
".webp",
".avif",
".mp4",
".webm",
".mov",
].join(",");
function patchItem(
background: EnvironmentBackground,
itemId: string,
patch: Partial<EnvironmentMediaItem>,
): EnvironmentBackground {
return {
...background,
items: background.items.map((item) => (
item.id === itemId ? { ...item, ...patch } : item
)),
};
}
export function EnvironmentMediaPlaylistEditor({
surfaceId,
background,
disabled,
error,
onChange,
onBusyChange,
onUpload,
}: EnvironmentMediaPlaylistEditorProps) {
const [uploadingIds, setUploadingIds] = useState<Set<string>>(new Set());
const [itemErrors, setItemErrors] = useState<Record<string, string>>({});
const mounted = useRef(true);
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const backgroundRef = useRef(background);
backgroundRef.current = background;
const displayedItems = useMemo(
() => [...background.items].reverse(),
[background.items],
);
useEffect(() => {
onBusyChange(uploadingIds.size > 0);
}, [onBusyChange, uploadingIds.size]);
useEffect(() => () => onBusyChange(false), [onBusyChange]);
const setItemError = (itemId: string, message?: string) => {
setItemErrors((current) => {
const next = { ...current };
if (message) next[itemId] = message;
else delete next[itemId];
return next;
});
};
const uploadFile = async (itemId: string, file?: File) => {
if (!file) return;
setUploadingIds((current) => new Set(current).add(itemId));
setItemError(itemId);
try {
const uploaded = await onUpload(surfaceId, itemId, file);
if (!mounted.current) return;
onChange(patchItem(backgroundRef.current, itemId, {
source: "file",
url: uploaded.url,
mediaKind: uploaded.mediaKind,
fileName: uploaded.fileName,
}));
} catch (reason) {
if (!mounted.current) return;
setItemError(
itemId,
reason instanceof Error
? reason.message
: "Не удалось загрузить медиаконтент.",
);
} finally {
if (mounted.current) setUploadingIds((current) => {
const next = new Set(current);
next.delete(itemId);
return next;
});
}
};
return (
<div className="nodedc-environment-media-playlist">
<div className="nodedc-environment-media-playlist__head">
<div>
<span>Видео / картинка</span>
<p>MP4, WebM, MOV, PNG, JPEG, GIF, WebP или AVIF · до 256 МБ.</p>
</div>
<IconButton
label="Добавить медиаконтент"
disabled={disabled || background.items.length >= maxEnvironmentMediaItems}
onClick={() => onChange(appendEnvironmentMediaItem(background))}
>
<Icon name="plus" />
</IconButton>
</div>
{displayedItems.length ? (
<SortableList
items={displayedItems}
getId={(item) => item.id}
className="nodedc-environment-media-playlist__items"
onReorder={(items) => !disabled && onChange({
...background,
items: [...items].reverse(),
})}
>
{(item, { handle }) => {
const playbackIndex = background.items.findIndex(
(candidate) => candidate.id === item.id,
);
return (
<div className="nodedc-environment-media-playlist__item">
<MediaSourceField
label={`Медиаконтент ${String(playbackIndex + 1).padStart(2, "0")}`}
kindLabel={item.mediaKind ?? "media"}
source={item.source}
url={item.url ?? ""}
fileName={item.fileName}
disabled={disabled}
uploading={uploadingIds.has(item.id)}
previewSrc={item.url}
previewKind={item.mediaKind}
accept={acceptedEnvironmentMedia}
hint="Файл сохраняется в приложении. Ссылка должна вести прямо на изображение или видео по HTTP(S)."
error={itemErrors[item.id] ?? (
playbackIndex === background.items.length - 1 ? error : null
)}
onSourceChange={(source) => {
if (source === item.source) return;
setItemError(item.id);
onChange(patchItem(background, item.id, {
source,
url: null,
mediaKind: null,
fileName: null,
}));
}}
onUrlChange={(url) => {
setItemError(item.id);
onChange(patchItem(background, item.id, {
source: "url",
url: url || null,
mediaKind: url ? inferEnvironmentMediaKind(url) : null,
fileName: null,
}));
}}
onFileChange={(file) => void uploadFile(item.id, file)}
/>
<div className="nodedc-environment-media-playlist__item-actions">
<IconButton
label={`Удалить медиаконтент ${playbackIndex + 1}`}
disabled={disabled || uploadingIds.has(item.id)}
onClick={() => {
setItemError(item.id);
onChange(removeEnvironmentMediaItem(background, item.id));
}}
>
<Icon name="trash" />
</IconButton>
{handle}
</div>
</div>
);
}}
</SortableList>
) : (
<>
<p className="nodedc-environment-media-playlist__empty">
Добавьте первый файл или прямую ссылку на медиаконтент.
</p>
{error ? (
<p className="nodedc-environment-media-playlist__error" role="alert">
{error}
</p>
) : null}
</>
)}
<div className="nodedc-environment-media-playlist__timing">
<RangeControl
label="Показывать изображение"
value={background.imageDurationSeconds}
min={1}
max={60}
step={1}
disabled={disabled}
formatValue={(value) => `${value} с`}
onChange={(imageDurationSeconds) => onChange({
...background,
imageDurationSeconds,
})}
/>
<span>
Новые элементы появляются сверху. Воспроизведение начинается снизу;
перетаскивание меняет порядок.
</span>
</div>
</div>
);
}
@@ -0,0 +1,355 @@
import { useEffect, useMemo, useState } from "react";
import {
Button,
FeatureSettingsWindow,
Select,
SettingsCard,
Switch,
TextAreaField,
TextField,
WindowFooterActions,
} from "./index.js";
import {
cloneEnvironmentSettings,
type EnvironmentBackground,
type EnvironmentPage,
type EnvironmentSettings,
type EnvironmentSurface,
type UploadedEnvironmentMedia,
} from "@nodedc/ui-core";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor.js";
export interface EnvironmentSettingsWindowProps {
productName: string;
surfaces: readonly EnvironmentSurface[];
initialSurfaceId?: string;
open: boolean;
settings: EnvironmentSettings;
state: "loading" | "ready" | "saving" | "error";
error: string | null;
onClose: () => void;
onSave: (settings: EnvironmentSettings) => Promise<EnvironmentSettings>;
onUpload: (
surfaceId: string,
itemId: string,
file: File,
) => Promise<UploadedEnvironmentMedia>;
}
function patchPage(
draft: EnvironmentSettings,
surfaceId: string,
patch: Partial<EnvironmentPage>,
): EnvironmentSettings {
return {
...draft,
pages: {
...draft.pages,
[surfaceId]: {
...draft.pages[surfaceId],
...patch,
},
},
};
}
function patchBackground(
draft: EnvironmentSettings,
surfaceId: string,
patch: Partial<EnvironmentBackground>,
): EnvironmentSettings {
const page = draft.pages[surfaceId];
return patchPage(draft, surfaceId, {
background: {
...page.background,
...patch,
},
});
}
export function EnvironmentSettingsWindow({
productName,
surfaces,
initialSurfaceId,
open,
settings,
state,
error,
onClose,
onSave,
onUpload,
}: EnvironmentSettingsWindowProps) {
const [draft, setDraft] = useState(() => cloneEnvironmentSettings(settings));
const [surfaceId, setSurfaceId] = useState(initialSurfaceId ?? surfaces[0]?.id ?? "home");
const [uploading, setUploading] = useState(false);
const [localError, setLocalError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setDraft(cloneEnvironmentSettings(settings));
setLocalError(null);
}, [open, settings]);
const selectedPage = draft.pages[surfaceId];
const selectedBackground = selectedPage.background;
const pageOptions = surfaces.map(surface => ({ value: surface.id, label: draft.pages[surface.id].headerLabel, description: surface.description }));
const selectedSurface = surfaces.find(surface => surface.id === surfaceId) ?? surfaces[0];
const quickActionWorkspaces = selectedSurface?.actions ?? [];
const quickActionOptions = useMemo(() => [
{
value: "none",
label: "Не показывать",
description: "Кнопка скрыта на стартовом экране",
},
...quickActionWorkspaces.map((workspace) => ({
value: workspace.id,
label: workspace.label,
description: workspace.description,
})),
], [quickActionWorkspaces]);
const dirty = useMemo(
() => JSON.stringify(draft) !== JSON.stringify(settings),
[draft, settings],
);
const busy = state === "loading" || state === "saving" || uploading;
const updatePage = (patch: Partial<EnvironmentPage>) => {
setDraft((current) => patchPage(current, surfaceId, patch));
};
const save = async () => {
const invalid = Object.entries(draft.pages).find(([, page]) => (
!page.headerLabel.trim()
|| !page.eyebrow.trim()
|| !page.title.trim()
|| !page.description.trim()
));
if (invalid) {
setLocalError("Название, надзаголовок, заголовок и описание не могут быть пустыми.");
return;
}
const duplicateActions = Object.entries(draft.pages).find(([, page]) => (
page.primaryWorkspaceId && page.primaryWorkspaceId === page.secondaryWorkspaceId
));
if (duplicateActions) {
setSurfaceId(duplicateActions[0]);
setLocalError("Быстрые кнопки должны вести на разные рабочие поверхности.");
return;
}
const invalidMedia = Object.entries(draft.pages).find(([, page]) => (
(page.background.enabled && !page.background.items.length)
|| page.background.items.some((item) => {
if (!item.url || !item.mediaKind) return true;
if (item.source !== "url") return false;
try {
const parsed = new URL(item.url);
return !["http:", "https:"].includes(parsed.protocol);
} catch {
return true;
}
})
));
if (invalidMedia) {
setSurfaceId(invalidMedia[0] as string);
setLocalError(
"Каждый элемент фона должен содержать загруженный файл или прямой HTTP(S) URL.",
);
return;
}
setLocalError(null);
try {
await onSave({
...draft,
pages: Object.fromEntries(
Object.entries(draft.pages).map(([id, page]) => [id, {
...page,
headerLabel: page.headerLabel.trim(),
eyebrow: page.eyebrow.trim(),
title: page.title.trim(),
description: page.description.trim(),
}]),
) as EnvironmentSettings["pages"],
});
onClose();
} catch (reason) {
setLocalError(reason instanceof Error
? reason.message
: "Не удалось сохранить настройки окружения.");
}
};
return (
<FeatureSettingsWindow
open={open}
title={`Настройки ${productName}`}
subtitle="Локальное операторское окружение"
identity={{
title: "DC",
subtitle: productName,
avatarLabel: "DC",
}}
sections={[
{
id: "environment",
label: "Окружение",
group: productName.toUpperCase(),
icon: "settings",
},
]}
activeSection="environment"
onSectionChange={() => undefined}
onClose={onClose}
footer={(
<WindowFooterActions>
<Button
variant="secondary"
disabled={!dirty || busy}
onClick={() => {
setDraft(cloneEnvironmentSettings(settings));
setLocalError(null);
}}
>
Сбросить изменения
</Button>
<Button
variant="primary"
tone="neutral"
disabled={!dirty || busy}
onClick={() => void save()}
>
{state === "saving" ? "Сохраняем…" : "Сохранить"}
</Button>
</WindowFooterActions>
)}
>
<div className="nodedc-environment-settings">
<SettingsCard
eyebrow="ОКРУЖЕНИЕ"
title="Основные элементы управления"
description="Выберите страницу и настройте её название в шапке, содержание стартового экрана, подложку и быстрые переходы."
actions={(
<Switch
disabled={busy}
checked={selectedBackground.enabled}
label="Показывать фон"
onChange={(enabled) => {
if (enabled && !selectedBackground.items.length) {
setLocalError("Сначала добавьте медиаконтент.");
return;
}
setLocalError(null);
setDraft((current) =>
patchBackground(current, surfaceId, { enabled }));
}}
/>
)}
>
<div className="nodedc-environment-settings__editor">
<div className="nodedc-environment-settings__surface">
<span>Страница</span>
<Select
disabled={busy}
label="Выбрать страницу окружения"
value={surfaceId}
options={pageOptions}
variant="split"
menuWidth="anchor"
onChange={(value) => {
setSurfaceId(value);
setLocalError(null);
}}
/>
</div>
<div className="nodedc-environment-settings__copy">
<TextField
disabled={busy}
label={selectedSurface?.home ? "Название продукта" : "Название в шапке"}
value={selectedPage.headerLabel}
maxLength={40}
onChange={(event) => updatePage({
headerLabel: event.currentTarget.value,
})}
/>
<TextField
disabled={busy}
label="Надзаголовок"
value={selectedPage.eyebrow}
maxLength={80}
onChange={(event) => updatePage({
eyebrow: event.currentTarget.value,
})}
/>
<TextField
disabled={busy}
label="Основной заголовок"
value={selectedPage.title}
maxLength={120}
onChange={(event) => updatePage({
title: event.currentTarget.value,
})}
/>
<TextAreaField
disabled={busy}
label="Описание"
value={selectedPage.description}
maxLength={500}
rows={3}
onChange={(event) => updatePage({
description: event.currentTarget.value,
})}
/>
</div>
<div className="nodedc-environment-settings__quick-actions">
<div>
<span>Кнопка 1</span>
<Select
disabled={busy}
label="Выбрать первую быструю кнопку"
value={selectedPage.primaryWorkspaceId ?? "none"}
options={quickActionOptions}
variant="split"
menuWidth="anchor"
onChange={(value) => updatePage({
primaryWorkspaceId: value === "none" ? null : value,
})}
/>
</div>
<div>
<span>Кнопка 2</span>
<Select
disabled={busy}
label="Выбрать вторую быструю кнопку"
value={selectedPage.secondaryWorkspaceId ?? "none"}
options={quickActionOptions}
variant="split"
menuWidth="anchor"
onChange={(value) => updatePage({
secondaryWorkspaceId: value === "none" ? null : value,
})}
/>
</div>
</div>
<EnvironmentMediaPlaylistEditor
key={surfaceId}
surfaceId={surfaceId}
background={selectedBackground}
disabled={busy}
error={localError ?? error}
onBusyChange={setUploading}
onChange={(background) => {
setLocalError(null);
setDraft((current) =>
patchBackground(current, surfaceId, background));
}}
onUpload={onUpload}
/>
</div>
</SettingsCard>
</div>
</FeatureSettingsWindow>
);
}
@@ -1,4 +1,4 @@
import type { ReactNode } from "react"; import { useLayoutEffect, useRef, type ReactNode } from "react";
import { HeaderAvatar } from "./AppHeader.js"; import { HeaderAvatar } from "./AppHeader.js";
import { Icon, type IconName } from "./Icon.js"; import { Icon, type IconName } from "./Icon.js";
import { Window } from "./Window.js"; import { Window } from "./Window.js";
@@ -27,6 +27,7 @@ export interface FeatureSettingsWindowProps<T extends string = string> {
onClose: () => void; onClose: () => void;
children: ReactNode; children: ReactNode;
footer?: ReactNode; footer?: ReactNode;
headerActions?: ReactNode;
} }
export function FeatureSettingsWindow<T extends string>({ export function FeatureSettingsWindow<T extends string>({
@@ -40,7 +41,10 @@ export function FeatureSettingsWindow<T extends string>({
onClose, onClose,
children, children,
footer, footer,
headerActions,
}: FeatureSettingsWindowProps<T>) { }: FeatureSettingsWindowProps<T>) {
const contentRef = useRef<HTMLElement>(null);
useLayoutEffect(() => { if (contentRef.current) contentRef.current.scrollTop = 0; }, [activeSection]);
return ( return (
<Window <Window
open={open} open={open}
@@ -49,11 +53,12 @@ export function FeatureSettingsWindow<T extends string>({
size="lg" size="lg"
className="nodedc-feature-settings-window" className="nodedc-feature-settings-window"
footer={footer} footer={footer}
headerActions={headerActions}
closeOnBackdrop={false} closeOnBackdrop={false}
onClose={onClose} onClose={onClose}
> >
<div className="nodedc-feature-settings"> <div className="nodedc-feature-settings">
<aside className="nodedc-feature-settings__navigation" aria-label="Разделы настроек"> <aside className="nodedc-feature-settings__navigation" aria-label="Разделы настроек" tabIndex={0}>
<div className="nodedc-feature-settings__identity"> <div className="nodedc-feature-settings__identity">
<HeaderAvatar label={identity.avatarLabel} imageUrl={identity.avatarUrl} /> <HeaderAvatar label={identity.avatarLabel} imageUrl={identity.avatarUrl} />
<span><strong>{identity.title}</strong>{identity.subtitle ? <small>{identity.subtitle}</small> : null}</span> <span><strong>{identity.title}</strong>{identity.subtitle ? <small>{identity.subtitle}</small> : null}</span>
@@ -79,7 +84,7 @@ export function FeatureSettingsWindow<T extends string>({
})} })}
</nav> </nav>
</aside> </aside>
<section className="nodedc-feature-settings__content">{children}</section> <section ref={contentRef} className="nodedc-feature-settings__content" aria-label="Содержимое настроек" tabIndex={0}>{children}</section>
</div> </div>
</Window> </Window>
); );
+3 -2
View File
@@ -3,6 +3,7 @@ import { cn } from "./cn.js";
export interface FieldFrameProps { export interface FieldFrameProps {
label: string; label: string;
labelPlacement?: "above" | "below";
hint?: string; hint?: string;
description?: string; description?: string;
htmlFor?: string; htmlFor?: string;
@@ -10,9 +11,9 @@ export interface FieldFrameProps {
className?: string; className?: string;
} }
export function FieldFrame({ label, hint, description, htmlFor, children, className }: FieldFrameProps) { export function FieldFrame({ label, hint, description, htmlFor, children, className, labelPlacement = "above" }: FieldFrameProps) {
return ( return (
<label className={cn("nodedc-field", className)} htmlFor={htmlFor}> <label className={cn("nodedc-field", labelPlacement === "below" && "nodedc-field--caption", className)} htmlFor={htmlFor}>
<span className="nodedc-field__label-row"> <span className="nodedc-field__label-row">
<span className="nodedc-field__label">{label}</span> <span className="nodedc-field__label">{label}</span>
{hint ? <span className="nodedc-field__hint">{hint}</span> : null} {hint ? <span className="nodedc-field__hint">{hint}</span> : null}
+1 -1
View File
@@ -2,7 +2,7 @@ import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
export type GlassTone = "default" | "strong" | "soft"; export type GlassTone = "default" | "strong" | "soft";
export type GlassRadius = "card" | "panel" | "modal"; export type GlassRadius = "card" | "panel" | "modal" | "pill";
export type GlassPadding = "none" | "sm" | "md" | "lg"; export type GlassPadding = "none" | "sm" | "md" | "lg";
export interface GlassSurfaceProps extends HTMLAttributes<HTMLDivElement> { export interface GlassSurfaceProps extends HTMLAttributes<HTMLDivElement> {
+44 -2
View File
@@ -1,10 +1,21 @@
import { import {
MousePointer2,
CirclePlus,
Box,
Scan,
PenTool,
RectangleHorizontal,
Spline,
Undo2,
Redo2,
Activity, Activity,
AlertTriangle, AlertTriangle,
Boxes, Boxes,
Building2, Building2,
Camera,
Check, Check,
ChevronDown, ChevronDown,
ChevronUp,
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
Circle, Circle,
@@ -12,30 +23,39 @@ import {
Copy, Copy,
Database, Database,
Download, Download,
Eye,
EyeOff,
ExternalLink, ExternalLink,
FileText, FileText,
FolderOpen, FolderOpen,
Globe2, Globe2,
Image, Image,
Inbox, Inbox,
Info,
KeyRound, KeyRound,
Layers,
LayoutDashboard, LayoutDashboard,
ListChecks, ListChecks,
LocateFixed, LocateFixed,
LockKeyhole, LockKeyhole,
MailPlus, MailPlus,
Map,
Maximize2, Maximize2,
Minimize2, Minimize2,
Network, Network,
PanelTop, PanelTop,
Pencil, Pencil,
Play,
Plus, Plus,
RefreshCw, RefreshCw,
RotateCw,
Save, Save,
Search, Search,
Settings, Settings,
ShieldCheck, ShieldCheck,
SlidersHorizontal, SlidersHorizontal,
Square,
Terminal,
Trash2, Trash2,
UploadCloud, UploadCloud,
UserCircle, UserCircle,
@@ -47,12 +67,23 @@ import {
} from "lucide-react"; } from "lucide-react";
const icons = { const icons = {
"add-point": CirclePlus,
perspective: Box,
orthographic: Scan,
select: MousePointer2,
pen: PenTool,
rectangle: RectangleHorizontal,
curve: Spline,
undo: Undo2,
redo: Redo2,
activity: Activity, activity: Activity,
alert: AlertTriangle, alert: AlertTriangle,
apps: Boxes, apps: Boxes,
building: Building2, building: Building2,
camera: Camera,
check: Check, check: Check,
"chevron-down": ChevronDown, "chevron-down": ChevronDown,
"chevron-up": ChevronUp,
"chevron-left": ChevronLeft, "chevron-left": ChevronLeft,
"chevron-right": ChevronRight, "chevron-right": ChevronRight,
circle: Circle, circle: Circle,
@@ -62,6 +93,8 @@ const icons = {
database: Database, database: Database,
download: Download, download: Download,
edit: Pencil, edit: Pencil,
eye: Eye,
"eye-off": EyeOff,
expand: Maximize2, expand: Maximize2,
external: ExternalLink, external: ExternalLink,
file: FileText, file: FileText,
@@ -70,7 +103,9 @@ const icons = {
grid: LayoutDashboard, grid: LayoutDashboard,
image: Image, image: Image,
inbox: Inbox, inbox: Inbox,
info: Info,
key: KeyRound, key: KeyRound,
layers: Layers,
list: ListChecks, list: ListChecks,
target: LocateFixed, target: LocateFixed,
lock: LockKeyhole, lock: LockKeyhole,
@@ -78,14 +113,19 @@ const icons = {
minimize: Minimize2, minimize: Minimize2,
network: Network, network: Network,
panel: PanelTop, panel: PanelTop,
plan: Map,
play: Play,
plus: Plus, plus: Plus,
profile: UserCircle, profile: UserCircle,
refresh: RefreshCw, refresh: RefreshCw,
"rotate-clockwise": RotateCw,
save: Save, save: Save,
search: Search, search: Search,
settings: Settings, settings: Settings,
shield: ShieldCheck, shield: ShieldCheck,
sliders: SlidersHorizontal, sliders: SlidersHorizontal,
stop: Square,
terminal: Terminal,
trash: Trash2, trash: Trash2,
upload: UploadCloud, upload: UploadCloud,
users: UsersRound, users: UsersRound,
@@ -99,13 +139,15 @@ export interface IconProps extends Omit<LucideProps, "ref"> {
label?: string; label?: string;
} }
export function Icon({ name, label, size = 16, strokeWidth = 1.6, ...props }: IconProps) { export function Icon({ name, label, size = 16, strokeWidth = 1.6, fill, ...props }: IconProps) {
const IconComponent = icons[name]; const IconComponent = icons[name];
const filledTransport = name === "play" || name === "stop";
return ( return (
<IconComponent <IconComponent
size={size} size={size}
strokeWidth={strokeWidth} strokeWidth={filledTransport ? 0 : strokeWidth}
fill={fill ?? (filledTransport ? "currentColor" : "none")}
aria-hidden={label ? undefined : "true"} aria-hidden={label ? undefined : "true"}
aria-label={label} aria-label={label}
role={label ? "img" : undefined} role={label ? "img" : undefined}
+9 -1
View File
@@ -3,6 +3,7 @@ import { InspectorSelectPolicyContext } from "./InspectorContext.js";
import { Select, type SelectProps } from "./Select.js"; import { Select, type SelectProps } from "./Select.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import { Icon } from "./Icon.js"; import { Icon } from "./Icon.js";
import { IconButton } from "./Button.js";
export interface InspectorSectionSpec { export interface InspectorSectionSpec {
id: string; id: string;
@@ -13,6 +14,7 @@ export interface InspectorSectionSpec {
disabled?: boolean; disabled?: boolean;
tone?: "default" | "accent"; tone?: "default" | "accent";
icon?: ReactNode; icon?: ReactNode;
action?: { label: string; icon: ReactNode; onAction: () => void; disabled?: boolean };
} }
export interface InspectorProps { export interface InspectorProps {
@@ -74,6 +76,7 @@ export function Inspector({
const isOpen = openIds.has(section.id); const isOpen = openIds.has(section.id);
return ( return (
<section className="nodedc-inspector__section" key={section.id}> <section className="nodedc-inspector__section" key={section.id}>
<div className="nodedc-inspector__section-head" data-action={section.action ? "true" : undefined}>
<button <button
type="button" type="button"
className="nodedc-inspector__section-trigger" className="nodedc-inspector__section-trigger"
@@ -91,8 +94,13 @@ export function Inspector({
<span className="nodedc-inspector__section-description">{section.description}</span> <span className="nodedc-inspector__section-description">{section.description}</span>
) : null} ) : null}
</span> </span>
<span className="nodedc-inspector__section-chevron" aria-hidden="true"><Icon name="chevron-right" size={14} /></span> <span className="nodedc-inspector__section-chevron" aria-hidden="true"><Icon name={variant === "panel" ? "chevron-down" : "chevron-right"} size={14} /></span>
</button> </button>
{section.action ? <IconButton className="nodedc-inspector__section-action" label={section.action.label}
disabled={section.disabled || section.action.disabled} onClick={section.action.onAction}>
{section.action.icon}
</IconButton> : null}
</div>
{isOpen ? <div className="nodedc-inspector__section-content">{section.content}</div> : null} {isOpen ? <div className="nodedc-inspector__section-content">{section.content}</div> : null}
</section> </section>
); );
+17
View File
@@ -0,0 +1,17 @@
import {forwardRef, type ButtonHTMLAttributes} from 'react';
import {cn} from './cn.js';
export interface KeyButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
/** Controlled physical/pointer input indication; this is never a toggle. */
pressed?: boolean;
label: string;
}
/** A momentary key surface. The consumer owns input, focus scope and release policy. */
export const KeyButton = forwardRef<HTMLButtonElement, KeyButtonProps>(function KeyButton(
{pressed=false,label,children,className,type='button',disabled,...props},ref,
) {
return <button {...props} ref={ref} type={type} disabled={disabled}
aria-label={label} title={label} aria-pressed={pressed && !disabled}
className={cn('nodedc-key-button',className)}>{children}</button>;
});
+51
View File
@@ -0,0 +1,51 @@
import type { ReactNode } from "react";
import type { EnvironmentPage } from "@nodedc/ui-core";
import { Button } from "./Button.js";
import { Icon, type IconName } from "./Icon.js";
import { EnvironmentBackgroundMedia } from "./EnvironmentBackgroundMedia.js";
export interface LandingStageProps {
page: EnvironmentPage;
pageId?: string;
actions?: readonly { id: string; label: string; icon?: IconName; onSelect: () => void }[];
status?: ReactNode;
footer?: ReactNode;
}
export function LandingStage({ page, pageId = "home", actions = [], status, footer }: LandingStageProps) {
const { background } = page;
const hasMedia = background.enabled && background.items.some(
(item) => item.url && item.mediaKind,
);
return (
<section
className="nodedc-landing-stage"
data-page={pageId}
data-has-media={hasMedia ? "true" : undefined}
>
<EnvironmentBackgroundMedia background={background} />
<div className="nodedc-landing-stage__shade" aria-hidden="true" />
<div className="nodedc-landing-stage__copy">
<span className="nodedc-landing-stage__eyebrow">{page.eyebrow}</span>
<h1>{page.title}</h1>
<p>{page.description}</p>
{actions.length ? (
<div className="nodedc-landing-stage__actions">
{actions.map((workspace, index) => (
<Button
key={workspace.id}
variant={index === 0 ? "primary" : "secondary"}
tone="neutral"
icon={workspace.icon ? <Icon name={workspace.icon} /> : undefined}
onClick={() => workspace.onSelect()}
>
{workspace.label}
</Button>
))}
</div>
) : null}
</div>
{status ? <div className="nodedc-landing-stage__status">{status}</div> : null}
{footer ? <footer className="nodedc-landing-stage__footer">{footer}</footer> : null}
</section>
);
}
+3
View File
@@ -0,0 +1,3 @@
import { createContext } from "react";
/** A composed content surface owns one pending indicator. Windows reset this scope. */
export const LoadingContext = createContext<null | ((id: string, pending: boolean) => void)>(null);
+38
View File
@@ -0,0 +1,38 @@
import { useCallback, useContext, useId, useLayoutEffect, useState, type HTMLAttributes } from "react";
import { ActivityIndicator } from "./ActivityIndicator.js";
import { LoadingContext } from "./LoadingContext.js";
import { cn } from "./cn.js";
export interface LoadingRegionProps extends HTMLAttributes<HTMLDivElement> {
loading: boolean;
label: string;
/** Collect nested initial-content loads into this surface's single indicator. */
aggregate?: boolean;
}
/** Keeps content mounted. Failures/unmounts release each nested pending lease. */
export function LoadingRegion({ loading, label, aggregate = false, children, className, ...props }: LoadingRegionProps) {
const parent = useContext(LoadingContext);
const id = useId();
const [pending, setPending] = useState<ReadonlySet<string>>(() => new Set());
const report = useCallback((key: string, busy: boolean) => {
setPending(previous => {
if (previous.has(key) === busy) return previous;
const next = new Set(previous);
if (busy) next.add(key); else next.delete(key);
return next;
});
}, []);
useLayoutEffect(() => {
parent?.(id, loading);
return () => parent?.(id, false);
}, [parent, id, loading]);
const busy = loading || (aggregate && !parent && pending.size > 0);
const content = <div {...props} className={cn("nodedc-loading-region", className)} aria-busy={busy}>
{children}
{busy && !parent ? <div className="nodedc-loading-region__status" role="status" aria-label={label}>
<ActivityIndicator /><span aria-hidden="true">{label}</span>
</div> : null}
</div>;
return aggregate && !parent ? <LoadingContext.Provider value={report}>{content}</LoadingContext.Provider> : content;
}
+6 -1
View File
@@ -11,6 +11,7 @@ export interface MediaSourceFieldProps {
url: string; url: string;
fileName?: string | null; fileName?: string | null;
uploading?: boolean; uploading?: boolean;
disabled?: boolean;
previewSrc?: string | null; previewSrc?: string | null;
previewKind?: MediaPreviewKind | null; previewKind?: MediaPreviewKind | null;
accept?: string; accept?: string;
@@ -43,6 +44,7 @@ export function MediaSourceField({
url, url,
fileName, fileName,
uploading = false, uploading = false,
disabled = false,
previewSrc, previewSrc,
previewKind, previewKind,
accept = "image/*,video/*", accept = "image/*,video/*",
@@ -73,11 +75,12 @@ export function MediaSourceField({
<div className="nodedc-media-file" hidden={source !== "file"} data-nodedc-media-source-panel="file"> <div className="nodedc-media-file" hidden={source !== "file"} data-nodedc-media-source-panel="file">
<label className="nodedc-media-file__button" htmlFor={inputId}>{fileButtonLabel}</label> <label className="nodedc-media-file__button" htmlFor={inputId}>{fileButtonLabel}</label>
<span className="nodedc-media-file__name" title={displayFileName}>{displayFileName}</span> <span className="nodedc-media-file__name" title={displayFileName}>{displayFileName}</span>
<input id={inputId} type="file" accept={accept} disabled={uploading} onChange={handleFileChange} /> <input id={inputId} type="file" accept={accept} disabled={disabled || uploading} onChange={handleFileChange} />
</div> </div>
<input <input
className="nodedc-media-url" className="nodedc-media-url"
type="url" type="url"
disabled={disabled || uploading}
value={url} value={url}
hidden={source !== "url"} hidden={source !== "url"}
data-nodedc-media-source-panel="url" data-nodedc-media-source-panel="url"
@@ -89,6 +92,7 @@ export function MediaSourceField({
<div className="nodedc-media-source-switch" aria-label={`${label}: источник`}> <div className="nodedc-media-source-switch" aria-label={`${label}: источник`}>
<button <button
type="button" type="button"
disabled={disabled || uploading}
className="nodedc-media-source-button" className="nodedc-media-source-button"
data-active={source === "file" ? "true" : undefined} data-active={source === "file" ? "true" : undefined}
data-nodedc-media-source-option="file" data-nodedc-media-source-option="file"
@@ -98,6 +102,7 @@ export function MediaSourceField({
>HD</button> >HD</button>
<button <button
type="button" type="button"
disabled={disabled || uploading}
className="nodedc-media-source-button" className="nodedc-media-source-button"
data-active={source === "url" ? "true" : undefined} data-active={source === "url" ? "true" : undefined}
data-nodedc-media-source-option="url" data-nodedc-media-source-option="url"
+57
View File
@@ -0,0 +1,57 @@
import {useState,type CSSProperties} from "react";
export type CubeDirection = [number,number,number];
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;
disabled?:boolean;
label?:string;
}
const faces = [
{axis:0,sign:1,label:"RIGHT"},{axis:0,sign:-1,label:"LEFT"},
{axis:1,sign:1,label:"TOP"},{axis:1,sign:-1,label:"BOTTOM"},
{axis:2,sign:1,label:"FRONT"},{axis:2,sign:-1,label:"BACK"},
];
const cuts=[-1,-.55,.55,1];
/** Inverse quaternion rotation; avoids a renderer or additional WebGL context. */
function view(p:number[],q:readonly number[]) {
const n=Math.hypot(...q)||1;
const [x,y,z,w]=[-q[0]/n,-q[1]/n,-q[2]/n,q[3]/n], [a,b,c]=p;
const tx=2*(y*c-z*b),ty=2*(z*a-x*c),tz=2*(x*b-y*a);
return [a+w*tx+y*tz-z*ty,b+w*ty+z*tx-x*tz,c+w*tz+x*ty-y*tx];
}
export function cubeRegions(quaternion:NavigationCubeProps["quaternion"]) {
return faces.flatMap(face=>{
const axes=[0,1,2].filter(k=>k!==face.axis),normal=[0,0,0];normal[face.axis]=face.sign;
if(view(normal,quaternion)[2]<1e-5)return [];
const point=(u:number,v:number)=>{const p=[0,0,0];p[face.axis]=face.sign;p[axes[0]]=u;p[axes[1]]=v;return p;};
return Array.from({length:9},(_,i)=>{
const row=Math.floor(i/3),col=i%3,direction=point(col-1,row-1) as CubeDirection;
const label=faces.filter(f=>direction[f.axis]===f.sign).map(f=>f.label).join(" · ");
const polygon=[[cuts[col],cuts[row]],[cuts[col+1],cuts[row]],[cuts[col+1],cuts[row+1]],[cuts[col],cuts[row+1]]]
.map(([u,v])=>view(point(u,v),quaternion)).map(p=>`${60+p[0]*30},${60-p[1]*30}`).join(" ");
const p=view(point(0,0),quaternion);
// Face-local right/up tangents keep labels printed on the rotating face.
const right=face.axis===0?[0,0,-face.sign]:face.axis===1?[1,0,0]:[face.sign,0,0];
const up=face.axis===1?[0,0,-face.sign]:[0,1,0];
const u=view(right,quaternion),v=view(up,quaternion);
const textMatrix=[u[0],-u[1],-v[0],v[1],60+p[0]*30,60-p[1]*30];
return {id:`${face.label}-${i}`,direction,label,polygon,faceLabel:i===4?face.label:null,textMatrix};
});
});
}
/** 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) {
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}>
{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)}
onClick={()=>{if(!disabled)onSelect(r.direction);}}
onKeyDown={e=>{if(!disabled&&(e.key==="Enter"||e.key===" ")){e.preventDefault();onSelect(r.direction);}}}>
<title>{r.label}</title><polygon points={r.polygon}/>
{r.faceLabel?<text transform={`matrix(${r.textMatrix.join(" ")})`} x={0} y={0} dy=".35em" textAnchor="middle">{r.faceLabel}</text>:null}
</g>)}
</svg>;
}
+20
View File
@@ -0,0 +1,20 @@
import type { CSSProperties, HTMLAttributes } from "react";
import { cn } from "./cn.js";
export interface ProgressBarProps extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
label: string;
/** Completed fraction from 0 to 1. Omit when the amount is unknown. */
value?: number;
valueText?: string;
}
export function ProgressBar({ label, value, valueText, className, style, ...props }: ProgressBarProps) {
const fraction = typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : undefined;
return <div {...props} className={cn("nodedc-progress-bar", className)} role="progressbar"
aria-label={label} aria-valuemin={0} aria-valuemax={100}
aria-valuenow={fraction === undefined ? undefined : Math.round(fraction * 100)}
aria-valuetext={valueText} data-indeterminate={fraction === undefined || undefined}
style={{ ...style, "--nodedc-progress-fraction": fraction ?? 0 } as CSSProperties}>
<span className="nodedc-progress-bar__fill" />
</div>;
}
+31
View File
@@ -0,0 +1,31 @@
import { useId } from "react";
import { Button, type ButtonProps } from "./Button.js";
import { ProgressBar } from "./ProgressBar.js";
import { Icon } from "./Icon.js";
import { cn } from "./cn.js";
export interface ProgressButtonProps extends Omit<ButtonProps, "children" | "loading" | "size"> {
label: string;
/** Presence means pending. Value is measured progress of the named phase, not elapsed time. */
progress?: { label: string; value?: number; valueText?: string };
}
export function ProgressButton({ label, progress, className, disabled, icon, ...props }: ProgressButtonProps) {
const statusId = useId();
return <div className={cn("nodedc-progress-button", className)} data-pending={!!progress || undefined}
data-icon={!!icon || undefined}>
<Button {...props} icon={icon} disabled={disabled || !!progress} aria-busy={!!progress}
aria-label={label} aria-describedby={progress ? statusId : undefined}>
<span className="nodedc-progress-button__label">{progress?.label ?? label}</span>
</Button>
{progress ? <>
<span id={statusId} className="nodedc-progress-button__status" role="status">{progress.label}</span>
<ProgressBar label={label} value={progress.value} valueText={progress.valueText ?? progress.label} />
</> : null}
</div>;
}
/** Decorative animation of the canonical layers glyph. The surrounding action owns live status. */
export function LayerStackIndicator() {
return <Icon name="layers" className="nodedc-layer-stack-indicator" />;
}
+70 -17
View File
@@ -1,13 +1,24 @@
import { useEffect, useRef, useState, type CSSProperties, type InputHTMLAttributes, type KeyboardEvent, type PointerEvent } from "react"; import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type InputHTMLAttributes, type KeyboardEvent, type PointerEvent } from "react";
import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBand.js";
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import { Dropdown } from "./Dropdown.js"; import { Dropdown } from "./Dropdown.js";
export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> { export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> {
label: string; label: string;
orientation?: "horizontal" | "vertical";
value: number; value: number;
min: number; min: number;
max: number; max: number;
exactValueBounds?: {
min?: number;
max?: number;
};
formatValue?: (value: number) => string; formatValue?: (value: number) => string;
/** Unit-free retained lower bound and moving upper/value boundary. */
formatLimit?: (value: number) => string;
/** Physical side for vertical endpoint labels; use the inward side of a scene rail. */
limitSide?: "left" | "right";
onChange: (value: number) => void; onChange: (value: number) => void;
} }
@@ -29,38 +40,56 @@ const normalizeEditedRangeValue = (
min: number, min: number,
max: number, max: number,
step: RangeControlProps["step"], step: RangeControlProps["step"],
exactValueBounds: RangeControlProps["exactValueBounds"],
) => { ) => {
const clamped = clampRangeValue(value, min, max); const exactMin = exactValueBounds?.min ?? Number.NEGATIVE_INFINITY;
const exactMax = exactValueBounds?.max ?? Number.POSITIVE_INFINITY;
const clamped = clampRangeValue(value, exactMin, exactMax);
if (step === "any") return clamped; if (step === "any") return clamped;
const numericStep = step === undefined ? 1 : Number(step); const numericStep = step === undefined ? 1 : Number(step);
if (!Number.isFinite(numericStep) || numericStep <= 0) return clamped; if (!Number.isFinite(numericStep) || numericStep <= 0) return clamped;
const precision = Math.min(12, Math.max(decimalPlaces(min), decimalPlaces(numericStep))); const precision = Math.min(12, Math.max(decimalPlaces(min), decimalPlaces(numericStep)));
const aligned = min + Math.round((clamped - min) / numericStep) * numericStep; const aligned = min + Math.round((clamped - min) / numericStep) * numericStep;
return clampRangeValue(Number(aligned.toFixed(precision)), min, max); return clampRangeValue(Number(aligned.toFixed(precision)), exactMin, exactMax);
}; };
const editableNumber = (value: number) => ( const editableNumber = (value: number) => (
Number.isInteger(value) ? String(value) : String(Number(value.toFixed(12))) Number.isInteger(value) ? String(value) : String(Number(value.toFixed(12)))
); );
export function RangeControl({ function isBand(props: RangeControlProps | RangeBandControlProps): props is RangeBandControlProps {
return Array.isArray(props.value);
}
export function RangeControl(props: RangeControlProps): ReturnType<typeof SingleRangeControl>;
export function RangeControl(props: RangeBandControlProps): ReturnType<typeof VerticalRangeBand>;
export function RangeControl(props: RangeControlProps | RangeBandControlProps) {
return isBand(props) ? <VerticalRangeBand {...props} /> : <SingleRangeControl {...props} />;
}
function SingleRangeControl({
label, label,
orientation = "horizontal",
value, value,
min, min,
max, max,
exactValueBounds,
step, step,
formatValue = String, formatValue = String,
formatLimit = String,
limitSide = "right",
onChange, onChange,
className, className,
disabled = false, disabled = false,
tabIndex, tabIndex,
...props ...props
}: RangeControlProps) { }: RangeControlProps) {
const rootRef = useRef<HTMLDivElement>(null);
const rangeRef = useRef<HTMLInputElement>(null); const rangeRef = useRef<HTMLInputElement>(null);
const editorRef = useRef<HTMLInputElement>(null); const editorRef = useRef<HTMLInputElement>(null);
const cancelNextBlurRef = useRef(false); const cancelNextBlurRef = useRef(false);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(() => editableNumber(value)); const [draft, setDraft] = useState(() => editableNumber(value));
const [editorContrast, setEditorContrast] = useState<"base" | "fill">("base");
const safeMax = max === min ? min + 1 : max; const safeMax = max === min ? min + 1 : max;
const progress = Math.max(0, Math.min(100, ((value - min) / (safeMax - min)) * 100)); const progress = Math.max(0, Math.min(100, ((value - min) / (safeMax - min)) * 100));
const displayValue = formatValue(value); const displayValue = formatValue(value);
@@ -77,10 +106,30 @@ export function RangeControl({
if (!editing) setDraft(editableNumber(value)); if (!editing) setDraft(editableNumber(value));
}, [editing, value]); }, [editing, value]);
useLayoutEffect(() => {
const root = rootRef.current;
const editor = editorRef.current;
if (!root || !editor) return undefined;
const updateContrast = () => {
const rootBounds = root.getBoundingClientRect();
const editorBounds = editor.getBoundingClientRect();
const paddingRight = Number.parseFloat(getComputedStyle(editor).paddingRight) || 0;
const fillRight = rootBounds.left + rootBounds.width * progress / 100;
const textRight = editorBounds.right - paddingRight;
setEditorContrast(fillRight >= textRight ? "fill" : "base");
};
updateContrast();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updateContrast);
observer?.observe(root);
return () => observer?.disconnect();
}, [editorCharacters, progress]);
const finishEditing = (commit: boolean, restoreRangeFocus: boolean) => { const finishEditing = (commit: boolean, restoreRangeFocus: boolean) => {
if (commit) { if (commit) {
const parsed = Number(draft.trim().replace(",", ".")); const parsed = Number(draft.trim().replace(",", "."));
if (Number.isFinite(parsed)) onChange(normalizeEditedRangeValue(parsed, min, max, step)); if (Number.isFinite(parsed)) {
onChange(normalizeEditedRangeValue(parsed, min, max, step, exactValueBounds));
}
} }
setEditing(false); setEditing(false);
if (restoreRangeFocus) requestAnimationFrame(() => rangeRef.current?.focus()); if (restoreRangeFocus) requestAnimationFrame(() => rangeRef.current?.focus());
@@ -102,8 +151,20 @@ export function RangeControl({
} }
}; };
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">
<input ref={rangeRef} {...props} type="range" value={value} min={min} max={safeMax} step={step}
disabled={disabled} tabIndex={tabIndex} aria-label={label} aria-orientation="vertical"
aria-valuetext={displayValue} onChange={(event) => onChange(Number(event.target.value))} />
</div>
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(clampRangeValue(value, min, safeMax))}</span>
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--min">{formatLimit(min)}</span>
</div>
);
return ( return (
<div className={cn("nodedc-range", className)} style={style} data-editing={editing || undefined}> <div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-editing={editing || undefined}>
<input <input
ref={rangeRef} ref={rangeRef}
{...props} {...props}
@@ -129,22 +190,14 @@ export function RangeControl({
className="nodedc-range__editor" className="nodedc-range__editor"
type="text" type="text"
inputMode="decimal" inputMode="decimal"
value={editing ? draft : editableNumber(value)} value={draft}
aria-label={`${label}: точное значение`} aria-label={`${label}: точное значение`}
disabled={disabled} disabled={disabled}
spellCheck={false} spellCheck={false}
data-active={editing || undefined} data-active={editing || undefined}
onPointerDown={() => { data-contrast={editorContrast}
if (!editing) {
setDraft(editableNumber(value));
setEditing(true);
}
}}
onFocus={() => { onFocus={() => {
if (!editing) { if (!editing) setEditing(true);
setDraft(editableNumber(value));
setEditing(true);
}
}} }}
onChange={(event) => setDraft(event.target.value)} onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleEditorKeyDown} onKeyDown={handleEditorKeyDown}
+36
View File
@@ -0,0 +1,36 @@
import type { HTMLAttributes, ReactNode } from "react";
import { ProgressBar, type ProgressBarProps } from "./ProgressBar.js";
import { cn } from "./cn.js";
export interface ResourceRowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title"> {
title: ReactNode;
icon?: ReactNode;
description?: ReactNode;
metadata?: ReactNode;
status?: ReactNode;
statusPlacement?: "leading" | "trailing";
actions?: ReactNode;
progress?: Pick<ProgressBarProps, "label" | "value" | "valueText">;
}
/** Compact resource presentation extracted from Mission Core AI Inference.
* Actions stay canonical controls; the row itself is not a nested button. */
export function ResourceRow({ title, icon, description, metadata, status, statusPlacement = "trailing", actions, progress, className, ...props }: ResourceRowProps) {
const leadingStatus = !progress && !!status && statusPlacement === "leading";
return <div className={cn("nodedc-resource-row", progress && "nodedc-resource-row--progress", leadingStatus && "nodedc-resource-row--leading-status", className)} {...props}>
{icon ? <span className="nodedc-resource-row__icon" aria-hidden="true">{icon}</span> : null}
{leadingStatus ? <div className="nodedc-resource-row__status">{status}</div> : null}
<div className="nodedc-resource-row__copy">
<strong>{title}</strong>
{description ? <span>{description}</span> : null}
{metadata ? <small>{metadata}</small> : null}
</div>
{progress ? <ProgressBar {...progress} /> : null}
{!progress && status && statusPlacement === "trailing" ? <div className="nodedc-resource-row__status">{status}</div> : null}
{actions ? <div className="nodedc-resource-row__actions">{actions}</div> : null}
</div>;
}
export function ResourceList({ className, children, ...props }: HTMLAttributes<HTMLUListElement>) {
return <ul className={cn("nodedc-resource-list", className)} {...props}>{children}</ul>;
}
+37 -31
View File
@@ -1,4 +1,4 @@
import type { ReactNode } from "react"; import { forwardRef, type ButtonHTMLAttributes, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
export interface SegmentedItem<T extends string> { export interface SegmentedItem<T extends string> {
@@ -7,40 +7,46 @@ export interface SegmentedItem<T extends string> {
icon?: ReactNode; icon?: ReactNode;
disabled?: boolean; disabled?: boolean;
} }
export type SegmentedControlSize = "default" | "dense";
export interface SegmentedControlProps<T extends string> { export type SegmentedControlProps<T extends string> = {
value: T;
items: Array<SegmentedItem<T>>; items: Array<SegmentedItem<T>>;
label: string; label: string;
size?: SegmentedControlSize;
className?: string; className?: string;
onChange: (value: T) => void; } & ({ selectionMode?: "single"; value: T; onChange: (value: T) => void }
| { selectionMode: "multiple"; value: readonly T[]; onChange: (value: T[]) => void });
export function SegmentedControl<T extends string>(props: SegmentedControlProps<T>) {
const { items, label, size = "default", className } = props;
const multiple = props.selectionMode === "multiple";
return <div className={cn("nodedc-segmented", className)}
role={multiple ? "group" : "tablist"} aria-label={label}
data-size={size === "default" ? undefined : size}>
{items.map(item => {
const active = props.selectionMode === "multiple" ? props.value.includes(item.value) : props.value === item.value;
return <button key={item.value} type="button" className="nodedc-segmented__item"
role={multiple ? undefined : "tab"} aria-selected={multiple ? undefined : active}
aria-pressed={multiple ? active : undefined} data-active={active ? "true" : undefined}
disabled={item.disabled} onClick={() => {
if (props.selectionMode === "multiple") {
props.onChange(active ? props.value.filter(value => value !== item.value) : [...props.value, item.value]);
} else props.onChange(item.value);
}}>{item.icon}{item.label}</button>;
})}
</div>;
} }
export function SegmentedControl<T extends string>({ /** Shared capsule for independently controlled toggles and menu triggers. */
value, export function SegmentedGroup({ label, size = "default", className, ...props }:
items, HTMLAttributes<HTMLDivElement> & { label: string; size?: SegmentedControlSize }) {
label, return <div {...props} className={cn("nodedc-segmented", className)} role="group" aria-label={label}
className, data-size={size === "default" ? undefined : size} />;
onChange,
}: SegmentedControlProps<T>) {
return (
<div className={cn("nodedc-segmented", className)} role="tablist" aria-label={label}>
{items.map((item) => (
<button
key={item.value}
type="button"
className="nodedc-segmented__item"
role="tab"
aria-selected={item.value === value}
data-active={item.value === value ? "true" : undefined}
disabled={item.disabled}
onClick={() => onChange(item.value)}
>
{item.icon}
{item.label}
</button>
))}
</div>
);
} }
/** Caller supplies aria-pressed for toggles or aria-expanded/haspopup for menu triggers. */
export const SegmentedButton = forwardRef<HTMLButtonElement,
ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean }
>(function SegmentedButton({ active, className, type = "button", ...props }, ref) {
return <button {...props} ref={ref} type={type} className={cn("nodedc-segmented__item", className)}
data-active={active ? "true" : undefined} />;
});
+56 -10
View File
@@ -1,6 +1,7 @@
import { useContext, useMemo, useState, type KeyboardEvent, type ReactNode } from "react"; import { useContext, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import type { FloatingPlacement } from "@nodedc/ui-core"; import type { FloatingPlacement } from "@nodedc/ui-core";
import { Dropdown } from "./Dropdown.js"; import { Dropdown } from "./Dropdown.js";
import { IconButton } from "./Button.js";
import { InspectorSelectPolicyContext } from "./InspectorContext.js"; import { InspectorSelectPolicyContext } from "./InspectorContext.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
@@ -10,9 +11,10 @@ export interface SelectOption<T extends string> {
description?: string; description?: string;
icon?: ReactNode; icon?: ReactNode;
disabled?: boolean; disabled?: boolean;
action?: { label: string; icon: ReactNode; disabled?: boolean; tone?: "neutral" | "danger"; onAction: () => void };
} }
export type SelectVariant = "integrated" | "split"; export type SelectVariant = "integrated" | "split" | "inline";
export interface SelectProps<T extends string> { export interface SelectProps<T extends string> {
value: T; value: T;
@@ -52,7 +54,11 @@ export function Select<T extends string>({
const inspectorSplitRequired = useContext(InspectorSelectPolicyContext); const inspectorSplitRequired = useContext(InspectorSelectPolicyContext);
const resolvedVariant: SelectVariant = inspectorSplitRequired ? "split" : variant; const resolvedVariant: SelectVariant = inspectorSplitRequired ? "split" : variant;
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const triggerButton = useRef<HTMLButtonElement | null>(null);
const selected = options.find((option) => option.value === value) ?? options[0]; const selected = options.find((option) => option.value === value) ?? options[0];
// Row actions are siblings, never nested interactive listbox options.
const withActions = options.some((option) => option.action);
const popupRole = withActions ? "dialog" : "listbox";
const visibleOptions = useMemo(() => { const visibleOptions = useMemo(() => {
const normalized = query.trim().toLocaleLowerCase(); const normalized = query.trim().toLocaleLowerCase();
if (!normalized) return options; if (!normalized) return options;
@@ -66,10 +72,15 @@ export function Select<T extends string>({
minWidth={minMenuWidth} minWidth={minMenuWidth}
width={menuWidth} width={menuWidth}
disabled={disabled} disabled={disabled}
surfaceRole="listbox" surfaceRole={popupRole}
surfaceClassName={cn(resolvedVariant === "split" && "nodedc-select__menu", menuClassName)} surfaceClassName={cn(resolvedVariant === "split" && "nodedc-select__menu", menuClassName)}
trigger={({ open, toggle, setAnchorRef, setTriggerRef, surfaceId }) => { trigger={({ open, toggle, setAnchorRef, setTriggerRef, surfaceId }) => {
const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
triggerButton.current = event.currentTarget;
toggle();
};
const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => { const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
triggerButton.current = event.currentTarget;
if (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ") { if (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ") {
event.preventDefault(); event.preventDefault();
if (!open) toggle(); if (!open) toggle();
@@ -88,11 +99,11 @@ export function Select<T extends string>({
type="button" type="button"
className="nodedc-select__toggle" className="nodedc-select__toggle"
aria-label={label} aria-label={label}
aria-haspopup="listbox" aria-haspopup={popupRole}
aria-controls={surfaceId} aria-controls={surfaceId}
aria-expanded={open} aria-expanded={open}
disabled={disabled} disabled={disabled}
onClick={toggle} onClick={handleClick}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
> >
<span className="nodedc-select-trigger__chevron" aria-hidden="true" /> <span className="nodedc-select-trigger__chevron" aria-hidden="true" />
@@ -102,17 +113,37 @@ export function Select<T extends string>({
); );
} }
if (resolvedVariant === "inline") {
return (
<button
ref={setTriggerRef}
type="button"
className={cn("nodedc-select-inline", triggerClassName)}
aria-label={label}
aria-haspopup={popupRole}
aria-controls={surfaceId}
aria-expanded={open}
disabled={disabled}
onClick={handleClick}
onKeyDown={handleKeyDown}
>
{selected?.icon ? <span className="nodedc-select-trigger__icon">{selected.icon}</span> : null}
<span>{selected?.label ?? "—"}</span>
</button>
);
}
return ( return (
<button <button
ref={setTriggerRef} ref={setTriggerRef}
type="button" type="button"
className={cn("nodedc-select-trigger", triggerClassName)} className={cn("nodedc-select-trigger", triggerClassName)}
aria-label={label} aria-label={label}
aria-haspopup="listbox" aria-haspopup={popupRole}
aria-controls={surfaceId} aria-controls={surfaceId}
aria-expanded={open} aria-expanded={open}
disabled={disabled} disabled={disabled}
onClick={toggle} onClick={handleClick}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
> >
{selected?.icon ? <span className="nodedc-select-trigger__icon">{selected.icon}</span> : <span className="nodedc-select-trigger__icon" aria-hidden="true" />} {selected?.icon ? <span className="nodedc-select-trigger__icon">{selected.icon}</span> : <span className="nodedc-select-trigger__icon" aria-hidden="true" />}
@@ -131,12 +162,13 @@ export function Select<T extends string>({
</label> </label>
) : null} ) : null}
{visibleOptions.map((option) => ( {visibleOptions.map((option) => (
<div key={option.value} className="nodedc-select-option-row">
<button <button
key={option.value}
type="button" type="button"
className="nodedc-dropdown-option" className="nodedc-dropdown-option"
role="option" role={withActions ? undefined : "option"}
aria-selected={option.value === value} aria-selected={withActions ? undefined : option.value === value}
aria-pressed={withActions ? option.value === value : undefined}
data-selected={option.value === value ? "true" : undefined} data-selected={option.value === value ? "true" : undefined}
disabled={option.disabled} disabled={option.disabled}
onClick={() => { onClick={() => {
@@ -153,6 +185,20 @@ export function Select<T extends string>({
</span> </span>
{option.value === value ? <span className="nodedc-dropdown-option__check" aria-hidden="true">•</span> : null} {option.value === value ? <span className="nodedc-dropdown-option__check" aria-hidden="true">•</span> : null}
</button> </button>
{option.action ? <IconButton
label={option.action.label}
data-tone={option.action.tone ?? "neutral"}
disabled={option.action.disabled}
onClick={() => {
setQuery("");
close();
// A modal must restore focus to a surviving trigger, not this
// row action which disappears when the menu closes.
triggerButton.current?.focus();
option.action?.onAction();
}}
>{option.action.icon}</IconButton> : null}
</div>
))} ))}
{visibleOptions.length === 0 ? <div className="nodedc-empty-state">{emptyLabel}</div> : null} {visibleOptions.length === 0 ? <div className="nodedc-empty-state">{emptyLabel}</div> : null}
</> </>
+6 -4
View File
@@ -1,4 +1,5 @@
import type { HTMLAttributes, ReactNode } from "react"; import type { HTMLAttributes, ReactNode } from "react";
import { Description } from "./Description.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
export interface SettingsCardProps extends Omit<HTMLAttributes<HTMLElement>, "title"> { export interface SettingsCardProps extends Omit<HTMLAttributes<HTMLElement>, "title"> {
@@ -6,20 +7,21 @@ export interface SettingsCardProps extends Omit<HTMLAttributes<HTMLElement>, "ti
title: ReactNode; title: ReactNode;
description?: ReactNode; description?: ReactNode;
actions?: ReactNode; actions?: ReactNode;
align?: "start" | "center";
} }
export function SettingsCard({ eyebrow, title, description, actions, children, className, ...props }: SettingsCardProps) { export function SettingsCard({ eyebrow, title, description, actions, children, align = "start", className, ...props }: SettingsCardProps) {
return ( return (
<section className={cn("nodedc-settings-card", className)} {...props}> <section className={cn("nodedc-settings-card", className)} data-align={align === "center" ? "center" : undefined} {...props}>
<header className="nodedc-settings-card__head"> <header className="nodedc-settings-card__head">
<div className="nodedc-settings-card__titles"> <div className="nodedc-settings-card__titles">
{eyebrow ? <span>{eyebrow}</span> : null} {eyebrow ? <span>{eyebrow}</span> : null}
<h2>{title}</h2> <h2>{title}</h2>
{description ? <p>{description}</p> : null} {description ? <Description>{description}</Description> : null}
</div> </div>
{actions ? <div className="nodedc-settings-card__actions">{actions}</div> : null} {actions ? <div className="nodedc-settings-card__actions">{actions}</div> : null}
</header> </header>
<div className="nodedc-settings-card__body">{children}</div> {align === "center" && (children === undefined || children === null || children === false) ? null : <div className="nodedc-settings-card__body">{children}</div>}
</section> </section>
); );
} }
+159
View File
@@ -0,0 +1,159 @@
import {
useRef,
useState,
type CSSProperties,
type HTMLAttributes,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
} from "react";
import { cn } from "./cn.js";
export type SplitPaneOrientation = "vertical" | "horizontal";
export interface SplitPaneProps extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
primary: ReactNode;
secondary: ReactNode;
primarySize: number;
onPrimarySizeChange: (primarySize: number) => void;
orientation?: SplitPaneOrientation;
minPrimarySize?: number;
minSecondarySize?: number;
step?: number;
resizable?: boolean;
separatorLabel: string;
separatorAppearance?: "line" | "invisible";
}
const clamp = (value: number, minimum: number, maximum: number) => (
Math.min(Math.max(value, minimum), maximum)
);
const normalizedLimits = (minPrimarySize: number, minSecondarySize: number) => {
const primary = clamp(minPrimarySize, 0, 100);
const secondary = clamp(minSecondarySize, 0, 100);
if (primary + secondary <= 100) return { minimum: primary, maximum: 100 - secondary };
const scale = 100 / (primary + secondary);
return { minimum: primary * scale, maximum: 100 - secondary * scale };
};
export function SplitPane({
primary,
secondary,
primarySize,
onPrimarySizeChange,
orientation = "vertical",
minPrimarySize = 20,
minSecondarySize = 20,
step = 2,
resizable = true,
separatorLabel,
separatorAppearance = "line",
className,
style,
...props
}: SplitPaneProps) {
const rootRef = useRef<HTMLDivElement>(null);
const activePointerIdRef = useRef<number | null>(null);
const [dragging, setDragging] = 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;
const emitPointerSize = (event: PointerEvent<HTMLElement>) => {
const root = rootRef.current;
if (!root) return;
const rect = root.getBoundingClientRect();
const available = orientation === "vertical" ? rect.width : rect.height;
if (available <= 0) return;
const offset = orientation === "vertical"
? event.clientX - rect.left
: event.clientY - rect.top;
onPrimarySizeChange(clamp(offset / available * 100, limits.minimum, limits.maximum));
};
const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
const multiplier = event.shiftKey ? 5 : 1;
const decrement = orientation === "vertical" ? "ArrowLeft" : "ArrowUp";
const increment = orientation === "vertical" ? "ArrowRight" : "ArrowDown";
let next: number | null = null;
if (event.key === decrement) next = size - keyboardIncrement * multiplier;
if (event.key === increment) next = size + keyboardIncrement * multiplier;
if (event.key === "Home") next = limits.minimum;
if (event.key === "End") next = limits.maximum;
if (next === null) return;
event.preventDefault();
onPrimarySizeChange(clamp(next, limits.minimum, limits.maximum));
};
const splitStyle = {
...style,
"--nodedc-split-pane-primary": `${size}%`,
} as CSSProperties;
return (
<div
ref={rootRef}
className={cn("nodedc-split-pane", className)}
data-orientation={orientation}
data-separator-appearance={separatorAppearance}
data-dragging={dragging ? "true" : undefined}
style={splitStyle}
{...props}
>
<div className="nodedc-split-pane__panel" data-pane="primary">
{primary}
</div>
<div className="nodedc-split-pane__panel" data-pane="secondary">
{secondary}
</div>
{resizable ? (
<div
className="nodedc-split-pane__separator"
role="separator"
tabIndex={0}
aria-label={separatorLabel}
aria-orientation={orientation}
aria-valuemin={Math.round(limits.minimum)}
aria-valuemax={Math.round(limits.maximum)}
aria-valuenow={Math.round(size)}
aria-valuetext={`${Math.round(size)}% / ${Math.round(100 - size)}%`}
onKeyDown={handleKeyDown}
onPointerDown={(event) => {
if (event.button !== 0) return;
event.currentTarget.focus();
activePointerIdRef.current = event.pointerId;
event.currentTarget.setPointerCapture(event.pointerId);
setDragging(true);
emitPointerSize(event);
event.preventDefault();
}}
onPointerMove={(event) => {
if (activePointerIdRef.current !== event.pointerId) return;
emitPointerSize(event);
event.preventDefault();
}}
onPointerUp={(event) => {
if (activePointerIdRef.current !== event.pointerId) return;
activePointerIdRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
setDragging(false);
}}
onPointerCancel={(event) => {
if (activePointerIdRef.current !== event.pointerId) return;
activePointerIdRef.current = null;
setDragging(false);
}}
onLostPointerCapture={(event) => {
if (activePointerIdRef.current !== event.pointerId) return;
activePointerIdRef.current = null;
setDragging(false);
}}
/>
) : null}
</div>
);
}
+6 -4
View File
@@ -5,13 +5,15 @@ export type StatusTone = "neutral" | "success" | "warning" | "danger" | "accent"
export interface StatusBadgeProps extends HTMLAttributes<HTMLSpanElement> { export interface StatusBadgeProps extends HTMLAttributes<HTMLSpanElement> {
tone?: StatusTone; tone?: StatusTone;
variant?: "badge" | "indicator";
/** Attention signal on the lamp only; respects reduced-motion preferences. */
pulse?: boolean;
} }
export function StatusBadge({ tone = "neutral", className, children, ...props }: StatusBadgeProps) { export function StatusBadge({ tone = "neutral", variant = "badge", pulse = false, className, children, ...props }: StatusBadgeProps) {
return ( return (
<span className={cn("nodedc-status", className)} data-tone={tone === "neutral" ? undefined : tone} {...props}> <span className={cn("nodedc-status", className)} data-tone={tone === "neutral" ? undefined : tone} data-variant={variant === "indicator" ? variant : undefined} data-pulse={pulse ? "true" : undefined} {...props}>
{children} {variant === "indicator" ? null : children}
</span> </span>
); );
} }
+23 -12
View File
@@ -1,4 +1,4 @@
import { useEffect, type HTMLAttributes } from "react"; import { useEffect, useRef, type HTMLAttributes } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import { Icon, type IconName } from "./Icon.js"; import { Icon, type IconName } from "./Icon.js";
@@ -21,6 +21,8 @@ const toastIcons: Record<ToastTone, IconName> = {
loading: "refresh", loading: "refresh",
}; };
const DEFAULT_TOAST_DURATION_MS = 10_000;
export interface ToastCardProps extends HTMLAttributes<HTMLDivElement> { export interface ToastCardProps extends HTMLAttributes<HTMLDivElement> {
item: ToastItem; item: ToastItem;
onDismiss?: (id: string) => void; onDismiss?: (id: string) => void;
@@ -48,21 +50,30 @@ export function ToastCard({ item, onDismiss, className, ...props }: ToastCardPro
); );
} }
export function ToastStack({ items, onDismiss }: { items: ToastItem[]; onDismiss: (id: string) => void }) { function TimedToastCard({ item, onDismiss }: { item: ToastItem; onDismiss: (id: string) => void }) {
useEffect(() => { const dismissRef = useRef(onDismiss);
const timers = items.flatMap((item) => {
const duration = item.durationMs === undefined ? 4200 : item.durationMs;
return typeof duration === "number" && duration > 0
? [window.setTimeout(() => onDismiss(item.id), duration)]
: [];
});
return () => timers.forEach((timer) => window.clearTimeout(timer));
}, [items, onDismiss]);
useEffect(() => {
dismissRef.current = onDismiss;
}, [onDismiss]);
useEffect(() => {
const duration = item.durationMs === undefined
? item.tone === "loading" ? null : DEFAULT_TOAST_DURATION_MS
: item.durationMs;
if (typeof duration !== "number" || duration <= 0) return undefined;
const timer = window.setTimeout(() => dismissRef.current(item.id), duration);
return () => window.clearTimeout(timer);
}, [item.durationMs, item.id, item.tone]);
return <ToastCard item={item} onDismiss={onDismiss} />;
}
export function ToastStack({ items, onDismiss }: { items: ToastItem[]; onDismiss: (id: string) => void }) {
if (typeof document === "undefined" || items.length === 0) return null; if (typeof document === "undefined" || items.length === 0) return null;
return createPortal( return createPortal(
<div className="nodedc-toast-viewport nodedc-ui-root" aria-live="polite" aria-relevant="additions removals"> <div className="nodedc-toast-viewport nodedc-ui-root" aria-live="polite" aria-relevant="additions removals">
{items.map((item) => <ToastCard key={item.id} item={item} onDismiss={onDismiss} />)} {items.map((item) => <TimedToastCard key={item.id} item={item} onDismiss={onDismiss} />)}
</div>, </div>,
document.body, document.body,
); );
+73 -20
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react"; import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { import {
calculateToolbarTargets, calculateToolbarTargets,
NODEDC_TOOLBAR_DEFAULTS, NODEDC_TOOLBAR_DEFAULTS,
@@ -6,6 +6,8 @@ import {
stepToolbarSpring, stepToolbarSpring,
type ToolbarPlacement as CoreToolbarPlacement, type ToolbarPlacement as CoreToolbarPlacement,
} from "@nodedc/ui-core"; } from "@nodedc/ui-core";
import { Dropdown, type DropdownTriggerApi } from "./Dropdown.js";
import { useToolbarMenus } from "./useToolbarMenus.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import { Icon, type IconName } from "./Icon.js"; import { Icon, type IconName } from "./Icon.js";
@@ -17,6 +19,8 @@ export interface ToolbarItem<T extends string = string> {
icon: IconName; icon: IconName;
active?: boolean; active?: boolean;
disabled?: boolean; disabled?: boolean;
shortcut?: string;
menu?: ReactNode | ((close: () => void) => ReactNode);
onSelect: (id: T) => void; onSelect: (id: T) => void;
} }
@@ -31,8 +35,12 @@ export interface ToolbarProps<T extends string = string> {
maxSize?: number; maxSize?: number;
lensCount?: number; lensCount?: number;
autoHide?: boolean; autoHide?: boolean;
hideDelay?: number;
gap?: number;
label?: string; label?: string;
className?: string; className?: string;
/** Render inside a positioned viewport; edge reveal follows that viewport. */
container?: HTMLElement;
} }
interface ToolbarMotion { interface ToolbarMotion {
@@ -55,9 +63,13 @@ export function Toolbar<T extends string = string>({
maxSize = NODEDC_TOOLBAR_DEFAULTS.maxSize, maxSize = NODEDC_TOOLBAR_DEFAULTS.maxSize,
lensCount = NODEDC_TOOLBAR_DEFAULTS.lensCount, lensCount = NODEDC_TOOLBAR_DEFAULTS.lensCount,
autoHide = false, autoHide = false,
hideDelay = NODEDC_TOOLBAR_DEFAULTS.hideDelay,
gap = NODEDC_TOOLBAR_DEFAULTS.gap,
label = "Панель инструментов", label = "Панель инструментов",
className, className,
container,
}: ToolbarProps<T>) { }: ToolbarProps<T>) {
const menus = useToolbarMenus();
const [visible, setVisible] = useState(!autoHide); const [visible, setVisible] = useState(!autoHide);
const [dockActive, setDockActive] = useState(false); const [dockActive, setDockActive] = useState(false);
const toolbarRef = useRef<HTMLDivElement | null>(null); const toolbarRef = useRef<HTMLDivElement | null>(null);
@@ -68,16 +80,19 @@ export function Toolbar<T extends string = string>({
const frameLastTsRef = useRef(0); const frameLastTsRef = useRef(0);
const hideTimerRef = useRef<number | null>(null); const hideTimerRef = useRef<number | null>(null);
const hoverDockRef = useRef(false); const hoverDockRef = useRef(false);
const openMenusRef = useRef(new Set<string>());
const vertical = placement !== "bottom"; const vertical = placement === "left" || placement === "right";
const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount }); const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount, gap });
const safeMin = normalized.minSize; const safeMin = normalized.minSize;
const safeMax = normalized.maxSize; const safeMax = normalized.maxSize;
const safeLens = normalized.lensCount; const safeLens = normalized.lensCount;
const safeGap = Math.min(24,normalized.gap);
const safeDelay = Math.max(0,Math.min(15000,Number.isFinite(hideDelay)?hideDelay:NODEDC_TOOLBAR_DEFAULTS.hideDelay));
const radius = Math.max(7, Math.round(safeMin * 0.28)); const radius = Math.max(7, Math.round(safeMin * 0.28));
const glyphSize = Math.max(12, Math.min(18, Math.round(safeMin * 0.62))); const glyphSize = Math.max(12, Math.min(18, Math.round(safeMin * 0.62)));
const settingsRef = useRef({ minSize: safeMin, maxSize: safeMax, lensCount: safeLens, vertical }); const settingsRef = useRef({ minSize: safeMin, maxSize: safeMax, lensCount: safeLens, gap:safeGap, vertical });
settingsRef.current = { minSize: safeMin, maxSize: safeMax, lensCount: safeLens, vertical }; settingsRef.current = { minSize: safeMin, maxSize: safeMax, lensCount: safeLens, gap:safeGap, vertical };
actionKeysRef.current = items.map((item) => String(item.id)); actionKeysRef.current = items.map((item) => String(item.id));
const getMotion = useCallback((key: string) => { const getMotion = useCallback((key: string) => {
@@ -176,7 +191,7 @@ export function Toolbar<T extends string = string>({
const toolbar = toolbarRef.current; const toolbar = toolbarRef.current;
const keys = actionKeysRef.current; const keys = actionKeysRef.current;
if (!toolbar || !keys.length) return; if (!toolbar || !keys.length) return;
const { minSize: currentMin, maxSize: currentMax, lensCount: currentLens, vertical: isVertical } = settingsRef.current; const { minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap:currentGap, vertical: isVertical } = settingsRef.current;
const toolbarRect = toolbar.getBoundingClientRect(); const toolbarRect = toolbar.getBoundingClientRect();
const entries = keys const entries = keys
.map((key) => { .map((key) => {
@@ -193,7 +208,7 @@ export function Toolbar<T extends string = string>({
const targets = calculateToolbarTargets( const targets = calculateToolbarTargets(
entries.map((entry) => entry.center), entries.map((entry) => entry.center),
pointerCoordinate, pointerCoordinate,
{ minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: NODEDC_TOOLBAR_DEFAULTS.gap }, { minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: currentGap },
); );
entries.forEach(({ key }, index) => { entries.forEach(({ key }, index) => {
const target = targets[index]; const target = targets[index];
@@ -213,18 +228,19 @@ export function Toolbar<T extends string = string>({
if (!autoHide || hideTimerRef.current != null) return; if (!autoHide || hideTimerRef.current != null) return;
hideTimerRef.current = window.setTimeout(() => { hideTimerRef.current = window.setTimeout(() => {
hideTimerRef.current = null; hideTimerRef.current = null;
if (hoverDockRef.current) return; if (hoverDockRef.current || openMenusRef.current.size || toolbarRef.current?.contains(document.activeElement)) return;
setVisible(false); setVisible(false);
resetMagnification(); resetMagnification();
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay); }, safeDelay);
}, [autoHide, resetMagnification]); }, [autoHide, resetMagnification, safeDelay]);
useEffect(() => { useEffect(() => {
if (hideTimerRef.current != null) { window.clearTimeout(hideTimerRef.current); hideTimerRef.current = null; }
if (!autoHide) { if (!autoHide) {
setVisible(true); setVisible(true);
return; return;
} }
setVisible(false); setVisible(hoverDockRef.current || openMenusRef.current.size > 0);
setDockActive(false); setDockActive(false);
}, [autoHide]); }, [autoHide]);
@@ -236,17 +252,19 @@ export function Toolbar<T extends string = string>({
if (!autoHide) return; if (!autoHide) return;
const handlePointerMove = (event: PointerEvent) => { const handlePointerMove = (event: PointerEvent) => {
const threshold = Math.max(32, settingsRef.current.maxSize * 0.75); const threshold = Math.max(32, settingsRef.current.maxSize * 0.75);
const nearEdge = placement === "left" const bounds = container?.getBoundingClientRect() ?? {left:0, top:0, right:window.innerWidth, bottom:window.innerHeight};
? event.clientX <= threshold const inside = event.clientX >= bounds.left && event.clientX <= bounds.right && event.clientY >= bounds.top && event.clientY <= bounds.bottom;
const nearEdge = inside && (placement === "left"
? event.clientX <= bounds.left + threshold
: placement === "right" : placement === "right"
? event.clientX >= window.innerWidth - threshold ? event.clientX >= bounds.right - threshold
: event.clientY >= window.innerHeight - threshold; : placement === "top" ? event.clientY <= bounds.top + threshold : event.clientY >= bounds.bottom - threshold);
if (nearEdge) showDock(); if (nearEdge) showDock();
else if (!hoverDockRef.current) scheduleHide(); else if (!hoverDockRef.current) scheduleHide();
}; };
window.addEventListener("pointermove", handlePointerMove, { passive: true }); window.addEventListener("pointermove", handlePointerMove, { passive: true });
return () => window.removeEventListener("pointermove", handlePointerMove); return () => window.removeEventListener("pointermove", handlePointerMove);
}, [autoHide, placement, scheduleHide, showDock]); }, [autoHide, placement, container, scheduleHide, showDock]);
useEffect(() => { useEffect(() => {
const handlePointerMove = (event: PointerEvent) => { const handlePointerMove = (event: PointerEvent) => {
@@ -271,6 +289,11 @@ export function Toolbar<T extends string = string>({
if (hideTimerRef.current != null) window.clearTimeout(hideTimerRef.current); if (hideTimerRef.current != null) window.clearTimeout(hideTimerRef.current);
}, []); }, []);
useEffect(()=>{
const keys=new Set(items.map(i=>String(i.id)));
for(const key of openMenusRef.current)if(!keys.has(key)){openMenusRef.current.delete(key);delete menus.apis.current[key];if(menus.active.current===key)menus.active.current=null;}
},[items,menus]);
const style = { const style = {
"--nodedc-toolbar-bg": background, "--nodedc-toolbar-bg": background,
"--nodedc-toolbar-border": border, "--nodedc-toolbar-border": border,
@@ -279,7 +302,7 @@ export function Toolbar<T extends string = string>({
"--nodedc-toolbar-min-size": `${safeMin}px`, "--nodedc-toolbar-min-size": `${safeMin}px`,
"--nodedc-toolbar-max-size": `${safeMax}px`, "--nodedc-toolbar-max-size": `${safeMax}px`,
"--nodedc-toolbar-radius": `${radius}px`, "--nodedc-toolbar-radius": `${radius}px`,
"--nodedc-toolbar-gap": `${NODEDC_TOOLBAR_DEFAULTS.gap}px`, "--nodedc-toolbar-gap": `${safeGap}px`,
"--nodedc-toolbar-padding": `${NODEDC_TOOLBAR_DEFAULTS.padding}px`, "--nodedc-toolbar-padding": `${NODEDC_TOOLBAR_DEFAULTS.padding}px`,
} as CSSProperties; } as CSSProperties;
@@ -287,6 +310,7 @@ export function Toolbar<T extends string = string>({
<div <div
className={cn("nodedc-toolbar-wrap", className)} className={cn("nodedc-toolbar-wrap", className)}
data-placement={placement} data-placement={placement}
data-scope={container ? "viewport" : "window"}
data-visible={visible ? "true" : undefined} data-visible={visible ? "true" : undefined}
data-active={dockActive ? "true" : undefined} data-active={dockActive ? "true" : undefined}
data-autohide={autoHide ? "true" : undefined} data-autohide={autoHide ? "true" : undefined}
@@ -324,17 +348,23 @@ export function Toolbar<T extends string = string>({
> >
{items.map((item) => { {items.map((item) => {
const key = String(item.id); const key = String(item.id);
const button = (api?: DropdownTriggerApi) => {
if(api)menus.apis.current[key]=api;
return ( return (
<button <button
key={item.id} key={item.id}
ref={(element) => { buttonRefs.current[key] = element; }} ref={(element) => { buttonRefs.current[key] = element; api?.setTriggerRef(element); }}
type="button" type="button"
className="nodedc-toolbar__button" className="nodedc-toolbar__button"
data-toolbar-menu={item.menu ? key : undefined}
data-active={item.active ? "true" : undefined} data-active={item.active ? "true" : undefined}
aria-label={item.label} aria-label={item.label}
title={item.shortcut ? `${item.label} · ${item.shortcut}` : item.label}
aria-keyshortcuts={item.shortcut}
aria-pressed={item.active} aria-pressed={item.active}
disabled={item.disabled} disabled={item.disabled}
onFocus={(event) => { onFocus={(event) => {
showDock();
const button = event.currentTarget; const button = event.currentTarget;
const toolbarRect = toolbarRef.current?.getBoundingClientRect(); const toolbarRect = toolbarRef.current?.getBoundingClientRect();
if (!toolbarRect) return; if (!toolbarRect) return;
@@ -345,11 +375,34 @@ export function Toolbar<T extends string = string>({
updateMagnification(coordinate); updateMagnification(coordinate);
}} }}
onBlur={resetMagnification} onBlur={resetMagnification}
onClick={() => item.onSelect(item.id)} aria-haspopup={item.menu ? "menu" : undefined}
aria-expanded={item.menu ? api?.open : undefined}
onClick={() => item.menu ? api?.toggle() : item.onSelect(item.id)}
> >
<Icon name={item.icon} size={glyphSize} /> <Icon name={item.icon} size={glyphSize} />
</button> </button>
); );};
return item.menu ? <Dropdown key={key} placement={placement === "right" ? "left-start" : placement === "left" ? "right-start" : placement === "bottom" ? "top-end" : "bottom-end"} flip={false} getAnchorRect={()=>{
const button=buttonRefs.current[key], toolbar=toolbarRef.current;
if(!button||!toolbar)return null;
const b=button.getBoundingClientRect(), t=toolbar.getBoundingClientRect();
// Reserve the largest possible icon, including while its spring is still moving.
const pad=Math.max(safeMax,...Object.values(buttonRefs.current).map(n=>n?.getBoundingClientRect().width??0));
if(placement==="right")return {...b.toJSON(),left:t.right-pad,right:t.right,width:pad};
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=>{
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"]')){
event.preventDefault();event.stopPropagation();
}
}} onOpenChange={open => {
if(open){openMenusRef.current.add(key);menus.active.current=key;showDock();}else{openMenusRef.current.delete(key);if(menus.active.current===key)menus.active.current=null;scheduleHide();}
}}>
{({close}) => typeof item.menu === "function" ? item.menu(close) : item.menu}
</Dropdown> : button();
})} })}
</div> </div>
</div> </div>
@@ -0,0 +1,67 @@
import { useRef, type CSSProperties, type PointerEvent } from "react";
import type { RangeControlProps } from "./RangeControl.js";
import { cn } from "./cn.js";
import { moveRangeBoundary, nearestRangeBoundary, normalizeRangeBand } from "./rangeBand.js";
export interface RangeBandControlProps extends Omit<RangeControlProps, "value" | "onChange" | "orientation" | "exactValueBounds"> {
orientation: "vertical";
value: readonly [number, number];
onChange: (value: [number, number]) => void;
lowerLabel?: string;
upperLabel?: string;
}
/** Two native keyboard targets, with one pointer track selecting its nearest boundary. */
export function VerticalRangeBand({ label, value, min, max, step = 1, onChange,
lowerLabel = `${label}: нижняя граница`, upperLabel = `${label}: верхняя граница`,
formatValue = String, formatLimit = String, limitSide = "right", disabled = false,
className, style, orientation: _orientation, ...props }: RangeBandControlProps) {
const safeMax = max > min ? max : min + 1;
const band = normalizeRangeBand(value, min, safeMax);
const current = useRef(band); current.current = band;
const inputs = useRef<(HTMLInputElement | null)[]>([]);
const drag = useRef<{ id: number; boundary: 0 | 1 } | null>(null);
const progress = band.map(n => (n - min) / (safeMax - min) * 100);
const variables = { ...style, "--nodedc-range-lower": `${progress[0]}%`,
"--nodedc-range-upper": `${progress[1]}%` } as CSSProperties;
const change = (boundary: 0 | 1, next: number) => {
const result = moveRangeBoundary(current.current, boundary, next, min, safeMax, step);
current.current = result; onChange(result);
};
const position = (event: PointerEvent<HTMLDivElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
return min + Math.max(0, Math.min(1, (rect.bottom - event.clientY) / rect.height)) * (safeMax - min);
};
const end = (event: PointerEvent<HTMLDivElement>) => {
if (drag.current?.id !== event.pointerId) return;
drag.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
};
return <div className="nodedc-range-scale" data-band="true" data-limit-side={limitSide} data-disabled={disabled || undefined} style={variables}>
<div className={cn("nodedc-range", className)} data-orientation="vertical">
<div className="nodedc-range-band__target"
onPointerDown={event => {
if (disabled || event.button !== 0 || drag.current) return;
event.preventDefault(); event.stopPropagation();
const next = position(event), boundary = nearestRangeBoundary(current.current, next);
drag.current = { id: event.pointerId, boundary };
inputs.current[boundary]?.focus({ preventScroll: true });
event.currentTarget.setPointerCapture(event.pointerId); change(boundary, next);
}}
onPointerMove={event => {
if (disabled || drag.current?.id !== event.pointerId) return;
event.preventDefault(); event.stopPropagation(); change(drag.current.boundary, position(event));
}} onPointerUp={end} onPointerCancel={end} onLostPointerCapture={() => { drag.current = null; }}>
{([0, 1] as const).map(boundary => <input {...props} key={boundary}
ref={node => { inputs.current[boundary] = node; }} type="range" data-boundary={boundary === 0 ? "lower" : "upper"}
min={min} max={safeMax} step={step} value={band[boundary]} disabled={disabled}
aria-label={boundary === 0 ? lowerLabel : upperLabel} aria-orientation="vertical"
aria-valuemin={boundary === 0 ? min : band[0]} aria-valuemax={boundary === 0 ? band[1] : safeMax}
aria-valuetext={formatValue(band[boundary])}
onChange={event => change(boundary, Number(event.target.value))} />)}
</div>
</div>
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(band[1])}</span>
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--min">{formatLimit(band[0])}</span>
</div>;
}
+10 -3
View File
@@ -9,6 +9,7 @@ import {
} from "react"; } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { InspectorSelectPolicyContext } from "./InspectorContext.js"; import { InspectorSelectPolicyContext } from "./InspectorContext.js";
import { LoadingContext } from "./LoadingContext.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import { Icon } from "./Icon.js"; import { Icon } from "./Icon.js";
@@ -30,6 +31,8 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
subtitle?: ReactNode; subtitle?: ReactNode;
children: ReactNode; children: ReactNode;
footer?: ReactNode; footer?: ReactNode;
/** Context actions beside close, using canonical IconButton controls. */
headerActions?: ReactNode;
size?: WindowSize; size?: WindowSize;
placement?: WindowPlacement; placement?: WindowPlacement;
closeLabel?: string; closeLabel?: string;
@@ -47,6 +50,7 @@ export function Window({
subtitle, subtitle,
children, children,
footer, footer,
headerActions,
size = "md", size = "md",
placement = "center", placement = "center",
closeLabel = "Закрыть", closeLabel = "Закрыть",
@@ -151,7 +155,7 @@ export function Window({
}; };
return createPortal( return createPortal(
<InspectorSelectPolicyContext.Provider value={false}> <LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} onPointerDown={handleBackdropPointerDown}> <div className="nodedc-overlay nodedc-ui-root" data-placement={placement} onPointerDown={handleBackdropPointerDown}>
<div <div
ref={dialogRef} ref={dialogRef}
@@ -182,16 +186,19 @@ export function Window({
<h2 id={titleId} className="nodedc-window__title">{title}</h2> <h2 id={titleId} className="nodedc-window__title">{title}</h2>
{subtitle ? <p id={descriptionId} className="nodedc-window__subtitle">{subtitle}</p> : null} {subtitle ? <p id={descriptionId} className="nodedc-window__subtitle">{subtitle}</p> : null}
</div> </div>
<div className="nodedc-window__actions">
{headerActions}
<button type="button" className="nodedc-window__close" aria-label={closeLabel} onClick={onClose}> <button type="button" className="nodedc-window__close" aria-label={closeLabel} onClick={onClose}>
<Icon name="close" size={16} strokeWidth={1.6} /> <Icon name="close" size={16} strokeWidth={1.6} />
</button> </button>
</div>
</header> </header>
<div className="nodedc-window__body">{children}</div> <div className="nodedc-window__body">{children}</div>
{footer ? <footer className="nodedc-window__footer">{footer}</footer> : null} {footer ? <footer className="nodedc-window__footer">{footer}</footer> : null}
</div> </div>
</div> </div>
</InspectorSelectPolicyContext.Provider>, </InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
document.body, document.fullscreenElement ?? document.body,
); );
} }
@@ -35,6 +35,7 @@ export interface WorkspaceWindowProps extends Omit<HTMLAttributes<HTMLDivElement
minWidth?: number; minWidth?: number;
minHeight?: number; minHeight?: number;
resizable?: boolean; resizable?: boolean;
resizeIndicator?: boolean;
autoHeight?: boolean; autoHeight?: boolean;
active?: boolean; active?: boolean;
zIndex?: number; zIndex?: number;
@@ -124,6 +125,7 @@ export function WorkspaceWindow({
minWidth = 260, minWidth = 260,
minHeight = 180, minHeight = 180,
resizable = true, resizable = true,
resizeIndicator = true,
autoHeight = false, autoHeight = false,
active = false, active = false,
zIndex, zIndex,
@@ -377,6 +379,7 @@ export function WorkspaceWindow({
data-active={active ? "true" : undefined} data-active={active ? "true" : undefined}
data-maximized={maximized ? "true" : undefined} data-maximized={maximized ? "true" : undefined}
data-resizable={resizable ? "true" : undefined} data-resizable={resizable ? "true" : undefined}
data-resize-indicator={resizeIndicator ? undefined : "hidden"}
data-auto-height={autoHeight ? "true" : undefined} data-auto-height={autoHeight ? "true" : undefined}
data-interaction={interactionKind ?? undefined} data-interaction={interactionKind ?? undefined}
role="dialog" role="dialog"
+19
View File
@@ -1,27 +1,46 @@
export * from "./AppHeader.js"; export * from "./AppHeader.js";
export * from "./ActivityIndicator.js";
export * from "./LoadingRegion.js";
export * from "./Description.js";
export * from "./ComparisonTable.js";
export * from "./AdminNavigationPanel.js"; export * from "./AdminNavigationPanel.js";
export * from "./ApplicationShell.js"; export * from "./ApplicationShell.js";
export * from "./ApplicationSidePanel.js"; export * from "./ApplicationSidePanel.js";
export * from "./ApplicationWorkspace.js"; export * from "./ApplicationWorkspace.js";
export * from "./Button.js"; export * from "./Button.js";
export * from "./ProgressButton.js";
export * from "./Checker.js"; export * from "./Checker.js";
export * from "./ConfirmationModal.js"; export * from "./ConfirmationModal.js";
export * from "./Dropdown.js"; export * from "./Dropdown.js";
export * from "./DragDrop.js"; export * from "./DragDrop.js";
export * from "./DockLayout.js";
export {decodeDockTree, dockIds, balancedDockTree, reconcileDockTree, pruneDockTree, moveDockPanel, resizeDockSplit, dockRects, dockPosition, type DockTree, type DockMove, type DockRect, type DockPosition} from "@nodedc/ui-core";
export * from "./Field.js"; export * from "./Field.js";
export * from "./FeatureSettingsWindow.js"; export * from "./FeatureSettingsWindow.js";
export * from "./Glass.js"; export * from "./Glass.js";
export * from "./Inspector.js"; export * from "./Inspector.js";
export * from "./Icon.js"; export * from "./Icon.js";
export * from "./NavigationCube.js";
export * from "./MediaSourceField.js"; export * from "./MediaSourceField.js";
export * from "./RangeControl.js"; export * from "./RangeControl.js";
export * from "./ResourceRow.js";
export * from "./SegmentedControl.js"; export * from "./SegmentedControl.js";
export * from "./Select.js"; export * from "./Select.js";
export * from "./StatusBadge.js"; export * from "./StatusBadge.js";
export * from "./Settings.js"; export * from "./Settings.js";
export * from "./SharingModals.js"; export * from "./SharingModals.js";
export * from "./SplitPane.js";
export * from "./Toolbar.js"; export * from "./Toolbar.js";
export * from "./Toast.js"; export * from "./Toast.js";
export * from "./UserProfileMenu.js"; export * from "./UserProfileMenu.js";
export * from "./Window.js"; export * from "./Window.js";
export * from "./WorkspaceWindow.js"; export * from "./WorkspaceWindow.js";
export { ProgressBar, type ProgressBarProps } from "./ProgressBar.js";
export * from "./EnvironmentSettingsWindow.js";
export * from "./EnvironmentMediaPlaylistEditor.js";
export * from "./EnvironmentBackgroundMedia.js";
export * from "./LandingStage.js";
export {KeyButton, type KeyButtonProps} from './KeyButton.js';
export type {DockMinimum, DockMinimums} from "@nodedc/ui-core";
+24
View File
@@ -0,0 +1,24 @@
export type RangeBand = readonly [number, number];
const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n));
export function normalizeRangeBand(value: RangeBand, min: number, max: number): [number, number] {
const low = clamp(value[0], min, max);
return [low, clamp(value[1], low, max)];
}
export function nearestRangeBoundary([low, high]: RangeBand, value: number): 0 | 1 {
// Coincident boundaries remain separable: below pulls the lower, above the upper.
return value <= (low + high) / 2 ? 0 : 1;
}
export function moveRangeBoundary(value: RangeBand, boundary: 0 | 1, next: number,
min: number, max: number, step: string | number = 1): [number, number] {
const band = normalizeRangeBand(value, min, max);
const increment = Number(step);
const bounded = clamp(next, min, max);
// Exact endpoints stay reachable even when the range is not step-aligned.
const aligned = bounded === min || bounded === max || !Number.isFinite(increment) || increment <= 0
? bounded : Number((min + Math.round((bounded - min) / increment) * increment).toPrecision(12));
band[boundary] = boundary === 0 ? clamp(aligned, min, band[1]) : clamp(aligned, band[0], max);
return band;
}
+33
View File
@@ -0,0 +1,33 @@
import {useEffect,useRef} from "react";
import {movingToMenu,type MenuPoint} from "@nodedc/ui-core";
import type {DropdownTriggerApi} from "./Dropdown.js";
export function useToolbarMenus() {
const apis=useRef<Record<string,DropdownTriggerApi>>({});
const active=useRef<string|null>(null);
useEffect(()=>{
let previous:MenuPoint|null=null, origin:MenuPoint|null=null, pending:string|null=null, timer:number|undefined;
const clear=()=>{window.clearTimeout(timer);timer=undefined;pending=null;};
const open=(key:string)=>{clear();apis.current[key]?.show();};
const move=(event:PointerEvent)=>{
const current={x:event.clientX,y:event.clientY}, old=previous;previous=current;
const key=active.current;if(!key){clear();origin=null;return;}
const api=apis.current[key], surface=document.getElementById(api?.surfaceId);
const target=event.target instanceof Element?event.target:null;
if(surface?.contains(target)){clear();origin=current;return;}
const button=target?.closest<HTMLButtonElement>('[data-toolbar-menu]');
const next=button?.dataset.toolbarMenu;
if(next===key){clear();origin=current;return;}
if(!next||!apis.current[next]||button?.disabled){clear();return;}
if(!origin)origin=old??current;
const delay=surface&&old&&movingToMenu(origin,old,current,surface.getBoundingClientRect());
if(!delay){open(next);origin=current;return;}
if(pending===next)return;
clear();pending=next;
// Bounded grace: pausing on a sibling still switches, crossing diagonally into the menu does not.
timer=window.setTimeout(()=>open(next),300);
};
document.addEventListener("pointermove",move,{passive:true});
return()=>{clear();document.removeEventListener("pointermove",move);};
},[]);
return {apis,active};
}
+904 -102
View File
File diff suppressed because it is too large Load Diff
+112 -14
View File
@@ -4,50 +4,148 @@
"package": "@nodedc/ui-react", "package": "@nodedc/ui-react",
"baseLibrary": "lucide-react", "baseLibrary": "lucide-react",
"defaultSize": 18, "defaultSize": 18,
"supportedSizes": [16, 18, 20], "supportedSizes": [
16,
18,
20
],
"strokeWidth": 1.8, "strokeWidth": 1.8,
"filledNames": [
"play",
"stop"
],
"groups": [ "groups": [
{ {
"id": "window-layer", "id": "window-layer",
"label": "Окно и слой", "label": "Окно и слой",
"referenceSources": ["launcher", "engine"], "referenceSources": [
"names": ["close", "plus", "expand", "minimize", "refresh", "panel", "apps"] "launcher",
"engine"
],
"names": [
"close",
"plus",
"expand",
"minimize",
"refresh",
"panel",
"apps",
"layers"
]
}, },
{ {
"id": "navigation", "id": "navigation",
"label": "Навигация", "label": "Навигация",
"referenceSources": ["launcher", "engine", "bim-viewer"], "referenceSources": [
"names": ["chevron-left", "chevron-right", "chevron-down", "grid", "list", "sliders", "search"] "launcher",
"engine",
"bim-viewer"
],
"names": [
"chevron-left",
"chevron-right",
"chevron-down",
"chevron-up",
"grid",
"list",
"sliders",
"search",
"orthographic",
"perspective"
]
}, },
{ {
"id": "editing", "id": "editing",
"label": "Редактирование", "label": "Редактирование",
"referenceSources": ["launcher", "seo"], "referenceSources": [
"names": ["save", "edit", "trash", "copy", "upload", "download", "external"] "launcher",
"seo"
],
"names": [
"save",
"edit",
"trash",
"copy",
"upload",
"download",
"external",
"rotate-clockwise",
"select",
"pen",
"rectangle",
"curve",
"undo",
"redo",
"add-point"
]
}, },
{ {
"id": "state-access", "id": "state-access",
"label": "Состояние и доступ", "label": "Состояние и доступ",
"referenceSources": ["launcher", "seo", "task-manager"], "referenceSources": [
"names": ["check", "alert", "activity", "lock", "key", "shield", "circle"] "launcher",
"seo",
"task-manager"
],
"names": [
"check",
"alert",
"info",
"activity",
"lock",
"key",
"shield",
"circle",
"eye",
"eye-off"
]
}, },
{ {
"id": "entities", "id": "entities",
"label": "Сущности", "label": "Сущности",
"referenceSources": ["launcher", "task-manager"], "referenceSources": [
"names": ["profile", "users", "building", "globe", "database", "network", "inbox", "mail"] "launcher",
"task-manager"
],
"names": [
"profile",
"users",
"building",
"globe",
"database",
"network",
"inbox",
"mail"
]
}, },
{ {
"id": "content", "id": "content",
"label": "Контент", "label": "Контент",
"referenceSources": ["seo", "bim-viewer", "engine"], "referenceSources": [
"names": ["image", "video", "file", "folder", "clipboard", "settings"] "seo",
"bim-viewer",
"engine"
],
"names": [
"camera",
"plan",
"play",
"stop",
"image",
"video",
"file",
"folder",
"clipboard",
"settings",
"terminal"
]
} }
], ],
"rules": [ "rules": [
"Use semantic icon names from this registry instead of importing an application-local icon by shape.", "Use semantic icon names from this registry instead of importing an application-local icon by shape.",
"Icons inherit currentColor; their button surface, active state and hit target are owned by Button, IconButton or the containing pattern.", "Icons inherit currentColor; their button surface, active state and hit target are owned by Button, IconButton or the containing pattern.",
"Do not copy the complete Font Awesome or Lucide vendor catalog into application code.", "Do not copy the complete Font Awesome or Lucide vendor catalog into application code.",
"A new icon requires a confirmed product use, a registry entry and a catalog specimen." "A new icon requires a confirmed product use, a registry entry and a catalog specimen.",
"Playback icons play and stop are filled semantic glyphs; all other canonical glyphs remain outline unless their semantic contract says otherwise."
] ]
} }
+9 -2
View File
@@ -43,7 +43,9 @@
"documentation": { "documentation": {
"architecture": "../docs/ARCHITECTURE.md", "architecture": "../docs/ARCHITECTURE.md",
"components": "../docs/COMPONENTS.md", "components": "../docs/COMPONENTS.md",
"loading": "../docs/LOADING_STATES.md",
"theming": "../docs/THEMING.md", "theming": "../docs/THEMING.md",
"operationalTypography": "../docs/OPERATIONAL_TYPOGRAPHY.md",
"windows": "../docs/WINDOWS_AND_LAYERS.md", "windows": "../docs/WINDOWS_AND_LAYERS.md",
"baseline": "../docs/SOURCE_BASELINE.md", "baseline": "../docs/SOURCE_BASELINE.md",
"governance": "../docs/GOVERNANCE.md", "governance": "../docs/GOVERNANCE.md",
@@ -53,7 +55,8 @@
"moduleFoundry": "../docs/MODULE_STUDIO.md", "moduleFoundry": "../docs/MODULE_STUDIO.md",
"mapTemplate": "../docs/MAP_TEMPLATE.md", "mapTemplate": "../docs/MAP_TEMPLATE.md",
"icons": "../docs/ICONS.md", "icons": "../docs/ICONS.md",
"consumption": "../docs/CONSUMPTION.md" "consumption": "../docs/CONSUMPTION.md",
"environmentSettings": "../docs/ENVIRONMENT_SETTINGS.md"
}, },
"applicationManifestSchema": "schemas/application-manifest-v0.1.schema.json", "applicationManifestSchema": "schemas/application-manifest-v0.1.schema.json",
"designProfileSchema": "schemas/design-profile-v0.1.schema.json", "designProfileSchema": "schemas/design-profile-v0.1.schema.json",
@@ -61,5 +64,9 @@
"mapLodPolicySchema": "schemas/map-lod-policy-v0.1.schema.json", "mapLodPolicySchema": "schemas/map-lod-policy-v0.1.schema.json",
"mapPresentationProfileRegistry": "map-presentation-profiles.json", "mapPresentationProfileRegistry": "map-presentation-profiles.json",
"mapSubjectDetailProfileRegistry": "map-subject-detail-profiles.json", "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." "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"
}
} }
@@ -92,13 +92,15 @@
"additionalProperties": false, "additionalProperties": false,
"required": ["placement", "background", "border", "outline", "minSize", "maxSize", "lensCount", "autoHide"], "required": ["placement", "background", "border", "outline", "minSize", "maxSize", "lensCount", "autoHide"],
"properties": { "properties": {
"placement": { "enum": ["left", "right", "bottom"] }, "placement": { "enum": ["left", "right", "top", "bottom"] },
"background": { "$ref": "#/$defs/hex" }, "background": { "$ref": "#/$defs/hex" },
"border": { "$ref": "#/$defs/hex" }, "border": { "$ref": "#/$defs/hex" },
"outline": { "$ref": "#/$defs/hex" }, "outline": { "$ref": "#/$defs/hex" },
"minSize": { "type": "number", "minimum": 16, "maximum": 64 }, "minSize": { "type": "number", "minimum": 16, "maximum": 64 },
"maxSize": { "type": "number", "minimum": 32, "maximum": 160 }, "maxSize": { "type": "number", "minimum": 32, "maximum": 160 },
"lensCount": { "type": "integer", "minimum": 1, "maximum": 12 }, "lensCount": { "type": "integer", "minimum": 1, "maximum": 13 },
"hideDelay": { "type": "number", "minimum": 0, "maximum": 15000 },
"gap": { "type": "number", "minimum": 0, "maximum": 24 },
"autoHide": { "type": "boolean" } "autoHide": { "type": "boolean" }
} }
}, },
@@ -0,0 +1,65 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { ActivityIndicator, Button, IconButton, LoadingRegion } from "../packages/ui-react/dist/index.js";
test("ActivityIndicator separates decorative and announced progress", () => {
const decorative = renderToStaticMarkup(createElement(ActivityIndicator, { size: "compact" }));
const announced = renderToStaticMarkup(createElement(ActivityIndicator, { label: "Подключаем устройство" }));
assert.match(decorative, /class="nodedc-activity-indicator"/);
assert.match(decorative, /data-size="compact"/);
assert.match(decorative, /aria-hidden="true"/);
assert.doesNotMatch(decorative, /role="status"/);
assert.match(announced, /role="status"/);
assert.match(announced, /aria-label="Подключаем устройство"/);
assert.doesNotMatch(announced, /aria-hidden/);
assert.doesNotMatch(announced, /data-size=/);
});
test("ActivityIndicator is registered, cataloged and motion-safe", async () => {
const [styles, registrySource, docs, catalog] = await Promise.all([
readFile(new URL("../packages/ui-core/styles.css", import.meta.url), "utf8"),
readFile(new URL("../registry/components.json", import.meta.url), "utf8"),
readFile(new URL("../docs/COMPONENTS.md", import.meta.url), "utf8"),
readFile(new URL("../apps/catalog/src/CatalogApp.tsx", import.meta.url), "utf8"),
]);
const registry = JSON.parse(registrySource);
const entry = registry.components.find((component) => component.id === "activity-indicator");
assert.deepEqual(entry?.variants, ["default", "compact"]);
assert.ok(entry?.exports.includes("ActivityIndicator"));
assert.match(styles, /\.nodedc-activity-indicator\s*\{[\s\S]*?animation: nodedc-activity-indicator-spin/);
assert.match(styles, /\.nodedc-activity-indicator\[data-size="compact"\]/);
assert.match(styles, /@media \(prefers-reduced-motion: reduce\) \{\s*\.nodedc-activity-indicator,[\s\S]*?animation: none/);
assert.match(docs, /## ActivityIndicator/);
assert.match(catalog, /<ActivityIndicator label="Загружаем данные"/);
assert.match(catalog, /<Button loading>/);
assert.match(catalog, /<LoadingRegion loading/);
});
test("pending actions preserve their name and content while disabling only the pending control", () => {
for (const [Component, props] of [[Button, {}], [IconButton, {label: "Обновить"}]]) {
const busy = renderToStaticMarkup(createElement(Component, {...props, loading: true, disabled: false}, "Обновить"));
const idle = renderToStaticMarkup(createElement(Component, props, "Обновить"));
assert.match(busy, /disabled=""/);
assert.match(busy, /aria-busy="true"/);
assert.match(busy, /Обновить/);
assert.equal((busy.match(/class="nodedc-activity-indicator"/g) || []).length, 1);
assert.doesNotMatch(idle, /nodedc-action-loading|disabled=""/);
}
});
test("content remains mounted throughout loading and the status disappears on completion", () => {
const view = createElement("video", {"data-source": "synthetic"});
const pending = renderToStaticMarkup(createElement(LoadingRegion, {loading:true, label:"Ожидаем изображение"}, view));
const ready = renderToStaticMarkup(createElement(LoadingRegion, {loading:false, label:"Ожидаем изображение"}, view));
assert.match(pending, /<video data-source="synthetic"/);
assert.match(ready, /<video data-source="synthetic"/);
assert.equal((pending.match(/role="status"/g) || []).length, 1);
assert.doesNotMatch(ready, /role="status"|nodedc-activity-indicator/);
});
+54
View File
@@ -0,0 +1,54 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { SegmentedControl, SegmentedGroup, SegmentedButton, ProgressButton, LayerStackIndicator } from '../packages/ui-react/dist/index.js';
test('multiple segments allow all/none and never drop another active layer', () => {
let value = ['gaussian'];
const items = [{value:'gaussian',label:'Gaussian'},{value:'collision',label:'Коллизии'}];
const render = () => SegmentedControl({selectionMode:'multiple',value,items,label:'Слои',onChange:next=>{value=next;}});
render().props.children[1].props.onClick();
assert.deepEqual(value,['gaussian','collision']);
render().props.children[0].props.onClick();
assert.deepEqual(value,['collision']);
render().props.children[1].props.onClick();
assert.deepEqual(value,[]);
const html=renderToStaticMarkup(render());
assert.match(html,/role="group"/);
assert.doesNotMatch(html,/role="tab|aria-selected/);
assert.equal((html.match(/aria-pressed="false"/g)||[]).length,2);
});
test('single segment consumers retain one selected tab and scalar changes', () => {
let value='3d';
const element=SegmentedControl({value,items:[{value:'3d',label:'3D'},{value:'top',label:'Top'}],label:'View',onChange:next=>{value=next;}});
assert.match(renderToStaticMarkup(element),/role="tablist"/);
element.props.children[1].props.onClick();
assert.equal(value,'top');
});
test('pending progress preserves action name, rejects reentry and exposes a separate measured progressbar', () => {
const html=renderToStaticMarkup(createElement(ProgressButton,{label:'Проанализировать',icon:createElement(LayerStackIndicator),progress:{label:'Анализ поверхности · 29 / 96',value:29/96}}));
assert.match(html,/<button[^>]*aria-label="Проанализировать"[^>]*disabled=""/);
assert.match(html,/aria-busy="true"/);
assert.match(html,/aria-valuenow="30"/);
assert.match(html,/<\/button>[\s\S]*role="progressbar"/);
assert.match(html,/Анализ поверхности/);
const unknown=renderToStaticMarkup(createElement(ProgressButton,{label:'Анализ',progress:{label:'Подготовка'}}));
assert.doesNotMatch(unknown,/aria-valuenow/);
const idle=renderToStaticMarkup(createElement(ProgressButton,{label:'Анализ'}));
assert.doesNotMatch(idle,/disabled=""|role="progressbar"/);
});
test('mixed capsule keeps toggle and menu semantics distinct', () => {
const html=renderToStaticMarkup(createElement(SegmentedGroup,{label:'Layers'},
createElement(SegmentedButton,{active:true,'aria-pressed':true},'Gaussian'),
createElement(SegmentedButton,{'aria-expanded':false,'aria-haspopup':'dialog'},'Memory')));
assert.match(html,/role="group" aria-label="Layers"/);
assert.match(html,/aria-pressed="true"[^>]*data-active="true"/);
assert.match(html,/aria-expanded="false" aria-haspopup="dialog"/);
assert.equal((html.match(/aria-pressed/g)||[]).length,1);
assert.doesNotMatch(html,/role="tab/);
});
+49
View File
@@ -0,0 +1,49 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { Button, SegmentedControl } from "../packages/ui-react/dist/index.js";
test("dense viewer controls remain a public Button and SegmentedControl contract", async () => {
const button = renderToStaticMarkup(createElement(Button, { size: "dense" }, "Source points"));
const segmented = renderToStaticMarkup(createElement(SegmentedControl, {
size: "dense",
value: "source",
items: [{ label: "Source points", value: "source" }],
label: "Viewer layer",
onChange: () => {},
}));
const [tokens, styles, registrySource, docs] = await Promise.all([
readFile(new URL("../packages/tokens/tokens.css", import.meta.url), "utf8"),
readFile(new URL("../packages/ui-core/styles.css", import.meta.url), "utf8"),
readFile(new URL("../registry/components.json", import.meta.url), "utf8"),
readFile(new URL("../docs/COMPONENTS.md", import.meta.url), "utf8"),
]);
const registry = JSON.parse(registrySource);
const buttonEntry = registry.components.find((component) => component.id === "button");
const segmentedEntry = registry.components.find((component) => component.id === "segmented-control");
assert.match(button, /data-size="dense"/);
assert.match(segmented, /data-size="dense"/);
assert.ok(buttonEntry?.sizes.includes("dense"));
assert.ok(segmentedEntry?.sizes.includes("dense"));
assert.match(tokens, /--nodedc-control-height-dense: 1\.875rem/);
assert.match(tokens, /--nodedc-font-size-dense: 0\.45rem/);
assert.match(styles, /\.nodedc-button\[data-size="dense"\]/);
assert.match(styles, /\.nodedc-segmented\[data-size="dense"\]/);
assert.match(docs, /size="dense"/);
assert.match(docs, /viewer/);
});
test("viewport controls share one scale without scaling nested controls twice", async () => {
const [tokens,styles,registrySource] = await Promise.all([
readFile(new URL("../packages/tokens/tokens.css",import.meta.url),"utf8"),
readFile(new URL("../packages/ui-core/styles.css",import.meta.url),"utf8"),
readFile(new URL("../registry/components.json",import.meta.url),"utf8"),
]);
assert.match(tokens,/--nodedc-viewport-control-scale: 0\.7/);
assert.match(styles,/zoom: var\(--nodedc-viewport-control-scale\)/);
assert.match(styles, /\.nodedc-segmented\) :is\([^}]+zoom: 1;/);
assert.ok(JSON.parse(registrySource).components.find(c=>c.id==='button').domContract.includes('nodedc-viewport-controls'));
});
+81
View File
@@ -0,0 +1,81 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {preferDockSizes,dockMinimum,constrainDockTree,balancedDockTree,decodeDockTree,dockIds,dockPosition,dockRects,moveDockPanel,pruneDockTree,reconcileDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js';
const bounds={left:0,top:0,width:1200,height:800};
const initial=balancedDockTree(['a','b','c']);
const rects=tree=>dockRects(tree,bounds);
test('three asymmetric panes: center exchanges contents without changing slots',()=>{
const before=rects(initial),next=rects(moveDockPanel(initial,{activeId:'c',overId:'a',position:'center'}));
assert.deepEqual(next.c,before.a);assert.deepEqual(next.a,before.c);assert.deepEqual(next.b,before.b);
});
test('left to top/bottom edge of right pane gives one left and two right',()=>{
for(const position of ['top','bottom']){
const next=moveDockPanel(initial,{activeId:'a',overId:'c',position}),r=rects(next);
assert.deepEqual(r.b,{left:0,top:0,width:600,height:800});
assert.deepEqual(r.a,{left:600,top:position==='top'?0:400,width:600,height:400});
assert.deepEqual(r.c,{left:600,top:position==='top'?400:0,width:600,height:400});
}
});
test('right window moves to any edge of a left pane; left/right create a middle column',()=>{
for(const position of ['left','right','top','bottom']){
const next=moveDockPanel(initial,{activeId:'c',overId:'a',position}),r=rects(next);
assert.deepEqual(r.b,{left:0,top:400,width:1200,height:400});
assert.equal(position==='left'?r.c.left<r.a.left:position==='right'?r.c.left>r.a.left:position==='top'?r.c.top<r.a.top:r.c.top>r.a.top,true);
}
});
test('every source/destination/edge for 2..12 panes retains each identity and tiles the whole area',()=>{
for(let n=2;n<=12;n++){
const ids=Array.from({length:n},(_,i)=>String(i));let tree=balancedDockTree(ids);
for(const activeId of ids)for(const overId of ids)for(const position of ['center','left','right','top','bottom']){
tree=moveDockPanel(tree,{activeId,overId,position});
assert.deepEqual([...dockIds(tree)].sort(),[...ids].sort());
const panels=Object.values(rects(tree));
assert.ok(Math.abs(panels.reduce((total,r)=>total+r.width*r.height,0)-bounds.width*bounds.height)<1e-6);
for(let i=0;i<panels.length;i++)for(let j=i+1;j<panels.length;j++){
const a=panels[i],b=panels[j],overlapX=Math.min(a.left+a.width,b.left+b.width)-Math.max(a.left,b.left),overlapY=Math.min(a.top+a.height,b.top+b.height)-Math.max(a.top,b.top);
assert.ok(overlapX<1e-8||overlapY<1e-8);
}
}
}
});
test('pointer position alone selects edge; leaving workspace or source cancels',()=>{
const r={left:400,top:100,width:800,height:600};
assert.equal(dockPosition(r,405,400),'left');assert.equal(dockPosition(r,1195,400),'right');
assert.equal(dockPosition(r,800,105),'top');assert.equal(dockPosition(r,800,695),'bottom');
assert.equal(dockPosition(r,800,400),'center');assert.equal(dockPosition(r,399,400),null);
assert.equal(moveDockPanel(initial,{activeId:'a',overId:'a',position:'left'}),initial);
assert.equal(moveDockPanel(initial,{activeId:'missing',overId:'c',position:'center'}),initial);
});
test('resize, focus, persistence and new/missing sources preserve identity',()=>{
const changed=resizeDockSplit(initial,'0',63);
assert.equal(changed.first.ratio,63);assert.equal(initial.first.ratio,50);
assert.deepEqual(decodeDockTree(JSON.parse(JSON.stringify(changed))),changed);
assert.deepEqual(pruneDockTree(changed,['c']),{id:'c'});
const restored=reconcileDockTree(pruneDockTree(changed,['a','c']),['a','b','c','d']);
assert.deepEqual(dockIds(restored).sort(),['a','b','c','d']);
assert.deepEqual(decodeDockTree({axis:'x',ratio:50,first:{id:'a'},second:{id:'a'}}),{id:'a'});
assert.equal(decodeDockTree({axis:'x',ratio:Infinity}),null);
});
test('recursive minimums protect all columns and rows after extreme resize',()=>{
const t={axis:'x',ratio:99,first:{id:'scene'},second:{axis:'y',ratio:1,first:{id:'telemetry'},second:{id:'camera'}}};
for(let n=1;n<=8;n++){
const sizes={telemetry:{width:144+88*n,height:280}},minimum=dockMinimum(t,sizes);
for(const requested of [{width:1200,height:800},{width:100,height:100}]){
const b={left:0,top:0,width:Math.max(requested.width,minimum.width),height:Math.max(requested.height,minimum.height)};
const c=constrainDockTree(t,b,sizes),r=dockRects(c,b);
assert.ok(r.telemetry.width+1e-8>=sizes.telemetry.width);assert.ok(r.telemetry.height+1e-8>=280);
assert.ok(r.scene.width+1e-8>=160);assert.ok(r.camera.height+1e-8>=120);
assert.deepEqual(constrainDockTree(c,b,sizes),c);
}
}
});
test('new compact panel uses its preferred size without changing saved ratios',()=>{
const t={axis:'x',ratio:65,first:{id:'map'},second:{axis:'y',ratio:40,first:{id:'telemetry'},second:{id:'camera'}}};
const sizes={telemetry:{width:320,height:280}};
const initial=constrainDockTree(preferDockSizes(t,bounds,sizes),bounds,sizes),r=rects(initial);
assert.ok(Math.abs(r.telemetry.width-320)<1e-8);assert.ok(Math.abs(r.telemetry.height-280)<1e-8);
assert.deepEqual(preferDockSizes(t,bounds,{}),t);
});
+44
View File
@@ -0,0 +1,44 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { appendEnvironmentMediaItem, removeEnvironmentMediaItem, cloneEnvironmentSettings } from "../packages/ui-core/dist/index.js";
import { LandingStage, Button, MediaSourceField } from "../packages/ui-react/dist/index.js";
const image = { id: "media-first", source: "url", url: "https://example.invalid/background.png", mediaKind: "image", fileName: null };
const video = { ...image, id: "media-second", url: "https://example.invalid/background.mp4", mediaKind: "video" };
const page = { headerLabel: "Product", eyebrow: "Board", title: "Home", description: "Local operator home", primaryWorkspaceId: null, secondaryWorkspaceId: null, background: { enabled: false, imageDurationSeconds: 10, items: [] } };
test("media edits preserve playback order and leave saved settings untouched", () => {
const settings = { revision: 9, pages: { home: { ...page, background: appendEnvironmentMediaItem(page.background, image) } } };
const draft = cloneEnvironmentSettings(settings);
draft.pages.home.background = appendEnvironmentMediaItem(draft.pages.home.background, video);
draft.pages.home.background.items[0].url = "https://example.invalid/edited.png";
assert.equal(settings.pages.home.background.items[0].url, image.url);
assert.deepEqual(draft.pages.home.background.items.map(item => item.id), [image.id, video.id]);
const removed = removeEnvironmentMediaItem(draft.pages.home.background, image.id);
assert.deepEqual(removed.items, [video]);
assert.equal(removeEnvironmentMediaItem(removed, video.id).enabled, false);
assert.equal(appendEnvironmentMediaItem(removed, video), removed);
});
test("shared home shows real configured media, and an empty home creates no media", () => {
const empty = renderToStaticMarkup(createElement(LandingStage, { page }));
assert.match(empty, /<h1>Home<\/h1>/);
assert.doesNotMatch(empty, /<(?:video|img)\b/);
const configured = { ...page, background: { ...page.background, enabled: true, items: [video] } };
const html = renderToStaticMarkup(createElement(LandingStage, { page: configured }));
assert.match(html, /<video[^>]+src="https:\/\/example.invalid\/background.mp4"/);
assert.match(html, /loop=""/);
assert.match(html, /muted=""/);
});
test("neutral primary retains native disabled semantics and theme default remains opt-in", () => {
const disabled = renderToStaticMarkup(createElement(Button, { variant: "primary", tone: "neutral", disabled: true }, "Start"));
assert.match(disabled, /data-tone="neutral"/);
assert.match(disabled, /disabled=""/);
const themed = renderToStaticMarkup(createElement(Button, { variant: "primary" }, "Start"));
assert.doesNotMatch(themed, /data-tone/);
const field = renderToStaticMarkup(createElement(MediaSourceField, { source: "url", url: "https://example.invalid/a.png", disabled: true, onSourceChange() {}, onUrlChange() {}, onFileChange() {} }));
assert.match(field, /<input[^>]*disabled=""/);
});
+30
View File
@@ -0,0 +1,30 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { Icon } from "../packages/ui-react/dist/index.js";
test("only registered playback glyphs are filled", async () => {
const registry = JSON.parse(await readFile(
new URL("../registry/icons.json", import.meta.url),
"utf8",
));
const names = registry.groups.flatMap((group) => group.names);
const filledNames = new Set(registry.filledNames);
assert.deepEqual([...filledNames], ["play", "stop"]);
assert.equal(new Set(names).size, names.length);
for (const name of names) {
const markup = renderToStaticMarkup(createElement(Icon, { name }));
const rootTag = markup.slice(0, markup.indexOf(">") + 1);
if (filledNames.has(name)) {
assert.match(rootTag, /fill="currentColor"/, `${name} must be filled`);
assert.match(rootTag, /stroke-width="0"/, `${name} must not retain an outline`);
} else {
assert.match(rootTag, /fill="none"/, `${name} must remain outline-only`);
assert.doesNotMatch(rootTag, /fill="currentColor"/, `${name} must not be filled`);
}
}
});
+24
View File
@@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {cubeRegions} from '../packages/ui-react/dist/NavigationCube.js';
test('cube exposes exactly 26 unique face/edge/corner directions over all sides',()=>{
const views=[[0,0,0,1],[0,1,0,0],[0,Math.SQRT1_2,0,Math.SQRT1_2],[0,-Math.SQRT1_2,0,Math.SQRT1_2],[Math.SQRT1_2,0,0,Math.SQRT1_2],[-Math.SQRT1_2,0,0,Math.SQRT1_2]];
const dirs=new Set(views.flatMap(q=>cubeRegions(q).map(r=>r.direction.join(','))));
assert.equal(dirs.size,26);assert.ok(!dirs.has('0,0,0'));
assert.deepEqual(cubeRegions([0,0,0,1]).filter(r=>r.faceLabel).map(r=>r.faceLabel),['FRONT']);
assert.deepEqual(cubeRegions([Math.SQRT1_2,0,0,Math.SQRT1_2]).filter(r=>r.faceLabel).map(r=>r.faceLabel),['BOTTOM']);
for(const q of views)for(const r of cubeRegions(q)){assert.ok(!r.polygon.includes('NaN'));assert.ok(r.label);}
});
test('labels are projected in each face plane with no mirrored front-facing text',()=>{
const q=[.28,-.36,.12,.88],regions=cubeRegions(q).filter(r=>r.faceLabel);
assert.equal(regions.length,3);
for(const r of regions){
const [a,b,c,d,e,f]=r.textMatrix;assert.ok(a*d-b*c>0);assert.ok(a*d-b*c<1);
assert.ok(r.textMatrix.every(Number.isFinite));assert.ok(Math.abs(b)+Math.abs(c)>0.05);
const points=r.polygon.split(' ').map(p=>p.split(',').map(Number));
assert.ok(Math.abs(points.reduce((n,p)=>n+p[0],0)/4-e)<1e-9);
assert.ok(Math.abs(points.reduce((n,p)=>n+p[1],0)/4-f)<1e-9);
}
assert.deepEqual(cubeRegions([0,0,0,1]).find(r=>r.faceLabel).textMatrix.map(n=>n||0),[1,0,0,1,60,60]);
});
+22
View File
@@ -0,0 +1,22 @@
import assert from "node:assert/strict";
import test from "node:test";
import {createElement} from "react";
import {renderToStaticMarkup} from "react-dom/server";
import {ProgressBar,ResourceRow} from "../packages/ui-react/dist/index.js";
test("progress exposes bounded measured values and unknown state without false percentages",()=>{
for(const [value, expected] of [[-1,0],[.5,50],[2,100]]) {
const html=renderToStaticMarkup(createElement(ProgressBar,{label:"Этапы",value}));
assert.match(html,new RegExp(`aria-valuenow="${expected}"`));
}
for(const value of [undefined,NaN,Infinity]) {
const html=renderToStaticMarkup(createElement(ProgressBar,{label:"Ожидание",value}));
assert.doesNotMatch(html,/aria-valuenow/);assert.match(html,/data-indeterminate="true"/);
}
});
test("row keeps progress between name and actions and suppresses duplicate status",()=>{
const html=renderToStaticMarkup(createElement(ResourceRow,{title:"Камера",status:"Old status",actions:"Actions",progress:{label:"Загрузка",value:.2}}));
assert.ok(html.indexOf("Камера")<html.indexOf('role="progressbar"'));
assert.ok(html.indexOf('role="progressbar"')<html.indexOf("Actions"));
assert.doesNotMatch(html,/Old status/);
});
+70 -1
View File
@@ -23,6 +23,35 @@ test("RangeControl keeps native drag semantics and exposes one persistent exact-
assert.doesNotMatch(markup, /nodedc-range__value-hit/); assert.doesNotMatch(markup, /nodedc-range__value-hit/);
}); });
test("vertical scale exposes retained bounds without center text and follows every value", () => {
for (const [value, progress] of [[-1.2, 0], [25.15, 50], [51.5, 100]]) {
for (const limitSide of ["left", "right"]) {
const markup = renderToStaticMarkup(createElement(RangeControl, {
label: "Срез", orientation: "vertical", limitSide, value, min: -1.2, max: 51.5, step: "any",
formatValue: n => `${n.toFixed(1)} м`, formatLimit: n => n.toFixed(1), onChange: () => {},
}));
const renderedProgress = Number(markup.match(/--nodedc-range-progress:([\d.]+)%/)?.[1]);
assert.ok(Math.abs(renderedProgress - progress) < 1e-9);
assert.ok(markup.includes(`data-limit-side="${limitSide}"`));
assert.ok(markup.includes(`nodedc-range-scale__limit--max">${value.toFixed(1)}</span>`));
assert.match(markup, /nodedc-range-scale__limit--min">-1.2<\/span>/);
assert.match(markup, /aria-label="Срез" aria-orientation="vertical"/);
assert.ok(markup.includes(`aria-valuetext="${value.toFixed(1)} м"`));
assert.match(markup, /min="-1.2" max="51.5" step="any"/);
assert.doesNotMatch(markup, /nodedc-range__label|nodedc-range__fill-text|nodedc-range__editor|formatLimit=/);
}
}
});
test("thin vertical rail retains a usable pointer target and boundary focus", async () => {
const styles = await readFile(new URL("../packages/ui-core/styles.css", import.meta.url), "utf8");
assert.match(styles, /width: calc\(var\(--nodedc-control-height\) \* 0\.2\)/);
assert.match(styles, /width: max\(100%, 24px\)/);
assert.match(styles, /limit--max \{ bottom: clamp\(/);
assert.match(styles, /range-scale:has\(input:focus-visible\) \.nodedc-range-scale__limit--max \{ text-decoration: underline/);
assert.match(styles, /data-orientation="vertical"\] \{[^}]*border: 0; outline: 0; box-shadow: none;/);
});
test("exact editing is a stable native caret field without remount, forced selection or a dark editor box", async () => { test("exact editing is a stable native caret field without remount, forced selection or a dark editor box", async () => {
const [component, styles, windowComponent] = await Promise.all([ const [component, styles, windowComponent] = await Promise.all([
readFile(new URL("../packages/ui-react/src/RangeControl.tsx", import.meta.url), "utf8"), readFile(new URL("../packages/ui-react/src/RangeControl.tsx", import.meta.url), "utf8"),
@@ -30,7 +59,17 @@ test("exact editing is a stable native caret field without remount, forced selec
readFile(new URL("../packages/ui-react/src/Window.tsx", import.meta.url), "utf8"), readFile(new URL("../packages/ui-react/src/Window.tsx", import.meta.url), "utf8"),
]); ]);
assert.match(component, /normalizeEditedRangeValue\(parsed, min, max, step\)/); assert.match(component, /exactValueBounds\?: \{/);
assert.match(component, /exactValueBounds\?\.min \?\? Number\.NEGATIVE_INFINITY/);
assert.match(component, /exactValueBounds\?\.max \?\? Number\.POSITIVE_INFINITY/);
assert.match(component, /normalizeEditedRangeValue\(parsed, min, max, step, exactValueBounds\)/);
assert.match(component, /value=\{draft\}/);
assert.match(component, /data-contrast=\{editorContrast\}/);
assert.match(component, /fillRight >= textRight \? "fill" : "base"/);
assert.match(component, /new ResizeObserver\(updateContrast\)/);
const editorSource = component.match(/className="nodedc-range__editor"[\s\S]*?onBlur=\{\(\) => \{[\s\S]*?\n \}\}\n \/>/)?.[0] ?? "";
assert.notEqual(editorSource, "");
assert.doesNotMatch(editorSource, /onPointerDown=/);
assert.match(component, /event\.key === "Enter"/); assert.match(component, /event\.key === "Enter"/);
assert.match(component, /event\.key === "Escape"/); assert.match(component, /event\.key === "Escape"/);
assert.match(component, /event\.stopPropagation\(\)/); assert.match(component, /event\.stopPropagation\(\)/);
@@ -43,8 +82,38 @@ test("exact editing is a stable native caret field without remount, forced selec
assert.match(styles, /\.nodedc-range input\[type="range"\][\s\S]*?z-index: 4/); assert.match(styles, /\.nodedc-range input\[type="range"\][\s\S]*?z-index: 4/);
assert.match(styles, /\.nodedc-range__editor[\s\S]*?z-index: 5[\s\S]*?background: transparent[\s\S]*?color: transparent[\s\S]*?caret-color: transparent[\s\S]*?box-shadow: none/); assert.match(styles, /\.nodedc-range__editor[\s\S]*?z-index: 5[\s\S]*?background: transparent[\s\S]*?color: transparent[\s\S]*?caret-color: transparent[\s\S]*?box-shadow: none/);
assert.match(styles, /\.nodedc-range__editor\[data-active\][\s\S]*?caret-color: currentColor/); assert.match(styles, /\.nodedc-range__editor\[data-active\][\s\S]*?caret-color: currentColor/);
assert.match(styles, /\.nodedc-range__editor\[data-active\]\[data-contrast="fill"\][\s\S]*?rgb\(var\(--nodedc-on-accent-rgb\)\)/);
assert.match(windowComponent, /const onCloseRef = useRef\(onClose\)/); assert.match(windowComponent, /const onCloseRef = useRef\(onClose\)/);
assert.match(windowComponent, /onCloseRef\.current = onClose/); assert.match(windowComponent, /onCloseRef\.current = onClose/);
assert.match(windowComponent, /onCloseRef\.current\(\)/); assert.match(windowComponent, /onCloseRef\.current\(\)/);
assert.doesNotMatch(windowComponent, /\[closeOnEscape, onClose, open, shouldLockBodyScroll, shouldTrapFocus\]/); assert.doesNotMatch(windowComponent, /\[closeOnEscape, onClose, open, shouldLockBodyScroll, shouldTrapFocus\]/);
}); });
test("vertical band exposes two independent accessible boundaries", () => {
for (const value of [[-52, 500], [10, 35], [20, 20]]) {
const markup = renderToStaticMarkup(createElement(RangeControl, {
label: "Срез", orientation: "vertical", value, min: -52, max: 500, step: "any",
formatValue: n => `${n} м`, onChange: () => {},
}));
assert.equal((markup.match(/type="range"/g) ?? []).length, 2);
assert.match(markup, /aria-label="Срез: нижняя граница"/);
assert.match(markup, /aria-label="Срез: верхняя граница"/);
assert.ok(markup.includes(`aria-valuemax="${value[1]}"`));
assert.ok(markup.includes(`aria-valuemin="${value[0]}"`));
assert.doesNotMatch(markup, /nodedc-range__label|nodedc-range__editor/);
}
});
test("both boundaries move, clamp independently, separate after coincidence and restore endpoints", async () => {
const {moveRangeBoundary: move, nearestRangeBoundary: nearest} = await import("../packages/ui-react/dist/rangeBand.js");
let band = [-52, 500];
assert.equal(nearest(band, -40), 0); assert.equal(nearest(band, 450), 1);
band = move(band, 0, 10, -52, 500, "any"); assert.deepEqual(band, [10, 500]);
band = move(band, 1, 30, -52, 500, "any"); assert.deepEqual(band, [10, 30]);
band = move(band, 0, 50, -52, 500, "any"); assert.deepEqual(band, [30, 30]);
assert.equal(nearest(band, 20), 0); assert.equal(nearest(band, 40), 1);
band = move(band, 0, -100, -52, 500, "any");
band = move(band, 1, 600, -52, 500, "any"); assert.deepEqual(band, [-52, 500]);
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]);
});
+39
View File
@@ -0,0 +1,39 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { Select } from '../packages/ui-react/dist/index.js';
test('select action menus use dialog semantics in all variants; ordinary select stays a listbox', () => {
for (const variant of ['integrated', 'split', 'inline']) {
for (const withAction of [false, true]) {
const markup = renderToStaticMarkup(createElement(Select, {
label: 'Records', variant, value: 'one', onChange: () => {},
options: [{value: 'one', label: 'One', ...(withAction ? {action: {label: 'Delete One', icon: 'x', onAction: () => {}}} : {})}],
}));
assert.match(markup, new RegExp(`aria-haspopup="${withAction ? 'dialog' : 'listbox'}"`));
}
}
});
test('row action is independent of selection, closes first and uses canonical IconButton', async () => {
const source = await readFile(new URL('../packages/ui-react/src/Select.tsx', import.meta.url), 'utf8');
assert.match(source, /<\/button>\s*\{option\.action \? <IconButton/);
assert.match(source, /disabled=\{option\.action\.disabled\}/);
assert.match(source, /close\(\);[\s\S]*triggerButton.current\?\.focus\(\);\s*option\.action\?\.onAction\(\)/);
assert.match(source, /role=\{withActions \? undefined : "option"\}/);
});
test('row action matches the compact session catalog without a circular backing', async () => {
const css = await readFile(new URL('../packages/ui-core/styles.css', import.meta.url), 'utf8');
const rule = css.match(/\.nodedc-select-option-row > \.nodedc-icon-button \{([^}]+)\}/)?.[1];
assert.match(rule, /width: 2\.35rem/);
assert.match(rule, /height: auto/);
assert.match(rule, /border-radius: 0/);
assert.match(rule, /background: transparent/);
assert.match(rule, /box-shadow: none/);
assert.match(rule, /color: var\(--nodedc-text-muted\)/);
assert.match(css, /\.nodedc-select-option-row > \.nodedc-icon-button > svg \{ width: 15px; height: 15px; transform: none/);
assert.match(css, /data-tone="danger"\]\:focus-visible \{ color: rgb\(var\(--nodedc-danger-rgb\)\)/);
});
+25
View File
@@ -0,0 +1,25 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {createElement as h} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {LoadingRegion,Description,SettingsCard,ComparisonTable} from '../packages/ui-react/dist/index.js';
test('composed loading draws exactly one owner even with multiple pending descendants',()=>{
const child=h(LoadingRegion,{loading:true,label:'child'},h('span',null,'retained'));
const markup=renderToStaticMarkup(h(LoadingRegion,{aggregate:true,loading:true,label:'equipment'},child,child,h(LoadingRegion,{aggregate:true,loading:true,label:'nested'},child)));
assert.equal((markup.match(/role="status"/g)||[]).length,1);assert.match(markup,/aria-label="equipment"/);assert.equal((markup.match(/retained/g)||[]).length,3);
});
test('independent surfaces keep their loaders and resolved content has no indicator',()=>{
const markup=renderToStaticMarkup(h('div',null,h(LoadingRegion,{loading:true,label:'a'}),h(LoadingRegion,{loading:true,label:'b'})));
assert.equal((markup.match(/role="status"/g)||[]).length,2);
assert.doesNotMatch(renderToStaticMarkup(h(LoadingRegion,{aggregate:true,loading:false,label:'done'},h(LoadingRegion,{loading:false,label:'child'},'ready'))),/role="status"/);
});
test('comparison has one label column, arbitrary entity columns and semantic headers',()=>{
for(const count of [1,2,3,4,8]){
const markup=renderToStaticMarkup(h(ComparisonTable,{label:'VESC',heading:'VESC',columns:Array.from({length:count},(_,i)=>({id:String(i),label:'id'+i})),rows:[{id:'position',label:'Расположение',cells:Array(count).fill('Левый')},{id:'current',label:'Ток',cells:[]}]}));
assert.equal((markup.match(/scope="col"/g)||[]).length,count+1);assert.equal((markup.match(/scope="row"/g)||[]).length,2);assert.equal((markup.match(/<td>/g)||[]).length,2*count);assert.match(markup,/tabindex="0"/);
}
});
test('SettingsCard and standalone explanatory paragraphs use one typography component',()=>{
assert.match(renderToStaticMarkup(h(Description,null,'help')),/class="nodedc-description"/);
assert.match(renderToStaticMarkup(h(SettingsCard,{title:'Settings',description:'help'})),/<p class="nodedc-description">help/);
});
+137
View File
@@ -0,0 +1,137 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
function lineNumber(lines, value) {
return lines.findIndex((line) => line.includes(value));
}
function assertLine(lines, value, message) {
const index = lineNumber(lines, value);
assert.ok(index >= 0, `${message} (expected near line 1+, missing: ${value})`);
return index + 1;
}
function extractBlock(lines, key) {
const start = lines.findIndex((line) => line.trim() === `${key} = """`);
assert.ok(start >= 0, `missing ${key} block start`);
let end = start + 1;
while (end < lines.length && lines[end] !== "\"\"\"") {
end += 1;
}
assert.ok(end < lines.length, `unterminated ${key} block`);
return lines.slice(start + 1, end).join("\n").replace(/\s+/g, " ").trim();
}
test("global spark agent configuration matches governance contract", async () => {
const configLines = (await readFile(new URL("../.codex/config.toml", import.meta.url), "utf8")).split(/\r?\n/);
const agentsLine = assertLine(configLines, "[agents]", "global config should declare [agents]");
const enabledLine = assertLine(configLines, 'enabled = true', "global config should enable agents");
const threadLine = assertLine(configLines, "max_concurrent_threads_per_session = 2", "global config should cap threads at 2");
const defaultModelLine = assertLine(configLines, 'default_subagent_model = "gpt-5.6-terra"', "global config should set default subagent model");
const effortLine = assertLine(configLines, 'default_subagent_reasoning_effort = "low"', "global config should set default low reasoning for unpinned subagents");
const interruptLine = assertLine(configLines, "interrupt_message = true", "global config should keep interruption messages enabled");
assert.equal(configLines[agentsLine - 1].trim(), "[agents]", "[agents] block should be present");
assert.equal(configLines[enabledLine - 1].trim(), 'enabled = true');
assert.equal(configLines[threadLine - 1].trim(), "max_concurrent_threads_per_session = 2");
assert.equal(configLines[defaultModelLine - 1].trim(), 'default_subagent_model = "gpt-5.6-terra"');
assert.equal(configLines[effortLine - 1].trim(), 'default_subagent_reasoning_effort = "low"');
assert.equal(configLines[interruptLine - 1].trim(), "interrupt_message = true");
});
test("spark_explorer contract", async () => {
const explorerLines = (await readFile(new URL("../.codex/agents/spark-explorer.toml", import.meta.url), "utf8")).split(/\r?\n/);
const instructions = extractBlock(explorerLines, "developer_instructions");
const nameLine = assertLine(explorerLines, 'name = "spark_explorer"', "explorer name should be spark_explorer");
const modelLine = assertLine(explorerLines, 'model = "gpt-5.3-codex-spark"', "explorer should pin model gpt-5.3-codex-spark");
const effortLine = assertLine(explorerLines, 'model_reasoning_effort = "medium"', "explorer should use medium reasoning");
const sandboxLine = assertLine(explorerLines, 'sandbox_mode = "read-only"', "explorer should use read-only sandbox mode");
assert.equal(explorerLines[nameLine - 1].trim(), 'name = "spark_explorer"');
assert.equal(explorerLines[modelLine - 1].trim(), 'model = "gpt-5.3-codex-spark"');
assert.equal(explorerLines[effortLine - 1].trim(), 'model_reasoning_effort = "medium"');
assert.equal(explorerLines[sandboxLine - 1].trim(), 'sandbox_mode = "read-only"');
assert.ok(
instructions.includes("Never edit, create, move, or delete files."),
"explorer instructions must prohibit edits",
);
assert.ok(
instructions.includes("Never spawn another agent."),
"explorer instructions must prohibit nested agents",
);
});
test("spark_worker contract", async () => {
const workerLines = (await readFile(new URL("../.codex/agents/spark-worker.toml", import.meta.url), "utf8")).split(/\r?\n/);
const instructions = extractBlock(workerLines, "developer_instructions");
const nameLine = assertLine(workerLines, 'name = "spark_worker"', "worker name should be spark_worker");
const modelLine = assertLine(workerLines, 'model = "gpt-5.3-codex-spark"', "worker should pin model gpt-5.3-codex-spark");
const effortLine = assertLine(workerLines, 'model_reasoning_effort = "medium"', "worker should use medium reasoning");
const sandboxLine = assertLine(workerLines, 'sandbox_mode = "workspace-write"', "worker should use workspace-write sandbox mode");
assert.equal(workerLines[nameLine - 1].trim(), 'name = "spark_worker"');
assert.equal(workerLines[modelLine - 1].trim(), 'model = "gpt-5.3-codex-spark"');
assert.equal(workerLines[effortLine - 1].trim(), 'model_reasoning_effort = "medium"');
assert.equal(workerLines[sandboxLine - 1].trim(), 'sandbox_mode = "workspace-write"');
assert.ok(
instructions.includes("exact allowed file"),
"worker instructions must require exact allowed path allowlist",
);
assert.ok(instructions.includes("Never commit, push, deploy, install dependencies, or change external systems."), "worker must not commit, push, deploy, or install");
assert.ok(instructions.includes("Never spawn another agent."), "worker must prohibit nested agents");
assert.ok(instructions.includes("One corrective retry is allowed after a failed check; then stop and return the failure evidence."), "worker must limit corrective retries");
});
test("AGENTS and governance contract documents", async () => {
const agentsLines = (await readFile(new URL("../AGENTS.md", import.meta.url), "utf8")).split(/\r?\n/);
const governanceLines = (await readFile(new URL("../docs/CODEX_SUBAGENT_GOVERNANCE.md", import.meta.url), "utf8")).split(/\r?\n/);
assert.ok(
agentsLines.some((line) => line.includes("`docs/CODEX_SUBAGENT_GOVERNANCE.md`")),
"AGENTS.md must point to governance document",
);
assert.ok(
agentsLines.some((line) => line.toLowerCase().includes("at most two subagents")),
"AGENTS.md should state max two subagents",
);
assert.ok(
agentsLines.some((line) => line.toLowerCase().includes("one write-capable")),
"AGENTS.md should state max one writer subagent",
);
assert.ok(
governanceLines.some((line) => line.includes("## Mandatory task packet")),
"governance should define mandatory task packet",
);
assert.ok(
governanceLines.some((line) => line.includes("1. Objective: one concrete outcome.")),
"governance should include mandatory objective field",
);
assert.ok(
governanceLines.some((line) => line.includes("2. Allowed scope: exact files, directories, or read-only tools.")),
"governance should include allowed scope field",
);
assert.ok(
governanceLines.some((line) => line.includes("3. Forbidden actions: especially external writes, commits, pushes, and deploys.")),
"governance should include forbidden actions field",
);
assert.ok(
governanceLines.some((line) => line.includes("4. Acceptance criteria: observable evidence of completion.")),
"governance should include acceptance criteria field",
);
assert.ok(
governanceLines.some((line) => line.includes("5. Verification: exact checks the worker may run.")),
"governance should include verification field",
);
assert.ok(
governanceLines.some((line) => line.includes("6. Output: a short structured summary, not raw logs.")),
"governance should include output field",
);
assert.ok(
governanceLines.some((line) => line.includes("Reviews the diff and performs final verification itself.")),
"governance should retain final primary review and verification ownership",
);
});
+75
View File
@@ -0,0 +1,75 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { SplitPane } from "../packages/ui-react/dist/index.js";
test("SplitPane exposes one controlled accessible separator", () => {
const markup = renderToStaticMarkup(createElement(SplitPane, {
primary: createElement("div", null, "Видео"),
secondary: createElement("div", null, "3D"),
primarySize: 64,
onPrimarySizeChange: () => {},
minPrimarySize: 25,
minSecondarySize: 30,
separatorLabel: "Изменить ширину представлений",
}));
assert.match(markup, /class="nodedc-split-pane"/);
assert.match(markup, /role="separator"/);
assert.match(markup, /aria-orientation="vertical"/);
assert.match(markup, /aria-valuemin="25"/);
assert.match(markup, /aria-valuemax="70"/);
assert.match(markup, /aria-valuenow="64"/);
assert.match(markup, /aria-valuetext="64% \/ 36%"/);
});
test("SplitPane can keep panel ownership stable without an inactive separator", () => {
const markup = renderToStaticMarkup(createElement(SplitPane, {
primary: createElement("div", null, "Видео"),
secondary: createElement("div", null, "3D"),
primarySize: 100,
onPrimarySizeChange: () => {},
separatorLabel: "Изменить ширину представлений",
resizable: false,
}));
assert.match(markup, /data-pane="primary"/);
assert.match(markup, /data-pane="secondary"/);
assert.doesNotMatch(markup, /role="separator"/);
});
test("SplitPane is registered, documented, cataloged and keyboard-addressable", async () => {
const [component, styles, registrySource, docs, catalog] = await Promise.all([
readFile(new URL("../packages/ui-react/src/SplitPane.tsx", import.meta.url), "utf8"),
readFile(new URL("../packages/ui-core/styles.css", import.meta.url), "utf8"),
readFile(new URL("../registry/components.json", import.meta.url), "utf8"),
readFile(new URL("../docs/COMPONENTS.md", import.meta.url), "utf8"),
readFile(new URL("../apps/catalog/src/CatalogApp.tsx", import.meta.url), "utf8"),
]);
const registry = JSON.parse(registrySource);
const entry = registry.components.find((item) => item.id === "split-pane");
assert.ok(entry?.exports.includes("SplitPane"));
assert.deepEqual(entry?.variants, ["vertical", "horizontal"]);
assert.match(component, /event\.key === "Home"/);
assert.match(component, /event\.key === "End"/);
assert.match(component, /setPointerCapture/);
assert.match(component, /activePointerIdRef\.current !== event\.pointerId/);
assert.match(component, /role="separator"/);
assert.match(styles, /\.nodedc-split-pane__separator:focus-visible::before/);
assert.match(docs, /## SplitPane/);
assert.match(catalog, /<SplitPane/);
});
test("invisible divider retains an accessible resize target", () => {
const markup = renderToStaticMarkup(createElement(SplitPane, {
primary: "Camera", secondary: "Map", primarySize: 40,
onPrimarySizeChange: () => {}, separatorLabel: "Resize", separatorAppearance: "invisible",
}));
assert.match(markup, /data-separator-appearance="invisible"/);
assert.match(markup, /role="separator"/);
assert.match(markup, /tabindex="0"/);
assert.match(markup, /aria-valuenow="40"/);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import test from "node:test";
import {createElement} from "react";
import {renderToStaticMarkup} from "react-dom/server";
import {StatusBadge} from "../packages/ui-react/dist/index.js";
test("status pulse is opt-in and does not replace the status text",()=>{
const status=renderToStaticMarkup(createElement(StatusBadge,{tone:"danger",pulse:true},"Привязка потеряна"));
assert.match(status,/data-pulse="true"/);
assert.match(status,/Привязка потеряна/);
assert.doesNotMatch(renderToStaticMarkup(createElement(StatusBadge,{},"Готово")),/data-pulse/);
});
test("only the lamp animates, with static reduced-motion fallback",()=>{
const css=readFileSync(new URL("../packages/ui-core/styles.css",import.meta.url),"utf8");
assert.match(css,/\.nodedc-status\[data-pulse="true"\]::before\s*\{[^}]*animation: nodedc-status-pulse/);
assert.match(css,/@media \(prefers-reduced-motion: reduce\) \{\s*\.nodedc-status\[data-pulse="true"\]::before \{ animation: none;/);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
const source = readFileSync(
new URL("../packages/ui-react/src/Toast.tsx", import.meta.url),
"utf8",
);
test("toast items own independent ten-second terminal lifetimes", () => {
assert.match(source, /const DEFAULT_TOAST_DURATION_MS = 10_000/);
assert.match(source, /function TimedToastCard/);
assert.match(source, /item\.tone === "loading" \? null : DEFAULT_TOAST_DURATION_MS/);
assert.match(source, /window\.setTimeout\(\(\) => dismissRef\.current\(item\.id\), duration\)/);
assert.match(source, /\[item\.durationMs, item\.id, item\.tone\]/);
assert.match(source, /items\.map\(\(item\) => <TimedToastCard key=\{item\.id\}/);
assert.doesNotMatch(source, /items\.flatMap/);
});
+23
View File
@@ -0,0 +1,23 @@
import assert from "node:assert/strict";
import {test} from "node:test";
import {computeFloatingPosition,movingToMenu} from "../packages/ui-core/dist/index.js";
test("menus stay beyond the maximum magnified edge, including narrow windows",()=>{
for(const width of [320,640,1400])for(const size of [25,42,88]){
const anchor={left:width-12-size,right:width-12,top:200,bottom:225,width:size,height:25};
const p=computeFloatingPosition({anchor,surfaceWidth:220,surfaceHeight:400,placement:"left-start",flip:false,viewportWidth:width,viewportHeight:600});
assert.ok(p.left+Math.min(220,p.maxWidth)<=anchor.left-8+1e-9);
assert.ok(p.left>=8);assert.ok(p.top+Math.min(400,p.maxHeight)<=592);
const mirror={...anchor,left:12,right:12+size};
const q=computeFloatingPosition({anchor:mirror,surfaceWidth:220,surfaceHeight:400,placement:"right-start",flip:false,viewportWidth:width,viewportHeight:600});
assert.ok(q.left>=mirror.right+8);assert.ok(q.left+Math.min(220,q.maxWidth)<=width-8);
}
});
test("intent triangle protects diagonal entry but never blocks deliberate vertical or reverse motion",()=>{
const s={left:200,right:450,top:100,bottom:500,width:250,height:400},o={x:490,y:200};
assert.equal(movingToMenu(o,o,{x:480,y:210},s),true);
assert.equal(movingToMenu(o,o,{x:490,y:240},s),false);
assert.equal(movingToMenu(o,{x:480,y:210},{x:485,y:220},s),false);
assert.equal(movingToMenu(o,o,{x:480,y:600},s),false);
assert.equal(movingToMenu({x:150,y:200},{x:150,y:200},{x:160,y:210},s),true);
assert.equal(movingToMenu({x:300,y:550},{x:300,y:550},{x:310,y:540},s),true);
});
+4 -2
View File
@@ -1121,7 +1121,7 @@ function validateDesignProfileLayout(value) {
if (media.logoSource !== "file" && media.logoSource !== "url") throw applicationError("invalid_design_profile_logo_source"); if (media.logoSource !== "file" && media.logoSource !== "url") throw applicationError("invalid_design_profile_logo_source");
if (!isObject(media.faviconAssets)) throw applicationError("invalid_design_profile_favicon_assets"); if (!isObject(media.faviconAssets)) throw applicationError("invalid_design_profile_favicon_assets");
if (glass.version !== 4) throw applicationError("unsupported_glass_material_version"); if (glass.version !== 4) throw applicationError("unsupported_glass_material_version");
if (!["left", "right", "bottom"].includes(toolbar.placement)) throw applicationError("invalid_toolbar_placement"); if (!["left", "right", "top", "bottom"].includes(toolbar.placement)) throw applicationError("invalid_toolbar_placement");
return { return {
theme: value.theme, theme: value.theme,
accentHex: requireHex(value.accentHex, "invalid_design_profile_accent"), accentHex: requireHex(value.accentHex, "invalid_design_profile_accent"),
@@ -1176,8 +1176,10 @@ function validateDesignProfileLayout(value) {
outline: requireHex(toolbar.outline, "invalid_toolbar_outline"), outline: requireHex(toolbar.outline, "invalid_toolbar_outline"),
minSize: requireNumber(toolbar.minSize, 16, 64, "invalid_toolbar_min_size"), minSize: requireNumber(toolbar.minSize, 16, 64, "invalid_toolbar_min_size"),
maxSize: requireNumber(toolbar.maxSize, 32, 160, "invalid_toolbar_max_size"), maxSize: requireNumber(toolbar.maxSize, 32, 160, "invalid_toolbar_max_size"),
lensCount: requireInteger(toolbar.lensCount, 1, 12, "invalid_toolbar_lens_count"), lensCount: requireInteger(toolbar.lensCount, 1, 13, "invalid_toolbar_lens_count"),
autoHide: requireBoolean(toolbar.autoHide, "invalid_toolbar_auto_hide"), autoHide: requireBoolean(toolbar.autoHide, "invalid_toolbar_auto_hide"),
hideDelay: requireNumber(toolbar.hideDelay ?? 5000,0,15000,"invalid_toolbar_hide_delay"),
gap: requireNumber(toolbar.gap ?? 10,0,24,"invalid_toolbar_gap"),
}, },
pageTypes: validateDesignProfilePageTypes(value.pageTypes), pageTypes: validateDesignProfilePageTypes(value.pageTypes),
}; };