Compare commits
51
Commits
cb534dbe39
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd08ac46f5 | ||
|
|
bcc121e7b2 | ||
|
|
13309f3209 | ||
|
|
d96eba824a | ||
|
|
6bf22988c5 | ||
|
|
3473cd9ef1 | ||
|
|
753d4d6edc | ||
|
|
533723883d | ||
|
|
8539a211ed | ||
|
|
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 |
@@ -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.4",
|
||||
"@nodedc/ui-react": "0.7.10",
|
||||
"cesium": "1.147.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
|
||||
+115
-30
@@ -1,13 +1,19 @@
|
||||
import { OperationalTypographyDemo } from "./OperationalTypographyDemo";
|
||||
import { ModalSizeExample } from './ModalSizeExample';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { applyGlassMaterial, applyNodedcTheme, defaultGlassMaterial, type GlassMaterialSettings, type NodedcTheme, type RgbTuple } from "@nodedc/ui-core";
|
||||
import { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTemplateDefinition } from "@nodedc/page-patterns";
|
||||
import {MissionThemeExample} from './MissionThemeExample';
|
||||
import {EditorDockExample} from './EditorDockExample';
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Tooltip,
|
||||
LoadingRegion,
|
||||
Description,
|
||||
ComparisonTable,
|
||||
StatusBadge,
|
||||
ProgressBar,
|
||||
LevelButton,
|
||||
ProgressButton,
|
||||
LayerStackIndicator,
|
||||
AdminNavigationPanel,
|
||||
@@ -30,8 +36,9 @@ import {
|
||||
FeatureSettingsWindow,
|
||||
GlassSurface,
|
||||
GlassMaterialSurface,
|
||||
ResizableViewport,
|
||||
SceneAnnotation,
|
||||
HeaderNavigation,
|
||||
HeaderProfile,
|
||||
HeaderWorkspace,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -41,6 +48,7 @@ import {
|
||||
RangeControl,
|
||||
ResourceRow,
|
||||
ResourceList,
|
||||
Tree,
|
||||
SegmentedControl,
|
||||
SegmentedGroup,
|
||||
SegmentedButton,
|
||||
@@ -49,6 +57,7 @@ import {
|
||||
ShareLinkModal,
|
||||
SplitPane,
|
||||
SortableItem,
|
||||
SortableList,
|
||||
SortableScope,
|
||||
SettingsCard,
|
||||
Switch,
|
||||
@@ -56,6 +65,7 @@ import {
|
||||
TextField,
|
||||
ToastCard,
|
||||
ToastStack,
|
||||
ToastObserver,
|
||||
Toolbar,
|
||||
NavigationCube,
|
||||
UserProfileMenu,
|
||||
@@ -117,7 +127,8 @@ const designProfileDocumentPath = (reference: { id: string; version: string; sta
|
||||
);
|
||||
|
||||
const accents: Array<{ label: string; value: RgbTuple; hex: string }> = [
|
||||
{ label: "NODE.DC", value: [255, 47, 146], hex: "#ff2f92" },
|
||||
{ label: "Mission Core", value: [247, 248, 244], hex: "#f7f8f4" },
|
||||
{ label: "Rose", value: [255, 47, 146], hex: "#ff2f92" },
|
||||
{ label: "Rose", value: [255, 62, 108], hex: "#ff3e6c" },
|
||||
{ label: "Blush", value: [255, 108, 175], hex: "#ff6caf" },
|
||||
{ label: "Magenta", value: [215, 70, 255], hex: "#d746ff" },
|
||||
@@ -143,7 +154,7 @@ const materialDefaults: Record<NodedcTheme, MaterialDraft> = {
|
||||
panelOpacity: 100,
|
||||
fieldHex: "#2a2a2c",
|
||||
fieldOpacity: 100,
|
||||
nestedHex: "#0b0b0d",
|
||||
nestedHex: "#0d0d0f",
|
||||
},
|
||||
light: {
|
||||
panelHex: "#ffffff",
|
||||
@@ -221,17 +232,17 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
{
|
||||
title: "Редактирование",
|
||||
note: "Launcher / SEO",
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "orthographic", "perspective", "select", "pen", "rectangle", "curve", "undo", "redo"],
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "ruler", "section", "isolate", "orthographic", "perspective", "fit-view", "select", "pen", "rectangle", "curve", "undo", "redo"],
|
||||
},
|
||||
{
|
||||
title: "Состояние и доступ",
|
||||
note: "Вся платформа",
|
||||
icons: ["check", "alert", "info", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
|
||||
icons: ["check", "alert", "info", "info-plain", "activity", "lock", "unlock", "key", "shield", "circle", "eye", "eye-off", "star"],
|
||||
},
|
||||
{
|
||||
title: "Сущности",
|
||||
note: "Общий словарь",
|
||||
icons: ["profile", "users", "building", "globe", "target", "database", "network", "inbox", "mail"],
|
||||
icons: ["profile", "users", "building", "globe", "target", "database", "pin", "network", "inbox", "mail"],
|
||||
},
|
||||
{
|
||||
title: "Контент",
|
||||
@@ -241,6 +252,11 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
];
|
||||
|
||||
const iconLabels: Record<IconName, string> = {
|
||||
star: "Избранное",
|
||||
pipette: "Пипетка",
|
||||
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
|
||||
power: "Питание",
|
||||
move: "Свободное окно",
|
||||
"add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить",
|
||||
activity: "Активность",
|
||||
alert: "Предупреждение",
|
||||
@@ -257,6 +273,7 @@ const iconLabels: Record<IconName, string> = {
|
||||
close: "Закрыть",
|
||||
copy: "Копировать",
|
||||
database: "База данных",
|
||||
pin: "Закрепить",
|
||||
download: "Скачать",
|
||||
edit: "Редактировать",
|
||||
eye: "Показать",
|
||||
@@ -270,10 +287,13 @@ const iconLabels: Record<IconName, string> = {
|
||||
image: "Изображение",
|
||||
inbox: "Уведомления",
|
||||
info: "Информация",
|
||||
"info-plain": "Информация без окружности",
|
||||
"fit-view": "Вписать модель",
|
||||
key: "Ключ",
|
||||
layers: "Слои",
|
||||
list: "Список задач",
|
||||
lock: "Закрыто",
|
||||
unlock: "Открыто",
|
||||
mail: "Приглашение",
|
||||
minimize: "Свернуть",
|
||||
network: "Связи",
|
||||
@@ -282,6 +302,7 @@ const iconLabels: Record<IconName, string> = {
|
||||
play: "Воспроизвести",
|
||||
target: "Таргеты",
|
||||
plus: "Добавить",
|
||||
minus: "Уменьшить",
|
||||
profile: "Профиль",
|
||||
refresh: "Обновить",
|
||||
"rotate-clockwise": "Повернуть по часовой стрелке",
|
||||
@@ -327,7 +348,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 },
|
||||
@@ -342,6 +363,7 @@ export function CatalogApp() {
|
||||
const [applicationSaveState, setApplicationSaveState] = useState<ApplicationDraftSaveState>("idle");
|
||||
const [applicationError, setApplicationError] = useState("");
|
||||
const [toasts, setToasts] = useState<ToastItem[]>([]);
|
||||
const [observedToasts, setObservedToasts] = useState<ToastItem[]>([]);
|
||||
const toastSequenceRef = useRef(0);
|
||||
const [sessionProfile, setSessionProfile] = useState<FoundrySessionProfile | null>(null);
|
||||
const [foundrySettingsOpen, setFoundrySettingsOpen] = useState(false);
|
||||
@@ -380,14 +402,23 @@ export function CatalogApp() {
|
||||
const [glowDistance, setGlowDistance] = useState(105);
|
||||
const [usePortColors, setUsePortColors] = useState(false);
|
||||
const [connectionType, setConnectionType] = useState("spline");
|
||||
const [lightColor, setLightColor] = useState("#ff2f92");
|
||||
const [lightColor, setLightColor] = useState("#f7f8f4");
|
||||
const [connectionColor, setConnectionColor] = useState("#404040");
|
||||
const [fillColor, setFillColor] = useState("#ff6caf");
|
||||
const [fillOpacity, setFillOpacity] = useState(100);
|
||||
const [strokeColor, setStrokeColor] = useState("#2b2b36");
|
||||
const [strokeOpacity, setStrokeOpacity] = useState(100);
|
||||
const [treeDemoOpen,setTreeDemoOpen]=useState(false);
|
||||
const [gridOrder,setGridOrder]=useState(["Первое изображение","Второе изображение","Третье изображение"]);
|
||||
const [detailFloating,setDetailFloating]=useState(false);
|
||||
const [detailRect,setDetailRect]=useState<import("@nodedc/ui-react").WindowRect>();
|
||||
const [treeDemoRect,setTreeDemoRect]=useState({left:32,top:96,width:380,height:480});
|
||||
const [treeSelected,setTreeSelected]=useState<string|null>('cells');
|
||||
const [treeVisible,setTreeVisible]=useState(true);
|
||||
const [treeSelectedIds,setTreeSelectedIds]=useState<string[]>(['cells']);
|
||||
const [inspectorOpen, setInspectorOpen] = useState(false);
|
||||
const workspaceWindowDemoRef = useRef<HTMLDivElement>(null);
|
||||
const [sceneDemoHeight, setSceneDemoHeight] = useState(480);
|
||||
const [workspaceWindowDemoOpen, setWorkspaceWindowDemoOpen] = useState(true);
|
||||
const [workspaceWindowDemoMaximized, setWorkspaceWindowDemoMaximized] = useState(false);
|
||||
const [workspaceWindowDemoRect, setWorkspaceWindowDemoRect] = useState<WorkspaceWindowRect>({ x: 24, y: 24, width: 340, height: 230 });
|
||||
@@ -396,7 +427,8 @@ export function CatalogApp() {
|
||||
const [splitPaneDemoSize, setSplitPaneDemoSize] = useState(50);
|
||||
const [sidePanelDemoOpen, setSidePanelDemoOpen] = useState(true);
|
||||
const [createModalOpen, setCreateModalOpen] = useState(false);
|
||||
const [missionAppearance, setMissionAppearance] = useState(false);
|
||||
const [missionAppearance, setMissionAppearance] = useState(true);
|
||||
const [flatEdges, setFlatEdges] = useState(true);
|
||||
const [featureSettingsDemoOpen, setFeatureSettingsDemoOpen] = useState(false);
|
||||
const [featureSettingsDemoSection, setFeatureSettingsDemoSection] = useState('general');
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
@@ -536,6 +568,7 @@ export function CatalogApp() {
|
||||
applyNodedcTheme(document.documentElement, {
|
||||
theme,
|
||||
appearance: missionAppearance ? "mission" : "default",
|
||||
edges: flatEdges ? "flat" : "default",
|
||||
accent,
|
||||
material: {
|
||||
panel: panelMaterial,
|
||||
@@ -545,7 +578,7 @@ export function CatalogApp() {
|
||||
},
|
||||
});
|
||||
document.documentElement.style.setProperty("--nodedc-canvas-soft", material.nestedHex);
|
||||
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme, missionAppearance]);
|
||||
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme, missionAppearance, flatEdges]);
|
||||
|
||||
useEffect(() => {
|
||||
applyGlassMaterial(document.documentElement, glassMaterial);
|
||||
@@ -1307,6 +1340,7 @@ export function CatalogApp() {
|
||||
onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)}
|
||||
/>
|
||||
<ControlRow label="Фон"><ColorField value={toolbarBg} onChange={setToolbarBg} /></ControlRow>
|
||||
<Description>HEX можно очистить и набрать заново; Enter применяет, Escape возвращает текущий цвет.</Description>
|
||||
<ControlRow label="Border"><ColorField value={toolbarBorder} onChange={setToolbarBorder} /></ControlRow>
|
||||
<ControlRow label="Outline"><ColorField value={toolbarOutline} onChange={setToolbarOutline} /></ControlRow>
|
||||
<RangeControl label="Минимальный размер" value={toolbarMinSize} min={18} max={42} formatValue={(value) => `${value}px`} onChange={(value) => {
|
||||
@@ -1330,6 +1364,7 @@ export function CatalogApp() {
|
||||
<>
|
||||
<ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow>
|
||||
<RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} />
|
||||
<RangeControl variant="rail" label="Тонкая горизонтальная шкала" value={brightness} min={0} max={100} formatValue={v=>`${v}%`} onChange={setBrightness}/>
|
||||
<div style={{ height: 180 }} title="Тонкая шкала: две границы двигаются независимо; без центрального текста"><RangeControl orientation="vertical" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
|
||||
<div style={{ height: 180, display: 'flex', justifyContent: 'flex-end' }} title="Шкала справа: границы слева; фокус подчёркивает выбранную границу"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
|
||||
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} exactValueBounds={{ min: 0 }} formatValue={(value) => `${value}%`} onChange={setGlowDistance} />
|
||||
@@ -1378,7 +1413,8 @@ export function CatalogApp() {
|
||||
case "controls":
|
||||
return (
|
||||
<div className="catalog-grid">
|
||||
<Preview title="Navigation cube" note="faces / edges / corners"><NavigationCube edgeOpacity={cubeEdgeOpacity} size={cubeSize} quaternion={[.28,-.36,.12,.88]} onSelect={setCubeDirection}/><RangeControl label="Размер 3D-куба" value={cubeSize} min={48} max={160} step={1} onChange={setCubeSize} formatValue={v=>`${v} px`}/><RangeControl label="Прозрачность линий куба" value={1-cubeEdgeOpacity} min={0} max={1} step={.05} onChange={v=>setCubeEdgeOpacity(1-v)} formatValue={v=>`${Math.round(v*100)}%`}/><p>{cubeDirection.join(" · ")}</p></Preview>
|
||||
<Preview title="Mission Core" note="canonical foundation / nested fields / portal" className="catalog-preview--wide"><MissionThemeExample/></Preview>
|
||||
<Preview title="Navigation cube" note="faces / edges / corners"><NavigationCube faceOpacity={.65} edgeOpacity={cubeEdgeOpacity} size={cubeSize} quaternion={[.28,-.36,.12,.88]} onSelect={setCubeDirection}/><RangeControl label="Размер 3D-куба" value={cubeSize} min={48} max={160} step={1} onChange={setCubeSize} formatValue={v=>`${v} px`}/><RangeControl label="Прозрачность линий куба" value={1-cubeEdgeOpacity} min={0} max={1} step={.05} onChange={v=>setCubeEdgeOpacity(1-v)} formatValue={v=>`${Math.round(v*100)}%`}/><p>{cubeDirection.join(" · ")}</p></Preview>
|
||||
<Preview title="Selection" note="integrated / split / inline">
|
||||
<div className="catalog-form">
|
||||
<FieldFrame label="Hub / integrated select" labelPlacement="below">
|
||||
@@ -1394,7 +1430,7 @@ export function CatalogApp() {
|
||||
</FieldFrame>
|
||||
<FieldFrame label="Engine / split select">
|
||||
<Select
|
||||
variant="split"
|
||||
variant="split" shape="pill"
|
||||
label="Тип связи"
|
||||
value={connectionType}
|
||||
options={[
|
||||
@@ -1438,6 +1474,7 @@ export function CatalogApp() {
|
||||
<div className="catalog-form">
|
||||
<TextField label="Название проекта" hint="обязательно" value={projectName} onChange={(event) => setProjectName(event.target.value)} />
|
||||
<TextAreaField label="Описание" value={notes} onChange={(event) => setNotes(event.target.value)} />
|
||||
<TextAreaField appearance="plain" label="" aria-label="Текст заметки" value={notes} onChange={(event) => setNotes(event.target.value)} />
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Действия" note="общая геометрия" className="catalog-preview--compact">
|
||||
@@ -1452,6 +1489,15 @@ export function CatalogApp() {
|
||||
<KeyButton label="Клавиша S недоступна" disabled>S</KeyButton>
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Подсказки" note="Скруглённое стекло без обводки · hover / focus / touch" className="catalog-preview--compact">
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<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">
|
||||
@@ -1488,6 +1534,15 @@ export function CatalogApp() {
|
||||
<SegmentedControl selectionMode="multiple" label="Слои сцены" value={previewLayers} onChange={setPreviewLayers}
|
||||
items={[{value:"source",label:"Источник"},{value:"geometry",label:"Геометрия"},{value:"unavailable",label:"Недоступно",disabled:true}]} />
|
||||
</Preview>
|
||||
<Preview title="Уровень ресурса" note="измерение / последние данные / неизвестно">
|
||||
<LevelButton label="Заряд аккумулятора" value={.82} levelTone="success" onClick={()=>setProjectName("Аккумулятор · 82%")}/>
|
||||
<LevelButton label="Заряд аккумулятора" value={.17} levelTone="warning" freshness="stale"/>
|
||||
<LevelButton label="Заряд аккумулятора" value={null} freshness="unknown" disabled/>
|
||||
<LevelButton label="Белая заливка" value={.82} fillColor="#ffffff"/>
|
||||
<LevelButton label="Чёрная заливка" value={.82} fillColor="#000000"/>
|
||||
<LevelButton label="Минимальный индикатор" value={1} valueText="100%" fillColor="#ffffff" geometry={{width:32,height:12,radius:4}}/>
|
||||
<LevelButton label="Широкий индикатор" value={.82} geometry={{width:160,height:24,radius:8}}/>
|
||||
</Preview>
|
||||
<Preview title="Линейный прогресс" note="измеренный / неизвестный / завершённый">
|
||||
<ProgressBar label="Подготовка" value={0.6} valueText="Три этапа из пяти" />
|
||||
<ProgressBar label="Получение сведений" />
|
||||
@@ -1499,9 +1554,14 @@ export function CatalogApp() {
|
||||
<li><ResourceRow icon={<Icon name="camera" />} title="Подключённая камера" description="Индикатор перед названием" statusPlacement="leading" status={<StatusBadge variant="indicator" tone="success" aria-label="Подключено" title="Подключено" />} actions={<IconButton label="Просмотреть камеру" onClick={() => setProjectName("Подключённая камера")}><Icon name="eye" /></IconButton>} /></li>
|
||||
<li><ResourceRow icon={<Icon name="camera" />} title="Подготовка камеры" metadata="Проверка потоков" progress={{label:"Подготовка камеры",value:0.8}} aria-busy="true" actions={<IconButton label="Просмотр недоступен" disabled><Icon name="eye" /></IconButton>} /></li>
|
||||
</ResourceList>
|
||||
<Button onClick={()=>setTreeDemoOpen(true)}>Дерево объектов · изменяемый размер</Button>
|
||||
<DragDropRoot onDragEnd={()=>{}}><DraggableItem id="whole-material-tile">{({activator})=><Button {...activator.attributes} {...activator.listeners}>Перенос за всю плитку</Button>}</DraggableItem></DragDropRoot>
|
||||
<SortableList handleSurface="control" layout="grid" className="catalog-sortable-grid" items={gridOrder} getId={item=>item} onReorder={setGridOrder}>{(item,{handle})=><GlassSurface padding="sm">{handle}<Icon name="image"/><Description>{item}</Description></GlassSurface>}</SortableList>
|
||||
<SettingsCard title="Устройства не обнаружены" description="Подключите устройство, чтобы оно появилось в списке." />
|
||||
<SettingsCard align="center" role="status" title="Настройки применены" description="Проверьте подключение устройства." />
|
||||
</Preview>
|
||||
<Preview title="Операционная типографика" note="единый размер во всех состояниях"><OperationalTypographyDemo /></Preview>
|
||||
<Preview title="Размер DOM-окна" note="геометрия с сохранением в приложении"><ModalSizeExample /></Preview>
|
||||
<Preview title="Главная и окружение" note="единые компоненты · сохранение в памяти каталога">
|
||||
<EnvironmentCatalogDemo />
|
||||
</Preview>
|
||||
@@ -1569,7 +1629,7 @@ export function CatalogApp() {
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
|
||||
</Preview>
|
||||
<Preview title="Split pane" note="pointer / keyboard / controlled" className="catalog-preview--wide catalog-split-pane-preview">
|
||||
<Preview title="Split pane" note="pointer resize: invisible / keyboard focus: visible" className="catalog-preview--wide catalog-split-pane-preview">
|
||||
<Switch label="Скрыть линию разделителя" checked={splitPaneInvisible} onChange={setSplitPaneInvisible} />
|
||||
<div className="catalog-split-pane-demo">
|
||||
<SplitPane
|
||||
@@ -1585,12 +1645,13 @@ export function CatalogApp() {
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">Граница изменяет контролируемую долю панелей; клавиши и pointer используют одни ограничения, а resize контейнера не сбрасывает выбранное соотношение.</p>
|
||||
</Preview>
|
||||
<Preview title="Dock layout" note="center swap / four edges / keyboard" className="catalog-preview--wide">
|
||||
<Preview title="Dock layout" note="center swap / panel edges / workspace edges / keyboard" className="catalog-preview--wide">
|
||||
<div style={{height:420}}><DockLayout tree={dockDemoTree} onTreeChange={setDockDemoTree}
|
||||
panels={[{id:'camera',label:'Камера'},{id:'depth',label:'Глубина'},{id:'map',label:'Карта'},{id:'scene',label:'Сцена',minimumSize:{width:320,height:280}}]}
|
||||
renderPanel={id=><GlassSurface tone="soft" radius="panel" style={{height:'100%'}}><DockHandle id={id} label={id}/><strong>{id}</strong></GlassSurface>}/></div>
|
||||
<p>Центр — обмен, край — разделение. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой.</p>
|
||||
<p>Центр окна — обмен, край окна — разделение, внешний край всей области — на всю сторону. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой; Shift + стрелки выбирают край всей области.</p>
|
||||
</Preview>
|
||||
<Preview title="Scene editor docking" note="fixed primary / detachable tools / return" className="catalog-preview--wide"><EditorDockExample/></Preview>
|
||||
<Preview title="Application side panel" note="end / push / controlled" className="catalog-preview--wide catalog-side-panel-preview">
|
||||
<div className="catalog-side-panel-demo">
|
||||
{sidePanelDemoOpen ? (
|
||||
@@ -1598,6 +1659,7 @@ export function CatalogApp() {
|
||||
eyebrow="MAP / SETTINGS"
|
||||
title="Настройки карты"
|
||||
description="Theme-aware application panel"
|
||||
headerActions={<IconButton label="Настройки панели" onClick={() => setInspectorOpen(true)}><Icon name="settings" /></IconButton>}
|
||||
onClose={() => setSidePanelDemoOpen(false)}
|
||||
>
|
||||
<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 />
|
||||
@@ -1696,16 +1758,22 @@ export function CatalogApp() {
|
||||
case "glass":
|
||||
return (
|
||||
<div className="catalog-glass-lab">
|
||||
<section className="catalog-glass-stage">
|
||||
<ResizableViewport className="catalog-glass-stage" resizeIndicator={false} height={sceneDemoHeight} minHeight={360} maxHeight={900} onHeightChange={setSceneDemoHeight}>
|
||||
<video key={stageMediaSrc} autoPlay muted loop playsInline aria-hidden="true"><source src={stageMediaSrc} type="video/mp4" /></video>
|
||||
<div className="catalog-glass-stage__shade" />
|
||||
<GlassMaterialSurface className="catalog-glass-stage__sample">
|
||||
<div className="catalog-viewport-actions nodedc-viewport-controls">
|
||||
<IconButton label="Приблизить пример" onClick={()=>setSceneDemoHeight(value=>Math.min(900,value+40))}><Icon name="plus"/></IconButton>
|
||||
<IconButton label="Отдалить пример" onClick={()=>setSceneDemoHeight(value=>Math.max(360,value-40))}><Icon name="minus"/></IconButton>
|
||||
<IconButton label="Вернуть размер примера" onClick={()=>setSceneDemoHeight(480)}><Icon name="select"/></IconButton>
|
||||
</div>
|
||||
<GlassMaterialSurface context="scene" radius="panel" material={glassMaterial} radiusPx={24} className="catalog-glass-stage__sample">
|
||||
<span>CANONICAL GLASS</span>
|
||||
<h2>Модальное окно и Inspector</h2>
|
||||
<h2>Прозрачная плашка над сценой</h2>
|
||||
<SceneAnnotation aria-label="Ячейка 01 · 4,15 В"><span>01</span><strong>4,15 В</strong></SceneAnnotation>
|
||||
<p>Фон остаётся различимым, но текст и контролы сохраняют контраст. Этот материал не применяется к обычным панелям приложения.</p>
|
||||
<div className="catalog-inline"><TextField label="Пример поля" name="organization" autoComplete="organization" defaultValue="NODE.DC" description="Автозаполнение сохраняет материал поля и клавиатурный фокус текущей темы." /><Button variant="primary" shape="pill">Применить</Button></div>
|
||||
</GlassMaterialSurface>
|
||||
</section>
|
||||
</ResizableViewport>
|
||||
<SettingsCard eyebrow="ENGINE / GLASS V4" title="Параметры материала" description="Общий token-контракт ui-core; изменения сразу видны на preview, модалках и Inspector.">
|
||||
<div className="catalog-glass-controls">
|
||||
<ControlRow label="Цвет тонировки"><ColorField value={glassMaterial.tintHex} onChange={(tintHex) => setGlassMaterial((current) => ({ ...current, tintHex }))} /></ControlRow>
|
||||
@@ -1736,6 +1804,7 @@ export function CatalogApp() {
|
||||
</div>
|
||||
</SettingsCard>
|
||||
<SettingsCard eyebrow="LIVE STATES" title="Проверка стека" description="Кнопки используют тот же bottom-right viewport, что и реальные save/update flows.">
|
||||
<Description>Последняя передача приложению: {observedToasts.map(item => item.title).join(', ') || 'нет уведомлений'}</Description>
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<Button onClick={() => pushToast("success", "Изменения сохранены", "Статус автоматически исчезнет.")}>Success</Button>
|
||||
<Button onClick={() => pushToast("info", "Профиль применён", "Application использует выбранную версию.")}>Info</Button>
|
||||
@@ -1760,7 +1829,7 @@ export function CatalogApp() {
|
||||
<p className="catalog-preview__explanation">Destructive-цвет появляется только у подтверждения.</p>
|
||||
<Button variant="danger" shape="pill" icon={<Icon name="trash" />} onClick={() => setConfirmOpen(true)}>Проверить удаление</Button>
|
||||
</Preview>
|
||||
<Preview title="Настройки модуля" note="адаптивное меню и форма" className="catalog-modal-preview"><Switch label="Визуальный профиль Mission Core" checked={missionAppearance} onChange={setMissionAppearance} />
|
||||
<Preview title="Настройки модуля" note="адаптивное меню и форма" className="catalog-modal-preview"><Switch label="Без декоративных обводок" checked={flatEdges} onChange={setFlatEdges} /><Switch label="Визуальный профиль Mission Core" checked={missionAppearance} onChange={setMissionAppearance} />
|
||||
<Button icon={<Icon name="settings" />} onClick={() => setFeatureSettingsDemoOpen(true)}>Открыть настройки модуля</Button>
|
||||
</Preview>
|
||||
<Preview title="Workflow sharing" note="ENGINE / access" className="catalog-modal-preview">
|
||||
@@ -1801,6 +1870,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 surface="none" label="В избранное" aria-pressed="false"><Icon name="star" /></IconButton>
|
||||
<IconButton surface="none" label="Убрать из избранного" aria-pressed="true"><Icon name="star" fill="currentColor" /></IconButton>
|
||||
<IconButton label="Камера включена" aria-pressed="true"><Icon name="camera" /></IconButton>
|
||||
<IconButton label="План"><Icon name="plan" /></IconButton>
|
||||
<IconButton label="Добавить"><Icon name="plus" /></IconButton>
|
||||
@@ -1918,7 +1989,7 @@ export function CatalogApp() {
|
||||
title="Состав страниц"
|
||||
description="Перетащите готовую страницу справа в конфигурацию приложения. Свободного canvas и произвольных компонентов нет."
|
||||
>
|
||||
<DragDropRoot onDragEnd={({ activeData, activeId, activeRect, overData, overId, overRect }) => {
|
||||
<DragDropRoot renderOverlay={({data})=><GlassSurface padding="sm"><span>{data?.type==='page-template'?getPageTemplate(String(data.templateId))?.title:'Страница'}</span></GlassSurface>} onDragEnd={({ activeData, activeId, activeRect, overData, overId, overRect }) => {
|
||||
if (!overId) return;
|
||||
if (activeData?.type === "page-template" && (overId === "application-pages" || overData?.type === "application-page")) {
|
||||
const horizontalOverlap = activeRect && overRect
|
||||
@@ -2132,10 +2203,12 @@ 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"
|
||||
headerAction={{label: 'Правая панель', pressed: sidePanelDemoOpen, onSelect: () => setSidePanelDemoOpen(open => !open)}}
|
||||
displayName={sessionProfile?.user?.displayName || "Профиль"}
|
||||
subtitle={sessionProfile?.user?.email || "NODE.DC Foundry"}
|
||||
avatarUrl={sessionProfile?.user?.avatarUrl || undefined}
|
||||
@@ -2145,7 +2218,6 @@ export function CatalogApp() {
|
||||
{ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" },
|
||||
]}
|
||||
/>
|
||||
</HeaderProfile>
|
||||
}
|
||||
/>
|
||||
}
|
||||
@@ -2167,6 +2239,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" ? (
|
||||
@@ -2308,7 +2382,7 @@ export function CatalogApp() {
|
||||
maxSize={toolbarMaxSize}
|
||||
lensCount={toolbarLensCount}
|
||||
autoHide={toolbarAutoHide}
|
||||
hideDelay={toolbarHideDelay} gap={toolbarGap}
|
||||
hideDelay={toolbarHideDelay} gap={toolbarGap} menuWidth={320}
|
||||
items={[{id:"hold",label:toolbarAutoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!toolbarAutoHide,onSelect:()=>setToolbarAutoHide(v=>!v)}, ...(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
|
||||
id,
|
||||
label: item.title,
|
||||
@@ -2320,21 +2394,30 @@ export function CatalogApp() {
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
|
||||
<div className="nodedc-viewport-surface" data-glass-context="scene"><IconButton label="Проверить fullscreen внутри окна" onClick={event=>{const viewport=event.currentTarget.parentElement!;void (document.fullscreenElement===viewport?document.exitFullscreen():viewport.requestFullscreen());}}><Icon name="expand"/></IconButton><Description>Окно и дерево сохраняются при развороте этого viewport и возврате.</Description></div>
|
||||
<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}
|
||||
floating={detailFloating} onFloatingChange={setDetailFloating}
|
||||
rect={detailRect} onRectCommit={setDetailRect}
|
||||
title="Создать модуль"
|
||||
subtitle="APPLICATION / DRAFT"
|
||||
headerActionsPlacement="before-close"
|
||||
headerActions={<IconButton label="Очистить форму" onClick={() => {setCreateModuleName("");setCreateModuleSlug("");}}><Icon name="trash"/></IconButton>}
|
||||
subtitle="Свободное окно · шапка: перемещение · края: размер"
|
||||
size="sm"
|
||||
onClose={() => setCreateModuleOpen(false)}
|
||||
footer={
|
||||
@@ -2428,14 +2511,14 @@ export function CatalogApp() {
|
||||
|
||||
<FoundrySettingsModal open={foundrySettingsOpen} isAdmin={isFoundryAdmin} onClose={() => setFoundrySettingsOpen(false)} />
|
||||
|
||||
<FeatureSettingsWindow open={featureSettingsDemoOpen} title="Настройки модуля" subtitle="Настройки и меню доступны также в полноэкранном просмотре"
|
||||
<FeatureSettingsWindow open={featureSettingsDemoOpen} title="Настройки модуля" subtitle="При откреплении окно использует стекло viewport; настройки доступны в полноэкранном просмотре"
|
||||
identity={{ title: 'Модуль', subtitle: 'Пример общего компонента', avatarLabel: 'DC' }}
|
||||
sections={[{ id: 'general', label: 'Основное', icon: 'settings' }, ...Array.from({length:16}, (_,i)=>({id:`details-${i}`,label:`Раздел ${i+1}`,group:'Сведения'}))]}
|
||||
activeSection={featureSettingsDemoSection} onSectionChange={setFeatureSettingsDemoSection}
|
||||
headerActions={<IconButton label="Обновить настройки примера" onClick={() => setProjectName('Обновлено')}><Icon name="refresh" /></IconButton>}
|
||||
onClose={() => setFeatureSettingsDemoOpen(false)}>
|
||||
{featureSettingsDemoSection === 'general' ? <SettingsCard title="Основное"><TextField label="Название модуля" value={projectName} onChange={(event) => setProjectName(event.target.value)} /></SettingsCard>
|
||||
: <SettingsCard title="Сведения" description="Общее пояснение к данным."><Description>Текст в теле использует тот же стиль.</Description><ComparisonTable density="compact" label="Сравнение устройств" heading="Устройство" columns={Array.from({length:4},(_,i)=>({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/><LoadingRegion aggregate loading label="Загрузка сведений"><LoadingRegion loading label="Вложенный запрос A"/><LoadingRegion loading label="Вложенный запрос B"/></LoadingRegion></SettingsCard>}
|
||||
: <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
|
||||
@@ -2567,7 +2650,9 @@ export function CatalogApp() {
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
onConfirm={() => setConfirmOpen(false)}
|
||||
/>
|
||||
<ToastStack items={toasts} onDismiss={dismissToast} />
|
||||
<ToastObserver onPresent={setObservedToasts}>
|
||||
<ToastStack items={toasts} onDismiss={dismissToast} />
|
||||
</ToastObserver>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>Сцена → Модель → Детали. Захват шапки — без рамки; Tab и стрелки — клавиатурное управление.</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></>;
|
||||
}
|
||||
@@ -15,13 +15,14 @@ export function EnvironmentCatalogDemo() {
|
||||
useEffect(() => () => urls.current.forEach(url => URL.revokeObjectURL(url)), []);
|
||||
return <>
|
||||
<div className="catalog-environment-actions">
|
||||
<UserProfileMenu displayName="DC" subtitle="Каталог компонентов" triggerLabel={null}
|
||||
<UserProfileMenu variant="default" displayName="DC" subtitle="Каталог компонентов" triggerLabel={null}
|
||||
actions={[{ id: "settings", label: "Настройки", icon: "settings", onSelect: () => setOpen(true) }]} />
|
||||
<Button variant="primary" tone="neutral" onClick={() => setOpen(true)}>Настройки окружения</Button>
|
||||
<Button variant="primary" tone="neutral" disabled>Неактивное действие</Button>
|
||||
</div>
|
||||
<div className="catalog-environment-stage"><LandingStage page={settings.pages.home} /></div>
|
||||
<EnvironmentSettingsWindow open={open} onClose={() => setOpen(false)} productName="Продукт"
|
||||
additionalSections={[{ id: "storage", label: "Хранилище", icon: "database", content: <p>Настройки хранения продукта используют общий каркас окна.</p> }]}
|
||||
surfaces={[{ id: "home", home: true, description: "Главная страница продукта", actions: [] }]}
|
||||
settings={settings} state="ready" error={null}
|
||||
onSave={async draft => { const next = { ...draft, revision: draft.revision + 1 }; setSettings(next); return next; }}
|
||||
|
||||
@@ -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>
|
||||
</>;
|
||||
}
|
||||
@@ -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>,
|
||||
);
|
||||
|
||||
|
||||
@@ -2304,3 +2304,8 @@ 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);}
|
||||
|
||||
.catalog-sortable-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:var(--nodedc-space-3,12px)}
|
||||
|
||||
+80
-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 |
|
||||
@@ -87,3 +88,79 @@ 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 самих контролов сохраняется.
|
||||
|
||||
+174
-9
@@ -4,17 +4,18 @@
|
||||
|
||||
## GlassSurface
|
||||
|
||||
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал с blur и rim используется только у floating-слоёв: modal `Window` и portal-dropdown/select.
|
||||
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал используется у floating-слоёв и явно выбранных информационных плашек над 3D-сценой.
|
||||
|
||||
- `default` — обычная карточка/панель;
|
||||
- `strong` — dropdown, modal и поверхность над сложным фоном;
|
||||
- `soft` — вложенная или вторичная область.
|
||||
- `soft` — утопленная вторичная область / canvas, не подложка формы;
|
||||
- `group` — нейтральная группа как SettingsCard, для самостоятельного элемента коллекции.
|
||||
|
||||
`radius="pill"` задаёт каноническую капсульную геометрию через `--nodedc-radius-circle`. Она предназначена, в частности, для компактных вертикальных и горизонтальных реек из круглых действий: верхняя и нижняя части поверхности повторяют круг кнопок без прямых торцевых пролётов. Consumer не воспроизводит этот радиус локальным CSS.
|
||||
|
||||
Material rim допустим только как часть floating glass. Жёсткая цветная рамка, случайный browser outline или debug border не являются rim.
|
||||
|
||||
`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют только modal `Window` и modeless draggable Inspector; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную.
|
||||
`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют modal `Window`, modeless draggable Inspector и информационные плашки над 3D через `context="scene"`; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную.
|
||||
|
||||
## Button и IconButton
|
||||
|
||||
@@ -45,7 +46,7 @@ Icon-only action по умолчанию круглый. Квадратная к
|
||||
|
||||
## Field
|
||||
|
||||
FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
|
||||
FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. `appearance="plain"` сохраняет вид обычного текста без подложки и позволяет сразу поставить каретку; при пустой подписи нужен `aria-label`. TextAreaField в этом режиме растёт по содержимому и ширине окна, нативные выделение, вставка и undo сохраняются. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
|
||||
|
||||
Приложение не должно вручную собирать label и input, если подходит Field. Ошибка и validation state будут расширением этого контракта, а не локальным классом приложения.
|
||||
|
||||
@@ -57,6 +58,8 @@ FieldFrame объединяет label, control, hint и description. `labelPlace
|
||||
|
||||
## RangeControl
|
||||
|
||||
`RangeControl variant="rail"` — горизонтальный односторонний вариант тонкой шкалы среза: та же толщина `0.2 × --nodedc-control-height`, заполнение слева и текущее `formatValue` над шкалой. Общей подложки, стекла, рамки и тени нет; прозрачная область захвата не ниже 24 px. Native range сохраняет стрелки, Home/End, доступное имя и disabled; focus-visible подчёркивает значение. Точный ввод остаётся у обычного варианта `field`. Позиционирование в viewport и время показа задаёт приложение.
|
||||
|
||||
Вертикальная шкала занимает `0.2 × --nodedc-control-height` (9.2 px при 46 px), вдвое тоньше предыдущей. Прозрачная область захвата не уже 24 px.
|
||||
|
||||
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. `min/max` задают только рабочий диапазон перетаскивания; ручной ввод по умолчанию принимает любое конечное число и не меняет геометрию ползунка. Опциональный `exactValueBounds` независимо задаёт жёсткие границы ручного ввода: например, `{ min: 0 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком.
|
||||
@@ -77,9 +80,9 @@ Engine/BIM-геометрия color field: круглый swatch и HEX-знач
|
||||
|
||||
## Dropdown
|
||||
|
||||
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. It does not change the material. Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
|
||||
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. The same scope now supplies scene Glass V4 to control backgrounds (owner revision 2026-11-14). Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
|
||||
|
||||
For opaque controls directly above imagery, `nodedc-scene-controls` adds the same geometry plus a common opaque field surface. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
|
||||
`nodedc-scene-controls` is the compatibility alias for the same geometry and scene Glass V4 material. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
|
||||
|
||||
Dropdown владеет floating-layer поведением:
|
||||
|
||||
@@ -126,12 +129,16 @@ Window — единая механика открытия modal и правой
|
||||
|
||||
Содержание, сохранение и запросы принадлежат приложению.
|
||||
|
||||
Отсоединённое центральное окно автоматически получает `data-glass-context="scene"` и каноническое стекло viewport. Подтверждение несохранённого профиля использует `allowFloating={false}` и отдельные действия отмены, отказа и сохранения.
|
||||
|
||||
`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.
|
||||
@@ -182,6 +189,8 @@ ConfirmationModal оборачивает Window и защищает async-confir
|
||||
|
||||
## SplitPane
|
||||
|
||||
Невидимый разделитель остаётся прозрачным при наведении и pointer-resize, даже после ввода в текстовом поле. Клавиатурное изменение размера сохраняет видимый focus cue.
|
||||
|
||||
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
|
||||
|
||||
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
|
||||
@@ -228,7 +237,14 @@ Pill navigation для верхней панели и компактного п
|
||||
|
||||
## UserProfileMenu
|
||||
|
||||
Каноническая выпадашка профиля для правой группы `AppHeader`. Она использует
|
||||
Каноническая правая группа `AppHeader`: «Профиль» → inbox → аватар.
|
||||
`UserProfileMenu` владеет всей группой, включая `HeaderProfile`; приложение
|
||||
передаёт только identity и действия. Настройки находятся в меню, отдельной
|
||||
шестерёнки после аватара нет. Нельзя добавлять внешнюю обёртку или локальные
|
||||
отступы. Все три элемента открывают меню; Escape возвращает фокус на вызвавшую кнопку.
|
||||
На узком экране подпись скрывается по общей адаптивной механике; иконка и аватар остаются доступны.
|
||||
|
||||
Она использует
|
||||
общий portal `Dropdown`, показывает identity cover с аватаром, именем и
|
||||
подписью и принимает список application-owned действий.
|
||||
|
||||
@@ -270,6 +286,8 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
Точные состояния и размеры зафиксированы в `docs/APPLICATION_TEMPLATE.md`.
|
||||
|
||||
Внешняя область stage использует `overflow: clip`: скрытый сдвинутый stage не должен создавать горизонтальную прокрутку всего приложения при смене фокуса или работе с плавающим окном. Прокрутка предметного содержимого остаётся внутри соответствующей панели.
|
||||
|
||||
## MediaSourceField
|
||||
|
||||
Общий компонент Launcher/CMS для медиа-поля: file control, имя файла, URL input, переключатель `HD / URL`, круглое превью, path/hint/error. Один контракт применяется и для stage-видео, и для изображений/логотипов; тип файла, подписи и preview задаёт consumer. Публичный API контролируемый.
|
||||
@@ -278,6 +296,13 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
## SettingsCard и Switch
|
||||
|
||||
В `UserProfileMenu` необязательный `headerAction={{label, onSelect}}` отделяет
|
||||
действие средней иконки от меню профиля. Аватар и текст профиля сохраняют меню.
|
||||
`ToastObserver onPresent` сообщает приложению новые и изменённые завершённые
|
||||
уведомления из вложенных `ToastStack`; хранение, даты и история принадлежат
|
||||
приложению. `ToastStack observe={false}` исключает повторную регистрацию
|
||||
сообщений, уже записанных сервером. Отображение и таймеры не изменяются.
|
||||
|
||||
`SettingsCard` фиксирует нейтральную структуру админской группы: eyebrow/title/description/actions/body. `Switch` покрывает компактное включение/видимость внутри таких групп. Данные секции, сохранение и права остаются в consumer.
|
||||
|
||||
Промежуточный loading-контейнер не должен обнулять вертикальный ритм тела
|
||||
@@ -304,8 +329,29 @@ 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
|
||||
|
||||
Перед кнопкой закрытия можно разместить действия через `headerActions`. Кнопка `UserProfileMenu.headerAction` принимает `pressed` и `controls` для связи с выдвижной панелью.
|
||||
|
||||
`ApplicationSidePanel` — правая application-level пара к `AdminNavigationPanel`.
|
||||
Она использует ту же ширину `332–352 px`, радиус, theme-aware surface, тень и
|
||||
круглые действия, но появляется справа налево. `ApplicationShell` размещает её
|
||||
@@ -328,6 +374,8 @@ variant="panel"`: accordion сохраняет свой layout-state, а его
|
||||
|
||||
`DragHandle`, `DragDropRoot`, `DraggableItem`, `DropZone`, `SortableScope`, `SortableItem` и `SortableList` образуют общий React-контракт переноса и сортировки. Он перенесён из рабочего Engine-паттерна: drag начинается только за шесть точек и только после движения на `6 px`, поэтому обычный клик по строке не конфликтует с навигацией.
|
||||
|
||||
`DragDropRoot.renderOverlay` включает portal-превью переноса поверх прокручиваемого списка. Исходная строка остаётся на месте. Escape/отмена снимают превью без назначения. `DragDropResult.pointer` содержит client-координаты отпускания для точного picking внутри canvas; проверка объекта остаётся у renderer. Существующие потребители без renderOverlay сохраняют прежнее поведение.
|
||||
|
||||
Sortable-строки ограничены вертикальной осью: горизонтальное движение указателя не сдвигает navigation или composition layout. `DragDropRoot` возвращает реальные active/over rectangles, поэтому consumer может принять перенос только после достаточного перекрытия destination. Module Foundry использует порог `20%` ширины переносимой строки: короткое движение, движение влево или касание границы не создаёт page instance.
|
||||
|
||||
В Module Foundry исходная строка Page Template остаётся в Page Library после переноса. Каждый подтверждённый drop создаёт новый page instance с уникальным id; состав приложения и левая навигация читают один массив страниц и потому всегда перестраиваются синхронно. Удаление instance выполняется стандартным `ConfirmationModal`, а не мгновенным действием крестика.
|
||||
@@ -352,6 +400,11 @@ Sortable-строки ограничены вертикальной осью: г
|
||||
|
||||
Единая accordion-панель для settings и definition controls. Источник — только новый Environment Settings и NDC Agent Inspector.
|
||||
|
||||
Inspector принимает `header` для полей перед секциями и `footer` для действий после них.
|
||||
Поля header и соседние секции разделяет `--nodedc-space-3` (12 px); footer
|
||||
центрирует действия. Вложенные Inspector сохраняют тот же шаг. Это общий контракт,
|
||||
а не локальные margin-правки потребителя. Вариант `panel` сохраняет компактные строки.
|
||||
|
||||
Inspector владеет:
|
||||
|
||||
- заголовками разделов;
|
||||
@@ -409,6 +462,8 @@ StatusBadge `variant="indicator"` отображает только одну л
|
||||
|
||||
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.
|
||||
|
||||
A window containing the fullscreen viewport keeps its original portal host and mounted content. Escape restores that viewport first; Tab stays within its visible controls. Newly opened child windows and menus still mount inside fullscreen.
|
||||
|
||||
### Scene window and accordion actions
|
||||
|
||||
`WorkspaceWindow resizeIndicator={false}` скрывает только видимый уголок. Размер по-прежнему меняется перетаскиванием правого нижнего угла или стрелками при фокусе на ручке; фокус остаётся видимым.
|
||||
@@ -419,13 +474,19 @@ React `Window` (including `FeatureSettingsWindow`) and `Dropdown` (including Sel
|
||||
|
||||
`DockLayout` and `DockHandle` compose stable viewport hosts over a serializable `DockTree`.
|
||||
Drop at the center to exchange views; the left/right/top/bottom zones split that destination.
|
||||
The outer 24 CSS pixels of the visible workspace dock across its whole side, including
|
||||
when the pointer is over the source panel. The remaining tree keeps its relative layout.
|
||||
This zone is capped at 8% per axis on small surfaces; it takes precedence over panel zones.
|
||||
The preview labels the scope as «Вся область». Outside drops still cancel.
|
||||
`DockMove.scope="workspace"` selects this operation; omitted/`panel` retains local docking.
|
||||
The serialized `DockTree` is unchanged. `dockMoveAtPoint` resolves both hit-test scopes.
|
||||
Removing the source collapses its old empty branch. The contour uses the resulting tree,
|
||||
so it previews the actual final position, even when the destination expands after removal.
|
||||
Any number of available panels can be composed with nested horizontal and vertical splits.
|
||||
`focusedId` expands a view without reparenting media; the application persists `tree`.
|
||||
There is no permanent outline. Outside/self drops and Escape leave the tree unchanged.
|
||||
There is no permanent outline. Outside drops, local self drops and Escape leave the tree unchanged.
|
||||
Keyboard: Enter/Space on the grip, Tab/Shift+Tab to choose a destination, arrows for edges,
|
||||
Home for center, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing.
|
||||
Home for center, Shift+arrows for a whole-workspace edge, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing.
|
||||
|
||||
The pure tree types, geometry and operations are exported by `@nodedc/ui-core`; React re-exports them for view consumers. Domain adapters import the framework-neutral package.
|
||||
|
||||
@@ -437,6 +498,11 @@ The pure tree types, geometry and operations are exported by `@nodedc/ui-core`;
|
||||
|
||||
`Description` is the shared explanatory paragraph. It matches `SettingsCard.description`: inherited family, small font token (12px), regular 400, muted text token, line-height 1.4. Use it for help below values, not a local paragraph override.
|
||||
|
||||
Use `Description role="status"` for explanatory pending/result copy. Unclassed
|
||||
paragraphs in a `SettingsCard` body inherit this same contract as a compatibility
|
||||
safeguard, even inside layout groups. New consumers must use `Description`.
|
||||
This safeguard does not restyle headings, controls or explicitly styled data.
|
||||
|
||||
## ComparisonTable
|
||||
|
||||
`ComparisonTable` accepts a heading, entity columns and labelled rows. Semantic headers, a 9rem minimum per column and horizontal overflow preserve 1–N comparisons in narrow panels. The keyboard scrollport contains wheel overscroll; no borders or cards per entity. Data freshness stays application-owned.
|
||||
@@ -472,3 +538,102 @@ menu choices use the neutral primary Button state as well as `aria-pressed`.
|
||||
The first optional Hold action controls the existing persisted `autoHide` setting. Disabling autohide cancels any pending hide timer. Dropdown observes outside pointerdown in capture phase; viewport Toolbar consumes background dismissal before canvas editing tools, while other controls retain their normal actions. Nested menus and trigger clicks retain lineage behavior. Catalog includes the Hold action.
|
||||
|
||||
- `NavigationCube`: [orientation cube](NAVIGATION_CUBE.md), controlled face/edge/corner navigation.
|
||||
|
||||
### Window free mode
|
||||
|
||||
`Window` and composed `FeatureSettingsWindow` expose the move toggle by default for centered placement. It removes the backdrop and enables bounded header drag and border/corner resize without remounting the form. Return restores canonical modal geometry. Use arrow keys on the floating header to move; Shift+arrows resize. `allowFloating={false}` is available for workflows that explicitly require a fixed modal. Inspectors stretch within window content. See WINDOWS_AND_LAYERS.md for focus, portal and lifetime rules.
|
||||
|
||||
### Tree · compact outliner
|
||||
|
||||
Visibility is independent of disclosure. Data/eye updates never re-open selected ancestors or scroll to an old selection. Disclosure uses its arrow (or ArrowLeft/ArrowRight), preserves the scroll position, and does not expand on row double-click. Only a new external selected ID/revealKey requests automatic reveal; asynchronous nodes can complete that pending request.
|
||||
|
||||
`Tree` accepts stable `TreeNode` IDs, a selected ID and `onSelect`, optional query and visibility callback. Rows stay on one line with ellipsis. Selection reveals ancestors and scrolls only the tree, avoiding page/camera jumps. Arrow keys, Home/End, Enter/Space support navigation. Use the canonical `Window resizable initialRect` for a movable object outliner.
|
||||
|
||||
`Window` end inspectors can opt into `resizable`; the same eight-edge geometry and header Shift+arrow keyboard sizing are used. Existing windows keep their defaults. `DraggableItem` also exposes `activator.attributes` and `activator.listeners` to attach directly to a tile button; separate handles remain the default for existing consumers.
|
||||
|
||||
## Scene overlays and viewport height
|
||||
|
||||
`GlassMaterialSurface context="scene" radius="panel"` reuses V4 tint, blur/saturation/brightness with independent scene opacity (52%) and blur (18 px). Mission appearance cannot turn it into the 97%-opaque modal. Use only over rendered imagery, keep telemetry hit areas interactive for page scrolling and leave empty overlay space transparent to scene input. No decorative rim is added in Mission appearance.
|
||||
|
||||
`ResizableViewport` owns two visible bottom grips, controlled `height`, `minHeight`, `maxHeight`, `onHeightChange` and `onHeightCommit`. Drag uses pointer capture; keyboard Up/Down moves 10 px, Shift 50 px, Home/End selects limits. Owner persists on commit per view. The viewer remains in document flow, so heights larger than the available area scroll normally. Grip strokes are structural resize indicators; focus is canonical.
|
||||
|
||||
`ApplicationPanel allowFullscreen` makes `useApplicationPanelFullscreen()` available to owned viewer actions. Fullscreen moves the whole panel including its one header above the app stage. Canvas identity is preserved by atomic DOM move; modeless inspectors remain above it. Restore/back/close leaves no detached panel. This is application full-window presentation, not browser fullscreen, so body portals remain usable.
|
||||
|
||||
`ResizableViewport resizeIndicator={false}` hides the resize strokes and hover surface. Only the pointer cursor changes; keyboard focus remains accessible. Pointer capture does not force focus, avoiding a focus ring after mouse drag.
|
||||
|
||||
`SceneAnnotation` is a transparent canonical ghost button for projected scene data. Renderer supplies screen coordinates, culls offscreen/hidden objects and owns identity; click, Enter and Space activate the same selected state. Use stacked object name/value and never fabricate sensor fields.
|
||||
|
||||
ColorField keeps a local HEX draft so deletion and replacement work with strict controlled values. Six hexadecimal digits (optional #) apply live; blur/Enter normalize valid input or revert incomplete input. Escape cancels the draft. External value changes, including undo, synchronize the displayed text.
|
||||
|
||||
`GlassMaterialSurface` accepts `material: GlassMaterialSettings` and optional `radiusPx` for operator-customizable overlays. Variables are scoped to that instance; scene tint opacity and blur use the scene context, without mutating modal or global appearance.
|
||||
|
||||
Exact `RangeControl` editors synchronize external controlled-value changes while focused, so undo/redo is visible immediately and subsequent blur cannot reapply an obsolete draft.
|
||||
|
||||
Window: `rect` / `onRectCommit` — восстановление и фиксация геометрии инструментов; см. WINDOWS_AND_LAYERS.md. Иконка `minus` дополняет `plus` для управления масштабом содержимого.
|
||||
|
||||
`EditorDockLayout` / `EditorWorkspace`: переносимый редактор с закреплённым основным видом, четырьмя зонами стыковки, разделителями и отрываемыми панелями. Управляемый `EditorDockState` хранится в документе приложения. Шапка редактора не участвует в стыковке; возврат восстанавливает исходный вид. Контракт, keyboard и минимумы — в WINDOWS_AND_LAYERS.md.
|
||||
|
||||
Размер поясняющего текста `Description` можно задать через
|
||||
`--nodedc-description-font-size`; по умолчанию используется `--nodedc-font-size-sm`.
|
||||
|
||||
Window header actions default to before the move toggle. `headerActionsPlacement="before-close"` places supplied canonical IconButtons between move and close, preserving DOM/Tab order. Deletion confirmation remains application-owned content in the same mounted Window.
|
||||
|
||||
|
||||
## Tooltip
|
||||
|
||||
Общий стандарт: скруглённое стекло 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.
|
||||
|
||||
### Remembered detail windows and sortable image grids
|
||||
|
||||
`Window.floating/onFloatingChange` lets the host persist modal/floating mode by
|
||||
window kind alongside `rect/onRectCommit`. See WINDOWS_AND_LAYERS.md.
|
||||
`SortableList` and `SortableScope` accept `layout="grid"`; rectangular sorting
|
||||
keeps the shared drag handle and activation threshold. The default stays vertical.
|
||||
|
||||
Для ручки поверх фотографии используйте `DragHandle surface="control"` или `SortableList handleSurface="control"`: видимый круг с общим стеклом внутри `nodedc-viewport-controls`. Bare-ручка остаётся вариантом по умолчанию для обычных строк.
|
||||
|
||||
Window `headerLayout="adaptive"` keeps contextual actions on one trailing row. The complete title moves below actions before clipping. The measured action width sets the minimum for all resize edges, keyboard resizing and restored layout; only an undersized device viewport allows horizontal action scrolling. `expanded` temporarily opens media at a moderate viewport-fitted size while retaining modal/floating presentation. Users can resize the expanded window; restoration returns the previous geometry without changing the regular rectangle. `expandedRect` / `onExpandedRectCommit` persist the user’s separate expanded position and dimensions; first expansion uses a moderate 960×800 ceiling within 80%/82% of the viewport.
|
||||
|
||||
@@ -17,3 +17,16 @@ The application validates URLs/media bytes, persists uploads and document revisi
|
||||
Mission Core passes all existing page definitions and its current operator-environment API. Mission Core Node passes home only and authenticated local presentation storage. Device control never depends on this document. The catalog EnvironmentCatalogDemo exercises the same exported components with an explicitly in-memory save/upload adapter; it is not a persistence service.
|
||||
|
||||
Validate the source migration, TypeScript builds, playlist functions, neutral enabled/disabled DOM contract, dark/light and multiple accents, modal Escape, media order/timing and both consumer persistence adapters. Long-running or physical device acceptance remains application-owned.
|
||||
|
||||
## Product sections (2026-11-08)
|
||||
|
||||
`additionalSections` accepts `{ id, label, icon, group?, content, footer? }`.
|
||||
Use unique IDs other than `environment`. Content and footer are product-owned;
|
||||
the shared shell retains navigation, focus, dragging, Escape and geometry.
|
||||
Environment drafts remain intact when switching sections. Each section owns its
|
||||
loading/error/saving states. No product API is called by the shared library.
|
||||
Mission Core uses this extension for the owner-requested Storage section.
|
||||
|
||||
The canonical `pin` icon is the Lucide Pin glyph. Pair it with IconButton and
|
||||
`aria-pressed` for pinned state; use a busy/disabled state during preparation.
|
||||
An absent local copy and an unpinned copy are separate states.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Favorites
|
||||
|
||||
Use the registered `star` icon in an IconButton with `aria-pressed`. The unset state is outline-only; the selected glyph uses `fill="currentColor"`. Keep the same hit target in both states. Place a card favorite action in its upper trailing corner, independent of opening the card. Persist the domain value at its owner; filtering favorites must not change it.
|
||||
|
||||
For a star without a surrounding disc, use `IconButton surface="none"`. The shared component owns the transparent surface and foreground; applications only position it. Keyboard focus and the hit target remain unchanged.
|
||||
@@ -59,3 +59,6 @@
|
||||
## Владение
|
||||
|
||||
У дизайн-системы должен быть явный code owner. Product team может предлагать компоненты, но общий API и theme contract проходят отдельное review, потому что изменение распространяется на все будущие приложения.
|
||||
|
||||
|
||||
Typography is a build gate, not a recommendation. See `OPERATIONAL_TYPOGRAPHY.md`: operational values/sections 13 px, descriptions/status/error copy 12 px, canonical window/page titles 18 px. Browser defaults, new local sizes and inline font overrides fail validation. The frozen compact legacy list cannot be expanded for new UI; exceptions require an explicit owner decision.
|
||||
|
||||
@@ -49,3 +49,17 @@ 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.
|
||||
|
||||
|
||||
### Блокировка в дереве
|
||||
|
||||
`lock` / `unlock` показывают закрытый / открытый замок. Компактное действие
|
||||
дерева использует прозрачную кнопку без `aria-pressed` и без белой активной
|
||||
подложки; доступное имя описывает действие «Разблокировать» / «Заблокировать».
|
||||
Состояние передаётся формой замка. Уменьшение glyph не уменьшает область нажатия.
|
||||
|
||||
@@ -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.
|
||||
Внешний отступ от соседних действий остаётся ответственностью композиции шапки.
|
||||
@@ -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`.
|
||||
@@ -95,3 +95,11 @@ height must not leave a visible head with its stem hidden below terrain.
|
||||
|
||||
Motion never recreates the Cesium viewer or any provider. A renderer teardown
|
||||
stops its single animation frame loop.
|
||||
|
||||
## Визуальные настройки и профили · 17.11.2026
|
||||
|
||||
`MapVisualSettings` дополнен необязательными полями `MapSceneEffects`: небо/солнце/луна, цвет света и тени, детализация рельефа, разрешение, FXAA, HDR/exposure/tonemapper, Bloom и HBAO. `DEFAULT_MAP_SCENE_EFFECTS` соответствует исходным значениям Cesium 1.147. Отсутствующие поля не меняют поведение других потребителей. Применение обновляет живую сцену; viewer, camera, providers, тайловые маршруты и доменные объекты не пересоздаются. HBAO включается только при поддержке графического контекста.
|
||||
|
||||
Для большого набора настроек используется `FeatureSettingsWindow`, слева разделы; контролы — `Checker`, `RangeControl` с exactValueBounds, `ColorField`, `Select`. Настройки спутниковой подложки не являются цветокоррекцией BIM/гауссов; OSM style не меняет их материалы. HDR exposure/tonemapper действует только при включённом HDR. Нативные API сверены с исходниками 1.147 и [Cesium PostProcessStageCollection](https://cesium.com/learn/cesiumjs/ref-doc/PostProcessStageCollection.html).
|
||||
|
||||
Профили сохраняет host через revision/atomic JSON. Снимок содержит только визуальные настройки и слои; не копирует камеру, размещение, токены, routing или cache intent. Применение профиля не меняет пространственный контекст. Выбор доступен в модалке и в стеклянном меню слоёв (`Dropdown surfaceClassName="nodedc-viewport-surface"`).
|
||||
|
||||
+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.
|
||||
|
||||
@@ -11,3 +11,5 @@ Visible hit regions have native tooltips, hover, keyboard focus, Enter/Space act
|
||||
Presentation props: `size` in CSS pixels (default 66), `face`, `text`, `edge`, `hover`, `hoverText`, `opacity`. Consumer preferences may persist these; omitted colors inherit theme tokens. Core exposes these under viewport settings → 3D-куб.
|
||||
|
||||
Face labels use the projected face-local right/up basis, including foreshortening and rotation; they never billboard towards the screen. `edgeOpacity` (0–1, default 1) independently controls structural grid/edge strokes without fading faces or labels.
|
||||
|
||||
`faceOpacity` (0–1, default 1) controls polygon fill only. It is independent of `edgeOpacity`, text and the legacy overall `opacity`; a transparent face remains a navigation target.
|
||||
|
||||
@@ -22,3 +22,45 @@ Checker, круг, pill или кнопку. Это знак результат
|
||||
Лампочка состояния устройства отдельно использует StatusBadge indicator.
|
||||
|
||||
Explanatory paragraphs use `Description`, the same contract as `SettingsCard.description`: inherited font family, regular 400, `--nodedc-font-size-sm`, `--nodedc-text-muted`, line-height 1.4 and zero paragraph margins. Applications must not create feature-specific equivalents.
|
||||
|
||||
Защита компонента: обычный `p` без класса внутри тела `SettingsCard` получает
|
||||
тот же стиль описания, включая вложенные группы. Это страховка для прежних
|
||||
потребителей, а не замена `Description` в новом коде. Статусы ожидания и
|
||||
пояснения вне карточки также используют `Description` с `role="status"`, если
|
||||
нужно объявление для скринридера. Заголовки, значения полей и кнопки сохраняют
|
||||
собственную типографику; глобальный стиль для всех `p` страницы не вводится.
|
||||
|
||||
|
||||
## Обязательная проверка сборки — 10.11.2026
|
||||
|
||||
Операционный UI имеет собственный базовый `md` (13 px), в том числе портальные
|
||||
`Window`, `WorkspaceWindow`, `ApplicationPanel` и `AdminPanel`. Размер body
|
||||
внешнего приложения не является контрактом. Корневой размер `html` не меняется:
|
||||
rem и пользовательское масштабирование остаются доступными. Семантические
|
||||
h1–h6 внутри этих поверхностей по умолчанию используют md, а явные канонические
|
||||
заголовки страницы/окна — title (18 px). Значения и заголовки секций — md;
|
||||
пояснения, ошибки, ожидание и результат команды — `Description` / sm (12 px).
|
||||
|
||||
Правило исполняется модулем `@nodedc/ui-core/typography` и обязательным
|
||||
`npm run test:typography` Design Guideline. Mission Core запускает
|
||||
`check:typography` перед сборкой Control Station и Node UI, а также в полном
|
||||
наборе unit-тестов. Проверяется исходный код всех экранов, общих пакетов и
|
||||
frontend-плагинов, а не только последний изменённый компонент.
|
||||
|
||||
Проверка запрещает новые локальные размеры вместо токенов, lg/title для данных,
|
||||
увеличивающие calc/clamp/em, font shorthand, inline fontSize и обычные p без
|
||||
явного класса. Сохранившиеся компактные значения старого UI (не более 13 px)
|
||||
зафиксированы по файлу, селектору и значению в `typography-policy.json`;
|
||||
добавлять туда новый UI запрещено. При изменении такого правила его переводят
|
||||
на токен, запись удаляют. Список не допускает крупных значений даже при ошибочном
|
||||
добавлении. Исключения перечислены отдельно с причиной и точным выражением:
|
||||
существующая обложка LandingStage, подписи в координатах SVG и управляемый
|
||||
пользователем масштаб сцены. Они не разрешают увеличивать текст рабочих панелей.
|
||||
Начальный размер значений батареи — 13 px; сохранённый пользователем масштаб
|
||||
3D-сцены не перезаписывается.
|
||||
|
||||
Изменение шкалы токенов, списка ролей или исключений требует явного решения
|
||||
владельца продукта и обновления живого каталога. Нельзя ослаблять проверку ради
|
||||
одного экрана, закрывать проблему локальным font-size или менять масштаб html.
|
||||
При приёмке проверяют computed font-size в обычном и плавающем окне, на узкой
|
||||
ширине, а также ожидание, ошибку, пустое состояние и результат команды.
|
||||
|
||||
@@ -13,3 +13,6 @@ aria-valuenow отсутствует. `label` обязателен; `valueText`
|
||||
ResourceRow.progress занимает свободное место между текстом и actions, скрывает
|
||||
status, на узком экране переносится ниже текста. Готовность не вычисляется
|
||||
компонентом. Каталог содержит завершённый, определённый и неизвестный прогресс.
|
||||
|
||||
Размер полосы задаётся опциональным `--nodedc-progress-height`; по умолчанию
|
||||
используется `--nodedc-space-2`. Плотность не меняет поведение и ARIA-состояния.
|
||||
|
||||
+66
-62
@@ -1,78 +1,82 @@
|
||||
# Темы и цвет приложения
|
||||
|
||||
## Основное правило
|
||||
## Один фундамент
|
||||
|
||||
NODE.DC-приложения отличаются цветовой схемой, а не набором заново нарисованных компонентов. Тема задаёт значения CSS custom properties. Компоненты сохраняют геометрию, состояния и поведение.
|
||||
С 2026-11-05 основа тёмной темы — проверенный локальный Mission Core
|
||||
(`b0332fa`, `apps/control-station/src/styles/base.css`, работающий интерфейс
|
||||
`127.0.0.1:8000`). Цвета находятся только в `@nodedc/tokens/themes.css`,
|
||||
геометрия и состояния — в `@nodedc/ui-core`, компоненты — в `@nodedc/ui-react`.
|
||||
Приложение выбирает тему, а не повторяет цвета, селекторы или устройство компонентов.
|
||||
|
||||
## Что меняет тема
|
||||
```ts
|
||||
import {applyNodedcTheme, missionDarkTheme} from '@nodedc/ui-core';
|
||||
applyNodedcTheme(document.documentElement, missionDarkTheme);
|
||||
```
|
||||
|
||||
- canvas/background;
|
||||
- основной и вторичный текст;
|
||||
- accent и автоматически вычисляемый on-accent;
|
||||
- цвет непрозрачных application surfaces;
|
||||
- field/control surfaces;
|
||||
- overlay;
|
||||
- тени controls и modal material;
|
||||
- semantic success/warning/danger tones при необходимости.
|
||||
Те же exports доступны из `@nodedc/ui-dom`. `applyNodedcTheme(root)` по умолчанию
|
||||
выбирает `dark / mission / flat`. `missionLightTheme` сохраняет общую геометрию
|
||||
и даёт светлую тему. Установка на `document.documentElement` обязательна для
|
||||
приложения с порталами: меню и модальные окна получают тот же профиль.
|
||||
|
||||
## Что тема не меняет
|
||||
## Роли поверхностей
|
||||
|
||||
- высоту контролов;
|
||||
- радиусы по классам компонентов;
|
||||
- положение логотипа;
|
||||
- механику окна и dropdown;
|
||||
- DOM anatomy;
|
||||
- keyboard behavior;
|
||||
- расположение footer actions;
|
||||
- API React/DOM компонентов.
|
||||
| Роль | Тёмная тема | Компонент |
|
||||
| --- | --- | --- |
|
||||
| Фон приложения | `#050506` | ApplicationShell |
|
||||
| Рабочая сцена | `#08090b` | доменный viewport, token `--nodedc-stage` |
|
||||
| Панель | `#151517` | ApplicationPanel, AdminNavigationPanel |
|
||||
| Группа | нейтральный слой `110 110 110 / .07` | SettingsCard |
|
||||
| Элемент коллекции | нейтральный слой `110 110 110 / .07` | GlassSurface tone="group" |
|
||||
| Утопленная вторичная область | `#0d0d0f` | GlassSurface tone="soft", вне форм |
|
||||
| Поле | `#2a2a2c`, непрозрачное | TextField, TextAreaField, Select, MediaSourceField |
|
||||
| Модальное окно | `15 15 17 / .97` | FeatureSettingsWindow, Window |
|
||||
| Выпадающее меню | `15 15 17 / .98` | Dropdown, Select portal |
|
||||
| Основное действие | `247 248 244 / .96`; тёмный текст | Button |
|
||||
|
||||
## Presets
|
||||
ApplicationPanel → SettingsCard → поля — композиция, проверенная в работающих
|
||||
настройках Mission Core. Сетка полей прозрачная, без отдельной подложки и отступов.
|
||||
Самостоятельный элемент коллекции может использовать GlassSurface tone="group":
|
||||
тот же нейтральный материал SettingsCard, а не почти чёрный canvas-soft.
|
||||
Не добавлять карточку вокруг списка карточек или вокруг каждого поля; максимум
|
||||
два уровня групп сохраняют отличие непрозрачного поля от подложки.
|
||||
|
||||
В baseline включены `dark` и `light`. Это не два отдельных продукта, а примеры одного контракта:
|
||||
Исправление 2026-11-05: прежний пример с tone="soft" ошибочно переносил цвет
|
||||
вторичного canvas в формы. Значение soft сохранено для его исходной роли;
|
||||
приложения исправляют композицию, а не перекрашивают canvas локальным CSS.
|
||||
|
||||
- dark соответствует текущей основной семье Launcher/Hub/CMS;
|
||||
- light воспроизводит SEO-поверхности: `#ececec` canvas, белые панели и поля, тёмный текст, чёрные primary actions и мягкую тень у белых secondary controls;
|
||||
- конкретный продукт может поверх preset задать свой accent и surface variables.
|
||||
Основной/вторичный/приглушённый/недоступный текст использует оттенок
|
||||
`247 248 244` с непрозрачностью `.96 / .72 / .48 / .34`. Состояния hover,
|
||||
active, focus, disabled задаёт библиотека; приложения не переопределяют их.
|
||||
Hover поля использует собственный непрозрачный материал, а не полупрозрачную
|
||||
заливку кнопки: поле не исчезает при наведении.
|
||||
Декоративные рамки и контуры отсутствуют. Клавиатурный фокус остаётся видимым
|
||||
через контрастную заливку. Success/warning/danger сохраняют смысловые цвета
|
||||
индикаторов; цвет акцента не подменяет состояние ошибки.
|
||||
|
||||
## Accent
|
||||
## Акцент и настройки
|
||||
|
||||
Accent задаётся RGB tuple. On-accent вычисляется по luminance и не должен вручную прописываться белым или чёрным в отдельном компоненте.
|
||||
Базовый акцент тёмной темы — `247 248 244`, светлой — `24 25 28`.
|
||||
Пользовательский `accent` остаётся допустимой настройкой активных контролов.
|
||||
`on-accent` вычисляется библиотекой по яркости. Нейтральное основное действие
|
||||
остаётся нейтральным. Возврат к теме вызывает `clearNodedcAccent(root)`, затем
|
||||
`applyNodedcTheme`; удалять пользовательское значение без явного сброса нельзя.
|
||||
Материалы можно исследовать в каталоге; приложения не должны хранить собственный
|
||||
набор цветов для восстановления стандартной темы.
|
||||
|
||||
Default accent текущего NODE.DC shell — `#ff2f92`. `ColorField` открывает единый portal-picker с saturation/value plane, hue slider, HEX и быстрыми цветами — системный `input[type=color]` не является runtime UI. Изменение accent сразу меняет Environment Settings, active actions, range fill, media file action и theme-aware window states без создания новой темы или fork компонентов. Blur, gloss и material rim не наследуются application panels: это материал только для floating modal и portal-dropdown/select.
|
||||
В светлой теме canvas — `#ececec`, панели и поля — белые, группы и вложенные
|
||||
области — `#f4f4f4`. Белое поле различимо внутри группы.
|
||||
Map-glass остаётся отдельным светлым полупрозрачным материалом над изображением;
|
||||
он не заменяет обычную тему форм, панелей и портальных окон.
|
||||
|
||||
Semantic status не обязан совпадать с accent. Например, ошибка остаётся danger, даже если приложение использует красный брендовый accent.
|
||||
## Проверка и совместимость
|
||||
|
||||
## Область применения
|
||||
Living catalog: Controls → Mission Core. Проверяются вложенная форма, текст,
|
||||
select, textarea, disabled, переключатель, статус и то же содержимое в портальном
|
||||
окне; дополнительно проверяются клавиатура и обе темы. CMS использует этот же
|
||||
профиль и immutable npm-пакеты, не копию исходников компонентов.
|
||||
|
||||
Тема может быть установлена:
|
||||
|
||||
- на корневом `html/body` для всего приложения;
|
||||
- на контейнере embedded-модуля;
|
||||
- на catalog preview для сравнения схем.
|
||||
|
||||
Portal-компоненты рендерятся в `document.body`, поэтому приложение должно либо задавать тему на `document.documentElement`, либо передавать согласованные переменные на body. Локальная тема глубоко внутри React subtree не сможет автоматически охватить portal без отдельного theme portal root.
|
||||
|
||||
Map-glass overlays являются отдельной, независимой от application theme
|
||||
поверхностью поверх imagery. Их светлые translucent controls используют
|
||||
`--nodedc-map-glass-text`, а непрозрачное светлое поле поиска обязано брать
|
||||
тёмный foreground из `--nodedc-map-field-text` и placeholder из
|
||||
`--nodedc-map-field-text-muted`. Светлый field не наследует белый текст
|
||||
map-glass родителя. `ApplicationSidePanel`, напротив, находится вне imagery и
|
||||
всегда наследует обычные theme-aware application panel/text tokens; при смене
|
||||
dark/light она меняется синхронно с `AdminNavigationPanel`.
|
||||
|
||||
## Совместимость
|
||||
|
||||
Существующие `--nodedc-*` имена сохранены намеренно. Это уменьшает стоимость будущего подключения Launcher, Engine, Task Manager и BIM Viewer.
|
||||
|
||||
## Mission Core operator appearance
|
||||
|
||||
`applyNodedcTheme(document.documentElement, { theme, accent, appearance: "mission" })`
|
||||
selects the shared visual profile qualified against Mission Core on 2026-09-30.
|
||||
It covers body portals, dark modal/floating fills, plain avatar surfaces,
|
||||
neutral actions and semantic dot statuses. `default` remains compatible with
|
||||
other consumers. Light theme retains its legible light surfaces. Reapplying
|
||||
`default` removes the profile through the data attribute, without CSS cleanup.
|
||||
Feature settings use the same geometry, focus, scrolling and responsive behavior.
|
||||
Application code owns section names and icons; tracker/VPS sections follow the
|
||||
text-only Mission equipment menu. Environment settings may retain their icons.
|
||||
`appearance: "default", edges: "default"` оставлены для явной совместимости
|
||||
со старой презентацией компонентов. Новые потребители используют Mission.
|
||||
Эта ревизия не меняет локальный Mission Core и его незакоммиченные эксперименты.
|
||||
Его прежние локальные CSS-дубли зафиксированы как миграционный долг: перенос
|
||||
зависимости требует отдельной проверки приложения, а не незаметной замены пакетов.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Интерфейс внутри 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.
|
||||
|
||||
Уточнение 17.11.2026: `Dropdown surfaceClassName="nodedc-viewport-surface"` получает тот же scene Glass V4 на самой portal-поверхности. Это применяется к меню слоёв карт; не добавлять под ним непрозрачную карточку. Настройки большого объёма открываются через `FeatureSettingsWindow` с навигацией слева, а не через отдельный draggable inspector.
|
||||
@@ -129,3 +129,59 @@ Selecting a different settings section resets only its content scroll to the top
|
||||
Docked content declares minimumSize for both axes. The divider stops at the recursive content boundary; a small overall viewport scrolls the layout canvas.
|
||||
|
||||
`DockLayout.panels[].preferredSize` задаёт начальный компактный размер. Продукт передаёт его только для новой раскладки без сохранённой геометрии; первый resize/dock сохраняет пользовательскую геометрию. Минимумы продолжают действовать при всех последующих размерах.
|
||||
|
||||
## Free-window mode for centered windows
|
||||
|
||||
A centered `Window` exposes the semantic `move` icon beside close (`allowFloating`, true by default). The toggle retains the mounted contents and captures their current dimensions. In floating mode the backdrop has no dimming or blur and passes interaction to the background; body scrolling and focus trapping are released. Drag the header or resize from any of the eight invisible border regions. No hover handles or decorative resize marks are drawn. Edges and corners expose their directional resize cursor; the movable header uses the move cursor. Keyboard users focus the header and use arrows to move or Shift+arrows to resize. Geometry is clamped on manipulation and viewport resize.
|
||||
|
||||
Turning the free mode off returns the same contents to the normal centered size and modal semantics. Turning it on again during the same opening restores the floating rectangle. Closing clears it. Portal ownership remains the active fullscreen element or body. Nested dialogs keep their own modal behavior. Inspector controls inside windows stretch to available width.
|
||||
|
||||
## Сохранённая геометрия инструментов
|
||||
|
||||
`Window.rect: WindowRect` и `onRectCommit` позволяют приложению хранить геометрию в своём документе. Для `placement="end" resizable` размеры и координаты восстанавливаются при открытии и при внешнем undo/import. Перетаскивание и resize обновляются локально; callback вызывается один раз при завершении жеста. Клавиатурный шаг тоже фиксируется. Автоматическое вписывание в уменьшенный экран не перезаписывает сохранённый прямоугольник. Без `rect` остаётся прежнее поведение `initialRect`. Пример дерева объектов в каталоге сохраняет прямоугольник между открытиями.
|
||||
|
||||
Действия уменьшения/увеличения содержимого палитр используют канонические `IconButton` с иконками `minus` / `plus` в `headerActions`, рядом с закрытием. Их прикладной масштаб хранится вместе с документом.
|
||||
|
||||
## Scene editor workspace and detachable tools
|
||||
|
||||
`EditorWorkspace` opens the same mounted content in a separate modeless editing window, then returns it to the original inline slot. Back, close and finishing editing share `onBack`; fullscreen is local to this editing window. The fixed header is not a docking target. The application retains its original view height, layout and camera document. The renderer host is moved atomically with `moveBefore` when available; canvas-based renderers remain mounted with the append fallback too.
|
||||
|
||||
`EditorDockLayout` receives `value: EditorDockState`, `onChange`, a locked `primary`, and typed `tools`. Tool descriptors supply title, open/close, content, actions, footer, minimum size and optional initial floating rectangle. The primary cannot detach. Each tool keeps its DOM host when docked, floating or temporarily hidden. The split tree, floating rectangles and any application-owned palette scale belong to the scene document, not a global library store.
|
||||
|
||||
Drag a tool header to any of four outer edges to create a full-side area; drop over another tool to split beside it. Drop in the primary center to detach. An exact destination preview is shown only during placement. A 24 px outer zone wins over panel targets; broader magnets reach 160 px horizontally / 96 px vertically, capped at 16% of the workspace. The center of a tool chooses its nearest side, never swaps it with the primary. Split minima protect content; small viewports scroll the bounded layout. Invisible floating edges resize, and only the cursor changes.
|
||||
|
||||
Header Enter/Space begins keyboard docking, arrows choose an edge, Shift+arrows choose the whole workspace, Tab selects a tool, Home selects floating, Enter commits and Escape cancels. Floating headers also accept arrows to move and Shift+arrows to resize. Pointer cancellation and Escape restore the uncommitted layout. Automatic viewport fitting does not overwrite stored rectangles. The living catalog includes the same workspace with a fixed scene, outliner and material palette.
|
||||
|
||||
When an EditorWorkspace detaches from a Window, the owning overlay is suspended
|
||||
without unmounting its children. Its backdrop and focus trap are inactive until
|
||||
the editor returns. Escape/Tab belong to the focused dialog, so nested settings
|
||||
close without also closing the battery/detail window.
|
||||
|
||||
|
||||
Portal typography is self-contained: Window text base is md/13 px, its title is title/18 px, and explanatory/status paragraphs use Description/sm/12 px. This stays identical in centered and floating modes and is independent of the host body size.
|
||||
|
||||
`EditorWorkspace purpose="view"` reuses the same stable host and docking grammar for viewers. Back/close return the mounted view to its inline slot; no edit-completion action is shown. Optional `headerActions` keeps application actions in the fixed window header. The default `purpose="edit"` preserves existing editors. The living docking example demonstrates both purposes.
|
||||
|
||||
Dock tool headings inherit the focused drag-header foreground, including title and subtitle, so the canonical inverted keyboard-focus fill retains readable text.
|
||||
|
||||
Keyboard-focused dock headers keep their action/close glyphs on the inherited contrast color, as well as title/subtitle.
|
||||
|
||||
Tool minimumSize governs floating and docked geometry alike, including restored JSON, pointer and keyboard resize. Screen bounds take priority when smaller. Put fixed bottom actions in EditorDockTool.footer; never append them to scrollable inspector content.
|
||||
|
||||
The primary scene owns an isolated stacking context so its toolbars stay behind floating tools. A tool outer shell clips without scrolling; only its body scrolls, keeping header/footer fixed even when a field receives focus.
|
||||
|
||||
ColorField spectrum has no decorative perimeter stroke; retain its visible sampling marker and keyboard focus. UserProfileMenu variant=header owns its HeaderProfile surface; consumers must not wrap it in another HeaderProfile.
|
||||
|
||||
## Focus of movable headers
|
||||
|
||||
Window, WorkspaceWindow and EditorDockLayout share the same drag-header focus contract. A pointer grab never inherits a keyboard focus ring or filled header from the previously focused input. Headers have no perimeter outline in any theme; keyboard focus uses the canonical contrasting surface. Pointer capture, focus ownership, Arrow/Shift+Arrow movement/resizing, Enter/Space docking and Escape cancellation remain unchanged. Check both direct grabbing and input → Tab → grabbing, in docked/floating and fullscreen contexts.
|
||||
|
||||
## Remembered presentation
|
||||
|
||||
Entity/detail windows persist presentation **by window kind**, not title or entity ID.
|
||||
The application stores `floating` and `rect` in its durable user preferences;
|
||||
`Window` consumes `floating`/`onFloatingChange` and `rect`/`onRectCommit`.
|
||||
Opening the next entity restores the same mode, position and size. Return to modal
|
||||
keeps the last floating rectangle for the next detachment. Viewport fitting does
|
||||
not overwrite saved geometry. Switching view/edit keeps the same mounted Window.
|
||||
Confirmation dialogs remain modal (`allowFloating=false`) and never inherit it.
|
||||
|
||||
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.4",
|
||||
"@nodedc/ui-react": "0.7.10",
|
||||
"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.4",
|
||||
"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.4",
|
||||
"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.4"
|
||||
}
|
||||
},
|
||||
"packages/ui-react": {
|
||||
"name": "@nodedc/ui-react",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.10",
|
||||
"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.4",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
+11
-3
@@ -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,7 +11,7 @@
|
||||
"scripts": {
|
||||
"build": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react && npm run build --workspace @nodedc/ui-catalog",
|
||||
"build:packages": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react",
|
||||
"check": "npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces",
|
||||
"check": "npm run test:typography && npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test: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",
|
||||
@@ -43,7 +43,15 @@
|
||||
"test:split-pane": "node --test scripts/split-pane-contract.test.mjs",
|
||||
"test:dock-layout": "node --test scripts/dock-layout.test.mjs",
|
||||
"test:analysis-controls": "node --test scripts/analysis-controls.test.mjs",
|
||||
"test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs"
|
||||
"test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs",
|
||||
"test:window-geometry": "node --test scripts/window-geometry.test.mjs",
|
||||
"test:editor-dock": "node --test scripts/editor-dock.test.mjs",
|
||||
"test:typography": "node --test scripts/operational-typography.test.mjs",
|
||||
"prebuild": "npm run test:typography",
|
||||
"test:flat-theme": "node --test scripts/flat-theme.test.mjs",
|
||||
"test:mission-theme": "node --test scripts/mission-theme.test.mjs",
|
||||
"test:modal-size": "node --test scripts/modal-size.test.mjs",
|
||||
"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.4",
|
||||
"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"
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
MapProviderId,
|
||||
MapRuntimeState,
|
||||
} from "./contracts.js";
|
||||
import {applyMapSceneEffects} from "./sceneEffects.js";
|
||||
import { advanceGhostPins } from "./ghostPins.js";
|
||||
import {
|
||||
parseProviderEndpoint,
|
||||
@@ -60,10 +61,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 +120,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 +196,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 +272,7 @@ export const CesiumMapRenderer = forwardRef<
|
||||
return () => {
|
||||
disposed = true;
|
||||
abortController.abort();
|
||||
try { disposeConsumer?.(); } finally {
|
||||
removeCameraListener?.();
|
||||
removeRenderListener?.();
|
||||
runtimeRef.current?.stopGhostPinAnimation?.();
|
||||
@@ -272,6 +280,7 @@ export const CesiumMapRenderer = forwardRef<
|
||||
viewer?.destroy();
|
||||
viewer = null;
|
||||
container.replaceChildren();
|
||||
}
|
||||
};
|
||||
}, [
|
||||
runtimeConfigUrl,
|
||||
@@ -487,7 +496,9 @@ function applyPresentation(
|
||||
buildings.maximumScreenSpaceError =
|
||||
settings.buildings_maximum_screen_space_error;
|
||||
buildings.style = new Cesium.Cesium3DTileStyle({
|
||||
color: `color('${settings.buildings_color}', ${settings.buildings_opacity})`,
|
||||
color: settings.buildings_style_default
|
||||
? `Boolean(\${feature['cesium#color']}) ? color(\${feature['cesium#color']}, ${settings.buildings_opacity}) : color('#ffffff', ${settings.buildings_opacity})`
|
||||
: `color('${settings.buildings_color}', ${settings.buildings_opacity})`,
|
||||
});
|
||||
}
|
||||
runtime.ghostPins.show = layers.targets;
|
||||
@@ -533,9 +544,9 @@ function applyPresentation(
|
||||
}
|
||||
viewer.shadows = settings.shadows_enabled;
|
||||
const sunDate = Cesium.JulianDate.toDate(Cesium.JulianDate.now());
|
||||
sunDate.setUTCHours(
|
||||
clamp(Math.round(settings.sun_hour), 0, 24),
|
||||
0,
|
||||
if (!settings.sun_time_current) sunDate.setUTCHours(
|
||||
Math.floor(clamp(settings.sun_hour, 0, 24)),
|
||||
Math.round((settings.sun_hour % 1) * 60),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
@@ -548,6 +559,7 @@ function applyPresentation(
|
||||
2,
|
||||
);
|
||||
viewer.scene.light = sun;
|
||||
applyMapSceneEffects(runtime, settings);
|
||||
viewer.scene.requestRender();
|
||||
}
|
||||
|
||||
|
||||
@@ -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";
|
||||
@@ -111,7 +112,7 @@ export type MapLayerVisibility = {
|
||||
targets: boolean;
|
||||
};
|
||||
|
||||
export type MapVisualSettings = {
|
||||
export type MapVisualSettings = Partial<MapSceneEffects> & {
|
||||
atmosphere_enabled: boolean;
|
||||
atmosphere_hue: number;
|
||||
atmosphere_saturation: number;
|
||||
@@ -119,6 +120,7 @@ export type MapVisualSettings = {
|
||||
fog_enabled: boolean;
|
||||
fog_density: number;
|
||||
sun_enabled: boolean;
|
||||
sun_time_current?: boolean;
|
||||
sun_hour: number;
|
||||
sun_intensity: number;
|
||||
shadows_enabled: boolean;
|
||||
@@ -133,6 +135,7 @@ export type MapVisualSettings = {
|
||||
globe_color: string;
|
||||
background_color: string;
|
||||
terrain_exaggeration: number;
|
||||
buildings_style_default?: boolean;
|
||||
buildings_color: string;
|
||||
buildings_opacity: number;
|
||||
buildings_maximum_screen_space_error: number;
|
||||
@@ -154,12 +157,47 @@ export type MapVisualSettings = {
|
||||
camera_animation_enabled: boolean;
|
||||
};
|
||||
|
||||
/** Optional controls preserve presentation in existing hosts until explicitly supplied. */
|
||||
export type MapSceneEffects = {
|
||||
skybox_enabled: boolean;
|
||||
sun_visible: boolean;
|
||||
moon_visible: boolean;
|
||||
ground_atmosphere_enabled: boolean;
|
||||
sun_color: string;
|
||||
shadow_darkness: number;
|
||||
shadow_soft: boolean;
|
||||
terrain_maximum_screen_space_error: number;
|
||||
resolution_scale: number;
|
||||
fxaa_enabled: boolean;
|
||||
hdr_enabled: boolean;
|
||||
exposure: number;
|
||||
tonemapper: "PBR_NEUTRAL" | "ACES" | "FILMIC" | "REINHARD" | "MODIFIED_REINHARD";
|
||||
bloom_enabled: boolean;
|
||||
bloom_contrast: number;
|
||||
bloom_brightness: number;
|
||||
bloom_sigma: number;
|
||||
bloom_step_size: number;
|
||||
ao_enabled: boolean;
|
||||
ao_intensity: number;
|
||||
ao_bias: number;
|
||||
ao_length_cap: number;
|
||||
};
|
||||
|
||||
export type MapCacheIntent = {
|
||||
enabled: boolean;
|
||||
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,
|
||||
@@ -22,6 +23,7 @@ export type {
|
||||
MapRuntimeConfiguration,
|
||||
MapRuntimeState,
|
||||
MapVisualSettings,
|
||||
MapSceneEffects,
|
||||
} from "./contracts.js";
|
||||
export {
|
||||
advanceGhostPins,
|
||||
@@ -37,3 +39,5 @@ export {
|
||||
readSafeErrorCode,
|
||||
withProviderState,
|
||||
} from "./runtime.js";
|
||||
|
||||
export {DEFAULT_MAP_SCENE_EFFECTS} from "./sceneEffects.js";
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type {MapSceneContext, MapSceneEffects, MapVisualSettings} from './contracts.js';
|
||||
|
||||
/** Native Cesium 1.147 defaults; adding a settings window does not change the scene. */
|
||||
export const DEFAULT_MAP_SCENE_EFFECTS: Readonly<MapSceneEffects> = Object.freeze({
|
||||
skybox_enabled:true, sun_visible:true, moon_visible:true, ground_atmosphere_enabled:true,
|
||||
sun_color:'#ffffff', shadow_darkness:0.3, shadow_soft:false,
|
||||
terrain_maximum_screen_space_error:2, resolution_scale:1, fxaa_enabled:false,
|
||||
hdr_enabled:false, exposure:1, tonemapper:'PBR_NEUTRAL',
|
||||
bloom_enabled:false, bloom_contrast:128, bloom_brightness:-0.3, bloom_sigma:2, bloom_step_size:1,
|
||||
ao_enabled:false, ao_intensity:3, ao_bias:0.1, ao_length_cap:0.26,
|
||||
});
|
||||
|
||||
/** Mutates visual properties only: never touches sources, camera, cache or domain objects. */
|
||||
export function applyMapSceneEffects({Cesium,viewer}:Pick<MapSceneContext,'Cesium'|'viewer'>,s:MapVisualSettings):void {
|
||||
const scene=viewer.scene, stages=scene.postProcessStages;
|
||||
if(s.skybox_enabled!==undefined && scene.skyBox)scene.skyBox.show=s.skybox_enabled;
|
||||
if(s.sun_visible!==undefined && scene.sun)scene.sun.show=s.sun_visible;
|
||||
if(s.moon_visible!==undefined && scene.moon)scene.moon.show=s.moon_visible;
|
||||
if(s.ground_atmosphere_enabled!==undefined)scene.globe.showGroundAtmosphere=s.ground_atmosphere_enabled;
|
||||
if(s.sun_color!==undefined)scene.light.color=Cesium.Color.fromCssColorString(s.sun_color)??Cesium.Color.WHITE;
|
||||
if(s.shadow_darkness!==undefined)viewer.shadowMap.darkness=s.shadow_darkness;
|
||||
if(s.shadow_soft!==undefined)viewer.shadowMap.softShadows=s.shadow_soft;
|
||||
if(s.terrain_maximum_screen_space_error!==undefined)scene.globe.maximumScreenSpaceError=s.terrain_maximum_screen_space_error;
|
||||
if(s.resolution_scale!==undefined)viewer.resolutionScale=s.resolution_scale;
|
||||
if(s.fxaa_enabled!==undefined)stages.fxaa.enabled=s.fxaa_enabled;
|
||||
if(s.hdr_enabled!==undefined)scene.highDynamicRange=s.hdr_enabled;
|
||||
if(s.exposure!==undefined)stages.exposure=s.exposure;
|
||||
if(s.tonemapper!==undefined)stages.tonemapper=Cesium.Tonemapper[s.tonemapper];
|
||||
if(s.bloom_enabled!==undefined)stages.bloom.enabled=s.bloom_enabled;
|
||||
if(s.bloom_contrast!==undefined)stages.bloom.uniforms.contrast=s.bloom_contrast;
|
||||
if(s.bloom_brightness!==undefined)stages.bloom.uniforms.brightness=s.bloom_brightness;
|
||||
if(s.bloom_sigma!==undefined)stages.bloom.uniforms.sigma=s.bloom_sigma;
|
||||
if(s.bloom_step_size!==undefined)stages.bloom.uniforms.stepSize=s.bloom_step_size;
|
||||
if(s.ao_enabled!==undefined)stages.ambientOcclusion.enabled=s.ao_enabled && Cesium.PostProcessStageLibrary.isAmbientOcclusionSupported(scene);
|
||||
if(s.ao_intensity!==undefined)stages.ambientOcclusion.uniforms.intensity=s.ao_intensity;
|
||||
if(s.ao_bias!==undefined)stages.ambientOcclusion.uniforms.bias=s.ao_bias;
|
||||
if(s.ao_length_cap!==undefined)stages.ambientOcclusion.uniforms.lengthCap=s.ao_length_cap;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {applyMapSceneEffects,DEFAULT_MAP_SCENE_EFFECTS} from '../dist/sceneEffects.js';
|
||||
|
||||
function context(supported=true){
|
||||
const viewer={resolutionScale:1,shadowMap:{},scene:{skyBox:{},sun:{},moon:{},globe:{},light:{},postProcessStages:{fxaa:{},bloom:{uniforms:{}},ambientOcclusion:{uniforms:{}}}}};
|
||||
const Cesium={Color:{fromCssColorString:value=>value,WHITE:'white'},Tonemapper:{ACES:'ACES',PBR_NEUTRAL:'PBR_NEUTRAL'},PostProcessStageLibrary:{isAmbientOcclusionSupported:()=>supported}};
|
||||
return {viewer,Cesium};
|
||||
}
|
||||
test('optional effects leave legacy consumers unchanged',()=>{
|
||||
const c=context(),before=structuredClone(c.viewer);applyMapSceneEffects(c,{});assert.deepEqual(c.viewer,before);
|
||||
});
|
||||
test('effects apply live and reset without changing camera or providers',()=>{
|
||||
const c=context();c.viewer.camera={position:'unchanged'};c.viewer.terrainProvider={id:'cache'};
|
||||
applyMapSceneEffects(c,{...DEFAULT_MAP_SCENE_EFFECTS,bloom_enabled:true,bloom_contrast:64,hdr_enabled:true,exposure:2,tonemapper:'ACES',ao_enabled:true,ao_intensity:6,sun_visible:false,resolution_scale:.7});
|
||||
const {scene}=c.viewer;
|
||||
assert.equal(scene.postProcessStages.bloom.enabled,true);assert.equal(scene.postProcessStages.bloom.uniforms.contrast,64);
|
||||
assert.equal(scene.postProcessStages.ambientOcclusion.uniforms.intensity,6);assert.equal(scene.postProcessStages.ambientOcclusion.enabled,true);
|
||||
assert.equal(scene.highDynamicRange,true);assert.equal(scene.postProcessStages.exposure,2);assert.equal(scene.postProcessStages.tonemapper,'ACES');
|
||||
assert.equal(scene.sun.show,false);assert.equal(c.viewer.resolutionScale,.7);
|
||||
applyMapSceneEffects(c,DEFAULT_MAP_SCENE_EFFECTS);
|
||||
assert.equal(scene.postProcessStages.bloom.enabled,false);assert.equal(scene.highDynamicRange,false);assert.equal(scene.sun.show,true);
|
||||
assert.deepEqual(c.viewer.camera,{position:'unchanged'});assert.deepEqual(c.viewer.terrainProvider,{id:'cache'});
|
||||
});
|
||||
test('unsupported ambient occlusion stays off',()=>{
|
||||
const c=context(false);applyMapSceneEffects(c,{ao_enabled:true});assert.equal(c.viewer.scene.postProcessStages.ambientOcclusion.enabled,false);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
:root {
|
||||
--nodedc-field-hover-bg: color-mix(in srgb, var(--nodedc-field-bg) 94%, var(--nodedc-text-primary));
|
||||
--nodedc-neutral-action-bg: rgba(247, 248, 244, 0.96);
|
||||
--nodedc-neutral-action-hover: #fff;
|
||||
--nodedc-neutral-action-color: rgba(8, 8, 10, 0.96);
|
||||
@@ -9,14 +10,16 @@
|
||||
:root,
|
||||
[data-nodedc-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--nodedc-accent-rgb: 255 47 146;
|
||||
--nodedc-on-accent-rgb: 11 17 23;
|
||||
--nodedc-accent-rgb: 247 248 244;
|
||||
--nodedc-on-accent-rgb: 8 8 10;
|
||||
--nodedc-danger-rgb: 255 116 116;
|
||||
--nodedc-warning-rgb: 255 209 102;
|
||||
--nodedc-success-rgb: 181 255 90;
|
||||
|
||||
--nodedc-canvas: #050506;
|
||||
--nodedc-canvas-soft: #0b0b0d;
|
||||
--nodedc-canvas-soft: #0d0d0f;
|
||||
--nodedc-stage: #08090b;
|
||||
--nodedc-surface-group: rgba(110, 110, 110, 0.07);
|
||||
--nodedc-text-primary: rgba(247, 248, 244, 0.96);
|
||||
--nodedc-text-secondary: rgba(247, 248, 244, 0.72);
|
||||
--nodedc-text-muted: rgba(247, 248, 244, 0.48);
|
||||
@@ -82,14 +85,16 @@
|
||||
|
||||
[data-nodedc-theme="light"] {
|
||||
color-scheme: light;
|
||||
--nodedc-accent-rgb: 255 47 146;
|
||||
--nodedc-on-accent-rgb: 11 17 23;
|
||||
--nodedc-accent-rgb: 24 25 28;
|
||||
--nodedc-on-accent-rgb: 247 248 244;
|
||||
--nodedc-danger-rgb: 205 47 67;
|
||||
--nodedc-warning-rgb: 173 111 0;
|
||||
--nodedc-success-rgb: 46 125 76;
|
||||
|
||||
--nodedc-canvas: #ececec;
|
||||
--nodedc-canvas-soft: #f4f4f4;
|
||||
--nodedc-stage: #ececec;
|
||||
--nodedc-surface-group: #f4f4f4;
|
||||
--nodedc-text-primary: rgba(18, 20, 22, 0.96);
|
||||
--nodedc-text-secondary: rgba(18, 20, 22, 0.7);
|
||||
--nodedc-text-muted: rgba(18, 20, 22, 0.48);
|
||||
@@ -152,3 +157,24 @@
|
||||
--nodedc-modal-shadow: 0 24px 72px rgb(0 0 0 / var(--nodedc-modal-glass-shadow-light-opacity)), inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
--nodedc-floating-surface: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(255, 255, 255, 0.72)), rgba(255, 255, 255, 0.94);
|
||||
}
|
||||
|
||||
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] {
|
||||
--nodedc-modal-surface: rgb(15 15 17 / .97);
|
||||
--nodedc-floating-surface: rgb(15 15 17 / .98);
|
||||
--nodedc-primary-action-bg: rgb(247 248 244 / .96);
|
||||
--nodedc-primary-action-hover: rgb(255 255 255);
|
||||
--nodedc-primary-action-color: rgb(8 8 10 / .96);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
--nodedc-focus-surface: rgb(255 255 255 / .09);
|
||||
}
|
||||
|
||||
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] {
|
||||
--nodedc-modal-surface: rgb(247 248 250 / .97);
|
||||
--nodedc-floating-surface: rgb(247 248 250 / .98);
|
||||
--nodedc-primary-action-bg: rgb(24 25 28 / .96);
|
||||
--nodedc-primary-action-hover: rgb(8 8 10);
|
||||
--nodedc-primary-action-color: rgb(247 248 244);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
}
|
||||
|
||||
@@ -72,3 +72,6 @@
|
||||
--nodedc-font-weight-medium: 620;
|
||||
--nodedc-font-weight-strong: 760;
|
||||
}
|
||||
|
||||
/* Readable V4 telemetry over moving scene imagery; independent of modal opacity. */
|
||||
:root { --nodedc-scene-glass-opacity: .52; --nodedc-scene-glass-blur: 18px; }
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
{
|
||||
"name": "@nodedc/ui-core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.4",
|
||||
"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"
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
export type DockTree = { id: string } | { axis: "x" | "y"; ratio: number; first: DockTree; second: DockTree };
|
||||
export type DockPosition = "center" | "left" | "right" | "top" | "bottom";
|
||||
export interface DockRect { left: number; top: number; width: number; height: number }
|
||||
export interface DockMove { activeId: string; overId: string; position: DockPosition }
|
||||
/** Workspace moves ignore overId and wrap the remaining layout at its outer edge. */
|
||||
export interface DockMove { activeId: string; overId: string; position: DockPosition; scope?: "panel" | "workspace" }
|
||||
|
||||
export function dockIds(tree: DockTree | null): string[] {
|
||||
return !tree ? [] : "id" in tree ? [tree.id] : [...dockIds(tree.first), ...dockIds(tree.second)];
|
||||
@@ -47,7 +48,15 @@ export function reconcileDockTree(tree: DockTree | null, ids: readonly string[])
|
||||
|
||||
export function moveDockPanel(tree: DockTree | null, move: DockMove): DockTree | null {
|
||||
const { activeId, overId, position } = move, ids = dockIds(tree);
|
||||
if (!tree || activeId === overId || !ids.includes(activeId) || !ids.includes(overId)) return tree;
|
||||
if (!tree || !ids.includes(activeId)) return tree;
|
||||
if (move.scope === "workspace") {
|
||||
if (position === "center" || ids.length < 2) return tree;
|
||||
const remaining = pruneDockTree(tree, ids.filter(id => id !== activeId))!;
|
||||
const before = position === "left" || position === "top";
|
||||
return {axis: position === "left" || position === "right" ? "x" : "y", ratio: 50,
|
||||
first: before ? {id: activeId} : remaining, second: before ? remaining : {id: activeId}};
|
||||
}
|
||||
if (activeId === overId || !ids.includes(overId)) return tree;
|
||||
const swap = (node: DockTree): DockTree => "id" in node
|
||||
? { id: node.id === activeId ? overId : node.id === overId ? activeId : node.id }
|
||||
: { ...node, first: swap(node.first), second: swap(node.second) };
|
||||
@@ -89,6 +98,26 @@ export function dockPosition(rect: DockRect, x: number, y: number): DockPosition
|
||||
}
|
||||
|
||||
|
||||
/** Outer 24 CSS px take priority over the existing per-panel zones.
|
||||
* bounds is the visible workspace, expressed in the same coordinates as rects.
|
||||
*/
|
||||
export function dockMoveAtPoint(bounds: DockRect, rects: Readonly<Record<string, DockRect>>, activeId: string, x: number, y: number): DockMove | null {
|
||||
if (![x, y, bounds.left, bounds.top, bounds.width, bounds.height].every(Number.isFinite)
|
||||
|| !dockPosition(bounds, x, y) || !(activeId in rects) || Object.keys(rects).length < 2) return null;
|
||||
const zoneX = Math.min(24, bounds.width * .08), zoneY = Math.min(24, bounds.height * .08);
|
||||
const edges: [Exclude<DockPosition, "center">, number][] = [
|
||||
["left", (x - bounds.left) / zoneX], ["right", (bounds.left + bounds.width - x) / zoneX],
|
||||
["top", (y - bounds.top) / zoneY], ["bottom", (bounds.top + bounds.height - y) / zoneY],
|
||||
];
|
||||
const nearest = edges.sort((a, b) => a[1] - b[1])[0];
|
||||
if (nearest[1] <= 1) return {activeId, overId: activeId, position: nearest[0], scope: "workspace"};
|
||||
for (const [id, rect] of Object.entries(rects)) {
|
||||
const position = dockPosition(rect, x, y);
|
||||
if (position && id !== activeId) return {activeId, overId: id, position};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface DockMinimum { width: number; height: number }
|
||||
export type DockMinimums = Readonly<Record<string, DockMinimum>>;
|
||||
/** Propagate content limits through every ancestor, not only the nearest split. */
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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`,
|
||||
|
||||
@@ -12,3 +12,4 @@ export {dockMinimum, constrainDockTree, type DockMinimum, type DockMinimums} fro
|
||||
export {preferDockSizes} from "./dockTree.js";
|
||||
|
||||
export * from "./menuAim.js";
|
||||
export * from "./editorDock.js";
|
||||
|
||||
@@ -15,12 +15,23 @@ export interface NodedcMaterial {
|
||||
|
||||
export interface ApplyThemeOptions {
|
||||
theme?: NodedcTheme;
|
||||
/** Operator UI qualified against Mission Core; opt-in across portals. */
|
||||
/** Mission Core is the canonical foundation. `default` is legacy compatibility. */
|
||||
appearance?: "default" | "mission";
|
||||
/** Flat surfaces remove decorative edges; keyboard focus uses a contrasting fill. */
|
||||
edges?: "default" | "flat";
|
||||
accent?: RgbTuple;
|
||||
material?: NodedcMaterial;
|
||||
}
|
||||
|
||||
/** Complete shared foundation; colors live exclusively in @nodedc/tokens/themes.css. */
|
||||
export const missionDarkTheme = Object.freeze({
|
||||
theme: "dark", appearance: "mission", edges: "flat",
|
||||
} as const satisfies ApplyThemeOptions);
|
||||
|
||||
export const missionLightTheme = Object.freeze({
|
||||
theme: "light", appearance: "mission", edges: "flat",
|
||||
} as const satisfies ApplyThemeOptions);
|
||||
|
||||
function formatRgb([red, green, blue]: RgbTuple): string {
|
||||
return `${red} ${green} ${blue}`;
|
||||
}
|
||||
@@ -31,10 +42,11 @@ function clampOpacity(value: number): number {
|
||||
|
||||
export function applyNodedcTheme(
|
||||
target: HTMLElement,
|
||||
{ theme = "dark", accent, material, appearance = "default" }: ApplyThemeOptions = {},
|
||||
{ theme = "dark", accent, material, appearance = "mission", edges = "flat" }: ApplyThemeOptions = {},
|
||||
): void {
|
||||
target.dataset.nodedcTheme = theme;
|
||||
target.dataset.nodedcAppearance = appearance;
|
||||
target.dataset.nodedcEdges = edges;
|
||||
target.dataset.nodedcUi = "true";
|
||||
|
||||
if (accent) {
|
||||
|
||||
+428
-54
@@ -1,7 +1,7 @@
|
||||
@import "@nodedc/tokens/tokens.css";
|
||||
@import "@nodedc/tokens/themes.css";
|
||||
|
||||
:where([data-nodedc-ui], .nodedc-ui-root) {
|
||||
:where([data-nodedc-ui], .nodedc-ui-root, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) {
|
||||
color: var(--nodedc-text-primary);
|
||||
font-family: var(--nodedc-font-family);
|
||||
font-synthesis: none;
|
||||
@@ -9,6 +9,18 @@
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* Theme attributes may live on html. Set the text base on body instead, so
|
||||
rem tokens and user zoom never get multiplied by the operational base. */
|
||||
:where([data-nodedc-ui]:not(html), .nodedc-ui-root:not(html), html[data-nodedc-ui] > body, html.nodedc-ui-root > body, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) {
|
||||
font-size: var(--nodedc-font-size-md);
|
||||
}
|
||||
|
||||
/* Semantic headings inside operational surfaces do not inherit browser h1–h6 scaling.
|
||||
Explicit canonical window/page titles retain their title token. */
|
||||
:where([data-nodedc-ui], .nodedc-ui-root, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) :where(h1, h2, h3, h4, h5, h6) {
|
||||
font-size: var(--nodedc-font-size-md);
|
||||
}
|
||||
|
||||
:where([data-nodedc-ui], .nodedc-ui-root) *,
|
||||
:where([data-nodedc-ui], .nodedc-ui-root) *::before,
|
||||
:where([data-nodedc-ui], .nodedc-ui-root) *::after {
|
||||
@@ -65,6 +77,12 @@
|
||||
box-shadow: var(--nodedc-glass-control-shadow);
|
||||
}
|
||||
|
||||
/* Form collections share SettingsCard's neutral group, not the recessed canvas. */
|
||||
.nodedc-glass[data-tone="group"] {
|
||||
background: var(--nodedc-surface-group);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.nodedc-glass[data-radius="panel"] {
|
||||
border-radius: var(--nodedc-radius-panel);
|
||||
}
|
||||
@@ -346,7 +364,8 @@
|
||||
color: var(--nodedc-text-primary);
|
||||
}
|
||||
|
||||
.nodedc-icon-button[aria-pressed="true"] {
|
||||
.nodedc-icon-button[aria-pressed="true"],
|
||||
.nodedc-header__profile .nodedc-icon-button[aria-pressed="true"] {
|
||||
background: var(--nodedc-glass-control-active);
|
||||
color: var(--nodedc-glass-control-active-text);
|
||||
}
|
||||
@@ -422,7 +441,7 @@
|
||||
}
|
||||
|
||||
.nodedc-field__control:hover:not(:disabled) {
|
||||
background: var(--nodedc-glass-control-hover);
|
||||
background: var(--nodedc-field-hover-bg);
|
||||
}
|
||||
|
||||
.nodedc-field__control:focus-visible {
|
||||
@@ -647,7 +666,7 @@ textarea.nodedc-field__control {
|
||||
min-width: 0;
|
||||
gap: 1rem;
|
||||
border-radius: var(--nodedc-radius-card);
|
||||
background: var(--nodedc-glass-control-bg);
|
||||
background: var(--nodedc-surface-group);
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
@@ -674,7 +693,8 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-settings-card__titles h2,
|
||||
.nodedc-description,
|
||||
.nodedc-settings-card__titles p {
|
||||
.nodedc-settings-card__titles p,
|
||||
.nodedc-settings-card__body :where(p:not([class])) {
|
||||
font-family: inherit;
|
||||
font-weight: 400;
|
||||
margin: 0;
|
||||
@@ -687,11 +707,12 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-description,
|
||||
.nodedc-settings-card__titles p {
|
||||
.nodedc-settings-card__titles p,
|
||||
.nodedc-settings-card__body :where(p:not([class])) {
|
||||
font-family: inherit;
|
||||
font-weight: 400;
|
||||
color: var(--nodedc-text-muted);
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
font-size: var(--nodedc-description-font-size, var(--nodedc-font-size-sm));
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
@@ -1018,7 +1039,7 @@ textarea.nodedc-field__control {
|
||||
position: relative;
|
||||
aspect-ratio: 1.5 / 1;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--nodedc-glass-outline);
|
||||
border: 0;
|
||||
border-radius: var(--nodedc-radius-control);
|
||||
outline: 0;
|
||||
background:
|
||||
@@ -1429,7 +1450,7 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-user-profile-card__cover strong {
|
||||
margin-top: 0.25rem;
|
||||
font-size: 0.92rem;
|
||||
font-size: var(--nodedc-font-size-md);
|
||||
}
|
||||
|
||||
.nodedc-user-profile-card__cover > span:not(.nodedc-header__avatar) {
|
||||
@@ -1456,7 +1477,7 @@ textarea.nodedc-field__control {
|
||||
text-align: left;
|
||||
text-decoration: none;
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
font-size: var(--nodedc-font-size-md);
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -1550,20 +1571,28 @@ textarea.nodedc-field__control {
|
||||
--nodedc-app-page-pad: 1.25rem;
|
||||
--nodedc-app-panel-gap: 1.25rem;
|
||||
--nodedc-app-nav-width: clamp(20.75rem, 19.5vw, 22rem);
|
||||
--nodedc-app-nav-current-width: var(--nodedc-app-nav-width);
|
||||
--nodedc-app-nav-rail-width: 4.55rem;
|
||||
--nodedc-app-navigation-motion: 440ms cubic-bezier(0.22, 1, 0.36, 1);
|
||||
--nodedc-app-content-width: calc(
|
||||
100vw - (var(--nodedc-app-page-pad) * 2) - (var(--nodedc-app-panel-gap) * 2) - (var(--nodedc-app-nav-width) * 2)
|
||||
100vw - (var(--nodedc-app-page-pad) * 2) - (var(--nodedc-app-panel-gap) * 2) - var(--nodedc-app-nav-current-width) - var(--nodedc-app-nav-width)
|
||||
);
|
||||
min-height: 100vh;
|
||||
overflow: hidden;
|
||||
background: var(--nodedc-canvas);
|
||||
}
|
||||
|
||||
.nodedc-app-shell[data-navigation-collapsed="true"] {
|
||||
--nodedc-app-nav-current-width: var(--nodedc-app-nav-rail-width);
|
||||
}
|
||||
|
||||
.nodedc-app-shell__main {
|
||||
position: relative;
|
||||
height: calc(100vh - var(--nodedc-app-header-height));
|
||||
min-height: 0;
|
||||
margin-top: var(--nodedc-app-header-height);
|
||||
overflow: hidden;
|
||||
/* Translated inactive stages must not become a focus-scroll destination. */
|
||||
overflow: clip;
|
||||
}
|
||||
|
||||
.nodedc-app-shell__stage {
|
||||
@@ -1591,18 +1620,21 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-app-shell__navigation {
|
||||
left: var(--nodedc-app-page-pad);
|
||||
width: var(--nodedc-app-nav-width);
|
||||
width: var(--nodedc-app-nav-current-width);
|
||||
transition: width var(--nodedc-app-navigation-motion);
|
||||
}
|
||||
|
||||
.nodedc-app-shell__content {
|
||||
left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-width) + var(--nodedc-app-panel-gap));
|
||||
left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-current-width) + var(--nodedc-app-panel-gap));
|
||||
width: max(32rem, var(--nodedc-app-content-width));
|
||||
transition: width 500ms cubic-bezier(0.22, 1, 0.36, 1), right 500ms cubic-bezier(0.22, 1, 0.36, 1);
|
||||
transition: left var(--nodedc-app-navigation-motion), width var(--nodedc-app-navigation-motion), right var(--nodedc-app-navigation-motion);
|
||||
}
|
||||
|
||||
.nodedc-app-shell__end-panel {
|
||||
right: var(--nodedc-app-page-pad);
|
||||
width: var(--nodedc-app-nav-width);
|
||||
transform: translateX(calc(100% + var(--nodedc-app-page-pad)));
|
||||
transition: transform var(--nodedc-app-navigation-motion), visibility 0s linear 440ms;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -1613,6 +1645,8 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-app-shell[data-end-panel-open="true"] .nodedc-app-shell__end-panel {
|
||||
transform: translateX(0);
|
||||
transition-delay: 0s;
|
||||
visibility: visible;
|
||||
pointer-events: auto;
|
||||
}
|
||||
@@ -1622,12 +1656,12 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-app-shell[data-navigation-open="true"] .nodedc-app-shell__stage {
|
||||
padding-left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-width) + var(--nodedc-app-panel-gap));
|
||||
padding-left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-current-width) + var(--nodedc-app-panel-gap));
|
||||
}
|
||||
|
||||
.nodedc-app-shell[data-content-open="true"]:not([data-content-expanded="true"]) .nodedc-app-shell__stage {
|
||||
padding-left: calc(
|
||||
var(--nodedc-app-page-pad) + var(--nodedc-app-nav-width) + var(--nodedc-app-panel-gap) +
|
||||
var(--nodedc-app-page-pad) + var(--nodedc-app-nav-current-width) + var(--nodedc-app-panel-gap) +
|
||||
max(32rem, var(--nodedc-app-content-width)) + var(--nodedc-app-panel-gap)
|
||||
);
|
||||
}
|
||||
@@ -1700,7 +1734,7 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-application-panel__titles h1 {
|
||||
font-size: 1.15rem;
|
||||
font-size: var(--nodedc-font-size-title);
|
||||
font-weight: 780;
|
||||
line-height: 1.15;
|
||||
}
|
||||
@@ -1708,7 +1742,7 @@ textarea.nodedc-field__control {
|
||||
.nodedc-application-panel__titles p {
|
||||
max-width: 42rem;
|
||||
color: var(--nodedc-text-muted);
|
||||
font-size: 0.75rem;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
@@ -1844,7 +1878,7 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-admin-panel__head p {
|
||||
color: var(--nodedc-text-muted);
|
||||
font-size: 0.68rem;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
font-weight: 850;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
@@ -1852,7 +1886,7 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-admin-panel__head h2 {
|
||||
margin-top: 0.55rem;
|
||||
font-size: 1.15rem;
|
||||
font-size: var(--nodedc-font-size-title);
|
||||
font-weight: 780;
|
||||
line-height: 1.1;
|
||||
}
|
||||
@@ -2005,7 +2039,7 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-admin-context__body strong {
|
||||
font-size: 0.92rem;
|
||||
font-size: var(--nodedc-font-size-md);
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
@@ -2044,7 +2078,7 @@ textarea.nodedc-field__control {
|
||||
color: var(--nodedc-text-secondary);
|
||||
padding: 5px 0.9rem 5px calc(5px + 2.92rem + 0.86rem);
|
||||
font: inherit;
|
||||
font-size: 0.91rem;
|
||||
font-size: var(--nodedc-font-size-md);
|
||||
font-weight: 570;
|
||||
text-align: left;
|
||||
opacity: 0.66;
|
||||
@@ -2109,7 +2143,7 @@ textarea.nodedc-field__control {
|
||||
padding-right: 3rem;
|
||||
}
|
||||
|
||||
.nodedc-admin-panel__sortable-row > .nodedc-drag-handle {
|
||||
.nodedc-admin-panel__sortable-row > span > .nodedc-drag-handle {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 0.72rem;
|
||||
@@ -2146,6 +2180,72 @@ textarea.nodedc-field__control {
|
||||
opacity: 0.82;
|
||||
}
|
||||
|
||||
/* Shared collapsible left navigation; the right application panel is independent. */
|
||||
.nodedc-admin-panel--navigation {
|
||||
--nodedc-app-nav-rail-width: 4.55rem;
|
||||
transition: width var(--nodedc-app-navigation-motion, 440ms cubic-bezier(0.22, 1, 0.36, 1));
|
||||
}
|
||||
.nodedc-admin-panel--navigation .nodedc-admin-panel__head { min-height: 3.55rem; }
|
||||
.nodedc-admin-panel__titles { min-width: 0; padding-right: 4.5rem; }
|
||||
.nodedc-admin-panel__titles,
|
||||
.nodedc-admin-panel__item-label,
|
||||
.nodedc-admin-panel--navigation .nodedc-admin-context__body,
|
||||
.nodedc-admin-panel--navigation .nodedc-admin-panel__footer > :not(.nodedc-admin-panel__nav-icon) {
|
||||
transition: opacity 160ms ease;
|
||||
}
|
||||
.nodedc-admin-panel__item-label { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.nodedc-admin-panel__extra-actions { display: contents; }
|
||||
.nodedc-admin-panel__extra-actions:empty { display: none; }
|
||||
.nodedc-admin-panel__extra-actions > .nodedc-icon-button { width: 2.92rem; height: 2.92rem; flex-basis: 2.92rem; }
|
||||
.nodedc-admin-panel__context-area { display: grid; gap: .48rem; }
|
||||
.nodedc-admin-panel--navigation .nodedc-admin-panel__item-tooltip { display: block; width: 100%; min-width: 0; }
|
||||
.nodedc-admin-panel--navigation [hidden] { display: none; }
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] { width: var(--nodedc-app-nav-rail-width); }
|
||||
.nodedc-admin-panel--navigation .nodedc-admin-context__main { width: 100%; }
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__titles { height: 0; }
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__titles,
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__item-label,
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-context__body,
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__footer > :not(.nodedc-admin-panel__nav-icon) {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
width: 0;
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__head-actions {
|
||||
left: 0; right: 0; justify-content: center;
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] :is(.nodedc-admin-panel__nav-item, .nodedc-admin-panel__footer, .nodedc-admin-context__main) {
|
||||
justify-content: center; gap: 0; padding-inline: 0;
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] :is(.nodedc-admin-panel__nav-item, .nodedc-admin-panel__footer, .nodedc-admin-context) {
|
||||
background: transparent; box-shadow: none;
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-context { grid-template-columns: minmax(0, 1fr); }
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-icon {
|
||||
position: static; transform: none;
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon,
|
||||
.nodedc-admin-panel--navigation .nodedc-admin-context__main:focus-visible .nodedc-admin-context__icon {
|
||||
background: var(--nodedc-glass-control-hover); color: var(--nodedc-text-primary);
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] :is(.nodedc-admin-panel__nav-item, .nodedc-admin-context__main):focus-visible {
|
||||
background: transparent; box-shadow: none;
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon,
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-context__main:focus-visible .nodedc-admin-context__icon {
|
||||
background: var(--nodedc-text-primary); color: var(--nodedc-canvas);
|
||||
}
|
||||
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon > svg { color: inherit; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.nodedc-admin-panel--navigation,
|
||||
.nodedc-admin-panel--navigation *,
|
||||
.nodedc-app-shell__navigation,
|
||||
.nodedc-app-shell__content,
|
||||
.nodedc-app-shell__stage { transition: none; animation: none; }
|
||||
}
|
||||
|
||||
.nodedc-dropdown-anchor {
|
||||
display: inline-flex;
|
||||
}
|
||||
@@ -2907,7 +3007,7 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-workspace-window__head:focus-visible {
|
||||
background: var(--nodedc-focus-surface);
|
||||
box-shadow: inset 0 0 0 1px rgb(var(--nodedc-accent-rgb) / 0.22);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.nodedc-workspace-window[data-maximized="true"] .nodedc-workspace-window__head {
|
||||
@@ -3148,7 +3248,9 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
/* Keep the full hit area and keyboard focus cue without a visible divider. */
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator:not(:focus-visible)::before {
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator:not(:focus-visible)::before,
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator[data-pointer-focus]::before,
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"][data-dragging="true"] > .nodedc-split-pane__separator::before {
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
@@ -3546,20 +3648,29 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-inspector {
|
||||
container-type: inline-size;
|
||||
container-name: nodedc-inspector;
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
width: min(var(--nodedc-inspector-inner-width), 100%);
|
||||
gap: 1px;
|
||||
gap: var(--nodedc-space-3);
|
||||
}
|
||||
|
||||
.nodedc-inspector__header { display: grid; min-width: 0; gap: var(--nodedc-space-3); }
|
||||
.nodedc-inspector__footer { display: flex; justify-content: center; align-items: center; flex-wrap: wrap; gap: var(--nodedc-space-3); }
|
||||
|
||||
.nodedc-inspector__group {
|
||||
display: grid;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--nodedc-space-3);
|
||||
}
|
||||
|
||||
.nodedc-inspector__section {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 1px;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.nodedc-inspector__section-trigger {
|
||||
@@ -3634,6 +3745,8 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-inspector__section-content {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--nodedc-space-3);
|
||||
padding: var(--nodedc-space-3) 0 var(--nodedc-space-2);
|
||||
animation: nodedc-section-in var(--nodedc-duration-fast) ease;
|
||||
@@ -3731,7 +3844,7 @@ textarea.nodedc-field__control {
|
||||
display: grid;
|
||||
width: min(var(--nodedc-inspector-inner-width), 100%);
|
||||
min-height: var(--nodedc-control-height);
|
||||
grid-template-columns: var(--nodedc-inspector-label-width) var(--nodedc-inspector-control-width);
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, var(--nodedc-inspector-control-width));
|
||||
align-items: center;
|
||||
gap: var(--nodedc-inspector-control-gap);
|
||||
}
|
||||
@@ -3842,6 +3955,11 @@ textarea.nodedc-field__control {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.nodedc-app-shell[data-navigation-collapsed="true"] .nodedc-app-shell__navigation {
|
||||
right: auto;
|
||||
width: var(--nodedc-app-nav-rail-width);
|
||||
}
|
||||
|
||||
.nodedc-app-shell[data-end-panel-open="true"] .nodedc-app-shell__content {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
@@ -3911,6 +4029,7 @@ textarea.nodedc-field__control {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.nodedc-header__profile-button,
|
||||
.nodedc-user-profile-menu__trigger-label {
|
||||
display: none;
|
||||
}
|
||||
@@ -4000,7 +4119,7 @@ textarea.nodedc-field__control {
|
||||
[data-nodedc-theme="light"] :is(.nodedc-header__brand, .nodedc-header__workspace)[data-monochrome="true"] img { filter: brightness(0); }
|
||||
|
||||
/* Owner-admitted linear progress in the shared resource row. */
|
||||
.nodedc-progress-bar { min-width: 3rem; height: var(--nodedc-space-2); overflow: hidden; border-radius: var(--nodedc-radius-circle); background: var(--nodedc-glass-control-bg); }
|
||||
.nodedc-progress-bar { min-width: 3rem; height: var(--nodedc-progress-height, var(--nodedc-space-2)); overflow: hidden; border-radius: var(--nodedc-radius-circle); background: var(--nodedc-glass-control-bg); }
|
||||
.nodedc-progress-bar__fill { display: block; width: 100%; height: 100%; background: var(--nodedc-text-secondary); border-radius: inherit; transform: scaleX(var(--nodedc-progress-fraction)); transform-origin: left; transition: transform var(--nodedc-duration-normal) var(--nodedc-ease-standard); }
|
||||
.nodedc-progress-bar[data-indeterminate] > .nodedc-progress-bar__fill { width: 35%; animation: nodedc-progress-travel 1.5s ease-in-out infinite alternate; }
|
||||
@keyframes nodedc-progress-travel { from { transform: translateX(-100%); } to { transform: translateX(285%); } }
|
||||
@@ -4093,7 +4212,7 @@ textarea.nodedc-field__control {
|
||||
max-width: 34rem;
|
||||
margin: 0;
|
||||
color: var(--nodedc-text-secondary);
|
||||
font-size: clamp(0.8rem, 1vw, 1rem);
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
@@ -4128,7 +4247,7 @@ textarea.nodedc-field__control {
|
||||
.nodedc-landing-stage__status p {
|
||||
margin: 0.15rem 0 0;
|
||||
color: var(--nodedc-text-muted);
|
||||
font-size: 0.66rem;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
@@ -4235,7 +4354,7 @@ textarea.nodedc-field__control {
|
||||
.nodedc-environment-media-playlist__error {
|
||||
margin: 0;
|
||||
color: var(--nodedc-text-muted);
|
||||
font-size: var(--nodedc-font-size-xs);
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
@@ -4347,7 +4466,7 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
@media (max-height: 720px) and (min-width: 761px) {
|
||||
.nodedc-landing-stage__copy p {
|
||||
font-size: 0.76rem;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
}
|
||||
}
|
||||
@media (max-height: 720px) and (min-width: 761px) {
|
||||
@@ -4373,26 +4492,11 @@ textarea.nodedc-field__control {
|
||||
.nodedc-key-button:disabled { opacity:.4; cursor:not-allowed; }
|
||||
.nodedc-key-button:focus-visible { outline:2px solid rgb(var(--nodedc-accent-rgb)); outline-offset:3px; }
|
||||
|
||||
/* Shared operator appearance, qualified against Mission Core 2026-09-30.
|
||||
/* Canonical operator appearance, audited against Mission Core 2026-11-05.
|
||||
Set on documentElement so modal and dropdown portals share the same profile. */
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] {
|
||||
--nodedc-modal-surface: rgb(15 15 17 / .97);
|
||||
--nodedc-floating-surface: rgb(15 15 17 / .98);
|
||||
--nodedc-primary-action-bg: rgb(247 248 244 / .96);
|
||||
--nodedc-primary-action-hover: rgb(255 255 255);
|
||||
--nodedc-primary-action-color: rgb(8 8 10 / .96);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
--nodedc-focus-surface: rgb(255 255 255 / .09);
|
||||
}
|
||||
|
||||
[data-nodedc-appearance="mission"] .nodedc-glass-material::before { display: none; }
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] {
|
||||
--nodedc-modal-surface: rgb(247 248 250 / .97);
|
||||
--nodedc-floating-surface: rgb(247 248 250 / .98);
|
||||
--nodedc-primary-action-bg: rgb(24 25 28 / .96);
|
||||
--nodedc-primary-action-hover: rgb(8 8 10);
|
||||
--nodedc-primary-action-color: rgb(247 248 244);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
}
|
||||
|
||||
[data-nodedc-appearance="mission"] .nodedc-header__avatar { background: rgb(226 226 226); }
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] .nodedc-feature-settings__section[data-active="true"] { background: rgb(247 248 244 / .14); }
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] .nodedc-feature-settings__section[data-active="true"] { background: rgb(8 8 10 / .09); }
|
||||
@@ -4517,6 +4621,34 @@ textarea.nodedc-field__control {
|
||||
/* Content minimums govern resizing; an undersized viewport scrolls the canvas. */
|
||||
.nodedc-dock-layout {overflow:auto; overscroll-behavior:contain;}
|
||||
.nodedc-dock-layout__canvas {position:relative; height:100%; width:100%;}
|
||||
|
||||
/* Shared editor workspace: its header is outside the docking bounds. */
|
||||
.nodedc-editor-workspace__slot,.nodedc-editor-workspace__host,.nodedc-editor-workspace {position:relative;width:100%;height:100%;min-width:0;min-height:0;}
|
||||
.nodedc-editor-workspace {display:flex;flex-direction:column;}
|
||||
.nodedc-editor-workspace__host[data-editing="true"] {position:fixed;inset:var(--nodedc-space-4);width:auto;height:auto;z-index:calc(var(--nodedc-layer-overlay) - 1);background:var(--nodedc-app-panel-surface);border-radius:var(--nodedc-radius-panel);box-shadow:var(--nodedc-modal-shadow);overflow:hidden;}
|
||||
.nodedc-editor-workspace__host[data-editing="true"][data-expanded="true"] {inset:0;border-radius:0;}
|
||||
.nodedc-editor-workspace__head {flex:none;}
|
||||
.nodedc-editor-workspace__body {position:relative;flex:1;min-height:0;min-width:0;overflow:hidden;}
|
||||
.nodedc-editor-dock {position:absolute;inset:0;overflow:auto;overscroll-behavior:contain;isolation:isolate;}
|
||||
.nodedc-editor-dock__canvas {position:relative;width:100%;height:100%;}
|
||||
.nodedc-editor-dock__primary {position:absolute;isolation:isolate;overflow:hidden;min-width:0;min-height:0;}
|
||||
.nodedc-editor-dock__tool {position:absolute;display:flex;flex-direction:column;box-sizing:border-box;min-width:0;min-height:0;}
|
||||
.nodedc-editor-dock__tool[hidden] {display:none;}
|
||||
.nodedc-editor-dock__tool:not([data-floating]) {border-radius:0;box-shadow:none;}
|
||||
.nodedc-editor-dock__tool::before {display:none;}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="top-left"] {border-top-left-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="top-right"] {border-top-right-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="bottom-right"] {border-bottom-right-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="bottom-left"] {border-bottom-left-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head {flex:none;cursor:grab;touch-action:none;user-select:none;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head:active {cursor:grabbing;}
|
||||
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head:focus-visible :is(.nodedc-window__title,.nodedc-window__subtitle,.nodedc-window__actions,.nodedc-window__close,.nodedc-icon-button) {color:inherit;}
|
||||
.nodedc-editor-dock__body {flex:1;min-height:0;min-width:0;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;padding:0 var(--nodedc-space-3) var(--nodedc-space-3);}
|
||||
.nodedc-editor-dock__tool .nodedc-inspector {width:100%;max-width:none;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__footer {flex:none;}
|
||||
.nodedc-editor-dock__shield {position:absolute;inset:0;z-index:30;cursor:grabbing;}
|
||||
.nodedc-editor-dock__preview {z-index:50;pointer-events:none;}
|
||||
.nodedc-comparison-table[data-density="compact"] table {min-width:calc(7.5rem + (var(--nodedc-comparison-columns) - 1) * 5.5rem); table-layout:fixed; line-height:1.25;}
|
||||
.nodedc-comparison-table[data-density="compact"] col:first-child {width:7.5rem;}
|
||||
.nodedc-comparison-table[data-density="compact"] th, .nodedc-comparison-table[data-density="compact"] td {padding:3px var(--nodedc-space-1);}
|
||||
@@ -4539,9 +4671,251 @@ textarea.nodedc-field__control {
|
||||
|
||||
/* Structural cube edges communicate face/edge/corner hit zones. */
|
||||
.nodedc-navigation-cube { width: 66px; height: 66px; overflow: visible; user-select: none; }
|
||||
.nodedc-navigation-cube polygon { fill: var(--cube-face, var(--nodedc-surface-raised, #292929)); stroke: var(--cube-edge, var(--nodedc-text-muted, #888)); stroke-width: .55; stroke-opacity: var(--cube-edge-opacity, 1); }
|
||||
.nodedc-navigation-cube polygon { fill: var(--cube-face, var(--nodedc-surface-raised, #292929)); stroke: var(--cube-edge, var(--nodedc-text-muted, #888)); stroke-width: .55; stroke-opacity: var(--cube-edge-opacity, 1); fill-opacity:var(--cube-face-opacity,1); }
|
||||
.nodedc-navigation-cube text { fill: var(--cube-text, var(--nodedc-text-primary, #eee)); font: 600 9px var(--nodedc-font-family); pointer-events: none; }
|
||||
.nodedc-navigation-cube g { cursor: pointer; }
|
||||
.nodedc-navigation-cube g.is-hovered polygon, .nodedc-navigation-cube g:focus-visible polygon { fill: var(--cube-hover, var(--nodedc-control-selected-bg, #eee)); }
|
||||
.nodedc-navigation-cube g.is-hovered text, .nodedc-navigation-cube g:focus-visible text { fill: var(--cube-hover-text, var(--nodedc-control-selected-text, #161616)); }
|
||||
.nodedc-navigation-cube g[aria-disabled="true"] { opacity: .45; cursor: default; }
|
||||
|
||||
.nodedc-window__resize:is([data-edge="n"], [data-edge="s"]) { cursor: ns-resize; }
|
||||
.nodedc-window__resize:is([data-edge="e"], [data-edge="w"]) { cursor: ew-resize; }
|
||||
.nodedc-window__resize:is([data-edge="ne"], [data-edge="sw"]) { cursor: nesw-resize; }
|
||||
.nodedc-window__resize:is([data-edge="nw"], [data-edge="se"]) { cursor: nwse-resize; }
|
||||
.nodedc-window[data-floating="true"] > .nodedc-window__head { cursor: move; }
|
||||
|
||||
/* Modeless mode retains the same mounted window and form. */
|
||||
.nodedc-overlay[data-floating="true"] {
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
pointer-events: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
.nodedc-window[data-floating="true"] { pointer-events: auto; }
|
||||
.nodedc-window[data-floating="true"] > .nodedc-window__head { touch-action: none; user-select: none; }
|
||||
.nodedc-window__resize { position: absolute; z-index: 3; touch-action: none; }
|
||||
.nodedc-window__resize[data-edge="n"] { top: 0; left: 12px; right: 12px; height: 6px; }
|
||||
.nodedc-window__resize[data-edge="s"] { bottom: 0; left: 12px; right: 12px; height: 6px; }
|
||||
.nodedc-window__resize[data-edge="e"] { right: 0; top: 12px; bottom: 12px; width: 6px; }
|
||||
.nodedc-window__resize[data-edge="w"] { left: 0; top: 12px; bottom: 12px; width: 6px; }
|
||||
.nodedc-window__resize[data-edge="ne"] { top: 0; right: 0; width: 12px; height: 12px; }
|
||||
.nodedc-window__resize[data-edge="nw"] { top: 0; left: 0; width: 12px; height: 12px; }
|
||||
.nodedc-window__resize[data-edge="se"] { bottom: 0; right: 0; width: 12px; height: 12px; }
|
||||
.nodedc-window__resize[data-edge="sw"] { bottom: 0; left: 0; width: 12px; height: 12px; }
|
||||
/* An inspector in a settings window follows the available content width. */
|
||||
.nodedc-window__body .nodedc-inspector,
|
||||
.nodedc-window__body .nodedc-control-row { width: 100%; min-width: 0; }
|
||||
|
||||
|
||||
.nodedc-feature-settings-window > .nodedc-window__body { container: nodedc-settings / inline-size; }
|
||||
@container nodedc-settings (max-width: 42rem) {
|
||||
.nodedc-feature-settings { grid-template-columns:minmax(0,1fr); grid-template-rows:auto minmax(0,1fr); }
|
||||
.nodedc-feature-settings__navigation { max-height:10rem; }
|
||||
}
|
||||
|
||||
/* Compact outliner: rows, indentation and selection; no nested card surfaces. */
|
||||
.nodedc-tree { overflow:auto; min-height:0; overscroll-behavior:contain; font-size:var(--nodedc-font-size-sm); }
|
||||
.nodedc-tree__row { display:flex; align-items:center; gap:6px; min-height:28px; padding:2px 6px 2px calc(4px + var(--tree-depth) * 14px); box-sizing:border-box; cursor:default; user-select:none; color:var(--nodedc-text-secondary); }
|
||||
.nodedc-tree__row:hover { background:rgb(var(--nodedc-accent-rgb) / .06); }
|
||||
.nodedc-tree__row[aria-selected="true"] { background:rgb(var(--nodedc-accent-rgb) / .14); color:var(--nodedc-text-primary); }
|
||||
.nodedc-tree__row:focus-visible { outline:2px solid var(--nodedc-accent); outline-offset:-2px; }
|
||||
.nodedc-tree__row > svg { flex:0 0 auto; }
|
||||
.nodedc-tree__branch { display:flex; flex:0 0 16px; }
|
||||
.nodedc-tree__label { flex:1; min-width:0; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
|
||||
.nodedc-tree button { appearance:none; border:0; padding:2px; background:transparent; color:inherit; display:flex; align-items:center; justify-content:center; width:20px; height:22px; cursor:pointer; }
|
||||
.nodedc-tree button:focus-visible { outline:2px solid var(--nodedc-accent); }
|
||||
.nodedc-tree__visibility { flex:0 0 20px; opacity:.6; }
|
||||
.nodedc-tree__visibility:hover { opacity:1; }
|
||||
.nodedc-window[data-resizable="true"] { display:flex; flex-direction:column; }
|
||||
.nodedc-window[data-resizable="true"] > .nodedc-window__body { flex:1; min-height:0; }
|
||||
|
||||
.nodedc-glass-material[data-radius="panel"] { border-radius:var(--nodedc-radius-panel); }
|
||||
.nodedc-glass-material[data-radius="card"] { border-radius:var(--nodedc-radius-card); }
|
||||
.nodedc-glass-material[data-radius="pill"] { border-radius:var(--nodedc-radius-circle); }
|
||||
.nodedc-glass-material[data-glass-context="scene"] {
|
||||
background:rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
|
||||
backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
-webkit-backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
box-shadow:var(--nodedc-glass-panel-shadow);
|
||||
}
|
||||
.nodedc-resizable-viewport { position:relative; min-width:0; isolation:isolate; }
|
||||
.nodedc-resizable-viewport__grip {
|
||||
position:absolute; z-index:4; bottom:0; width:28px; height:28px;
|
||||
color:var(--nodedc-text-secondary); cursor:ns-resize; touch-action:none; user-select:none;
|
||||
border-radius:var(--nodedc-radius-sm);
|
||||
}
|
||||
.nodedc-resizable-viewport__grip[data-corner="end"] { right:0; }
|
||||
.nodedc-resizable-viewport__grip[data-corner="start"] { left:0; transform:scaleX(-1); }
|
||||
.nodedc-resizable-viewport__grip::before, .nodedc-resizable-viewport__grip::after {
|
||||
content:""; position:absolute; right:5px; bottom:5px;
|
||||
border-right:1px solid currentColor; border-bottom:1px solid currentColor;
|
||||
}
|
||||
.nodedc-resizable-viewport__grip::before { width:12px; height:12px; }
|
||||
.nodedc-resizable-viewport__grip::after { width:6px; height:6px; }
|
||||
.nodedc-resizable-viewport__grip:hover { color:var(--nodedc-text-primary); background:var(--nodedc-glass-control-hover); }
|
||||
.nodedc-resizable-viewport__grip:focus-visible { outline:2px solid rgb(var(--nodedc-accent-rgb)); outline-offset:-3px; }
|
||||
.nodedc-panel-viewport-anchor, .nodedc-panel-viewport-anchor > div, .nodedc-panel-viewport { height:100%; min-height:0; }
|
||||
.nodedc-panel-viewport[data-fullscreen="true"] { position:fixed; inset:var(--nodedc-space-3); height:auto; z-index:calc(var(--nodedc-layer-overlay) - 1); }
|
||||
.nodedc-panel-viewport[data-fullscreen="true"] > .nodedc-application-panel { animation:none; }
|
||||
|
||||
.nodedc-resizable-viewport[data-resize-indicator="hidden"] .nodedc-resizable-viewport__grip::before,
|
||||
.nodedc-resizable-viewport[data-resize-indicator="hidden"] .nodedc-resizable-viewport__grip::after { display:none; }
|
||||
.nodedc-resizable-viewport[data-resize-indicator="hidden"] .nodedc-resizable-viewport__grip:hover { background:transparent; }
|
||||
.nodedc-scene-annotation.nodedc-button { min-width:0; padding:var(--nodedc-space-1); background:transparent; text-shadow:0 1px 4px rgb(0 0 0 / .85); }
|
||||
.nodedc-scene-annotation .nodedc-button__content { display:grid; gap:0; text-align:center; font-variant-numeric:tabular-nums; }
|
||||
.nodedc-scene-annotation:hover, .nodedc-scene-annotation[aria-pressed="true"] { background:var(--nodedc-glass-control-hover); }
|
||||
.nodedc-scene-annotation[aria-pressed="true"] { box-shadow:var(--nodedc-glass-control-shadow); }
|
||||
|
||||
.nodedc-scene-annotation.nodedc-button[hidden] { display:none; }
|
||||
|
||||
/* A measured resource capsule; its containing row never owns a surface. */
|
||||
.nodedc-level-button.nodedc-button{min-width:calc(var(--nodedc-control-height) * 2.5);font-variant-numeric:tabular-nums;--nodedc-level-color:var(--nodedc-text-secondary)}
|
||||
.nodedc-level-button[data-level-tone="success"]{--nodedc-level-color:rgb(var(--nodedc-success-rgb))}
|
||||
.nodedc-level-button[data-level-tone="warning"]{--nodedc-level-color:rgb(var(--nodedc-warning-rgb))}
|
||||
.nodedc-level-button[data-level-tone="danger"]{--nodedc-level-color:rgb(var(--nodedc-danger-rgb))}
|
||||
.nodedc-level-button[data-freshness="stale"],.nodedc-level-button[data-freshness="unknown"]{--nodedc-level-color:var(--nodedc-text-secondary)}
|
||||
.nodedc-level-button.nodedc-button,.nodedc-level-button.nodedc-button:hover{background-image:linear-gradient(90deg,color-mix(in srgb,var(--nodedc-level-color) 26%,transparent) var(--nodedc-level-percent),transparent var(--nodedc-level-percent))}
|
||||
|
||||
.nodedc-level-button[data-custom-fill].nodedc-button{position:relative;overflow:hidden;background-image:none}
|
||||
.nodedc-level-button__fill{position:absolute;inset:0;display:grid;place-items:center;pointer-events:none;background:var(--nodedc-level-custom);color:var(--nodedc-level-ink);clip-path:inset(0 calc(100% - var(--nodedc-level-percent)) 0 0)}
|
||||
|
||||
|
||||
.nodedc-tooltip-anchor { display: inline-flex; min-width: 0; }
|
||||
.nodedc-tooltip-anchor[tabindex] { border-radius: var(--nodedc-radius-control-compact); }
|
||||
.nodedc-tooltip-anchor[tabindex]:focus-visible { outline: 2px solid var(--nodedc-text-primary); outline-offset: 3px; }
|
||||
.nodedc-tooltip {
|
||||
position: fixed; z-index: var(--nodedc-layer-popover); box-sizing: border-box;
|
||||
width: max-content; max-width: min(280px, calc(100vw - 16px)); overflow: auto;
|
||||
padding: var(--nodedc-space-3) var(--nodedc-space-4);
|
||||
border-radius: var(--nodedc-radius-control-compact);
|
||||
border: 0; outline: 0;
|
||||
background: rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
|
||||
backdrop-filter: blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation));
|
||||
-webkit-backdrop-filter: blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)); color: var(--nodedc-text-primary);
|
||||
box-shadow: none; font-family: var(--nodedc-font-family);
|
||||
font-size: var(--nodedc-font-size-sm); font-weight: var(--nodedc-font-weight-regular); line-height: 1.4;
|
||||
animation: nodedc-tooltip-in var(--nodedc-duration-fast) var(--nodedc-ease-standard);
|
||||
}
|
||||
@keyframes nodedc-tooltip-in { from { opacity: 0; } to { opacity: 1; } }
|
||||
@media (prefers-reduced-motion: reduce) { .nodedc-tooltip { animation: none; } }
|
||||
|
||||
/* Opt-in flat material. Applies at the document root, including portal layers.
|
||||
Focus remains visible through a high-contrast fill instead of a contour. */
|
||||
[data-nodedc-edges="flat"] {
|
||||
--nodedc-glass-outline: transparent;
|
||||
--nodedc-glass-control-shadow: none;
|
||||
--nodedc-panel-action-border: transparent;
|
||||
--nodedc-panel-action-border-hover: transparent;
|
||||
--nodedc-panel-action-shadow: none;
|
||||
}
|
||||
[data-nodedc-edges="flat"] .nodedc-material-rim::after,
|
||||
[data-nodedc-edges="flat"] .nodedc-glass-material::before { display: none; }
|
||||
[data-nodedc-edges="flat"] :is(.nodedc-admin-panel__nav-item, .nodedc-application-panel__action, .nodedc-admin-panel__close, .nodedc-media-source-button, .nodedc-media-preview, .nodedc-color-field__swatch) {
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
[data-nodedc-edges="flat"] :is(button, input, textarea, [tabindex]):focus-visible {
|
||||
outline: 0;
|
||||
box-shadow: none;
|
||||
background-color: var(--nodedc-text-primary);
|
||||
color: var(--nodedc-canvas);
|
||||
}
|
||||
[data-nodedc-edges="flat"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon {
|
||||
background: var(--nodedc-canvas);
|
||||
color: var(--nodedc-text-primary);
|
||||
}
|
||||
|
||||
.nodedc-select[data-shape="pill"] :is(.nodedc-select__value,.nodedc-select__toggle) { border-radius: var(--nodedc-radius-circle); }
|
||||
|
||||
/* Owner canon 2026-11-14: all viewport-backed UI shares scene Glass V4.
|
||||
Geometry, disabled opacity, pressed selection and keyboard focus are retained.
|
||||
The DOM surface class is for existing semantic overlays, never the renderer. */
|
||||
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar__button:not([data-active="true"]),
|
||||
.nodedc-viewport-surface[data-glass-context="scene"],
|
||||
.nodedc-dropdown-surface.nodedc-viewport-surface,
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-icon-button:not([aria-pressed="true"]), .nodedc-button:is([data-variant="secondary"], [data-variant="ghost"]):not([aria-pressed="true"]), .nodedc-select__toggle, .nodedc-segmented, .nodedc-workspace-window__action:not([aria-pressed="true"])) {
|
||||
background: rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
|
||||
color: var(--nodedc-text-primary);
|
||||
backdrop-filter: blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
-webkit-backdrop-filter: blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
}
|
||||
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar__button:hover:not(:disabled):not([data-active="true"]),
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-icon-button, .nodedc-button:is([data-variant="secondary"], [data-variant="ghost"]), .nodedc-workspace-window__action):hover:not(:disabled):not([aria-pressed="true"]) {
|
||||
background: color-mix(in srgb, var(--nodedc-text-primary) 12%, rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity)));
|
||||
}
|
||||
|
||||
.nodedc-tree__actions {display:flex;flex:none;align-items:center;}
|
||||
.nodedc-tree__actions .nodedc-icon-button {flex:0 0 24px;width:24px;height:24px;min-width:24px;padding:0;}
|
||||
|
||||
/* A backdrop root on the transparent rail would prevent button glass sampling the scene. */
|
||||
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar {will-change:transform;}
|
||||
|
||||
/* Floating inspectors may be narrower than the browser; respond to their own width. */
|
||||
@container nodedc-inspector (max-width: 329px) {
|
||||
.nodedc-control-row { grid-template-columns: minmax(0, 1fr); gap: var(--nodedc-space-2); }
|
||||
}
|
||||
.nodedc-editor-dock__tool.nodedc-glass-material { overflow: clip; }
|
||||
|
||||
/* Same thin scale as the vertical section rail, with one horizontal boundary. */
|
||||
.nodedc-range-rail { display: flex; flex-direction: column; gap: var(--nodedc-space-2); width: 100%; padding-block: var(--nodedc-space-2); }
|
||||
.nodedc-range-rail__value { text-align: center; color: var(--nodedc-text-primary); font-size: var(--nodedc-font-size-md); line-height: var(--nodedc-line-height-normal); font-weight: var(--nodedc-font-weight-medium); font-variant-numeric: tabular-nums; pointer-events: none; }
|
||||
.nodedc-range[data-variant="rail"] { height: calc(var(--nodedc-control-height) * 0.2); overflow: visible; border: 0; outline: 0; box-shadow: none; }
|
||||
.nodedc-range[data-variant="rail"] input[type="range"] { top: 50%; height: max(100%, 24px); transform: translateY(-50%); }
|
||||
.nodedc-range-rail:has(input:focus-visible) .nodedc-range-rail__value { text-decoration: underline; text-underline-offset: 2px; }
|
||||
.nodedc-range-rail[data-disabled] { opacity: var(--nodedc-disabled-opacity, 0.5); }
|
||||
|
||||
/* Shared move handles: no browser perimeter or pointer-inherited focus flash.
|
||||
Keyboard navigation retains the canonical focus surface in every window. */
|
||||
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex] {
|
||||
outline: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex]:focus-visible {
|
||||
outline: 0;
|
||||
box-shadow: none;
|
||||
background: var(--nodedc-focus-surface);
|
||||
}
|
||||
[data-nodedc-edges="flat"] :is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex]:focus-visible {
|
||||
background: var(--nodedc-text-primary);
|
||||
color: var(--nodedc-canvas);
|
||||
}
|
||||
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex]:focus-visible :is(.nodedc-window__title, .nodedc-window__subtitle, .nodedc-workspace-window__title, .nodedc-workspace-window__subtitle) {
|
||||
color: inherit;
|
||||
}
|
||||
[data-nodedc-edges] :is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex][data-pointer-focus="true"],
|
||||
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex][data-pointer-focus="true"] {
|
||||
outline: 0;
|
||||
box-shadow: none;
|
||||
background: transparent;
|
||||
color: var(--nodedc-text-primary);
|
||||
}
|
||||
|
||||
/* Directly editable detail copy: no permanent field plate. */
|
||||
.nodedc-field--unlabelled > .nodedc-field__label-row {display:none;}
|
||||
.nodedc-field--plain {gap:0;}
|
||||
.nodedc-field--plain .nodedc-field__control {
|
||||
min-height:0; padding:0; border-radius:var(--nodedc-radius-control-compact);
|
||||
background:transparent; box-shadow:none; color:inherit; font:inherit; line-height:inherit;
|
||||
}
|
||||
.nodedc-field--plain .nodedc-field__control:focus-visible {background:var(--nodedc-focus-surface);}
|
||||
.nodedc-field--plain textarea.nodedc-field__control {resize:none;overflow:hidden;}
|
||||
.nodedc-drag-handle[data-surface="control"] {background:var(--nodedc-glass-control-bg);color:var(--nodedc-text-primary);}
|
||||
:is(.nodedc-viewport-controls,.nodedc-scene-controls) .nodedc-drag-handle[data-surface="control"] {
|
||||
background:rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
|
||||
backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation));
|
||||
-webkit-backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation));
|
||||
}
|
||||
.nodedc-drag-handle[data-surface="control"]:hover {background:var(--nodedc-glass-control-hover);}
|
||||
|
||||
/* An adaptive action row defines the minimum resizable width. */
|
||||
.nodedc-window[data-header-layout="adaptive"]>.nodedc-window__head>.nodedc-window__actions{flex-wrap:nowrap;width:max-content;max-width:100%;justify-self:end;overflow-x:auto}
|
||||
.nodedc-window[data-header-stacked="true"]>.nodedc-window__head{grid-template-columns:minmax(0,1fr)}
|
||||
.nodedc-window[data-header-stacked="true"]>.nodedc-window__head>.nodedc-window__actions{grid-row:1}
|
||||
.nodedc-window[data-header-stacked="true"]>.nodedc-window__head>.nodedc-window__titles{grid-row:2}
|
||||
|
||||
.nodedc-window[data-header-layout="adaptive"]>.nodedc-window__head>.nodedc-window__actions>*{flex-shrink:0}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.nodedc-app-shell__end-panel { transition: none; }
|
||||
}
|
||||
|
||||
@@ -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.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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.10",
|
||||
"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.4",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode } from "react";
|
||||
import type { ButtonHTMLAttributes, ReactNode, Ref } from "react";
|
||||
|
||||
export interface AppHeaderProps {
|
||||
brand: ReactNode;
|
||||
@@ -74,10 +74,11 @@ export function HeaderNavigation<T extends string>({ label, value, items, onChan
|
||||
|
||||
export interface HeaderProfileProps {
|
||||
children: ReactNode;
|
||||
ref?: Ref<HTMLDivElement>;
|
||||
}
|
||||
|
||||
export function HeaderProfile({ children }: HeaderProfileProps) {
|
||||
return <div className="nodedc-header__profile">{children}</div>;
|
||||
export function HeaderProfile({ children, ref }: HeaderProfileProps) {
|
||||
return <div ref={ref} className="nodedc-header__profile">{children}</div>;
|
||||
}
|
||||
|
||||
export interface HeaderProfileButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className" | "style"> {}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import {createContext, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
|
||||
const FullscreenContext = createContext<{fullscreen:boolean; setFullscreen:(value:boolean)=>void} | null>(null);
|
||||
/** Shared full-window presentation. Portaled inspectors remain above the panel. */
|
||||
export const useApplicationPanelFullscreen = () => useContext(FullscreenContext);
|
||||
export function ApplicationPanelFullscreen({children}: {children:ReactNode}) {
|
||||
const [fullscreen,setFullscreen] = useState(false);
|
||||
const [mount] = useState(() => typeof document === "undefined" ? null : document.createElement("div"));
|
||||
const anchor = useRef<HTMLDivElement>(null);
|
||||
const value = useMemo(() => ({fullscreen,setFullscreen}), [fullscreen]);
|
||||
useLayoutEffect(() => {
|
||||
if (!mount || !anchor.current) return;
|
||||
anchor.current.append(mount);
|
||||
return () => mount.remove();
|
||||
}, [mount]);
|
||||
useLayoutEffect(() => {
|
||||
if (!mount || !anchor.current) return;
|
||||
const target = (fullscreen ? document.body : anchor.current) as HTMLElement & {moveBefore?:(node:Node, before:Node|null)=>void};
|
||||
if (mount.parentElement !== target) {
|
||||
if (target.moveBefore) target.moveBefore(mount, null); else target.append(mount);
|
||||
}
|
||||
}, [fullscreen,mount]);
|
||||
const content = <FullscreenContext.Provider value={value}><div className="nodedc-panel-viewport nodedc-ui-root" data-fullscreen={fullscreen || undefined}>{children}</div></FullscreenContext.Provider>;
|
||||
return mount ? <><div ref={anchor} className="nodedc-panel-viewport-anchor"/>{createPortal(content,mount)}</> : content;
|
||||
}
|
||||
@@ -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;
|
||||
@@ -76,6 +95,7 @@ export function ApplicationPanel({
|
||||
title,
|
||||
description,
|
||||
expanded = false,
|
||||
allowFullscreen = false,
|
||||
expandLabel = "Развернуть окно",
|
||||
closeLabel = "Закрыть окно",
|
||||
onExpandedChange,
|
||||
@@ -86,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">
|
||||
@@ -131,4 +151,5 @@ export function ApplicationPanel({
|
||||
<div className="nodedc-application-panel__body">{children}</div>
|
||||
</section>
|
||||
);
|
||||
return allowFullscreen ? <ApplicationPanelFullscreen>{panel}</ApplicationPanelFullscreen> : panel;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface ApplicationSidePanelProps extends Omit<HTMLAttributes<HTMLEleme
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
closeLabel?: string;
|
||||
headerActions?: ReactNode;
|
||||
footer?: ReactNode;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
@@ -23,6 +24,7 @@ export function ApplicationSidePanel({
|
||||
title,
|
||||
description,
|
||||
closeLabel = "Закрыть панель",
|
||||
headerActions,
|
||||
footer,
|
||||
onClose,
|
||||
children,
|
||||
@@ -42,6 +44,7 @@ export function ApplicationSidePanel({
|
||||
{description ? <span className="nodedc-application-side-panel__description">{description}</span> : null}
|
||||
</div>
|
||||
<div className="nodedc-admin-panel__head-actions">
|
||||
{headerActions}
|
||||
<button type="button" className="nodedc-admin-panel__close" aria-label={closeLabel} onClick={onClose}>
|
||||
<Icon name="close" size={16} strokeWidth={1.6} />
|
||||
</button>
|
||||
|
||||
@@ -65,12 +65,16 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
|
||||
export interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
label: string;
|
||||
shape?: "circle" | "rounded";
|
||||
/** Glyph-only action; keeps the normal hit target and keyboard focus. */
|
||||
surface?: "default" | "none";
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton({
|
||||
label,
|
||||
shape = "circle",
|
||||
surface = "default",
|
||||
style,
|
||||
className,
|
||||
children,
|
||||
type = "button",
|
||||
@@ -84,6 +88,7 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
type={type}
|
||||
className={cn("nodedc-icon-button", className)}
|
||||
data-shape={shape === "circle" ? undefined : shape}
|
||||
style={surface === "none" ? { ...style, background: "transparent", boxShadow: "none", color: "var(--nodedc-text-primary)" } : style}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
{...props}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {DndContext, PointerSensor, useDraggable, useSensor, useSensors, type Dra
|
||||
import {DragHandle} from "./DragDrop.js";
|
||||
import {SplitPane} from "./SplitPane.js";
|
||||
import {cn} from "./cn.js";
|
||||
import {dockIds, dockPosition, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
|
||||
import {dockIds, dockMoveAtPoint, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
|
||||
|
||||
const DockContext = createContext<{disabled: boolean; onKey: (id: string, event: KeyboardEvent<HTMLDivElement>) => void}>({disabled: true, onKey: () => {}});
|
||||
/** The shared six-dot grip supports pointer dragging and keyboard docking. */
|
||||
@@ -27,7 +27,7 @@ export interface DockLayoutProps {
|
||||
|
||||
/** Media stay in stable sibling hosts; only geometry changes, including focus. */
|
||||
export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId, className, children}: DockLayoutProps) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const host = useRef<HTMLDivElement>(null), viewport = useRef<HTMLDivElement>(null);
|
||||
// React must not reorder these DOM siblings: moving an iframe node reloads
|
||||
// its browsing context even when its key and portal content are unchanged.
|
||||
const hostOrder = useRef<string[]>([]);
|
||||
@@ -57,14 +57,19 @@ export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId,
|
||||
const locate = (event: DragMoveEvent): DockMove | null => {
|
||||
const start = event.activatorEvent as PointerEvent, box = host.current!.getBoundingClientRect();
|
||||
const x = start.clientX + event.delta.x - box.left, y = start.clientY + event.delta.y - box.top;
|
||||
for (const [id, rect] of Object.entries(rects)) {
|
||||
const position = dockPosition(rect, x, y);
|
||||
if (position && id !== String(event.active.id)) return {activeId: String(event.active.id), overId: id, position};
|
||||
}
|
||||
return null;
|
||||
const view = viewport.current!, screen = view.getBoundingClientRect();
|
||||
const visible = {left: screen.left + view.clientLeft - box.left, top: screen.top + view.clientTop - box.top,
|
||||
width: view.clientWidth, height: view.clientHeight};
|
||||
return dockMoveAtPoint(visible, rects, String(event.active.id), x, y);
|
||||
};
|
||||
// Preview and commit use the same content limits, including a newly enlarged canvas.
|
||||
const projectMove = (move: DockMove | null) => {
|
||||
const next = move && moveDockPanel(constrained, move), required = dockMinimum(next, minimums);
|
||||
const area = {...bounds, width: Math.max(bounds.width, required.width), height: Math.max(bounds.height, required.height)};
|
||||
return {tree: constrainDockTree(next, area, minimums), area};
|
||||
};
|
||||
const commit = (move: DockMove | null) => {
|
||||
const next = move && moveDockPanel(constrained, move);
|
||||
const next = projectMove(move).tree;
|
||||
if (next) onTreeChange(next);
|
||||
reset();
|
||||
};
|
||||
@@ -80,29 +85,31 @@ export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId,
|
||||
const candidates = dockIds(visibleTree).filter(value => value !== active), index = candidates.indexOf(target?.overId ?? "");
|
||||
setTarget({activeId: active!, overId: candidates[(index + (event.shiftKey ? -1 : 1) + candidates.length) % candidates.length], position: target?.position ?? "center"});
|
||||
} else {
|
||||
const position = ({ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const)[event.key as "ArrowLeft"];
|
||||
const positions = {ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const;
|
||||
const position = positions[event.key as keyof typeof positions];
|
||||
if (!position || !target) return;
|
||||
setTarget({...target, position});
|
||||
setTarget({...target, position, scope: event.shiftKey && position !== "center" ? "workspace" : "panel"});
|
||||
}
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
};
|
||||
const preview = target ? dockRects(moveDockPanel(constrained, target), canvas)[target.activeId] : null;
|
||||
const projected = projectMove(target);
|
||||
const preview = target ? dockRects(projected.tree, projected.area)[target.activeId] : null;
|
||||
const action = target ? ({center: "Поменять местами", left: "Слева", right: "Справа", top: "Сверху", bottom: "Снизу"})[target.position] : "Выберите окно и край";
|
||||
const label = target ? panels.find(panel => panel.id === target.overId)?.label : "";
|
||||
const label = target?.scope === "workspace" ? "Вся область" : target ? panels.find(panel => panel.id === target.overId)?.label : "";
|
||||
return <DndContext sensors={sensors} autoScroll={false}
|
||||
onDragStart={event => {setActive(String(event.active.id)); setKeyboard(false);}}
|
||||
onDragMove={event => setTarget(locate(event))}
|
||||
onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
|
||||
<DockContext.Provider value={{disabled, onKey}}>
|
||||
<div className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
|
||||
<div ref={viewport} className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
|
||||
<div ref={host} className="nodedc-dock-layout__canvas" style={{minWidth:minimum.width, minHeight:minimum.height}}>
|
||||
<DockSlots tree={constrained} bounds={canvas} minimums={minimums} onResize={(path, ratio) => {if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/>
|
||||
{hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel => <div key={panel.id} className="nodedc-dock-layout__panel" data-dock-id={panel.id}
|
||||
data-dock-source={active === panel.id ? "true" : undefined} style={rects[panel.id] ?? {display: "none"}}>{renderPanel(panel.id)}</div>)}
|
||||
{active ? <div className="nodedc-dock-layout__overlay" aria-hidden="true">
|
||||
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} style={preview}><span>{action} · {label}</span></div> : null}
|
||||
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} data-dock-scope={target!.scope ?? "panel"} style={preview}><span>{action} · {label}</span></div> : null}
|
||||
</div> : null}
|
||||
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
|
||||
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край окна, Shift+стрелки — край всей области, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
|
||||
@@ -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,
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
arrayMove,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
rectSortingStrategy,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import { cn } from "./cn.js";
|
||||
@@ -36,6 +39,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 ? ({
|
||||
@@ -47,8 +52,9 @@ const copyRect = (rect: DragRect | null | undefined): DragRect | undefined => re
|
||||
height: rect.height,
|
||||
}) : undefined;
|
||||
|
||||
export function DragHandle({ label = "Перетащить", listeners, attributes, className }: {
|
||||
export function DragHandle({ label = "Перетащить", listeners, attributes, className, surface="none" }: {
|
||||
label?: string;
|
||||
surface?: "none" | "control";
|
||||
listeners?: ReturnType<typeof useDraggable>["listeners"];
|
||||
attributes?: ReturnType<typeof useDraggable>["attributes"];
|
||||
className?: string;
|
||||
@@ -57,6 +63,7 @@ export function DragHandle({ label = "Перетащить", listeners, attribut
|
||||
<button
|
||||
type="button"
|
||||
className={cn("nodedc-drag-handle", className)}
|
||||
data-surface={surface}
|
||||
aria-label={label}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
@@ -70,9 +77,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 +93,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>
|
||||
);
|
||||
}
|
||||
@@ -108,31 +123,36 @@ export function DropZone({ id, data, className, children }: { id: string; data?:
|
||||
return <div ref={setNodeRef} className={cn(className, isOver && "is-drag-over")}>{children}</div>;
|
||||
}
|
||||
|
||||
export function SortableScope({ ids, children }: { ids: string[]; children: ReactNode }) {
|
||||
return <SortableContext items={ids} strategy={verticalListSortingStrategy}>{children}</SortableContext>;
|
||||
const SortableLayoutContext=createContext<"list"|"grid">("list");
|
||||
export function SortableScope({ ids, children, layout="list" }: { ids: string[]; children: ReactNode; layout?:"list"|"grid" }) {
|
||||
return <SortableLayoutContext.Provider value={layout}><SortableContext items={ids} strategy={layout==="grid"?rectSortingStrategy:verticalListSortingStrategy}>{children}</SortableContext></SortableLayoutContext.Provider>;
|
||||
}
|
||||
|
||||
export function SortableItem({ id, data, className, children }: {
|
||||
export function SortableItem({ id, data, className, children, handleSurface="none" }: {
|
||||
id: string;
|
||||
handleSurface?: "none" | "control";
|
||||
data?: NodedcDragData;
|
||||
className?: string;
|
||||
children: (state: { handle: ReactNode; isDragging: boolean }) => ReactNode;
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, data });
|
||||
const verticalTransform = transform ? { ...transform, x: 0 } : null;
|
||||
const layout=useContext(SortableLayoutContext);
|
||||
const verticalTransform = transform && layout!=="grid" ? { ...transform, x: 0 } : transform;
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
className={cn(className, isDragging && "is-dragging")}
|
||||
style={{ transform: CSS.Transform.toString(verticalTransform), transition, opacity: isDragging ? 0.65 : undefined }}
|
||||
>
|
||||
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging })}
|
||||
{children({ handle: <DragHandle surface={handleSurface} listeners={listeners} attributes={attributes} />, isDragging })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SortableList<T>({ items, getId, className, onReorder, children }: {
|
||||
export function SortableList<T>({ items, getId, className, onReorder, children, layout="list", handleSurface="none" }: {
|
||||
items: T[];
|
||||
handleSurface?: "none" | "control";
|
||||
layout?: "list" | "grid";
|
||||
getId: (item: T) => string;
|
||||
className?: string;
|
||||
onReorder: (items: T[]) => void;
|
||||
@@ -146,10 +166,10 @@ export function SortableList<T>({ items, getId, className, onReorder, children }
|
||||
const to = ids.indexOf(overId);
|
||||
if (from >= 0 && to >= 0) onReorder(arrayMove(items, from, to));
|
||||
}}>
|
||||
<SortableScope ids={ids}>
|
||||
<SortableScope ids={ids} layout={layout}>
|
||||
<div className={className}>
|
||||
{items.map((item) => (
|
||||
<SortableItem key={getId(item)} id={getId(item)}>
|
||||
<SortableItem key={getId(item)} id={getId(item)} handleSurface={handleSurface}>
|
||||
{(state) => children(item, state)}
|
||||
</SortableItem>
|
||||
))}
|
||||
|
||||
@@ -126,6 +126,13 @@ export function Dropdown({
|
||||
updatePosition();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !surfaceRef.current) return;
|
||||
const observer = new ResizeObserver(updatePosition);
|
||||
observer.observe(surfaceRef.current);
|
||||
return () => observer.disconnect();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !getAnchorRect) return;
|
||||
let frame:number;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import {dragHandleFocus} from './dragHandleFocus.js';
|
||||
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 {...dragHandleFocus} 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>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Button,
|
||||
FeatureSettingsWindow,
|
||||
@@ -18,9 +18,12 @@ import {
|
||||
type EnvironmentSurface,
|
||||
type UploadedEnvironmentMedia,
|
||||
} from "@nodedc/ui-core";
|
||||
import type { FeatureSettingsSection } from "./FeatureSettingsWindow.js";
|
||||
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor.js";
|
||||
|
||||
export interface EnvironmentSettingsWindowProps {
|
||||
/** Product-owned sections reuse this shell; each owns its content and save lifecycle. */
|
||||
additionalSections?: readonly (FeatureSettingsSection & { content: ReactNode; footer?: ReactNode })[];
|
||||
productName: string;
|
||||
surfaces: readonly EnvironmentSurface[];
|
||||
initialSurfaceId?: string;
|
||||
@@ -70,6 +73,7 @@ function patchBackground(
|
||||
|
||||
export function EnvironmentSettingsWindow({
|
||||
productName,
|
||||
additionalSections = [],
|
||||
surfaces,
|
||||
initialSurfaceId,
|
||||
open,
|
||||
@@ -80,6 +84,8 @@ export function EnvironmentSettingsWindow({
|
||||
onSave,
|
||||
onUpload,
|
||||
}: EnvironmentSettingsWindowProps) {
|
||||
const [activeSection, setActiveSection] = useState("environment");
|
||||
const extension = additionalSections.find(section => section.id === activeSection);
|
||||
const [draft, setDraft] = useState(() => cloneEnvironmentSettings(settings));
|
||||
const [surfaceId, setSurfaceId] = useState(initialSurfaceId ?? surfaces[0]?.id ?? "home");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
@@ -196,11 +202,12 @@ export function EnvironmentSettingsWindow({
|
||||
group: productName.toUpperCase(),
|
||||
icon: "settings",
|
||||
},
|
||||
...additionalSections,
|
||||
]}
|
||||
activeSection="environment"
|
||||
onSectionChange={() => undefined}
|
||||
activeSection={extension ? activeSection : "environment"}
|
||||
onSectionChange={setActiveSection}
|
||||
onClose={onClose}
|
||||
footer={(
|
||||
footer={extension ? extension.footer : (
|
||||
<WindowFooterActions>
|
||||
<Button
|
||||
variant="secondary"
|
||||
@@ -223,7 +230,7 @@ export function EnvironmentSettingsWindow({
|
||||
</WindowFooterActions>
|
||||
)}
|
||||
>
|
||||
<div className="nodedc-environment-settings">
|
||||
{extension ? extension.content : <div className="nodedc-environment-settings">
|
||||
<SettingsCard
|
||||
eyebrow="ОКРУЖЕНИЕ"
|
||||
title="Основные элементы управления"
|
||||
@@ -349,7 +356,7 @@ export function EnvironmentSettingsWindow({
|
||||
/>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</div>
|
||||
</div>}
|
||||
</FeatureSettingsWindow>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useId, type InputHTMLAttributes, type ReactNode, type TextareaHTMLAttributes } from "react";
|
||||
import { useId, useLayoutEffect, useRef, type InputHTMLAttributes, type ReactNode, type TextareaHTMLAttributes } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface FieldFrameProps {
|
||||
@@ -29,6 +29,8 @@ export interface TextFieldProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||
hint?: string;
|
||||
description?: string;
|
||||
fieldClassName?: string;
|
||||
/** Plain text appearance for directly editable detail content. Keep an accessible name. */
|
||||
appearance?: "default" | "plain";
|
||||
}
|
||||
|
||||
export function TextField({
|
||||
@@ -36,6 +38,7 @@ export function TextField({
|
||||
hint,
|
||||
description,
|
||||
fieldClassName,
|
||||
appearance = "default",
|
||||
className,
|
||||
id,
|
||||
...props
|
||||
@@ -43,7 +46,7 @@ export function TextField({
|
||||
const generatedId = useId();
|
||||
const controlId = id ?? generatedId;
|
||||
return (
|
||||
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={fieldClassName}>
|
||||
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={cn(fieldClassName, appearance === "plain" && "nodedc-field--plain", !label && "nodedc-field--unlabelled")}>
|
||||
<input id={controlId} className={cn("nodedc-field__control", className)} {...props} />
|
||||
</FieldFrame>
|
||||
);
|
||||
@@ -54,6 +57,8 @@ export interface TextAreaFieldProps extends TextareaHTMLAttributes<HTMLTextAreaE
|
||||
hint?: string;
|
||||
description?: string;
|
||||
fieldClassName?: string;
|
||||
/** Plain text appearance for directly editable detail content. Keep an accessible name. */
|
||||
appearance?: "default" | "plain";
|
||||
}
|
||||
|
||||
export function TextAreaField({
|
||||
@@ -61,15 +66,29 @@ export function TextAreaField({
|
||||
hint,
|
||||
description,
|
||||
fieldClassName,
|
||||
appearance = "default",
|
||||
className,
|
||||
id,
|
||||
...props
|
||||
}: TextAreaFieldProps) {
|
||||
const generatedId = useId();
|
||||
const controlId = id ?? generatedId;
|
||||
const area = useRef<HTMLTextAreaElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const el = area.current;
|
||||
if (!el || appearance !== "plain") return;
|
||||
const resize = () => { el.style.height = "auto"; el.style.height = el.scrollHeight + "px"; };
|
||||
resize();
|
||||
let width = el.clientWidth;
|
||||
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
|
||||
if (el.clientWidth !== width) { width = el.clientWidth; resize(); }
|
||||
});
|
||||
observer?.observe(el);
|
||||
return () => observer?.disconnect();
|
||||
}, [appearance, props.value]);
|
||||
return (
|
||||
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={fieldClassName}>
|
||||
<textarea id={controlId} className={cn("nodedc-field__control", className)} {...props} />
|
||||
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={cn(fieldClassName, appearance === "plain" && "nodedc-field--plain", !label && "nodedc-field--unlabelled")}>
|
||||
<textarea ref={area} id={controlId} className={cn("nodedc-field__control", className)} {...props} />
|
||||
</FieldFrame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { createGlassMaterialVariables, type GlassMaterialSettings } from "@nodedc/ui-core";
|
||||
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export type GlassTone = "default" | "strong" | "soft";
|
||||
export type GlassTone = "default" | "strong" | "soft" | "group";
|
||||
export type GlassRadius = "card" | "panel" | "modal" | "pill";
|
||||
export type GlassPadding = "none" | "sm" | "md" | "lg";
|
||||
|
||||
@@ -37,11 +38,17 @@ export function GlassSurface({
|
||||
|
||||
export interface GlassMaterialSurfaceProps extends HTMLAttributes<HTMLDivElement> {
|
||||
children: ReactNode;
|
||||
/** Scene telemetry uses the translucent V4 material, independent of modal density. */
|
||||
context?: "floating" | "scene";
|
||||
radius?: GlassRadius;
|
||||
/** Per-instance appearance; never changes the global theme or other surfaces. */
|
||||
material?: GlassMaterialSettings;
|
||||
radiusPx?: number;
|
||||
}
|
||||
|
||||
/** Canonical modal/Inspector material. General application panels must not use it. */
|
||||
export function GlassMaterialSurface({ children, className, ...props }: GlassMaterialSurfaceProps) {
|
||||
return <div className={cn("nodedc-glass-material", className)} {...props}>{children}</div>;
|
||||
/** Canonical floating/scene-overlay material. Ordinary application panels stay matte. */
|
||||
export function GlassMaterialSurface({ children, className, context = "floating", radius = "modal", material, radiusPx, style, ...props }: GlassMaterialSurfaceProps) {
|
||||
return <div className={cn("nodedc-glass-material", className)} data-glass-context={context} data-radius={radius} style={{ ...material && createGlassMaterialVariables(material, context), ...Number.isFinite(radiusPx) && {borderRadius: Math.max(0, Math.min(120, radiusPx!))}, ...style } as CSSProperties} {...props}>{children}</div>;
|
||||
}
|
||||
|
||||
export interface MapGlassSurfaceProps extends HTMLAttributes<HTMLDivElement> {
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import {
|
||||
MousePointer2,
|
||||
Pipette,
|
||||
createLucideIcon,
|
||||
Glasses,
|
||||
Cuboid,
|
||||
Move,
|
||||
CirclePlus,
|
||||
Box,
|
||||
Scan,
|
||||
@@ -38,6 +43,7 @@ import {
|
||||
ListChecks,
|
||||
LocateFixed,
|
||||
LockKeyhole,
|
||||
LockKeyholeOpen,
|
||||
MailPlus,
|
||||
Map,
|
||||
Maximize2,
|
||||
@@ -46,7 +52,10 @@ import {
|
||||
PanelTop,
|
||||
Pencil,
|
||||
Play,
|
||||
Pin,
|
||||
Power,
|
||||
Plus,
|
||||
Minus,
|
||||
RefreshCw,
|
||||
RotateCw,
|
||||
Save,
|
||||
@@ -55,6 +64,7 @@ import {
|
||||
ShieldCheck,
|
||||
SlidersHorizontal,
|
||||
Square,
|
||||
Star,
|
||||
Terminal,
|
||||
Trash2,
|
||||
UploadCloud,
|
||||
@@ -66,11 +76,28 @@ import {
|
||||
type LucideProps,
|
||||
} from "lucide-react";
|
||||
|
||||
// CAD vocabulary: dimension line, cutting plane and unframed information glyph.
|
||||
const DimensionLine = createLucideIcon('DimensionLine', [
|
||||
['path', {d:'M4 5v14M20 5v14M4 12h16M8 9l-4 3 4 3M16 9l4 3-4 3',key:'dimension'}],
|
||||
]);
|
||||
const SectionPlane = createLucideIcon('SectionPlane', [
|
||||
['path', {d:'m5 7 7-4 7 4v10l-7 4-7-4V7m0 0 7 4 7-4M12 11v10',key:'model'}],
|
||||
['path', {d:'m2 12 10-5 10 5-10 5-10-5Z',key:'plane'}],
|
||||
]);
|
||||
const InformationPlain = createLucideIcon('InformationPlain', [
|
||||
['path', {d:'M12 4h.01M10 9h2v11M9 20h6',key:'information'}],
|
||||
]);
|
||||
const icons = {
|
||||
pipette: Pipette,
|
||||
"add-point": CirclePlus,
|
||||
perspective: Box,
|
||||
orthographic: Scan,
|
||||
ruler: DimensionLine,
|
||||
section: SectionPlane,
|
||||
isolate: Glasses,
|
||||
perspective: Cuboid,
|
||||
orthographic: Box,
|
||||
"fit-view": Scan,
|
||||
select: MousePointer2,
|
||||
move: Move,
|
||||
pen: PenTool,
|
||||
rectangle: RectangleHorizontal,
|
||||
curve: Spline,
|
||||
@@ -91,6 +118,7 @@ const icons = {
|
||||
close: X,
|
||||
copy: Copy,
|
||||
database: Database,
|
||||
pin: Pin,
|
||||
download: Download,
|
||||
edit: Pencil,
|
||||
eye: Eye,
|
||||
@@ -104,18 +132,22 @@ const icons = {
|
||||
image: Image,
|
||||
inbox: Inbox,
|
||||
info: Info,
|
||||
"info-plain": InformationPlain,
|
||||
key: KeyRound,
|
||||
layers: Layers,
|
||||
list: ListChecks,
|
||||
target: LocateFixed,
|
||||
lock: LockKeyhole,
|
||||
unlock: LockKeyholeOpen,
|
||||
mail: MailPlus,
|
||||
minimize: Minimize2,
|
||||
network: Network,
|
||||
panel: PanelTop,
|
||||
plan: Map,
|
||||
play: Play,
|
||||
power: Power,
|
||||
plus: Plus,
|
||||
minus: Minus,
|
||||
profile: UserCircle,
|
||||
refresh: RefreshCw,
|
||||
"rotate-clockwise": RotateCw,
|
||||
@@ -125,6 +157,7 @@ const icons = {
|
||||
shield: ShieldCheck,
|
||||
sliders: SlidersHorizontal,
|
||||
stop: Square,
|
||||
star: Star,
|
||||
terminal: Terminal,
|
||||
trash: Trash2,
|
||||
upload: UploadCloud,
|
||||
|
||||
@@ -19,6 +19,9 @@ export interface InspectorSectionSpec {
|
||||
|
||||
export interface InspectorProps {
|
||||
sections: InspectorSectionSpec[];
|
||||
/** Spaced form fields above sections and centered actions below them. */
|
||||
header?: ReactNode;
|
||||
footer?: ReactNode;
|
||||
defaultOpen?: string[];
|
||||
openSections?: string[];
|
||||
activeId?: string;
|
||||
@@ -31,6 +34,8 @@ export interface InspectorProps {
|
||||
|
||||
export function Inspector({
|
||||
sections,
|
||||
header,
|
||||
footer,
|
||||
defaultOpen = [],
|
||||
openSections,
|
||||
activeId,
|
||||
@@ -70,6 +75,7 @@ export function Inspector({
|
||||
return (
|
||||
<InspectorSelectPolicyContext.Provider value>
|
||||
<div className={cn("nodedc-inspector", className)} data-variant={variant === "default" ? undefined : variant}>
|
||||
{header ? <div className="nodedc-inspector__header">{header}</div> : null}
|
||||
{groups.map((group, groupIndex) => (
|
||||
<div className="nodedc-inspector__group" key={`${group.label ?? "root"}-${groupIndex}`}>
|
||||
{group.sections.map((section) => {
|
||||
@@ -107,6 +113,7 @@ export function Inspector({
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
{footer ? <div className="nodedc-inspector__footer">{footer}</div> : null}
|
||||
</div>
|
||||
</InspectorSelectPolicyContext.Provider>
|
||||
);
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ export interface NavigationCubeProps {
|
||||
/** Camera world quaternion, Y up. Directions point from target toward camera. */
|
||||
quaternion: readonly [number,number,number,number];
|
||||
onSelect: (direction:CubeDirection)=>void;
|
||||
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number;
|
||||
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number; faceOpacity?:number;
|
||||
disabled?:boolean;
|
||||
label?:string;
|
||||
}
|
||||
@@ -42,9 +42,9 @@ export function cubeRegions(quaternion:NavigationCubeProps["quaternion"]) {
|
||||
});
|
||||
}
|
||||
/** BIM-style face / edge / corner navigation, independent of the scene engine. */
|
||||
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1}:NavigationCubeProps) {
|
||||
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1,faceOpacity=1}:NavigationCubeProps) {
|
||||
const [hover,setHover]=useState<string|null>(null);
|
||||
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
|
||||
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-face-opacity":faceOpacity,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
|
||||
{cubeRegions(quaternion).map(r=><g key={r.id} role="button" aria-label={`Ракурс: ${r.label}`} aria-disabled={disabled}
|
||||
tabIndex={disabled?-1:0} className={hover===r.label?"is-hovered":""}
|
||||
onPointerEnter={()=>setHover(r.label)} onPointerLeave={()=>setHover(null)}
|
||||
|
||||
@@ -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);
|
||||
@@ -3,10 +3,16 @@ import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBa
|
||||
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Dropdown } from "./Dropdown.js";
|
||||
import { Button } from "./Button.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { Description } from "./Description.js";
|
||||
import { screenColorPicker } from "./screenColorPicker.js";
|
||||
|
||||
export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> {
|
||||
label: string;
|
||||
orientation?: "horizontal" | "vertical";
|
||||
/** Thin horizontal single-value rail; no containing surface or exact editor. */
|
||||
variant?: "field" | "rail";
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
@@ -69,6 +75,7 @@ export function RangeControl(props: RangeControlProps | RangeBandControlProps) {
|
||||
function SingleRangeControl({
|
||||
label,
|
||||
orientation = "horizontal",
|
||||
variant = "field",
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
@@ -102,6 +109,10 @@ function SingleRangeControl({
|
||||
"--nodedc-range-editor-characters": editorCharacters,
|
||||
} as CSSProperties;
|
||||
|
||||
// External undo/redo owns the controlled value even while the exact editor is focused.
|
||||
// Otherwise its next blur would commit an obsolete draft over the restored value.
|
||||
useLayoutEffect(() => setDraft(editableNumber(value)), [value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editing) setDraft(editableNumber(value));
|
||||
}, [editing, value]);
|
||||
@@ -151,6 +162,17 @@ function SingleRangeControl({
|
||||
}
|
||||
};
|
||||
|
||||
if (orientation === "horizontal" && variant === "rail") return (
|
||||
<div className={cn("nodedc-range-rail", className)} data-disabled={disabled || undefined}>
|
||||
<span className="nodedc-range-rail__value" aria-hidden="true">{displayValue}</span>
|
||||
<div ref={rootRef} className="nodedc-range" style={style} data-variant="rail">
|
||||
<input ref={rangeRef} {...props} type="range" value={value} min={min} max={safeMax} step={step}
|
||||
disabled={disabled} tabIndex={tabIndex} aria-label={label} aria-orientation="horizontal"
|
||||
aria-valuetext={displayValue} onChange={event => onChange(Number(event.target.value))}/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (orientation === "vertical") return (
|
||||
<div className="nodedc-range-scale" data-limit-side={limitSide} style={style}>
|
||||
<div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical">
|
||||
@@ -271,7 +293,29 @@ function hsvToHex({ h, s, v }: Hsv): string {
|
||||
return `#${base.map((channel) => Math.round((channel + offset) * 255).toString(16).padStart(2, "0")).join("")}`;
|
||||
}
|
||||
|
||||
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, ...props }: ColorFieldProps) {
|
||||
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, onBlur, onKeyDown, ...props }: ColorFieldProps) {
|
||||
const [draft, setDraft] = useState(value);
|
||||
const [paletteOpen, setPaletteOpen] = useState(false), [picking, setPicking] = useState(false), [pickError, setPickError] = useState(false);
|
||||
const nativePicker = useRef<HTMLInputElement>(null), sampling = useRef<AbortController | null>(null);
|
||||
const screenPicker = screenColorPicker();
|
||||
useEffect(() => () => { sampling.current?.abort(); }, []);
|
||||
useEffect(() => { if (disabled || !paletteOpen) { sampling.current?.abort(); sampling.current = null; setPicking(false); } }, [disabled, paletteOpen]);
|
||||
useEffect(() => setDraft(value), [value]);
|
||||
const sampleScreen = async () => {
|
||||
if (disabled || sampling.current) return;
|
||||
setPickError(false);
|
||||
if (!screenPicker) { nativePicker.current?.click(); return; }
|
||||
const controller = new AbortController(); sampling.current = controller; setPicking(true);
|
||||
try {
|
||||
// open() executes synchronously in this trusted click before the first await.
|
||||
const result = await new screenPicker().open({ signal: controller.signal });
|
||||
if (!controller.signal.aborted && parseHexColor(result.sRGBHex)) { setDraft(result.sRGBHex.toLowerCase()); onChange(result.sRGBHex.toLowerCase()); }
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted && !(error instanceof Error && error.name === 'AbortError')) setPickError(true);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) { setPicking(false); sampling.current = null; }
|
||||
}
|
||||
};
|
||||
const validColor = hexToHsv(value);
|
||||
const [hsv, setHsv] = useState<Hsv>(() => validColor ?? { h: 330, s: 82, v: 100 });
|
||||
const style = { "--nodedc-color-value": validColor ? hsvToHex(validColor) : hsvToHex(hsv) } as CSSProperties;
|
||||
@@ -283,6 +327,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
const commit = (next: Hsv) => {
|
||||
const normalized = { h: clamp(next.h, 0, 360), s: clamp(next.s, 0, 100), v: clamp(next.v, 0, 100) };
|
||||
setHsv(normalized);
|
||||
setDraft(hsvToHex(normalized));
|
||||
onChange(hsvToHex(normalized));
|
||||
};
|
||||
|
||||
@@ -295,6 +340,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
<div className={cn("nodedc-color-field", className)} style={style}>
|
||||
<Dropdown
|
||||
className="nodedc-color-field__dropdown"
|
||||
onOpenChange={setPaletteOpen}
|
||||
placement="bottom-start"
|
||||
minWidth={296}
|
||||
width={296}
|
||||
@@ -347,6 +393,10 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
<span>Оттенок</span>
|
||||
<input type="range" min={0} max={360} value={Math.round(hsv.h)} aria-label={`${label}: оттенок`} disabled={disabled} onChange={(event) => commit({ ...hsv, h: Number(event.target.value) })} />
|
||||
</label>
|
||||
<Button width="full" icon={<Icon name="pipette"/>} disabled={disabled} loading={picking} onClick={() => void sampleScreen()} title={screenPicker ? 'Выбрать цвет в любой точке экрана; Escape — отменить' : 'В этом браузере выбор цвета с экрана доступен через системную палитру, если она поддерживает пипетку'}>
|
||||
{screenPicker ? 'Цвет с экрана' : 'Системная палитра'}
|
||||
</Button>
|
||||
{pickError && <Description role="status">Не удалось включить пипетку. Повторите попытку.</Description>}
|
||||
<div className="nodedc-color-palette__presets" aria-label="Быстрые цвета">
|
||||
{palettePresets.map((preset) => (
|
||||
<button
|
||||
@@ -364,14 +414,28 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
</div>
|
||||
</div>
|
||||
</Dropdown>
|
||||
<input ref={nativePicker} type="color" hidden tabIndex={-1} aria-hidden="true" disabled={disabled} value={validColor ? hsvToHex(validColor) : '#000000'} onChange={event => { setDraft(event.target.value); onChange(event.target.value); }}/>
|
||||
<input
|
||||
className="nodedc-color-field__text"
|
||||
value={value}
|
||||
{...props}
|
||||
value={draft}
|
||||
aria-label={`${label}: HEX`}
|
||||
disabled={disabled}
|
||||
spellCheck={false}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
{...props}
|
||||
onChange={(event) => {
|
||||
const text = event.target.value;
|
||||
setDraft(text);
|
||||
if (parseHexColor(text)) onChange(`#${text.trim().replace(/^#/, "").toLowerCase()}`);
|
||||
}}
|
||||
onBlur={(event) => {
|
||||
setDraft(parseHexColor(draft) ? `#${draft.trim().replace(/^#/, "").toLowerCase()}` : value);
|
||||
onBlur?.(event);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setDraft(value); }
|
||||
if (event.key === "Enter") { event.preventDefault(); event.currentTarget.blur(); }
|
||||
onKeyDown?.(event);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {useRef, type HTMLAttributes, type ReactNode} from "react";
|
||||
import {cn} from "./cn.js";
|
||||
|
||||
export interface ResizableViewportProps extends Omit<HTMLAttributes<HTMLDivElement>, "children" | "onChange"> {
|
||||
children: ReactNode;
|
||||
height: number;
|
||||
minHeight?: number;
|
||||
maxHeight?: number;
|
||||
onHeightChange: (height: number) => void;
|
||||
onHeightCommit?: (height: number) => void;
|
||||
resizeLabel?: string;
|
||||
resizeIndicator?: boolean;
|
||||
}
|
||||
/** In-flow viewer with height-only corner grips. Persistence belongs to its owner. */
|
||||
export function ResizableViewport({children, height, minHeight = 360, maxHeight = 2160, onHeightChange, onHeightCommit, resizeLabel = "Высота 3D-окна", resizeIndicator = true, className, style, ...props}: ResizableViewportProps) {
|
||||
const drag = useRef<{id:number; y:number; height:number; current:number} | null>(null);
|
||||
const fit = (value:number) => Math.round(Math.max(minHeight, Math.min(maxHeight, value)));
|
||||
const current = fit(height);
|
||||
return <div {...props} data-resize-indicator={resizeIndicator ? undefined : "hidden"} className={cn("nodedc-resizable-viewport", className)} style={{...style, height:current}}>
|
||||
{children}
|
||||
{(["start", "end"] as const).map(corner => <div key={corner} className="nodedc-resizable-viewport__grip" data-corner={corner}
|
||||
role="separator" aria-orientation="horizontal" tabIndex={0} aria-label={`${resizeLabel} · ${corner === "start" ? "левый угол" : "правый угол"}`}
|
||||
aria-valuenow={current} aria-valuemin={minHeight} aria-valuemax={maxHeight} aria-valuetext={`${current} px`}
|
||||
onPointerDown={event => {
|
||||
if (event.button !== 0 || drag.current) return;
|
||||
event.preventDefault(); event.stopPropagation(); event.currentTarget.setPointerCapture(event.pointerId);
|
||||
drag.current = {id:event.pointerId, y:event.clientY, height:current, current};
|
||||
}}
|
||||
onPointerMove={event => {
|
||||
const gesture = drag.current;
|
||||
if (!gesture || event.pointerId !== gesture.id) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
gesture.current = fit(gesture.height + event.clientY - gesture.y); onHeightChange(gesture.current);
|
||||
}}
|
||||
onPointerUp={event => {
|
||||
const gesture = drag.current; if (!gesture || event.pointerId !== gesture.id) return;
|
||||
event.stopPropagation(); drag.current = null; event.currentTarget.releasePointerCapture(event.pointerId); onHeightCommit?.(gesture.current);
|
||||
}}
|
||||
onLostPointerCapture={() => {const gesture = drag.current; drag.current = null; if (gesture) onHeightCommit?.(gesture.current);}}
|
||||
onKeyDown={event => {
|
||||
const step = event.shiftKey ? 50 : 10;
|
||||
const next = event.key === "ArrowUp" ? current - step : event.key === "ArrowDown" ? current + step : event.key === "Home" ? minHeight : event.key === "End" ? maxHeight : null;
|
||||
if (next === null) return;
|
||||
event.preventDefault(); event.stopPropagation(); const value = fit(next); onHeightChange(value); onHeightCommit?.(value);
|
||||
}}/>) }
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {forwardRef} from "react";
|
||||
import {Button,type ButtonProps} from "./Button.js";
|
||||
import {cn} from "./cn.js";
|
||||
/** Screen-projected data anchored to a real scene object; coordinates belong to the renderer. */
|
||||
export const SceneAnnotation=forwardRef<HTMLButtonElement,ButtonProps>(function SceneAnnotation({className,...props},ref){
|
||||
return <Button {...props} ref={ref} variant="ghost" size="dense" className={cn("nodedc-scene-annotation",className)}/>;
|
||||
});
|
||||
@@ -29,6 +29,8 @@ export interface SelectProps<T extends string> {
|
||||
menuWidth?: number | "anchor";
|
||||
disabled?: boolean;
|
||||
variant?: SelectVariant;
|
||||
/** Split site/workspace selectors can align with adjacent circular actions. */
|
||||
shape?: "default" | "pill";
|
||||
className?: string;
|
||||
triggerClassName?: string;
|
||||
menuClassName?: string;
|
||||
@@ -47,6 +49,7 @@ export function Select<T extends string>({
|
||||
menuWidth = "anchor",
|
||||
disabled = false,
|
||||
variant = "integrated",
|
||||
shape = "default",
|
||||
className,
|
||||
triggerClassName,
|
||||
menuClassName,
|
||||
@@ -88,7 +91,7 @@ export function Select<T extends string>({
|
||||
};
|
||||
if (resolvedVariant === "split") {
|
||||
return (
|
||||
<div className={cn("nodedc-select", triggerClassName)} data-disabled={disabled ? "true" : undefined}>
|
||||
<div className={cn("nodedc-select", triggerClassName)} data-shape={shape === "pill" ? "pill" : undefined} data-disabled={disabled ? "true" : undefined}>
|
||||
<div ref={setAnchorRef} className="nodedc-select__control">
|
||||
<div className="nodedc-select__value">
|
||||
{selected?.icon ? <span className="nodedc-select__value-icon">{selected.icon}</span> : null}
|
||||
|
||||
@@ -57,6 +57,7 @@ export function SplitPane({
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const activePointerIdRef = useRef<number | null>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [pointerFocus, setPointerFocus] = useState(false);
|
||||
const limits = normalizedLimits(minPrimarySize, minSecondarySize);
|
||||
const size = clamp(Number.isFinite(primarySize) ? primarySize : 50, limits.minimum, limits.maximum);
|
||||
const keyboardIncrement = Number.isFinite(step) && step > 0 ? step : 2;
|
||||
@@ -74,6 +75,7 @@ export function SplitPane({
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
|
||||
setPointerFocus(false);
|
||||
const multiplier = event.shiftKey ? 5 : 1;
|
||||
const decrement = orientation === "vertical" ? "ArrowLeft" : "ArrowUp";
|
||||
const increment = orientation === "vertical" ? "ArrowRight" : "ArrowDown";
|
||||
@@ -119,10 +121,13 @@ export function SplitPane({
|
||||
aria-valuemax={Math.round(limits.maximum)}
|
||||
aria-valuenow={Math.round(size)}
|
||||
aria-valuetext={`${Math.round(size)}% / ${Math.round(100 - size)}%`}
|
||||
data-pointer-focus={pointerFocus || undefined}
|
||||
onBlur={() => setPointerFocus(false)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button !== 0) return;
|
||||
event.currentTarget.focus();
|
||||
setPointerFocus(true);
|
||||
event.currentTarget.focus({ preventScroll: true });
|
||||
activePointerIdRef.current = event.pointerId;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
setDragging(true);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, type HTMLAttributes } from "react";
|
||||
import { createContext, useContext, useEffect, useRef, type HTMLAttributes, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
@@ -13,6 +13,13 @@ export type ToastItem = {
|
||||
durationMs?: number | null;
|
||||
};
|
||||
|
||||
const ToastObservation = createContext<((items: ToastItem[]) => void) | null>(null);
|
||||
|
||||
/** The application owns history/storage; this only reports terminal presentations. */
|
||||
export function ToastObserver({onPresent, children}: {onPresent: (items: ToastItem[]) => void; children: ReactNode}) {
|
||||
return <ToastObservation.Provider value={onPresent}>{children}</ToastObservation.Provider>;
|
||||
}
|
||||
|
||||
const toastIcons: Record<ToastTone, IconName> = {
|
||||
success: "check",
|
||||
error: "alert",
|
||||
@@ -69,7 +76,21 @@ function TimedToastCard({ item, onDismiss }: { item: ToastItem; onDismiss: (id:
|
||||
return <ToastCard item={item} onDismiss={onDismiss} />;
|
||||
}
|
||||
|
||||
export function ToastStack({ items, onDismiss }: { items: ToastItem[]; onDismiss: (id: string) => void }) {
|
||||
export function ToastStack({ items, onDismiss, observe = true }: { items: ToastItem[]; onDismiss: (id: string) => void; observe?: boolean }) {
|
||||
const observer = useContext(ToastObservation);
|
||||
const presented = useRef(new Map<string, string>());
|
||||
useEffect(() => {
|
||||
const next = new Map<string, string>();
|
||||
const fresh: ToastItem[] = [];
|
||||
for (const item of items) {
|
||||
if (item.tone === 'loading') continue;
|
||||
const identity = JSON.stringify([item.tone, item.title, item.description]);
|
||||
next.set(item.id, identity);
|
||||
if (presented.current.get(item.id) !== identity) fresh.push(item);
|
||||
}
|
||||
presented.current = next;
|
||||
if (observe && fresh.length) observer?.(fresh);
|
||||
}, [items, observer, observe]);
|
||||
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">
|
||||
|
||||
@@ -38,6 +38,8 @@ export interface ToolbarProps<T extends string = string> {
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
label?: string;
|
||||
/** Dropdown width; placement still clamps to the visible viewport. */
|
||||
menuWidth?: number;
|
||||
className?: string;
|
||||
/** Render inside a positioned viewport; edge reveal follows that viewport. */
|
||||
container?: HTMLElement;
|
||||
@@ -66,6 +68,7 @@ export function Toolbar<T extends string = string>({
|
||||
hideDelay = NODEDC_TOOLBAR_DEFAULTS.hideDelay,
|
||||
gap = NODEDC_TOOLBAR_DEFAULTS.gap,
|
||||
label = "Панель инструментов",
|
||||
menuWidth = 220,
|
||||
className,
|
||||
container,
|
||||
}: ToolbarProps<T>) {
|
||||
@@ -392,7 +395,7 @@ export function Toolbar<T extends string = string>({
|
||||
if(placement==="left")return {...b.toJSON(),left:t.left,right:t.left+pad,width:pad};
|
||||
if(placement==="bottom")return {...b.toJSON(),top:t.bottom-pad,bottom:t.bottom,height:pad};
|
||||
return {...b.toJSON(),top:t.top,bottom:t.top+pad,height:pad};
|
||||
}} width={220} trigger={button} onPointerDownOutside={event=>{
|
||||
}} width={Number.isFinite(menuWidth)?Math.max(180,Math.min(600,menuWidth)):220} trigger={button} onPointerDownOutside={event=>{
|
||||
const target=event.target as Element;
|
||||
// Dismiss a menu before a viewport tool can turn this same click into an edit.
|
||||
if(container?.contains(target)&&!target.closest('button,input,select,textarea,a,[role="button"],[role="tab"]')){
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import {cloneElement,isValidElement,useCallback,useEffect,useId,useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode,type ReactElement} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {computeFloatingPosition,type FloatingPlacement} from '@nodedc/ui-core';
|
||||
import {cn} from './cn.js';
|
||||
|
||||
export interface TooltipProps {
|
||||
children:ReactNode;
|
||||
content:ReactNode;
|
||||
label?:string;
|
||||
/** Use for a read-only graphic; buttons already supply their own focus target. */
|
||||
focusable?:boolean;
|
||||
disabled?:boolean;
|
||||
placement?:FloatingPlacement;
|
||||
className?:string;
|
||||
}
|
||||
|
||||
/** Non-interactive explanation; selection/actions belong to Dropdown. */
|
||||
export function Tooltip({children,content,label,focusable=false,disabled=false,placement='top-start',className}:TooltipProps){
|
||||
const id=`tooltip-${useId().replaceAll(':','')}`;
|
||||
const anchor=useRef<HTMLSpanElement>(null),surface=useRef<HTMLDivElement>(null);
|
||||
const timer=useRef<ReturnType<typeof setTimeout>|undefined>(undefined);
|
||||
const [open,setOpen]=useState(false),[style,setStyle]=useState<CSSProperties>({visibility:'hidden'});
|
||||
const clear=useCallback(()=>{clearTimeout(timer.current);},[]);
|
||||
const close=useCallback(()=>{clear();setOpen(false);},[clear]);
|
||||
const show=useCallback(()=>{clear();if(!disabled)setOpen(true);},[clear,disabled]);
|
||||
const leave=()=>{
|
||||
clear();
|
||||
if(anchor.current?.contains(document.activeElement))return;
|
||||
timer.current=setTimeout(close,140);
|
||||
};
|
||||
useEffect(()=>()=>clear(),[clear]);
|
||||
useEffect(()=>{if(disabled)close();},[disabled,close]);
|
||||
useLayoutEffect(()=>{
|
||||
if(!open)return;
|
||||
const position=()=>{
|
||||
if(!anchor.current||!surface.current)return;
|
||||
const rect=anchor.current.getBoundingClientRect(),size=surface.current.getBoundingClientRect();
|
||||
if(rect.bottom<=0||rect.top>=window.innerHeight||rect.right<=0||rect.left>=window.innerWidth){close();return;}
|
||||
const p=computeFloatingPosition({anchor:rect,surfaceWidth:size.width,surfaceHeight:size.height,placement,offset:8});
|
||||
setStyle({left:p.left,top:p.top,maxHeight:p.maxHeight,visibility:'visible'});
|
||||
};
|
||||
position();
|
||||
const observer=new ResizeObserver(position);
|
||||
if(anchor.current)observer.observe(anchor.current);
|
||||
if(surface.current)observer.observe(surface.current);
|
||||
window.addEventListener('resize',position);window.addEventListener('scroll',position,true);
|
||||
document.addEventListener('fullscreenchange',close);
|
||||
return()=>{observer.disconnect();window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true);document.removeEventListener('fullscreenchange',close);};
|
||||
},[open,placement,close]);
|
||||
useEffect(()=>{
|
||||
if(!open)return;
|
||||
const key=(e:KeyboardEvent)=>{if(e.key==='Escape'){close();e.preventDefault();e.stopImmediatePropagation();}};
|
||||
const outside=(e:PointerEvent)=>{if(e.target instanceof Node&&!anchor.current?.contains(e.target)&&!surface.current?.contains(e.target))close();};
|
||||
const other=(e:Event)=>{if((e as CustomEvent<string>).detail!==id)close();};
|
||||
document.addEventListener('keydown',key,true);document.addEventListener('pointerdown',outside,true);
|
||||
window.addEventListener('nodedc-tooltip-open',other);
|
||||
window.dispatchEvent(new CustomEvent('nodedc-tooltip-open',{detail:id}));
|
||||
return()=>{document.removeEventListener('keydown',key,true);document.removeEventListener('pointerdown',outside,true);window.removeEventListener('nodedc-tooltip-open',other);};
|
||||
},[open,id,close]);
|
||||
return <span ref={anchor} className={cn('nodedc-tooltip-anchor',className)}
|
||||
tabIndex={focusable&&!disabled?0:undefined} role={focusable?'img':undefined} aria-label={label}
|
||||
aria-describedby={open?id:undefined} onPointerEnter={e=>{if(e.pointerType!=='touch')show();}}
|
||||
onPointerLeave={leave} onFocus={show} onBlur={e=>{if(!e.currentTarget.contains(e.relatedTarget)&&!e.currentTarget.matches(':hover'))close();}}
|
||||
onPointerDown={e=>{if(e.pointerType==='touch'){if(open)close();else show();}}}>
|
||||
{focusable||!isValidElement(children)?children:cloneElement(children as ReactElement<{'aria-describedby'?:string;title?:string}>,{title:undefined,'aria-describedby':[children.props && (children.props as {'aria-describedby'?:string})['aria-describedby'],open?id:undefined].filter(Boolean).join(' ')||undefined})}
|
||||
{open&&typeof document!=='undefined'&&createPortal(<div ref={surface} id={id} role="tooltip"
|
||||
className="nodedc-tooltip" style={style} onPointerEnter={clear} onPointerLeave={leave}>{content}</div>,document.fullscreenElement??document.body)}
|
||||
</span>;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import {createContext,useContext,useEffect,useId,useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {computeFloatingPosition} from '@nodedc/ui-core';
|
||||
import {TooltipTitles} from './tooltipTitles.js';
|
||||
|
||||
const Installed=createContext(false);
|
||||
/** One application-wide bridge for native title hints. Nested modules reuse the host. */
|
||||
export function TooltipProvider({children}:{children?:ReactNode}){
|
||||
const installed=useContext(Installed);
|
||||
return installed?<>{children}</>:<Installed.Provider value={true}><TitleTooltips/>{children}</Installed.Provider>;
|
||||
}
|
||||
function TitleTooltips(){
|
||||
const id=`tooltip-layer-${useId().replaceAll(':','')}`;
|
||||
const [target,setTarget]=useState<{element:Element;text:string}|null>(null);
|
||||
const [style,setStyle]=useState<CSSProperties>({visibility:'hidden'});
|
||||
const surface=useRef<HTMLDivElement>(null),titles=useRef(new TooltipTitles());
|
||||
const hide=useRef(()=>{});
|
||||
useEffect(()=>{
|
||||
let anchor:Element|null=null,timer:ReturnType<typeof setTimeout>|undefined,leaving:ReturnType<typeof setTimeout>|undefined,observer:MutationObserver|null=null;
|
||||
const clear=()=>{clearTimeout(timer);clearTimeout(leaving);};
|
||||
const close=()=>{clear();observer?.disconnect();observer=null;anchor=null;titles.current.restore();setTarget(null);};hide.current=close;
|
||||
const show=(element:Element,text:string)=>{
|
||||
titles.current.describe(element,id);setTarget({element,text});
|
||||
window.dispatchEvent(new CustomEvent('nodedc-tooltip-open',{detail:id}));
|
||||
};
|
||||
const enter=(node:EventTarget|null,keyboard=false)=>{
|
||||
if(!(node instanceof Element))return;
|
||||
if(surface.current?.contains(node)){clear();return;}
|
||||
if(anchor?.contains(node)){clearTimeout(leaving);if(keyboard){const text=titles.current.text(anchor);if(text)show(anchor,text);}return;}
|
||||
close();
|
||||
// Explicit Tooltip already owns rich content and its accessible description.
|
||||
if(node.closest('.nodedc-tooltip-anchor,[data-nodedc-tooltip="off"]'))return;
|
||||
const found=titles.current.find(node);if(!found)return;
|
||||
anchor=found.element;titles.current.suppress(anchor);
|
||||
observer=new MutationObserver(()=>{
|
||||
if(!anchor)return;
|
||||
const updated=anchor.getAttribute('data-nodedc-tooltip')??anchor.getAttribute('title');if(updated===null)return;
|
||||
titles.current.suppress(anchor);if(updated.trim())show(anchor,updated);else close();
|
||||
});observer.observe(anchor,{attributes:true,attributeFilter:['title','data-nodedc-tooltip']});
|
||||
if(keyboard)show(anchor,found.text);else timer=setTimeout(()=>{if(anchor)show(anchor,found.text);},220);
|
||||
};
|
||||
const leave=(related:EventTarget|null)=>{
|
||||
if(related instanceof Node&&(anchor?.contains(related)||surface.current?.contains(related)))return;
|
||||
if(anchor?.contains(document.activeElement))return;
|
||||
clearTimeout(leaving);leaving=setTimeout(close,140);
|
||||
};
|
||||
const over=(event:PointerEvent)=>{if(event.pointerType!=='touch')enter(event.composedPath()[0]??event.target);};
|
||||
const out=(event:PointerEvent)=>leave(event.relatedTarget);
|
||||
const focus=(event:FocusEvent)=>enter(event.composedPath()[0]??event.target,true);
|
||||
const blur=(event:FocusEvent)=>{if(!(event.relatedTarget instanceof Node)||!anchor?.contains(event.relatedTarget))close();};
|
||||
const down=()=>{clear();setTarget(null);};
|
||||
const key=(event:KeyboardEvent)=>{if(event.key==='Escape'&&anchor){close();event.preventDefault();event.stopImmediatePropagation();}};
|
||||
const other=(event:Event)=>{if((event as CustomEvent<string>).detail!==id)close();};
|
||||
document.addEventListener('pointerover',over,true);document.addEventListener('pointerout',out,true);
|
||||
document.addEventListener('focusin',focus,true);document.addEventListener('focusout',blur,true);
|
||||
document.addEventListener('pointerdown',down,true);document.addEventListener('keydown',key,true);
|
||||
document.addEventListener('fullscreenchange',close);window.addEventListener('blur',close);window.addEventListener('nodedc-tooltip-open',other);
|
||||
return()=>{close();document.removeEventListener('pointerover',over,true);document.removeEventListener('pointerout',out,true);document.removeEventListener('focusin',focus,true);document.removeEventListener('focusout',blur,true);document.removeEventListener('pointerdown',down,true);document.removeEventListener('keydown',key,true);document.removeEventListener('fullscreenchange',close);window.removeEventListener('blur',close);window.removeEventListener('nodedc-tooltip-open',other);};
|
||||
},[id]);
|
||||
useLayoutEffect(()=>{
|
||||
if(!target)return;
|
||||
const position=()=>{
|
||||
if(!surface.current||!target.element.isConnected){hide.current();return;}
|
||||
const rect=target.element.getBoundingClientRect();if(rect.bottom<=0||rect.top>=window.innerHeight||rect.right<=0||rect.left>=window.innerWidth){hide.current();return;}
|
||||
const size=surface.current.getBoundingClientRect(),p=computeFloatingPosition({anchor:rect,surfaceWidth:size.width,surfaceHeight:size.height,placement:'bottom-start',offset:8});
|
||||
setStyle({left:p.left,top:p.top,maxHeight:p.maxHeight,visibility:'visible'});
|
||||
};
|
||||
position();const observer=new ResizeObserver(position);observer.observe(target.element);if(surface.current)observer.observe(surface.current);
|
||||
window.addEventListener('resize',position);window.addEventListener('scroll',position,true);
|
||||
return()=>{observer.disconnect();window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true);};
|
||||
},[target]);
|
||||
return target&&typeof document!=='undefined'?createPortal(<div ref={surface} id={id} role="tooltip" className="nodedc-tooltip" style={style}>{target.text}</div>,document.fullscreenElement??document.body):null;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode} from 'react';
|
||||
import {treeSelectionRange} from './treeSelectionRange.js';
|
||||
import {Icon,type IconName} from './Icon.js';
|
||||
|
||||
export interface TreeNode {id:string;label:string;children?:TreeNode[];icon?:IconName;visible?:boolean}
|
||||
export interface TreeSelectionGesture {ctrlKey:boolean;metaKey:boolean;shiftKey:boolean;rangeIds:string[]}
|
||||
export interface TreeProps {nodes:TreeNode[];selected:string|null;selectedIds?:readonly string[];onSelect:(id:string,gesture:TreeSelectionGesture)=>void;onVisibilityChange?:(id:string,visible:boolean)=>void;label:string;query?:string;revealKey?:number;defaultExpandedDepth?:number;renderActions?:(node:TreeNode)=>ReactNode}
|
||||
|
||||
/** Compact outliner. Selection reveals ancestors without scrolling its host page. */
|
||||
export function Tree({nodes,selected,selectedIds,onSelect,onVisibilityChange,label,query='',revealKey,defaultExpandedDepth=Infinity,renderActions}:TreeProps){
|
||||
const [collapsed,setCollapsed]=useState<Map<string,boolean>>(()=>new Map());
|
||||
const [focus,setFocus]=useState<string|null>(null);
|
||||
const anchor=useRef<string|null>(null);
|
||||
const lastReveal=useRef<{selected:string;key:number|undefined}|null>(null),pendingReveal=useRef<string|null>(null);
|
||||
const disclosureScroll=useRef<number|null>(null);
|
||||
const host=useRef<HTMLDivElement>(null),elements=useRef(new Map<string,HTMLDivElement>());
|
||||
const parents=new Map<string,string>(),index=new Map<string,TreeNode>();
|
||||
const visit=(items:TreeNode[],parent?:string)=>{for(const item of items){index.set(item.id,item);if(parent)parents.set(item.id,parent);visit(item.children??[],item.id);}};visit(nodes);
|
||||
const ancestors=new Set<string>();let parent=selected?parents.get(selected):undefined;while(parent){ancestors.add(parent);parent=parents.get(parent);}
|
||||
const matches=(item:TreeNode):boolean=>!query||item.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())||!!item.children?.some(matches);
|
||||
const rows:{node:TreeNode;depth:number;open:boolean}[]=[];
|
||||
const flatten=(items:TreeNode[],depth=0)=>{for(const node of items){if(!matches(node))continue;const open=!!query||!(collapsed.get(node.id)??depth>=defaultExpandedDepth);rows.push({node,depth,open});if(open)flatten(node.children??[],depth+1);}};flatten(nodes);
|
||||
const reveal=(id:string)=>{const target=elements.current.get(id),container=host.current;if(!target||!container)return;const row=target.getBoundingClientRect(),box=container.getBoundingClientRect();if(row.top<box.top)container.scrollTop-=box.top-row.top;else if(row.bottom>box.bottom)container.scrollTop+=row.bottom-box.bottom;};
|
||||
// Data/visibility refreshes are not a new selection. An unresolved external
|
||||
// selection may wait for async nodes, but a manual disclosure always wins.
|
||||
useLayoutEffect(()=>{
|
||||
if(!selected){lastReveal.current=null;pendingReveal.current=null;return;}
|
||||
if(lastReveal.current?.selected===selected&&lastReveal.current.key===revealKey)return;
|
||||
if(!index.has(selected))return;
|
||||
lastReveal.current={selected,key:revealKey};pendingReveal.current=selected;setFocus(selected);
|
||||
setCollapsed(old=>{if([...ancestors].every(id=>old.get(id)===false))return old;const next=new Map(old);for(const id of ancestors)next.set(id,false);return next;});
|
||||
},[selected,revealKey,nodes]);
|
||||
useLayoutEffect(()=>{
|
||||
if(disclosureScroll.current!==null){if(host.current)host.current.scrollTop=disclosureScroll.current;disclosureScroll.current=null;return;}
|
||||
const id=pendingReveal.current;if(id&&elements.current.has(id)){reveal(id);pendingReveal.current=null;}
|
||||
},[selected,revealKey,nodes,query,collapsed]);
|
||||
const toggle=(id:string)=>{
|
||||
pendingReveal.current=null;disclosureScroll.current=host.current?.scrollTop??null;
|
||||
setCollapsed(old=>{const next=new Map(old);const depth=rows.find(row=>row.node.id===id)?.depth??0;next.set(id,!(old.get(id)??depth>=defaultExpandedDepth));return next;});
|
||||
};
|
||||
const select=(id:string,event:{ctrlKey:boolean;metaKey:boolean;shiftKey:boolean})=>{setFocus(id);
|
||||
const rangeIds=event.shiftKey&&selectedIds?treeSelectionRange(rows.map(row=>row.node.id),anchor.current,id):[id];
|
||||
if(!event.shiftKey)anchor.current=id;
|
||||
onSelect(id,{ctrlKey:event.ctrlKey,metaKey:event.metaKey,shiftKey:event.shiftKey,rangeIds});elements.current.get(id)?.focus({preventScroll:true});reveal(id);};
|
||||
return <div ref={host} className="nodedc-tree" role="tree" aria-label={label} aria-multiselectable={selectedIds?true:undefined}>
|
||||
{rows.map(({node,depth,open},position)=><div key={node.id} ref={element=>{if(element)elements.current.set(node.id,element);else elements.current.delete(node.id);}} role="treeitem" aria-level={depth+1} aria-selected={selectedIds?selectedIds.includes(node.id):selected===node.id} aria-expanded={node.children?.length?open:undefined} tabIndex={(focus??selected??rows[0]?.node.id)===node.id?0:-1} className="nodedc-tree__row" style={{'--tree-depth':depth} as CSSProperties} title={node.label} onFocus={()=>setFocus(node.id)} onClick={event=>select(node.id,event)} onKeyDown={event=>{
|
||||
if(event.target!==event.currentTarget)return;
|
||||
let next:string|undefined;
|
||||
if(event.key==='ArrowDown')next=rows[Math.min(rows.length-1,position+1)]?.node.id;
|
||||
else if(event.key==='ArrowUp')next=rows[Math.max(0,position-1)]?.node.id;
|
||||
else if(event.key==='Home')next=rows[0]?.node.id;
|
||||
else if(event.key==='End')next=rows.at(-1)?.node.id;
|
||||
else if(event.key==='ArrowRight'){if(node.children?.length){if(!open)toggle(node.id);else next=node.children[0].id;}}
|
||||
else if(event.key==='ArrowLeft'){if(open&&node.children?.length)toggle(node.id);else next=parents.get(node.id);}
|
||||
else if(event.key==='Enter'||event.key===' ')next=node.id;
|
||||
else return;
|
||||
event.preventDefault();event.stopPropagation();if(next)select(next,event);
|
||||
}}>
|
||||
<span className="nodedc-tree__branch">{node.children?.length?<button type="button" tabIndex={-1} aria-label={`${open?'Свернуть':'Развернуть'} ${node.label}`} onClick={event=>{event.stopPropagation();toggle(node.id);}}><Icon name={open?'chevron-down':'chevron-right'} size={14}/></button>:null}</span>
|
||||
<Icon name={node.icon??(node.children?.length?'folder':'layers')} size={14}/>
|
||||
<span className="nodedc-tree__label">{node.label}</span>
|
||||
{renderActions&&<span className="nodedc-tree__actions" onClick={event=>event.stopPropagation()} onDoubleClick={event=>event.stopPropagation()}>{renderActions(node)}</span>}
|
||||
{onVisibilityChange&&node.visible!==undefined&&<button type="button" className="nodedc-tree__visibility" tabIndex={focus===node.id?0:-1} aria-label={`${node.visible?'Скрыть':'Показать'} ${node.label}`} aria-pressed={node.visible} onClick={event=>{event.stopPropagation();onVisibilityChange(node.id,!node.visible);}}><Icon name={node.visible?'eye':'eye-off'} size={14}/></button>}
|
||||
</div>)}
|
||||
</div>;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Dropdown } from "./Dropdown.js";
|
||||
import { HeaderAvatar } from "./AppHeader.js";
|
||||
import { HeaderAvatar, HeaderProfile, HeaderProfileButton } from "./AppHeader.js";
|
||||
import { IconButton } from "./Button.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
|
||||
export interface UserProfileMenuAction {
|
||||
@@ -15,19 +16,28 @@ export interface UserProfileMenuAction {
|
||||
|
||||
export interface UserProfileMenuProps {
|
||||
displayName: string;
|
||||
/** Header is canonical. "default" retains the legacy compact trigger outside headers. */
|
||||
variant?: "default" | "header";
|
||||
subtitle?: string;
|
||||
avatarUrl?: string;
|
||||
coverImageUrl?: string;
|
||||
triggerLabel?: ReactNode;
|
||||
/** Optional status glyph between the label and avatar. */
|
||||
triggerIcon?: IconName;
|
||||
/** Independent header action; the avatar still opens the profile menu. */
|
||||
headerAction?: { label: string; pressed?: boolean; controls?: string; onSelect: () => void };
|
||||
actions: readonly UserProfileMenuAction[];
|
||||
}
|
||||
|
||||
export function UserProfileMenu({
|
||||
displayName,
|
||||
variant = "header",
|
||||
subtitle,
|
||||
avatarUrl,
|
||||
coverImageUrl,
|
||||
triggerLabel,
|
||||
triggerIcon,
|
||||
headerAction,
|
||||
actions,
|
||||
}: UserProfileMenuProps) {
|
||||
const label = displayName || "NODE.DC";
|
||||
@@ -37,7 +47,29 @@ export function UserProfileMenu({
|
||||
width={296}
|
||||
offset={10}
|
||||
surfaceClassName="nodedc-user-profile-menu"
|
||||
trigger={({ open, toggle, setTriggerRef, surfaceId }) => (
|
||||
trigger={({ open, toggle, setTriggerRef, setAnchorRef, surfaceId }) => variant === "header" ? (
|
||||
<HeaderProfile ref={setAnchorRef}>
|
||||
<HeaderProfileButton aria-haspopup="menu" aria-expanded={open} aria-controls={surfaceId} onClick={(event) => { setTriggerRef(event.currentTarget); toggle(); }}>
|
||||
{triggerLabel ?? "Профиль"}
|
||||
</HeaderProfileButton>
|
||||
<IconButton
|
||||
ref={setTriggerRef}
|
||||
label={headerAction?.label ?? `Меню пользователя ${label}`}
|
||||
aria-haspopup={headerAction ? undefined : "menu"}
|
||||
aria-pressed={headerAction?.pressed}
|
||||
aria-expanded={headerAction ? headerAction.pressed : open}
|
||||
aria-controls={headerAction ? headerAction.controls : surfaceId}
|
||||
onClick={(event) => {
|
||||
if (headerAction) { if (open) toggle(); headerAction.onSelect(); }
|
||||
else { setTriggerRef(event.currentTarget); toggle(); }
|
||||
}}
|
||||
><Icon name={triggerIcon ?? "inbox"} size={20} strokeWidth={1.7} /></IconButton>
|
||||
<button type="button" className="nodedc-user-profile-menu__trigger" aria-label={`Профиль ${label}`} aria-haspopup="menu" aria-expanded={open} aria-controls={surfaceId}
|
||||
onClick={(event) => { setTriggerRef(event.currentTarget); toggle(); }}>
|
||||
<HeaderAvatar label={label} imageUrl={avatarUrl} />
|
||||
</button>
|
||||
</HeaderProfile>
|
||||
) : (
|
||||
<button
|
||||
ref={setTriggerRef}
|
||||
type="button"
|
||||
@@ -49,6 +81,7 @@ export function UserProfileMenu({
|
||||
onClick={toggle}
|
||||
>
|
||||
{triggerLabel === null ? null : <span className="nodedc-user-profile-menu__trigger-label">{triggerLabel ?? label}</span>}
|
||||
{triggerIcon ? <Icon name={triggerIcon} size={18} /> : null}
|
||||
<HeaderAvatar label={label} imageUrl={avatarUrl} />
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import {dragHandleFocus} from './dragHandleFocus.js';
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type HTMLAttributes,
|
||||
@@ -10,8 +13,11 @@ import {
|
||||
import { createPortal } from "react-dom";
|
||||
import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { LoadingContext } from "./LoadingContext.js";
|
||||
import { WindowSuspensionContext } from "./WindowSuspensionContext.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { IconButton } from "./Button.js";
|
||||
import { fitWindow, resizeWindow, windowResizeEdges, type WindowRect, type ResizeEdge } from "./windowGeometry.js";
|
||||
|
||||
const focusableSelector = [
|
||||
"a[href]",
|
||||
@@ -24,6 +30,7 @@ const focusableSelector = [
|
||||
|
||||
export type WindowSize = "sm" | "md" | "lg";
|
||||
export type WindowPlacement = "center" | "end";
|
||||
export type { WindowRect } from "./windowGeometry.js";
|
||||
|
||||
export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title"> {
|
||||
open: boolean;
|
||||
@@ -33,6 +40,15 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
|
||||
footer?: ReactNode;
|
||||
/** Context actions beside close, using canonical IconButton controls. */
|
||||
headerActions?: ReactNode;
|
||||
/** Keep actions on one line; place title below them when space is limited. */
|
||||
headerLayout?: "inline" | "adaptive";
|
||||
/** Temporarily enlarge within the viewport; restoring retains prior geometry and presentation. */
|
||||
expanded?: boolean;
|
||||
/** Separate durable layout for expanded media, committed only after a user gesture. */
|
||||
expandedRect?: WindowRect;
|
||||
onExpandedRectCommit?: (rect: WindowRect) => void;
|
||||
/** Keep contextual actions immediately before close when requested. */
|
||||
headerActionsPlacement?: "before-move" | "before-close";
|
||||
size?: WindowSize;
|
||||
placement?: WindowPlacement;
|
||||
closeLabel?: string;
|
||||
@@ -41,6 +57,18 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
|
||||
lockBodyScroll?: boolean;
|
||||
trapFocus?: boolean;
|
||||
draggable?: boolean;
|
||||
/** Resize a modeless inspector using the same eight edges as floating windows. */
|
||||
resizable?: boolean;
|
||||
initialRect?: WindowRect;
|
||||
/** Application-owned geometry, restored on open and on external undo/import. */
|
||||
rect?: WindowRect;
|
||||
/** One commit after a drag/resize, or a keyboard geometry step. */
|
||||
onRectCommit?: (rect: WindowRect) => void;
|
||||
/** Centered windows can become modeless without remounting their contents. */
|
||||
allowFloating?: boolean;
|
||||
/** App-owned presentation, persisted by window kind alongside rect. */
|
||||
floating?: boolean;
|
||||
onFloatingChange?: (floating: boolean) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -51,6 +79,11 @@ export function Window({
|
||||
children,
|
||||
footer,
|
||||
headerActions,
|
||||
headerLayout = "inline",
|
||||
expanded = false,
|
||||
expandedRect,
|
||||
onExpandedRectCommit,
|
||||
headerActionsPlacement = "before-move",
|
||||
size = "md",
|
||||
placement = "center",
|
||||
closeLabel = "Закрыть",
|
||||
@@ -59,40 +92,106 @@ export function Window({
|
||||
lockBodyScroll,
|
||||
trapFocus,
|
||||
draggable = false,
|
||||
resizable = false,
|
||||
initialRect,
|
||||
rect,
|
||||
onRectCommit,
|
||||
allowFloating = true,
|
||||
floating: controlledFloating,
|
||||
onFloatingChange,
|
||||
onClose,
|
||||
className,
|
||||
style,
|
||||
...props
|
||||
}: WindowProps) {
|
||||
const [suspensions, setSuspensions] = useState(0);
|
||||
const suspend = useCallback(() => {setSuspensions(value => value + 1); return () => setSuspensions(value => Math.max(0, value - 1));}, []);
|
||||
const suspended = suspensions > 0;
|
||||
const titleId = useId();
|
||||
const descriptionId = useId();
|
||||
const dialogRef = useRef<HTMLDivElement>(null);
|
||||
const minimumRef = useRef({width:320,height:200});
|
||||
const [headerMinimum,setHeaderMinimum]=useState(320);
|
||||
const [stackedTitle,setStackedTitle]=useState(false);
|
||||
const portalHostRef = useRef<Element | null>(null);
|
||||
const onCloseRef = useRef(onClose);
|
||||
const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number } | null>(null);
|
||||
const [dragPosition, setDragPosition] = useState<{ left: number; top: number } | null>(null);
|
||||
const shouldLockBodyScroll = lockBodyScroll ?? placement === "center";
|
||||
const shouldTrapFocus = trapFocus ?? placement === "center";
|
||||
const [floating, setFloating] = useState(false);
|
||||
const [floatingRect, setFloatingRect] = useState<WindowRect | null>(null);
|
||||
const rectRef = useRef<WindowRect | null>(null);
|
||||
const initialRectRef = useRef<WindowRect | null>(null);
|
||||
const expansionRestoreRef = useRef<WindowRect | null>(null);
|
||||
const commitRef = useRef(onRectCommit);
|
||||
// Temporary media expansion never replaces the application-owned window layout.
|
||||
commitRef.current = expanded ? onExpandedRectCommit : onRectCommit;
|
||||
const changeRect = (next: WindowRect | null) => { rectRef.current = next; setFloatingRect(next); };
|
||||
const gestureChanged = useRef(false);
|
||||
const resizeRef = useRef<{ pointerId: number; x: number; y: number; rect: WindowRect; edge: ResizeEdge } | null>(null);
|
||||
const isFloating = (controlledFloating ?? floating) && allowFloating && placement === "center";
|
||||
const freeGeometry = expanded || isFloating || (resizable && placement === "end");
|
||||
const canDrag = draggable || freeGeometry;
|
||||
const shouldLockBodyScroll = !suspended && !isFloating && (lockBodyScroll ?? placement === "center");
|
||||
const shouldTrapFocus = !suspended && !isFloating && (trapFocus ?? placement === "center");
|
||||
const modeRef = useRef({ shouldTrapFocus, isFloating, suspended });
|
||||
modeRef.current = { shouldTrapFocus, isFloating, suspended };
|
||||
onCloseRef.current = onClose;
|
||||
|
||||
useLayoutEffect(()=>{
|
||||
if(!open || headerLayout!=="adaptive")return;
|
||||
const dialog=dialogRef.current,head=dialog?.querySelector<HTMLElement>(".nodedc-window__head"),actions=head?.querySelector<HTMLElement>(".nodedc-window__actions"),heading=head?.querySelector<HTMLElement>(".nodedc-window__title");
|
||||
if(!dialog||!head||!actions||!heading)return;
|
||||
const measure=()=>{
|
||||
const headStyle=window.getComputedStyle(head),input=heading.querySelector<HTMLInputElement>("input"),copyStyle=window.getComputedStyle(input??heading);
|
||||
const sample=document.createElement("span");
|
||||
Object.assign(sample.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"pre",font:copyStyle.font,letterSpacing:copyStyle.letterSpacing});
|
||||
sample.textContent=input?.value??heading.textContent??"";head.appendChild(sample);
|
||||
const titleWidth=sample.getBoundingClientRect().width+(parseFloat(copyStyle.paddingLeft)||0)+(parseFloat(copyStyle.paddingRight)||0);sample.remove();
|
||||
const padding=(parseFloat(headStyle.paddingLeft)||0)+(parseFloat(headStyle.paddingRight)||0),actionWidth=actions.scrollWidth;
|
||||
const minimum=Math.max(320,Math.ceil(actionWidth+padding+2));
|
||||
minimumRef.current={width:minimum,height:200};setHeaderMinimum(minimum);
|
||||
setStackedTitle(head.clientWidth < padding+actionWidth+titleWidth+(parseFloat(headStyle.columnGap)||0)+2);
|
||||
if(freeGeometry&&rectRef.current){
|
||||
const fitted=fitWindow(rectRef.current,{width:window.innerWidth,height:window.innerHeight},minimumRef.current);
|
||||
if(fitted.left!==rectRef.current.left||fitted.top!==rectRef.current.top||fitted.width!==rectRef.current.width||fitted.height!==rectRef.current.height){changeRect(fitted);if(!resizeRef.current&&!dragRef.current)commitRef.current?.(fitted);}
|
||||
}
|
||||
};
|
||||
measure();
|
||||
const observer=typeof ResizeObserver!=="undefined"?new ResizeObserver(measure):null;
|
||||
observer?.observe(head);observer?.observe(actions);window.addEventListener("resize",measure);
|
||||
return()=>{observer?.disconnect();window.removeEventListener("resize",measure);};
|
||||
},[open,headerLayout,title,headerActions,freeGeometry]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || typeof document === "undefined") return;
|
||||
const previousActiveElement = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
if (shouldLockBodyScroll) document.body.style.overflow = "hidden";
|
||||
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
const firstFocusable = dialogRef.current?.querySelector<HTMLElement>(focusableSelector);
|
||||
const firstFocusable = Array.from(dialogRef.current?.querySelectorAll<HTMLElement>(focusableSelector) ?? []).find(element => element.getClientRects().length > 0);
|
||||
(firstFocusable ?? dialogRef.current)?.focus();
|
||||
});
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape" && closeOnEscape) {
|
||||
if (event.defaultPrevented || modeRef.current.suspended) return;
|
||||
// Portalled child dialogs own their Escape/Tab keys. A parent listener
|
||||
// can run first, so event.defaultPrevented alone cannot guard nesting.
|
||||
const focusedDialog = document.activeElement?.closest('[role="dialog"]');
|
||||
if (focusedDialog && focusedDialog !== dialogRef.current) return;
|
||||
if (!focusedDialog) {
|
||||
const topModal = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"][aria-modal="true"]')).filter(dialog => dialog.getClientRects().length > 0).at(-1);
|
||||
if (topModal && topModal !== dialogRef.current) return;
|
||||
}
|
||||
const ownedFullscreen = document.fullscreenElement && dialogRef.current?.contains(document.fullscreenElement);
|
||||
// Escape restores the embedded viewport, never closes its owning form.
|
||||
if (event.key === "Escape" && ownedFullscreen) return;
|
||||
if (event.key === "Escape" && closeOnEscape && (!modeRef.current.isFloating || dialogRef.current?.contains(document.activeElement))) {
|
||||
event.preventDefault();
|
||||
onCloseRef.current();
|
||||
return;
|
||||
}
|
||||
if (event.key !== "Tab" || !shouldTrapFocus || !dialogRef.current) return;
|
||||
const focusable = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(focusableSelector));
|
||||
if (event.key !== "Tab" || !modeRef.current.shouldTrapFocus || !dialogRef.current) return;
|
||||
const focusScope = ownedFullscreen ? document.fullscreenElement! : dialogRef.current;
|
||||
const focusable = Array.from(focusScope.querySelectorAll<HTMLElement>(focusableSelector)).filter(element => element.getClientRects().length > 0);
|
||||
if (focusable.length === 0) {
|
||||
event.preventDefault();
|
||||
dialogRef.current.focus();
|
||||
@@ -113,28 +212,80 @@ export function Window({
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
if (shouldLockBodyScroll) document.body.style.overflow = previousOverflow;
|
||||
previousActiveElement?.focus();
|
||||
if (!modeRef.current.isFloating || document.activeElement === document.body || dialogRef.current?.contains(document.activeElement)) previousActiveElement?.focus();
|
||||
};
|
||||
}, [closeOnEscape, open, shouldLockBodyScroll, shouldTrapFocus]);
|
||||
}, [closeOnEscape, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setDragPosition(null);
|
||||
if (!open || !shouldLockBodyScroll) return;
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
return () => { document.body.style.overflow = previousOverflow; };
|
||||
}, [open, shouldLockBodyScroll]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open) return;
|
||||
const viewport={width:window.innerWidth,height:window.innerHeight};
|
||||
if(expanded){
|
||||
if(!expansionRestoreRef.current){
|
||||
const bounds=dialogRef.current?.getBoundingClientRect();
|
||||
if(bounds){
|
||||
expansionRestoreRef.current=rectRef.current??{left:bounds.left,top:bounds.top,width:bounds.width,height:bounds.height};
|
||||
const width=Math.min(960,viewport.width*0.8),height=Math.min(800,viewport.height*0.82);
|
||||
const prior=expansionRestoreRef.current;
|
||||
changeRect(fitWindow(expandedRect??{left:prior.left+(prior.width-width)/2,top:prior.top+(prior.height-height)/2,width,height},viewport,minimumRef.current));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(expansionRestoreRef.current){
|
||||
changeRect(fitWindow(expansionRestoreRef.current,viewport,minimumRef.current));
|
||||
expansionRestoreRef.current=null;
|
||||
return;
|
||||
}
|
||||
if (freeGeometry && !dragRef.current && !resizeRef.current) {
|
||||
// The modal move toggle already restores its local rectangle. An
|
||||
// uncontrolled floating window must retain it when toggled twice.
|
||||
if (placement === "center" && !onRectCommit && !rect && rectRef.current) return;
|
||||
const bounds=dialogRef.current?.getBoundingClientRect();
|
||||
if(bounds){
|
||||
initialRectRef.current ??= initialRect??{left:bounds.left,top:bounds.top,width:bounds.width,height:bounds.height};
|
||||
changeRect(fitWindow(rect??initialRectRef.current,{width:window.innerWidth,height:window.innerHeight},minimumRef.current));
|
||||
}
|
||||
}
|
||||
},[open,expanded,freeGeometry,rect?.left,rect?.top,rect?.width,rect?.height]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) { setDragPosition(null); setFloating(false); changeRect(null); initialRectRef.current = null; expansionRestoreRef.current = null; dragRef.current = null; resizeRef.current = null; }
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!draggable || !open) return;
|
||||
if (!canDrag || !open) return;
|
||||
const handlePointerMove = (event: globalThis.PointerEvent) => {
|
||||
const resizing = resizeRef.current;
|
||||
if (resizing && event.pointerId === resizing.pointerId) {
|
||||
gestureChanged.current = true;
|
||||
changeRect(resizeWindow(resizing.rect, resizing.edge, event.clientX - resizing.x, event.clientY - resizing.y, { width: window.innerWidth, height: window.innerHeight },minimumRef.current));
|
||||
return;
|
||||
}
|
||||
const drag = dragRef.current;
|
||||
const dialog = dialogRef.current;
|
||||
if (!drag || !dialog || event.pointerId !== drag.pointerId) return;
|
||||
const bounds = dialog.getBoundingClientRect();
|
||||
if (freeGeometry) {
|
||||
gestureChanged.current = true;
|
||||
changeRect(fitWindow({ left: event.clientX - drag.offsetX, top: event.clientY - drag.offsetY, width: bounds.width, height: bounds.height }, { width: window.innerWidth, height: window.innerHeight },minimumRef.current));
|
||||
return;
|
||||
}
|
||||
const left = Math.max(8, Math.min(window.innerWidth - bounds.width - 8, event.clientX - drag.offsetX));
|
||||
const top = Math.max(76, Math.min(window.innerHeight - bounds.height - 8, event.clientY - drag.offsetY));
|
||||
setDragPosition({ left, top });
|
||||
};
|
||||
const handlePointerUp = (event: globalThis.PointerEvent) => {
|
||||
const owned = dragRef.current?.pointerId === event.pointerId || resizeRef.current?.pointerId === event.pointerId;
|
||||
if (dragRef.current?.pointerId === event.pointerId) dragRef.current = null;
|
||||
if (resizeRef.current?.pointerId === event.pointerId) resizeRef.current = null;
|
||||
if (owned && gestureChanged.current && rectRef.current) { gestureChanged.current = false; commitRef.current?.({...rectRef.current}); }
|
||||
};
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
@@ -144,41 +295,75 @@ export function Window({
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
};
|
||||
}, [draggable, open]);
|
||||
}, [canDrag, freeGeometry, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!freeGeometry || !open) return;
|
||||
const fit = () => { if(rectRef.current) changeRect(fitWindow((expanded ? expandedRect : rect) ?? rectRef.current, { width: window.innerWidth, height: window.innerHeight },minimumRef.current)); };
|
||||
window.addEventListener("resize", fit);
|
||||
return () => window.removeEventListener("resize", fit);
|
||||
}, [freeGeometry, open, rect, expanded, expandedRect]);
|
||||
|
||||
if (!open || typeof document === "undefined") return null;
|
||||
|
||||
const allowBackdropClose = closeOnBackdrop ?? placement === "center";
|
||||
const allowBackdropClose = !isFloating && (closeOnBackdrop ?? placement === "center");
|
||||
|
||||
const handleBackdropPointerDown = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (allowBackdropClose && event.target === event.currentTarget) onClose();
|
||||
};
|
||||
|
||||
// Keep an owning window in its existing portal while its child is fullscreen.
|
||||
// Reparenting it into that child would form a DOM cycle and remount the renderer.
|
||||
const fullscreen = document.fullscreenElement;
|
||||
if (!portalHostRef.current || !fullscreen || !dialogRef.current?.contains(fullscreen)) {
|
||||
portalHostRef.current = fullscreen ?? document.body;
|
||||
}
|
||||
const baseStyle={...style,...(headerLayout==="adaptive"?{minWidth:Math.min(headerMinimum,Math.max(1,window.innerWidth-16))}:{})};
|
||||
return createPortal(
|
||||
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
|
||||
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} onPointerDown={handleBackdropPointerDown}>
|
||||
<WindowSuspensionContext.Provider value={suspend}><div className="nodedc-overlay nodedc-ui-root" style={suspended ? {display:"none"} : undefined} data-placement={placement} data-floating={isFloating || undefined} onPointerDown={handleBackdropPointerDown}>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
className={cn("nodedc-window nodedc-glass-material nodedc-material-rim", className)}
|
||||
data-expanded={expanded||undefined}
|
||||
data-header-layout={headerLayout}
|
||||
data-header-stacked={stackedTitle||undefined}
|
||||
data-material="glass-v4"
|
||||
data-glass-context={isFloating ? "scene" : undefined}
|
||||
data-size={size === "md" ? undefined : size}
|
||||
data-placement={placement}
|
||||
data-draggable={draggable ? "true" : undefined}
|
||||
data-draggable={canDrag ? "true" : undefined}
|
||||
data-resizable={freeGeometry || undefined}
|
||||
data-floating={isFloating || undefined}
|
||||
role="dialog"
|
||||
aria-modal={placement === "center" ? "true" : undefined}
|
||||
aria-modal={placement === "center" && !isFloating ? "true" : undefined}
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={subtitle ? descriptionId : undefined}
|
||||
tabIndex={-1}
|
||||
style={dragPosition ? { ...style, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : style}
|
||||
style={freeGeometry && floatingRect ? { ...baseStyle, position: "fixed", ...floatingRect, right: "auto", bottom: "auto", maxWidth: "none", maxHeight: "none" } : dragPosition ? { ...baseStyle, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : baseStyle}
|
||||
{...props}
|
||||
>
|
||||
<header
|
||||
{...dragHandleFocus}
|
||||
className="nodedc-window__head"
|
||||
tabIndex={freeGeometry ? 0 : undefined}
|
||||
aria-label={freeGeometry ? "Перемещение окна: стрелки; изменение размера: Shift и стрелки" : undefined}
|
||||
onKeyDown={(event) => {
|
||||
if (!freeGeometry || !floatingRect || event.target !== event.currentTarget || !event.key.startsWith("Arrow")) return;
|
||||
event.preventDefault();
|
||||
const dx = event.key === "ArrowLeft" ? -10 : event.key === "ArrowRight" ? 10 : 0;
|
||||
const dy = event.key === "ArrowUp" ? -10 : event.key === "ArrowDown" ? 10 : 0;
|
||||
const bounds = { width: window.innerWidth, height: window.innerHeight };
|
||||
const next = event.shiftKey ? resizeWindow(floatingRect, "se", dx, dy, bounds,minimumRef.current) : fitWindow({ ...floatingRect, left: floatingRect.left + dx, top: floatingRect.top + dy }, bounds,minimumRef.current);
|
||||
changeRect(next); commitRef.current?.(next);
|
||||
}}
|
||||
onPointerDown={(event) => {
|
||||
if (!draggable || event.button !== 0 || (event.target as HTMLElement).closest("button, input, select, textarea, a")) return;
|
||||
if (!canDrag || event.button !== 0 || (event.target as HTMLElement).closest("button, input, select, textarea, a")) return;
|
||||
const bounds = dialogRef.current?.getBoundingClientRect();
|
||||
if (!bounds) return;
|
||||
dragRef.current = { pointerId: event.pointerId, offsetX: event.clientX - bounds.left, offsetY: event.clientY - bounds.top };
|
||||
gestureChanged.current = false;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
event.preventDefault();
|
||||
}}
|
||||
>
|
||||
@@ -187,18 +372,36 @@ export function Window({
|
||||
{subtitle ? <p id={descriptionId} className="nodedc-window__subtitle">{subtitle}</p> : null}
|
||||
</div>
|
||||
<div className="nodedc-window__actions">
|
||||
{headerActions}
|
||||
{headerActionsPlacement === "before-move" && headerActions}
|
||||
{allowFloating && placement === "center" && <IconButton label={isFloating ? "Вернуть модальный режим" : "Свободное окно"} aria-pressed={isFloating} onClick={() => {
|
||||
dragRef.current = null; resizeRef.current = null;
|
||||
if (!isFloating) {
|
||||
const rect = dialogRef.current?.getBoundingClientRect();
|
||||
if (rect) changeRect(fitWindow(rectRef.current ?? { left: rect.left, top: rect.top, width: rect.width, height: rect.height }, { width: window.innerWidth, height: window.innerHeight },minimumRef.current));
|
||||
}
|
||||
if (rectRef.current) commitRef.current?.({...rectRef.current});
|
||||
setFloating(!isFloating);
|
||||
onFloatingChange?.(!isFloating);
|
||||
}}><Icon name="move" /></IconButton>}
|
||||
{headerActionsPlacement === "before-close" && headerActions}
|
||||
<button type="button" className="nodedc-window__close" aria-label={closeLabel} onClick={onClose}>
|
||||
<Icon name="close" size={16} strokeWidth={1.6} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
{freeGeometry && windowResizeEdges.map(edge => <div key={edge} className="nodedc-window__resize" data-edge={edge} aria-hidden="true" onPointerDown={event => {
|
||||
if (event.button !== 0 || !floatingRect) return;
|
||||
resizeRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, rect: floatingRect, edge };
|
||||
gestureChanged.current = false;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
}} />)}
|
||||
<div className="nodedc-window__body">{children}</div>
|
||||
{footer ? <footer className="nodedc-window__footer">{footer}</footer> : null}
|
||||
</div>
|
||||
</div>
|
||||
</InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
|
||||
document.fullscreenElement ?? document.body,
|
||||
</WindowSuspensionContext.Provider></InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
|
||||
portalHostRef.current,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import {createContext} from 'react';
|
||||
/** A detached editor hides its owning window without unmounting its contents. */
|
||||
export const WindowSuspensionContext=createContext<null|(()=>()=>void)>(null);
|
||||
@@ -1,3 +1,4 @@
|
||||
import {dragHandleFocus} from './dragHandleFocus.js';
|
||||
import {
|
||||
useEffect,
|
||||
useId,
|
||||
@@ -397,6 +398,7 @@ export function WorkspaceWindow({
|
||||
}}
|
||||
>
|
||||
<header
|
||||
{...dragHandleFocus}
|
||||
ref={headRef}
|
||||
className="nodedc-workspace-window__head"
|
||||
tabIndex={maximized ? -1 : 0}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import type {FocusEvent, KeyboardEvent, PointerEvent} from 'react';
|
||||
|
||||
/** A pointer grab must not inherit the previous input's keyboard focus ring. */
|
||||
export const dragHandleFocus = {
|
||||
onPointerDownCapture(event: PointerEvent<HTMLElement>) {
|
||||
if (event.button !== 0 || (event.target as HTMLElement).closest('button,input,select,textarea,a,[role=slider]')) return;
|
||||
event.currentTarget.dataset.pointerFocus = 'true';
|
||||
},
|
||||
onKeyDownCapture(event: KeyboardEvent<HTMLElement>) {
|
||||
if (event.target === event.currentTarget) delete event.currentTarget.dataset.pointerFocus;
|
||||
},
|
||||
onBlur(event: FocusEvent<HTMLElement>) {
|
||||
if (event.target === event.currentTarget) delete event.currentTarget.dataset.pointerFocus;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import type {DockRect} from '@nodedc/ui-core';
|
||||
/** Only corners on both outer edges are rounded; all internal seams stay square. */
|
||||
export function editorDockCorners(rect:DockRect,area:DockRect):string {
|
||||
const same=(a:number,b:number)=>Math.abs(a-b)<.01;
|
||||
const left=same(rect.left,area.left),top=same(rect.top,area.top);
|
||||
const right=same(rect.left+rect.width,area.left+area.width),bottom=same(rect.top+rect.height,area.top+area.height);
|
||||
return [top&&left?'top-left':'',top&&right?'top-right':'',bottom&&right?'bottom-right':'',bottom&&left?'bottom-left':''].filter(Boolean).join(' ');
|
||||
}
|
||||
@@ -14,7 +14,10 @@ export * from "./ConfirmationModal.js";
|
||||
export * from "./Dropdown.js";
|
||||
export * from "./DragDrop.js";
|
||||
export * from "./DockLayout.js";
|
||||
export {decodeDockTree, dockIds, balancedDockTree, reconcileDockTree, pruneDockTree, moveDockPanel, resizeDockSplit, dockRects, dockPosition, type DockTree, type DockMove, type DockRect, type DockPosition} from "@nodedc/ui-core";
|
||||
export * from "./EditorDockLayout.js";
|
||||
export * from "./EditorWorkspace.js";
|
||||
export {decodeEditorDock,dockEditorTool,editorDockTarget,mergeEditorDockRatios,type EditorDockState} from "@nodedc/ui-core";
|
||||
export {decodeDockTree, dockIds, balancedDockTree, reconcileDockTree, pruneDockTree, moveDockPanel, resizeDockSplit, dockRects, dockPosition, dockMoveAtPoint, type DockTree, type DockMove, type DockRect, type DockPosition} from "@nodedc/ui-core";
|
||||
export * from "./Field.js";
|
||||
export * from "./FeatureSettingsWindow.js";
|
||||
export * from "./Glass.js";
|
||||
@@ -44,3 +47,16 @@ export * from "./LandingStage.js";
|
||||
export {KeyButton, type KeyButtonProps} from './KeyButton.js';
|
||||
|
||||
export type {DockMinimum, DockMinimums} from "@nodedc/ui-core";
|
||||
|
||||
export {Tree,type TreeNode,type TreeProps,type TreeSelectionGesture} from "./Tree.js";
|
||||
|
||||
export * from "./ResizableViewport.js";
|
||||
export {useApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
|
||||
|
||||
export {SceneAnnotation} from "./SceneAnnotation.js";
|
||||
|
||||
export {LevelButton,type LevelButtonProps} from "./LevelButton.js";
|
||||
|
||||
export {Tooltip,type TooltipProps} from "./Tooltip.js";
|
||||
|
||||
export {TooltipProvider} from "./TooltipProvider.js";
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import type {CSSProperties} from 'react';
|
||||
export type LevelButtonGeometry={width:number;height:number;radius?:number};
|
||||
/** Keep type and padding proportional when the operator chooses a tiny indicator. */
|
||||
export function levelButtonGeometry(value:LevelButtonGeometry|undefined,characters:number):CSSProperties{
|
||||
if(!value)return {};
|
||||
const bounded=(n:number|undefined,fallback:number,min:number,max:number)=>typeof n==='number'&&Number.isFinite(n)?Math.max(min,Math.min(max,n)):fallback;
|
||||
const width=bounded(value.width,115,32,4096),height=bounded(value.height,46,12,1024),radius=bounded(value.radius,999,0,4096);
|
||||
const scale=Math.min(1,height/24,width/Math.max(64,(characters+2)*8));
|
||||
return {width,minWidth:width,height,minHeight:height,borderRadius:radius,flexShrink:0,fontSize:`calc(var(--nodedc-font-size-md) * ${scale})`,lineHeight:1,padding:`calc(0.25rem * ${scale}) calc(var(--nodedc-space-2) * ${scale})`};
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Screen sampling requires a secure context and an explicit trusted click. No screenshots are retained. */
|
||||
export type ScreenColorPicker = new () => { open(options: { signal: AbortSignal }): Promise<{ sRGBHex: string }> };
|
||||
export function screenColorPicker(): ScreenColorPicker | undefined {
|
||||
return (globalThis as typeof globalThis & { EyeDropper?: ScreenColorPicker }).EyeDropper;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Suppress native tooltips only during interaction; preserve changing titles and ARIA. */
|
||||
export class TooltipTitles {
|
||||
private titles=new Map<Element,string>();
|
||||
private description:{element:Element;id:string;label?:string}|null=null;
|
||||
text(element:Element){return element.getAttribute('data-nodedc-tooltip')??this.titles.get(element)??element.getAttribute('title');}
|
||||
find(start:Element){for(let element:Element|null=start;element;element=element.parentElement){const text=element.getAttribute('data-nodedc-tooltip')??element.getAttribute('title');if(text!==null)return text.trim()?{element,text}:null;}return null;}
|
||||
suppress(start:Element){for(let element:Element|null=start;element;element=element.parentElement){const text=element.getAttribute('title');if(text!==null){this.titles.set(element,text);element.removeAttribute('title');}}}
|
||||
describe(element:Element,id:string){
|
||||
const ids=new Set((element.getAttribute('aria-describedby')??'').split(/\s+/).filter(Boolean));ids.add(id);element.setAttribute('aria-describedby',[...ids].join(' '));
|
||||
let label=this.description?.label;
|
||||
if(!element.hasAttribute('aria-label')&&!element.hasAttribute('aria-labelledby')&&!element.textContent?.trim()){
|
||||
label=this.text(element)??undefined;if(label)element.setAttribute('aria-label',label);
|
||||
}
|
||||
this.description={element,id,label};
|
||||
}
|
||||
restore(){
|
||||
for(const [element,text] of this.titles)if(!element.hasAttribute('title'))element.setAttribute('title',text);this.titles.clear();
|
||||
if(this.description){const {element,id,label}=this.description;const ids=(element.getAttribute('aria-describedby')??'').split(/\s+/).filter(value=>value&&value!==id);if(ids.length)element.setAttribute('aria-describedby',ids.join(' '));else element.removeAttribute('aria-describedby');if(label&&element.getAttribute('aria-label')===label)element.removeAttribute('aria-label');this.description=null;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Range follows displayed rows only; folded/filtered-out branches cannot leak in. */
|
||||
export function treeSelectionRange(rows:readonly string[],anchor:string|null,target:string):string[]{
|
||||
const a=rows.indexOf(anchor??target),b=rows.indexOf(target);
|
||||
return a<0||b<0?[target]:rows.slice(Math.min(a,b),Math.max(a,b)+1);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Viewport-local geometry shared by pointer and keyboard window manipulation. */
|
||||
export type WindowRect = { left: number; top: number; width: number; height: number };
|
||||
export type ResizeEdge = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
|
||||
export const windowResizeEdges: ResizeEdge[] = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];
|
||||
type Bounds = { width: number; height: number };
|
||||
const defaultMinimum: Bounds = { width: 320, height: 200 };
|
||||
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value));
|
||||
export function fitWindow(rect: WindowRect, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
|
||||
const width = clamp(rect.width, Math.max(1, Math.min(minimum.width, bounds.width - 16)), Math.max(1, bounds.width - 16));
|
||||
const height = clamp(rect.height, Math.max(1, Math.min(minimum.height, bounds.height - 16)), Math.max(1, bounds.height - 16));
|
||||
return { width, height, left: clamp(rect.left, 8, Math.max(8, bounds.width - width - 8)), top: clamp(rect.top, 8, Math.max(8, bounds.height - height - 8)) };
|
||||
}
|
||||
export function resizeWindow(rect: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
|
||||
const r = fitWindow(rect, bounds, minimum), right = r.left + r.width, bottom = r.top + r.height;
|
||||
const minWidth = Math.max(1, Math.min(minimum.width, bounds.width - 16)), minHeight = Math.max(1, Math.min(minimum.height, bounds.height - 16));
|
||||
const left = edge.includes('w') ? clamp(r.left + dx, 8, right - minWidth) : r.left;
|
||||
const top = edge.includes('n') ? clamp(r.top + dy, 8, bottom - minHeight) : r.top;
|
||||
const endX = edge.includes('e') ? clamp(right + dx, left + minWidth, bounds.width - 8) : right;
|
||||
const endY = edge.includes('s') ? clamp(bottom + dy, top + minHeight, bounds.height - 8) : bottom;
|
||||
return { left, top, width: endX - left, height: endY - top };
|
||||
}
|
||||
+121
-34
@@ -6,90 +6,177 @@
|
||||
"id": "calendar-popover",
|
||||
"classification": "planned-primitive",
|
||||
"priority": "P1",
|
||||
"referenceSources": ["launcher", "task-manager"],
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"task-manager"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["dropdown", "button", "field"],
|
||||
"requiredBehavior": ["portal", "locale-aware labels", "single date", "date range", "keyboard navigation"],
|
||||
"dependsOn": [
|
||||
"dropdown",
|
||||
"button",
|
||||
"field"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"portal",
|
||||
"locale-aware labels",
|
||||
"single date",
|
||||
"date range",
|
||||
"keyboard navigation"
|
||||
],
|
||||
"reasonNotBaseline": "Current Launcher and Task Manager implementations must be reconciled before one API is declared canonical."
|
||||
},
|
||||
{
|
||||
"id": "profile-menu",
|
||||
"classification": "planned-pattern",
|
||||
"priority": "P1",
|
||||
"referenceSources": ["launcher", "task-manager"],
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"task-manager"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["dropdown", "button", "status-badge"],
|
||||
"requiredBehavior": ["avatar trigger", "identity summary", "role/workspace switch", "logout action"],
|
||||
"dependsOn": [
|
||||
"dropdown",
|
||||
"button",
|
||||
"status-badge"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"avatar trigger",
|
||||
"identity summary",
|
||||
"role/workspace switch",
|
||||
"logout action"
|
||||
],
|
||||
"reasonNotBaseline": "Identity and role data contracts differ between Hub and Ops and must remain application-owned."
|
||||
},
|
||||
{
|
||||
"id": "action-dropdown",
|
||||
"classification": "planned-pattern",
|
||||
"priority": "P1",
|
||||
"referenceSources": ["task-manager", "launcher"],
|
||||
"referenceSources": [
|
||||
"task-manager",
|
||||
"launcher"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["dropdown"],
|
||||
"requiredBehavior": ["commands", "disabled rows", "danger row", "optional groups", "keyboard navigation"],
|
||||
"dependsOn": [
|
||||
"dropdown"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"commands",
|
||||
"disabled rows",
|
||||
"danger row",
|
||||
"optional groups",
|
||||
"keyboard navigation"
|
||||
],
|
||||
"reasonNotBaseline": "Floating behavior is stable; command-row API still needs validation against Ops consumers."
|
||||
},
|
||||
{
|
||||
"id": "data-table",
|
||||
"classification": "planned-pattern",
|
||||
"priority": "P1",
|
||||
"referenceSources": ["launcher", "task-manager"],
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"task-manager"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["button", "select", "status-badge", "field"],
|
||||
"requiredBehavior": ["toolbar", "responsive overflow", "row actions", "editable cells", "loading", "empty state"],
|
||||
"dependsOn": [
|
||||
"button",
|
||||
"select",
|
||||
"status-badge",
|
||||
"field"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"toolbar",
|
||||
"responsive overflow",
|
||||
"row actions",
|
||||
"editable cells",
|
||||
"loading",
|
||||
"empty state"
|
||||
],
|
||||
"reasonNotBaseline": "The library should own presentation and interaction slots, not adopt Launcher entity schemas or Plane table models."
|
||||
},
|
||||
{
|
||||
"id": "avatar-stack",
|
||||
"classification": "planned-primitive",
|
||||
"priority": "P1",
|
||||
"referenceSources": ["engine", "task-manager"],
|
||||
"referenceSources": [
|
||||
"engine",
|
||||
"task-manager"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["dropdown"],
|
||||
"requiredBehavior": ["overflow count", "presence", "picker mode", "fallback initials"],
|
||||
"dependsOn": [
|
||||
"dropdown"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"overflow count",
|
||||
"presence",
|
||||
"picker mode",
|
||||
"fallback initials"
|
||||
],
|
||||
"reasonNotBaseline": "Engine picker behavior and Task Manager presence semantics must not be coupled accidentally."
|
||||
},
|
||||
{
|
||||
"id": "service-rail-card",
|
||||
"classification": "product-pattern",
|
||||
"priority": "P2",
|
||||
"referenceSources": ["launcher"],
|
||||
"referenceSources": [
|
||||
"launcher"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["glass-surface", "status-badge", "button"],
|
||||
"requiredBehavior": ["ambient media", "access status", "selected state", "open/request action"],
|
||||
"dependsOn": [
|
||||
"glass-surface",
|
||||
"status-badge",
|
||||
"button"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"ambient media",
|
||||
"access status",
|
||||
"selected state",
|
||||
"open/request action"
|
||||
],
|
||||
"reasonNotBaseline": "Likely reusable for product catalogs, but current contract is tightly connected to Launcher service data."
|
||||
},
|
||||
{
|
||||
"id": "work-item-card",
|
||||
"classification": "product-pattern",
|
||||
"priority": "P2",
|
||||
"referenceSources": ["task-manager"],
|
||||
"referenceSources": [
|
||||
"task-manager"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["glass-surface", "avatar-stack", "status-badge", "action-dropdown"],
|
||||
"requiredBehavior": ["selected state", "drag state", "assignees", "dates", "quick actions"],
|
||||
"dependsOn": [
|
||||
"glass-surface",
|
||||
"avatar-stack",
|
||||
"status-badge",
|
||||
"action-dropdown"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"selected state",
|
||||
"drag state",
|
||||
"assignees",
|
||||
"dates",
|
||||
"quick actions"
|
||||
],
|
||||
"reasonNotBaseline": "The visual pattern is mature, but task-domain fields must be separated from the reusable card shell."
|
||||
},
|
||||
{
|
||||
"id": "tooltip",
|
||||
"classification": "missing-primitive",
|
||||
"priority": "P2",
|
||||
"referenceSources": ["launcher", "task-manager", "engine"],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["dropdown"],
|
||||
"requiredBehavior": ["hover", "focus", "delay", "viewport placement"],
|
||||
"reasonNotBaseline": "Needs a small dedicated accessibility contract rather than reuse of an application tooltip."
|
||||
},
|
||||
{
|
||||
"id": "empty-loading-error",
|
||||
"classification": "planned-pattern",
|
||||
"priority": "P2",
|
||||
"referenceSources": ["launcher", "seo", "task-manager"],
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"seo",
|
||||
"task-manager"
|
||||
],
|
||||
"expectedPackage": "@nodedc/ui-react",
|
||||
"dependsOn": ["button", "status-badge"],
|
||||
"requiredBehavior": ["empty message", "retry", "loading progress", "fatal error"],
|
||||
"dependsOn": [
|
||||
"button",
|
||||
"status-badge"
|
||||
],
|
||||
"requiredBehavior": [
|
||||
"empty message",
|
||||
"retry",
|
||||
"loading progress",
|
||||
"fatal error"
|
||||
],
|
||||
"reasonNotBaseline": "Copy and domain actions vary; the layout contract still needs examples from all product families."
|
||||
}
|
||||
]
|
||||
|
||||
+345
-43
@@ -1,6 +1,28 @@
|
||||
{
|
||||
"schemaVersion": "1.0.0",
|
||||
"components": [
|
||||
{
|
||||
"id": "mission-theme",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-core",
|
||||
"exports": [
|
||||
"applyNodedcTheme",
|
||||
"missionDarkTheme",
|
||||
"missionLightTheme"
|
||||
],
|
||||
"domContract": [
|
||||
"data-nodedc-theme",
|
||||
"data-nodedc-appearance",
|
||||
"data-nodedc-edges"
|
||||
],
|
||||
"summary": "Canonical Mission Core theme foundation shared by React, DOM and body portals.",
|
||||
"rules": [
|
||||
"Colors belong to tokens/themes.css; applications select a preset and may provide an explicit user accent.",
|
||||
"ApplicationPanel → SettingsCard → fields matches Mission Core forms. Collection entries may use GlassSurface tone=group; never wrap field grids in recessed soft surfaces or add a card around a list of cards.",
|
||||
"No decorative outlines; keyboard focus, disabled states and semantic error/success indicators remain visible."
|
||||
],
|
||||
"documentation": "../docs/THEMING.md"
|
||||
},
|
||||
{
|
||||
"id": "progress-button",
|
||||
"status": "baseline",
|
||||
@@ -83,9 +105,10 @@
|
||||
"nodedc-glass",
|
||||
"nodedc-glass-material",
|
||||
"nodedc-map-glass",
|
||||
"nodedc-material-rim"
|
||||
"nodedc-material-rim",
|
||||
"nodedc-viewport-surface"
|
||||
],
|
||||
"summary": "Matte application surfaces, the Engine V4 modal material and the light translucent surface used over Cesium imagery.",
|
||||
"summary": "Matte application surfaces, the Engine V4 modal material and the light translucent surface used over Cesium imagery. Scene overlays reuse V4 blur and tint with independent translucent density.",
|
||||
"anatomy": [
|
||||
"theme-provided surface",
|
||||
"modal tint",
|
||||
@@ -98,7 +121,8 @@
|
||||
"default",
|
||||
"strong",
|
||||
"soft",
|
||||
"map"
|
||||
"map",
|
||||
"scene"
|
||||
],
|
||||
"radiusVariants": [
|
||||
"card",
|
||||
@@ -108,12 +132,14 @@
|
||||
],
|
||||
"rules": [
|
||||
"Geometry is invariant across application themes.",
|
||||
"Opt-in appearance=mission applies the qualified Mission Core operator surfaces, avatars and dot statuses across portals without changing geometry.",
|
||||
"The default Mission Core foundation supplies surfaces, avatars and dot statuses across portals without changing geometry.",
|
||||
"Compact rails of canonical round actions use the pill radius; consumers do not recreate it with a local border radius.",
|
||||
"A material rim is a glass highlight, not a hard product-colored border.",
|
||||
"Nested surfaces must use a softer tone to avoid card-inside-card noise.",
|
||||
"GlassyMaterialSurface is restricted to modal Windows and the draggable Inspector.",
|
||||
"MapGlassSurface is restricted to overlays over Cesium/map imagery and must match the map Toolbar translucency."
|
||||
"Form collections use tone=group, the same neutral material as SettingsCard. tone=soft is a recessed secondary canvas, never a form-grid background.",
|
||||
"GlassMaterialSurface supports modal/Inspector floating material and explicit context=scene telemetry overlays over rendered imagery; ordinary panels remain matte. Optional material and radiusPx apply appearance to one instance without changing the global theme.",
|
||||
"MapGlassSurface is restricted to overlays over Cesium/map imagery and must match the map Toolbar translucency.",
|
||||
"Theme edges=flat removes decorative rims and active outlines across portals; keyboard focus uses contrasting fill without changing geometry.",
|
||||
"Owner 2026-11-14: all backed UI inside every map/3D/camera/replay viewport uses scene Glass V4, independent of renderer. Use GlassMaterialSurface context=scene or nodedc-viewport-surface for an existing semantic overlay. Never tint the renderer itself. See docs/VIEWPORT_UI.md."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -150,13 +176,16 @@
|
||||
],
|
||||
"rules": [
|
||||
"Icon-only actions are circular by default.",
|
||||
"IconButton surface=none keeps the normal hit target and focus while removing the disc. Favorite stars use outline/filled glyph states; see docs/FAVORITES.md.",
|
||||
"Groups over rendered imagery use nodedc-scene-controls: Button, IconButton, Select and SegmentedControl share the opaque field surface and interaction states; all viewport controls use the same 70-percent geometry, and rails must not inherit the translucent header background.",
|
||||
"Controlled toggle actions expose aria-pressed and use the canonical active surface without changing geometry.",
|
||||
"Filled accent actions derive foreground contrast from the actual accent.",
|
||||
"Destructive actions remain neutral until confirmation unless danger is the principal message.",
|
||||
"loading displays one centered indicator inside the initiating action, disables repeat activation and preserves dimensions and accessible name. Never place its spinner beside or below the action group.",
|
||||
"Primary tone=neutral is white when enabled and gray when disabled in every theme/accent; use it for accent-independent operator actions without local CSS overrides.",
|
||||
"nodedc-viewport-controls is the shared geometry context for every viewer toolbar: 0.7 times standard controls, including icons, fonts and rims. It normalizes legacy compact/dense variants, never compounds in nested groups, and excludes portaled menus/settings and scene content."
|
||||
"nodedc-viewport-controls is the shared geometry context for every viewer toolbar: 0.7 times standard controls, including icons, fonts and rims. It normalizes legacy compact/dense variants, never compounds in nested groups, and excludes portaled menus/settings and scene content.",
|
||||
"Viewport action scopes apply scene Glass V4 to normal backgrounds; selected/disabled/hover and focus semantics are preserved. No local nearly transparent substitutes.",
|
||||
"Viewport round action rails keep their group container transparent: glass belongs to each circle, not a shared capsule."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -228,7 +257,8 @@
|
||||
"Labels and validation copy are part of the field contract.",
|
||||
"Keyboard focus changes the surface and remains visible without a browser-blue outline.",
|
||||
"Browser autofill retains the canonical field material, text and caret; keyboard focus remains visible.",
|
||||
"FieldFrame labelPlacement=below is the compact muted caption variant for header selectors; above remains the default."
|
||||
"FieldFrame labelPlacement=below is the compact muted caption variant for header selectors; above remains the default.",
|
||||
"appearance=plain renders immediately editable detail copy without a permanent plate; empty labels require aria-label, textarea grows to content, keyboard focus remains visible."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -284,7 +314,8 @@
|
||||
"The browser places the caret at the clicked character, preserves native drag or keyboard selection, and replaces the selected substring on typing without pointer-state interception.",
|
||||
"Editor foreground and caret switch automatically between theme text and on-accent tokens according to the actual fill edge beneath the value area.",
|
||||
"The editor has no separate background box and keeps focus across parent window rerenders and pointer leave.",
|
||||
"Editor keyboard events do not bubble into enclosing Window shortcuts."
|
||||
"Editor keyboard events do not bubble into enclosing Window shortcuts.",
|
||||
"variant=rail is the single-value horizontal counterpart of the thin vertical section scale: 0.2 control-height shaft, minimum 24 px transparent target, value above, native arrows/Home/End, disabled and value underline focus. No enclosing surface, glass, outline, shadow or exact-value editor. Consumer owns placement and visibility timing."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -304,11 +335,14 @@
|
||||
"hue slider",
|
||||
"quick colors",
|
||||
"portal palette",
|
||||
"keyboard spectrum adjustment"
|
||||
"keyboard spectrum adjustment",
|
||||
"explicit screen eyedropper with cancellation; system palette fallback when EyeDropper is unavailable"
|
||||
],
|
||||
"rules": [
|
||||
"Do not expose a browser-native color dialog as the product runtime UI.",
|
||||
"The palette owns choice geometry; the consumer owns color validation, persistence and domain reaction."
|
||||
"The palette owns choice geometry; the consumer owns color validation, persistence and domain reaction.",
|
||||
"HEX text keeps incomplete drafts; valid six-digit colors apply live, invalid drafts revert on blur/Escape, Enter commits; external undo updates the field.",
|
||||
"The themed palette remains primary. Screen sampling starts only on a trusted button click, never pointer leave; unsupported browsers expose an explicit system-palette fallback. No screenshots are captured or stored. Escape, closing or unmount cancels sampling without applying a color.",
|
||||
"Spectrum has no decorative perimeter border; sampling marker and keyboard focus remain visible."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -324,12 +358,15 @@
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-dropdown-surface",
|
||||
"nodedc-dropdown-option"
|
||||
"nodedc-dropdown-option",
|
||||
"nodedc-viewport-surface"
|
||||
],
|
||||
"summary": "Shared portal/fixed floating layer for action and selection menus.",
|
||||
"behavior": [
|
||||
"portal to active fullscreen element or document body",
|
||||
"viewport clamp",
|
||||
"scene Glass V4 via surfaceClassName nodedc-viewport-surface",
|
||||
"content resize repositions an open dropdown within viewport bounds",
|
||||
"vertical flip",
|
||||
"capture-phase outside pointer close before scene tool interception",
|
||||
"optional outside-pointer consumer for editing viewports",
|
||||
@@ -380,7 +417,8 @@
|
||||
"Split is the Engine form: a separate value surface and a 46 px toggle separated by an 8 px gap.",
|
||||
"Inline is a compact label-only toolbar trigger without a persistent surface or chevron; its menu and keyboard behavior remain canonical.",
|
||||
"Integrated Select is forbidden inside Inspector; use InspectorSelectField so the visible label is above a full-width split control.",
|
||||
"The portal menu preserves its source-family row geometry instead of inheriting card radii."
|
||||
"The portal menu preserves its source-family row geometry instead of inheriting card radii.",
|
||||
"Split Select accepts shape=pill to align its separate toggle with circular workspace actions."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -389,17 +427,20 @@
|
||||
"package": "@nodedc/ui-react",
|
||||
"exports": [
|
||||
"Window",
|
||||
"WindowFooterActions"
|
||||
"WindowFooterActions",
|
||||
"WindowRect"
|
||||
],
|
||||
"domPackage": "@nodedc/ui-dom",
|
||||
"domExports": [
|
||||
"createModalController"
|
||||
"createModalController",
|
||||
"createModalSizeController",
|
||||
"fitModalSize"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-overlay",
|
||||
"nodedc-window"
|
||||
],
|
||||
"summary": "Canonical controlled window for modal and right-side panel presentations, with optional headerActions beside close.",
|
||||
"summary": "Canonical controlled window with a move toggle between centered modal and draggable, resizable modeless presentation.",
|
||||
"behavior": [
|
||||
"portal to active fullscreen element or body",
|
||||
"focus entry",
|
||||
@@ -408,9 +449,14 @@
|
||||
"Escape close",
|
||||
"backdrop close policy",
|
||||
"modal-only body scroll lock",
|
||||
"optional bounded dragging for modeless inspectors"
|
||||
"optional bounded dragging for modeless inspectors",
|
||||
"move toggle: preserve mounted contents and current size; remove dimming, backdrop close, scroll lock and focus trap; header drag and eight invisible resize regions",
|
||||
"Escape and Tab belong to the focused or topmost visible modal; parent windows do not dismiss behind nested settings.",
|
||||
"An embedded fullscreen viewport keeps its owning window mounted at the existing portal host; Escape restores the viewport and Tab stays inside its visible controls.",
|
||||
"DOM modal resizing shares eight canonical edge handles, centered viewport bounds and keyboard Shift+arrow control; onSizeCommit runs only for completed user changes."
|
||||
],
|
||||
"rules": [
|
||||
"headerActionsPlacement=before-close places context actions between the move toggle and close in both visual and keyboard order; the default preserves existing consumers.",
|
||||
"WindowFooterActions aligns modal actions to the trailing edge, including a footer with only one action group; actions wrap within narrow windows.",
|
||||
"Centered windows at narrow widths subtract both overlay gutters from their maximum width and height.",
|
||||
"Open state belongs to the application; focus/layer behavior belongs to the component.",
|
||||
@@ -418,7 +464,17 @@
|
||||
"A right-side inspector is modeless by default: no dimming, no backdrop blur, no backdrop close, no focus trap and no body scroll lock.",
|
||||
"A draggable inspector moves by its header and remains clamped to the viewport.",
|
||||
"Closing a modeless inspector is never gated by autosave; preserve the draft, close immediately and report persistence failure through ToastStack.",
|
||||
"Operational copy inside Window uses component typography tokens; browser-default paragraph or heading sizes are forbidden."
|
||||
"Operational copy inside Window uses component typography tokens; browser-default paragraph or heading sizes are forbidden.",
|
||||
"Centered windows expose the move toggle by default; allowFloating opts a workflow out. Returning to modal restores canonical centered geometry; uncontrolled windows clear floating geometry on close.",
|
||||
"Floating header supports arrow-key movement and Shift+arrow resizing. Bounds stay inside the viewport. Resize affordances have no hover decoration.",
|
||||
"Inspectors inside a Window use its full available content width.",
|
||||
"End inspectors opt into resizable with an optional initialRect; existing eight edge geometry and keyboard resize are shared with floating windows.",
|
||||
"Application-owned rect restores modeless window geometry on reopen and external undo/import. onRectCommit reports one completed drag/resize or keyboard step; viewport fitting never overwrites saved geometry.",
|
||||
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions.",
|
||||
"Drag headers never draw perimeter outlines or inherit keyboard-focus fill on pointer grab. Keyboard focus remains visible through the canonical surface; arrows, Shift+arrows and docking shortcuts remain available.",
|
||||
"Detached center windows automatically use scene Glass V4; fixed confirmations opt out of detachment with allowFloating=false. Unsaved profile confirmation is owned by the application.",
|
||||
"floating/onFloatingChange and rect/onRectCommit allow durable application-owned presentation by window kind, independent of the currently displayed entity. Reopening restores mode and fitted geometry. Fixed confirmations do not inherit this state.",
|
||||
"Adaptive headers keep actions on one row, place the full title below before clipping, and derive the resize minimum from actual actions. Expanded media opens at a moderate size and remains resizable. Separate expandedRect/onExpandedRectCommit preferences restore its user-chosen position and dimensions; returning restores regular geometry."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -456,7 +512,9 @@
|
||||
"Rectangle, maximized state, visibility, activation and z-order are controlled by the application.",
|
||||
"resizeIndicator=false hides only the corner glyph; pointer hit area, cursor and keyboard resizing remain available.",
|
||||
"Use WorkspaceWindow for auxiliary views inside a stage; modal workflows and viewport inspectors continue to use Window.",
|
||||
"Dragging and resizing remain clamped when the workspace changes size, including when it becomes smaller than the requested minimum."
|
||||
"Dragging and resizing remain clamped when the workspace changes size, including when it becomes smaller than the requested minimum.",
|
||||
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions.",
|
||||
"Drag headers never draw perimeter outlines or inherit keyboard-focus fill on pointer grab. Keyboard focus remains visible through the canonical surface; arrows, Shift+arrows and docking shortcuts remain available."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -500,7 +558,7 @@
|
||||
"behavior": [
|
||||
"controlled percentage",
|
||||
"optional resizable separator",
|
||||
"line or invisible separator appearance with retained keyboard focus",
|
||||
"line or invisible separator appearance with retained keyboard focus; pointer resize never paints the invisible divider",
|
||||
"pointer capture drag",
|
||||
"Arrow/Home/End keyboard sizing",
|
||||
"ARIA separator range",
|
||||
@@ -650,14 +708,18 @@
|
||||
"behavior": [
|
||||
"portal dropdown",
|
||||
"profile identity card",
|
||||
"optional pressed state and controlled region on independent header action; its selected circle and glyph use the active IconButton colors, including on hover",
|
||||
"theme-independent cover",
|
||||
"action links and callbacks",
|
||||
"outside pointer and Escape close"
|
||||
"outside pointer and Escape close",
|
||||
"responsive profile label hides with the shared mobile header layout"
|
||||
],
|
||||
"rules": [
|
||||
"The component owns menu geometry and profile presentation; the application owns settings, profile and logout actions.",
|
||||
"Use the existing Dropdown engine so the menu is never clipped by the fixed application header.",
|
||||
"Do not embed product permissions or sharing rules in the visual menu."
|
||||
"Do not embed product permissions or sharing rules in the visual menu.",
|
||||
"The default header composes HeaderProfileButton, an independent menu IconButton and HeaderAvatar using the existing header geometry. Application settings belong inside this menu; do not add an adjacent settings button or another HeaderProfile wrapper.",
|
||||
"Optional headerAction separates the middle icon action from the avatar/profile trigger; without it legacy behavior is preserved."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -696,7 +758,8 @@
|
||||
"exports": [
|
||||
"ApplicationShell",
|
||||
"ApplicationPanel",
|
||||
"useApplicationWorkspace"
|
||||
"useApplicationWorkspace",
|
||||
"useApplicationPanelFullscreen"
|
||||
],
|
||||
"domPackage": "@nodedc/ui-dom",
|
||||
"domExports": [
|
||||
@@ -722,14 +785,18 @@
|
||||
"expanded content replaces stage",
|
||||
"global utility actions remain in the panel header across sections",
|
||||
"mobile panels use the available viewport sequentially",
|
||||
"independent content scrolling"
|
||||
"independent content scrolling",
|
||||
"the outer stage boundary clips overflow without becoming a focus-scroll container"
|
||||
],
|
||||
"rules": [
|
||||
"The bottom Launcher service rail is product-specific and is not part of the general application template.",
|
||||
"Desktop page gap is 20 px and navigation width follows the Launcher 332–352 px range.",
|
||||
"Shared navigationCollapsed state contracts the left column to a 4.55rem icon rail, preserves workspace identity and leaves the end column full-width. Width and content offset animate together with reduced-motion support.",
|
||||
"Applications supply routes, profile data, stage media and panel content without changing shell geometry.",
|
||||
"Light panels use the SEO white surface and shadow tokens rather than a dark shell with inverted text.",
|
||||
"A layout-level save action belongs to ApplicationPanel.utilityActions and is never duplicated inside individual content cards."
|
||||
"A layout-level save action belongs to ApplicationPanel.utilityActions and is never duplicated inside individual content cards.",
|
||||
"ApplicationPanel allowFullscreen exposes an owned full-window context; the whole panel and its header move atomically, preserving the renderer and body-portaled inspectors.",
|
||||
"ApplicationPanel establishes md/13px operational typography independent of the host; its page title alone uses title/18px. Semantic section headings remain md; explanatory copy uses Description/sm."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -763,6 +830,8 @@
|
||||
"viewport container scope with local edge reveal",
|
||||
"native tooltips with keyboard shortcut hints",
|
||||
"optional canonical dropdown for toolbar item menus",
|
||||
"viewport-scoped buttons share scene Glass V4; the rail stays transparent",
|
||||
"bounded menuWidth for rich inspectors; default remains 220 px",
|
||||
"theme-independent geometry",
|
||||
"menus outside maximum magnified icon envelope",
|
||||
"bounded triangle intent corridor before sibling menu activation",
|
||||
@@ -811,10 +880,10 @@
|
||||
"domContract": [
|
||||
"nodedc-admin-panel"
|
||||
],
|
||||
"summary": "Hub-derived left administration panel with context selectors, route navigation, close action and footer identity.",
|
||||
"summary": "Shared collapsible left administration panel with context selectors, accessible icon rail, route navigation and footer identity.",
|
||||
"anatomy": [
|
||||
"eyebrow and title",
|
||||
"close action",
|
||||
"collapse/expand and close actions",
|
||||
"workspace context",
|
||||
"company context",
|
||||
"route items",
|
||||
@@ -823,7 +892,10 @@
|
||||
"rules": [
|
||||
"The panel shell, full-bleed pills and icon circles are library geometry; routes and identity data remain application-owned.",
|
||||
"The desktop panel follows the Launcher 332–352 px width range with a 21.6 px shell radius and a 20 px page gap.",
|
||||
"Active route state uses the active surface and icon contrast from the theme."
|
||||
"Active route state uses the active surface and icon contrast from the theme.",
|
||||
"All left navigation panels collapse to the shared 4.55rem icon rail; title, labels, close and secondary actions disappear. Icon names and hover/focus tooltips remain.",
|
||||
"ApplicationShell owns synchronized rail/content width and route-independent collapse state without remounting the workspace. Right panels retain their width.",
|
||||
"Use shell navigationCollapsed/onNavigationCollapsedChange for controlled state; standalone panels accept collapsed/onCollapsedChange. Respect reduced motion."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -838,7 +910,7 @@
|
||||
"nodedc-application-side-panel",
|
||||
"nodedc-app-shell__end-panel"
|
||||
],
|
||||
"summary": "Theme-aware trailing application panel paired with AdminNavigationPanel and hosted in a separate ApplicationShell end column.",
|
||||
"summary": "Theme-aware trailing application panel with optional header actions before close, hosted in a separate ApplicationShell end column.",
|
||||
"anatomy": [
|
||||
"eyebrow and title",
|
||||
"optional description",
|
||||
@@ -909,8 +981,10 @@
|
||||
"The card owns grouping geometry but not product form schemas.",
|
||||
"Use align=center for compact result or empty messages: center the content on both axes and omit an empty body. The default start layout remains unchanged.",
|
||||
"Section and empty-state titles use the compact md token; descriptions use sm. Page/window title sizes and browser heading defaults are forbidden inside cards.",
|
||||
"Unclassed paragraphs in the body, including nested layout groups, share Description typography as a compatibility safeguard. New explanatory copy must use Description; headings and controls retain their own typography.",
|
||||
"Use Switch for compact visibility/enable states; use Checker for the Engine inspector treatment.",
|
||||
"Switch keeps its track width beside wrapped labels. The checked thumb uses on-accent contrast; the unchecked track follows theme text instead of a fixed white tint."
|
||||
"Switch keeps its track width beside wrapped labels. The checked thumb uses on-accent contrast; the unchecked track follows theme text instead of a fixed white tint.",
|
||||
"Fields sit directly in the card body, as in Mission Core. Layout grids are transparent; use at most one additional neutral group for a collection entry, not a card around the entire form."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -941,7 +1015,8 @@
|
||||
"ToastCard",
|
||||
"ToastStack",
|
||||
"ToastItem",
|
||||
"ToastTone"
|
||||
"ToastTone",
|
||||
"ToastObserver"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-toast-viewport",
|
||||
@@ -969,7 +1044,8 @@
|
||||
"Errors and status copy use the compact Toast typography; consumers do not substitute browser-default paragraphs or title-sized text.",
|
||||
"Adding or updating another notification never restarts the lifetime of an existing item; each item owns its timer by stable id.",
|
||||
"Loading notifications remain until the operation updates or dismisses them.",
|
||||
"Status notifications never replace a blocking confirmation modal."
|
||||
"Status notifications never replace a blocking confirmation modal.",
|
||||
"ToastObserver reports new or changed terminal presentations to the consumer; storage and history belong to the application. Set observe=false for server-originated items already recorded in history."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -992,7 +1068,8 @@
|
||||
"moveDockPanel",
|
||||
"resizeDockSplit",
|
||||
"dockRects",
|
||||
"dockPosition"
|
||||
"dockPosition",
|
||||
"dockMoveAtPoint"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-dock-layout",
|
||||
@@ -1006,10 +1083,11 @@
|
||||
"empty source branches collapse",
|
||||
"6 px handle activation",
|
||||
"pointer-position hit testing",
|
||||
"outside and self drops cancel",
|
||||
"outside and local self drops cancel",
|
||||
"keyboard docking",
|
||||
"resizable splits",
|
||||
"focus preserves media hosts"
|
||||
"focus preserves media hosts",
|
||||
"four outer workspace edges wrap the remaining layout"
|
||||
],
|
||||
"rules": [
|
||||
"Applications persist the serializable tree and own panel content.",
|
||||
@@ -1018,7 +1096,8 @@
|
||||
"Space or Enter starts keyboard docking, Tab chooses the destination, arrows choose an edge, Home chooses swap, Enter commits and Escape cancels.",
|
||||
"Only the active drag paints a destination contour; no permanent decorative panel outlines.",
|
||||
"Panel minimumSize propagates through split ancestors, constrains pointer/keyboard resize and expands a scrollable canvas below the viewport limit; never clips content to satisfy a ratio.",
|
||||
"preferredSize applies only to an unsaved default layout; minimumSize always constrains nested splits and scroll canvas."
|
||||
"preferredSize applies only to an unsaved default layout; minimumSize always constrains nested splits and scroll canvas.",
|
||||
"The outer visible-workspace zone is 24 CSS px, capped at 8% per axis; it wins over local panel zones, including over the source. Shift+arrows select the same workspace edges. Preview and commit both apply panel minimum sizes; existing DockTree persistence is unchanged."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1051,7 +1130,12 @@
|
||||
"A transfer is accepted only when the dragged surface overlaps the destination by at least the consumer-defined threshold; Module Foundry uses 20 percent.",
|
||||
"Consumers own domain mutations while the package owns sensors, transforms, accessible drag attributes and geometry.",
|
||||
"Repeated page-template drops create distinct application page instances instead of consuming the source template.",
|
||||
"A reordered application page array is the single source of truth for both composition and navigation order."
|
||||
"A reordered application page array is the single source of truth for both composition and navigation order.",
|
||||
"Optional renderOverlay portals the drag preview above scroll clipping without moving source layout; cancellation clears it.",
|
||||
"Pointer drops report client coordinates for consumer-owned canvas hit testing; dropping on empty space never implies an object target.",
|
||||
"DraggableItem exposes activator attributes/listeners for whole-tile dragging without a separate handle; the same activation threshold distinguishes clicks from drags.",
|
||||
"SortableList/SortableScope layout=grid uses rectangular sorting and two-axis movement with the same handle-only interaction; list remains vertical by default.",
|
||||
"DragHandle surface=control and SortableList handleSurface=control put the grip in a visible circle; viewport contexts use the shared glass material."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1076,7 +1160,9 @@
|
||||
"Inspector selection fields use InspectorSelectField only: a stacked visible label and the 276/8/46 px split control; integrated pills are prohibited.",
|
||||
"The panel variant reuses AdminNavigationPanel pill, icon and theme tokens while retaining the same controlled accordion state and domain-owned content.",
|
||||
"A section action is a sibling IconButton before the disclosure chevron, never nested in the trigger. It does not toggle the section. Panel chevrons point down when collapsed and up when expanded.",
|
||||
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts."
|
||||
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts.",
|
||||
"Default sections and optional header fields use the canonical 12 px spacing token; footer actions are centered with the same gap. Nested Inspectors retain this rhythm; the panel variant retains its compact row geometry.",
|
||||
"Inspector responds to its own container width: fields stack below 330px and intrinsic tracks must not clip content."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1091,14 +1177,15 @@
|
||||
"nodedc-environment-settings",
|
||||
"nodedc-environment-media-playlist"
|
||||
],
|
||||
"summary": "Shared avatar Settings → Environment composition for product/home copy, quick actions and image/video playlists.",
|
||||
"summary": "Shared avatar Settings composition with Environment editing and optional consumer-owned settings sections.",
|
||||
"behavior": [
|
||||
"product-configured page list",
|
||||
"draft/reset/save",
|
||||
"upload adapter",
|
||||
"ordered media playlist",
|
||||
"image timing",
|
||||
"parent save/upload disabled state"
|
||||
"parent save/upload disabled state",
|
||||
"additionalSections extends shared navigation with consumer-owned content and footer while preserving the Environment draft"
|
||||
],
|
||||
"rules": [
|
||||
"Reuse FeatureSettingsWindow and existing form primitives; never fork an application-specific settings form.",
|
||||
@@ -1168,7 +1255,9 @@
|
||||
],
|
||||
"summary": "Secondary explanatory copy matching SettingsCard descriptions.",
|
||||
"rules": [
|
||||
"Use the same inherited family, regular 400 weight, small font token, muted text token and 1.4 line height for explanatory paragraphs. Do not restyle per feature."
|
||||
"Use the same inherited family, regular 400 weight, small font token, muted text token and 1.4 line height for explanatory paragraphs. Do not restyle per feature.",
|
||||
"Use role=status for explanatory pending/result copy. SettingsCard applies the same contract to unclassed body paragraphs as a fallback, without changing headings or controls.",
|
||||
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1204,6 +1293,7 @@
|
||||
],
|
||||
"summary": "Renderer-independent BIM-style orientation cube; six faces, twelve edges, eight corners.",
|
||||
"behavior": [
|
||||
"independent faceOpacity, edgeOpacity and text colors; overall opacity remains compatible",
|
||||
"Tracks camera quaternion; never changes projection implicitly",
|
||||
"Visible regions support hover, focus, Enter/Space and disabled state",
|
||||
"Consumer owns camera navigation and coordinate conversion",
|
||||
@@ -1211,6 +1301,218 @@
|
||||
"Labels rotate and foreshorten in the face plane; they never billboard"
|
||||
],
|
||||
"documentation": "../docs/NAVIGATION_CUBE.md"
|
||||
},
|
||||
{
|
||||
"id": "tree",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-react",
|
||||
"exports": [
|
||||
"Tree",
|
||||
"TreeNode",
|
||||
"TreeProps",
|
||||
"TreeSelectionGesture"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-tree",
|
||||
"nodedc-tree__row"
|
||||
],
|
||||
"summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.",
|
||||
"behavior": [
|
||||
"new external selection expands ancestors and scrolls only the tree container",
|
||||
"visibility/data refresh keeps disclosure state; arrow disclosure keeps scroll position; row double-click does not expand",
|
||||
"Arrow/Home/End navigation, disclosure and optional visibility actions",
|
||||
"long names ellipsize without growing row height",
|
||||
"filter retains matching ancestors",
|
||||
"optional renderActions slot composes canonical controls without selecting the row",
|
||||
"defaultExpandedDepth limits initial expansion; external selection reveals ancestors"
|
||||
],
|
||||
"rules": [
|
||||
"Use for object hierarchies; no nested ResourceRow cards.",
|
||||
"Host owns model identity and visibility; the tree owns navigation presentation.",
|
||||
"Compact information uses info-plain at 14px beside the independent visibility eye.",
|
||||
"Optional controlled selectedIds and modifier/range callback support multiple selection; Shift ranges use displayed rows only. Existing single-selection consumers remain compatible."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "resizable-viewport",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-react",
|
||||
"exports": [
|
||||
"ResizableViewport",
|
||||
"ResizableViewportProps"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-resizable-viewport",
|
||||
"nodedc-resizable-viewport__grip"
|
||||
],
|
||||
"summary": "In-flow viewer with controlled height and two accessible bottom corner grips.",
|
||||
"anatomy": [
|
||||
"content",
|
||||
"bottom-left grip",
|
||||
"bottom-right grip"
|
||||
],
|
||||
"variants": [
|
||||
"height-only",
|
||||
"hidden-indicator"
|
||||
],
|
||||
"states": [
|
||||
"idle",
|
||||
"hover",
|
||||
"focus",
|
||||
"resizing"
|
||||
],
|
||||
"rules": [
|
||||
"The owner persists height per view; the component never writes application storage.",
|
||||
"Pointer capture isolates resizing from scene navigation. Up/Down resize, Shift accelerates, Home/End use limits.",
|
||||
"Only the viewport height changes; the page and browser retain their dimensions.",
|
||||
"resizeIndicator=false hides both glyphs and hover surfaces. Pointer resizing shows only the cursor; keyboard focus remains visible."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "scene-annotation",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-react",
|
||||
"exports": [
|
||||
"SceneAnnotation"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-scene-annotation"
|
||||
],
|
||||
"summary": "Transparent interactive data label projected onto a real scene object.",
|
||||
"anatomy": [
|
||||
"canonical ghost button",
|
||||
"stacked label and data"
|
||||
],
|
||||
"states": [
|
||||
"idle",
|
||||
"hover",
|
||||
"selected",
|
||||
"keyboard-focus"
|
||||
],
|
||||
"rules": [
|
||||
"Renderer owns projection and offscreen/hidden-object clipping; the label does not infer measurements.",
|
||||
"Use canonical button keyboard and focus semantics, transparent resting surface, compact numeric typography."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "editor-dock-layout",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-react",
|
||||
"exports": [
|
||||
"EditorDockLayout",
|
||||
"EditorDockLayoutProps",
|
||||
"EditorDockTool",
|
||||
"EditorDockState",
|
||||
"EditorWorkspace",
|
||||
"EditorWorkspaceProps",
|
||||
"decodeEditorDock",
|
||||
"dockEditorTool",
|
||||
"editorDockTarget",
|
||||
"mergeEditorDockRatios"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-editor-dock",
|
||||
"nodedc-editor-dock__tool",
|
||||
"nodedc-editor-workspace"
|
||||
],
|
||||
"summary": "Fixed primary scene with detachable docked tools and a separate editor window that restores the original view.",
|
||||
"behavior": [
|
||||
"four outer magnetic edges",
|
||||
"nested adjacent tool splits",
|
||||
"only exterior workspace corners are rounded; adjoining pane seams remain square and update after dock, resize or close",
|
||||
"drag header to detach over primary",
|
||||
"floating and dragged tools use canonical scene Glass V4; docking restores tiled surface context",
|
||||
"invisible resize regions",
|
||||
"controlled JSON layout",
|
||||
"stable mounted renderer",
|
||||
"keyboard docking and cancellation",
|
||||
"fixed header outside docking bounds"
|
||||
],
|
||||
"rules": [
|
||||
"Applications own scene content, visibility and persisted layout; tools share one generic docking implementation.",
|
||||
"Primary content cannot detach or swap with a tool. Dropping in the primary center makes a tool floating.",
|
||||
"Outer 24 px has priority; additional magnets extend to 160 px horizontally and 96 px vertically, capped at 16% of the host.",
|
||||
"Header Enter/Space starts keyboard docking; arrows select edges, Shift+arrows the whole workspace, Tab cycles tools, Home floats, Escape cancels. Floating headers also support arrows and Shift+arrows for move/resize.",
|
||||
"Hidden tools retain their docking placement and remembered floating rectangle. Viewport clamps never overwrite preferred geometry.",
|
||||
"EditorWorkspace keeps one mounted portal host, moves it atomically when supported, and restores its original slot on return. It never changes the source-view layout.",
|
||||
"The fixed editor header is outside docking bounds. Back, edit completion and close return to the original view.",
|
||||
"When opened inside Window, the editor suspends that overlay, backdrop and focus trap without unmounting; returning restores the same window.",
|
||||
"EditorWorkspace purpose=view uses the same mounted host, return/fullscreen behavior and optional fixed headerActions; purpose=edit remains the compatible default.",
|
||||
"Tool minimumSize applies to floating restore, pointer and keyboard resize as well as docked splits; small screens clamp to available space. Footer remains outside the body scroller.",
|
||||
"Drag headers never draw perimeter outlines or inherit keyboard-focus fill on pointer grab. Keyboard focus remains visible through the canonical surface; arrows, Shift+arrows and docking shortcuts remain available."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "level-button",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-react",
|
||||
"exports": [
|
||||
"LevelButton",
|
||||
"LevelButtonProps",
|
||||
"LevelButtonGeometry"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-level-button"
|
||||
],
|
||||
"summary": "Compact measured resource level inside a canonical pill button opening details.",
|
||||
"rules": [
|
||||
"Consumer supplies a measured fraction and freshness; unknown is not zero.",
|
||||
"Stale retains the last number and accessible stale text; explicit user fill colours are retained.",
|
||||
"Keyboard, focus, disabled and pointer behavior come from Button. Explicit fillColor uses contrast-correct text on the filled portion.",
|
||||
"Optional geometry sets width, height and radius with a 32 × 12 px minimum. At small dimensions the text and padding shrink proportionally; both contrast layers share the same type geometry. Consumer owns header-group offset."
|
||||
],
|
||||
"documentation": "../docs/LEVEL_BUTTON.md"
|
||||
},
|
||||
{
|
||||
"id": "tooltip",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-react",
|
||||
"exports": [
|
||||
"Tooltip",
|
||||
"TooltipProps",
|
||||
"TooltipProvider"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-tooltip-anchor",
|
||||
"nodedc-tooltip"
|
||||
],
|
||||
"summary": "Neutral non-interactive explanation on hover, focus or touch.",
|
||||
"behavior": [
|
||||
"portal to active fullscreen element or body",
|
||||
"shared viewport clamp and flip",
|
||||
"hoverable content and focus persistence",
|
||||
"Escape dismisses tooltip without closing its parent",
|
||||
"one tooltip at a time",
|
||||
"scroll/resize reposition",
|
||||
"reduced-motion fade disabled"
|
||||
],
|
||||
"rules": [
|
||||
"Use focusable for read-only graphics; action triggers own their focus.",
|
||||
"Content is descriptive, never a menu or interactive form.",
|
||||
"No new app-local tooltip geometry or layer management.",
|
||||
"All tooltip surfaces use rounded scene glass without decorative border, outline or rim.",
|
||||
"Mount TooltipProvider once at the application root to present legacy native title hints through the same accessible portal. Nested reusable modules reuse the host provider."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "path-bar",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-dom",
|
||||
"exports": [
|
||||
"renderPathBar",
|
||||
"PathBarItem"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-path-bar"
|
||||
],
|
||||
"summary": "Compact Finder-style path navigation with neutral folder icons, separators and native folder buttons.",
|
||||
"behavior": [
|
||||
"Application supplies items, icon factory and navigation callback.",
|
||||
"Current location uses aria-current; long paths scroll without wrapping."
|
||||
],
|
||||
"rules": [
|
||||
"Use ui-dom/styles.css, theme tokens and textContent labels; no application-local breadcrumb pills."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+15
-3
@@ -25,12 +25,16 @@
|
||||
"names": [
|
||||
"close",
|
||||
"plus",
|
||||
"minus",
|
||||
"expand",
|
||||
"minimize",
|
||||
"refresh",
|
||||
"panel",
|
||||
"apps",
|
||||
"layers"
|
||||
"layers",
|
||||
"move",
|
||||
"power",
|
||||
"pipette"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -51,6 +55,7 @@
|
||||
"sliders",
|
||||
"search",
|
||||
"orthographic",
|
||||
"fit-view",
|
||||
"perspective"
|
||||
]
|
||||
},
|
||||
@@ -76,7 +81,10 @@
|
||||
"curve",
|
||||
"undo",
|
||||
"redo",
|
||||
"add-point"
|
||||
"add-point",
|
||||
"ruler",
|
||||
"section",
|
||||
"isolate"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -91,13 +99,16 @@
|
||||
"check",
|
||||
"alert",
|
||||
"info",
|
||||
"info-plain",
|
||||
"activity",
|
||||
"lock",
|
||||
"unlock",
|
||||
"key",
|
||||
"shield",
|
||||
"circle",
|
||||
"eye",
|
||||
"eye-off"
|
||||
"eye-off",
|
||||
"star"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -113,6 +124,7 @@
|
||||
"building",
|
||||
"globe",
|
||||
"database",
|
||||
"pin",
|
||||
"network",
|
||||
"inbox",
|
||||
"mail"
|
||||
|
||||
+22
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": "1.0.0",
|
||||
"libraryVersion": "0.7.0",
|
||||
"libraryVersion": "0.7.1",
|
||||
"name": "NODE.DC Design System",
|
||||
"purpose": "Canonical code-level UI system for current and future NODE.DC applications.",
|
||||
"packages": [
|
||||
@@ -32,7 +32,7 @@
|
||||
{
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"path": "packages/map-cesium-react",
|
||||
"role": "credential-free Cesium renderer adapter for the canonical Map Page and same-origin Platform Map Gateway BFFs"
|
||||
"role": "credential-free Cesium 1.147.0 renderer adapter for canonical Map Page and same-origin Map Gateway BFFs; optional lifetime-scoped ready-domain geometry hook"
|
||||
}
|
||||
],
|
||||
"sourceRegistry": "sources.json",
|
||||
@@ -56,7 +56,8 @@
|
||||
"mapTemplate": "../docs/MAP_TEMPLATE.md",
|
||||
"icons": "../docs/ICONS.md",
|
||||
"consumption": "../docs/CONSUMPTION.md",
|
||||
"environmentSettings": "../docs/ENVIRONMENT_SETTINGS.md"
|
||||
"environmentSettings": "../docs/ENVIRONMENT_SETTINGS.md",
|
||||
"viewportUi": "../docs/VIEWPORT_UI.md"
|
||||
},
|
||||
"applicationManifestSchema": "schemas/application-manifest-v0.1.schema.json",
|
||||
"designProfileSchema": "schemas/design-profile-v0.1.schema.json",
|
||||
@@ -66,7 +67,23 @@
|
||||
"mapSubjectDetailProfileRegistry": "map-subject-detail-profiles.json",
|
||||
"operatingRule": "Check this registry before creating a NODE.DC interface element. Reuse or extend the canonical export instead of creating an application-local copy.",
|
||||
"appearanceProfiles": {
|
||||
"default": "Existing theme/material behavior",
|
||||
"mission": "Opt-in operator appearance, qualified against live Mission Core 2026-09-30; shared modal/floating surfaces, neutral avatars and dot statuses"
|
||||
"default": "Explicit legacy component presentation; no application-local overrides.",
|
||||
"mission": "Canonical Mission Core foundation, audited on 2026-11-05: complete dark palette, surface hierarchy, neutral actions, portal materials, semantic dots and flat edges. Default for new applications."
|
||||
},
|
||||
"surfaceEdgeProfiles": {
|
||||
"default": "Existing surface edges",
|
||||
"flat": "No decorative borders or rims; contrasting keyboard focus fill"
|
||||
},
|
||||
"themePresets": {
|
||||
"missionDarkTheme": {
|
||||
"theme": "dark",
|
||||
"appearance": "mission",
|
||||
"edges": "flat"
|
||||
},
|
||||
"missionLightTheme": {
|
||||
"theme": "light",
|
||||
"appearance": "mission",
|
||||
"edges": "flat"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +108,21 @@
|
||||
"docs/ARCHITECTURE.md"
|
||||
],
|
||||
"policy": "architecture-context"
|
||||
},
|
||||
{
|
||||
"id": "mission-core",
|
||||
"repository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE.git",
|
||||
"auditedRevision": "b0332fa",
|
||||
"role": "Owner-approved canonical dark theme and shared operator presentation, 2026-11-05; source and running canonical localhost:8000 audited.",
|
||||
"approvedPaths": [
|
||||
"apps/control-station/src/styles/base.css",
|
||||
"apps/control-station/src/main.tsx"
|
||||
],
|
||||
"policy": "reference",
|
||||
"excludedPaths": [
|
||||
"domain scene renderers",
|
||||
"uncommitted simulation work"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
const fs = require('node:fs'), path = require('node:path'), os = require('node:os'), assert = require('node:assert/strict');
|
||||
const root = process.env.DG_ROOT || path.resolve(__dirname, '..');
|
||||
const {JSDOM} = require('jsdom'), React = require(root + '/node_modules/react'), {act} = React;
|
||||
const {createRoot} = require(root + '/node_modules/react-dom/client');
|
||||
const dom = new JSDOM('<div id="app"></div>', {pretendToBeVisual: true});
|
||||
for (const name of ['window','document','HTMLElement','Element','Node','Event','MouseEvent','KeyboardEvent','CustomEvent']) global[name] = dom.window[name];
|
||||
global.ResizeObserver = class {observe() {} disconnect() {}};
|
||||
global.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
HTMLElement.prototype.getBoundingClientRect = () => ({top: 20, bottom: 60, left: 20, right: 80, width: 60, height: 40});
|
||||
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'nodedc-sidebar-'));
|
||||
require(root + '/node_modules/esbuild').buildSync({stdin: {contents: `export {AdminNavigationPanel} from './AdminNavigationPanel.tsx'; export {ApplicationShell} from './ApplicationShell.tsx';`, resolveDir: root + '/packages/ui-react/src'}, outfile: scratch + '/sidebar.cjs', bundle: true, platform: 'node', format: 'cjs', external: ['react','react/*','react-dom','react-dom/*'], jsx: 'automatic'});
|
||||
const {ApplicationShell, AdminNavigationPanel} = require(scratch + '/sidebar.cjs');
|
||||
const ui = createRoot(document.getElementById('app')), h = React.createElement;
|
||||
let selected = 'one', section = 'Data', open = true, mounts = 0, closes = 0, notified = [];
|
||||
function Workspace() {React.useEffect(() => {mounts++;}, []); return h('input', {defaultValue: 'keep draft', 'aria-label': 'Draft'});}
|
||||
const panel = () => h(AdminNavigationPanel, {key: section, title: section, onClose: () => closes++, closeLabel: 'Close navigation', activeId: selected, onItemChange: id => selected = id, contexts: [{id: 'context', label: 'Context', onToggle: () => {}, icon: 'C'}], headerActions: h('button', null, 'Extra'), items: [{id: 'one', label: 'One', icon: '1'}, {id: 'two', label: 'Two', icon: '2', sortable: true}], onItemsReorder: () => {}});
|
||||
const render = (extra = {}) => act(async () => ui.render(h(ApplicationShell, {header: null, stage: null, navigation: panel(), navigationOpen: open, contentOpen: true, contentExpanded: true, content: h(Workspace), endPanel: h('div', {'data-testid': 'right'}, 'Right'), onNavigationCollapsedChange: value => notified.push(value), ...extra})));
|
||||
const button = label => [...document.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === label);
|
||||
const click = el => act(async () => el.dispatchEvent(new MouseEvent('click', {bubbles: true})));
|
||||
const shell = () => document.querySelector('.nodedc-app-shell');
|
||||
(async () => {
|
||||
await render(); const draft = document.querySelector('input'); draft.value = 'unsaved text';
|
||||
await click(button('Свернуть панель навигации'));
|
||||
assert.equal(shell().dataset.navigationCollapsed, 'true');
|
||||
assert.equal(document.querySelector('aside').dataset.collapsed, 'true');
|
||||
assert.equal(button('Развернуть панель навигации').getAttribute('aria-expanded'), 'false');
|
||||
assert(button('Close navigation').hidden); assert.equal(closes, 0);
|
||||
assert(button('Выбрать: Context').hidden); assert(document.querySelector('.nodedc-admin-panel__extra-actions').hidden);
|
||||
assert.equal(button('One').getAttribute('aria-current'), 'page');
|
||||
await click(button('Two')); assert.equal(selected, 'two');
|
||||
section = 'System'; await render(); assert.equal(document.querySelector('aside').dataset.collapsed, 'true', 'new root uses retained shell state');
|
||||
open = false; await render(); open = true; await render(); assert.equal(document.querySelector('aside').dataset.collapsed, 'true', 'close/reopen preserves rail');
|
||||
await act(async () => button('Two').focus()); assert.equal(document.querySelector('[role=tooltip]').textContent, 'Two');
|
||||
await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape', bubbles: true})));
|
||||
assert.equal(document.querySelector('[role=tooltip]'), null); assert.equal(closes, 0, 'Escape closes tooltip only');
|
||||
await click(button('Развернуть панель навигации')); assert.equal(shell().dataset.navigationCollapsed, undefined);
|
||||
assert.equal(button('Close navigation').hidden, false);
|
||||
assert.equal(mounts, 1); assert.equal(document.querySelector('input'), draft); assert.equal(draft.value, 'unsaved text');
|
||||
assert.deepEqual(notified, [true, false]);
|
||||
await render({navigationCollapsed: false}); await click(button('Свернуть панель навигации'));
|
||||
assert.equal(shell().dataset.navigationCollapsed, undefined, 'controlled shell awaits owner acceptance');
|
||||
await render({navigationCollapsed: true}); assert.equal(document.querySelector('aside').dataset.collapsed, 'true');
|
||||
assert.equal(document.querySelector('[data-testid=right]').textContent, 'Right');
|
||||
await act(async () => ui.render(h(AdminNavigationPanel, {title: 'Standalone', items: [], onClose: () => {}, onItemChange: () => {}, defaultCollapsed: true})));
|
||||
assert(button('Развернуть панель навигации')); await click(button('Развернуть панель навигации')); assert(button('Свернуть панель навигации'));
|
||||
await act(async () => ui.unmount());
|
||||
console.log('PASS: shared/standalone/controlled collapse, root and reopen persistence, hidden actions, icon navigation, accessible names and Escape tooltip, workspace remains mounted with its draft.');
|
||||
})().catch(e => {console.error(e); process.exitCode = 1;}).finally(() => {fs.rmSync(scratch, {recursive: true, force: true}); dom.window.close();});
|
||||
@@ -47,3 +47,19 @@ test("viewport controls share one scale without scaling nested controls twice",
|
||||
assert.match(styles, /\.nodedc-segmented\) :is\([^}]+zoom: 1;/);
|
||||
assert.ok(JSON.parse(registrySource).components.find(c=>c.id==='button').domContract.includes('nodedc-viewport-controls'));
|
||||
});
|
||||
|
||||
import { LevelButton } from "../packages/ui-react/dist/index.js";
|
||||
import { levelButtonGeometry } from "../packages/ui-react/dist/levelButtonGeometry.js";
|
||||
test("compact level indicators fit both contrast layers with proportional text and padding", () => {
|
||||
const tiny=levelButtonGeometry({width:32,height:12,radius:4},4);
|
||||
const normal=levelButtonGeometry({width:64,height:24,radius:8},4);
|
||||
assert.equal(tiny.fontSize,'calc(var(--nodedc-font-size-md) * 0.5)');
|
||||
assert.equal(tiny.padding,'calc(0.25rem * 0.5) calc(var(--nodedc-space-2) * 0.5)');
|
||||
assert.equal(normal.fontSize,'calc(var(--nodedc-font-size-md) * 1)');
|
||||
assert.equal(levelButtonGeometry({width:-1,height:NaN},4).width,32);
|
||||
assert.equal(levelButtonGeometry({width:-1,height:NaN},4).height,46);
|
||||
const markup=renderToStaticMarkup(createElement(LevelButton,{value:1,label:'Battery',fillColor:'#ffffff',geometry:{width:32,height:12,radius:4}}));
|
||||
assert.match(markup,/width:32px/);assert.match(markup,/height:12px/);
|
||||
assert.match(markup,/nodedc-level-button__fill/);
|
||||
assert.match(markup,/100/);assert.match(markup,/aria-label="Battery: 100%"/);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {preferDockSizes,dockMinimum,constrainDockTree,balancedDockTree,decodeDockTree,dockIds,dockPosition,dockRects,moveDockPanel,pruneDockTree,reconcileDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js';
|
||||
import {dockMoveAtPoint,preferDockSizes,dockMinimum,constrainDockTree,balancedDockTree,decodeDockTree,dockIds,dockPosition,dockRects,moveDockPanel,pruneDockTree,reconcileDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js';
|
||||
const bounds={left:0,top:0,width:1200,height:800};
|
||||
const initial=balancedDockTree(['a','b','c']);
|
||||
const rects=tree=>dockRects(tree,bounds);
|
||||
@@ -79,3 +79,58 @@ test('new compact panel uses its preferred size without changing saved ratios',(
|
||||
assert.ok(Math.abs(r.telemetry.width-320)<1e-8);assert.ok(Math.abs(r.telemetry.height-280)<1e-8);
|
||||
assert.deepEqual(preferDockSizes(t,bounds,{}),t);
|
||||
});
|
||||
|
||||
|
||||
test('workspace edges span the whole side and preserve the remaining nested tree',()=>{
|
||||
const original={axis:'x',ratio:35,first:{axis:'y',ratio:30,first:{id:'map'},second:{id:'rover'}},second:{axis:'y',ratio:60,first:{id:'camera'},second:{id:'telemetry'}}};
|
||||
const snapshot=JSON.stringify(original),remaining=pruneDockTree(original,['map','rover','telemetry']);
|
||||
for(const position of ['left','right','top','bottom']){
|
||||
const moved=moveDockPanel(original,{activeId:'camera',overId:'camera',position,scope:'workspace'});
|
||||
const before=position==='left'||position==='top';
|
||||
assert.deepEqual(before?moved.second:moved.first,remaining);
|
||||
const r=rects(moved).camera;
|
||||
assert.deepEqual(r,position==='left'?{left:0,top:0,width:600,height:800}:
|
||||
position==='right'?{left:600,top:0,width:600,height:800}:
|
||||
position==='top'?{left:0,top:0,width:1200,height:400}:{left:0,top:400,width:1200,height:400});
|
||||
assert.deepEqual(dockIds(moved).sort(),['camera','map','rover','telemetry']);
|
||||
assert.deepEqual(decodeDockTree(JSON.parse(JSON.stringify(moved))),moved);
|
||||
}
|
||||
assert.equal(JSON.stringify(original),snapshot);
|
||||
assert.equal(moveDockPanel(original,{activeId:'camera',overId:'map',position:'center',scope:'workspace'}),original);
|
||||
assert.equal(moveDockPanel({id:'camera'},{activeId:'camera',overId:'camera',position:'top',scope:'workspace'}).id,'camera');
|
||||
});
|
||||
|
||||
test('outer workspace zones win over source and panel edges; local docking remains reachable',()=>{
|
||||
const r=rects(initial);
|
||||
for(const [x,y,position] of [[10,300,'left'],[1190,300,'right'],[800,10,'top'],[800,790,'bottom']]){
|
||||
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',x,y),{activeId:'a',overId:'a',position,scope:'workspace'});
|
||||
}
|
||||
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',620,400),{activeId:'a',overId:'c',position:'left'});
|
||||
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',900,50),{activeId:'a',overId:'c',position:'top'});
|
||||
assert.deepEqual(dockMoveAtPoint(bounds,r,'a',900,400),{activeId:'a',overId:'c',position:'center'});
|
||||
assert.equal(dockMoveAtPoint(bounds,r,'a',300,200),null);
|
||||
for(const [x,y] of [[-1,300],[1201,300],[500,-1],[500,801],[NaN,100],[100,Infinity]])assert.equal(dockMoveAtPoint(bounds,r,'a',x,y),null);
|
||||
assert.equal(dockMoveAtPoint(bounds,r,'missing',10,300),null);
|
||||
assert.equal(dockMoveAtPoint(bounds,{a:bounds},'a',10,300),null);
|
||||
assert.equal(dockMoveAtPoint(bounds,r,'a',5,15).position,'left');
|
||||
assert.equal(dockMoveAtPoint(bounds,r,'a',15,5).position,'top');
|
||||
});
|
||||
|
||||
test('visible viewport coordinates retain workspace docking while the canvas is scrolled',()=>{
|
||||
const visible={left:300,top:120,width:500,height:400};
|
||||
const target=dockMoveAtPoint(visible,rects(initial),'a',795,300);
|
||||
assert.equal(target.scope,'workspace');assert.equal(target.position,'right');
|
||||
assert.equal(dockMoveAtPoint(visible,rects(initial),'a',810,300),null);
|
||||
});
|
||||
|
||||
test('workspace moves respect content minima and serialize a stable final geometry',()=>{
|
||||
const sizes={a:{width:300,height:250},b:{width:480,height:350},c:{width:250,height:200}};
|
||||
for(const position of ['left','right','top','bottom']){
|
||||
const moved=moveDockPanel(initial,{activeId:'a',overId:'a',position,scope:'workspace'}),minimum=dockMinimum(moved,sizes);
|
||||
const area={left:0,top:0,width:Math.max(700,minimum.width),height:Math.max(500,minimum.height)};
|
||||
const final=constrainDockTree(moved,area,sizes),r=dockRects(final,area);
|
||||
for(const id of ['a','b','c']){assert.ok(r[id].width>=sizes[id].width-1e-8);assert.ok(r[id].height>=sizes[id].height-1e-8);}
|
||||
assert.deepEqual(dockRects(constrainDockTree(final,area,sizes),area),r);
|
||||
assert.ok(Math.abs(Object.values(r).reduce((s,v)=>s+v.width*v.height,0)-area.width*area.height)<1e-6);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {dockIds,dockRects,pruneDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js';
|
||||
import {decodeEditorDock,dockEditorTool,editorDockTarget,mergeEditorDockRatios} from '../packages/ui-core/dist/editorDock.js';
|
||||
const bounds={left:0,top:0,width:1400,height:900},rect={left:400,top:200,width:360,height:400};
|
||||
const start={tree:{id:'viewport'},floating:{}};
|
||||
test('floating tools can dock to every side; primary survives every detach',()=>{
|
||||
for(const position of ['left','right','top','bottom']){
|
||||
const dock=dockEditorTool(start,'viewport',{activeId:'tree',overId:'viewport',position,scope:'workspace'},'tree',rect);
|
||||
assert.deepEqual(dockIds(dock.tree).sort(),['tree','viewport']);
|
||||
const r=dockRects(dock.tree,bounds);assert.equal(position==='left'?r.tree.left===0:position==='right'?r.tree.left>r.viewport.left:position==='top'?r.tree.top===0:r.tree.top>r.viewport.top,true);
|
||||
const free=dockEditorTool(dock,'viewport',null,'tree',rect);assert.deepEqual(free.tree,start.tree);assert.deepEqual(free.floating.tree,rect);
|
||||
assert.equal(dockEditorTool(dock,'viewport',null,'viewport',rect),dock);
|
||||
}
|
||||
});
|
||||
test('adjacent bottom tools fill one row; detaching collapses only their empty branch',()=>{
|
||||
const a=dockEditorTool(start,'viewport',{activeId:'palette',overId:'viewport',position:'bottom',scope:'workspace'},'palette',rect);
|
||||
const b=dockEditorTool(a,'viewport',{activeId:'tree',overId:'palette',position:'right'},'tree',rect),r=dockRects(b.tree,bounds);
|
||||
assert.equal(r.tree.top,r.palette.top);assert.equal(r.tree.height,r.palette.height);assert.equal(r.viewport.width,1400);
|
||||
assert.deepEqual(dockEditorTool(b,'viewport',null,'tree',rect).tree,a.tree);
|
||||
});
|
||||
test('primary center floats, broad edge magnets and panel targets use pointer location',()=>{
|
||||
const r={viewport:bounds,palette:{left:0,top:700,width:1400,height:200}};
|
||||
assert.equal(editorDockTarget(bounds,r,'viewport','tree',700,400),null);
|
||||
assert.equal(editorDockTarget(bounds,r,'viewport','tree',100,400).position,'left');
|
||||
assert.equal(editorDockTarget(bounds,r,'viewport','tree',700,40).position,'top');
|
||||
assert.equal(editorDockTarget(bounds,r,'viewport','tree',1300,800).overId,'palette');
|
||||
assert.equal(editorDockTarget(bounds,r,'viewport','tree',700,899).scope,'workspace');
|
||||
assert.equal(editorDockTarget(bounds,r,'viewport','tree',100,-1),null);
|
||||
});
|
||||
test('closed tool retains placement when a visible split resizes',()=>{
|
||||
const full={axis:'x',ratio:25,first:{id:'objects'},second:{axis:'y',ratio:70,first:{id:'viewport'},second:{id:'palette'}}};
|
||||
const visible=pruneDockTree(full,['viewport','palette']);
|
||||
const next=mergeEditorDockRatios(full,resizeDockSplit(visible,'',62));
|
||||
assert.equal(next.ratio,25);assert.equal(next.second.ratio,62);assert.deepEqual(next.first,full.first);
|
||||
});
|
||||
test('outer magnets follow the visible viewport when minimum-size canvas is scrolled',()=>{
|
||||
const b={left:112,top:40,width:768,height:580},r={viewport:{left:280,top:0,width:320,height:400},objects:{left:0,top:0,width:280,height:580},material:{left:600,top:0,width:280,height:580}};
|
||||
assert.equal(editorDockTarget(b,r,'viewport','objects',879,300).position,'right');
|
||||
assert.equal(editorDockTarget(b,r,'viewport','objects',400,41).position,'top');
|
||||
assert.equal(editorDockTarget(b,r,'viewport','objects',100,300),null);
|
||||
});
|
||||
test('untrusted layout excludes unknown identities and primary floating geometry',()=>{
|
||||
const value=decodeEditorDock({tree:{axis:'x',ratio:Infinity,first:{id:'bad'},second:{id:'objects'}},floating:{viewport:rect,objects:{...rect,width:NaN},palette:rect}},'viewport',['objects','palette']);
|
||||
assert.deepEqual(value.tree,{id:'viewport'});assert.deepEqual(value.floating,{palette:rect});
|
||||
assert.deepEqual(decodeEditorDock(JSON.parse(JSON.stringify(value)),'viewport',['objects','palette']),value);
|
||||
});
|
||||
test('repeated dock and float transitions retain unique tools and tile the full workspace',()=>{
|
||||
let state=start;
|
||||
for(let round=0;round<4;round++)for(const id of ['objects','palette','material','environment'])for(const position of ['left','right','top','bottom']){
|
||||
state=dockEditorTool(state,'viewport',{activeId:id,overId:'viewport',position,scope:'workspace'},id,rect);
|
||||
const ids=dockIds(state.tree);assert.equal(new Set(ids).size,ids.length);assert.ok(ids.includes('viewport'));
|
||||
const boxes=Object.values(dockRects(state.tree,bounds));assert.ok(Math.abs(boxes.reduce((n,r)=>n+r.width*r.height,0)-bounds.width*bounds.height)<1e-6);
|
||||
const free=dockEditorTool(state,'viewport',null,id,rect);assert.ok(!dockIds(free.tree).includes(id));assert.deepEqual(free.floating[id],rect);
|
||||
}
|
||||
});
|
||||
|
||||
import {editorDockCorners} from '../packages/ui-react/dist/editorDockCorners.js';
|
||||
test('left stacked panels round only the outer top and bottom; close restores both corners',()=>{
|
||||
const tree={axis:'x',ratio:25,first:{axis:'y',ratio:50,first:{id:'a'},second:{id:'b'}},second:{id:'viewport'}};
|
||||
const r=dockRects(tree,bounds);
|
||||
assert.equal(editorDockCorners(r.a,bounds),'top-left');assert.equal(editorDockCorners(r.b,bounds),'bottom-left');
|
||||
assert.equal(editorDockCorners(r.viewport,bounds),'top-right bottom-right');
|
||||
const remaining=dockRects(pruneDockTree(tree,['a','viewport']),bounds);
|
||||
assert.equal(editorDockCorners(remaining.a,bounds),'top-left bottom-left');
|
||||
});
|
||||
test('top and bottom rows retain square seams at every size and canvas origin',()=>{
|
||||
for(const position of ['top','bottom'])for(const area of [bounds,{left:80,top:45,width:713.5,height:528.3}]){
|
||||
const first=dockEditorTool(start,'viewport',{activeId:'a',overId:'viewport',position,scope:'workspace'},'a',rect);
|
||||
const split=dockEditorTool(first,'viewport',{activeId:'b',overId:'a',position:'right',scope:'panel'},'b',rect);
|
||||
const r=dockRects(split.tree,area);
|
||||
assert.equal(editorDockCorners(r.a,area),position+'-left');assert.equal(editorDockCorners(r.b,area),position+'-right');
|
||||
}
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user