Compare commits
79
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
872f01cd27 | ||
|
|
f4e7369eec | ||
|
|
f8aa8022f1 | ||
|
|
ae82c01049 | ||
|
|
d0648014f5 | ||
|
|
4390d1350d | ||
|
|
fea966a3f0 | ||
|
|
8b49296efa | ||
|
|
70d5d8b385 | ||
|
|
cb49932706 | ||
|
|
5f93defabf | ||
|
|
d7885fe098 | ||
|
|
d8ed37e09d | ||
|
|
9a00d0bb06 | ||
|
|
616ec9160a | ||
|
|
1cc360f99a | ||
|
|
31ed774529 | ||
|
|
6f2f9644fe | ||
|
|
91a5ebe8da | ||
|
|
ce1b707348 | ||
|
|
64908711a4 | ||
|
|
3d4c4aaa08 | ||
|
|
541fb2a2c3 | ||
|
|
1326ec6cc9 | ||
|
|
1ec17b3098 | ||
|
|
661ca2afd2 | ||
|
|
59411f4937 | ||
|
|
601ca62e9a | ||
|
|
633b0db7b3 | ||
|
|
189bb70377 | ||
|
|
3750a94200 | ||
|
|
06cb8ad4cd | ||
|
|
55fa5fa6bc | ||
|
|
fdc93a3136 | ||
|
|
8addef187b | ||
|
|
4904fbe1f7 | ||
|
|
be929f9d8e | ||
|
|
8ff33a6a17 | ||
|
|
bbbfa8912f | ||
|
|
972944e6f2 | ||
|
|
ecf53ce974 | ||
|
|
ac65b1167f | ||
|
|
cb534dbe39 | ||
|
|
a6e6c8f2d9 | ||
|
|
2d23a0262e | ||
|
|
2ee34ac912 | ||
|
|
77091fda98 | ||
|
|
1b63366d2e | ||
|
|
9aa6f949b0 | ||
|
|
a5a73c8753 | ||
|
|
8dd9190573 | ||
|
|
67025ee209 | ||
|
|
8c53f73ee5 | ||
|
|
b10fd5d645 | ||
|
|
26a1bf72a2 | ||
|
|
5b882bc3d9 | ||
|
|
1bdfc6c240 | ||
|
|
70ce00f2d0 | ||
|
|
999864e5b0 | ||
|
|
3adeb33b1b | ||
|
|
be6463fd59 | ||
|
|
47d4f19d99 | ||
|
|
17e150b1c7 | ||
|
|
8a79dfe84d | ||
|
|
d51d8bb7f6 | ||
|
|
c8f4916423 | ||
|
|
6e7255ecdb | ||
|
|
c7e136cc14 | ||
|
|
51cb426c6b | ||
|
|
8f38c76f79 | ||
|
|
2fa1951f51 | ||
|
|
19f0d97e23 | ||
|
|
bbb50e06b4 | ||
|
|
d6c62da470 | ||
|
|
a3385e83c4 | ||
|
|
9fa81fde9a | ||
|
|
117bfe0c3a | ||
|
|
1c5246afe8 | ||
|
|
4116f5ba95 |
@@ -12,6 +12,8 @@ Before adding UI to a NODE.DC application:
|
||||
|
||||
Canonical source limits:
|
||||
|
||||
- Mission Core is the owner-approved dark-theme reference (2026-11-05). Its audited palette and shared operator presentation are maintained here; apps consume `missionDarkTheme`, not copied CSS.
|
||||
|
||||
- Launcher/Hub, CMS and SEO are the reference product family for application shell, headers, windows and common controls.
|
||||
- From Engine, only the redesigned environment settings, shared glass controls and NDC agent inspector are approved reference sources.
|
||||
- Legacy Engine inspectors and legacy Engine plates are explicitly non-canonical.
|
||||
@@ -37,3 +39,8 @@ All subagent work in this repository follows
|
||||
deploy, install dependencies or expand their own scope.
|
||||
- Do not invent per-agent token measurements. Report measured usage only when the
|
||||
product exposes it; otherwise report model, task, state, turns and outcome.
|
||||
|
||||
|
||||
## Enforced compact typography
|
||||
|
||||
Operational values/section headings use md (13 px), explanatory/status/error copy uses Description/sm (12 px). Only canonical window/page title roles use title (18 px). Do not add browser-default paragraphs, local larger sizes, font shorthand or inline fontSize. Typography checks are mandatory build gates; never extend the frozen compact legacy baseline or generalize scene/display exceptions to satisfy a feature. Run the typography contract tests and verify computed sizes in centered/floating and narrow windows. See Design Guideline docs/OPERATIONAL_TYPOGRAPHY.md.
|
||||
|
||||
@@ -6,13 +6,14 @@
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"build": "tsc -b && vite build",
|
||||
"typecheck": "tsc -b --pretty false"
|
||||
"typecheck": "tsc -b --pretty false",
|
||||
"prebuild": "node --test ../../scripts/operational-typography.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nodedc/page-patterns": "0.1.0",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-react": "0.7.0",
|
||||
"cesium": "^1.143.0",
|
||||
"@nodedc/ui-core": "0.7.1",
|
||||
"@nodedc/ui-react": "0.7.1",
|
||||
"cesium": "1.147.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
|
||||
+295
-34
@@ -1,26 +1,44 @@
|
||||
import { OperationalTypographyDemo } from "./OperationalTypographyDemo";
|
||||
import { ModalSizeExample } from './ModalSizeExample';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { applyGlassMaterial, applyNodedcTheme, defaultGlassMaterial, type GlassMaterialSettings, type NodedcTheme, type RgbTuple } from "@nodedc/ui-core";
|
||||
import { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTemplateDefinition } from "@nodedc/page-patterns";
|
||||
import {MissionThemeExample} from './MissionThemeExample';
|
||||
import {EditorDockExample} from './EditorDockExample';
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Tooltip,
|
||||
LoadingRegion,
|
||||
Description,
|
||||
ComparisonTable,
|
||||
StatusBadge,
|
||||
ProgressBar,
|
||||
LevelButton,
|
||||
ProgressButton,
|
||||
LayerStackIndicator,
|
||||
AdminNavigationPanel,
|
||||
AppHeader,
|
||||
ApplicationPanel,
|
||||
ApplicationShell,
|
||||
ApplicationSidePanel,
|
||||
Button,
|
||||
KeyButton,
|
||||
Checker,
|
||||
ColorField,
|
||||
ConfirmationModal,
|
||||
ControlRow,
|
||||
Dropdown,
|
||||
DragDropRoot,
|
||||
DockLayout, DockHandle, balancedDockTree, type DockTree,
|
||||
DraggableItem,
|
||||
DropZone,
|
||||
FieldFrame,
|
||||
FeatureSettingsWindow,
|
||||
GlassSurface,
|
||||
GlassMaterialSurface,
|
||||
ResizableViewport,
|
||||
SceneAnnotation,
|
||||
HeaderNavigation,
|
||||
HeaderProfile,
|
||||
HeaderWorkspace,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -28,10 +46,16 @@ import {
|
||||
InspectorSelectField,
|
||||
MediaSourceField,
|
||||
RangeControl,
|
||||
ResourceRow,
|
||||
ResourceList,
|
||||
Tree,
|
||||
SegmentedControl,
|
||||
SegmentedGroup,
|
||||
SegmentedButton,
|
||||
Select,
|
||||
ShareAccessModal,
|
||||
ShareLinkModal,
|
||||
SplitPane,
|
||||
SortableItem,
|
||||
SortableScope,
|
||||
SettingsCard,
|
||||
@@ -41,6 +65,7 @@ import {
|
||||
ToastCard,
|
||||
ToastStack,
|
||||
Toolbar,
|
||||
NavigationCube,
|
||||
UserProfileMenu,
|
||||
useApplicationWorkspace,
|
||||
Window,
|
||||
@@ -76,6 +101,7 @@ import {
|
||||
type StoredLayout,
|
||||
} from "./designProfile.js";
|
||||
import { FoundrySettingsModal } from "./FoundrySettingsModal.js";
|
||||
import { EnvironmentCatalogDemo } from "./EnvironmentCatalogDemo.js";
|
||||
|
||||
type CatalogSection = "controls" | "media" | "glass" | "status" | "modals" | "icons";
|
||||
type StudioContext = "visual" | "pages" | "applications";
|
||||
@@ -99,7 +125,8 @@ const designProfileDocumentPath = (reference: { id: string; version: string; sta
|
||||
);
|
||||
|
||||
const accents: Array<{ label: string; value: RgbTuple; hex: string }> = [
|
||||
{ label: "NODE.DC", value: [255, 47, 146], hex: "#ff2f92" },
|
||||
{ label: "Mission Core", value: [247, 248, 244], hex: "#f7f8f4" },
|
||||
{ label: "Rose", value: [255, 47, 146], hex: "#ff2f92" },
|
||||
{ label: "Rose", value: [255, 62, 108], hex: "#ff3e6c" },
|
||||
{ label: "Blush", value: [255, 108, 175], hex: "#ff6caf" },
|
||||
{ label: "Magenta", value: [215, 70, 255], hex: "#d746ff" },
|
||||
@@ -125,7 +152,7 @@ const materialDefaults: Record<NodedcTheme, MaterialDraft> = {
|
||||
panelOpacity: 100,
|
||||
fieldHex: "#2a2a2c",
|
||||
fieldOpacity: 100,
|
||||
nestedHex: "#0b0b0d",
|
||||
nestedHex: "#0d0d0f",
|
||||
},
|
||||
light: {
|
||||
panelHex: "#ffffff",
|
||||
@@ -193,7 +220,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
{
|
||||
title: "Окно и слой",
|
||||
note: "Launcher / Hub",
|
||||
icons: ["close", "plus", "expand", "minimize", "refresh", "panel", "apps"],
|
||||
icons: ["close", "plus", "expand", "minimize", "refresh", "panel", "apps", "layers"],
|
||||
},
|
||||
{
|
||||
title: "Навигация",
|
||||
@@ -203,32 +230,39 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
{
|
||||
title: "Редактирование",
|
||||
note: "Launcher / SEO",
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external"],
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "ruler", "section", "isolate", "orthographic", "perspective", "fit-view", "select", "pen", "rectangle", "curve", "undo", "redo"],
|
||||
},
|
||||
{
|
||||
title: "Состояние и доступ",
|
||||
note: "Вся платформа",
|
||||
icons: ["check", "alert", "activity", "lock", "key", "shield", "circle"],
|
||||
icons: ["check", "alert", "info", "info-plain", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
|
||||
},
|
||||
{
|
||||
title: "Сущности",
|
||||
note: "Общий словарь",
|
||||
icons: ["profile", "users", "building", "globe", "target", "database", "network", "inbox", "mail"],
|
||||
icons: ["profile", "users", "building", "globe", "target", "database", "pin", "network", "inbox", "mail"],
|
||||
},
|
||||
{
|
||||
title: "Контент",
|
||||
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> = {
|
||||
pipette: "Пипетка",
|
||||
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
|
||||
power: "Питание",
|
||||
move: "Свободное окно",
|
||||
"add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить",
|
||||
activity: "Активность",
|
||||
alert: "Предупреждение",
|
||||
apps: "Приложения",
|
||||
building: "Компания",
|
||||
camera: "Камера",
|
||||
check: "Готово",
|
||||
"chevron-down": "Раскрыть",
|
||||
"chevron-up": "Свернуть",
|
||||
"chevron-left": "Назад",
|
||||
"chevron-right": "Вперёд",
|
||||
circle: "Маркер",
|
||||
@@ -236,8 +270,11 @@ const iconLabels: Record<IconName, string> = {
|
||||
close: "Закрыть",
|
||||
copy: "Копировать",
|
||||
database: "База данных",
|
||||
pin: "Закрепить",
|
||||
download: "Скачать",
|
||||
edit: "Редактировать",
|
||||
eye: "Показать",
|
||||
"eye-off": "Скрыть",
|
||||
expand: "Развернуть",
|
||||
external: "Открыть снаружи",
|
||||
file: "Файл",
|
||||
@@ -246,22 +283,32 @@ const iconLabels: Record<IconName, string> = {
|
||||
grid: "Обзор",
|
||||
image: "Изображение",
|
||||
inbox: "Уведомления",
|
||||
info: "Информация",
|
||||
"info-plain": "Информация без окружности",
|
||||
"fit-view": "Вписать модель",
|
||||
key: "Ключ",
|
||||
layers: "Слои",
|
||||
list: "Список задач",
|
||||
lock: "Закрыто",
|
||||
mail: "Приглашение",
|
||||
minimize: "Свернуть",
|
||||
network: "Связи",
|
||||
panel: "Панель",
|
||||
plan: "План",
|
||||
play: "Воспроизвести",
|
||||
target: "Таргеты",
|
||||
plus: "Добавить",
|
||||
minus: "Уменьшить",
|
||||
profile: "Профиль",
|
||||
refresh: "Обновить",
|
||||
"rotate-clockwise": "Повернуть по часовой стрелке",
|
||||
save: "Сохранить",
|
||||
search: "Поиск",
|
||||
settings: "Настройки",
|
||||
shield: "Доступ",
|
||||
sliders: "Параметры",
|
||||
stop: "Остановить",
|
||||
terminal: "Консоль команд",
|
||||
trash: "Удалить",
|
||||
upload: "Загрузить",
|
||||
users: "Участники",
|
||||
@@ -297,7 +344,7 @@ function Preview({ title, note, children, className }: {
|
||||
|
||||
export function CatalogApp() {
|
||||
const [theme, setTheme] = useState<NodedcTheme>("dark");
|
||||
const [accentHex, setAccentHex] = useState("#ff2f92");
|
||||
const [accentHex, setAccentHex] = useState("#f7f8f4");
|
||||
const [materialByTheme, setMaterialByTheme] = useState<Record<NodedcTheme, MaterialDraft>>(() => ({
|
||||
dark: { ...materialDefaults.dark },
|
||||
light: { ...materialDefaults.light },
|
||||
@@ -328,6 +375,7 @@ export function CatalogApp() {
|
||||
const [createModuleDescription, setCreateModuleDescription] = useState("");
|
||||
const [deleteModuleOpen, setDeleteModuleOpen] = useState(false);
|
||||
const [pageRemovalId, setPageRemovalId] = useState<string | null>(null);
|
||||
const [previewLayers, setPreviewLayers] = useState<string[]>(["source"]);
|
||||
const [applicationMode, setApplicationMode] = useState<"edit" | "preview">("edit");
|
||||
const [designProfileSaveOpen, setDesignProfileSaveOpen] = useState(false);
|
||||
const [designProfileSaveMode, setDesignProfileSaveMode] = useState<"save" | "save-as">("save");
|
||||
@@ -345,22 +393,36 @@ export function CatalogApp() {
|
||||
const activePageTemplateId = pageTemplateIdFromView(activeView);
|
||||
const [selectedStatus, setSelectedStatus] = useState<(typeof selectOptions)[number]["value"]>("active");
|
||||
const [brightness, setBrightness] = useState(49);
|
||||
const [sliceBand, setSliceBand] = useState<[number, number]>([-1.2, 51.5]);
|
||||
const [glowDistance, setGlowDistance] = useState(105);
|
||||
const [usePortColors, setUsePortColors] = useState(false);
|
||||
const [connectionType, setConnectionType] = useState("spline");
|
||||
const [lightColor, setLightColor] = useState("#ff2f92");
|
||||
const [lightColor, setLightColor] = useState("#f7f8f4");
|
||||
const [connectionColor, setConnectionColor] = useState("#404040");
|
||||
const [fillColor, setFillColor] = useState("#ff6caf");
|
||||
const [fillOpacity, setFillOpacity] = useState(100);
|
||||
const [strokeColor, setStrokeColor] = useState("#2b2b36");
|
||||
const [strokeOpacity, setStrokeOpacity] = useState(100);
|
||||
const [treeDemoOpen,setTreeDemoOpen]=useState(false);
|
||||
const [treeDemoRect,setTreeDemoRect]=useState({left:32,top:96,width:380,height:480});
|
||||
const [treeSelected,setTreeSelected]=useState<string|null>('cells');
|
||||
const [treeVisible,setTreeVisible]=useState(true);
|
||||
const [treeSelectedIds,setTreeSelectedIds]=useState<string[]>(['cells']);
|
||||
const [inspectorOpen, setInspectorOpen] = useState(false);
|
||||
const workspaceWindowDemoRef = useRef<HTMLDivElement>(null);
|
||||
const [sceneDemoHeight, setSceneDemoHeight] = useState(480);
|
||||
const [workspaceWindowDemoOpen, setWorkspaceWindowDemoOpen] = useState(true);
|
||||
const [workspaceWindowDemoMaximized, setWorkspaceWindowDemoMaximized] = useState(false);
|
||||
const [workspaceWindowDemoRect, setWorkspaceWindowDemoRect] = useState<WorkspaceWindowRect>({ x: 24, y: 24, width: 340, height: 230 });
|
||||
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 [createModalOpen, setCreateModalOpen] = useState(false);
|
||||
const [missionAppearance, setMissionAppearance] = useState(true);
|
||||
const [flatEdges, setFlatEdges] = useState(true);
|
||||
const [featureSettingsDemoOpen, setFeatureSettingsDemoOpen] = useState(false);
|
||||
const [featureSettingsDemoSection, setFeatureSettingsDemoSection] = useState('general');
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [shareAccessOpen, setShareAccessOpen] = useState(false);
|
||||
const [shareLinkOpen, setShareLinkOpen] = useState(false);
|
||||
@@ -399,6 +461,9 @@ export function CatalogApp() {
|
||||
icon512: "/favicon/icon-512.png",
|
||||
});
|
||||
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 [toolbarBg, setToolbarBg] = useState("#111115");
|
||||
const [toolbarBorder, setToolbarBorder] = useState("#111117");
|
||||
@@ -407,6 +472,8 @@ export function CatalogApp() {
|
||||
const [toolbarMaxSize, setToolbarMaxSize] = useState(87);
|
||||
const [toolbarLensCount, setToolbarLensCount] = useState(5);
|
||||
const [toolbarAutoHide, setToolbarAutoHide] = useState(false);
|
||||
const [toolbarHideDelay,setToolbarHideDelay]=useState(5000);
|
||||
const [toolbarGap,setToolbarGap]=useState(10);
|
||||
const [shareEmail, setShareEmail] = useState("");
|
||||
const [shareRole, setShareRole] = useState<ShareRole>("editor");
|
||||
const [shareMessage, setShareMessage] = useState("");
|
||||
@@ -470,6 +537,8 @@ export function CatalogApp() {
|
||||
if (typeof stored.toolbar?.minSize === "number") setToolbarMinSize(stored.toolbar.minSize);
|
||||
if (typeof stored.toolbar?.maxSize === "number") setToolbarMaxSize(stored.toolbar.maxSize);
|
||||
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);
|
||||
}, []);
|
||||
|
||||
@@ -490,6 +559,8 @@ export function CatalogApp() {
|
||||
useEffect(() => {
|
||||
applyNodedcTheme(document.documentElement, {
|
||||
theme,
|
||||
appearance: missionAppearance ? "mission" : "default",
|
||||
edges: flatEdges ? "flat" : "default",
|
||||
accent,
|
||||
material: {
|
||||
panel: panelMaterial,
|
||||
@@ -499,7 +570,7 @@ export function CatalogApp() {
|
||||
},
|
||||
});
|
||||
document.documentElement.style.setProperty("--nodedc-canvas-soft", material.nestedHex);
|
||||
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme]);
|
||||
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme, missionAppearance, flatEdges]);
|
||||
|
||||
useEffect(() => {
|
||||
applyGlassMaterial(document.documentElement, glassMaterial);
|
||||
@@ -570,13 +641,15 @@ export function CatalogApp() {
|
||||
}
|
||||
const toolbar = stored.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.border) setToolbarBorder(toolbar.border);
|
||||
if (toolbar.outline) setToolbarOutline(toolbar.outline);
|
||||
if (typeof toolbar.minSize === "number") setToolbarMinSize(toolbar.minSize);
|
||||
if (typeof toolbar.maxSize === "number") setToolbarMaxSize(toolbar.maxSize);
|
||||
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);
|
||||
}
|
||||
setLayoutSaveState("saved");
|
||||
@@ -1045,6 +1118,7 @@ export function CatalogApp() {
|
||||
maxSize: toolbarMaxSize,
|
||||
lensCount: toolbarLensCount,
|
||||
autoHide: toolbarAutoHide,
|
||||
hideDelay:toolbarHideDelay,gap:toolbarGap,
|
||||
},
|
||||
};
|
||||
const response = await fetch("/api/layout", {
|
||||
@@ -1253,10 +1327,12 @@ export function CatalogApp() {
|
||||
{ value: "left", label: "Слева" },
|
||||
{ value: "right", label: "Справа" },
|
||||
{ value: "bottom", label: "Снизу" },
|
||||
{ value: "top", label: "Сверху" },
|
||||
]}
|
||||
onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)}
|
||||
/>
|
||||
<ControlRow label="Фон"><ColorField value={toolbarBg} onChange={setToolbarBg} /></ControlRow>
|
||||
<Description>HEX можно очистить и набрать заново; Enter применяет, Escape возвращает текущий цвет.</Description>
|
||||
<ControlRow label="Border"><ColorField value={toolbarBorder} onChange={setToolbarBorder} /></ControlRow>
|
||||
<ControlRow label="Outline"><ColorField value={toolbarOutline} onChange={setToolbarOutline} /></ControlRow>
|
||||
<RangeControl label="Минимальный размер" value={toolbarMinSize} min={18} max={42} formatValue={(value) => `${value}px`} onChange={(value) => {
|
||||
@@ -1267,6 +1343,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={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} />
|
||||
<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 +1356,10 @@ export function CatalogApp() {
|
||||
<>
|
||||
<ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow>
|
||||
<RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} />
|
||||
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} formatValue={(value) => `${value}%`} onChange={setGlowDistance} />
|
||||
<RangeControl variant="rail" label="Тонкая горизонтальная шкала" value={brightness} min={0} max={100} formatValue={v=>`${v}%`} onChange={setBrightness}/>
|
||||
<div style={{ height: 180 }} title="Тонкая шкала: две границы двигаются независимо; без центрального текста"><RangeControl orientation="vertical" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
|
||||
<div style={{ height: 180, display: 'flex', justifyContent: 'flex-end' }} title="Шкала справа: границы слева; фокус подчёркивает выбранную границу"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
|
||||
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} exactValueBounds={{ min: 0 }} formatValue={(value) => `${value}%`} onChange={setGlowDistance} />
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -1324,14 +1405,24 @@ export function CatalogApp() {
|
||||
case "controls":
|
||||
return (
|
||||
<div className="catalog-grid">
|
||||
<Preview title="Selection" note="integrated / split">
|
||||
<Preview title="Mission Core" note="canonical foundation / nested fields / portal" className="catalog-preview--wide"><MissionThemeExample/></Preview>
|
||||
<Preview title="Navigation cube" note="faces / edges / corners"><NavigationCube faceOpacity={.65} edgeOpacity={cubeEdgeOpacity} size={cubeSize} quaternion={[.28,-.36,.12,.88]} onSelect={setCubeDirection}/><RangeControl label="Размер 3D-куба" value={cubeSize} min={48} max={160} step={1} onChange={setCubeSize} formatValue={v=>`${v} px`}/><RangeControl label="Прозрачность линий куба" value={1-cubeEdgeOpacity} min={0} max={1} step={.05} onChange={v=>setCubeEdgeOpacity(1-v)} formatValue={v=>`${Math.round(v*100)}%`}/><p>{cubeDirection.join(" · ")}</p></Preview>
|
||||
<Preview title="Selection" note="integrated / split / inline">
|
||||
<div className="catalog-form">
|
||||
<FieldFrame label="Hub / integrated select">
|
||||
<FieldFrame label="Hub / integrated select" labelPlacement="below">
|
||||
<Select label="Статус" value={selectedStatus} options={[...selectOptions]} searchable onChange={setSelectedStatus} />
|
||||
</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">
|
||||
<Select
|
||||
variant="split"
|
||||
variant="split" shape="pill"
|
||||
label="Тип связи"
|
||||
value={connectionType}
|
||||
options={[
|
||||
@@ -1342,6 +1433,19 @@ export function CatalogApp() {
|
||||
onChange={setConnectionType}
|
||||
/>
|
||||
</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
|
||||
trigger={({ open, toggle, setTriggerRef, surfaceId }) => (
|
||||
<Button ref={setTriggerRef} aria-expanded={open} aria-controls={surfaceId} icon={<Icon name="chevron-down" />} onClick={toggle}>Действия</Button>
|
||||
@@ -1349,6 +1453,7 @@ export function CatalogApp() {
|
||||
>
|
||||
{({ 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="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>
|
||||
@@ -1370,16 +1475,111 @@ export function CatalogApp() {
|
||||
<Button variant="ghost" icon={<Icon name="external" />}>Открыть</Button>
|
||||
<Button variant="danger" icon={<Icon name="trash" />}>Удалить</Button>
|
||||
<IconButton label="Добавить"><Icon name="plus" /></IconButton>
|
||||
<KeyButton label="Клавиша W">W</KeyButton>
|
||||
<KeyButton label="Клавиша A нажата" pressed>A</KeyButton>
|
||||
<KeyButton label="Клавиша S недоступна" disabled>S</KeyButton>
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Оконные действия" note="круг `46 px`" className="catalog-preview--compact">
|
||||
<div className="catalog-window-actions-demo">
|
||||
<Preview title="Подсказки" note="Скруглённое стекло без обводки · hover / focus / touch" className="catalog-preview--compact">
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<IconButton label="Инспектор"><Icon name="network" /></IconButton>
|
||||
<Button title="Общая подсказка для существующего title">Подсказка приложения</Button>
|
||||
<Tooltip content="Короткое пояснение. Escape закрывает только подсказку."><Button>Подробнее</Button></Tooltip>
|
||||
<Tooltip focusable label="Текущий уровень" content="Доступно мышью, клавиатурой и касанием."><StatusBadge tone="neutral">Нормальный уровень</StatusBadge></Tooltip>
|
||||
<Tooltip disabled content="Эта подсказка отключена"><Button disabled>Недоступно</Button></Tooltip>
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Активность" note="default / compact" className="catalog-preview--compact">
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<span className="catalog-inline">
|
||||
<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="измерение / последние данные / неизвестно">
|
||||
<LevelButton label="Заряд аккумулятора" value={.82} levelTone="success" onClick={()=>setProjectName("Аккумулятор · 82%")}/>
|
||||
<LevelButton label="Заряд аккумулятора" value={.17} levelTone="warning" freshness="stale"/>
|
||||
<LevelButton label="Заряд аккумулятора" value={null} freshness="unknown" disabled/>
|
||||
<LevelButton label="Белая заливка" value={.82} fillColor="#ffffff"/>
|
||||
<LevelButton label="Чёрная заливка" value={.82} fillColor="#000000"/>
|
||||
<LevelButton label="Минимальный индикатор" value={1} valueText="100%" fillColor="#ffffff" geometry={{width:32,height:12,radius:4}}/>
|
||||
<LevelButton label="Широкий индикатор" value={.82} geometry={{width:160,height:24,radius:8}}/>
|
||||
</Preview>
|
||||
<Preview title="Линейный прогресс" note="измеренный / неизвестный / завершённый">
|
||||
<ProgressBar label="Подготовка" value={0.6} valueText="Три этапа из пяти" />
|
||||
<ProgressBar label="Получение сведений" />
|
||||
<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>
|
||||
<Button onClick={()=>setTreeDemoOpen(true)}>Дерево объектов · изменяемый размер</Button>
|
||||
<DragDropRoot onDragEnd={()=>{}}><DraggableItem id="whole-material-tile">{({activator})=><Button {...activator.attributes} {...activator.listeners}>Перенос за всю плитку</Button>}</DraggableItem></DragDropRoot>
|
||||
<SettingsCard title="Устройства не обнаружены" description="Подключите устройство, чтобы оно появилось в списке." />
|
||||
<SettingsCard align="center" role="status" title="Настройки применены" description="Проверьте подключение устройства." />
|
||||
</Preview>
|
||||
<Preview title="Операционная типографика" note="единый размер во всех состояниях"><OperationalTypographyDemo /></Preview>
|
||||
<Preview title="Размер DOM-окна" note="геометрия с сохранением в приложении"><ModalSizeExample /></Preview>
|
||||
<Preview title="Главная и окружение" note="единые компоненты · сохранение в памяти каталога">
|
||||
<EnvironmentCatalogDemo />
|
||||
</Preview>
|
||||
<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>
|
||||
<Select label="Статус примера сцены" value={selectedStatus} options={[...selectOptions]} onChange={setSelectedStatus} />
|
||||
<IconButton label="Добавить"><Icon name="plus" /></IconButton>
|
||||
<IconButton label="Развернуть"><Icon name="expand" /></IconButton>
|
||||
<IconButton label="Закрыть"><Icon name="close" /></IconButton>
|
||||
</div>
|
||||
</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">
|
||||
<div ref={workspaceWindowDemoRef} className="catalog-workspace-window-demo">
|
||||
{workspaceWindowDemoOpen ? (
|
||||
@@ -1394,6 +1594,7 @@ export function CatalogApp() {
|
||||
setWorkspaceWindowDemoOpen(false);
|
||||
setWorkspaceWindowDemoMaximized(false);
|
||||
}}
|
||||
resizeIndicator={false}
|
||||
title="Визуальный канал"
|
||||
subtitle="WORKSPACE / AUXILIARY VIEW"
|
||||
status="LIVE"
|
||||
@@ -1418,6 +1619,29 @@ export function CatalogApp() {
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
|
||||
</Preview>
|
||||
<Preview title="Split pane" note="pointer resize: invisible / keyboard focus: visible" className="catalog-preview--wide catalog-split-pane-preview">
|
||||
<Switch label="Скрыть линию разделителя" checked={splitPaneInvisible} onChange={setSplitPaneInvisible} />
|
||||
<div className="catalog-split-pane-demo">
|
||||
<SplitPane
|
||||
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 / panel edges / workspace edges / keyboard" className="catalog-preview--wide">
|
||||
<div style={{height:420}}><DockLayout tree={dockDemoTree} onTreeChange={setDockDemoTree}
|
||||
panels={[{id:'camera',label:'Камера'},{id:'depth',label:'Глубина'},{id:'map',label:'Карта'},{id:'scene',label:'Сцена',minimumSize:{width:320,height:280}}]}
|
||||
renderPanel={id=><GlassSurface tone="soft" radius="panel" style={{height:'100%'}}><DockHandle id={id} label={id}/><strong>{id}</strong></GlassSurface>}/></div>
|
||||
<p>Центр окна — обмен, край окна — разделение, внешний край всей области — на всю сторону. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой; Shift + стрелки выбирают край всей области.</p>
|
||||
</Preview>
|
||||
<Preview title="Scene editor docking" note="fixed primary / detachable tools / return" className="catalog-preview--wide"><EditorDockExample/></Preview>
|
||||
<Preview title="Application side panel" note="end / push / controlled" className="catalog-preview--wide catalog-side-panel-preview">
|
||||
<div className="catalog-side-panel-demo">
|
||||
{sidePanelDemoOpen ? (
|
||||
@@ -1427,7 +1651,7 @@ export function CatalogApp() {
|
||||
description="Theme-aware application panel"
|
||||
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>
|
||||
) : (
|
||||
<Button shape="pill" icon={<Icon name="panel" />} onClick={() => setSidePanelDemoOpen(true)}>Открыть правую панель</Button>
|
||||
@@ -1450,6 +1674,10 @@ export function CatalogApp() {
|
||||
description="MP4 или URL становятся частью единого server-side layout вместе с темой, материалом и Toolbar."
|
||||
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
|
||||
label="Видео / картинка"
|
||||
source={mediaSource}
|
||||
@@ -1519,16 +1747,22 @@ export function CatalogApp() {
|
||||
case "glass":
|
||||
return (
|
||||
<div className="catalog-glass-lab">
|
||||
<section className="catalog-glass-stage">
|
||||
<ResizableViewport className="catalog-glass-stage" resizeIndicator={false} height={sceneDemoHeight} minHeight={360} maxHeight={900} onHeightChange={setSceneDemoHeight}>
|
||||
<video key={stageMediaSrc} autoPlay muted loop playsInline aria-hidden="true"><source src={stageMediaSrc} type="video/mp4" /></video>
|
||||
<div className="catalog-glass-stage__shade" />
|
||||
<GlassMaterialSurface className="catalog-glass-stage__sample">
|
||||
<div className="catalog-viewport-actions nodedc-viewport-controls">
|
||||
<IconButton label="Приблизить пример" onClick={()=>setSceneDemoHeight(value=>Math.min(900,value+40))}><Icon name="plus"/></IconButton>
|
||||
<IconButton label="Отдалить пример" onClick={()=>setSceneDemoHeight(value=>Math.max(360,value-40))}><Icon name="minus"/></IconButton>
|
||||
<IconButton label="Вернуть размер примера" onClick={()=>setSceneDemoHeight(480)}><Icon name="select"/></IconButton>
|
||||
</div>
|
||||
<GlassMaterialSurface context="scene" radius="panel" material={glassMaterial} radiusPx={24} className="catalog-glass-stage__sample">
|
||||
<span>CANONICAL GLASS</span>
|
||||
<h2>Модальное окно и Inspector</h2>
|
||||
<h2>Прозрачная плашка над сценой</h2>
|
||||
<SceneAnnotation aria-label="Ячейка 01 · 4,15 В"><span>01</span><strong>4,15 В</strong></SceneAnnotation>
|
||||
<p>Фон остаётся различимым, но текст и контролы сохраняют контраст. Этот материал не применяется к обычным панелям приложения.</p>
|
||||
<div className="catalog-inline"><TextField label="Пример поля" 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>
|
||||
</section>
|
||||
</ResizableViewport>
|
||||
<SettingsCard eyebrow="ENGINE / GLASS V4" title="Параметры материала" description="Общий token-контракт ui-core; изменения сразу видны на preview, модалках и Inspector.">
|
||||
<div className="catalog-glass-controls">
|
||||
<ControlRow label="Цвет тонировки"><ColorField value={glassMaterial.tintHex} onChange={(tintHex) => setGlassMaterial((current) => ({ ...current, tintHex }))} /></ControlRow>
|
||||
@@ -1583,6 +1817,9 @@ export function CatalogApp() {
|
||||
<p className="catalog-preview__explanation">Destructive-цвет появляется только у подтверждения.</p>
|
||||
<Button variant="danger" shape="pill" icon={<Icon name="trash" />} onClick={() => setConfirmOpen(true)}>Проверить удаление</Button>
|
||||
</Preview>
|
||||
<Preview title="Настройки модуля" note="адаптивное меню и форма" className="catalog-modal-preview"><Switch label="Без декоративных обводок" checked={flatEdges} onChange={setFlatEdges} /><Switch label="Визуальный профиль Mission Core" checked={missionAppearance} onChange={setMissionAppearance} />
|
||||
<Button icon={<Icon name="settings" />} onClick={() => setFeatureSettingsDemoOpen(true)}>Открыть настройки модуля</Button>
|
||||
</Preview>
|
||||
<Preview title="Workflow sharing" note="ENGINE / access" className="catalog-modal-preview">
|
||||
<p className="catalog-preview__explanation">Участники, роли, приглашение и immutable-владелец.</p>
|
||||
<Button variant="primary" shape="pill" icon={<Icon name="users" />} onClick={() => setShareAccessOpen(true)}>Поделиться графом</Button>
|
||||
@@ -1621,6 +1858,8 @@ export function CatalogApp() {
|
||||
<div className="catalog-icon-catalog">
|
||||
<Preview title="Размеры и поверхности" note="glyph 16 px" className="catalog-preview--wide">
|
||||
<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="refresh" /></IconButton>
|
||||
<IconButton label="Развернуть"><Icon name="expand" /></IconButton>
|
||||
@@ -1736,7 +1975,7 @@ export function CatalogApp() {
|
||||
title="Состав страниц"
|
||||
description="Перетащите готовую страницу справа в конфигурацию приложения. Свободного canvas и произвольных компонентов нет."
|
||||
>
|
||||
<DragDropRoot onDragEnd={({ activeData, activeId, activeRect, overData, overId, overRect }) => {
|
||||
<DragDropRoot renderOverlay={({data})=><GlassSurface padding="sm"><span>{data?.type==='page-template'?getPageTemplate(String(data.templateId))?.title:'Страница'}</span></GlassSurface>} onDragEnd={({ activeData, activeId, activeRect, overData, overId, overRect }) => {
|
||||
if (!overId) return;
|
||||
if (activeData?.type === "page-template" && (overId === "application-pages" || overData?.type === "application-page")) {
|
||||
const horizontalOverlap = activeRect && overRect
|
||||
@@ -1925,6 +2164,7 @@ export function CatalogApp() {
|
||||
endPanel={<div ref={setMapSettingsPanelHost} className="catalog-map-settings-panel-host" />}
|
||||
header={
|
||||
<AppHeader
|
||||
brandMonochrome
|
||||
brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />}
|
||||
brandHref="/"
|
||||
center={
|
||||
@@ -1949,10 +2189,11 @@ export function CatalogApp() {
|
||||
/>
|
||||
</>
|
||||
}
|
||||
// The shared profile owns its responsive label; consumers do not size it.
|
||||
right={
|
||||
<HeaderProfile>
|
||||
<IconButton label="Уведомления"><Icon name="inbox" size={20} strokeWidth={1.7} /></IconButton>
|
||||
<UserProfileMenu
|
||||
triggerLabel="Профиль"
|
||||
triggerIcon="inbox"
|
||||
displayName={sessionProfile?.user?.displayName || "Профиль"}
|
||||
subtitle={sessionProfile?.user?.email || "NODE.DC Foundry"}
|
||||
avatarUrl={sessionProfile?.user?.avatarUrl || undefined}
|
||||
@@ -1962,7 +2203,6 @@ export function CatalogApp() {
|
||||
{ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" },
|
||||
]}
|
||||
/>
|
||||
</HeaderProfile>
|
||||
}
|
||||
/>
|
||||
}
|
||||
@@ -1984,6 +2224,8 @@ export function CatalogApp() {
|
||||
eyebrow="NODE.DC"
|
||||
title={studioContext === "applications" ? "Applications" : studioContext === "pages" ? "Page Library" : "Visual Library"}
|
||||
closeLabel="Закрыть Module Foundry"
|
||||
collapseLabel="Свернуть панель навигации"
|
||||
expandLabel="Развернуть панель навигации"
|
||||
navigationLabel={studioContext === "applications" ? "Application Drafts" : studioContext === "pages" ? "Page Templates" : "Разделы Visual Library"}
|
||||
onClose={closeGuideline}
|
||||
headerActions={studioContext === "applications" ? (
|
||||
@@ -2115,7 +2357,7 @@ export function CatalogApp() {
|
||||
/>
|
||||
|
||||
{guidelineOpen && studioContext === "visual" ? (
|
||||
<Toolbar<CatalogSection>
|
||||
<Toolbar<CatalogSection | "hold">
|
||||
placement={toolbarPlacement}
|
||||
background={toolbarBg}
|
||||
border={toolbarBorder}
|
||||
@@ -2125,31 +2367,39 @@ export function CatalogApp() {
|
||||
maxSize={toolbarMaxSize}
|
||||
lensCount={toolbarLensCount}
|
||||
autoHide={toolbarAutoHide}
|
||||
items={(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
|
||||
hideDelay={toolbarHideDelay} gap={toolbarGap} menuWidth={320}
|
||||
items={[{id:"hold",label:toolbarAutoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!toolbarAutoHide,onSelect:()=>setToolbarAutoHide(v=>!v)}, ...(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
|
||||
id,
|
||||
label: item.title,
|
||||
shortcut: id === "icons" ? "I" : undefined,
|
||||
icon: item.icon,
|
||||
active: activeSection === id,
|
||||
onSelect: openSection,
|
||||
}))}
|
||||
onSelect: () => openSection(id),
|
||||
}))]}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
|
||||
<Tree defaultExpandedDepth={2} renderActions={node=><Dropdown width={320} trigger={({setTriggerRef,show,open})=><IconButton ref={setTriggerRef} label={`Информация: ${node.label}`} aria-expanded={open} onMouseEnter={show} onClick={show}><Icon name="info-plain" size={14}/></IconButton>}><Description>{node.label}</Description></Dropdown>} label="Пример дерева объектов: стрелка раскрывает, глазик меняет видимость без прокрутки" selected={treeSelected} selectedIds={treeSelectedIds} onSelect={(id,gesture)=>{setTreeSelected(id);setTreeSelectedIds(old=>gesture.shiftKey?gesture.rangeIds:gesture.metaKey?(old.includes(id)?old.filter(key=>key!==id):[...old,id]):gesture.ctrlKey?[...new Set([...old,id])]:[id]);}} onVisibilityChange={(_,visible)=>setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/>
|
||||
</Window>
|
||||
<Window
|
||||
open={inspectorOpen}
|
||||
title="Настройки окружения"
|
||||
subtitle="ENGINE / draggable inspector"
|
||||
resizable
|
||||
placement="end"
|
||||
draggable
|
||||
onClose={() => setInspectorOpen(false)}
|
||||
>
|
||||
<Inspector sections={environmentSections} defaultOpen={["application-material"]} />
|
||||
<Inspector header={<Description>Поля и секции разделены единым шагом 12 px.</Description>} footer={<Button variant="primary" tone="neutral" onClick={()=>setInspectorOpen(false)}>Готово</Button>} sections={environmentSections} defaultOpen={["application-material"]} />
|
||||
</Window>
|
||||
|
||||
<Window
|
||||
open={createModuleOpen}
|
||||
title="Создать модуль"
|
||||
subtitle="APPLICATION / DRAFT"
|
||||
headerActionsPlacement="before-close"
|
||||
headerActions={<IconButton label="Очистить форму" onClick={() => {setCreateModuleName("");setCreateModuleSlug("");}}><Icon name="trash"/></IconButton>}
|
||||
subtitle="Свободное окно · шапка: перемещение · края: размер"
|
||||
size="sm"
|
||||
onClose={() => setCreateModuleOpen(false)}
|
||||
footer={
|
||||
@@ -2243,8 +2493,19 @@ export function CatalogApp() {
|
||||
|
||||
<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><div><p>Пояснение прежнего потребителя без класса — тот же компактный стиль.</p></div><Description role="status">Ожидаем ответ устройства…</Description><ComparisonTable density="compact" label="Сравнение устройств" heading="Устройство" columns={Array.from({length:4},(_,i)=>({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/><LoadingRegion aggregate loading label="Загрузка сведений"><LoadingRegion loading label="Вложенный запрос A"/><LoadingRegion loading label="Вложенный запрос B"/></LoadingRegion></SettingsCard>}
|
||||
</FeatureSettingsWindow>
|
||||
|
||||
<Window
|
||||
open={createModalOpen}
|
||||
headerActions={<IconButton label="Обновить пример" onClick={() => setProjectName("Обновлено")}><Icon name="refresh" /></IconButton>}
|
||||
title="Создать проект"
|
||||
subtitle="Адаптивная форма"
|
||||
size="sm"
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Window,Description,ColorField,ControlRow,Inspector,EditorDockLayout,EditorWorkspace,type EditorDockState} from '@nodedc/ui-react';
|
||||
export function EditorDockExample({inWindow=false}:{inWindow?:boolean}){
|
||||
const [color,setColor]=useState('#292929');
|
||||
const [modal,setModal]=useState(false),[purpose,setPurpose]=useState<'edit'|'view'>('edit');
|
||||
const [editing,setEditing]=useState(false),[open,setOpen]=useState({objects:true,materials:true});
|
||||
const [layout,setLayout]=useState<EditorDockState>({tree:{axis:'y',ratio:70,first:{axis:'x',ratio:25,first:{id:'objects'},second:{id:'viewport'}},second:{id:'materials'}},floating:{}});
|
||||
return <>{!inWindow&&<><Button onClick={()=>setModal(true)}>Сцена в модальном окне</Button><Window open={modal} title="Просмотр сцены" onClose={()=>setModal(false)}><EditorDockExample inWindow/></Window></>}<Button onClick={()=>{setPurpose('edit');setOpen({objects:true,materials:true});setEditing(true);}}>Открыть редактор сцены</Button><Button onClick={()=>{setPurpose('view');setEditing(true);}}>Отдельное окно просмотра</Button><div style={{height:480}}>
|
||||
<EditorWorkspace editing={editing} purpose={purpose} title={purpose==='view'?'Просмотр сцены':'Редактор сцены'} subtitle="Общая оконная система" onBack={()=>setEditing(false)} headerActions={purpose==='view'?<Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button>:undefined}>
|
||||
<EditorDockLayout value={layout} onChange={setLayout} enabled={editing} primary={<div style={{display:'grid',height:'100%',placeContent:'center'}}><Description>Закреплённая сцена · откреплённые инструменты используют scene Glass V4</Description><Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button></div>}
|
||||
tools={[{id:'objects',title:'Объекты',label:'Объекты',open:open.objects,onClose:()=>setOpen(v=>({...v,objects:false})),content:<Description>Сцена → Модель → Детали</Description>},
|
||||
{id:'materials',title:'Материалы',label:'Материалы',minimumSize:{width:380,height:280},footer:<Button width="full" onClick={()=>setColor('#292929')}>Сбросить настройки</Button>,open:open.materials,onClose:()=>setOpen(v=>({...v,materials:false})),content:<Inspector sections={[{id:"color",label:"Цвет без обводки и пипетка",content:<ControlRow label="Цвет"><ColorField label="Цвет материала" value={color} onChange={setColor}/></ControlRow>}]} defaultOpen={["color"]} header={<Description>Минимум 380 × 280. Пипетка берёт цвет с экрана после нажатия; Escape отменяет выбор. Нижняя кнопка не прокручивается.</Description>}/>}]}/>
|
||||
</EditorWorkspace>
|
||||
</div></>;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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 variant="default" displayName="DC" subtitle="Каталог компонентов" triggerLabel={null}
|
||||
actions={[{ id: "settings", label: "Настройки", icon: "settings", onSelect: () => setOpen(true) }]} />
|
||||
<Button variant="primary" tone="neutral" onClick={() => setOpen(true)}>Настройки окружения</Button>
|
||||
<Button variant="primary" tone="neutral" disabled>Неактивное действие</Button>
|
||||
</div>
|
||||
<div className="catalog-environment-stage"><LandingStage page={settings.pages.home} /></div>
|
||||
<EnvironmentSettingsWindow open={open} onClose={() => setOpen(false)} productName="Продукт"
|
||||
additionalSections={[{ id: "storage", label: "Хранилище", icon: "database", content: <p>Настройки хранения продукта используют общий каркас окна.</p> }]}
|
||||
surfaces={[{ id: "home", home: true, description: "Главная страница продукта", actions: [] }]}
|
||||
settings={settings} state="ready" error={null}
|
||||
onSave={async draft => { const next = { ...draft, revision: draft.revision + 1 }; setSettings(next); return next; }}
|
||||
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" };
|
||||
}} />
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {useState} from 'react';
|
||||
import {Button, Description, FeatureSettingsWindow, GlassSurface, Select, SettingsCard, StatusBadge, Switch, TextAreaField, TextField} from '@nodedc/ui-react';
|
||||
|
||||
/** Living acceptance fixture. All materials and control states come from the library. */
|
||||
export function MissionThemeExample() {
|
||||
const [open,setOpen]=useState(false);
|
||||
const [name,setName]=useState('Mission Core');
|
||||
const [enabled,setEnabled]=useState(true);
|
||||
const [mode,setMode]=useState('review');
|
||||
const fields=<div className="catalog-theme-fields">
|
||||
<TextField label="Название" value={name} onChange={event=>setName(event.target.value)}/>
|
||||
<TextAreaField label="Описание" defaultValue="Панель, группа и поле сохраняют собственные поверхности."/>
|
||||
<Select label="Режим" value={mode} options={[{value:'review',label:'Просмотр'},{value:'edit',label:'Редактирование'}]} onChange={setMode}/>
|
||||
<TextField label="Недоступное поле" value="Только чтение" disabled/>
|
||||
</div>;
|
||||
return <SettingsCard title="Фундамент Mission Core" description="Единая тёмная тема: поверхности, поля, действия и окна." actions={<Switch label="Включено" checked={enabled} onChange={setEnabled}/>}>
|
||||
{fields}
|
||||
<GlassSurface tone="group" padding="md" materialRim={false}>
|
||||
<TextField label="Элемент коллекции" defaultValue="Дополнительная ссылка"/>
|
||||
</GlassSurface>
|
||||
<StatusBadge tone="success">Сохранено</StatusBadge>
|
||||
<Button variant="primary" onClick={()=>setOpen(true)}>Открыть настройки</Button>
|
||||
<Description>Поля лежат прямо в SettingsCard; самостоятельный элемент коллекции использует тот же серый материал через GlassSurface tone="group".</Description>
|
||||
<FeatureSettingsWindow open={open} onClose={()=>setOpen(false)} title="Настройки темы" identity={{title:'Профиль',subtitle:'Mission Core',avatarLabel:'DC'}} sections={[{id:'appearance',label:'Оформление',group:'Общие'}]} activeSection="appearance" onSectionChange={()=>{}}>
|
||||
<SettingsCard title="Форма в окне" description="Тот же материал полей в портальном окне.">{fields}</SettingsCard>
|
||||
</FeatureSettingsWindow>
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { createModalController, createModalSizeController, renderPathBar } from '@nodedc/ui-dom';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import '@nodedc/ui-dom/styles.css';
|
||||
import { Button, Description, Icon } from '@nodedc/ui-react';
|
||||
|
||||
export function ModalSizeExample() {
|
||||
const overlay = useRef<HTMLDivElement>(null), dialog = useRef<HTMLDivElement>(null);
|
||||
const modal = useRef<ReturnType<typeof createModalController> | null>(null);
|
||||
const path = useRef<HTMLDivElement>(null);
|
||||
const saved = useRef({ width: 800, height: 500 });
|
||||
useEffect(() => {
|
||||
renderPathBar(path.current!, [{label:'Файлы',path:'',kind:'folder'},{label:'Изображения',path:'images',kind:'folder'},{label:'example.png',path:'images/example.png',kind:'file',current:true}], {onNavigate: () => {}, icon: kind => { const span=document.createElement('span'); span.innerHTML=renderToStaticMarkup(<Icon name={kind}/>); return span.firstElementChild!; }});
|
||||
const size = createModalSizeController({ dialog: dialog.current!, initialSize: saved.current, onSizeCommit: value => { saved.current = value; } });
|
||||
modal.current = createModalController({ overlay: overlay.current!, dialog: dialog.current!, onOpenChange: open => { if (open) size.refresh(); } });
|
||||
return () => { modal.current?.destroy(); size.destroy(); };
|
||||
}, []);
|
||||
return <><Button onClick={() => modal.current?.open()}>Окно с сохранением размера</Button>
|
||||
{createPortal(<div ref={overlay} hidden><div ref={dialog} className="nodedc-glass" aria-labelledby="modal-size-example-title">
|
||||
<header className="nodedc-window__head"><h2 id="modal-size-example-title" className="nodedc-window__title">Размер модального окна</h2></header>
|
||||
<div className="nodedc-window__body"><Description>Перетаскивание за края и углы. Для клавиатуры: фокус на шапке, Shift + стрелки. Повторное открытие сохраняет размер; уменьшение экрана не меняет предпочтение.</Description><div ref={path}/></div>
|
||||
<footer className="nodedc-window__footer"><Button onClick={() => modal.current?.close()}>Закрыть</Button></footer>
|
||||
</div></div>, document.body)}</>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useState } from "react";
|
||||
import { Button, Description, SettingsCard, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
|
||||
/** Catalog-only sample: verify host-size independence and centered/floating status copy. */
|
||||
export function OperationalTypographyDemo() {
|
||||
const [open, setOpen] = useState(false);
|
||||
return <>
|
||||
<SettingsCard title="Компактная типографика" description="Значения и секции — 13 px, пояснения — 12 px, заголовок окна — 18 px.">
|
||||
<h3>Подключение</h3>
|
||||
<div>192.168.1.1</div>
|
||||
<Description>Нет сведений о подключении.</Description>
|
||||
<Description role="alert">Не удалось получить ответ устройства.</Description>
|
||||
<Button onClick={() => setOpen(true)}>Проверить типографику окна</Button>
|
||||
</SettingsCard>
|
||||
<Window open={open} size="sm" title="Состояние подключения" onClose={() => setOpen(false)}
|
||||
footer={<WindowFooterActions><Button onClick={() => setOpen(false)}>Понятно</Button></WindowFooterActions>}>
|
||||
<Description role="status">Связь прервалась после приёма команды. Проверьте, выключился ли борт.</Description>
|
||||
</Window>
|
||||
</>;
|
||||
}
|
||||
@@ -61,6 +61,8 @@ export interface StoredLayout {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
};
|
||||
/** Design fragments are keyed by a registered Page Library type/version. */
|
||||
pageTypes?: Record<string, DesignProfilePageFragment>;
|
||||
|
||||
@@ -2,11 +2,12 @@ import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "@nodedc/ui-core/styles.css";
|
||||
import "./styles.css";
|
||||
import { TooltipProvider } from "@nodedc/ui-react";
|
||||
import { CatalogApp } from "./CatalogApp";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<CatalogApp />
|
||||
<TooltipProvider><CatalogApp /></TooltipProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
|
||||
@@ -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 {
|
||||
background: var(--nodedc-canvas);
|
||||
}
|
||||
@@ -1678,6 +1681,33 @@ textarea {
|
||||
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 {
|
||||
align-content: stretch;
|
||||
}
|
||||
@@ -1754,6 +1784,14 @@ textarea {
|
||||
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 {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
@@ -2266,3 +2304,6 @@ textarea {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.catalog-theme-fields { display: grid; gap: var(--nodedc-space-4); }
|
||||
|
||||
.catalog-viewport-actions {position:absolute;top:var(--nodedc-space-3);right:var(--nodedc-space-3);display:flex;gap:var(--nodedc-space-2);padding:var(--nodedc-space-2);}
|
||||
|
||||
+93
-3
@@ -2,7 +2,7 @@
|
||||
|
||||
## Текущее состояние
|
||||
|
||||
Первый этап не меняет существующие приложения. Репозиторий фиксирует baseline и создаёт пакетный контракт. Это позволяет продолжать текущую разработку без одномоментной переделки Engine, Ops, BIM, CMS, SEO и Launcher.
|
||||
Пакетный контракт действует: CMS использует общие tokens, ui-core, ui-dom и ui-react, включая принятую тему Mission Core; Device Core использует общую шапку. Точные consumer pins и границы приведены ниже. Остальные приложения переводятся по отдельным проверенным этапам; наличие общего компонента не означает автоматическую миграцию всех consumer.
|
||||
|
||||
## Рекомендуемый порядок
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
### 3. CMS и SEO
|
||||
|
||||
Используют те же компоненты и механику окон. CMS подключает DOM-layer, SEO — React-layer. Первым общим admin pattern подключается `MediaSourceField`/`createMediaSourceController`; storage API остаётся в приложении. Цветовые различия оформляются theme overrides.
|
||||
Используют те же компоненты и механику окон. CMS уже подключает DOM-layer и контролируемые React islands; целевой слой SEO — React. Общий admin pattern `MediaSourceField`/`createMediaSourceController`; storage API остаётся в приложении. Цветовые сочетания определяются библиотечным theme preset, без локальных копий палитры.
|
||||
|
||||
### 4. Engine
|
||||
|
||||
@@ -62,7 +62,8 @@
|
||||
| --- | --- | --- | --- |
|
||||
| Launcher/Hub | React/local shared | React | header, button, dropdown, window |
|
||||
| SEO | React/local overrides | React | theme, window, field, select |
|
||||
| CMS | Vanilla DOM | DOM | theme, header, modal, select |
|
||||
| CMS | Пакеты + тонкий DOM/React adapter | Подключено, domain UI остаётся в CMS | Mission theme, shell/header, forms, modal, controls |
|
||||
| Device Core | Общий UserProfileMenu, pin 06cb8ad | Шапка подключена, формы без изменений | responsive profile, menu, avatar |
|
||||
| Engine | React/mixed generations | React | new inspector and environment settings only |
|
||||
| Ops | React/Plane packages | React | floating behavior and modal primitives |
|
||||
| BIM Viewer | Vanilla JS | DOM | tokens, glass select, settings surfaces |
|
||||
@@ -74,3 +75,92 @@
|
||||
- не поддерживать отдельную тему путём fork компонента;
|
||||
- не использовать legacy Engine inspector как промежуточный канон;
|
||||
- не удалять 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 не публиковался, исходники компонентов в приложение не копируются.
|
||||
|
||||
## DC CMS package adoption (2026-11-05)
|
||||
|
||||
DC_CMS now consumes the immutable npm distributions of tokens, ui-core, ui-dom
|
||||
and ui-react, pinned to a canonical source SHA plus package hashes in the
|
||||
consumer's `ui/design-system.lock.json`. Its build renders AppHeader,
|
||||
ApplicationShell, AdminNavigationPanel, ApplicationPanel and control templates
|
||||
from exports. Select, Switch, RangeControl, ProgressBar, StatusBadge and Dropdown
|
||||
run directly as controlled React islands. Core CSS and tokens are bundled once.
|
||||
|
||||
The thin compatibility adapter is `DC_CMS/ui/src/design-system.mjs`: it retains
|
||||
native CMS form/model bindings and listeners, adopts generated field/card/button
|
||||
anatomy, uses ui-dom modal/workspace controllers and connects MediaSourceField's
|
||||
DOM contract to the existing CMS file manager. Folder columns, editable block
|
||||
collections and knowledge content remain domain UI. No package source is copied
|
||||
or maintained as a local component fork. Remove this adapter as those domain
|
||||
renderers move to direct component composition. CMS CI rejects stale generated
|
||||
assets; the existing Git-to-canonical-runner deployment foundation is unchanged.
|
||||
|
||||
CMS visual follow-up, 2026-11-05: flat theme edges, neutral white default accent,
|
||||
UserProfileMenu with a session avatar and inbox glyph, FeatureSettingsWindow,
|
||||
ColorField, pill-shaped split Select, and the canonical six-dot DragHandle.
|
||||
UI preferences belong to authenticated per-user server metadata; site content and deployment
|
||||
credentials stay in the existing CMS model. Immutable npm snapshots retain
|
||||
package semver and are identified by source commit plus archive SHA-256.
|
||||
|
||||
CMS uses `UserProfileMenu`: profile label, menu icon, avatar.
|
||||
The menu opens settings; the application does not add a fourth action.
|
||||
|
||||
|
||||
Device Core and CMS share the complete `UserProfileMenu` header, not local copies.
|
||||
The reference composition is the existing rounded profile group in Launcher/Hub
|
||||
and Engine (`EnginePlatformHeader.tsx` / `TopBar.tsx`); its reusable geometry is
|
||||
already in AppHeader, HeaderProfileButton, IconButton and HeaderAvatar. The owner
|
||||
confirmed the order profile → inbox → avatar and settings inside the middle
|
||||
icon's menu on 2026-11-05. No application CSS overrides are needed.
|
||||
Device Core retains session identity, profile URL, permissions and logout actions.
|
||||
|
||||
|
||||
### 2026-11-05 — Mission dark foundation → CMS
|
||||
|
||||
Owner selected the running local Mission Core as the canonical dark reference.
|
||||
Source audit: b0332fa, styles/base.css and main.tsx; uncommitted simulation changes excluded.
|
||||
The complete Mission/flat preset now lives in tokens + ui-core, exported for React and DOM consumers.
|
||||
CMS consumes the immutable packages and retains only domain layout/event adapters.
|
||||
Nested forms use SettingsCard with a transparent layout grid and opaque fields; collection entries use GlassSurface group. The soft canvas is not a form-group material; no CMS palette.
|
||||
Mission Core itself remains on its existing local package state; its duplicated base overrides are recorded migration debt, not silently updated.
|
||||
|
||||
|
||||
### CMS form composition correction — 2026-11-05
|
||||
|
||||
Mission Core environment settings were verified in the running app: SettingsCard
|
||||
uses the neutral group material, its form grid is transparent, fields are opaque.
|
||||
CMS removes the extra field-grid surface and the card around the full list of
|
||||
content cards. Collection entries and native JSON disclosures adopt the shared
|
||||
GlassSurface group material. No local palette, field colors or business logic
|
||||
are introduced. The prior soft-canvas composition is superseded in THEMING and
|
||||
the living catalog; soft itself remains available for recessed non-form areas.
|
||||
|
||||
## CMS: размеры модальных окон
|
||||
|
||||
CMS подключает `createModalSizeController` из immutable ui-dom package, без копии resize-кода. Тонкий адаптер связывает `media-library` с серверным пользовательским GUI JSON; оформление и размеры записываются через аутентифицированный API. Медиатека остаётся привязанной к сайту, геометрия — к пользователю.
|
||||
|
||||
## CMS: строка пути файлов
|
||||
|
||||
CMS подключает `renderPathBar` и его stylesheet из ui-dom, source `1326ec6`,
|
||||
immutable archive `nodedc-ui-dom-0.7.0-modal.2.tgz`. Адаптер передаёт пути
|
||||
выбранного сайта, стандартный Icon и callback перехода в папку. Общий компонент
|
||||
владеет компактной строкой Finder, разделителями и нейтральными иконками.
|
||||
Сетка файлов, поиск и фильтрация по нескольким типам остаются доменной логикой
|
||||
CMS; переключатели используют общий IconButton. Проверены выбор глубокого
|
||||
пути, переход в каталог, dark/light и узкое окно 390 px.
|
||||
|
||||
## Общие подсказки · 2026-11-16
|
||||
|
||||
Mission Core подключает `TooltipProvider` из ui-react 0.7.1 один раз над приложением. BIM Mod 0.2.45 подключает его в переносимом workspace и переиспользует provider хоста. Существующие HTML `title` обрабатываются через общий портал, SVG-подсказки — через `data-nodedc-tooltip` с доступным именем `aria-label`. Богатый контент использует `Tooltip`. Вложенные приложения не создают второй слой подсказок. Общий материал: скруглённое стекло без border, outline и декоративного rim; keyboard focus самих контролов сохраняется.
|
||||
|
||||
@@ -44,3 +44,7 @@ Modal остаётся portal-слоем. Его тело прокручивае
|
||||
- предметное содержимое content window.
|
||||
|
||||
Shell владеет геометрией, слоями, переходами и breakpoint-поведением. См. готовый путь подключения в `docs/CONSUMPTION.md`.
|
||||
|
||||
На узком экране скрывается именно действие `data-action="expand"`.
|
||||
Порядок utility actions не является признаком типа действия: плюс и обновление
|
||||
остаются доступны, даже когда стоят первыми в шапке. Исправлено при QA Node 0.3.
|
||||
|
||||
+336
-10
@@ -4,15 +4,18 @@
|
||||
|
||||
## GlassSurface
|
||||
|
||||
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал с blur и rim используется только у floating-слоёв: modal `Window` и portal-dropdown/select.
|
||||
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал используется у floating-слоёв и явно выбранных информационных плашек над 3D-сценой.
|
||||
|
||||
- `default` — обычная карточка/панель;
|
||||
- `strong` — dropdown, modal и поверхность над сложным фоном;
|
||||
- `soft` — вложенная или вторичная область.
|
||||
- `soft` — утопленная вторичная область / canvas, не подложка формы;
|
||||
- `group` — нейтральная группа как SettingsCard, для самостоятельного элемента коллекции.
|
||||
|
||||
`radius="pill"` задаёт каноническую капсульную геометрию через `--nodedc-radius-circle`. Она предназначена, в частности, для компактных вертикальных и горизонтальных реек из круглых действий: верхняя и нижняя части поверхности повторяют круг кнопок без прямых торцевых пролётов. Consumer не воспроизводит этот радиус локальным CSS.
|
||||
|
||||
Material rim допустим только как часть floating glass. Жёсткая цветная рамка, случайный browser outline или debug border не являются rim.
|
||||
|
||||
`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют только modal `Window` и modeless draggable Inspector; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную.
|
||||
`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют modal `Window`, modeless draggable Inspector и информационные плашки над 3D через `context="scene"`; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную.
|
||||
|
||||
## Button и IconButton
|
||||
|
||||
@@ -25,9 +28,25 @@ Button используется для всех текстовых действ
|
||||
|
||||
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
|
||||
|
||||
FieldFrame объединяет label, control, hint и description. TextField/TextAreaField реализуют стандартные текстовые поля.
|
||||
FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
|
||||
|
||||
Приложение не должно вручную собирать label и input, если подходит Field. Ошибка и validation state будут расширением этого контракта, а не локальным классом приложения.
|
||||
|
||||
@@ -39,7 +58,19 @@ FieldFrame объединяет label, control, hint и description. TextField/T
|
||||
|
||||
## 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 только при открытии и не отбирает фокус при последующих ререндерах.
|
||||
`RangeControl variant="rail"` — горизонтальный односторонний вариант тонкой шкалы среза: та же толщина `0.2 × --nodedc-control-height`, заполнение слева и текущее `formatValue` над шкалой. Общей подложки, стекла, рамки и тени нет; прозрачная область захвата не ниже 24 px. Native range сохраняет стрелки, Home/End, доступное имя и disabled; focus-visible подчёркивает значение. Точный ввод остаётся у обычного варианта `field`. Позиционирование в viewport и время показа задаёт приложение.
|
||||
|
||||
Вертикальная шкала занимает `0.2 × --nodedc-control-height` (9.2 px при 46 px), вдвое тоньше предыдущей. Прозрачная область захвата не уже 24 px.
|
||||
|
||||
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. `min/max` задают только рабочий диапазон перетаскивания; ручной ввод по умолчанию принимает любое конечное число и не меняет геометрию ползунка. Опциональный `exactValueBounds` независимо задаёт жёсткие границы ручного ввода: например, `{ min: 0 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком.
|
||||
|
||||
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
|
||||
|
||||
@@ -49,6 +80,10 @@ Engine/BIM-геометрия color field: круглый swatch и HEX-знач
|
||||
|
||||
## Dropdown
|
||||
|
||||
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. The same scope now supplies scene Glass V4 to control backgrounds (owner revision 2026-11-14). Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
|
||||
|
||||
`nodedc-scene-controls` is the compatibility alias for the same geometry and scene Glass V4 material. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
|
||||
|
||||
Dropdown владеет floating-layer поведением:
|
||||
|
||||
- рендерится в `document.body`;
|
||||
@@ -61,7 +96,7 @@ Dropdown владеет floating-layer поведением:
|
||||
- закрывается, когда trigger полностью уходит за границы viewport;
|
||||
- закрывается по outside pointer и Escape;
|
||||
- после Escape возвращает фокус на реальную trigger-кнопку, не закрывая родительское окно;
|
||||
- закрывает другой открытый dropdown.
|
||||
- закрывает другой корневой dropdown; вложенный Select сохраняет родительское меню, выбор закрывает только Select, Escape закрывает самый глубокий слой.
|
||||
|
||||
Содержимое меню передаётся приложением. Selection, action menu и filter menu используют один engine.
|
||||
|
||||
@@ -69,15 +104,20 @@ Dropdown владеет floating-layer поведением:
|
||||
|
||||
## Select
|
||||
|
||||
Select добавляет к Dropdown контролируемое значение, options и необязательный поиск. У него две канонические формы:
|
||||
Select добавляет к Dropdown контролируемое значение, options и необязательный поиск. У него три канонические формы:
|
||||
|
||||
- `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`.
|
||||
|
||||
Внутри `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 — единая механика открытия modal и правой panel:
|
||||
@@ -89,8 +129,14 @@ 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 автоматически.
|
||||
|
||||
DOM: `createModalSizeController({dialog, initialSize, minimum, onSizeCommit})` дополняет `createModalController` изменением размера за восемь краёв/углов. Шапка получает клавиатурный resize через Shift + стрелки. `setSize` восстанавливает сохранённый размер, `refresh` подгоняет окно после открытия. Подгонка под экран и pointercancel не записывают новое предпочтение. Контроллер не меняет modal/focus contract; приложение хранит размер отдельно для текущего пользователя. Живой пример: «Размер DOM-окна».
|
||||
|
||||
## WorkspaceWindow
|
||||
|
||||
`WorkspaceWindow` — modeless-окно внутри рабочей сцены приложения. Оно рендерится непосредственно в переданном workspace, не использует portal и не может перекрыть шапку, навигацию или соседние панели за пределами этого workspace.
|
||||
@@ -139,6 +185,20 @@ Enter при отсутствии совпадения разрешает оди
|
||||
|
||||
ConfirmationModal оборачивает Window и защищает async-confirm от повторного запуска. До завершения операции закрытие можно заблокировать.
|
||||
|
||||
## SplitPane
|
||||
|
||||
Невидимый разделитель остаётся прозрачным при наведении и pointer-resize, даже после ввода в текстовом поле. Клавиатурное изменение размера сохраняет видимый focus cue.
|
||||
|
||||
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
|
||||
|
||||
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
|
||||
|
||||
Вертикальная граница меняется мышью или клавишами `←/→`, горизонтальная — `↑/↓`; `Home/End` переходят к разрешённым границам, а `Shift` ускоряет клавиатурный шаг. Доля сохраняется при resize контейнера. Минимальные проценты обеих панелей применяются одинаково к pointer и keyboard interaction.
|
||||
|
||||
Разделитель является структурной границей между двумя рабочими представлениями и не создаёт декоративную рамку вокруг контента. При `resizable={false}` панели сохраняют ту же стабильную DOM-композицию, а separator полностью отсутствует в визуальном слое и accessibility tree; это позволяет приложению сворачивать одну из панелей без remount тяжёлого renderer.
|
||||
|
||||
При `separatorAppearance="invisible"` линия скрыта в покое, при наведении и перетаскивании. Зона захвата, курсор, клавиатурное изменение размера и индикатор клавиатурного фокуса сохраняются.
|
||||
|
||||
## ShareAccessModal
|
||||
|
||||
Workflow-sharing modal из нового Engine: заголовок ресурса, compact avatar stack, список участников, редактирование ролей, удаление доступа, email и роль нового участника. Компонент сохраняет Engine-геометрию `600 px` и controls `46 px`, но не импортирует ACL API. Consumer передаёт members, permissions и callbacks.
|
||||
@@ -151,8 +211,14 @@ Read-only link/copy окно из BIM Viewer. React-компонент испо
|
||||
|
||||
## 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 приложения.
|
||||
|
||||
`size="dense"` применяется только в насыщенной панели слоёв или режимов непосредственно над viewer. Шапка приложения сохраняет default-геометрию; consumer не воспроизводит dense-отступы или шрифт локальным CSS.
|
||||
|
||||
## AppHeader
|
||||
|
||||
Трёхосевая верхняя панель:
|
||||
@@ -169,7 +235,14 @@ Pill navigation для верхней панели и компактного п
|
||||
|
||||
## UserProfileMenu
|
||||
|
||||
Каноническая выпадашка профиля для правой группы `AppHeader`. Она использует
|
||||
Каноническая правая группа `AppHeader`: «Профиль» → inbox → аватар.
|
||||
`UserProfileMenu` владеет всей группой, включая `HeaderProfile`; приложение
|
||||
передаёт только identity и действия. Настройки находятся в меню, отдельной
|
||||
шестерёнки после аватара нет. Нельзя добавлять внешнюю обёртку или локальные
|
||||
отступы. Все три элемента открывают меню; Escape возвращает фокус на вызвавшую кнопку.
|
||||
На узком экране подпись скрывается по общей адаптивной механике; иконка и аватар остаются доступны.
|
||||
|
||||
Она использует
|
||||
общий portal `Dropdown`, показывает identity cover с аватаром, именем и
|
||||
подписью и принимает список application-owned действий.
|
||||
|
||||
@@ -205,8 +278,14 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
Постоянные действия всего рабочего окна передаются через `ApplicationPanel.utilityActions` и всегда находятся в правой части шапки перед expand/close. Сохранение общего layout или настроек приложения — одно такое действие для всего окна; оно не дублируется внутри отдельных карточек и секций.
|
||||
|
||||
Переключение режима выбранного объекта может передать `pressed` в utility action: состояние получает `aria-pressed` и общую активную поверхность. Например, `info` открывает обзор текущей сохранённой сессии Mission Core.
|
||||
|
||||
Если заголовок и действия не помещаются в одну строку, шапка переносит действия на следующую строку с выравниванием вправо. Кнопки не обрезаются, заголовок сохраняет читаемую ширину. Состав действий одинаков в обычном и развёрнутом окне.
|
||||
|
||||
Точные состояния и размеры зафиксированы в `docs/APPLICATION_TEMPLATE.md`.
|
||||
|
||||
Внешняя область stage использует `overflow: clip`: скрытый сдвинутый stage не должен создавать горизонтальную прокрутку всего приложения при смене фокуса или работе с плавающим окном. Прокрутка предметного содержимого остаётся внутри соответствующей панели.
|
||||
|
||||
## MediaSourceField
|
||||
|
||||
Общий компонент Launcher/CMS для медиа-поля: file control, имя файла, URL input, переключатель `HD / URL`, круглое превью, path/hint/error. Один контракт применяется и для stage-видео, и для изображений/логотипов; тип файла, подписи и preview задаёт consumer. Публичный API контролируемый.
|
||||
@@ -217,6 +296,22 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
`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
|
||||
|
||||
Левая выезжающая панель Hub/Launcher. Библиотека владеет оболочкой `352 px`, радиусом `21.6 px`, внутренними отступами, full-bleed context/navigation pills, круглыми icon surfaces и анимацией появления. Приложение передаёт workspace/company, маршруты, active id и footer identity.
|
||||
@@ -225,6 +320,25 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
`AdminNavigationPanel` поддерживает сортируемые route-items через общий Drag & Drop contract. Приложение передаёт новый порядок id, а панель использует каноническую шеститочечную ручку Engine. Порядок не хранится отдельно внутри navigation-компонента.
|
||||
|
||||
### Сворачивание левой навигации — общий стандарт
|
||||
|
||||
Все левые `AdminNavigationPanel` имеют круглую стрелку рядом с крестиком.
|
||||
В компактном состоянии остаются круги с иконками и стрелка вправо: заголовок,
|
||||
подписи, крестик и вторичные действия скрыты, в том числе от клавиатурного фокуса.
|
||||
Иконки сохраняют доступные имена, выбранный маршрут и Tooltip при наведении/фокусе.
|
||||
Раскрытие возвращает контекстные селекторы, сортировку и дополнительные действия.
|
||||
|
||||
`ApplicationShell` синхронно сжимает колонку до `4.55rem` и расширяет рабочую область
|
||||
на канонической кривой анимации оболочки; содержимое workspace не перемонтируется.
|
||||
Состояние общее для переходов между разделами и открытия/закрытия рабочих поверхностей.
|
||||
Для управляемого состояния: `navigationCollapsed`, `onNavigationCollapsedChange`;
|
||||
начальное — `defaultNavigationCollapsed`. Без shell панель поддерживает `collapsed`,
|
||||
`defaultCollapsed`, `onCollapsedChange`. Приоритет внутри shell принадлежит shell.
|
||||
Библиотека не пишет в localStorage: долговременная персонализация принадлежит приложению.
|
||||
`collapseLabel`/`expandLabel` локализуют подписи. Footer с каноническим
|
||||
`nodedc-admin-panel__nav-icon` сохраняет только этот круг. Right/end panel не сужается.
|
||||
Reduced motion отключает анимацию. На узком экране сохраняется один активный экран.
|
||||
|
||||
## ApplicationSidePanel
|
||||
|
||||
`ApplicationSidePanel` — правая application-level пара к `AdminNavigationPanel`.
|
||||
@@ -249,6 +363,8 @@ variant="panel"`: accordion сохраняет свой layout-state, а его
|
||||
|
||||
`DragHandle`, `DragDropRoot`, `DraggableItem`, `DropZone`, `SortableScope`, `SortableItem` и `SortableList` образуют общий React-контракт переноса и сортировки. Он перенесён из рабочего Engine-паттерна: drag начинается только за шесть точек и только после движения на `6 px`, поэтому обычный клик по строке не конфликтует с навигацией.
|
||||
|
||||
`DragDropRoot.renderOverlay` включает portal-превью переноса поверх прокручиваемого списка. Исходная строка остаётся на месте. Escape/отмена снимают превью без назначения. `DragDropResult.pointer` содержит client-координаты отпускания для точного picking внутри canvas; проверка объекта остаётся у renderer. Существующие потребители без renderOverlay сохраняют прежнее поведение.
|
||||
|
||||
Sortable-строки ограничены вертикальной осью: горизонтальное движение указателя не сдвигает navigation или composition layout. `DragDropRoot` возвращает реальные active/over rectangles, поэтому consumer может принять перенос только после достаточного перекрытия destination. Module Foundry использует порог `20%` ширины переносимой строки: короткое движение, движение влево или касание границы не создаёт page instance.
|
||||
|
||||
В Module Foundry исходная строка Page Template остаётся в Page Library после переноса. Каждый подтверждённый drop создаёт новый page instance с уникальным id; состав приложения и левая навигация читают один массив страниц и потому всегда перестраиваются синхронно. Удаление instance выполняется стандартным `ConfirmationModal`, а не мгновенным действием крестика.
|
||||
@@ -263,14 +379,21 @@ Sortable-строки ограничены вертикальной осью: г
|
||||
|
||||
Статус использует semantic tone: neutral, success, warning, danger или accent. Бизнес-статус приложения маппится на tone в самом приложении.
|
||||
|
||||
`pulse` добавляет пульсацию только лампы, не текста и не фона. Подходит для потери подтверждения или другого состояния, требующего внимания. При `prefers-reduced-motion: reduce` лампа остаётся постоянной. Текст статуса обязателен рядом с отдельным индикатором или в самом badge.
|
||||
|
||||
## 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
|
||||
|
||||
Единая accordion-панель для settings и definition controls. Источник — только новый Environment Settings и NDC Agent Inspector.
|
||||
|
||||
Inspector принимает `header` для полей перед секциями и `footer` для действий после них.
|
||||
Поля header и соседние секции разделяет `--nodedc-space-3` (12 px); footer
|
||||
центрирует действия. Вложенные Inspector сохраняют тот же шаг. Это общий контракт,
|
||||
а не локальные margin-правки потребителя. Вариант `panel` сохраняет компактные строки.
|
||||
|
||||
Inspector владеет:
|
||||
|
||||
- заголовками разделов;
|
||||
@@ -287,3 +410,206 @@ 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 продолжает владеть определениями полей, типами нод и сохранением значений. В живом 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.
|
||||
The outer 24 CSS pixels of the visible workspace dock across its whole side, including
|
||||
when the pointer is over the source panel. The remaining tree keeps its relative layout.
|
||||
This zone is capped at 8% per axis on small surfaces; it takes precedence over panel zones.
|
||||
The preview labels the scope as «Вся область». Outside drops still cancel.
|
||||
`DockMove.scope="workspace"` selects this operation; omitted/`panel` retains local docking.
|
||||
The serialized `DockTree` is unchanged. `dockMoveAtPoint` resolves both hit-test scopes.
|
||||
Removing the source collapses its old empty branch. The contour uses the resulting tree,
|
||||
so it previews the actual final position, even when the destination expands after removal.
|
||||
Any number of available panels can be composed with nested horizontal and vertical splits.
|
||||
`focusedId` expands a view without reparenting media; the application persists `tree`.
|
||||
There is no permanent outline. Outside drops, local self drops and Escape leave the tree unchanged.
|
||||
Keyboard: Enter/Space on the grip, Tab/Shift+Tab to choose a destination, arrows for edges,
|
||||
Home for center, Shift+arrows for a whole-workspace edge, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing.
|
||||
|
||||
The pure tree types, geometry and operations are exported by `@nodedc/ui-core`; React re-exports them for view consumers. Domain adapters import the framework-neutral package.
|
||||
|
||||
## 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.
|
||||
|
||||
Use `Description role="status"` for explanatory pending/result copy. Unclassed
|
||||
paragraphs in a `SettingsCard` body inherit this same contract as a compatibility
|
||||
safeguard, even inside layout groups. New consumers must use `Description`.
|
||||
This safeguard does not restyle headings, controls or explicitly styled data.
|
||||
|
||||
## ComparisonTable
|
||||
|
||||
`ComparisonTable` accepts a heading, entity columns and labelled rows. Semantic headers, a 9rem minimum per column and horizontal overflow preserve 1–N comparisons in narrow panels. The keyboard scrollport contains wheel overscroll; no borders or cards per entity. Data freshness stays application-owned.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
### Window free mode
|
||||
|
||||
`Window` and composed `FeatureSettingsWindow` expose the move toggle by default for centered placement. It removes the backdrop and enables bounded header drag and border/corner resize without remounting the form. Return restores canonical modal geometry. Use arrow keys on the floating header to move; Shift+arrows resize. `allowFloating={false}` is available for workflows that explicitly require a fixed modal. Inspectors stretch within window content. See WINDOWS_AND_LAYERS.md for focus, portal and lifetime rules.
|
||||
|
||||
### Tree · compact outliner
|
||||
|
||||
Visibility is independent of disclosure. Data/eye updates never re-open selected ancestors or scroll to an old selection. Disclosure uses its arrow (or ArrowLeft/ArrowRight), preserves the scroll position, and does not expand on row double-click. Only a new external selected ID/revealKey requests automatic reveal; asynchronous nodes can complete that pending request.
|
||||
|
||||
`Tree` accepts stable `TreeNode` IDs, a selected ID and `onSelect`, optional query and visibility callback. Rows stay on one line with ellipsis. Selection reveals ancestors and scrolls only the tree, avoiding page/camera jumps. Arrow keys, Home/End, Enter/Space support navigation. Use the canonical `Window resizable initialRect` for a movable object outliner.
|
||||
|
||||
`Window` end inspectors can opt into `resizable`; the same eight-edge geometry and header Shift+arrow keyboard sizing are used. Existing windows keep their defaults. `DraggableItem` also exposes `activator.attributes` and `activator.listeners` to attach directly to a tile button; separate handles remain the default for existing consumers.
|
||||
|
||||
## Scene overlays and viewport height
|
||||
|
||||
`GlassMaterialSurface context="scene" radius="panel"` reuses V4 tint, blur/saturation/brightness with independent scene opacity (52%) and blur (18 px). Mission appearance cannot turn it into the 97%-opaque modal. Use only over rendered imagery, keep telemetry hit areas interactive for page scrolling and leave empty overlay space transparent to scene input. No decorative rim is added in Mission appearance.
|
||||
|
||||
`ResizableViewport` owns two visible bottom grips, controlled `height`, `minHeight`, `maxHeight`, `onHeightChange` and `onHeightCommit`. Drag uses pointer capture; keyboard Up/Down moves 10 px, Shift 50 px, Home/End selects limits. Owner persists on commit per view. The viewer remains in document flow, so heights larger than the available area scroll normally. Grip strokes are structural resize indicators; focus is canonical.
|
||||
|
||||
`ApplicationPanel allowFullscreen` makes `useApplicationPanelFullscreen()` available to owned viewer actions. Fullscreen moves the whole panel including its one header above the app stage. Canvas identity is preserved by atomic DOM move; modeless inspectors remain above it. Restore/back/close leaves no detached panel. This is application full-window presentation, not browser fullscreen, so body portals remain usable.
|
||||
|
||||
`ResizableViewport resizeIndicator={false}` hides the resize strokes and hover surface. Only the pointer cursor changes; keyboard focus remains accessible. Pointer capture does not force focus, avoiding a focus ring after mouse drag.
|
||||
|
||||
`SceneAnnotation` is a transparent canonical ghost button for projected scene data. Renderer supplies screen coordinates, culls offscreen/hidden objects and owns identity; click, Enter and Space activate the same selected state. Use stacked object name/value and never fabricate sensor fields.
|
||||
|
||||
ColorField keeps a local HEX draft so deletion and replacement work with strict controlled values. Six hexadecimal digits (optional #) apply live; blur/Enter normalize valid input or revert incomplete input. Escape cancels the draft. External value changes, including undo, synchronize the displayed text.
|
||||
|
||||
`GlassMaterialSurface` accepts `material: GlassMaterialSettings` and optional `radiusPx` for operator-customizable overlays. Variables are scoped to that instance; scene tint opacity and blur use the scene context, without mutating modal or global appearance.
|
||||
|
||||
Exact `RangeControl` editors synchronize external controlled-value changes while focused, so undo/redo is visible immediately and subsequent blur cannot reapply an obsolete draft.
|
||||
|
||||
Window: `rect` / `onRectCommit` — восстановление и фиксация геометрии инструментов; см. WINDOWS_AND_LAYERS.md. Иконка `minus` дополняет `plus` для управления масштабом содержимого.
|
||||
|
||||
`EditorDockLayout` / `EditorWorkspace`: переносимый редактор с закреплённым основным видом, четырьмя зонами стыковки, разделителями и отрываемыми панелями. Управляемый `EditorDockState` хранится в документе приложения. Шапка редактора не участвует в стыковке; возврат восстанавливает исходный вид. Контракт, keyboard и минимумы — в WINDOWS_AND_LAYERS.md.
|
||||
|
||||
Размер поясняющего текста `Description` можно задать через
|
||||
`--nodedc-description-font-size`; по умолчанию используется `--nodedc-font-size-sm`.
|
||||
|
||||
Window header actions default to before the move toggle. `headerActionsPlacement="before-close"` places supplied canonical IconButtons between move and close, preserving DOM/Tab order. Deletion confirmation remains application-owned content in the same mounted Window.
|
||||
|
||||
|
||||
## Tooltip
|
||||
|
||||
Общий стандарт: скруглённое стекло Scene Glass без декоративной рамки, outline и обводки. `TooltipProvider` подключается один раз на корне приложения и заменяет браузерные квадратные подсказки `title`, в том числе в старых экранах. Вложенный переносимый модуль использует уже установленный provider. Rich-content `Tooltip` сохраняет собственный триггер; две подсказки одновременно не появляются. `aria-describedby`, клавиатурный фокус, Escape, fullscreen и положение у границ окна сохраняются.
|
||||
|
||||
Нейтральная подсказка с `content`, `children`, необязательными `label`, `focusable`, `disabled` и `placement`. Оборачивает триггер; `focusable` делает читаемую графику доступной клавиатуре, обычная кнопка сохраняет собственный фокус. Hover, focus и touch показывают один общий portal над окном; Escape закрывает подсказку, не родительское окно. Можно перевести курсор в подсказку. Позиция пересчитывается при scroll/resize, с общим clamp/flip. Не содержит действий: для меню используется Dropdown. Нет рамки, акцентных цветов или анимации при reduced motion.
|
||||
|
||||
Принят для запрошенных владельцем пояснений шкал сигнала,10.11.2026; приложение владеет диапазонами и текстом, общий компонент — формой и взаимодействием.
|
||||
|
||||
|
||||
Window, WorkspaceWindow, ApplicationPanel and AdminPanel establish an independent compact md text base, including portals. Native semantic headings inside operational surfaces use md unless an explicit canonical title rule applies. Use Description for result/error/pending paragraphs. The living catalog includes a typography example with values, nested headings and a status dialog. See OPERATIONAL_TYPOGRAPHY.md and the exported build-time `@nodedc/ui-core/typography` contract.
|
||||
|
||||
## Flat surface profile and profile trigger
|
||||
|
||||
The shared theme supports `edges: "flat"` for borderless surfaces, including portal windows. Keyboard focus changes the fill and foreground instead of adding an outline. The living catalog exposes this alongside the Mission appearance switch. `UserProfileMenu` composes the canonical profile label, independent inbox/menu button and avatar. CMS puts settings inside that menu. No additional settings button or HeaderProfile wrapper is needed; spacing comes from existing HeaderProfileButton and IconButton geometry.
|
||||
|
||||
`Select variant="split" shape="pill"` aligns a compact workspace/site selector with adjacent round actions, preserving the shared dimensions and keyboard behavior.
|
||||
|
||||
|
||||
## Mission Core theme foundation
|
||||
|
||||
`missionDarkTheme` и `missionLightTheme` — общий профиль из `@nodedc/ui-core` / `@nodedc/ui-dom`. `applyNodedcTheme` по умолчанию выбирает Mission и flat. Полный контракт цветов и композиции вложенных форм находится в [THEMING.md](THEMING.md). SettingsCard использует семантическую поверхность группы; поля расположены непосредственно в его body, как в Mission Core. GlassSurface tone="group" использует тот же материал для элементов коллекций. tone="soft" не применяется к формам. Ни CMS, ни другой потребитель не повторяет палитру локально. Living catalog содержит форму и её портальную версию.
|
||||
|
||||
## Viewport UI — правило владельца 14.11.2026
|
||||
|
||||
Все элементы интерфейса с подложкой внутри viewport используют общий Glass V4: карты, BIM, LAS/облака точек, 3DGS, PlayCanvas, камеры и replay. Поиск, отдельные кнопки прозрачного action rail, информационные плашки и меню относятся к этому правилу независимо от движка. Обычные панели вне viewport остаются matte. См. [контракт, применение и проверку](VIEWPORT_UI.md).
|
||||
|
||||
## PathBar (DOM)
|
||||
|
||||
`renderPathBar(target, items, {icon, onNavigate})` — компактная строка пути в стиле Finder: нейтральные иконки папок, текст и разделители `›`, без pill-кнопок. Подключается `@nodedc/ui-dom/styles.css`. Папки — клавиатурно доступные кнопки; конечный файл — текст с `aria-current`. Длинный путь прокручивается по горизонтали. Consumer передаёт пути и существующий Icon, хранение и навигация остаются в приложении. Живой пример: «Размер DOM-окна».
|
||||
|
||||
Toolbar `menuWidth` controls inspector menu width (default 220 px, bounded 180–600 px); Dropdown retains viewport clamping. Tree `renderActions(node)` supports per-item information menus without duplicating the outliner. `defaultExpandedDepth` limits initial expansion; selecting an item still reveals and scrolls to its ancestors. BIM uses canonical `ruler` (dimension line), `section` (model/plane), and `isolate` (temporary visibility) glyphs.
|
||||
|
||||
Open Dropdown surfaces observe content size changes and recompute their viewport bounds, including asynchronous property/volume results. Information triggers open on hover or explicit pointer/keyboard activation with `show`. Do not open on focus alone: Escape restores trigger focus and must keep the menu closed.
|
||||
|
||||
|
||||
EditorDockLayout rounds only the external corners of its complete tiled area using the shared panel radius. A left stack has a rounded top-left on its first pane and bottom-left on its last; a bottom row has only the outer lower corners. Internal joins remain square. Corners recompute after docking, closing, resizing or restoring panels. Floating tools retain all four window corners. The primary viewport follows the same outside-edge rule.
|
||||
|
||||
Viewport-scoped Toolbar buttons use the same scene Glass V4 material as the top viewport controls, preserving pressed, disabled and keyboard states. Its rail remains transparent. Compact Tree information actions use `info-plain` at 14 px beside the existing eye.
|
||||
|
||||
Tree supports optional controlled `selectedIds` for multi-selection. Its selection callback includes keyboard modifiers and the Shift range across displayed rows only. Consumers own set semantics and geometry identities; existing single-selection callers remain unchanged. Pointer and keyboard selection share the same path. Visibility and information actions do not alter the selection. The living Tree example demonstrates Shift range, Ctrl add and Command toggle.
|
||||
|
||||
|
||||
ColorField screen sampling (owner direction, 2026-11-14): the shared palette includes a Pipette action. In secure browsers supporting EyeDropper, click “Цвет с экрана”, then any screen pixel, including another application or desktop. Escape cancels without a change. Sampling never starts on pointer leave, never captures a screenshot, and is aborted when the control closes, disables or unmounts. Unsupported browsers expose “Системная палитра”; desktop sampling there depends on the native browser/OS picker. Palette/HEX remain usable regardless. This explicit fallback is the approved exception to the old no-native-dialog rule.
|
||||
|
||||
Floating EditorDockLayout tools honor minimumSize on restore, all eight resize edges and keyboard resize. If the available viewport is smaller, they fit that viewport; Inspector fields stack below a 330px content width instead of clipping. Tool footer is separate from the scrolling body; a Button width="full" is the canonical adaptive bottom action. The catalog's scene editor example demonstrates minimum size, a ColorField and fixed reset footer.
|
||||
|
||||
EditorDockLayout: every floating or actively detached tool uses context="scene" Glass V4 (shared scene tint/blur); docking removes that context and retains tiled surface/corner rules. Applies to hierarchy, layers, settings and any other editor tool. No application tint/blur overrides.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# 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.
|
||||
|
||||
## Product sections (2026-11-08)
|
||||
|
||||
`additionalSections` accepts `{ id, label, icon, group?, content, footer? }`.
|
||||
Use unique IDs other than `environment`. Content and footer are product-owned;
|
||||
the shared shell retains navigation, focus, dragging, Escape and geometry.
|
||||
Environment drafts remain intact when switching sections. Each section owns its
|
||||
loading/error/saving states. No product API is called by the shared library.
|
||||
Mission Core uses this extension for the owner-requested Storage section.
|
||||
|
||||
The canonical `pin` icon is the Lucide Pin glyph. Pair it with IconButton and
|
||||
`aria-pressed` for pinned state; use a busy/disabled state during preparation.
|
||||
An absent local copy and an unpinned copy are separate states.
|
||||
@@ -29,6 +29,12 @@
|
||||
|
||||
Допустимы 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
|
||||
|
||||
Перед удалением export:
|
||||
@@ -54,3 +60,5 @@
|
||||
|
||||
У дизайн-системы должен быть явный code owner. Product team может предлагать компоненты, но общий API и theme contract проходят отдельное review, потому что изменение распространяется на все будущие приложения.
|
||||
|
||||
|
||||
Typography is a build gate, not a recommendation. See `OPERATIONAL_TYPOGRAPHY.md`: operational values/sections 13 px, descriptions/status/error copy 12 px, canonical window/page titles 18 px. Browser defaults, new local sizes and inline font overrides fail validation. The frozen compact legacy list cannot be expanded for new UI; exceptions require an explicit owner decision.
|
||||
|
||||
+31
-4
@@ -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 не делает иконку канонической.
|
||||
|
||||
## Геометрия
|
||||
@@ -16,15 +18,40 @@
|
||||
|
||||
| Группа | Канонические имена |
|
||||
| --- | --- |
|
||||
| Окно и слой | `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` |
|
||||
| Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external` |
|
||||
| Состояние и доступ | `check`, `alert`, `activity`, `lock`, `key`, `shield`, `circle` |
|
||||
| Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external`, `rotate-clockwise` |
|
||||
| Состояние и доступ | `check`, `alert`, `activity`, `lock`, `key`, `shield`, `circle`, `eye`, `eye-off` |
|
||||
| Сущности | `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`.
|
||||
|
||||
## Правило расширения
|
||||
|
||||
Новая иконка добавляется только после подтверждённого применения в продукте. Нужно выбрать семантическое имя, добавить 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`.
|
||||
|
||||
`power` — штатное выключение компьютера. Запрошено владельцем Mission Core 04.11.2026 для шапки окна «Бортовой компьютер». Используется в стандартном `IconButton` с доступной подписью; недоступность и выполняемое действие блокируют кнопку. Нажатие открывает `ConfirmationModal`; сам glyph не запускает выключение. Живой каталог получает иконку из `registry/icons.json`.
|
||||
|
||||
BIM controls use `ruler` (dimension line with extension lines/arrows), `section` (model intersected by a plane), `isolate` (temporary visibility/glasses), `perspective`/`orthographic` (projection cubes), and `fit-view` (frame extents). `info-plain` is an unframed i for compact tree actions next to the visibility eye; use 14 px for both glyphs. They share the canonical stroke and accessible control behavior.
|
||||
|
||||
Semantic references: [Revit measurement](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-Model/files/GUID-65EA44EC-C777-4C97-8718-5783C3A80B0A.htm), [temporary hide/isolate](https://help.autodesk.com/cloudhelp/2014/ENU/Revit-LT/files/GUID-A5E51D5E-8E18-4834-8A2F-8B4E3E6379A1.htm), [section box](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-GetStarted/files/GUID-C9EA51CB-3214-4BD8-AD55-3BEB1CCD15B6.htm). Glyphs are original monochrome NODE.DC vectors; this does not claim copied Autodesk artwork or full Section Box functionality.
|
||||
|
||||
@@ -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).
|
||||
@@ -0,0 +1,28 @@
|
||||
# LevelButton
|
||||
|
||||
Measured resource level inside the standard pill Button. Initial consumer: Mission
|
||||
Core battery state in the observatory header. Width is 2.5 canonical controls;
|
||||
height, focus, keyboard, disabled and hover grammar remain Button-owned.
|
||||
|
||||
`value` is a fraction in [0,1]; unknown/NaN has no fill and displays an em dash.
|
||||
`valueText` supplies the visible value; `label` names the resource. `freshness`
|
||||
is live, stale or unknown. Stale retains the reading, neutralises fill and adds
|
||||
accessible last-reading text. No animation, no fabricated progress, no nested
|
||||
interactive elements. `levelTone` uses semantic tokens, never a local palette.
|
||||
|
||||
Click opens domain details supplied by the consumer. The consumer decides which
|
||||
physical resource is selected; it must not average unrelated batteries or treat
|
||||
a stale number as fresh. Catalog includes normal, stale and unavailable states.
|
||||
|
||||
An explicit operator-selected `fillColor` (#RRGGBB) overrides semantic tint.
|
||||
The measured fraction clips a solid fill and a second, aria-hidden copy of its
|
||||
label. WCAG luminance chooses black/white text independently over the filled
|
||||
part, while the unfilled part keeps the normal theme text. Unknown has no fill;
|
||||
stale retains the chosen colour and its accessible stale label. Colour-range
|
||||
configuration belongs to the domain profile, not the visual component.
|
||||
|
||||
`geometry={{width, height, radius}}` задаёт операторские размеры с минимумом
|
||||
32 × 12 px. Ниже 64 × 24 текст и padding уменьшаются пропорционально
|
||||
ограничивающему размеру; длинная подпись также учитывается. Оба слоя текста
|
||||
наследуют одинаковые размеры. Без geometry сохраняется прежний размер Button.
|
||||
Внешний отступ от соседних действий остаётся ответственностью композиции шапки.
|
||||
@@ -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.
|
||||
@@ -1,7 +1,7 @@
|
||||
# Shared Cesium React adapter
|
||||
|
||||
`@nodedc/map-cesium-react 0.1.0` is the shared renderer boundary for the
|
||||
canonical `Map Page 0.1.0` and CesiumJS `1.143.0`.
|
||||
`@nodedc/map-cesium-react 0.1.2` is the shared renderer boundary for the
|
||||
canonical `Map Page 0.1.0` and CesiumJS `1.147.0`.
|
||||
|
||||
It is not a Foundry application component and does not own product navigation,
|
||||
Inspector fields, tokens, provider allowlists, TileCache storage or admin
|
||||
@@ -25,7 +25,7 @@ must not be used as a substitute for the `DC Default` treatment.
|
||||
|
||||
- The browser receives only same-origin BFF paths.
|
||||
- Runtime config must use `missioncore.map-runtime/v1`, Map Page `0.1.0` and
|
||||
Cesium `1.143.0`.
|
||||
Cesium `1.147.0`.
|
||||
- Canonical assets are fixed to imagery `2`, terrain `1` and buildings
|
||||
`96188`.
|
||||
- Provider endpoint documents must declare `credentialMode=gateway`.
|
||||
|
||||
+19
-2
@@ -231,9 +231,9 @@ Page/Visual/Application previews не содержат shipped domain fixtures.
|
||||
|
||||
Во внутренней sandbox-сборке Map Page временно скрывает визуальный credit overlay renderer, потому что он перекрывает рабочую композицию во время настройки шаблона. Метаданные provider attribution не удаляются из runtime. Перед любым внешним, пользовательским или коммерческим развёртыванием overlay должен быть возвращён в соответствии с условиями выбранного provider. Это зафиксированный технический долг, а не правило production-интерфейса.
|
||||
|
||||
## Cesium adapter 1.143
|
||||
## Cesium adapter 1.147
|
||||
|
||||
Текущий reference adapter использует CesiumJS `1.143.0`. Он загружается отдельным lazy chunk только при открытии Map Page и преобразует только declared Application bindings в реальные Cesium entities. Пустая Map Page не содержит domain entities.
|
||||
Текущий reference adapter использует CesiumJS `1.147.0`. Он загружается отдельным lazy chunk только при открытии Map Page и преобразует только declared Application bindings в реальные Cesium entities. Пустая Map Page не содержит domain entities.
|
||||
|
||||
Server-side runtime contract:
|
||||
|
||||
@@ -319,3 +319,20 @@ Data Plane, а не Map Template.
|
||||
факте для quality/diagnostics, но не образуют дополнительные UI-фильтры. Цвет,
|
||||
геометрия таргета, label и порядок фильтров остаются в Foundry presentation
|
||||
profile.
|
||||
|
||||
## Domain geometry in the existing renderer
|
||||
|
||||
`@nodedc/map-cesium-react` 0.1.1 adds optional `onSceneReady(context)`;
|
||||
Version 0.1.2 pins CesiumJS to **1.147.0**, retaining this callback contract. Existing consumers need no changes.
|
||||
`context` contains the existing `Cesium` namespace, renderer-owned `viewer`,
|
||||
and an abort `signal`. A consumer can attach ready domain geometry, pick
|
||||
objects and move the camera, returning synchronous cleanup for its own
|
||||
entities, primitives and listeners. Cleanup runs after abort and before
|
||||
viewer destruction, including provider toggles and renderer recovery.
|
||||
Asynchronous work must check the signal before attaching anything.
|
||||
|
||||
The callback must not create another Viewer, replace providers, introduce
|
||||
upstream credentials, or bypass the same-origin runtime/Map Gateway. Prepared
|
||||
BIM mesh residency, product leases, geometry budgets and project placement
|
||||
belong to the portable BIM consumer. The shared adapter retains sole ownership
|
||||
of imagery, terrain, buildings, network/cache intent and render recovery.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# 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.
|
||||
|
||||
`faceOpacity` (0–1, default 1) controls polygon fill only. It is independent of `edgeOpacity`, text and the legacy overall `opacity`; a transparent face remains a navigation target.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Компактная операционная типографика
|
||||
|
||||
Уточнение владельца 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.
|
||||
|
||||
Защита компонента: обычный `p` без класса внутри тела `SettingsCard` получает
|
||||
тот же стиль описания, включая вложенные группы. Это страховка для прежних
|
||||
потребителей, а не замена `Description` в новом коде. Статусы ожидания и
|
||||
пояснения вне карточки также используют `Description` с `role="status"`, если
|
||||
нужно объявление для скринридера. Заголовки, значения полей и кнопки сохраняют
|
||||
собственную типографику; глобальный стиль для всех `p` страницы не вводится.
|
||||
|
||||
|
||||
## Обязательная проверка сборки — 10.11.2026
|
||||
|
||||
Операционный UI имеет собственный базовый `md` (13 px), в том числе портальные
|
||||
`Window`, `WorkspaceWindow`, `ApplicationPanel` и `AdminPanel`. Размер body
|
||||
внешнего приложения не является контрактом. Корневой размер `html` не меняется:
|
||||
rem и пользовательское масштабирование остаются доступными. Семантические
|
||||
h1–h6 внутри этих поверхностей по умолчанию используют md, а явные канонические
|
||||
заголовки страницы/окна — title (18 px). Значения и заголовки секций — md;
|
||||
пояснения, ошибки, ожидание и результат команды — `Description` / sm (12 px).
|
||||
|
||||
Правило исполняется модулем `@nodedc/ui-core/typography` и обязательным
|
||||
`npm run test:typography` Design Guideline. Mission Core запускает
|
||||
`check:typography` перед сборкой Control Station и Node UI, а также в полном
|
||||
наборе unit-тестов. Проверяется исходный код всех экранов, общих пакетов и
|
||||
frontend-плагинов, а не только последний изменённый компонент.
|
||||
|
||||
Проверка запрещает новые локальные размеры вместо токенов, lg/title для данных,
|
||||
увеличивающие calc/clamp/em, font shorthand, inline fontSize и обычные p без
|
||||
явного класса. Сохранившиеся компактные значения старого UI (не более 13 px)
|
||||
зафиксированы по файлу, селектору и значению в `typography-policy.json`;
|
||||
добавлять туда новый UI запрещено. При изменении такого правила его переводят
|
||||
на токен, запись удаляют. Список не допускает крупных значений даже при ошибочном
|
||||
добавлении. Исключения перечислены отдельно с причиной и точным выражением:
|
||||
существующая обложка LandingStage, подписи в координатах SVG и управляемый
|
||||
пользователем масштаб сцены. Они не разрешают увеличивать текст рабочих панелей.
|
||||
Начальный размер значений батареи — 13 px; сохранённый пользователем масштаб
|
||||
3D-сцены не перезаписывается.
|
||||
|
||||
Изменение шкалы токенов, списка ролей или исключений требует явного решения
|
||||
владельца продукта и обновления живого каталога. Нельзя ослаблять проверку ради
|
||||
одного экрана, закрывать проблему локальным font-size или менять масштаб html.
|
||||
При приёмке проверяют computed font-size в обычном и плавающем окне, на узкой
|
||||
ширине, а также ожидание, ошибку, пустое состояние и результат команды.
|
||||
@@ -0,0 +1,18 @@
|
||||
# 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, на узком экране переносится ниже текста. Готовность не вычисляется
|
||||
компонентом. Каталог содержит завершённый, определённый и неизвестный прогресс.
|
||||
|
||||
Размер полосы задаётся опциональным `--nodedc-progress-height`; по умолчанию
|
||||
используется `--nodedc-space-2`. Плотность не меняет поведение и ARIA-состояния.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
+66
-50
@@ -1,66 +1,82 @@
|
||||
# Темы и цвет приложения
|
||||
|
||||
## Основное правило
|
||||
## Один фундамент
|
||||
|
||||
NODE.DC-приложения отличаются цветовой схемой, а не набором заново нарисованных компонентов. Тема задаёт значения CSS custom properties. Компоненты сохраняют геометрию, состояния и поведение.
|
||||
С 2026-11-05 основа тёмной темы — проверенный локальный Mission Core
|
||||
(`b0332fa`, `apps/control-station/src/styles/base.css`, работающий интерфейс
|
||||
`127.0.0.1:8000`). Цвета находятся только в `@nodedc/tokens/themes.css`,
|
||||
геометрия и состояния — в `@nodedc/ui-core`, компоненты — в `@nodedc/ui-react`.
|
||||
Приложение выбирает тему, а не повторяет цвета, селекторы или устройство компонентов.
|
||||
|
||||
## Что меняет тема
|
||||
```ts
|
||||
import {applyNodedcTheme, missionDarkTheme} from '@nodedc/ui-core';
|
||||
applyNodedcTheme(document.documentElement, missionDarkTheme);
|
||||
```
|
||||
|
||||
- canvas/background;
|
||||
- основной и вторичный текст;
|
||||
- accent и автоматически вычисляемый on-accent;
|
||||
- цвет непрозрачных application surfaces;
|
||||
- field/control surfaces;
|
||||
- overlay;
|
||||
- тени controls и modal material;
|
||||
- semantic success/warning/danger tones при необходимости.
|
||||
Те же exports доступны из `@nodedc/ui-dom`. `applyNodedcTheme(root)` по умолчанию
|
||||
выбирает `dark / mission / flat`. `missionLightTheme` сохраняет общую геометрию
|
||||
и даёт светлую тему. Установка на `document.documentElement` обязательна для
|
||||
приложения с порталами: меню и модальные окна получают тот же профиль.
|
||||
|
||||
## Что тема не меняет
|
||||
## Роли поверхностей
|
||||
|
||||
- высоту контролов;
|
||||
- радиусы по классам компонентов;
|
||||
- положение логотипа;
|
||||
- механику окна и dropdown;
|
||||
- DOM anatomy;
|
||||
- keyboard behavior;
|
||||
- расположение footer actions;
|
||||
- API React/DOM компонентов.
|
||||
| Роль | Тёмная тема | Компонент |
|
||||
| --- | --- | --- |
|
||||
| Фон приложения | `#050506` | ApplicationShell |
|
||||
| Рабочая сцена | `#08090b` | доменный viewport, token `--nodedc-stage` |
|
||||
| Панель | `#151517` | ApplicationPanel, AdminNavigationPanel |
|
||||
| Группа | нейтральный слой `110 110 110 / .07` | SettingsCard |
|
||||
| Элемент коллекции | нейтральный слой `110 110 110 / .07` | GlassSurface tone="group" |
|
||||
| Утопленная вторичная область | `#0d0d0f` | GlassSurface tone="soft", вне форм |
|
||||
| Поле | `#2a2a2c`, непрозрачное | TextField, TextAreaField, Select, MediaSourceField |
|
||||
| Модальное окно | `15 15 17 / .97` | FeatureSettingsWindow, Window |
|
||||
| Выпадающее меню | `15 15 17 / .98` | Dropdown, Select portal |
|
||||
| Основное действие | `247 248 244 / .96`; тёмный текст | Button |
|
||||
|
||||
## Presets
|
||||
ApplicationPanel → SettingsCard → поля — композиция, проверенная в работающих
|
||||
настройках Mission Core. Сетка полей прозрачная, без отдельной подложки и отступов.
|
||||
Самостоятельный элемент коллекции может использовать GlassSurface tone="group":
|
||||
тот же нейтральный материал SettingsCard, а не почти чёрный canvas-soft.
|
||||
Не добавлять карточку вокруг списка карточек или вокруг каждого поля; максимум
|
||||
два уровня групп сохраняют отличие непрозрачного поля от подложки.
|
||||
|
||||
В baseline включены `dark` и `light`. Это не два отдельных продукта, а примеры одного контракта:
|
||||
Исправление 2026-11-05: прежний пример с tone="soft" ошибочно переносил цвет
|
||||
вторичного canvas в формы. Значение soft сохранено для его исходной роли;
|
||||
приложения исправляют композицию, а не перекрашивают canvas локальным CSS.
|
||||
|
||||
- dark соответствует текущей основной семье Launcher/Hub/CMS;
|
||||
- light воспроизводит SEO-поверхности: `#ececec` canvas, белые панели и поля, тёмный текст, чёрные primary actions и мягкую тень у белых secondary controls;
|
||||
- конкретный продукт может поверх preset задать свой accent и surface variables.
|
||||
Основной/вторичный/приглушённый/недоступный текст использует оттенок
|
||||
`247 248 244` с непрозрачностью `.96 / .72 / .48 / .34`. Состояния hover,
|
||||
active, focus, disabled задаёт библиотека; приложения не переопределяют их.
|
||||
Hover поля использует собственный непрозрачный материал, а не полупрозрачную
|
||||
заливку кнопки: поле не исчезает при наведении.
|
||||
Декоративные рамки и контуры отсутствуют. Клавиатурный фокус остаётся видимым
|
||||
через контрастную заливку. Success/warning/danger сохраняют смысловые цвета
|
||||
индикаторов; цвет акцента не подменяет состояние ошибки.
|
||||
|
||||
## Accent
|
||||
## Акцент и настройки
|
||||
|
||||
Accent задаётся RGB tuple. On-accent вычисляется по luminance и не должен вручную прописываться белым или чёрным в отдельном компоненте.
|
||||
Базовый акцент тёмной темы — `247 248 244`, светлой — `24 25 28`.
|
||||
Пользовательский `accent` остаётся допустимой настройкой активных контролов.
|
||||
`on-accent` вычисляется библиотекой по яркости. Нейтральное основное действие
|
||||
остаётся нейтральным. Возврат к теме вызывает `clearNodedcAccent(root)`, затем
|
||||
`applyNodedcTheme`; удалять пользовательское значение без явного сброса нельзя.
|
||||
Материалы можно исследовать в каталоге; приложения не должны хранить собственный
|
||||
набор цветов для восстановления стандартной темы.
|
||||
|
||||
Default accent текущего NODE.DC shell — `#ff2f92`. `ColorField` открывает единый portal-picker с saturation/value plane, hue slider, HEX и быстрыми цветами — системный `input[type=color]` не является runtime UI. Изменение accent сразу меняет Environment Settings, active actions, range fill, media file action и theme-aware window states без создания новой темы или fork компонентов. Blur, gloss и material rim не наследуются application panels: это материал только для floating modal и portal-dropdown/select.
|
||||
В светлой теме canvas — `#ececec`, панели и поля — белые, группы и вложенные
|
||||
области — `#f4f4f4`. Белое поле различимо внутри группы.
|
||||
Map-glass остаётся отдельным светлым полупрозрачным материалом над изображением;
|
||||
он не заменяет обычную тему форм, панелей и портальных окон.
|
||||
|
||||
Semantic status не обязан совпадать с accent. Например, ошибка остаётся danger, даже если приложение использует красный брендовый accent.
|
||||
## Проверка и совместимость
|
||||
|
||||
## Область применения
|
||||
Living catalog: Controls → Mission Core. Проверяются вложенная форма, текст,
|
||||
select, textarea, disabled, переключатель, статус и то же содержимое в портальном
|
||||
окне; дополнительно проверяются клавиатура и обе темы. CMS использует этот же
|
||||
профиль и immutable npm-пакеты, не копию исходников компонентов.
|
||||
|
||||
Тема может быть установлена:
|
||||
|
||||
- на корневом `html/body` для всего приложения;
|
||||
- на контейнере embedded-модуля;
|
||||
- на catalog preview для сравнения схем.
|
||||
|
||||
Portal-компоненты рендерятся в `document.body`, поэтому приложение должно либо задавать тему на `document.documentElement`, либо передавать согласованные переменные на body. Локальная тема глубоко внутри React subtree не сможет автоматически охватить portal без отдельного theme portal root.
|
||||
|
||||
Map-glass overlays являются отдельной, независимой от application theme
|
||||
поверхностью поверх imagery. Их светлые translucent controls используют
|
||||
`--nodedc-map-glass-text`, а непрозрачное светлое поле поиска обязано брать
|
||||
тёмный foreground из `--nodedc-map-field-text` и placeholder из
|
||||
`--nodedc-map-field-text-muted`. Светлый field не наследует белый текст
|
||||
map-glass родителя. `ApplicationSidePanel`, напротив, находится вне imagery и
|
||||
всегда наследует обычные theme-aware application panel/text tokens; при смене
|
||||
dark/light она меняется синхронно с `AdminNavigationPanel`.
|
||||
|
||||
## Совместимость
|
||||
|
||||
Существующие `--nodedc-*` имена сохранены намеренно. Это уменьшает стоимость будущего подключения Launcher, Engine, Task Manager и BIM Viewer.
|
||||
`appearance: "default", edges: "default"` оставлены для явной совместимости
|
||||
со старой презентацией компонентов. Новые потребители используют Mission.
|
||||
Эта ревизия не меняет локальный Mission Core и его незакоммиченные эксперименты.
|
||||
Его прежние локальные CSS-дубли зафиксированы как миграционный долг: перенос
|
||||
зависимости требует отдельной проверки приложения, а не незаметной замены пакетов.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Интерфейс внутри viewport
|
||||
|
||||
Правило владельца от 14.11.2026. Любая подложка интерфейса поверх изображения viewport — общий **Glass V4**, тот же материал, что информационные плашки аппаратов. Правило одинаково для MapLibre/Cesium, IFC/BIM, point cloud/LAS, 3DGS, PlayCanvas, камер и replay; новые движки не создают новый материал.
|
||||
|
||||
## Применение
|
||||
|
||||
- Поиск, панели действий, легенды, статусы и плавающие плашки: `GlassMaterialSurface context="scene"`. `radius="panel"` для текста/поиска. У рейки круглых действий фон получают сами кнопки; общий контейнер остаётся прозрачным, без общей капсулы (уточнение владельца 14.11). На существующий семантический overlay разрешён DOM-контракт `className="nodedc-viewport-surface" data-glass-context="scene"`; позиционирование и радиус остаются у композиции.
|
||||
- `nodedc-viewport-controls` и совместимый `nodedc-scene-controls` сохраняют масштаб 0.7 и задают Glass V4 кнопкам, select и segmented. Нельзя оборачивать этим scope весь renderer ради изменения размеров текста.
|
||||
- Стекло меняет фон, а не opacity всей кнопки: иконки/текст сохраняют контраст. Общие scene tokens задают плотность 52% и blur 18px, отдельно от модальных окон. Настройки материала через публичный `material` contract; приложения не копируют blur/tint CSS.
|
||||
- Открытые Dropdown/Select/Window используют canonical floating Glass V4, в том числе при fullscreen portal. Hover, pressed, disabled, focus и видимость меню сохраняются. Активная кнопка может использовать существующую контрастную заливку: это состояние общего контрола.
|
||||
- Canvas, video, геометрия, текстуры/цвета модели, карта и содержимое изображения не покрываются стеклом. Полноэкранный пустой renderer/background не является плашкой. Обычный список, каталог и настройки за пределами viewport остаются matte.
|
||||
|
||||
## Эталон и проверка
|
||||
|
||||
Живой каталог → Glassy material: общий материал плашки и компактная панель управления над тем же фоном. Проверять на тёмном и светлом изображении, без наведения и при hover/focus, узком размере и fullscreen. Для BIM и центра наблюдения отдельно проверять реальные action rails; изменение CSS не является доказательством связи с устройством или работоспособности renderer.
|
||||
|
||||
Миграция начинается с BIM-карты/viewer и Центра наблюдения. Общий action scope охватывает существующие scene/map/replay controls; оставшиеся собственные подложки переводятся на тот же surface contract. Не создавать глобальную непрозрачную плашку вокруг всех viewports.
|
||||
|
||||
Уточнение 15.11.2026: все откреплённые панели `EditorDockLayout` (иерархия, слои, настройки и другие инструменты) автоматически получают `data-glass-context="scene"`. Материал действует уже во время отрыва/перетаскивания и после восстановления плавающего положения. Повторная стыковка возвращает материал и наружные углы tiled-панелей. Приложение не задаёт свои tint/blur/opacity.
|
||||
@@ -28,7 +28,7 @@
|
||||
7. trigger, полностью ушедший за viewport, закрывает surface;
|
||||
8. outside pointer и Escape закрывают surface;
|
||||
9. после Escape фокус возвращается на trigger;
|
||||
10. открытие другого dropdown закрывает предыдущий.
|
||||
10. открытие другого корневого dropdown закрывает предыдущий; вложенные меню сохраняют предков, а Escape закрывает только самый глубокий слой.
|
||||
|
||||
Inline absolute dropdown внутри card/sidebar/sticky container является дефектом.
|
||||
|
||||
@@ -115,3 +115,59 @@ map-glass дизайне, что Objects.
|
||||
Библиотека не создаёт глобальный store окон. Приложение владеет тем, какое окно открыто и какие данные в нём загружены. Библиотека владеет одинаковым поведением самого слоя.
|
||||
|
||||
Stack workspace-окон остаётся контролируемым приложением: оно передаёт active-state и `zIndex`, а компонент отвечает только за одинаковую геометрию и взаимодействие. Глобальный stack viewport-level modeless-окон остаётся отдельным будущим контрактом.
|
||||
|
||||
## Контекстные действия заголовка
|
||||
|
||||
`Window.headerActions` и `FeatureSettingsWindow.headerActions` принимают канонические `IconButton`. Обновление содержимого находится рядом с закрытием; сохранение и отмена формы остаются в footer. Слот входит в focus trap окна, а клики по действиям не начинают перетаскивание. Pending/disabled задаёт владелец данных; закрытие остаётся доступным.
|
||||
|
||||
На узком экране центрированное окно учитывает padding своего overlay с обеих сторон. В `FeatureSettingsWindow` меню занимает высоту содержимого, а оставшаяся высота отдана прокручиваемой форме. Проверочный пример «Настройки модуля» находится в живом каталоге окон; проверять в том числе на ширине 390 px.
|
||||
|
||||
FeatureSettingsWindow owns two independent scrollports. Its outer body is overflow-hidden; both navigation and content are min-height:0, overflow:auto, keyboard-focusable and overscroll-contained. Long left menus never move the right body. At narrow widths navigation remains capped and the content receives the remaining height.
|
||||
|
||||
Selecting a different settings section resets only its content scroll to the top; navigation keeps its position.
|
||||
|
||||
Docked content declares minimumSize for both axes. The divider stops at the recursive content boundary; a small overall viewport scrolls the layout canvas.
|
||||
|
||||
`DockLayout.panels[].preferredSize` задаёт начальный компактный размер. Продукт передаёт его только для новой раскладки без сохранённой геометрии; первый resize/dock сохраняет пользовательскую геометрию. Минимумы продолжают действовать при всех последующих размерах.
|
||||
|
||||
## Free-window mode for centered windows
|
||||
|
||||
A centered `Window` exposes the semantic `move` icon beside close (`allowFloating`, true by default). The toggle retains the mounted contents and captures their current dimensions. In floating mode the backdrop has no dimming or blur and passes interaction to the background; body scrolling and focus trapping are released. Drag the header or resize from any of the eight invisible border regions. No hover handles or decorative resize marks are drawn. Edges and corners expose their directional resize cursor; the movable header uses the move cursor. Keyboard users focus the header and use arrows to move or Shift+arrows to resize. Geometry is clamped on manipulation and viewport resize.
|
||||
|
||||
Turning the free mode off returns the same contents to the normal centered size and modal semantics. Turning it on again during the same opening restores the floating rectangle. Closing clears it. Portal ownership remains the active fullscreen element or body. Nested dialogs keep their own modal behavior. Inspector controls inside windows stretch to available width.
|
||||
|
||||
## Сохранённая геометрия инструментов
|
||||
|
||||
`Window.rect: WindowRect` и `onRectCommit` позволяют приложению хранить геометрию в своём документе. Для `placement="end" resizable` размеры и координаты восстанавливаются при открытии и при внешнем undo/import. Перетаскивание и resize обновляются локально; callback вызывается один раз при завершении жеста. Клавиатурный шаг тоже фиксируется. Автоматическое вписывание в уменьшенный экран не перезаписывает сохранённый прямоугольник. Без `rect` остаётся прежнее поведение `initialRect`. Пример дерева объектов в каталоге сохраняет прямоугольник между открытиями.
|
||||
|
||||
Действия уменьшения/увеличения содержимого палитр используют канонические `IconButton` с иконками `minus` / `plus` в `headerActions`, рядом с закрытием. Их прикладной масштаб хранится вместе с документом.
|
||||
|
||||
## Scene editor workspace and detachable tools
|
||||
|
||||
`EditorWorkspace` opens the same mounted content in a separate modeless editing window, then returns it to the original inline slot. Back, close and finishing editing share `onBack`; fullscreen is local to this editing window. The fixed header is not a docking target. The application retains its original view height, layout and camera document. The renderer host is moved atomically with `moveBefore` when available; canvas-based renderers remain mounted with the append fallback too.
|
||||
|
||||
`EditorDockLayout` receives `value: EditorDockState`, `onChange`, a locked `primary`, and typed `tools`. Tool descriptors supply title, open/close, content, actions, footer, minimum size and optional initial floating rectangle. The primary cannot detach. Each tool keeps its DOM host when docked, floating or temporarily hidden. The split tree, floating rectangles and any application-owned palette scale belong to the scene document, not a global library store.
|
||||
|
||||
Drag a tool header to any of four outer edges to create a full-side area; drop over another tool to split beside it. Drop in the primary center to detach. An exact destination preview is shown only during placement. A 24 px outer zone wins over panel targets; broader magnets reach 160 px horizontally / 96 px vertically, capped at 16% of the workspace. The center of a tool chooses its nearest side, never swaps it with the primary. Split minima protect content; small viewports scroll the bounded layout. Invisible floating edges resize, and only the cursor changes.
|
||||
|
||||
Header Enter/Space begins keyboard docking, arrows choose an edge, Shift+arrows choose the whole workspace, Tab selects a tool, Home selects floating, Enter commits and Escape cancels. Floating headers also accept arrows to move and Shift+arrows to resize. Pointer cancellation and Escape restore the uncommitted layout. Automatic viewport fitting does not overwrite stored rectangles. The living catalog includes the same workspace with a fixed scene, outliner and material palette.
|
||||
|
||||
When an EditorWorkspace detaches from a Window, the owning overlay is suspended
|
||||
without unmounting its children. Its backdrop and focus trap are inactive until
|
||||
the editor returns. Escape/Tab belong to the focused dialog, so nested settings
|
||||
close without also closing the battery/detail window.
|
||||
|
||||
|
||||
Portal typography is self-contained: Window text base is md/13 px, its title is title/18 px, and explanatory/status paragraphs use Description/sm/12 px. This stays identical in centered and floating modes and is independent of the host body size.
|
||||
|
||||
`EditorWorkspace purpose="view"` reuses the same stable host and docking grammar for viewers. Back/close return the mounted view to its inline slot; no edit-completion action is shown. Optional `headerActions` keeps application actions in the fixed window header. The default `purpose="edit"` preserves existing editors. The living docking example demonstrates both purposes.
|
||||
|
||||
Dock tool headings inherit the focused drag-header foreground, including title and subtitle, so the canonical inverted keyboard-focus fill retains readable text.
|
||||
|
||||
Keyboard-focused dock headers keep their action/close glyphs on the inherited contrast color, as well as title/subtitle.
|
||||
|
||||
Tool minimumSize governs floating and docked geometry alike, including restored JSON, pointer and keyboard resize. Screen bounds take priority when smaller. Put fixed bottom actions in EditorDockTool.footer; never append them to scrollable inspector content.
|
||||
|
||||
The primary scene owns an isolated stacking context so its toolbars stay behind floating tools. A tool outer shell clips without scrolling; only its body scrolls, keeping header/footer fixed even when a field receives focus.
|
||||
|
||||
ColorField spectrum has no decorative perimeter stroke; retain its visible sampling marker and keyboard focus. UserProfileMenu variant=header owns its HeaderProfile surface; consumers must not wrap it in another HeaderProfile.
|
||||
|
||||
Generated
+90
-58
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "nodedc-design-guideline",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "nodedc-design-guideline",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"workspaces": [
|
||||
"packages/*",
|
||||
"apps/*"
|
||||
@@ -28,9 +28,9 @@
|
||||
"version": "0.7.0",
|
||||
"dependencies": {
|
||||
"@nodedc/page-patterns": "0.1.0",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-react": "0.7.0",
|
||||
"cesium": "^1.143.0",
|
||||
"@nodedc/ui-core": "0.7.1",
|
||||
"@nodedc/ui-react": "0.7.1",
|
||||
"cesium": "1.147.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
@@ -325,36 +325,63 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@cesium/engine": {
|
||||
"version": "26.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/engine/-/engine-26.1.0.tgz",
|
||||
"integrity": "sha512-WzeJEcmGD7/htBJ8JEZt95OgZjErPwUHqyAlJY/mCzmDm7hfwpuucLBSUhiynWW3khqBT1C7dhibjb7tdic7oA==",
|
||||
"node_modules/@cesium/core": {
|
||||
"version": "0.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/core/-/core-0.1.1.tgz",
|
||||
"integrity": "sha512-2twC6bAYWdrJ4YVS2UPCpgkE7EZWHl+GVuh5n9IT6gVL9W9OYPas29Vh+wrUVI/9Hs8TeiNtis+Du2U9b+ce6A==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"earcut": "3.0.2",
|
||||
"mersenne-twister": "^1.1.0",
|
||||
"urijs": "^1.19.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@cesium/engine": {
|
||||
"version": "26.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/engine/-/engine-26.5.0.tgz",
|
||||
"integrity": "sha512-vpMuIOQ7QXNVrVTCCPWQ9y0zyfR+lhKLUOWt8XRCrDibtsASVpXGRFKQEdONf2D2EznIAQZ09sGOC8LwhvOeIQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@cesium/core": "^0.1.1",
|
||||
"@cesium/gltf": "^0.1.1",
|
||||
"@cesium/wasm-splats": "^0.1.0-alpha.2",
|
||||
"@spz-loader/core": "0.3.1",
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
"@zip.js/zip.js": "^2.8.1",
|
||||
"@zip.js/zip.js": "^2.9.0",
|
||||
"autolinker": "^4.0.0",
|
||||
"bitmap-sdf": "^1.0.3",
|
||||
"dompurify": "^3.3.0",
|
||||
"draco3d": "^1.5.1",
|
||||
"earcut": "3.0.2",
|
||||
"dompurify": "^3.4.14",
|
||||
"draco3d": "1.5.7",
|
||||
"grapheme-splitter": "^1.0.4",
|
||||
"jsep": "^1.3.8",
|
||||
"kdbush": "^4.0.1",
|
||||
"ktx-parse": "^1.0.0",
|
||||
"kdbush": "^4.1.0",
|
||||
"ktx-parse": "^2.0.0",
|
||||
"lerc": "^2.0.0",
|
||||
"mersenne-twister": "^1.1.0",
|
||||
"meshoptimizer": "^1.0.1",
|
||||
"meshoptimizer": "^1.2.0",
|
||||
"pako": "^3.0.0",
|
||||
"protobufjs": "^8.6.5",
|
||||
"protobufjs": "^8.8.0",
|
||||
"rbush": "^4.0.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"urijs": "^1.19.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
"node": ">=22.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@cesium/gltf": {
|
||||
"version": "0.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/gltf/-/gltf-0.1.1.tgz",
|
||||
"integrity": "sha512-tACM+dBXm+hXU4iyMynEK11ymce6GqUaB8TjF7jbtqBfxVYh45C2zBjNnv3ElpwhlwjLjwbc25zKZrO8oGYegw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@cesium/core": "^0.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@cesium/wasm-splats": {
|
||||
@@ -364,16 +391,17 @@
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@cesium/widgets": {
|
||||
"version": "16.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/widgets/-/widgets-16.1.0.tgz",
|
||||
"integrity": "sha512-c+jt8F3YIZs2x6+X+HS4q0S9nd2jVcbPVShUmlrDK1s+C7IlEvXceDGrkjivHRElAVCzfaWEEwY1g7Lg5HCGmA==",
|
||||
"version": "16.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/widgets/-/widgets-16.3.1.tgz",
|
||||
"integrity": "sha512-eyAGPYYL4v/WeLasmphRwxFcCl/qeTcRhncbBlOzMTSTLjgjZSea0IcEDCKC2ip/mHPeGe887X84xi1SV8mcEQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@cesium/engine": "^26.1.0",
|
||||
"@cesium/core": "^0.1.1",
|
||||
"@cesium/engine": "^26.5.0",
|
||||
"nosleep.js": "^0.12.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
"node": ">=22.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
@@ -1433,9 +1461,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@zip.js/zip.js": {
|
||||
"version": "2.8.26",
|
||||
"resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.8.26.tgz",
|
||||
"integrity": "sha512-RQ4h9F6DOiHxpdocUDrOl6xBM+yOtz+LkUol47AVWcfebGBDpZ7w7Xvz9PS24JgXvLGiXXzSAfdCdVy1tPlaFA==",
|
||||
"version": "2.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.25.0.tgz",
|
||||
"integrity": "sha512-oNRqUuU1XFu6G5d7Z0jufJ9dS9WteO0xiU/PNxsUrb4itZCsSbn191jpJzU00Gmc6S680X3DPZeF5EV4zAEMAg==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"bun": ">=0.7.0",
|
||||
@@ -1583,22 +1611,26 @@
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/cesium": {
|
||||
"version": "1.143.0",
|
||||
"resolved": "https://registry.npmjs.org/cesium/-/cesium-1.143.0.tgz",
|
||||
"integrity": "sha512-EHz61NBp/2UPYE4iWCZ+YK9Jcb0d2hzRfqkj4DRaUM3cJmA9hE2FTmcPPZ2iL7w+W0YUScI0gc9XeSTXlPIQtA==",
|
||||
"version": "1.147.0",
|
||||
"resolved": "https://registry.npmjs.org/cesium/-/cesium-1.147.0.tgz",
|
||||
"integrity": "sha512-gY5TF0rSyIMtnSIFHUuiHnrCuhdKaHUzLWFcjxytsdheKfKtYYOWicIWMypGjwYfnmJrgPgNF7HNjO9SK/JIkw==",
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
"packages/core",
|
||||
"packages/gltf",
|
||||
"packages/engine",
|
||||
"packages/widgets",
|
||||
"packages/sandcastle"
|
||||
],
|
||||
"dependencies": {
|
||||
"@cesium/engine": "^26.1.0",
|
||||
"@cesium/widgets": "^16.1.0",
|
||||
"protobufjs": "^8.6.5"
|
||||
"@cesium/core": "^0.1.1",
|
||||
"@cesium/engine": "^26.5.0",
|
||||
"@cesium/gltf": "^0.1.1",
|
||||
"@cesium/widgets": "^16.3.1",
|
||||
"protobufjs": "^8.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
"node": ">=22.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
@@ -1665,9 +1697,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.4.12",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.12.tgz",
|
||||
"integrity": "sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==",
|
||||
"version": "3.4.18",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.18.tgz",
|
||||
"integrity": "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
@@ -1873,12 +1905,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsep": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/jsep/-/jsep-1.4.0.tgz",
|
||||
"integrity": "sha512-B7qPcEVE3NVkmSJbaYxvv4cHkVW7DQsZz13pUMrfS8z8Q/BuShN+gcTXrUlPiGqM2/t/EEaI030bpxMqY8gMlw==",
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/jsep/-/jsep-1.6.0.tgz",
|
||||
"integrity": "sha512-Y8Tr54CX7B5YGAwo7/n8eumidEX3Opx98RyyQVnlHqUaZcPA8uUzL2v1rshr9ypW9Q6hNjfJtg3sL+8kaNE7TA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10.16.0"
|
||||
"node": ">= 20.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jsesc": {
|
||||
@@ -1914,9 +1946,9 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ktx-parse": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz",
|
||||
"integrity": "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==",
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-2.0.0.tgz",
|
||||
"integrity": "sha512-PW38i6SBZagE7c4yCYru636ICCkhJ8FNjOzAdjGkC65BZ0gElQJvFenSGc62SHFj5Fg0ft+U38PPhMZsWYQLCg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lerc": {
|
||||
@@ -1957,9 +1989,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/meshoptimizer": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.2.0.tgz",
|
||||
"integrity": "sha512-davRZeIJbxJrE24cwQle7ZDsxjdk/OphNOV83oX+efQinyoHY9Jcyz3MHbaoG0qySZajldGztNZ1RN/T19PZsg==",
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.3.0.tgz",
|
||||
"integrity": "sha512-2oZqMAcEEiCtXWUjIGtZ71oPx1B0ZxYGTqIKsXB1wzWFhleNsCFxQuUJzgCV706bRcwPWtMGf1odmQvAcqKkIw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ms": {
|
||||
@@ -2028,9 +2060,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/pako": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-3.0.1.tgz",
|
||||
"integrity": "sha512-GupotUUI0mlhugKjUs4bjOwLt3nrehy9Ys2dxC0GtgVef5cnKggkDMmf2bq2poCCuVXopWPmqsc9VDT2iJUy+w==",
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-3.0.3.tgz",
|
||||
"integrity": "sha512-tmrebBBYI5FOw8QICGwJNqE8fotC8R+gwcxOvoFNv+GKehOI6Lc6YBolNcQNnC4v96l1wt7rh102ifD4kVeZAQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -2093,9 +2125,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/protobufjs": {
|
||||
"version": "8.7.0",
|
||||
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-8.7.0.tgz",
|
||||
"integrity": "sha512-uu52JNxLh3vsL7tXU/h0gDaywufvuUCTbGSi0NKQKBZ2ZopkmrWQJSQO/EFqzu/5YhiwgVM8rq/a/iVpx4eZ0g==",
|
||||
"version": "8.8.1",
|
||||
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-8.8.1.tgz",
|
||||
"integrity": "sha512-d9e9179bjXSJdpJ3+R9fP8hzXsnKLyxTjHLG1dUzje8a27pPyXCe6PrcRtgx2rjoM3IZzHd2vAs+6J/BsO1k7Q==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"long": "^5.3.2"
|
||||
@@ -2462,9 +2494,9 @@
|
||||
},
|
||||
"packages/map-cesium-react": {
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.2",
|
||||
"dependencies": {
|
||||
"cesium": "1.143.0"
|
||||
"cesium": "1.147.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.1.0",
|
||||
@@ -2484,7 +2516,7 @@
|
||||
},
|
||||
"packages/ui-core": {
|
||||
"name": "@nodedc/ui-core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "0.6.0"
|
||||
}
|
||||
@@ -2493,17 +2525,17 @@
|
||||
"name": "@nodedc/ui-dom",
|
||||
"version": "0.7.0",
|
||||
"dependencies": {
|
||||
"@nodedc/ui-core": "0.7.0"
|
||||
"@nodedc/ui-core": "0.7.1"
|
||||
}
|
||||
},
|
||||
"packages/ui-react": {
|
||||
"name": "@nodedc/ui-react",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-core": "0.7.1",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
+22
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nodedc-design-guideline",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"description": "Canonical NODE.DC design system, reusable UI packages and living component catalog.",
|
||||
"type": "module",
|
||||
@@ -11,10 +11,11 @@
|
||||
"scripts": {
|
||||
"build": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react && npm run build --workspace @nodedc/ui-catalog",
|
||||
"build:packages": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react",
|
||||
"check": "npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test: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 test:typography && npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:tooltip && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock && npm run test:flat-theme && npm run test:mission-theme && npm run test:modal-size",
|
||||
"dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog",
|
||||
"serve": "node server/catalog-server.mjs",
|
||||
"validate:registry": "node scripts/validate-registry.mjs",
|
||||
"test:environment-settings": "node --test scripts/environment-settings.test.mjs",
|
||||
"test:platform-settings": "node scripts/smoke-platform-settings.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",
|
||||
@@ -31,9 +32,26 @@
|
||||
"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-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:inspector-select": "node --test scripts/inspector-select-contract.test.mjs",
|
||||
"test:range-control": "node --test scripts/range-control-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:split-pane": "node --test scripts/split-pane-contract.test.mjs",
|
||||
"test:dock-layout": "node --test scripts/dock-layout.test.mjs",
|
||||
"test:analysis-controls": "node --test scripts/analysis-controls.test.mjs",
|
||||
"test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs",
|
||||
"test:window-geometry": "node --test scripts/window-geometry.test.mjs",
|
||||
"test:editor-dock": "node --test scripts/editor-dock.test.mjs",
|
||||
"test:typography": "node --test scripts/operational-typography.test.mjs",
|
||||
"prebuild": "npm run test:typography",
|
||||
"test:flat-theme": "node --test scripts/flat-theme.test.mjs",
|
||||
"test:mission-theme": "node --test scripts/mission-theme.test.mjs",
|
||||
"test:modal-size": "node --test scripts/modal-size.test.mjs",
|
||||
"test:tooltip": "node --test scripts/tooltip-titles.test.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.2",
|
||||
"description": "Shared credential-free Cesium adapter for NODE.DC Map Page consumers.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
@@ -21,7 +21,7 @@
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"cesium": "1.143.0"
|
||||
"cesium": "1.147.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
|
||||
@@ -60,10 +60,13 @@ export const CesiumMapRenderer = forwardRef<
|
||||
className,
|
||||
onRuntimeStateChange,
|
||||
onCameraChange,
|
||||
onSceneReady,
|
||||
}, forwardedRef) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const stateCallbackRef = useRef(onRuntimeStateChange);
|
||||
const cameraCallbackRef = useRef(onCameraChange);
|
||||
const sceneCallbackRef = useRef(onSceneReady);
|
||||
sceneCallbackRef.current = onSceneReady;
|
||||
const runtimeRef = useRef<RendererRuntime | null>(null);
|
||||
const settingsRef = useRef(settings);
|
||||
const layersRef = useRef(layers);
|
||||
@@ -116,6 +119,7 @@ export const CesiumMapRenderer = forwardRef<
|
||||
const abortController = new AbortController();
|
||||
let disposed = false;
|
||||
let viewer: CesiumModule.Viewer | null = null;
|
||||
let disposeConsumer: (() => void) | void;
|
||||
let removeCameraListener: (() => void) | undefined;
|
||||
let removeRenderListener: (() => void) | undefined;
|
||||
let runtimeState = initialMapRuntimeState();
|
||||
@@ -191,6 +195,8 @@ export const CesiumMapRenderer = forwardRef<
|
||||
);
|
||||
removeRenderListener = bindRenderRecovery(viewer, publish);
|
||||
|
||||
disposeConsumer = sceneCallbackRef.current?.({Cesium, viewer, signal: abortController.signal});
|
||||
|
||||
const providerJobs = (["imagery", "terrain", "buildings"] as const).map(
|
||||
async (providerId) => {
|
||||
const visible = layers[providerId];
|
||||
@@ -265,6 +271,7 @@ export const CesiumMapRenderer = forwardRef<
|
||||
return () => {
|
||||
disposed = true;
|
||||
abortController.abort();
|
||||
try { disposeConsumer?.(); } finally {
|
||||
removeCameraListener?.();
|
||||
removeRenderListener?.();
|
||||
runtimeRef.current?.stopGhostPinAnimation?.();
|
||||
@@ -272,6 +279,7 @@ export const CesiumMapRenderer = forwardRef<
|
||||
viewer?.destroy();
|
||||
viewer = null;
|
||||
container.replaceChildren();
|
||||
}
|
||||
};
|
||||
}, [
|
||||
runtimeConfigUrl,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type * as Cesium from "cesium";
|
||||
export const MAP_RUNTIME_SCHEMA_VERSION = "missioncore.map-runtime/v1" as const;
|
||||
export const MAP_PAGE_VERSION = "0.1.0" as const;
|
||||
export const CESIUM_RENDERER_VERSION = "1.143.0" as const;
|
||||
export const CESIUM_RENDERER_VERSION = "1.147.0" as const;
|
||||
|
||||
export type MapProviderId = "imagery" | "terrain" | "buildings";
|
||||
export type MapProviderPhase = "idle" | "loading" | "ready" | "disabled" | "error";
|
||||
@@ -159,7 +160,16 @@ export type MapCacheIntent = {
|
||||
no_overwrite: boolean;
|
||||
};
|
||||
|
||||
/** A consumer may attach domain objects to this renderer-owned scene. It must
|
||||
* remove its objects/listeners in the returned synchronous cleanup. Pending
|
||||
* work must observe signal; it may never destroy the viewer or change providers. */
|
||||
export type MapSceneContext = {
|
||||
Cesium: typeof Cesium;
|
||||
viewer: Cesium.Viewer;
|
||||
signal: AbortSignal;
|
||||
};
|
||||
export type CesiumMapRendererProps = {
|
||||
onSceneReady?: (context: MapSceneContext) => (() => void) | void;
|
||||
runtimeConfigUrl: string;
|
||||
camera: MapCamera | null;
|
||||
layers: MapLayerVisibility;
|
||||
|
||||
@@ -7,6 +7,7 @@ export {
|
||||
export type {
|
||||
CesiumMapRendererHandle,
|
||||
CesiumMapRendererProps,
|
||||
MapSceneContext,
|
||||
MapCacheIntent,
|
||||
MapCamera,
|
||||
MapGeoPoint,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { DefaultProxy, Resource, VERSION } from "cesium";
|
||||
import { CESIUM_RENDERER_VERSION } from "../dist/contracts.js";
|
||||
import { applyCacheIntent, fetchMapRuntimeConfiguration } from "../dist/runtime.js";
|
||||
|
||||
test("installed Cesium and the runtime contract agree", () => {
|
||||
assert.equal(VERSION, CESIUM_RENDERER_VERSION);
|
||||
});
|
||||
|
||||
test("Cesium derived terrain and building resources retain the existing cache route", () => {
|
||||
for (const [root, child] of [
|
||||
["https://assets.ion.cesium.com/1/", "12/124/113.terrain?v=1"],
|
||||
["https://assets.ion.cesium.com/96188/tileset.json", "12/124/113.b3dm"],
|
||||
]) {
|
||||
const resource = new Resource({
|
||||
url: applyCacheIntent(root, { enabled: true, no_overwrite: true }, false),
|
||||
proxy: new DefaultProxy("/api/v1/map/gateway/cache?url="),
|
||||
});
|
||||
const derived = resource.getDerivedResource({ url: child });
|
||||
const proxied = new URL(derived.getUrlComponent(true, true), "http://127.0.0.1:8000");
|
||||
assert.equal(proxied.pathname, "/api/v1/map/gateway/cache");
|
||||
const upstream = new URL(proxied.searchParams.get("url"));
|
||||
assert.equal(upstream.searchParams.get("nodedc_cache_profile"), "live");
|
||||
assert.equal(upstream.searchParams.has("nodedc_cache_refresh"), false);
|
||||
assert.equal(upstream.searchParams.has("access_token"), false);
|
||||
assert.equal(upstream.pathname, new URL(child, root).pathname);
|
||||
}
|
||||
});
|
||||
|
||||
test("a mismatched renderer cannot silently start against another runtime release", async (t) => {
|
||||
const originalWindow = globalThis.window;
|
||||
globalThis.window = { location: { origin: "http://127.0.0.1:8000" } };
|
||||
t.after(() => {
|
||||
if (originalWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = originalWindow;
|
||||
});
|
||||
const configuration = {
|
||||
schema_version: "missioncore.map-runtime/v1",
|
||||
map_page_version: "0.1.0",
|
||||
renderer: { id: "cesium", version: CESIUM_RENDERER_VERSION },
|
||||
gateway: {
|
||||
configured: true,
|
||||
health_url: "/api/v1/map/gateway/health",
|
||||
asset_endpoint_template: "/api/v1/map/gateway/ion/assets/{asset_id}/endpoint",
|
||||
cache_proxy_prefix: "/api/v1/map/gateway/cache?url=",
|
||||
},
|
||||
assets: { imagery: 2, terrain: 1, buildings: 96188 },
|
||||
};
|
||||
t.mock.method(globalThis, "fetch", async () => Response.json(configuration));
|
||||
assert.equal((await fetchMapRuntimeConfiguration("/api/v1/map/runtime-config", new AbortController().signal)).renderer.version, CESIUM_RENDERER_VERSION);
|
||||
configuration.renderer.version = "1.143.0";
|
||||
await assert.rejects(fetchMapRuntimeConfiguration("/api/v1/map/runtime-config", new AbortController().signal), { code: "map_runtime_contract_mismatch" });
|
||||
});
|
||||
|
||||
test("project focus keeps its range and survives the persisted camera round trip", async () => {
|
||||
const C = await import("cesium");
|
||||
const scene = {
|
||||
drawingBufferWidth: 840, drawingBufferHeight: 461,
|
||||
mapProjection: new C.GeographicProjection(), ellipsoid: C.Ellipsoid.WGS84,
|
||||
mode: C.SceneMode.SCENE3D,
|
||||
screenSpaceCameraController: { minimumZoomDistance: 1, maximumZoomDistance: Infinity },
|
||||
};
|
||||
const camera = new C.Camera(scene);
|
||||
scene.camera = camera;
|
||||
camera.update(C.SceneMode.SCENE3D);
|
||||
for (const [lon, lat, height] of [[3.711, 51.065, 10], [37.58, 55.75, 160], [-97.736, 30.287, 180]]) {
|
||||
const target = C.Cartesian3.fromDegrees(lon, lat, height);
|
||||
camera.flyToBoundingSphere(new C.BoundingSphere(target, 160), {
|
||||
duration: 0, offset: new C.HeadingPitchRange(0, -Math.PI / 4, 600),
|
||||
});
|
||||
assert.ok(Math.abs(C.Cartesian3.distance(camera.positionWC, target) - 600) < 1e-5);
|
||||
const position = C.Cartographic.clone(camera.positionCartographic);
|
||||
const orientation = { heading: camera.heading, pitch: camera.pitch, roll: camera.roll };
|
||||
camera.setView({ destination: C.Cartesian3.fromRadians(position.longitude, position.latitude, position.height), orientation });
|
||||
const toward = C.Cartesian3.normalize(C.Cartesian3.subtract(target, camera.positionWC, new C.Cartesian3()), new C.Cartesian3());
|
||||
assert.ok(C.Cartesian3.dot(camera.directionWC, toward) > 0.999999);
|
||||
assert.ok(Math.abs(C.Cartesian3.distance(camera.positionWC, target) - 600) < 1e-5);
|
||||
}
|
||||
});
|
||||
@@ -1,14 +1,25 @@
|
||||
:root {
|
||||
--nodedc-field-hover-bg: color-mix(in srgb, var(--nodedc-field-bg) 94%, var(--nodedc-text-primary));
|
||||
--nodedc-neutral-action-bg: rgba(247, 248, 244, 0.96);
|
||||
--nodedc-neutral-action-hover: #fff;
|
||||
--nodedc-neutral-action-color: rgba(8, 8, 10, 0.96);
|
||||
--nodedc-neutral-action-disabled-bg: #757575;
|
||||
--nodedc-neutral-action-disabled-color: #242424;
|
||||
}
|
||||
|
||||
:root,
|
||||
[data-nodedc-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--nodedc-accent-rgb: 255 47 146;
|
||||
--nodedc-on-accent-rgb: 11 17 23;
|
||||
--nodedc-accent-rgb: 247 248 244;
|
||||
--nodedc-on-accent-rgb: 8 8 10;
|
||||
--nodedc-danger-rgb: 255 116 116;
|
||||
--nodedc-warning-rgb: 255 209 102;
|
||||
--nodedc-success-rgb: 181 255 90;
|
||||
|
||||
--nodedc-canvas: #050506;
|
||||
--nodedc-canvas-soft: #0b0b0d;
|
||||
--nodedc-canvas-soft: #0d0d0f;
|
||||
--nodedc-stage: #08090b;
|
||||
--nodedc-surface-group: rgba(110, 110, 110, 0.07);
|
||||
--nodedc-text-primary: rgba(247, 248, 244, 0.96);
|
||||
--nodedc-text-secondary: rgba(247, 248, 244, 0.72);
|
||||
--nodedc-text-muted: rgba(247, 248, 244, 0.48);
|
||||
@@ -74,14 +85,16 @@
|
||||
|
||||
[data-nodedc-theme="light"] {
|
||||
color-scheme: light;
|
||||
--nodedc-accent-rgb: 255 47 146;
|
||||
--nodedc-on-accent-rgb: 11 17 23;
|
||||
--nodedc-accent-rgb: 24 25 28;
|
||||
--nodedc-on-accent-rgb: 247 248 244;
|
||||
--nodedc-danger-rgb: 205 47 67;
|
||||
--nodedc-warning-rgb: 173 111 0;
|
||||
--nodedc-success-rgb: 46 125 76;
|
||||
|
||||
--nodedc-canvas: #ececec;
|
||||
--nodedc-canvas-soft: #f4f4f4;
|
||||
--nodedc-stage: #ececec;
|
||||
--nodedc-surface-group: #f4f4f4;
|
||||
--nodedc-text-primary: rgba(18, 20, 22, 0.96);
|
||||
--nodedc-text-secondary: rgba(18, 20, 22, 0.7);
|
||||
--nodedc-text-muted: rgba(18, 20, 22, 0.48);
|
||||
@@ -144,3 +157,24 @@
|
||||
--nodedc-modal-shadow: 0 24px 72px rgb(0 0 0 / var(--nodedc-modal-glass-shadow-light-opacity)), inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
--nodedc-floating-surface: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(255, 255, 255, 0.72)), rgba(255, 255, 255, 0.94);
|
||||
}
|
||||
|
||||
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] {
|
||||
--nodedc-modal-surface: rgb(15 15 17 / .97);
|
||||
--nodedc-floating-surface: rgb(15 15 17 / .98);
|
||||
--nodedc-primary-action-bg: rgb(247 248 244 / .96);
|
||||
--nodedc-primary-action-hover: rgb(255 255 255);
|
||||
--nodedc-primary-action-color: rgb(8 8 10 / .96);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
--nodedc-focus-surface: rgb(255 255 255 / .09);
|
||||
}
|
||||
|
||||
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] {
|
||||
--nodedc-modal-surface: rgb(247 248 250 / .97);
|
||||
--nodedc-floating-surface: rgb(247 248 250 / .98);
|
||||
--nodedc-primary-action-bg: rgb(24 25 28 / .96);
|
||||
--nodedc-primary-action-hover: rgb(8 8 10);
|
||||
--nodedc-primary-action-color: rgb(247 248 244);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
--nodedc-radius-circle: 999px;
|
||||
|
||||
--nodedc-control-height: 2.875rem;
|
||||
--nodedc-viewport-control-scale: 0.7;
|
||||
--nodedc-control-height-compact: 2.375rem;
|
||||
--nodedc-control-height-dense: 1.875rem;
|
||||
--nodedc-icon-button-size: 2.875rem;
|
||||
--nodedc-header-row-height: 3rem;
|
||||
--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-size-xs: 0.6875rem;
|
||||
--nodedc-font-size-dense: 0.45rem;
|
||||
--nodedc-font-size-sm: 0.75rem;
|
||||
--nodedc-font-size-md: 0.8125rem;
|
||||
--nodedc-font-size-lg: 1rem;
|
||||
@@ -69,3 +72,6 @@
|
||||
--nodedc-font-weight-medium: 620;
|
||||
--nodedc-font-weight-strong: 760;
|
||||
}
|
||||
|
||||
/* Readable V4 telemetry over moving scene imagery; independent of modal opacity. */
|
||||
:root { --nodedc-scene-glass-opacity: .52; --nodedc-scene-glass-blur: 18px; }
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
{
|
||||
"name": "@nodedc/ui-core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist",
|
||||
"styles.css"
|
||||
"styles.css",
|
||||
"typography.mjs"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -13,11 +14,13 @@
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./styles.css": "./styles.css"
|
||||
"./styles.css": "./styles.css",
|
||||
"./typography": "./typography.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"prebuild": "node --test ../../scripts/operational-typography.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "0.6.0"
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
/** 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 }
|
||||
/** Workspace moves ignore overId and wrap the remaining layout at its outer edge. */
|
||||
export interface DockMove { activeId: string; overId: string; position: DockPosition; scope?: "panel" | "workspace" }
|
||||
|
||||
export function dockIds(tree: DockTree | null): string[] {
|
||||
return !tree ? [] : "id" in tree ? [tree.id] : [...dockIds(tree.first), ...dockIds(tree.second)];
|
||||
}
|
||||
|
||||
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 || !ids.includes(activeId)) return tree;
|
||||
if (move.scope === "workspace") {
|
||||
if (position === "center" || ids.length < 2) return tree;
|
||||
const remaining = pruneDockTree(tree, ids.filter(id => id !== activeId))!;
|
||||
const before = position === "left" || position === "top";
|
||||
return {axis: position === "left" || position === "right" ? "x" : "y", ratio: 50,
|
||||
first: before ? {id: activeId} : remaining, second: before ? remaining : {id: activeId}};
|
||||
}
|
||||
if (activeId === overId || !ids.includes(overId)) return tree;
|
||||
const swap = (node: DockTree): DockTree => "id" in node
|
||||
? { id: node.id === activeId ? overId : node.id === overId ? activeId : node.id }
|
||||
: { ...node, first: swap(node.first), second: swap(node.second) };
|
||||
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";
|
||||
}
|
||||
|
||||
|
||||
/** Outer 24 CSS px take priority over the existing per-panel zones.
|
||||
* bounds is the visible workspace, expressed in the same coordinates as rects.
|
||||
*/
|
||||
export function dockMoveAtPoint(bounds: DockRect, rects: Readonly<Record<string, DockRect>>, activeId: string, x: number, y: number): DockMove | null {
|
||||
if (![x, y, bounds.left, bounds.top, bounds.width, bounds.height].every(Number.isFinite)
|
||||
|| !dockPosition(bounds, x, y) || !(activeId in rects) || Object.keys(rects).length < 2) return null;
|
||||
const zoneX = Math.min(24, bounds.width * .08), zoneY = Math.min(24, bounds.height * .08);
|
||||
const edges: [Exclude<DockPosition, "center">, number][] = [
|
||||
["left", (x - bounds.left) / zoneX], ["right", (bounds.left + bounds.width - x) / zoneX],
|
||||
["top", (y - bounds.top) / zoneY], ["bottom", (bounds.top + bounds.height - y) / zoneY],
|
||||
];
|
||||
const nearest = edges.sort((a, b) => a[1] - b[1])[0];
|
||||
if (nearest[1] <= 1) return {activeId, overId: activeId, position: nearest[0], scope: "workspace"};
|
||||
for (const [id, rect] of Object.entries(rects)) {
|
||||
const position = dockPosition(rect, x, y);
|
||||
if (position && id !== activeId) return {activeId, overId: id, position};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface DockMinimum { width: number; height: number }
|
||||
export type DockMinimums = Readonly<Record<string, DockMinimum>>;
|
||||
/** Propagate content limits through every ancestor, not only the nearest split. */
|
||||
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)!};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {decodeDockTree,dockIds,dockPosition,pruneDockTree,type DockTree,type DockRect,type DockMove} from './dockTree.js';
|
||||
|
||||
/** The primary view is permanent. Tools can leave the split tree without losing their identity. */
|
||||
export interface EditorDockState {tree:DockTree;floating:Record<string,DockRect>}
|
||||
export function decodeEditorDock(raw:unknown,primary:string,tools:readonly string[]):EditorDockState|null {
|
||||
if(!raw||typeof raw!=='object')return null;
|
||||
const value=raw as Partial<EditorDockState>,allowed=[primary,...tools];
|
||||
let tree=pruneDockTree(decodeDockTree(value.tree),allowed);
|
||||
if(!dockIds(tree).includes(primary))tree=tree?{axis:'x',ratio:70,first:{id:primary},second:tree}:{id:primary};
|
||||
const floating:Record<string,DockRect>={};
|
||||
for(const id of tools){const r=value.floating?.[id];if(!r||!['left','top','width','height'].every(k=>Number.isFinite(r[k as keyof DockRect]))||r.width<=0||r.height<=0)continue;
|
||||
floating[id]={left:Math.max(-16384,Math.min(16384,r.left)),top:Math.max(-16384,Math.min(16384,r.top)),width:Math.min(16384,r.width),height:Math.min(16384,r.height)};
|
||||
}
|
||||
return {tree:tree!,floating};
|
||||
}
|
||||
|
||||
/** Inserts an absent/floating tool, or moves an existing tool. Never swaps the primary view. */
|
||||
export function dockEditorTool(state:EditorDockState,primary:string,move:DockMove|null,id:string,rect:DockRect):EditorDockState {
|
||||
if(id===primary)return state;
|
||||
const remaining=pruneDockTree(state.tree,dockIds(state.tree).filter(v=>v!==id))??{id:primary};
|
||||
const floating={...state.floating,[id]:rect};
|
||||
if(!move||move.position==='center'||(move.scope!=='workspace'&&!dockIds(remaining).includes(move.overId)))return {tree:remaining,floating};
|
||||
const before=move.position==='left'||move.position==='top',axis=move.position==='left'||move.position==='right'?'x':'y';
|
||||
const wrap=(node:DockTree,ratio:number):DockTree=>({axis,ratio:before?ratio:100-ratio,first:before?{id}:node,second:before?node:{id}});
|
||||
const insert=(node:DockTree):DockTree=>'id' in node?(node.id===move.overId?wrap(node,50):node):{...node,first:insert(node.first),second:insert(node.second)};
|
||||
return {tree:move.scope==='workspace'?wrap(remaining,axis==='x'?25:28):insert(remaining),floating};
|
||||
}
|
||||
|
||||
/** Outer edge has priority; broad magnets fill the gap between a tool and the viewport. */
|
||||
export function editorDockTarget(bounds:DockRect,rects:Record<string,DockRect>,primary:string,id:string,x:number,y:number):DockMove|null {
|
||||
if(!dockPosition(bounds,x,y))return null;
|
||||
const edges:[DockMove['position'],number][]=[['left',x-bounds.left],['right',bounds.left+bounds.width-x],['top',y-bounds.top],['bottom',bounds.top+bounds.height-y]];
|
||||
const nearest=edges.slice().sort((a,b)=>a[1]-b[1])[0];
|
||||
if(nearest[1]<=24)return {activeId:id,overId:primary,position:nearest[0],scope:'workspace'};
|
||||
for(const [target,r] of Object.entries(rects)){
|
||||
if(target===id||target===primary||!dockPosition(r,x,y))continue;
|
||||
const distances:[DockMove['position'],number][]=[['left',(x-r.left)/r.width],['right',(r.left+r.width-x)/r.width],['top',(y-r.top)/r.height],['bottom',(r.top+r.height-y)/r.height]];
|
||||
return {activeId:id,overId:target,position:distances.sort((a,b)=>a[1]-b[1])[0][0],scope:'panel'};
|
||||
}
|
||||
const magnets=edges.map(([position,distance])=>[position,distance/Math.min(position==='left'||position==='right'?160:96,(position==='left'||position==='right'?bounds.width:bounds.height)*.16)] as const).sort((a,b)=>a[1]-b[1]);
|
||||
return magnets[0][1]<=1?{activeId:id,overId:primary,position:magnets[0][0],scope:'workspace'}:null;
|
||||
}
|
||||
|
||||
/** Resize visible splits while retaining the positions of temporarily closed tools. */
|
||||
export function mergeEditorDockRatios(full:DockTree,visible:DockTree):DockTree {
|
||||
const ids=dockIds(visible),ratios=new Map<string,number>();
|
||||
const key=(node:DockTree)=>dockIds(node).sort().join('\0');
|
||||
const collect=(node:DockTree)=>{if('id' in node)return;ratios.set(key(node),node.ratio);collect(node.first);collect(node.second);};collect(visible);
|
||||
const merge=(node:DockTree):DockTree=>{
|
||||
if('id' in node)return node;
|
||||
const a=pruneDockTree(node.first,ids),b=pruneDockTree(node.second,ids),shown=pruneDockTree(node,ids);
|
||||
return {...node,ratio:a&&b&&shown?(ratios.get(key(shown))??node.ratio):node.ratio,first:merge(node.first),second:merge(node.second)};
|
||||
};return merge(full);
|
||||
}
|
||||
@@ -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 })) },
|
||||
}])) };
|
||||
}
|
||||
@@ -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 {
|
||||
top: number;
|
||||
@@ -15,6 +15,7 @@ export interface FloatingPositionOptions {
|
||||
surfaceHeight: number;
|
||||
placement?: FloatingPlacement;
|
||||
offset?: number;
|
||||
flip?: boolean;
|
||||
viewportWidth?: number;
|
||||
viewportHeight?: number;
|
||||
viewportPadding?: number;
|
||||
@@ -24,6 +25,7 @@ export interface FloatingPosition {
|
||||
top: number;
|
||||
left: number;
|
||||
maxHeight: number;
|
||||
maxWidth?: number;
|
||||
resolvedPlacement: FloatingPlacement;
|
||||
}
|
||||
|
||||
@@ -33,6 +35,7 @@ export function computeFloatingPosition({
|
||||
surfaceHeight,
|
||||
placement = "bottom-start",
|
||||
offset = 8,
|
||||
flip = true,
|
||||
viewportWidth = typeof window === "undefined" ? 1920 : window.innerWidth,
|
||||
viewportHeight = typeof window === "undefined" ? 1080 : window.innerHeight,
|
||||
viewportPadding = 8,
|
||||
@@ -41,6 +44,22 @@ export function computeFloatingPosition({
|
||||
0,
|
||||
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(
|
||||
viewportAvailableHeight,
|
||||
Math.max(0, viewportHeight - anchor.bottom - offset - viewportPadding),
|
||||
@@ -50,9 +69,9 @@ export function computeFloatingPosition({
|
||||
Math.max(0, anchor.top - offset - viewportPadding),
|
||||
);
|
||||
const requestedTop = placement.startsWith("top");
|
||||
const shouldFlip = requestedTop
|
||||
const shouldFlip = flip && (requestedTop
|
||||
? surfaceHeight > roomAbove && roomBelow > roomAbove
|
||||
: surfaceHeight > roomBelow && roomAbove > roomBelow;
|
||||
: surfaceHeight > roomBelow && roomAbove > roomBelow);
|
||||
const resolvedPlacement = shouldFlip
|
||||
? (`${requestedTop ? "bottom" : "top"}-${placement.endsWith("end") ? "end" : "start"}` as FloatingPlacement)
|
||||
: placement;
|
||||
|
||||
@@ -29,12 +29,16 @@ function clamp(value: number, min: number, max: number) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
export function createGlassMaterialVariables(settings: GlassMaterialSettings): Record<string, string> {
|
||||
export function createGlassMaterialVariables(settings: GlassMaterialSettings, context: "floating" | "scene" = "floating"): Record<string, string> {
|
||||
const tintHex = normalizeHex(settings.tintHex);
|
||||
const red = Number.parseInt(tintHex.slice(1, 3), 16);
|
||||
const green = Number.parseInt(tintHex.slice(3, 5), 16);
|
||||
const blue = Number.parseInt(tintHex.slice(5, 7), 16);
|
||||
return {
|
||||
...(context === "scene" ? {
|
||||
"--nodedc-scene-glass-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
|
||||
"--nodedc-scene-glass-blur": `${clamp(settings.blur, 0, 120)}px`,
|
||||
} : {}),
|
||||
"--nodedc-modal-glass-tint-rgb": `${red} ${green} ${blue}`,
|
||||
"--nodedc-modal-glass-tint-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
|
||||
"--nodedc-blur-modal": `${clamp(settings.blur, 0, 120)}px`,
|
||||
|
||||
@@ -3,3 +3,13 @@ export * from "./floating.js";
|
||||
export * from "./glass.js";
|
||||
export * from "./theme.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";
|
||||
export * from "./editorDock.js";
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -15,10 +15,23 @@ export interface NodedcMaterial {
|
||||
|
||||
export interface ApplyThemeOptions {
|
||||
theme?: NodedcTheme;
|
||||
/** Mission Core is the canonical foundation. `default` is legacy compatibility. */
|
||||
appearance?: "default" | "mission";
|
||||
/** Flat surfaces remove decorative edges; keyboard focus uses a contrasting fill. */
|
||||
edges?: "default" | "flat";
|
||||
accent?: RgbTuple;
|
||||
material?: NodedcMaterial;
|
||||
}
|
||||
|
||||
/** Complete shared foundation; colors live exclusively in @nodedc/tokens/themes.css. */
|
||||
export const missionDarkTheme = Object.freeze({
|
||||
theme: "dark", appearance: "mission", edges: "flat",
|
||||
} as const satisfies ApplyThemeOptions);
|
||||
|
||||
export const missionLightTheme = Object.freeze({
|
||||
theme: "light", appearance: "mission", edges: "flat",
|
||||
} as const satisfies ApplyThemeOptions);
|
||||
|
||||
function formatRgb([red, green, blue]: RgbTuple): string {
|
||||
return `${red} ${green} ${blue}`;
|
||||
}
|
||||
@@ -29,9 +42,11 @@ function clampOpacity(value: number): number {
|
||||
|
||||
export function applyNodedcTheme(
|
||||
target: HTMLElement,
|
||||
{ theme = "dark", accent, material }: ApplyThemeOptions = {},
|
||||
{ theme = "dark", accent, material, appearance = "mission", edges = "flat" }: ApplyThemeOptions = {},
|
||||
): void {
|
||||
target.dataset.nodedcTheme = theme;
|
||||
target.dataset.nodedcAppearance = appearance;
|
||||
target.dataset.nodedcEdges = edges;
|
||||
target.dataset.nodedcUi = "true";
|
||||
|
||||
if (accent) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type ToolbarPlacement = "left" | "right" | "bottom";
|
||||
export type ToolbarPlacement = "left" | "right" | "top" | "bottom";
|
||||
|
||||
export interface ToolbarSettings {
|
||||
minSize: number;
|
||||
|
||||
+1289
-36
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,46 @@
|
||||
/** Build-time typography contract. CSS parsers/TypeScript are supplied by the consumer. */
|
||||
export const operationalFontSizes = Object.freeze({xs: 11, sm: 12, md: 13, dense: 7.2});
|
||||
export const titleFontSize = 18;
|
||||
export function declarationKey({file, selector, property, value}) {
|
||||
return [file, selector.replace(/\s+/g,' ').trim(), property, value].join(' | ');
|
||||
}
|
||||
export function typographyViolation(declaration, policy={}) {
|
||||
const {property,value}=declaration,key=declarationKey(declaration);
|
||||
if(property.startsWith('--nodedc-font-size-'))return 'Do not redefine canonical size tokens in a consumer';
|
||||
if(property!=='font-size'&&property!=='font'&&!/font-size$/.test(property))return null;
|
||||
if(property==='font-size'&&/(^|[,\s])(?:html|:root)(?=$|[,\s])/.test(declaration.selector))return 'Do not resize html/rem to make operational UI smaller';
|
||||
if(policy.exceptions?.some(e=>e.key===key&&e.reason))return null;
|
||||
if(property==='font-size'&&declaration.selector.split(',').some(s=>/(?:^|[\s>+~])p$|\.nodedc-description$/.test(s.trim()))&&value!=='var(--nodedc-font-size-sm)')return 'Explanatory paragraphs use sm/12px; do not restyle Description per feature';
|
||||
if(property==='font')return value==='inherit'?null:'Use inherited typography; font shorthand can reintroduce browser/large sizes';
|
||||
if(/^var\(--nodedc-font-size-(xs|sm|md|dense)\)$/.test(value))return null;
|
||||
if(value==='var(--nodedc-font-size-title)'&&policy.titles?.includes(declaration.selector))return null;
|
||||
// Existing compact custom geometry is frozen by exact declaration, never an open size allowance.
|
||||
if(policy.compactLegacy?.includes(key)){
|
||||
const literal=/^([\d.]+)(px|rem)$/.exec(value);
|
||||
if(literal&&Number(literal[1])*(literal[2]==='rem'?16:1)<=13)return null;
|
||||
}
|
||||
return 'Use xs/sm/md tokens (11/12/13 px); title is reserved for canonical page/window titles';
|
||||
}
|
||||
export function auditStyles(postcss, text, file, policy) {
|
||||
const violations=[];
|
||||
postcss.parse(text,{from:file}).walkDecls(d=>{
|
||||
const declaration={file,selector:d.parent.selector||d.parent.name||'',property:d.prop,value:d.value};
|
||||
const reason=typographyViolation(declaration,policy);
|
||||
if(reason)violations.push(`${file}:${d.source.start.line}: ${d.parent.selector}: ${d.prop}: ${d.value}: ${reason}`);
|
||||
});
|
||||
return violations;
|
||||
}
|
||||
export function auditMarkup(ts,text,file,{allowBareParagraphs=false,inlineExceptions=[]}={}) {
|
||||
const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,file.endsWith('tsx')?ts.ScriptKind.TSX:ts.ScriptKind.TS),violations=[];
|
||||
function report(n,reason){const fragment=n.getText(source);if(!inlineExceptions.some(e=>e.file===file&&e.fragment===fragment&&e.reason))violations.push(`${file}:${source.getLineAndCharacterOfPosition(n.getStart(source)).line+1}: ${reason}`);}
|
||||
function visit(n){
|
||||
if(ts.isJsxOpeningElement(n)||ts.isJsxSelfClosingElement(n)){
|
||||
if(!allowBareParagraphs&&n.tagName.getText(source)==='p'&&!n.attributes.properties.some(p=>ts.isJsxAttribute(p)&&p.name.text==='className'))report(n,'Use Description for explanatory/status copy, or an explicitly styled data paragraph');
|
||||
for(const a of n.attributes.properties)if(ts.isJsxAttribute(a)&&/^(fontSize|style)$/.test(a.name.text)&&a.initializer){
|
||||
if(a.name.text==='fontSize'||(ts.isStringLiteral(a.initializer)&&/font(?:-size)?\s*:/.test(a.initializer.text)))report(a,'Inline typography bypasses the shared contract');
|
||||
}
|
||||
}
|
||||
if(ts.isPropertyAssignment(n)&&(/^(fontSize|font|--nodedc-font-size-.+)$/.test(n.name.getText(source).replace(/['"]/g,''))))report(n,'Inline typography bypasses the shared contract');
|
||||
ts.forEachChild(n,visit);
|
||||
}visit(source);return violations;
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
"version": "0.7.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist"
|
||||
"dist",
|
||||
"styles.css"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -11,13 +12,14 @@
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./styles.css": "./styles.css"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nodedc/ui-core": "0.7.0"
|
||||
"@nodedc/ui-core": "0.7.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
export { applyNodedcTheme, clearNodedcAccent, createAccentVariables, readableTextRgb } from "@nodedc/ui-core";
|
||||
export { applyNodedcTheme, missionDarkTheme, missionLightTheme, clearNodedcAccent, createAccentVariables, readableTextRgb } from "@nodedc/ui-core";
|
||||
export * from "./applicationWorkspace.js";
|
||||
export * from "./floating.js";
|
||||
export * from "./mediaSource.js";
|
||||
export * from "./modal.js";
|
||||
export * from "./modalSize.js";
|
||||
export * from "./pathBar.js";
|
||||
export * from "./select.js";
|
||||
export * from "./shareLink.js";
|
||||
export * from "./toolbar.js";
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
export type ModalSize = { width: number; height: number };
|
||||
export function fitModalSize(size: ModalSize, viewport: ModalSize, minimum: ModalSize = { width: 320, height: 200 }): ModalSize {
|
||||
const fit = (value: number, available: number, min: number) => Math.max(Math.min(min, Math.max(1, available - 32)), Math.min(value, Math.max(1, available - 32)));
|
||||
return { width: fit(size.width, viewport.width, minimum.width), height: fit(size.height, viewport.height, minimum.height) };
|
||||
}
|
||||
/** Resize a centered DOM modal without changing its focus/layer controller.
|
||||
* Persistence belongs to the consumer; only completed user gestures commit.
|
||||
*/
|
||||
export function createModalSizeController({ dialog, initialSize, minimum, onSizeCommit }: {
|
||||
dialog: HTMLElement; initialSize: ModalSize; minimum?: ModalSize; onSizeCommit?: (size: ModalSize) => void;
|
||||
}) {
|
||||
const head = dialog.querySelector<HTMLElement>('.nodedc-window__head');
|
||||
const previous = { width: dialog.style.width, height: dialog.style.height, maxHeight: dialog.style.maxHeight, tab: head?.getAttribute('tabindex'), title: head?.getAttribute('title') };
|
||||
let desired = { ...initialSize };
|
||||
let gesture: { id: number; x: number; y: number; edge: string; size: ModalSize; before: ModalSize } | null = null;
|
||||
const viewport = () => ({ width: window.innerWidth, height: window.innerHeight });
|
||||
const visible = () => dialog.getClientRects().length > 0;
|
||||
const apply = (size = desired) => {
|
||||
const fitted = fitModalSize(size, viewport(), minimum);
|
||||
dialog.style.width = `${fitted.width}px`;
|
||||
dialog.style.height = `${fitted.height}px`;
|
||||
dialog.style.maxHeight = 'calc(100dvh - 2rem)';
|
||||
return fitted;
|
||||
};
|
||||
const handles = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map(edge => {
|
||||
const handle = document.createElement('div');
|
||||
handle.className = 'nodedc-window__resize'; handle.dataset.edge = edge; handle.setAttribute('aria-hidden', 'true');
|
||||
handle.addEventListener('pointerdown', event => {
|
||||
if (event.button !== 0 || gesture) return;
|
||||
const rect = dialog.getBoundingClientRect();
|
||||
gesture = { id: event.pointerId, x: event.clientX, y: event.clientY, edge, size: { width: rect.width, height: rect.height }, before: desired };
|
||||
handle.setPointerCapture(event.pointerId); event.preventDefault();
|
||||
});
|
||||
dialog.append(handle); return handle;
|
||||
});
|
||||
const move = (event: PointerEvent) => {
|
||||
if (!gesture || event.pointerId !== gesture.id) return;
|
||||
const { size, edge, x, y } = gesture;
|
||||
desired = apply({ width: size.width + (event.clientX - x) * (edge.includes('e') ? 2 : edge.includes('w') ? -2 : 0), height: size.height + (event.clientY - y) * (edge.includes('s') ? 2 : edge.includes('n') ? -2 : 0) });
|
||||
event.preventDefault();
|
||||
};
|
||||
const end = (event: PointerEvent) => {
|
||||
if (!gesture || event.pointerId !== gesture.id) return;
|
||||
const before = gesture.before; gesture = null;
|
||||
if (event.type === 'pointercancel') { desired = before; apply(); return; }
|
||||
if (desired.width !== before.width || desired.height !== before.height) onSizeCommit?.({ ...desired });
|
||||
};
|
||||
const key = (event: KeyboardEvent) => {
|
||||
if (event.target !== head || !event.shiftKey || !event.key.startsWith('Arrow')) return;
|
||||
event.preventDefault();
|
||||
const size = fitModalSize(desired, viewport(), minimum);
|
||||
desired = apply({ width: size.width + (event.key === 'ArrowRight' ? 20 : event.key === 'ArrowLeft' ? -20 : 0), height: size.height + (event.key === 'ArrowDown' ? 20 : event.key === 'ArrowUp' ? -20 : 0) });
|
||||
onSizeCommit?.({ ...desired });
|
||||
};
|
||||
const refresh = () => { if (visible() && !gesture) apply(); };
|
||||
if (head) { head.tabIndex = 0; head.title = 'Размер окна: Shift + стрелки. Мышью — за край или угол.'; head.addEventListener('keydown', key); }
|
||||
window.addEventListener('pointermove', move); window.addEventListener('pointerup', end); window.addEventListener('pointercancel', end); window.addEventListener('resize', refresh);
|
||||
apply();
|
||||
return {
|
||||
refresh,
|
||||
setSize(size: ModalSize) { if (!gesture) { desired = { ...size }; apply(); } },
|
||||
destroy() {
|
||||
window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', end); window.removeEventListener('pointercancel', end); window.removeEventListener('resize', refresh);
|
||||
head?.removeEventListener('keydown', key); handles.forEach(handle => handle.remove());
|
||||
for (const name of ['width', 'height', 'maxHeight'] as const) dialog.style[name] = previous[name];
|
||||
if (head) for (const [name, value] of [['tabindex', previous.tab], ['title', previous.title]]) { if (value == null) head.removeAttribute(name!); else head.setAttribute(name!, value); }
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export type PathBarItem = { label: string; path: string; kind: 'folder' | 'file'; current?: boolean };
|
||||
/** Compact Finder-style path row. Navigation and icon source belong to the app. */
|
||||
export function renderPathBar(target: HTMLElement, items: PathBarItem[], options: { onNavigate: (path: string) => void; icon: (kind: 'folder' | 'file') => Node }) {
|
||||
target.classList.add('nodedc-path-bar');
|
||||
target.setAttribute('role', 'navigation'); target.setAttribute('aria-label', 'Путь к файлу');
|
||||
const nodes: Node[] = [];
|
||||
items.forEach((item, index) => {
|
||||
if (index) { const separator = document.createElement('span'); separator.className = 'nodedc-path-bar__separator'; separator.textContent = '›'; separator.setAttribute('aria-hidden', 'true'); nodes.push(separator); }
|
||||
const part = document.createElement(item.kind === 'folder' ? 'button' : 'span');
|
||||
part.className = 'nodedc-path-bar__item'; part.title = item.path || item.label;
|
||||
if (item.current) part.setAttribute('aria-current', 'location');
|
||||
const icon = document.createElement('span'); icon.className = 'nodedc-path-bar__icon'; icon.setAttribute('aria-hidden', 'true'); icon.append(options.icon(item.kind));
|
||||
const text = document.createElement('span'); text.textContent = item.label;
|
||||
part.append(icon, text);
|
||||
if (part instanceof HTMLButtonElement) { part.type = 'button'; part.addEventListener('click', () => options.onNavigate(item.path)); }
|
||||
nodes.push(part);
|
||||
});
|
||||
target.replaceChildren(...nodes);
|
||||
}
|
||||
@@ -17,6 +17,8 @@ export interface ToolbarControllerOptions {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
}
|
||||
|
||||
export interface ToolbarController {
|
||||
@@ -112,7 +114,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
};
|
||||
|
||||
const updateMagnification = (coordinate: number) => {
|
||||
const vertical = options.placement !== "bottom";
|
||||
const vertical = options.placement !== "bottom" && options.placement !== "top";
|
||||
const toolbarRect = toolbar.getBoundingClientRect();
|
||||
const entries = buttons
|
||||
.map((button) => ({
|
||||
@@ -148,7 +150,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
hideTimer = window.setTimeout(() => {
|
||||
hideTimer = null;
|
||||
if (!hovering) hide();
|
||||
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay);
|
||||
}, Math.max(0,Math.min(15000,options.hideDelay ?? NODEDC_TOOLBAR_DEFAULTS.hideDelay)));
|
||||
};
|
||||
|
||||
const applyOptions = () => {
|
||||
@@ -208,7 +210,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
? event.clientX >= window.innerWidth - threshold
|
||||
: options.placement === "bottom"
|
||||
? event.clientY >= window.innerHeight - threshold
|
||||
: event.clientX <= threshold;
|
||||
: options.placement === "top" ? event.clientY <= threshold : event.clientX <= threshold;
|
||||
if (nearEdge) show();
|
||||
else if (visible && !hovering) scheduleHide();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
.nodedc-path-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-1);
|
||||
overflow-x: auto;
|
||||
flex: none;
|
||||
padding: var(--nodedc-space-2) var(--nodedc-space-3);
|
||||
color: var(--nodedc-text-secondary);
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
background: var(--nodedc-surface-group);
|
||||
}
|
||||
.nodedc-path-bar__item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-1);
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
font-family: inherit;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.5;
|
||||
}
|
||||
button.nodedc-path-bar__item { cursor: pointer; }
|
||||
button.nodedc-path-bar__item:hover { color: var(--nodedc-text-primary); }
|
||||
button.nodedc-path-bar__item:focus-visible { outline: 2px solid var(--nodedc-text-primary); outline-offset: 2px; }
|
||||
.nodedc-path-bar__icon { display: inline-flex; color: var(--nodedc-text-primary); }
|
||||
.nodedc-path-bar__icon svg { width: 14px; height: 14px; }
|
||||
.nodedc-path-bar__separator { flex: none; color: var(--nodedc-text-muted); }
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@nodedc/ui-react",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -21,7 +21,7 @@
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-core": "0.7.1",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -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"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import {useContext, useState, type HTMLAttributes, type ReactNode} from "react";
|
||||
import {IconButton} from "./Button.js";
|
||||
import {NavigationPanelState} from "./NavigationPanelState.js";
|
||||
import {Tooltip} from "./Tooltip.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { SortableList } from "./DragDrop.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
@@ -31,6 +34,12 @@ export interface AdminNavigationPanelProps extends Omit<HTMLAttributes<HTMLEleme
|
||||
activeId?: string;
|
||||
footer?: ReactNode;
|
||||
closeLabel?: string;
|
||||
collapseLabel?: string;
|
||||
expandLabel?: string;
|
||||
/** Standalone state. Inside ApplicationShell, use its navigationCollapsed API. */
|
||||
collapsed?: boolean;
|
||||
defaultCollapsed?: boolean;
|
||||
onCollapsedChange?: (collapsed: boolean) => void;
|
||||
navigationLabel?: string;
|
||||
onClose: () => void;
|
||||
onItemChange: (id: string) => void;
|
||||
@@ -47,6 +56,11 @@ export function AdminNavigationPanel({
|
||||
activeId,
|
||||
footer,
|
||||
closeLabel = "Закрыть администрирование",
|
||||
collapseLabel = "Свернуть панель навигации",
|
||||
expandLabel = "Развернуть панель навигации",
|
||||
collapsed: controlledCollapsed,
|
||||
defaultCollapsed = false,
|
||||
onCollapsedChange,
|
||||
navigationLabel = "Разделы администрирования",
|
||||
onClose,
|
||||
onItemChange,
|
||||
@@ -54,40 +68,66 @@ export function AdminNavigationPanel({
|
||||
className,
|
||||
...props
|
||||
}: AdminNavigationPanelProps) {
|
||||
const shell = useContext(NavigationPanelState);
|
||||
const [localCollapsed, setLocalCollapsed] = useState(defaultCollapsed);
|
||||
const collapsed = shell?.collapsed ?? controlledCollapsed ?? localCollapsed;
|
||||
const toggleCollapsed = () => {
|
||||
const next = !collapsed;
|
||||
if (shell) shell.onCollapsedChange(next);
|
||||
else if (controlledCollapsed === undefined) setLocalCollapsed(next);
|
||||
onCollapsedChange?.(next);
|
||||
};
|
||||
const renderItem = (item: AdminNavigationItem) => (
|
||||
<Tooltip content={item.label} disabled={!collapsed} placement="right-start" className="nodedc-admin-panel__item-tooltip">
|
||||
<button type="button" className="nodedc-admin-panel__nav-item"
|
||||
aria-label={item.label} aria-current={activeId === item.id ? "page" : undefined}
|
||||
data-active={activeId === item.id ? "true" : undefined} onClick={() => onItemChange(item.id)}>
|
||||
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">{item.icon ?? <Icon name="grid" />}</span>
|
||||
<span className="nodedc-admin-panel__item-label" aria-hidden={collapsed || undefined}>{item.label}</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
return (
|
||||
<aside className={cn("nodedc-admin-panel", className)} data-has-contexts={contexts.length > 0 || contextSlot ? "true" : undefined} {...props}>
|
||||
<aside className={cn("nodedc-admin-panel", "nodedc-admin-panel--navigation", className)} data-collapsed={collapsed ? "true" : undefined} data-has-contexts={contexts.length > 0 || contextSlot ? "true" : undefined} {...props}>
|
||||
<header className="nodedc-admin-panel__head">
|
||||
<div>
|
||||
<div className="nodedc-admin-panel__titles" aria-hidden={collapsed || undefined}>
|
||||
<p>{eyebrow}</p>
|
||||
<h2>{title}</h2>
|
||||
</div>
|
||||
<div className="nodedc-admin-panel__head-actions">
|
||||
{headerActions}
|
||||
<button type="button" className="nodedc-admin-panel__close" aria-label={closeLabel} onClick={onClose}>
|
||||
<span className="nodedc-admin-panel__extra-actions" hidden={collapsed}>{headerActions}</span>
|
||||
<IconButton label={collapsed ? expandLabel : collapseLabel} aria-expanded={!collapsed}
|
||||
className="nodedc-admin-panel__collapse" onClick={toggleCollapsed}>
|
||||
<Icon name={collapsed ? "chevron-right" : "chevron-left"} />
|
||||
</IconButton>
|
||||
<button hidden={collapsed} type="button" className="nodedc-admin-panel__close" aria-label={closeLabel} onClick={onClose}>
|
||||
<Icon name="close" size={16} strokeWidth={1.6} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{contextSlot ? <div className="nodedc-admin-panel__context-slot">{contextSlot}</div> : null}
|
||||
{contexts.length > 0 || contextSlot ? <div className="nodedc-admin-panel__context-area">
|
||||
{contextSlot ? <div className="nodedc-admin-panel__context-slot" hidden={collapsed}>{contextSlot}</div> : null}
|
||||
|
||||
{contexts.length > 0 ? <div className="nodedc-admin-panel__contexts">
|
||||
{contexts.map((context) => (
|
||||
<div className="nodedc-admin-panel__context-group" key={context.id}>
|
||||
{context.groupLabel ? <span className="nodedc-admin-panel__group-label">{context.groupLabel}</span> : null}
|
||||
{context.groupLabel ? <span className="nodedc-admin-panel__group-label" hidden={collapsed}>{context.groupLabel}</span> : null}
|
||||
<div
|
||||
className={cn("nodedc-admin-context", context.onToggle && "nodedc-admin-context--split")}
|
||||
data-active={context.active ? "true" : undefined}
|
||||
>
|
||||
<button type="button" className="nodedc-admin-context__main" onClick={context.onSelect}>
|
||||
<span className="nodedc-admin-context__icon" aria-hidden="true">{context.icon}</span>
|
||||
<span className="nodedc-admin-context__body">
|
||||
<Tooltip content={context.label} disabled={!collapsed} placement="right-start" className="nodedc-admin-panel__item-tooltip">
|
||||
<button type="button" className="nodedc-admin-context__main" aria-label={context.label} onClick={context.onSelect ?? context.onToggle}>
|
||||
<span className="nodedc-admin-context__icon" aria-hidden="true">{context.icon ?? <Icon name="grid" />}</span>
|
||||
<span className="nodedc-admin-context__body" aria-hidden={collapsed || undefined}>
|
||||
<strong>{context.label}</strong>
|
||||
{context.description ? <small>{context.description}</small> : null}
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{context.onToggle ? (
|
||||
<button type="button" className="nodedc-admin-context__toggle" aria-label={`Выбрать: ${context.label}`} onClick={context.onToggle}>
|
||||
<button hidden={collapsed} type="button" className="nodedc-admin-context__toggle" aria-label={`Выбрать: ${context.label}`} onClick={context.onToggle}>
|
||||
<span className="nodedc-select-trigger__chevron" aria-hidden="true" />
|
||||
</button>
|
||||
) : null}
|
||||
@@ -95,20 +135,10 @@ export function AdminNavigationPanel({
|
||||
</div>
|
||||
))}
|
||||
</div> : null}
|
||||
</div> : null}
|
||||
|
||||
<nav className="nodedc-admin-panel__nav" aria-label={navigationLabel}>
|
||||
{items.filter((item) => !item.sortable).map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className="nodedc-admin-panel__nav-item"
|
||||
data-active={activeId === item.id ? "true" : undefined}
|
||||
onClick={() => onItemChange(item.id)}
|
||||
>
|
||||
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">{item.icon}</span>
|
||||
<span>{item.label}</span>
|
||||
</button>
|
||||
))}
|
||||
{items.filter((item) => !item.sortable).map((item) => <div key={item.id}>{renderItem(item)}</div>)}
|
||||
{items.some((item) => item.sortable) ? (
|
||||
<SortableList
|
||||
className="nodedc-admin-panel__sortable-nav"
|
||||
@@ -118,23 +148,15 @@ export function AdminNavigationPanel({
|
||||
>
|
||||
{(item, { handle }) => (
|
||||
<div className="nodedc-admin-panel__sortable-row">
|
||||
<button
|
||||
type="button"
|
||||
className="nodedc-admin-panel__nav-item"
|
||||
data-active={activeId === item.id ? "true" : undefined}
|
||||
onClick={() => onItemChange(item.id)}
|
||||
>
|
||||
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">{item.icon}</span>
|
||||
<span>{item.label}</span>
|
||||
</button>
|
||||
{handle}
|
||||
{renderItem(item)}
|
||||
<span hidden={collapsed}>{handle}</span>
|
||||
</div>
|
||||
)}
|
||||
</SortableList>
|
||||
) : null}
|
||||
</nav>
|
||||
|
||||
{footer ? <footer className="nodedc-admin-panel__footer">{footer}</footer> : null}
|
||||
{footer ? <footer className="nodedc-admin-panel__footer" aria-hidden={collapsed || undefined}>{footer}</footer> : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode } from "react";
|
||||
import type { ButtonHTMLAttributes, ReactNode, Ref } from "react";
|
||||
|
||||
export interface AppHeaderProps {
|
||||
brand: ReactNode;
|
||||
brandHref?: string;
|
||||
brandLabel?: string;
|
||||
/** Opt in only for a light, single-color mark, never a full-color image. */
|
||||
brandMonochrome?: boolean;
|
||||
left?: ReactNode;
|
||||
center?: ReactNode;
|
||||
right?: ReactNode;
|
||||
@@ -13,14 +15,15 @@ export function AppHeader({
|
||||
brand,
|
||||
brandHref,
|
||||
brandLabel = "NODE.DC",
|
||||
brandMonochrome = false,
|
||||
left,
|
||||
center,
|
||||
right,
|
||||
}: AppHeaderProps) {
|
||||
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 (
|
||||
@@ -71,10 +74,11 @@ export function HeaderNavigation<T extends string>({ label, value, items, onChan
|
||||
|
||||
export interface HeaderProfileProps {
|
||||
children: ReactNode;
|
||||
ref?: Ref<HTMLDivElement>;
|
||||
}
|
||||
|
||||
export function HeaderProfile({ children }: HeaderProfileProps) {
|
||||
return <div className="nodedc-header__profile">{children}</div>;
|
||||
export function HeaderProfile({ children, ref }: HeaderProfileProps) {
|
||||
return <div ref={ref} className="nodedc-header__profile">{children}</div>;
|
||||
}
|
||||
|
||||
export interface HeaderProfileButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className" | "style"> {}
|
||||
@@ -100,11 +104,12 @@ export interface HeaderWorkspaceProps {
|
||||
label: string;
|
||||
imageUrl?: string;
|
||||
kind?: "mark" | "avatar";
|
||||
monochrome?: boolean;
|
||||
}
|
||||
|
||||
export function HeaderWorkspace({ label, imageUrl, kind = "mark" }: HeaderWorkspaceProps) {
|
||||
export function HeaderWorkspace({ label, imageUrl, kind = "mark", monochrome = false }: HeaderWorkspaceProps) {
|
||||
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()}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import {createContext, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
|
||||
const FullscreenContext = createContext<{fullscreen:boolean; setFullscreen:(value:boolean)=>void} | null>(null);
|
||||
/** Shared full-window presentation. Portaled inspectors remain above the panel. */
|
||||
export const useApplicationPanelFullscreen = () => useContext(FullscreenContext);
|
||||
export function ApplicationPanelFullscreen({children}: {children:ReactNode}) {
|
||||
const [fullscreen,setFullscreen] = useState(false);
|
||||
const [mount] = useState(() => typeof document === "undefined" ? null : document.createElement("div"));
|
||||
const anchor = useRef<HTMLDivElement>(null);
|
||||
const value = useMemo(() => ({fullscreen,setFullscreen}), [fullscreen]);
|
||||
useLayoutEffect(() => {
|
||||
if (!mount || !anchor.current) return;
|
||||
anchor.current.append(mount);
|
||||
return () => mount.remove();
|
||||
}, [mount]);
|
||||
useLayoutEffect(() => {
|
||||
if (!mount || !anchor.current) return;
|
||||
const target = (fullscreen ? document.body : anchor.current) as HTMLElement & {moveBefore?:(node:Node, before:Node|null)=>void};
|
||||
if (mount.parentElement !== target) {
|
||||
if (target.moveBefore) target.moveBefore(mount, null); else target.append(mount);
|
||||
}
|
||||
}, [fullscreen,mount]);
|
||||
const content = <FullscreenContext.Provider value={value}><div className="nodedc-panel-viewport nodedc-ui-root" data-fullscreen={fullscreen || undefined}>{children}</div></FullscreenContext.Provider>;
|
||||
return mount ? <><div ref={anchor} className="nodedc-panel-viewport-anchor"/>{createPortal(content,mount)}</> : content;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import {useCallback, useMemo, useState, type HTMLAttributes, type ReactNode} from "react";
|
||||
import {NavigationPanelState} from "./NavigationPanelState.js";
|
||||
import { cn } from "./cn.js";
|
||||
import {ApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
|
||||
export interface ApplicationShellProps extends Omit<HTMLAttributes<HTMLDivElement>, "content"> {
|
||||
@@ -9,6 +11,10 @@ export interface ApplicationShellProps extends Omit<HTMLAttributes<HTMLDivElemen
|
||||
content?: ReactNode;
|
||||
endPanel?: ReactNode;
|
||||
navigationOpen?: boolean;
|
||||
/** Shared across navigation routes; closing a workspace does not reset it. */
|
||||
navigationCollapsed?: boolean;
|
||||
defaultNavigationCollapsed?: boolean;
|
||||
onNavigationCollapsedChange?: (collapsed: boolean) => void;
|
||||
contentOpen?: boolean;
|
||||
contentExpanded?: boolean;
|
||||
endPanelOpen?: boolean;
|
||||
@@ -21,16 +27,27 @@ export function ApplicationShell({
|
||||
content,
|
||||
endPanel,
|
||||
navigationOpen = false,
|
||||
navigationCollapsed,
|
||||
defaultNavigationCollapsed = false,
|
||||
onNavigationCollapsedChange,
|
||||
contentOpen = false,
|
||||
contentExpanded = false,
|
||||
endPanelOpen = false,
|
||||
className,
|
||||
...props
|
||||
}: ApplicationShellProps) {
|
||||
const [localCollapsed, setLocalCollapsed] = useState(defaultNavigationCollapsed);
|
||||
const collapsed = navigationCollapsed ?? localCollapsed;
|
||||
const onCollapsedChange = useCallback((next: boolean) => {
|
||||
if (navigationCollapsed === undefined) setLocalCollapsed(next);
|
||||
onNavigationCollapsedChange?.(next);
|
||||
}, [navigationCollapsed, onNavigationCollapsedChange]);
|
||||
const navigationState = useMemo(() => ({collapsed, onCollapsedChange}), [collapsed, onCollapsedChange]);
|
||||
return (
|
||||
<div
|
||||
className={cn("nodedc-app-shell", className)}
|
||||
data-navigation-open={navigationOpen ? "true" : undefined}
|
||||
data-navigation-collapsed={collapsed ? "true" : undefined}
|
||||
data-content-open={contentOpen ? "true" : undefined}
|
||||
data-content-expanded={contentOpen && contentExpanded ? "true" : undefined}
|
||||
data-end-panel-open={endPanelOpen ? "true" : undefined}
|
||||
@@ -39,7 +56,7 @@ export function ApplicationShell({
|
||||
{header}
|
||||
<main className="nodedc-app-shell__main">
|
||||
<div className="nodedc-app-shell__stage">{stage}</div>
|
||||
{navigationOpen && navigation ? <div className="nodedc-app-shell__navigation">{navigation}</div> : null}
|
||||
{navigationOpen && navigation ? <div className="nodedc-app-shell__navigation"><NavigationPanelState.Provider value={navigationState}>{navigation}</NavigationPanelState.Provider></div> : null}
|
||||
{contentOpen && content ? <div className="nodedc-app-shell__content">{content}</div> : null}
|
||||
{endPanel ? <div className="nodedc-app-shell__end-panel">{endPanel}</div> : null}
|
||||
</main>
|
||||
@@ -52,6 +69,8 @@ export interface ApplicationPanelProps extends Omit<HTMLAttributes<HTMLElement>,
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
expanded?: boolean;
|
||||
/** Enables full-window presentation requested by an owned viewer through context. */
|
||||
allowFullscreen?: boolean;
|
||||
expandLabel?: string;
|
||||
closeLabel?: string;
|
||||
onExpandedChange?: (expanded: boolean) => void;
|
||||
@@ -68,6 +87,7 @@ export interface ApplicationPanelUtilityAction {
|
||||
icon: IconName;
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
pressed?: boolean;
|
||||
}
|
||||
|
||||
export function ApplicationPanel({
|
||||
@@ -75,6 +95,7 @@ export function ApplicationPanel({
|
||||
title,
|
||||
description,
|
||||
expanded = false,
|
||||
allowFullscreen = false,
|
||||
expandLabel = "Развернуть окно",
|
||||
closeLabel = "Закрыть окно",
|
||||
onExpandedChange,
|
||||
@@ -85,7 +106,7 @@ export function ApplicationPanel({
|
||||
className,
|
||||
...props
|
||||
}: ApplicationPanelProps) {
|
||||
return (
|
||||
const panel = (
|
||||
<section className={cn("nodedc-application-panel", className)} data-expanded={expanded ? "true" : undefined} {...props}>
|
||||
<header className="nodedc-application-panel__head">
|
||||
<div className="nodedc-application-panel__titles">
|
||||
@@ -102,6 +123,8 @@ export function ApplicationPanel({
|
||||
className="nodedc-application-panel__action"
|
||||
data-action="utility"
|
||||
aria-label={action.label}
|
||||
aria-pressed={action.pressed}
|
||||
data-active={action.pressed ? "true" : undefined}
|
||||
disabled={action.disabled}
|
||||
onClick={action.onClick}
|
||||
>
|
||||
@@ -128,4 +151,5 @@ export function ApplicationPanel({
|
||||
<div className="nodedc-application-panel__body">{children}</div>
|
||||
</section>
|
||||
);
|
||||
return allowFullscreen ? <ApplicationPanelFullscreen>{panel}</ApplicationPanelFullscreen> : panel;
|
||||
}
|
||||
|
||||
@@ -1,22 +1,28 @@
|
||||
import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from "react";
|
||||
import { createAccentVariables, type RgbTuple } from "@nodedc/ui-core";
|
||||
import { cn } from "./cn.js";
|
||||
import { ActivityIndicator } from "./ActivityIndicator.js";
|
||||
|
||||
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 interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: ButtonVariant;
|
||||
/** Neutral primary actions remain white/gray independently of the product accent. */
|
||||
tone?: "theme" | "neutral";
|
||||
size?: ButtonSize;
|
||||
width?: "auto" | "full";
|
||||
shape?: ButtonShape;
|
||||
accent?: RgbTuple;
|
||||
icon?: ReactNode;
|
||||
/** Pending state belongs to this action; dimensions and accessible name stay unchanged. */
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button({
|
||||
variant = "secondary",
|
||||
tone = "theme",
|
||||
size = "default",
|
||||
width = "auto",
|
||||
shape = "default",
|
||||
@@ -26,6 +32,8 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
|
||||
children,
|
||||
style,
|
||||
type = "button",
|
||||
loading = false,
|
||||
disabled,
|
||||
...props
|
||||
}, ref) {
|
||||
const accentStyle = accent ? createAccentVariables(accent) : undefined;
|
||||
@@ -35,14 +43,21 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
|
||||
type={type}
|
||||
className={cn("nodedc-button", className)}
|
||||
data-variant={variant}
|
||||
data-tone={tone === "theme" ? undefined : tone}
|
||||
data-size={size === "default" ? undefined : size}
|
||||
data-width={width === "auto" ? undefined : width}
|
||||
data-shape={shape === "default" ? undefined : shape}
|
||||
style={accentStyle ? { ...accentStyle, ...style } : style}
|
||||
{...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}
|
||||
{children}
|
||||
</span>
|
||||
{loading ? <span className="nodedc-action-loading" aria-hidden="true"><ActivityIndicator size="compact" /></span> : null}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
@@ -50,6 +65,7 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
|
||||
export interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
label: string;
|
||||
shape?: "circle" | "rounded";
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton({
|
||||
@@ -58,6 +74,8 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
className,
|
||||
children,
|
||||
type = "button",
|
||||
loading = false,
|
||||
disabled,
|
||||
...props
|
||||
}, ref) {
|
||||
return (
|
||||
@@ -69,8 +87,12 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
aria-label={label}
|
||||
title={label}
|
||||
{...props}
|
||||
disabled={disabled || loading}
|
||||
aria-busy={loading || props["aria-busy"]}
|
||||
data-loading={loading || undefined}
|
||||
>
|
||||
{children}
|
||||
{loading ? <span className="nodedc-action-loading" aria-hidden="true"><ActivityIndicator size="compact" /></span> : null}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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)} />;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
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, dockMoveAtPoint, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
|
||||
|
||||
const DockContext = createContext<{disabled: boolean; onKey: (id: string, event: KeyboardEvent<HTMLDivElement>) => void}>({disabled: true, onKey: () => {}});
|
||||
/** The shared six-dot grip supports pointer dragging and keyboard docking. */
|
||||
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), viewport = useRef<HTMLDivElement>(null);
|
||||
// React must not reorder these DOM siblings: moving an iframe node reloads
|
||||
// its browsing context even when its key and portal content are unchanged.
|
||||
const hostOrder = useRef<string[]>([]);
|
||||
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;
|
||||
const view = viewport.current!, screen = view.getBoundingClientRect();
|
||||
const visible = {left: screen.left + view.clientLeft - box.left, top: screen.top + view.clientTop - box.top,
|
||||
width: view.clientWidth, height: view.clientHeight};
|
||||
return dockMoveAtPoint(visible, rects, String(event.active.id), x, y);
|
||||
};
|
||||
// Preview and commit use the same content limits, including a newly enlarged canvas.
|
||||
const projectMove = (move: DockMove | null) => {
|
||||
const next = move && moveDockPanel(constrained, move), required = dockMinimum(next, minimums);
|
||||
const area = {...bounds, width: Math.max(bounds.width, required.width), height: Math.max(bounds.height, required.height)};
|
||||
return {tree: constrainDockTree(next, area, minimums), area};
|
||||
};
|
||||
const commit = (move: DockMove | null) => {
|
||||
const next = projectMove(move).tree;
|
||||
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 positions = {ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const;
|
||||
const position = positions[event.key as keyof typeof positions];
|
||||
if (!position || !target) return;
|
||||
setTarget({...target, position, scope: event.shiftKey && position !== "center" ? "workspace" : "panel"});
|
||||
}
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
};
|
||||
const projected = projectMove(target);
|
||||
const preview = target ? dockRects(projected.tree, projected.area)[target.activeId] : null;
|
||||
const action = target ? ({center: "Поменять местами", left: "Слева", right: "Справа", top: "Сверху", bottom: "Снизу"})[target.position] : "Выберите окно и край";
|
||||
const label = target?.scope === "workspace" ? "Вся область" : target ? panels.find(panel => panel.id === target.overId)?.label : "";
|
||||
return <DndContext sensors={sensors} autoScroll={false}
|
||||
onDragStart={event => {setActive(String(event.active.id)); setKeyboard(false);}}
|
||||
onDragMove={event => setTarget(locate(event))}
|
||||
onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
|
||||
<DockContext.Provider value={{disabled, onKey}}>
|
||||
<div ref={viewport} className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
|
||||
<div ref={host} className="nodedc-dock-layout__canvas" style={{minWidth:minimum.width, minHeight:minimum.height}}>
|
||||
<DockSlots tree={constrained} bounds={canvas} minimums={minimums} onResize={(path, ratio) => {if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/>
|
||||
{hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel => <div key={panel.id} className="nodedc-dock-layout__panel" data-dock-id={panel.id}
|
||||
data-dock-source={active === panel.id ? "true" : undefined} style={rects[panel.id] ?? {display: "none"}}>{renderPanel(panel.id)}</div>)}
|
||||
{active ? <div className="nodedc-dock-layout__overlay" aria-hidden="true">
|
||||
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} data-dock-scope={target!.scope ?? "panel"} style={preview}><span>{action} · {label}</span></div> : null}
|
||||
</div> : null}
|
||||
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край окна, Shift+стрелки — край всей области, 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"}/>}/>;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { ReactNode } from "react";
|
||||
import {createContext, useContext, useEffect, useRef, useState, type ReactNode} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
DragOverlay,
|
||||
PointerSensor,
|
||||
useDraggable,
|
||||
useDroppable,
|
||||
@@ -36,6 +38,8 @@ export interface DragDropResult {
|
||||
overData?: NodedcDragData;
|
||||
activeRect?: DragRect;
|
||||
overRect?: DragRect;
|
||||
/** Client coordinates of the pointer, for exact canvas/object drop targets. */
|
||||
pointer?: {x:number;y:number};
|
||||
}
|
||||
|
||||
const copyRect = (rect: DragRect | null | undefined): DragRect | undefined => rect ? ({
|
||||
@@ -70,9 +74,15 @@ export function DragHandle({ label = "Перетащить", listeners, attribut
|
||||
);
|
||||
}
|
||||
|
||||
export function DragDropRoot({ children, onDragEnd }: { children: ReactNode; onDragEnd: (result: DragDropResult) => void }) {
|
||||
const DragOverlayContext=createContext(false);
|
||||
export function DragDropRoot({ children, onDragEnd, renderOverlay }: { children: ReactNode; onDragEnd: (result: DragDropResult) => void; renderOverlay?:(item:{id:string;data?:NodedcDragData})=>ReactNode }) {
|
||||
const [active,setActive]=useState<{id:string;data?:NodedcDragData}|null>(null);
|
||||
const dragging=useRef(false),pointer=useRef<{x:number;y:number}|undefined>(undefined);
|
||||
useEffect(()=>{const track=(event:PointerEvent)=>{if(dragging.current)pointer.current={x:event.clientX,y:event.clientY};};window.addEventListener('pointermove',track,true);window.addEventListener('pointerup',track,true);return()=>{window.removeEventListener('pointermove',track,true);window.removeEventListener('pointerup',track,true);};},[]);
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
setActive(null);dragging.current=false;
|
||||
const origin=event.activatorEvent as PointerEvent;
|
||||
onDragEnd({
|
||||
activeId: String(event.active.id),
|
||||
overId: event.over ? String(event.over.id) : null,
|
||||
@@ -80,25 +90,27 @@ export function DragDropRoot({ children, onDragEnd }: { children: ReactNode; onD
|
||||
overData: event.over?.data.current as NodedcDragData | undefined,
|
||||
activeRect: copyRect(event.active.rect.current.translated),
|
||||
overRect: copyRect(event.over?.rect),
|
||||
pointer: pointer.current??(typeof origin.clientX==='number'?{x:origin.clientX+event.delta.x,y:origin.clientY+event.delta.y}:undefined),
|
||||
});
|
||||
};
|
||||
return <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>{children}</DndContext>;
|
||||
return <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={event=>{dragging.current=true;pointer.current=undefined;setActive({id:String(event.active.id),data:event.active.data.current});}} onDragCancel={()=>{dragging.current=false;setActive(null);}} onDragEnd={handleDragEnd}><DragOverlayContext.Provider value={!!renderOverlay}>{children}</DragOverlayContext.Provider>{renderOverlay&&typeof document!=='undefined'&&createPortal(<DragOverlay dropAnimation={null} style={{pointerEvents:"none"}}>{active?renderOverlay(active):null}</DragOverlay>,document.fullscreenElement??document.body)}</DndContext>;
|
||||
}
|
||||
|
||||
export function DraggableItem({ id, data, className, children }: {
|
||||
id: string;
|
||||
data?: NodedcDragData;
|
||||
className?: string;
|
||||
children: (state: { handle: ReactNode; isDragging: boolean }) => ReactNode;
|
||||
children: (state: { handle: ReactNode; isDragging: boolean; activator: {attributes:ReturnType<typeof useDraggable>["attributes"];listeners:ReturnType<typeof useDraggable>["listeners"]} }) => ReactNode;
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id, data });
|
||||
const overlay=useContext(DragOverlayContext);
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
className={cn(className, isDragging && "is-dragging")}
|
||||
style={{ transform: CSS.Translate.toString(transform), opacity: isDragging ? 0.65 : undefined }}
|
||||
style={{ transform: overlay?undefined:CSS.Translate.toString(transform), opacity: isDragging ? 0.65 : undefined }}
|
||||
>
|
||||
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging })}
|
||||
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging, activator:{attributes,listeners} })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useMemo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
@@ -9,9 +12,12 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
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";
|
||||
|
||||
const DropdownLineage = createContext<readonly string[]>([]);
|
||||
const openDropdowns = new Map<string, readonly string[]>();
|
||||
|
||||
export interface DropdownTriggerApi {
|
||||
open: boolean;
|
||||
show: () => void;
|
||||
@@ -34,6 +40,11 @@ export interface DropdownProps {
|
||||
surfaceClassName?: string;
|
||||
surfaceRole?: "menu" | "listbox" | "dialog";
|
||||
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({
|
||||
@@ -48,8 +59,13 @@ export function Dropdown({
|
||||
surfaceClassName,
|
||||
surfaceRole = "menu",
|
||||
onOpenChange,
|
||||
getAnchorRect,
|
||||
flip = true,
|
||||
onPointerDownOutside,
|
||||
}: DropdownProps) {
|
||||
const instanceId = useId();
|
||||
const ancestors = useContext(DropdownLineage);
|
||||
const lineage = useMemo(() => [...ancestors, instanceId], [ancestors, instanceId]);
|
||||
const surfaceId = `${instanceId.replaceAll(":", "")}-surface`;
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null);
|
||||
@@ -72,7 +88,7 @@ export function Dropdown({
|
||||
const updatePosition = useCallback(() => {
|
||||
const anchorNode = anchorElement ?? triggerElement;
|
||||
if (!anchorNode || !surfaceRef.current) return;
|
||||
const anchor = anchorNode.getBoundingClientRect();
|
||||
const anchor = getAnchorRect?.() ?? anchorNode.getBoundingClientRect();
|
||||
const anchorVisible = (
|
||||
anchor.bottom > 0
|
||||
&& anchor.top < window.innerHeight
|
||||
@@ -93,58 +109,80 @@ export function Dropdown({
|
||||
surfaceWidth,
|
||||
surfaceHeight,
|
||||
placement,
|
||||
offset,
|
||||
offset, flip,
|
||||
});
|
||||
setSurfaceStyle({
|
||||
const next:CSSProperties = {
|
||||
top: position.top,
|
||||
left: position.left,
|
||||
width: surfaceWidth,
|
||||
width: Math.min(surfaceWidth, position.maxWidth ?? surfaceWidth),
|
||||
maxHeight: position.maxHeight,
|
||||
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(() => {
|
||||
if (!isOpen) return;
|
||||
updatePosition();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !surfaceRef.current) return;
|
||||
const observer = new ResizeObserver(updatePosition);
|
||||
observer.observe(surfaceRef.current);
|
||||
return () => observer.disconnect();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !getAnchorRect) return;
|
||||
let frame:number;
|
||||
const tick=()=>{updatePosition();frame=requestAnimationFrame(tick);};
|
||||
frame=requestAnimationFrame(tick);
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[isOpen,getAnchorRect,updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof Node)) 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();
|
||||
onPointerDownOutside?.(event);
|
||||
};
|
||||
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();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
triggerElement?.focus();
|
||||
}
|
||||
};
|
||||
const handleOtherOpen = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ id?: string }>).detail;
|
||||
if (detail.id !== instanceId) close();
|
||||
const detail = (event as CustomEvent<{ id?: string; lineage?: readonly string[] }>).detail;
|
||||
if (detail.id !== instanceId && !detail.lineage?.includes(instanceId)) close();
|
||||
};
|
||||
const handleViewportChange = () => updatePosition();
|
||||
|
||||
window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId } }));
|
||||
document.addEventListener("pointerdown", handlePointerDown);
|
||||
openDropdowns.set(instanceId, lineage);
|
||||
window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId, lineage } }));
|
||||
document.addEventListener("pointerdown", handlePointerDown, true);
|
||||
document.addEventListener("keydown", handleKeyDown, true);
|
||||
window.addEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
|
||||
window.addEventListener("resize", handleViewportChange);
|
||||
window.addEventListener("scroll", handleViewportChange, true);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", handlePointerDown);
|
||||
openDropdowns.delete(instanceId);
|
||||
document.removeEventListener("pointerdown", handlePointerDown, true);
|
||||
document.removeEventListener("keydown", handleKeyDown, true);
|
||||
window.removeEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
|
||||
window.removeEventListener("resize", handleViewportChange);
|
||||
window.removeEventListener("scroll", handleViewportChange, true);
|
||||
};
|
||||
}, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition]);
|
||||
}, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition, lineage, onPointerDownOutside]);
|
||||
|
||||
return (
|
||||
<span className={cn("nodedc-dropdown-anchor", className)}>
|
||||
@@ -154,13 +192,16 @@ export function Dropdown({
|
||||
<div
|
||||
ref={surfaceRef}
|
||||
id={surfaceId}
|
||||
data-dropdown-lineage={lineage.join(' ')}
|
||||
className={cn("nodedc-dropdown-surface", surfaceClassName)}
|
||||
role={surfaceRole}
|
||||
style={surfaceStyle}
|
||||
>
|
||||
{typeof children === "function" ? children({ close }) : children}
|
||||
<DropdownLineage.Provider value={lineage}>
|
||||
{typeof children === "function" ? children({ close }) : children}
|
||||
</DropdownLineage.Provider>
|
||||
</div>,
|
||||
document.body,
|
||||
document.fullscreenElement ?? document.body,
|
||||
)
|
||||
: null}
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import {useEffect,useLayoutEffect,useRef,useState,type KeyboardEvent,type PointerEvent,type ReactNode} from 'react';
|
||||
import {constrainDockTree,dockIds,dockMinimum,dockRects,dockEditorTool,editorDockTarget,mergeEditorDockRatios,pruneDockTree,resizeDockSplit,type DockMinimum,type DockMove,type DockRect,type DockTree,type EditorDockState} from '@nodedc/ui-core';
|
||||
import {IconButton} from './Button.js';
|
||||
import {Icon} from './Icon.js';
|
||||
import {SplitPane} from './SplitPane.js';
|
||||
import {InspectorSelectPolicyContext} from './InspectorContext.js';
|
||||
import {LoadingContext} from './LoadingContext.js';
|
||||
import {fitWindow,resizeWindow,windowResizeEdges,type ResizeEdge} from './windowGeometry.js';
|
||||
import {cn} from './cn.js';
|
||||
import {editorDockCorners} from './editorDockCorners.js';
|
||||
|
||||
export interface EditorDockTool {
|
||||
id:string;title:ReactNode;label:string;open:boolean;onClose:()=>void;content:ReactNode;
|
||||
subtitle?:ReactNode;actions?:ReactNode;footer?:ReactNode;className?:string;
|
||||
minimumSize?:DockMinimum;initialRect?:DockRect;activationKey?:string|number;
|
||||
}
|
||||
export interface EditorDockLayoutProps {
|
||||
value:EditorDockState;onChange:(value:EditorDockState)=>void;
|
||||
primary:ReactNode;primaryId?:string;primaryMinimum?:DockMinimum;
|
||||
tools:EditorDockTool[];enabled?:boolean;className?:string;
|
||||
}
|
||||
type Gesture={id:string;pointer:number;x:number;y:number;rect:DockRect;edge?:ResizeEdge;moved:boolean;current:DockRect;target:DockMove|null};
|
||||
const actionNames={left:'Слева',right:'Справа',top:'Сверху',bottom:'Снизу',center:'Рядом'};
|
||||
/** A locked primary renderer, docked tools and floating tools share stable sibling hosts. */
|
||||
export function EditorDockLayout({value,onChange,primary,primaryId='viewport',primaryMinimum={width:320,height:240},tools,enabled=true,className}:EditorDockLayoutProps){
|
||||
const host=useRef<HTMLDivElement>(null),viewport=useRef<HTMLDivElement>(null);
|
||||
const [bounds,setBounds]=useState<DockRect>({left:0,top:0,width:1,height:1});
|
||||
const [drag,setDrag]=useState<Gesture|null>(null),gesture=useRef<Gesture|null>(null);
|
||||
const [order,setOrder]=useState<string[]>([]),[keyboard,setKeyboard]=useState<{id:string;target:DockMove|null}|null>(null);
|
||||
const previousTools=useRef(new Map<string,{open:boolean;key?:string|number}>());
|
||||
useEffect(()=>{
|
||||
const raised=tools.filter(t=>t.open&&(!previousTools.current.get(t.id)?.open||previousTools.current.get(t.id)?.key!==t.activationKey)).map(t=>t.id);
|
||||
previousTools.current=new Map(tools.map(t=>[t.id,{open:t.open,key:t.activationKey}]));
|
||||
if(enabled&&raised.length)setOrder(v=>[...v.filter(id=>!raised.includes(id)),...raised]);
|
||||
});
|
||||
const visible=[primaryId,...tools.filter(t=>enabled&&t.open).map(t=>t.id)];
|
||||
const minimums={...Object.fromEntries(tools.map(t=>[t.id,t.minimumSize??{width:280,height:180}])),[primaryId]:primaryMinimum};
|
||||
const visibleTree=pruneDockTree(value.tree,visible)??{id:primaryId};
|
||||
const required=dockMinimum(visibleTree,minimums),area={...bounds,width:Math.max(bounds.width,required.width),height:Math.max(bounds.height,required.height)};
|
||||
const constrained=constrainDockTree(visibleTree,area,minimums)!;
|
||||
const rects=dockRects(constrained,area);
|
||||
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds,tools.find(t=>t.id===id)?.minimumSize);
|
||||
const latest=useRef({value,onChange,rects,bounds,enabled,tools});latest.current={value,onChange,rects,bounds,enabled,tools};
|
||||
const activate=(id:string)=>setOrder(v=>[...v.filter(x=>x!==id),id]);
|
||||
useLayoutEffect(()=>{const v=viewport.current!;const measure=()=>setBounds({left:0,top:0,width:v.clientWidth,height:v.clientHeight});measure();const ro=new ResizeObserver(measure);ro.observe(v);return()=>ro.disconnect();},[]);
|
||||
const point=(e:{clientX:number;clientY:number})=>{const r=host.current!.getBoundingClientRect();return {x:e.clientX-r.left,y:e.clientY-r.top};};
|
||||
const begin=(id:string,e:PointerEvent<HTMLElement>,edge?:ResizeEdge)=>{
|
||||
if(!enabled||e.button!==0||gesture.current||(!edge&&(e.target as HTMLElement).closest('button,input,select,textarea,a,[role=slider]')))return;
|
||||
const p=point(e),docked=rects[id],saved=floatingRect(id);
|
||||
const rect=docked?{...saved,left:p.x-Math.min(saved.width-24,Math.max(24,p.x-docked.left)),top:p.y-Math.min(48,p.y-docked.top)}:saved;
|
||||
gesture.current={id,pointer:e.pointerId,x:p.x,y:p.y,rect,edge,moved:false,current:rect,target:null};
|
||||
e.currentTarget.setPointerCapture(e.pointerId);e.currentTarget.focus();activate(id);setKeyboard(null);e.preventDefault();e.stopPropagation();
|
||||
};
|
||||
useEffect(()=>{
|
||||
const move=(e:globalThis.PointerEvent)=>{
|
||||
const g=gesture.current;if(!g||e.pointerId!==g.pointer)return;
|
||||
const p=point(e),dx=p.x-g.x,dy=p.y-g.y;
|
||||
if(!g.moved&&Math.hypot(dx,dy)<6)return;
|
||||
g.moved=true;
|
||||
const b=latest.current.bounds,minimum=latest.current.tools.find(t=>t.id===g.id)?.minimumSize;
|
||||
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b,minimum):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b,minimum);
|
||||
const visibleBounds={...b,left:viewport.current?.scrollLeft??0,top:viewport.current?.scrollTop??0};
|
||||
g.target=g.edge?null:editorDockTarget(visibleBounds,latest.current.rects,primaryId,g.id,p.x,p.y);
|
||||
setDrag({...g});e.preventDefault();
|
||||
};
|
||||
const finish=(e:globalThis.PointerEvent)=>{
|
||||
const g=gesture.current;if(!g||g.pointer!==e.pointerId)return;
|
||||
if(e.type==='pointerup'&&g.moved){const v=latest.current;v.onChange(g.edge?{...v.value,floating:{...v.value.floating,[g.id]:g.current}}:dockEditorTool(v.value,primaryId,g.target,g.id,g.current));}
|
||||
gesture.current=null;setDrag(null);
|
||||
};
|
||||
const cancel=(e:globalThis.KeyboardEvent)=>{if(e.key==='Escape'&&gesture.current){gesture.current=null;setDrag(null);e.preventDefault();e.stopPropagation();}};
|
||||
const blur=()=>{gesture.current=null;setDrag(null);};
|
||||
window.addEventListener('pointermove',move,{passive:false});window.addEventListener('pointerup',finish);window.addEventListener('pointercancel',finish);window.addEventListener('keydown',cancel,true);window.addEventListener('blur',blur);
|
||||
return()=>{window.removeEventListener('pointermove',move);window.removeEventListener('pointerup',finish);window.removeEventListener('pointercancel',finish);window.removeEventListener('keydown',cancel,true);window.removeEventListener('blur',blur);};
|
||||
},[primaryId]);
|
||||
useEffect(()=>{if(!enabled||!tools.some(t=>t.open&&t.id===(gesture.current?.id??keyboard?.id))){gesture.current=null;setDrag(null);setKeyboard(null);}},[enabled,tools.map(t=>`${t.id}:${t.open}`).join('|')]);
|
||||
const key=(id:string,e:KeyboardEvent<HTMLElement>)=>{
|
||||
if(e.target!==e.currentTarget)return;
|
||||
const positions={ArrowLeft:'left',ArrowRight:'right',ArrowUp:'top',ArrowDown:'bottom'} as const,position=positions[e.key as keyof typeof positions];
|
||||
if(keyboard?.id===id){
|
||||
if(e.key==='Escape')setKeyboard(null);
|
||||
else if(e.key==='Enter'||e.key===' '){onChange(dockEditorTool(value,primaryId,keyboard.target,id,floatingRect(id)));setKeyboard(null);}
|
||||
else if(e.key==='Home')setKeyboard({id,target:null});
|
||||
else if(e.key==='Tab'){const candidates=Object.keys(rects).filter(x=>x!==id&&x!==primaryId);if(candidates.length){const index=candidates.indexOf(keyboard.target?.overId??'');setKeyboard({id,target:{activeId:id,overId:candidates[(index+(e.shiftKey?-1:1)+candidates.length)%candidates.length],position:keyboard.target?.position??'right',scope:'panel'}});}}
|
||||
else if(position)setKeyboard({id,target:{activeId:id,overId:keyboard.target?.overId??primaryId,position,scope:e.shiftKey||!keyboard.target?'workspace':keyboard.target.scope}});
|
||||
else return;
|
||||
}else if(e.key==='Enter'||e.key===' '){setKeyboard({id,target:null});activate(id);}
|
||||
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds,tools.find(t=>t.id===id)?.minimumSize):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds,tools.find(t=>t.id===id)?.minimumSize)}});}
|
||||
else return;
|
||||
e.preventDefault();e.stopPropagation();
|
||||
};
|
||||
const target=drag?.target??keyboard?.target,active=drag?.id??keyboard?.id;
|
||||
const projected=target&&active?dockEditorTool(value,primaryId,target,active,drag?.current??floatingRect(active)):null;
|
||||
const previewTree=projected?pruneDockTree(projected.tree,visible):null,previewMinimum=dockMinimum(previewTree,minimums);
|
||||
const previewArea={...bounds,width:Math.max(bounds.width,previewMinimum.width),height:Math.max(bounds.height,previewMinimum.height)};
|
||||
const preview=active&&previewTree?dockRects(constrainDockTree(previewTree,previewArea,minimums),previewArea)[active]:null;
|
||||
const announcement=active?`${target?`${actionNames[target.position]} · ${target.scope==='workspace'?'вся область':tools.find(t=>t.id===target.overId)?.label}`:'Свободное окно'}. Стрелки — край, Shift+стрелки — вся область, Tab — панель, Home — свободно, Enter — применить, Escape — отменить.`:'';
|
||||
return <div ref={viewport} className={cn('nodedc-editor-dock',className)} data-editing={enabled||undefined} data-dragging={!!drag||undefined}>
|
||||
<div ref={host} className="nodedc-editor-dock__canvas" style={{minWidth:required.width,minHeight:required.height}}>
|
||||
<EditorSplits tree={constrained} bounds={area} minimums={minimums} onResize={(path,ratio)=>onChange({...value,tree:mergeEditorDockRatios(value.tree,resizeDockSplit(constrained,path,ratio))})}/>
|
||||
<div className="nodedc-editor-dock__primary" data-editor-primary={primaryId} data-dock-corners={editorDockCorners(rects[primaryId],area)} style={rects[primaryId]}>{primary}</div>
|
||||
{tools.map(tool=>{
|
||||
const moving=drag?.id===tool.id,free=!rects[tool.id]||moving;
|
||||
const rect=moving?drag.current:rects[tool.id]??floatingRect(tool.id);
|
||||
return <div key={tool.id} className={cn('nodedc-editor-dock__tool nodedc-glass-material nodedc-ui-root',tool.className)} data-editor-tool={tool.id} data-floating={free||undefined} data-glass-context={free?'scene':undefined} data-dock-corners={free?undefined:editorDockCorners(rect,area)} data-active={order.at(-1)===tool.id||undefined}
|
||||
role="region" aria-label={tool.label} hidden={!enabled||!tool.open} style={{...rect,zIndex:moving?40:free?10+Math.max(0,order.indexOf(tool.id)):1}}
|
||||
onPointerDownCapture={()=>activate(tool.id)} onFocusCapture={()=>activate(tool.id)}>
|
||||
<header className="nodedc-window__head" tabIndex={0} aria-label={`Переместить · ${tool.label}`} aria-roledescription="Перемещаемая панель" onPointerDown={e=>begin(tool.id,e)} onKeyDown={e=>key(tool.id,e)}>
|
||||
<div className="nodedc-window__titles"><h2 className="nodedc-window__title">{tool.title}</h2>{tool.subtitle&&<p className="nodedc-window__subtitle">{tool.subtitle}</p>}</div>
|
||||
<div className="nodedc-window__actions">{tool.actions}<IconButton label={`Закрыть · ${tool.label}`} onClick={tool.onClose}><Icon name="close"/></IconButton></div>
|
||||
</header>
|
||||
<InspectorSelectPolicyContext.Provider value={false}><LoadingContext.Provider value={null}>
|
||||
<div className="nodedc-window__body nodedc-editor-dock__body">{tool.content}</div>
|
||||
{tool.footer&&<footer className="nodedc-window__footer">{tool.footer}</footer>}
|
||||
</LoadingContext.Provider></InspectorSelectPolicyContext.Provider>
|
||||
{free&&windowResizeEdges.map(edge=><div key={edge} className="nodedc-window__resize" data-edge={edge} aria-hidden="true" onPointerDown={e=>begin(tool.id,e,edge)}/>)}
|
||||
</div>;
|
||||
})}
|
||||
{drag&&<div className="nodedc-editor-dock__shield"/>}
|
||||
{preview&&<div className="nodedc-dock-layout__preview nodedc-editor-dock__preview" style={preview} aria-hidden="true"><span>{target&&actionNames[target.position]}</span></div>}
|
||||
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{announcement}</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
function EditorSplits({tree,bounds,minimums,onResize,path=''}:{tree:DockTree;bounds:DockMinimum;minimums:Record<string,DockMinimum>;onResize:(path:string,ratio:number)=>void;path?:string}){
|
||||
if('id' in tree)return null;
|
||||
const k=tree.axis==='x'?'width':'height',span=bounds[k];
|
||||
return <SplitPane className="nodedc-dock-layout__split" separatorAppearance="invisible" orientation={tree.axis==='x'?'vertical':'horizontal'} primarySize={tree.ratio}
|
||||
minPrimarySize={span?dockMinimum(tree.first,minimums)[k]/span*100:0} minSecondarySize={span?dockMinimum(tree.second,minimums)[k]/span*100:0} onPrimarySizeChange={ratio=>onResize(path,ratio)} separatorLabel="Изменить размеры панелей редактора"
|
||||
primary={<EditorSplits tree={tree.first} bounds={{...bounds,[k]:span*tree.ratio/100}} minimums={minimums} onResize={onResize} path={path+'0'}/>}
|
||||
secondary={<EditorSplits tree={tree.second} bounds={{...bounds,[k]:span*(1-tree.ratio/100)}} minimums={minimums} onResize={onResize} path={path+'1'}/>}/>;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import {useContext,useEffect,useId,useLayoutEffect,useRef,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {IconButton} from './Button.js';
|
||||
import {Icon} from './Icon.js';
|
||||
import {WindowSuspensionContext} from './WindowSuspensionContext.js';
|
||||
import {cn} from './cn.js';
|
||||
|
||||
export interface EditorWorkspaceProps {editing:boolean;title:ReactNode;subtitle?:ReactNode;onBack:()=>void;children:ReactNode;className?:string;purpose?:'edit'|'view';headerActions?:ReactNode}
|
||||
/** One mounted renderer moves between its original slot and a modeless editor window. */
|
||||
export function EditorWorkspace({editing,title,subtitle,onBack,children,className,purpose='edit',headerActions}:EditorWorkspaceProps){
|
||||
const suspend=useContext(WindowSuspensionContext);
|
||||
useLayoutEffect(()=>{if(editing)return suspend?.();},[editing,suspend]);
|
||||
const inline=useRef<HTMLDivElement>(null),[host]=useState(()=>document.createElement('div'));
|
||||
const [expanded,setExpanded]=useState(false),opener=useRef<HTMLElement|null>(null),titleId=useId();
|
||||
useLayoutEffect(()=>{host.className='nodedc-editor-workspace__host';inline.current!.append(host);return()=>host.remove();},[host]);
|
||||
useLayoutEffect(()=>{
|
||||
const target=(editing?(document.fullscreenElement??document.body):inline.current!) as HTMLElement&{moveBefore?:(node:Node,before:Node|null)=>void};
|
||||
if(editing)opener.current=document.activeElement instanceof HTMLElement?document.activeElement:null;
|
||||
if(host.parentElement!==target){if(target.moveBefore&&host.isConnected)target.moveBefore(host,null);else target.append(host);}
|
||||
host.dataset.editing=String(editing);
|
||||
if(editing)host.querySelector<HTMLElement>('[data-editor-back]')?.focus({preventScroll:true});
|
||||
else {setExpanded(false);const frame=requestAnimationFrame(()=>{if(opener.current?.isConnected)opener.current.focus({preventScroll:true});});return()=>cancelAnimationFrame(frame);}
|
||||
},[editing,host]);
|
||||
useEffect(()=>{host.dataset.expanded=String(expanded);},[expanded,host]);
|
||||
return <div ref={inline} className={cn('nodedc-editor-workspace__slot',className)}>{createPortal(
|
||||
<div className="nodedc-editor-workspace nodedc-ui-root" data-editing={editing||undefined} role={editing?'dialog':undefined} aria-modal={editing?'false':undefined} aria-labelledby={editing?titleId:undefined}
|
||||
onKeyDown={event=>{if(!editing||event.key!=='Escape'||event.defaultPrevented)return;const dialog=(event.target as HTMLElement).closest('[role=dialog]');if(dialog!==event.currentTarget)return;event.preventDefault();event.stopPropagation();if(expanded)setExpanded(false);else onBack();}}>
|
||||
{editing&&<header className="nodedc-window__head nodedc-editor-workspace__head">
|
||||
<div className="nodedc-window__titles"><h1 id={titleId} className="nodedc-window__title">{title}</h1>{subtitle&&<p className="nodedc-window__subtitle">{subtitle}</p>}</div>
|
||||
<div className="nodedc-window__actions">
|
||||
{headerActions}
|
||||
<IconButton data-editor-back label={purpose==='view'?'Вернуть просмотр в рабочую область':'Вернуться из редактора сцены'} onClick={onBack}><Icon name="chevron-left"/></IconButton>
|
||||
<IconButton label={expanded?(purpose==='view'?'Восстановить окно просмотра':'Восстановить окно редактора'):(purpose==='view'?'Развернуть окно просмотра':'Развернуть окно редактора')} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton>
|
||||
{purpose==='edit'&&<IconButton label="Завершить редактирование сцены" aria-pressed onClick={onBack}><Icon name="edit"/></IconButton>}
|
||||
<IconButton label={purpose==='view'?'Закрыть отдельное окно просмотра':'Закрыть редактор сцены'} onClick={onBack}><Icon name="close"/></IconButton>
|
||||
</div>
|
||||
</header>}
|
||||
<div className="nodedc-editor-workspace__body">{children}</div>
|
||||
</div>,host)}</div>;
|
||||
}
|
||||
@@ -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,362 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } 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 type { FeatureSettingsSection } from "./FeatureSettingsWindow.js";
|
||||
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor.js";
|
||||
|
||||
export interface EnvironmentSettingsWindowProps {
|
||||
/** Product-owned sections reuse this shell; each owns its content and save lifecycle. */
|
||||
additionalSections?: readonly (FeatureSettingsSection & { content: ReactNode; footer?: ReactNode })[];
|
||||
productName: string;
|
||||
surfaces: readonly EnvironmentSurface[];
|
||||
initialSurfaceId?: string;
|
||||
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,
|
||||
additionalSections = [],
|
||||
surfaces,
|
||||
initialSurfaceId,
|
||||
open,
|
||||
settings,
|
||||
state,
|
||||
error,
|
||||
onClose,
|
||||
onSave,
|
||||
onUpload,
|
||||
}: EnvironmentSettingsWindowProps) {
|
||||
const [activeSection, setActiveSection] = useState("environment");
|
||||
const extension = additionalSections.find(section => section.id === activeSection);
|
||||
const [draft, setDraft] = useState(() => cloneEnvironmentSettings(settings));
|
||||
const [surfaceId, setSurfaceId] = useState(initialSurfaceId ?? surfaces[0]?.id ?? "home");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
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",
|
||||
},
|
||||
...additionalSections,
|
||||
]}
|
||||
activeSection={extension ? activeSection : "environment"}
|
||||
onSectionChange={setActiveSection}
|
||||
onClose={onClose}
|
||||
footer={extension ? extension.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>
|
||||
)}
|
||||
>
|
||||
{extension ? extension.content : <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 { Icon, type IconName } from "./Icon.js";
|
||||
import { Window } from "./Window.js";
|
||||
@@ -27,6 +27,7 @@ export interface FeatureSettingsWindowProps<T extends string = string> {
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
headerActions?: ReactNode;
|
||||
}
|
||||
|
||||
export function FeatureSettingsWindow<T extends string>({
|
||||
@@ -40,7 +41,10 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
onClose,
|
||||
children,
|
||||
footer,
|
||||
headerActions,
|
||||
}: FeatureSettingsWindowProps<T>) {
|
||||
const contentRef = useRef<HTMLElement>(null);
|
||||
useLayoutEffect(() => { if (contentRef.current) contentRef.current.scrollTop = 0; }, [activeSection]);
|
||||
return (
|
||||
<Window
|
||||
open={open}
|
||||
@@ -49,11 +53,12 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
size="lg"
|
||||
className="nodedc-feature-settings-window"
|
||||
footer={footer}
|
||||
headerActions={headerActions}
|
||||
closeOnBackdrop={false}
|
||||
onClose={onClose}
|
||||
>
|
||||
<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">
|
||||
<HeaderAvatar label={identity.avatarLabel} imageUrl={identity.avatarUrl} />
|
||||
<span><strong>{identity.title}</strong>{identity.subtitle ? <small>{identity.subtitle}</small> : null}</span>
|
||||
@@ -79,7 +84,7 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
})}
|
||||
</nav>
|
||||
</aside>
|
||||
<section className="nodedc-feature-settings__content">{children}</section>
|
||||
<section ref={contentRef} className="nodedc-feature-settings__content" aria-label="Содержимое настроек" tabIndex={0}>{children}</section>
|
||||
</div>
|
||||
</Window>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { cn } from "./cn.js";
|
||||
|
||||
export interface FieldFrameProps {
|
||||
label: string;
|
||||
labelPlacement?: "above" | "below";
|
||||
hint?: string;
|
||||
description?: string;
|
||||
htmlFor?: string;
|
||||
@@ -10,9 +11,9 @@ export interface FieldFrameProps {
|
||||
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 (
|
||||
<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">{label}</span>
|
||||
{hint ? <span className="nodedc-field__hint">{hint}</span> : null}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { createGlassMaterialVariables, type GlassMaterialSettings } from "@nodedc/ui-core";
|
||||
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export type GlassTone = "default" | "strong" | "soft";
|
||||
export type GlassRadius = "card" | "panel" | "modal";
|
||||
export type GlassTone = "default" | "strong" | "soft" | "group";
|
||||
export type GlassRadius = "card" | "panel" | "modal" | "pill";
|
||||
export type GlassPadding = "none" | "sm" | "md" | "lg";
|
||||
|
||||
export interface GlassSurfaceProps extends HTMLAttributes<HTMLDivElement> {
|
||||
@@ -37,11 +38,17 @@ export function GlassSurface({
|
||||
|
||||
export interface GlassMaterialSurfaceProps extends HTMLAttributes<HTMLDivElement> {
|
||||
children: ReactNode;
|
||||
/** Scene telemetry uses the translucent V4 material, independent of modal density. */
|
||||
context?: "floating" | "scene";
|
||||
radius?: GlassRadius;
|
||||
/** Per-instance appearance; never changes the global theme or other surfaces. */
|
||||
material?: GlassMaterialSettings;
|
||||
radiusPx?: number;
|
||||
}
|
||||
|
||||
/** Canonical modal/Inspector material. General application panels must not use it. */
|
||||
export function GlassMaterialSurface({ children, className, ...props }: GlassMaterialSurfaceProps) {
|
||||
return <div className={cn("nodedc-glass-material", className)} {...props}>{children}</div>;
|
||||
/** Canonical floating/scene-overlay material. Ordinary application panels stay matte. */
|
||||
export function GlassMaterialSurface({ children, className, context = "floating", radius = "modal", material, radiusPx, style, ...props }: GlassMaterialSurfaceProps) {
|
||||
return <div className={cn("nodedc-glass-material", className)} data-glass-context={context} data-radius={radius} style={{ ...material && createGlassMaterialVariables(material, context), ...Number.isFinite(radiusPx) && {borderRadius: Math.max(0, Math.min(120, radiusPx!))}, ...style } as CSSProperties} {...props}>{children}</div>;
|
||||
}
|
||||
|
||||
export interface MapGlassSurfaceProps extends HTMLAttributes<HTMLDivElement> {
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
import {
|
||||
MousePointer2,
|
||||
Pipette,
|
||||
createLucideIcon,
|
||||
Glasses,
|
||||
Cuboid,
|
||||
Move,
|
||||
CirclePlus,
|
||||
Box,
|
||||
Scan,
|
||||
PenTool,
|
||||
RectangleHorizontal,
|
||||
Spline,
|
||||
Undo2,
|
||||
Redo2,
|
||||
Activity,
|
||||
AlertTriangle,
|
||||
Boxes,
|
||||
Building2,
|
||||
Camera,
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Circle,
|
||||
@@ -12,30 +28,42 @@ import {
|
||||
Copy,
|
||||
Database,
|
||||
Download,
|
||||
Eye,
|
||||
EyeOff,
|
||||
ExternalLink,
|
||||
FileText,
|
||||
FolderOpen,
|
||||
Globe2,
|
||||
Image,
|
||||
Inbox,
|
||||
Info,
|
||||
KeyRound,
|
||||
Layers,
|
||||
LayoutDashboard,
|
||||
ListChecks,
|
||||
LocateFixed,
|
||||
LockKeyhole,
|
||||
MailPlus,
|
||||
Map,
|
||||
Maximize2,
|
||||
Minimize2,
|
||||
Network,
|
||||
PanelTop,
|
||||
Pencil,
|
||||
Play,
|
||||
Pin,
|
||||
Power,
|
||||
Plus,
|
||||
Minus,
|
||||
RefreshCw,
|
||||
RotateCw,
|
||||
Save,
|
||||
Search,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
SlidersHorizontal,
|
||||
Square,
|
||||
Terminal,
|
||||
Trash2,
|
||||
UploadCloud,
|
||||
UserCircle,
|
||||
@@ -46,13 +74,41 @@ import {
|
||||
type LucideProps,
|
||||
} from "lucide-react";
|
||||
|
||||
// CAD vocabulary: dimension line, cutting plane and unframed information glyph.
|
||||
const DimensionLine = createLucideIcon('DimensionLine', [
|
||||
['path', {d:'M4 5v14M20 5v14M4 12h16M8 9l-4 3 4 3M16 9l4 3-4 3',key:'dimension'}],
|
||||
]);
|
||||
const SectionPlane = createLucideIcon('SectionPlane', [
|
||||
['path', {d:'m5 7 7-4 7 4v10l-7 4-7-4V7m0 0 7 4 7-4M12 11v10',key:'model'}],
|
||||
['path', {d:'m2 12 10-5 10 5-10 5-10-5Z',key:'plane'}],
|
||||
]);
|
||||
const InformationPlain = createLucideIcon('InformationPlain', [
|
||||
['path', {d:'M12 4h.01M10 9h2v11M9 20h6',key:'information'}],
|
||||
]);
|
||||
const icons = {
|
||||
pipette: Pipette,
|
||||
"add-point": CirclePlus,
|
||||
ruler: DimensionLine,
|
||||
section: SectionPlane,
|
||||
isolate: Glasses,
|
||||
perspective: Cuboid,
|
||||
orthographic: Box,
|
||||
"fit-view": Scan,
|
||||
select: MousePointer2,
|
||||
move: Move,
|
||||
pen: PenTool,
|
||||
rectangle: RectangleHorizontal,
|
||||
curve: Spline,
|
||||
undo: Undo2,
|
||||
redo: Redo2,
|
||||
activity: Activity,
|
||||
alert: AlertTriangle,
|
||||
apps: Boxes,
|
||||
building: Building2,
|
||||
camera: Camera,
|
||||
check: Check,
|
||||
"chevron-down": ChevronDown,
|
||||
"chevron-up": ChevronUp,
|
||||
"chevron-left": ChevronLeft,
|
||||
"chevron-right": ChevronRight,
|
||||
circle: Circle,
|
||||
@@ -60,8 +116,11 @@ const icons = {
|
||||
close: X,
|
||||
copy: Copy,
|
||||
database: Database,
|
||||
pin: Pin,
|
||||
download: Download,
|
||||
edit: Pencil,
|
||||
eye: Eye,
|
||||
"eye-off": EyeOff,
|
||||
expand: Maximize2,
|
||||
external: ExternalLink,
|
||||
file: FileText,
|
||||
@@ -70,7 +129,10 @@ const icons = {
|
||||
grid: LayoutDashboard,
|
||||
image: Image,
|
||||
inbox: Inbox,
|
||||
info: Info,
|
||||
"info-plain": InformationPlain,
|
||||
key: KeyRound,
|
||||
layers: Layers,
|
||||
list: ListChecks,
|
||||
target: LocateFixed,
|
||||
lock: LockKeyhole,
|
||||
@@ -78,14 +140,21 @@ const icons = {
|
||||
minimize: Minimize2,
|
||||
network: Network,
|
||||
panel: PanelTop,
|
||||
plan: Map,
|
||||
play: Play,
|
||||
power: Power,
|
||||
plus: Plus,
|
||||
minus: Minus,
|
||||
profile: UserCircle,
|
||||
refresh: RefreshCw,
|
||||
"rotate-clockwise": RotateCw,
|
||||
save: Save,
|
||||
search: Search,
|
||||
settings: Settings,
|
||||
shield: ShieldCheck,
|
||||
sliders: SlidersHorizontal,
|
||||
stop: Square,
|
||||
terminal: Terminal,
|
||||
trash: Trash2,
|
||||
upload: UploadCloud,
|
||||
users: UsersRound,
|
||||
@@ -99,13 +168,15 @@ export interface IconProps extends Omit<LucideProps, "ref"> {
|
||||
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 filledTransport = name === "play" || name === "stop";
|
||||
|
||||
return (
|
||||
<IconComponent
|
||||
size={size}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeWidth={filledTransport ? 0 : strokeWidth}
|
||||
fill={fill ?? (filledTransport ? "currentColor" : "none")}
|
||||
aria-hidden={label ? undefined : "true"}
|
||||
aria-label={label}
|
||||
role={label ? "img" : undefined}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { Select, type SelectProps } from "./Select.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { IconButton } from "./Button.js";
|
||||
|
||||
export interface InspectorSectionSpec {
|
||||
id: string;
|
||||
@@ -13,10 +14,14 @@ export interface InspectorSectionSpec {
|
||||
disabled?: boolean;
|
||||
tone?: "default" | "accent";
|
||||
icon?: ReactNode;
|
||||
action?: { label: string; icon: ReactNode; onAction: () => void; disabled?: boolean };
|
||||
}
|
||||
|
||||
export interface InspectorProps {
|
||||
sections: InspectorSectionSpec[];
|
||||
/** Spaced form fields above sections and centered actions below them. */
|
||||
header?: ReactNode;
|
||||
footer?: ReactNode;
|
||||
defaultOpen?: string[];
|
||||
openSections?: string[];
|
||||
activeId?: string;
|
||||
@@ -29,6 +34,8 @@ export interface InspectorProps {
|
||||
|
||||
export function Inspector({
|
||||
sections,
|
||||
header,
|
||||
footer,
|
||||
defaultOpen = [],
|
||||
openSections,
|
||||
activeId,
|
||||
@@ -68,12 +75,14 @@ export function Inspector({
|
||||
return (
|
||||
<InspectorSelectPolicyContext.Provider value>
|
||||
<div className={cn("nodedc-inspector", className)} data-variant={variant === "default" ? undefined : variant}>
|
||||
{header ? <div className="nodedc-inspector__header">{header}</div> : null}
|
||||
{groups.map((group, groupIndex) => (
|
||||
<div className="nodedc-inspector__group" key={`${group.label ?? "root"}-${groupIndex}`}>
|
||||
{group.sections.map((section) => {
|
||||
const isOpen = openIds.has(section.id);
|
||||
return (
|
||||
<section className="nodedc-inspector__section" key={section.id}>
|
||||
<div className="nodedc-inspector__section-head" data-action={section.action ? "true" : undefined}>
|
||||
<button
|
||||
type="button"
|
||||
className="nodedc-inspector__section-trigger"
|
||||
@@ -91,14 +100,20 @@ export function Inspector({
|
||||
<span className="nodedc-inspector__section-description">{section.description}</span>
|
||||
) : null}
|
||||
</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>
|
||||
{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}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
{footer ? <div className="nodedc-inspector__footer">{footer}</div> : null}
|
||||
</div>
|
||||
</InspectorSelectPolicyContext.Provider>
|
||||
);
|
||||
|
||||
@@ -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>;
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {levelButtonGeometry,type LevelButtonGeometry} from './levelButtonGeometry.js';
|
||||
export type {LevelButtonGeometry} from './levelButtonGeometry.js';
|
||||
import type {CSSProperties} from 'react';
|
||||
import {Button,type ButtonProps} from './Button.js';
|
||||
import {cn} from './cn.js';
|
||||
|
||||
export interface LevelButtonProps extends Omit<ButtonProps,'children'|'shape'|'value'> {
|
||||
label:string;
|
||||
/** Optional operator geometry; text and padding shrink together below 64 × 24. */
|
||||
geometry?:LevelButtonGeometry;
|
||||
/** Measured fraction. Missing is unknown, never zero or animated progress. */
|
||||
value?:number|null;
|
||||
valueText?:string;
|
||||
freshness?:'live'|'stale'|'unknown';
|
||||
levelTone?:'neutral'|'success'|'warning'|'danger';
|
||||
/** Explicit operator-selected fill; labels retain contrast over both parts. */
|
||||
fillColor?:string;
|
||||
}
|
||||
/** Compact measured resource level which opens details, with native button semantics. */
|
||||
export function LevelButton({label,value,valueText,freshness='live',levelTone='neutral',fillColor,geometry,className,style,...props}:LevelButtonProps){
|
||||
const fraction=typeof value==='number'&&Number.isFinite(value)?Math.max(0,Math.min(1,value)):null;
|
||||
const custom=typeof fillColor==='string'&&/^#[0-9a-f]{6}$/i.test(fillColor)?fillColor:null;
|
||||
const channels=custom?.slice(1).match(/../g)?.map(v=>{const c=parseInt(v,16)/255;return c<=.04045?c/12.92:((c+.055)/1.055)**2.4;});
|
||||
const ink=channels&&(.2126*channels[0]+.7152*channels[1]+.0722*channels[2])>.179?'#000000':'#ffffff';
|
||||
const text=valueText??(fraction===null?'—':`${Math.round(fraction*100)}%`);
|
||||
return <Button {...props} shape="pill" className={cn('nodedc-level-button',className)}
|
||||
aria-label={`${label}: ${text}${freshness==='stale'?' · последние показания':''}`}
|
||||
data-level-tone={levelTone} data-freshness={freshness} data-custom-fill={custom?true:undefined}
|
||||
style={{...style,...levelButtonGeometry(geometry,text.length),'--nodedc-level-percent':`${(fraction??0)*100}%`,...(custom?{'--nodedc-level-custom':custom,'--nodedc-level-ink':ink}:{})} as CSSProperties}><span aria-hidden="true">{text}</span>{custom&&fraction!==null&&<span aria-hidden="true" className="nodedc-level-button__fill">{text}</span>}</Button>;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export interface MediaSourceFieldProps {
|
||||
url: string;
|
||||
fileName?: string | null;
|
||||
uploading?: boolean;
|
||||
disabled?: boolean;
|
||||
previewSrc?: string | null;
|
||||
previewKind?: MediaPreviewKind | null;
|
||||
accept?: string;
|
||||
@@ -43,6 +44,7 @@ export function MediaSourceField({
|
||||
url,
|
||||
fileName,
|
||||
uploading = false,
|
||||
disabled = false,
|
||||
previewSrc,
|
||||
previewKind,
|
||||
accept = "image/*,video/*",
|
||||
@@ -73,11 +75,12 @@ export function MediaSourceField({
|
||||
<div className="nodedc-media-file" hidden={source !== "file"} data-nodedc-media-source-panel="file">
|
||||
<label className="nodedc-media-file__button" htmlFor={inputId}>{fileButtonLabel}</label>
|
||||
<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>
|
||||
<input
|
||||
className="nodedc-media-url"
|
||||
type="url"
|
||||
disabled={disabled || uploading}
|
||||
value={url}
|
||||
hidden={source !== "url"}
|
||||
data-nodedc-media-source-panel="url"
|
||||
@@ -89,6 +92,7 @@ export function MediaSourceField({
|
||||
<div className="nodedc-media-source-switch" aria-label={`${label}: источник`}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled || uploading}
|
||||
className="nodedc-media-source-button"
|
||||
data-active={source === "file" ? "true" : undefined}
|
||||
data-nodedc-media-source-option="file"
|
||||
@@ -98,6 +102,7 @@ export function MediaSourceField({
|
||||
>HD</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled || uploading}
|
||||
className="nodedc-media-source-button"
|
||||
data-active={source === "url" ? "true" : undefined}
|
||||
data-nodedc-media-source-option="url"
|
||||
|
||||
@@ -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; faceOpacity?: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,faceOpacity=1}:NavigationCubeProps) {
|
||||
const [hover,setHover]=useState<string|null>(null);
|
||||
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-face-opacity":faceOpacity,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
|
||||
{cubeRegions(quaternion).map(r=><g key={r.id} role="button" aria-label={`Ракурс: ${r.label}`} aria-disabled={disabled}
|
||||
tabIndex={disabled?-1:0} className={hover===r.label?"is-hovered":""}
|
||||
onPointerEnter={()=>setHover(r.label)} onPointerLeave={()=>setHover(null)}
|
||||
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>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {createContext} from "react";
|
||||
|
||||
/** The shell owns rail width and panel presentation as one state. */
|
||||
export const NavigationPanelState = createContext<{
|
||||
collapsed: boolean;
|
||||
onCollapsedChange: (collapsed: boolean) => void;
|
||||
} | null>(null);
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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" />;
|
||||
}
|
||||
@@ -1,13 +1,30 @@
|
||||
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 { Dropdown } from "./Dropdown.js";
|
||||
import { Button } from "./Button.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { Description } from "./Description.js";
|
||||
import { screenColorPicker } from "./screenColorPicker.js";
|
||||
|
||||
export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> {
|
||||
label: string;
|
||||
orientation?: "horizontal" | "vertical";
|
||||
/** Thin horizontal single-value rail; no containing surface or exact editor. */
|
||||
variant?: "field" | "rail";
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
exactValueBounds?: {
|
||||
min?: number;
|
||||
max?: number;
|
||||
};
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -29,38 +46,57 @@ const normalizeEditedRangeValue = (
|
||||
min: number,
|
||||
max: number,
|
||||
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;
|
||||
const numericStep = step === undefined ? 1 : Number(step);
|
||||
if (!Number.isFinite(numericStep) || numericStep <= 0) return clamped;
|
||||
const precision = Math.min(12, Math.max(decimalPlaces(min), decimalPlaces(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) => (
|
||||
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,
|
||||
orientation = "horizontal",
|
||||
variant = "field",
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
exactValueBounds,
|
||||
step,
|
||||
formatValue = String,
|
||||
formatLimit = String,
|
||||
limitSide = "right",
|
||||
onChange,
|
||||
className,
|
||||
disabled = false,
|
||||
tabIndex,
|
||||
...props
|
||||
}: RangeControlProps) {
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const rangeRef = useRef<HTMLInputElement>(null);
|
||||
const editorRef = useRef<HTMLInputElement>(null);
|
||||
const cancelNextBlurRef = useRef(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(() => editableNumber(value));
|
||||
const [editorContrast, setEditorContrast] = useState<"base" | "fill">("base");
|
||||
const safeMax = max === min ? min + 1 : max;
|
||||
const progress = Math.max(0, Math.min(100, ((value - min) / (safeMax - min)) * 100));
|
||||
const displayValue = formatValue(value);
|
||||
@@ -73,14 +109,38 @@ export function RangeControl({
|
||||
"--nodedc-range-editor-characters": editorCharacters,
|
||||
} as CSSProperties;
|
||||
|
||||
// External undo/redo owns the controlled value even while the exact editor is focused.
|
||||
// Otherwise its next blur would commit an obsolete draft over the restored value.
|
||||
useLayoutEffect(() => setDraft(editableNumber(value)), [value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editing) setDraft(editableNumber(value));
|
||||
}, [editing, value]);
|
||||
|
||||
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) => {
|
||||
if (commit) {
|
||||
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);
|
||||
if (restoreRangeFocus) requestAnimationFrame(() => rangeRef.current?.focus());
|
||||
@@ -102,8 +162,31 @@ export function RangeControl({
|
||||
}
|
||||
};
|
||||
|
||||
if (orientation === "horizontal" && variant === "rail") return (
|
||||
<div className={cn("nodedc-range-rail", className)} data-disabled={disabled || undefined}>
|
||||
<span className="nodedc-range-rail__value" aria-hidden="true">{displayValue}</span>
|
||||
<div ref={rootRef} className="nodedc-range" style={style} data-variant="rail">
|
||||
<input ref={rangeRef} {...props} type="range" value={value} min={min} max={safeMax} step={step}
|
||||
disabled={disabled} tabIndex={tabIndex} aria-label={label} aria-orientation="horizontal"
|
||||
aria-valuetext={displayValue} onChange={event => onChange(Number(event.target.value))}/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (orientation === "vertical") return (
|
||||
<div className="nodedc-range-scale" data-limit-side={limitSide} style={style}>
|
||||
<div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical">
|
||||
<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 (
|
||||
<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
|
||||
ref={rangeRef}
|
||||
{...props}
|
||||
@@ -129,22 +212,14 @@ export function RangeControl({
|
||||
className="nodedc-range__editor"
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
value={editing ? draft : editableNumber(value)}
|
||||
value={draft}
|
||||
aria-label={`${label}: точное значение`}
|
||||
disabled={disabled}
|
||||
spellCheck={false}
|
||||
data-active={editing || undefined}
|
||||
onPointerDown={() => {
|
||||
if (!editing) {
|
||||
setDraft(editableNumber(value));
|
||||
setEditing(true);
|
||||
}
|
||||
}}
|
||||
data-contrast={editorContrast}
|
||||
onFocus={() => {
|
||||
if (!editing) {
|
||||
setDraft(editableNumber(value));
|
||||
setEditing(true);
|
||||
}
|
||||
if (!editing) setEditing(true);
|
||||
}}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={handleEditorKeyDown}
|
||||
@@ -218,7 +293,29 @@ function hsvToHex({ h, s, v }: Hsv): string {
|
||||
return `#${base.map((channel) => Math.round((channel + offset) * 255).toString(16).padStart(2, "0")).join("")}`;
|
||||
}
|
||||
|
||||
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, ...props }: ColorFieldProps) {
|
||||
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, onBlur, onKeyDown, ...props }: ColorFieldProps) {
|
||||
const [draft, setDraft] = useState(value);
|
||||
const [paletteOpen, setPaletteOpen] = useState(false), [picking, setPicking] = useState(false), [pickError, setPickError] = useState(false);
|
||||
const nativePicker = useRef<HTMLInputElement>(null), sampling = useRef<AbortController | null>(null);
|
||||
const screenPicker = screenColorPicker();
|
||||
useEffect(() => () => { sampling.current?.abort(); }, []);
|
||||
useEffect(() => { if (disabled || !paletteOpen) { sampling.current?.abort(); sampling.current = null; setPicking(false); } }, [disabled, paletteOpen]);
|
||||
useEffect(() => setDraft(value), [value]);
|
||||
const sampleScreen = async () => {
|
||||
if (disabled || sampling.current) return;
|
||||
setPickError(false);
|
||||
if (!screenPicker) { nativePicker.current?.click(); return; }
|
||||
const controller = new AbortController(); sampling.current = controller; setPicking(true);
|
||||
try {
|
||||
// open() executes synchronously in this trusted click before the first await.
|
||||
const result = await new screenPicker().open({ signal: controller.signal });
|
||||
if (!controller.signal.aborted && parseHexColor(result.sRGBHex)) { setDraft(result.sRGBHex.toLowerCase()); onChange(result.sRGBHex.toLowerCase()); }
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted && !(error instanceof Error && error.name === 'AbortError')) setPickError(true);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) { setPicking(false); sampling.current = null; }
|
||||
}
|
||||
};
|
||||
const validColor = hexToHsv(value);
|
||||
const [hsv, setHsv] = useState<Hsv>(() => validColor ?? { h: 330, s: 82, v: 100 });
|
||||
const style = { "--nodedc-color-value": validColor ? hsvToHex(validColor) : hsvToHex(hsv) } as CSSProperties;
|
||||
@@ -230,6 +327,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
const commit = (next: Hsv) => {
|
||||
const normalized = { h: clamp(next.h, 0, 360), s: clamp(next.s, 0, 100), v: clamp(next.v, 0, 100) };
|
||||
setHsv(normalized);
|
||||
setDraft(hsvToHex(normalized));
|
||||
onChange(hsvToHex(normalized));
|
||||
};
|
||||
|
||||
@@ -242,6 +340,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
<div className={cn("nodedc-color-field", className)} style={style}>
|
||||
<Dropdown
|
||||
className="nodedc-color-field__dropdown"
|
||||
onOpenChange={setPaletteOpen}
|
||||
placement="bottom-start"
|
||||
minWidth={296}
|
||||
width={296}
|
||||
@@ -294,6 +393,10 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
<span>Оттенок</span>
|
||||
<input type="range" min={0} max={360} value={Math.round(hsv.h)} aria-label={`${label}: оттенок`} disabled={disabled} onChange={(event) => commit({ ...hsv, h: Number(event.target.value) })} />
|
||||
</label>
|
||||
<Button width="full" icon={<Icon name="pipette"/>} disabled={disabled} loading={picking} onClick={() => void sampleScreen()} title={screenPicker ? 'Выбрать цвет в любой точке экрана; Escape — отменить' : 'В этом браузере выбор цвета с экрана доступен через системную палитру, если она поддерживает пипетку'}>
|
||||
{screenPicker ? 'Цвет с экрана' : 'Системная палитра'}
|
||||
</Button>
|
||||
{pickError && <Description role="status">Не удалось включить пипетку. Повторите попытку.</Description>}
|
||||
<div className="nodedc-color-palette__presets" aria-label="Быстрые цвета">
|
||||
{palettePresets.map((preset) => (
|
||||
<button
|
||||
@@ -311,14 +414,28 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
</div>
|
||||
</div>
|
||||
</Dropdown>
|
||||
<input ref={nativePicker} type="color" hidden tabIndex={-1} aria-hidden="true" disabled={disabled} value={validColor ? hsvToHex(validColor) : '#000000'} onChange={event => { setDraft(event.target.value); onChange(event.target.value); }}/>
|
||||
<input
|
||||
className="nodedc-color-field__text"
|
||||
value={value}
|
||||
{...props}
|
||||
value={draft}
|
||||
aria-label={`${label}: HEX`}
|
||||
disabled={disabled}
|
||||
spellCheck={false}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
{...props}
|
||||
onChange={(event) => {
|
||||
const text = event.target.value;
|
||||
setDraft(text);
|
||||
if (parseHexColor(text)) onChange(`#${text.trim().replace(/^#/, "").toLowerCase()}`);
|
||||
}}
|
||||
onBlur={(event) => {
|
||||
setDraft(parseHexColor(draft) ? `#${draft.trim().replace(/^#/, "").toLowerCase()}` : value);
|
||||
onBlur?.(event);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setDraft(value); }
|
||||
if (event.key === "Enter") { event.preventDefault(); event.currentTarget.blur(); }
|
||||
onKeyDown?.(event);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {useRef, type HTMLAttributes, type ReactNode} from "react";
|
||||
import {cn} from "./cn.js";
|
||||
|
||||
export interface ResizableViewportProps extends Omit<HTMLAttributes<HTMLDivElement>, "children" | "onChange"> {
|
||||
children: ReactNode;
|
||||
height: number;
|
||||
minHeight?: number;
|
||||
maxHeight?: number;
|
||||
onHeightChange: (height: number) => void;
|
||||
onHeightCommit?: (height: number) => void;
|
||||
resizeLabel?: string;
|
||||
resizeIndicator?: boolean;
|
||||
}
|
||||
/** In-flow viewer with height-only corner grips. Persistence belongs to its owner. */
|
||||
export function ResizableViewport({children, height, minHeight = 360, maxHeight = 2160, onHeightChange, onHeightCommit, resizeLabel = "Высота 3D-окна", resizeIndicator = true, className, style, ...props}: ResizableViewportProps) {
|
||||
const drag = useRef<{id:number; y:number; height:number; current:number} | null>(null);
|
||||
const fit = (value:number) => Math.round(Math.max(minHeight, Math.min(maxHeight, value)));
|
||||
const current = fit(height);
|
||||
return <div {...props} data-resize-indicator={resizeIndicator ? undefined : "hidden"} className={cn("nodedc-resizable-viewport", className)} style={{...style, height:current}}>
|
||||
{children}
|
||||
{(["start", "end"] as const).map(corner => <div key={corner} className="nodedc-resizable-viewport__grip" data-corner={corner}
|
||||
role="separator" aria-orientation="horizontal" tabIndex={0} aria-label={`${resizeLabel} · ${corner === "start" ? "левый угол" : "правый угол"}`}
|
||||
aria-valuenow={current} aria-valuemin={minHeight} aria-valuemax={maxHeight} aria-valuetext={`${current} px`}
|
||||
onPointerDown={event => {
|
||||
if (event.button !== 0 || drag.current) return;
|
||||
event.preventDefault(); event.stopPropagation(); event.currentTarget.setPointerCapture(event.pointerId);
|
||||
drag.current = {id:event.pointerId, y:event.clientY, height:current, current};
|
||||
}}
|
||||
onPointerMove={event => {
|
||||
const gesture = drag.current;
|
||||
if (!gesture || event.pointerId !== gesture.id) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
gesture.current = fit(gesture.height + event.clientY - gesture.y); onHeightChange(gesture.current);
|
||||
}}
|
||||
onPointerUp={event => {
|
||||
const gesture = drag.current; if (!gesture || event.pointerId !== gesture.id) return;
|
||||
event.stopPropagation(); drag.current = null; event.currentTarget.releasePointerCapture(event.pointerId); onHeightCommit?.(gesture.current);
|
||||
}}
|
||||
onLostPointerCapture={() => {const gesture = drag.current; drag.current = null; if (gesture) onHeightCommit?.(gesture.current);}}
|
||||
onKeyDown={event => {
|
||||
const step = event.shiftKey ? 50 : 10;
|
||||
const next = event.key === "ArrowUp" ? current - step : event.key === "ArrowDown" ? current + step : event.key === "Home" ? minHeight : event.key === "End" ? maxHeight : null;
|
||||
if (next === null) return;
|
||||
event.preventDefault(); event.stopPropagation(); const value = fit(next); onHeightChange(value); onHeightCommit?.(value);
|
||||
}}/>) }
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,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>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {forwardRef} from "react";
|
||||
import {Button,type ButtonProps} from "./Button.js";
|
||||
import {cn} from "./cn.js";
|
||||
/** Screen-projected data anchored to a real scene object; coordinates belong to the renderer. */
|
||||
export const SceneAnnotation=forwardRef<HTMLButtonElement,ButtonProps>(function SceneAnnotation({className,...props},ref){
|
||||
return <Button {...props} ref={ref} variant="ghost" size="dense" className={cn("nodedc-scene-annotation",className)}/>;
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { forwardRef, type ButtonHTMLAttributes, type HTMLAttributes, type ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface SegmentedItem<T extends string> {
|
||||
@@ -7,40 +7,46 @@ export interface SegmentedItem<T extends string> {
|
||||
icon?: ReactNode;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface SegmentedControlProps<T extends string> {
|
||||
value: T;
|
||||
export type SegmentedControlSize = "default" | "dense";
|
||||
export type SegmentedControlProps<T extends string> = {
|
||||
items: Array<SegmentedItem<T>>;
|
||||
label: string;
|
||||
size?: SegmentedControlSize;
|
||||
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>({
|
||||
value,
|
||||
items,
|
||||
label,
|
||||
className,
|
||||
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>
|
||||
);
|
||||
/** Shared capsule for independently controlled toggles and menu triggers. */
|
||||
export function SegmentedGroup({ label, size = "default", className, ...props }:
|
||||
HTMLAttributes<HTMLDivElement> & { label: string; size?: SegmentedControlSize }) {
|
||||
return <div {...props} className={cn("nodedc-segmented", className)} role="group" aria-label={label}
|
||||
data-size={size === "default" ? undefined : size} />;
|
||||
}
|
||||
|
||||
/** 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} />;
|
||||
});
|
||||
|
||||
@@ -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 { Dropdown } from "./Dropdown.js";
|
||||
import { IconButton } from "./Button.js";
|
||||
import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
@@ -10,9 +11,10 @@ export interface SelectOption<T extends string> {
|
||||
description?: string;
|
||||
icon?: ReactNode;
|
||||
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> {
|
||||
value: T;
|
||||
@@ -27,6 +29,8 @@ export interface SelectProps<T extends string> {
|
||||
menuWidth?: number | "anchor";
|
||||
disabled?: boolean;
|
||||
variant?: SelectVariant;
|
||||
/** Split site/workspace selectors can align with adjacent circular actions. */
|
||||
shape?: "default" | "pill";
|
||||
className?: string;
|
||||
triggerClassName?: string;
|
||||
menuClassName?: string;
|
||||
@@ -45,6 +49,7 @@ export function Select<T extends string>({
|
||||
menuWidth = "anchor",
|
||||
disabled = false,
|
||||
variant = "integrated",
|
||||
shape = "default",
|
||||
className,
|
||||
triggerClassName,
|
||||
menuClassName,
|
||||
@@ -52,7 +57,11 @@ export function Select<T extends string>({
|
||||
const inspectorSplitRequired = useContext(InspectorSelectPolicyContext);
|
||||
const resolvedVariant: SelectVariant = inspectorSplitRequired ? "split" : variant;
|
||||
const [query, setQuery] = useState("");
|
||||
const triggerButton = useRef<HTMLButtonElement | null>(null);
|
||||
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 normalized = query.trim().toLocaleLowerCase();
|
||||
if (!normalized) return options;
|
||||
@@ -66,10 +75,15 @@ export function Select<T extends string>({
|
||||
minWidth={minMenuWidth}
|
||||
width={menuWidth}
|
||||
disabled={disabled}
|
||||
surfaceRole="listbox"
|
||||
surfaceRole={popupRole}
|
||||
surfaceClassName={cn(resolvedVariant === "split" && "nodedc-select__menu", menuClassName)}
|
||||
trigger={({ open, toggle, setAnchorRef, setTriggerRef, surfaceId }) => {
|
||||
const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
|
||||
triggerButton.current = event.currentTarget;
|
||||
toggle();
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
|
||||
triggerButton.current = event.currentTarget;
|
||||
if (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
if (!open) toggle();
|
||||
@@ -77,7 +91,7 @@ export function Select<T extends string>({
|
||||
};
|
||||
if (resolvedVariant === "split") {
|
||||
return (
|
||||
<div className={cn("nodedc-select", triggerClassName)} data-disabled={disabled ? "true" : undefined}>
|
||||
<div className={cn("nodedc-select", triggerClassName)} data-shape={shape === "pill" ? "pill" : undefined} data-disabled={disabled ? "true" : undefined}>
|
||||
<div ref={setAnchorRef} className="nodedc-select__control">
|
||||
<div className="nodedc-select__value">
|
||||
{selected?.icon ? <span className="nodedc-select__value-icon">{selected.icon}</span> : null}
|
||||
@@ -88,11 +102,11 @@ export function Select<T extends string>({
|
||||
type="button"
|
||||
className="nodedc-select__toggle"
|
||||
aria-label={label}
|
||||
aria-haspopup="listbox"
|
||||
aria-haspopup={popupRole}
|
||||
aria-controls={surfaceId}
|
||||
aria-expanded={open}
|
||||
disabled={disabled}
|
||||
onClick={toggle}
|
||||
onClick={handleClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<span className="nodedc-select-trigger__chevron" aria-hidden="true" />
|
||||
@@ -102,17 +116,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 (
|
||||
<button
|
||||
ref={setTriggerRef}
|
||||
type="button"
|
||||
className={cn("nodedc-select-trigger", triggerClassName)}
|
||||
aria-label={label}
|
||||
aria-haspopup="listbox"
|
||||
aria-haspopup={popupRole}
|
||||
aria-controls={surfaceId}
|
||||
aria-expanded={open}
|
||||
disabled={disabled}
|
||||
onClick={toggle}
|
||||
onClick={handleClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
{selected?.icon ? <span className="nodedc-select-trigger__icon">{selected.icon}</span> : <span className="nodedc-select-trigger__icon" aria-hidden="true" />}
|
||||
@@ -131,12 +165,13 @@ export function Select<T extends string>({
|
||||
</label>
|
||||
) : null}
|
||||
{visibleOptions.map((option) => (
|
||||
<div key={option.value} className="nodedc-select-option-row">
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
className="nodedc-dropdown-option"
|
||||
role="option"
|
||||
aria-selected={option.value === value}
|
||||
role={withActions ? undefined : "option"}
|
||||
aria-selected={withActions ? undefined : option.value === value}
|
||||
aria-pressed={withActions ? option.value === value : undefined}
|
||||
data-selected={option.value === value ? "true" : undefined}
|
||||
disabled={option.disabled}
|
||||
onClick={() => {
|
||||
@@ -153,6 +188,20 @@ export function Select<T extends string>({
|
||||
</span>
|
||||
{option.value === value ? <span className="nodedc-dropdown-option__check" aria-hidden="true">•</span> : null}
|
||||
</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}
|
||||
</>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { Description } from "./Description.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface SettingsCardProps extends Omit<HTMLAttributes<HTMLElement>, "title"> {
|
||||
@@ -6,20 +7,21 @@ export interface SettingsCardProps extends Omit<HTMLAttributes<HTMLElement>, "ti
|
||||
title: ReactNode;
|
||||
description?: 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 (
|
||||
<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">
|
||||
<div className="nodedc-settings-card__titles">
|
||||
{eyebrow ? <span>{eyebrow}</span> : null}
|
||||
<h2>{title}</h2>
|
||||
{description ? <p>{description}</p> : null}
|
||||
{description ? <Description>{description}</Description> : null}
|
||||
</div>
|
||||
{actions ? <div className="nodedc-settings-card__actions">{actions}</div> : null}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
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 [pointerFocus, setPointerFocus] = useState(false);
|
||||
const limits = normalizedLimits(minPrimarySize, minSecondarySize);
|
||||
const size = clamp(Number.isFinite(primarySize) ? primarySize : 50, limits.minimum, limits.maximum);
|
||||
const keyboardIncrement = Number.isFinite(step) && step > 0 ? step : 2;
|
||||
|
||||
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>) => {
|
||||
setPointerFocus(false);
|
||||
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)}%`}
|
||||
data-pointer-focus={pointerFocus || undefined}
|
||||
onBlur={() => setPointerFocus(false)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button !== 0) return;
|
||||
setPointerFocus(true);
|
||||
event.currentTarget.focus({ preventScroll: true });
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -5,13 +5,15 @@ export type StatusTone = "neutral" | "success" | "warning" | "danger" | "accent"
|
||||
|
||||
export interface StatusBadgeProps extends HTMLAttributes<HTMLSpanElement> {
|
||||
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 (
|
||||
<span className={cn("nodedc-status", className)} data-tone={tone === "neutral" ? undefined : tone} {...props}>
|
||||
{children}
|
||||
<span className={cn("nodedc-status", className)} data-tone={tone === "neutral" ? undefined : tone} data-variant={variant === "indicator" ? variant : undefined} data-pulse={pulse ? "true" : undefined} {...props}>
|
||||
{variant === "indicator" ? null : children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, type HTMLAttributes } from "react";
|
||||
import { useEffect, useRef, type HTMLAttributes } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
@@ -21,6 +21,8 @@ const toastIcons: Record<ToastTone, IconName> = {
|
||||
loading: "refresh",
|
||||
};
|
||||
|
||||
const DEFAULT_TOAST_DURATION_MS = 10_000;
|
||||
|
||||
export interface ToastCardProps extends HTMLAttributes<HTMLDivElement> {
|
||||
item: ToastItem;
|
||||
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 }) {
|
||||
useEffect(() => {
|
||||
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]);
|
||||
function TimedToastCard({ item, onDismiss }: { item: ToastItem; onDismiss: (id: string) => void }) {
|
||||
const dismissRef = useRef(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;
|
||||
return createPortal(
|
||||
<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>,
|
||||
document.body,
|
||||
);
|
||||
|
||||
@@ -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 {
|
||||
calculateToolbarTargets,
|
||||
NODEDC_TOOLBAR_DEFAULTS,
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
stepToolbarSpring,
|
||||
type ToolbarPlacement as CoreToolbarPlacement,
|
||||
} from "@nodedc/ui-core";
|
||||
import { Dropdown, type DropdownTriggerApi } from "./Dropdown.js";
|
||||
import { useToolbarMenus } from "./useToolbarMenus.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
|
||||
@@ -17,6 +19,8 @@ export interface ToolbarItem<T extends string = string> {
|
||||
icon: IconName;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
shortcut?: string;
|
||||
menu?: ReactNode | ((close: () => void) => ReactNode);
|
||||
onSelect: (id: T) => void;
|
||||
}
|
||||
|
||||
@@ -31,8 +35,14 @@ export interface ToolbarProps<T extends string = string> {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
label?: string;
|
||||
/** Dropdown width; placement still clamps to the visible viewport. */
|
||||
menuWidth?: number;
|
||||
className?: string;
|
||||
/** Render inside a positioned viewport; edge reveal follows that viewport. */
|
||||
container?: HTMLElement;
|
||||
}
|
||||
|
||||
interface ToolbarMotion {
|
||||
@@ -55,9 +65,14 @@ export function Toolbar<T extends string = string>({
|
||||
maxSize = NODEDC_TOOLBAR_DEFAULTS.maxSize,
|
||||
lensCount = NODEDC_TOOLBAR_DEFAULTS.lensCount,
|
||||
autoHide = false,
|
||||
hideDelay = NODEDC_TOOLBAR_DEFAULTS.hideDelay,
|
||||
gap = NODEDC_TOOLBAR_DEFAULTS.gap,
|
||||
label = "Панель инструментов",
|
||||
menuWidth = 220,
|
||||
className,
|
||||
container,
|
||||
}: ToolbarProps<T>) {
|
||||
const menus = useToolbarMenus();
|
||||
const [visible, setVisible] = useState(!autoHide);
|
||||
const [dockActive, setDockActive] = useState(false);
|
||||
const toolbarRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -68,16 +83,19 @@ export function Toolbar<T extends string = string>({
|
||||
const frameLastTsRef = useRef(0);
|
||||
const hideTimerRef = useRef<number | null>(null);
|
||||
const hoverDockRef = useRef(false);
|
||||
const openMenusRef = useRef(new Set<string>());
|
||||
|
||||
const vertical = placement !== "bottom";
|
||||
const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount });
|
||||
const vertical = placement === "left" || placement === "right";
|
||||
const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount, gap });
|
||||
const safeMin = normalized.minSize;
|
||||
const safeMax = normalized.maxSize;
|
||||
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 glyphSize = Math.max(12, Math.min(18, Math.round(safeMin * 0.62)));
|
||||
const settingsRef = useRef({ minSize: safeMin, maxSize: safeMax, lensCount: safeLens, vertical });
|
||||
settingsRef.current = { 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, gap:safeGap, vertical };
|
||||
actionKeysRef.current = items.map((item) => String(item.id));
|
||||
|
||||
const getMotion = useCallback((key: string) => {
|
||||
@@ -176,7 +194,7 @@ export function Toolbar<T extends string = string>({
|
||||
const toolbar = toolbarRef.current;
|
||||
const keys = actionKeysRef.current;
|
||||
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 entries = keys
|
||||
.map((key) => {
|
||||
@@ -193,7 +211,7 @@ export function Toolbar<T extends string = string>({
|
||||
const targets = calculateToolbarTargets(
|
||||
entries.map((entry) => entry.center),
|
||||
pointerCoordinate,
|
||||
{ minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: NODEDC_TOOLBAR_DEFAULTS.gap },
|
||||
{ minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: currentGap },
|
||||
);
|
||||
entries.forEach(({ key }, index) => {
|
||||
const target = targets[index];
|
||||
@@ -213,18 +231,19 @@ export function Toolbar<T extends string = string>({
|
||||
if (!autoHide || hideTimerRef.current != null) return;
|
||||
hideTimerRef.current = window.setTimeout(() => {
|
||||
hideTimerRef.current = null;
|
||||
if (hoverDockRef.current) return;
|
||||
if (hoverDockRef.current || openMenusRef.current.size || toolbarRef.current?.contains(document.activeElement)) return;
|
||||
setVisible(false);
|
||||
resetMagnification();
|
||||
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay);
|
||||
}, [autoHide, resetMagnification]);
|
||||
}, safeDelay);
|
||||
}, [autoHide, resetMagnification, safeDelay]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hideTimerRef.current != null) { window.clearTimeout(hideTimerRef.current); hideTimerRef.current = null; }
|
||||
if (!autoHide) {
|
||||
setVisible(true);
|
||||
return;
|
||||
}
|
||||
setVisible(false);
|
||||
setVisible(hoverDockRef.current || openMenusRef.current.size > 0);
|
||||
setDockActive(false);
|
||||
}, [autoHide]);
|
||||
|
||||
@@ -236,17 +255,19 @@ export function Toolbar<T extends string = string>({
|
||||
if (!autoHide) return;
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
const threshold = Math.max(32, settingsRef.current.maxSize * 0.75);
|
||||
const nearEdge = placement === "left"
|
||||
? event.clientX <= threshold
|
||||
const bounds = container?.getBoundingClientRect() ?? {left:0, top:0, right:window.innerWidth, bottom:window.innerHeight};
|
||||
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"
|
||||
? event.clientX >= window.innerWidth - threshold
|
||||
: event.clientY >= window.innerHeight - threshold;
|
||||
? event.clientX >= bounds.right - threshold
|
||||
: placement === "top" ? event.clientY <= bounds.top + threshold : event.clientY >= bounds.bottom - threshold);
|
||||
if (nearEdge) showDock();
|
||||
else if (!hoverDockRef.current) scheduleHide();
|
||||
};
|
||||
window.addEventListener("pointermove", handlePointerMove, { passive: true });
|
||||
return () => window.removeEventListener("pointermove", handlePointerMove);
|
||||
}, [autoHide, placement, scheduleHide, showDock]);
|
||||
}, [autoHide, placement, container, scheduleHide, showDock]);
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
@@ -271,6 +292,11 @@ export function Toolbar<T extends string = string>({
|
||||
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 = {
|
||||
"--nodedc-toolbar-bg": background,
|
||||
"--nodedc-toolbar-border": border,
|
||||
@@ -279,7 +305,7 @@ export function Toolbar<T extends string = string>({
|
||||
"--nodedc-toolbar-min-size": `${safeMin}px`,
|
||||
"--nodedc-toolbar-max-size": `${safeMax}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`,
|
||||
} as CSSProperties;
|
||||
|
||||
@@ -287,6 +313,7 @@ export function Toolbar<T extends string = string>({
|
||||
<div
|
||||
className={cn("nodedc-toolbar-wrap", className)}
|
||||
data-placement={placement}
|
||||
data-scope={container ? "viewport" : "window"}
|
||||
data-visible={visible ? "true" : undefined}
|
||||
data-active={dockActive ? "true" : undefined}
|
||||
data-autohide={autoHide ? "true" : undefined}
|
||||
@@ -324,17 +351,23 @@ export function Toolbar<T extends string = string>({
|
||||
>
|
||||
{items.map((item) => {
|
||||
const key = String(item.id);
|
||||
return (
|
||||
const button = (api?: DropdownTriggerApi) => {
|
||||
if(api)menus.apis.current[key]=api;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
ref={(element) => { buttonRefs.current[key] = element; }}
|
||||
ref={(element) => { buttonRefs.current[key] = element; api?.setTriggerRef(element); }}
|
||||
type="button"
|
||||
className="nodedc-toolbar__button"
|
||||
data-toolbar-menu={item.menu ? key : undefined}
|
||||
data-active={item.active ? "true" : undefined}
|
||||
aria-label={item.label}
|
||||
title={item.shortcut ? `${item.label} · ${item.shortcut}` : item.label}
|
||||
aria-keyshortcuts={item.shortcut}
|
||||
aria-pressed={item.active}
|
||||
disabled={item.disabled}
|
||||
onFocus={(event) => {
|
||||
showDock();
|
||||
const button = event.currentTarget;
|
||||
const toolbarRect = toolbarRef.current?.getBoundingClientRect();
|
||||
if (!toolbarRect) return;
|
||||
@@ -345,11 +378,34 @@ export function Toolbar<T extends string = string>({
|
||||
updateMagnification(coordinate);
|
||||
}}
|
||||
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} />
|
||||
</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={Number.isFinite(menuWidth)?Math.max(180,Math.min(600,menuWidth)):220} trigger={button} onPointerDownOutside={event=>{
|
||||
const target=event.target as Element;
|
||||
// Dismiss a menu before a viewport tool can turn this same click into an edit.
|
||||
if(container?.contains(target)&&!target.closest('button,input,select,textarea,a,[role="button"],[role="tab"]')){
|
||||
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>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user