Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88cbef1aba | ||
|
|
f645725e8c | ||
|
|
b70e165910 |
@@ -12,8 +12,6 @@ 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.
|
||||
@@ -39,8 +37,3 @@ 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,14 +6,13 @@
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"build": "tsc -b && vite build",
|
||||
"typecheck": "tsc -b --pretty false",
|
||||
"prebuild": "node --test ../../scripts/operational-typography.test.mjs"
|
||||
"typecheck": "tsc -b --pretty false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nodedc/page-patterns": "0.1.0",
|
||||
"@nodedc/ui-core": "0.7.4",
|
||||
"@nodedc/ui-react": "0.7.10",
|
||||
"cesium": "1.147.0",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-react": "0.7.0",
|
||||
"cesium": "^1.143.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
|
||||
+37
-317
@@ -1,44 +1,26 @@
|
||||
import { OperationalTypographyDemo } from "./OperationalTypographyDemo";
|
||||
import { ModalSizeExample } from './ModalSizeExample';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { applyGlassMaterial, applyNodedcTheme, defaultGlassMaterial, type GlassMaterialSettings, type NodedcTheme, type RgbTuple } from "@nodedc/ui-core";
|
||||
import { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTemplateDefinition } from "@nodedc/page-patterns";
|
||||
import {MissionThemeExample} from './MissionThemeExample';
|
||||
import {EditorDockExample} from './EditorDockExample';
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Tooltip,
|
||||
LoadingRegion,
|
||||
Description,
|
||||
ComparisonTable,
|
||||
StatusBadge,
|
||||
ProgressBar,
|
||||
LevelButton,
|
||||
ProgressButton,
|
||||
LayerStackIndicator,
|
||||
AdminNavigationPanel,
|
||||
AppHeader,
|
||||
ApplicationPanel,
|
||||
ApplicationShell,
|
||||
ApplicationSidePanel,
|
||||
Button,
|
||||
KeyButton,
|
||||
Checker,
|
||||
ColorField,
|
||||
ConfirmationModal,
|
||||
ControlRow,
|
||||
Dropdown,
|
||||
DragDropRoot,
|
||||
DockLayout, DockHandle, balancedDockTree, type DockTree,
|
||||
DraggableItem,
|
||||
DropZone,
|
||||
FieldFrame,
|
||||
FeatureSettingsWindow,
|
||||
GlassSurface,
|
||||
GlassMaterialSurface,
|
||||
ResizableViewport,
|
||||
SceneAnnotation,
|
||||
HeaderNavigation,
|
||||
HeaderProfile,
|
||||
HeaderWorkspace,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -46,18 +28,11 @@ import {
|
||||
InspectorSelectField,
|
||||
MediaSourceField,
|
||||
RangeControl,
|
||||
ResourceRow,
|
||||
ResourceList,
|
||||
Tree,
|
||||
SegmentedControl,
|
||||
SegmentedGroup,
|
||||
SegmentedButton,
|
||||
Select,
|
||||
ShareAccessModal,
|
||||
ShareLinkModal,
|
||||
SplitPane,
|
||||
SortableItem,
|
||||
SortableList,
|
||||
SortableScope,
|
||||
SettingsCard,
|
||||
Switch,
|
||||
@@ -65,9 +40,7 @@ import {
|
||||
TextField,
|
||||
ToastCard,
|
||||
ToastStack,
|
||||
ToastObserver,
|
||||
Toolbar,
|
||||
NavigationCube,
|
||||
UserProfileMenu,
|
||||
useApplicationWorkspace,
|
||||
Window,
|
||||
@@ -92,7 +65,8 @@ import {
|
||||
type DesignProfileSummary,
|
||||
type DesignProfileStatus,
|
||||
} from "./applicationManifest.js";
|
||||
import { createDefaultMapPageLayout, MapFixturePreview, type MapFixturePreviewHandle, type MapPageLayout } from "./MapFixturePreview.js";
|
||||
import { MapFixturePreview } from "./MapFixturePreview.js";
|
||||
import { createDefaultMapPageLayout, type MapFixturePreviewHandle, type MapPageLayout } from "./mapPageContract.js";
|
||||
import {
|
||||
mapDesignFragmentForLayout,
|
||||
mapDesignFragmentFromLayout,
|
||||
@@ -103,7 +77,6 @@ import {
|
||||
type StoredLayout,
|
||||
} from "./designProfile.js";
|
||||
import { FoundrySettingsModal } from "./FoundrySettingsModal.js";
|
||||
import { EnvironmentCatalogDemo } from "./EnvironmentCatalogDemo.js";
|
||||
|
||||
type CatalogSection = "controls" | "media" | "glass" | "status" | "modals" | "icons";
|
||||
type StudioContext = "visual" | "pages" | "applications";
|
||||
@@ -127,8 +100,7 @@ const designProfileDocumentPath = (reference: { id: string; version: string; sta
|
||||
);
|
||||
|
||||
const accents: Array<{ label: string; value: RgbTuple; hex: string }> = [
|
||||
{ label: "Mission Core", value: [247, 248, 244], hex: "#f7f8f4" },
|
||||
{ label: "Rose", value: [255, 47, 146], hex: "#ff2f92" },
|
||||
{ label: "NODE.DC", 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" },
|
||||
@@ -154,7 +126,7 @@ const materialDefaults: Record<NodedcTheme, MaterialDraft> = {
|
||||
panelOpacity: 100,
|
||||
fieldHex: "#2a2a2c",
|
||||
fieldOpacity: 100,
|
||||
nestedHex: "#0d0d0f",
|
||||
nestedHex: "#0b0b0d",
|
||||
},
|
||||
light: {
|
||||
panelHex: "#ffffff",
|
||||
@@ -222,7 +194,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
{
|
||||
title: "Окно и слой",
|
||||
note: "Launcher / Hub",
|
||||
icons: ["close", "plus", "expand", "minimize", "refresh", "panel", "apps", "layers"],
|
||||
icons: ["close", "plus", "expand", "minimize", "refresh", "panel", "apps"],
|
||||
},
|
||||
{
|
||||
title: "Навигация",
|
||||
@@ -232,40 +204,32 @@ 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", "ruler", "section", "isolate", "orthographic", "perspective", "fit-view", "select", "pen", "rectangle", "curve", "undo", "redo"],
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external"],
|
||||
},
|
||||
{
|
||||
title: "Состояние и доступ",
|
||||
note: "Вся платформа",
|
||||
icons: ["check", "alert", "info", "info-plain", "activity", "lock", "unlock", "key", "shield", "circle", "eye", "eye-off", "star"],
|
||||
icons: ["check", "alert", "activity", "lock", "key", "shield", "circle"],
|
||||
},
|
||||
{
|
||||
title: "Сущности",
|
||||
note: "Общий словарь",
|
||||
icons: ["profile", "users", "building", "globe", "target", "database", "pin", "network", "inbox", "mail"],
|
||||
icons: ["profile", "users", "building", "globe", "target", "database", "network", "inbox", "mail"],
|
||||
},
|
||||
{
|
||||
title: "Контент",
|
||||
note: "SEO / BIM / Engine",
|
||||
icons: ["camera", "plan", "play", "stop", "image", "video", "file", "folder", "clipboard", "settings", "terminal"],
|
||||
icons: ["image", "video", "file", "folder", "clipboard", "settings"],
|
||||
},
|
||||
];
|
||||
|
||||
const iconLabels: Record<IconName, string> = {
|
||||
star: "Избранное",
|
||||
pipette: "Пипетка",
|
||||
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
|
||||
power: "Питание",
|
||||
move: "Свободное окно",
|
||||
"add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить",
|
||||
activity: "Активность",
|
||||
alert: "Предупреждение",
|
||||
apps: "Приложения",
|
||||
building: "Компания",
|
||||
camera: "Камера",
|
||||
check: "Готово",
|
||||
"chevron-down": "Раскрыть",
|
||||
"chevron-up": "Свернуть",
|
||||
"chevron-left": "Назад",
|
||||
"chevron-right": "Вперёд",
|
||||
circle: "Маркер",
|
||||
@@ -273,11 +237,8 @@ const iconLabels: Record<IconName, string> = {
|
||||
close: "Закрыть",
|
||||
copy: "Копировать",
|
||||
database: "База данных",
|
||||
pin: "Закрепить",
|
||||
download: "Скачать",
|
||||
edit: "Редактировать",
|
||||
eye: "Показать",
|
||||
"eye-off": "Скрыть",
|
||||
expand: "Развернуть",
|
||||
external: "Открыть снаружи",
|
||||
file: "Файл",
|
||||
@@ -286,33 +247,22 @@ const iconLabels: Record<IconName, string> = {
|
||||
grid: "Обзор",
|
||||
image: "Изображение",
|
||||
inbox: "Уведомления",
|
||||
info: "Информация",
|
||||
"info-plain": "Информация без окружности",
|
||||
"fit-view": "Вписать модель",
|
||||
key: "Ключ",
|
||||
layers: "Слои",
|
||||
list: "Список задач",
|
||||
lock: "Закрыто",
|
||||
unlock: "Открыто",
|
||||
mail: "Приглашение",
|
||||
minimize: "Свернуть",
|
||||
network: "Связи",
|
||||
panel: "Панель",
|
||||
plan: "План",
|
||||
play: "Воспроизвести",
|
||||
target: "Таргеты",
|
||||
plus: "Добавить",
|
||||
minus: "Уменьшить",
|
||||
profile: "Профиль",
|
||||
refresh: "Обновить",
|
||||
"rotate-clockwise": "Повернуть по часовой стрелке",
|
||||
save: "Сохранить",
|
||||
search: "Поиск",
|
||||
settings: "Настройки",
|
||||
shield: "Доступ",
|
||||
sliders: "Параметры",
|
||||
stop: "Остановить",
|
||||
terminal: "Консоль команд",
|
||||
trash: "Удалить",
|
||||
upload: "Загрузить",
|
||||
users: "Участники",
|
||||
@@ -348,7 +298,7 @@ function Preview({ title, note, children, className }: {
|
||||
|
||||
export function CatalogApp() {
|
||||
const [theme, setTheme] = useState<NodedcTheme>("dark");
|
||||
const [accentHex, setAccentHex] = useState("#f7f8f4");
|
||||
const [accentHex, setAccentHex] = useState("#ff2f92");
|
||||
const [materialByTheme, setMaterialByTheme] = useState<Record<NodedcTheme, MaterialDraft>>(() => ({
|
||||
dark: { ...materialDefaults.dark },
|
||||
light: { ...materialDefaults.light },
|
||||
@@ -363,7 +313,6 @@ 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,7 +329,6 @@ export function CatalogApp() {
|
||||
const [createModuleDescription, setCreateModuleDescription] = useState("");
|
||||
const [deleteModuleOpen, setDeleteModuleOpen] = useState(false);
|
||||
const [pageRemovalId, setPageRemovalId] = useState<string | null>(null);
|
||||
const [previewLayers, setPreviewLayers] = useState<string[]>(["source"]);
|
||||
const [applicationMode, setApplicationMode] = useState<"edit" | "preview">("edit");
|
||||
const [designProfileSaveOpen, setDesignProfileSaveOpen] = useState(false);
|
||||
const [designProfileSaveMode, setDesignProfileSaveMode] = useState<"save" | "save-as">("save");
|
||||
@@ -398,39 +346,22 @@ export function CatalogApp() {
|
||||
const activePageTemplateId = pageTemplateIdFromView(activeView);
|
||||
const [selectedStatus, setSelectedStatus] = useState<(typeof selectOptions)[number]["value"]>("active");
|
||||
const [brightness, setBrightness] = useState(49);
|
||||
const [sliceBand, setSliceBand] = useState<[number, number]>([-1.2, 51.5]);
|
||||
const [glowDistance, setGlowDistance] = useState(105);
|
||||
const [usePortColors, setUsePortColors] = useState(false);
|
||||
const [connectionType, setConnectionType] = useState("spline");
|
||||
const [lightColor, setLightColor] = useState("#f7f8f4");
|
||||
const [lightColor, setLightColor] = useState("#ff2f92");
|
||||
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 });
|
||||
const [dockDemoTree, setDockDemoTree] = useState<DockTree | null>(() => balancedDockTree(["camera", "depth", "map", "scene"]));
|
||||
const [splitPaneInvisible, setSplitPaneInvisible] = useState(false);
|
||||
const [splitPaneDemoSize, setSplitPaneDemoSize] = useState(50);
|
||||
const [sidePanelDemoOpen, setSidePanelDemoOpen] = useState(true);
|
||||
const [createModalOpen, setCreateModalOpen] = useState(false);
|
||||
const [missionAppearance, setMissionAppearance] = useState(true);
|
||||
const [flatEdges, setFlatEdges] = useState(true);
|
||||
const [featureSettingsDemoOpen, setFeatureSettingsDemoOpen] = useState(false);
|
||||
const [featureSettingsDemoSection, setFeatureSettingsDemoSection] = useState('general');
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [shareAccessOpen, setShareAccessOpen] = useState(false);
|
||||
const [shareLinkOpen, setShareLinkOpen] = useState(false);
|
||||
@@ -469,9 +400,6 @@ export function CatalogApp() {
|
||||
icon512: "/favicon/icon-512.png",
|
||||
});
|
||||
const pendingFaviconIcoRef = useRef<Blob | null>(null);
|
||||
const [cubeSize,setCubeSize]=useState(66);
|
||||
const [cubeEdgeOpacity,setCubeEdgeOpacity]=useState(1);
|
||||
const [cubeDirection,setCubeDirection]=useState<number[]>([0,0,1]);
|
||||
const [toolbarPlacement, setToolbarPlacement] = useState<ToolbarPlacement>("bottom");
|
||||
const [toolbarBg, setToolbarBg] = useState("#111115");
|
||||
const [toolbarBorder, setToolbarBorder] = useState("#111117");
|
||||
@@ -480,8 +408,6 @@ export function CatalogApp() {
|
||||
const [toolbarMaxSize, setToolbarMaxSize] = useState(87);
|
||||
const [toolbarLensCount, setToolbarLensCount] = useState(5);
|
||||
const [toolbarAutoHide, setToolbarAutoHide] = useState(false);
|
||||
const [toolbarHideDelay,setToolbarHideDelay]=useState(5000);
|
||||
const [toolbarGap,setToolbarGap]=useState(10);
|
||||
const [shareEmail, setShareEmail] = useState("");
|
||||
const [shareRole, setShareRole] = useState<ShareRole>("editor");
|
||||
const [shareMessage, setShareMessage] = useState("");
|
||||
@@ -545,8 +471,6 @@ export function CatalogApp() {
|
||||
if (typeof stored.toolbar?.minSize === "number") setToolbarMinSize(stored.toolbar.minSize);
|
||||
if (typeof stored.toolbar?.maxSize === "number") setToolbarMaxSize(stored.toolbar.maxSize);
|
||||
if (typeof stored.toolbar?.lensCount === "number") setToolbarLensCount(stored.toolbar.lensCount);
|
||||
if (typeof stored.toolbar?.hideDelay === "number") setToolbarHideDelay(stored.toolbar.hideDelay);
|
||||
if (typeof stored.toolbar?.gap === "number") setToolbarGap(stored.toolbar.gap);
|
||||
if (typeof stored.toolbar?.autoHide === "boolean") setToolbarAutoHide(stored.toolbar.autoHide);
|
||||
}, []);
|
||||
|
||||
@@ -567,8 +491,6 @@ export function CatalogApp() {
|
||||
useEffect(() => {
|
||||
applyNodedcTheme(document.documentElement, {
|
||||
theme,
|
||||
appearance: missionAppearance ? "mission" : "default",
|
||||
edges: flatEdges ? "flat" : "default",
|
||||
accent,
|
||||
material: {
|
||||
panel: panelMaterial,
|
||||
@@ -578,7 +500,7 @@ export function CatalogApp() {
|
||||
},
|
||||
});
|
||||
document.documentElement.style.setProperty("--nodedc-canvas-soft", material.nestedHex);
|
||||
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme, missionAppearance, flatEdges]);
|
||||
}, [accent, fieldMaterial, material.fieldOpacity, material.nestedHex, material.panelOpacity, panelMaterial, theme]);
|
||||
|
||||
useEffect(() => {
|
||||
applyGlassMaterial(document.documentElement, glassMaterial);
|
||||
@@ -649,15 +571,13 @@ export function CatalogApp() {
|
||||
}
|
||||
const toolbar = stored.toolbar;
|
||||
if (toolbar) {
|
||||
if (toolbar.placement === "left" || toolbar.placement === "right" || toolbar.placement === "bottom" || toolbar.placement === "top") setToolbarPlacement(toolbar.placement);
|
||||
if (toolbar.placement === "left" || toolbar.placement === "right" || toolbar.placement === "bottom") setToolbarPlacement(toolbar.placement);
|
||||
if (toolbar.background) setToolbarBg(toolbar.background);
|
||||
if (toolbar.border) setToolbarBorder(toolbar.border);
|
||||
if (toolbar.outline) setToolbarOutline(toolbar.outline);
|
||||
if (typeof toolbar.minSize === "number") setToolbarMinSize(toolbar.minSize);
|
||||
if (typeof toolbar.maxSize === "number") setToolbarMaxSize(toolbar.maxSize);
|
||||
if (typeof toolbar.lensCount === "number") setToolbarLensCount(toolbar.lensCount);
|
||||
if (typeof toolbar.hideDelay === "number") setToolbarHideDelay(toolbar.hideDelay);
|
||||
if (typeof toolbar.gap === "number") setToolbarGap(toolbar.gap);
|
||||
if (typeof toolbar.autoHide === "boolean") setToolbarAutoHide(toolbar.autoHide);
|
||||
}
|
||||
setLayoutSaveState("saved");
|
||||
@@ -1126,7 +1046,6 @@ export function CatalogApp() {
|
||||
maxSize: toolbarMaxSize,
|
||||
lensCount: toolbarLensCount,
|
||||
autoHide: toolbarAutoHide,
|
||||
hideDelay:toolbarHideDelay,gap:toolbarGap,
|
||||
},
|
||||
};
|
||||
const response = await fetch("/api/layout", {
|
||||
@@ -1335,12 +1254,10 @@ export function CatalogApp() {
|
||||
{ value: "left", label: "Слева" },
|
||||
{ value: "right", label: "Справа" },
|
||||
{ value: "bottom", label: "Снизу" },
|
||||
{ value: "top", label: "Сверху" },
|
||||
]}
|
||||
onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)}
|
||||
/>
|
||||
<ControlRow label="Фон"><ColorField value={toolbarBg} onChange={setToolbarBg} /></ControlRow>
|
||||
<Description>HEX можно очистить и набрать заново; Enter применяет, Escape возвращает текущий цвет.</Description>
|
||||
<ControlRow label="Border"><ColorField value={toolbarBorder} onChange={setToolbarBorder} /></ControlRow>
|
||||
<ControlRow label="Outline"><ColorField value={toolbarOutline} onChange={setToolbarOutline} /></ControlRow>
|
||||
<RangeControl label="Минимальный размер" value={toolbarMinSize} min={18} max={42} formatValue={(value) => `${value}px`} onChange={(value) => {
|
||||
@@ -1351,8 +1268,6 @@ export function CatalogApp() {
|
||||
<RangeControl label="Максимальный размер" value={toolbarMaxSize} min={28} max={88} formatValue={(value) => `${value}px`} onChange={(value) => setToolbarMaxSize(Math.max(toolbarMinSize, Math.round(value)))} />
|
||||
<RangeControl label="Линза" value={toolbarLensCount} min={1} max={13} step={2} formatValue={(value) => `${value} иконок`} onChange={(value) => setToolbarLensCount(Math.round(value) % 2 === 0 ? Math.round(value) + 1 : Math.round(value))} />
|
||||
<Checker checked={toolbarAutoHide} label="Автоскрытие" onChange={setToolbarAutoHide} />
|
||||
<RangeControl label="Задержка скрытия" value={toolbarHideDelay} min={0} max={15000} step={250} formatValue={v=>`${v/1000} с`} onChange={setToolbarHideDelay}/>
|
||||
<RangeControl label="Расстояние между кнопками" value={toolbarGap} min={0} max={24} step={1} formatValue={v=>`${v} px`} onChange={setToolbarGap}/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -1364,10 +1279,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} />
|
||||
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} formatValue={(value) => `${value}%`} onChange={setGlowDistance} />
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -1413,24 +1325,14 @@ export function CatalogApp() {
|
||||
case "controls":
|
||||
return (
|
||||
<div className="catalog-grid">
|
||||
<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">
|
||||
<Preview title="Selection" note="integrated / split">
|
||||
<div className="catalog-form">
|
||||
<FieldFrame label="Hub / integrated select" labelPlacement="below">
|
||||
<FieldFrame label="Hub / integrated select">
|
||||
<Select label="Статус" value={selectedStatus} options={[...selectOptions]} searchable onChange={setSelectedStatus} />
|
||||
</FieldFrame>
|
||||
<FieldFrame label="Select / независимое действие строки">
|
||||
<Select label="Записи" value={selectedStatus} searchable onChange={setSelectedStatus}
|
||||
options={selectOptions.map(option => ({ ...option, action: {
|
||||
label: `Удалить ${option.label}`, icon: <Icon name="trash" />, tone: 'danger' as const,
|
||||
disabled: option.value === 'active',
|
||||
onAction: () => setConfirmOpen(true),
|
||||
} }))} />
|
||||
</FieldFrame>
|
||||
<FieldFrame label="Engine / split select">
|
||||
<Select
|
||||
variant="split" shape="pill"
|
||||
variant="split"
|
||||
label="Тип связи"
|
||||
value={connectionType}
|
||||
options={[
|
||||
@@ -1441,19 +1343,6 @@ export function CatalogApp() {
|
||||
onChange={setConnectionType}
|
||||
/>
|
||||
</FieldFrame>
|
||||
<FieldFrame label="Toolbar / inline select">
|
||||
<Select
|
||||
variant="inline"
|
||||
label="Скорость воспроизведения"
|
||||
value="1"
|
||||
options={[
|
||||
{ value: "0.5", label: "0,5×" },
|
||||
{ value: "1", label: "1×" },
|
||||
{ value: "2", label: "2×" },
|
||||
]}
|
||||
onChange={() => undefined}
|
||||
/>
|
||||
</FieldFrame>
|
||||
<Dropdown
|
||||
trigger={({ open, toggle, setTriggerRef, surfaceId }) => (
|
||||
<Button ref={setTriggerRef} aria-expanded={open} aria-controls={surfaceId} icon={<Icon name="chevron-down" />} onClick={toggle}>Действия</Button>
|
||||
@@ -1461,7 +1350,6 @@ export function CatalogApp() {
|
||||
>
|
||||
{({ close }) => (
|
||||
<>
|
||||
<Select label="Вложенный выбор статуса" value={selectedStatus} options={[...selectOptions]} onChange={setSelectedStatus} />
|
||||
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="edit" /><span className="nodedc-dropdown-option__label">Переименовать</span></button>
|
||||
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="copy" /><span className="nodedc-dropdown-option__label">Дублировать</span></button>
|
||||
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="folder" /><span className="nodedc-dropdown-option__label">Архивировать</span></button>
|
||||
@@ -1474,7 +1362,6 @@ 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">
|
||||
@@ -1484,112 +1371,16 @@ export function CatalogApp() {
|
||||
<Button variant="ghost" icon={<Icon name="external" />}>Открыть</Button>
|
||||
<Button variant="danger" icon={<Icon name="trash" />}>Удалить</Button>
|
||||
<IconButton label="Добавить"><Icon name="plus" /></IconButton>
|
||||
<KeyButton label="Клавиша W">W</KeyButton>
|
||||
<KeyButton label="Клавиша A нажата" pressed>A</KeyButton>
|
||||
<KeyButton label="Клавиша S недоступна" disabled>S</KeyButton>
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Подсказки" note="Скруглённое стекло без обводки · hover / focus / touch" className="catalog-preview--compact">
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<IconButton label="Инспектор"><Icon name="network" /></IconButton>
|
||||
<Button title="Общая подсказка для существующего title">Подсказка приложения</Button>
|
||||
<Tooltip content="Короткое пояснение. Escape закрывает только подсказку."><Button>Подробнее</Button></Tooltip>
|
||||
<Tooltip focusable label="Текущий уровень" content="Доступно мышью, клавиатурой и касанием."><StatusBadge tone="neutral">Нормальный уровень</StatusBadge></Tooltip>
|
||||
<Tooltip disabled content="Эта подсказка отключена"><Button disabled>Недоступно</Button></Tooltip>
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Активность" note="default / compact" className="catalog-preview--compact">
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<span className="catalog-inline">
|
||||
<ActivityIndicator label="Загружаем данные" />
|
||||
<span>Загружаем данные</span>
|
||||
</span>
|
||||
<Button loading>Подключить</Button>
|
||||
<IconButton label="Обновить" loading><Icon name="refresh" /></IconButton>
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">При reduced motion кольцо остаётся видимым без вращения; процесс и его завершение принадлежат приложению.</p>
|
||||
</Preview>
|
||||
<Preview title="Загрузка содержимого" note="в центре собственной области">
|
||||
<LoadingRegion loading label="Ожидаем содержимое" />
|
||||
</Preview>
|
||||
<Preview title="Лампы состояния" note="один индикатор без дублирующего значка"><StatusBadge variant="indicator" tone="success" aria-label="Готово" title="Готово" /><StatusBadge variant="indicator" aria-label="Недоступно" title="Недоступно" /><StatusBadge tone="danger" pulse>Требуется внимание</StatusBadge></Preview>
|
||||
<Preview title="Прогресс действия" note="idle / pending / disabled">
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<ProgressButton label="Проанализировать" icon={<Icon name="layers" />} />
|
||||
<ProgressButton label="Проанализировать" icon={<LayerStackIndicator />} progress={{label:"Анализ поверхности · 29 / 96",value:29/96}} />
|
||||
<ProgressButton label="Проанализировать" icon={<LayerStackIndicator />} progress={{label:"Подготовка данных"}} />
|
||||
<ProgressButton label="Проанализировать" disabled icon={<Icon name="layers" />} />
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Независимые слои" note="multiple / empty / all">
|
||||
<SegmentedGroup label="Слои и память">
|
||||
<SegmentedButton active={previewLayers.includes("gaussian")} aria-pressed={previewLayers.includes("gaussian")}
|
||||
onClick={()=>setPreviewLayers(current=>current.includes("gaussian")?current.filter(v=>v!=="gaussian"):[...current,"gaussian"])}>Gaussian</SegmentedButton>
|
||||
<SegmentedButton disabled>Недоступный слой</SegmentedButton>
|
||||
<Dropdown surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><SegmentedButton
|
||||
ref={setTriggerRef} active={open} aria-expanded={open} aria-haspopup="dialog" aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
|
||||
<p>Накопленные проезды этой локации.</p>
|
||||
</Dropdown>
|
||||
</SegmentedGroup>
|
||||
<SegmentedControl selectionMode="multiple" label="Слои сцены" value={previewLayers} onChange={setPreviewLayers}
|
||||
items={[{value:"source",label:"Источник"},{value:"geometry",label:"Геометрия"},{value:"unavailable",label:"Недоступно",disabled:true}]} />
|
||||
</Preview>
|
||||
<Preview title="Уровень ресурса" note="измерение / последние данные / неизвестно">
|
||||
<LevelButton label="Заряд аккумулятора" value={.82} levelTone="success" onClick={()=>setProjectName("Аккумулятор · 82%")}/>
|
||||
<LevelButton label="Заряд аккумулятора" value={.17} levelTone="warning" freshness="stale"/>
|
||||
<LevelButton label="Заряд аккумулятора" value={null} freshness="unknown" disabled/>
|
||||
<LevelButton label="Белая заливка" value={.82} fillColor="#ffffff"/>
|
||||
<LevelButton label="Чёрная заливка" value={.82} fillColor="#000000"/>
|
||||
<LevelButton label="Минимальный индикатор" value={1} valueText="100%" fillColor="#ffffff" geometry={{width:32,height:12,radius:4}}/>
|
||||
<LevelButton label="Широкий индикатор" value={.82} geometry={{width:160,height:24,radius:8}}/>
|
||||
</Preview>
|
||||
<Preview title="Линейный прогресс" note="измеренный / неизвестный / завершённый">
|
||||
<ProgressBar label="Подготовка" value={0.6} valueText="Три этапа из пяти" />
|
||||
<ProgressBar label="Получение сведений" />
|
||||
<ProgressBar label="Завершено" value={1} />
|
||||
</Preview>
|
||||
<Preview title="Строки ресурсов" note="Mission Core / общий список">
|
||||
<ResourceList aria-label="Пример списка ресурсов">
|
||||
<li><ResourceRow icon={<Icon name="file" />} title="Сохранённый результат" metadata="Сегодня · доступен для просмотра" actions={<IconButton label="Просмотреть пример" onClick={() => setProjectName("Сохранённый результат")}><Icon name="eye" /></IconButton>} /></li>
|
||||
<li><ResourceRow icon={<Icon name="camera" />} title="Подключённая камера" description="Индикатор перед названием" statusPlacement="leading" status={<StatusBadge variant="indicator" tone="success" aria-label="Подключено" title="Подключено" />} actions={<IconButton label="Просмотреть камеру" onClick={() => setProjectName("Подключённая камера")}><Icon name="eye" /></IconButton>} /></li>
|
||||
<li><ResourceRow icon={<Icon name="camera" />} title="Подготовка камеры" metadata="Проверка потоков" progress={{label:"Подготовка камеры",value:0.8}} aria-busy="true" actions={<IconButton label="Просмотр недоступен" disabled><Icon name="eye" /></IconButton>} /></li>
|
||||
</ResourceList>
|
||||
<Button onClick={()=>setTreeDemoOpen(true)}>Дерево объектов · изменяемый размер</Button>
|
||||
<DragDropRoot onDragEnd={()=>{}}><DraggableItem id="whole-material-tile">{({activator})=><Button {...activator.attributes} {...activator.listeners}>Перенос за всю плитку</Button>}</DraggableItem></DragDropRoot>
|
||||
<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>
|
||||
<Preview title="Действия поверх сцены" note="круг `32.2 px` · единый viewport-канон 70%" className="catalog-preview--compact">
|
||||
<div className="catalog-window-actions-demo nodedc-scene-controls">
|
||||
<SegmentedControl label="Инструмент сцены" value={applicationMode} items={[{value:"edit",label:"Обзор"},{value:"preview",label:"Точки"}]} onChange={setApplicationMode}/>
|
||||
<Preview title="Оконные действия" note="круг `46 px`" className="catalog-preview--compact">
|
||||
<div className="catalog-window-actions-demo">
|
||||
<Button shape="pill" icon={<Icon name="refresh" />}>Обновить источник</Button>
|
||||
<Select label="Статус примера сцены" value={selectedStatus} options={[...selectOptions]} onChange={setSelectedStatus} />
|
||||
<IconButton label="Добавить"><Icon name="plus" /></IconButton>
|
||||
<IconButton label="Развернуть"><Icon name="expand" /></IconButton>
|
||||
<IconButton label="Закрыть"><Icon name="close" /></IconButton>
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Вертикальная рейка" note="glass pill / круг `46 px`" className="catalog-preview--compact">
|
||||
<GlassSurface
|
||||
className="catalog-icon-rail-demo"
|
||||
tone="strong"
|
||||
radius="pill"
|
||||
padding="sm"
|
||||
materialRim={false}
|
||||
role="toolbar"
|
||||
aria-label="Режимы просмотра"
|
||||
>
|
||||
<IconButton label="Камера" aria-pressed="true"><Icon name="camera" /></IconButton>
|
||||
<IconButton label="3D"><span aria-hidden="true">3D</span></IconButton>
|
||||
<IconButton label="План"><Icon name="plan" /></IconButton>
|
||||
</GlassSurface>
|
||||
</Preview>
|
||||
<Preview title="Workspace window" note="inline / bounded / controlled" className="catalog-preview--wide catalog-workspace-window-preview">
|
||||
<div ref={workspaceWindowDemoRef} className="catalog-workspace-window-demo">
|
||||
{workspaceWindowDemoOpen ? (
|
||||
@@ -1604,7 +1395,6 @@ export function CatalogApp() {
|
||||
setWorkspaceWindowDemoOpen(false);
|
||||
setWorkspaceWindowDemoMaximized(false);
|
||||
}}
|
||||
resizeIndicator={false}
|
||||
title="Визуальный канал"
|
||||
subtitle="WORKSPACE / AUXILIARY VIEW"
|
||||
status="LIVE"
|
||||
@@ -1629,29 +1419,6 @@ export function CatalogApp() {
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
|
||||
</Preview>
|
||||
<Preview title="Split pane" note="pointer resize: invisible / keyboard focus: visible" className="catalog-preview--wide catalog-split-pane-preview">
|
||||
<Switch label="Скрыть линию разделителя" checked={splitPaneInvisible} onChange={setSplitPaneInvisible} />
|
||||
<div className="catalog-split-pane-demo">
|
||||
<SplitPane
|
||||
primarySize={splitPaneDemoSize}
|
||||
separatorAppearance={splitPaneInvisible ? "invisible" : "line"}
|
||||
onPrimarySizeChange={setSplitPaneDemoSize}
|
||||
minPrimarySize={25}
|
||||
minSecondarySize={25}
|
||||
separatorLabel="Изменить ширину синхронных представлений"
|
||||
primary={<div className="catalog-split-pane-demo__panel"><Icon name="video" /><strong>Видео</strong></div>}
|
||||
secondary={<div className="catalog-split-pane-demo__panel"><Icon name="grid" /><strong>Пространственная сцена</strong></div>}
|
||||
/>
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">Граница изменяет контролируемую долю панелей; клавиши и pointer используют одни ограничения, а resize контейнера не сбрасывает выбранное соотношение.</p>
|
||||
</Preview>
|
||||
<Preview title="Dock layout" note="center swap / panel edges / workspace edges / keyboard" className="catalog-preview--wide">
|
||||
<div style={{height:420}}><DockLayout tree={dockDemoTree} onTreeChange={setDockDemoTree}
|
||||
panels={[{id:'camera',label:'Камера'},{id:'depth',label:'Глубина'},{id:'map',label:'Карта'},{id:'scene',label:'Сцена',minimumSize:{width:320,height:280}}]}
|
||||
renderPanel={id=><GlassSurface tone="soft" radius="panel" style={{height:'100%'}}><DockHandle id={id} label={id}/><strong>{id}</strong></GlassSurface>}/></div>
|
||||
<p>Центр окна — обмен, край окна — разделение, внешний край всей области — на всю сторону. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой; Shift + стрелки выбирают край всей области.</p>
|
||||
</Preview>
|
||||
<Preview title="Scene editor docking" note="fixed primary / detachable tools / return" className="catalog-preview--wide"><EditorDockExample/></Preview>
|
||||
<Preview title="Application side panel" note="end / push / controlled" className="catalog-preview--wide catalog-side-panel-preview">
|
||||
<div className="catalog-side-panel-demo">
|
||||
{sidePanelDemoOpen ? (
|
||||
@@ -1659,10 +1426,9 @@ 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 />
|
||||
<Inspector variant="panel" sections={environmentSections.slice(0, 3)} defaultOpen={[environmentSections[0]?.id ?? ""]} singleOpen />
|
||||
</ApplicationSidePanel>
|
||||
) : (
|
||||
<Button shape="pill" icon={<Icon name="panel" />} onClick={() => setSidePanelDemoOpen(true)}>Открыть правую панель</Button>
|
||||
@@ -1685,10 +1451,6 @@ export function CatalogApp() {
|
||||
description="MP4 или URL становятся частью единого server-side layout вместе с темой, материалом и Toolbar."
|
||||
actions={<Switch checked={mediaVisible} label="Показать" onChange={setMediaVisible} />}
|
||||
>
|
||||
<div style={{"--nodedc-accent-rgb":"247 248 244","--nodedc-on-accent-rgb":"8 8 10"} as CSSProperties}>
|
||||
<Switch checked={mediaVisible} label="Белый акцент · видимость" onChange={setMediaVisible} />
|
||||
<Switch checked={false} label="Выключено" disabled onChange={()=>{}} />
|
||||
</div>
|
||||
<MediaSourceField
|
||||
label="Видео / картинка"
|
||||
source={mediaSource}
|
||||
@@ -1758,22 +1520,16 @@ export function CatalogApp() {
|
||||
case "glass":
|
||||
return (
|
||||
<div className="catalog-glass-lab">
|
||||
<ResizableViewport className="catalog-glass-stage" resizeIndicator={false} height={sceneDemoHeight} minHeight={360} maxHeight={900} onHeightChange={setSceneDemoHeight}>
|
||||
<section className="catalog-glass-stage">
|
||||
<video key={stageMediaSrc} autoPlay muted loop playsInline aria-hidden="true"><source src={stageMediaSrc} type="video/mp4" /></video>
|
||||
<div className="catalog-glass-stage__shade" />
|
||||
<div className="catalog-viewport-actions nodedc-viewport-controls">
|
||||
<IconButton label="Приблизить пример" onClick={()=>setSceneDemoHeight(value=>Math.min(900,value+40))}><Icon name="plus"/></IconButton>
|
||||
<IconButton label="Отдалить пример" onClick={()=>setSceneDemoHeight(value=>Math.max(360,value-40))}><Icon name="minus"/></IconButton>
|
||||
<IconButton label="Вернуть размер примера" onClick={()=>setSceneDemoHeight(480)}><Icon name="select"/></IconButton>
|
||||
</div>
|
||||
<GlassMaterialSurface context="scene" radius="panel" material={glassMaterial} radiusPx={24} className="catalog-glass-stage__sample">
|
||||
<GlassMaterialSurface className="catalog-glass-stage__sample">
|
||||
<span>CANONICAL GLASS</span>
|
||||
<h2>Прозрачная плашка над сценой</h2>
|
||||
<SceneAnnotation aria-label="Ячейка 01 · 4,15 В"><span>01</span><strong>4,15 В</strong></SceneAnnotation>
|
||||
<h2>Модальное окно и Inspector</h2>
|
||||
<p>Фон остаётся различимым, но текст и контролы сохраняют контраст. Этот материал не применяется к обычным панелям приложения.</p>
|
||||
<div className="catalog-inline"><TextField label="Пример поля" name="organization" autoComplete="organization" defaultValue="NODE.DC" description="Автозаполнение сохраняет материал поля и клавиатурный фокус текущей темы." /><Button variant="primary" shape="pill">Применить</Button></div>
|
||||
<div className="catalog-inline"><TextField label="Пример поля" defaultValue="NODE.DC" /><Button variant="primary" shape="pill">Применить</Button></div>
|
||||
</GlassMaterialSurface>
|
||||
</ResizableViewport>
|
||||
</section>
|
||||
<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>
|
||||
@@ -1804,7 +1560,6 @@ 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>
|
||||
@@ -1829,9 +1584,6 @@ export function CatalogApp() {
|
||||
<p className="catalog-preview__explanation">Destructive-цвет появляется только у подтверждения.</p>
|
||||
<Button variant="danger" shape="pill" icon={<Icon name="trash" />} onClick={() => setConfirmOpen(true)}>Проверить удаление</Button>
|
||||
</Preview>
|
||||
<Preview title="Настройки модуля" note="адаптивное меню и форма" className="catalog-modal-preview"><Switch label="Без декоративных обводок" checked={flatEdges} onChange={setFlatEdges} /><Switch label="Визуальный профиль Mission Core" checked={missionAppearance} onChange={setMissionAppearance} />
|
||||
<Button icon={<Icon name="settings" />} onClick={() => setFeatureSettingsDemoOpen(true)}>Открыть настройки модуля</Button>
|
||||
</Preview>
|
||||
<Preview title="Workflow sharing" note="ENGINE / access" className="catalog-modal-preview">
|
||||
<p className="catalog-preview__explanation">Участники, роли, приглашение и immutable-владелец.</p>
|
||||
<Button variant="primary" shape="pill" icon={<Icon name="users" />} onClick={() => setShareAccessOpen(true)}>Поделиться графом</Button>
|
||||
@@ -1870,10 +1622,6 @@ 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>
|
||||
<IconButton label="Обновить"><Icon name="refresh" /></IconButton>
|
||||
<IconButton label="Развернуть"><Icon name="expand" /></IconButton>
|
||||
@@ -1989,7 +1737,7 @@ export function CatalogApp() {
|
||||
title="Состав страниц"
|
||||
description="Перетащите готовую страницу справа в конфигурацию приложения. Свободного canvas и произвольных компонентов нет."
|
||||
>
|
||||
<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 }) => {
|
||||
<DragDropRoot 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
|
||||
@@ -2178,7 +1926,6 @@ export function CatalogApp() {
|
||||
endPanel={<div ref={setMapSettingsPanelHost} className="catalog-map-settings-panel-host" />}
|
||||
header={
|
||||
<AppHeader
|
||||
brandMonochrome
|
||||
brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />}
|
||||
brandHref="/"
|
||||
center={
|
||||
@@ -2203,12 +1950,10 @@ 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}
|
||||
@@ -2218,6 +1963,7 @@ export function CatalogApp() {
|
||||
{ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" },
|
||||
]}
|
||||
/>
|
||||
</HeaderProfile>
|
||||
}
|
||||
/>
|
||||
}
|
||||
@@ -2239,8 +1985,6 @@ 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" ? (
|
||||
@@ -2372,7 +2116,7 @@ export function CatalogApp() {
|
||||
/>
|
||||
|
||||
{guidelineOpen && studioContext === "visual" ? (
|
||||
<Toolbar<CatalogSection | "hold">
|
||||
<Toolbar<CatalogSection>
|
||||
placement={toolbarPlacement}
|
||||
background={toolbarBg}
|
||||
border={toolbarBorder}
|
||||
@@ -2382,42 +2126,31 @@ export function CatalogApp() {
|
||||
maxSize={toolbarMaxSize}
|
||||
lensCount={toolbarLensCount}
|
||||
autoHide={toolbarAutoHide}
|
||||
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]) => ({
|
||||
items={(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
|
||||
id,
|
||||
label: item.title,
|
||||
shortcut: id === "icons" ? "I" : undefined,
|
||||
icon: item.icon,
|
||||
active: activeSection === id,
|
||||
onSelect: () => openSection(id),
|
||||
}))]}
|
||||
onSelect: openSection,
|
||||
}))}
|
||||
/>
|
||||
) : 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 header={<Description>Поля и секции разделены единым шагом 12 px.</Description>} footer={<Button variant="primary" tone="neutral" onClick={()=>setInspectorOpen(false)}>Готово</Button>} sections={environmentSections} defaultOpen={["application-material"]} />
|
||||
<Inspector sections={environmentSections} defaultOpen={["application-material"]} />
|
||||
</Window>
|
||||
|
||||
<Window
|
||||
open={createModuleOpen}
|
||||
floating={detailFloating} onFloatingChange={setDetailFloating}
|
||||
rect={detailRect} onRectCommit={setDetailRect}
|
||||
title="Создать модуль"
|
||||
headerActionsPlacement="before-close"
|
||||
headerActions={<IconButton label="Очистить форму" onClick={() => {setCreateModuleName("");setCreateModuleSlug("");}}><Icon name="trash"/></IconButton>}
|
||||
subtitle="Свободное окно · шапка: перемещение · края: размер"
|
||||
subtitle="APPLICATION / DRAFT"
|
||||
size="sm"
|
||||
onClose={() => setCreateModuleOpen(false)}
|
||||
footer={
|
||||
@@ -2511,19 +2244,8 @@ export function CatalogApp() {
|
||||
|
||||
<FoundrySettingsModal open={foundrySettingsOpen} isAdmin={isFoundryAdmin} onClose={() => setFoundrySettingsOpen(false)} />
|
||||
|
||||
<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><div><p>Пояснение прежнего потребителя без класса — тот же компактный стиль.</p></div><Description role="status">Ожидаем ответ устройства…</Description><ComparisonTable density="compact" label="Сравнение устройств" heading="Устройство" columns={Array.from({length:4},(_,i)=>({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/><LoadingRegion aggregate loading label="Загрузка сведений"><LoadingRegion loading label="Вложенный запрос A"/><LoadingRegion loading label="Вложенный запрос B"/></LoadingRegion></SettingsCard>}
|
||||
</FeatureSettingsWindow>
|
||||
|
||||
<Window
|
||||
open={createModalOpen}
|
||||
headerActions={<IconButton label="Обновить пример" onClick={() => setProjectName("Обновлено")}><Icon name="refresh" /></IconButton>}
|
||||
title="Создать проект"
|
||||
subtitle="Адаптивная форма"
|
||||
size="sm"
|
||||
@@ -2650,9 +2372,7 @@ export function CatalogApp() {
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
onConfirm={() => setConfirmOpen(false)}
|
||||
/>
|
||||
<ToastObserver onPresent={setObservedToasts}>
|
||||
<ToastStack items={toasts} onDismiss={dismissToast} />
|
||||
</ToastObserver>
|
||||
<ToastStack items={toasts} onDismiss={dismissToast} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
+124
-1991
File diff suppressed because it is too large
Load Diff
@@ -1,15 +0,0 @@
|
||||
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></>;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { EnvironmentSettings } from "@nodedc/ui-core";
|
||||
import { Button, EnvironmentSettingsWindow, LandingStage, UserProfileMenu } from "@nodedc/ui-react";
|
||||
|
||||
const initial: EnvironmentSettings = { revision: 0, pages: { home: {
|
||||
headerLabel: "Продукт", eyebrow: "NODE.DC / ГЛАВНАЯ", title: "Главная продукта",
|
||||
description: "Общая композиция страницы и настроек окружения.", primaryWorkspaceId: null, secondaryWorkspaceId: null,
|
||||
background: { enabled: false, imageDurationSeconds: 10, items: [] },
|
||||
} } };
|
||||
|
||||
export function EnvironmentCatalogDemo() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [settings, setSettings] = useState(initial);
|
||||
const urls = useRef<string[]>([]);
|
||||
useEffect(() => () => urls.current.forEach(url => URL.revokeObjectURL(url)), []);
|
||||
return <>
|
||||
<div className="catalog-environment-actions">
|
||||
<UserProfileMenu variant="default" displayName="DC" subtitle="Каталог компонентов" triggerLabel={null}
|
||||
actions={[{ id: "settings", label: "Настройки", icon: "settings", onSelect: () => setOpen(true) }]} />
|
||||
<Button variant="primary" tone="neutral" onClick={() => setOpen(true)}>Настройки окружения</Button>
|
||||
<Button variant="primary" tone="neutral" disabled>Неактивное действие</Button>
|
||||
</div>
|
||||
<div className="catalog-environment-stage"><LandingStage page={settings.pages.home} /></div>
|
||||
<EnvironmentSettingsWindow open={open} onClose={() => setOpen(false)} productName="Продукт"
|
||||
additionalSections={[{ id: "storage", label: "Хранилище", icon: "database", content: <p>Настройки хранения продукта используют общий каркас окна.</p> }]}
|
||||
surfaces={[{ id: "home", home: true, description: "Главная страница продукта", actions: [] }]}
|
||||
settings={settings} state="ready" error={null}
|
||||
onSave={async draft => { const next = { ...draft, revision: draft.revision + 1 }; setSettings(next); return next; }}
|
||||
onUpload={async (_surface, _item, file) => {
|
||||
const url = URL.createObjectURL(file); urls.current.push(url);
|
||||
return { url, fileName: file.name, mediaKind: file.type.startsWith("video/") ? "video" : "image" };
|
||||
}} />
|
||||
</>;
|
||||
}
|
||||
+396
-1844
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,212 @@
|
||||
import type { RefObject } from "react";
|
||||
import { Button, Checker, Icon, WorkspaceWindow } from "@nodedc/ui-react";
|
||||
import type { WorkspaceWindowRect } from "@nodedc/ui-react";
|
||||
import type { GridSectorSelection } from "./mapRendererContract.js";
|
||||
import {
|
||||
MAP_SCOPE_MISSING_VALUE,
|
||||
MAP_SCOPE_OBJECT_KIND_FIELD,
|
||||
MAP_SCOPE_PROVIDER_FIELD,
|
||||
formatGridSectorArea,
|
||||
gridSectorBoundsLabel,
|
||||
normalizedSectorScopeValue,
|
||||
} from "./mapSectorWorkspace.js";
|
||||
import type { MapSelectableEntity } from "./mapWorkspaceModel.mjs";
|
||||
|
||||
type ScopeOption = { value: string; label: string; count: number };
|
||||
|
||||
export function MapSectorWorkspaceWindow({
|
||||
boundsRef,
|
||||
selection,
|
||||
rect,
|
||||
maximized,
|
||||
active,
|
||||
zIndex,
|
||||
copyState,
|
||||
spatialEntities,
|
||||
visibleEntities,
|
||||
bindingOptions,
|
||||
providerOptions,
|
||||
objectKindOptions,
|
||||
excludedBindingIds,
|
||||
excludedProviders,
|
||||
excludedObjectKinds,
|
||||
hideOutside,
|
||||
selectedEntityId,
|
||||
onRectChange,
|
||||
onMaximizedChange,
|
||||
onActivate,
|
||||
onDeactivate,
|
||||
onCopyStableId,
|
||||
onHideOutsideChange,
|
||||
onBindingEnabledChange,
|
||||
onProviderEnabledChange,
|
||||
onObjectKindEnabledChange,
|
||||
onSelectEntity,
|
||||
}: {
|
||||
boundsRef: RefObject<HTMLElement | null>;
|
||||
selection: GridSectorSelection;
|
||||
rect: WorkspaceWindowRect;
|
||||
maximized: boolean;
|
||||
active: boolean;
|
||||
zIndex: number;
|
||||
copyState: "idle" | "copied" | "error";
|
||||
spatialEntities: MapSelectableEntity[];
|
||||
visibleEntities: MapSelectableEntity[];
|
||||
bindingOptions: ScopeOption[];
|
||||
providerOptions: ScopeOption[];
|
||||
objectKindOptions: ScopeOption[];
|
||||
excludedBindingIds: string[];
|
||||
excludedProviders: string[];
|
||||
excludedObjectKinds: string[];
|
||||
hideOutside: boolean;
|
||||
selectedEntityId?: string;
|
||||
onRectChange: (rect: WorkspaceWindowRect) => void;
|
||||
onMaximizedChange: (value: boolean) => void;
|
||||
onActivate: () => void;
|
||||
onDeactivate: () => void;
|
||||
onCopyStableId: () => void;
|
||||
onHideOutsideChange: (value: boolean) => void;
|
||||
onBindingEnabledChange: (bindingId: string, enabled: boolean) => void;
|
||||
onProviderEnabledChange: (provider: string, enabled: boolean) => void;
|
||||
onObjectKindEnabledChange: (objectKind: string, enabled: boolean) => void;
|
||||
onSelectEntity: (entityId: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<WorkspaceWindow
|
||||
boundsRef={boundsRef}
|
||||
rect={rect}
|
||||
onRectChange={onRectChange}
|
||||
maximized={maximized}
|
||||
onMaximizedChange={onMaximizedChange}
|
||||
onActivate={onActivate}
|
||||
onClose={onDeactivate}
|
||||
title={`Активный сектор · LOD ${selection.lod}`}
|
||||
subtitle={selection.label}
|
||||
status={`${visibleEntities.length} / ${spatialEntities.length}`}
|
||||
active={active}
|
||||
zIndex={zIndex}
|
||||
minWidth={340}
|
||||
minHeight={380}
|
||||
footer={(
|
||||
<Button variant="secondary" size="compact" width="full" onClick={onDeactivate}>
|
||||
Деактивировать сектор
|
||||
</Button>
|
||||
)}
|
||||
className="catalog-map-fixture__sector-window catalog-map-fixture__map-glass-window"
|
||||
aria-label={`Активный сектор: ${selection.id}`}
|
||||
>
|
||||
<div className="catalog-map-sector-window">
|
||||
<section className="catalog-map-sector-window__summary" aria-label="Параметры сектора">
|
||||
<code title={selection.id}>{selection.id}</code>
|
||||
<span>{gridSectorBoundsLabel(selection)}</span>
|
||||
<span>{formatGridSectorArea(selection.areaSquareMeters)}</span>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="compact"
|
||||
width="full"
|
||||
icon={<Icon name={copyState === "copied" ? "check" : "copy"} />}
|
||||
onClick={onCopyStableId}
|
||||
>{copyState === "copied" ? "ID скопирован" : "Копировать stable ID"}</Button>
|
||||
</section>
|
||||
|
||||
<Checker checked={hideOutside} label="Скрыть объекты за сектором" onChange={onHideOutsideChange} />
|
||||
|
||||
<ScopeFilterSection
|
||||
id="map-sector-domains"
|
||||
title="Домены данных"
|
||||
options={bindingOptions}
|
||||
excluded={excludedBindingIds}
|
||||
onEnabledChange={onBindingEnabledChange}
|
||||
/>
|
||||
|
||||
{providerOptions.length ? (
|
||||
<ScopeFilterSection
|
||||
id="map-sector-providers"
|
||||
title="Провайдеры"
|
||||
options={providerOptions}
|
||||
excluded={excludedProviders}
|
||||
exposeRawValue
|
||||
onEnabledChange={onProviderEnabledChange}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{objectKindOptions.length ? (
|
||||
<ScopeFilterSection
|
||||
id="map-sector-kinds"
|
||||
title="Типы объектов"
|
||||
options={objectKindOptions}
|
||||
excluded={excludedObjectKinds}
|
||||
exposeRawValue
|
||||
onEnabledChange={onObjectKindEnabledChange}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<section className="catalog-map-sector-window__objects" aria-labelledby="map-sector-objects-title">
|
||||
<div className="catalog-map-sector-window__section-title">
|
||||
<strong id="map-sector-objects-title">Объекты сектора</strong>
|
||||
<small>{visibleEntities.length} / {spatialEntities.length}</small>
|
||||
</div>
|
||||
<div className="catalog-map-sector-window__object-list">
|
||||
{visibleEntities.map((entity) => {
|
||||
const provider = normalizedSectorScopeValue(entity.fact.attributes[MAP_SCOPE_PROVIDER_FIELD]);
|
||||
const objectKind = normalizedSectorScopeValue(entity.fact.attributes[MAP_SCOPE_OBJECT_KIND_FIELD]);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={entity.id}
|
||||
data-selected={entity.id === selectedEntityId || undefined}
|
||||
onClick={() => onSelectEntity(entity.id)}
|
||||
>
|
||||
<span>{entity.title}</span>
|
||||
<code>{entity.fact.sourceId}</code>
|
||||
<small>{[provider, objectKind, entity.status].filter(Boolean).join(" · ")}</small>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{!visibleEntities.length ? (
|
||||
<small className="catalog-map-sector-window__empty">
|
||||
{spatialEntities.length
|
||||
? "Объекты скрыты текущими фильтрами."
|
||||
: "В секторе нет точечных объектов подключённых Data Products."}
|
||||
</small>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</WorkspaceWindow>
|
||||
);
|
||||
}
|
||||
|
||||
function ScopeFilterSection({
|
||||
id,
|
||||
title,
|
||||
options,
|
||||
excluded,
|
||||
exposeRawValue = false,
|
||||
onEnabledChange,
|
||||
}: {
|
||||
id: string;
|
||||
title: string;
|
||||
options: ScopeOption[];
|
||||
excluded: string[];
|
||||
exposeRawValue?: boolean;
|
||||
onEnabledChange: (value: string, enabled: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<section className="catalog-map-sector-window__filters" aria-labelledby={`${id}-title`}>
|
||||
<div className="catalog-map-sector-window__section-title">
|
||||
<strong id={`${id}-title`}>{title}</strong>
|
||||
<small>{options.length}</small>
|
||||
</div>
|
||||
{options.map((option) => (
|
||||
<Checker
|
||||
key={option.value}
|
||||
checked={!excluded.includes(option.value)}
|
||||
label={`${option.label} · ${option.count}`}
|
||||
title={exposeRawValue && option.value !== MAP_SCOPE_MISSING_VALUE ? option.value : undefined}
|
||||
onChange={(enabled) => onEnabledChange(option.value, enabled)}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import type { Dispatch, RefObject } from "react";
|
||||
import { Icon, SegmentedControl, WorkspaceWindow } from "@nodedc/ui-react";
|
||||
import {
|
||||
mapFactMatchesFilters,
|
||||
mapPresentationFacetValueIsEnabled,
|
||||
} from "./mapPresentationProfile.mjs";
|
||||
import type { MapSubjectCardModel } from "./mapSubjectCard.mjs";
|
||||
import {
|
||||
mapProfileHasSubjectWindowControls,
|
||||
type MapFilteredTarget,
|
||||
type MapPresentationSummary,
|
||||
type MapSelectableEntity,
|
||||
} from "./mapWorkspaceModel.mjs";
|
||||
import type {
|
||||
MapWorkspaceAction,
|
||||
MapWorkspaceState,
|
||||
} from "./mapWorkspaceState.mjs";
|
||||
|
||||
export function MapSubjectWorkspaceWindows({
|
||||
boundsRef,
|
||||
workspaceState,
|
||||
dispatch,
|
||||
summaries,
|
||||
filteredTargets,
|
||||
selectable,
|
||||
expandedFacetRows,
|
||||
selectedSubjectCard,
|
||||
onToggleFacetRow,
|
||||
onTogglePresentationFilter,
|
||||
onSelectEntity,
|
||||
}: {
|
||||
boundsRef: RefObject<HTMLElement | null>;
|
||||
workspaceState: MapWorkspaceState;
|
||||
dispatch: Dispatch<MapWorkspaceAction>;
|
||||
summaries: MapPresentationSummary[];
|
||||
filteredTargets: MapFilteredTarget[];
|
||||
selectable: MapSelectableEntity[];
|
||||
expandedFacetRows: Record<string, boolean>;
|
||||
selectedSubjectCard: MapSubjectCardModel | null;
|
||||
onToggleFacetRow: (rowId: string) => void;
|
||||
onTogglePresentationFilter: (bindingId: string, field: string, value: string, availableValues: string[]) => void;
|
||||
onSelectEntity: (entityId: string) => void;
|
||||
}) {
|
||||
const selectedEntityId = workspaceState.selectedEntityId;
|
||||
return (
|
||||
<>
|
||||
{summaries.map((summary) => {
|
||||
const state = workspaceState.subjectStates[summary.bindingId];
|
||||
if (!state?.window.open || !mapProfileHasSubjectWindowControls(summary.profile)) return null;
|
||||
const visibleCount = filteredTargets.filter((target) => target.bindingId === summary.bindingId && target.renderable).length;
|
||||
return (
|
||||
<WorkspaceWindow
|
||||
key={summary.bindingId}
|
||||
boundsRef={boundsRef}
|
||||
rect={state.window.rect}
|
||||
onRectChange={(rect) => dispatch({
|
||||
type: "set-subject-window-rect",
|
||||
bindingId: summary.bindingId,
|
||||
rect,
|
||||
})}
|
||||
maximized={state.window.maximized}
|
||||
onMaximizedChange={(value) => dispatch({
|
||||
type: "set-subject-window-maximized",
|
||||
bindingId: summary.bindingId,
|
||||
value,
|
||||
})}
|
||||
onActivate={() => dispatch({ type: "activate-window", windowId: `binding:${summary.bindingId}` })}
|
||||
onClose={() => dispatch({ type: "close-subject-window", bindingId: summary.bindingId })}
|
||||
title={summary.displayName}
|
||||
subtitle={`${summary.total} всего · ${visibleCount} на карте`}
|
||||
active={workspaceState.activeWindowId === `binding:${summary.bindingId}`}
|
||||
zIndex={state.window.zIndex}
|
||||
minWidth={240}
|
||||
minHeight={220}
|
||||
autoHeight
|
||||
className="catalog-map-fixture__subject-window catalog-map-fixture__map-glass-window"
|
||||
>
|
||||
<div className="catalog-map-fixture__target-filters">
|
||||
<section aria-label={`${summary.displayName}: фильтры и счётчики`}>
|
||||
<div className="catalog-map-fixture__target-filter-list">
|
||||
{summary.profile.facets.filter((facet) => facet.counter || facet.filterable).flatMap((facet) => (
|
||||
facet.values.map((item) => {
|
||||
const active = mapPresentationFacetValueIsEnabled(state.filters, facet.field, item.value);
|
||||
const rowId = `${summary.bindingId}:${facet.field}:${item.value}`;
|
||||
const expanded = Boolean(expandedFacetRows[rowId]);
|
||||
const matchingEntities = selectable.filter((entity) => (
|
||||
entity.bindingId === summary.bindingId
|
||||
&& mapFactMatchesFilters(
|
||||
entity.fact,
|
||||
summary.profile,
|
||||
{
|
||||
[summary.bindingId]: {
|
||||
visible: true,
|
||||
facets: { [facet.field]: [item.value] },
|
||||
},
|
||||
},
|
||||
summary.bindingId,
|
||||
)
|
||||
));
|
||||
return (
|
||||
<div className="catalog-map-fixture__target-filter-branch" key={`${facet.field}:${item.value}`}>
|
||||
<div className="catalog-map-fixture__target-filter-row" data-active={active || undefined}>
|
||||
<button
|
||||
type="button"
|
||||
className="catalog-map-fixture__target-filter-body"
|
||||
aria-pressed={active}
|
||||
disabled={!facet.filterable}
|
||||
onClick={() => onTogglePresentationFilter(
|
||||
summary.bindingId,
|
||||
facet.field,
|
||||
item.value,
|
||||
facet.values.map((value) => value.value),
|
||||
)}
|
||||
>
|
||||
<span className="catalog-map-fixture__target-filter-label">{item.label}</span>
|
||||
<span className="catalog-map-fixture__target-filter-count">{summary.counts[facet.field]?.[item.value] ?? 0}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="catalog-map-fixture__target-filter-expander"
|
||||
aria-label={`${expanded ? "Свернуть" : "Развернуть"} ${item.label}`}
|
||||
aria-expanded={expanded}
|
||||
onClick={() => onToggleFacetRow(rowId)}
|
||||
>
|
||||
<Icon name="chevron-right" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{expanded ? (
|
||||
<div className="catalog-map-fixture__target-filter-children">
|
||||
{matchingEntities.map((entity) => (
|
||||
<button
|
||||
type="button"
|
||||
className="catalog-map-fixture__target-filter-entity"
|
||||
key={entity.id}
|
||||
data-selected={entity.id === selectedEntityId || undefined}
|
||||
onClick={() => onSelectEntity(entity.id)}
|
||||
>
|
||||
<span>{entity.title}</span>
|
||||
{entity.status ? <small>{entity.status}</small> : null}
|
||||
</button>
|
||||
))}
|
||||
{!matchingEntities.length ? <small>Нет объектов в группе.</small> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</WorkspaceWindow>
|
||||
);
|
||||
})}
|
||||
|
||||
{workspaceState.subjectCard.open && selectedSubjectCard ? (
|
||||
<WorkspaceWindow
|
||||
boundsRef={boundsRef}
|
||||
rect={workspaceState.subjectCard.rect}
|
||||
onRectChange={(rect) => dispatch({ type: "set-subject-card-rect", rect })}
|
||||
maximized={workspaceState.subjectCard.maximized}
|
||||
onMaximizedChange={(value) => dispatch({ type: "set-subject-card-maximized", value })}
|
||||
onActivate={() => dispatch({ type: "activate-window", windowId: "subject-card" })}
|
||||
onClose={() => dispatch({ type: "close-subject-card" })}
|
||||
title={selectedSubjectCard.title}
|
||||
subtitle={selectedSubjectCard.sourceId}
|
||||
active={workspaceState.activeWindowId === "subject-card"}
|
||||
zIndex={workspaceState.subjectCard.zIndex}
|
||||
minWidth={320}
|
||||
minHeight={320}
|
||||
className="catalog-map-fixture__subject-card catalog-map-fixture__map-glass-window"
|
||||
aria-label={`Карточка объекта: ${selectedSubjectCard.title}`}
|
||||
>
|
||||
<MapSubjectCard
|
||||
model={selectedSubjectCard}
|
||||
tabId={workspaceState.subjectCard.tabId}
|
||||
onTabChange={(tabId) => dispatch({ type: "set-subject-card-tab", tabId })}
|
||||
/>
|
||||
</WorkspaceWindow>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MapSubjectCard({
|
||||
model,
|
||||
tabId,
|
||||
onTabChange,
|
||||
}: {
|
||||
model: MapSubjectCardModel;
|
||||
tabId: string;
|
||||
onTabChange: (tabId: string) => void;
|
||||
}) {
|
||||
const activeTabId = model.tabs.some((tab) => tab.id === tabId) ? tabId : model.defaultTabId;
|
||||
return (
|
||||
<div className="catalog-map-subject-card">
|
||||
<div className="catalog-map-subject-card__tabs">
|
||||
<SegmentedControl
|
||||
value={activeTabId}
|
||||
items={model.tabs.map((tab) => ({ value: tab.id, label: tab.label }))}
|
||||
label="Разделы карточки объекта"
|
||||
onChange={onTabChange}
|
||||
/>
|
||||
</div>
|
||||
{model.tabs.filter((tab) => tab.id === activeTabId).map((tab) => (
|
||||
<div key={tab.id} className="catalog-map-subject-card__tab-panel" role="tabpanel">
|
||||
{tab.empty ? <div className="catalog-map-subject-card__empty">{tab.emptyMessage}</div> : null}
|
||||
{tab.sections.map((section) => (
|
||||
<section key={section.id} className="catalog-map-subject-card__section" aria-labelledby={`subject-card-${tab.id}-${section.id}`}>
|
||||
<h3 id={`subject-card-${tab.id}-${section.id}`}>{section.label}</h3>
|
||||
{section.rows.length ? (
|
||||
<dl>
|
||||
{section.rows.map((row) => (
|
||||
<div key={row.key} className="catalog-map-subject-card__row">
|
||||
<dt>{row.label}</dt>
|
||||
<dd>{row.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : null}
|
||||
{section.readings.length ? (
|
||||
<div className="catalog-map-subject-card__readings">
|
||||
{section.readings.map((reading) => (
|
||||
<div className="catalog-map-subject-card__reading" key={reading.id}>
|
||||
<span>{reading.label}</span>
|
||||
<strong>{reading.value}</strong>
|
||||
{reading.observedAt ? <time dateTime={reading.observedAt}>{new Date(reading.observedAt).toLocaleString("ru-RU")}</time> : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
import type { KeyboardEvent, RefObject } from "react";
|
||||
import { Checker, Dropdown, Icon, IconButton } from "@nodedc/ui-react";
|
||||
import type { MapPageSettings, MapSubjectState } from "./mapPageContract.js";
|
||||
import type { MapProviderStatus } from "./mapRendererContract.js";
|
||||
import type { MapSearchDocument } from "./mapSearch.mjs";
|
||||
import {
|
||||
mapProfileHasSubjectWindowControls,
|
||||
type MapFilteredTarget,
|
||||
type MapPresentationSummary,
|
||||
} from "./mapWorkspaceModel.mjs";
|
||||
|
||||
type ReferenceObjectSummary = {
|
||||
layer: { id: string; visible: boolean };
|
||||
displayName: string;
|
||||
total: number;
|
||||
};
|
||||
|
||||
const providerStateLabel: Record<MapProviderStatus["imagery"], string> = {
|
||||
loading: "загружается",
|
||||
ready: "готов",
|
||||
error: "недоступен",
|
||||
"not-configured": "не настроен",
|
||||
};
|
||||
|
||||
export function MapWorkspaceToolbar({
|
||||
searchOpen,
|
||||
searchQuery,
|
||||
searchInputRef,
|
||||
searchResults,
|
||||
searchActiveIndex,
|
||||
remoteSearchQuery,
|
||||
referenceSearchState,
|
||||
summaries,
|
||||
referenceSummaries,
|
||||
subjectStates,
|
||||
filteredTargets,
|
||||
providerStatus,
|
||||
mapSettings,
|
||||
liveCacheSummary,
|
||||
transportDiagnostic,
|
||||
gatewayHealthAge,
|
||||
gatewayCheckState,
|
||||
gatewayCheckError,
|
||||
onOpenSubjectWindow,
|
||||
onToggleSubjectVisibility,
|
||||
onToggleReferenceLayer,
|
||||
onLayersOpenChange,
|
||||
onTerrainChange,
|
||||
onBuildingsVisibleChange,
|
||||
onGridVisibleChange,
|
||||
onCacheEnabledChange,
|
||||
onCacheNoOverwriteChange,
|
||||
onFitVisibleTargets,
|
||||
onToggleSearch,
|
||||
onSearchQueryChange,
|
||||
onSearchKeyDown,
|
||||
onSearchActiveIndexChange,
|
||||
onSearchResult,
|
||||
}: {
|
||||
searchOpen: boolean;
|
||||
searchQuery: string;
|
||||
searchInputRef: RefObject<HTMLInputElement | null>;
|
||||
searchResults: MapSearchDocument[];
|
||||
searchActiveIndex: number;
|
||||
remoteSearchQuery: string;
|
||||
referenceSearchState: "idle" | "loading" | "ready" | "error";
|
||||
summaries: MapPresentationSummary[];
|
||||
referenceSummaries: ReferenceObjectSummary[];
|
||||
subjectStates: Record<string, MapSubjectState>;
|
||||
filteredTargets: MapFilteredTarget[];
|
||||
providerStatus: MapProviderStatus;
|
||||
mapSettings: MapPageSettings;
|
||||
liveCacheSummary: string;
|
||||
transportDiagnostic: string | null;
|
||||
gatewayHealthAge: string | null;
|
||||
gatewayCheckState: "idle" | "checking" | "ready" | "stale" | "error";
|
||||
gatewayCheckError: string | null;
|
||||
onOpenSubjectWindow: (bindingId: string) => void;
|
||||
onToggleSubjectVisibility: (bindingId: string) => void;
|
||||
onToggleReferenceLayer: (layerId: string) => void;
|
||||
onLayersOpenChange: (open: boolean) => void;
|
||||
onTerrainChange: (value: boolean) => void;
|
||||
onBuildingsVisibleChange: (value: boolean) => void;
|
||||
onGridVisibleChange: (value: boolean) => void;
|
||||
onCacheEnabledChange: (value: boolean) => void;
|
||||
onCacheNoOverwriteChange: (value: boolean) => void;
|
||||
onFitVisibleTargets: () => void;
|
||||
onToggleSearch: () => void;
|
||||
onSearchQueryChange: (value: string) => void;
|
||||
onSearchKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void;
|
||||
onSearchActiveIndexChange: (index: number) => void;
|
||||
onSearchResult: (result: MapSearchDocument) => void;
|
||||
}) {
|
||||
const objectLayerCount = summaries.length + referenceSummaries.length;
|
||||
return (
|
||||
<div className="catalog-map-fixture__toolbar" aria-label="Map toolbar" data-search-open={searchOpen || undefined}>
|
||||
<MapObjectsMenu
|
||||
objectLayerCount={objectLayerCount}
|
||||
summaries={summaries}
|
||||
referenceSummaries={referenceSummaries}
|
||||
subjectStates={subjectStates}
|
||||
filteredTargets={filteredTargets}
|
||||
onOpenSubjectWindow={onOpenSubjectWindow}
|
||||
onToggleSubjectVisibility={onToggleSubjectVisibility}
|
||||
onToggleReferenceLayer={onToggleReferenceLayer}
|
||||
/>
|
||||
<MapLayersMenu
|
||||
providerStatus={providerStatus}
|
||||
mapSettings={mapSettings}
|
||||
liveCacheSummary={liveCacheSummary}
|
||||
transportDiagnostic={transportDiagnostic}
|
||||
gatewayHealthAge={gatewayHealthAge}
|
||||
gatewayCheckState={gatewayCheckState}
|
||||
gatewayCheckError={gatewayCheckError}
|
||||
onOpenChange={onLayersOpenChange}
|
||||
onTerrainChange={onTerrainChange}
|
||||
onBuildingsVisibleChange={onBuildingsVisibleChange}
|
||||
onGridVisibleChange={onGridVisibleChange}
|
||||
onCacheEnabledChange={onCacheEnabledChange}
|
||||
onCacheNoOverwriteChange={onCacheNoOverwriteChange}
|
||||
/>
|
||||
<IconButton label="Обзор объектов" onClick={onFitVisibleTargets}><Icon name="globe" /></IconButton>
|
||||
<IconButton
|
||||
label={searchOpen ? "Закрыть поиск" : "Поиск"}
|
||||
aria-expanded={searchOpen}
|
||||
aria-controls="map-subject-search"
|
||||
data-active={searchOpen || undefined}
|
||||
onClick={onToggleSearch}
|
||||
><Icon name="search" /></IconButton>
|
||||
<MapSearch
|
||||
open={searchOpen}
|
||||
query={searchQuery}
|
||||
inputRef={searchInputRef}
|
||||
results={searchResults}
|
||||
activeIndex={searchActiveIndex}
|
||||
remoteQuery={remoteSearchQuery}
|
||||
referenceSearchState={referenceSearchState}
|
||||
onQueryChange={onSearchQueryChange}
|
||||
onKeyDown={onSearchKeyDown}
|
||||
onActiveIndexChange={onSearchActiveIndexChange}
|
||||
onResult={onSearchResult}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MapObjectsMenu({
|
||||
objectLayerCount,
|
||||
summaries,
|
||||
referenceSummaries,
|
||||
subjectStates,
|
||||
filteredTargets,
|
||||
onOpenSubjectWindow,
|
||||
onToggleSubjectVisibility,
|
||||
onToggleReferenceLayer,
|
||||
}: {
|
||||
objectLayerCount: number;
|
||||
summaries: MapPresentationSummary[];
|
||||
referenceSummaries: ReferenceObjectSummary[];
|
||||
subjectStates: Record<string, MapSubjectState>;
|
||||
filteredTargets: MapFilteredTarget[];
|
||||
onOpenSubjectWindow: (bindingId: string) => void;
|
||||
onToggleSubjectVisibility: (bindingId: string) => void;
|
||||
onToggleReferenceLayer: (layerId: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<Dropdown
|
||||
placement="top-start"
|
||||
width={320}
|
||||
minWidth={240}
|
||||
offset={10}
|
||||
surfaceRole="menu"
|
||||
surfaceClassName="catalog-map-fixture__objects-menu nodedc-map-glass"
|
||||
trigger={({ open, toggle, setTriggerRef, surfaceId }) => (
|
||||
<IconButton ref={setTriggerRef} label="Объекты" aria-controls={surfaceId} aria-expanded={open} aria-pressed={open} data-active={open || undefined} onClick={toggle}><Icon name="target" /></IconButton>
|
||||
)}
|
||||
>
|
||||
{({ close }) => (
|
||||
<div className="catalog-map-fixture__objects-menu-list">
|
||||
<div className="catalog-map-fixture__objects-menu-head">
|
||||
<strong>Объекты</strong>
|
||||
<small>{objectLayerCount} {objectLayerCount === 1 ? "группа" : "групп"}</small>
|
||||
</div>
|
||||
{summaries.map((summary) => {
|
||||
const state = subjectStates[summary.bindingId];
|
||||
const visibleCount = filteredTargets.filter((target) => target.bindingId === summary.bindingId && target.renderable).length;
|
||||
const visible = state?.visible !== false;
|
||||
const hasControls = mapProfileHasSubjectWindowControls(summary.profile);
|
||||
return (
|
||||
<div
|
||||
className="catalog-map-fixture__objects-menu-item"
|
||||
key={summary.bindingId}
|
||||
data-visible={visible || undefined}
|
||||
data-open={hasControls && state?.window.open || undefined}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role={hasControls ? "menuitem" : "menuitemcheckbox"}
|
||||
aria-checked={hasControls ? undefined : visible}
|
||||
className="catalog-map-fixture__objects-menu-toggle"
|
||||
onClick={() => {
|
||||
if (hasControls) {
|
||||
onOpenSubjectWindow(summary.bindingId);
|
||||
close();
|
||||
} else onToggleSubjectVisibility(summary.bindingId);
|
||||
}}
|
||||
>
|
||||
<span>{summary.displayName}</span>
|
||||
<small>{visible ? `на карте: ${visibleCount}` : `слой скрыт · ${summary.total} объектов`}</small>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{referenceSummaries.map(({ layer, displayName, total }) => (
|
||||
<div className="catalog-map-fixture__objects-menu-item" key={layer.id} data-visible={layer.visible || undefined}>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitemcheckbox"
|
||||
aria-checked={layer.visible}
|
||||
className="catalog-map-fixture__objects-menu-toggle"
|
||||
onClick={() => onToggleReferenceLayer(layer.id)}
|
||||
>
|
||||
<span>{displayName}</span>
|
||||
<small>{layer.visible ? `на карте: ${total}` : `слой скрыт · ${total} объектов`}</small>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{!objectLayerCount ? <small className="catalog-map-fixture__objects-menu-empty">Нет подключённых объектов.</small> : null}
|
||||
</div>
|
||||
)}
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
function MapLayersMenu({
|
||||
providerStatus,
|
||||
mapSettings,
|
||||
liveCacheSummary,
|
||||
transportDiagnostic,
|
||||
gatewayHealthAge,
|
||||
gatewayCheckState,
|
||||
gatewayCheckError,
|
||||
onOpenChange,
|
||||
onTerrainChange,
|
||||
onBuildingsVisibleChange,
|
||||
onGridVisibleChange,
|
||||
onCacheEnabledChange,
|
||||
onCacheNoOverwriteChange,
|
||||
}: {
|
||||
providerStatus: MapProviderStatus;
|
||||
mapSettings: MapPageSettings;
|
||||
liveCacheSummary: string;
|
||||
transportDiagnostic: string | null;
|
||||
gatewayHealthAge: string | null;
|
||||
gatewayCheckState: "idle" | "checking" | "ready" | "stale" | "error";
|
||||
gatewayCheckError: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onTerrainChange: (value: boolean) => void;
|
||||
onBuildingsVisibleChange: (value: boolean) => void;
|
||||
onGridVisibleChange: (value: boolean) => void;
|
||||
onCacheEnabledChange: (value: boolean) => void;
|
||||
onCacheNoOverwriteChange: (value: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<Dropdown
|
||||
placement="top-start"
|
||||
width={320}
|
||||
minWidth={240}
|
||||
offset={10}
|
||||
surfaceRole="dialog"
|
||||
surfaceClassName="catalog-map-fixture__objects-menu catalog-map-fixture__layers-menu nodedc-map-glass"
|
||||
onOpenChange={onOpenChange}
|
||||
trigger={({ open, toggle, setTriggerRef, surfaceId }) => (
|
||||
<IconButton ref={setTriggerRef} label="Слои карты" aria-controls={surfaceId} aria-expanded={open} aria-pressed={open} data-active={open || undefined} onClick={toggle}><Icon name="grid" /></IconButton>
|
||||
)}
|
||||
>
|
||||
<div className="catalog-map-fixture__layers-content" aria-label="Настройки слоёв карты">
|
||||
<div className="catalog-map-fixture__objects-menu-head">
|
||||
<strong>Слои карты</strong>
|
||||
<small>Подложка, рельеф и визуальные слои</small>
|
||||
</div>
|
||||
<div className="catalog-map-fixture__provider">
|
||||
<strong>Cesium World Imagery</strong>
|
||||
<small>официальный live provider · imagery: {providerStateLabel[providerStatus.imagery]} · terrain: {providerStateLabel[providerStatus.terrain]}</small>
|
||||
</div>
|
||||
{Object.entries(providerStatus.errors).map(([provider, error]) => <small key={provider} className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">{provider}: {error}</small>)}
|
||||
<Checker checked={mapSettings.terrainEnabled} label="Terrain" onChange={onTerrainChange} />
|
||||
<Checker checked={mapSettings.buildingsVisible} label="3D здания" onChange={onBuildingsVisibleChange} />
|
||||
<Checker checked={mapSettings.gridVisible} label="Планетарная сетка" onChange={onGridVisibleChange} />
|
||||
<small className="catalog-map-inspector__note">Live Cache: {liveCacheSummary}</small>
|
||||
{transportDiagnostic ? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">{transportDiagnostic}</small> : null}
|
||||
{gatewayHealthAge ? <small className="catalog-map-inspector__note">{gatewayHealthAge}</small> : null}
|
||||
{gatewayCheckState === "error" || gatewayCheckState === "stale" ? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">{gatewayCheckError}</small> : null}
|
||||
<Checker className="catalog-map-fixture__cache-toggle" checked={mapSettings.cacheEnabled} label="Кэшировать live-данные" onChange={onCacheEnabledChange} />
|
||||
<Checker className="catalog-map-fixture__cache-toggle" checked={mapSettings.cacheNoOverwrite} disabled={!mapSettings.cacheEnabled} label="Не перезаписывать cache" onChange={onCacheNoOverwriteChange} />
|
||||
</div>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
function MapSearch({
|
||||
open,
|
||||
query,
|
||||
inputRef,
|
||||
results,
|
||||
activeIndex,
|
||||
remoteQuery,
|
||||
referenceSearchState,
|
||||
onQueryChange,
|
||||
onKeyDown,
|
||||
onActiveIndexChange,
|
||||
onResult,
|
||||
}: {
|
||||
open: boolean;
|
||||
query: string;
|
||||
inputRef: RefObject<HTMLInputElement | null>;
|
||||
results: MapSearchDocument[];
|
||||
activeIndex: number;
|
||||
remoteQuery: string;
|
||||
referenceSearchState: "idle" | "loading" | "ready" | "error";
|
||||
onQueryChange: (value: string) => void;
|
||||
onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void;
|
||||
onActiveIndexChange: (index: number) => void;
|
||||
onResult: (result: MapSearchDocument) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="catalog-map-search" data-open={open || undefined}>
|
||||
<label className="catalog-map-search__field" htmlFor="map-subject-search">
|
||||
<Icon name="search" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
id="map-subject-search"
|
||||
type="search"
|
||||
value={query}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder="Название, ID объекта или трекера"
|
||||
aria-label="Поиск объектов карты"
|
||||
aria-controls="map-subject-search-results"
|
||||
aria-activedescendant={results.length ? `map-subject-search-result-${activeIndex}` : undefined}
|
||||
onChange={(event) => onQueryChange(event.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
</label>
|
||||
{query.trim() ? (
|
||||
<div id="map-subject-search-results" className="catalog-map-search__results nodedc-map-glass" role="listbox" aria-label="Результаты поиска">
|
||||
{results.map((result, index) => (
|
||||
<button
|
||||
key={`${result.bindingId}:${result.sourceId}`}
|
||||
id={`map-subject-search-result-${index}`}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={index === activeIndex}
|
||||
data-active={index === activeIndex || undefined}
|
||||
onPointerEnter={() => onActiveIndexChange(index)}
|
||||
onClick={() => onResult(result)}
|
||||
>
|
||||
<span>{result.title}</span>
|
||||
<small>{result.groupTitle}</small>
|
||||
</button>
|
||||
))}
|
||||
{!results.length ? (
|
||||
<small className="catalog-map-search__empty">
|
||||
{remoteQuery === query.trim()
|
||||
? (referenceSearchState === "loading"
|
||||
? "Ищем станцию в OSM…"
|
||||
: referenceSearchState === "error"
|
||||
? "Поиск OSM временно недоступен; локальные данные сохранены."
|
||||
: "Станции с таким точным названием не найдены.")
|
||||
: "Совпадений нет. Enter — найти станцию по точному названию в OSM."}
|
||||
</small>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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>;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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)}</>;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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>
|
||||
</>;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { NodedcTheme } from "@nodedc/ui-core";
|
||||
import type { MapPageLayout, MapPageSettings } from "./MapFixturePreview.js";
|
||||
import type { MapPageLayout, MapPageSettings } from "./mapPageContract.js";
|
||||
import type { MapPresentationProfile } from "./mapPresentationProfile.js";
|
||||
|
||||
export const applicationManifestSchemaVersion = "0.1.0" as const;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { GlassMaterialSettings, NodedcTheme } from "@nodedc/ui-core";
|
||||
import type { ToolbarPlacement } from "@nodedc/ui-react";
|
||||
import type { FaviconAssetUrls } from "./favicon.js";
|
||||
import type { MapPageLayout, MapPageSettings } from "./MapFixturePreview.js";
|
||||
import type { MapPageLayout, MapPageSettings } from "./mapPageContract.js";
|
||||
import type { MapPresentationProfile } from "./mapPresentationProfile.js";
|
||||
|
||||
export type MaterialDraft = {
|
||||
@@ -61,8 +61,6 @@ export interface StoredLayout {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
};
|
||||
/** Design fragments are keyed by a registered Page Library type/version. */
|
||||
pageTypes?: Record<string, DesignProfilePageFragment>;
|
||||
|
||||
@@ -2,12 +2,11 @@ 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>
|
||||
<TooltipProvider><CatalogApp /></TooltipProvider>
|
||||
<CatalogApp />
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,610 @@
|
||||
import {
|
||||
BillboardGraphics,
|
||||
CallbackProperty,
|
||||
CallbackPositionProperty,
|
||||
Cartesian2,
|
||||
Cartesian3,
|
||||
Cartographic,
|
||||
ClassificationType,
|
||||
Color,
|
||||
ColorGeometryInstanceAttribute,
|
||||
ConstantPositionProperty,
|
||||
CustomDataSource,
|
||||
GeometryInstance,
|
||||
GroundPolylineGeometry,
|
||||
GroundPolylinePrimitive,
|
||||
GroundPrimitive,
|
||||
HeightReference,
|
||||
HorizontalOrigin,
|
||||
LabelGraphics,
|
||||
LabelStyle,
|
||||
PerInstanceColorAppearance,
|
||||
PointGraphics,
|
||||
PolygonGeometry,
|
||||
PolygonHierarchy,
|
||||
PolylineColorAppearance,
|
||||
PolylineGraphics,
|
||||
VerticalOrigin,
|
||||
Viewer,
|
||||
} from "cesium";
|
||||
import { mapRuntimeEntityId, type MapRuntimeBinding, type MapRuntimeFact } from "./useMapDataProductRuntime.js";
|
||||
import {
|
||||
mapPresentationProfileForFact,
|
||||
mapRuntimeDisplayLabel,
|
||||
mapRuntimeFactIsVisible,
|
||||
resolveMapPresentationClass,
|
||||
resolveMapPresentationStyle,
|
||||
type MapPresentationFilters,
|
||||
type MapPresentationProfile,
|
||||
} from "./mapPresentationProfile.js";
|
||||
import { normalizeHGeoZoneRing } from "./hGeoZoneProjection.mjs";
|
||||
|
||||
const MAX_HGEOZONE_INSTANCES_PER_BATCH = 256;
|
||||
const elevatedTargetImageCache = new Map<string, string>();
|
||||
|
||||
function elevatedTargetImage(
|
||||
fillColor: Color,
|
||||
outlineColor: Color,
|
||||
outlineWidthPx: number,
|
||||
headSizePx: number,
|
||||
) {
|
||||
const safeHeadSize = Math.max(1, headSizePx);
|
||||
const safeOutlineWidth = Math.max(0, outlineWidthPx);
|
||||
const imageSize = Math.max(1, Math.ceil(safeHeadSize + safeOutlineWidth * 2));
|
||||
const key = [
|
||||
fillColor.toCssColorString(),
|
||||
outlineColor.toCssColorString(),
|
||||
safeOutlineWidth,
|
||||
safeHeadSize,
|
||||
imageSize,
|
||||
].join("|");
|
||||
const cached = elevatedTargetImageCache.get(key);
|
||||
if (cached) return { image: cached, size: imageSize };
|
||||
const center = imageSize / 2;
|
||||
const radius = Math.max(0.5, safeHeadSize / 2);
|
||||
const svg = [
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${imageSize}" height="${imageSize}" viewBox="0 0 ${imageSize} ${imageSize}">`,
|
||||
`<circle cx="${center}" cy="${center}" r="${radius}" fill="${fillColor.toCssColorString()}"`,
|
||||
safeOutlineWidth > 0
|
||||
? ` stroke="${outlineColor.toCssColorString()}" stroke-width="${safeOutlineWidth}"/>`
|
||||
: "/>",
|
||||
"</svg>",
|
||||
].join("");
|
||||
const image = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
||||
elevatedTargetImageCache.set(key, image);
|
||||
return { image, size: imageSize };
|
||||
}
|
||||
|
||||
const accent = Color.fromCssColorString("#ff2f92");
|
||||
const violet = Color.fromCssColorString("#8f72dc");
|
||||
function showBelowCameraHeight(viewer: Viewer, limit?: number) {
|
||||
if (!limit) return true;
|
||||
return new CallbackProperty(() => Number(viewer.camera.positionCartographic?.height || 0) <= limit, false);
|
||||
}
|
||||
|
||||
function elevatedPinGroundHeight(viewer: Viewer, longitude: number, latitude: number, fallbackHeightMeters = 0) {
|
||||
const sampled = viewer.scene.globe.getHeight(Cartographic.fromDegrees(longitude, latitude));
|
||||
return Number.isFinite(sampled) ? Number(sampled) : fallbackHeightMeters;
|
||||
}
|
||||
|
||||
function elevatedPinTopPosition(
|
||||
viewer: Viewer,
|
||||
longitude: number,
|
||||
latitude: number,
|
||||
stemHeightMeters: number,
|
||||
fallbackHeightMeters = 0,
|
||||
) {
|
||||
return new CallbackPositionProperty(() => Cartesian3.fromDegrees(
|
||||
longitude,
|
||||
latitude,
|
||||
elevatedPinGroundHeight(viewer, longitude, latitude, fallbackHeightMeters) + stemHeightMeters,
|
||||
), false);
|
||||
}
|
||||
|
||||
function elevatedPinStemPositions(
|
||||
viewer: Viewer,
|
||||
longitude: number,
|
||||
latitude: number,
|
||||
stemHeightMeters: number,
|
||||
fallbackHeightMeters = 0,
|
||||
) {
|
||||
return new CallbackProperty(() => {
|
||||
const groundHeight = elevatedPinGroundHeight(viewer, longitude, latitude, fallbackHeightMeters);
|
||||
return [
|
||||
Cartesian3.fromDegrees(longitude, latitude, groundHeight),
|
||||
Cartesian3.fromDegrees(longitude, latitude, groundHeight + stemHeightMeters),
|
||||
];
|
||||
}, false);
|
||||
}
|
||||
|
||||
function runtimePointColor(fact: MapRuntimeFact) {
|
||||
// This is a semantic default for the generic Map entity-stream adapter,
|
||||
// not a provider style. A renderer-neutral style profile can refine it
|
||||
// later without changing a data product or its L2 workflow.
|
||||
if (fact.presentationStatus === "stale") return Color.fromCssColorString("#f5a623");
|
||||
if (["inactive", "no-position", "no_position"].includes(fact.presentationStatus)) {
|
||||
return Color.fromCssColorString("#7d8491");
|
||||
}
|
||||
return fact.semanticType === "map.moving_object" ? accent : violet;
|
||||
}
|
||||
|
||||
export type HGeoZonePickId = {
|
||||
kind: "nodedc-hgeozone";
|
||||
entityId: string;
|
||||
instanceId: string;
|
||||
};
|
||||
|
||||
type HGeoZoneFillPart = {
|
||||
pickId: HGeoZonePickId;
|
||||
hierarchy: PolygonHierarchy;
|
||||
color: Color;
|
||||
};
|
||||
|
||||
type HGeoZoneOutlinePart = {
|
||||
pickId: HGeoZonePickId;
|
||||
positions: Cartesian3[];
|
||||
color: Color;
|
||||
};
|
||||
|
||||
type HGeoZonePrimitiveBatch<TPart> = {
|
||||
primitive: GroundPrimitive | GroundPolylinePrimitive;
|
||||
parts: TPart[];
|
||||
};
|
||||
|
||||
export type HGeoZoneProjectionLayer = {
|
||||
geometryKey: string;
|
||||
styleKey: string;
|
||||
hideCameraHeightMeters: number | null;
|
||||
fills: Array<HGeoZonePrimitiveBatch<HGeoZoneFillPart>>;
|
||||
outlines: Array<HGeoZonePrimitiveBatch<HGeoZoneOutlinePart>>;
|
||||
};
|
||||
|
||||
function hGeoZoneRingPositions(ring: Array<[number, number]>) {
|
||||
return normalizeHGeoZoneRing(ring)
|
||||
.map(([longitude, latitude]) => Cartesian3.fromDegrees(longitude, latitude, 0));
|
||||
}
|
||||
|
||||
function hGeoZoneHierarchy(polygon: Array<Array<[number, number]>>) {
|
||||
const outer = hGeoZoneRingPositions(polygon[0]);
|
||||
if (outer.length < 3) return null;
|
||||
const holes = polygon.slice(1)
|
||||
.map((ring) => hGeoZoneRingPositions(ring))
|
||||
.filter((ring) => ring.length >= 3)
|
||||
.map((ring) => new PolygonHierarchy(ring));
|
||||
return new PolygonHierarchy(outer, holes);
|
||||
}
|
||||
|
||||
function hGeoZoneBatches<T>(items: T[]) {
|
||||
const batches: T[][] = [];
|
||||
for (let index = 0; index < items.length; index += MAX_HGEOZONE_INSTANCES_PER_BATCH) {
|
||||
batches.push(items.slice(index, index + MAX_HGEOZONE_INSTANCES_PER_BATCH));
|
||||
}
|
||||
return batches;
|
||||
}
|
||||
|
||||
function removeHGeoZoneLayer(viewer: Viewer, layer: HGeoZoneProjectionLayer) {
|
||||
for (const batch of [...layer.fills, ...layer.outlines]) {
|
||||
viewer.scene.groundPrimitives.remove(batch.primitive);
|
||||
}
|
||||
}
|
||||
|
||||
function hGeoZoneFaultKey(bindingId: string, geometryKey: string) {
|
||||
return `${bindingId}\u0000${geometryKey}`;
|
||||
}
|
||||
|
||||
export function quarantineHGeoZoneLayers(
|
||||
viewer: Viewer,
|
||||
layers: Map<string, HGeoZoneProjectionLayer>,
|
||||
faultedGeometryKeys: Set<string>,
|
||||
) {
|
||||
if (!layers.size) return false;
|
||||
const hasPendingGeometry = [...layers.values()].some((layer) => (
|
||||
[...layer.fills, ...layer.outlines].some((batch) => !batch.primitive.ready)
|
||||
));
|
||||
if (!hasPendingGeometry) return false;
|
||||
for (const [bindingId, layer] of layers) {
|
||||
faultedGeometryKeys.add(hGeoZoneFaultKey(bindingId, layer.geometryKey));
|
||||
removeHGeoZoneLayer(viewer, layer);
|
||||
}
|
||||
layers.clear();
|
||||
viewer.scene.requestRender();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function syncHGeoZoneVisibility(viewer: Viewer, layers: Map<string, HGeoZoneProjectionLayer>) {
|
||||
const cameraHeight = Number(viewer.camera.positionCartographic?.height || 0);
|
||||
for (const layer of layers.values()) {
|
||||
const show = layer.hideCameraHeightMeters === null || cameraHeight <= layer.hideCameraHeightMeters;
|
||||
for (const batch of [...layer.fills, ...layer.outlines]) batch.primitive.show = show;
|
||||
}
|
||||
viewer.scene.requestRender();
|
||||
}
|
||||
|
||||
function updateHGeoZoneColors<TPart extends { pickId: HGeoZonePickId; color: Color }>(
|
||||
batches: Array<HGeoZonePrimitiveBatch<TPart>>,
|
||||
nextParts: TPart[],
|
||||
) {
|
||||
const nextColors = new Map(nextParts.map((part) => [part.pickId.instanceId, part.color]));
|
||||
for (const batch of batches) {
|
||||
for (const part of batch.parts) {
|
||||
const color = nextColors.get(part.pickId.instanceId);
|
||||
if (!color) continue;
|
||||
const attributes = batch.primitive.getGeometryInstanceAttributes(part.pickId);
|
||||
if (attributes) attributes.color = ColorGeometryInstanceAttribute.toValue(color);
|
||||
part.color = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createHGeoZoneLayer(
|
||||
viewer: Viewer,
|
||||
geometryKey: string,
|
||||
styleKey: string,
|
||||
hideCameraHeightMeters: number | null,
|
||||
fillParts: HGeoZoneFillPart[],
|
||||
outlineParts: HGeoZoneOutlinePart[],
|
||||
outlineWidthPx: number,
|
||||
) {
|
||||
const fills = hGeoZoneBatches(fillParts).map((parts) => {
|
||||
const primitive = viewer.scene.groundPrimitives.add(new GroundPrimitive({
|
||||
geometryInstances: parts.map((part) => new GeometryInstance({
|
||||
id: part.pickId,
|
||||
geometry: new PolygonGeometry({
|
||||
polygonHierarchy: part.hierarchy,
|
||||
vertexFormat: PerInstanceColorAppearance.FLAT_VERTEX_FORMAT,
|
||||
}),
|
||||
attributes: { color: ColorGeometryInstanceAttribute.fromColor(part.color) },
|
||||
})),
|
||||
appearance: new PerInstanceColorAppearance({ flat: true, translucent: true }),
|
||||
allowPicking: true,
|
||||
asynchronous: true,
|
||||
classificationType: ClassificationType.TERRAIN,
|
||||
releaseGeometryInstances: true,
|
||||
}));
|
||||
return { primitive, parts };
|
||||
});
|
||||
const outlines = outlineWidthPx <= 0 ? [] : hGeoZoneBatches(outlineParts).map((parts) => {
|
||||
const primitive = viewer.scene.groundPrimitives.add(new GroundPolylinePrimitive({
|
||||
geometryInstances: parts.map((part) => new GeometryInstance({
|
||||
id: part.pickId,
|
||||
geometry: new GroundPolylineGeometry({
|
||||
positions: part.positions,
|
||||
width: outlineWidthPx,
|
||||
loop: true,
|
||||
}),
|
||||
attributes: { color: ColorGeometryInstanceAttribute.fromColor(part.color) },
|
||||
})),
|
||||
appearance: new PolylineColorAppearance({ translucent: true }),
|
||||
allowPicking: true,
|
||||
asynchronous: true,
|
||||
classificationType: ClassificationType.TERRAIN,
|
||||
releaseGeometryInstances: true,
|
||||
}));
|
||||
return { primitive, parts };
|
||||
});
|
||||
const layer = { geometryKey, styleKey, hideCameraHeightMeters, fills, outlines };
|
||||
syncHGeoZoneVisibility(viewer, new Map([["layer", layer]]));
|
||||
return layer;
|
||||
}
|
||||
|
||||
function syncHGeoZoneLayers(
|
||||
viewer: Viewer,
|
||||
layers: Map<string, HGeoZoneProjectionLayer>,
|
||||
bindings: MapRuntimeBinding[],
|
||||
presentationProfiles: MapPresentationProfile[],
|
||||
presentationFilters: MapPresentationFilters,
|
||||
faultedGeometryKeys: Set<string>,
|
||||
) {
|
||||
const activeBindings = new Set(bindings.filter((binding) => binding.slotId === "zones").map((binding) => binding.bindingId));
|
||||
for (const [bindingId, layer] of layers) {
|
||||
if (activeBindings.has(bindingId)) continue;
|
||||
removeHGeoZoneLayer(viewer, layer);
|
||||
layers.delete(bindingId);
|
||||
}
|
||||
|
||||
for (const binding of bindings) {
|
||||
if (binding.slotId !== "zones") continue;
|
||||
const fillParts: HGeoZoneFillPart[] = [];
|
||||
const outlineParts: HGeoZoneOutlinePart[] = [];
|
||||
const geometryMembers: string[] = [];
|
||||
let outlineWidthPx = 1.5;
|
||||
let hideCameraHeightMeters: number | null = null;
|
||||
let outlineColor = Color.fromCssColorString("#c9b6ff").withAlpha(0.9);
|
||||
const styleMembers: string[] = [];
|
||||
|
||||
for (const fact of binding.facts) {
|
||||
const profile = mapPresentationProfileForFact(
|
||||
presentationProfiles,
|
||||
binding.presentationProfileId,
|
||||
fact.semanticType,
|
||||
);
|
||||
if (
|
||||
!fact.geometry
|
||||
|| fact.geometry.type === "Point"
|
||||
|| (profile && profile.target.variant !== "surface-fill")
|
||||
|| (profile && !mapRuntimeFactIsVisible(fact, profile, presentationFilters, binding.bindingId))
|
||||
) continue;
|
||||
const presentationClass = profile ? resolveMapPresentationClass(fact, profile) : undefined;
|
||||
const resolvedStyle = profile ? resolveMapPresentationStyle(profile, presentationClass) : undefined;
|
||||
const fillColor = resolvedStyle
|
||||
? Color.fromCssColorString(resolvedStyle.color).withAlpha(resolvedStyle.opacity)
|
||||
: runtimePointColor(fact).withAlpha(0.28);
|
||||
if (profile?.target.variant === "surface-fill") {
|
||||
outlineWidthPx = profile.target.outlineWidthPx;
|
||||
hideCameraHeightMeters = profile.target.hideCameraHeightMeters;
|
||||
outlineColor = Color.fromCssColorString(profile.target.outlineColor).withAlpha(profile.target.outlineOpacity);
|
||||
}
|
||||
const polygons = fact.geometry.type === "Polygon" ? [fact.geometry.coordinates] : fact.geometry.coordinates;
|
||||
const baseEntityId = mapRuntimeEntityId(binding.bindingId, fact);
|
||||
for (const [polygonIndex, polygon] of polygons.entries()) {
|
||||
const hierarchy = hGeoZoneHierarchy(polygon);
|
||||
if (!hierarchy) continue;
|
||||
const instanceBase = `${baseEntityId}:part:${polygonIndex}`;
|
||||
const fillPickId: HGeoZonePickId = {
|
||||
kind: "nodedc-hgeozone",
|
||||
entityId: baseEntityId,
|
||||
instanceId: `${instanceBase}:fill`,
|
||||
};
|
||||
fillParts.push({ pickId: fillPickId, hierarchy, color: fillColor });
|
||||
geometryMembers.push(fillPickId.instanceId);
|
||||
styleMembers.push(`${fillPickId.instanceId}:${resolvedStyle?.id ?? "default"}:${fillColor.toCssHexString()}:${fillColor.alpha}`);
|
||||
for (const [ringIndex, ring] of polygon.entries()) {
|
||||
const positions = hGeoZoneRingPositions(ring);
|
||||
if (positions.length < 3) continue;
|
||||
const outlinePickId: HGeoZonePickId = {
|
||||
kind: "nodedc-hgeozone",
|
||||
entityId: baseEntityId,
|
||||
instanceId: `${instanceBase}:ring:${ringIndex}`,
|
||||
};
|
||||
outlineParts.push({ pickId: outlinePickId, positions, color: outlineColor });
|
||||
geometryMembers.push(outlinePickId.instanceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const geometryKey = JSON.stringify([binding.cursor, outlineWidthPx, geometryMembers]);
|
||||
const styleKey = JSON.stringify([styleMembers, outlineColor.toCssHexString(), outlineColor.alpha]);
|
||||
const current = layers.get(binding.bindingId);
|
||||
if (!fillParts.length) {
|
||||
if (current) removeHGeoZoneLayer(viewer, current);
|
||||
layers.delete(binding.bindingId);
|
||||
continue;
|
||||
}
|
||||
if (faultedGeometryKeys.has(hGeoZoneFaultKey(binding.bindingId, geometryKey))) {
|
||||
if (current) removeHGeoZoneLayer(viewer, current);
|
||||
layers.delete(binding.bindingId);
|
||||
continue;
|
||||
}
|
||||
if (current?.geometryKey === geometryKey) {
|
||||
current.hideCameraHeightMeters = hideCameraHeightMeters;
|
||||
if (current.styleKey !== styleKey) {
|
||||
const ready = [...current.fills, ...current.outlines].every((batch) => batch.primitive.ready);
|
||||
if (ready) {
|
||||
updateHGeoZoneColors(current.fills, fillParts);
|
||||
updateHGeoZoneColors(current.outlines, outlineParts);
|
||||
current.styleKey = styleKey;
|
||||
syncHGeoZoneVisibility(viewer, layers);
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
syncHGeoZoneVisibility(viewer, layers);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (current) removeHGeoZoneLayer(viewer, current);
|
||||
layers.set(binding.bindingId, createHGeoZoneLayer(
|
||||
viewer,
|
||||
geometryKey,
|
||||
styleKey,
|
||||
hideCameraHeightMeters,
|
||||
fillParts,
|
||||
outlineParts,
|
||||
outlineWidthPx,
|
||||
));
|
||||
}
|
||||
viewer.scene.requestRender();
|
||||
}
|
||||
|
||||
export function syncRuntimeDataSources(
|
||||
viewer: Viewer,
|
||||
dataSources: Map<string, CustomDataSource>,
|
||||
hGeoZoneLayers: Map<string, HGeoZoneProjectionLayer>,
|
||||
bindings: MapRuntimeBinding[],
|
||||
presentationProfiles: MapPresentationProfile[],
|
||||
presentationFilters: MapPresentationFilters,
|
||||
faultedHGeoZoneGeometryKeys: Set<string>,
|
||||
) {
|
||||
const activeBindings = new Map(bindings
|
||||
.filter((binding) => (
|
||||
binding.slotId === "points"
|
||||
|| binding.slotId === "reference-points"
|
||||
|| binding.slotId === "zones"
|
||||
))
|
||||
.map((binding) => [binding.bindingId, binding]));
|
||||
|
||||
for (const [bindingId, dataSource] of dataSources) {
|
||||
if (activeBindings.has(bindingId)) continue;
|
||||
viewer.dataSources.remove(dataSource, true);
|
||||
dataSources.delete(bindingId);
|
||||
}
|
||||
|
||||
for (const binding of activeBindings.values()) {
|
||||
let dataSource = dataSources.get(binding.bindingId);
|
||||
if (!dataSource) {
|
||||
dataSource = new CustomDataSource(`nodedc-map-slot:${binding.bindingId}`);
|
||||
viewer.dataSources.add(dataSource);
|
||||
dataSources.set(binding.bindingId, dataSource);
|
||||
}
|
||||
const wanted = new Set<string>();
|
||||
for (const fact of binding.facts) {
|
||||
const profile = mapPresentationProfileForFact(
|
||||
presentationProfiles,
|
||||
binding.presentationProfileId,
|
||||
fact.semanticType,
|
||||
);
|
||||
const presentationClass = profile ? resolveMapPresentationClass(fact, profile) : undefined;
|
||||
if (
|
||||
!fact.geometry
|
||||
|| (profile && !mapRuntimeFactIsVisible(fact, profile, presentationFilters, binding.bindingId))
|
||||
) continue;
|
||||
const resolvedStyle = profile ? resolveMapPresentationStyle(profile, presentationClass) : undefined;
|
||||
const color = resolvedStyle
|
||||
? Color.fromCssColorString(resolvedStyle.color).withAlpha(resolvedStyle.opacity)
|
||||
: runtimePointColor(fact);
|
||||
const label = mapRuntimeDisplayLabel(fact, profile);
|
||||
const baseEntityId = mapRuntimeEntityId(binding.bindingId, fact);
|
||||
|
||||
if (fact.geometry.type === "Point" && (binding.slotId === "points" || binding.slotId === "reference-points")) {
|
||||
if (profile && profile.target.variant !== "elevated-spike") continue;
|
||||
const entityId = baseEntityId;
|
||||
wanted.add(entityId);
|
||||
const [longitude, latitude] = fact.geometry.coordinates;
|
||||
const entity = dataSource.entities.getById(entityId) ?? dataSource.entities.add({ id: entityId });
|
||||
entity.name = label;
|
||||
entity.polygon = undefined;
|
||||
if (!profile) {
|
||||
entity.billboard = undefined;
|
||||
entity.position = new ConstantPositionProperty(Cartesian3.fromDegrees(longitude, latitude, 0));
|
||||
entity.polyline = undefined;
|
||||
entity.point = new PointGraphics({
|
||||
pixelSize: 10,
|
||||
color,
|
||||
outlineColor: Color.TRANSPARENT,
|
||||
outlineWidth: 0,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
entity.label = new LabelGraphics({
|
||||
text: label,
|
||||
font: "700 13px Arial",
|
||||
fillColor: Color.WHITE,
|
||||
outlineColor: Color.TRANSPARENT,
|
||||
outlineWidth: 0,
|
||||
style: LabelStyle.FILL,
|
||||
showBackground: true,
|
||||
backgroundColor: Color.BLACK.withAlpha(0.72),
|
||||
backgroundPadding: new Cartesian2(10, 7),
|
||||
pixelOffset: new Cartesian2(10, 0),
|
||||
horizontalOrigin: HorizontalOrigin.LEFT,
|
||||
verticalOrigin: VerticalOrigin.BOTTOM,
|
||||
heightReference: HeightReference.NONE,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (profile.target.variant !== "elevated-spike") continue;
|
||||
const target = profile.target;
|
||||
const fallbackHeightMeters = typeof fact.attributes.elevation_meters === "number" && Number.isFinite(fact.attributes.elevation_meters)
|
||||
? fact.attributes.elevation_meters
|
||||
: 0;
|
||||
entity.position = elevatedPinTopPosition(
|
||||
viewer,
|
||||
longitude,
|
||||
latitude,
|
||||
target.stemHeightMeters,
|
||||
fallbackHeightMeters,
|
||||
);
|
||||
entity.polyline = new PolylineGraphics({
|
||||
positions: elevatedPinStemPositions(
|
||||
viewer,
|
||||
longitude,
|
||||
latitude,
|
||||
target.stemHeightMeters,
|
||||
fallbackHeightMeters,
|
||||
),
|
||||
width: target.stemWidthPx,
|
||||
material: color,
|
||||
show: showBelowCameraHeight(viewer, target.hideCameraHeightMeters),
|
||||
});
|
||||
const targetImage = elevatedTargetImage(
|
||||
color,
|
||||
Color.fromCssColorString(target.outlineColor).withAlpha(target.outlineOpacity),
|
||||
target.outlineWidthPx,
|
||||
target.headSizePx,
|
||||
);
|
||||
entity.point = undefined;
|
||||
entity.billboard = new BillboardGraphics({
|
||||
image: targetImage.image,
|
||||
width: targetImage.size,
|
||||
height: targetImage.size,
|
||||
horizontalOrigin: HorizontalOrigin.CENTER,
|
||||
verticalOrigin: VerticalOrigin.CENTER,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
show: showBelowCameraHeight(viewer, target.hideCameraHeightMeters),
|
||||
});
|
||||
entity.label = new LabelGraphics({
|
||||
text: label,
|
||||
font: `${profile.label.fontWeight} ${profile.label.sizePx}px Arial`,
|
||||
fillColor: Color.fromCssColorString(profile.label.color),
|
||||
outlineColor: Color.TRANSPARENT,
|
||||
outlineWidth: 0,
|
||||
style: LabelStyle.FILL,
|
||||
showBackground: profile.label.backgroundOpacity > 0,
|
||||
backgroundColor: Color.fromCssColorString(profile.label.backgroundColor).withAlpha(profile.label.backgroundOpacity),
|
||||
backgroundPadding: new Cartesian2(profile.label.paddingX, profile.label.paddingY),
|
||||
pixelOffset: new Cartesian2(profile.label.offsetX, profile.label.offsetY),
|
||||
horizontalOrigin: HorizontalOrigin.LEFT,
|
||||
verticalOrigin: VerticalOrigin.BOTTOM,
|
||||
heightReference: HeightReference.NONE,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
show: profile.label.mode !== "none" && showBelowCameraHeight(viewer, profile.label.hideCameraHeightMeters),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
binding.slotId !== "zones"
|
||||
|| fact.geometry.type === "Point"
|
||||
|| (profile && profile.target.variant !== "surface-fill")
|
||||
) continue;
|
||||
const polygons = fact.geometry.type === "Polygon" ? [fact.geometry.coordinates] : fact.geometry.coordinates;
|
||||
const outerRing = normalizeHGeoZoneRing(polygons[0]?.[0] ?? []);
|
||||
if (!outerRing.length) continue;
|
||||
wanted.add(baseEntityId);
|
||||
const labelAnchor = outerRing.reduce(
|
||||
(accumulator, [longitude, latitude]) => [accumulator[0] + longitude, accumulator[1] + latitude] as [number, number],
|
||||
[0, 0] as [number, number],
|
||||
);
|
||||
const divisor = Math.max(1, outerRing.length);
|
||||
const entity = dataSource.entities.getById(baseEntityId) ?? dataSource.entities.add({ id: baseEntityId });
|
||||
entity.name = label;
|
||||
entity.position = new ConstantPositionProperty(Cartesian3.fromDegrees(labelAnchor[0] / divisor, labelAnchor[1] / divisor, 0));
|
||||
entity.billboard = undefined;
|
||||
entity.point = undefined;
|
||||
entity.polygon = undefined;
|
||||
entity.polyline = undefined;
|
||||
entity.label = new LabelGraphics({
|
||||
text: label,
|
||||
font: profile ? `${profile.label.fontWeight} ${profile.label.sizePx}px Arial` : "700 13px Arial",
|
||||
fillColor: profile ? Color.fromCssColorString(profile.label.color) : Color.WHITE,
|
||||
outlineColor: Color.TRANSPARENT,
|
||||
outlineWidth: 0,
|
||||
style: LabelStyle.FILL,
|
||||
showBackground: (profile?.label.backgroundOpacity ?? 0.72) > 0,
|
||||
backgroundColor: profile
|
||||
? Color.fromCssColorString(profile.label.backgroundColor).withAlpha(profile.label.backgroundOpacity)
|
||||
: Color.BLACK.withAlpha(0.72),
|
||||
backgroundPadding: new Cartesian2(profile?.label.paddingX ?? 10, profile?.label.paddingY ?? 7),
|
||||
pixelOffset: new Cartesian2(profile?.label.offsetX ?? 10, profile?.label.offsetY ?? 0),
|
||||
horizontalOrigin: HorizontalOrigin.LEFT,
|
||||
verticalOrigin: VerticalOrigin.BOTTOM,
|
||||
heightReference: HeightReference.CLAMP_TO_GROUND,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
show: (profile?.label.mode ?? "attributes") !== "none"
|
||||
&& (profile ? showBelowCameraHeight(viewer, profile.label.hideCameraHeightMeters) : true),
|
||||
});
|
||||
}
|
||||
for (const entity of [...dataSource.entities.values]) {
|
||||
if (typeof entity.id === "string" && !wanted.has(entity.id)) dataSource.entities.remove(entity);
|
||||
}
|
||||
}
|
||||
syncHGeoZoneLayers(
|
||||
viewer,
|
||||
hGeoZoneLayers,
|
||||
bindings,
|
||||
presentationProfiles,
|
||||
presentationFilters,
|
||||
faultedHGeoZoneGeometryKeys,
|
||||
);
|
||||
viewer.scene.requestRender();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import {
|
||||
Button,
|
||||
Checker,
|
||||
ColorField,
|
||||
ControlRow,
|
||||
Icon,
|
||||
InspectorSelectField,
|
||||
RangeControl,
|
||||
SegmentedControl,
|
||||
} from "@nodedc/ui-react";
|
||||
import type { SelectOption } from "@nodedc/ui-react";
|
||||
import { DEFAULT_GRID_LOD_PROFILES } from "./mapGridPolicy.mjs";
|
||||
import { MAX_LOCAL_GRID_INDEX } from "./mapSectorGrid.mjs";
|
||||
import {
|
||||
GRID_SECTOR_DIRECTIONS,
|
||||
formatGridSectorArea,
|
||||
gridSectorBoundsLabel,
|
||||
gridSectorCenterLabel,
|
||||
normalizedGraticuleStepDegrees,
|
||||
normalizedMajorTileSizeKm,
|
||||
type GridSectorDirection,
|
||||
type SectorGridLodProfile,
|
||||
} from "./mapSectorWorkspace.js";
|
||||
import type {
|
||||
GridMajorTileSelection,
|
||||
GridSectorSelection,
|
||||
} from "./mapRendererContract.js";
|
||||
import type { MapPageSettings } from "./mapPageContract.js";
|
||||
import type { MapInspectorSection } from "./mapInspectorSections.js";
|
||||
|
||||
const GRID_MODE_OPTIONS: Array<SelectOption<"3d" | "graticule">> = [
|
||||
{ value: "3d", label: "3D", description: "Приподнятая пространственная сетка" },
|
||||
{ value: "graticule", label: "Гратикула", description: "Проекция по поверхности" },
|
||||
];
|
||||
|
||||
type GridSectorCopyState = "idle" | "copied" | "error";
|
||||
|
||||
export function buildMapGridInspectorSections({
|
||||
mapSettings,
|
||||
updateMapSettings,
|
||||
selectedGridLod,
|
||||
setSelectedGridLod,
|
||||
selectedGridLodIndex,
|
||||
activeGridLod,
|
||||
minimumGridLodHeight,
|
||||
maximumGridLodHeight,
|
||||
updateGridLod,
|
||||
updateGridVolumeRange,
|
||||
activeGraticuleMajorStepDegrees,
|
||||
selectedGridSector,
|
||||
gridSectorCopyState,
|
||||
copySelectedGridSectorId,
|
||||
mapRendererReady,
|
||||
focusGridMajorTile,
|
||||
selectedGridParentLod,
|
||||
sectorGridLodProfiles,
|
||||
focusGridSector,
|
||||
selectedGridNeighborTargets,
|
||||
selectedGridSectorProfile,
|
||||
selectedGridVolumeTargets,
|
||||
}: {
|
||||
mapSettings: MapPageSettings;
|
||||
updateMapSettings: (patch: Partial<MapPageSettings>) => void;
|
||||
selectedGridLod: string;
|
||||
setSelectedGridLod: Dispatch<SetStateAction<string>>;
|
||||
selectedGridLodIndex: number;
|
||||
activeGridLod: SectorGridLodProfile;
|
||||
minimumGridLodHeight: number;
|
||||
maximumGridLodHeight: number;
|
||||
updateGridLod: (patch: Partial<SectorGridLodProfile>) => void;
|
||||
updateGridVolumeRange: (patch: Partial<Pick<SectorGridLodProfile,
|
||||
"volumeMinimumHeightMeters" | "volumeMaximumHeightMeters" | "volumeBandHeightMeters">>) => void;
|
||||
activeGraticuleMajorStepDegrees: number | null;
|
||||
selectedGridSector: GridSectorSelection | null;
|
||||
gridSectorCopyState: GridSectorCopyState;
|
||||
copySelectedGridSectorId: () => Promise<void>;
|
||||
mapRendererReady: boolean;
|
||||
focusGridMajorTile: (tile: GridMajorTileSelection) => void;
|
||||
selectedGridParentLod: GridSectorSelection | null;
|
||||
sectorGridLodProfiles: SectorGridLodProfile[];
|
||||
focusGridSector: (sector: GridSectorSelection | null) => void;
|
||||
selectedGridNeighborTargets: Record<GridSectorDirection, GridSectorSelection | null>;
|
||||
selectedGridSectorProfile: SectorGridLodProfile | null;
|
||||
selectedGridVolumeTargets: { above: GridSectorSelection | null; below: GridSectorSelection | null };
|
||||
}): MapInspectorSection[] {
|
||||
return [
|
||||
{
|
||||
id: "map-grid",
|
||||
label: "Сетка и LOD",
|
||||
description: "first adapter control",
|
||||
group: "Слои",
|
||||
icon: <Icon name="grid" />,
|
||||
content: <div className="catalog-map-grid-inspector">
|
||||
<small className="catalog-map-inspector__note">Фиксированная московская ENU-адресация задаёт неизменные сектора на LOD 1–3. LOD 4–5 используют глобальную WGS84-гратику́лу; камера выбирает только LOD и видимую область.</small>
|
||||
<Checker checked={mapSettings.gridVisible} label="Сетка" onChange={(gridVisible) => updateMapSettings({ gridVisible })} />
|
||||
<Checker checked={mapSettings.grid3dEnabled} label="3D-сетка" onChange={(grid3dEnabled) => updateMapSettings({ grid3dEnabled })} />
|
||||
<Checker checked={mapSettings.gridGraticuleEnabled} label="Гратикула" onChange={(gridGraticuleEnabled) => updateMapSettings({ gridGraticuleEnabled })} />
|
||||
<Checker checked={mapSettings.gridLodEnabled} label="LOD по высоте камеры" onChange={(gridLodEnabled) => updateMapSettings({ gridLodEnabled })} />
|
||||
<Checker checked={mapSettings.gridRebuildOnMoveEnd} label="Перестраивать после движения" onChange={(gridRebuildOnMoveEnd) => updateMapSettings({ gridRebuildOnMoveEnd })} />
|
||||
<ControlRow label="Система координат"><strong>Fixed ENU · WGS84</strong></ControlRow>
|
||||
<RangeControl label="Origin: широта" value={mapSettings.gridCenterLatitude} min={-89.9} max={89.9} step={0.000001} formatValue={(value) => value.toFixed(6)} onChange={(gridCenterLatitude) => updateMapSettings({ gridCenterLatitude })} />
|
||||
<RangeControl label="Origin: долгота" value={mapSettings.gridCenterLongitude} min={-180} max={180} step={0.000001} formatValue={(value) => value.toFixed(6)} onChange={(gridCenterLongitude) => updateMapSettings({ gridCenterLongitude })} />
|
||||
<RangeControl label="Автовыключение выше" value={mapSettings.gridAutoDisableHeightKm} min={0} max={50_000} step={100} formatValue={(value) => value === 0 ? "выкл" : `${value} км`} onChange={(gridAutoDisableHeightKm) => updateMapSettings({ gridAutoDisableHeightKm })} />
|
||||
<div className="catalog-map-grid-lod-tabs">
|
||||
<SegmentedControl value={selectedGridLod} items={DEFAULT_GRID_LOD_PROFILES.map((_profile, index) => ({ value: String(index), label: `LOD ${index + 1}` }))} label="Уровень детализации сетки" onChange={setSelectedGridLod} />
|
||||
</div>
|
||||
<RangeControl label={selectedGridLodIndex === 4 ? "Порог профиля" : "До высоты"} value={activeGridLod.maxHeightKm} min={minimumGridLodHeight} max={maximumGridLodHeight} step={0.1} formatValue={(value) => `${value} км`} onChange={(maxHeightKm) => updateGridLod({ maxHeightKm })} />
|
||||
{selectedGridLodIndex === 4 ? <small className="catalog-map-inspector__note">Последний LOD остаётся активным выше своего порога до общего автовыключения.</small> : null}
|
||||
<InspectorSelectField
|
||||
label="Режим"
|
||||
value={activeGridLod.mode}
|
||||
options={GRID_MODE_OPTIONS}
|
||||
onChange={(mode) => updateGridLod({
|
||||
mode,
|
||||
volumeEnabled: mode === "3d" && activeGridLod.volumeEnabled,
|
||||
...(mode === "3d" ? {
|
||||
stepKm: Math.min(50, activeGridLod.stepKm),
|
||||
tileSizeKm: normalizedMajorTileSizeKm(Math.min(50, activeGridLod.stepKm), activeGridLod.tileSizeKm),
|
||||
} : {
|
||||
graticuleStepDegrees: normalizedGraticuleStepDegrees(activeGridLod.graticuleStepDegrees),
|
||||
}),
|
||||
})}
|
||||
/>
|
||||
<RangeControl label="Высота WGS84" value={activeGridLod.heightMeters} min={0} max={5_000} step={10} formatValue={(value) => `${value} м`} onChange={(heightMeters) => updateGridLod({ heightMeters })} />
|
||||
<RangeControl label="Конус видимости 3D" value={activeGridLod.max3dViewAngleDegrees} min={30} max={170} step={1} formatValue={(value) => `${value}°`} onChange={(max3dViewAngleDegrees) => updateGridLod({ max3dViewAngleDegrees })} />
|
||||
<RangeControl
|
||||
label="Шаг ENU-секторов"
|
||||
value={activeGridLod.stepKm}
|
||||
min={0.1}
|
||||
max={activeGridLod.mode === "3d" ? 50 : 5_000}
|
||||
step={0.1}
|
||||
formatValue={(value) => `${value} км`}
|
||||
onChange={(stepKm) => updateGridLod({
|
||||
stepKm,
|
||||
tileSizeKm: normalizedMajorTileSizeKm(stepKm, Math.max(stepKm, activeGridLod.tileSizeKm)),
|
||||
radiusKm: Math.min(activeGridLod.radiusKm, stepKm * MAX_LOCAL_GRID_INDEX),
|
||||
})}
|
||||
/>
|
||||
<RangeControl
|
||||
label="Размер major-тайла ENU"
|
||||
value={activeGridLod.tileSizeKm}
|
||||
min={activeGridLod.stepKm}
|
||||
max={Math.max(activeGridLod.stepKm, 50)}
|
||||
step={activeGridLod.stepKm}
|
||||
formatValue={(value) => `${value} км`}
|
||||
onChange={(tileSizeKm) => updateGridLod({ tileSizeKm: normalizedMajorTileSizeKm(activeGridLod.stepKm, tileSizeKm) })}
|
||||
/>
|
||||
<small className="catalog-map-inspector__note">Major-тайл содержит целое число ENU-секторов. Для гратикулы major-шаг равен пяти minor-шагам.</small>
|
||||
<Checker
|
||||
checked={activeGridLod.majorLinesEnabled}
|
||||
label="Major-линии"
|
||||
onChange={(majorLinesEnabled) => updateGridLod({
|
||||
majorLinesEnabled,
|
||||
majorLabelsEnabled: majorLinesEnabled && activeGridLod.majorLabelsEnabled,
|
||||
})}
|
||||
/>
|
||||
<Checker checked={activeGridLod.majorLabelsEnabled} disabled={!activeGridLod.majorLinesEnabled} label="Подписи major-тайлов" onChange={(majorLabelsEnabled) => updateGridLod({ majorLabelsEnabled })} />
|
||||
<RangeControl label="Толщина major-линий" value={activeGridLod.majorLineWidthMultiplier} min={1} max={8} step={0.1} formatValue={(value) => `×${value.toFixed(1)}`} onChange={(majorLineWidthMultiplier) => updateGridLod({ majorLineWidthMultiplier })} />
|
||||
<small className="catalog-map-inspector__note">Прозрачность major-линий наследует прозрачность линий текущего LOD.</small>
|
||||
{activeGridLod.mode === "graticule" && activeGridLod.majorLinesEnabled && activeGraticuleMajorStepDegrees === null
|
||||
? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">Major-разметка недоступна для этого шага: пять minor-интервалов должны точно делить 90°-квадрант.</small>
|
||||
: null}
|
||||
<RangeControl label="Радиус ENU-поля" value={activeGridLod.radiusKm} min={1} max={Math.min(100_000, activeGridLod.stepKm * MAX_LOCAL_GRID_INDEX)} step={1} formatValue={(value) => `${value} км`} onChange={(radiusKm) => updateGridLod({ radiusKm })} />
|
||||
<RangeControl label="Диаметр 3D-линий" value={activeGridLod.lineDiameterMeters} min={1} max={100} step={1} formatValue={(value) => `${value} м`} onChange={(lineDiameterMeters) => updateGridLod({ lineDiameterMeters })} />
|
||||
<ControlRow label="Цвет 3D-линий"><ColorField label="Цвет линий ENU-сетки" value={activeGridLod.lineColor} onChange={(lineColor) => updateGridLod({ lineColor })} /></ControlRow>
|
||||
<RangeControl label="Прозрачность 3D-линий" value={activeGridLod.lineOpacity} min={0} max={100} formatValue={(value) => `${value}%`} onChange={(lineOpacity) => updateGridLod({ lineOpacity })} />
|
||||
<Checker checked={activeGridLod.dotsEnabled} label="Кружки" onChange={(dotsEnabled) => updateGridLod({ dotsEnabled })} />
|
||||
<RangeControl label="Кружки: диаметр" value={activeGridLod.dotsDiameterMeters} min={1} max={1_000} step={1} formatValue={(value) => `${value} м`} onChange={(dotsDiameterMeters) => updateGridLod({ dotsDiameterMeters })} />
|
||||
<ControlRow label="Кружки: цвет"><ColorField label="Цвет кружков сетки" value={activeGridLod.dotsColor} onChange={(dotsColor) => updateGridLod({ dotsColor })} /></ControlRow>
|
||||
<RangeControl label="Кружки: прозрачность" value={activeGridLod.dotsOpacity} min={0} max={100} formatValue={(value) => `${value}%`} onChange={(dotsOpacity) => updateGridLod({ dotsOpacity })} />
|
||||
<Checker checked={activeGridLod.crossesEnabled} label="Кресты" onChange={(crossesEnabled) => updateGridLod({ crossesEnabled })} />
|
||||
<RangeControl label="Кресты: длина" value={activeGridLod.crossesLengthMeters} min={2} max={5_000} step={2} formatValue={(value) => `${value} м`} onChange={(crossesLengthMeters) => updateGridLod({ crossesLengthMeters })} />
|
||||
<RangeControl label="Кресты: ширина" value={activeGridLod.crossesWidthMeters} min={1} max={500} step={1} formatValue={(value) => `${value} м`} onChange={(crossesWidthMeters) => updateGridLod({ crossesWidthMeters })} />
|
||||
<ControlRow label="Кресты: цвет"><ColorField label="Цвет крестов сетки" value={activeGridLod.crossesColor} onChange={(crossesColor) => updateGridLod({ crossesColor })} /></ControlRow>
|
||||
<RangeControl label="Кресты: прозрачность" value={activeGridLod.crossesOpacity} min={0} max={100} formatValue={(value) => `${value}%`} onChange={(crossesOpacity) => updateGridLod({ crossesOpacity })} />
|
||||
<RangeControl label="Шаг гратикулы" value={activeGridLod.graticuleStepDegrees} min={0.1} max={10} step={0.05} formatValue={(value) => `${value}°`} onChange={(graticuleStepDegrees) => updateGridLod({ graticuleStepDegrees: normalizedGraticuleStepDegrees(graticuleStepDegrees) })} />
|
||||
<RangeControl label="Толщина гратикулы" value={activeGridLod.graticuleLineWidthPx} min={1} max={3} step={1} formatValue={(value) => `${value} px`} onChange={(graticuleLineWidthPx) => updateGridLod({ graticuleLineWidthPx })} />
|
||||
<ControlRow label="Цвет гратикулы"><ColorField label="Цвет WGS84-гратику́лы" value={activeGridLod.graticuleColor} onChange={(graticuleColor) => updateGridLod({ graticuleColor })} /></ControlRow>
|
||||
<RangeControl label="Прозрачность гратикулы" value={activeGridLod.graticuleOpacity} min={0} max={100} formatValue={(value) => `${value}%`} onChange={(graticuleOpacity) => updateGridLod({ graticuleOpacity })} />
|
||||
{activeGridLod.mode === "3d" ? <>
|
||||
<Checker checked={activeGridLod.volumeEnabled} label="Объёмный выбор сектора" onChange={(volumeEnabled) => updateGridLod({ volumeEnabled })} />
|
||||
<RangeControl
|
||||
label="Нижняя отметка объёма"
|
||||
value={activeGridLod.volumeMinimumHeightMeters}
|
||||
min={-1_000}
|
||||
max={activeGridLod.volumeMaximumHeightMeters - 1}
|
||||
step={10}
|
||||
formatValue={(value) => `${value} м WGS84`}
|
||||
onChange={(volumeMinimumHeightMeters) => updateGridVolumeRange({ volumeMinimumHeightMeters })}
|
||||
/>
|
||||
<RangeControl
|
||||
label="Верхняя отметка объёма"
|
||||
value={activeGridLod.volumeMaximumHeightMeters}
|
||||
min={activeGridLod.volumeMinimumHeightMeters + 1}
|
||||
max={10_000}
|
||||
step={10}
|
||||
formatValue={(value) => `${value} м WGS84`}
|
||||
onChange={(volumeMaximumHeightMeters) => updateGridVolumeRange({ volumeMaximumHeightMeters })}
|
||||
/>
|
||||
<RangeControl
|
||||
label="Высота адресного диапазона"
|
||||
value={activeGridLod.volumeBandHeightMeters}
|
||||
min={1}
|
||||
max={1_000}
|
||||
step={10}
|
||||
formatValue={(value) => `${value} м`}
|
||||
onChange={(volumeBandHeightMeters) => updateGridVolumeRange({ volumeBandHeightMeters })}
|
||||
/>
|
||||
<small className="catalog-map-inspector__note">Горизонтальный ID сектора остаётся стабильным. Высотный band добавляется как отдельный адрес внутри выбранной ENU-ячейки.</small>
|
||||
</> : null}
|
||||
<ControlRow label="Цвет заливки сектора">
|
||||
<ColorField
|
||||
label="Цвет заливки выбранного сектора"
|
||||
value={activeGridLod.selectionFillColor}
|
||||
onChange={(selectionFillColor) => updateGridLod({ selectionFillColor })}
|
||||
/>
|
||||
</ControlRow>
|
||||
<RangeControl
|
||||
label="Прозрачность заливки"
|
||||
value={activeGridLod.selectionFillOpacityPercent}
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
formatValue={(value) => `${value}%`}
|
||||
onChange={(selectionFillOpacityPercent) => updateGridLod({ selectionFillOpacityPercent })}
|
||||
/>
|
||||
<ControlRow label="Цвет линии сектора">
|
||||
<ColorField
|
||||
label="Цвет линии выбранного сектора"
|
||||
value={activeGridLod.selectionOutlineColor}
|
||||
onChange={(selectionOutlineColor) => updateGridLod({ selectionOutlineColor })}
|
||||
/>
|
||||
</ControlRow>
|
||||
<RangeControl
|
||||
label="Толщина линии"
|
||||
value={activeGridLod.selectionOutlineWidthPx}
|
||||
min={1}
|
||||
max={12}
|
||||
step={0.25}
|
||||
formatValue={(value) => `${value} px`}
|
||||
onChange={(selectionOutlineWidthPx) => updateGridLod({ selectionOutlineWidthPx })}
|
||||
/>
|
||||
<RangeControl
|
||||
label="Прозрачность линии"
|
||||
value={activeGridLod.selectionOutlineOpacityPercent}
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
formatValue={(value) => `${value}%`}
|
||||
onChange={(selectionOutlineOpacityPercent) => updateGridLod({ selectionOutlineOpacityPercent })}
|
||||
/>
|
||||
<small className="catalog-map-inspector__note">Оформление применяется к выбранному сектору текущего LOD.</small>
|
||||
<section className="catalog-map-grid-sector" aria-label="Выбранный сектор">
|
||||
<ControlRow label="Выбранный сектор"><strong className="catalog-map-grid-sector-id">{selectedGridSector?.id ?? "Нажмите сектор на карте"}</strong></ControlRow>
|
||||
{selectedGridSector ? <>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="compact"
|
||||
width="full"
|
||||
shape="pill"
|
||||
icon={<Icon name={gridSectorCopyState === "copied" ? "check" : "copy"} />}
|
||||
onClick={() => void copySelectedGridSectorId()}
|
||||
>{gridSectorCopyState === "copied" ? "ID скопирован" : "Копировать stable ID"}</Button>
|
||||
{gridSectorCopyState === "error" ? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">Не удалось записать ID в буфер обмена.</small> : null}
|
||||
<div className="catalog-map-grid-sector__facts">
|
||||
<ControlRow label="Family / LOD"><strong>{selectedGridSector.mode === "3d" ? "Local ENU" : "WGS84 graticule"} · LOD {selectedGridSector.lod}</strong></ControlRow>
|
||||
<ControlRow label="Адрес"><span>{selectedGridSector.label}</span></ControlRow>
|
||||
<ControlRow label="Границы"><span>{gridSectorBoundsLabel(selectedGridSector)}</span></ControlRow>
|
||||
<ControlRow label="Центр"><span>{gridSectorCenterLabel(selectedGridSector)}</span></ControlRow>
|
||||
<ControlRow label="Площадь"><strong>{formatGridSectorArea(selectedGridSector.areaSquareMeters)}</strong></ControlRow>
|
||||
</div>
|
||||
{selectedGridSector.parentMajorTile ? <div className="catalog-map-grid-sector__relation">
|
||||
<small>Parent major tile · {selectedGridSector.parentMajorTile.label}</small>
|
||||
<code title={selectedGridSector.parentMajorTile.id}>{selectedGridSector.parentMajorTile.id}</code>
|
||||
<small>{selectedGridSector.parentMajorTile.minorPerSide} × {selectedGridSector.parentMajorTile.minorPerSide} · {selectedGridSector.parentMajorTile.childCount} дочерних секторов · {formatGridSectorArea(selectedGridSector.parentMajorTile.areaSquareMeters)}</small>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="compact"
|
||||
width="full"
|
||||
data-grid-navigation-intent="parent-major"
|
||||
disabled={!mapRendererReady}
|
||||
onClick={() => focusGridMajorTile(selectedGridSector.parentMajorTile!)}
|
||||
>Фокус major-тайла</Button>
|
||||
</div> : <small className="catalog-map-inspector__note">Parent major tile выключен или недоступен для текущей топологии.</small>}
|
||||
<div className="catalog-map-grid-sector__relation">
|
||||
<small>Следующий LOD</small>
|
||||
{selectedGridParentLod ? <>
|
||||
<code title={selectedGridParentLod.id}>{selectedGridParentLod.id}</code>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="compact"
|
||||
width="full"
|
||||
data-grid-navigation-intent="next-lod"
|
||||
disabled={!mapRendererReady}
|
||||
onClick={() => focusGridSector(selectedGridParentLod)}
|
||||
>Перейти в LOD {selectedGridParentLod.lod}</Button>
|
||||
</> : <span>{selectedGridSector.lod >= sectorGridLodProfiles.length
|
||||
? "Верхний уровень иерархии"
|
||||
: `LOD ${selectedGridSector.lod + 1} меняет систему адресации`}</span>}
|
||||
</div>
|
||||
<div className="catalog-map-grid-sector__neighbors" aria-label="Соседние сектора">
|
||||
{GRID_SECTOR_DIRECTIONS.map(({ id, label }) => {
|
||||
const target = selectedGridNeighborTargets[id];
|
||||
return <div className="catalog-map-grid-sector__neighbor" key={id}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="compact"
|
||||
width="full"
|
||||
data-grid-navigation-intent={id}
|
||||
disabled={!target || !mapRendererReady}
|
||||
onClick={() => focusGridSector(target)}
|
||||
>{label}</Button>
|
||||
<code title={target?.id}>{target?.id ?? "Граница адресного пространства"}</code>
|
||||
</div>;
|
||||
})}
|
||||
</div>
|
||||
{selectedGridSector.mode === "3d" && selectedGridSectorProfile ? <div className="catalog-map-grid-sector__volume" data-enabled={selectedGridSectorProfile.volumeEnabled || undefined}>
|
||||
<ControlRow label="Высотный выбор"><strong>{selectedGridSectorProfile.volumeEnabled ? "Включён" : "Выключен"}</strong></ControlRow>
|
||||
<ControlRow label="Floor"><span>{selectedGridSector.volume?.floor ?? selectedGridSectorProfile.volumeMinimumHeightMeters} м WGS84</span></ControlRow>
|
||||
<ControlRow label="Ceiling"><span>{selectedGridSector.volume?.ceiling ?? selectedGridSectorProfile.volumeMaximumHeightMeters} м WGS84</span></ControlRow>
|
||||
<ControlRow label="Height band"><span>{selectedGridSector.volume?.bandHeight ?? selectedGridSectorProfile.volumeBandHeightMeters} м</span></ControlRow>
|
||||
{selectedGridSector.volume ? <code title={selectedGridSector.volume.id}>{selectedGridSector.volume.id}</code> : null}
|
||||
{selectedGridSectorProfile.volumeEnabled ? <div className="catalog-map-grid-sector__volume-actions">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="compact"
|
||||
width="full"
|
||||
data-grid-navigation-intent="below"
|
||||
disabled={!selectedGridVolumeTargets.below || !mapRendererReady}
|
||||
onClick={() => focusGridSector(selectedGridVolumeTargets.below)}
|
||||
>Ниже</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="compact"
|
||||
width="full"
|
||||
data-grid-navigation-intent="above"
|
||||
disabled={!selectedGridVolumeTargets.above || !mapRendererReady}
|
||||
onClick={() => focusGridSector(selectedGridVolumeTargets.above)}
|
||||
>Выше</Button>
|
||||
</div> : null}
|
||||
</div> : null}
|
||||
</> : <small className="catalog-map-inspector__note">Кликните ячейку, чтобы получить устойчивый адрес, геометрию и навигацию по соседям.</small>}
|
||||
</section>
|
||||
</div>,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { MapPresentation } from "./CesiumMapRenderer.js";
|
||||
import type { MapPresentation } from "./mapRendererContract.js";
|
||||
|
||||
export type GridLodMode = "3d" | "graticule";
|
||||
export type GridLodProfile = {
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
import type { Dispatch, ReactNode, SetStateAction } from "react";
|
||||
import {
|
||||
Button,
|
||||
Checker,
|
||||
ColorField,
|
||||
ControlRow,
|
||||
Icon,
|
||||
InspectorSelectField,
|
||||
RangeControl,
|
||||
} from "@nodedc/ui-react";
|
||||
import type { SelectOption } from "@nodedc/ui-react";
|
||||
import {
|
||||
OSM_BUILDINGS_OBSERVED_BAND_COUNT,
|
||||
cameraSurveySpiralDistance,
|
||||
type CameraSurveySelection,
|
||||
} from "./mapCameraPresets.js";
|
||||
import {
|
||||
isMapReferencePresentationProfile,
|
||||
type MapReferenceLayer,
|
||||
} from "./mapReferenceStations.js";
|
||||
import type { MapPageSettings } from "./mapPageContract.js";
|
||||
import type { MapGatewayHealth, MapProviderStatus } from "./mapRendererContract.js";
|
||||
import type { MapPresentationProfile } from "./mapPresentationProfile.js";
|
||||
import type { MapSelectableEntity } from "./mapWorkspaceModel.mjs";
|
||||
|
||||
export type MapInspectorSection = {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string;
|
||||
group: string;
|
||||
icon: ReactNode;
|
||||
content: ReactNode;
|
||||
};
|
||||
|
||||
type UpdateMapSettings = (patch: Partial<MapPageSettings>) => void;
|
||||
type UpdatePresentationProfile = (
|
||||
profileId: string,
|
||||
updater: (profile: MapPresentationProfile) => MapPresentationProfile,
|
||||
) => void;
|
||||
type UpdatePresentationStyle = (
|
||||
profileId: string,
|
||||
styleId: string,
|
||||
patch: Partial<MapPresentationProfile["styles"][number]>,
|
||||
) => void;
|
||||
type GatewayCheckState = "idle" | "checking" | "ready" | "stale" | "error";
|
||||
|
||||
const providerStateLabel: Record<MapProviderStatus["imagery"], string> = {
|
||||
loading: "загружается",
|
||||
ready: "готов",
|
||||
error: "недоступен",
|
||||
"not-configured": "не настроен",
|
||||
};
|
||||
|
||||
const logarithmicControlValue = (value: number) => Math.log10(Math.max(Number.MIN_VALUE, value));
|
||||
const valueFromLogarithmicControl = (value: number) => Math.max(1, Math.round(10 ** value));
|
||||
|
||||
export const formatMetricDistance = (value: number) => value >= 1000
|
||||
? `${(value / 1000).toLocaleString("ru-RU", { maximumFractionDigits: value >= 10_000 ? 0 : 1 })} км`
|
||||
: `${Math.round(value)} м`;
|
||||
|
||||
const formatMetricSpeed = (value: number) => value >= 1000
|
||||
? `${(value / 1000).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} км/с`
|
||||
: `${Math.round(value)} м/с`;
|
||||
|
||||
const formatDuration = (seconds: number) => {
|
||||
if (seconds >= 86_400) return `${(seconds / 86_400).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} сут`;
|
||||
if (seconds >= 3_600) return `${(seconds / 3_600).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} ч`;
|
||||
if (seconds >= 60) return `${Math.round(seconds / 60)} мин`;
|
||||
return `${Math.max(1, Math.round(seconds))} с`;
|
||||
};
|
||||
|
||||
export function buildMapSurfaceInspectorSections({
|
||||
mapSettings,
|
||||
providerStatus,
|
||||
updateMapSettings,
|
||||
}: {
|
||||
mapSettings: MapPageSettings;
|
||||
providerStatus: MapProviderStatus;
|
||||
updateMapSettings: UpdateMapSettings;
|
||||
}): MapInspectorSection[] {
|
||||
return [
|
||||
{
|
||||
id: "map-base",
|
||||
label: "Подложка и terrain",
|
||||
description: "provider-neutral surface",
|
||||
group: "Карта",
|
||||
icon: <Icon name="globe" />,
|
||||
content: <>
|
||||
<ControlRow label="Подложка"><strong>Cesium World Imagery</strong></ControlRow>
|
||||
<small className="catalog-map-inspector__note">Текущий официальный provider. Другие provider-слои появятся только после отдельного asset-контракта Platform.</small>
|
||||
<ControlRow label="Live providers"><span>Imagery: {providerStateLabel[providerStatus.imagery]} · Terrain: {providerStateLabel[providerStatus.terrain]} · 3D: {providerStateLabel[providerStatus.buildings]}</span></ControlRow>
|
||||
{Object.entries(providerStatus.errors).map(([provider, error]) => <small key={provider} className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">{provider}: {error}</small>)}
|
||||
<small className="catalog-map-inspector__note">Рельеф — отдельный слой под imagery.</small>
|
||||
<Checker checked={mapSettings.terrainEnabled} label="Terrain" onChange={(terrainEnabled) => updateMapSettings({ terrainEnabled })} />
|
||||
<RangeControl label="Вертикальное преувеличение рельефа" value={mapSettings.terrainExaggeration * 100} min={25} max={300} formatValue={(value) => `${(value / 100).toFixed(2)}×`} onChange={(value) => updateMapSettings({ terrainExaggeration: value / 100 })} />
|
||||
<Checker checked={mapSettings.monochrome} label="Монохромная поверхность" onChange={(monochrome) => updateMapSettings({ monochrome })} />
|
||||
<ControlRow label="Цвет монохрома"><ColorField label="Цвет монохромной поверхности" value={mapSettings.monochromeColor} onChange={(monochromeColor) => updateMapSettings({ monochromeColor })} /></ControlRow>
|
||||
<RangeControl label="Яркость" value={mapSettings.imageryBrightness} min={0} max={200} formatValue={(value) => `${value}%`} onChange={(imageryBrightness) => updateMapSettings({ imageryBrightness })} />
|
||||
<RangeControl label="Контраст" value={mapSettings.imageryContrast} min={0} max={200} formatValue={(value) => `${value}%`} onChange={(imageryContrast) => updateMapSettings({ imageryContrast })} />
|
||||
<RangeControl label="Насыщенность" value={mapSettings.imagerySaturation} min={0} max={200} formatValue={(value) => `${value}%`} onChange={(imagerySaturation) => updateMapSettings({ imagerySaturation })} />
|
||||
<RangeControl label="Гамма" value={mapSettings.imageryGamma} min={0} max={300} formatValue={(value) => `${value}%`} onChange={(imageryGamma) => updateMapSettings({ imageryGamma })} />
|
||||
<RangeControl label="Оттенок" value={mapSettings.imageryHue} min={-180} max={180} formatValue={(value) => `${value}°`} onChange={(imageryHue) => updateMapSettings({ imageryHue })} />
|
||||
<RangeControl label="Прозрачность imagery" value={mapSettings.imageryAlpha} min={0} max={100} formatValue={(value) => `${value}%`} onChange={(imageryAlpha) => updateMapSettings({ imageryAlpha })} />
|
||||
<ControlRow label="Цвет планеты"><ColorField label="Цвет terrain без imagery" value={mapSettings.globeColor} onChange={(globeColor) => updateMapSettings({ globeColor })} /></ControlRow>
|
||||
<ControlRow label="Фон сцены"><ColorField label="Цвет фона сцены" value={mapSettings.backgroundColor} onChange={(backgroundColor) => updateMapSettings({ backgroundColor })} /></ControlRow>
|
||||
</>,
|
||||
},
|
||||
{
|
||||
id: "map-atmosphere",
|
||||
label: "Атмосфера и освещение",
|
||||
description: "scene / color correction",
|
||||
group: "Карта",
|
||||
icon: <Icon name="activity" />,
|
||||
content: <>
|
||||
<Checker checked={mapSettings.atmosphereEnabled} label="Показывать атмосферу" onChange={(atmosphereEnabled) => updateMapSettings({ atmosphereEnabled })} />
|
||||
<RangeControl label="Атмосфера: оттенок" value={mapSettings.atmosphereHue} min={-100} max={100} formatValue={(value) => `${value}%`} onChange={(atmosphereHue) => updateMapSettings({ atmosphereHue })} />
|
||||
<RangeControl label="Атмосфера: насыщенность" value={mapSettings.atmosphereSaturation} min={-100} max={100} formatValue={(value) => `${value}%`} onChange={(atmosphereSaturation) => updateMapSettings({ atmosphereSaturation })} />
|
||||
<RangeControl label="Атмосфера: яркость" value={mapSettings.atmosphereBrightness} min={-100} max={100} formatValue={(value) => `${value}%`} onChange={(atmosphereBrightness) => updateMapSettings({ atmosphereBrightness })} />
|
||||
<Checker checked={mapSettings.fogEnabled} label="Туман" onChange={(fogEnabled) => updateMapSettings({ fogEnabled })} />
|
||||
<RangeControl label="Плотность тумана" value={mapSettings.fogDensity} min={0} max={100} formatValue={(value) => `${(value / 10000).toFixed(4)}`} onChange={(fogDensity) => updateMapSettings({ fogDensity })} />
|
||||
<Checker checked={mapSettings.sunEnabled} label="Солнечное освещение" onChange={(sunEnabled) => updateMapSettings({ sunEnabled })} />
|
||||
<RangeControl label="Час солнца" value={mapSettings.sunHour} min={0} max={24} formatValue={(value) => `${value}:00 UTC`} onChange={(sunHour) => updateMapSettings({ sunHour })} />
|
||||
<RangeControl label="Интенсивность света" value={mapSettings.sunIntensity} min={0} max={200} formatValue={(value) => `${value}%`} onChange={(sunIntensity) => updateMapSettings({ sunIntensity })} />
|
||||
<Checker checked={mapSettings.shadowsEnabled} label="Тени" onChange={(shadowsEnabled) => updateMapSettings({ shadowsEnabled })} />
|
||||
</>,
|
||||
},
|
||||
{
|
||||
id: "map-buildings",
|
||||
label: "3D здания",
|
||||
description: "3D Tiles / detail",
|
||||
group: "Карта",
|
||||
icon: <Icon name="building" />,
|
||||
content: <>
|
||||
<Checker checked={mapSettings.buildingsVisible} label="Показывать 3D здания" onChange={(buildingsVisible) => updateMapSettings({ buildingsVisible })} />
|
||||
<ControlRow label="Цвет"><ColorField label="Цвет зданий" value={mapSettings.buildingsColor} onChange={(buildingsColor) => updateMapSettings({ buildingsColor })} /></ControlRow>
|
||||
<RangeControl label="Прозрачность" value={Math.round(mapSettings.buildingsOpacity * 100)} min={0} max={100} formatValue={(value) => `${value}%`} onChange={(value) => updateMapSettings({ buildingsOpacity: value / 100 })} />
|
||||
<RangeControl label="Детализация" value={mapSettings.buildingsDetail} min={4} max={32} formatValue={(value) => `SSE ${value}`} onChange={(buildingsDetail) => updateMapSettings({ buildingsDetail })} />
|
||||
</>,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function buildMapPresentationInspectorSections({
|
||||
presentationProfiles,
|
||||
referenceLayers,
|
||||
setReferenceLayers,
|
||||
updatePresentationProfile,
|
||||
updatePresentationStyle,
|
||||
}: {
|
||||
presentationProfiles: MapPresentationProfile[];
|
||||
referenceLayers: MapReferenceLayer[];
|
||||
setReferenceLayers: Dispatch<SetStateAction<MapReferenceLayer[]>>;
|
||||
updatePresentationProfile: UpdatePresentationProfile;
|
||||
updatePresentationStyle: UpdatePresentationStyle;
|
||||
}): MapInspectorSection[] {
|
||||
return [
|
||||
...presentationProfiles.flatMap((profile) => {
|
||||
const referenceProfile = isMapReferencePresentationProfile(profile);
|
||||
const referenceLayer = referenceLayers.find((layer) => layer.presentationProfileId === profile.id);
|
||||
return [
|
||||
{
|
||||
id: `map-target-${profile.id}`,
|
||||
label: referenceProfile ? profile.title : profile.target.variant === "surface-fill" ? "HGeoZone" : "Таргет",
|
||||
description: profile.target.variant === "surface-fill" ? `проекция · ${profile.title}` : profile.title,
|
||||
group: referenceProfile ? "Станции" : profile.target.variant === "surface-fill" ? "Слои" : "Таргеты",
|
||||
icon: <Icon name={referenceProfile ? "globe" : profile.target.variant === "surface-fill" ? "grid" : "target"} />,
|
||||
content: <>
|
||||
<small className="catalog-map-inspector__note">Профиль принадлежит этой странице Application и управляется тем же provider-neutral MCP-контрактом. Исходный API в настройках отсутствует.</small>
|
||||
{referenceLayer ? (
|
||||
<Checker
|
||||
checked={referenceLayer.visible}
|
||||
label={`Показывать слой «${profile.title}»`}
|
||||
onChange={(visible) => setReferenceLayers((current) => current.map((layer) => (
|
||||
layer.id === referenceLayer.id ? { ...layer, visible } : layer
|
||||
)))}
|
||||
/>
|
||||
) : null}
|
||||
{profile.target.variant === "surface-fill" && <>
|
||||
<ControlRow label="Тип слоя"><strong>HGeoZone · ground projection</strong></ControlRow>
|
||||
{profile.styles.map((style) => {
|
||||
const classLabels = profile.classes.filter((item) => item.styleId === style.id).map((item) => item.label);
|
||||
const label = classLabels.length ? classLabels.join(" · ") : style.id;
|
||||
return <div className="catalog-map-inspector__style" key={style.id}>
|
||||
<ControlRow label={`Заливка · ${label}`}><ColorField label={`Цвет заливки: ${label}`} value={style.color} onChange={(color) => updatePresentationStyle(profile.id, style.id, { color })} /></ControlRow>
|
||||
<RangeControl label={`Прозрачность заливки · ${label}`} value={Math.round(style.opacity * 100)} min={0} max={100} step={1} formatValue={(value) => `${value}%`} onChange={(value) => updatePresentationStyle(profile.id, style.id, { opacity: value / 100 })} />
|
||||
</div>;
|
||||
})}
|
||||
<ControlRow label="Граница"><ColorField label="Цвет границы HGeoZone" value={profile.target.outlineColor} onChange={(outlineColor) => updatePresentationProfile(profile.id, (current) => current.target.variant === "surface-fill" ? ({ ...current, target: { ...current.target, outlineColor } }) : current)} /></ControlRow>
|
||||
<RangeControl label="Прозрачность границы" value={Math.round(profile.target.outlineOpacity * 100)} min={0} max={100} step={1} formatValue={(value) => `${value}%`} onChange={(value) => updatePresentationProfile(profile.id, (current) => current.target.variant === "surface-fill" ? ({ ...current, target: { ...current.target, outlineOpacity: value / 100 } }) : current)} />
|
||||
<RangeControl label="Толщина границы" value={profile.target.outlineWidthPx} min={0} max={8} step={0.5} formatValue={(value) => `${value} px`} onChange={(outlineWidthPx) => updatePresentationProfile(profile.id, (current) => current.target.variant === "surface-fill" ? ({ ...current, target: { ...current.target, outlineWidthPx } }) : current)} />
|
||||
</>}
|
||||
{profile.target.variant === "elevated-spike" && <>
|
||||
<RangeControl label="Высота таргета" value={profile.target.stemHeightMeters} min={100} max={10_000} step={50} formatValue={(value) => `${value} м`} onChange={(stemHeightMeters) => updatePresentationProfile(profile.id, (current) => current.target.variant === "elevated-spike" ? ({ ...current, target: { ...current.target, stemHeightMeters } }) : current)} />
|
||||
<RangeControl label="Размер головки" value={profile.target.headSizePx} min={1} max={32} step={1} formatValue={(value) => `${value} px`} onChange={(headSizePx) => updatePresentationProfile(profile.id, (current) => current.target.variant === "elevated-spike" ? ({ ...current, target: { ...current.target, headSizePx } }) : current)} />
|
||||
<RangeControl label="Толщина стержня" value={profile.target.stemWidthPx} min={0.25} max={12} step={0.25} formatValue={(value) => `${value} px`} onChange={(stemWidthPx) => updatePresentationProfile(profile.id, (current) => current.target.variant === "elevated-spike" ? ({ ...current, target: { ...current.target, stemWidthPx } }) : current)} />
|
||||
</>}
|
||||
<InspectorSelectField
|
||||
label="Подпись"
|
||||
value={profile.label.mode}
|
||||
options={[
|
||||
{ value: "subject_id", label: "ID", description: "Стабильный идентификатор сущности" },
|
||||
{ value: "attributes", label: "Имя", description: "Первое доступное display-поле" },
|
||||
{ value: "none", label: "Нет", description: "Не показывать плашку" },
|
||||
]}
|
||||
onChange={(mode) => updatePresentationProfile(profile.id, (current) => ({ ...current, label: { ...current.label, mode } }))}
|
||||
/>
|
||||
<RangeControl label="Размер подписи" value={profile.label.sizePx} min={8} max={32} step={1} formatValue={(value) => `${value} px`} onChange={(sizePx) => updatePresentationProfile(profile.id, (current) => ({ ...current, label: { ...current.label, sizePx } }))} />
|
||||
<RangeControl label="Смещение подписи X" value={profile.label.offsetX} min={-100} max={100} step={1} formatValue={(value) => `${value} px`} onChange={(offsetX) => updatePresentationProfile(profile.id, (current) => ({ ...current, label: { ...current.label, offsetX } }))} />
|
||||
<RangeControl label="Смещение подписи Y" value={profile.label.offsetY} min={-100} max={100} step={1} formatValue={(value) => `${value} px`} onChange={(offsetY) => updatePresentationProfile(profile.id, (current) => ({ ...current, label: { ...current.label, offsetY } }))} />
|
||||
<RangeControl label="Скрывать подпись выше" value={profile.label.hideCameraHeightMeters} min={1_000} max={500_000} step={1_000} formatValue={(value) => `${Math.round(value / 1_000)} км`} onChange={(hideCameraHeightMeters) => updatePresentationProfile(profile.id, (current) => ({ ...current, label: { ...current.label, hideCameraHeightMeters } }))} />
|
||||
<RangeControl label={profile.target.variant === "surface-fill" ? "Скрывать HGeoZone выше" : "Скрывать таргет выше"} value={profile.target.hideCameraHeightMeters} min={1_000} max={500_000} step={1_000} formatValue={(value) => `${Math.round(value / 1_000)} км`} onChange={(hideCameraHeightMeters) => updatePresentationProfile(profile.id, (current) => ({ ...current, target: { ...current.target, hideCameraHeightMeters } }))} />
|
||||
<ControlRow label="Фон плашки"><ColorField label="Цвет фона подписи" value={profile.label.backgroundColor} onChange={(backgroundColor) => updatePresentationProfile(profile.id, (current) => ({ ...current, label: { ...current.label, backgroundColor } }))} /></ControlRow>
|
||||
<RangeControl label="Прозрачность плашки" value={Math.round(profile.label.backgroundOpacity * 100)} min={0} max={100} step={1} formatValue={(value) => `${value}%`} onChange={(value) => updatePresentationProfile(profile.id, (current) => ({ ...current, label: { ...current.label, backgroundOpacity: value / 100 } }))} />
|
||||
</>,
|
||||
},
|
||||
...(profile.target.variant === "surface-fill" || referenceProfile ? [] : [{
|
||||
id: `map-state-classes-${profile.id}`,
|
||||
label: "Классы состояния",
|
||||
description: "нормализованные фасеты онтологии",
|
||||
group: "Таргеты",
|
||||
icon: <Icon name="sliders" />,
|
||||
content: <>
|
||||
<small className="catalog-map-inspector__note">Цвета назначены семантическим классам после нормализации данных. Здесь нет названий provider-статусов и привязки к транспорту.</small>
|
||||
{profile.styles.map((style) => {
|
||||
const classLabels = profile.classes.filter((item) => item.styleId === style.id).map((item) => item.label);
|
||||
const label = classLabels.length ? classLabels.join(" · ") : style.id;
|
||||
return <div className="catalog-map-inspector__style" key={style.id}>
|
||||
<ControlRow label={label}><ColorField label={`Цвет: ${label}`} value={style.color} onChange={(color) => updatePresentationStyle(profile.id, style.id, { color })} /></ControlRow>
|
||||
<RangeControl label={`${label}: прозрачность`} value={Math.round(style.opacity * 100)} min={0} max={100} step={1} formatValue={(value) => `${value}%`} onChange={(value) => updatePresentationStyle(profile.id, style.id, { opacity: value / 100 })} />
|
||||
</div>;
|
||||
})}
|
||||
</>,
|
||||
}]),
|
||||
];
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
export function buildMapRuntimeInspectorSections({
|
||||
animationModeEnabled,
|
||||
setAnimationMode,
|
||||
spiralPresetId,
|
||||
spiralPresetOptions,
|
||||
spiralRunning,
|
||||
selectSpiralPreset,
|
||||
spiralHeightMeters,
|
||||
setSpiralHeightMeters,
|
||||
spiralSpeedMetersPerSecond,
|
||||
setSpiralSpeedMetersPerSecond,
|
||||
spiralPitchMetersPerTurn,
|
||||
setSpiralPitchMetersPerTurn,
|
||||
spiralTargetRadiusMeters,
|
||||
setSpiralTargetRadiusMeters,
|
||||
setSpiralPresetId,
|
||||
spiralCanStart,
|
||||
spiralTileCacheReady,
|
||||
providerStatus,
|
||||
gatewayHealth,
|
||||
gatewayCheckState,
|
||||
toggleSpiralAnimation,
|
||||
spiralMessage,
|
||||
mapSettings,
|
||||
setCacheEnabled,
|
||||
setCacheNoOverwrite,
|
||||
gatewayEndpoint,
|
||||
liveCacheSummary,
|
||||
refreshCurrentViewport,
|
||||
cacheRefresh,
|
||||
verifyGateway,
|
||||
transportDiagnostic,
|
||||
gatewayHealthAge,
|
||||
gatewayCheckError,
|
||||
selected,
|
||||
}: {
|
||||
animationModeEnabled: boolean;
|
||||
setAnimationMode: (enabled: boolean) => void;
|
||||
spiralPresetId: CameraSurveySelection;
|
||||
spiralPresetOptions: Array<SelectOption<CameraSurveySelection>>;
|
||||
spiralRunning: boolean;
|
||||
selectSpiralPreset: (presetId: CameraSurveySelection) => void;
|
||||
spiralHeightMeters: number;
|
||||
setSpiralHeightMeters: Dispatch<SetStateAction<number>>;
|
||||
spiralSpeedMetersPerSecond: number;
|
||||
setSpiralSpeedMetersPerSecond: Dispatch<SetStateAction<number>>;
|
||||
spiralPitchMetersPerTurn: number;
|
||||
setSpiralPitchMetersPerTurn: Dispatch<SetStateAction<number>>;
|
||||
spiralTargetRadiusMeters: number;
|
||||
setSpiralTargetRadiusMeters: Dispatch<SetStateAction<number>>;
|
||||
setSpiralPresetId: Dispatch<SetStateAction<CameraSurveySelection>>;
|
||||
spiralCanStart: boolean;
|
||||
spiralTileCacheReady: boolean;
|
||||
providerStatus: MapProviderStatus;
|
||||
gatewayHealth: MapGatewayHealth | null;
|
||||
gatewayCheckState: GatewayCheckState;
|
||||
toggleSpiralAnimation: () => void;
|
||||
spiralMessage: string | null;
|
||||
mapSettings: MapPageSettings;
|
||||
setCacheEnabled: (enabled: boolean) => void;
|
||||
setCacheNoOverwrite: (enabled: boolean) => void;
|
||||
gatewayEndpoint: string | null;
|
||||
liveCacheSummary: string;
|
||||
refreshCurrentViewport: () => void;
|
||||
cacheRefresh: boolean;
|
||||
verifyGateway: () => void | Promise<void>;
|
||||
transportDiagnostic: string | null;
|
||||
gatewayHealthAge: string | null;
|
||||
gatewayCheckError: string | null;
|
||||
selected: MapSelectableEntity | undefined;
|
||||
}): MapInspectorSection[] {
|
||||
return [
|
||||
{
|
||||
id: "map-camera-animation",
|
||||
label: "Анимация камеры",
|
||||
description: "geodesic spiral survey",
|
||||
group: "Камера",
|
||||
icon: <Icon name="activity" />,
|
||||
content: <>
|
||||
<Checker checked={animationModeEnabled} label="Режим анимации" onChange={setAnimationMode} />
|
||||
{animationModeEnabled ? <>
|
||||
<small className="catalog-map-inspector__note">Стартовая точка берётся из текущей позиции камеры. Камера смотрит почти в надир, а маршрут ждёт текущие tiles перед продолжением. Движение идёт по региональной геодезической спирали WGS84 до выбранного радиуса.</small>
|
||||
<InspectorSelectField
|
||||
label="Профиль покрытия"
|
||||
value={spiralPresetId}
|
||||
options={spiralPresetOptions}
|
||||
disabled={spiralRunning}
|
||||
onChange={selectSpiralPreset}
|
||||
/>
|
||||
<small className="catalog-map-inspector__note">У текущего OSM Buildings подтверждено {OSM_BUILDINGS_OBSERVED_BAND_COUNT} иерархических bands. Десять профилей управляют высотой и покрытием; фактический LOD Cesium выбирает по SSE, viewport и расстоянию.</small>
|
||||
<ControlRow label="Слои прохода"><small>Imagery · Terrain · OSM Buildings</small></ControlRow>
|
||||
<RangeControl
|
||||
label="Высота над землёй"
|
||||
value={logarithmicControlValue(spiralHeightMeters)}
|
||||
min={logarithmicControlValue(10)}
|
||||
max={logarithmicControlValue(100_000)}
|
||||
step={0.01}
|
||||
disabled={spiralRunning}
|
||||
formatValue={(value) => formatMetricDistance(10 ** value)}
|
||||
onChange={(value) => {
|
||||
setSpiralPresetId("custom");
|
||||
setSpiralHeightMeters(valueFromLogarithmicControl(value));
|
||||
}}
|
||||
/>
|
||||
<RangeControl
|
||||
label="Скорость камеры"
|
||||
value={logarithmicControlValue(spiralSpeedMetersPerSecond)}
|
||||
min={logarithmicControlValue(1)}
|
||||
max={logarithmicControlValue(5_000)}
|
||||
step={0.01}
|
||||
disabled={spiralRunning}
|
||||
formatValue={(value) => formatMetricSpeed(10 ** value)}
|
||||
onChange={(value) => {
|
||||
setSpiralPresetId("custom");
|
||||
setSpiralSpeedMetersPerSecond(valueFromLogarithmicControl(value));
|
||||
}}
|
||||
/>
|
||||
<RangeControl
|
||||
label="Шаг спирали"
|
||||
value={logarithmicControlValue(spiralPitchMetersPerTurn)}
|
||||
min={logarithmicControlValue(20)}
|
||||
max={logarithmicControlValue(100_000)}
|
||||
step={0.01}
|
||||
disabled={spiralRunning}
|
||||
formatValue={(value) => formatMetricDistance(10 ** value)}
|
||||
onChange={(value) => {
|
||||
setSpiralPresetId("custom");
|
||||
setSpiralPitchMetersPerTurn(valueFromLogarithmicControl(value));
|
||||
}}
|
||||
/>
|
||||
<RangeControl
|
||||
label="Радиус прохода"
|
||||
value={logarithmicControlValue(spiralTargetRadiusMeters)}
|
||||
min={logarithmicControlValue(1_000)}
|
||||
max={logarithmicControlValue(250_000)}
|
||||
step={0.01}
|
||||
disabled={spiralRunning}
|
||||
formatValue={(value) => formatMetricDistance(10 ** value)}
|
||||
onChange={(value) => {
|
||||
setSpiralPresetId("custom");
|
||||
setSpiralTargetRadiusMeters(valueFromLogarithmicControl(value));
|
||||
}}
|
||||
/>
|
||||
<small className="catalog-map-inspector__note">Расчётное движение без ожидания сети: {formatDuration(cameraSurveySpiralDistance(spiralTargetRadiusMeters, spiralPitchMetersPerTurn) / spiralSpeedMetersPerSecond)}. Tile waits и автоматическое сужение шага под viewport увеличат фактическое время.</small>
|
||||
{!spiralCanStart && !spiralRunning ? <small className="catalog-map-inspector__note" role="status">Подготовка: imagery — {providerStateLabel[providerStatus.imagery]}, terrain — {providerStateLabel[providerStatus.terrain]}, OSM Buildings — {providerStateLabel[providerStatus.buildings]}, TileCache — {spiralTileCacheReady ? "готов" : gatewayHealth?.cache?.atCapacity ? "заполнен" : gatewayCheckState === "checking" ? "проверяется" : "недоступен для записи"}.</small> : null}
|
||||
<Button variant="secondary" shape="pill" onClick={toggleSpiralAnimation} disabled={!spiralRunning && !spiralCanStart}>{spiralRunning ? "Остановить" : "Запустить режим анимации"}</Button>
|
||||
{spiralRunning ? <small className="catalog-map-inspector__note">Камера движется от исходной точки. Выключение режима, уход со страницы или reload остановят сессию.</small> : null}
|
||||
{spiralMessage ? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="status">{spiralMessage}</small> : null}
|
||||
</> : null}
|
||||
</>,
|
||||
},
|
||||
{
|
||||
id: "map-cache",
|
||||
label: "TileCache",
|
||||
description: "Platform Map Gateway",
|
||||
group: "Хранение",
|
||||
icon: <Icon name="database" />,
|
||||
content: <>
|
||||
<small className="catalog-map-inspector__note">Общий persistent cache Platform: он не принадлежит приложению, странице или пользователю.</small>
|
||||
<Checker checked={mapSettings.cacheEnabled} label="Кэшировать live-данные" onChange={setCacheEnabled} />
|
||||
<small className="catalog-map-inspector__note">Cache hit отдаётся как есть; новый tile записывается только при miss.</small>
|
||||
<Checker checked={mapSettings.cacheNoOverwrite} disabled={!mapSettings.cacheEnabled} label="Не перезаписывать уже полученное" onChange={setCacheNoOverwrite} />
|
||||
<ControlRow className="catalog-map-inspector__cache-fact" label="Режим"><span>{mapSettings.cacheEnabled ? mapSettings.cacheNoOverwrite ? "Live + Cache · append-only" : "Live + Cache · обновление разрешено" : "Live без persistent cache"}</span></ControlRow>
|
||||
<ControlRow className="catalog-map-inspector__cache-fact" label="Хранилище"><span>Platform Map Gateway</span></ControlRow>
|
||||
<ControlRow className="catalog-map-inspector__cache-fact" label="Подключение"><span>{gatewayEndpoint ?? "runtime profile · не проверено"}</span></ControlRow>
|
||||
<ControlRow className="catalog-map-inspector__cache-fact" label="Записано"><span>{liveCacheSummary}</span></ControlRow>
|
||||
<ControlRow className="catalog-map-inspector__cache-fact" label="Политика"><span>{gatewayHealth?.cache?.writePolicy ?? "append-only · проверяется"}</span></ControlRow>
|
||||
<Button variant="secondary" shape="pill" icon={<Icon name="refresh" />} onClick={refreshCurrentViewport} disabled={!mapSettings.cacheEnabled || cacheRefresh}> {cacheRefresh ? "Обновляем viewport…" : "Обновить текущий viewport"}</Button>
|
||||
<Button variant="secondary" shape="pill" icon={<Icon name="refresh" />} onClick={() => void verifyGateway()} disabled={gatewayCheckState === "checking"}>{gatewayCheckState === "checking" ? "Проверяем Gateway…" : "Проверить подключение"}</Button>
|
||||
<small className="catalog-map-inspector__note">Live Cache: {liveCacheSummary} · {gatewayHealth?.cache?.mode ?? "проверяется"}</small>
|
||||
{transportDiagnostic ? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">{transportDiagnostic}</small> : null}
|
||||
{gatewayHealthAge ? <small className="catalog-map-inspector__note">{gatewayHealthAge}</small> : null}
|
||||
<small className="catalog-map-inspector__note">{mapSettings.cacheEnabled ? mapSettings.cacheNoOverwrite ? "Новые miss дописываются; при заполнении объёма Gateway продолжит live-маршрут без удаления прежних tiles." : "Новые запросы этого Application могут явно обновлять уже записанные tiles." : "Real-time: provider остаётся официальным, чтение и запись persistent cache выключены."}</small>
|
||||
{gatewayHealth?.cache?.atCapacity ? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">TileCache заполнен: новые tiles показываются live, но не записываются. Существующий cache не удаляется.</small> : null}
|
||||
{gatewayCheckState === "error" || gatewayCheckState === "stale" ? <small className="catalog-map-inspector__note catalog-map-inspector__note--error" role="alert">{gatewayCheckError}</small> : null}
|
||||
</>,
|
||||
},
|
||||
{
|
||||
id: "map-selection",
|
||||
label: "Выбранная сущность",
|
||||
description: "selection contract",
|
||||
group: "Данные",
|
||||
icon: <Icon name="target" />,
|
||||
content: <>
|
||||
<ControlRow label="Сущность"><strong>{selected?.title ?? "Нет выбора"}</strong></ControlRow>
|
||||
<ControlRow label="Тип"><span>{selected?.kind ?? "—"}{selected?.status ? ` · ${selected.status}` : ""}</span></ControlRow>
|
||||
</>,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { WorkspaceWindowRect } from "@nodedc/ui-react";
|
||||
import type { GridLodProfile, MapCameraView, MapPresentation } from "./mapRendererContract.js";
|
||||
import { DEFAULT_GRID_LOD_PROFILES } from "./mapGridPolicy.mjs";
|
||||
import type { MapPresentationProfile } from "./mapPresentationProfile.js";
|
||||
import {
|
||||
ensureMapReferencePresentationProfiles,
|
||||
initialMapReferenceLayers,
|
||||
type MapReferenceLayer,
|
||||
} from "./mapReferenceStations.js";
|
||||
import { DEFAULT_MAP_SUBJECT_DETAIL_PROFILE } from "./mapSubjectCard.mjs";
|
||||
import type { MapSubjectDetailProfile } from "./mapSubjectCard.mjs";
|
||||
|
||||
export type MapPageSettings = Omit<MapPresentation, "cacheRefresh">;
|
||||
|
||||
/**
|
||||
* A stable, provider-neutral visual binding owned by one Map Page instance.
|
||||
*
|
||||
* This is intentionally distinct from a live Data Product subject. Engine can
|
||||
* identify the source entity, while Foundry owns the pin presentation and its
|
||||
* page-local placement contract.
|
||||
*/
|
||||
export type MapPinBinding = {
|
||||
id: string;
|
||||
subjectId: string;
|
||||
kind: "elevated-spike";
|
||||
label: string;
|
||||
status: string;
|
||||
coordinates: { longitude: number; latitude: number; heightMeters: number };
|
||||
source: { entityId: string; streamId: string; displayFields: string[] };
|
||||
attributes: Record<string, string | number | boolean>;
|
||||
};
|
||||
|
||||
/**
|
||||
* A renderer-neutral declaration of a Data Product assigned to a Map slot.
|
||||
*
|
||||
* It contains no provider endpoint, tenant/connection scope, credential,
|
||||
* browser token or raw payload. Foundry resolves the target-scoped server
|
||||
* consumer from application/page/binding identity.
|
||||
*/
|
||||
export type MapDataProductBinding = {
|
||||
id: string;
|
||||
displayName?: string;
|
||||
order?: number;
|
||||
dataProductId: string;
|
||||
slotId: string;
|
||||
delivery: "snapshot+patch";
|
||||
semanticTypes: string[];
|
||||
fieldProjection: string[];
|
||||
presentationProfileId?: string;
|
||||
subjectDetailProfileId?: string;
|
||||
aspectId?: string;
|
||||
joinToBindingId?: string;
|
||||
dataClass?: "operational" | "restricted";
|
||||
};
|
||||
|
||||
export type MapSubjectWindowState = {
|
||||
open: boolean;
|
||||
rect: WorkspaceWindowRect;
|
||||
maximized: boolean;
|
||||
zIndex: number;
|
||||
};
|
||||
|
||||
export type MapWorkspaceWindowId = "sector" | "subject-card" | `binding:${string}`;
|
||||
|
||||
export type MapSubjectState = {
|
||||
bindingId: string;
|
||||
visible: boolean;
|
||||
/** Missing facet means unconstrained; an explicit empty list means no matches. */
|
||||
filters: Record<string, string[]>;
|
||||
window: MapSubjectWindowState;
|
||||
};
|
||||
|
||||
export type MapPageLayout = {
|
||||
schemaVersion: 1;
|
||||
pageId: "map";
|
||||
settings: MapPageSettings;
|
||||
mapHeight: number;
|
||||
camera: MapCameraView;
|
||||
pinBindings: MapPinBinding[];
|
||||
presentationProfiles: MapPresentationProfile[];
|
||||
subjectDetailProfiles: MapSubjectDetailProfile[];
|
||||
dataProductBindings: MapDataProductBinding[];
|
||||
subjectStates: MapSubjectState[];
|
||||
referenceLayers: MapReferenceLayer[];
|
||||
inspectorOpenSections: string[];
|
||||
savedAt?: string;
|
||||
};
|
||||
|
||||
export type MapFixturePreviewHandle = {
|
||||
getLayout: () => MapPageLayout | null;
|
||||
};
|
||||
|
||||
export const initialMapSettings: MapPageSettings = {
|
||||
imagerySource: "cesium-live",
|
||||
imageryVisible: true,
|
||||
cacheEnabled: true,
|
||||
cacheNoOverwrite: true,
|
||||
terrainEnabled: true,
|
||||
terrainExaggeration: 1,
|
||||
monochrome: false,
|
||||
monochromeColor: "#15151b",
|
||||
imageryGamma: 57,
|
||||
imageryHue: 13,
|
||||
imageryAlpha: 27,
|
||||
globeColor: "#15151b",
|
||||
backgroundColor: "#08090d",
|
||||
atmosphereEnabled: false,
|
||||
atmosphereHue: 0,
|
||||
atmosphereSaturation: 0,
|
||||
atmosphereBrightness: 0,
|
||||
fogEnabled: true,
|
||||
fogDensity: 2,
|
||||
sunEnabled: true,
|
||||
sunHour: 12,
|
||||
sunIntensity: 200,
|
||||
shadowsEnabled: true,
|
||||
buildingsVisible: true,
|
||||
buildingsColor: "#a27aff",
|
||||
buildingsOpacity: 1,
|
||||
buildingsDetail: 4,
|
||||
imageryBrightness: 118,
|
||||
imageryContrast: 102,
|
||||
imagerySaturation: 0,
|
||||
gridVisible: true,
|
||||
gridLodEnabled: true,
|
||||
grid3dEnabled: true,
|
||||
gridGraticuleEnabled: true,
|
||||
gridCenterMode: "fixed",
|
||||
gridCenterLatitude: 55.7558,
|
||||
gridCenterLongitude: 37.6173,
|
||||
gridTileSizeKm: 10,
|
||||
gridAutoDisableHeightKm: 10_000,
|
||||
gridRebuildOnMoveEnd: true,
|
||||
gridLegacyMode: false,
|
||||
gridMax3dViewAngleDegrees: 30,
|
||||
gridHeightMeters: 500,
|
||||
gridLod1MaxHeightKm: 10,
|
||||
gridLod1StepKm: 1,
|
||||
gridLod1Mode: "3d",
|
||||
gridLod2MaxHeightKm: 50,
|
||||
gridLod2StepKm: 5,
|
||||
gridLod2Mode: "3d",
|
||||
gridLod3MaxHeightKm: 200,
|
||||
gridLod3StepKm: 25,
|
||||
gridLod3Mode: "3d",
|
||||
gridLod4MaxHeightKm: 800,
|
||||
gridLod4StepKm: 50,
|
||||
gridLod4Mode: "graticule",
|
||||
gridLod5MaxHeightKm: 3_000,
|
||||
gridLod5StepKm: 50,
|
||||
gridLod5Mode: "graticule",
|
||||
gridRadiusKm: 40,
|
||||
gridLineWidth: 1,
|
||||
gridLineDiameterMeters: 7,
|
||||
gridColor: "#9c9c9c",
|
||||
gridOpacity: 12,
|
||||
gridDotsEnabled: true,
|
||||
gridDotsSize: 7,
|
||||
gridDotsDiameterMeters: 10,
|
||||
gridDotsColor: "#9c9c9c",
|
||||
gridDotsOpacity: 58,
|
||||
gridCrossesEnabled: false,
|
||||
gridCrossesLengthMeters: 60,
|
||||
gridCrossesWidthMeters: 10,
|
||||
gridCrossesColor: "#9c9c9c",
|
||||
gridCrossesOpacity: 46,
|
||||
gridLodProfiles: structuredClone(DEFAULT_GRID_LOD_PROFILES) as GridLodProfile[],
|
||||
};
|
||||
|
||||
// A deterministic provider-neutral viewport exists before the renderer emits
|
||||
// its first camera update, so a freshly created page is immediately saveable.
|
||||
export const fallbackMapCamera: MapCameraView = {
|
||||
longitude: 37.618423,
|
||||
latitude: 55.751244,
|
||||
height: 40_000,
|
||||
heading: 0,
|
||||
pitch: -0.9,
|
||||
roll: 0,
|
||||
};
|
||||
|
||||
export function createDefaultMapPageLayout(expanded = false): MapPageLayout {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
pageId: "map",
|
||||
settings: structuredClone(initialMapSettings),
|
||||
mapHeight: expanded ? 620 : 470,
|
||||
camera: { ...fallbackMapCamera },
|
||||
pinBindings: [],
|
||||
presentationProfiles: ensureMapReferencePresentationProfiles([]),
|
||||
subjectDetailProfiles: [structuredClone(DEFAULT_MAP_SUBJECT_DETAIL_PROFILE) as MapSubjectDetailProfile],
|
||||
dataProductBindings: [],
|
||||
subjectStates: [],
|
||||
referenceLayers: initialMapReferenceLayers(),
|
||||
inspectorOpenSections: ["map-base"],
|
||||
};
|
||||
}
|
||||
|
||||
export function defaultSubjectWindowState(index: number): MapSubjectWindowState {
|
||||
return {
|
||||
open: false,
|
||||
rect: {
|
||||
x: 24 + (index % 5) * 28,
|
||||
y: 56 + (index % 5) * 28,
|
||||
width: 280,
|
||||
height: 260,
|
||||
},
|
||||
maximized: false,
|
||||
zIndex: 20 + index,
|
||||
};
|
||||
}
|
||||
|
||||
export const defaultSectorWindowRect: WorkspaceWindowRect = {
|
||||
x: 24,
|
||||
y: 72,
|
||||
width: 380,
|
||||
height: 530,
|
||||
};
|
||||
|
||||
export const defaultSubjectCardRect: WorkspaceWindowRect = {
|
||||
x: 940,
|
||||
y: 72,
|
||||
width: 390,
|
||||
height: 520,
|
||||
};
|
||||
|
||||
export type { MapSubjectDetailProfile } from "./mapSubjectCard.mjs";
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { MapRuntimeFact } from "./useMapDataProductRuntime.js";
|
||||
|
||||
export type MapPresentationFacetValue = {
|
||||
value: string;
|
||||
label: string;
|
||||
order: number;
|
||||
};
|
||||
|
||||
export type MapPresentationFacet = {
|
||||
id: string;
|
||||
field: string;
|
||||
label: string;
|
||||
filterable: boolean;
|
||||
counter: boolean;
|
||||
values: MapPresentationFacetValue[];
|
||||
};
|
||||
|
||||
export type MapPresentationStyle = {
|
||||
id: string;
|
||||
color: string;
|
||||
opacity: number;
|
||||
};
|
||||
|
||||
export type MapPresentationClass = {
|
||||
id: string;
|
||||
label: string;
|
||||
priority: number;
|
||||
match: Array<{ field: string; equals: string }>;
|
||||
styleId: string;
|
||||
renderable: boolean;
|
||||
};
|
||||
|
||||
export type MapPresentationProfile = {
|
||||
id: string;
|
||||
version: string;
|
||||
title: string;
|
||||
semanticTypes: string[];
|
||||
label: {
|
||||
mode: "subject_id" | "attributes" | "none";
|
||||
fields: string[];
|
||||
fontWeight: number;
|
||||
sizePx: number;
|
||||
color: string;
|
||||
outlineColor: string;
|
||||
outlineWidthPx: number;
|
||||
backgroundColor: string;
|
||||
backgroundOpacity: number;
|
||||
paddingX: number;
|
||||
paddingY: number;
|
||||
maxLength: number;
|
||||
offsetX: number;
|
||||
offsetY: number;
|
||||
hideCameraHeightMeters: number;
|
||||
};
|
||||
target: ({
|
||||
variant: "elevated-spike";
|
||||
stemHeightMeters: number;
|
||||
headSizePx: number;
|
||||
stemWidthPx: number;
|
||||
} | {
|
||||
variant: "surface-fill";
|
||||
}) & {
|
||||
outlineColor: string;
|
||||
outlineOpacity: number;
|
||||
outlineWidthPx: number;
|
||||
hideCameraHeightMeters: number;
|
||||
};
|
||||
facets: MapPresentationFacet[];
|
||||
styles: MapPresentationStyle[];
|
||||
classes: MapPresentationClass[];
|
||||
defaultClassId: string;
|
||||
sort: Array<{ field: string; order: string[] }>;
|
||||
};
|
||||
|
||||
export type MapSubjectFilterState = {
|
||||
/** False is an explicit empty map state. It must never normalize to all. */
|
||||
visible: boolean;
|
||||
/** Missing facet is unconstrained; explicit empty facet matches nothing. */
|
||||
facets: Record<string, string[]>;
|
||||
};
|
||||
|
||||
export type MapPresentationFilters = Record<string, MapSubjectFilterState>;
|
||||
|
||||
export function normalizeClientMapPresentationProfiles(profiles: MapPresentationProfile[]): MapPresentationProfile[];
|
||||
export function mapPresentationBindingIsAll(bindingId: string, filters: MapPresentationFilters): boolean;
|
||||
export function mapPresentationFacetValueIsEnabled(facets: Record<string, string[]>, field: string, value: string): boolean;
|
||||
export function normalizeMapPresentationFacetSelections(facets: Record<string, string[]>, profile: MapPresentationProfile): Record<string, string[]>;
|
||||
export function toggleMapPresentationFacetSelection(facets: Record<string, string[]>, field: string, value: string, availableValues: string[]): Record<string, string[]>;
|
||||
export function mapPresentationProfileForFact(profiles: MapPresentationProfile[], presentationProfileId: string | undefined, semanticType: string): MapPresentationProfile | undefined;
|
||||
export function resolveMapPresentationClass(fact: MapRuntimeFact, profile: MapPresentationProfile): MapPresentationClass | undefined;
|
||||
export function resolveMapPresentationStyle(profile: MapPresentationProfile, presentationClass?: MapPresentationClass): MapPresentationStyle | undefined;
|
||||
export function mapRuntimeDisplayLabel(fact: MapRuntimeFact, profile?: MapPresentationProfile): string;
|
||||
export function mapRuntimeFactIsRenderable(fact: MapRuntimeFact, profile: MapPresentationProfile): boolean;
|
||||
export function mapRuntimeFactIsVisible(fact: MapRuntimeFact, profile: MapPresentationProfile, filters: MapPresentationFilters, bindingId: string): boolean;
|
||||
export function mapFactMatchesFilters(fact: MapRuntimeFact, profile: MapPresentationProfile, filters: MapPresentationFilters, bindingId: string): boolean;
|
||||
export function compareMapRuntimeFacts(left: MapRuntimeFact, right: MapRuntimeFact, profile: MapPresentationProfile): number;
|
||||
export function mapPresentationFacetCounts(facts: MapRuntimeFact[], profile: MapPresentationProfile): Record<string, Record<string, number>>;
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Runtime-only implementation of the provider-neutral presentation model.
|
||||
* Types live beside it in mapPresentationProfile.d.mts so Node tests can
|
||||
* execute the same code that the browser uses without a TypeScript loader.
|
||||
*/
|
||||
|
||||
export function normalizeClientMapPresentationProfiles(profiles) {
|
||||
return profiles.flatMap((profile) => {
|
||||
const legacyPin = profile.pin;
|
||||
const target = profile.target ?? legacyPin;
|
||||
if (!target) return [];
|
||||
const normalized = { ...profile, target };
|
||||
delete normalized.pin;
|
||||
return [normalized];
|
||||
});
|
||||
}
|
||||
|
||||
export function mapPresentationBindingIsAll(bindingId, filters) {
|
||||
const state = filters[bindingId];
|
||||
return state?.visible !== false && Object.keys(state?.facets ?? {}).length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A missing facet is compact canonical “all”. An explicit array is the exact
|
||||
* enabled subset; an empty array therefore remains intentional “none”.
|
||||
*/
|
||||
export function mapPresentationFacetValueIsEnabled(facets, field, value) {
|
||||
const selected = facets[field];
|
||||
return selected === undefined || selected.includes(value);
|
||||
}
|
||||
|
||||
export function normalizeMapPresentationFacetSelections(facets, profile) {
|
||||
return Object.fromEntries(profile.facets.flatMap((facet) => {
|
||||
const selected = facets[facet.field];
|
||||
if (selected === undefined) return [];
|
||||
const availableValues = [...new Set(facet.values.map((item) => item.value))];
|
||||
const enabledValues = availableValues.filter((value) => selected.includes(value));
|
||||
// Legacy layouts could persist every value explicitly. Canonicalize that
|
||||
// to unconstrained so a scoped facet cannot suppress unrelated subjects.
|
||||
return availableValues.length > 0 && enabledValues.length === availableValues.length
|
||||
? []
|
||||
: [[facet.field, enabledValues]];
|
||||
}));
|
||||
}
|
||||
|
||||
export function toggleMapPresentationFacetSelection(facets, field, value, availableValues) {
|
||||
const values = [...new Set(availableValues)];
|
||||
if (!values.includes(value)) return facets;
|
||||
const selected = facets[field];
|
||||
const enabled = new Set(selected === undefined
|
||||
? values
|
||||
: values.filter((item) => selected.includes(item)));
|
||||
if (enabled.has(value)) enabled.delete(value);
|
||||
else enabled.add(value);
|
||||
const nextEnabled = values.filter((item) => enabled.has(item));
|
||||
const next = { ...facets };
|
||||
if (nextEnabled.length === values.length) delete next[field];
|
||||
else next[field] = nextEnabled;
|
||||
return next;
|
||||
}
|
||||
|
||||
export function mapPresentationProfileForFact(profiles, presentationProfileId, semanticType) {
|
||||
const exact = presentationProfileId
|
||||
? profiles.find((profile) => profile.id === presentationProfileId)
|
||||
: undefined;
|
||||
if (exact?.semanticTypes.includes(semanticType)) return exact;
|
||||
return profiles.find((profile) => profile.semanticTypes.includes(semanticType));
|
||||
}
|
||||
|
||||
export function resolveMapPresentationClass(fact, profile) {
|
||||
const classes = [...profile.classes].sort((left, right) => right.priority - left.priority || left.id.localeCompare(right.id));
|
||||
return classes.find((item) => item.match.every((condition) => (
|
||||
normalizedFacetValue(fact.attributes[condition.field]) === condition.equals
|
||||
))) ?? classes.find((item) => item.id === profile.defaultClassId) ?? classes.at(-1);
|
||||
}
|
||||
|
||||
export function resolveMapPresentationStyle(profile, presentationClass) {
|
||||
const selected = presentationClass ?? profile.classes.find((item) => item.id === profile.defaultClassId);
|
||||
return profile.styles.find((style) => style.id === selected?.styleId) ?? profile.styles[0];
|
||||
}
|
||||
|
||||
export function mapRuntimeDisplayLabel(fact, profile) {
|
||||
if (profile?.label.mode === "subject_id") return fact.sourceId;
|
||||
const fields = profile?.label.fields ?? ["display_name", "label", "name", "title"];
|
||||
for (const key of fields) {
|
||||
const value = fact.attributes[key];
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const normalized = value.trim();
|
||||
const limit = profile?.label.maxLength ?? 80;
|
||||
return normalized.length > limit ? `${normalized.slice(0, Math.max(1, limit - 1))}…` : normalized;
|
||||
}
|
||||
}
|
||||
return fact.sourceId;
|
||||
}
|
||||
|
||||
export function mapRuntimeFactIsRenderable(fact, profile) {
|
||||
return Boolean(fact.geometry) && resolveMapPresentationClass(fact, profile)?.renderable === true;
|
||||
}
|
||||
|
||||
export function mapRuntimeFactIsVisible(fact, profile, filters, bindingId) {
|
||||
return mapRuntimeFactIsRenderable(fact, profile) && mapFactMatchesFilters(fact, profile, filters, bindingId);
|
||||
}
|
||||
|
||||
export function mapFactMatchesFilters(fact, profile, filters, bindingId) {
|
||||
const state = filters[bindingId];
|
||||
if (state?.visible === false) return false;
|
||||
|
||||
const selectedFacets = profile.facets.flatMap((facet) => {
|
||||
const selected = state?.facets?.[facet.field];
|
||||
return selected === undefined ? [] : [{ facet, selected }];
|
||||
});
|
||||
|
||||
if (selectedFacets.some(({ selected }) => selected.length === 0)) return false;
|
||||
if (selectedFacets.length === 0) return true;
|
||||
|
||||
return selectedFacets.every(({ facet, selected }) => (
|
||||
mapFactParticipatesInFacet(fact, profile, facet)
|
||||
&& selected.includes(normalizedFacetValue(fact.attributes[facet.field]))
|
||||
));
|
||||
}
|
||||
|
||||
export function compareMapRuntimeFacts(left, right, profile) {
|
||||
for (const rule of profile.sort) {
|
||||
const leftRank = sortRank(rule.order, normalizedFacetValue(left.attributes[rule.field]));
|
||||
const rightRank = sortRank(rule.order, normalizedFacetValue(right.attributes[rule.field]));
|
||||
if (leftRank !== rightRank) return leftRank - rightRank;
|
||||
}
|
||||
return mapRuntimeDisplayLabel(left, profile).localeCompare(mapRuntimeDisplayLabel(right, profile), "ru");
|
||||
}
|
||||
|
||||
export function mapPresentationFacetCounts(facts, profile) {
|
||||
return Object.fromEntries(profile.facets.map((facet) => {
|
||||
const counts = Object.fromEntries(facet.values.map((item) => [item.value, 0]));
|
||||
for (const fact of facts) {
|
||||
if (!mapFactParticipatesInFacet(fact, profile, facet)) continue;
|
||||
const value = normalizedFacetValue(fact.attributes[facet.field]);
|
||||
if (Object.hasOwn(counts, value)) counts[value] += 1;
|
||||
}
|
||||
return [facet.field, counts];
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Movement remains an independent fact, but an inactive subject must not
|
||||
* present a stale last speed as current movement.
|
||||
*/
|
||||
function mapFactParticipatesInFacet(fact, profile, facet) {
|
||||
if (facet.field !== "movement_state") return true;
|
||||
if (!profile.facets.some((item) => item.field === "signal_state")) return true;
|
||||
return normalizedFacetValue(fact.attributes.signal_state) === "active";
|
||||
}
|
||||
|
||||
function normalizedFacetValue(value) {
|
||||
return typeof value === "string" ? value.trim().toLowerCase() : "unknown";
|
||||
}
|
||||
|
||||
function sortRank(order, value) {
|
||||
const index = order.indexOf(value);
|
||||
return index === -1 ? order.length : index;
|
||||
}
|
||||
@@ -1,287 +1,3 @@
|
||||
import type { MapRuntimeFact } from "./useMapDataProductRuntime.js";
|
||||
|
||||
export type MapPresentationFacetValue = {
|
||||
value: string;
|
||||
label: string;
|
||||
order: number;
|
||||
};
|
||||
|
||||
export type MapPresentationFacet = {
|
||||
id: string;
|
||||
field: string;
|
||||
label: string;
|
||||
filterable: boolean;
|
||||
counter: boolean;
|
||||
values: MapPresentationFacetValue[];
|
||||
};
|
||||
|
||||
export type MapPresentationStyle = {
|
||||
id: string;
|
||||
color: string;
|
||||
opacity: number;
|
||||
};
|
||||
|
||||
export type MapPresentationClass = {
|
||||
id: string;
|
||||
label: string;
|
||||
priority: number;
|
||||
match: Array<{ field: string; equals: string }>;
|
||||
styleId: string;
|
||||
renderable: boolean;
|
||||
};
|
||||
|
||||
export type MapPresentationProfile = {
|
||||
id: string;
|
||||
version: string;
|
||||
title: string;
|
||||
semanticTypes: string[];
|
||||
label: {
|
||||
mode: "subject_id" | "attributes" | "none";
|
||||
fields: string[];
|
||||
fontWeight: number;
|
||||
sizePx: number;
|
||||
color: string;
|
||||
outlineColor: string;
|
||||
outlineWidthPx: number;
|
||||
backgroundColor: string;
|
||||
backgroundOpacity: number;
|
||||
paddingX: number;
|
||||
paddingY: number;
|
||||
maxLength: number;
|
||||
offsetX: number;
|
||||
offsetY: number;
|
||||
hideCameraHeightMeters: number;
|
||||
};
|
||||
target: ({
|
||||
variant: "elevated-spike";
|
||||
stemHeightMeters: number;
|
||||
headSizePx: number;
|
||||
stemWidthPx: number;
|
||||
} | {
|
||||
variant: "surface-fill";
|
||||
}) & {
|
||||
outlineColor: string;
|
||||
outlineOpacity: number;
|
||||
outlineWidthPx: number;
|
||||
hideCameraHeightMeters: number;
|
||||
};
|
||||
facets: MapPresentationFacet[];
|
||||
styles: MapPresentationStyle[];
|
||||
classes: MapPresentationClass[];
|
||||
defaultClassId: string;
|
||||
sort: Array<{ field: string; order: string[] }>;
|
||||
};
|
||||
|
||||
export type MapSubjectFilterState = {
|
||||
/** False is an explicit empty map state. It must never be normalized to all. */
|
||||
visible: boolean;
|
||||
/** Missing facet = no constraint; an explicitly empty facet = match nothing. */
|
||||
facets: Record<string, string[]>;
|
||||
};
|
||||
|
||||
/** Application view state is keyed by stable binding id, never by editable labels. */
|
||||
export type MapPresentationFilters = Record<string, MapSubjectFilterState>;
|
||||
|
||||
/**
|
||||
* Application manifests persisted before profile v1.1 used the internal key
|
||||
* `pin`. Normalize that storage shape before the first React render so an old
|
||||
* application cannot crash while it is being upgraded to the public `target`
|
||||
* contract through MCP.
|
||||
*/
|
||||
export function normalizeClientMapPresentationProfiles(profiles: MapPresentationProfile[]) {
|
||||
return profiles.flatMap((profile) => {
|
||||
const legacyPin = (profile as MapPresentationProfile & { pin?: MapPresentationProfile["target"] }).pin;
|
||||
const target = profile.target ?? legacyPin;
|
||||
if (!target) return [];
|
||||
const normalized = { ...profile, target } as MapPresentationProfile & { pin?: MapPresentationProfile["target"] };
|
||||
delete normalized.pin;
|
||||
return [normalized];
|
||||
});
|
||||
}
|
||||
|
||||
export function mapPresentationBindingIsAll(bindingId: string, filters: MapPresentationFilters) {
|
||||
const state = filters[bindingId];
|
||||
return state?.visible !== false && Object.keys(state?.facets ?? {}).length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A missing facet is the compact canonical representation of every configured
|
||||
* value being enabled. An explicit array is the exact enabled subset; an empty
|
||||
* array therefore remains an intentional match-nothing state.
|
||||
*/
|
||||
export function mapPresentationFacetValueIsEnabled(
|
||||
facets: Record<string, string[]>,
|
||||
field: string,
|
||||
value: string,
|
||||
) {
|
||||
const selected = facets[field];
|
||||
return selected === undefined || selected.includes(value);
|
||||
}
|
||||
|
||||
export function normalizeMapPresentationFacetSelections(
|
||||
facets: Record<string, string[]>,
|
||||
profile: MapPresentationProfile,
|
||||
) {
|
||||
return Object.fromEntries(profile.facets.flatMap((facet) => {
|
||||
const selected = facets[facet.field];
|
||||
if (selected === undefined) return [];
|
||||
const availableValues = [...new Set(facet.values.map((item) => item.value))];
|
||||
const enabledValues = availableValues.filter((value) => selected.includes(value));
|
||||
// Legacy layouts could persist every value explicitly. Canonicalize that
|
||||
// shape to an unconstrained facet so scoped facets (for example movement
|
||||
// on online subjects) cannot accidentally suppress unrelated subjects.
|
||||
return availableValues.length > 0 && enabledValues.length === availableValues.length
|
||||
? []
|
||||
: [[facet.field, enabledValues] as const];
|
||||
}));
|
||||
}
|
||||
|
||||
export function toggleMapPresentationFacetSelection(
|
||||
facets: Record<string, string[]>,
|
||||
field: string,
|
||||
value: string,
|
||||
availableValues: string[],
|
||||
) {
|
||||
const values = [...new Set(availableValues)];
|
||||
if (!values.includes(value)) return facets;
|
||||
const selected = facets[field];
|
||||
const enabled = new Set(selected === undefined
|
||||
? values
|
||||
: values.filter((item) => selected.includes(item)));
|
||||
if (enabled.has(value)) enabled.delete(value);
|
||||
else enabled.add(value);
|
||||
const nextEnabled = values.filter((item) => enabled.has(item));
|
||||
const next = { ...facets };
|
||||
if (nextEnabled.length === values.length) delete next[field];
|
||||
else next[field] = nextEnabled;
|
||||
return next;
|
||||
}
|
||||
|
||||
export function mapPresentationProfileForFact(
|
||||
profiles: MapPresentationProfile[],
|
||||
presentationProfileId: string | undefined,
|
||||
semanticType: string,
|
||||
) {
|
||||
const exact = presentationProfileId
|
||||
? profiles.find((profile) => profile.id === presentationProfileId)
|
||||
: undefined;
|
||||
if (exact?.semanticTypes.includes(semanticType)) return exact;
|
||||
return profiles.find((profile) => profile.semanticTypes.includes(semanticType));
|
||||
}
|
||||
|
||||
export function resolveMapPresentationClass(fact: MapRuntimeFact, profile: MapPresentationProfile) {
|
||||
const classes = [...profile.classes].sort((left, right) => right.priority - left.priority || left.id.localeCompare(right.id));
|
||||
return classes.find((item) => item.match.every((condition) => (
|
||||
normalizedFacetValue(fact.attributes[condition.field]) === condition.equals
|
||||
))) ?? classes.find((item) => item.id === profile.defaultClassId) ?? classes.at(-1);
|
||||
}
|
||||
|
||||
export function resolveMapPresentationStyle(profile: MapPresentationProfile, presentationClass?: MapPresentationClass) {
|
||||
const selected = presentationClass ?? profile.classes.find((item) => item.id === profile.defaultClassId);
|
||||
return profile.styles.find((style) => style.id === selected?.styleId) ?? profile.styles[0];
|
||||
}
|
||||
|
||||
export function mapRuntimeDisplayLabel(fact: MapRuntimeFact, profile?: MapPresentationProfile) {
|
||||
if (profile?.label.mode === "subject_id") return fact.sourceId;
|
||||
const fields = profile?.label.fields ?? ["display_name", "label", "name", "title"];
|
||||
for (const key of fields) {
|
||||
const value = fact.attributes[key];
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const normalized = value.trim();
|
||||
const limit = profile?.label.maxLength ?? 80;
|
||||
return normalized.length > limit ? `${normalized.slice(0, Math.max(1, limit - 1))}…` : normalized;
|
||||
}
|
||||
}
|
||||
return fact.sourceId;
|
||||
}
|
||||
|
||||
export function mapRuntimeFactIsRenderable(fact: MapRuntimeFact, profile: MapPresentationProfile) {
|
||||
return Boolean(fact.geometry) && resolveMapPresentationClass(fact, profile)?.renderable === true;
|
||||
}
|
||||
|
||||
export function mapRuntimeFactIsVisible(
|
||||
fact: MapRuntimeFact,
|
||||
profile: MapPresentationProfile,
|
||||
filters: MapPresentationFilters,
|
||||
bindingId: string,
|
||||
) {
|
||||
return mapRuntimeFactIsRenderable(fact, profile) && mapFactMatchesFilters(fact, profile, filters, bindingId);
|
||||
}
|
||||
|
||||
export function mapFactMatchesFilters(
|
||||
fact: MapRuntimeFact,
|
||||
profile: MapPresentationProfile,
|
||||
filters: MapPresentationFilters,
|
||||
bindingId: string,
|
||||
) {
|
||||
const state = filters[bindingId];
|
||||
if (state?.visible === false) return false;
|
||||
|
||||
const selectedFacets = profile.facets.flatMap((facet) => {
|
||||
const selected = state?.facets?.[facet.field];
|
||||
if (selected === undefined) return [];
|
||||
return [{ facet, selected }];
|
||||
});
|
||||
|
||||
// Persisted empty arrays and the final interactive deselection are an
|
||||
// explicit match-nothing state.
|
||||
if (selectedFacets.some(({ selected }) => selected.length === 0)) return false;
|
||||
if (selectedFacets.length === 0) return true;
|
||||
|
||||
// Values inside one facet form a union; independently selected facets are
|
||||
// conjunctive. This keeps provider/type/state filters composable.
|
||||
return selectedFacets.every(({ facet, selected }) => (
|
||||
mapFactParticipatesInFacet(fact, profile, facet)
|
||||
&& selected.includes(normalizedFacetValue(fact.attributes[facet.field]))
|
||||
));
|
||||
}
|
||||
|
||||
export function compareMapRuntimeFacts(left: MapRuntimeFact, right: MapRuntimeFact, profile: MapPresentationProfile) {
|
||||
for (const rule of profile.sort) {
|
||||
const leftRank = sortRank(rule.order, normalizedFacetValue(left.attributes[rule.field]));
|
||||
const rightRank = sortRank(rule.order, normalizedFacetValue(right.attributes[rule.field]));
|
||||
if (leftRank !== rightRank) return leftRank - rightRank;
|
||||
}
|
||||
return mapRuntimeDisplayLabel(left, profile).localeCompare(mapRuntimeDisplayLabel(right, profile), "ru");
|
||||
}
|
||||
|
||||
export function mapPresentationFacetCounts(
|
||||
facts: MapRuntimeFact[],
|
||||
profile: MapPresentationProfile,
|
||||
) {
|
||||
return Object.fromEntries(profile.facets.map((facet) => {
|
||||
const counts = Object.fromEntries(facet.values.map((item) => [item.value, 0]));
|
||||
for (const fact of facts) {
|
||||
if (!mapFactParticipatesInFacet(fact, profile, facet)) continue;
|
||||
const value = normalizedFacetValue(fact.attributes[facet.field]);
|
||||
if (Object.hasOwn(counts, value)) counts[value] += 1;
|
||||
}
|
||||
return [facet.field, counts];
|
||||
})) as Record<string, Record<string, number>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* `signal_state` and `movement_state` remain orthogonal Data Product facts.
|
||||
* The operational Map, however, must not present a stale last speed as a
|
||||
* current movement state. When both canonical facets exist, the movement
|
||||
* facet is therefore scoped to currently active subjects. Other profiles and
|
||||
* fields keep their ordinary independent-facet behaviour.
|
||||
*/
|
||||
function mapFactParticipatesInFacet(
|
||||
fact: MapRuntimeFact,
|
||||
profile: MapPresentationProfile,
|
||||
facet: MapPresentationFacet,
|
||||
) {
|
||||
if (facet.field !== "movement_state") return true;
|
||||
if (!profile.facets.some((item) => item.field === "signal_state")) return true;
|
||||
return normalizedFacetValue(fact.attributes.signal_state) === "active";
|
||||
}
|
||||
|
||||
function normalizedFacetValue(value: unknown) {
|
||||
return typeof value === "string" ? value.trim().toLowerCase() : "unknown";
|
||||
}
|
||||
|
||||
function sortRank(order: string[], value: string) {
|
||||
const index = order.indexOf(value);
|
||||
return index === -1 ? order.length : index;
|
||||
}
|
||||
// Stable TypeScript facade for existing `.js` specifiers. Runtime behavior is
|
||||
// executable JavaScript so browser code and Node behavioral tests share it.
|
||||
export * from "./mapPresentationProfile.mjs";
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
export type MapProviderStartupPolicy = Readonly<{
|
||||
providerInitializationTimeoutMs: number;
|
||||
imageryViewportTimeoutMs: number;
|
||||
terrainViewportTimeoutMs: number;
|
||||
minimumRenderFrames: number;
|
||||
}>;
|
||||
|
||||
export type MapProviderStartupReason = "loaded" | "timeout" | "cancelled";
|
||||
export type MapProviderStartupResult = "complete" | "cancelled";
|
||||
export type MapProviderName = "imagery" | "terrain" | "buildings";
|
||||
|
||||
type CesiumEventLike<TListener extends (...args: never[]) => void> = {
|
||||
addEventListener(listener: TListener): () => void;
|
||||
};
|
||||
|
||||
export const MAP_PROVIDER_STARTUP_POLICY: MapProviderStartupPolicy;
|
||||
|
||||
export function waitForGlobeViewportReady(input: {
|
||||
globe: {
|
||||
readonly tilesLoaded: boolean;
|
||||
tileLoadProgressEvent: CesiumEventLike<(pendingRequests: number) => void>;
|
||||
};
|
||||
scene: {
|
||||
postRender: CesiumEventLike<() => void>;
|
||||
requestRender(): void;
|
||||
};
|
||||
signal?: AbortSignal;
|
||||
timeoutMs: number;
|
||||
minimumRenderFrames?: number;
|
||||
}): Promise<MapProviderStartupReason>;
|
||||
|
||||
export function runStagedMapProviders(input: {
|
||||
signal?: AbortSignal;
|
||||
isCancelled?: () => boolean;
|
||||
providerInitializationTimeoutMs?: number;
|
||||
loadImagery: (context: { signal: AbortSignal }) => void | Promise<void>;
|
||||
waitAfterImagery?: () => void | Promise<void>;
|
||||
loadTerrain: (context: { signal: AbortSignal }) => void | Promise<void>;
|
||||
waitAfterTerrain?: () => void | Promise<void>;
|
||||
loadBuildings: (context: { signal: AbortSignal }) => void | Promise<void>;
|
||||
loadDeferred?: () => void | Promise<void>;
|
||||
onProviderError?: (provider: MapProviderName, error: unknown) => void;
|
||||
onDeferredError?: (error: unknown) => void;
|
||||
}): Promise<MapProviderStartupResult>;
|
||||
@@ -0,0 +1,141 @@
|
||||
export const MAP_PROVIDER_STARTUP_POLICY = Object.freeze({
|
||||
providerInitializationTimeoutMs: 8_000,
|
||||
imageryViewportTimeoutMs: 6_000,
|
||||
terrainViewportTimeoutMs: 5_000,
|
||||
minimumRenderFrames: 2,
|
||||
});
|
||||
|
||||
/**
|
||||
* Wait until Cesium has rendered enough frames to discover the current
|
||||
* viewport and the public Globe queue reports that its terrain and imagery
|
||||
* are loaded. The deadline is deliberate: a slow or unavailable provider
|
||||
* must never block the next independent layer.
|
||||
*/
|
||||
export function waitForGlobeViewportReady({
|
||||
globe,
|
||||
scene,
|
||||
signal,
|
||||
timeoutMs,
|
||||
minimumRenderFrames = MAP_PROVIDER_STARTUP_POLICY.minimumRenderFrames,
|
||||
}) {
|
||||
if (signal?.aborted) return Promise.resolve("cancelled");
|
||||
|
||||
const frameTarget = Math.max(1, Math.trunc(minimumRenderFrames));
|
||||
const deadlineMs = Math.max(0, Math.trunc(timeoutMs));
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
let renderFrames = 0;
|
||||
let removeProgressListener;
|
||||
let removePostRenderListener;
|
||||
let timeout;
|
||||
|
||||
const cleanup = () => {
|
||||
removeProgressListener?.();
|
||||
removePostRenderListener?.();
|
||||
if (timeout !== undefined) clearTimeout(timeout);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
};
|
||||
const finish = (reason) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
cleanup();
|
||||
resolve(reason);
|
||||
};
|
||||
const inspect = () => {
|
||||
if (renderFrames >= frameTarget && globe.tilesLoaded) finish("loaded");
|
||||
};
|
||||
const onAbort = () => finish("cancelled");
|
||||
const onTileLoadProgress = () => {
|
||||
inspect();
|
||||
if (!settled) scene.requestRender();
|
||||
};
|
||||
const onPostRender = () => {
|
||||
renderFrames += 1;
|
||||
inspect();
|
||||
if (!settled && renderFrames < frameTarget) scene.requestRender();
|
||||
};
|
||||
|
||||
removeProgressListener = globe.tileLoadProgressEvent.addEventListener(onTileLoadProgress);
|
||||
removePostRenderListener = scene.postRender.addEventListener(onPostRender);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
timeout = setTimeout(() => finish("timeout"), deadlineMs);
|
||||
scene.requestRender();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Preserve independent failure domains while giving the base map first use
|
||||
* of network and decode capacity. Each provider owns its error; viewport
|
||||
* gates are scheduling hints and therefore never become provider failures.
|
||||
*/
|
||||
export async function runStagedMapProviders({
|
||||
signal,
|
||||
isCancelled,
|
||||
providerInitializationTimeoutMs = MAP_PROVIDER_STARTUP_POLICY.providerInitializationTimeoutMs,
|
||||
loadImagery,
|
||||
waitAfterImagery,
|
||||
loadTerrain,
|
||||
waitAfterTerrain,
|
||||
loadBuildings,
|
||||
loadDeferred,
|
||||
onProviderError,
|
||||
onDeferredError,
|
||||
}) {
|
||||
const cancelled = () => Boolean(signal?.aborted || isCancelled?.());
|
||||
const loadProvider = async (provider, load) => {
|
||||
if (cancelled()) return false;
|
||||
const stageAbort = new AbortController();
|
||||
let timeout;
|
||||
let rejectDeadline;
|
||||
const abortStage = () => {
|
||||
rejectDeadline?.(new Error(`${provider}_startup_cancelled`));
|
||||
stageAbort.abort();
|
||||
};
|
||||
signal?.addEventListener("abort", abortStage, { once: true });
|
||||
const deadline = new Promise((_, reject) => {
|
||||
rejectDeadline = reject;
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(`${provider}_startup_timeout`));
|
||||
stageAbort.abort();
|
||||
}, Math.max(0, Math.trunc(providerInitializationTimeoutMs)));
|
||||
});
|
||||
try {
|
||||
await Promise.race([load({ signal: stageAbort.signal }), deadline]);
|
||||
return !cancelled() && !stageAbort.signal.aborted;
|
||||
} catch (error) {
|
||||
if (!cancelled()) onProviderError?.(provider, error);
|
||||
return false;
|
||||
} finally {
|
||||
if (timeout !== undefined) clearTimeout(timeout);
|
||||
signal?.removeEventListener("abort", abortStage);
|
||||
}
|
||||
};
|
||||
const waitForViewport = async (wait) => {
|
||||
if (!wait || cancelled()) return;
|
||||
try {
|
||||
await wait();
|
||||
} catch {
|
||||
// A readiness gate controls ordering only. The provider's own error
|
||||
// event remains the authority for availability and user diagnostics.
|
||||
}
|
||||
};
|
||||
|
||||
const imageryReady = await loadProvider("imagery", loadImagery);
|
||||
if (imageryReady) await waitForViewport(waitAfterImagery);
|
||||
|
||||
const terrainReady = await loadProvider("terrain", loadTerrain);
|
||||
if (terrainReady) await waitForViewport(waitAfterTerrain);
|
||||
|
||||
await loadProvider("buildings", loadBuildings);
|
||||
|
||||
if (loadDeferred && !cancelled()) {
|
||||
try {
|
||||
await loadDeferred();
|
||||
} catch (error) {
|
||||
if (!cancelled()) onDeferredError?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
return cancelled() ? "cancelled" : "complete";
|
||||
}
|
||||
@@ -51,7 +51,7 @@ export const defaultMapReferencePresentationProfiles: readonly MapPresentationPr
|
||||
semanticTypes: [...definition.semanticTypes],
|
||||
label: {
|
||||
mode: "attributes",
|
||||
fields: ["name", "official_name", "local_name"],
|
||||
fields: ["name", "official_name", "local_name", "alternate_names"],
|
||||
fontWeight: 600,
|
||||
sizePx: 20,
|
||||
color: "#cccccc",
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
import type {
|
||||
GraticuleSectorSummary,
|
||||
LocalSectorSummary,
|
||||
} from "./mapSectorGrid.mjs";
|
||||
|
||||
/**
|
||||
* Provider-neutral scene settings consumed by a renderer adapter.
|
||||
*
|
||||
* The persisted Map Page contract may use these fields, but it never stores
|
||||
* Cesium entities, provider endpoints, credentials or raw provider payloads.
|
||||
*/
|
||||
export type MapPresentation = {
|
||||
imagerySource: "cesium-live";
|
||||
imageryVisible: boolean;
|
||||
cacheEnabled: boolean;
|
||||
cacheNoOverwrite: boolean;
|
||||
terrainEnabled: boolean;
|
||||
terrainExaggeration: number;
|
||||
monochrome: boolean;
|
||||
monochromeColor: string;
|
||||
imageryGamma: number;
|
||||
imageryHue: number;
|
||||
imageryAlpha: number;
|
||||
globeColor: string;
|
||||
backgroundColor: string;
|
||||
atmosphereEnabled: boolean;
|
||||
atmosphereHue: number;
|
||||
atmosphereSaturation: number;
|
||||
atmosphereBrightness: number;
|
||||
fogEnabled: boolean;
|
||||
fogDensity: number;
|
||||
sunEnabled: boolean;
|
||||
sunHour: number;
|
||||
sunIntensity: number;
|
||||
shadowsEnabled: boolean;
|
||||
buildingsVisible: boolean;
|
||||
buildingsColor: string;
|
||||
buildingsOpacity: number;
|
||||
buildingsDetail: number;
|
||||
imageryBrightness: number;
|
||||
imageryContrast: number;
|
||||
imagerySaturation: number;
|
||||
gridVisible: boolean;
|
||||
gridLodEnabled: boolean;
|
||||
grid3dEnabled: boolean;
|
||||
gridGraticuleEnabled: boolean;
|
||||
gridCenterMode: "fixed";
|
||||
gridCenterLatitude: number;
|
||||
gridCenterLongitude: number;
|
||||
gridTileSizeKm: number;
|
||||
gridAutoDisableHeightKm: number;
|
||||
gridRebuildOnMoveEnd: boolean;
|
||||
gridLegacyMode: boolean;
|
||||
gridMax3dViewAngleDegrees: number;
|
||||
gridHeightMeters: number;
|
||||
gridLod1MaxHeightKm: number;
|
||||
gridLod1StepKm: number;
|
||||
gridLod1Mode: "3d" | "graticule";
|
||||
gridLod2MaxHeightKm: number;
|
||||
gridLod2StepKm: number;
|
||||
gridLod2Mode: "3d" | "graticule";
|
||||
gridLod3MaxHeightKm: number;
|
||||
gridLod3StepKm: number;
|
||||
gridLod3Mode: "3d" | "graticule";
|
||||
gridLod4MaxHeightKm: number;
|
||||
gridLod4StepKm: number;
|
||||
gridLod4Mode: "3d" | "graticule";
|
||||
gridLod5StepKm: number;
|
||||
gridLod5MaxHeightKm: number;
|
||||
gridLod5Mode: "3d" | "graticule";
|
||||
gridRadiusKm: number;
|
||||
gridLineWidth: number;
|
||||
gridLineDiameterMeters: number;
|
||||
gridColor: string;
|
||||
gridOpacity: number;
|
||||
gridDotsEnabled: boolean;
|
||||
gridDotsSize: number;
|
||||
gridDotsDiameterMeters: number;
|
||||
gridDotsColor: string;
|
||||
gridDotsOpacity: number;
|
||||
gridCrossesEnabled: boolean;
|
||||
gridCrossesLengthMeters: number;
|
||||
gridCrossesWidthMeters: number;
|
||||
gridCrossesColor: string;
|
||||
gridCrossesOpacity: number;
|
||||
gridLodProfiles: GridLodProfile[];
|
||||
/** One-shot renderer command; it is intentionally excluded from persistence. */
|
||||
cacheRefresh: boolean;
|
||||
};
|
||||
|
||||
export type GridLodProfile = {
|
||||
maxHeightKm: number;
|
||||
stepKm: number;
|
||||
mode: "3d" | "graticule";
|
||||
heightMeters: number;
|
||||
max3dViewAngleDegrees: number;
|
||||
tileSizeKm: number;
|
||||
radiusKm: number;
|
||||
lineDiameterMeters: number;
|
||||
lineColor: string;
|
||||
lineOpacity: number;
|
||||
dotsEnabled: boolean;
|
||||
dotsDiameterMeters: number;
|
||||
dotsColor: string;
|
||||
dotsOpacity: number;
|
||||
crossesEnabled: boolean;
|
||||
crossesLengthMeters: number;
|
||||
crossesWidthMeters: number;
|
||||
crossesColor: string;
|
||||
crossesOpacity: number;
|
||||
graticuleStepDegrees: number;
|
||||
graticuleLineWidthPx: number;
|
||||
graticuleColor: string;
|
||||
graticuleOpacity: number;
|
||||
majorLinesEnabled: boolean;
|
||||
majorLabelsEnabled: boolean;
|
||||
majorLineWidthMultiplier: number;
|
||||
volumeEnabled: boolean;
|
||||
volumeMinimumHeightMeters: number;
|
||||
volumeMaximumHeightMeters: number;
|
||||
volumeBandHeightMeters: number;
|
||||
selectionFillColor: string;
|
||||
selectionFillOpacityPercent: number;
|
||||
selectionOutlineColor: string;
|
||||
selectionOutlineWidthPx: number;
|
||||
selectionOutlineOpacityPercent: number;
|
||||
};
|
||||
|
||||
export type GridVolumeSelection = {
|
||||
id: string;
|
||||
index: number;
|
||||
floor: number;
|
||||
ceiling: number;
|
||||
bandHeight: number;
|
||||
};
|
||||
|
||||
export type LocalGridSectorSelection = LocalSectorSummary & {
|
||||
mode: "3d";
|
||||
units: "meters-enu";
|
||||
volume: GridVolumeSelection | null;
|
||||
};
|
||||
|
||||
export type GraticuleGridSectorSelection = GraticuleSectorSummary & {
|
||||
mode: "graticule";
|
||||
units: "degrees-wgs84";
|
||||
volume: null;
|
||||
};
|
||||
|
||||
export type GridSectorSelection = LocalGridSectorSelection | GraticuleGridSectorSelection;
|
||||
export type GridMajorTileSelection = NonNullable<GridSectorSelection["parentMajorTile"]>;
|
||||
|
||||
export type MapCameraView = {
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
height: number;
|
||||
heading: number;
|
||||
pitch: number;
|
||||
roll: number;
|
||||
};
|
||||
|
||||
export type CameraSpiralConfig = {
|
||||
heightAboveGroundMeters: number;
|
||||
speedMetersPerSecond: number;
|
||||
pitchMetersPerTurn: number;
|
||||
targetRadiusMeters?: number;
|
||||
viewPitchRadians?: number;
|
||||
waitForTiles?: boolean;
|
||||
};
|
||||
|
||||
export type CameraSpiralState = {
|
||||
running: boolean;
|
||||
reason?: "stopped" | "mode_disabled" | "renderer_restarted" | "page_hidden" | "render_error" | "spiral_extent_limit" | "spiral_runtime_error" | "terrain_sampling_error" | "tile_loading_timeout" | "tile_loading_error" | "target_radius_reached";
|
||||
};
|
||||
|
||||
export type MapGatewayHealth = {
|
||||
cache?: {
|
||||
mode?: string;
|
||||
writePolicy?: string;
|
||||
entries?: number;
|
||||
bytes?: number;
|
||||
maxBytes?: number;
|
||||
atCapacity?: boolean;
|
||||
persistent?: boolean;
|
||||
byResourceKind?: Record<string, { entries?: number; bytes?: number }>;
|
||||
};
|
||||
diagnostics?: {
|
||||
cacheHits?: number;
|
||||
cacheMisses?: number;
|
||||
cacheRefreshes?: number;
|
||||
upstreamRequests?: number;
|
||||
egressRequests?: number;
|
||||
upstreamFailures?: number;
|
||||
slowUpstreamRequests?: number;
|
||||
lastFailure?: string | null;
|
||||
lastFailureAt?: string | null;
|
||||
};
|
||||
referenceSources?: {
|
||||
transportStations?: {
|
||||
profileId?: string;
|
||||
seedFactCount?: number;
|
||||
fetchEnabled?: boolean;
|
||||
cellDegrees?: number;
|
||||
cachedCellCount?: number;
|
||||
indexedFactCount?: number;
|
||||
upstreamRequests?: number;
|
||||
upstreamFailures?: number;
|
||||
searchRequests?: number;
|
||||
searchFailures?: number;
|
||||
upstreamState?: "idle" | "ready" | "degraded";
|
||||
activeFetches?: number;
|
||||
queuedFetches?: number;
|
||||
lastRefreshAt?: string | null;
|
||||
lastFailure?: string | null;
|
||||
lastFailureAt?: string | null;
|
||||
};
|
||||
};
|
||||
providerCache?: Array<{
|
||||
assetId?: number;
|
||||
type?: string;
|
||||
cachedEndpoint?: boolean;
|
||||
credentialUsable?: boolean;
|
||||
entryPointCached?: boolean;
|
||||
}>;
|
||||
ionConfigured?: boolean;
|
||||
};
|
||||
|
||||
export type MapProviderState = "loading" | "ready" | "error" | "not-configured";
|
||||
|
||||
export type MapProviderStatus = {
|
||||
imagery: MapProviderState;
|
||||
terrain: MapProviderState;
|
||||
buildings: MapProviderState;
|
||||
errors: Partial<Record<"imagery" | "terrain" | "buildings" | "projection", string>>;
|
||||
};
|
||||
|
||||
/** Imperative adapter surface; callers never receive a Cesium object. */
|
||||
export type MapRendererHandle = {
|
||||
startSpiralAnimation: (config: CameraSpiralConfig) => boolean;
|
||||
stopSpiralAnimation: (reason?: CameraSpiralState["reason"]) => void;
|
||||
getCameraView: () => MapCameraView | null;
|
||||
fitRuntimeEntities: (entityIds?: string[]) => boolean;
|
||||
focusRuntimeEntity: (entityId: string) => boolean;
|
||||
focusSubjectCoordinates: (longitude: number, latitude: number) => boolean;
|
||||
focusCoordinates: (longitude: number, latitude: number) => boolean;
|
||||
focusGridSector: (sector: GridSectorSelection) => boolean;
|
||||
focusGridMajorTile: (tile: GridMajorTileSelection) => boolean;
|
||||
};
|
||||
|
||||
/** @deprecated Use the provider-neutral MapRendererHandle name. */
|
||||
export type CesiumMapRendererHandle = MapRendererHandle;
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { MapRuntimeFact } from "./useMapDataProductRuntime.js";
|
||||
|
||||
export function mapRuntimeFactKey(fact: Pick<MapRuntimeFact, "sourceId" | "semanticType">): string;
|
||||
export function mapRuntimeEntityId(bindingId: string, fact: Pick<MapRuntimeFact, "sourceId" | "semanticType">): string;
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Stable Data Product fact identity: semantic type plus source id. */
|
||||
export function mapRuntimeFactKey(fact) {
|
||||
return `${fact.semanticType}\u0000${fact.sourceId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable renderer adapter identity. It never depends on a provider message id,
|
||||
* display label, current geometry or transient Cesium entity instance.
|
||||
*/
|
||||
export function mapRuntimeEntityId(bindingId, fact) {
|
||||
return `nodedc-runtime:${bindingId}:${fact.semanticType}:${fact.sourceId}`;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { MapDataProductBinding } from "./MapFixturePreview.js";
|
||||
import type { MapDataProductBinding } from "./mapPageContract.js";
|
||||
import type { MapPresentationProfile } from "./mapPresentationProfile.js";
|
||||
import type { MapRuntimeBinding } from "./useMapDataProductRuntime.js";
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { GridSectorSelection } from "./mapRendererContract.js";
|
||||
import type { SectorGridLodProfile } from "./mapSectorWorkspace.js";
|
||||
import type { MapRuntimeFact } from "./useMapDataProductRuntime.js";
|
||||
|
||||
export const MAP_SCOPE_PROVIDER_FIELD: "position_source";
|
||||
export const MAP_SCOPE_OBJECT_KIND_FIELD: "object_kind";
|
||||
export const MAP_SCOPE_MISSING_VALUE: "__nodedc_missing__";
|
||||
|
||||
export function normalizedSectorScopeValue(value: unknown): string | null;
|
||||
export function sectorScopeValueLabel(value: string): string;
|
||||
export function mapFactSectorScopeValue(fact: MapRuntimeFact, field: string): string;
|
||||
export function mapFactPointCoordinates(fact: MapRuntimeFact | undefined): [number, number] | null;
|
||||
export function mapFactInsideGridSector(
|
||||
fact: MapRuntimeFact,
|
||||
selection: GridSectorSelection,
|
||||
profiles: SectorGridLodProfile[],
|
||||
origin: { latitude: number; longitude: number },
|
||||
): boolean;
|
||||
@@ -0,0 +1,49 @@
|
||||
import { graticuleSectorAt, localSectorAtGeodetic } from "./mapSectorGrid.mjs";
|
||||
|
||||
export const MAP_SCOPE_PROVIDER_FIELD = "position_source";
|
||||
export const MAP_SCOPE_OBJECT_KIND_FIELD = "object_kind";
|
||||
export const MAP_SCOPE_MISSING_VALUE = "__nodedc_missing__";
|
||||
|
||||
export function normalizedSectorScopeValue(value) {
|
||||
if (typeof value !== "string") return null;
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 120 || /[\u0000-\u001f\u007f]/.test(normalized)) return null;
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function sectorScopeValueLabel(value) {
|
||||
if (value === MAP_SCOPE_MISSING_VALUE) return "Не указано";
|
||||
return value.replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
export function mapFactSectorScopeValue(fact, field) {
|
||||
return normalizedSectorScopeValue(fact.attributes[field]) ?? MAP_SCOPE_MISSING_VALUE;
|
||||
}
|
||||
|
||||
export function mapFactPointCoordinates(fact) {
|
||||
if (fact?.geometry?.type !== "Point") return null;
|
||||
const [longitude, latitude] = fact.geometry.coordinates;
|
||||
return Number.isFinite(longitude) && longitude >= -180 && longitude <= 180
|
||||
&& Number.isFinite(latitude) && latitude >= -90 && latitude <= 90
|
||||
? [longitude, latitude]
|
||||
: null;
|
||||
}
|
||||
|
||||
export function mapFactInsideGridSector(fact, selection, profiles, origin) {
|
||||
if (fact.geometry?.type !== "Point") return false;
|
||||
const [longitude, latitude] = fact.geometry.coordinates;
|
||||
const profile = profiles[selection.lod - 1];
|
||||
if (!profile || profile.mode !== selection.mode) return false;
|
||||
if (selection.mode === "graticule") {
|
||||
return graticuleSectorAt({ longitude, latitude }, {
|
||||
lod: selection.lod,
|
||||
stepDegrees: profile.graticuleStepDegrees,
|
||||
}).id === selection.id;
|
||||
}
|
||||
return localSectorAtGeodetic({ longitude, latitude }, {
|
||||
lod: selection.lod,
|
||||
originLatitude: origin.latitude,
|
||||
originLongitude: origin.longitude,
|
||||
stepMeters: profile.stepKm * 1_000,
|
||||
}).id === selection.id;
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import { gridLodProfile } from "./mapGridPolicy.mjs";
|
||||
import {
|
||||
graticuleSectorAt,
|
||||
graticuleSectorSummary,
|
||||
localSectorAt,
|
||||
localSectorSummary,
|
||||
localVolumeAt,
|
||||
type GraticuleSectorAddress,
|
||||
type LocalSectorAddress,
|
||||
} from "./mapSectorGrid.mjs";
|
||||
import { initialMapSettings, type MapPageSettings } from "./mapPageContract.js";
|
||||
import type {
|
||||
GridLodProfile,
|
||||
GridSectorSelection,
|
||||
MapPresentation,
|
||||
} from "./mapRendererContract.js";
|
||||
export {
|
||||
MAP_SCOPE_MISSING_VALUE,
|
||||
MAP_SCOPE_OBJECT_KIND_FIELD,
|
||||
MAP_SCOPE_PROVIDER_FIELD,
|
||||
mapFactInsideGridSector,
|
||||
mapFactPointCoordinates,
|
||||
mapFactSectorScopeValue,
|
||||
normalizedSectorScopeValue,
|
||||
sectorScopeValueLabel,
|
||||
} from "./mapSectorRuntime.mjs";
|
||||
|
||||
export type SectorGridLodProfile = GridLodProfile & {
|
||||
majorLinesEnabled: boolean;
|
||||
majorLabelsEnabled: boolean;
|
||||
majorLineWidthMultiplier: number;
|
||||
selectionFillColor: string;
|
||||
selectionFillOpacityPercent: number;
|
||||
selectionOutlineColor: string;
|
||||
selectionOutlineWidthPx: number;
|
||||
selectionOutlineOpacityPercent: number;
|
||||
volumeEnabled: boolean;
|
||||
volumeMinimumHeightMeters: number;
|
||||
volumeMaximumHeightMeters: number;
|
||||
volumeBandHeightMeters: number;
|
||||
};
|
||||
|
||||
export type GridSectorDirection = "north" | "east" | "south" | "west";
|
||||
|
||||
export const GRID_SECTOR_DIRECTIONS: Array<{ id: GridSectorDirection; label: string }> = [
|
||||
{ id: "north", label: "Север" },
|
||||
{ id: "east", label: "Восток" },
|
||||
{ id: "south", label: "Юг" },
|
||||
{ id: "west", label: "Запад" },
|
||||
];
|
||||
|
||||
export function normalizedMajorTileSizeKm(stepKm: number, requestedTileSizeKm: number) {
|
||||
const safeStepKm = Math.min(50, Math.max(0.1, stepKm));
|
||||
const maximumRatio = Math.max(1, Math.floor((50 + Number.EPSILON) / safeStepKm));
|
||||
const requestedRatio = Math.max(1, Math.ceil((requestedTileSizeKm - Number.EPSILON) / safeStepKm));
|
||||
const ratio = Math.min(maximumRatio, requestedRatio);
|
||||
return Number((safeStepKm * ratio).toFixed(6));
|
||||
}
|
||||
|
||||
export function normalizedGraticuleStepDegrees(requestedStepDegrees: number) {
|
||||
const safeStepDegrees = Math.min(10, Math.max(0.1, requestedStepDegrees));
|
||||
const requestedDivisions = Math.max(1, Math.round(180 / safeStepDegrees));
|
||||
// Five minor intervals form one major tile and every 90° quadrant must end
|
||||
// on a major boundary. A hemisphere therefore uses a multiple of ten.
|
||||
const hemisphereDivisions = Math.max(10, Math.round(requestedDivisions / 10) * 10);
|
||||
return 180 / hemisphereDivisions;
|
||||
}
|
||||
|
||||
export function graticuleMajorStepDegrees(stepDegrees: number) {
|
||||
const candidate = stepDegrees * 5;
|
||||
const quadrantBands = 90 / candidate;
|
||||
return Math.abs(quadrantBands - Math.round(quadrantBands)) <= 1e-9 * Math.max(1, Math.abs(quadrantBands))
|
||||
? candidate
|
||||
: null;
|
||||
}
|
||||
|
||||
export function normalizeSectorGridLodProfile(profile: SectorGridLodProfile): SectorGridLodProfile {
|
||||
const stepKm = profile.mode === "3d" ? Math.min(50, profile.stepKm) : profile.stepKm;
|
||||
const volumeMinimumHeightMeters = profile.volumeMinimumHeightMeters;
|
||||
const volumeMaximumHeightMeters = Math.max(volumeMinimumHeightMeters + 1, profile.volumeMaximumHeightMeters);
|
||||
return {
|
||||
...profile,
|
||||
stepKm,
|
||||
tileSizeKm: profile.mode === "3d"
|
||||
? normalizedMajorTileSizeKm(stepKm, Math.max(stepKm, profile.tileSizeKm))
|
||||
: profile.tileSizeKm,
|
||||
graticuleStepDegrees: profile.mode === "graticule"
|
||||
? normalizedGraticuleStepDegrees(profile.graticuleStepDegrees)
|
||||
: profile.graticuleStepDegrees,
|
||||
majorLabelsEnabled: profile.majorLinesEnabled && profile.majorLabelsEnabled,
|
||||
volumeEnabled: profile.mode === "3d" && profile.volumeEnabled,
|
||||
volumeMinimumHeightMeters,
|
||||
volumeMaximumHeightMeters,
|
||||
volumeBandHeightMeters: Math.min(
|
||||
volumeMaximumHeightMeters - volumeMinimumHeightMeters,
|
||||
Math.max(1, profile.volumeBandHeightMeters),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveGridLodProfiles(settings?: Partial<MapPageSettings>): GridLodProfile[] {
|
||||
// Layouts saved by the previous flat contract retain their tuned values.
|
||||
// The next ordinary page save persists the canonical five-profile array.
|
||||
const legacySettings: MapPresentation = {
|
||||
...initialMapSettings,
|
||||
...settings,
|
||||
gridLodProfiles: Array.isArray(settings?.gridLodProfiles) ? settings.gridLodProfiles : [],
|
||||
cacheRefresh: false,
|
||||
};
|
||||
return Array.from({ length: 5 }, (_unused, index) => normalizeSectorGridLodProfile(
|
||||
gridLodProfile(legacySettings, index) as SectorGridLodProfile,
|
||||
));
|
||||
}
|
||||
|
||||
export function localGridSectorSelection(
|
||||
address: LocalSectorAddress,
|
||||
profile: SectorGridLodProfile,
|
||||
origin: { latitude: number; longitude: number },
|
||||
preferredAltitudeMeters?: number,
|
||||
): GridSectorSelection {
|
||||
const definition = {
|
||||
lod: address.lod,
|
||||
originLatitude: origin.latitude,
|
||||
originLongitude: origin.longitude,
|
||||
stepMeters: profile.stepKm * 1_000,
|
||||
tileSizeMeters: profile.tileSizeKm * 1_000,
|
||||
};
|
||||
const summary = localSectorSummary(address, definition);
|
||||
const volumeSpan = profile.volumeMaximumHeightMeters - profile.volumeMinimumHeightMeters;
|
||||
const volume = profile.volumeEnabled && volumeSpan > 0
|
||||
? (() => {
|
||||
const altitudeMeters = Math.min(
|
||||
profile.volumeMaximumHeightMeters - Number.EPSILON,
|
||||
Math.max(
|
||||
profile.volumeMinimumHeightMeters,
|
||||
preferredAltitudeMeters ?? profile.volumeMinimumHeightMeters + Math.min(profile.volumeBandHeightMeters, volumeSpan) / 2,
|
||||
),
|
||||
);
|
||||
const volumeAddress = localVolumeAt({ ...summary.center, altitudeMeters }, {
|
||||
lod: address.lod,
|
||||
originLatitude: origin.latitude,
|
||||
originLongitude: origin.longitude,
|
||||
stepMeters: profile.stepKm * 1_000,
|
||||
altitudeFloorMeters: profile.volumeMinimumHeightMeters,
|
||||
altitudeCeilingMeters: profile.volumeMaximumHeightMeters,
|
||||
altitudeBandMeters: profile.volumeBandHeightMeters,
|
||||
});
|
||||
if (!volumeAddress) return null;
|
||||
return {
|
||||
id: volumeAddress.id,
|
||||
index: volumeAddress.bandIndex,
|
||||
floor: Math.max(profile.volumeMinimumHeightMeters, volumeAddress.altitudeFloorMeters),
|
||||
ceiling: Math.min(profile.volumeMaximumHeightMeters, volumeAddress.altitudeCeilingMeters),
|
||||
bandHeight: volumeAddress.altitudeBandMeters,
|
||||
};
|
||||
})()
|
||||
: null;
|
||||
return {
|
||||
...summary,
|
||||
mode: "3d",
|
||||
address,
|
||||
units: "meters-enu",
|
||||
volume,
|
||||
};
|
||||
}
|
||||
|
||||
export function graticuleGridSectorSelection(
|
||||
address: GraticuleSectorAddress,
|
||||
profile: SectorGridLodProfile,
|
||||
): GridSectorSelection {
|
||||
const majorStepDegrees = profile.majorLinesEnabled
|
||||
? graticuleMajorStepDegrees(profile.graticuleStepDegrees) ?? undefined
|
||||
: undefined;
|
||||
return {
|
||||
...graticuleSectorSummary(address, {
|
||||
lod: address.lod,
|
||||
stepDegrees: profile.graticuleStepDegrees,
|
||||
majorStepDegrees,
|
||||
}),
|
||||
mode: "graticule",
|
||||
address,
|
||||
units: "degrees-wgs84",
|
||||
volume: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function gridSectorNeighborSelection(
|
||||
selection: GridSectorSelection,
|
||||
direction: GridSectorDirection,
|
||||
profiles: SectorGridLodProfile[],
|
||||
origin: { latitude: number; longitude: number },
|
||||
) {
|
||||
const profile = profiles[selection.lod - 1];
|
||||
if (!profile) return null;
|
||||
if (selection.mode === "3d") {
|
||||
const neighbor = selection.neighbors[direction];
|
||||
const preferredAltitudeMeters = selection.volume
|
||||
? (selection.volume.floor + selection.volume.ceiling) / 2
|
||||
: undefined;
|
||||
return neighbor ? localGridSectorSelection(neighbor.address, profile, origin, preferredAltitudeMeters) : null;
|
||||
}
|
||||
const neighbor = selection.neighbors[direction];
|
||||
return neighbor ? graticuleGridSectorSelection(neighbor.address, profile) : null;
|
||||
}
|
||||
|
||||
export function gridSectorParentLodSelection(
|
||||
selection: GridSectorSelection,
|
||||
profiles: SectorGridLodProfile[],
|
||||
origin: { latitude: number; longitude: number },
|
||||
) {
|
||||
const parentProfile = profiles[selection.lod];
|
||||
if (!parentProfile || parentProfile.mode !== selection.mode) return null;
|
||||
if (selection.mode === "3d") {
|
||||
const address = localSectorAt(selection.center, {
|
||||
lod: selection.lod + 1,
|
||||
originLatitude: origin.latitude,
|
||||
originLongitude: origin.longitude,
|
||||
stepMeters: parentProfile.stepKm * 1_000,
|
||||
});
|
||||
const preferredAltitudeMeters = selection.volume
|
||||
? (selection.volume.floor + selection.volume.ceiling) / 2
|
||||
: undefined;
|
||||
return localGridSectorSelection(address, parentProfile, origin, preferredAltitudeMeters);
|
||||
}
|
||||
return graticuleGridSectorSelection(graticuleSectorAt(selection.center, {
|
||||
lod: selection.lod + 1,
|
||||
stepDegrees: parentProfile.graticuleStepDegrees,
|
||||
}), parentProfile);
|
||||
}
|
||||
|
||||
export function gridSectorVolumeNeighborSelection(
|
||||
selection: GridSectorSelection,
|
||||
direction: "above" | "below",
|
||||
profile: SectorGridLodProfile | null,
|
||||
origin: { latitude: number; longitude: number },
|
||||
) {
|
||||
if (selection.mode !== "3d" || !selection.volume || !profile?.volumeEnabled) return null;
|
||||
const targetIndex = selection.volume.index + (direction === "above" ? 1 : -1);
|
||||
const targetFloorMeters = profile.volumeMinimumHeightMeters + targetIndex * profile.volumeBandHeightMeters;
|
||||
if (targetIndex < 0 || targetFloorMeters >= profile.volumeMaximumHeightMeters) return null;
|
||||
const targetCeilingMeters = Math.min(
|
||||
profile.volumeMaximumHeightMeters,
|
||||
targetFloorMeters + profile.volumeBandHeightMeters,
|
||||
);
|
||||
return localGridSectorSelection(
|
||||
selection.address,
|
||||
profile,
|
||||
origin,
|
||||
(targetFloorMeters + targetCeilingMeters) / 2,
|
||||
);
|
||||
}
|
||||
|
||||
const formatGridMetric = (value: number, maximumFractionDigits = 1) => value.toLocaleString("ru-RU", {
|
||||
maximumFractionDigits,
|
||||
});
|
||||
|
||||
export const formatGridSectorArea = (areaSquareMeters: number) => areaSquareMeters >= 1_000_000
|
||||
? `${formatGridMetric(areaSquareMeters / 1_000_000, areaSquareMeters >= 1_000_000_000 ? 0 : 2)} км²`
|
||||
: `${formatGridMetric(areaSquareMeters, 0)} м²`;
|
||||
|
||||
export function gridSectorBoundsLabel(selection: GridSectorSelection) {
|
||||
const { west, east, south, north } = selection.bounds;
|
||||
return selection.mode === "3d"
|
||||
? `E ${formatGridMetric(west)}…${formatGridMetric(east)} м · N ${formatGridMetric(south)}…${formatGridMetric(north)} м`
|
||||
: `λ ${formatGridMetric(west, 6)}…${formatGridMetric(east, 6)}° · φ ${formatGridMetric(south, 6)}…${formatGridMetric(north, 6)}°`;
|
||||
}
|
||||
|
||||
export function gridSectorCenterLabel(selection: GridSectorSelection) {
|
||||
return selection.mode === "3d"
|
||||
? `E ${formatGridMetric(selection.center.eastMeters)} м · N ${formatGridMetric(selection.center.northMeters)} м`
|
||||
: `${formatGridMetric(selection.center.latitude, 6)}°, ${formatGridMetric(selection.center.longitude, 6)}°`;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { MapDataProductBinding, MapSubjectState } from "./mapPageContract.js";
|
||||
import type { MapPresentationFilters, MapPresentationProfile } from "./mapPresentationProfile.js";
|
||||
import type { GridSectorSelection } from "./mapRendererContract.js";
|
||||
import type { SectorGridLodProfile } from "./mapSectorWorkspace.js";
|
||||
import type { MapRuntimeBinding, MapRuntimeFact } from "./useMapDataProductRuntime.js";
|
||||
|
||||
export type MapSelectableEntity = {
|
||||
id: string;
|
||||
title: string;
|
||||
kind: string;
|
||||
status: string;
|
||||
bindingId: string;
|
||||
dataProductId: string;
|
||||
fact: MapRuntimeFact;
|
||||
};
|
||||
|
||||
export type MapSectorScope = {
|
||||
excludedBindingIds: string[];
|
||||
excludedProviders: string[];
|
||||
excludedObjectKinds: string[];
|
||||
};
|
||||
|
||||
export type MapPresentationSummary = {
|
||||
bindingId: string;
|
||||
displayName: string;
|
||||
profile: MapPresentationProfile;
|
||||
total: number;
|
||||
counts: Record<string, Record<string, number>>;
|
||||
};
|
||||
|
||||
export type MapFilteredTarget = {
|
||||
bindingId: string;
|
||||
entityId: string;
|
||||
title: string;
|
||||
status: string;
|
||||
renderable: boolean;
|
||||
};
|
||||
|
||||
export function mapProfileHasSubjectWindowControls(profile: MapPresentationProfile): boolean;
|
||||
export function primaryMapBindingConfigs(bindingConfigs: MapDataProductBinding[]): MapDataProductBinding[];
|
||||
export function primaryMapRuntimeBindings(runtimeBindings: MapRuntimeBinding[], bindingConfigs: MapDataProductBinding[]): MapRuntimeBinding[];
|
||||
export function buildMapPresentationFilters(subjectStates: Record<string, MapSubjectState>, bindingConfigs: MapDataProductBinding[], profiles: MapPresentationProfile[]): MapPresentationFilters;
|
||||
export function buildSelectableMapEntities(runtimeBindings: MapRuntimeBinding[], bindingConfigs: MapDataProductBinding[], profiles: MapPresentationProfile[]): MapSelectableEntity[];
|
||||
export function buildSectorSpatialEntities(selectable: MapSelectableEntity[], selection: GridSectorSelection | null, profiles: SectorGridLodProfile[], origin: { latitude: number; longitude: number }): MapSelectableEntity[];
|
||||
export function buildSectorBindingOptions(bindingConfigs: MapDataProductBinding[], sectorEntities: MapSelectableEntity[]): Array<{ value: string; label: string; count: number }>;
|
||||
export function bindingProjectsField(bindingConfigs: MapDataProductBinding[], field: string): boolean;
|
||||
export function buildSectorScopeOptions(sectorEntities: MapSelectableEntity[], field: string, enabled?: boolean): Array<{ value: string; label: string; count: number }>;
|
||||
export function sectorEntityIsExcluded(entity: MapSelectableEntity, scope: MapSectorScope): boolean;
|
||||
export function buildSectorVisibleEntities(input: { sectorEntities: MapSelectableEntity[]; bindingConfigs: MapDataProductBinding[]; presentationProfiles: MapPresentationProfile[]; presentationFilters: MapPresentationFilters; scope: MapSectorScope }): MapSelectableEntity[];
|
||||
export function scopeMapRuntimeBindings(input: { runtimeBindings: MapRuntimeBinding[]; selection: GridSectorSelection | null; gridProfiles: SectorGridLodProfile[]; origin: { latitude: number; longitude: number }; hideOutsideSector: boolean; scope: MapSectorScope }): MapRuntimeBinding[];
|
||||
export function buildMapPresentationSummaries(bindingConfigs: MapDataProductBinding[], runtimeBindings: MapRuntimeBinding[], profiles: MapPresentationProfile[]): MapPresentationSummary[];
|
||||
export function buildFilteredMapTargets(runtimeBindings: MapRuntimeBinding[], bindingConfigs: MapDataProductBinding[], profiles: MapPresentationProfile[], filters: MapPresentationFilters): MapFilteredTarget[];
|
||||
export function planMapSubjectReveal(input: { entity: MapSelectableEntity; subjectState: MapSubjectState; profile: MapPresentationProfile | undefined; selectedSector: GridSectorSelection | null; gridProfiles: SectorGridLodProfile[]; origin: { latitude: number; longitude: number }; hideOutsideSector: boolean; scope: MapSectorScope }): { subjectState: MapSubjectState; hideOutsideSector: boolean; scope: MapSectorScope };
|
||||
@@ -0,0 +1,256 @@
|
||||
import {
|
||||
compareMapRuntimeFacts,
|
||||
mapFactMatchesFilters,
|
||||
mapPresentationFacetCounts,
|
||||
mapPresentationProfileForFact,
|
||||
mapRuntimeDisplayLabel,
|
||||
mapRuntimeFactIsRenderable,
|
||||
normalizeMapPresentationFacetSelections,
|
||||
resolveMapPresentationClass,
|
||||
} from "./mapPresentationProfile.mjs";
|
||||
import { mapRuntimeEntityId } from "./mapRuntimeIdentity.mjs";
|
||||
import {
|
||||
MAP_SCOPE_OBJECT_KIND_FIELD,
|
||||
MAP_SCOPE_PROVIDER_FIELD,
|
||||
mapFactInsideGridSector,
|
||||
mapFactSectorScopeValue,
|
||||
sectorScopeValueLabel,
|
||||
} from "./mapSectorRuntime.mjs";
|
||||
|
||||
export function mapProfileHasSubjectWindowControls(profile) {
|
||||
return profile.facets.some((facet) => facet.counter || facet.filterable);
|
||||
}
|
||||
|
||||
/** Primary bindings create map subjects; joined aspects only enrich them. */
|
||||
export function primaryMapBindingConfigs(bindingConfigs) {
|
||||
return [...bindingConfigs]
|
||||
.filter((binding) => !binding.joinToBindingId)
|
||||
.sort(bindingOrder);
|
||||
}
|
||||
|
||||
export function primaryMapRuntimeBindings(runtimeBindings, bindingConfigs) {
|
||||
const runtimeById = new Map(runtimeBindings.map((binding) => [binding.bindingId, binding]));
|
||||
return primaryMapBindingConfigs(bindingConfigs)
|
||||
.map((binding) => runtimeById.get(binding.id))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
export function buildMapPresentationFilters(subjectStates, bindingConfigs, profiles) {
|
||||
return Object.fromEntries(Object.entries(subjectStates).map(([bindingId, state]) => {
|
||||
const binding = bindingConfigs.find((candidate) => candidate.id === bindingId);
|
||||
const profile = mapPresentationProfileForFact(
|
||||
profiles,
|
||||
binding?.presentationProfileId,
|
||||
binding?.semanticTypes?.[0] ?? "",
|
||||
);
|
||||
return [bindingId, {
|
||||
visible: state.visible,
|
||||
facets: profile ? normalizeMapPresentationFacetSelections(state.filters, profile) : state.filters,
|
||||
}];
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildSelectableMapEntities(runtimeBindings, bindingConfigs, profiles) {
|
||||
const configById = new Map(bindingConfigs.map((binding) => [binding.id, binding]));
|
||||
return primaryMapRuntimeBindings(runtimeBindings, bindingConfigs).flatMap((binding) => {
|
||||
const bindingConfig = configById.get(binding.bindingId);
|
||||
const facts = [...binding.facts];
|
||||
const primaryProfile = mapPresentationProfileForFact(
|
||||
profiles,
|
||||
bindingConfig?.presentationProfileId,
|
||||
bindingConfig?.semanticTypes?.[0] ?? facts[0]?.semanticType ?? "",
|
||||
);
|
||||
if (primaryProfile) facts.sort((left, right) => compareMapRuntimeFacts(left, right, primaryProfile));
|
||||
return facts.map((fact) => {
|
||||
const profile = mapPresentationProfileForFact(profiles, bindingConfig?.presentationProfileId, fact.semanticType);
|
||||
const presentationClass = profile ? resolveMapPresentationClass(fact, profile) : undefined;
|
||||
return {
|
||||
id: mapRuntimeEntityId(binding.bindingId, fact),
|
||||
title: mapRuntimeDisplayLabel(fact, profile),
|
||||
kind: fact.semanticType,
|
||||
status: presentationClass?.label ?? fact.presentationStatus,
|
||||
bindingId: binding.bindingId,
|
||||
dataProductId: binding.dataProductId,
|
||||
fact,
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function buildSectorSpatialEntities(selectable, selection, profiles, origin) {
|
||||
return selection
|
||||
? selectable.filter((entity) => mapFactInsideGridSector(entity.fact, selection, profiles, origin))
|
||||
: [];
|
||||
}
|
||||
|
||||
export function buildSectorBindingOptions(bindingConfigs, sectorEntities) {
|
||||
return primaryMapBindingConfigs(bindingConfigs).map((binding) => ({
|
||||
value: binding.id,
|
||||
label: binding.displayName?.trim() || binding.id,
|
||||
count: sectorEntities.filter((entity) => entity.bindingId === binding.id).length,
|
||||
}));
|
||||
}
|
||||
|
||||
export function bindingProjectsField(bindingConfigs, field) {
|
||||
return bindingConfigs.some((binding) => !binding.joinToBindingId && binding.fieldProjection.includes(field));
|
||||
}
|
||||
|
||||
export function buildSectorScopeOptions(sectorEntities, field, enabled = true) {
|
||||
if (!enabled) return [];
|
||||
const counts = new Map();
|
||||
for (const { fact } of sectorEntities) {
|
||||
const value = mapFactSectorScopeValue(fact, field);
|
||||
counts.set(value, (counts.get(value) ?? 0) + 1);
|
||||
}
|
||||
return [...counts]
|
||||
.map(([value, count]) => ({ value, count, label: sectorScopeValueLabel(value) }))
|
||||
.sort((left, right) => left.label.localeCompare(right.label, "ru"));
|
||||
}
|
||||
|
||||
export function sectorEntityIsExcluded(entity, scope) {
|
||||
return scope.excludedBindingIds.includes(entity.bindingId)
|
||||
|| scope.excludedProviders.includes(mapFactSectorScopeValue(entity.fact, MAP_SCOPE_PROVIDER_FIELD))
|
||||
|| scope.excludedObjectKinds.includes(mapFactSectorScopeValue(entity.fact, MAP_SCOPE_OBJECT_KIND_FIELD));
|
||||
}
|
||||
|
||||
export function buildSectorVisibleEntities({
|
||||
sectorEntities,
|
||||
bindingConfigs,
|
||||
presentationProfiles,
|
||||
presentationFilters,
|
||||
scope,
|
||||
}) {
|
||||
const configById = new Map(bindingConfigs.map((binding) => [binding.id, binding]));
|
||||
return sectorEntities.filter((entity) => {
|
||||
if (sectorEntityIsExcluded(entity, scope)) return false;
|
||||
const binding = configById.get(entity.bindingId);
|
||||
const profile = mapPresentationProfileForFact(
|
||||
presentationProfiles,
|
||||
binding?.presentationProfileId,
|
||||
entity.fact.semanticType,
|
||||
);
|
||||
return Boolean(profile && mapFactMatchesFilters(
|
||||
entity.fact,
|
||||
profile,
|
||||
presentationFilters,
|
||||
entity.bindingId,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
export function scopeMapRuntimeBindings({
|
||||
runtimeBindings,
|
||||
selection,
|
||||
gridProfiles,
|
||||
origin,
|
||||
hideOutsideSector,
|
||||
scope,
|
||||
}) {
|
||||
if (!selection) return runtimeBindings;
|
||||
return runtimeBindings.map((binding) => ({
|
||||
...binding,
|
||||
facts: binding.facts.filter((fact) => {
|
||||
if (scope.excludedBindingIds.includes(binding.bindingId)) return false;
|
||||
if (scope.excludedProviders.includes(mapFactSectorScopeValue(fact, MAP_SCOPE_PROVIDER_FIELD))) return false;
|
||||
if (scope.excludedObjectKinds.includes(mapFactSectorScopeValue(fact, MAP_SCOPE_OBJECT_KIND_FIELD))) return false;
|
||||
return !hideOutsideSector || mapFactInsideGridSector(fact, selection, gridProfiles, origin);
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildMapPresentationSummaries(bindingConfigs, runtimeBindings, profiles) {
|
||||
const runtimeById = new Map(runtimeBindings.map((binding) => [binding.bindingId, binding]));
|
||||
return primaryMapBindingConfigs(bindingConfigs).flatMap((bindingConfig) => {
|
||||
const binding = runtimeById.get(bindingConfig.id);
|
||||
const facts = binding?.facts ?? [];
|
||||
const semanticType = bindingConfig.semanticTypes[0] ?? facts[0]?.semanticType ?? "";
|
||||
const profile = mapPresentationProfileForFact(profiles, bindingConfig.presentationProfileId, semanticType);
|
||||
return profile ? [{
|
||||
bindingId: bindingConfig.id,
|
||||
displayName: bindingConfig.displayName?.trim() || profile.title || bindingConfig.id,
|
||||
profile,
|
||||
total: facts.length,
|
||||
counts: mapPresentationFacetCounts(facts, profile),
|
||||
}] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Object overview order is the same declared profile order used by facets and
|
||||
* renderer subjects. A title-only resort must not silently override MCP sort.
|
||||
*/
|
||||
export function buildFilteredMapTargets(runtimeBindings, bindingConfigs, profiles, filters) {
|
||||
return buildSelectableMapEntities(runtimeBindings, bindingConfigs, profiles).flatMap((entity) => {
|
||||
const binding = bindingConfigs.find((candidate) => candidate.id === entity.bindingId);
|
||||
const profile = mapPresentationProfileForFact(profiles, binding?.presentationProfileId, entity.fact.semanticType);
|
||||
if (!profile || !mapFactMatchesFilters(entity.fact, profile, filters, entity.bindingId)) return [];
|
||||
return [{
|
||||
bindingId: entity.bindingId,
|
||||
entityId: entity.id,
|
||||
title: entity.title,
|
||||
status: resolveMapPresentationClass(entity.fact, profile)?.label ?? "",
|
||||
renderable: mapRuntimeFactIsRenderable(entity.fact, profile),
|
||||
}];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search reveal changes only constraints that hide the selected subject. The
|
||||
* active sector identity is preserved; outside-sector clipping is relaxed only
|
||||
* when needed so focus and the rendered subject cannot diverge.
|
||||
*/
|
||||
export function planMapSubjectReveal({
|
||||
entity,
|
||||
subjectState,
|
||||
profile,
|
||||
selectedSector,
|
||||
gridProfiles,
|
||||
origin,
|
||||
hideOutsideSector,
|
||||
scope,
|
||||
}) {
|
||||
let filters = { ...(subjectState?.filters ?? {}) };
|
||||
for (const facet of profile?.facets ?? []) {
|
||||
const selected = filters[facet.field];
|
||||
if (selected === undefined) continue;
|
||||
const factValue = normalizedFacetValue(entity.fact.attributes[facet.field]);
|
||||
const available = facet.values.map((item) => item.value);
|
||||
if (!available.includes(factValue)) {
|
||||
delete filters[facet.field];
|
||||
continue;
|
||||
}
|
||||
filters[facet.field] = available.filter((value) => selected.includes(value) || value === factValue);
|
||||
}
|
||||
if (profile) filters = normalizeMapPresentationFacetSelections(filters, profile);
|
||||
if (profile && !mapFactMatchesFilters(entity.fact, profile, {
|
||||
[entity.bindingId]: { visible: true, facets: filters },
|
||||
}, entity.bindingId)) filters = {};
|
||||
|
||||
const provider = mapFactSectorScopeValue(entity.fact, MAP_SCOPE_PROVIDER_FIELD);
|
||||
const objectKind = mapFactSectorScopeValue(entity.fact, MAP_SCOPE_OBJECT_KIND_FIELD);
|
||||
const insideSector = selectedSector
|
||||
? mapFactInsideGridSector(entity.fact, selectedSector, gridProfiles, origin)
|
||||
: true;
|
||||
return {
|
||||
subjectState: {
|
||||
...subjectState,
|
||||
bindingId: entity.bindingId,
|
||||
visible: true,
|
||||
filters,
|
||||
},
|
||||
hideOutsideSector: hideOutsideSector && (!selectedSector || insideSector),
|
||||
scope: {
|
||||
excludedBindingIds: scope.excludedBindingIds.filter((value) => value !== entity.bindingId),
|
||||
excludedProviders: scope.excludedProviders.filter((value) => value !== provider),
|
||||
excludedObjectKinds: scope.excludedObjectKinds.filter((value) => value !== objectKind),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function bindingOrder(left, right) {
|
||||
return (left.order ?? 0) - (right.order ?? 0) || left.id.localeCompare(right.id);
|
||||
}
|
||||
|
||||
function normalizedFacetValue(value) {
|
||||
return typeof value === "string" ? value.trim().toLowerCase() : "unknown";
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { WorkspaceWindowRect } from "@nodedc/ui-react";
|
||||
import type { MapSubjectState, MapWorkspaceWindowId } from "./mapPageContract.js";
|
||||
import type { GridSectorSelection } from "./mapRendererContract.js";
|
||||
import type { MapSectorScope } from "./mapWorkspaceModel.mjs";
|
||||
|
||||
export type MapWorkspaceState = {
|
||||
selectedEntityId?: string;
|
||||
selectedSector: GridSectorSelection | null;
|
||||
subjectStates: Record<string, MapSubjectState>;
|
||||
activeWindowId?: MapWorkspaceWindowId;
|
||||
sector: {
|
||||
window: { rect: WorkspaceWindowRect; maximized: boolean; zIndex: number };
|
||||
hideOutside: boolean;
|
||||
scope: MapSectorScope;
|
||||
};
|
||||
subjectCard: {
|
||||
open: boolean;
|
||||
rect: WorkspaceWindowRect;
|
||||
maximized: boolean;
|
||||
zIndex: number;
|
||||
tabId: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type MapWorkspaceAction =
|
||||
| { type: "reset-sector-definition" }
|
||||
| { type: "deactivate-sector" }
|
||||
| { type: "set-sector-selection"; selection: GridSectorSelection | null }
|
||||
| { type: "select-sector"; selection: GridSectorSelection | null }
|
||||
| { type: "set-sector-hide-outside"; value: boolean }
|
||||
| { type: "set-sector-scope"; scope: MapSectorScope }
|
||||
| { type: "set-sector-scope-enabled"; dimension: "binding" | "provider" | "object-kind"; value: string; enabled: boolean }
|
||||
| { type: "set-sector-window-rect"; rect: WorkspaceWindowRect }
|
||||
| { type: "set-sector-window-maximized"; value: boolean }
|
||||
| { type: "toggle-subject-filter"; bindingId: string; field: string; value: string; availableValues: string[] }
|
||||
| { type: "toggle-subject-visibility"; bindingId: string }
|
||||
| { type: "replace-subject-state"; bindingId: string; subjectState: MapSubjectState }
|
||||
| { type: "open-subject-window"; bindingId: string }
|
||||
| { type: "close-subject-window"; bindingId: string }
|
||||
| { type: "set-subject-window-rect"; bindingId: string; rect: WorkspaceWindowRect }
|
||||
| { type: "set-subject-window-maximized"; bindingId: string; value: boolean }
|
||||
| { type: "activate-window"; windowId: MapWorkspaceWindowId }
|
||||
| { type: "clear-active-window"; windowId: MapWorkspaceWindowId }
|
||||
| { type: "select-entity"; entityId: string; validTabIds: string[]; defaultTabId: string }
|
||||
| { type: "close-subject-card" }
|
||||
| { type: "set-subject-card-rect"; rect: WorkspaceWindowRect }
|
||||
| { type: "set-subject-card-maximized"; value: boolean }
|
||||
| { type: "set-subject-card-tab"; tabId: string }
|
||||
| { type: "reveal-subject"; bindingId: string; subjectState: MapSubjectState; hideOutsideSector: boolean; scope: MapSectorScope };
|
||||
|
||||
export function createMapWorkspaceState(input: {
|
||||
subjectStates: Record<string, MapSubjectState>;
|
||||
sectorWindowRect: WorkspaceWindowRect;
|
||||
subjectCardRect: WorkspaceWindowRect;
|
||||
}): MapWorkspaceState;
|
||||
export function mapWorkspaceReducer(state: MapWorkspaceState, action: MapWorkspaceAction): MapWorkspaceState;
|
||||
@@ -0,0 +1,223 @@
|
||||
import { toggleMapPresentationFacetSelection } from "./mapPresentationProfile.mjs";
|
||||
|
||||
export function createMapWorkspaceState({ subjectStates, sectorWindowRect, subjectCardRect }) {
|
||||
return {
|
||||
selectedEntityId: undefined,
|
||||
selectedSector: null,
|
||||
subjectStates,
|
||||
activeWindowId: undefined,
|
||||
sector: {
|
||||
window: { rect: sectorWindowRect, maximized: false, zIndex: 142 },
|
||||
hideOutside: false,
|
||||
scope: {
|
||||
excludedBindingIds: [],
|
||||
excludedProviders: [],
|
||||
excludedObjectKinds: [],
|
||||
},
|
||||
},
|
||||
subjectCard: {
|
||||
open: false,
|
||||
rect: subjectCardRect,
|
||||
maximized: false,
|
||||
zIndex: 140,
|
||||
tabId: "overview",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function mapWorkspaceReducer(state, action) {
|
||||
switch (action.type) {
|
||||
case "reset-sector-definition":
|
||||
case "deactivate-sector":
|
||||
return {
|
||||
...state,
|
||||
selectedSector: null,
|
||||
activeWindowId: state.activeWindowId === "sector" ? undefined : state.activeWindowId,
|
||||
sector: {
|
||||
...state.sector,
|
||||
scope: { excludedBindingIds: [], excludedProviders: [], excludedObjectKinds: [] },
|
||||
},
|
||||
};
|
||||
case "set-sector-selection":
|
||||
return { ...state, selectedSector: action.selection };
|
||||
case "select-sector":
|
||||
return action.selection
|
||||
? activateWindow({ ...state, selectedSector: action.selection }, "sector")
|
||||
: mapWorkspaceReducer(state, { type: "deactivate-sector" });
|
||||
case "set-sector-hide-outside":
|
||||
return { ...state, sector: { ...state.sector, hideOutside: action.value } };
|
||||
case "set-sector-scope":
|
||||
return { ...state, sector: { ...state.sector, scope: action.scope } };
|
||||
case "set-sector-scope-enabled": {
|
||||
const key = action.dimension === "binding"
|
||||
? "excludedBindingIds"
|
||||
: action.dimension === "provider"
|
||||
? "excludedProviders"
|
||||
: "excludedObjectKinds";
|
||||
return {
|
||||
...state,
|
||||
sector: {
|
||||
...state.sector,
|
||||
scope: {
|
||||
...state.sector.scope,
|
||||
[key]: setScopeValueEnabled(state.sector.scope[key], action.value, action.enabled),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
case "set-sector-window-rect":
|
||||
return {
|
||||
...state,
|
||||
sector: { ...state.sector, window: { ...state.sector.window, rect: action.rect } },
|
||||
};
|
||||
case "set-sector-window-maximized":
|
||||
return {
|
||||
...state,
|
||||
sector: { ...state.sector, window: { ...state.sector.window, maximized: action.value } },
|
||||
};
|
||||
case "toggle-subject-filter": {
|
||||
const subject = state.subjectStates[action.bindingId];
|
||||
if (!subject) return state;
|
||||
const filters = subject.visible ? subject.filters : {};
|
||||
return replaceSubjectState(state, action.bindingId, {
|
||||
...subject,
|
||||
visible: true,
|
||||
filters: toggleMapPresentationFacetSelection(
|
||||
filters,
|
||||
action.field,
|
||||
action.value,
|
||||
action.availableValues,
|
||||
),
|
||||
});
|
||||
}
|
||||
case "toggle-subject-visibility": {
|
||||
const subject = state.subjectStates[action.bindingId];
|
||||
return subject
|
||||
? replaceSubjectState(state, action.bindingId, { ...subject, visible: !subject.visible })
|
||||
: state;
|
||||
}
|
||||
case "replace-subject-state":
|
||||
return replaceSubjectState(state, action.bindingId, action.subjectState);
|
||||
case "open-subject-window": {
|
||||
const subject = state.subjectStates[action.bindingId];
|
||||
if (!subject) return state;
|
||||
return activateWindow(replaceSubjectState(state, action.bindingId, {
|
||||
...subject,
|
||||
window: { ...subject.window, open: true },
|
||||
}), `binding:${action.bindingId}`);
|
||||
}
|
||||
case "close-subject-window": {
|
||||
const subject = state.subjectStates[action.bindingId];
|
||||
if (!subject) return state;
|
||||
const next = replaceSubjectState(state, action.bindingId, {
|
||||
...subject,
|
||||
window: { ...subject.window, open: false },
|
||||
});
|
||||
const windowId = `binding:${action.bindingId}`;
|
||||
return { ...next, activeWindowId: next.activeWindowId === windowId ? undefined : next.activeWindowId };
|
||||
}
|
||||
case "set-subject-window-rect": {
|
||||
const subject = state.subjectStates[action.bindingId];
|
||||
return subject ? replaceSubjectState(state, action.bindingId, {
|
||||
...subject,
|
||||
window: { ...subject.window, rect: action.rect },
|
||||
}) : state;
|
||||
}
|
||||
case "set-subject-window-maximized": {
|
||||
const subject = state.subjectStates[action.bindingId];
|
||||
return subject ? replaceSubjectState(state, action.bindingId, {
|
||||
...subject,
|
||||
window: { ...subject.window, maximized: action.value },
|
||||
}) : state;
|
||||
}
|
||||
case "activate-window":
|
||||
return activateWindow(state, action.windowId);
|
||||
case "clear-active-window":
|
||||
return {
|
||||
...state,
|
||||
activeWindowId: state.activeWindowId === action.windowId ? undefined : state.activeWindowId,
|
||||
};
|
||||
case "select-entity": {
|
||||
const tabId = action.validTabIds.includes(state.subjectCard.tabId)
|
||||
? state.subjectCard.tabId
|
||||
: action.defaultTabId;
|
||||
return activateWindow({
|
||||
...state,
|
||||
selectedEntityId: action.entityId,
|
||||
subjectCard: { ...state.subjectCard, open: true, tabId },
|
||||
}, "subject-card");
|
||||
}
|
||||
case "close-subject-card":
|
||||
return {
|
||||
...state,
|
||||
activeWindowId: state.activeWindowId === "subject-card" ? undefined : state.activeWindowId,
|
||||
subjectCard: { ...state.subjectCard, open: false },
|
||||
};
|
||||
case "set-subject-card-rect":
|
||||
return { ...state, subjectCard: { ...state.subjectCard, rect: action.rect } };
|
||||
case "set-subject-card-maximized":
|
||||
return { ...state, subjectCard: { ...state.subjectCard, maximized: action.value } };
|
||||
case "set-subject-card-tab":
|
||||
return { ...state, subjectCard: { ...state.subjectCard, tabId: action.tabId } };
|
||||
case "reveal-subject":
|
||||
return {
|
||||
...replaceSubjectState(state, action.bindingId, action.subjectState),
|
||||
sector: {
|
||||
...state.sector,
|
||||
hideOutside: action.hideOutsideSector,
|
||||
scope: action.scope,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
function replaceSubjectState(state, bindingId, subjectState) {
|
||||
return {
|
||||
...state,
|
||||
subjectStates: { ...state.subjectStates, [bindingId]: subjectState },
|
||||
};
|
||||
}
|
||||
|
||||
function activateWindow(state, windowId) {
|
||||
if (state.activeWindowId === windowId) return state;
|
||||
const nextZIndex = Math.max(
|
||||
20,
|
||||
state.sector.window.zIndex,
|
||||
state.subjectCard.zIndex,
|
||||
...Object.values(state.subjectStates).map((subject) => subject.window.zIndex),
|
||||
) + 1;
|
||||
if (windowId === "sector") {
|
||||
return {
|
||||
...state,
|
||||
activeWindowId: windowId,
|
||||
sector: { ...state.sector, window: { ...state.sector.window, zIndex: nextZIndex } },
|
||||
};
|
||||
}
|
||||
if (windowId === "subject-card") {
|
||||
return {
|
||||
...state,
|
||||
activeWindowId: windowId,
|
||||
subjectCard: { ...state.subjectCard, zIndex: nextZIndex },
|
||||
};
|
||||
}
|
||||
if (windowId.startsWith("binding:")) {
|
||||
const bindingId = windowId.slice("binding:".length);
|
||||
const subject = state.subjectStates[bindingId];
|
||||
return subject ? {
|
||||
...replaceSubjectState(state, bindingId, {
|
||||
...subject,
|
||||
window: { ...subject.window, zIndex: nextZIndex },
|
||||
}),
|
||||
activeWindowId: windowId,
|
||||
} : state;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function setScopeValueEnabled(values, value, enabled) {
|
||||
return enabled
|
||||
? values.filter((candidate) => candidate !== value)
|
||||
: [...new Set([...values, value])];
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
.catalog-environment-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
|
||||
.catalog-environment-stage { display: grid; width: 100%; min-height: 480px; }
|
||||
|
||||
:root {
|
||||
background: var(--nodedc-canvas);
|
||||
}
|
||||
@@ -1681,33 +1678,6 @@ textarea {
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.catalog-split-pane-preview .catalog-preview__body {
|
||||
align-content: stretch;
|
||||
}
|
||||
|
||||
.catalog-split-pane-demo {
|
||||
min-height: 18rem;
|
||||
overflow: hidden;
|
||||
border-radius: var(--nodedc-radius-card);
|
||||
background: var(--nodedc-nested-surface);
|
||||
}
|
||||
|
||||
.catalog-split-pane-demo__panel {
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
place-content: center;
|
||||
justify-items: center;
|
||||
gap: 0.5rem;
|
||||
background: color-mix(in srgb, var(--nodedc-canvas) 82%, transparent);
|
||||
color: var(--nodedc-text-secondary);
|
||||
}
|
||||
|
||||
.catalog-split-pane-demo__panel strong {
|
||||
color: var(--nodedc-text-primary);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.catalog-side-panel-preview .catalog-preview__body {
|
||||
align-content: stretch;
|
||||
}
|
||||
@@ -1784,14 +1754,6 @@ textarea {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.catalog-icon-rail-demo {
|
||||
display: flex;
|
||||
width: max-content;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-2);
|
||||
}
|
||||
|
||||
.catalog-form {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
@@ -2304,8 +2266,3 @@ 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)}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import type { MapDataProductBinding } from "./MapFixturePreview.js";
|
||||
import type { MapDataProductBinding } from "./mapPageContract.js";
|
||||
import { mapRuntimeFactKey } from "./mapRuntimeIdentity.mjs";
|
||||
|
||||
export { mapRuntimeEntityId } from "./mapRuntimeIdentity.mjs";
|
||||
|
||||
export type DataProductPoint = {
|
||||
type: "Point";
|
||||
@@ -78,14 +81,6 @@ type BindingState = {
|
||||
const identifier = /^[A-Za-z0-9._:-]{1,160}$/;
|
||||
const cursorPattern = /^(?:0|[1-9]\d*)$/;
|
||||
|
||||
function factKey(fact: MapRuntimeFact) {
|
||||
return `${fact.semanticType}\u0000${fact.sourceId}`;
|
||||
}
|
||||
|
||||
export function mapRuntimeEntityId(bindingId: string, fact: Pick<MapRuntimeFact, "sourceId" | "semanticType">) {
|
||||
return `nodedc-runtime:${bindingId}:${fact.semanticType}:${fact.sourceId}`;
|
||||
}
|
||||
|
||||
function isIsoTimestamp(value: unknown): value is string {
|
||||
return typeof value === "string" && !Number.isNaN(Date.parse(value));
|
||||
}
|
||||
@@ -246,7 +241,7 @@ function replaceSnapshot(current: BindingState, snapshot: SnapshotEnvelope): Bin
|
||||
...current,
|
||||
cursor: snapshot.cursor,
|
||||
state: "ready",
|
||||
facts: Object.fromEntries(snapshot.facts.map((fact) => [factKey(fact), fact])),
|
||||
facts: Object.fromEntries(snapshot.facts.map((fact) => [mapRuntimeFactKey(fact), fact])),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -257,8 +252,8 @@ function applyPatch(current: BindingState, patch: PatchEnvelope): BindingState |
|
||||
if (current.cursor !== patch.previousCursor) return null;
|
||||
const facts = { ...current.facts };
|
||||
for (const operation of patch.operations) {
|
||||
if (operation.op === "upsert") facts[factKey(operation.fact)] = operation.fact;
|
||||
else delete facts[`${operation.semanticType}\u0000${operation.sourceId}`];
|
||||
if (operation.op === "upsert") facts[mapRuntimeFactKey(operation.fact)] = operation.fact;
|
||||
else delete facts[mapRuntimeFactKey(operation)];
|
||||
}
|
||||
return { ...current, facts, cursor: patch.cursor, state: "ready" };
|
||||
}
|
||||
@@ -266,7 +261,7 @@ function applyPatch(current: BindingState, patch: PatchEnvelope): BindingState |
|
||||
function applyPresentationPatch(current: BindingState, patch: PresentationPatchEnvelope): BindingState {
|
||||
const facts = { ...current.facts };
|
||||
for (const operation of patch.operations) {
|
||||
const key = `${operation.semanticType}\u0000${operation.sourceId}`;
|
||||
const key = mapRuntimeFactKey(operation);
|
||||
if (facts[key]) facts[key] = { ...facts[key], presentationStatus: operation.status };
|
||||
}
|
||||
return { ...current, facts };
|
||||
@@ -421,7 +416,7 @@ export function useMapDataProductRuntime({
|
||||
dataProductId: binding.dataProductId,
|
||||
slotId: binding.slotId,
|
||||
presentationProfileId: binding.presentationProfileId,
|
||||
facts: Object.values(record.facts).sort((left, right) => factKey(left).localeCompare(factKey(right))),
|
||||
facts: Object.values(record.facts).sort((left, right) => mapRuntimeFactKey(left).localeCompare(mapRuntimeFactKey(right))),
|
||||
cursor: record.cursor,
|
||||
state: record.state,
|
||||
};
|
||||
|
||||
@@ -211,7 +211,13 @@ function asFact(value: unknown): MapRuntimeFact | null {
|
||||
|| !isIso(value.observedAt) || !isIso(value.receivedAt)
|
||||
|| !isObject(value.attributes) || !categories.has(value.attributes.category as MapReferenceStationCategory)
|
||||
|| !isPoint(value.geometry)) return null;
|
||||
const allowedAttributes = new Set(["name", "category", "network", "operator", "official_name", "local_name", "uic_ref", "wheelchair"]);
|
||||
if (value.attributes.alternate_names !== undefined
|
||||
&& (!Array.isArray(value.attributes.alternate_names)
|
||||
|| value.attributes.alternate_names.length > 16
|
||||
|| value.attributes.alternate_names.some((name) => typeof name !== "string" || !name.trim() || name.length > 256))) {
|
||||
return null;
|
||||
}
|
||||
const allowedAttributes = new Set(["name", "category", "network", "operator", "official_name", "local_name", "alternate_names", "uic_ref", "wheelchair"]);
|
||||
return {
|
||||
sourceId: value.sourceId,
|
||||
semanticType: String(value.semanticType),
|
||||
|
||||
+3
-93
@@ -2,7 +2,7 @@
|
||||
|
||||
## Текущее состояние
|
||||
|
||||
Пакетный контракт действует: CMS использует общие tokens, ui-core, ui-dom и ui-react, включая принятую тему Mission Core; Device Core использует общую шапку. Точные consumer pins и границы приведены ниже. Остальные приложения переводятся по отдельным проверенным этапам; наличие общего компонента не означает автоматическую миграцию всех consumer.
|
||||
Первый этап не меняет существующие приложения. Репозиторий фиксирует baseline и создаёт пакетный контракт. Это позволяет продолжать текущую разработку без одномоментной переделки Engine, Ops, BIM, CMS, SEO и Launcher.
|
||||
|
||||
## Рекомендуемый порядок
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
### 3. CMS и SEO
|
||||
|
||||
Используют те же компоненты и механику окон. CMS уже подключает DOM-layer и контролируемые React islands; целевой слой SEO — React. Общий admin pattern `MediaSourceField`/`createMediaSourceController`; storage API остаётся в приложении. Цветовые сочетания определяются библиотечным theme preset, без локальных копий палитры.
|
||||
Используют те же компоненты и механику окон. CMS подключает DOM-layer, SEO — React-layer. Первым общим admin pattern подключается `MediaSourceField`/`createMediaSourceController`; storage API остаётся в приложении. Цветовые различия оформляются theme overrides.
|
||||
|
||||
### 4. Engine
|
||||
|
||||
@@ -62,8 +62,7 @@
|
||||
| --- | --- | --- | --- |
|
||||
| Launcher/Hub | React/local shared | React | header, button, dropdown, window |
|
||||
| SEO | React/local overrides | React | theme, window, field, select |
|
||||
| CMS | Пакеты + тонкий DOM/React adapter | Подключено, domain UI остаётся в CMS | Mission theme, shell/header, forms, modal, controls |
|
||||
| Device Core | Общий UserProfileMenu, pin 06cb8ad | Шапка подключена, формы без изменений | responsive profile, menu, avatar |
|
||||
| CMS | Vanilla DOM | DOM | theme, header, modal, select |
|
||||
| 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 |
|
||||
@@ -75,92 +74,3 @@
|
||||
- не поддерживать отдельную тему путём fork компонента;
|
||||
- не использовать legacy Engine inspector как промежуточный канон;
|
||||
- не удалять production local component до проверки package replacement.
|
||||
# Mission Core and onboard Home (R17)
|
||||
|
||||
Mission Core and Mission Core Node consume `EnvironmentSettingsWindow`,
|
||||
`EnvironmentMediaPlaylistEditor`, `EnvironmentBackgroundMedia` and `LandingStage`
|
||||
from `@nodedc/ui-react`. The former Control Station files are thin API/product
|
||||
registry adapters or compatibility re-exports. They own no copied form markup or
|
||||
presentation CSS. Node supplies Home only; Core retains all existing pages and
|
||||
its wire/storage schema. Both use the existing `UserProfileMenu` avatar dropdown.
|
||||
The component contract and catalog example are in `ENVIRONMENT_SETTINGS.md`.
|
||||
|
||||
## Mission Core loading (2026-09-08)
|
||||
|
||||
Core и Node используют общий sensor-ui/X4 frontend с Button.loading, IconButton.loading и LoadingRegion из Design Guideline. SDK/network semantics остаются в consumer, геометрия ожидания принадлежит DG. Этот локальный кандидат передаётся через source manifest с hashes вместе с Node installer; public npm release не публиковался, исходники компонентов в приложение не копируются.
|
||||
|
||||
## DC CMS package adoption (2026-11-05)
|
||||
|
||||
DC_CMS now consumes the immutable npm distributions of tokens, ui-core, ui-dom
|
||||
and ui-react, pinned to a canonical source SHA plus package hashes in the
|
||||
consumer's `ui/design-system.lock.json`. Its build renders AppHeader,
|
||||
ApplicationShell, AdminNavigationPanel, ApplicationPanel and control templates
|
||||
from exports. Select, Switch, RangeControl, ProgressBar, StatusBadge and Dropdown
|
||||
run directly as controlled React islands. Core CSS and tokens are bundled once.
|
||||
|
||||
The thin compatibility adapter is `DC_CMS/ui/src/design-system.mjs`: it retains
|
||||
native CMS form/model bindings and listeners, adopts generated field/card/button
|
||||
anatomy, uses ui-dom modal/workspace controllers and connects MediaSourceField's
|
||||
DOM contract to the existing CMS file manager. Folder columns, editable block
|
||||
collections and knowledge content remain domain UI. No package source is copied
|
||||
or maintained as a local component fork. Remove this adapter as those domain
|
||||
renderers move to direct component composition. CMS CI rejects stale generated
|
||||
assets; the existing Git-to-canonical-runner deployment foundation is unchanged.
|
||||
|
||||
CMS visual follow-up, 2026-11-05: flat theme edges, neutral white default accent,
|
||||
UserProfileMenu with a session avatar and inbox glyph, FeatureSettingsWindow,
|
||||
ColorField, pill-shaped split Select, and the canonical six-dot DragHandle.
|
||||
UI preferences belong to authenticated per-user server metadata; site content and deployment
|
||||
credentials stay in the existing CMS model. Immutable npm snapshots retain
|
||||
package semver and are identified by source commit plus archive SHA-256.
|
||||
|
||||
CMS uses `UserProfileMenu`: profile label, menu icon, avatar.
|
||||
The menu opens settings; the application does not add a fourth action.
|
||||
|
||||
|
||||
Device Core and CMS share the complete `UserProfileMenu` header, not local copies.
|
||||
The reference composition is the existing rounded profile group in Launcher/Hub
|
||||
and Engine (`EnginePlatformHeader.tsx` / `TopBar.tsx`); its reusable geometry is
|
||||
already in AppHeader, HeaderProfileButton, IconButton and HeaderAvatar. The owner
|
||||
confirmed the order profile → inbox → avatar and settings inside the middle
|
||||
icon's menu on 2026-11-05. No application CSS overrides are needed.
|
||||
Device Core retains session identity, profile URL, permissions and logout actions.
|
||||
|
||||
|
||||
### 2026-11-05 — Mission dark foundation → CMS
|
||||
|
||||
Owner selected the running local Mission Core as the canonical dark reference.
|
||||
Source audit: b0332fa, styles/base.css and main.tsx; uncommitted simulation changes excluded.
|
||||
The complete Mission/flat preset now lives in tokens + ui-core, exported for React and DOM consumers.
|
||||
CMS consumes the immutable packages and retains only domain layout/event adapters.
|
||||
Nested forms use SettingsCard with a transparent layout grid and opaque fields; collection entries use GlassSurface group. The soft canvas is not a form-group material; no CMS palette.
|
||||
Mission Core itself remains on its existing local package state; its duplicated base overrides are recorded migration debt, not silently updated.
|
||||
|
||||
|
||||
### CMS form composition correction — 2026-11-05
|
||||
|
||||
Mission Core environment settings were verified in the running app: SettingsCard
|
||||
uses the neutral group material, its form grid is transparent, fields are opaque.
|
||||
CMS removes the extra field-grid surface and the card around the full list of
|
||||
content cards. Collection entries and native JSON disclosures adopt the shared
|
||||
GlassSurface group material. No local palette, field colors or business logic
|
||||
are introduced. The prior soft-canvas composition is superseded in THEMING and
|
||||
the living catalog; soft itself remains available for recessed non-form areas.
|
||||
|
||||
## CMS: размеры модальных окон
|
||||
|
||||
CMS подключает `createModalSizeController` из immutable ui-dom package, без копии resize-кода. Тонкий адаптер связывает `media-library` с серверным пользовательским GUI JSON; оформление и размеры записываются через аутентифицированный API. Медиатека остаётся привязанной к сайту, геометрия — к пользователю.
|
||||
|
||||
## CMS: строка пути файлов
|
||||
|
||||
CMS подключает `renderPathBar` и его stylesheet из ui-dom, source `1326ec6`,
|
||||
immutable archive `nodedc-ui-dom-0.7.0-modal.2.tgz`. Адаптер передаёт пути
|
||||
выбранного сайта, стандартный Icon и callback перехода в папку. Общий компонент
|
||||
владеет компактной строкой Finder, разделителями и нейтральными иконками.
|
||||
Сетка файлов, поиск и фильтрация по нескольким типам остаются доменной логикой
|
||||
CMS; переключатели используют общий IconButton. Проверены выбор глубокого
|
||||
пути, переход в каталог, dark/light и узкое окно 390 px.
|
||||
|
||||
## Общие подсказки · 2026-11-16
|
||||
|
||||
Mission Core подключает `TooltipProvider` из ui-react 0.7.1 один раз над приложением. BIM Mod 0.2.45 подключает его в переносимом workspace и переиспользует provider хоста. Существующие HTML `title` обрабатываются через общий портал, SVG-подсказки — через `data-nodedc-tooltip` с доступным именем `aria-label`. Богатый контент использует `Tooltip`. Вложенные приложения не создают второй слой подсказок. Общий материал: скруглённое стекло без border, outline и декоративного rim; keyboard focus самих контролов сохраняется.
|
||||
|
||||
@@ -44,7 +44,3 @@ Modal остаётся portal-слоем. Его тело прокручивае
|
||||
- предметное содержимое content window.
|
||||
|
||||
Shell владеет геометрией, слоями, переходами и breakpoint-поведением. См. готовый путь подключения в `docs/CONSUMPTION.md`.
|
||||
|
||||
На узком экране скрывается именно действие `data-action="expand"`.
|
||||
Порядок utility actions не является признаком типа действия: плюс и обновление
|
||||
остаются доступны, даже когда стоят первыми в шапке. Исправлено при QA Node 0.3.
|
||||
|
||||
+10
-360
@@ -4,18 +4,15 @@
|
||||
|
||||
## GlassSurface
|
||||
|
||||
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал используется у floating-слоёв и явно выбранных информационных плашек над 3D-сценой.
|
||||
Базовая непрозрачная поверхность для карточки, панели и большого окна. Варианты меняют плотность нейтральной поверхности, но не создают отдельный дизайн. Реальный glass-материал с blur и rim используется только у floating-слоёв: modal `Window` и portal-dropdown/select.
|
||||
|
||||
- `default` — обычная карточка/панель;
|
||||
- `strong` — dropdown, modal и поверхность над сложным фоном;
|
||||
- `soft` — утопленная вторичная область / canvas, не подложка формы;
|
||||
- `group` — нейтральная группа как SettingsCard, для самостоятельного элемента коллекции.
|
||||
|
||||
`radius="pill"` задаёт каноническую капсульную геометрию через `--nodedc-radius-circle`. Она предназначена, в частности, для компактных вертикальных и горизонтальных реек из круглых действий: верхняя и нижняя части поверхности повторяют круг кнопок без прямых торцевых пролётов. Consumer не воспроизводит этот радиус локальным CSS.
|
||||
- `soft` — вложенная или вторичная область.
|
||||
|
||||
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 и информационные плашки над 3D через `context="scene"`; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную.
|
||||
`GlassMaterialSurface` — отдельный переносимый контракт Engine Glass V4. Он централизует tint/opacity, blur, saturation, brightness, gradient rim и shadow. Его используют только modal `Window` и modeless draggable Inspector; обычные Launcher/SEO панели остаются непрозрачными. Сам `Window` всегда получает класс `nodedc-glass-material` и `data-material="glass-v4"`, поэтому sharing, confirmation и остальные modal-паттерны физически используют тот же surface, что Inspector и лабораторный preview. Настройки применяются через `applyGlassMaterial`, поэтому consumer не пересобирает CSS материала вручную.
|
||||
|
||||
## Button и IconButton
|
||||
|
||||
@@ -28,25 +25,9 @@ Button используется для всех текстовых действ
|
||||
|
||||
Icon-only action по умолчанию круглый. Квадратная кнопка с маленьким радиусом допустима только как кнопка закрытия окна или плотный инструмент, где это зафиксировано контрактом.
|
||||
|
||||
`size="dense"` — каноническая плотность для текстовых layer/mode-действий внутри визуализатора. Она уменьшает площадь и подпись контрола, но не меняет hover, active, disabled и focus-состояния. В шапках приложения и обычных формах эта плотность не используется.
|
||||
|
||||
Переключаемый IconButton передаёт контролируемое состояние через `aria-pressed`. Активная поверхность и контраст принадлежат дизайн-системе; размер круга и glyph при переключении не меняются.
|
||||
|
||||
`loading` в `Button` и `IconButton` помещает индикатор по центру нажатой кнопки, сохраняет её размеры и accessible name, выставляет `aria-busy` и блокирует повторное нажатие. Подробный контракт — [состояния загрузки](LOADING_STATES.md).
|
||||
|
||||
## LoadingRegion
|
||||
|
||||
`LoadingRegion loading={pending} label="Получаем данные"` центрирует ожидание внутри области содержимого, сохраняя её детей смонтированными. Приложение резервирует размер визуализатора и снимает loading после первого пригодного содержимого, ошибки или timeout. Командный spinner принадлежит кнопке и сюда не дублируется.
|
||||
|
||||
## ActivityIndicator
|
||||
|
||||
`ActivityIndicator` — общий индикатор неопределённого по длительности процесса. `default` используется внутри `LoadingRegion` или явного inline-статуса, `compact` — внутри `Button.loading`/`IconButton.loading` либо фиксированного слота строки ресурса. Владелец операции по-прежнему задаёт видимый текст pending-состояния и `aria-busy`; индикатор не хранит таймер и не определяет завершение операции.
|
||||
|
||||
Без `label` индикатор декоративный и скрыт от accessibility tree. `label` включает `role="status"` только когда сам индикатор должен объявить процесс. При `prefers-reduced-motion: reduce` кольцо остаётся видимым, но не вращается.
|
||||
|
||||
## Field
|
||||
|
||||
FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. `appearance="plain"` сохраняет вид обычного текста без подложки и позволяет сразу поставить каретку; при пустой подписи нужен `aria-label`. TextAreaField в этом режиме растёт по содержимому и ширине окна, нативные выделение, вставка и undo сохраняются. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
|
||||
FieldFrame объединяет label, control, hint и description. TextField/TextAreaField реализуют стандартные текстовые поля.
|
||||
|
||||
Приложение не должно вручную собирать label и input, если подходит Field. Ошибка и validation state будут расширением этого контракта, а не локальным классом приложения.
|
||||
|
||||
@@ -58,19 +39,7 @@ 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 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком.
|
||||
|
||||
Drag всегда принадлежит невидимому native range и продолжается под областью значения. Над числом постоянно смонтирован один прозрачный native text input: фокус включает редактирование без замены DOM-узла и без pointer-state mutation, браузер ставит каретку в фактическое место клика, а drag/keyboard-selection и замена выделенного текста остаются полностью нативными. Поле не получает собственной подложки, select-all или второго focus-ring. Цвет текста и каретки автоматически выбирается между theme text и `on-accent` по фактической границе заливки под областью значения, поэтому светлая заливка получает тёмный контраст без application-local цвета. Enter/blur применяют значение с exact-bound/step-нормализацией, Escape отменяет ввод; события редактора не всплывают в оконные shortcuts. Оконный focus-manager выполняет начальный autofocus только при открытии и не отбирает фокус при последующих ререндерах.
|
||||
|
||||
`RangeControl orientation="vertical"` показывает текущую верхнюю границу среза у края заливки и нижнюю сохранённую границу `min` внизу. `formatLimit` форматирует эти числа без единиц по умолчанию. Центральная надпись отсутствует; имя и `formatValue(value)` остаются доступны screen reader. Верхняя подпись следует значению, ограничена высотой шкалы и не перекрывает нижнюю у минимума. `limitSide="left"` зеркалит подписи для шкалы справа от сцены.
|
||||
|
||||
Для двухстороннего среза передайте `value={[lower, upper]}` и `onChange={(band) => …}`. Обе границы независимы; заливка показывает оставшийся между ними слой. Drag выбирает ближайшую границу и удерживает её до отпускания. Границы не пересекаются; совпавшие можно снова развести движением вниз/вверх. Два native range доступны отдельно с клавиатуры и screen reader (`lowerLabel`/`upperLabel`). Подписи следуют обеим границам и разводятся у совпадения; центрального текста нет. Home/End возвращают выбранную границу к допустимому краю. Домен отдельно отключает нижнее/верхнее отсечение на соответствующем краю. Скалярный режим сохраняет совместимость.
|
||||
|
||||
В скалярном режиме заливка растёт снизу. Drag, стрелки и Home/End работают нативно. Фокус подчёркивает движущееся значение; контур, border и тень не добавляются. Домен определяет диапазон и отключение среза у верхнего края.
|
||||
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. Drag всегда принадлежит невидимому native range и продолжается под областью значения. Над числом постоянно смонтирован один прозрачный native text input: клик включает редактирование без замены DOM-узла, браузер ставит каретку в фактическое место клика, а drag-selection остаётся нативным. Поле не получает собственной подложки, select-all или второго focus-ring. Enter/blur применяют значение с clamp/step-нормализацией, Escape отменяет ввод; события редактора не всплывают в оконные shortcuts. Оконный focus-manager выполняет начальный autofocus только при открытии и не отбирает фокус при последующих ререндерах.
|
||||
|
||||
## ColorField
|
||||
|
||||
@@ -80,10 +49,6 @@ Engine/BIM-геометрия color field: круглый swatch и HEX-знач
|
||||
|
||||
## Dropdown
|
||||
|
||||
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. The same scope now supplies scene Glass V4 to control backgrounds (owner revision 2026-11-14). Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
|
||||
|
||||
`nodedc-scene-controls` is the compatibility alias for the same geometry and scene Glass V4 material. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
|
||||
|
||||
Dropdown владеет floating-layer поведением:
|
||||
|
||||
- рендерится в `document.body`;
|
||||
@@ -96,7 +61,7 @@ Dropdown владеет floating-layer поведением:
|
||||
- закрывается, когда trigger полностью уходит за границы viewport;
|
||||
- закрывается по outside pointer и Escape;
|
||||
- после Escape возвращает фокус на реальную trigger-кнопку, не закрывая родительское окно;
|
||||
- закрывает другой корневой dropdown; вложенный Select сохраняет родительское меню, выбор закрывает только Select, Escape закрывает самый глубокий слой.
|
||||
- закрывает другой открытый dropdown.
|
||||
|
||||
Содержимое меню передаётся приложением. Selection, action menu и filter menu используют один engine.
|
||||
|
||||
@@ -104,20 +69,15 @@ Dropdown владеет floating-layer поведением:
|
||||
|
||||
## Select
|
||||
|
||||
Select добавляет к Dropdown контролируемое значение, options и необязательный поиск. У него три канонические формы:
|
||||
Select добавляет к Dropdown контролируемое значение, options и необязательный поиск. У него две канонические формы:
|
||||
|
||||
- `integrated` — единая pill-поверхность Hub/Launcher: label слева, chevron строго у правого края;
|
||||
- `split` — форма Engine с отдельной областью значения и отдельной кнопкой раскрытия `46 px`, между ними зазор `8 px`;
|
||||
- `inline` — компактный toolbar-trigger: только текущее значение без постоянной подложки и chevron; всё значение открывает обычное portal-меню.
|
||||
- `split` — форма Engine с отдельной областью значения и отдельной кнопкой раскрытия `46 px`, между ними зазор `8 px`.
|
||||
|
||||
Native select не используется как видимый runtime UI. Меню рендерится через portal; у Engine-варианта меню имеет радиус `20 px`, а строки — `14 px` и высоту `42 px`.
|
||||
|
||||
Внутри `Inspector` форма `integrated` запрещена. Selection-поле собирается только через `InspectorSelectField`: видимая подпись находится сверху, а полноширинный control всегда использует `split`. Компонент намеренно не принимает `layout` и `variant`, поэтому consumer не может вернуть Inspector к Hub/Launcher pill-форме.
|
||||
|
||||
`SelectOption.action` добавляет независимое действие справа от строки (`label`, `icon`, `disabled`, `onAction`), например корзину. Это соседний канонический `IconButton`, не вложенная кнопка. Действие закрывает меню, не выбирает строку и не вызывает `onChange`; подтверждение и запрос принадлежат приложению. Меню с действиями использует dialog-семантику и отдельные доступные кнопки выбора/действия; обычный Select сохраняет listbox. Состояние `option.disabled` не блокирует независимое действие — для него предусмотрен `action.disabled`.
|
||||
|
||||
Действие строки повторяет принятый образец каталога сессий Mission Core: прозрачная колонка нажатия `2.35rem`, иконка `15 px`, приглушённый цвет, без круглой подложки, скругления или тени. Опциональный `tone="danger"` меняет цвет при наведении и клавиатурном фокусе, но не окрашивает корзину постоянно. Доступный focus-индикатор общего IconButton сохраняется.
|
||||
|
||||
## Window
|
||||
|
||||
Window — единая механика открытия modal и правой panel:
|
||||
@@ -129,16 +89,8 @@ 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.
|
||||
@@ -187,20 +139,6 @@ Enter при отсутствии совпадения разрешает оди
|
||||
|
||||
ConfirmationModal оборачивает Window и защищает async-confirm от повторного запуска. До завершения операции закрытие можно заблокировать.
|
||||
|
||||
## SplitPane
|
||||
|
||||
Невидимый разделитель остаётся прозрачным при наведении и pointer-resize, даже после ввода в текстовом поле. Клавиатурное изменение размера сохраняет видимый focus cue.
|
||||
|
||||
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
|
||||
|
||||
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
|
||||
|
||||
Вертикальная граница меняется мышью или клавишами `←/→`, горизонтальная — `↑/↓`; `Home/End` переходят к разрешённым границам, а `Shift` ускоряет клавиатурный шаг. Доля сохраняется при resize контейнера. Минимальные проценты обеих панелей применяются одинаково к pointer и keyboard interaction.
|
||||
|
||||
Разделитель является структурной границей между двумя рабочими представлениями и не создаёт декоративную рамку вокруг контента. При `resizable={false}` панели сохраняют ту же стабильную DOM-композицию, а separator полностью отсутствует в визуальном слое и accessibility tree; это позволяет приложению сворачивать одну из панелей без remount тяжёлого renderer.
|
||||
|
||||
При `separatorAppearance="invisible"` линия скрыта в покое, при наведении и перетаскивании. Зона захвата, курсор, клавиатурное изменение размера и индикатор клавиатурного фокуса сохраняются.
|
||||
|
||||
## ShareAccessModal
|
||||
|
||||
Workflow-sharing modal из нового Engine: заголовок ресурса, compact avatar stack, список участников, редактирование ролей, удаление доступа, email и роль нового участника. Компонент сохраняет Engine-геометрию `600 px` и controls `46 px`, но не импортирует ACL API. Consumer передаёт members, permissions и callbacks.
|
||||
@@ -213,14 +151,8 @@ Read-only link/copy окно из BIM Viewer. React-компонент испо
|
||||
|
||||
## SegmentedControl
|
||||
|
||||
`SegmentedGroup` + `SegmentedButton` собирают переключатели и триггер `Dropdown` в одной капсуле. `active` задаёт оформление; `aria-pressed` передаётся только переключателю, а `aria-expanded`/`aria-haspopup` — меню. Ref кнопки передаётся в `Dropdown.setTriggerRef`, поэтому сохраняются позиционирование и возврат фокуса. Геометрия, состояния и темы совпадают с `SegmentedControl`.
|
||||
|
||||
`selectionMode="multiple"` принимает массив `value` и возвращает массив в `onChange`. Это независимые кнопки `aria-pressed` в одной капсуле: допустимы ноль, один или все включённые сегменты. Обычный режим остаётся одиночным.
|
||||
|
||||
Pill navigation для верхней панели и компактного переключения режимов. Active segment использует активную поверхность темы; это не обязательно основной accent приложения.
|
||||
|
||||
`size="dense"` применяется только в насыщенной панели слоёв или режимов непосредственно над viewer. Шапка приложения сохраняет default-геометрию; consumer не воспроизводит dense-отступы или шрифт локальным CSS.
|
||||
|
||||
## AppHeader
|
||||
|
||||
Трёхосевая верхняя панель:
|
||||
@@ -237,14 +169,7 @@ Pill navigation для верхней панели и компактного п
|
||||
|
||||
## UserProfileMenu
|
||||
|
||||
Каноническая правая группа `AppHeader`: «Профиль» → inbox → аватар.
|
||||
`UserProfileMenu` владеет всей группой, включая `HeaderProfile`; приложение
|
||||
передаёт только identity и действия. Настройки находятся в меню, отдельной
|
||||
шестерёнки после аватара нет. Нельзя добавлять внешнюю обёртку или локальные
|
||||
отступы. Все три элемента открывают меню; Escape возвращает фокус на вызвавшую кнопку.
|
||||
На узком экране подпись скрывается по общей адаптивной механике; иконка и аватар остаются доступны.
|
||||
|
||||
Она использует
|
||||
Каноническая выпадашка профиля для правой группы `AppHeader`. Она использует
|
||||
общий portal `Dropdown`, показывает identity cover с аватаром, именем и
|
||||
подписью и принимает список application-owned действий.
|
||||
|
||||
@@ -280,14 +205,8 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
Постоянные действия всего рабочего окна передаются через `ApplicationPanel.utilityActions` и всегда находятся в правой части шапки перед expand/close. Сохранение общего layout или настроек приложения — одно такое действие для всего окна; оно не дублируется внутри отдельных карточек и секций.
|
||||
|
||||
Переключение режима выбранного объекта может передать `pressed` в utility action: состояние получает `aria-pressed` и общую активную поверхность. Например, `info` открывает обзор текущей сохранённой сессии Mission Core.
|
||||
|
||||
Если заголовок и действия не помещаются в одну строку, шапка переносит действия на следующую строку с выравниванием вправо. Кнопки не обрезаются, заголовок сохраняет читаемую ширину. Состав действий одинаков в обычном и развёрнутом окне.
|
||||
|
||||
Точные состояния и размеры зафиксированы в `docs/APPLICATION_TEMPLATE.md`.
|
||||
|
||||
Внешняя область stage использует `overflow: clip`: скрытый сдвинутый stage не должен создавать горизонтальную прокрутку всего приложения при смене фокуса или работе с плавающим окном. Прокрутка предметного содержимого остаётся внутри соответствующей панели.
|
||||
|
||||
## MediaSourceField
|
||||
|
||||
Общий компонент Launcher/CMS для медиа-поля: file control, имя файла, URL input, переключатель `HD / URL`, круглое превью, path/hint/error. Один контракт применяется и для stage-видео, и для изображений/логотипов; тип файла, подписи и preview задаёт consumer. Публичный API контролируемый.
|
||||
@@ -296,31 +215,8 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
## SettingsCard и Switch
|
||||
|
||||
В `UserProfileMenu` необязательный `headerAction={{label, onSelect}}` отделяет
|
||||
действие средней иконки от меню профиля. Аватар и текст профиля сохраняют меню.
|
||||
`ToastObserver onPresent` сообщает приложению новые и изменённые завершённые
|
||||
уведомления из вложенных `ToastStack`; хранение, даты и история принадлежат
|
||||
приложению. `ToastStack observe={false}` исключает повторную регистрацию
|
||||
сообщений, уже записанных сервером. Отображение и таймеры не изменяются.
|
||||
|
||||
`SettingsCard` фиксирует нейтральную структуру админской группы: eyebrow/title/description/actions/body. `Switch` покрывает компактное включение/видимость внутри таких групп. Данные секции, сохранение и права остаются в consumer.
|
||||
|
||||
Промежуточный loading-контейнер не должен обнулять вертикальный ритм тела
|
||||
карточки. Если `LoadingRegion` оборачивает несколько полей, consumer передаёт
|
||||
ему свою stack-компоновку с gap из spacing tokens. Связанные действия размещаются
|
||||
в flex-группе с token gap и переносом, а не соседними кнопками без интервала.
|
||||
Это применяется также к условно появляющимся фильтрам и действиям импорта/экспорта.
|
||||
|
||||
Бегунок включённого `Switch` использует `--nodedc-on-accent-rgb`, поэтому
|
||||
сохраняет контраст с белым, цветным и тёмным акцентом. Выключенный track
|
||||
наследует тон темы от text-primary. Длина track не сжимается при переносе
|
||||
подписи; положение бегунка остаётся дополнительным признаком состояния.
|
||||
|
||||
Для компактных сообщений о результате и пустых состояний `SettingsCard align="center"`
|
||||
центрирует содержимое по горизонтали и вертикали. Пустой body не создаёт
|
||||
асимметричный нижний отступ. Обычные группы настроек сохраняют `align="start"`;
|
||||
вариант не задаёт высоту и не меняет токены темы.
|
||||
|
||||
## AdminNavigationPanel
|
||||
|
||||
Левая выезжающая панель Hub/Launcher. Библиотека владеет оболочкой `352 px`, радиусом `21.6 px`, внутренними отступами, full-bleed context/navigation pills, круглыми icon surfaces и анимацией появления. Приложение передаёт workspace/company, маршруты, active id и footer identity.
|
||||
@@ -329,29 +225,8 @@ 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` размещает её
|
||||
@@ -374,8 +249,6 @@ 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`, а не мгновенным действием крестика.
|
||||
@@ -390,21 +263,14 @@ Sortable-строки ограничены вертикальной осью: г
|
||||
|
||||
Статус использует semantic tone: neutral, success, warning, danger или accent. Бизнес-статус приложения маппится на tone в самом приложении.
|
||||
|
||||
`pulse` добавляет пульсацию только лампы, не текста и не фона. Подходит для потери подтверждения или другого состояния, требующего внимания. При `prefers-reduced-motion: reduce` лампа остаётся постоянной. Текст статуса обязателен рядом с отдельным индикатором или в самом badge.
|
||||
|
||||
## ToastStack
|
||||
|
||||
`ToastCard` и `ToastStack` фиксируют Tasker-derived bottom-right уведомления для `success`, `error`, `warning`, `info` и `loading`. Приложение владеет текстом и состоянием операции; стек владеет portal, геометрией, aria-live и таймерами. Обычный terminal toast по умолчанию живёт `10 000 ms`; каждый стабильный `id` получает собственный таймер, поэтому добавление соседнего уведомления не продлевает уже показанное. Loading не закрывается автоматически и обновляется тем же id после завершения операции; после перехода в terminal tone для него запускается обычный независимый таймер. Toast не используется вместо modal confirmation.
|
||||
`ToastCard` и `ToastStack` фиксируют Tasker-derived bottom-right уведомления для `success`, `error`, `warning`, `info` и `loading`. Приложение владеет текстом и состоянием операции; стек владеет portal, геометрией, aria-live и таймерами. Loading не закрывается автоматически и обновляется тем же id после завершения операции. Toast не используется вместо modal confirmation.
|
||||
|
||||
## Environment Controls: Inspector и ControlRow
|
||||
|
||||
Единая accordion-панель для settings и definition controls. Источник — только новый Environment Settings и NDC Agent Inspector.
|
||||
|
||||
Inspector принимает `header` для полей перед секциями и `footer` для действий после них.
|
||||
Поля header и соседние секции разделяет `--nodedc-space-3` (12 px); footer
|
||||
центрирует действия. Вложенные Inspector сохраняют тот же шаг. Это общий контракт,
|
||||
а не локальные margin-правки потребителя. Вариант `panel` сохраняет компактные строки.
|
||||
|
||||
Inspector владеет:
|
||||
|
||||
- заголовками разделов;
|
||||
@@ -421,219 +287,3 @@ Inspector владеет:
|
||||
Для Engine Environment Settings desktop-контракт точный: окно `390 px`, рабочая колонка `330 px`, строка `154 + 14 + 162 px`, высота контрола `46 px`, section header `50 px` с радиусом `12 px`. Accent-filled section headers и полноширинные range/checker/select сохраняют геометрию исходника.
|
||||
|
||||
Engine продолжает владеть определениями полей, типами нод и сохранением значений. В живом catalog эти collapsible sections находятся в `Guideline → Контролы`; отдельной product-вкладки Inspector нет.
|
||||
|
||||
## ResourceRow и ResourceList
|
||||
|
||||
Общие компактные строки ресурсов, выделенные из Mission Core AI Inference.
|
||||
Контракт, состояния и происхождение: [RESOURCE_ROW.md](RESOURCE_ROW.md).
|
||||
|
||||
Светлый одноцветный знак шапки явно помечается `AppHeader.brandMonochrome` и
|
||||
`HeaderWorkspace.monochrome`: общая тема обеспечивает контраст на светлом фоне.
|
||||
По умолчанию флаг выключен; цветные изображения и аватары не меняются.
|
||||
|
||||
## ProgressBar
|
||||
|
||||
Линейная полоса выполнения: `label`, измеренная доля `value` 0…1 или
|
||||
неопределённая продолжительность без `value`, доступный `valueText`.
|
||||
В `ResourceRow` передаётся через `progress` и заменяет статус между
|
||||
наименованием и кнопками. Процент принадлежит приложению, анимация его не выдумывает.
|
||||
См. [контракт](PROGRESS_BAR.md).
|
||||
|
||||
StatusBadge `variant="indicator"` отображает только одну лампу состояния.
|
||||
Передавайте `aria-label` и `title`; дополнительный текст и значки скрываются.
|
||||
|
||||
## EnvironmentSettingsWindow и EnvironmentMediaPlaylistEditor
|
||||
|
||||
Единый редактор окружения перенесён из принятой композиции Mission Core. Принимает страницы, quick-action варианты, документ, состояние, upload/save adapters и название продукта. Использует тот же FeatureSettingsWindow, поля, переключатели, медиаконтент и перестановку; новое приложение передаёт данные, а не копирует форму. Для бортового приложения передаётся только home. Контракты и пример: [ENVIRONMENT_SETTINGS.md](ENVIRONMENT_SETTINGS.md).
|
||||
|
||||
## LandingStage и EnvironmentBackgroundMedia
|
||||
|
||||
Общая главная: надзаголовок, заголовок, описание, быстрые действия, фон и необязательные status/footer slots. Изображения меняются по таймеру, видео — после завершения; ошибочные источники пропускаются. Пустой фон однотонный, без декоративного круга. Состояние страниц и хранение принадлежат приложению.
|
||||
|
||||
Для primary Button `tone="neutral"` фиксирует белый enabled и серый disabled, независимо от темы и акцента; keyboard focus остаётся видимым. MediaSourceField принимает `disabled` и блокирует все операции выбора источника, пока родитель сохраняет документ или загружает файл.
|
||||
|
||||
## KeyButton
|
||||
|
||||
Контурная клавиша удержания с контролируемым pressed-состоянием. [Контракт](KEY_BUTTON.md).
|
||||
|
||||
`Window` и `FeatureSettingsWindow`: `headerActions` размещает обновление и другие контекстные IconButton рядом с закрытием; footer предназначен для завершения формы.
|
||||
|
||||
### Fullscreen portal ownership
|
||||
|
||||
React `Window` (including `FeatureSettingsWindow`) and `Dropdown` (including Select and ColorField) mount into the active native fullscreen element, falling back to document.body. Menu geometry remains viewport-fixed. Consumers must let an open dialog/menu handle Escape before restoring the fullscreen viewer.
|
||||
|
||||
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}` скрывает только видимый уголок. Размер по-прежнему меняется перетаскиванием правого нижнего угла или стрелками при фокусе на ручке; фокус остаётся видимым.
|
||||
|
||||
`InspectorSectionSpec.action` задаёт `{label, icon, disabled?, onAction}`. Это отдельная от раскрывающего заголовка кнопка: её нажатие не раскрывает секцию. В варианте `panel` она стоит левее стрелки; стрелка смотрит вниз в закрытом состоянии и вверх в открытом.
|
||||
|
||||
## DockLayout
|
||||
|
||||
`DockLayout` and `DockHandle` compose stable viewport hosts over a serializable `DockTree`.
|
||||
Drop at the center to exchange views; the left/right/top/bottom zones split that destination.
|
||||
The outer 24 CSS pixels of the visible workspace dock across its whole side, including
|
||||
when the pointer is over the source panel. The remaining tree keeps its relative layout.
|
||||
This zone is capped at 8% per axis on small surfaces; it takes precedence over panel zones.
|
||||
The preview labels the scope as «Вся область». Outside drops still cancel.
|
||||
`DockMove.scope="workspace"` selects this operation; omitted/`panel` retains local docking.
|
||||
The serialized `DockTree` is unchanged. `dockMoveAtPoint` resolves both hit-test scopes.
|
||||
Removing the source collapses its old empty branch. The contour uses the resulting tree,
|
||||
so it previews the actual final position, even when the destination expands after removal.
|
||||
Any number of available panels can be composed with nested horizontal and vertical splits.
|
||||
`focusedId` expands a view without reparenting media; the application persists `tree`.
|
||||
There is no permanent outline. Outside drops, local self drops and Escape leave the tree unchanged.
|
||||
Keyboard: Enter/Space on the grip, Tab/Shift+Tab to choose a destination, arrows for edges,
|
||||
Home for center, Shift+arrows for a whole-workspace edge, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing.
|
||||
|
||||
The pure tree types, geometry and operations are exported by `@nodedc/ui-core`; React re-exports them for view consumers. Domain adapters import the framework-neutral package.
|
||||
|
||||
## ProgressButton
|
||||
|
||||
Фаза и полоса выполнения внутри инициирующей кнопки. `LayerStackIndicator` анимирует канонический значок layers. [API и состояния](PROGRESS_BUTTON.md).
|
||||
|
||||
## Description
|
||||
|
||||
`Description` is the shared explanatory paragraph. It matches `SettingsCard.description`: inherited family, small font token (12px), regular 400, muted text token, line-height 1.4. Use it for help below values, not a local paragraph override.
|
||||
|
||||
Use `Description role="status"` for explanatory pending/result copy. Unclassed
|
||||
paragraphs in a `SettingsCard` body inherit this same contract as a compatibility
|
||||
safeguard, even inside layout groups. New consumers must use `Description`.
|
||||
This safeguard does not restyle headings, controls or explicitly styled data.
|
||||
|
||||
## ComparisonTable
|
||||
|
||||
`ComparisonTable` accepts a heading, entity columns and labelled rows. Semantic headers, a 9rem minimum per column and horizontal overflow preserve 1–N comparisons in narrow panels. The keyboard scrollport contains wheel overscroll; no borders or cards per entity. Data freshness stays application-owned.
|
||||
|
||||
|
||||
DockLayout panels accept minimumSize in CSS pixels. Recursive minimums apply to
|
||||
all ancestor splits and keyboard/pointer resizing. Below the whole-layout limit,
|
||||
the canvas scrolls instead of shrinking or overlapping panel contents.
|
||||
ComparisonTable density="compact" reduces 31px rows to21px (about32%). Its label
|
||||
column has a120px minimum, each data column88px, and available width is shared by
|
||||
data columns. Hosts provide matching content limits; typography stays12px.
|
||||
|
||||
### Toolbar in scene editors
|
||||
|
||||
Pass `container` and portal the shared `Toolbar` into a positioned viewport to keep it and its autohide reveal edge inside that viewport (including fullscreen). Omission retains window scope. Item `shortcut` adds a native tooltip and `aria-keyshortcuts`; the owning editor implements the scoped key binding. Focus reveals a hidden dock. Editing icons `select`, `pen`, `rectangle`, `curve`, `undo`, and `redo` use the shared Lucide adapter and catalog.
|
||||
|
||||
Toolbar item `menu` composes the canonical `Dropdown`, anchored to the tool button. Supply content or a function receiving `close`; menu controls remain canonical buttons, checkers or selects.
|
||||
|
||||
### Toolbar menus and settings
|
||||
|
||||
Toolbar supports left/right/top/bottom, minimum/maximum size, lens count, gap,
|
||||
material colors, autohide and `hideDelay` in milliseconds (0–15000). Applications
|
||||
persist these props in their existing preferences. A viewport `container` owns
|
||||
its reveal edges. Item menus open inward beyond the maximum magnified button
|
||||
extent; the shared Dropdown reserves that envelope throughout spring motion.
|
||||
Once a menu is open, hovering another menu trigger changes it. A 300 ms bounded
|
||||
pointer-intent triangle protects diagonal travel to the current menu. Clicking
|
||||
or keyboard activation remains immediate. Open menus suspend autohide. Selected
|
||||
menu choices use the neutral primary Button state as well as `aria-pressed`.
|
||||
|
||||
### Toolbar: Hold and scene dismissal (2026-10-21)
|
||||
|
||||
The first optional Hold action controls the existing persisted `autoHide` setting. Disabling autohide cancels any pending hide timer. Dropdown observes outside pointerdown in capture phase; viewport Toolbar consumes background dismissal before canvas editing tools, while other controls retain their normal actions. Nested menus and trigger clicks retain lineage behavior. Catalog includes the Hold action.
|
||||
|
||||
- `NavigationCube`: [orientation cube](NAVIGATION_CUBE.md), controlled face/edge/corner navigation.
|
||||
|
||||
### Window free mode
|
||||
|
||||
`Window` and composed `FeatureSettingsWindow` expose the move toggle by default for centered placement. It removes the backdrop and enables bounded header drag and border/corner resize without remounting the form. Return restores canonical modal geometry. Use arrow keys on the floating header to move; Shift+arrows resize. `allowFloating={false}` is available for workflows that explicitly require a fixed modal. Inspectors stretch within window content. See WINDOWS_AND_LAYERS.md for focus, portal and lifetime rules.
|
||||
|
||||
### Tree · compact outliner
|
||||
|
||||
Visibility is independent of disclosure. Data/eye updates never re-open selected ancestors or scroll to an old selection. Disclosure uses its arrow (or ArrowLeft/ArrowRight), preserves the scroll position, and does not expand on row double-click. Only a new external selected ID/revealKey requests automatic reveal; asynchronous nodes can complete that pending request.
|
||||
|
||||
`Tree` accepts stable `TreeNode` IDs, a selected ID and `onSelect`, optional query and visibility callback. Rows stay on one line with ellipsis. Selection reveals ancestors and scrolls only the tree, avoiding page/camera jumps. Arrow keys, Home/End, Enter/Space support navigation. Use the canonical `Window resizable initialRect` for a movable object outliner.
|
||||
|
||||
`Window` end inspectors can opt into `resizable`; the same eight-edge geometry and header Shift+arrow keyboard sizing are used. Existing windows keep their defaults. `DraggableItem` also exposes `activator.attributes` and `activator.listeners` to attach directly to a tile button; separate handles remain the default for existing consumers.
|
||||
|
||||
## Scene overlays and viewport height
|
||||
|
||||
`GlassMaterialSurface context="scene" radius="panel"` reuses V4 tint, blur/saturation/brightness with independent scene opacity (52%) and blur (18 px). Mission appearance cannot turn it into the 97%-opaque modal. Use only over rendered imagery, keep telemetry hit areas interactive for page scrolling and leave empty overlay space transparent to scene input. No decorative rim is added in Mission appearance.
|
||||
|
||||
`ResizableViewport` owns two visible bottom grips, controlled `height`, `minHeight`, `maxHeight`, `onHeightChange` and `onHeightCommit`. Drag uses pointer capture; keyboard Up/Down moves 10 px, Shift 50 px, Home/End selects limits. Owner persists on commit per view. The viewer remains in document flow, so heights larger than the available area scroll normally. Grip strokes are structural resize indicators; focus is canonical.
|
||||
|
||||
`ApplicationPanel allowFullscreen` makes `useApplicationPanelFullscreen()` available to owned viewer actions. Fullscreen moves the whole panel including its one header above the app stage. Canvas identity is preserved by atomic DOM move; modeless inspectors remain above it. Restore/back/close leaves no detached panel. This is application full-window presentation, not browser fullscreen, so body portals remain usable.
|
||||
|
||||
`ResizableViewport resizeIndicator={false}` hides the resize strokes and hover surface. Only the pointer cursor changes; keyboard focus remains accessible. Pointer capture does not force focus, avoiding a focus ring after mouse drag.
|
||||
|
||||
`SceneAnnotation` is a transparent canonical ghost button for projected scene data. Renderer supplies screen coordinates, culls offscreen/hidden objects and owns identity; click, Enter and Space activate the same selected state. Use stacked object name/value and never fabricate sensor fields.
|
||||
|
||||
ColorField keeps a local HEX draft so deletion and replacement work with strict controlled values. Six hexadecimal digits (optional #) apply live; blur/Enter normalize valid input or revert incomplete input. Escape cancels the draft. External value changes, including undo, synchronize the displayed text.
|
||||
|
||||
`GlassMaterialSurface` accepts `material: GlassMaterialSettings` and optional `radiusPx` for operator-customizable overlays. Variables are scoped to that instance; scene tint opacity and blur use the scene context, without mutating modal or global appearance.
|
||||
|
||||
Exact `RangeControl` editors synchronize external controlled-value changes while focused, so undo/redo is visible immediately and subsequent blur cannot reapply an obsolete draft.
|
||||
|
||||
Window: `rect` / `onRectCommit` — восстановление и фиксация геометрии инструментов; см. WINDOWS_AND_LAYERS.md. Иконка `minus` дополняет `plus` для управления масштабом содержимого.
|
||||
|
||||
`EditorDockLayout` / `EditorWorkspace`: переносимый редактор с закреплённым основным видом, четырьмя зонами стыковки, разделителями и отрываемыми панелями. Управляемый `EditorDockState` хранится в документе приложения. Шапка редактора не участвует в стыковке; возврат восстанавливает исходный вид. Контракт, keyboard и минимумы — в WINDOWS_AND_LAYERS.md.
|
||||
|
||||
Размер поясняющего текста `Description` можно задать через
|
||||
`--nodedc-description-font-size`; по умолчанию используется `--nodedc-font-size-sm`.
|
||||
|
||||
Window header actions default to before the move toggle. `headerActionsPlacement="before-close"` places supplied canonical IconButtons between move and close, preserving DOM/Tab order. Deletion confirmation remains application-owned content in the same mounted Window.
|
||||
|
||||
|
||||
## Tooltip
|
||||
|
||||
Общий стандарт: скруглённое стекло Scene Glass без декоративной рамки, outline и обводки. `TooltipProvider` подключается один раз на корне приложения и заменяет браузерные квадратные подсказки `title`, в том числе в старых экранах. Вложенный переносимый модуль использует уже установленный provider. Rich-content `Tooltip` сохраняет собственный триггер; две подсказки одновременно не появляются. `aria-describedby`, клавиатурный фокус, Escape, fullscreen и положение у границ окна сохраняются.
|
||||
|
||||
Нейтральная подсказка с `content`, `children`, необязательными `label`, `focusable`, `disabled` и `placement`. Оборачивает триггер; `focusable` делает читаемую графику доступной клавиатуре, обычная кнопка сохраняет собственный фокус. Hover, focus и touch показывают один общий portal над окном; Escape закрывает подсказку, не родительское окно. Можно перевести курсор в подсказку. Позиция пересчитывается при scroll/resize, с общим clamp/flip. Не содержит действий: для меню используется Dropdown. Нет рамки, акцентных цветов или анимации при reduced motion.
|
||||
|
||||
Принят для запрошенных владельцем пояснений шкал сигнала,10.11.2026; приложение владеет диапазонами и текстом, общий компонент — формой и взаимодействием.
|
||||
|
||||
|
||||
Window, WorkspaceWindow, ApplicationPanel and AdminPanel establish an independent compact md text base, including portals. Native semantic headings inside operational surfaces use md unless an explicit canonical title rule applies. Use Description for result/error/pending paragraphs. The living catalog includes a typography example with values, nested headings and a status dialog. See OPERATIONAL_TYPOGRAPHY.md and the exported build-time `@nodedc/ui-core/typography` contract.
|
||||
|
||||
## Flat surface profile and profile trigger
|
||||
|
||||
The shared theme supports `edges: "flat"` for borderless surfaces, including portal windows. Keyboard focus changes the fill and foreground instead of adding an outline. The living catalog exposes this alongside the Mission appearance switch. `UserProfileMenu` composes the canonical profile label, independent inbox/menu button and avatar. CMS puts settings inside that menu. No additional settings button or HeaderProfile wrapper is needed; spacing comes from existing HeaderProfileButton and IconButton geometry.
|
||||
|
||||
`Select variant="split" shape="pill"` aligns a compact workspace/site selector with adjacent round actions, preserving the shared dimensions and keyboard behavior.
|
||||
|
||||
|
||||
## Mission Core theme foundation
|
||||
|
||||
`missionDarkTheme` и `missionLightTheme` — общий профиль из `@nodedc/ui-core` / `@nodedc/ui-dom`. `applyNodedcTheme` по умолчанию выбирает Mission и flat. Полный контракт цветов и композиции вложенных форм находится в [THEMING.md](THEMING.md). SettingsCard использует семантическую поверхность группы; поля расположены непосредственно в его body, как в Mission Core. GlassSurface tone="group" использует тот же материал для элементов коллекций. tone="soft" не применяется к формам. Ни CMS, ни другой потребитель не повторяет палитру локально. Living catalog содержит форму и её портальную версию.
|
||||
|
||||
## Viewport UI — правило владельца 14.11.2026
|
||||
|
||||
Все элементы интерфейса с подложкой внутри viewport используют общий Glass V4: карты, BIM, LAS/облака точек, 3DGS, PlayCanvas, камеры и replay. Поиск, отдельные кнопки прозрачного action rail, информационные плашки и меню относятся к этому правилу независимо от движка. Обычные панели вне viewport остаются matte. См. [контракт, применение и проверку](VIEWPORT_UI.md).
|
||||
|
||||
## PathBar (DOM)
|
||||
|
||||
`renderPathBar(target, items, {icon, onNavigate})` — компактная строка пути в стиле Finder: нейтральные иконки папок, текст и разделители `›`, без pill-кнопок. Подключается `@nodedc/ui-dom/styles.css`. Папки — клавиатурно доступные кнопки; конечный файл — текст с `aria-current`. Длинный путь прокручивается по горизонтали. Consumer передаёт пути и существующий Icon, хранение и навигация остаются в приложении. Живой пример: «Размер DOM-окна».
|
||||
|
||||
Toolbar `menuWidth` controls inspector menu width (default 220 px, bounded 180–600 px); Dropdown retains viewport clamping. Tree `renderActions(node)` supports per-item information menus without duplicating the outliner. `defaultExpandedDepth` limits initial expansion; selecting an item still reveals and scrolls to its ancestors. BIM uses canonical `ruler` (dimension line), `section` (model/plane), and `isolate` (temporary visibility) glyphs.
|
||||
|
||||
Open Dropdown surfaces observe content size changes and recompute their viewport bounds, including asynchronous property/volume results. Information triggers open on hover or explicit pointer/keyboard activation with `show`. Do not open on focus alone: Escape restores trigger focus and must keep the menu closed.
|
||||
|
||||
|
||||
EditorDockLayout rounds only the external corners of its complete tiled area using the shared panel radius. A left stack has a rounded top-left on its first pane and bottom-left on its last; a bottom row has only the outer lower corners. Internal joins remain square. Corners recompute after docking, closing, resizing or restoring panels. Floating tools retain all four window corners. The primary viewport follows the same outside-edge rule.
|
||||
|
||||
Viewport-scoped Toolbar buttons use the same scene Glass V4 material as the top viewport controls, preserving pressed, disabled and keyboard states. Its rail remains transparent. Compact Tree information actions use `info-plain` at 14 px beside the existing eye.
|
||||
|
||||
Tree supports optional controlled `selectedIds` for multi-selection. Its selection callback includes keyboard modifiers and the Shift range across displayed rows only. Consumers own set semantics and geometry identities; existing single-selection callers remain unchanged. Pointer and keyboard selection share the same path. Visibility and information actions do not alter the selection. The living Tree example demonstrates Shift range, Ctrl add and Command toggle.
|
||||
|
||||
|
||||
ColorField screen sampling (owner direction, 2026-11-14): the shared palette includes a Pipette action. In secure browsers supporting EyeDropper, click “Цвет с экрана”, then any screen pixel, including another application or desktop. Escape cancels without a change. Sampling never starts on pointer leave, never captures a screenshot, and is aborted when the control closes, disables or unmounts. Unsupported browsers expose “Системная палитра”; desktop sampling there depends on the native browser/OS picker. Palette/HEX remain usable regardless. This explicit fallback is the approved exception to the old no-native-dialog rule.
|
||||
|
||||
Floating EditorDockLayout tools honor minimumSize on restore, all eight resize edges and keyboard resize. If the available viewport is smaller, they fit that viewport; Inspector fields stack below a 330px content width instead of clipping. Tool footer is separate from the scrolling body; a Button width="full" is the canonical adaptive bottom action. The catalog's scene editor example demonstrates minimum size, a ColorField and fixed reset footer.
|
||||
|
||||
EditorDockLayout: every floating or actively detached tool uses context="scene" Glass V4 (shared scene tint/blur); docking removes that context and retains tiled surface/corner rules. Applies to hierarchy, layers, settings and any other editor tool. No application tint/blur overrides.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
# Shared environment and home
|
||||
|
||||
The owner-approved Mission Core settings anatomy is now canonical, not a screenshot to reproduce. Consumers use UserProfileMenu for the avatar dropdown, EnvironmentSettingsWindow for the settings composition, EnvironmentMediaPlaylistEditor for the list and LandingStage/EnvironmentBackgroundMedia for the home. All geometry and responsive styles live in ui-core.
|
||||
|
||||
The neutral primary Button tone comes from shared tokens, stays white when enabled and gray when disabled across dark/light and accent changes. It does not alter other applications' default primary theme.
|
||||
|
||||
## Consumer contract
|
||||
|
||||
Pass productName, a nonempty stable surfaces list, optional initialSurfaceId, a revision/pages document and save/upload adapters. Each surface references one present page and declares its available quick actions. Workspace IDs are opaque application-owned identifiers. The library owns only draft/form/list/playback behavior; it never imports Mission Core's registry or calls product APIs. Shared data shapes/list functions are exported by ui-core so nonvisual application contracts do not depend on React.
|
||||
|
||||
Settings uses the existing FeatureSettingsWindow/Window focus and Escape behavior. A busy parent disables editing and save; failed saves retain the draft. Each playlist has up to 24 items. Images use the configured delay; a video advances on ended, with one video looping. Failed media is skipped. List display reverses playback order to keep newly added media at the top, as in the accepted source UI.
|
||||
|
||||
The application validates URLs/media bytes, persists uploads and document revisions, handles authentication and rejects stale saves. An upload response provides URL, fileName and mediaKind. A file URL belongs to the storage adapter; an external source must use HTTP(S). No media defaults to an invented graphic. The product may supply status/footer slots without forking the stage.
|
||||
|
||||
## Adoption and validation
|
||||
|
||||
Mission Core passes all existing page definitions and its current operator-environment API. Mission Core Node passes home only and authenticated local presentation storage. Device control never depends on this document. The catalog EnvironmentCatalogDemo exercises the same exported components with an explicitly in-memory save/upload adapter; it is not a persistence service.
|
||||
|
||||
Validate the source migration, TypeScript builds, playlist functions, neutral enabled/disabled DOM contract, dark/light and multiple accents, modal Escape, media order/timing and both consumer persistence adapters. Long-running or physical device acceptance remains application-owned.
|
||||
|
||||
## Product sections (2026-11-08)
|
||||
|
||||
`additionalSections` accepts `{ id, label, icon, group?, content, footer? }`.
|
||||
Use unique IDs other than `environment`. Content and footer are product-owned;
|
||||
the shared shell retains navigation, focus, dragging, Escape and geometry.
|
||||
Environment drafts remain intact when switching sections. Each section owns its
|
||||
loading/error/saving states. No product API is called by the shared library.
|
||||
Mission Core uses this extension for the owner-requested Storage section.
|
||||
|
||||
The canonical `pin` icon is the Lucide Pin glyph. Pair it with IconButton and
|
||||
`aria-pressed` for pinned state; use a busy/disabled state during preparation.
|
||||
An absent local copy and an unpinned copy are separate states.
|
||||
@@ -1,5 +0,0 @@
|
||||
# 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.
|
||||
@@ -29,12 +29,6 @@
|
||||
|
||||
Допустимы density variants, если они имеют устойчивое назначение (`default`, `compact`) и тестируются как часть API.
|
||||
|
||||
## Типографика и операционные сообщения
|
||||
|
||||
Продуктовый интерфейс использует только типографические токены. Browser-default размеры у `h1`–`h6`, `p`, `strong` и form controls не являются допустимым стилем. `--nodedc-font-size-title` разрешён только для заголовка страницы или окна; названия конфигураций, статусы, ошибки, подписи полей и сообщения внутри рабочей сцены используют `md`, `sm`, `xs` или готовую типографику канонического компонента.
|
||||
|
||||
Ошибка сохранения или запроса не рендерится свободным текстовым блоком поверх рабочей сцены. Приложение использует семантический error-state канонического поля либо `ToastStack`, который владеет размером текста, цветом, положением и закрытием. Ошибка автосохранения modeless-инспектора не блокирует закрытие окна: draft остаётся в текущем просмотре, окно закрывается сразу, а сбой показывается неблокирующим error toast.
|
||||
|
||||
## Deprecated
|
||||
|
||||
Перед удалением export:
|
||||
@@ -60,5 +54,3 @@
|
||||
|
||||
У дизайн-системы должен быть явный 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.
|
||||
|
||||
+4
-39
@@ -1,7 +1,5 @@
|
||||
# Иконки
|
||||
|
||||
`info` — информация о выбранном объекте или записи. Иконка используется в стандартном круглом `IconButton`, с доступной подписью и `aria-pressed` для переключаемого обзора. Продуктовое применение: обзор сохранённой сессии Mission Core; одобрено владельцем 2026-09-11.
|
||||
|
||||
Канонический набор собран по реально используемым действиям Launcher/Hub, SEO, BIM Viewer и разрешённым новым участкам Engine. Полные vendor-наборы не являются частью дизайн-системы: наличие SVG в Font Awesome или export в Lucide не делает иконку канонической.
|
||||
|
||||
## Геометрия
|
||||
@@ -18,48 +16,15 @@
|
||||
|
||||
| Группа | Канонические имена |
|
||||
| --- | --- |
|
||||
| Окно и слой | `close`, `plus`, `expand`, `minimize`, `refresh`, `panel`, `apps`, `layers` |
|
||||
| Окно и слой | `close`, `plus`, `expand`, `minimize`, `refresh`, `panel`, `apps` |
|
||||
| Навигация | `chevron-left`, `chevron-right`, `chevron-down`, `grid`, `list`, `sliders`, `search` |
|
||||
| Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external`, `rotate-clockwise` |
|
||||
| Состояние и доступ | `check`, `alert`, `activity`, `lock`, `key`, `shield`, `circle`, `eye`, `eye-off` |
|
||||
| Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external` |
|
||||
| Состояние и доступ | `check`, `alert`, `activity`, `lock`, `key`, `shield`, `circle` |
|
||||
| Сущности | `profile`, `users`, `building`, `globe`, `database`, `network`, `inbox`, `mail` |
|
||||
| Контент | `camera`, `plan`, `play`, `stop`, `image`, `video`, `file`, `folder`, `clipboard`, `settings`, `terminal` |
|
||||
| Контент | `image`, `video`, `file`, `folder`, `clipboard`, `settings` |
|
||||
|
||||
Живая таблица с названиями, поверхностями и размерами находится в разделе `Guideline → Иконки`. Машинный список — в `registry/icons.json`.
|
||||
|
||||
## Правило расширения
|
||||
|
||||
Новая иконка добавляется только после подтверждённого применения в продукте. Нужно выбрать семантическое имя, добавить export в `Icon`, запись в registry и specimen в каталоге. Локальный импорт иконки только ради немного другой формы запрещён.
|
||||
|
||||
`camera` обозначает оптический канал, а `plan` — пространственное представление сверху. Оба glyph контурные и используют общую stroke-геометрию набора.
|
||||
|
||||
`layers` открывает управление видимостью слоёв карты или визуального источника.
|
||||
Применение подтверждено владельцем Mission Core 10.09.2026: кнопка слоёв в
|
||||
заголовке карты Центра наблюдения. `settings` остаётся общей конфигурацией.
|
||||
Кнопка наследует обычные hover, focus, disabled и active-состояния `IconButton`.
|
||||
|
||||
`play` и `stop` — компактные полнотелые транспортные glyph: залитый треугольник запуска и залитый квадрат остановки/паузы. Видимая текстовая подпись не требуется, но action обязан сохранить доступный `aria-label`.
|
||||
|
||||
`terminal` — контурный знак `>_` для входа в консоль и журнал команд.
|
||||
Применение подтверждено владельцем Mission Core 28.09.2026 для ARNavi B2.
|
||||
Это действие использует обычный `IconButton` с доступной подписью; состояния
|
||||
hover, focus, disabled и pending принадлежат кнопке. `activity` остаётся
|
||||
обозначением телеметрии и состояния, а не отправки команд.
|
||||
|
||||
Раскрытие строки вниз: `chevron-down` в закрытом состоянии, `chevron-up` в открытом; кнопка сообщает `aria-expanded` и `aria-controls`.
|
||||
|
||||
`rotate-clockwise` — поворот изображения по часовой стрелке. Применение: независимая ориентация объективов Insta360 в Центре наблюдения Mission Core, по запросу владельца 09.10.2026. Шаг задаёт приложение; подпись кнопки сообщает угол. Состояния и геометрия принадлежат каноническому `IconButton`.
|
||||
|
||||
`power` — штатное выключение компьютера. Запрошено владельцем Mission Core 04.11.2026 для шапки окна «Бортовой компьютер». Используется в стандартном `IconButton` с доступной подписью; недоступность и выполняемое действие блокируют кнопку. Нажатие открывает `ConfirmationModal`; сам glyph не запускает выключение. Живой каталог получает иконку из `registry/icons.json`.
|
||||
|
||||
BIM controls use `ruler` (dimension line with extension lines/arrows), `section` (model intersected by a plane), `isolate` (temporary visibility/glasses), `perspective`/`orthographic` (projection cubes), and `fit-view` (frame extents). `info-plain` is an unframed i for compact tree actions next to the visibility eye; use 14 px for both glyphs. They share the canonical stroke and accessible control behavior.
|
||||
|
||||
Semantic references: [Revit measurement](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-Model/files/GUID-65EA44EC-C777-4C97-8718-5783C3A80B0A.htm), [temporary hide/isolate](https://help.autodesk.com/cloudhelp/2014/ENU/Revit-LT/files/GUID-A5E51D5E-8E18-4834-8A2F-8B4E3E6379A1.htm), [section box](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-GetStarted/files/GUID-C9EA51CB-3214-4BD8-AD55-3BEB1CCD15B6.htm). Glyphs are original monochrome NODE.DC vectors; this does not claim copied Autodesk artwork or full Section Box functionality.
|
||||
|
||||
|
||||
### Блокировка в дереве
|
||||
|
||||
`lock` / `unlock` показывают закрытый / открытый замок. Компактное действие
|
||||
дерева использует прозрачную кнопку без `aria-pressed` и без белой активной
|
||||
подложки; доступное имя описывает действие «Разблокировать» / «Заблокировать».
|
||||
Состояние передаётся формой замка. Уменьшение glyph не уменьшает область нажатия.
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
# KeyButton
|
||||
|
||||
Owner-approved momentary keyboard/pointer visualization (Mission Core, 2026-09-25).
|
||||
Outlined square key surface; pressed is white with black text in every theme.
|
||||
This explicit outline identifies a key, not a decorative panel border.
|
||||
|
||||
`label` is the complete accessible action; children are the short key legend.
|
||||
`pressed` is controlled and never toggled by the component. Native button keyboard
|
||||
semantics, disabled behavior and focus indicator are retained. Consumers own
|
||||
pointer capture and release, keyboard scope, blur/cancel/unmount handling and
|
||||
any domain command lease. A displayed pressed key is not an acknowledgement
|
||||
from equipment. Disabled always renders released. No global listeners exist.
|
||||
|
||||
Catalog includes idle, pressed, disabled and focusable surfaces. Use only for
|
||||
momentary key input, not ordinary actions (Button) or mode choice (SegmentedControl).
|
||||
@@ -1,28 +0,0 @@
|
||||
# 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,36 +0,0 @@
|
||||
# Состояния загрузки
|
||||
|
||||
Общий контракт для Mission Core, Mission Core Node и других NODE.DC consumers. Кольцо рисует ActivityIndicator; место и семантику определяют Button.loading, IconButton.loading или LoadingRegion. Локальные absolute-спиннеры и свободные ActivityIndicator под группой действий запрещены.
|
||||
|
||||
| Причина ожидания | Компонент и место | Завершение |
|
||||
|---|---|---|
|
||||
| Нажата команда | loading только у инициирующей Button/IconButton, по центру внутри её прежних границ | Подтверждение результата, ошибка или timeout команды |
|
||||
| Начальная загрузка содержимого | LoadingRegion вокруг конкретной области, по центру её границ | Первое пригодное содержимое, ошибка или timeout |
|
||||
| Подключение видео | LoadingRegion вокруг смонтированного video/canvas, включая расширенный вид | Первый декодированный кадр; одного ICE connected недостаточно |
|
||||
| Фоновое обновление с доступным содержимым | loading у явной кнопки обновления; без overlay при автоматическом polling | Ответ запроса или ошибка |
|
||||
| Измеряемая многошаговая подготовка | Существующий ProgressBar/ResourceRow.progress и статусы этапов | Результат этапа/операции |
|
||||
| Ошибка, offline, отсутствие свежих кадров | Конечный статус и разрешённое действие повторения | Не оставлять бесконечный spinner |
|
||||
|
||||
Приложение хранит pending по device ID, session и конкретному action key. Блокировка соседних несовместимых действий не делает их загружающимися. Для одной команды показывается один индикатор; последующее получение содержимого — отдельный этап. Элемент управления сохраняет размеры, надпись для screen reader и свой порядок в layout; spinner не добавляет строку и не сдвигает соседей. Повторная активация pending-кнопки блокируется native disabled.
|
||||
|
||||
LoadingRegion не размонтирует video/canvas и не присваивает область страницы целиком. Визуализатор задаёт собственную стабильную высоту/aspect ratio; индикатор центрируется относительно этой области и автоматически следует её normal/expanded размеру. Компонент не блокирует управление сам: consumer отключает только конфликтующие действия. Закрытие просмотра остаётся доступным.
|
||||
|
||||
Владелец операции задаёт начало и конец ожидания. Компоненты не запускают запросы, не выдумывают проценты, не повторяют операции и не скрывают ошибки по таймеру. Reduced motion сохраняет статическое кольцо. Button сохраняет accessible name и aria-busy; LoadingRegion имеет один status с label, декоративное кольцо скрыто от accessibility tree.
|
||||
|
||||
```tsx
|
||||
<Button loading={pending === 'save'} onClick={save}>Сохранить</Button>
|
||||
<IconButton label="Обновить" loading={pending === 'refresh'} onClick={refresh}><Icon name="refresh" /></IconButton>
|
||||
<LoadingRegion loading={connecting || awaitingFirstFrame} label="Ожидаем изображение">
|
||||
<video autoPlay muted playsInline />
|
||||
</LoadingRegion>
|
||||
```
|
||||
|
||||
Living catalog показывает action, icon-action и content loading. Изменение согласовано владельцем08.09.2026 для обоих Mission Core consumers. Локальный кандидат включается в hash-bound Ubuntu source artifact; внешний package release в рамках этой задачи не публикуется.
|
||||
|
||||
## Проверка кандидата 08.09.2026
|
||||
|
||||
N09: typecheck, registry validation, четыре loading contract tests и production catalog build прошли. В браузере проверены light/dark и два accent colors: loading не меняет размер Button/IconButton, кольцо сохраняет нейтральный цвет, content status центрируется вместе с подписью. В Mission Core проверены pending read-only action, video first frame, normal/expanded/Escape и terminal error: mounted video сохраняется, после кадра или ошибки лишних индикаторов нет. Тот же shared frontend включён в установленный Node0.8.18; отдельная визуальная проверка native Node shell остаётся задачей consumer acceptance.
|
||||
|
||||
### Composed content
|
||||
|
||||
Use `<LoadingRegion aggregate loading={ownPending} label="Loading equipment">` around a composed surface. Descendant `LoadingRegion`s register pending state without drawing another indicator. All visible nested initial requests share exactly one surface indicator. A terminal error or unmount releases the lease; background refresh with usable data must not register. Independent modal Windows reset the scope. Button operations retain their own progress. Do not aggregate unrelated observation panes.
|
||||
@@ -1,7 +1,7 @@
|
||||
# Shared Cesium React adapter
|
||||
|
||||
`@nodedc/map-cesium-react 0.1.2` is the shared renderer boundary for the
|
||||
canonical `Map Page 0.1.0` and CesiumJS `1.147.0`.
|
||||
`@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`.
|
||||
|
||||
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.147.0`.
|
||||
Cesium `1.143.0`.
|
||||
- Canonical assets are fixed to imagery `2`, terrain `1` and buildings
|
||||
`96188`.
|
||||
- Provider endpoint documents must declare `credentialMode=gateway`.
|
||||
@@ -95,11 +95,3 @@ 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"`).
|
||||
|
||||
+2
-19
@@ -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.147
|
||||
## Cesium adapter 1.143
|
||||
|
||||
Текущий reference adapter использует CesiumJS `1.147.0`. Он загружается отдельным lazy chunk только при открытии Map Page и преобразует только declared Application bindings в реальные Cesium entities. Пустая Map Page не содержит domain entities.
|
||||
Текущий reference adapter использует CesiumJS `1.143.0`. Он загружается отдельным lazy chunk только при открытии Map Page и преобразует только declared Application bindings в реальные Cesium entities. Пустая Map Page не содержит domain entities.
|
||||
|
||||
Server-side runtime contract:
|
||||
|
||||
@@ -319,20 +319,3 @@ 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.
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
# NavigationCube
|
||||
|
||||
Owner-requested on 2026-10-21 for semantic editing. Reference: BIM Viewer `frontend/dcViewer.js` NavCube, size 100; Xeokit renderer coupling is replaced by a controlled SVG adapter, with no extra GPU context.
|
||||
|
||||
`quaternion` is camera-to-world, Y up; `onSelect([x,y,z])` points from target to camera. Six face centres, twelve edge directions and eight corner directions. Adjacent face regions share the same direction. The consumer preserves framing, projection and semantic data. The cube reflects free camera rotation. Projection is a separate explicit control. Top is +Y, front is +Z, right is +X; domain adapters convert coordinate conventions.
|
||||
|
||||
Visible hit regions have native tooltips, hover, keyboard focus, Enter/Space activation and disabled state. Face/edge strokes are structural. Tokens own colors. No motion or GPU loop in the component. Catalog controls section demonstrates the cube.
|
||||
|
||||
`add-point` is a centered circled plus, distinct from whole-element `plus`. Projection icons: `orthographic`, `perspective`.
|
||||
|
||||
Presentation props: `size` in CSS pixels (default 66), `face`, `text`, `edge`, `hover`, `hoverText`, `opacity`. Consumer preferences may persist these; omitted colors inherit theme tokens. Core exposes these under viewport settings → 3D-куб.
|
||||
|
||||
Face labels use the projected face-local right/up basis, including foreshortening and rotation; they never billboard towards the screen. `edgeOpacity` (0–1, default 1) independently controls structural grid/edge strokes without fading faces or labels.
|
||||
|
||||
`faceOpacity` (0–1, default 1) controls polygon fill only. It is independent of `edgeOpacity`, text and the legacy overall `opacity`; a transparent face remains a navigation target.
|
||||
@@ -1,66 +0,0 @@
|
||||
# Компактная операционная типографика
|
||||
|
||||
Уточнение владельца 06.09.2026 для Mission Core / Node, обязательное для
|
||||
общих компонентов NODE.DC. Повторяющиеся сообщения и подписи не оформляются
|
||||
крупными заголовками. Этот документ зарегистрирован в registry/registry.json.
|
||||
|
||||
- Заголовок страницы или окна: только предусмотренный шаблоном title-токен.
|
||||
- Заголовок секции, SettingsCard, короткое сообщение пустого списка: md
|
||||
(0.8125rem / 13 px при стандартном корневом размере), без увеличения через h2.
|
||||
- Описание, пояснение, сведения о состоянии: sm (0.75rem / 12 px).
|
||||
- Технические метаданные: xs либо типографика ResourceRow.
|
||||
- Browser-default h1–h6/p/strong и локальные крупные размеры запрещены.
|
||||
- Размер не умножается из-за вложенности карточек, ошибки или отсутствия данных.
|
||||
|
||||
SettingsCard и nodedc-empty-state закрепляют эти размеры в ui-core. Текст
|
||||
«Устройства не обнаружены» не является заголовком нового раздела. В живом
|
||||
каталоге рядом со строками ресурсов есть пример пустого списка.
|
||||
|
||||
В завершённом этапе настройки окружения status-слот ResourceRow содержит
|
||||
только Icon check с доступным названием. Галочка не оборачивается в StatusBadge,
|
||||
Checker, круг, pill или кнопку. Это знак результата, а не интерактивный контрол.
|
||||
Лампочка состояния устройства отдельно использует StatusBadge indicator.
|
||||
|
||||
Explanatory paragraphs use `Description`, the same contract as `SettingsCard.description`: inherited font family, regular 400, `--nodedc-font-size-sm`, `--nodedc-text-muted`, line-height 1.4 and zero paragraph margins. Applications must not create feature-specific equivalents.
|
||||
|
||||
Защита компонента: обычный `p` без класса внутри тела `SettingsCard` получает
|
||||
тот же стиль описания, включая вложенные группы. Это страховка для прежних
|
||||
потребителей, а не замена `Description` в новом коде. Статусы ожидания и
|
||||
пояснения вне карточки также используют `Description` с `role="status"`, если
|
||||
нужно объявление для скринридера. Заголовки, значения полей и кнопки сохраняют
|
||||
собственную типографику; глобальный стиль для всех `p` страницы не вводится.
|
||||
|
||||
|
||||
## Обязательная проверка сборки — 10.11.2026
|
||||
|
||||
Операционный UI имеет собственный базовый `md` (13 px), в том числе портальные
|
||||
`Window`, `WorkspaceWindow`, `ApplicationPanel` и `AdminPanel`. Размер body
|
||||
внешнего приложения не является контрактом. Корневой размер `html` не меняется:
|
||||
rem и пользовательское масштабирование остаются доступными. Семантические
|
||||
h1–h6 внутри этих поверхностей по умолчанию используют md, а явные канонические
|
||||
заголовки страницы/окна — title (18 px). Значения и заголовки секций — md;
|
||||
пояснения, ошибки, ожидание и результат команды — `Description` / sm (12 px).
|
||||
|
||||
Правило исполняется модулем `@nodedc/ui-core/typography` и обязательным
|
||||
`npm run test:typography` Design Guideline. Mission Core запускает
|
||||
`check:typography` перед сборкой Control Station и Node UI, а также в полном
|
||||
наборе unit-тестов. Проверяется исходный код всех экранов, общих пакетов и
|
||||
frontend-плагинов, а не только последний изменённый компонент.
|
||||
|
||||
Проверка запрещает новые локальные размеры вместо токенов, lg/title для данных,
|
||||
увеличивающие calc/clamp/em, font shorthand, inline fontSize и обычные p без
|
||||
явного класса. Сохранившиеся компактные значения старого UI (не более 13 px)
|
||||
зафиксированы по файлу, селектору и значению в `typography-policy.json`;
|
||||
добавлять туда новый UI запрещено. При изменении такого правила его переводят
|
||||
на токен, запись удаляют. Список не допускает крупных значений даже при ошибочном
|
||||
добавлении. Исключения перечислены отдельно с причиной и точным выражением:
|
||||
существующая обложка LandingStage, подписи в координатах SVG и управляемый
|
||||
пользователем масштаб сцены. Они не разрешают увеличивать текст рабочих панелей.
|
||||
Начальный размер значений батареи — 13 px; сохранённый пользователем масштаб
|
||||
3D-сцены не перезаписывается.
|
||||
|
||||
Изменение шкалы токенов, списка ролей или исключений требует явного решения
|
||||
владельца продукта и обновления живого каталога. Нельзя ослаблять проверку ради
|
||||
одного экрана, закрывать проблему локальным font-size или менять масштаб html.
|
||||
При приёмке проверяют computed font-size в обычном и плавающем окне, на узкой
|
||||
ширине, а также ожидание, ошибку, пустое состояние и результат команды.
|
||||
@@ -1,18 +0,0 @@
|
||||
# ProgressBar
|
||||
|
||||
Владелец Mission Core 05.09.2026 явно запросил горизонтальную заполняющуюся
|
||||
полосу вместо кружка и точки в строке подготовки устройства. Общий компонент
|
||||
добавлен в Design Guideline до подключения в Node/Core.
|
||||
|
||||
`value` — завершённая доля 0…1; NaN/Infinity трактуются как неизвестная величина,
|
||||
выход за границы ограничивается. Без value используется движущийся сегмент,
|
||||
aria-valuenow отсутствует. `label` обязателен; `valueText` описывает текущий этап.
|
||||
Нет интерактивности и focus. Темы используют существующие семантические токены.
|
||||
При reduced motion движение выключено, видимый сегмент сохраняется.
|
||||
|
||||
ResourceRow.progress занимает свободное место между текстом и actions, скрывает
|
||||
status, на узком экране переносится ниже текста. Готовность не вычисляется
|
||||
компонентом. Каталог содержит завершённый, определённый и неизвестный прогресс.
|
||||
|
||||
Размер полосы задаётся опциональным `--nodedc-progress-height`; по умолчанию
|
||||
используется `--nodedc-space-2`. Плотность не меняет поведение и ARIA-состояния.
|
||||
@@ -1,22 +0,0 @@
|
||||
# ProgressButton
|
||||
|
||||
Принят владельцем Mission Core 10.10.2026: этап чуть выше центра кнопки,
|
||||
заполняющаяся полоса ниже, слева слои последовательно опускаются и проседают.
|
||||
|
||||
`label` — стабильное имя действия; `progress?: { label, value?, valueText? }`
|
||||
— текущая фаза с измеренной долей 0…1. Без доли полоса неопределённая.
|
||||
При наличии progress кнопка блокирует повторный запуск, сохраняет читаемость
|
||||
и сообщает aria-busy. После ошибки consumer убирает progress, возвращая запуск;
|
||||
ошибка передаётся обычным каналом приложения. `disabled` отдельно закрывает
|
||||
действие без объявления несуществующей активности. Управление, отмена и жизненный
|
||||
цикл остаются у приложения. Высота стандартного Button не меняется.
|
||||
|
||||
ProgressBar расположен визуально внутри кнопки, но в DOM является соседним
|
||||
элементом: его доступная семантика не теряется внутри нативного button.
|
||||
Текущее описание связано через aria-describedby; role=status сообщает фазу.
|
||||
Tab/Enter/Space работают как у Button; pending исключает повторную активацию.
|
||||
|
||||
`LayerStackIndicator` использует существующий `Icon name="layers"`, без нового
|
||||
знака или зависимости. Анимация не вычисляет процент. При reduced motion
|
||||
оставляет неподвижный знак; статус и измеренная полоса остаются доступны.
|
||||
Каталог показывает idle, disabled, определённый и неопределённый progress.
|
||||
@@ -1,34 +0,0 @@
|
||||
# ResourceRow и ResourceList
|
||||
|
||||
Владелец 2026-09-05 запросил перенос существующих длинных строк Mission Core
|
||||
AI Inference в Node с повторным использованием Design Guideline. Источник:
|
||||
ObservatoryWorkspace / observatory-evidence-card. Это выделение существующего
|
||||
оформления в общий компонент, без лабораторной модели данных.
|
||||
|
||||
`ResourceList` содержит обычные `li`; внутри — `ResourceRow` с обязательным
|
||||
`title`, опциональными `icon`, `description`, `metadata`, `status`, `actions`.
|
||||
Слоты действий принимают канонические Button/IconButton. Клик по всей строке
|
||||
не назначается: самостоятельные действия имеют свои доступные подписи и focus.
|
||||
|
||||
Геометрия источника сохранена: минимум 4.25rem, отступы .7/.85rem, значок
|
||||
2.15rem, компактный радиус и существующие токены поверхности/типографики.
|
||||
Длинное название переносится; метаданные сокращаются визуально, полный текст
|
||||
можно передать через title. На узком экране статус и действия переходят ниже.
|
||||
|
||||
Состояния поставляет consumer: нормальное, пустой список, загрузка, ошибка,
|
||||
недоступное действие. Pending отмечается aria-busy и ActivityIndicator;
|
||||
disabled и keyboard/focus остаются у общего контрола. Строка не объявляет
|
||||
объект доступным или подключённым самостоятельно.
|
||||
|
||||
Пример находится в живом каталоге, раздел «Контролы → Строки ресурсов».
|
||||
|
||||
Для длительных операций с линейной индикацией используйте `progress`
|
||||
(ProgressBar: label, value, valueText). Он заменяет status, оставляет действия
|
||||
справа и занимает промежуток после названия.
|
||||
|
||||
`statusPlacement="leading"` размещает компактный индикатор после иконки и
|
||||
перед всем текстовым блоком, с выравниванием по вертикальному центру строки.
|
||||
По умолчанию остаётся `trailing` перед действиями. Статус не дублируется;
|
||||
во время `progress` он скрыт в любом положении. Для одной лампы используйте
|
||||
StatusBadge variant="indicator" с aria-label и title. Это согласованное
|
||||
06.09.2026 расположение индикатора устройств Mission Core / Node.
|
||||
+50
-66
@@ -1,82 +1,66 @@
|
||||
# Темы и цвет приложения
|
||||
|
||||
## Один фундамент
|
||||
## Основное правило
|
||||
|
||||
С 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`.
|
||||
Приложение выбирает тему, а не повторяет цвета, селекторы или устройство компонентов.
|
||||
NODE.DC-приложения отличаются цветовой схемой, а не набором заново нарисованных компонентов. Тема задаёт значения CSS custom properties. Компоненты сохраняют геометрию, состояния и поведение.
|
||||
|
||||
```ts
|
||||
import {applyNodedcTheme, missionDarkTheme} from '@nodedc/ui-core';
|
||||
applyNodedcTheme(document.documentElement, missionDarkTheme);
|
||||
```
|
||||
## Что меняет тема
|
||||
|
||||
Те же exports доступны из `@nodedc/ui-dom`. `applyNodedcTheme(root)` по умолчанию
|
||||
выбирает `dark / mission / flat`. `missionLightTheme` сохраняет общую геометрию
|
||||
и даёт светлую тему. Установка на `document.documentElement` обязательна для
|
||||
приложения с порталами: меню и модальные окна получают тот же профиль.
|
||||
- canvas/background;
|
||||
- основной и вторичный текст;
|
||||
- accent и автоматически вычисляемый on-accent;
|
||||
- цвет непрозрачных application surfaces;
|
||||
- field/control surfaces;
|
||||
- overlay;
|
||||
- тени controls и modal material;
|
||||
- semantic success/warning/danger tones при необходимости.
|
||||
|
||||
## Роли поверхностей
|
||||
## Что тема не меняет
|
||||
|
||||
| Роль | Тёмная тема | Компонент |
|
||||
| --- | --- | --- |
|
||||
| Фон приложения | `#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 |
|
||||
- высоту контролов;
|
||||
- радиусы по классам компонентов;
|
||||
- положение логотипа;
|
||||
- механику окна и dropdown;
|
||||
- DOM anatomy;
|
||||
- keyboard behavior;
|
||||
- расположение footer actions;
|
||||
- API React/DOM компонентов.
|
||||
|
||||
ApplicationPanel → SettingsCard → поля — композиция, проверенная в работающих
|
||||
настройках Mission Core. Сетка полей прозрачная, без отдельной подложки и отступов.
|
||||
Самостоятельный элемент коллекции может использовать GlassSurface tone="group":
|
||||
тот же нейтральный материал SettingsCard, а не почти чёрный canvas-soft.
|
||||
Не добавлять карточку вокруг списка карточек или вокруг каждого поля; максимум
|
||||
два уровня групп сохраняют отличие непрозрачного поля от подложки.
|
||||
## Presets
|
||||
|
||||
Исправление 2026-11-05: прежний пример с tone="soft" ошибочно переносил цвет
|
||||
вторичного canvas в формы. Значение soft сохранено для его исходной роли;
|
||||
приложения исправляют композицию, а не перекрашивают canvas локальным CSS.
|
||||
В baseline включены `dark` и `light`. Это не два отдельных продукта, а примеры одного контракта:
|
||||
|
||||
Основной/вторичный/приглушённый/недоступный текст использует оттенок
|
||||
`247 248 244` с непрозрачностью `.96 / .72 / .48 / .34`. Состояния hover,
|
||||
active, focus, disabled задаёт библиотека; приложения не переопределяют их.
|
||||
Hover поля использует собственный непрозрачный материал, а не полупрозрачную
|
||||
заливку кнопки: поле не исчезает при наведении.
|
||||
Декоративные рамки и контуры отсутствуют. Клавиатурный фокус остаётся видимым
|
||||
через контрастную заливку. Success/warning/danger сохраняют смысловые цвета
|
||||
индикаторов; цвет акцента не подменяет состояние ошибки.
|
||||
- dark соответствует текущей основной семье Launcher/Hub/CMS;
|
||||
- light воспроизводит SEO-поверхности: `#ececec` canvas, белые панели и поля, тёмный текст, чёрные primary actions и мягкую тень у белых secondary controls;
|
||||
- конкретный продукт может поверх preset задать свой accent и surface variables.
|
||||
|
||||
## Акцент и настройки
|
||||
## Accent
|
||||
|
||||
Базовый акцент тёмной темы — `247 248 244`, светлой — `24 25 28`.
|
||||
Пользовательский `accent` остаётся допустимой настройкой активных контролов.
|
||||
`on-accent` вычисляется библиотекой по яркости. Нейтральное основное действие
|
||||
остаётся нейтральным. Возврат к теме вызывает `clearNodedcAccent(root)`, затем
|
||||
`applyNodedcTheme`; удалять пользовательское значение без явного сброса нельзя.
|
||||
Материалы можно исследовать в каталоге; приложения не должны хранить собственный
|
||||
набор цветов для восстановления стандартной темы.
|
||||
Accent задаётся RGB tuple. On-accent вычисляется по luminance и не должен вручную прописываться белым или чёрным в отдельном компоненте.
|
||||
|
||||
В светлой теме canvas — `#ececec`, панели и поля — белые, группы и вложенные
|
||||
области — `#f4f4f4`. Белое поле различимо внутри группы.
|
||||
Map-glass остаётся отдельным светлым полупрозрачным материалом над изображением;
|
||||
он не заменяет обычную тему форм, панелей и портальных окон.
|
||||
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.
|
||||
|
||||
## Проверка и совместимость
|
||||
Semantic status не обязан совпадать с accent. Например, ошибка остаётся danger, даже если приложение использует красный брендовый accent.
|
||||
|
||||
Living catalog: Controls → Mission Core. Проверяются вложенная форма, текст,
|
||||
select, textarea, disabled, переключатель, статус и то же содержимое в портальном
|
||||
окне; дополнительно проверяются клавиатура и обе темы. CMS использует этот же
|
||||
профиль и immutable npm-пакеты, не копию исходников компонентов.
|
||||
## Область применения
|
||||
|
||||
`appearance: "default", edges: "default"` оставлены для явной совместимости
|
||||
со старой презентацией компонентов. Новые потребители используют Mission.
|
||||
Эта ревизия не меняет локальный Mission Core и его незакоммиченные эксперименты.
|
||||
Его прежние локальные CSS-дубли зафиксированы как миграционный долг: перенос
|
||||
зависимости требует отдельной проверки приложения, а не незаметной замены пакетов.
|
||||
Тема может быть установлена:
|
||||
|
||||
- на корневом `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.
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
# Интерфейс внутри 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.
|
||||
@@ -28,7 +28,7 @@
|
||||
7. trigger, полностью ушедший за viewport, закрывает surface;
|
||||
8. outside pointer и Escape закрывают surface;
|
||||
9. после Escape фокус возвращается на trigger;
|
||||
10. открытие другого корневого dropdown закрывает предыдущий; вложенные меню сохраняют предков, а Escape закрывает только самый глубокий слой.
|
||||
10. открытие другого dropdown закрывает предыдущий.
|
||||
|
||||
Inline absolute dropdown внутри card/sidebar/sticky container является дефектом.
|
||||
|
||||
@@ -115,73 +115,3 @@ map-glass дизайне, что Objects.
|
||||
Библиотека не создаёт глобальный store окон. Приложение владеет тем, какое окно открыто и какие данные в нём загружены. Библиотека владеет одинаковым поведением самого слоя.
|
||||
|
||||
Stack workspace-окон остаётся контролируемым приложением: оно передаёт active-state и `zIndex`, а компонент отвечает только за одинаковую геометрию и взаимодействие. Глобальный stack viewport-level modeless-окон остаётся отдельным будущим контрактом.
|
||||
|
||||
## Контекстные действия заголовка
|
||||
|
||||
`Window.headerActions` и `FeatureSettingsWindow.headerActions` принимают канонические `IconButton`. Обновление содержимого находится рядом с закрытием; сохранение и отмена формы остаются в footer. Слот входит в focus trap окна, а клики по действиям не начинают перетаскивание. Pending/disabled задаёт владелец данных; закрытие остаётся доступным.
|
||||
|
||||
На узком экране центрированное окно учитывает padding своего overlay с обеих сторон. В `FeatureSettingsWindow` меню занимает высоту содержимого, а оставшаяся высота отдана прокручиваемой форме. Проверочный пример «Настройки модуля» находится в живом каталоге окон; проверять в том числе на ширине 390 px.
|
||||
|
||||
FeatureSettingsWindow owns two independent scrollports. Its outer body is overflow-hidden; both navigation and content are min-height:0, overflow:auto, keyboard-focusable and overscroll-contained. Long left menus never move the right body. At narrow widths navigation remains capped and the content receives the remaining height.
|
||||
|
||||
Selecting a different settings section resets only its content scroll to the top; navigation keeps its position.
|
||||
|
||||
Docked content declares minimumSize for both axes. The divider stops at the recursive content boundary; a small overall viewport scrolls the layout canvas.
|
||||
|
||||
`DockLayout.panels[].preferredSize` задаёт начальный компактный размер. Продукт передаёт его только для новой раскладки без сохранённой геометрии; первый resize/dock сохраняет пользовательскую геометрию. Минимумы продолжают действовать при всех последующих размерах.
|
||||
|
||||
## Free-window mode for centered windows
|
||||
|
||||
A centered `Window` exposes the semantic `move` icon beside close (`allowFloating`, true by default). The toggle retains the mounted contents and captures their current dimensions. In floating mode the backdrop has no dimming or blur and passes interaction to the background; body scrolling and focus trapping are released. Drag the header or resize from any of the eight invisible border regions. No hover handles or decorative resize marks are drawn. Edges and corners expose their directional resize cursor; the movable header uses the move cursor. Keyboard users focus the header and use arrows to move or Shift+arrows to resize. Geometry is clamped on manipulation and viewport resize.
|
||||
|
||||
Turning the free mode off returns the same contents to the normal centered size and modal semantics. Turning it on again during the same opening restores the floating rectangle. Closing clears it. Portal ownership remains the active fullscreen element or body. Nested dialogs keep their own modal behavior. Inspector controls inside windows stretch to available width.
|
||||
|
||||
## Сохранённая геометрия инструментов
|
||||
|
||||
`Window.rect: WindowRect` и `onRectCommit` позволяют приложению хранить геометрию в своём документе. Для `placement="end" resizable` размеры и координаты восстанавливаются при открытии и при внешнем undo/import. Перетаскивание и resize обновляются локально; callback вызывается один раз при завершении жеста. Клавиатурный шаг тоже фиксируется. Автоматическое вписывание в уменьшенный экран не перезаписывает сохранённый прямоугольник. Без `rect` остаётся прежнее поведение `initialRect`. Пример дерева объектов в каталоге сохраняет прямоугольник между открытиями.
|
||||
|
||||
Действия уменьшения/увеличения содержимого палитр используют канонические `IconButton` с иконками `minus` / `plus` в `headerActions`, рядом с закрытием. Их прикладной масштаб хранится вместе с документом.
|
||||
|
||||
## Scene editor workspace and detachable tools
|
||||
|
||||
`EditorWorkspace` opens the same mounted content in a separate modeless editing window, then returns it to the original inline slot. Back, close and finishing editing share `onBack`; fullscreen is local to this editing window. The fixed header is not a docking target. The application retains its original view height, layout and camera document. The renderer host is moved atomically with `moveBefore` when available; canvas-based renderers remain mounted with the append fallback too.
|
||||
|
||||
`EditorDockLayout` receives `value: EditorDockState`, `onChange`, a locked `primary`, and typed `tools`. Tool descriptors supply title, open/close, content, actions, footer, minimum size and optional initial floating rectangle. The primary cannot detach. Each tool keeps its DOM host when docked, floating or temporarily hidden. The split tree, floating rectangles and any application-owned palette scale belong to the scene document, not a global library store.
|
||||
|
||||
Drag a tool header to any of four outer edges to create a full-side area; drop over another tool to split beside it. Drop in the primary center to detach. An exact destination preview is shown only during placement. A 24 px outer zone wins over panel targets; broader magnets reach 160 px horizontally / 96 px vertically, capped at 16% of the workspace. The center of a tool chooses its nearest side, never swaps it with the primary. Split minima protect content; small viewports scroll the bounded layout. Invisible floating edges resize, and only the cursor changes.
|
||||
|
||||
Header Enter/Space begins keyboard docking, arrows choose an edge, Shift+arrows choose the whole workspace, Tab selects a tool, Home selects floating, Enter commits and Escape cancels. Floating headers also accept arrows to move and Shift+arrows to resize. Pointer cancellation and Escape restore the uncommitted layout. Automatic viewport fitting does not overwrite stored rectangles. The living catalog includes the same workspace with a fixed scene, outliner and material palette.
|
||||
|
||||
When an EditorWorkspace detaches from a Window, the owning overlay is suspended
|
||||
without unmounting its children. Its backdrop and focus trap are inactive until
|
||||
the editor returns. Escape/Tab belong to the focused dialog, so nested settings
|
||||
close without also closing the battery/detail window.
|
||||
|
||||
|
||||
Portal typography is self-contained: Window text base is md/13 px, its title is title/18 px, and explanatory/status paragraphs use Description/sm/12 px. This stays identical in centered and floating modes and is independent of the host body size.
|
||||
|
||||
`EditorWorkspace purpose="view"` reuses the same stable host and docking grammar for viewers. Back/close return the mounted view to its inline slot; no edit-completion action is shown. Optional `headerActions` keeps application actions in the fixed window header. The default `purpose="edit"` preserves existing editors. The living docking example demonstrates both purposes.
|
||||
|
||||
Dock tool headings inherit the focused drag-header foreground, including title and subtitle, so the canonical inverted keyboard-focus fill retains readable text.
|
||||
|
||||
Keyboard-focused dock headers keep their action/close glyphs on the inherited contrast color, as well as title/subtitle.
|
||||
|
||||
Tool minimumSize governs floating and docked geometry alike, including restored JSON, pointer and keyboard resize. Screen bounds take priority when smaller. Put fixed bottom actions in EditorDockTool.footer; never append them to scrollable inspector content.
|
||||
|
||||
The primary scene owns an isolated stacking context so its toolbars stay behind floating tools. A tool outer shell clips without scrolling; only its body scrolls, keeping header/footer fixed even when a field receives focus.
|
||||
|
||||
ColorField spectrum has no decorative perimeter stroke; retain its visible sampling marker and keyboard focus. UserProfileMenu variant=header owns its HeaderProfile surface; consumers must not wrap it in another HeaderProfile.
|
||||
|
||||
## 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
+57
-89
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "nodedc-design-guideline",
|
||||
"version": "0.7.1",
|
||||
"version": "0.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "nodedc-design-guideline",
|
||||
"version": "0.7.1",
|
||||
"version": "0.7.0",
|
||||
"workspaces": [
|
||||
"packages/*",
|
||||
"apps/*"
|
||||
@@ -28,9 +28,9 @@
|
||||
"version": "0.7.0",
|
||||
"dependencies": {
|
||||
"@nodedc/page-patterns": "0.1.0",
|
||||
"@nodedc/ui-core": "0.7.4",
|
||||
"@nodedc/ui-react": "0.7.10",
|
||||
"cesium": "1.147.0",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-react": "0.7.0",
|
||||
"cesium": "^1.143.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
@@ -325,63 +325,36 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"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==",
|
||||
"version": "26.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/engine/-/engine-26.1.0.tgz",
|
||||
"integrity": "sha512-WzeJEcmGD7/htBJ8JEZt95OgZjErPwUHqyAlJY/mCzmDm7hfwpuucLBSUhiynWW3khqBT1C7dhibjb7tdic7oA==",
|
||||
"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.9.0",
|
||||
"@zip.js/zip.js": "^2.8.1",
|
||||
"autolinker": "^4.0.0",
|
||||
"bitmap-sdf": "^1.0.3",
|
||||
"dompurify": "^3.4.14",
|
||||
"draco3d": "1.5.7",
|
||||
"dompurify": "^3.3.0",
|
||||
"draco3d": "^1.5.1",
|
||||
"earcut": "3.0.2",
|
||||
"grapheme-splitter": "^1.0.4",
|
||||
"jsep": "^1.3.8",
|
||||
"kdbush": "^4.1.0",
|
||||
"ktx-parse": "^2.0.0",
|
||||
"kdbush": "^4.0.1",
|
||||
"ktx-parse": "^1.0.0",
|
||||
"lerc": "^2.0.0",
|
||||
"mersenne-twister": "^1.1.0",
|
||||
"meshoptimizer": "^1.2.0",
|
||||
"meshoptimizer": "^1.0.1",
|
||||
"pako": "^3.0.0",
|
||||
"protobufjs": "^8.8.0",
|
||||
"protobufjs": "^8.6.5",
|
||||
"rbush": "^4.0.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"urijs": "^1.19.7"
|
||||
},
|
||||
"engines": {
|
||||
"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": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@cesium/wasm-splats": {
|
||||
@@ -391,17 +364,16 @@
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@cesium/widgets": {
|
||||
"version": "16.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/widgets/-/widgets-16.3.1.tgz",
|
||||
"integrity": "sha512-eyAGPYYL4v/WeLasmphRwxFcCl/qeTcRhncbBlOzMTSTLjgjZSea0IcEDCKC2ip/mHPeGe887X84xi1SV8mcEQ==",
|
||||
"version": "16.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@cesium/widgets/-/widgets-16.1.0.tgz",
|
||||
"integrity": "sha512-c+jt8F3YIZs2x6+X+HS4q0S9nd2jVcbPVShUmlrDK1s+C7IlEvXceDGrkjivHRElAVCzfaWEEwY1g7Lg5HCGmA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@cesium/core": "^0.1.1",
|
||||
"@cesium/engine": "^26.5.0",
|
||||
"@cesium/engine": "^26.1.0",
|
||||
"nosleep.js": "^0.12.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.17.0"
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
@@ -1461,9 +1433,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@zip.js/zip.js": {
|
||||
"version": "2.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.25.0.tgz",
|
||||
"integrity": "sha512-oNRqUuU1XFu6G5d7Z0jufJ9dS9WteO0xiU/PNxsUrb4itZCsSbn191jpJzU00Gmc6S680X3DPZeF5EV4zAEMAg==",
|
||||
"version": "2.8.26",
|
||||
"resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.8.26.tgz",
|
||||
"integrity": "sha512-RQ4h9F6DOiHxpdocUDrOl6xBM+yOtz+LkUol47AVWcfebGBDpZ7w7Xvz9PS24JgXvLGiXXzSAfdCdVy1tPlaFA==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"bun": ">=0.7.0",
|
||||
@@ -1611,26 +1583,22 @@
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/cesium": {
|
||||
"version": "1.147.0",
|
||||
"resolved": "https://registry.npmjs.org/cesium/-/cesium-1.147.0.tgz",
|
||||
"integrity": "sha512-gY5TF0rSyIMtnSIFHUuiHnrCuhdKaHUzLWFcjxytsdheKfKtYYOWicIWMypGjwYfnmJrgPgNF7HNjO9SK/JIkw==",
|
||||
"version": "1.143.0",
|
||||
"resolved": "https://registry.npmjs.org/cesium/-/cesium-1.143.0.tgz",
|
||||
"integrity": "sha512-EHz61NBp/2UPYE4iWCZ+YK9Jcb0d2hzRfqkj4DRaUM3cJmA9hE2FTmcPPZ2iL7w+W0YUScI0gc9XeSTXlPIQtA==",
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
"packages/core",
|
||||
"packages/gltf",
|
||||
"packages/engine",
|
||||
"packages/widgets",
|
||||
"packages/sandcastle"
|
||||
],
|
||||
"dependencies": {
|
||||
"@cesium/core": "^0.1.1",
|
||||
"@cesium/engine": "^26.5.0",
|
||||
"@cesium/gltf": "^0.1.1",
|
||||
"@cesium/widgets": "^16.3.1",
|
||||
"protobufjs": "^8.8.0"
|
||||
"@cesium/engine": "^26.1.0",
|
||||
"@cesium/widgets": "^16.1.0",
|
||||
"protobufjs": "^8.6.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.17.0"
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
@@ -1697,9 +1665,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.4.18",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.18.tgz",
|
||||
"integrity": "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==",
|
||||
"version": "3.4.12",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.12.tgz",
|
||||
"integrity": "sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
@@ -1905,12 +1873,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsep": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/jsep/-/jsep-1.6.0.tgz",
|
||||
"integrity": "sha512-Y8Tr54CX7B5YGAwo7/n8eumidEX3Opx98RyyQVnlHqUaZcPA8uUzL2v1rshr9ypW9Q6hNjfJtg3sL+8kaNE7TA==",
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/jsep/-/jsep-1.4.0.tgz",
|
||||
"integrity": "sha512-B7qPcEVE3NVkmSJbaYxvv4cHkVW7DQsZz13pUMrfS8z8Q/BuShN+gcTXrUlPiGqM2/t/EEaI030bpxMqY8gMlw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 20.16.0"
|
||||
"node": ">= 10.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jsesc": {
|
||||
@@ -1946,9 +1914,9 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ktx-parse": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-2.0.0.tgz",
|
||||
"integrity": "sha512-PW38i6SBZagE7c4yCYru636ICCkhJ8FNjOzAdjGkC65BZ0gElQJvFenSGc62SHFj5Fg0ft+U38PPhMZsWYQLCg==",
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz",
|
||||
"integrity": "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lerc": {
|
||||
@@ -1989,9 +1957,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/meshoptimizer": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.3.0.tgz",
|
||||
"integrity": "sha512-2oZqMAcEEiCtXWUjIGtZ71oPx1B0ZxYGTqIKsXB1wzWFhleNsCFxQuUJzgCV706bRcwPWtMGf1odmQvAcqKkIw==",
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.2.0.tgz",
|
||||
"integrity": "sha512-davRZeIJbxJrE24cwQle7ZDsxjdk/OphNOV83oX+efQinyoHY9Jcyz3MHbaoG0qySZajldGztNZ1RN/T19PZsg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ms": {
|
||||
@@ -2060,9 +2028,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/pako": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-3.0.3.tgz",
|
||||
"integrity": "sha512-tmrebBBYI5FOw8QICGwJNqE8fotC8R+gwcxOvoFNv+GKehOI6Lc6YBolNcQNnC4v96l1wt7rh102ifD4kVeZAQ==",
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-3.0.1.tgz",
|
||||
"integrity": "sha512-GupotUUI0mlhugKjUs4bjOwLt3nrehy9Ys2dxC0GtgVef5cnKggkDMmf2bq2poCCuVXopWPmqsc9VDT2iJUy+w==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -2125,9 +2093,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/protobufjs": {
|
||||
"version": "8.8.1",
|
||||
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-8.8.1.tgz",
|
||||
"integrity": "sha512-d9e9179bjXSJdpJ3+R9fP8hzXsnKLyxTjHLG1dUzje8a27pPyXCe6PrcRtgx2rjoM3IZzHd2vAs+6J/BsO1k7Q==",
|
||||
"version": "8.7.0",
|
||||
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-8.7.0.tgz",
|
||||
"integrity": "sha512-uu52JNxLh3vsL7tXU/h0gDaywufvuUCTbGSi0NKQKBZ2ZopkmrWQJSQO/EFqzu/5YhiwgVM8rq/a/iVpx4eZ0g==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"long": "^5.3.2"
|
||||
@@ -2494,9 +2462,9 @@
|
||||
},
|
||||
"packages/map-cesium-react": {
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"cesium": "1.147.0"
|
||||
"cesium": "1.143.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.1.0",
|
||||
@@ -2516,7 +2484,7 @@
|
||||
},
|
||||
"packages/ui-core": {
|
||||
"name": "@nodedc/ui-core",
|
||||
"version": "0.7.4",
|
||||
"version": "0.7.0",
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "0.6.0"
|
||||
}
|
||||
@@ -2525,17 +2493,17 @@
|
||||
"name": "@nodedc/ui-dom",
|
||||
"version": "0.7.0",
|
||||
"dependencies": {
|
||||
"@nodedc/ui-core": "0.7.4"
|
||||
"@nodedc/ui-core": "0.7.0"
|
||||
}
|
||||
},
|
||||
"packages/ui-react": {
|
||||
"name": "@nodedc/ui-react",
|
||||
"version": "0.7.10",
|
||||
"version": "0.7.0",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@nodedc/ui-core": "0.7.4",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
+6
-22
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nodedc-design-guideline",
|
||||
"version": "0.7.1",
|
||||
"version": "0.7.0",
|
||||
"private": true,
|
||||
"description": "Canonical NODE.DC design system, reusable UI packages and living component catalog.",
|
||||
"type": "module",
|
||||
@@ -11,11 +11,10 @@
|
||||
"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 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",
|
||||
"check": "npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:hgeozone-projection && npm run test:map-provider-startup && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-workspace-model && 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",
|
||||
"dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog",
|
||||
"serve": "node server/catalog-server.mjs",
|
||||
"validate:registry": "node scripts/validate-registry.mjs",
|
||||
"test:environment-settings": "node --test scripts/environment-settings.test.mjs",
|
||||
"test:platform-settings": "node scripts/smoke-platform-settings.mjs",
|
||||
"test:data-product-runtime": "node scripts/smoke-data-product-runtime.mjs",
|
||||
"test:data-product-consumer": "node --test server/foundry-data-product-consumer.test.mjs",
|
||||
@@ -23,6 +22,7 @@
|
||||
"test:foundry-agent": "node --test server/foundry-agent-store.test.mjs server/foundry-agent-gateway.test.mjs scripts/foundry-agent-installer.test.mjs",
|
||||
"test:map-animation": "node --test scripts/map-spiral.test.mjs scripts/map-camera-presets.test.mjs",
|
||||
"test:map-filters": "node --test scripts/map-presentation-filters.test.mjs",
|
||||
"test:map-workspace-model": "node --test scripts/map-workspace-model.test.mjs scripts/map-workspace-state.test.mjs",
|
||||
"test:hgeozone-projection": "node --test scripts/hgeozone-projection.test.mjs",
|
||||
"test:map-grid-lod": "node --test scripts/map-grid-lod.test.mjs scripts/map-sector-grid.test.mjs server/map-grid-persistence.test.mjs",
|
||||
"test:map-object-layers": "node --test scripts/map-object-layers.test.mjs",
|
||||
@@ -32,26 +32,10 @@
|
||||
"test:map-subject-card": "node --test scripts/map-subject-card.test.mjs",
|
||||
"test:map-subject-detail-profile": "node --test server/map-subject-detail-profile.test.mjs server/map-live-data-slot.test.mjs",
|
||||
"test:map-cache-contract": "node --test scripts/map-cache-resource-contract.test.mjs",
|
||||
"test:spark-governance": "node --test scripts/spark-governance-contract.test.mjs",
|
||||
"test:activity-indicator": "node --test scripts/activity-indicator-contract.test.mjs",
|
||||
"test:control-density": "node --test scripts/control-density-contract.test.mjs",
|
||||
"test:icon-contract": "node --test scripts/icon-contract.test.mjs",
|
||||
"test:toast-contract": "node --test scripts/toast-contract.test.mjs",
|
||||
"test:map-provider-startup": "node --test scripts/map-provider-startup.test.mjs",
|
||||
"test:floating-position": "node --test scripts/floating-position-contract.test.mjs",
|
||||
"test:inspector-select": "node --test scripts/inspector-select-contract.test.mjs scripts/select-actions-contract.test.mjs",
|
||||
"test:range-control": "node --test scripts/range-control-contract.test.mjs",
|
||||
"test:split-pane": "node --test scripts/split-pane-contract.test.mjs",
|
||||
"test:dock-layout": "node --test scripts/dock-layout.test.mjs",
|
||||
"test:analysis-controls": "node --test scripts/analysis-controls.test.mjs",
|
||||
"test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs",
|
||||
"test:window-geometry": "node --test scripts/window-geometry.test.mjs",
|
||||
"test:editor-dock": "node --test scripts/editor-dock.test.mjs",
|
||||
"test:typography": "node --test scripts/operational-typography.test.mjs",
|
||||
"prebuild": "npm run test:typography",
|
||||
"test:flat-theme": "node --test scripts/flat-theme.test.mjs",
|
||||
"test:mission-theme": "node --test scripts/mission-theme.test.mjs",
|
||||
"test:modal-size": "node --test scripts/modal-size.test.mjs",
|
||||
"test:tooltip": "node --test scripts/tooltip-titles.test.mjs"
|
||||
"test:inspector-select": "node --test scripts/inspector-select-contract.test.mjs",
|
||||
"test:range-control": "node --test scripts/range-control-contract.test.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.0",
|
||||
"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.147.0"
|
||||
"cesium": "1.143.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
|
||||
@@ -15,7 +15,6 @@ import type {
|
||||
MapProviderId,
|
||||
MapRuntimeState,
|
||||
} from "./contracts.js";
|
||||
import {applyMapSceneEffects} from "./sceneEffects.js";
|
||||
import { advanceGhostPins } from "./ghostPins.js";
|
||||
import {
|
||||
parseProviderEndpoint,
|
||||
@@ -61,13 +60,10 @@ 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);
|
||||
@@ -120,7 +116,6 @@ 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();
|
||||
@@ -196,8 +191,6 @@ 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];
|
||||
@@ -272,7 +265,6 @@ export const CesiumMapRenderer = forwardRef<
|
||||
return () => {
|
||||
disposed = true;
|
||||
abortController.abort();
|
||||
try { disposeConsumer?.(); } finally {
|
||||
removeCameraListener?.();
|
||||
removeRenderListener?.();
|
||||
runtimeRef.current?.stopGhostPinAnimation?.();
|
||||
@@ -280,7 +272,6 @@ export const CesiumMapRenderer = forwardRef<
|
||||
viewer?.destroy();
|
||||
viewer = null;
|
||||
container.replaceChildren();
|
||||
}
|
||||
};
|
||||
}, [
|
||||
runtimeConfigUrl,
|
||||
@@ -496,9 +487,7 @@ function applyPresentation(
|
||||
buildings.maximumScreenSpaceError =
|
||||
settings.buildings_maximum_screen_space_error;
|
||||
buildings.style = new Cesium.Cesium3DTileStyle({
|
||||
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})`,
|
||||
color: `color('${settings.buildings_color}', ${settings.buildings_opacity})`,
|
||||
});
|
||||
}
|
||||
runtime.ghostPins.show = layers.targets;
|
||||
@@ -544,9 +533,9 @@ function applyPresentation(
|
||||
}
|
||||
viewer.shadows = settings.shadows_enabled;
|
||||
const sunDate = Cesium.JulianDate.toDate(Cesium.JulianDate.now());
|
||||
if (!settings.sun_time_current) sunDate.setUTCHours(
|
||||
Math.floor(clamp(settings.sun_hour, 0, 24)),
|
||||
Math.round((settings.sun_hour % 1) * 60),
|
||||
sunDate.setUTCHours(
|
||||
clamp(Math.round(settings.sun_hour), 0, 24),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
@@ -559,7 +548,6 @@ function applyPresentation(
|
||||
2,
|
||||
);
|
||||
viewer.scene.light = sun;
|
||||
applyMapSceneEffects(runtime, settings);
|
||||
viewer.scene.requestRender();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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.147.0" as const;
|
||||
export const CESIUM_RENDERER_VERSION = "1.143.0" as const;
|
||||
|
||||
export type MapProviderId = "imagery" | "terrain" | "buildings";
|
||||
export type MapProviderPhase = "idle" | "loading" | "ready" | "disabled" | "error";
|
||||
@@ -112,7 +111,7 @@ export type MapLayerVisibility = {
|
||||
targets: boolean;
|
||||
};
|
||||
|
||||
export type MapVisualSettings = Partial<MapSceneEffects> & {
|
||||
export type MapVisualSettings = {
|
||||
atmosphere_enabled: boolean;
|
||||
atmosphere_hue: number;
|
||||
atmosphere_saturation: number;
|
||||
@@ -120,7 +119,6 @@ export type MapVisualSettings = Partial<MapSceneEffects> & {
|
||||
fog_enabled: boolean;
|
||||
fog_density: number;
|
||||
sun_enabled: boolean;
|
||||
sun_time_current?: boolean;
|
||||
sun_hour: number;
|
||||
sun_intensity: number;
|
||||
shadows_enabled: boolean;
|
||||
@@ -135,7 +133,6 @@ export type MapVisualSettings = Partial<MapSceneEffects> & {
|
||||
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;
|
||||
@@ -157,47 +154,12 @@ export type MapVisualSettings = Partial<MapSceneEffects> & {
|
||||
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,7 +7,6 @@ export {
|
||||
export type {
|
||||
CesiumMapRendererHandle,
|
||||
CesiumMapRendererProps,
|
||||
MapSceneContext,
|
||||
MapCacheIntent,
|
||||
MapCamera,
|
||||
MapGeoPoint,
|
||||
@@ -23,7 +22,6 @@ export type {
|
||||
MapRuntimeConfiguration,
|
||||
MapRuntimeState,
|
||||
MapVisualSettings,
|
||||
MapSceneEffects,
|
||||
} from "./contracts.js";
|
||||
export {
|
||||
advanceGhostPins,
|
||||
@@ -39,5 +37,3 @@ export {
|
||||
readSafeErrorCode,
|
||||
withProviderState,
|
||||
} from "./runtime.js";
|
||||
|
||||
export {DEFAULT_MAP_SCENE_EFFECTS} from "./sceneEffects.js";
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { DefaultProxy, Resource, VERSION } from "cesium";
|
||||
import { CESIUM_RENDERER_VERSION } from "../dist/contracts.js";
|
||||
import { applyCacheIntent, fetchMapRuntimeConfiguration } from "../dist/runtime.js";
|
||||
|
||||
test("installed Cesium and the runtime contract agree", () => {
|
||||
assert.equal(VERSION, CESIUM_RENDERER_VERSION);
|
||||
});
|
||||
|
||||
test("Cesium derived terrain and building resources retain the existing cache route", () => {
|
||||
for (const [root, child] of [
|
||||
["https://assets.ion.cesium.com/1/", "12/124/113.terrain?v=1"],
|
||||
["https://assets.ion.cesium.com/96188/tileset.json", "12/124/113.b3dm"],
|
||||
]) {
|
||||
const resource = new Resource({
|
||||
url: applyCacheIntent(root, { enabled: true, no_overwrite: true }, false),
|
||||
proxy: new DefaultProxy("/api/v1/map/gateway/cache?url="),
|
||||
});
|
||||
const derived = resource.getDerivedResource({ url: child });
|
||||
const proxied = new URL(derived.getUrlComponent(true, true), "http://127.0.0.1:8000");
|
||||
assert.equal(proxied.pathname, "/api/v1/map/gateway/cache");
|
||||
const upstream = new URL(proxied.searchParams.get("url"));
|
||||
assert.equal(upstream.searchParams.get("nodedc_cache_profile"), "live");
|
||||
assert.equal(upstream.searchParams.has("nodedc_cache_refresh"), false);
|
||||
assert.equal(upstream.searchParams.has("access_token"), false);
|
||||
assert.equal(upstream.pathname, new URL(child, root).pathname);
|
||||
}
|
||||
});
|
||||
|
||||
test("a mismatched renderer cannot silently start against another runtime release", async (t) => {
|
||||
const originalWindow = globalThis.window;
|
||||
globalThis.window = { location: { origin: "http://127.0.0.1:8000" } };
|
||||
t.after(() => {
|
||||
if (originalWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = originalWindow;
|
||||
});
|
||||
const configuration = {
|
||||
schema_version: "missioncore.map-runtime/v1",
|
||||
map_page_version: "0.1.0",
|
||||
renderer: { id: "cesium", version: CESIUM_RENDERER_VERSION },
|
||||
gateway: {
|
||||
configured: true,
|
||||
health_url: "/api/v1/map/gateway/health",
|
||||
asset_endpoint_template: "/api/v1/map/gateway/ion/assets/{asset_id}/endpoint",
|
||||
cache_proxy_prefix: "/api/v1/map/gateway/cache?url=",
|
||||
},
|
||||
assets: { imagery: 2, terrain: 1, buildings: 96188 },
|
||||
};
|
||||
t.mock.method(globalThis, "fetch", async () => Response.json(configuration));
|
||||
assert.equal((await fetchMapRuntimeConfiguration("/api/v1/map/runtime-config", new AbortController().signal)).renderer.version, CESIUM_RENDERER_VERSION);
|
||||
configuration.renderer.version = "1.143.0";
|
||||
await assert.rejects(fetchMapRuntimeConfiguration("/api/v1/map/runtime-config", new AbortController().signal), { code: "map_runtime_contract_mismatch" });
|
||||
});
|
||||
|
||||
test("project focus keeps its range and survives the persisted camera round trip", async () => {
|
||||
const C = await import("cesium");
|
||||
const scene = {
|
||||
drawingBufferWidth: 840, drawingBufferHeight: 461,
|
||||
mapProjection: new C.GeographicProjection(), ellipsoid: C.Ellipsoid.WGS84,
|
||||
mode: C.SceneMode.SCENE3D,
|
||||
screenSpaceCameraController: { minimumZoomDistance: 1, maximumZoomDistance: Infinity },
|
||||
};
|
||||
const camera = new C.Camera(scene);
|
||||
scene.camera = camera;
|
||||
camera.update(C.SceneMode.SCENE3D);
|
||||
for (const [lon, lat, height] of [[3.711, 51.065, 10], [37.58, 55.75, 160], [-97.736, 30.287, 180]]) {
|
||||
const target = C.Cartesian3.fromDegrees(lon, lat, height);
|
||||
camera.flyToBoundingSphere(new C.BoundingSphere(target, 160), {
|
||||
duration: 0, offset: new C.HeadingPitchRange(0, -Math.PI / 4, 600),
|
||||
});
|
||||
assert.ok(Math.abs(C.Cartesian3.distance(camera.positionWC, target) - 600) < 1e-5);
|
||||
const position = C.Cartographic.clone(camera.positionCartographic);
|
||||
const orientation = { heading: camera.heading, pitch: camera.pitch, roll: camera.roll };
|
||||
camera.setView({ destination: C.Cartesian3.fromRadians(position.longitude, position.latitude, position.height), orientation });
|
||||
const toward = C.Cartesian3.normalize(C.Cartesian3.subtract(target, camera.positionWC, new C.Cartesian3()), new C.Cartesian3());
|
||||
assert.ok(C.Cartesian3.dot(camera.directionWC, toward) > 0.999999);
|
||||
assert.ok(Math.abs(C.Cartesian3.distance(camera.positionWC, target) - 600) < 1e-5);
|
||||
}
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
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,25 +1,14 @@
|
||||
:root {
|
||||
--nodedc-field-hover-bg: color-mix(in srgb, var(--nodedc-field-bg) 94%, var(--nodedc-text-primary));
|
||||
--nodedc-neutral-action-bg: rgba(247, 248, 244, 0.96);
|
||||
--nodedc-neutral-action-hover: #fff;
|
||||
--nodedc-neutral-action-color: rgba(8, 8, 10, 0.96);
|
||||
--nodedc-neutral-action-disabled-bg: #757575;
|
||||
--nodedc-neutral-action-disabled-color: #242424;
|
||||
}
|
||||
|
||||
:root,
|
||||
[data-nodedc-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--nodedc-accent-rgb: 247 248 244;
|
||||
--nodedc-on-accent-rgb: 8 8 10;
|
||||
--nodedc-accent-rgb: 255 47 146;
|
||||
--nodedc-on-accent-rgb: 11 17 23;
|
||||
--nodedc-danger-rgb: 255 116 116;
|
||||
--nodedc-warning-rgb: 255 209 102;
|
||||
--nodedc-success-rgb: 181 255 90;
|
||||
|
||||
--nodedc-canvas: #050506;
|
||||
--nodedc-canvas-soft: #0d0d0f;
|
||||
--nodedc-stage: #08090b;
|
||||
--nodedc-surface-group: rgba(110, 110, 110, 0.07);
|
||||
--nodedc-canvas-soft: #0b0b0d;
|
||||
--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);
|
||||
@@ -85,16 +74,14 @@
|
||||
|
||||
[data-nodedc-theme="light"] {
|
||||
color-scheme: light;
|
||||
--nodedc-accent-rgb: 24 25 28;
|
||||
--nodedc-on-accent-rgb: 247 248 244;
|
||||
--nodedc-accent-rgb: 255 47 146;
|
||||
--nodedc-on-accent-rgb: 11 17 23;
|
||||
--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);
|
||||
@@ -157,24 +144,3 @@
|
||||
--nodedc-modal-shadow: 0 24px 72px rgb(0 0 0 / var(--nodedc-modal-glass-shadow-light-opacity)), inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
--nodedc-floating-surface: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(255, 255, 255, 0.72)), rgba(255, 255, 255, 0.94);
|
||||
}
|
||||
|
||||
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="dark"] {
|
||||
--nodedc-modal-surface: rgb(15 15 17 / .97);
|
||||
--nodedc-floating-surface: rgb(15 15 17 / .98);
|
||||
--nodedc-primary-action-bg: rgb(247 248 244 / .96);
|
||||
--nodedc-primary-action-hover: rgb(255 255 255);
|
||||
--nodedc-primary-action-color: rgb(8 8 10 / .96);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
--nodedc-focus-surface: rgb(255 255 255 / .09);
|
||||
}
|
||||
|
||||
|
||||
[data-nodedc-appearance="mission"][data-nodedc-theme="light"] {
|
||||
--nodedc-modal-surface: rgb(247 248 250 / .97);
|
||||
--nodedc-floating-surface: rgb(247 248 250 / .98);
|
||||
--nodedc-primary-action-bg: rgb(24 25 28 / .96);
|
||||
--nodedc-primary-action-hover: rgb(8 8 10);
|
||||
--nodedc-primary-action-color: rgb(247 248 244);
|
||||
--nodedc-primary-action-shadow: none;
|
||||
}
|
||||
|
||||
@@ -9,9 +9,7 @@
|
||||
--nodedc-radius-circle: 999px;
|
||||
|
||||
--nodedc-control-height: 2.875rem;
|
||||
--nodedc-viewport-control-scale: 0.7;
|
||||
--nodedc-control-height-compact: 2.375rem;
|
||||
--nodedc-control-height-dense: 1.875rem;
|
||||
--nodedc-icon-button-size: 2.875rem;
|
||||
--nodedc-header-row-height: 3rem;
|
||||
--nodedc-header-pill-height: 3.45rem;
|
||||
@@ -63,7 +61,6 @@
|
||||
|
||||
--nodedc-font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--nodedc-font-size-xs: 0.6875rem;
|
||||
--nodedc-font-size-dense: 0.45rem;
|
||||
--nodedc-font-size-sm: 0.75rem;
|
||||
--nodedc-font-size-md: 0.8125rem;
|
||||
--nodedc-font-size-lg: 1rem;
|
||||
@@ -72,6 +69,3 @@
|
||||
--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,11 +1,10 @@
|
||||
{
|
||||
"name": "@nodedc/ui-core",
|
||||
"version": "0.7.4",
|
||||
"version": "0.7.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist",
|
||||
"styles.css",
|
||||
"typography.mjs"
|
||||
"styles.css"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -14,13 +13,11 @@
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./styles.css": "./styles.css",
|
||||
"./typography": "./typography.mjs"
|
||||
"./styles.css": "./styles.css"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"prebuild": "node --test ../../scripts/operational-typography.test.mjs"
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "0.6.0"
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
/** Serializable split tree. Content identity is independent of its position. */
|
||||
export type DockTree = { id: string } | { axis: "x" | "y"; ratio: number; first: DockTree; second: DockTree };
|
||||
export type DockPosition = "center" | "left" | "right" | "top" | "bottom";
|
||||
export interface DockRect { left: number; top: number; width: number; height: number }
|
||||
/** Workspace moves ignore overId and wrap the remaining layout at its outer edge. */
|
||||
export interface DockMove { activeId: string; overId: string; position: DockPosition; scope?: "panel" | "workspace" }
|
||||
|
||||
export function dockIds(tree: DockTree | null): string[] {
|
||||
return !tree ? [] : "id" in tree ? [tree.id] : [...dockIds(tree.first), ...dockIds(tree.second)];
|
||||
}
|
||||
|
||||
export function decodeDockTree(raw: unknown): DockTree | null {
|
||||
const seen = new Set<string>();
|
||||
const read = (value: unknown, depth: number): DockTree | null => {
|
||||
if (!value || typeof value !== "object" || depth > 128 || seen.size > 128) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
if (typeof v.id === "string" && v.id.length > 0 && v.id.length < 512) {
|
||||
if (seen.has(v.id)) return null;
|
||||
seen.add(v.id); return { id: v.id };
|
||||
}
|
||||
if ((v.axis !== "x" && v.axis !== "y") || typeof v.ratio !== "number" || !Number.isFinite(v.ratio)) return null;
|
||||
const first = read(v.first, depth + 1), second = read(v.second, depth + 1);
|
||||
return first && second ? { axis: v.axis, ratio: Math.max(10, Math.min(90, v.ratio)), first, second } : first ?? second;
|
||||
};
|
||||
return read(raw, 0);
|
||||
}
|
||||
|
||||
export function pruneDockTree(tree: DockTree | null, ids: readonly string[]): DockTree | null {
|
||||
if (!tree) return null;
|
||||
if ("id" in tree) return ids.includes(tree.id) ? tree : null;
|
||||
const first = pruneDockTree(tree.first, ids), second = pruneDockTree(tree.second, ids);
|
||||
return first && second ? { ...tree, first, second } : first ?? second;
|
||||
}
|
||||
|
||||
export function balancedDockTree(ids: readonly string[], axis: "x" | "y" = "x"): DockTree | null {
|
||||
if (!ids.length) return null;
|
||||
if (ids.length === 1) return { id: ids[0] };
|
||||
const mid = Math.ceil(ids.length / 2);
|
||||
return { axis, ratio: 50, first: balancedDockTree(ids.slice(0, mid), axis === "x" ? "y" : "x")!,
|
||||
second: balancedDockTree(ids.slice(mid), axis === "x" ? "y" : "x")! };
|
||||
}
|
||||
|
||||
export function reconcileDockTree(tree: DockTree | null, ids: readonly string[]): DockTree | null {
|
||||
const kept = pruneDockTree(tree, ids), present = dockIds(kept), missing = ids.filter(id => !present.includes(id));
|
||||
if (!kept) return balancedDockTree(missing);
|
||||
return missing.length ? { axis: "x", ratio: 50, first: kept, second: balancedDockTree(missing)! } : kept;
|
||||
}
|
||||
|
||||
export function moveDockPanel(tree: DockTree | null, move: DockMove): DockTree | null {
|
||||
const { activeId, overId, position } = move, ids = dockIds(tree);
|
||||
if (!tree || !ids.includes(activeId)) return tree;
|
||||
if (move.scope === "workspace") {
|
||||
if (position === "center" || ids.length < 2) return tree;
|
||||
const remaining = pruneDockTree(tree, ids.filter(id => id !== activeId))!;
|
||||
const before = position === "left" || position === "top";
|
||||
return {axis: position === "left" || position === "right" ? "x" : "y", ratio: 50,
|
||||
first: before ? {id: activeId} : remaining, second: before ? remaining : {id: activeId}};
|
||||
}
|
||||
if (activeId === overId || !ids.includes(overId)) return tree;
|
||||
const swap = (node: DockTree): DockTree => "id" in node
|
||||
? { id: node.id === activeId ? overId : node.id === overId ? activeId : node.id }
|
||||
: { ...node, first: swap(node.first), second: swap(node.second) };
|
||||
if (position === "center") return swap(tree);
|
||||
const remaining = pruneDockTree(tree, ids.filter(id => id !== activeId))!;
|
||||
const insert = (node: DockTree): DockTree => {
|
||||
if (!("id" in node)) return { ...node, first: insert(node.first), second: insert(node.second) };
|
||||
if (node.id !== overId) return node;
|
||||
const before = position === "left" || position === "top";
|
||||
return { axis: position === "left" || position === "right" ? "x" : "y", ratio: 50,
|
||||
first: before ? { id: activeId } : node, second: before ? node : { id: activeId } };
|
||||
};
|
||||
return insert(remaining);
|
||||
}
|
||||
|
||||
export function resizeDockSplit(tree: DockTree, path: string, ratio: number): DockTree {
|
||||
if ("id" in tree || !Number.isFinite(ratio)) return tree;
|
||||
if (!path) return { ...tree, ratio: Math.max(10, Math.min(90, ratio)) };
|
||||
const side = path[0] === "0" ? "first" : "second";
|
||||
return { ...tree, [side]: resizeDockSplit(tree[side], path.slice(1), ratio) };
|
||||
}
|
||||
|
||||
export function dockRects(tree: DockTree | null, bounds: DockRect): Record<string, DockRect> {
|
||||
if (!tree) return {};
|
||||
if ("id" in tree) return { [tree.id]: bounds };
|
||||
const fraction = tree.ratio / 100;
|
||||
const first = tree.axis === "x" ? { ...bounds, width: bounds.width * fraction } : { ...bounds, height: bounds.height * fraction };
|
||||
const second = tree.axis === "x" ? { ...bounds, left: bounds.left + first.width, width: bounds.width - first.width }
|
||||
: { ...bounds, top: bounds.top + first.height, height: bounds.height - first.height };
|
||||
return { ...dockRects(tree.first, first), ...dockRects(tree.second, second) };
|
||||
}
|
||||
|
||||
export function dockPosition(rect: DockRect, x: number, y: number): DockPosition | null {
|
||||
if (rect.width <= 0 || rect.height <= 0 || x < rect.left || y < rect.top || x > rect.left + rect.width || y > rect.top + rect.height) return null;
|
||||
const u = (x - rect.left) / rect.width, v = (y - rect.top) / rect.height;
|
||||
const distances: [DockPosition, number][] = [["left", u], ["right", 1 - u], ["top", v], ["bottom", 1 - v]];
|
||||
const nearest = distances.sort((a, b) => a[1] - b[1])[0];
|
||||
return nearest[1] <= .23 ? nearest[0] : "center";
|
||||
}
|
||||
|
||||
|
||||
/** Outer 24 CSS px take priority over the existing per-panel zones.
|
||||
* bounds is the visible workspace, expressed in the same coordinates as rects.
|
||||
*/
|
||||
export function dockMoveAtPoint(bounds: DockRect, rects: Readonly<Record<string, DockRect>>, activeId: string, x: number, y: number): DockMove | null {
|
||||
if (![x, y, bounds.left, bounds.top, bounds.width, bounds.height].every(Number.isFinite)
|
||||
|| !dockPosition(bounds, x, y) || !(activeId in rects) || Object.keys(rects).length < 2) return null;
|
||||
const zoneX = Math.min(24, bounds.width * .08), zoneY = Math.min(24, bounds.height * .08);
|
||||
const edges: [Exclude<DockPosition, "center">, number][] = [
|
||||
["left", (x - bounds.left) / zoneX], ["right", (bounds.left + bounds.width - x) / zoneX],
|
||||
["top", (y - bounds.top) / zoneY], ["bottom", (bounds.top + bounds.height - y) / zoneY],
|
||||
];
|
||||
const nearest = edges.sort((a, b) => a[1] - b[1])[0];
|
||||
if (nearest[1] <= 1) return {activeId, overId: activeId, position: nearest[0], scope: "workspace"};
|
||||
for (const [id, rect] of Object.entries(rects)) {
|
||||
const position = dockPosition(rect, x, y);
|
||||
if (position && id !== activeId) return {activeId, overId: id, position};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface DockMinimum { width: number; height: number }
|
||||
export type DockMinimums = Readonly<Record<string, DockMinimum>>;
|
||||
/** Propagate content limits through every ancestor, not only the nearest split. */
|
||||
export function dockMinimum(tree: DockTree | null, minimums: DockMinimums = {}): DockMinimum {
|
||||
if (!tree) return {width: 0, height: 0};
|
||||
if ("id" in tree) {
|
||||
const value = minimums[tree.id];
|
||||
const valid = (v: number | undefined, fallback: number) => typeof v === "number" && Number.isFinite(v) ? Math.max(0, v) : fallback;
|
||||
return {width: valid(value?.width, 160), height: valid(value?.height, 120)};
|
||||
}
|
||||
const a = dockMinimum(tree.first, minimums), b = dockMinimum(tree.second, minimums);
|
||||
return tree.axis === "x" ? {width: a.width + b.width, height: Math.max(a.height, b.height)}
|
||||
: {width: Math.max(a.width, b.width), height: a.height + b.height};
|
||||
}
|
||||
/** Host expands to the recursive minimum when the whole viewport is too small. */
|
||||
export function constrainDockTree(tree: DockTree | null, bounds: DockMinimum, minimums: DockMinimums = {}): DockTree | null {
|
||||
if (!tree || "id" in tree) return tree;
|
||||
const required = dockMinimum(tree, minimums), size = {width: Math.max(bounds.width, required.width), height: Math.max(bounds.height, required.height)};
|
||||
const a = dockMinimum(tree.first, minimums), b = dockMinimum(tree.second, minimums), key = tree.axis === "x" ? "width" : "height";
|
||||
const available = size[key];
|
||||
const cut = Math.max(a[key], Math.min(available - b[key], available * tree.ratio / 100));
|
||||
const ratio=available>0?cut/available*100:50;
|
||||
return {...tree, ratio:Math.abs(ratio-tree.ratio)<1e-9?tree.ratio:ratio,
|
||||
first: constrainDockTree(tree.first, {...size, [key]: cut}, minimums)!,
|
||||
second: constrainDockTree(tree.second, {...size, [key]: available - cut}, minimums)!};
|
||||
}
|
||||
|
||||
/** Initial preferred sizes apply only until the product persists a user layout. */
|
||||
export function preferDockSizes(tree:DockTree|null,bounds:DockMinimum,preferred:DockMinimums):DockTree|null {
|
||||
if(!tree||'id' in tree)return tree;
|
||||
const a=dockIds(tree.first).some(id=>id in preferred),b=dockIds(tree.second).some(id=>id in preferred);
|
||||
const key=tree.axis==='x'?'width':'height';
|
||||
let ratio=tree.ratio;
|
||||
if(a!==b){const wanted=dockMinimum(a?tree.first:tree.second,preferred)[key];ratio=(a?wanted:bounds[key]-wanted)/bounds[key]*100;}
|
||||
ratio=Math.max(1,Math.min(99,Number.isFinite(ratio)?ratio:50));
|
||||
return {...tree,ratio,first:preferDockSizes(tree.first,{...bounds,[key]:bounds[key]*ratio/100},preferred)!,second:preferDockSizes(tree.second,{...bounds,[key]:bounds[key]*(1-ratio/100)},preferred)!};
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
export type EnvironmentMediaKind = "image" | "video";
|
||||
export type EnvironmentMediaSource = "file" | "url";
|
||||
|
||||
export interface EnvironmentMediaItem {
|
||||
id: string;
|
||||
source: EnvironmentMediaSource;
|
||||
url: string | null;
|
||||
mediaKind: EnvironmentMediaKind | null;
|
||||
fileName: string | null;
|
||||
}
|
||||
|
||||
export interface EnvironmentBackground {
|
||||
enabled: boolean;
|
||||
imageDurationSeconds: number;
|
||||
items: EnvironmentMediaItem[];
|
||||
}
|
||||
|
||||
export interface EnvironmentPage {
|
||||
headerLabel: string;
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
description: string;
|
||||
primaryWorkspaceId: string | null;
|
||||
secondaryWorkspaceId: string | null;
|
||||
background: EnvironmentBackground;
|
||||
}
|
||||
|
||||
export interface EnvironmentSettings { revision: number; pages: Record<string, EnvironmentPage> }
|
||||
export interface UploadedEnvironmentMedia { url: string; fileName: string; mediaKind: EnvironmentMediaKind }
|
||||
export interface EnvironmentAction { id: string; label: string; description?: string }
|
||||
export interface EnvironmentSurface { id: string; home?: boolean; description?: string; actions: readonly EnvironmentAction[] }
|
||||
|
||||
export const defaultEnvironmentImageDurationSeconds = 10;
|
||||
export const maxEnvironmentMediaItems = 24;
|
||||
|
||||
export function createEnvironmentMediaItem(): EnvironmentMediaItem {
|
||||
return {
|
||||
id: `media-${crypto.randomUUID()}`,
|
||||
source: "file",
|
||||
url: null,
|
||||
mediaKind: null,
|
||||
fileName: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function appendEnvironmentMediaItem(
|
||||
background: EnvironmentBackground,
|
||||
item: EnvironmentMediaItem = createEnvironmentMediaItem(),
|
||||
): EnvironmentBackground {
|
||||
if (
|
||||
background.items.length >= maxEnvironmentMediaItems
|
||||
|| background.items.some((candidate) => candidate.id === item.id)
|
||||
) {
|
||||
return background;
|
||||
}
|
||||
return {
|
||||
...background,
|
||||
enabled: background.items.length === 0 ? true : background.enabled,
|
||||
items: [...background.items, item],
|
||||
};
|
||||
}
|
||||
|
||||
export function removeEnvironmentMediaItem(
|
||||
background: EnvironmentBackground,
|
||||
itemId: string,
|
||||
): EnvironmentBackground {
|
||||
const items = background.items.filter((item) => item.id !== itemId);
|
||||
if (items.length === background.items.length) return background;
|
||||
return {
|
||||
...background,
|
||||
enabled: items.length > 0 && background.enabled,
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
export function inferEnvironmentMediaKind(url: string): EnvironmentMediaKind {
|
||||
return /\.(mp4|webm|mov)(?:[?#].*)?$/i.test(url) ? "video" : "image";
|
||||
}
|
||||
|
||||
export function cloneEnvironmentSettings(settings: EnvironmentSettings): EnvironmentSettings {
|
||||
return { ...settings, pages: Object.fromEntries(Object.entries(settings.pages).map(([id, page]) => [id, {
|
||||
...page, background: { ...page.background, items: page.background.items.map(item => ({ ...item })) },
|
||||
}])) };
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export type FloatingPlacement = "bottom-start" | "bottom-end" | "top-start" | "top-end" | "left-start" | "right-start";
|
||||
export type FloatingPlacement = "bottom-start" | "bottom-end" | "top-start" | "top-end";
|
||||
|
||||
export interface RectLike {
|
||||
top: number;
|
||||
@@ -15,7 +15,6 @@ export interface FloatingPositionOptions {
|
||||
surfaceHeight: number;
|
||||
placement?: FloatingPlacement;
|
||||
offset?: number;
|
||||
flip?: boolean;
|
||||
viewportWidth?: number;
|
||||
viewportHeight?: number;
|
||||
viewportPadding?: number;
|
||||
@@ -25,7 +24,6 @@ export interface FloatingPosition {
|
||||
top: number;
|
||||
left: number;
|
||||
maxHeight: number;
|
||||
maxWidth?: number;
|
||||
resolvedPlacement: FloatingPlacement;
|
||||
}
|
||||
|
||||
@@ -35,7 +33,6 @@ export function computeFloatingPosition({
|
||||
surfaceHeight,
|
||||
placement = "bottom-start",
|
||||
offset = 8,
|
||||
flip = true,
|
||||
viewportWidth = typeof window === "undefined" ? 1920 : window.innerWidth,
|
||||
viewportHeight = typeof window === "undefined" ? 1080 : window.innerHeight,
|
||||
viewportPadding = 8,
|
||||
@@ -44,22 +41,6 @@ export function computeFloatingPosition({
|
||||
0,
|
||||
viewportHeight - viewportPadding * 2,
|
||||
);
|
||||
if (placement.startsWith("left") || placement.startsWith("right")) {
|
||||
const roomLeft = Math.max(0, anchor.left - offset - viewportPadding);
|
||||
const roomRight = Math.max(0, viewportWidth - anchor.right - offset - viewportPadding);
|
||||
const leftRequested = placement.startsWith("left");
|
||||
const switched = flip && (leftRequested ? surfaceWidth > roomLeft && roomRight > roomLeft : surfaceWidth > roomRight && roomLeft > roomRight);
|
||||
const toLeft = switched ? !leftRequested : leftRequested;
|
||||
const maxWidth = toLeft ? roomLeft : roomRight;
|
||||
const actualWidth = Math.min(surfaceWidth, maxWidth);
|
||||
const visibleHeight = Math.min(surfaceHeight, viewportAvailableHeight);
|
||||
return {
|
||||
left: toLeft ? anchor.left - offset - actualWidth : anchor.right + offset,
|
||||
top: Math.max(viewportPadding, Math.min(anchor.top, viewportHeight - viewportPadding - visibleHeight)),
|
||||
maxHeight: viewportAvailableHeight, maxWidth,
|
||||
resolvedPlacement: toLeft ? "left-start" : "right-start",
|
||||
};
|
||||
}
|
||||
const roomBelow = Math.min(
|
||||
viewportAvailableHeight,
|
||||
Math.max(0, viewportHeight - anchor.bottom - offset - viewportPadding),
|
||||
@@ -69,9 +50,9 @@ export function computeFloatingPosition({
|
||||
Math.max(0, anchor.top - offset - viewportPadding),
|
||||
);
|
||||
const requestedTop = placement.startsWith("top");
|
||||
const shouldFlip = flip && (requestedTop
|
||||
const shouldFlip = requestedTop
|
||||
? surfaceHeight > roomAbove && roomBelow > roomAbove
|
||||
: surfaceHeight > roomBelow && roomAbove > roomBelow);
|
||||
: surfaceHeight > roomBelow && roomAbove > roomBelow;
|
||||
const resolvedPlacement = shouldFlip
|
||||
? (`${requestedTop ? "bottom" : "top"}-${placement.endsWith("end") ? "end" : "start"}` as FloatingPlacement)
|
||||
: placement;
|
||||
|
||||
@@ -29,16 +29,12 @@ function clamp(value: number, min: number, max: number) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
export function createGlassMaterialVariables(settings: GlassMaterialSettings, context: "floating" | "scene" = "floating"): Record<string, string> {
|
||||
export function createGlassMaterialVariables(settings: GlassMaterialSettings): Record<string, string> {
|
||||
const tintHex = normalizeHex(settings.tintHex);
|
||||
const red = Number.parseInt(tintHex.slice(1, 3), 16);
|
||||
const green = Number.parseInt(tintHex.slice(3, 5), 16);
|
||||
const blue = Number.parseInt(tintHex.slice(5, 7), 16);
|
||||
return {
|
||||
...(context === "scene" ? {
|
||||
"--nodedc-scene-glass-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
|
||||
"--nodedc-scene-glass-blur": `${clamp(settings.blur, 0, 120)}px`,
|
||||
} : {}),
|
||||
"--nodedc-modal-glass-tint-rgb": `${red} ${green} ${blue}`,
|
||||
"--nodedc-modal-glass-tint-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
|
||||
"--nodedc-blur-modal": `${clamp(settings.blur, 0, 120)}px`,
|
||||
|
||||
@@ -3,13 +3,3 @@ export * from "./floating.js";
|
||||
export * from "./glass.js";
|
||||
export * from "./theme.js";
|
||||
export * from "./toolbar.js";
|
||||
export * from "./environment.js";
|
||||
|
||||
export * from "./dockTree.js";
|
||||
|
||||
export {dockMinimum, constrainDockTree, type DockMinimum, type DockMinimums} from "./dockTree.js";
|
||||
|
||||
export {preferDockSizes} from "./dockTree.js";
|
||||
|
||||
export * from "./menuAim.js";
|
||||
export * from "./editorDock.js";
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import type { RectLike } from "./floating.js";
|
||||
export type MenuPoint = {x:number;y:number};
|
||||
/** Delay sibling activation only while the pointer advances through the corridor to the open menu. */
|
||||
export function movingToMenu(origin:MenuPoint, previous:MenuPoint, current:MenuPoint, surface:RectLike):boolean {
|
||||
const horizontal = origin.x < surface.left || origin.x > surface.right;
|
||||
const edge = horizontal ? (origin.x < surface.left ? surface.left : surface.right) : (origin.y < surface.top ? surface.top : surface.bottom);
|
||||
const a = horizontal ? {x:edge,y:surface.top-6} : {x:surface.left-6,y:edge};
|
||||
const b = horizontal ? {x:edge,y:surface.bottom+6} : {x:surface.right+6,y:edge};
|
||||
const cross=(p:MenuPoint,q:MenuPoint,v:MenuPoint)=>(q.x-p.x)*(v.y-p.y)-(q.y-p.y)*(v.x-p.x);
|
||||
const signs=[cross(origin,a,current),cross(a,b,current),cross(b,origin,current)];
|
||||
const inside=signs.every(v=>v>=-0.01)||signs.every(v=>v<=0.01);
|
||||
const axis=horizontal?"x":"y";
|
||||
return inside && Math.abs(current[axis]-edge)<Math.abs(previous[axis]-edge)-0.1;
|
||||
}
|
||||
@@ -15,23 +15,10 @@ export interface NodedcMaterial {
|
||||
|
||||
export interface ApplyThemeOptions {
|
||||
theme?: NodedcTheme;
|
||||
/** Mission Core is the canonical foundation. `default` is legacy compatibility. */
|
||||
appearance?: "default" | "mission";
|
||||
/** Flat surfaces remove decorative edges; keyboard focus uses a contrasting fill. */
|
||||
edges?: "default" | "flat";
|
||||
accent?: RgbTuple;
|
||||
material?: NodedcMaterial;
|
||||
}
|
||||
|
||||
/** Complete shared foundation; colors live exclusively in @nodedc/tokens/themes.css. */
|
||||
export const missionDarkTheme = Object.freeze({
|
||||
theme: "dark", appearance: "mission", edges: "flat",
|
||||
} as const satisfies ApplyThemeOptions);
|
||||
|
||||
export const missionLightTheme = Object.freeze({
|
||||
theme: "light", appearance: "mission", edges: "flat",
|
||||
} as const satisfies ApplyThemeOptions);
|
||||
|
||||
function formatRgb([red, green, blue]: RgbTuple): string {
|
||||
return `${red} ${green} ${blue}`;
|
||||
}
|
||||
@@ -42,11 +29,9 @@ function clampOpacity(value: number): number {
|
||||
|
||||
export function applyNodedcTheme(
|
||||
target: HTMLElement,
|
||||
{ theme = "dark", accent, material, appearance = "mission", edges = "flat" }: ApplyThemeOptions = {},
|
||||
{ theme = "dark", accent, material }: ApplyThemeOptions = {},
|
||||
): void {
|
||||
target.dataset.nodedcTheme = theme;
|
||||
target.dataset.nodedcAppearance = appearance;
|
||||
target.dataset.nodedcEdges = edges;
|
||||
target.dataset.nodedcUi = "true";
|
||||
|
||||
if (accent) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type ToolbarPlacement = "left" | "right" | "top" | "bottom";
|
||||
export type ToolbarPlacement = "left" | "right" | "bottom";
|
||||
|
||||
export interface ToolbarSettings {
|
||||
minSize: number;
|
||||
|
||||
+37
-1351
File diff suppressed because it is too large
Load Diff
@@ -1,46 +0,0 @@
|
||||
/** 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,8 +3,7 @@
|
||||
"version": "0.7.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist",
|
||||
"styles.css"
|
||||
"dist"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -12,14 +11,13 @@
|
||||
".": {
|
||||
"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.4"
|
||||
"@nodedc/ui-core": "0.7.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
export { applyNodedcTheme, missionDarkTheme, missionLightTheme, clearNodedcAccent, createAccentVariables, readableTextRgb } from "@nodedc/ui-core";
|
||||
export { applyNodedcTheme, 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";
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
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); }
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
export type PathBarItem = { label: string; path: string; kind: 'folder' | 'file'; current?: boolean };
|
||||
/** Compact Finder-style path row. Navigation and icon source belong to the app. */
|
||||
export function renderPathBar(target: HTMLElement, items: PathBarItem[], options: { onNavigate: (path: string) => void; icon: (kind: 'folder' | 'file') => Node }) {
|
||||
target.classList.add('nodedc-path-bar');
|
||||
target.setAttribute('role', 'navigation'); target.setAttribute('aria-label', 'Путь к файлу');
|
||||
const nodes: Node[] = [];
|
||||
items.forEach((item, index) => {
|
||||
if (index) { const separator = document.createElement('span'); separator.className = 'nodedc-path-bar__separator'; separator.textContent = '›'; separator.setAttribute('aria-hidden', 'true'); nodes.push(separator); }
|
||||
const part = document.createElement(item.kind === 'folder' ? 'button' : 'span');
|
||||
part.className = 'nodedc-path-bar__item'; part.title = item.path || item.label;
|
||||
if (item.current) part.setAttribute('aria-current', 'location');
|
||||
const icon = document.createElement('span'); icon.className = 'nodedc-path-bar__icon'; icon.setAttribute('aria-hidden', 'true'); icon.append(options.icon(item.kind));
|
||||
const text = document.createElement('span'); text.textContent = item.label;
|
||||
part.append(icon, text);
|
||||
if (part instanceof HTMLButtonElement) { part.type = 'button'; part.addEventListener('click', () => options.onNavigate(item.path)); }
|
||||
nodes.push(part);
|
||||
});
|
||||
target.replaceChildren(...nodes);
|
||||
}
|
||||
@@ -17,8 +17,6 @@ export interface ToolbarControllerOptions {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
}
|
||||
|
||||
export interface ToolbarController {
|
||||
@@ -114,7 +112,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
};
|
||||
|
||||
const updateMagnification = (coordinate: number) => {
|
||||
const vertical = options.placement !== "bottom" && options.placement !== "top";
|
||||
const vertical = options.placement !== "bottom";
|
||||
const toolbarRect = toolbar.getBoundingClientRect();
|
||||
const entries = buttons
|
||||
.map((button) => ({
|
||||
@@ -150,7 +148,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
hideTimer = window.setTimeout(() => {
|
||||
hideTimer = null;
|
||||
if (!hovering) hide();
|
||||
}, Math.max(0,Math.min(15000,options.hideDelay ?? NODEDC_TOOLBAR_DEFAULTS.hideDelay)));
|
||||
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay);
|
||||
};
|
||||
|
||||
const applyOptions = () => {
|
||||
@@ -210,7 +208,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
? event.clientX >= window.innerWidth - threshold
|
||||
: options.placement === "bottom"
|
||||
? event.clientY >= window.innerHeight - threshold
|
||||
: options.placement === "top" ? event.clientY <= threshold : event.clientX <= threshold;
|
||||
: event.clientX <= threshold;
|
||||
if (nearEdge) show();
|
||||
else if (visible && !hovering) scheduleHide();
|
||||
};
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
.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.10",
|
||||
"version": "0.7.0",
|
||||
"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.4",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export type ActivityIndicatorSize = "default" | "compact";
|
||||
|
||||
export interface ActivityIndicatorProps extends Omit<
|
||||
HTMLAttributes<HTMLSpanElement>,
|
||||
"aria-hidden" | "aria-label" | "children" | "role"
|
||||
> {
|
||||
size?: ActivityIndicatorSize;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function ActivityIndicator({
|
||||
size = "default",
|
||||
label,
|
||||
className,
|
||||
...props
|
||||
}: ActivityIndicatorProps) {
|
||||
const accessibleLabel = label?.trim() || undefined;
|
||||
|
||||
return (
|
||||
<span
|
||||
{...props}
|
||||
className={cn("nodedc-activity-indicator", className)}
|
||||
data-size={size === "default" ? undefined : size}
|
||||
role={accessibleLabel ? "status" : undefined}
|
||||
aria-label={accessibleLabel}
|
||||
aria-hidden={accessibleLabel ? undefined : "true"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
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 type { HTMLAttributes, ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
import { SortableList } from "./DragDrop.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
@@ -34,12 +31,6 @@ 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;
|
||||
@@ -56,11 +47,6 @@ export function AdminNavigationPanel({
|
||||
activeId,
|
||||
footer,
|
||||
closeLabel = "Закрыть администрирование",
|
||||
collapseLabel = "Свернуть панель навигации",
|
||||
expandLabel = "Развернуть панель навигации",
|
||||
collapsed: controlledCollapsed,
|
||||
defaultCollapsed = false,
|
||||
onCollapsedChange,
|
||||
navigationLabel = "Разделы администрирования",
|
||||
onClose,
|
||||
onItemChange,
|
||||
@@ -68,66 +54,40 @@ 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", "nodedc-admin-panel--navigation", className)} data-collapsed={collapsed ? "true" : undefined} data-has-contexts={contexts.length > 0 || contextSlot ? "true" : undefined} {...props}>
|
||||
<aside className={cn("nodedc-admin-panel", className)} data-has-contexts={contexts.length > 0 || contextSlot ? "true" : undefined} {...props}>
|
||||
<header className="nodedc-admin-panel__head">
|
||||
<div className="nodedc-admin-panel__titles" aria-hidden={collapsed || undefined}>
|
||||
<div>
|
||||
<p>{eyebrow}</p>
|
||||
<h2>{title}</h2>
|
||||
</div>
|
||||
<div className="nodedc-admin-panel__head-actions">
|
||||
<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}>
|
||||
{headerActions}
|
||||
<button type="button" className="nodedc-admin-panel__close" aria-label={closeLabel} onClick={onClose}>
|
||||
<Icon name="close" size={16} strokeWidth={1.6} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{contexts.length > 0 || contextSlot ? <div className="nodedc-admin-panel__context-area">
|
||||
{contextSlot ? <div className="nodedc-admin-panel__context-slot" hidden={collapsed}>{contextSlot}</div> : null}
|
||||
{contextSlot ? <div className="nodedc-admin-panel__context-slot">{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" hidden={collapsed}>{context.groupLabel}</span> : null}
|
||||
{context.groupLabel ? <span className="nodedc-admin-panel__group-label">{context.groupLabel}</span> : null}
|
||||
<div
|
||||
className={cn("nodedc-admin-context", context.onToggle && "nodedc-admin-context--split")}
|
||||
data-active={context.active ? "true" : undefined}
|
||||
>
|
||||
<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}>
|
||||
<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">
|
||||
<strong>{context.label}</strong>
|
||||
{context.description ? <small>{context.description}</small> : null}
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{context.onToggle ? (
|
||||
<button hidden={collapsed} type="button" className="nodedc-admin-context__toggle" aria-label={`Выбрать: ${context.label}`} onClick={context.onToggle}>
|
||||
<button 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}
|
||||
@@ -135,10 +95,20 @@ export function AdminNavigationPanel({
|
||||
</div>
|
||||
))}
|
||||
</div> : null}
|
||||
</div> : null}
|
||||
|
||||
<nav className="nodedc-admin-panel__nav" aria-label={navigationLabel}>
|
||||
{items.filter((item) => !item.sortable).map((item) => <div key={item.id}>{renderItem(item)}</div>)}
|
||||
{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.some((item) => item.sortable) ? (
|
||||
<SortableList
|
||||
className="nodedc-admin-panel__sortable-nav"
|
||||
@@ -148,15 +118,23 @@ export function AdminNavigationPanel({
|
||||
>
|
||||
{(item, { handle }) => (
|
||||
<div className="nodedc-admin-panel__sortable-row">
|
||||
{renderItem(item)}
|
||||
<span hidden={collapsed}>{handle}</span>
|
||||
<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}
|
||||
</div>
|
||||
)}
|
||||
</SortableList>
|
||||
) : null}
|
||||
</nav>
|
||||
|
||||
{footer ? <footer className="nodedc-admin-panel__footer" aria-hidden={collapsed || undefined}>{footer}</footer> : null}
|
||||
{footer ? <footer className="nodedc-admin-panel__footer">{footer}</footer> : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode, Ref } from "react";
|
||||
import type { ButtonHTMLAttributes, ReactNode } from "react";
|
||||
|
||||
export interface AppHeaderProps {
|
||||
brand: ReactNode;
|
||||
brandHref?: string;
|
||||
brandLabel?: string;
|
||||
/** Opt in only for a light, single-color mark, never a full-color image. */
|
||||
brandMonochrome?: boolean;
|
||||
left?: ReactNode;
|
||||
center?: ReactNode;
|
||||
right?: ReactNode;
|
||||
@@ -15,15 +13,14 @@ export function AppHeader({
|
||||
brand,
|
||||
brandHref,
|
||||
brandLabel = "NODE.DC",
|
||||
brandMonochrome = false,
|
||||
left,
|
||||
center,
|
||||
right,
|
||||
}: AppHeaderProps) {
|
||||
const brandNode = brandHref ? (
|
||||
<a className="nodedc-header__brand" data-monochrome={brandMonochrome || undefined} href={brandHref} aria-label={brandLabel}>{brand}</a>
|
||||
<a className="nodedc-header__brand" href={brandHref} aria-label={brandLabel}>{brand}</a>
|
||||
) : (
|
||||
<span className="nodedc-header__brand" data-monochrome={brandMonochrome || undefined} aria-label={brandLabel}>{brand}</span>
|
||||
<span className="nodedc-header__brand" aria-label={brandLabel}>{brand}</span>
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -74,11 +71,10 @@ export function HeaderNavigation<T extends string>({ label, value, items, onChan
|
||||
|
||||
export interface HeaderProfileProps {
|
||||
children: ReactNode;
|
||||
ref?: Ref<HTMLDivElement>;
|
||||
}
|
||||
|
||||
export function HeaderProfile({ children, ref }: HeaderProfileProps) {
|
||||
return <div ref={ref} className="nodedc-header__profile">{children}</div>;
|
||||
export function HeaderProfile({ children }: HeaderProfileProps) {
|
||||
return <div className="nodedc-header__profile">{children}</div>;
|
||||
}
|
||||
|
||||
export interface HeaderProfileButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className" | "style"> {}
|
||||
@@ -104,12 +100,11 @@ export interface HeaderWorkspaceProps {
|
||||
label: string;
|
||||
imageUrl?: string;
|
||||
kind?: "mark" | "avatar";
|
||||
monochrome?: boolean;
|
||||
}
|
||||
|
||||
export function HeaderWorkspace({ label, imageUrl, kind = "mark", monochrome = false }: HeaderWorkspaceProps) {
|
||||
export function HeaderWorkspace({ label, imageUrl, kind = "mark" }: HeaderWorkspaceProps) {
|
||||
return (
|
||||
<span className="nodedc-header__workspace" data-kind={kind} data-monochrome={monochrome || undefined} title={label}>
|
||||
<span className="nodedc-header__workspace" data-kind={kind} title={label}>
|
||||
{imageUrl ? <img src={imageUrl} alt="" /> : label.slice(0, 2).toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
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,7 +1,5 @@
|
||||
import {useCallback, useMemo, useState, type HTMLAttributes, type ReactNode} from "react";
|
||||
import {NavigationPanelState} from "./NavigationPanelState.js";
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
import {ApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
|
||||
export interface ApplicationShellProps extends Omit<HTMLAttributes<HTMLDivElement>, "content"> {
|
||||
@@ -11,10 +9,6 @@ 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;
|
||||
@@ -27,27 +21,16 @@ 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}
|
||||
@@ -56,7 +39,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"><NavigationPanelState.Provider value={navigationState}>{navigation}</NavigationPanelState.Provider></div> : null}
|
||||
{navigationOpen && navigation ? <div className="nodedc-app-shell__navigation">{navigation}</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>
|
||||
@@ -69,8 +52,6 @@ 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;
|
||||
@@ -87,7 +68,6 @@ export interface ApplicationPanelUtilityAction {
|
||||
icon: IconName;
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
pressed?: boolean;
|
||||
}
|
||||
|
||||
export function ApplicationPanel({
|
||||
@@ -95,7 +75,6 @@ export function ApplicationPanel({
|
||||
title,
|
||||
description,
|
||||
expanded = false,
|
||||
allowFullscreen = false,
|
||||
expandLabel = "Развернуть окно",
|
||||
closeLabel = "Закрыть окно",
|
||||
onExpandedChange,
|
||||
@@ -106,7 +85,7 @@ export function ApplicationPanel({
|
||||
className,
|
||||
...props
|
||||
}: ApplicationPanelProps) {
|
||||
const panel = (
|
||||
return (
|
||||
<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">
|
||||
@@ -123,8 +102,6 @@ export function ApplicationPanel({
|
||||
className="nodedc-application-panel__action"
|
||||
data-action="utility"
|
||||
aria-label={action.label}
|
||||
aria-pressed={action.pressed}
|
||||
data-active={action.pressed ? "true" : undefined}
|
||||
disabled={action.disabled}
|
||||
onClick={action.onClick}
|
||||
>
|
||||
@@ -151,5 +128,4 @@ export function ApplicationPanel({
|
||||
<div className="nodedc-application-panel__body">{children}</div>
|
||||
</section>
|
||||
);
|
||||
return allowFullscreen ? <ApplicationPanelFullscreen>{panel}</ApplicationPanelFullscreen> : panel;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ export interface ApplicationSidePanelProps extends Omit<HTMLAttributes<HTMLEleme
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
closeLabel?: string;
|
||||
headerActions?: ReactNode;
|
||||
footer?: ReactNode;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
@@ -24,7 +23,6 @@ export function ApplicationSidePanel({
|
||||
title,
|
||||
description,
|
||||
closeLabel = "Закрыть панель",
|
||||
headerActions,
|
||||
footer,
|
||||
onClose,
|
||||
children,
|
||||
@@ -44,7 +42,6 @@ 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>
|
||||
|
||||
@@ -1,28 +1,22 @@
|
||||
import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from "react";
|
||||
import { createAccentVariables, type RgbTuple } from "@nodedc/ui-core";
|
||||
import { cn } from "./cn.js";
|
||||
import { ActivityIndicator } from "./ActivityIndicator.js";
|
||||
|
||||
export type ButtonVariant = "primary" | "secondary" | "ghost" | "danger" | "accent";
|
||||
export type ButtonSize = "default" | "compact" | "dense";
|
||||
export type ButtonSize = "default" | "compact";
|
||||
export type ButtonShape = "default" | "pill" | "rounded";
|
||||
|
||||
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: ButtonVariant;
|
||||
/** Neutral primary actions remain white/gray independently of the product accent. */
|
||||
tone?: "theme" | "neutral";
|
||||
size?: ButtonSize;
|
||||
width?: "auto" | "full";
|
||||
shape?: ButtonShape;
|
||||
accent?: RgbTuple;
|
||||
icon?: ReactNode;
|
||||
/** Pending state belongs to this action; dimensions and accessible name stay unchanged. */
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button({
|
||||
variant = "secondary",
|
||||
tone = "theme",
|
||||
size = "default",
|
||||
width = "auto",
|
||||
shape = "default",
|
||||
@@ -32,8 +26,6 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
|
||||
children,
|
||||
style,
|
||||
type = "button",
|
||||
loading = false,
|
||||
disabled,
|
||||
...props
|
||||
}, ref) {
|
||||
const accentStyle = accent ? createAccentVariables(accent) : undefined;
|
||||
@@ -43,21 +35,14 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
|
||||
type={type}
|
||||
className={cn("nodedc-button", className)}
|
||||
data-variant={variant}
|
||||
data-tone={tone === "theme" ? undefined : tone}
|
||||
data-size={size === "default" ? undefined : size}
|
||||
data-width={width === "auto" ? undefined : width}
|
||||
data-shape={shape === "default" ? undefined : shape}
|
||||
style={accentStyle ? { ...accentStyle, ...style } : style}
|
||||
{...props}
|
||||
disabled={disabled || loading}
|
||||
aria-busy={loading || props["aria-busy"]}
|
||||
data-loading={loading || undefined}
|
||||
>
|
||||
<span className="nodedc-button__content">
|
||||
{icon ? <span className="nodedc-button__icon" aria-hidden="true">{icon}</span> : null}
|
||||
{children}
|
||||
</span>
|
||||
{loading ? <span className="nodedc-action-loading" aria-hidden="true"><ActivityIndicator size="compact" /></span> : null}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
@@ -65,21 +50,14 @@ 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",
|
||||
loading = false,
|
||||
disabled,
|
||||
...props
|
||||
}, ref) {
|
||||
return (
|
||||
@@ -88,16 +66,11 @@ 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}
|
||||
disabled={disabled || loading}
|
||||
aria-busy={loading || props["aria-busy"]}
|
||||
data-loading={loading || undefined}
|
||||
>
|
||||
{children}
|
||||
{loading ? <span className="nodedc-action-loading" aria-hidden="true"><ActivityIndicator size="compact" /></span> : null}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import type { ReactNode, CSSProperties } from "react";
|
||||
export interface ComparisonTableProps {
|
||||
density?: "default" | "compact";
|
||||
label: string;
|
||||
heading: ReactNode;
|
||||
columns: readonly { id: string; label: ReactNode }[];
|
||||
rows: readonly { id: string; label: ReactNode; cells: readonly ReactNode[] }[];
|
||||
}
|
||||
/** One label column, one non-collapsing column per entity. Scrolls as a unit. */
|
||||
export function ComparisonTable({ density = "default", label, heading, columns, rows }: ComparisonTableProps) {
|
||||
return <div className="nodedc-comparison-table" data-density={density} role="region" aria-label={label} tabIndex={0}
|
||||
style={{ "--nodedc-comparison-columns": columns.length + 1 } as CSSProperties}>
|
||||
<table aria-label={label}>
|
||||
<colgroup><col/>{columns.map(column => <col key={column.id}/>)}</colgroup>
|
||||
<thead><tr><th scope="col">{heading}</th>{columns.map(column => <th key={column.id} scope="col">{column.label}</th>)}</tr></thead>
|
||||
<tbody>{rows.map(row => <tr key={row.id}><th scope="row">{row.label}</th>{columns.map((column, index) => <td key={column.id}>{row.cells[index] ?? "—"}</td>)}</tr>)}</tbody>
|
||||
</table>
|
||||
</div>;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user