feat(ui): add docking, viewport controls and composed settings
Add shared dock layouts, navigation cube, range bands, progress actions and comparison surfaces. Extend toolbar menus and loading composition, and align tokens, registry entries, documentation and the living catalog.
This commit is contained in:
@@ -4,8 +4,12 @@ import { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTempla
|
||||
import {
|
||||
ActivityIndicator,
|
||||
LoadingRegion,
|
||||
Description,
|
||||
ComparisonTable,
|
||||
StatusBadge,
|
||||
ProgressBar,
|
||||
ProgressButton,
|
||||
LayerStackIndicator,
|
||||
AdminNavigationPanel,
|
||||
AppHeader,
|
||||
ApplicationPanel,
|
||||
@@ -19,6 +23,7 @@ import {
|
||||
ControlRow,
|
||||
Dropdown,
|
||||
DragDropRoot,
|
||||
DockLayout, DockHandle, balancedDockTree, type DockTree,
|
||||
DraggableItem,
|
||||
DropZone,
|
||||
FieldFrame,
|
||||
@@ -37,6 +42,8 @@ import {
|
||||
ResourceRow,
|
||||
ResourceList,
|
||||
SegmentedControl,
|
||||
SegmentedGroup,
|
||||
SegmentedButton,
|
||||
Select,
|
||||
ShareAccessModal,
|
||||
ShareLinkModal,
|
||||
@@ -50,6 +57,7 @@ import {
|
||||
ToastCard,
|
||||
ToastStack,
|
||||
Toolbar,
|
||||
NavigationCube,
|
||||
UserProfileMenu,
|
||||
useApplicationWorkspace,
|
||||
Window,
|
||||
@@ -213,7 +221,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
{
|
||||
title: "Редактирование",
|
||||
note: "Launcher / SEO",
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external"],
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "orthographic", "perspective", "select", "pen", "rectangle", "curve", "undo", "redo"],
|
||||
},
|
||||
{
|
||||
title: "Состояние и доступ",
|
||||
@@ -233,6 +241,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
];
|
||||
|
||||
const iconLabels: Record<IconName, string> = {
|
||||
"add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить",
|
||||
activity: "Активность",
|
||||
alert: "Предупреждение",
|
||||
apps: "Приложения",
|
||||
@@ -275,6 +284,7 @@ const iconLabels: Record<IconName, string> = {
|
||||
plus: "Добавить",
|
||||
profile: "Профиль",
|
||||
refresh: "Обновить",
|
||||
"rotate-clockwise": "Повернуть по часовой стрелке",
|
||||
save: "Сохранить",
|
||||
search: "Поиск",
|
||||
settings: "Настройки",
|
||||
@@ -348,6 +358,7 @@ export function CatalogApp() {
|
||||
const [createModuleDescription, setCreateModuleDescription] = useState("");
|
||||
const [deleteModuleOpen, setDeleteModuleOpen] = useState(false);
|
||||
const [pageRemovalId, setPageRemovalId] = useState<string | null>(null);
|
||||
const [previewLayers, setPreviewLayers] = useState<string[]>(["source"]);
|
||||
const [applicationMode, setApplicationMode] = useState<"edit" | "preview">("edit");
|
||||
const [designProfileSaveOpen, setDesignProfileSaveOpen] = useState(false);
|
||||
const [designProfileSaveMode, setDesignProfileSaveMode] = useState<"save" | "save-as">("save");
|
||||
@@ -365,6 +376,7 @@ 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");
|
||||
@@ -379,6 +391,7 @@ export function CatalogApp() {
|
||||
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);
|
||||
@@ -424,6 +437,9 @@ export function CatalogApp() {
|
||||
icon512: "/favicon/icon-512.png",
|
||||
});
|
||||
const pendingFaviconIcoRef = useRef<Blob | null>(null);
|
||||
const [cubeSize,setCubeSize]=useState(66);
|
||||
const [cubeEdgeOpacity,setCubeEdgeOpacity]=useState(1);
|
||||
const [cubeDirection,setCubeDirection]=useState<number[]>([0,0,1]);
|
||||
const [toolbarPlacement, setToolbarPlacement] = useState<ToolbarPlacement>("bottom");
|
||||
const [toolbarBg, setToolbarBg] = useState("#111115");
|
||||
const [toolbarBorder, setToolbarBorder] = useState("#111117");
|
||||
@@ -432,6 +448,8 @@ export function CatalogApp() {
|
||||
const [toolbarMaxSize, setToolbarMaxSize] = useState(87);
|
||||
const [toolbarLensCount, setToolbarLensCount] = useState(5);
|
||||
const [toolbarAutoHide, setToolbarAutoHide] = useState(false);
|
||||
const [toolbarHideDelay,setToolbarHideDelay]=useState(5000);
|
||||
const [toolbarGap,setToolbarGap]=useState(10);
|
||||
const [shareEmail, setShareEmail] = useState("");
|
||||
const [shareRole, setShareRole] = useState<ShareRole>("editor");
|
||||
const [shareMessage, setShareMessage] = useState("");
|
||||
@@ -495,6 +513,8 @@ export function CatalogApp() {
|
||||
if (typeof stored.toolbar?.minSize === "number") setToolbarMinSize(stored.toolbar.minSize);
|
||||
if (typeof stored.toolbar?.maxSize === "number") setToolbarMaxSize(stored.toolbar.maxSize);
|
||||
if (typeof stored.toolbar?.lensCount === "number") setToolbarLensCount(stored.toolbar.lensCount);
|
||||
if (typeof stored.toolbar?.hideDelay === "number") setToolbarHideDelay(stored.toolbar.hideDelay);
|
||||
if (typeof stored.toolbar?.gap === "number") setToolbarGap(stored.toolbar.gap);
|
||||
if (typeof stored.toolbar?.autoHide === "boolean") setToolbarAutoHide(stored.toolbar.autoHide);
|
||||
}, []);
|
||||
|
||||
@@ -596,13 +616,15 @@ export function CatalogApp() {
|
||||
}
|
||||
const toolbar = stored.toolbar;
|
||||
if (toolbar) {
|
||||
if (toolbar.placement === "left" || toolbar.placement === "right" || toolbar.placement === "bottom") setToolbarPlacement(toolbar.placement);
|
||||
if (toolbar.placement === "left" || toolbar.placement === "right" || toolbar.placement === "bottom" || toolbar.placement === "top") setToolbarPlacement(toolbar.placement);
|
||||
if (toolbar.background) setToolbarBg(toolbar.background);
|
||||
if (toolbar.border) setToolbarBorder(toolbar.border);
|
||||
if (toolbar.outline) setToolbarOutline(toolbar.outline);
|
||||
if (typeof toolbar.minSize === "number") setToolbarMinSize(toolbar.minSize);
|
||||
if (typeof toolbar.maxSize === "number") setToolbarMaxSize(toolbar.maxSize);
|
||||
if (typeof toolbar.lensCount === "number") setToolbarLensCount(toolbar.lensCount);
|
||||
if (typeof toolbar.hideDelay === "number") setToolbarHideDelay(toolbar.hideDelay);
|
||||
if (typeof toolbar.gap === "number") setToolbarGap(toolbar.gap);
|
||||
if (typeof toolbar.autoHide === "boolean") setToolbarAutoHide(toolbar.autoHide);
|
||||
}
|
||||
setLayoutSaveState("saved");
|
||||
@@ -1071,6 +1093,7 @@ export function CatalogApp() {
|
||||
maxSize: toolbarMaxSize,
|
||||
lensCount: toolbarLensCount,
|
||||
autoHide: toolbarAutoHide,
|
||||
hideDelay:toolbarHideDelay,gap:toolbarGap,
|
||||
},
|
||||
};
|
||||
const response = await fetch("/api/layout", {
|
||||
@@ -1279,6 +1302,7 @@ export function CatalogApp() {
|
||||
{ value: "left", label: "Слева" },
|
||||
{ value: "right", label: "Справа" },
|
||||
{ value: "bottom", label: "Снизу" },
|
||||
{ value: "top", label: "Сверху" },
|
||||
]}
|
||||
onChange={(value) => setToolbarPlacement(value as ToolbarPlacement)}
|
||||
/>
|
||||
@@ -1293,6 +1317,8 @@ export function CatalogApp() {
|
||||
<RangeControl label="Максимальный размер" value={toolbarMaxSize} min={28} max={88} formatValue={(value) => `${value}px`} onChange={(value) => setToolbarMaxSize(Math.max(toolbarMinSize, Math.round(value)))} />
|
||||
<RangeControl label="Линза" value={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}/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -1304,8 +1330,8 @@ export function CatalogApp() {
|
||||
<>
|
||||
<ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow>
|
||||
<RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} />
|
||||
<div style={{ height: 180 }} title="Тонкая шкала: границы справа; подпись и значение закреплены в центре, контраст следует заливке"><RangeControl orientation="vertical" label="Срез" value={brightness / 100 * 52.7 - 1.2} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={(value) => setBrightness((value + 1.2) / 52.7 * 100)} /></div>
|
||||
<div style={{ height: 180, display: 'flex', justifyContent: 'flex-end' }} title="Шкала справа: границы слева; без контура при drag и фокусе, фокус подчёркивает подпись"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={brightness / 100 * 52.7 - 1.2} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={(value) => setBrightness((value + 1.2) / 52.7 * 100)} /></div>
|
||||
<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} />
|
||||
</>
|
||||
),
|
||||
@@ -1352,9 +1378,10 @@ export function CatalogApp() {
|
||||
case "controls":
|
||||
return (
|
||||
<div className="catalog-grid">
|
||||
<Preview title="Navigation cube" note="faces / edges / corners"><NavigationCube edgeOpacity={cubeEdgeOpacity} size={cubeSize} quaternion={[.28,-.36,.12,.88]} onSelect={setCubeDirection}/><RangeControl label="Размер 3D-куба" value={cubeSize} min={48} max={160} step={1} onChange={setCubeSize} formatValue={v=>`${v} px`}/><RangeControl label="Прозрачность линий куба" value={1-cubeEdgeOpacity} min={0} max={1} step={.05} onChange={v=>setCubeEdgeOpacity(1-v)} formatValue={v=>`${Math.round(v*100)}%`}/><p>{cubeDirection.join(" · ")}</p></Preview>
|
||||
<Preview title="Selection" note="integrated / split / inline">
|
||||
<div className="catalog-form">
|
||||
<FieldFrame label="Hub / integrated select">
|
||||
<FieldFrame label="Hub / integrated select" labelPlacement="below">
|
||||
<Select label="Статус" value={selectedStatus} options={[...selectOptions]} searchable onChange={setSelectedStatus} />
|
||||
</FieldFrame>
|
||||
<FieldFrame label="Select / независимое действие строки">
|
||||
@@ -1398,6 +1425,7 @@ export function CatalogApp() {
|
||||
>
|
||||
{({ close }) => (
|
||||
<>
|
||||
<Select label="Вложенный выбор статуса" value={selectedStatus} options={[...selectOptions]} onChange={setSelectedStatus} />
|
||||
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="edit" /><span className="nodedc-dropdown-option__label">Переименовать</span></button>
|
||||
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="copy" /><span className="nodedc-dropdown-option__label">Дублировать</span></button>
|
||||
<button className="nodedc-dropdown-option" data-nodedc-option onClick={close}><Icon name="folder" /><span className="nodedc-dropdown-option__label">Архивировать</span></button>
|
||||
@@ -1439,6 +1467,27 @@ export function CatalogApp() {
|
||||
<LoadingRegion loading label="Ожидаем содержимое" />
|
||||
</Preview>
|
||||
<Preview title="Лампы состояния" note="один индикатор без дублирующего значка"><StatusBadge variant="indicator" tone="success" aria-label="Готово" title="Готово" /><StatusBadge variant="indicator" aria-label="Недоступно" title="Недоступно" /><StatusBadge tone="danger" pulse>Требуется внимание</StatusBadge></Preview>
|
||||
<Preview title="Прогресс действия" note="idle / pending / disabled">
|
||||
<div className="catalog-inline catalog-inline--wrap">
|
||||
<ProgressButton label="Проанализировать" icon={<Icon name="layers" />} />
|
||||
<ProgressButton label="Проанализировать" icon={<LayerStackIndicator />} progress={{label:"Анализ поверхности · 29 / 96",value:29/96}} />
|
||||
<ProgressButton label="Проанализировать" icon={<LayerStackIndicator />} progress={{label:"Подготовка данных"}} />
|
||||
<ProgressButton label="Проанализировать" disabled icon={<Icon name="layers" />} />
|
||||
</div>
|
||||
</Preview>
|
||||
<Preview title="Независимые слои" note="multiple / empty / all">
|
||||
<SegmentedGroup label="Слои и память">
|
||||
<SegmentedButton active={previewLayers.includes("gaussian")} aria-pressed={previewLayers.includes("gaussian")}
|
||||
onClick={()=>setPreviewLayers(current=>current.includes("gaussian")?current.filter(v=>v!=="gaussian"):[...current,"gaussian"])}>Gaussian</SegmentedButton>
|
||||
<SegmentedButton disabled>Недоступный слой</SegmentedButton>
|
||||
<Dropdown surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><SegmentedButton
|
||||
ref={setTriggerRef} active={open} aria-expanded={open} aria-haspopup="dialog" aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
|
||||
<p>Накопленные проезды этой локации.</p>
|
||||
</Dropdown>
|
||||
</SegmentedGroup>
|
||||
<SegmentedControl selectionMode="multiple" label="Слои сцены" value={previewLayers} onChange={setPreviewLayers}
|
||||
items={[{value:"source",label:"Источник"},{value:"geometry",label:"Геометрия"},{value:"unavailable",label:"Недоступно",disabled:true}]} />
|
||||
</Preview>
|
||||
<Preview title="Линейный прогресс" note="измеренный / неизвестный / завершённый">
|
||||
<ProgressBar label="Подготовка" value={0.6} valueText="Три этапа из пяти" />
|
||||
<ProgressBar label="Получение сведений" />
|
||||
@@ -1456,9 +1505,11 @@ export function CatalogApp() {
|
||||
<Preview title="Главная и окружение" note="единые компоненты · сохранение в памяти каталога">
|
||||
<EnvironmentCatalogDemo />
|
||||
</Preview>
|
||||
<Preview title="Оконные действия" note="круг `46 px` · действия footer справа" className="catalog-preview--compact">
|
||||
<div className="catalog-window-actions-demo">
|
||||
<Preview title="Действия поверх сцены" note="круг `32.2 px` · единый viewport-канон 70%" className="catalog-preview--compact">
|
||||
<div className="catalog-window-actions-demo nodedc-scene-controls">
|
||||
<SegmentedControl label="Инструмент сцены" value={applicationMode} items={[{value:"edit",label:"Обзор"},{value:"preview",label:"Точки"}]} onChange={setApplicationMode}/>
|
||||
<Button shape="pill" icon={<Icon name="refresh" />}>Обновить источник</Button>
|
||||
<Select label="Статус примера сцены" value={selectedStatus} options={[...selectOptions]} onChange={setSelectedStatus} />
|
||||
<IconButton label="Добавить"><Icon name="plus" /></IconButton>
|
||||
<IconButton label="Развернуть"><Icon name="expand" /></IconButton>
|
||||
<IconButton label="Закрыть"><Icon name="close" /></IconButton>
|
||||
@@ -1493,6 +1544,7 @@ export function CatalogApp() {
|
||||
setWorkspaceWindowDemoOpen(false);
|
||||
setWorkspaceWindowDemoMaximized(false);
|
||||
}}
|
||||
resizeIndicator={false}
|
||||
title="Визуальный канал"
|
||||
subtitle="WORKSPACE / AUXILIARY VIEW"
|
||||
status="LIVE"
|
||||
@@ -1533,6 +1585,12 @@ export function CatalogApp() {
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">Граница изменяет контролируемую долю панелей; клавиши и pointer используют одни ограничения, а resize контейнера не сбрасывает выбранное соотношение.</p>
|
||||
</Preview>
|
||||
<Preview title="Dock layout" note="center swap / four edges / keyboard" className="catalog-preview--wide">
|
||||
<div style={{height:420}}><DockLayout tree={dockDemoTree} onTreeChange={setDockDemoTree}
|
||||
panels={[{id:'camera',label:'Камера'},{id:'depth',label:'Глубина'},{id:'map',label:'Карта'},{id:'scene',label:'Сцена',minimumSize:{width:320,height:280}}]}
|
||||
renderPanel={id=><GlassSurface tone="soft" radius="panel" style={{height:'100%'}}><DockHandle id={id} label={id}/><strong>{id}</strong></GlassSurface>}/></div>
|
||||
<p>Центр — обмен, край — разделение. Сцена не сжимается ниже 320 × 280; при нехватке места прокручивается рабочая область. Контур показывает место окна. Enter на ручке включает управление клавиатурой.</p>
|
||||
</Preview>
|
||||
<Preview title="Application side panel" note="end / push / controlled" className="catalog-preview--wide catalog-side-panel-preview">
|
||||
<div className="catalog-side-panel-demo">
|
||||
{sidePanelDemoOpen ? (
|
||||
@@ -1542,7 +1600,7 @@ export function CatalogApp() {
|
||||
description="Theme-aware application panel"
|
||||
onClose={() => setSidePanelDemoOpen(false)}
|
||||
>
|
||||
<Inspector variant="panel" sections={environmentSections.slice(0, 3)} defaultOpen={[environmentSections[0]?.id ?? ""]} singleOpen />
|
||||
<Inspector variant="panel" sections={environmentSections.slice(0, 3).map(section=>({...section,action:{label:`Действие секции ${section.label}`,icon:<Icon name="edit"/>,onAction:()=>setInspectorOpen(true)}}))} defaultOpen={[environmentSections[0]?.id ?? ""]} singleOpen />
|
||||
</ApplicationSidePanel>
|
||||
) : (
|
||||
<Button shape="pill" icon={<Icon name="panel" />} onClick={() => setSidePanelDemoOpen(true)}>Открыть правую панель</Button>
|
||||
@@ -2240,7 +2298,7 @@ export function CatalogApp() {
|
||||
/>
|
||||
|
||||
{guidelineOpen && studioContext === "visual" ? (
|
||||
<Toolbar<CatalogSection>
|
||||
<Toolbar<CatalogSection | "hold">
|
||||
placement={toolbarPlacement}
|
||||
background={toolbarBg}
|
||||
border={toolbarBorder}
|
||||
@@ -2250,13 +2308,15 @@ export function CatalogApp() {
|
||||
maxSize={toolbarMaxSize}
|
||||
lensCount={toolbarLensCount}
|
||||
autoHide={toolbarAutoHide}
|
||||
items={(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
|
||||
hideDelay={toolbarHideDelay} gap={toolbarGap}
|
||||
items={[{id:"hold",label:toolbarAutoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!toolbarAutoHide,onSelect:()=>setToolbarAutoHide(v=>!v)}, ...(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
|
||||
id,
|
||||
label: item.title,
|
||||
shortcut: id === "icons" ? "I" : undefined,
|
||||
icon: item.icon,
|
||||
active: activeSection === id,
|
||||
onSelect: openSection,
|
||||
}))}
|
||||
onSelect: () => openSection(id),
|
||||
}))]}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -2368,14 +2428,14 @@ export function CatalogApp() {
|
||||
|
||||
<FoundrySettingsModal open={foundrySettingsOpen} isAdmin={isFoundryAdmin} onClose={() => setFoundrySettingsOpen(false)} />
|
||||
|
||||
<FeatureSettingsWindow open={featureSettingsDemoOpen} title="Настройки модуля"
|
||||
<FeatureSettingsWindow open={featureSettingsDemoOpen} title="Настройки модуля" subtitle="Настройки и меню доступны также в полноэкранном просмотре"
|
||||
identity={{ title: 'Модуль', subtitle: 'Пример общего компонента', avatarLabel: 'DC' }}
|
||||
sections={[{ id: 'general', label: 'Основное', icon: 'settings' }, { id: 'details', label: 'Сведения', icon: 'clipboard' }]}
|
||||
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>
|
||||
: <ResourceList><li><ResourceRow title="Версия" metadata="1.0" /></li><li><ResourceRow title="Состояние" metadata="Доступен" /></li></ResourceList>}
|
||||
: <SettingsCard title="Сведения" description="Общее пояснение к данным."><Description>Текст в теле использует тот же стиль.</Description><ComparisonTable density="compact" label="Сравнение устройств" heading="Устройство" columns={Array.from({length:4},(_,i)=>({id:String(i),label:`Устройство ${i+1}`}))} rows={Array.from({length:24},(_,i)=>({id:String(i),label:`Показатель ${i+1}`,cells:['12','34','56','78']}))}/><LoadingRegion aggregate loading label="Загрузка сведений"><LoadingRegion loading label="Вложенный запрос A"/><LoadingRegion loading label="Вложенный запрос B"/></LoadingRegion></SettingsCard>}
|
||||
</FeatureSettingsWindow>
|
||||
|
||||
<Window
|
||||
|
||||
@@ -61,6 +61,8 @@ export interface StoredLayout {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
};
|
||||
/** Design fragments are keyed by a registered Page Library type/version. */
|
||||
pageTypes?: Record<string, DesignProfilePageFragment>;
|
||||
|
||||
+88
-6
@@ -45,7 +45,7 @@ Icon-only action по умолчанию круглый. Квадратная к
|
||||
|
||||
## Field
|
||||
|
||||
FieldFrame объединяет label, control, hint и description. TextField/TextAreaField реализуют стандартные текстовые поля. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
|
||||
FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
|
||||
|
||||
Приложение не должно вручную собирать label и input, если подходит Field. Ошибка и validation state будут расширением этого контракта, а не локальным классом приложения.
|
||||
|
||||
@@ -57,17 +57,17 @@ FieldFrame объединяет label, control, hint и description. TextField/T
|
||||
|
||||
## RangeControl
|
||||
|
||||
Вертикальная шкала занимает `0.4 × --nodedc-control-height` по ширине (18.4 px при базовой высоте 46 px): на 20% тоньше первоначального варианта 11.09.2026. Высота, диапазон и управление сохраняются.
|
||||
Вертикальная шкала занимает `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"` — утверждённый владельцем 11.09.2026 вертикальный вариант для высоты среза. Максимум расположен сверху, заливка растёт снизу, стрелки вверх/вниз меняют значение. Подпись, числовое значение, контраст и focus принадлежат тому же компоненту. Узкий вертикальный вариант использует drag/клавиатуру без inline-редактора; точные границы задаёт домен.
|
||||
`RangeControl orientation="vertical"` показывает текущую верхнюю границу среза у края заливки и нижнюю сохранённую границу `min` внизу. `formatLimit` форматирует эти числа без единиц по умолчанию. Центральная надпись отсутствует; имя и `formatValue(value)` остаются доступны screen reader. Верхняя подпись следует значению, ограничена высотой шкалы и не перекрывает нижнюю у минимума. `limitSide="left"` зеркалит подписи для шкалы справа от сцены.
|
||||
|
||||
Последнее уточнение владельца от 19.09.2026 заменяет промежуточный вариант с границами внутри: верхняя и нижняя границы вынесены с внутренней стороны сцены, читаются горизонтально и сохраняют цвет theme text, не меняясь от заливки. `formatLimit` форматирует их отдельно от текущего значения, без единицы измерения по умолчанию. По умолчанию это правая сторона; `limitSide="left"` зеркалит только внешние границы для шкалы, закреплённой справа от сцены. В центре неподвижно расположена строка «подпись · значение»; единица остаётся в `formatValue`. Внутренний и наружный шрифт уменьшены на 10% относительно токенов sm/xs. Два совпадающих центральных текстовых слоя и маска формы заливки меняют контраст ровно по её границе, в том числе посередине символа.
|
||||
Для двухстороннего среза передайте `value={[lower, upper]}` и `onChange={(band) => …}`. Обе границы независимы; заливка показывает оставшийся между ними слой. Drag выбирает ближайшую границу и удерживает её до отпускания. Границы не пересекаются; совпавшие можно снова развести движением вниз/вверх. Два native range доступны отдельно с клавиатуры и screen reader (`lowerLabel`/`upperLabel`). Подписи следуют обеим границам и разводятся у совпадения; центрального текста нет. Home/End возвращают выбранную границу к допустимому краю. Домен отдельно отключает нижнее/верхнее отсечение на соответствующем краю. Скалярный режим сохраняет совместимость.
|
||||
|
||||
Уточнение от 20.09.2026: вертикальная шкала не получает border, outline или тень по периметру ни в одном состоянии. Native range может сохранять `:focus-visible` и после pointer-ввода, поэтому этот селектор больше не рисует контур. Доступный фокус обозначается подчёркиванием центральной подписи в обоих контрастных слоях; стрелки и Home/End продолжают работать нативно.
|
||||
В скалярном режиме заливка растёт снизу. Drag, стрелки и Home/End работают нативно. Фокус подчёркивает движущееся значение; контур, border и тень не добавляются. Домен определяет диапазон и отключение среза у верхнего края.
|
||||
|
||||
## ColorField
|
||||
|
||||
@@ -77,6 +77,10 @@ Engine/BIM-геометрия color field: круглый swatch и HEX-знач
|
||||
|
||||
## Dropdown
|
||||
|
||||
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. It does not change the material. Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
|
||||
|
||||
For opaque controls directly above imagery, `nodedc-scene-controls` adds the same geometry plus a common opaque field surface. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
|
||||
|
||||
Dropdown владеет floating-layer поведением:
|
||||
|
||||
- рендерится в `document.body`;
|
||||
@@ -89,7 +93,7 @@ Dropdown владеет floating-layer поведением:
|
||||
- закрывается, когда trigger полностью уходит за границы viewport;
|
||||
- закрывается по outside pointer и Escape;
|
||||
- после Escape возвращает фокус на реальную trigger-кнопку, не закрывая родительское окно;
|
||||
- закрывает другой открытый dropdown.
|
||||
- закрывает другой корневой dropdown; вложенный Select сохраняет родительское меню, выбор закрывает только Select, Escape закрывает самый глубокий слой.
|
||||
|
||||
Содержимое меню передаётся приложением. Selection, action menu и filter menu используют один engine.
|
||||
|
||||
@@ -200,6 +204,10 @@ 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.
|
||||
@@ -272,6 +280,12 @@ setup-команды, сохранение, API и права принадлеж
|
||||
|
||||
`SettingsCard` фиксирует нейтральную структуру админской группы: eyebrow/title/description/actions/body. `Switch` покрывает компактное включение/видимость внутри таких групп. Данные секции, сохранение и права остаются в consumer.
|
||||
|
||||
Промежуточный loading-контейнер не должен обнулять вертикальный ритм тела
|
||||
карточки. Если `LoadingRegion` оборачивает несколько полей, consumer передаёт
|
||||
ему свою stack-компоновку с gap из spacing tokens. Связанные действия размещаются
|
||||
в flex-группе с token gap и переносом, а не соседними кнопками без интервала.
|
||||
Это применяется также к условно появляющимся фильтрам и действиям импорта/экспорта.
|
||||
|
||||
Бегунок включённого `Switch` использует `--nodedc-on-accent-rgb`, поэтому
|
||||
сохраняет контраст с белым, цветным и тёмным акцентом. Выключенный track
|
||||
наследует тон темы от text-primary. Длина track не сжимается при переносе
|
||||
@@ -390,3 +404,71 @@ StatusBadge `variant="indicator"` отображает только одну л
|
||||
Контурная клавиша удержания с контролируемым pressed-состоянием. [Контракт](KEY_BUTTON.md).
|
||||
|
||||
`Window` и `FeatureSettingsWindow`: `headerActions` размещает обновление и другие контекстные IconButton рядом с закрытием; footer предназначен для завершения формы.
|
||||
|
||||
### Fullscreen portal ownership
|
||||
|
||||
React `Window` (including `FeatureSettingsWindow`) and `Dropdown` (including Select and ColorField) mount into the active native fullscreen element, falling back to document.body. Menu geometry remains viewport-fixed. Consumers must let an open dialog/menu handle Escape before restoring the fullscreen viewer.
|
||||
|
||||
### Scene window and accordion actions
|
||||
|
||||
`WorkspaceWindow resizeIndicator={false}` скрывает только видимый уголок. Размер по-прежнему меняется перетаскиванием правого нижнего угла или стрелками при фокусе на ручке; фокус остаётся видимым.
|
||||
|
||||
`InspectorSectionSpec.action` задаёт `{label, icon, disabled?, onAction}`. Это отдельная от раскрывающего заголовка кнопка: её нажатие не раскрывает секцию. В варианте `panel` она стоит левее стрелки; стрелка смотрит вниз в закрытом состоянии и вверх в открытом.
|
||||
|
||||
## DockLayout
|
||||
|
||||
`DockLayout` and `DockHandle` compose stable viewport hosts over a serializable `DockTree`.
|
||||
Drop at the center to exchange views; the left/right/top/bottom zones split that destination.
|
||||
Removing the source collapses its old empty branch. The contour uses the resulting tree,
|
||||
so it previews the actual final position, even when the destination expands after removal.
|
||||
Any number of available panels can be composed with nested horizontal and vertical splits.
|
||||
`focusedId` expands a view without reparenting media; the application persists `tree`.
|
||||
There is no permanent outline. Outside/self drops and Escape leave the tree unchanged.
|
||||
Keyboard: Enter/Space on the grip, Tab/Shift+Tab to choose a destination, arrows for edges,
|
||||
Home for center, Enter to commit, Escape to cancel. Separators retain SplitPane keyboard sizing.
|
||||
|
||||
The pure tree types, geometry and operations are exported by `@nodedc/ui-core`; React re-exports them for view consumers. Domain adapters import the framework-neutral package.
|
||||
|
||||
## ProgressButton
|
||||
|
||||
Фаза и полоса выполнения внутри инициирующей кнопки. `LayerStackIndicator` анимирует канонический значок layers. [API и состояния](PROGRESS_BUTTON.md).
|
||||
|
||||
## Description
|
||||
|
||||
`Description` is the shared explanatory paragraph. It matches `SettingsCard.description`: inherited family, small font token (12px), regular 400, muted text token, line-height 1.4. Use it for help below values, not a local paragraph override.
|
||||
|
||||
## ComparisonTable
|
||||
|
||||
`ComparisonTable` accepts a heading, entity columns and labelled rows. Semantic headers, a 9rem minimum per column and horizontal overflow preserve 1–N comparisons in narrow panels. The keyboard scrollport contains wheel overscroll; no borders or cards per entity. Data freshness stays application-owned.
|
||||
|
||||
|
||||
DockLayout panels accept minimumSize in CSS pixels. Recursive minimums apply to
|
||||
all ancestor splits and keyboard/pointer resizing. Below the whole-layout limit,
|
||||
the canvas scrolls instead of shrinking or overlapping panel contents.
|
||||
ComparisonTable density="compact" reduces 31px rows to21px (about32%). Its label
|
||||
column has a120px minimum, each data column88px, and available width is shared by
|
||||
data columns. Hosts provide matching content limits; typography stays12px.
|
||||
|
||||
### Toolbar in scene editors
|
||||
|
||||
Pass `container` and portal the shared `Toolbar` into a positioned viewport to keep it and its autohide reveal edge inside that viewport (including fullscreen). Omission retains window scope. Item `shortcut` adds a native tooltip and `aria-keyshortcuts`; the owning editor implements the scoped key binding. Focus reveals a hidden dock. Editing icons `select`, `pen`, `rectangle`, `curve`, `undo`, and `redo` use the shared Lucide adapter and catalog.
|
||||
|
||||
Toolbar item `menu` composes the canonical `Dropdown`, anchored to the tool button. Supply content or a function receiving `close`; menu controls remain canonical buttons, checkers or selects.
|
||||
|
||||
### Toolbar menus and settings
|
||||
|
||||
Toolbar supports left/right/top/bottom, minimum/maximum size, lens count, gap,
|
||||
material colors, autohide and `hideDelay` in milliseconds (0–15000). Applications
|
||||
persist these props in their existing preferences. A viewport `container` owns
|
||||
its reveal edges. Item menus open inward beyond the maximum magnified button
|
||||
extent; the shared Dropdown reserves that envelope throughout spring motion.
|
||||
Once a menu is open, hovering another menu trigger changes it. A 300 ms bounded
|
||||
pointer-intent triangle protects diagonal travel to the current menu. Clicking
|
||||
or keyboard activation remains immediate. Open menus suspend autohide. Selected
|
||||
menu choices use the neutral primary Button state as well as `aria-pressed`.
|
||||
|
||||
### Toolbar: Hold and scene dismissal (2026-10-21)
|
||||
|
||||
The first optional Hold action controls the existing persisted `autoHide` setting. Disabling autohide cancels any pending hide timer. Dropdown observes outside pointerdown in capture phase; viewport Toolbar consumes background dismissal before canvas editing tools, while other controls retain their normal actions. Nested menus and trigger clicks retain lineage behavior. Catalog includes the Hold action.
|
||||
|
||||
- `NavigationCube`: [orientation cube](NAVIGATION_CUBE.md), controlled face/edge/corner navigation.
|
||||
|
||||
+3
-1
@@ -20,7 +20,7 @@
|
||||
| --- | --- |
|
||||
| Окно и слой | `close`, `plus`, `expand`, `minimize`, `refresh`, `panel`, `apps`, `layers` |
|
||||
| Навигация | `chevron-left`, `chevron-right`, `chevron-down`, `grid`, `list`, `sliders`, `search` |
|
||||
| Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external` |
|
||||
| Редактирование | `save`, `edit`, `trash`, `copy`, `upload`, `download`, `external`, `rotate-clockwise` |
|
||||
| Состояние и доступ | `check`, `alert`, `activity`, `lock`, `key`, `shield`, `circle`, `eye`, `eye-off` |
|
||||
| Сущности | `profile`, `users`, `building`, `globe`, `database`, `network`, `inbox`, `mail` |
|
||||
| Контент | `camera`, `plan`, `play`, `stop`, `image`, `video`, `file`, `folder`, `clipboard`, `settings`, `terminal` |
|
||||
@@ -47,3 +47,5 @@ hover, focus, disabled и pending принадлежат кнопке. `activity
|
||||
обозначением телеметрии и состояния, а не отправки команд.
|
||||
|
||||
Раскрытие строки вниз: `chevron-down` в закрытом состоянии, `chevron-up` в открытом; кнопка сообщает `aria-expanded` и `aria-controls`.
|
||||
|
||||
`rotate-clockwise` — поворот изображения по часовой стрелке. Применение: независимая ориентация объективов Insta360 в Центре наблюдения Mission Core, по запросу владельца 09.10.2026. Шаг задаёт приложение; подпись кнопки сообщает угол. Состояния и геометрия принадлежат каноническому `IconButton`.
|
||||
|
||||
@@ -30,3 +30,7 @@ Living catalog показывает action, icon-action и content loading. Из
|
||||
## Проверка кандидата 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.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# NavigationCube
|
||||
|
||||
Owner-requested on 2026-10-21 for semantic editing. Reference: BIM Viewer `frontend/dcViewer.js` NavCube, size 100; Xeokit renderer coupling is replaced by a controlled SVG adapter, with no extra GPU context.
|
||||
|
||||
`quaternion` is camera-to-world, Y up; `onSelect([x,y,z])` points from target to camera. Six face centres, twelve edge directions and eight corner directions. Adjacent face regions share the same direction. The consumer preserves framing, projection and semantic data. The cube reflects free camera rotation. Projection is a separate explicit control. Top is +Y, front is +Z, right is +X; domain adapters convert coordinate conventions.
|
||||
|
||||
Visible hit regions have native tooltips, hover, keyboard focus, Enter/Space activation and disabled state. Face/edge strokes are structural. Tokens own colors. No motion or GPU loop in the component. Catalog controls section demonstrates the cube.
|
||||
|
||||
`add-point` is a centered circled plus, distinct from whole-element `plus`. Projection icons: `orthographic`, `perspective`.
|
||||
|
||||
Presentation props: `size` in CSS pixels (default 66), `face`, `text`, `edge`, `hover`, `hoverText`, `opacity`. Consumer preferences may persist these; omitted colors inherit theme tokens. Core exposes these under viewport settings → 3D-куб.
|
||||
|
||||
Face labels use the projected face-local right/up basis, including foreshortening and rotation; they never billboard towards the screen. `edgeOpacity` (0–1, default 1) independently controls structural grid/edge strokes without fading faces or labels.
|
||||
@@ -20,3 +20,5 @@ SettingsCard и nodedc-empty-state закрепляют эти размеры в
|
||||
только 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.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# ProgressButton
|
||||
|
||||
Принят владельцем Mission Core 10.10.2026: этап чуть выше центра кнопки,
|
||||
заполняющаяся полоса ниже, слева слои последовательно опускаются и проседают.
|
||||
|
||||
`label` — стабильное имя действия; `progress?: { label, value?, valueText? }`
|
||||
— текущая фаза с измеренной долей 0…1. Без доли полоса неопределённая.
|
||||
При наличии progress кнопка блокирует повторный запуск, сохраняет читаемость
|
||||
и сообщает aria-busy. После ошибки consumer убирает progress, возвращая запуск;
|
||||
ошибка передаётся обычным каналом приложения. `disabled` отдельно закрывает
|
||||
действие без объявления несуществующей активности. Управление, отмена и жизненный
|
||||
цикл остаются у приложения. Высота стандартного Button не меняется.
|
||||
|
||||
ProgressBar расположен визуально внутри кнопки, но в DOM является соседним
|
||||
элементом: его доступная семантика не теряется внутри нативного button.
|
||||
Текущее описание связано через aria-describedby; role=status сообщает фазу.
|
||||
Tab/Enter/Space работают как у Button; pending исключает повторную активацию.
|
||||
|
||||
`LayerStackIndicator` использует существующий `Icon name="layers"`, без нового
|
||||
знака или зависимости. Анимация не вычисляет процент. При reduced motion
|
||||
оставляет неподвижный знак; статус и измеренная полоса остаются доступны.
|
||||
Каталог показывает idle, disabled, определённый и неопределённый progress.
|
||||
@@ -28,7 +28,7 @@
|
||||
7. trigger, полностью ушедший за viewport, закрывает surface;
|
||||
8. outside pointer и Escape закрывают surface;
|
||||
9. после Escape фокус возвращается на trigger;
|
||||
10. открытие другого dropdown закрывает предыдущий.
|
||||
10. открытие другого корневого dropdown закрывает предыдущий; вложенные меню сохраняют предков, а Escape закрывает только самый глубокий слой.
|
||||
|
||||
Inline absolute dropdown внутри card/sidebar/sticky container является дефектом.
|
||||
|
||||
@@ -121,3 +121,11 @@ Stack workspace-окон остаётся контролируемым прил
|
||||
`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 сохраняет пользовательскую геометрию. Минимумы продолжают действовать при всех последующих размерах.
|
||||
|
||||
+5
-2
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"build": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react && npm run build --workspace @nodedc/ui-catalog",
|
||||
"build:packages": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react",
|
||||
"check": "npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test: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",
|
||||
"check": "npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces",
|
||||
"dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog",
|
||||
"serve": "node server/catalog-server.mjs",
|
||||
"validate:registry": "node scripts/validate-registry.mjs",
|
||||
@@ -40,7 +40,10 @@
|
||||
"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:split-pane": "node --test scripts/split-pane-contract.test.mjs",
|
||||
"test:dock-layout": "node --test scripts/dock-layout.test.mjs",
|
||||
"test:analysis-controls": "node --test scripts/analysis-controls.test.mjs",
|
||||
"test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
|
||||
@@ -9,6 +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;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
/** Serializable split tree. Content identity is independent of its position. */
|
||||
export type DockTree = { id: string } | { axis: "x" | "y"; ratio: number; first: DockTree; second: DockTree };
|
||||
export type DockPosition = "center" | "left" | "right" | "top" | "bottom";
|
||||
export interface DockRect { left: number; top: number; width: number; height: number }
|
||||
export interface DockMove { activeId: string; overId: string; position: DockPosition }
|
||||
|
||||
export function dockIds(tree: DockTree | null): string[] {
|
||||
return !tree ? [] : "id" in tree ? [tree.id] : [...dockIds(tree.first), ...dockIds(tree.second)];
|
||||
}
|
||||
|
||||
export function decodeDockTree(raw: unknown): DockTree | null {
|
||||
const seen = new Set<string>();
|
||||
const read = (value: unknown, depth: number): DockTree | null => {
|
||||
if (!value || typeof value !== "object" || depth > 128 || seen.size > 128) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
if (typeof v.id === "string" && v.id.length > 0 && v.id.length < 512) {
|
||||
if (seen.has(v.id)) return null;
|
||||
seen.add(v.id); return { id: v.id };
|
||||
}
|
||||
if ((v.axis !== "x" && v.axis !== "y") || typeof v.ratio !== "number" || !Number.isFinite(v.ratio)) return null;
|
||||
const first = read(v.first, depth + 1), second = read(v.second, depth + 1);
|
||||
return first && second ? { axis: v.axis, ratio: Math.max(10, Math.min(90, v.ratio)), first, second } : first ?? second;
|
||||
};
|
||||
return read(raw, 0);
|
||||
}
|
||||
|
||||
export function pruneDockTree(tree: DockTree | null, ids: readonly string[]): DockTree | null {
|
||||
if (!tree) return null;
|
||||
if ("id" in tree) return ids.includes(tree.id) ? tree : null;
|
||||
const first = pruneDockTree(tree.first, ids), second = pruneDockTree(tree.second, ids);
|
||||
return first && second ? { ...tree, first, second } : first ?? second;
|
||||
}
|
||||
|
||||
export function balancedDockTree(ids: readonly string[], axis: "x" | "y" = "x"): DockTree | null {
|
||||
if (!ids.length) return null;
|
||||
if (ids.length === 1) return { id: ids[0] };
|
||||
const mid = Math.ceil(ids.length / 2);
|
||||
return { axis, ratio: 50, first: balancedDockTree(ids.slice(0, mid), axis === "x" ? "y" : "x")!,
|
||||
second: balancedDockTree(ids.slice(mid), axis === "x" ? "y" : "x")! };
|
||||
}
|
||||
|
||||
export function reconcileDockTree(tree: DockTree | null, ids: readonly string[]): DockTree | null {
|
||||
const kept = pruneDockTree(tree, ids), present = dockIds(kept), missing = ids.filter(id => !present.includes(id));
|
||||
if (!kept) return balancedDockTree(missing);
|
||||
return missing.length ? { axis: "x", ratio: 50, first: kept, second: balancedDockTree(missing)! } : kept;
|
||||
}
|
||||
|
||||
export function moveDockPanel(tree: DockTree | null, move: DockMove): DockTree | null {
|
||||
const { activeId, overId, position } = move, ids = dockIds(tree);
|
||||
if (!tree || activeId === overId || !ids.includes(activeId) || !ids.includes(overId)) return tree;
|
||||
const swap = (node: DockTree): DockTree => "id" in node
|
||||
? { id: node.id === activeId ? overId : node.id === overId ? activeId : node.id }
|
||||
: { ...node, first: swap(node.first), second: swap(node.second) };
|
||||
if (position === "center") return swap(tree);
|
||||
const remaining = pruneDockTree(tree, ids.filter(id => id !== activeId))!;
|
||||
const insert = (node: DockTree): DockTree => {
|
||||
if (!("id" in node)) return { ...node, first: insert(node.first), second: insert(node.second) };
|
||||
if (node.id !== overId) return node;
|
||||
const before = position === "left" || position === "top";
|
||||
return { axis: position === "left" || position === "right" ? "x" : "y", ratio: 50,
|
||||
first: before ? { id: activeId } : node, second: before ? node : { id: activeId } };
|
||||
};
|
||||
return insert(remaining);
|
||||
}
|
||||
|
||||
export function resizeDockSplit(tree: DockTree, path: string, ratio: number): DockTree {
|
||||
if ("id" in tree || !Number.isFinite(ratio)) return tree;
|
||||
if (!path) return { ...tree, ratio: Math.max(10, Math.min(90, ratio)) };
|
||||
const side = path[0] === "0" ? "first" : "second";
|
||||
return { ...tree, [side]: resizeDockSplit(tree[side], path.slice(1), ratio) };
|
||||
}
|
||||
|
||||
export function dockRects(tree: DockTree | null, bounds: DockRect): Record<string, DockRect> {
|
||||
if (!tree) return {};
|
||||
if ("id" in tree) return { [tree.id]: bounds };
|
||||
const fraction = tree.ratio / 100;
|
||||
const first = tree.axis === "x" ? { ...bounds, width: bounds.width * fraction } : { ...bounds, height: bounds.height * fraction };
|
||||
const second = tree.axis === "x" ? { ...bounds, left: bounds.left + first.width, width: bounds.width - first.width }
|
||||
: { ...bounds, top: bounds.top + first.height, height: bounds.height - first.height };
|
||||
return { ...dockRects(tree.first, first), ...dockRects(tree.second, second) };
|
||||
}
|
||||
|
||||
export function dockPosition(rect: DockRect, x: number, y: number): DockPosition | null {
|
||||
if (rect.width <= 0 || rect.height <= 0 || x < rect.left || y < rect.top || x > rect.left + rect.width || y > rect.top + rect.height) return null;
|
||||
const u = (x - rect.left) / rect.width, v = (y - rect.top) / rect.height;
|
||||
const distances: [DockPosition, number][] = [["left", u], ["right", 1 - u], ["top", v], ["bottom", 1 - v]];
|
||||
const nearest = distances.sort((a, b) => a[1] - b[1])[0];
|
||||
return nearest[1] <= .23 ? nearest[0] : "center";
|
||||
}
|
||||
|
||||
|
||||
export interface DockMinimum { width: number; height: number }
|
||||
export type DockMinimums = Readonly<Record<string, DockMinimum>>;
|
||||
/** Propagate content limits through every ancestor, not only the nearest split. */
|
||||
export function dockMinimum(tree: DockTree | null, minimums: DockMinimums = {}): DockMinimum {
|
||||
if (!tree) return {width: 0, height: 0};
|
||||
if ("id" in tree) {
|
||||
const value = minimums[tree.id];
|
||||
const valid = (v: number | undefined, fallback: number) => typeof v === "number" && Number.isFinite(v) ? Math.max(0, v) : fallback;
|
||||
return {width: valid(value?.width, 160), height: valid(value?.height, 120)};
|
||||
}
|
||||
const a = dockMinimum(tree.first, minimums), b = dockMinimum(tree.second, minimums);
|
||||
return tree.axis === "x" ? {width: a.width + b.width, height: Math.max(a.height, b.height)}
|
||||
: {width: Math.max(a.width, b.width), height: a.height + b.height};
|
||||
}
|
||||
/** Host expands to the recursive minimum when the whole viewport is too small. */
|
||||
export function constrainDockTree(tree: DockTree | null, bounds: DockMinimum, minimums: DockMinimums = {}): DockTree | null {
|
||||
if (!tree || "id" in tree) return tree;
|
||||
const required = dockMinimum(tree, minimums), size = {width: Math.max(bounds.width, required.width), height: Math.max(bounds.height, required.height)};
|
||||
const a = dockMinimum(tree.first, minimums), b = dockMinimum(tree.second, minimums), key = tree.axis === "x" ? "width" : "height";
|
||||
const available = size[key];
|
||||
const cut = Math.max(a[key], Math.min(available - b[key], available * tree.ratio / 100));
|
||||
const ratio=available>0?cut/available*100:50;
|
||||
return {...tree, ratio:Math.abs(ratio-tree.ratio)<1e-9?tree.ratio:ratio,
|
||||
first: constrainDockTree(tree.first, {...size, [key]: cut}, minimums)!,
|
||||
second: constrainDockTree(tree.second, {...size, [key]: available - cut}, minimums)!};
|
||||
}
|
||||
|
||||
/** Initial preferred sizes apply only until the product persists a user layout. */
|
||||
export function preferDockSizes(tree:DockTree|null,bounds:DockMinimum,preferred:DockMinimums):DockTree|null {
|
||||
if(!tree||'id' in tree)return tree;
|
||||
const a=dockIds(tree.first).some(id=>id in preferred),b=dockIds(tree.second).some(id=>id in preferred);
|
||||
const key=tree.axis==='x'?'width':'height';
|
||||
let ratio=tree.ratio;
|
||||
if(a!==b){const wanted=dockMinimum(a?tree.first:tree.second,preferred)[key];ratio=(a?wanted:bounds[key]-wanted)/bounds[key]*100;}
|
||||
ratio=Math.max(1,Math.min(99,Number.isFinite(ratio)?ratio:50));
|
||||
return {...tree,ratio,first:preferDockSizes(tree.first,{...bounds,[key]:bounds[key]*ratio/100},preferred)!,second:preferDockSizes(tree.second,{...bounds,[key]:bounds[key]*(1-ratio/100)},preferred)!};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export type FloatingPlacement = "bottom-start" | "bottom-end" | "top-start" | "top-end";
|
||||
export type FloatingPlacement = "bottom-start" | "bottom-end" | "top-start" | "top-end" | "left-start" | "right-start";
|
||||
|
||||
export interface RectLike {
|
||||
top: number;
|
||||
@@ -15,6 +15,7 @@ export interface FloatingPositionOptions {
|
||||
surfaceHeight: number;
|
||||
placement?: FloatingPlacement;
|
||||
offset?: number;
|
||||
flip?: boolean;
|
||||
viewportWidth?: number;
|
||||
viewportHeight?: number;
|
||||
viewportPadding?: number;
|
||||
@@ -24,6 +25,7 @@ export interface FloatingPosition {
|
||||
top: number;
|
||||
left: number;
|
||||
maxHeight: number;
|
||||
maxWidth?: number;
|
||||
resolvedPlacement: FloatingPlacement;
|
||||
}
|
||||
|
||||
@@ -33,6 +35,7 @@ export function computeFloatingPosition({
|
||||
surfaceHeight,
|
||||
placement = "bottom-start",
|
||||
offset = 8,
|
||||
flip = true,
|
||||
viewportWidth = typeof window === "undefined" ? 1920 : window.innerWidth,
|
||||
viewportHeight = typeof window === "undefined" ? 1080 : window.innerHeight,
|
||||
viewportPadding = 8,
|
||||
@@ -41,6 +44,22 @@ export function computeFloatingPosition({
|
||||
0,
|
||||
viewportHeight - viewportPadding * 2,
|
||||
);
|
||||
if (placement.startsWith("left") || placement.startsWith("right")) {
|
||||
const roomLeft = Math.max(0, anchor.left - offset - viewportPadding);
|
||||
const roomRight = Math.max(0, viewportWidth - anchor.right - offset - viewportPadding);
|
||||
const leftRequested = placement.startsWith("left");
|
||||
const switched = flip && (leftRequested ? surfaceWidth > roomLeft && roomRight > roomLeft : surfaceWidth > roomRight && roomLeft > roomRight);
|
||||
const toLeft = switched ? !leftRequested : leftRequested;
|
||||
const maxWidth = toLeft ? roomLeft : roomRight;
|
||||
const actualWidth = Math.min(surfaceWidth, maxWidth);
|
||||
const visibleHeight = Math.min(surfaceHeight, viewportAvailableHeight);
|
||||
return {
|
||||
left: toLeft ? anchor.left - offset - actualWidth : anchor.right + offset,
|
||||
top: Math.max(viewportPadding, Math.min(anchor.top, viewportHeight - viewportPadding - visibleHeight)),
|
||||
maxHeight: viewportAvailableHeight, maxWidth,
|
||||
resolvedPlacement: toLeft ? "left-start" : "right-start",
|
||||
};
|
||||
}
|
||||
const roomBelow = Math.min(
|
||||
viewportAvailableHeight,
|
||||
Math.max(0, viewportHeight - anchor.bottom - offset - viewportPadding),
|
||||
@@ -50,9 +69,9 @@ export function computeFloatingPosition({
|
||||
Math.max(0, anchor.top - offset - viewportPadding),
|
||||
);
|
||||
const requestedTop = placement.startsWith("top");
|
||||
const shouldFlip = requestedTop
|
||||
const shouldFlip = flip && (requestedTop
|
||||
? surfaceHeight > roomAbove && roomBelow > roomAbove
|
||||
: surfaceHeight > roomBelow && roomAbove > roomBelow;
|
||||
: surfaceHeight > roomBelow && roomAbove > roomBelow);
|
||||
const resolvedPlacement = shouldFlip
|
||||
? (`${requestedTop ? "bottom" : "top"}-${placement.endsWith("end") ? "end" : "start"}` as FloatingPlacement)
|
||||
: placement;
|
||||
|
||||
@@ -4,3 +4,11 @@ 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";
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { RectLike } from "./floating.js";
|
||||
export type MenuPoint = {x:number;y:number};
|
||||
/** Delay sibling activation only while the pointer advances through the corridor to the open menu. */
|
||||
export function movingToMenu(origin:MenuPoint, previous:MenuPoint, current:MenuPoint, surface:RectLike):boolean {
|
||||
const horizontal = origin.x < surface.left || origin.x > surface.right;
|
||||
const edge = horizontal ? (origin.x < surface.left ? surface.left : surface.right) : (origin.y < surface.top ? surface.top : surface.bottom);
|
||||
const a = horizontal ? {x:edge,y:surface.top-6} : {x:surface.left-6,y:edge};
|
||||
const b = horizontal ? {x:edge,y:surface.bottom+6} : {x:surface.right+6,y:edge};
|
||||
const cross=(p:MenuPoint,q:MenuPoint,v:MenuPoint)=>(q.x-p.x)*(v.y-p.y)-(q.y-p.y)*(v.x-p.x);
|
||||
const signs=[cross(origin,a,current),cross(a,b,current),cross(b,origin,current)];
|
||||
const inside=signs.every(v=>v>=-0.01)||signs.every(v=>v<=0.01);
|
||||
const axis=horizontal?"x":"y";
|
||||
return inside && Math.abs(current[axis]-edge)<Math.abs(previous[axis]-edge)-0.1;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export type ToolbarPlacement = "left" | "right" | "bottom";
|
||||
export type ToolbarPlacement = "left" | "right" | "top" | "bottom";
|
||||
|
||||
export interface ToolbarSettings {
|
||||
minSize: number;
|
||||
|
||||
+175
-10
@@ -107,6 +107,13 @@
|
||||
-webkit-backdrop-filter: blur(var(--nodedc-blur-control));
|
||||
}
|
||||
|
||||
/* Controls above imagery need an opaque, common resting surface. Scope this
|
||||
material to the control group, never the renderer or its settings window. */
|
||||
.nodedc-scene-controls {
|
||||
--nodedc-glass-control-bg: var(--nodedc-field-bg);
|
||||
--nodedc-glass-control-hover: var(--nodedc-glass-panel-surface-strong);
|
||||
}
|
||||
|
||||
.nodedc-button {
|
||||
position: relative;
|
||||
--nodedc-button-bg: var(--nodedc-glass-control-bg);
|
||||
@@ -666,7 +673,10 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-settings-card__titles h2,
|
||||
.nodedc-description,
|
||||
.nodedc-settings-card__titles p {
|
||||
font-family: inherit;
|
||||
font-weight: 400;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -676,7 +686,10 @@ textarea.nodedc-field__control {
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.nodedc-description,
|
||||
.nodedc-settings-card__titles p {
|
||||
font-family: inherit;
|
||||
font-weight: 400;
|
||||
color: var(--nodedc-text-muted);
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.4;
|
||||
@@ -855,19 +868,17 @@ textarea.nodedc-field__control {
|
||||
.nodedc-select-option-row > .nodedc-icon-button[data-tone="danger"]:hover:not(:disabled),
|
||||
.nodedc-select-option-row > .nodedc-icon-button[data-tone="danger"]:focus-visible { color: rgb(var(--nodedc-danger-rgb)); }
|
||||
.nodedc-select-option-row > .nodedc-icon-button:active:not(:disabled) { transform: none; }
|
||||
.nodedc-range-scale { position: relative; width: calc(var(--nodedc-control-height) * 0.4); height: 100%; min-height: 6rem; }
|
||||
.nodedc-range[data-orientation="vertical"] { width: 100%; height: 100%; border: 0; outline: 0; box-shadow: none; }
|
||||
.nodedc-range-scale { position: relative; width: calc(var(--nodedc-control-height) * 0.2); height: 100%; min-height: 6rem; }
|
||||
.nodedc-range[data-orientation="vertical"] { width: 100%; height: 100%; overflow: visible; border: 0; outline: 0; box-shadow: none; }
|
||||
.nodedc-range[data-orientation="vertical"]::before { inset: auto 0 0; width: 100%; height: var(--nodedc-range-progress); }
|
||||
.nodedc-range[data-orientation="vertical"] input[type="range"] { writing-mode: vertical-lr; direction: rtl; }
|
||||
.nodedc-range[data-orientation="vertical"] .nodedc-range__label { left: 50%; max-width: none; font-size: calc(var(--nodedc-font-size-sm) * 0.9); writing-mode: vertical-rl; transform: translate(-50%, -50%) rotate(180deg); }
|
||||
.nodedc-range[data-orientation="vertical"] input[type="range"] { writing-mode: vertical-lr; direction: rtl; width: max(100%, 24px); left: 50%; transform: translateX(-50%); }
|
||||
.nodedc-range-scale__limit { position: absolute; left: calc(100% + 0.4rem); color: var(--nodedc-text-primary); font-size: calc(var(--nodedc-font-size-xs) * 0.9); font-weight: var(--nodedc-font-weight-medium); line-height: 1; font-variant-numeric: tabular-nums; white-space: nowrap; pointer-events: none; }
|
||||
.nodedc-range-scale[data-limit-side="left"] .nodedc-range-scale__limit { right: calc(100% + 0.4rem); left: auto; text-align: right; }
|
||||
.nodedc-range-scale__limit--max { top: 0.75rem; }
|
||||
.nodedc-range-scale__limit--min { bottom: 0.75rem; }
|
||||
.nodedc-range[data-orientation="vertical"] .nodedc-range__fill-text { clip-path: inset(calc(100% - var(--nodedc-range-progress)) 0 0 round var(--nodedc-radius-circle)); }
|
||||
.nodedc-range-scale__limit--max { bottom: clamp(1.6rem, var(--nodedc-range-progress), calc(100% - 0.65rem)); transform: translateY(50%); }
|
||||
.nodedc-range-scale__limit--min { bottom: 0.2rem; }
|
||||
/* Native ranges may match focus-visible after pointer input too. Keep every
|
||||
state perimeter-free; underline both contrast layers to identify focus. */
|
||||
.nodedc-range[data-orientation="vertical"]:has(input:focus-visible) .nodedc-range__label { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 2px; }
|
||||
state perimeter-free; underline the moving boundary to identify focus. */
|
||||
.nodedc-range-scale:has(input:focus-visible) .nodedc-range-scale__limit--max { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 2px; }
|
||||
|
||||
.nodedc-range__label,
|
||||
.nodedc-range__value {
|
||||
@@ -1149,6 +1160,11 @@ textarea.nodedc-field__control {
|
||||
box-shadow: var(--nodedc-glass-control-shadow);
|
||||
}
|
||||
|
||||
.nodedc-scene-controls .nodedc-segmented {
|
||||
--nodedc-header-pill-height: var(--nodedc-control-height);
|
||||
background: var(--nodedc-field-bg);
|
||||
}
|
||||
|
||||
.nodedc-segmented__item {
|
||||
display: inline-flex;
|
||||
min-height: calc(var(--nodedc-header-pill-height) - 0.64rem);
|
||||
@@ -2541,6 +2557,7 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-feature-settings-window .nodedc-window__body {
|
||||
overflow: hidden;
|
||||
padding: 0.35rem 1rem 1rem;
|
||||
}
|
||||
|
||||
@@ -2549,10 +2566,14 @@ textarea.nodedc-field__control {
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
grid-template-columns: minmax(14rem, 16rem) minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
gap: 1.2rem;
|
||||
}
|
||||
|
||||
.nodedc-feature-settings__navigation {
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
display: grid;
|
||||
min-height: 0;
|
||||
align-content: start;
|
||||
@@ -2641,6 +2662,8 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-feature-settings__content {
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
@@ -3022,6 +3045,11 @@ textarea.nodedc-field__control {
|
||||
content: "";
|
||||
}
|
||||
|
||||
.nodedc-workspace-window[data-resize-indicator="hidden"] .nodedc-workspace-window__resize::before,
|
||||
.nodedc-workspace-window[data-resize-indicator="hidden"] .nodedc-workspace-window__resize::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.nodedc-workspace-window__resize::before {
|
||||
width: 0.72rem;
|
||||
height: 0.72rem;
|
||||
@@ -3560,6 +3588,18 @@ textarea.nodedc-field__control {
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.nodedc-inspector__section-head { position: relative; min-width: 0; }
|
||||
.nodedc-inspector__section-head[data-action="true"] .nodedc-inspector__section-body {
|
||||
padding-inline-end: calc(var(--nodedc-control-height) + var(--nodedc-space-2));
|
||||
}
|
||||
.nodedc-inspector__section-action {
|
||||
position: absolute;
|
||||
right: var(--nodedc-space-3);
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
.nodedc-inspector[data-variant="panel"] .nodedc-inspector__section-action { right: 2.8rem; }
|
||||
|
||||
.nodedc-inspector__section-trigger:not([data-open="true"]):hover {
|
||||
background: var(--nodedc-glass-control-hover);
|
||||
color: var(--nodedc-text-primary);
|
||||
@@ -3668,7 +3708,7 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-inspector[data-variant="panel"] .nodedc-inspector__section-trigger[data-open="true"] .nodedc-inspector__section-chevron {
|
||||
transform: rotate(90deg);
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.nodedc-inspector[data-variant="panel"] .nodedc-inspector__section-content {
|
||||
@@ -4380,3 +4420,128 @@ textarea.nodedc-field__control {
|
||||
background: var(--nodedc-glass-control-hover); color: var(--nodedc-text-primary);
|
||||
}
|
||||
[data-nodedc-appearance="mission"] .nodedc-inspector__section-trigger:is([data-open="true"], [data-active="true"], [data-tone="accent"]) .nodedc-inspector__section-description { color: var(--nodedc-text-muted); }
|
||||
|
||||
/* Docking keeps media mounted; the contour exists only during a move. */
|
||||
.nodedc-dock-layout { position:relative; height:100%; min-width:0; min-height:0; isolation:isolate; }
|
||||
.nodedc-dock-layout__panel { position:absolute; z-index:0; min-width:0; min-height:0; }
|
||||
.nodedc-dock-layout__handle { display:flex; flex-shrink:0; }
|
||||
.nodedc-dock-layout__split { height:100%; pointer-events:none; }
|
||||
.nodedc-dock-layout__split .nodedc-split-pane__separator { pointer-events:auto; z-index:2; }
|
||||
.nodedc-dock-layout__panel[data-dock-source="true"] { opacity:.55; }
|
||||
.nodedc-dock-layout__overlay { position:absolute; inset:0; z-index:3; cursor:grabbing; }
|
||||
.nodedc-dock-layout__preview { position:absolute; box-sizing:border-box; border:2px solid var(--nodedc-text-primary); border-radius:var(--nodedc-radius-panel); background:color-mix(in srgb, var(--nodedc-text-primary) 12%, transparent); display:grid; place-items:center; padding:var(--nodedc-space-2); overflow:hidden; pointer-events:none; }
|
||||
.nodedc-dock-layout__preview > span { color:var(--nodedc-text-primary); background:var(--nodedc-glass-panel-bg-strong); border-radius:var(--nodedc-radius-control); padding:var(--nodedc-space-2) var(--nodedc-space-3); font-size:var(--nodedc-font-size-sm); text-align:center; }
|
||||
.nodedc-dock-layout__announcement { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; }
|
||||
|
||||
/* Owner-approved in-action phase/progress and accumulating layers, 2026-10-10. */
|
||||
.nodedc-progress-button { position: relative; display: inline-flex; max-width: 100%; }
|
||||
.nodedc-progress-button > .nodedc-button { width: 100%; }
|
||||
.nodedc-progress-button[data-pending] > .nodedc-button { opacity: 1; cursor: progress; }
|
||||
.nodedc-progress-button[data-pending] .nodedc-progress-button__label { transform: translateY(calc(-1 * var(--nodedc-space-1))); }
|
||||
.nodedc-progress-button > .nodedc-progress-bar { position: absolute; left: var(--nodedc-space-5); right: var(--nodedc-space-5); bottom: var(--nodedc-space-2); height: var(--nodedc-space-1); pointer-events: none; }
|
||||
.nodedc-progress-button[data-icon] > .nodedc-progress-bar { left: calc(var(--nodedc-space-5) + var(--nodedc-space-4) + var(--nodedc-space-2)); }
|
||||
.nodedc-progress-button__status { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.nodedc-layer-stack-indicator { overflow: visible; }
|
||||
.nodedc-layer-stack-indicator > path { transform-box: fill-box; transform-origin: center bottom; animation: nodedc-layer-arrive 1.8s var(--nodedc-ease-standard) infinite; }
|
||||
.nodedc-layer-stack-indicator > path:nth-child(2) { animation-delay: -1.2s; }
|
||||
.nodedc-layer-stack-indicator > path:nth-child(3) { animation-delay: -0.6s; }
|
||||
@keyframes nodedc-layer-arrive {
|
||||
0% { opacity: 0; transform: translateY(-6px); }
|
||||
22% { opacity: 1; transform: translateY(1px) scaleY(.82); }
|
||||
34%, 82% { opacity: 1; transform: translateY(0) scaleY(1); }
|
||||
100% { opacity: 0; transform: translateY(0); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.nodedc-layer-stack-indicator > path { animation: none; }
|
||||
}
|
||||
|
||||
/* Media windows participate in the viewport canon only when opted in. */
|
||||
.nodedc-viewport-controls > .nodedc-workspace-window__head .nodedc-workspace-window__action {
|
||||
width: var(--nodedc-icon-button-size);
|
||||
height: var(--nodedc-icon-button-size);
|
||||
zoom: var(--nodedc-viewport-control-scale);
|
||||
}
|
||||
|
||||
/* One viewport action density. Scale control boxes (including typography, icons
|
||||
and rims), not renderers, titles, portals or settings. Nested groups do not
|
||||
multiply the scale. Legacy compact/dense props normalize in this context. */
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-button, .nodedc-icon-button, .nodedc-select-anchor, .nodedc-segmented) {
|
||||
zoom: var(--nodedc-viewport-control-scale);
|
||||
}
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-button, .nodedc-icon-button, .nodedc-select-anchor, .nodedc-segmented) :is(.nodedc-button, .nodedc-icon-button, .nodedc-select-anchor, .nodedc-segmented) {
|
||||
zoom: 1;
|
||||
}
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) .nodedc-button {
|
||||
min-height: var(--nodedc-control-height);
|
||||
border-radius: var(--nodedc-radius-control);
|
||||
padding: 0.25rem 1.25rem;
|
||||
font-size: var(--nodedc-font-size-md);
|
||||
}
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) .nodedc-button[data-shape="pill"] { border-radius: var(--nodedc-radius-circle); }
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) .nodedc-segmented {
|
||||
--nodedc-header-pill-height: var(--nodedc-control-height);
|
||||
min-height: var(--nodedc-control-height);
|
||||
gap: 0.18rem;
|
||||
padding: 0.32rem;
|
||||
}
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) .nodedc-segmented .nodedc-segmented__item {
|
||||
min-height: calc(var(--nodedc-control-height) - 0.64rem);
|
||||
gap: 0.45rem;
|
||||
padding: 0.2rem 1.15rem;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
}
|
||||
|
||||
/* Two-sided vertical band. The rail stays thin; pointer capture uses a wider
|
||||
invisible target. Native inputs retain independent keyboard and AT access. */
|
||||
.nodedc-range-band__target { position: absolute; inset: 0 auto 0 50%; transform: translateX(-50%); width: max(100%, 24px); touch-action: none; cursor: ns-resize; }
|
||||
.nodedc-range-scale[data-band] input[type="range"] { pointer-events: none; }
|
||||
.nodedc-range-scale[data-band] .nodedc-range::before { bottom: var(--nodedc-range-lower); height: calc(var(--nodedc-range-upper) - var(--nodedc-range-lower)); }
|
||||
.nodedc-range-scale[data-band] .nodedc-range-scale__limit--min { bottom: clamp(0.65rem, var(--nodedc-range-lower), calc(100% - 1.65rem)); transform: translateY(50%); }
|
||||
.nodedc-range-scale[data-band] .nodedc-range-scale__limit--max { bottom: clamp(1.65rem, max(var(--nodedc-range-upper), calc(var(--nodedc-range-lower) + 1rem)), calc(100% - 0.65rem)); }
|
||||
.nodedc-range-scale[data-band]:has(input:focus-visible) .nodedc-range-scale__limit--max { text-decoration: none; }
|
||||
.nodedc-range-scale[data-band]:has([data-boundary="lower"]:focus-visible) .nodedc-range-scale__limit--min,
|
||||
.nodedc-range-scale[data-band]:has([data-boundary="upper"]:focus-visible) .nodedc-range-scale__limit--max { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 2px; }
|
||||
.nodedc-range-scale[data-disabled] { opacity: var(--nodedc-disabled-opacity, 0.5); }
|
||||
.nodedc-range-scale[data-disabled] .nodedc-range-band__target { cursor: default; }
|
||||
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) .nodedc-select-inline { min-height: var(--nodedc-control-height); }
|
||||
|
||||
/* Entity comparison never compresses values to fit the viewport. */
|
||||
.nodedc-comparison-table {min-width:0; max-width:100%; overflow:auto; overscroll-behavior:contain; scrollbar-width:thin;}
|
||||
.nodedc-comparison-table table {width:100%; min-width:calc(var(--nodedc-comparison-columns) * 9rem); table-layout:fixed; border-collapse:collapse; font-size:var(--nodedc-font-size-sm);}
|
||||
.nodedc-comparison-table th, .nodedc-comparison-table td {text-align:left; vertical-align:top; padding:var(--nodedc-space-2); overflow-wrap:anywhere;}
|
||||
.nodedc-comparison-table tbody th {color:var(--nodedc-text-secondary); font-weight:400;}
|
||||
.nodedc-comparison-table td {font-variant-numeric:tabular-nums;}
|
||||
.nodedc-comparison-table:focus-visible {outline:2px solid rgb(var(--nodedc-accent-rgb)); outline-offset:-2px;}
|
||||
|
||||
/* Content minimums govern resizing; an undersized viewport scrolls the canvas. */
|
||||
.nodedc-dock-layout {overflow:auto; overscroll-behavior:contain;}
|
||||
.nodedc-dock-layout__canvas {position:relative; height:100%; width:100%;}
|
||||
.nodedc-comparison-table[data-density="compact"] table {min-width:calc(7.5rem + (var(--nodedc-comparison-columns) - 1) * 5.5rem); table-layout:fixed; line-height:1.25;}
|
||||
.nodedc-comparison-table[data-density="compact"] col:first-child {width:7.5rem;}
|
||||
.nodedc-comparison-table[data-density="compact"] th, .nodedc-comparison-table[data-density="compact"] td {padding:3px var(--nodedc-space-1);}
|
||||
|
||||
/* Header selectors may place their compact caption below the control. */
|
||||
.nodedc-field--caption > .nodedc-field__label-row { order: 1; }
|
||||
.nodedc-field--caption .nodedc-field__label { color: var(--nodedc-text-muted); font-size: var(--nodedc-font-size-sm); font-weight: var(--nodedc-font-weight-regular, 400); }
|
||||
|
||||
/* A viewport owns clipping, placement and its reveal edge. */
|
||||
.nodedc-toolbar-wrap[data-scope="viewport"] { position: absolute; z-index: 12; }
|
||||
|
||||
.nodedc-toolbar > .nodedc-dropdown-anchor { display: contents; }
|
||||
|
||||
.nodedc-toolbar-wrap[data-placement="top"] { top: .75rem; left: 50%; transform: translateX(-50%); }
|
||||
.nodedc-toolbar-wrap[data-placement="top"] .nodedc-toolbar { height: var(--nodedc-toolbar-min-size); align-items: flex-start; padding: 0 var(--nodedc-toolbar-padding,6px); }
|
||||
.nodedc-toolbar-wrap[data-placement="top"][data-active="true"] .nodedc-toolbar { height: var(--nodedc-toolbar-max-size); }
|
||||
.nodedc-toolbar-wrap[data-placement="top"][data-autohide="true"]:not([data-visible="true"]) .nodedc-toolbar { transform: translateY(calc(-100% - 1rem)); }
|
||||
.nodedc-toolbar-wrap[data-placement="top"] .nodedc-toolbar__hotzone { right:5rem; top:0; left:5rem; height:1.1rem; }
|
||||
.nodedc-toolbar-wrap[data-placement="top"] .nodedc-toolbar__button { transform:translateX(var(--nodedc-toolbar-shift,0px)) scale(var(--nodedc-toolbar-scale,1)); transform-origin:center top; }
|
||||
|
||||
/* Structural cube edges communicate face/edge/corner hit zones. */
|
||||
.nodedc-navigation-cube { width: 66px; height: 66px; overflow: visible; user-select: none; }
|
||||
.nodedc-navigation-cube polygon { fill: var(--cube-face, var(--nodedc-surface-raised, #292929)); stroke: var(--cube-edge, var(--nodedc-text-muted, #888)); stroke-width: .55; stroke-opacity: var(--cube-edge-opacity, 1); }
|
||||
.nodedc-navigation-cube text { fill: var(--cube-text, var(--nodedc-text-primary, #eee)); font: 600 9px var(--nodedc-font-family); pointer-events: none; }
|
||||
.nodedc-navigation-cube g { cursor: pointer; }
|
||||
.nodedc-navigation-cube g.is-hovered polygon, .nodedc-navigation-cube g:focus-visible polygon { fill: var(--cube-hover, var(--nodedc-control-selected-bg, #eee)); }
|
||||
.nodedc-navigation-cube g.is-hovered text, .nodedc-navigation-cube g:focus-visible text { fill: var(--cube-hover-text, var(--nodedc-control-selected-text, #161616)); }
|
||||
.nodedc-navigation-cube g[aria-disabled="true"] { opacity: .45; cursor: default; }
|
||||
|
||||
@@ -17,6 +17,8 @@ export interface ToolbarControllerOptions {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
}
|
||||
|
||||
export interface ToolbarController {
|
||||
@@ -112,7 +114,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
};
|
||||
|
||||
const updateMagnification = (coordinate: number) => {
|
||||
const vertical = options.placement !== "bottom";
|
||||
const vertical = options.placement !== "bottom" && options.placement !== "top";
|
||||
const toolbarRect = toolbar.getBoundingClientRect();
|
||||
const entries = buttons
|
||||
.map((button) => ({
|
||||
@@ -148,7 +150,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
hideTimer = window.setTimeout(() => {
|
||||
hideTimer = null;
|
||||
if (!hovering) hide();
|
||||
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay);
|
||||
}, Math.max(0,Math.min(15000,options.hideDelay ?? NODEDC_TOOLBAR_DEFAULTS.hideDelay)));
|
||||
};
|
||||
|
||||
const applyOptions = () => {
|
||||
@@ -208,7 +210,7 @@ export function createToolbarController(initial: ToolbarControllerOptions): Tool
|
||||
? event.clientX >= window.innerWidth - threshold
|
||||
: options.placement === "bottom"
|
||||
? event.clientY >= window.innerHeight - threshold
|
||||
: event.clientX <= threshold;
|
||||
: options.placement === "top" ? event.clientY <= threshold : event.clientX <= threshold;
|
||||
if (nearEdge) show();
|
||||
else if (visible && !hovering) scheduleHide();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ReactNode, CSSProperties } from "react";
|
||||
export interface ComparisonTableProps {
|
||||
density?: "default" | "compact";
|
||||
label: string;
|
||||
heading: ReactNode;
|
||||
columns: readonly { id: string; label: ReactNode }[];
|
||||
rows: readonly { id: string; label: ReactNode; cells: readonly ReactNode[] }[];
|
||||
}
|
||||
/** One label column, one non-collapsing column per entity. Scrolls as a unit. */
|
||||
export function ComparisonTable({ density = "default", label, heading, columns, rows }: ComparisonTableProps) {
|
||||
return <div className="nodedc-comparison-table" data-density={density} role="region" aria-label={label} tabIndex={0}
|
||||
style={{ "--nodedc-comparison-columns": columns.length + 1 } as CSSProperties}>
|
||||
<table aria-label={label}>
|
||||
<colgroup><col/>{columns.map(column => <col key={column.id}/>)}</colgroup>
|
||||
<thead><tr><th scope="col">{heading}</th>{columns.map(column => <th key={column.id} scope="col">{column.label}</th>)}</tr></thead>
|
||||
<tbody>{rows.map(row => <tr key={row.id}><th scope="row">{row.label}</th>{columns.map((column, index) => <td key={column.id}>{row.cells[index] ?? "—"}</td>)}</tr>)}</tbody>
|
||||
</table>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
/** Secondary explanatory copy; identical inside and outside SettingsCard headers. */
|
||||
export function Description({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {
|
||||
return <p {...props} className={cn("nodedc-description", className)} />;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import {createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode} from "react";
|
||||
import {DndContext, PointerSensor, useDraggable, useSensor, useSensors, type DragMoveEvent} from "@dnd-kit/core";
|
||||
import {DragHandle} from "./DragDrop.js";
|
||||
import {SplitPane} from "./SplitPane.js";
|
||||
import {cn} from "./cn.js";
|
||||
import {dockIds, dockPosition, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
|
||||
|
||||
const DockContext = createContext<{disabled: boolean; onKey: (id: string, event: KeyboardEvent<HTMLDivElement>) => void}>({disabled: true, onKey: () => {}});
|
||||
/** The shared six-dot grip supports pointer dragging and keyboard docking. */
|
||||
export function DockHandle({id, label}: {id: string; label: string}) {
|
||||
const {disabled, onKey} = useContext(DockContext);
|
||||
const {attributes, listeners, setNodeRef} = useDraggable({id, disabled});
|
||||
return <div ref={setNodeRef} className="nodedc-dock-layout__handle" onKeyDown={event => onKey(id, event)}>
|
||||
<DragHandle label={`Переместить · ${label}`} attributes={{...attributes, "aria-disabled": disabled}} listeners={listeners}/>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export interface DockLayoutProps {
|
||||
tree: DockTree | null;
|
||||
onTreeChange: (tree: DockTree) => void;
|
||||
panels: {id: string; label: string; minimumSize?: DockMinimum; preferredSize?: DockMinimum}[];
|
||||
renderPanel: (id: string) => ReactNode;
|
||||
focusedId?: string | null;
|
||||
className?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/** Media stay in stable sibling hosts; only geometry changes, including focus. */
|
||||
export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId, className, children}: DockLayoutProps) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
// React must not reorder these DOM siblings: moving an iframe node reloads
|
||||
// its browsing context even when its key and portal content are unchanged.
|
||||
const hostOrder = useRef<string[]>([]);
|
||||
const available = new Set(panels.map(panel => panel.id));
|
||||
hostOrder.current = hostOrder.current.filter(id => available.has(id));
|
||||
for (const panel of panels) if (!hostOrder.current.includes(panel.id)) hostOrder.current.push(panel.id);
|
||||
const [bounds, setBounds] = useState<DockRect>({left: 0, top: 0, width: 0, height: 0});
|
||||
const [active, setActive] = useState<string | null>(null), [target, setTarget] = useState<DockMove | null>(null);
|
||||
const [keyboard, setKeyboard] = useState(false);
|
||||
const sensors = useSensors(useSensor(PointerSensor, {activationConstraint: {distance: 6}}));
|
||||
const ids = panels.map(panel => panel.id), visibleTree = pruneDockTree(tree, focusedId ? [focusedId] : ids);
|
||||
const minimums = Object.fromEntries(panels.filter(p => p.minimumSize).map(p => [p.id, p.minimumSize!]));
|
||||
const minimum = dockMinimum(visibleTree, minimums);
|
||||
const canvas = {...bounds, width: Math.max(bounds.width, minimum.width), height: Math.max(bounds.height, minimum.height)};
|
||||
const preferred = Object.fromEntries(panels.filter(p => p.preferredSize).map(p => [p.id,p.preferredSize!]));
|
||||
const constrained = constrainDockTree(preferDockSizes(visibleTree,canvas,preferred), canvas, minimums);
|
||||
const rects = dockRects(constrained, canvas);
|
||||
const disabled = !!focusedId || ids.length < 2;
|
||||
const reset = () => {setActive(null); setTarget(null); setKeyboard(false);};
|
||||
useLayoutEffect(() => {
|
||||
const element = host.current!;
|
||||
const measure = () => {const r = element.getBoundingClientRect(); setBounds({left: 0, top: 0, width: r.width, height: r.height});};
|
||||
measure(); const observer = new ResizeObserver(measure); observer.observe(element); return () => observer.disconnect();
|
||||
}, []);
|
||||
useEffect(() => {if (disabled || (active && !ids.includes(active))) reset();}, [disabled, panels.map(p => p.id).join("\0")]);
|
||||
// Block iframe hit-testing only during a drag so pointer motion stays in the document.
|
||||
const locate = (event: DragMoveEvent): DockMove | null => {
|
||||
const start = event.activatorEvent as PointerEvent, box = host.current!.getBoundingClientRect();
|
||||
const x = start.clientX + event.delta.x - box.left, y = start.clientY + event.delta.y - box.top;
|
||||
for (const [id, rect] of Object.entries(rects)) {
|
||||
const position = dockPosition(rect, x, y);
|
||||
if (position && id !== String(event.active.id)) return {activeId: String(event.active.id), overId: id, position};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const commit = (move: DockMove | null) => {
|
||||
const next = move && moveDockPanel(constrained, move);
|
||||
if (next) onTreeChange(next);
|
||||
reset();
|
||||
};
|
||||
const onKey = (id: string, event: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (disabled) return;
|
||||
if (!keyboard) {
|
||||
if (event.key !== " " && event.key !== "Enter") return;
|
||||
const overId = ids.find(value => value !== id)!;
|
||||
setActive(id); setTarget({activeId: id, overId, position: "center"}); setKeyboard(true);
|
||||
} else if (event.key === "Escape") reset();
|
||||
else if (event.key === "Enter" || event.key === " ") commit(target);
|
||||
else if (event.key === "Tab") {
|
||||
const candidates = dockIds(visibleTree).filter(value => value !== active), index = candidates.indexOf(target?.overId ?? "");
|
||||
setTarget({activeId: active!, overId: candidates[(index + (event.shiftKey ? -1 : 1) + candidates.length) % candidates.length], position: target?.position ?? "center"});
|
||||
} else {
|
||||
const position = ({ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const)[event.key as "ArrowLeft"];
|
||||
if (!position || !target) return;
|
||||
setTarget({...target, position});
|
||||
}
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
};
|
||||
const preview = target ? dockRects(moveDockPanel(constrained, target), canvas)[target.activeId] : null;
|
||||
const action = target ? ({center: "Поменять местами", left: "Слева", right: "Справа", top: "Сверху", bottom: "Снизу"})[target.position] : "Выберите окно и край";
|
||||
const label = target ? panels.find(panel => panel.id === target.overId)?.label : "";
|
||||
return <DndContext sensors={sensors} autoScroll={false}
|
||||
onDragStart={event => {setActive(String(event.active.id)); setKeyboard(false);}}
|
||||
onDragMove={event => setTarget(locate(event))}
|
||||
onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
|
||||
<DockContext.Provider value={{disabled, onKey}}>
|
||||
<div className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
|
||||
<div ref={host} className="nodedc-dock-layout__canvas" style={{minWidth:minimum.width, minHeight:minimum.height}}>
|
||||
<DockSlots tree={constrained} bounds={canvas} minimums={minimums} onResize={(path, ratio) => {if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/>
|
||||
{hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel => <div key={panel.id} className="nodedc-dock-layout__panel" data-dock-id={panel.id}
|
||||
data-dock-source={active === panel.id ? "true" : undefined} style={rects[panel.id] ?? {display: "none"}}>{renderPanel(panel.id)}</div>)}
|
||||
{active ? <div className="nodedc-dock-layout__overlay" aria-hidden="true">
|
||||
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} style={preview}><span>{action} · {label}</span></div> : null}
|
||||
</div> : null}
|
||||
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</DockContext.Provider>
|
||||
</DndContext>;
|
||||
}
|
||||
|
||||
function DockSlots({tree, bounds, minimums, onResize, path = ""}: {tree: DockTree | null; bounds: DockMinimum; minimums: Record<string,DockMinimum>; onResize: (path: string, ratio: number) => void; path?: string}) {
|
||||
if (!tree || "id" in tree) return null;
|
||||
const key = tree.axis === "x" ? "width" : "height", span = bounds[key];
|
||||
return <SplitPane className="nodedc-dock-layout__split" separatorAppearance="invisible" orientation={tree.axis === "x" ? "vertical" : "horizontal"}
|
||||
primarySize={tree.ratio} minPrimarySize={span ? dockMinimum(tree.first,minimums)[key]/span*100 : 0} minSecondarySize={span ? dockMinimum(tree.second,minimums)[key]/span*100 : 0} onPrimarySizeChange={ratio => onResize(path, ratio)} separatorLabel="Изменить размеры окон"
|
||||
primary={<DockSlots tree={tree.first} bounds={{...bounds,[key]:span*tree.ratio/100}} minimums={minimums} onResize={onResize} path={path + "0"}/>}
|
||||
secondary={<DockSlots tree={tree.second} bounds={{...bounds,[key]:span*(1-tree.ratio/100)}} minimums={minimums} onResize={onResize} path={path + "1"}/>}/>;
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useMemo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
@@ -9,9 +12,12 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { computeFloatingPosition, type FloatingPlacement } from "@nodedc/ui-core";
|
||||
import { computeFloatingPosition, type FloatingPlacement, type RectLike } from "@nodedc/ui-core";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
const DropdownLineage = createContext<readonly string[]>([]);
|
||||
const openDropdowns = new Map<string, readonly string[]>();
|
||||
|
||||
export interface DropdownTriggerApi {
|
||||
open: boolean;
|
||||
show: () => void;
|
||||
@@ -34,6 +40,11 @@ export interface DropdownProps {
|
||||
surfaceClassName?: string;
|
||||
surfaceRole?: "menu" | "listbox" | "dialog";
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
/** Animated controls may reserve their maximum extent as a stable anchor. */
|
||||
getAnchorRect?: () => RectLike | null;
|
||||
flip?: boolean;
|
||||
/** Capture-phase dismissal may consume a scene gesture before its tools run. */
|
||||
onPointerDownOutside?: (event: PointerEvent) => void;
|
||||
}
|
||||
|
||||
export function Dropdown({
|
||||
@@ -48,8 +59,13 @@ export function Dropdown({
|
||||
surfaceClassName,
|
||||
surfaceRole = "menu",
|
||||
onOpenChange,
|
||||
getAnchorRect,
|
||||
flip = true,
|
||||
onPointerDownOutside,
|
||||
}: DropdownProps) {
|
||||
const instanceId = useId();
|
||||
const ancestors = useContext(DropdownLineage);
|
||||
const lineage = useMemo(() => [...ancestors, instanceId], [ancestors, instanceId]);
|
||||
const surfaceId = `${instanceId.replaceAll(":", "")}-surface`;
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null);
|
||||
@@ -72,7 +88,7 @@ export function Dropdown({
|
||||
const updatePosition = useCallback(() => {
|
||||
const anchorNode = anchorElement ?? triggerElement;
|
||||
if (!anchorNode || !surfaceRef.current) return;
|
||||
const anchor = anchorNode.getBoundingClientRect();
|
||||
const anchor = getAnchorRect?.() ?? anchorNode.getBoundingClientRect();
|
||||
const anchorVisible = (
|
||||
anchor.bottom > 0
|
||||
&& anchor.top < window.innerHeight
|
||||
@@ -93,58 +109,73 @@ export function Dropdown({
|
||||
surfaceWidth,
|
||||
surfaceHeight,
|
||||
placement,
|
||||
offset,
|
||||
offset, flip,
|
||||
});
|
||||
setSurfaceStyle({
|
||||
const next:CSSProperties = {
|
||||
top: position.top,
|
||||
left: position.left,
|
||||
width: surfaceWidth,
|
||||
width: Math.min(surfaceWidth, position.maxWidth ?? surfaceWidth),
|
||||
maxHeight: position.maxHeight,
|
||||
visibility: "visible",
|
||||
});
|
||||
}, [anchorElement, close, minWidth, offset, placement, triggerElement, width]);
|
||||
};
|
||||
setSurfaceStyle(old => Object.keys(next).every(key => old[key as keyof CSSProperties] === next[key as keyof CSSProperties]) ? old : next);
|
||||
}, [anchorElement, close, minWidth, offset, placement, triggerElement, width, getAnchorRect, flip]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!isOpen) return;
|
||||
updatePosition();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !getAnchorRect) return;
|
||||
let frame:number;
|
||||
const tick=()=>{updatePosition();frame=requestAnimationFrame(tick);};
|
||||
frame=requestAnimationFrame(tick);
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[isOpen,getAnchorRect,updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof Node)) return;
|
||||
if (anchorElement?.contains(target) || triggerElement?.contains(target) || surfaceRef.current?.contains(target)) return;
|
||||
const surface = (target instanceof Element ? target : target.parentElement)?.closest('[data-dropdown-lineage]');
|
||||
if (surface?.getAttribute('data-dropdown-lineage')?.split(' ').includes(instanceId)) return;
|
||||
close();
|
||||
onPointerDownOutside?.(event);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
if (event.key === "Escape" && !event.defaultPrevented) {
|
||||
if ([...openDropdowns].some(([id, parents]) => id !== instanceId && parents.includes(instanceId))) return;
|
||||
close();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
triggerElement?.focus();
|
||||
}
|
||||
};
|
||||
const handleOtherOpen = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ id?: string }>).detail;
|
||||
if (detail.id !== instanceId) close();
|
||||
const detail = (event as CustomEvent<{ id?: string; lineage?: readonly string[] }>).detail;
|
||||
if (detail.id !== instanceId && !detail.lineage?.includes(instanceId)) close();
|
||||
};
|
||||
const handleViewportChange = () => updatePosition();
|
||||
|
||||
window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId } }));
|
||||
document.addEventListener("pointerdown", handlePointerDown);
|
||||
openDropdowns.set(instanceId, lineage);
|
||||
window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId, lineage } }));
|
||||
document.addEventListener("pointerdown", handlePointerDown, true);
|
||||
document.addEventListener("keydown", handleKeyDown, true);
|
||||
window.addEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
|
||||
window.addEventListener("resize", handleViewportChange);
|
||||
window.addEventListener("scroll", handleViewportChange, true);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", handlePointerDown);
|
||||
openDropdowns.delete(instanceId);
|
||||
document.removeEventListener("pointerdown", handlePointerDown, true);
|
||||
document.removeEventListener("keydown", handleKeyDown, true);
|
||||
window.removeEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
|
||||
window.removeEventListener("resize", handleViewportChange);
|
||||
window.removeEventListener("scroll", handleViewportChange, true);
|
||||
};
|
||||
}, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition]);
|
||||
}, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition, lineage, onPointerDownOutside]);
|
||||
|
||||
return (
|
||||
<span className={cn("nodedc-dropdown-anchor", className)}>
|
||||
@@ -154,13 +185,16 @@ export function Dropdown({
|
||||
<div
|
||||
ref={surfaceRef}
|
||||
id={surfaceId}
|
||||
data-dropdown-lineage={lineage.join(' ')}
|
||||
className={cn("nodedc-dropdown-surface", surfaceClassName)}
|
||||
role={surfaceRole}
|
||||
style={surfaceStyle}
|
||||
>
|
||||
{typeof children === "function" ? children({ close }) : children}
|
||||
<DropdownLineage.Provider value={lineage}>
|
||||
{typeof children === "function" ? children({ close }) : children}
|
||||
</DropdownLineage.Provider>
|
||||
</div>,
|
||||
document.body,
|
||||
document.fullscreenElement ?? document.body,
|
||||
)
|
||||
: null}
|
||||
</span>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useLayoutEffect, useRef, type ReactNode } from "react";
|
||||
import { HeaderAvatar } from "./AppHeader.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
import { Window } from "./Window.js";
|
||||
@@ -43,6 +43,8 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
footer,
|
||||
headerActions,
|
||||
}: FeatureSettingsWindowProps<T>) {
|
||||
const contentRef = useRef<HTMLElement>(null);
|
||||
useLayoutEffect(() => { if (contentRef.current) contentRef.current.scrollTop = 0; }, [activeSection]);
|
||||
return (
|
||||
<Window
|
||||
open={open}
|
||||
@@ -56,7 +58,7 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
onClose={onClose}
|
||||
>
|
||||
<div className="nodedc-feature-settings">
|
||||
<aside className="nodedc-feature-settings__navigation" aria-label="Разделы настроек">
|
||||
<aside className="nodedc-feature-settings__navigation" aria-label="Разделы настроек" tabIndex={0}>
|
||||
<div className="nodedc-feature-settings__identity">
|
||||
<HeaderAvatar label={identity.avatarLabel} imageUrl={identity.avatarUrl} />
|
||||
<span><strong>{identity.title}</strong>{identity.subtitle ? <small>{identity.subtitle}</small> : null}</span>
|
||||
@@ -82,7 +84,7 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
})}
|
||||
</nav>
|
||||
</aside>
|
||||
<section className="nodedc-feature-settings__content">{children}</section>
|
||||
<section ref={contentRef} className="nodedc-feature-settings__content" aria-label="Содержимое настроек" tabIndex={0}>{children}</section>
|
||||
</div>
|
||||
</Window>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { cn } from "./cn.js";
|
||||
|
||||
export interface FieldFrameProps {
|
||||
label: string;
|
||||
labelPlacement?: "above" | "below";
|
||||
hint?: string;
|
||||
description?: string;
|
||||
htmlFor?: string;
|
||||
@@ -10,9 +11,9 @@ export interface FieldFrameProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function FieldFrame({ label, hint, description, htmlFor, children, className }: FieldFrameProps) {
|
||||
export function FieldFrame({ label, hint, description, htmlFor, children, className, labelPlacement = "above" }: FieldFrameProps) {
|
||||
return (
|
||||
<label className={cn("nodedc-field", className)} htmlFor={htmlFor}>
|
||||
<label className={cn("nodedc-field", labelPlacement === "below" && "nodedc-field--caption", className)} htmlFor={htmlFor}>
|
||||
<span className="nodedc-field__label-row">
|
||||
<span className="nodedc-field__label">{label}</span>
|
||||
{hint ? <span className="nodedc-field__hint">{hint}</span> : null}
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import {
|
||||
MousePointer2,
|
||||
CirclePlus,
|
||||
Box,
|
||||
Scan,
|
||||
PenTool,
|
||||
RectangleHorizontal,
|
||||
Spline,
|
||||
Undo2,
|
||||
Redo2,
|
||||
Activity,
|
||||
AlertTriangle,
|
||||
Boxes,
|
||||
@@ -39,6 +48,7 @@ import {
|
||||
Play,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
RotateCw,
|
||||
Save,
|
||||
Search,
|
||||
Settings,
|
||||
@@ -57,6 +67,15 @@ import {
|
||||
} from "lucide-react";
|
||||
|
||||
const icons = {
|
||||
"add-point": CirclePlus,
|
||||
perspective: Box,
|
||||
orthographic: Scan,
|
||||
select: MousePointer2,
|
||||
pen: PenTool,
|
||||
rectangle: RectangleHorizontal,
|
||||
curve: Spline,
|
||||
undo: Undo2,
|
||||
redo: Redo2,
|
||||
activity: Activity,
|
||||
alert: AlertTriangle,
|
||||
apps: Boxes,
|
||||
@@ -99,6 +118,7 @@ const icons = {
|
||||
plus: Plus,
|
||||
profile: UserCircle,
|
||||
refresh: RefreshCw,
|
||||
"rotate-clockwise": RotateCw,
|
||||
save: Save,
|
||||
search: Search,
|
||||
settings: Settings,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { Select, type SelectProps } from "./Select.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { IconButton } from "./Button.js";
|
||||
|
||||
export interface InspectorSectionSpec {
|
||||
id: string;
|
||||
@@ -13,6 +14,7 @@ export interface InspectorSectionSpec {
|
||||
disabled?: boolean;
|
||||
tone?: "default" | "accent";
|
||||
icon?: ReactNode;
|
||||
action?: { label: string; icon: ReactNode; onAction: () => void; disabled?: boolean };
|
||||
}
|
||||
|
||||
export interface InspectorProps {
|
||||
@@ -74,6 +76,7 @@ export function Inspector({
|
||||
const isOpen = openIds.has(section.id);
|
||||
return (
|
||||
<section className="nodedc-inspector__section" key={section.id}>
|
||||
<div className="nodedc-inspector__section-head" data-action={section.action ? "true" : undefined}>
|
||||
<button
|
||||
type="button"
|
||||
className="nodedc-inspector__section-trigger"
|
||||
@@ -91,8 +94,13 @@ export function Inspector({
|
||||
<span className="nodedc-inspector__section-description">{section.description}</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="nodedc-inspector__section-chevron" aria-hidden="true"><Icon name="chevron-right" size={14} /></span>
|
||||
<span className="nodedc-inspector__section-chevron" aria-hidden="true"><Icon name={variant === "panel" ? "chevron-down" : "chevron-right"} size={14} /></span>
|
||||
</button>
|
||||
{section.action ? <IconButton className="nodedc-inspector__section-action" label={section.action.label}
|
||||
disabled={section.disabled || section.action.disabled} onClick={section.action.onAction}>
|
||||
{section.action.icon}
|
||||
</IconButton> : null}
|
||||
</div>
|
||||
{isOpen ? <div className="nodedc-inspector__section-content">{section.content}</div> : null}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import { createContext } from "react";
|
||||
/** A composed content surface owns one pending indicator. Windows reset this scope. */
|
||||
export const LoadingContext = createContext<null | ((id: string, pending: boolean) => void)>(null);
|
||||
@@ -1,23 +1,38 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import { useCallback, useContext, useId, useLayoutEffect, useState, type HTMLAttributes } from "react";
|
||||
import { ActivityIndicator } from "./ActivityIndicator.js";
|
||||
import { LoadingContext } from "./LoadingContext.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface LoadingRegionProps extends HTMLAttributes<HTMLDivElement> {
|
||||
loading: boolean;
|
||||
label: string;
|
||||
/** Collect nested initial-content loads into this surface's single indicator. */
|
||||
aggregate?: boolean;
|
||||
}
|
||||
|
||||
/** Keeps content mounted and centers pending feedback inside its own bounds. */
|
||||
export function LoadingRegion({ loading, label, children, className, ...props }: LoadingRegionProps) {
|
||||
return (
|
||||
<div {...props} className={cn("nodedc-loading-region", className)} aria-busy={loading}>
|
||||
{children}
|
||||
{loading ? (
|
||||
<div className="nodedc-loading-region__status" role="status" aria-label={label}>
|
||||
<ActivityIndicator />
|
||||
<span aria-hidden="true">{label}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
/** Keeps content mounted. Failures/unmounts release each nested pending lease. */
|
||||
export function LoadingRegion({ loading, label, aggregate = false, children, className, ...props }: LoadingRegionProps) {
|
||||
const parent = useContext(LoadingContext);
|
||||
const id = useId();
|
||||
const [pending, setPending] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const report = useCallback((key: string, busy: boolean) => {
|
||||
setPending(previous => {
|
||||
if (previous.has(key) === busy) return previous;
|
||||
const next = new Set(previous);
|
||||
if (busy) next.add(key); else next.delete(key);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
parent?.(id, loading);
|
||||
return () => parent?.(id, false);
|
||||
}, [parent, id, loading]);
|
||||
const busy = loading || (aggregate && !parent && pending.size > 0);
|
||||
const content = <div {...props} className={cn("nodedc-loading-region", className)} aria-busy={busy}>
|
||||
{children}
|
||||
{busy && !parent ? <div className="nodedc-loading-region__status" role="status" aria-label={label}>
|
||||
<ActivityIndicator /><span aria-hidden="true">{label}</span>
|
||||
</div> : null}
|
||||
</div>;
|
||||
return aggregate && !parent ? <LoadingContext.Provider value={report}>{content}</LoadingContext.Provider> : content;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import {useState,type CSSProperties} from "react";
|
||||
export type CubeDirection = [number,number,number];
|
||||
export interface NavigationCubeProps {
|
||||
/** Camera world quaternion, Y up. Directions point from target toward camera. */
|
||||
quaternion: readonly [number,number,number,number];
|
||||
onSelect: (direction:CubeDirection)=>void;
|
||||
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number;
|
||||
disabled?:boolean;
|
||||
label?:string;
|
||||
}
|
||||
const faces = [
|
||||
{axis:0,sign:1,label:"RIGHT"},{axis:0,sign:-1,label:"LEFT"},
|
||||
{axis:1,sign:1,label:"TOP"},{axis:1,sign:-1,label:"BOTTOM"},
|
||||
{axis:2,sign:1,label:"FRONT"},{axis:2,sign:-1,label:"BACK"},
|
||||
];
|
||||
const cuts=[-1,-.55,.55,1];
|
||||
/** Inverse quaternion rotation; avoids a renderer or additional WebGL context. */
|
||||
function view(p:number[],q:readonly number[]) {
|
||||
const n=Math.hypot(...q)||1;
|
||||
const [x,y,z,w]=[-q[0]/n,-q[1]/n,-q[2]/n,q[3]/n], [a,b,c]=p;
|
||||
const tx=2*(y*c-z*b),ty=2*(z*a-x*c),tz=2*(x*b-y*a);
|
||||
return [a+w*tx+y*tz-z*ty,b+w*ty+z*tx-x*tz,c+w*tz+x*ty-y*tx];
|
||||
}
|
||||
export function cubeRegions(quaternion:NavigationCubeProps["quaternion"]) {
|
||||
return faces.flatMap(face=>{
|
||||
const axes=[0,1,2].filter(k=>k!==face.axis),normal=[0,0,0];normal[face.axis]=face.sign;
|
||||
if(view(normal,quaternion)[2]<1e-5)return [];
|
||||
const point=(u:number,v:number)=>{const p=[0,0,0];p[face.axis]=face.sign;p[axes[0]]=u;p[axes[1]]=v;return p;};
|
||||
return Array.from({length:9},(_,i)=>{
|
||||
const row=Math.floor(i/3),col=i%3,direction=point(col-1,row-1) as CubeDirection;
|
||||
const label=faces.filter(f=>direction[f.axis]===f.sign).map(f=>f.label).join(" · ");
|
||||
const polygon=[[cuts[col],cuts[row]],[cuts[col+1],cuts[row]],[cuts[col+1],cuts[row+1]],[cuts[col],cuts[row+1]]]
|
||||
.map(([u,v])=>view(point(u,v),quaternion)).map(p=>`${60+p[0]*30},${60-p[1]*30}`).join(" ");
|
||||
const p=view(point(0,0),quaternion);
|
||||
// Face-local right/up tangents keep labels printed on the rotating face.
|
||||
const right=face.axis===0?[0,0,-face.sign]:face.axis===1?[1,0,0]:[face.sign,0,0];
|
||||
const up=face.axis===1?[0,0,-face.sign]:[0,1,0];
|
||||
const u=view(right,quaternion),v=view(up,quaternion);
|
||||
const textMatrix=[u[0],-u[1],-v[0],v[1],60+p[0]*30,60-p[1]*30];
|
||||
return {id:`${face.label}-${i}`,direction,label,polygon,faceLabel:i===4?face.label:null,textMatrix};
|
||||
});
|
||||
});
|
||||
}
|
||||
/** BIM-style face / edge / corner navigation, independent of the scene engine. */
|
||||
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1}:NavigationCubeProps) {
|
||||
const [hover,setHover]=useState<string|null>(null);
|
||||
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
|
||||
{cubeRegions(quaternion).map(r=><g key={r.id} role="button" aria-label={`Ракурс: ${r.label}`} aria-disabled={disabled}
|
||||
tabIndex={disabled?-1:0} className={hover===r.label?"is-hovered":""}
|
||||
onPointerEnter={()=>setHover(r.label)} onPointerLeave={()=>setHover(null)}
|
||||
onClick={()=>{if(!disabled)onSelect(r.direction);}}
|
||||
onKeyDown={e=>{if(!disabled&&(e.key==="Enter"||e.key===" ")){e.preventDefault();onSelect(r.direction);}}}>
|
||||
<title>{r.label}</title><polygon points={r.polygon}/>
|
||||
{r.faceLabel?<text transform={`matrix(${r.textMatrix.join(" ")})`} x={0} y={0} dy=".35em" textAnchor="middle">{r.faceLabel}</text>:null}
|
||||
</g>)}
|
||||
</svg>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useId } from "react";
|
||||
import { Button, type ButtonProps } from "./Button.js";
|
||||
import { ProgressBar } from "./ProgressBar.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface ProgressButtonProps extends Omit<ButtonProps, "children" | "loading" | "size"> {
|
||||
label: string;
|
||||
/** Presence means pending. Value is measured progress of the named phase, not elapsed time. */
|
||||
progress?: { label: string; value?: number; valueText?: string };
|
||||
}
|
||||
|
||||
export function ProgressButton({ label, progress, className, disabled, icon, ...props }: ProgressButtonProps) {
|
||||
const statusId = useId();
|
||||
return <div className={cn("nodedc-progress-button", className)} data-pending={!!progress || undefined}
|
||||
data-icon={!!icon || undefined}>
|
||||
<Button {...props} icon={icon} disabled={disabled || !!progress} aria-busy={!!progress}
|
||||
aria-label={label} aria-describedby={progress ? statusId : undefined}>
|
||||
<span className="nodedc-progress-button__label">{progress?.label ?? label}</span>
|
||||
</Button>
|
||||
{progress ? <>
|
||||
<span id={statusId} className="nodedc-progress-button__status" role="status">{progress.label}</span>
|
||||
<ProgressBar label={label} value={progress.value} valueText={progress.valueText ?? progress.label} />
|
||||
</> : null}
|
||||
</div>;
|
||||
}
|
||||
|
||||
/** Decorative animation of the canonical layers glyph. The surrounding action owns live status. */
|
||||
export function LayerStackIndicator() {
|
||||
return <Icon name="layers" className="nodedc-layer-stack-indicator" />;
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type InputHTMLAttributes, type KeyboardEvent, type PointerEvent } from "react";
|
||||
import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBand.js";
|
||||
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Dropdown } from "./Dropdown.js";
|
||||
|
||||
@@ -13,7 +15,7 @@ export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputEle
|
||||
max?: number;
|
||||
};
|
||||
formatValue?: (value: number) => string;
|
||||
/** Unit-free endpoint labels beside the vertical scale. */
|
||||
/** Unit-free retained lower bound and moving upper/value boundary. */
|
||||
formatLimit?: (value: number) => string;
|
||||
/** Physical side for vertical endpoint labels; use the inward side of a scene rail. */
|
||||
limitSide?: "left" | "right";
|
||||
@@ -55,7 +57,16 @@ const editableNumber = (value: number) => (
|
||||
Number.isInteger(value) ? String(value) : String(Number(value.toFixed(12)))
|
||||
);
|
||||
|
||||
export function RangeControl({
|
||||
function isBand(props: RangeControlProps | RangeBandControlProps): props is RangeBandControlProps {
|
||||
return Array.isArray(props.value);
|
||||
}
|
||||
export function RangeControl(props: RangeControlProps): ReturnType<typeof SingleRangeControl>;
|
||||
export function RangeControl(props: RangeBandControlProps): ReturnType<typeof VerticalRangeBand>;
|
||||
export function RangeControl(props: RangeControlProps | RangeBandControlProps) {
|
||||
return isBand(props) ? <VerticalRangeBand {...props} /> : <SingleRangeControl {...props} />;
|
||||
}
|
||||
|
||||
function SingleRangeControl({
|
||||
label,
|
||||
orientation = "horizontal",
|
||||
value,
|
||||
@@ -141,17 +152,13 @@ export function RangeControl({
|
||||
};
|
||||
|
||||
if (orientation === "vertical") return (
|
||||
<div className="nodedc-range-scale" data-limit-side={limitSide}>
|
||||
<div className="nodedc-range-scale" data-limit-side={limitSide} style={style}>
|
||||
<div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical">
|
||||
<input ref={rangeRef} {...props} type="range" value={value} min={min} max={safeMax} step={step}
|
||||
disabled={disabled} tabIndex={tabIndex} aria-label={label} aria-orientation="vertical"
|
||||
aria-valuetext={displayValue} onChange={(event) => onChange(Number(event.target.value))} />
|
||||
<span className="nodedc-range__label">{label} · {displayValue}</span>
|
||||
<span className="nodedc-range__fill-text" aria-hidden="true">
|
||||
<span className="nodedc-range__label">{label} · {displayValue}</span>
|
||||
</span>
|
||||
</div>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(max)}</span>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(clampRangeValue(value, min, safeMax))}</span>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--min">{formatLimit(min)}</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { forwardRef, type ButtonHTMLAttributes, type HTMLAttributes, type ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface SegmentedItem<T extends string> {
|
||||
@@ -7,48 +7,46 @@ export interface SegmentedItem<T extends string> {
|
||||
icon?: ReactNode;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export type SegmentedControlSize = "default" | "dense";
|
||||
|
||||
export interface SegmentedControlProps<T extends string> {
|
||||
value: T;
|
||||
export type SegmentedControlProps<T extends string> = {
|
||||
items: Array<SegmentedItem<T>>;
|
||||
label: string;
|
||||
size?: SegmentedControlSize;
|
||||
className?: string;
|
||||
onChange: (value: T) => void;
|
||||
} & ({ selectionMode?: "single"; value: T; onChange: (value: T) => void }
|
||||
| { selectionMode: "multiple"; value: readonly T[]; onChange: (value: T[]) => void });
|
||||
|
||||
export function SegmentedControl<T extends string>(props: SegmentedControlProps<T>) {
|
||||
const { items, label, size = "default", className } = props;
|
||||
const multiple = props.selectionMode === "multiple";
|
||||
return <div className={cn("nodedc-segmented", className)}
|
||||
role={multiple ? "group" : "tablist"} aria-label={label}
|
||||
data-size={size === "default" ? undefined : size}>
|
||||
{items.map(item => {
|
||||
const active = props.selectionMode === "multiple" ? props.value.includes(item.value) : props.value === item.value;
|
||||
return <button key={item.value} type="button" className="nodedc-segmented__item"
|
||||
role={multiple ? undefined : "tab"} aria-selected={multiple ? undefined : active}
|
||||
aria-pressed={multiple ? active : undefined} data-active={active ? "true" : undefined}
|
||||
disabled={item.disabled} onClick={() => {
|
||||
if (props.selectionMode === "multiple") {
|
||||
props.onChange(active ? props.value.filter(value => value !== item.value) : [...props.value, item.value]);
|
||||
} else props.onChange(item.value);
|
||||
}}>{item.icon}{item.label}</button>;
|
||||
})}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function SegmentedControl<T extends string>({
|
||||
value,
|
||||
items,
|
||||
label,
|
||||
size = "default",
|
||||
className,
|
||||
onChange,
|
||||
}: SegmentedControlProps<T>) {
|
||||
return (
|
||||
<div
|
||||
className={cn("nodedc-segmented", className)}
|
||||
role="tablist"
|
||||
aria-label={label}
|
||||
data-size={size === "default" ? undefined : size}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.value}
|
||||
type="button"
|
||||
className="nodedc-segmented__item"
|
||||
role="tab"
|
||||
aria-selected={item.value === value}
|
||||
data-active={item.value === value ? "true" : undefined}
|
||||
disabled={item.disabled}
|
||||
onClick={() => onChange(item.value)}
|
||||
>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
/** Shared capsule for independently controlled toggles and menu triggers. */
|
||||
export function SegmentedGroup({ label, size = "default", className, ...props }:
|
||||
HTMLAttributes<HTMLDivElement> & { label: string; size?: SegmentedControlSize }) {
|
||||
return <div {...props} className={cn("nodedc-segmented", className)} role="group" aria-label={label}
|
||||
data-size={size === "default" ? undefined : size} />;
|
||||
}
|
||||
|
||||
/** Caller supplies aria-pressed for toggles or aria-expanded/haspopup for menu triggers. */
|
||||
export const SegmentedButton = forwardRef<HTMLButtonElement,
|
||||
ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean }
|
||||
>(function SegmentedButton({ active, className, type = "button", ...props }, ref) {
|
||||
return <button {...props} ref={ref} type={type} className={cn("nodedc-segmented__item", className)}
|
||||
data-active={active ? "true" : undefined} />;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { Description } from "./Description.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface SettingsCardProps extends Omit<HTMLAttributes<HTMLElement>, "title"> {
|
||||
@@ -16,7 +17,7 @@ export function SettingsCard({ eyebrow, title, description, actions, children, a
|
||||
<div className="nodedc-settings-card__titles">
|
||||
{eyebrow ? <span>{eyebrow}</span> : null}
|
||||
<h2>{title}</h2>
|
||||
{description ? <p>{description}</p> : null}
|
||||
{description ? <Description>{description}</Description> : null}
|
||||
</div>
|
||||
{actions ? <div className="nodedc-settings-card__actions">{actions}</div> : null}
|
||||
</header>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import {
|
||||
calculateToolbarTargets,
|
||||
NODEDC_TOOLBAR_DEFAULTS,
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
stepToolbarSpring,
|
||||
type ToolbarPlacement as CoreToolbarPlacement,
|
||||
} from "@nodedc/ui-core";
|
||||
import { Dropdown, type DropdownTriggerApi } from "./Dropdown.js";
|
||||
import { useToolbarMenus } from "./useToolbarMenus.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
|
||||
@@ -17,6 +19,8 @@ export interface ToolbarItem<T extends string = string> {
|
||||
icon: IconName;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
shortcut?: string;
|
||||
menu?: ReactNode | ((close: () => void) => ReactNode);
|
||||
onSelect: (id: T) => void;
|
||||
}
|
||||
|
||||
@@ -31,8 +35,12 @@ export interface ToolbarProps<T extends string = string> {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
label?: string;
|
||||
className?: string;
|
||||
/** Render inside a positioned viewport; edge reveal follows that viewport. */
|
||||
container?: HTMLElement;
|
||||
}
|
||||
|
||||
interface ToolbarMotion {
|
||||
@@ -55,9 +63,13 @@ export function Toolbar<T extends string = string>({
|
||||
maxSize = NODEDC_TOOLBAR_DEFAULTS.maxSize,
|
||||
lensCount = NODEDC_TOOLBAR_DEFAULTS.lensCount,
|
||||
autoHide = false,
|
||||
hideDelay = NODEDC_TOOLBAR_DEFAULTS.hideDelay,
|
||||
gap = NODEDC_TOOLBAR_DEFAULTS.gap,
|
||||
label = "Панель инструментов",
|
||||
className,
|
||||
container,
|
||||
}: ToolbarProps<T>) {
|
||||
const menus = useToolbarMenus();
|
||||
const [visible, setVisible] = useState(!autoHide);
|
||||
const [dockActive, setDockActive] = useState(false);
|
||||
const toolbarRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -68,16 +80,19 @@ export function Toolbar<T extends string = string>({
|
||||
const frameLastTsRef = useRef(0);
|
||||
const hideTimerRef = useRef<number | null>(null);
|
||||
const hoverDockRef = useRef(false);
|
||||
const openMenusRef = useRef(new Set<string>());
|
||||
|
||||
const vertical = placement !== "bottom";
|
||||
const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount });
|
||||
const vertical = placement === "left" || placement === "right";
|
||||
const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount, gap });
|
||||
const safeMin = normalized.minSize;
|
||||
const safeMax = normalized.maxSize;
|
||||
const safeLens = normalized.lensCount;
|
||||
const safeGap = Math.min(24,normalized.gap);
|
||||
const safeDelay = Math.max(0,Math.min(15000,Number.isFinite(hideDelay)?hideDelay:NODEDC_TOOLBAR_DEFAULTS.hideDelay));
|
||||
const radius = Math.max(7, Math.round(safeMin * 0.28));
|
||||
const glyphSize = Math.max(12, Math.min(18, Math.round(safeMin * 0.62)));
|
||||
const settingsRef = useRef({ minSize: safeMin, maxSize: safeMax, lensCount: safeLens, vertical });
|
||||
settingsRef.current = { minSize: safeMin, maxSize: safeMax, lensCount: safeLens, vertical };
|
||||
const settingsRef = useRef({ minSize: safeMin, maxSize: safeMax, lensCount: safeLens, gap:safeGap, vertical });
|
||||
settingsRef.current = { minSize: safeMin, maxSize: safeMax, lensCount: safeLens, gap:safeGap, vertical };
|
||||
actionKeysRef.current = items.map((item) => String(item.id));
|
||||
|
||||
const getMotion = useCallback((key: string) => {
|
||||
@@ -176,7 +191,7 @@ export function Toolbar<T extends string = string>({
|
||||
const toolbar = toolbarRef.current;
|
||||
const keys = actionKeysRef.current;
|
||||
if (!toolbar || !keys.length) return;
|
||||
const { minSize: currentMin, maxSize: currentMax, lensCount: currentLens, vertical: isVertical } = settingsRef.current;
|
||||
const { minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap:currentGap, vertical: isVertical } = settingsRef.current;
|
||||
const toolbarRect = toolbar.getBoundingClientRect();
|
||||
const entries = keys
|
||||
.map((key) => {
|
||||
@@ -193,7 +208,7 @@ export function Toolbar<T extends string = string>({
|
||||
const targets = calculateToolbarTargets(
|
||||
entries.map((entry) => entry.center),
|
||||
pointerCoordinate,
|
||||
{ minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: NODEDC_TOOLBAR_DEFAULTS.gap },
|
||||
{ minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: currentGap },
|
||||
);
|
||||
entries.forEach(({ key }, index) => {
|
||||
const target = targets[index];
|
||||
@@ -213,18 +228,19 @@ export function Toolbar<T extends string = string>({
|
||||
if (!autoHide || hideTimerRef.current != null) return;
|
||||
hideTimerRef.current = window.setTimeout(() => {
|
||||
hideTimerRef.current = null;
|
||||
if (hoverDockRef.current) return;
|
||||
if (hoverDockRef.current || openMenusRef.current.size || toolbarRef.current?.contains(document.activeElement)) return;
|
||||
setVisible(false);
|
||||
resetMagnification();
|
||||
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay);
|
||||
}, [autoHide, resetMagnification]);
|
||||
}, safeDelay);
|
||||
}, [autoHide, resetMagnification, safeDelay]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hideTimerRef.current != null) { window.clearTimeout(hideTimerRef.current); hideTimerRef.current = null; }
|
||||
if (!autoHide) {
|
||||
setVisible(true);
|
||||
return;
|
||||
}
|
||||
setVisible(false);
|
||||
setVisible(hoverDockRef.current || openMenusRef.current.size > 0);
|
||||
setDockActive(false);
|
||||
}, [autoHide]);
|
||||
|
||||
@@ -236,17 +252,19 @@ export function Toolbar<T extends string = string>({
|
||||
if (!autoHide) return;
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
const threshold = Math.max(32, settingsRef.current.maxSize * 0.75);
|
||||
const nearEdge = placement === "left"
|
||||
? event.clientX <= threshold
|
||||
const bounds = container?.getBoundingClientRect() ?? {left:0, top:0, right:window.innerWidth, bottom:window.innerHeight};
|
||||
const inside = event.clientX >= bounds.left && event.clientX <= bounds.right && event.clientY >= bounds.top && event.clientY <= bounds.bottom;
|
||||
const nearEdge = inside && (placement === "left"
|
||||
? event.clientX <= bounds.left + threshold
|
||||
: placement === "right"
|
||||
? event.clientX >= window.innerWidth - threshold
|
||||
: event.clientY >= window.innerHeight - threshold;
|
||||
? event.clientX >= bounds.right - threshold
|
||||
: placement === "top" ? event.clientY <= bounds.top + threshold : event.clientY >= bounds.bottom - threshold);
|
||||
if (nearEdge) showDock();
|
||||
else if (!hoverDockRef.current) scheduleHide();
|
||||
};
|
||||
window.addEventListener("pointermove", handlePointerMove, { passive: true });
|
||||
return () => window.removeEventListener("pointermove", handlePointerMove);
|
||||
}, [autoHide, placement, scheduleHide, showDock]);
|
||||
}, [autoHide, placement, container, scheduleHide, showDock]);
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
@@ -271,6 +289,11 @@ export function Toolbar<T extends string = string>({
|
||||
if (hideTimerRef.current != null) window.clearTimeout(hideTimerRef.current);
|
||||
}, []);
|
||||
|
||||
useEffect(()=>{
|
||||
const keys=new Set(items.map(i=>String(i.id)));
|
||||
for(const key of openMenusRef.current)if(!keys.has(key)){openMenusRef.current.delete(key);delete menus.apis.current[key];if(menus.active.current===key)menus.active.current=null;}
|
||||
},[items,menus]);
|
||||
|
||||
const style = {
|
||||
"--nodedc-toolbar-bg": background,
|
||||
"--nodedc-toolbar-border": border,
|
||||
@@ -279,7 +302,7 @@ export function Toolbar<T extends string = string>({
|
||||
"--nodedc-toolbar-min-size": `${safeMin}px`,
|
||||
"--nodedc-toolbar-max-size": `${safeMax}px`,
|
||||
"--nodedc-toolbar-radius": `${radius}px`,
|
||||
"--nodedc-toolbar-gap": `${NODEDC_TOOLBAR_DEFAULTS.gap}px`,
|
||||
"--nodedc-toolbar-gap": `${safeGap}px`,
|
||||
"--nodedc-toolbar-padding": `${NODEDC_TOOLBAR_DEFAULTS.padding}px`,
|
||||
} as CSSProperties;
|
||||
|
||||
@@ -287,6 +310,7 @@ export function Toolbar<T extends string = string>({
|
||||
<div
|
||||
className={cn("nodedc-toolbar-wrap", className)}
|
||||
data-placement={placement}
|
||||
data-scope={container ? "viewport" : "window"}
|
||||
data-visible={visible ? "true" : undefined}
|
||||
data-active={dockActive ? "true" : undefined}
|
||||
data-autohide={autoHide ? "true" : undefined}
|
||||
@@ -324,17 +348,23 @@ export function Toolbar<T extends string = string>({
|
||||
>
|
||||
{items.map((item) => {
|
||||
const key = String(item.id);
|
||||
return (
|
||||
const button = (api?: DropdownTriggerApi) => {
|
||||
if(api)menus.apis.current[key]=api;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
ref={(element) => { buttonRefs.current[key] = element; }}
|
||||
ref={(element) => { buttonRefs.current[key] = element; api?.setTriggerRef(element); }}
|
||||
type="button"
|
||||
className="nodedc-toolbar__button"
|
||||
data-toolbar-menu={item.menu ? key : undefined}
|
||||
data-active={item.active ? "true" : undefined}
|
||||
aria-label={item.label}
|
||||
title={item.shortcut ? `${item.label} · ${item.shortcut}` : item.label}
|
||||
aria-keyshortcuts={item.shortcut}
|
||||
aria-pressed={item.active}
|
||||
disabled={item.disabled}
|
||||
onFocus={(event) => {
|
||||
showDock();
|
||||
const button = event.currentTarget;
|
||||
const toolbarRect = toolbarRef.current?.getBoundingClientRect();
|
||||
if (!toolbarRect) return;
|
||||
@@ -345,11 +375,34 @@ export function Toolbar<T extends string = string>({
|
||||
updateMagnification(coordinate);
|
||||
}}
|
||||
onBlur={resetMagnification}
|
||||
onClick={() => item.onSelect(item.id)}
|
||||
aria-haspopup={item.menu ? "menu" : undefined}
|
||||
aria-expanded={item.menu ? api?.open : undefined}
|
||||
onClick={() => item.menu ? api?.toggle() : item.onSelect(item.id)}
|
||||
>
|
||||
<Icon name={item.icon} size={glyphSize} />
|
||||
</button>
|
||||
);
|
||||
);};
|
||||
return item.menu ? <Dropdown key={key} placement={placement === "right" ? "left-start" : placement === "left" ? "right-start" : placement === "bottom" ? "top-end" : "bottom-end"} flip={false} getAnchorRect={()=>{
|
||||
const button=buttonRefs.current[key], toolbar=toolbarRef.current;
|
||||
if(!button||!toolbar)return null;
|
||||
const b=button.getBoundingClientRect(), t=toolbar.getBoundingClientRect();
|
||||
// Reserve the largest possible icon, including while its spring is still moving.
|
||||
const pad=Math.max(safeMax,...Object.values(buttonRefs.current).map(n=>n?.getBoundingClientRect().width??0));
|
||||
if(placement==="right")return {...b.toJSON(),left:t.right-pad,right:t.right,width:pad};
|
||||
if(placement==="left")return {...b.toJSON(),left:t.left,right:t.left+pad,width:pad};
|
||||
if(placement==="bottom")return {...b.toJSON(),top:t.bottom-pad,bottom:t.bottom,height:pad};
|
||||
return {...b.toJSON(),top:t.top,bottom:t.top+pad,height:pad};
|
||||
}} width={220} trigger={button} onPointerDownOutside={event=>{
|
||||
const target=event.target as Element;
|
||||
// Dismiss a menu before a viewport tool can turn this same click into an edit.
|
||||
if(container?.contains(target)&&!target.closest('button,input,select,textarea,a,[role="button"],[role="tab"]')){
|
||||
event.preventDefault();event.stopPropagation();
|
||||
}
|
||||
}} onOpenChange={open => {
|
||||
if(open){openMenusRef.current.add(key);menus.active.current=key;showDock();}else{openMenusRef.current.delete(key);if(menus.active.current===key)menus.active.current=null;scheduleHide();}
|
||||
}}>
|
||||
{({close}) => typeof item.menu === "function" ? item.menu(close) : item.menu}
|
||||
</Dropdown> : button();
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useRef, type CSSProperties, type PointerEvent } from "react";
|
||||
import type { RangeControlProps } from "./RangeControl.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { moveRangeBoundary, nearestRangeBoundary, normalizeRangeBand } from "./rangeBand.js";
|
||||
|
||||
export interface RangeBandControlProps extends Omit<RangeControlProps, "value" | "onChange" | "orientation" | "exactValueBounds"> {
|
||||
orientation: "vertical";
|
||||
value: readonly [number, number];
|
||||
onChange: (value: [number, number]) => void;
|
||||
lowerLabel?: string;
|
||||
upperLabel?: string;
|
||||
}
|
||||
|
||||
/** Two native keyboard targets, with one pointer track selecting its nearest boundary. */
|
||||
export function VerticalRangeBand({ label, value, min, max, step = 1, onChange,
|
||||
lowerLabel = `${label}: нижняя граница`, upperLabel = `${label}: верхняя граница`,
|
||||
formatValue = String, formatLimit = String, limitSide = "right", disabled = false,
|
||||
className, style, orientation: _orientation, ...props }: RangeBandControlProps) {
|
||||
const safeMax = max > min ? max : min + 1;
|
||||
const band = normalizeRangeBand(value, min, safeMax);
|
||||
const current = useRef(band); current.current = band;
|
||||
const inputs = useRef<(HTMLInputElement | null)[]>([]);
|
||||
const drag = useRef<{ id: number; boundary: 0 | 1 } | null>(null);
|
||||
const progress = band.map(n => (n - min) / (safeMax - min) * 100);
|
||||
const variables = { ...style, "--nodedc-range-lower": `${progress[0]}%`,
|
||||
"--nodedc-range-upper": `${progress[1]}%` } as CSSProperties;
|
||||
const change = (boundary: 0 | 1, next: number) => {
|
||||
const result = moveRangeBoundary(current.current, boundary, next, min, safeMax, step);
|
||||
current.current = result; onChange(result);
|
||||
};
|
||||
const position = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
return min + Math.max(0, Math.min(1, (rect.bottom - event.clientY) / rect.height)) * (safeMax - min);
|
||||
};
|
||||
const end = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (drag.current?.id !== event.pointerId) return;
|
||||
drag.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
};
|
||||
return <div className="nodedc-range-scale" data-band="true" data-limit-side={limitSide} data-disabled={disabled || undefined} style={variables}>
|
||||
<div className={cn("nodedc-range", className)} data-orientation="vertical">
|
||||
<div className="nodedc-range-band__target"
|
||||
onPointerDown={event => {
|
||||
if (disabled || event.button !== 0 || drag.current) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const next = position(event), boundary = nearestRangeBoundary(current.current, next);
|
||||
drag.current = { id: event.pointerId, boundary };
|
||||
inputs.current[boundary]?.focus({ preventScroll: true });
|
||||
event.currentTarget.setPointerCapture(event.pointerId); change(boundary, next);
|
||||
}}
|
||||
onPointerMove={event => {
|
||||
if (disabled || drag.current?.id !== event.pointerId) return;
|
||||
event.preventDefault(); event.stopPropagation(); change(drag.current.boundary, position(event));
|
||||
}} onPointerUp={end} onPointerCancel={end} onLostPointerCapture={() => { drag.current = null; }}>
|
||||
{([0, 1] as const).map(boundary => <input {...props} key={boundary}
|
||||
ref={node => { inputs.current[boundary] = node; }} type="range" data-boundary={boundary === 0 ? "lower" : "upper"}
|
||||
min={min} max={safeMax} step={step} value={band[boundary]} disabled={disabled}
|
||||
aria-label={boundary === 0 ? lowerLabel : upperLabel} aria-orientation="vertical"
|
||||
aria-valuemin={boundary === 0 ? min : band[0]} aria-valuemax={boundary === 0 ? band[1] : safeMax}
|
||||
aria-valuetext={formatValue(band[boundary])}
|
||||
onChange={event => change(boundary, Number(event.target.value))} />)}
|
||||
</div>
|
||||
</div>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(band[1])}</span>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--min">{formatLimit(band[0])}</span>
|
||||
</div>;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { LoadingContext } from "./LoadingContext.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
|
||||
@@ -154,7 +155,7 @@ export function Window({
|
||||
};
|
||||
|
||||
return createPortal(
|
||||
<InspectorSelectPolicyContext.Provider value={false}>
|
||||
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
|
||||
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} onPointerDown={handleBackdropPointerDown}>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
@@ -196,8 +197,8 @@ export function Window({
|
||||
{footer ? <footer className="nodedc-window__footer">{footer}</footer> : null}
|
||||
</div>
|
||||
</div>
|
||||
</InspectorSelectPolicyContext.Provider>,
|
||||
document.body,
|
||||
</InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
|
||||
document.fullscreenElement ?? document.body,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ export interface WorkspaceWindowProps extends Omit<HTMLAttributes<HTMLDivElement
|
||||
minWidth?: number;
|
||||
minHeight?: number;
|
||||
resizable?: boolean;
|
||||
resizeIndicator?: boolean;
|
||||
autoHeight?: boolean;
|
||||
active?: boolean;
|
||||
zIndex?: number;
|
||||
@@ -124,6 +125,7 @@ export function WorkspaceWindow({
|
||||
minWidth = 260,
|
||||
minHeight = 180,
|
||||
resizable = true,
|
||||
resizeIndicator = true,
|
||||
autoHeight = false,
|
||||
active = false,
|
||||
zIndex,
|
||||
@@ -377,6 +379,7 @@ export function WorkspaceWindow({
|
||||
data-active={active ? "true" : undefined}
|
||||
data-maximized={maximized ? "true" : undefined}
|
||||
data-resizable={resizable ? "true" : undefined}
|
||||
data-resize-indicator={resizeIndicator ? undefined : "hidden"}
|
||||
data-auto-height={autoHeight ? "true" : undefined}
|
||||
data-interaction={interactionKind ?? undefined}
|
||||
role="dialog"
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
export * from "./AppHeader.js";
|
||||
export * from "./ActivityIndicator.js";
|
||||
export * from "./LoadingRegion.js";
|
||||
export * from "./Description.js";
|
||||
export * from "./ComparisonTable.js";
|
||||
export * from "./AdminNavigationPanel.js";
|
||||
export * from "./ApplicationShell.js";
|
||||
export * from "./ApplicationSidePanel.js";
|
||||
export * from "./ApplicationWorkspace.js";
|
||||
export * from "./Button.js";
|
||||
export * from "./ProgressButton.js";
|
||||
export * from "./Checker.js";
|
||||
export * from "./ConfirmationModal.js";
|
||||
export * from "./Dropdown.js";
|
||||
export * from "./DragDrop.js";
|
||||
export * from "./DockLayout.js";
|
||||
export {decodeDockTree, dockIds, balancedDockTree, reconcileDockTree, pruneDockTree, moveDockPanel, resizeDockSplit, dockRects, dockPosition, type DockTree, type DockMove, type DockRect, type DockPosition} from "@nodedc/ui-core";
|
||||
export * from "./Field.js";
|
||||
export * from "./FeatureSettingsWindow.js";
|
||||
export * from "./Glass.js";
|
||||
export * from "./Inspector.js";
|
||||
export * from "./Icon.js";
|
||||
export * from "./NavigationCube.js";
|
||||
export * from "./MediaSourceField.js";
|
||||
export * from "./RangeControl.js";
|
||||
export * from "./ResourceRow.js";
|
||||
@@ -36,3 +42,5 @@ export * from "./EnvironmentMediaPlaylistEditor.js";
|
||||
export * from "./EnvironmentBackgroundMedia.js";
|
||||
export * from "./LandingStage.js";
|
||||
export {KeyButton, type KeyButtonProps} from './KeyButton.js';
|
||||
|
||||
export type {DockMinimum, DockMinimums} from "@nodedc/ui-core";
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export type RangeBand = readonly [number, number];
|
||||
const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n));
|
||||
|
||||
export function normalizeRangeBand(value: RangeBand, min: number, max: number): [number, number] {
|
||||
const low = clamp(value[0], min, max);
|
||||
return [low, clamp(value[1], low, max)];
|
||||
}
|
||||
|
||||
export function nearestRangeBoundary([low, high]: RangeBand, value: number): 0 | 1 {
|
||||
// Coincident boundaries remain separable: below pulls the lower, above the upper.
|
||||
return value <= (low + high) / 2 ? 0 : 1;
|
||||
}
|
||||
|
||||
export function moveRangeBoundary(value: RangeBand, boundary: 0 | 1, next: number,
|
||||
min: number, max: number, step: string | number = 1): [number, number] {
|
||||
const band = normalizeRangeBand(value, min, max);
|
||||
const increment = Number(step);
|
||||
const bounded = clamp(next, min, max);
|
||||
// Exact endpoints stay reachable even when the range is not step-aligned.
|
||||
const aligned = bounded === min || bounded === max || !Number.isFinite(increment) || increment <= 0
|
||||
? bounded : Number((min + Math.round((bounded - min) / increment) * increment).toPrecision(12));
|
||||
band[boundary] = boundary === 0 ? clamp(aligned, min, band[1]) : clamp(aligned, band[0], max);
|
||||
return band;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useEffect,useRef} from "react";
|
||||
import {movingToMenu,type MenuPoint} from "@nodedc/ui-core";
|
||||
import type {DropdownTriggerApi} from "./Dropdown.js";
|
||||
export function useToolbarMenus() {
|
||||
const apis=useRef<Record<string,DropdownTriggerApi>>({});
|
||||
const active=useRef<string|null>(null);
|
||||
useEffect(()=>{
|
||||
let previous:MenuPoint|null=null, origin:MenuPoint|null=null, pending:string|null=null, timer:number|undefined;
|
||||
const clear=()=>{window.clearTimeout(timer);timer=undefined;pending=null;};
|
||||
const open=(key:string)=>{clear();apis.current[key]?.show();};
|
||||
const move=(event:PointerEvent)=>{
|
||||
const current={x:event.clientX,y:event.clientY}, old=previous;previous=current;
|
||||
const key=active.current;if(!key){clear();origin=null;return;}
|
||||
const api=apis.current[key], surface=document.getElementById(api?.surfaceId);
|
||||
const target=event.target instanceof Element?event.target:null;
|
||||
if(surface?.contains(target)){clear();origin=current;return;}
|
||||
const button=target?.closest<HTMLButtonElement>('[data-toolbar-menu]');
|
||||
const next=button?.dataset.toolbarMenu;
|
||||
if(next===key){clear();origin=current;return;}
|
||||
if(!next||!apis.current[next]||button?.disabled){clear();return;}
|
||||
if(!origin)origin=old??current;
|
||||
const delay=surface&&old&&movingToMenu(origin,old,current,surface.getBoundingClientRect());
|
||||
if(!delay){open(next);origin=current;return;}
|
||||
if(pending===next)return;
|
||||
clear();pending=next;
|
||||
// Bounded grace: pausing on a sibling still switches, crossing diagonally into the menu does not.
|
||||
timer=window.setTimeout(()=>open(next),300);
|
||||
};
|
||||
document.addEventListener("pointermove",move,{passive:true});
|
||||
return()=>{clear();document.removeEventListener("pointermove",move);};
|
||||
},[]);
|
||||
return {apis,active};
|
||||
}
|
||||
+689
-132
File diff suppressed because it is too large
Load Diff
+110
-14
@@ -4,45 +4,141 @@
|
||||
"package": "@nodedc/ui-react",
|
||||
"baseLibrary": "lucide-react",
|
||||
"defaultSize": 18,
|
||||
"supportedSizes": [16, 18, 20],
|
||||
"supportedSizes": [
|
||||
16,
|
||||
18,
|
||||
20
|
||||
],
|
||||
"strokeWidth": 1.8,
|
||||
"filledNames": ["play", "stop"],
|
||||
"filledNames": [
|
||||
"play",
|
||||
"stop"
|
||||
],
|
||||
"groups": [
|
||||
{
|
||||
"id": "window-layer",
|
||||
"label": "Окно и слой",
|
||||
"referenceSources": ["launcher", "engine"],
|
||||
"names": ["close", "plus", "expand", "minimize", "refresh", "panel", "apps", "layers"]
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"engine"
|
||||
],
|
||||
"names": [
|
||||
"close",
|
||||
"plus",
|
||||
"expand",
|
||||
"minimize",
|
||||
"refresh",
|
||||
"panel",
|
||||
"apps",
|
||||
"layers"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "navigation",
|
||||
"label": "Навигация",
|
||||
"referenceSources": ["launcher", "engine", "bim-viewer"],
|
||||
"names": ["chevron-left", "chevron-right", "chevron-down", "chevron-up", "grid", "list", "sliders", "search"]
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"engine",
|
||||
"bim-viewer"
|
||||
],
|
||||
"names": [
|
||||
"chevron-left",
|
||||
"chevron-right",
|
||||
"chevron-down",
|
||||
"chevron-up",
|
||||
"grid",
|
||||
"list",
|
||||
"sliders",
|
||||
"search",
|
||||
"orthographic",
|
||||
"perspective"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "editing",
|
||||
"label": "Редактирование",
|
||||
"referenceSources": ["launcher", "seo"],
|
||||
"names": ["save", "edit", "trash", "copy", "upload", "download", "external"]
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"seo"
|
||||
],
|
||||
"names": [
|
||||
"save",
|
||||
"edit",
|
||||
"trash",
|
||||
"copy",
|
||||
"upload",
|
||||
"download",
|
||||
"external",
|
||||
"rotate-clockwise",
|
||||
"select",
|
||||
"pen",
|
||||
"rectangle",
|
||||
"curve",
|
||||
"undo",
|
||||
"redo",
|
||||
"add-point"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "state-access",
|
||||
"label": "Состояние и доступ",
|
||||
"referenceSources": ["launcher", "seo", "task-manager"],
|
||||
"names": ["check", "alert", "info", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"]
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"seo",
|
||||
"task-manager"
|
||||
],
|
||||
"names": [
|
||||
"check",
|
||||
"alert",
|
||||
"info",
|
||||
"activity",
|
||||
"lock",
|
||||
"key",
|
||||
"shield",
|
||||
"circle",
|
||||
"eye",
|
||||
"eye-off"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "entities",
|
||||
"label": "Сущности",
|
||||
"referenceSources": ["launcher", "task-manager"],
|
||||
"names": ["profile", "users", "building", "globe", "database", "network", "inbox", "mail"]
|
||||
"referenceSources": [
|
||||
"launcher",
|
||||
"task-manager"
|
||||
],
|
||||
"names": [
|
||||
"profile",
|
||||
"users",
|
||||
"building",
|
||||
"globe",
|
||||
"database",
|
||||
"network",
|
||||
"inbox",
|
||||
"mail"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "content",
|
||||
"label": "Контент",
|
||||
"referenceSources": ["seo", "bim-viewer", "engine"],
|
||||
"names": ["camera", "plan", "play", "stop", "image", "video", "file", "folder", "clipboard", "settings", "terminal"]
|
||||
"referenceSources": [
|
||||
"seo",
|
||||
"bim-viewer",
|
||||
"engine"
|
||||
],
|
||||
"names": [
|
||||
"camera",
|
||||
"plan",
|
||||
"play",
|
||||
"stop",
|
||||
"image",
|
||||
"video",
|
||||
"file",
|
||||
"folder",
|
||||
"clipboard",
|
||||
"settings",
|
||||
"terminal"
|
||||
]
|
||||
}
|
||||
],
|
||||
"rules": [
|
||||
|
||||
@@ -92,13 +92,15 @@
|
||||
"additionalProperties": false,
|
||||
"required": ["placement", "background", "border", "outline", "minSize", "maxSize", "lensCount", "autoHide"],
|
||||
"properties": {
|
||||
"placement": { "enum": ["left", "right", "bottom"] },
|
||||
"placement": { "enum": ["left", "right", "top", "bottom"] },
|
||||
"background": { "$ref": "#/$defs/hex" },
|
||||
"border": { "$ref": "#/$defs/hex" },
|
||||
"outline": { "$ref": "#/$defs/hex" },
|
||||
"minSize": { "type": "number", "minimum": 16, "maximum": 64 },
|
||||
"maxSize": { "type": "number", "minimum": 32, "maximum": 160 },
|
||||
"lensCount": { "type": "integer", "minimum": 1, "maximum": 12 },
|
||||
"lensCount": { "type": "integer", "minimum": 1, "maximum": 13 },
|
||||
"hideDelay": { "type": "number", "minimum": 0, "maximum": 15000 },
|
||||
"gap": { "type": "number", "minimum": 0, "maximum": 24 },
|
||||
"autoHide": { "type": "boolean" }
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { SegmentedControl, SegmentedGroup, SegmentedButton, ProgressButton, LayerStackIndicator } from '../packages/ui-react/dist/index.js';
|
||||
|
||||
test('multiple segments allow all/none and never drop another active layer', () => {
|
||||
let value = ['gaussian'];
|
||||
const items = [{value:'gaussian',label:'Gaussian'},{value:'collision',label:'Коллизии'}];
|
||||
const render = () => SegmentedControl({selectionMode:'multiple',value,items,label:'Слои',onChange:next=>{value=next;}});
|
||||
render().props.children[1].props.onClick();
|
||||
assert.deepEqual(value,['gaussian','collision']);
|
||||
render().props.children[0].props.onClick();
|
||||
assert.deepEqual(value,['collision']);
|
||||
render().props.children[1].props.onClick();
|
||||
assert.deepEqual(value,[]);
|
||||
const html=renderToStaticMarkup(render());
|
||||
assert.match(html,/role="group"/);
|
||||
assert.doesNotMatch(html,/role="tab|aria-selected/);
|
||||
assert.equal((html.match(/aria-pressed="false"/g)||[]).length,2);
|
||||
});
|
||||
|
||||
test('single segment consumers retain one selected tab and scalar changes', () => {
|
||||
let value='3d';
|
||||
const element=SegmentedControl({value,items:[{value:'3d',label:'3D'},{value:'top',label:'Top'}],label:'View',onChange:next=>{value=next;}});
|
||||
assert.match(renderToStaticMarkup(element),/role="tablist"/);
|
||||
element.props.children[1].props.onClick();
|
||||
assert.equal(value,'top');
|
||||
});
|
||||
|
||||
test('pending progress preserves action name, rejects reentry and exposes a separate measured progressbar', () => {
|
||||
const html=renderToStaticMarkup(createElement(ProgressButton,{label:'Проанализировать',icon:createElement(LayerStackIndicator),progress:{label:'Анализ поверхности · 29 / 96',value:29/96}}));
|
||||
assert.match(html,/<button[^>]*aria-label="Проанализировать"[^>]*disabled=""/);
|
||||
assert.match(html,/aria-busy="true"/);
|
||||
assert.match(html,/aria-valuenow="30"/);
|
||||
assert.match(html,/<\/button>[\s\S]*role="progressbar"/);
|
||||
assert.match(html,/Анализ поверхности/);
|
||||
const unknown=renderToStaticMarkup(createElement(ProgressButton,{label:'Анализ',progress:{label:'Подготовка'}}));
|
||||
assert.doesNotMatch(unknown,/aria-valuenow/);
|
||||
const idle=renderToStaticMarkup(createElement(ProgressButton,{label:'Анализ'}));
|
||||
assert.doesNotMatch(idle,/disabled=""|role="progressbar"/);
|
||||
});
|
||||
|
||||
|
||||
test('mixed capsule keeps toggle and menu semantics distinct', () => {
|
||||
const html=renderToStaticMarkup(createElement(SegmentedGroup,{label:'Layers'},
|
||||
createElement(SegmentedButton,{active:true,'aria-pressed':true},'Gaussian'),
|
||||
createElement(SegmentedButton,{'aria-expanded':false,'aria-haspopup':'dialog'},'Memory')));
|
||||
assert.match(html,/role="group" aria-label="Layers"/);
|
||||
assert.match(html,/aria-pressed="true"[^>]*data-active="true"/);
|
||||
assert.match(html,/aria-expanded="false" aria-haspopup="dialog"/);
|
||||
assert.equal((html.match(/aria-pressed/g)||[]).length,1);
|
||||
assert.doesNotMatch(html,/role="tab/);
|
||||
});
|
||||
@@ -35,3 +35,15 @@ test("dense viewer controls remain a public Button and SegmentedControl contract
|
||||
assert.match(docs, /size="dense"/);
|
||||
assert.match(docs, /viewer/);
|
||||
});
|
||||
|
||||
test("viewport controls share one scale without scaling nested controls twice", async () => {
|
||||
const [tokens,styles,registrySource] = await Promise.all([
|
||||
readFile(new URL("../packages/tokens/tokens.css",import.meta.url),"utf8"),
|
||||
readFile(new URL("../packages/ui-core/styles.css",import.meta.url),"utf8"),
|
||||
readFile(new URL("../registry/components.json",import.meta.url),"utf8"),
|
||||
]);
|
||||
assert.match(tokens,/--nodedc-viewport-control-scale: 0\.7/);
|
||||
assert.match(styles,/zoom: var\(--nodedc-viewport-control-scale\)/);
|
||||
assert.match(styles, /\.nodedc-segmented\) :is\([^}]+zoom: 1;/);
|
||||
assert.ok(JSON.parse(registrySource).components.find(c=>c.id==='button').domContract.includes('nodedc-viewport-controls'));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {preferDockSizes,dockMinimum,constrainDockTree,balancedDockTree,decodeDockTree,dockIds,dockPosition,dockRects,moveDockPanel,pruneDockTree,reconcileDockTree,resizeDockSplit} from '../packages/ui-core/dist/dockTree.js';
|
||||
const bounds={left:0,top:0,width:1200,height:800};
|
||||
const initial=balancedDockTree(['a','b','c']);
|
||||
const rects=tree=>dockRects(tree,bounds);
|
||||
|
||||
test('three asymmetric panes: center exchanges contents without changing slots',()=>{
|
||||
const before=rects(initial),next=rects(moveDockPanel(initial,{activeId:'c',overId:'a',position:'center'}));
|
||||
assert.deepEqual(next.c,before.a);assert.deepEqual(next.a,before.c);assert.deepEqual(next.b,before.b);
|
||||
});
|
||||
test('left to top/bottom edge of right pane gives one left and two right',()=>{
|
||||
for(const position of ['top','bottom']){
|
||||
const next=moveDockPanel(initial,{activeId:'a',overId:'c',position}),r=rects(next);
|
||||
assert.deepEqual(r.b,{left:0,top:0,width:600,height:800});
|
||||
assert.deepEqual(r.a,{left:600,top:position==='top'?0:400,width:600,height:400});
|
||||
assert.deepEqual(r.c,{left:600,top:position==='top'?400:0,width:600,height:400});
|
||||
}
|
||||
});
|
||||
test('right window moves to any edge of a left pane; left/right create a middle column',()=>{
|
||||
for(const position of ['left','right','top','bottom']){
|
||||
const next=moveDockPanel(initial,{activeId:'c',overId:'a',position}),r=rects(next);
|
||||
assert.deepEqual(r.b,{left:0,top:400,width:1200,height:400});
|
||||
assert.equal(position==='left'?r.c.left<r.a.left:position==='right'?r.c.left>r.a.left:position==='top'?r.c.top<r.a.top:r.c.top>r.a.top,true);
|
||||
}
|
||||
});
|
||||
test('every source/destination/edge for 2..12 panes retains each identity and tiles the whole area',()=>{
|
||||
for(let n=2;n<=12;n++){
|
||||
const ids=Array.from({length:n},(_,i)=>String(i));let tree=balancedDockTree(ids);
|
||||
for(const activeId of ids)for(const overId of ids)for(const position of ['center','left','right','top','bottom']){
|
||||
tree=moveDockPanel(tree,{activeId,overId,position});
|
||||
assert.deepEqual([...dockIds(tree)].sort(),[...ids].sort());
|
||||
const panels=Object.values(rects(tree));
|
||||
assert.ok(Math.abs(panels.reduce((total,r)=>total+r.width*r.height,0)-bounds.width*bounds.height)<1e-6);
|
||||
for(let i=0;i<panels.length;i++)for(let j=i+1;j<panels.length;j++){
|
||||
const a=panels[i],b=panels[j],overlapX=Math.min(a.left+a.width,b.left+b.width)-Math.max(a.left,b.left),overlapY=Math.min(a.top+a.height,b.top+b.height)-Math.max(a.top,b.top);
|
||||
assert.ok(overlapX<1e-8||overlapY<1e-8);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
test('pointer position alone selects edge; leaving workspace or source cancels',()=>{
|
||||
const r={left:400,top:100,width:800,height:600};
|
||||
assert.equal(dockPosition(r,405,400),'left');assert.equal(dockPosition(r,1195,400),'right');
|
||||
assert.equal(dockPosition(r,800,105),'top');assert.equal(dockPosition(r,800,695),'bottom');
|
||||
assert.equal(dockPosition(r,800,400),'center');assert.equal(dockPosition(r,399,400),null);
|
||||
assert.equal(moveDockPanel(initial,{activeId:'a',overId:'a',position:'left'}),initial);
|
||||
assert.equal(moveDockPanel(initial,{activeId:'missing',overId:'c',position:'center'}),initial);
|
||||
});
|
||||
test('resize, focus, persistence and new/missing sources preserve identity',()=>{
|
||||
const changed=resizeDockSplit(initial,'0',63);
|
||||
assert.equal(changed.first.ratio,63);assert.equal(initial.first.ratio,50);
|
||||
assert.deepEqual(decodeDockTree(JSON.parse(JSON.stringify(changed))),changed);
|
||||
assert.deepEqual(pruneDockTree(changed,['c']),{id:'c'});
|
||||
const restored=reconcileDockTree(pruneDockTree(changed,['a','c']),['a','b','c','d']);
|
||||
assert.deepEqual(dockIds(restored).sort(),['a','b','c','d']);
|
||||
assert.deepEqual(decodeDockTree({axis:'x',ratio:50,first:{id:'a'},second:{id:'a'}}),{id:'a'});
|
||||
assert.equal(decodeDockTree({axis:'x',ratio:Infinity}),null);
|
||||
});
|
||||
|
||||
test('recursive minimums protect all columns and rows after extreme resize',()=>{
|
||||
const t={axis:'x',ratio:99,first:{id:'scene'},second:{axis:'y',ratio:1,first:{id:'telemetry'},second:{id:'camera'}}};
|
||||
for(let n=1;n<=8;n++){
|
||||
const sizes={telemetry:{width:144+88*n,height:280}},minimum=dockMinimum(t,sizes);
|
||||
for(const requested of [{width:1200,height:800},{width:100,height:100}]){
|
||||
const b={left:0,top:0,width:Math.max(requested.width,minimum.width),height:Math.max(requested.height,minimum.height)};
|
||||
const c=constrainDockTree(t,b,sizes),r=dockRects(c,b);
|
||||
assert.ok(r.telemetry.width+1e-8>=sizes.telemetry.width);assert.ok(r.telemetry.height+1e-8>=280);
|
||||
assert.ok(r.scene.width+1e-8>=160);assert.ok(r.camera.height+1e-8>=120);
|
||||
assert.deepEqual(constrainDockTree(c,b,sizes),c);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('new compact panel uses its preferred size without changing saved ratios',()=>{
|
||||
const t={axis:'x',ratio:65,first:{id:'map'},second:{axis:'y',ratio:40,first:{id:'telemetry'},second:{id:'camera'}}};
|
||||
const sizes={telemetry:{width:320,height:280}};
|
||||
const initial=constrainDockTree(preferDockSizes(t,bounds,sizes),bounds,sizes),r=rects(initial);
|
||||
assert.ok(Math.abs(r.telemetry.width-320)<1e-8);assert.ok(Math.abs(r.telemetry.height-280)<1e-8);
|
||||
assert.deepEqual(preferDockSizes(t,bounds,{}),t);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {cubeRegions} from '../packages/ui-react/dist/NavigationCube.js';
|
||||
test('cube exposes exactly 26 unique face/edge/corner directions over all sides',()=>{
|
||||
const views=[[0,0,0,1],[0,1,0,0],[0,Math.SQRT1_2,0,Math.SQRT1_2],[0,-Math.SQRT1_2,0,Math.SQRT1_2],[Math.SQRT1_2,0,0,Math.SQRT1_2],[-Math.SQRT1_2,0,0,Math.SQRT1_2]];
|
||||
const dirs=new Set(views.flatMap(q=>cubeRegions(q).map(r=>r.direction.join(','))));
|
||||
assert.equal(dirs.size,26);assert.ok(!dirs.has('0,0,0'));
|
||||
assert.deepEqual(cubeRegions([0,0,0,1]).filter(r=>r.faceLabel).map(r=>r.faceLabel),['FRONT']);
|
||||
assert.deepEqual(cubeRegions([Math.SQRT1_2,0,0,Math.SQRT1_2]).filter(r=>r.faceLabel).map(r=>r.faceLabel),['BOTTOM']);
|
||||
for(const q of views)for(const r of cubeRegions(q)){assert.ok(!r.polygon.includes('NaN'));assert.ok(r.label);}
|
||||
});
|
||||
|
||||
test('labels are projected in each face plane with no mirrored front-facing text',()=>{
|
||||
const q=[.28,-.36,.12,.88],regions=cubeRegions(q).filter(r=>r.faceLabel);
|
||||
assert.equal(regions.length,3);
|
||||
for(const r of regions){
|
||||
const [a,b,c,d,e,f]=r.textMatrix;assert.ok(a*d-b*c>0);assert.ok(a*d-b*c<1);
|
||||
assert.ok(r.textMatrix.every(Number.isFinite));assert.ok(Math.abs(b)+Math.abs(c)>0.05);
|
||||
const points=r.polygon.split(' ').map(p=>p.split(',').map(Number));
|
||||
assert.ok(Math.abs(points.reduce((n,p)=>n+p[0],0)/4-e)<1e-9);
|
||||
assert.ok(Math.abs(points.reduce((n,p)=>n+p[1],0)/4-f)<1e-9);
|
||||
}
|
||||
assert.deepEqual(cubeRegions([0,0,0,1]).find(r=>r.faceLabel).textMatrix.map(n=>n||0),[1,0,0,1,60,60]);
|
||||
});
|
||||
@@ -23,47 +23,33 @@ test("RangeControl keeps native drag semantics and exposes one persistent exact-
|
||||
assert.doesNotMatch(markup, /nodedc-range__value-hit/);
|
||||
});
|
||||
|
||||
test("vertical scale keeps endpoints outside and the label/value centered at every fill level", () => {
|
||||
test("vertical scale exposes retained bounds without center text and follows every value", () => {
|
||||
for (const [value, progress] of [[-1.2, 0], [25.15, 50], [51.5, 100]]) {
|
||||
const markup = renderToStaticMarkup(createElement(RangeControl, {
|
||||
label: "Срез", orientation: "vertical", value, min: -1.2, max: 51.5, step: "any",
|
||||
formatValue: (n) => `${n.toFixed(1).replace('.', ',')} м`,
|
||||
formatLimit: (n) => n.toFixed(1).replace('.', ','), onChange: () => {},
|
||||
}));
|
||||
const renderedProgress = Number(markup.match(/--nodedc-range-progress:([\d.]+)%/)?.[1]);
|
||||
assert.ok(Math.abs(renderedProgress - progress) < 1e-9);
|
||||
assert.match(markup, /aria-label="Срез" aria-orientation="vertical"/);
|
||||
assert.match(markup, /min="-1.2" max="51.5" step="any"/);
|
||||
assert.equal((markup.match(/nodedc-range-scale__limit--max">51,5<\/span>/g) ?? []).length, 1);
|
||||
assert.equal((markup.match(/nodedc-range-scale__limit--min">-1,2<\/span>/g) ?? []).length, 1);
|
||||
assert.match(markup, /<\/span><\/span><\/div><span class="nodedc-range-scale__limit/);
|
||||
assert.equal((markup.match(/nodedc-range__label">Срез · /g) ?? []).length, 2);
|
||||
assert.match(markup, /nodedc-range__fill-text" aria-hidden="true"/);
|
||||
assert.doesNotMatch(markup, /nodedc-range__value|nodedc-range__editor|formatLimit=/);
|
||||
for (const limitSide of ["left", "right"]) {
|
||||
const markup = renderToStaticMarkup(createElement(RangeControl, {
|
||||
label: "Срез", orientation: "vertical", limitSide, value, min: -1.2, max: 51.5, step: "any",
|
||||
formatValue: n => `${n.toFixed(1)} м`, formatLimit: n => n.toFixed(1), onChange: () => {},
|
||||
}));
|
||||
const renderedProgress = Number(markup.match(/--nodedc-range-progress:([\d.]+)%/)?.[1]);
|
||||
assert.ok(Math.abs(renderedProgress - progress) < 1e-9);
|
||||
assert.ok(markup.includes(`data-limit-side="${limitSide}"`));
|
||||
assert.ok(markup.includes(`nodedc-range-scale__limit--max">${value.toFixed(1)}</span>`));
|
||||
assert.match(markup, /nodedc-range-scale__limit--min">-1.2<\/span>/);
|
||||
assert.match(markup, /aria-label="Срез" aria-orientation="vertical"/);
|
||||
assert.ok(markup.includes(`aria-valuetext="${value.toFixed(1)} м"`));
|
||||
assert.match(markup, /min="-1.2" max="51.5" step="any"/);
|
||||
assert.doesNotMatch(markup, /nodedc-range__label|nodedc-range__fill-text|nodedc-range__editor|formatLimit=/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("vertical scale mirrors only endpoint labels for the opposite scene edge", () => {
|
||||
const markup = renderToStaticMarkup(createElement(RangeControl, {
|
||||
label: "Срез", orientation: "vertical", limitSide: "left", value: 25.15, min: -1.2, max: 51.5,
|
||||
step: "any", formatLimit: (n) => n.toFixed(1).replace('.', ','), onChange: () => {},
|
||||
}));
|
||||
assert.match(markup, /class="nodedc-range-scale" data-limit-side="left"/);
|
||||
assert.match(markup, /nodedc-range-scale__limit--max">51,5<\/span>/);
|
||||
assert.match(markup, /nodedc-range-scale__limit--min">-1,2<\/span>/);
|
||||
});
|
||||
|
||||
test("vertical contrast clips both glyph layers and visible focus has no perimeter", async () => {
|
||||
test("thin vertical rail retains a usable pointer target and boundary focus", async () => {
|
||||
const styles = await readFile(new URL("../packages/ui-core/styles.css", import.meta.url), "utf8");
|
||||
assert.match(styles, /\.nodedc-range\[data-orientation="vertical"\] \.nodedc-range__fill-text \{ clip-path: inset\(calc\(100% - var\(--nodedc-range-progress\)\) 0 0 round var\(--nodedc-radius-circle\)\)/);
|
||||
assert.match(styles, /\.nodedc-range-scale \{[^}]*width: calc\(var\(--nodedc-control-height\) \* 0\.4\)/);
|
||||
assert.match(styles, /\.nodedc-range-scale__limit \{[^}]*left: calc\(100% \+ 0\.4rem\);[^}]*color: var\(--nodedc-text-primary\);[^}]*font-size: calc\(var\(--nodedc-font-size-xs\) \* 0\.9\)/);
|
||||
assert.match(styles, /\.nodedc-range-scale\[data-limit-side="left"\] \.nodedc-range-scale__limit \{[^}]*right: calc\(100% \+ 0\.4rem\);[^}]*left: auto;[^}]*text-align: right/);
|
||||
assert.match(styles, /\.nodedc-range\[data-orientation="vertical"\] \.nodedc-range__label \{[^}]*font-size: calc\(var\(--nodedc-font-size-sm\) \* 0\.9\)/);
|
||||
assert.match(styles, /\.nodedc-range\[data-orientation="vertical"\] \{[^}]*border: 0; outline: 0; box-shadow: none;/);
|
||||
assert.match(styles, /\.nodedc-range\[data-orientation="vertical"\]:has\(input:focus-visible\) \.nodedc-range__label \{ text-decoration: underline; text-decoration-thickness: 2px;/);
|
||||
assert.doesNotMatch(styles, /\.nodedc-range\[data-orientation="vertical"\]:has\(input:focus-visible\) \{/);
|
||||
assert.doesNotMatch(styles, /\.nodedc-range\[data-orientation="vertical"\]:focus-within/);
|
||||
assert.match(styles, /width: calc\(var\(--nodedc-control-height\) \* 0\.2\)/);
|
||||
assert.match(styles, /width: max\(100%, 24px\)/);
|
||||
assert.match(styles, /limit--max \{ bottom: clamp\(/);
|
||||
assert.match(styles, /range-scale:has\(input:focus-visible\) \.nodedc-range-scale__limit--max \{ text-decoration: underline/);
|
||||
assert.match(styles, /data-orientation="vertical"\] \{[^}]*border: 0; outline: 0; box-shadow: none;/);
|
||||
});
|
||||
|
||||
test("exact editing is a stable native caret field without remount, forced selection or a dark editor box", async () => {
|
||||
@@ -102,3 +88,32 @@ test("exact editing is a stable native caret field without remount, forced selec
|
||||
assert.match(windowComponent, /onCloseRef\.current\(\)/);
|
||||
assert.doesNotMatch(windowComponent, /\[closeOnEscape, onClose, open, shouldLockBodyScroll, shouldTrapFocus\]/);
|
||||
});
|
||||
|
||||
test("vertical band exposes two independent accessible boundaries", () => {
|
||||
for (const value of [[-52, 500], [10, 35], [20, 20]]) {
|
||||
const markup = renderToStaticMarkup(createElement(RangeControl, {
|
||||
label: "Срез", orientation: "vertical", value, min: -52, max: 500, step: "any",
|
||||
formatValue: n => `${n} м`, onChange: () => {},
|
||||
}));
|
||||
assert.equal((markup.match(/type="range"/g) ?? []).length, 2);
|
||||
assert.match(markup, /aria-label="Срез: нижняя граница"/);
|
||||
assert.match(markup, /aria-label="Срез: верхняя граница"/);
|
||||
assert.ok(markup.includes(`aria-valuemax="${value[1]}"`));
|
||||
assert.ok(markup.includes(`aria-valuemin="${value[0]}"`));
|
||||
assert.doesNotMatch(markup, /nodedc-range__label|nodedc-range__editor/);
|
||||
}
|
||||
});
|
||||
|
||||
test("both boundaries move, clamp independently, separate after coincidence and restore endpoints", async () => {
|
||||
const {moveRangeBoundary: move, nearestRangeBoundary: nearest} = await import("../packages/ui-react/dist/rangeBand.js");
|
||||
let band = [-52, 500];
|
||||
assert.equal(nearest(band, -40), 0); assert.equal(nearest(band, 450), 1);
|
||||
band = move(band, 0, 10, -52, 500, "any"); assert.deepEqual(band, [10, 500]);
|
||||
band = move(band, 1, 30, -52, 500, "any"); assert.deepEqual(band, [10, 30]);
|
||||
band = move(band, 0, 50, -52, 500, "any"); assert.deepEqual(band, [30, 30]);
|
||||
assert.equal(nearest(band, 20), 0); assert.equal(nearest(band, 40), 1);
|
||||
band = move(band, 0, -100, -52, 500, "any");
|
||||
band = move(band, 1, 600, -52, 500, "any"); assert.deepEqual(band, [-52, 500]);
|
||||
assert.deepEqual(move([0, 10], 1, 7.3, 0, 10, .5), [0, 7.5]);
|
||||
assert.deepEqual(move([0, 9], 1, 10.1, 0, 10.1, 3), [0, 10.1]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {createElement as h} from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {LoadingRegion,Description,SettingsCard,ComparisonTable} from '../packages/ui-react/dist/index.js';
|
||||
test('composed loading draws exactly one owner even with multiple pending descendants',()=>{
|
||||
const child=h(LoadingRegion,{loading:true,label:'child'},h('span',null,'retained'));
|
||||
const markup=renderToStaticMarkup(h(LoadingRegion,{aggregate:true,loading:true,label:'equipment'},child,child,h(LoadingRegion,{aggregate:true,loading:true,label:'nested'},child)));
|
||||
assert.equal((markup.match(/role="status"/g)||[]).length,1);assert.match(markup,/aria-label="equipment"/);assert.equal((markup.match(/retained/g)||[]).length,3);
|
||||
});
|
||||
test('independent surfaces keep their loaders and resolved content has no indicator',()=>{
|
||||
const markup=renderToStaticMarkup(h('div',null,h(LoadingRegion,{loading:true,label:'a'}),h(LoadingRegion,{loading:true,label:'b'})));
|
||||
assert.equal((markup.match(/role="status"/g)||[]).length,2);
|
||||
assert.doesNotMatch(renderToStaticMarkup(h(LoadingRegion,{aggregate:true,loading:false,label:'done'},h(LoadingRegion,{loading:false,label:'child'},'ready'))),/role="status"/);
|
||||
});
|
||||
test('comparison has one label column, arbitrary entity columns and semantic headers',()=>{
|
||||
for(const count of [1,2,3,4,8]){
|
||||
const markup=renderToStaticMarkup(h(ComparisonTable,{label:'VESC',heading:'VESC',columns:Array.from({length:count},(_,i)=>({id:String(i),label:'id'+i})),rows:[{id:'position',label:'Расположение',cells:Array(count).fill('Левый')},{id:'current',label:'Ток',cells:[]}]}));
|
||||
assert.equal((markup.match(/scope="col"/g)||[]).length,count+1);assert.equal((markup.match(/scope="row"/g)||[]).length,2);assert.equal((markup.match(/<td>/g)||[]).length,2*count);assert.match(markup,/tabindex="0"/);
|
||||
}
|
||||
});
|
||||
test('SettingsCard and standalone explanatory paragraphs use one typography component',()=>{
|
||||
assert.match(renderToStaticMarkup(h(Description,null,'help')),/class="nodedc-description"/);
|
||||
assert.match(renderToStaticMarkup(h(SettingsCard,{title:'Settings',description:'help'})),/<p class="nodedc-description">help/);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {test} from "node:test";
|
||||
import {computeFloatingPosition,movingToMenu} from "../packages/ui-core/dist/index.js";
|
||||
test("menus stay beyond the maximum magnified edge, including narrow windows",()=>{
|
||||
for(const width of [320,640,1400])for(const size of [25,42,88]){
|
||||
const anchor={left:width-12-size,right:width-12,top:200,bottom:225,width:size,height:25};
|
||||
const p=computeFloatingPosition({anchor,surfaceWidth:220,surfaceHeight:400,placement:"left-start",flip:false,viewportWidth:width,viewportHeight:600});
|
||||
assert.ok(p.left+Math.min(220,p.maxWidth)<=anchor.left-8+1e-9);
|
||||
assert.ok(p.left>=8);assert.ok(p.top+Math.min(400,p.maxHeight)<=592);
|
||||
const mirror={...anchor,left:12,right:12+size};
|
||||
const q=computeFloatingPosition({anchor:mirror,surfaceWidth:220,surfaceHeight:400,placement:"right-start",flip:false,viewportWidth:width,viewportHeight:600});
|
||||
assert.ok(q.left>=mirror.right+8);assert.ok(q.left+Math.min(220,q.maxWidth)<=width-8);
|
||||
}
|
||||
});
|
||||
test("intent triangle protects diagonal entry but never blocks deliberate vertical or reverse motion",()=>{
|
||||
const s={left:200,right:450,top:100,bottom:500,width:250,height:400},o={x:490,y:200};
|
||||
assert.equal(movingToMenu(o,o,{x:480,y:210},s),true);
|
||||
assert.equal(movingToMenu(o,o,{x:490,y:240},s),false);
|
||||
assert.equal(movingToMenu(o,{x:480,y:210},{x:485,y:220},s),false);
|
||||
assert.equal(movingToMenu(o,o,{x:480,y:600},s),false);
|
||||
assert.equal(movingToMenu({x:150,y:200},{x:150,y:200},{x:160,y:210},s),true);
|
||||
assert.equal(movingToMenu({x:300,y:550},{x:300,y:550},{x:310,y:540},s),true);
|
||||
});
|
||||
@@ -1121,7 +1121,7 @@ function validateDesignProfileLayout(value) {
|
||||
if (media.logoSource !== "file" && media.logoSource !== "url") throw applicationError("invalid_design_profile_logo_source");
|
||||
if (!isObject(media.faviconAssets)) throw applicationError("invalid_design_profile_favicon_assets");
|
||||
if (glass.version !== 4) throw applicationError("unsupported_glass_material_version");
|
||||
if (!["left", "right", "bottom"].includes(toolbar.placement)) throw applicationError("invalid_toolbar_placement");
|
||||
if (!["left", "right", "top", "bottom"].includes(toolbar.placement)) throw applicationError("invalid_toolbar_placement");
|
||||
return {
|
||||
theme: value.theme,
|
||||
accentHex: requireHex(value.accentHex, "invalid_design_profile_accent"),
|
||||
@@ -1176,8 +1176,10 @@ function validateDesignProfileLayout(value) {
|
||||
outline: requireHex(toolbar.outline, "invalid_toolbar_outline"),
|
||||
minSize: requireNumber(toolbar.minSize, 16, 64, "invalid_toolbar_min_size"),
|
||||
maxSize: requireNumber(toolbar.maxSize, 32, 160, "invalid_toolbar_max_size"),
|
||||
lensCount: requireInteger(toolbar.lensCount, 1, 12, "invalid_toolbar_lens_count"),
|
||||
lensCount: requireInteger(toolbar.lensCount, 1, 13, "invalid_toolbar_lens_count"),
|
||||
autoHide: requireBoolean(toolbar.autoHide, "invalid_toolbar_auto_hide"),
|
||||
hideDelay: requireNumber(toolbar.hideDelay ?? 5000,0,15000,"invalid_toolbar_hide_delay"),
|
||||
gap: requireNumber(toolbar.gap ?? 10,0,24,"invalid_toolbar_gap"),
|
||||
},
|
||||
pageTypes: validateDesignProfilePageTypes(value.pageTypes),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user