Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0648014f5 | ||
|
|
4390d1350d | ||
|
|
fea966a3f0 | ||
|
|
8b49296efa | ||
|
|
70d5d8b385 | ||
|
|
cb49932706 | ||
|
|
5f93defabf | ||
|
|
d7885fe098 | ||
|
|
d8ed37e09d | ||
|
|
9a00d0bb06 | ||
|
|
616ec9160a | ||
|
|
1cc360f99a | ||
|
|
31ed774529 | ||
|
|
6f2f9644fe | ||
|
|
91a5ebe8da | ||
|
|
ce1b707348 | ||
|
|
64908711a4 | ||
|
|
3d4c4aaa08 | ||
|
|
541fb2a2c3 | ||
|
|
1326ec6cc9 | ||
|
|
1ec17b3098 |
@@ -1,4 +1,5 @@
|
||||
import { OperationalTypographyDemo } from "./OperationalTypographyDemo";
|
||||
import { ModalSizeExample } from './ModalSizeExample';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { applyGlassMaterial, applyNodedcTheme, defaultGlassMaterial, type GlassMaterialSettings, type NodedcTheme, type RgbTuple } from "@nodedc/ui-core";
|
||||
import { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTemplateDefinition } from "@nodedc/page-patterns";
|
||||
@@ -229,12 +230,12 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
{
|
||||
title: "Редактирование",
|
||||
note: "Launcher / SEO",
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "orthographic", "perspective", "select", "pen", "rectangle", "curve", "undo", "redo"],
|
||||
icons: ["save", "edit", "trash", "copy", "upload", "download", "external", "rotate-clockwise", "add-point", "ruler", "section", "isolate", "orthographic", "perspective", "fit-view", "select", "pen", "rectangle", "curve", "undo", "redo"],
|
||||
},
|
||||
{
|
||||
title: "Состояние и доступ",
|
||||
note: "Вся платформа",
|
||||
icons: ["check", "alert", "info", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
|
||||
icons: ["check", "alert", "info", "info-plain", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
|
||||
},
|
||||
{
|
||||
title: "Сущности",
|
||||
@@ -249,6 +250,8 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
||||
];
|
||||
|
||||
const iconLabels: Record<IconName, string> = {
|
||||
pipette: "Пипетка",
|
||||
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
|
||||
power: "Питание",
|
||||
move: "Свободное окно",
|
||||
"add-point":"Добавить точку",orthographic:"Ортографическая проекция",perspective:"Перспективная проекция",select:"Выделение",pen:"Перо",rectangle:"Прямоугольник",curve:"Кривая",undo:"Отменить",redo:"Повторить",
|
||||
@@ -281,6 +284,8 @@ const iconLabels: Record<IconName, string> = {
|
||||
image: "Изображение",
|
||||
inbox: "Уведомления",
|
||||
info: "Информация",
|
||||
"info-plain": "Информация без окружности",
|
||||
"fit-view": "Вписать модель",
|
||||
key: "Ключ",
|
||||
layers: "Слои",
|
||||
list: "Список задач",
|
||||
@@ -402,6 +407,7 @@ export function CatalogApp() {
|
||||
const [treeDemoRect,setTreeDemoRect]=useState({left:32,top:96,width:380,height:480});
|
||||
const [treeSelected,setTreeSelected]=useState<string|null>('cells');
|
||||
const [treeVisible,setTreeVisible]=useState(true);
|
||||
const [treeSelectedIds,setTreeSelectedIds]=useState<string[]>(['cells']);
|
||||
const [inspectorOpen, setInspectorOpen] = useState(false);
|
||||
const workspaceWindowDemoRef = useRef<HTMLDivElement>(null);
|
||||
const [sceneDemoHeight, setSceneDemoHeight] = useState(480);
|
||||
@@ -1350,6 +1356,7 @@ export function CatalogApp() {
|
||||
<>
|
||||
<ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow>
|
||||
<RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} />
|
||||
<RangeControl variant="rail" label="Тонкая горизонтальная шкала" value={brightness} min={0} max={100} formatValue={v=>`${v}%`} onChange={setBrightness}/>
|
||||
<div style={{ height: 180 }} title="Тонкая шкала: две границы двигаются независимо; без центрального текста"><RangeControl orientation="vertical" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
|
||||
<div style={{ height: 180, display: 'flex', justifyContent: 'flex-end' }} title="Шкала справа: границы слева; фокус подчёркивает выбранную границу"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
|
||||
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} exactValueBounds={{ min: 0 }} formatValue={(value) => `${value}%`} onChange={setGlowDistance} />
|
||||
@@ -1399,7 +1406,7 @@ export function CatalogApp() {
|
||||
return (
|
||||
<div className="catalog-grid">
|
||||
<Preview title="Mission Core" note="canonical foundation / nested fields / portal" className="catalog-preview--wide"><MissionThemeExample/></Preview>
|
||||
<Preview title="Navigation cube" note="faces / edges / corners"><NavigationCube 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="Navigation cube" note="faces / edges / corners"><NavigationCube faceOpacity={.65} edgeOpacity={cubeEdgeOpacity} size={cubeSize} quaternion={[.28,-.36,.12,.88]} onSelect={setCubeDirection}/><RangeControl label="Размер 3D-куба" value={cubeSize} min={48} max={160} step={1} onChange={setCubeSize} formatValue={v=>`${v} px`}/><RangeControl label="Прозрачность линий куба" value={1-cubeEdgeOpacity} min={0} max={1} step={.05} onChange={v=>setCubeEdgeOpacity(1-v)} formatValue={v=>`${Math.round(v*100)}%`}/><p>{cubeDirection.join(" · ")}</p></Preview>
|
||||
<Preview title="Selection" note="integrated / split / inline">
|
||||
<div className="catalog-form">
|
||||
<FieldFrame label="Hub / integrated select" labelPlacement="below">
|
||||
@@ -1542,6 +1549,7 @@ export function CatalogApp() {
|
||||
<SettingsCard align="center" role="status" title="Настройки применены" description="Проверьте подключение устройства." />
|
||||
</Preview>
|
||||
<Preview title="Операционная типографика" note="единый размер во всех состояниях"><OperationalTypographyDemo /></Preview>
|
||||
<Preview title="Размер DOM-окна" note="геометрия с сохранением в приложении"><ModalSizeExample /></Preview>
|
||||
<Preview title="Главная и окружение" note="единые компоненты · сохранение в памяти каталога">
|
||||
<EnvironmentCatalogDemo />
|
||||
</Preview>
|
||||
@@ -1609,7 +1617,7 @@ export function CatalogApp() {
|
||||
</div>
|
||||
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
|
||||
</Preview>
|
||||
<Preview title="Split pane" note="pointer / keyboard / controlled" className="catalog-preview--wide catalog-split-pane-preview">
|
||||
<Preview title="Split pane" note="pointer resize: invisible / keyboard focus: visible" className="catalog-preview--wide catalog-split-pane-preview">
|
||||
<Switch label="Скрыть линию разделителя" checked={splitPaneInvisible} onChange={setSplitPaneInvisible} />
|
||||
<div className="catalog-split-pane-demo">
|
||||
<SplitPane
|
||||
@@ -1740,6 +1748,11 @@ export function CatalogApp() {
|
||||
<ResizableViewport className="catalog-glass-stage" resizeIndicator={false} height={sceneDemoHeight} minHeight={360} maxHeight={900} onHeightChange={setSceneDemoHeight}>
|
||||
<video key={stageMediaSrc} autoPlay muted loop playsInline aria-hidden="true"><source src={stageMediaSrc} type="video/mp4" /></video>
|
||||
<div className="catalog-glass-stage__shade" />
|
||||
<div className="catalog-viewport-actions nodedc-viewport-controls">
|
||||
<IconButton label="Приблизить пример" onClick={()=>setSceneDemoHeight(value=>Math.min(900,value+40))}><Icon name="plus"/></IconButton>
|
||||
<IconButton label="Отдалить пример" onClick={()=>setSceneDemoHeight(value=>Math.max(360,value-40))}><Icon name="minus"/></IconButton>
|
||||
<IconButton label="Вернуть размер примера" onClick={()=>setSceneDemoHeight(480)}><Icon name="select"/></IconButton>
|
||||
</div>
|
||||
<GlassMaterialSurface context="scene" radius="panel" material={glassMaterial} radiusPx={24} className="catalog-glass-stage__sample">
|
||||
<span>CANONICAL GLASS</span>
|
||||
<h2>Прозрачная плашка над сценой</h2>
|
||||
@@ -2350,7 +2363,7 @@ export function CatalogApp() {
|
||||
maxSize={toolbarMaxSize}
|
||||
lensCount={toolbarLensCount}
|
||||
autoHide={toolbarAutoHide}
|
||||
hideDelay={toolbarHideDelay} gap={toolbarGap}
|
||||
hideDelay={toolbarHideDelay} gap={toolbarGap} menuWidth={320}
|
||||
items={[{id:"hold",label:toolbarAutoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!toolbarAutoHide,onSelect:()=>setToolbarAutoHide(v=>!v)}, ...(Object.entries(sectionDefinitions) as Array<[CatalogSection, (typeof sectionDefinitions)[CatalogSection]]>).map(([id, item]) => ({
|
||||
id,
|
||||
label: item.title,
|
||||
@@ -2363,7 +2376,7 @@ export function CatalogApp() {
|
||||
) : null}
|
||||
|
||||
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
|
||||
<Tree label="Пример дерева объектов" selected={treeSelected} onSelect={setTreeSelected} onVisibilityChange={(_,visible)=>setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/>
|
||||
<Tree defaultExpandedDepth={2} renderActions={node=><Dropdown width={320} trigger={({setTriggerRef,show,open})=><IconButton ref={setTriggerRef} label={`Информация: ${node.label}`} aria-expanded={open} onMouseEnter={show} onClick={show}><Icon name="info-plain" size={14}/></IconButton>}><Description>{node.label}</Description></Dropdown>} label="Пример дерева объектов: стрелка раскрывает, глазик меняет видимость без прокрутки" selected={treeSelected} selectedIds={treeSelectedIds} onSelect={(id,gesture)=>{setTreeSelected(id);setTreeSelectedIds(old=>gesture.shiftKey?gesture.rangeIds:gesture.metaKey?(old.includes(id)?old.filter(key=>key!==id):[...old,id]):gesture.ctrlKey?[...new Set([...old,id])]:[id]);}} onVisibilityChange={(_,visible)=>setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/>
|
||||
</Window>
|
||||
<Window
|
||||
open={inspectorOpen}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Window,Description,EditorDockLayout,EditorWorkspace,type EditorDockState} from '@nodedc/ui-react';
|
||||
import {Button,Window,Description,ColorField,ControlRow,Inspector,EditorDockLayout,EditorWorkspace,type EditorDockState} from '@nodedc/ui-react';
|
||||
export function EditorDockExample({inWindow=false}:{inWindow?:boolean}){
|
||||
const [modal,setModal]=useState(false);
|
||||
const [color,setColor]=useState('#292929');
|
||||
const [modal,setModal]=useState(false),[purpose,setPurpose]=useState<'edit'|'view'>('edit');
|
||||
const [editing,setEditing]=useState(false),[open,setOpen]=useState({objects:true,materials:true});
|
||||
const [layout,setLayout]=useState<EditorDockState>({tree:{axis:'y',ratio:70,first:{axis:'x',ratio:25,first:{id:'objects'},second:{id:'viewport'}},second:{id:'materials'}},floating:{}});
|
||||
return <>{!inWindow&&<><Button onClick={()=>setModal(true)}>Сцена в модальном окне</Button><Window open={modal} title="Просмотр сцены" onClose={()=>setModal(false)}><EditorDockExample inWindow/></Window></>}<Button onClick={()=>{setOpen({objects:true,materials:true});setEditing(true);}}>Открыть редактор сцены</Button><div style={{height:480}}>
|
||||
<EditorWorkspace editing={editing} title="Редактор сцены" subtitle="Общая оконная система" onBack={()=>setEditing(false)}>
|
||||
<EditorDockLayout value={layout} onChange={setLayout} enabled={editing} primary={<div style={{display:'grid',height:'100%',placeContent:'center'}}><Description>Закреплённая сцена</Description><Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button></div>}
|
||||
return <>{!inWindow&&<><Button onClick={()=>setModal(true)}>Сцена в модальном окне</Button><Window open={modal} title="Просмотр сцены" onClose={()=>setModal(false)}><EditorDockExample inWindow/></Window></>}<Button onClick={()=>{setPurpose('edit');setOpen({objects:true,materials:true});setEditing(true);}}>Открыть редактор сцены</Button><Button onClick={()=>{setPurpose('view');setEditing(true);}}>Отдельное окно просмотра</Button><div style={{height:480}}>
|
||||
<EditorWorkspace editing={editing} purpose={purpose} title={purpose==='view'?'Просмотр сцены':'Редактор сцены'} subtitle="Общая оконная система" onBack={()=>setEditing(false)} headerActions={purpose==='view'?<Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button>:undefined}>
|
||||
<EditorDockLayout value={layout} onChange={setLayout} enabled={editing} primary={<div style={{display:'grid',height:'100%',placeContent:'center'}}><Description>Закреплённая сцена · откреплённые инструменты используют scene Glass V4</Description><Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button></div>}
|
||||
tools={[{id:'objects',title:'Объекты',label:'Объекты',open:open.objects,onClose:()=>setOpen(v=>({...v,objects:false})),content:<Description>Сцена → Модель → Детали</Description>},
|
||||
{id:'materials',title:'Материалы',label:'Материалы',open:open.materials,onClose:()=>setOpen(v=>({...v,materials:false})),content:<Description>Перетащите шапку к краю, рядом с другим инструментом или в центр сцены.</Description>}]}/>
|
||||
{id:'materials',title:'Материалы',label:'Материалы',minimumSize:{width:380,height:280},footer:<Button width="full" onClick={()=>setColor('#292929')}>Сбросить настройки</Button>,open:open.materials,onClose:()=>setOpen(v=>({...v,materials:false})),content:<Inspector sections={[{id:"color",label:"Цвет без обводки и пипетка",content:<ControlRow label="Цвет"><ColorField label="Цвет материала" value={color} onChange={setColor}/></ControlRow>}]} defaultOpen={["color"]} header={<Description>Минимум 380 × 280. Пипетка берёт цвет с экрана после нажатия; Escape отменяет выбор. Нижняя кнопка не прокручивается.</Description>}/>}]}/>
|
||||
</EditorWorkspace>
|
||||
</div></>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { createModalController, createModalSizeController, renderPathBar } from '@nodedc/ui-dom';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import '@nodedc/ui-dom/styles.css';
|
||||
import { Button, Description, Icon } from '@nodedc/ui-react';
|
||||
|
||||
export function ModalSizeExample() {
|
||||
const overlay = useRef<HTMLDivElement>(null), dialog = useRef<HTMLDivElement>(null);
|
||||
const modal = useRef<ReturnType<typeof createModalController> | null>(null);
|
||||
const path = useRef<HTMLDivElement>(null);
|
||||
const saved = useRef({ width: 800, height: 500 });
|
||||
useEffect(() => {
|
||||
renderPathBar(path.current!, [{label:'Файлы',path:'',kind:'folder'},{label:'Изображения',path:'images',kind:'folder'},{label:'example.png',path:'images/example.png',kind:'file',current:true}], {onNavigate: () => {}, icon: kind => { const span=document.createElement('span'); span.innerHTML=renderToStaticMarkup(<Icon name={kind}/>); return span.firstElementChild!; }});
|
||||
const size = createModalSizeController({ dialog: dialog.current!, initialSize: saved.current, onSizeCommit: value => { saved.current = value; } });
|
||||
modal.current = createModalController({ overlay: overlay.current!, dialog: dialog.current!, onOpenChange: open => { if (open) size.refresh(); } });
|
||||
return () => { modal.current?.destroy(); size.destroy(); };
|
||||
}, []);
|
||||
return <><Button onClick={() => modal.current?.open()}>Окно с сохранением размера</Button>
|
||||
{createPortal(<div ref={overlay} hidden><div ref={dialog} className="nodedc-glass" aria-labelledby="modal-size-example-title">
|
||||
<header className="nodedc-window__head"><h2 id="modal-size-example-title" className="nodedc-window__title">Размер модального окна</h2></header>
|
||||
<div className="nodedc-window__body"><Description>Перетаскивание за края и углы. Для клавиатуры: фокус на шапке, Shift + стрелки. Повторное открытие сохраняет размер; уменьшение экрана не меняет предпочтение.</Description><div ref={path}/></div>
|
||||
<footer className="nodedc-window__footer"><Button onClick={() => modal.current?.close()}>Закрыть</Button></footer>
|
||||
</div></div>, document.body)}</>;
|
||||
}
|
||||
@@ -2305,3 +2305,5 @@ textarea {
|
||||
}
|
||||
}
|
||||
.catalog-theme-fields { display: grid; gap: var(--nodedc-space-4); }
|
||||
|
||||
.catalog-viewport-actions {position:absolute;top:var(--nodedc-space-3);right:var(--nodedc-space-3);display:flex;gap:var(--nodedc-space-2);padding:var(--nodedc-space-2);}
|
||||
|
||||
+15
-1
@@ -110,7 +110,7 @@ assets; the existing Git-to-canonical-runner deployment foundation is unchanged.
|
||||
CMS visual follow-up, 2026-11-05: flat theme edges, neutral white default accent,
|
||||
UserProfileMenu with a session avatar and inbox glyph, FeatureSettingsWindow,
|
||||
ColorField, pill-shaped split Select, and the canonical six-dot DragHandle.
|
||||
UI preferences belong to browser-local storage; site content and deployment
|
||||
UI preferences belong to authenticated per-user server metadata; site content and deployment
|
||||
credentials stay in the existing CMS model. Immutable npm snapshots retain
|
||||
package semver and are identified by source commit plus archive SHA-256.
|
||||
|
||||
@@ -146,3 +146,17 @@ content cards. Collection entries and native JSON disclosures adopt the shared
|
||||
GlassSurface group material. No local palette, field colors or business logic
|
||||
are introduced. The prior soft-canvas composition is superseded in THEMING and
|
||||
the living catalog; soft itself remains available for recessed non-form areas.
|
||||
|
||||
## CMS: размеры модальных окон
|
||||
|
||||
CMS подключает `createModalSizeController` из immutable ui-dom package, без копии resize-кода. Тонкий адаптер связывает `media-library` с серверным пользовательским GUI JSON; оформление и размеры записываются через аутентифицированный API. Медиатека остаётся привязанной к сайту, геометрия — к пользователю.
|
||||
|
||||
## CMS: строка пути файлов
|
||||
|
||||
CMS подключает `renderPathBar` и его stylesheet из ui-dom, source `1326ec6`,
|
||||
immutable archive `nodedc-ui-dom-0.7.0-modal.2.tgz`. Адаптер передаёт пути
|
||||
выбранного сайта, стандартный Icon и callback перехода в папку. Общий компонент
|
||||
владеет компактной строкой Finder, разделителями и нейтральными иконками.
|
||||
Сетка файлов, поиск и фильтрация по нескольким типам остаются доменной логикой
|
||||
CMS; переключатели используют общий IconButton. Проверены выбор глубокого
|
||||
пути, переход в каталог, dark/light и узкое окно 390 px.
|
||||
|
||||
+36
-2
@@ -58,6 +58,8 @@ FieldFrame объединяет label, control, hint и description. `labelPlace
|
||||
|
||||
## RangeControl
|
||||
|
||||
`RangeControl variant="rail"` — горизонтальный односторонний вариант тонкой шкалы среза: та же толщина `0.2 × --nodedc-control-height`, заполнение слева и текущее `formatValue` над шкалой. Общей подложки, стекла, рамки и тени нет; прозрачная область захвата не ниже 24 px. Native range сохраняет стрелки, Home/End, доступное имя и disabled; focus-visible подчёркивает значение. Точный ввод остаётся у обычного варианта `field`. Позиционирование в viewport и время показа задаёт приложение.
|
||||
|
||||
Вертикальная шкала занимает `0.2 × --nodedc-control-height` (9.2 px при 46 px), вдвое тоньше предыдущей. Прозрачная область захвата не уже 24 px.
|
||||
|
||||
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. `min/max` задают только рабочий диапазон перетаскивания; ручной ввод по умолчанию принимает любое конечное число и не меняет геометрию ползунка. Опциональный `exactValueBounds` независимо задаёт жёсткие границы ручного ввода: например, `{ min: 0 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком.
|
||||
@@ -78,9 +80,9 @@ Engine/BIM-геометрия color field: круглый swatch и HEX-знач
|
||||
|
||||
## Dropdown
|
||||
|
||||
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. It does not change the material. Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
|
||||
Every viewer toolbar uses `nodedc-viewport-controls`: scene, camera, map, replay and observation panes share 70% of standard control geometry (46 → 32.2 px), including icons, typography, padding and rims. The scope normalizes old `compact`/`dense` props and never multiplies scaling in nested groups. Apply it only to action groups, not the renderer, titles, settings or portaled menus. The same scope now supplies scene Glass V4 to control backgrounds (owner revision 2026-11-14). Floating media WorkspaceWindow consumers may apply this class to their root; their header actions use the same viewport size, while ordinary settings windows retain their own density.
|
||||
|
||||
For opaque controls directly above imagery, `nodedc-scene-controls` adds the same geometry plus a common opaque field surface. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
|
||||
`nodedc-scene-controls` is the compatibility alias for the same geometry and scene Glass V4 material. Both names consume `--nodedc-viewport-control-scale`; applications must not choose local sizes. Segmented docks align with Select and IconButton.
|
||||
|
||||
Dropdown владеет floating-layer поведением:
|
||||
|
||||
@@ -133,6 +135,8 @@ Modeless Inspector закрывается независимо от резуль
|
||||
|
||||
Для modeless Inspector доступен `draggable`: окно двигается за header, не блокирует приложение и ограничивается viewport. Modal-окна не становятся draggable автоматически.
|
||||
|
||||
DOM: `createModalSizeController({dialog, initialSize, minimum, onSizeCommit})` дополняет `createModalController` изменением размера за восемь краёв/углов. Шапка получает клавиатурный resize через Shift + стрелки. `setSize` восстанавливает сохранённый размер, `refresh` подгоняет окно после открытия. Подгонка под экран и pointercancel не записывают новое предпочтение. Контроллер не меняет modal/focus contract; приложение хранит размер отдельно для текущего пользователя. Живой пример: «Размер DOM-окна».
|
||||
|
||||
## WorkspaceWindow
|
||||
|
||||
`WorkspaceWindow` — modeless-окно внутри рабочей сцены приложения. Оно рендерится непосредственно в переданном workspace, не использует portal и не может перекрыть шапку, навигацию или соседние панели за пределами этого workspace.
|
||||
@@ -183,6 +187,8 @@ ConfirmationModal оборачивает Window и защищает async-confir
|
||||
|
||||
## SplitPane
|
||||
|
||||
Невидимый разделитель остаётся прозрачным при наведении и pointer-resize, даже после ввода в текстовом поле. Клавиатурное изменение размера сохраняет видимый focus cue.
|
||||
|
||||
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
|
||||
|
||||
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
|
||||
@@ -507,6 +513,8 @@ The first optional Hold action controls the existing persisted `autoHide` settin
|
||||
|
||||
### Tree · compact outliner
|
||||
|
||||
Visibility is independent of disclosure. Data/eye updates never re-open selected ancestors or scroll to an old selection. Disclosure uses its arrow (or ArrowLeft/ArrowRight), preserves the scroll position, and does not expand on row double-click. Only a new external selected ID/revealKey requests automatic reveal; asynchronous nodes can complete that pending request.
|
||||
|
||||
`Tree` accepts stable `TreeNode` IDs, a selected ID and `onSelect`, optional query and visibility callback. Rows stay on one line with ellipsis. Selection reveals ancestors and scrolls only the tree, avoiding page/camera jumps. Arrow keys, Home/End, Enter/Space support navigation. Use the canonical `Window resizable initialRect` for a movable object outliner.
|
||||
|
||||
`Window` end inspectors can opt into `resizable`; the same eight-edge geometry and header Shift+arrow keyboard sizing are used. Existing windows keep their defaults. `DraggableItem` also exposes `activator.attributes` and `activator.listeners` to attach directly to a tile button; separate handles remain the default for existing consumers.
|
||||
@@ -558,3 +566,29 @@ The shared theme supports `edges: "flat"` for borderless surfaces, including por
|
||||
## Mission Core theme foundation
|
||||
|
||||
`missionDarkTheme` и `missionLightTheme` — общий профиль из `@nodedc/ui-core` / `@nodedc/ui-dom`. `applyNodedcTheme` по умолчанию выбирает Mission и flat. Полный контракт цветов и композиции вложенных форм находится в [THEMING.md](THEMING.md). SettingsCard использует семантическую поверхность группы; поля расположены непосредственно в его body, как в Mission Core. GlassSurface tone="group" использует тот же материал для элементов коллекций. tone="soft" не применяется к формам. Ни CMS, ни другой потребитель не повторяет палитру локально. Living catalog содержит форму и её портальную версию.
|
||||
|
||||
## Viewport UI — правило владельца 14.11.2026
|
||||
|
||||
Все элементы интерфейса с подложкой внутри viewport используют общий Glass V4: карты, BIM, LAS/облака точек, 3DGS, PlayCanvas, камеры и replay. Поиск, отдельные кнопки прозрачного action rail, информационные плашки и меню относятся к этому правилу независимо от движка. Обычные панели вне viewport остаются matte. См. [контракт, применение и проверку](VIEWPORT_UI.md).
|
||||
|
||||
## PathBar (DOM)
|
||||
|
||||
`renderPathBar(target, items, {icon, onNavigate})` — компактная строка пути в стиле Finder: нейтральные иконки папок, текст и разделители `›`, без pill-кнопок. Подключается `@nodedc/ui-dom/styles.css`. Папки — клавиатурно доступные кнопки; конечный файл — текст с `aria-current`. Длинный путь прокручивается по горизонтали. Consumer передаёт пути и существующий Icon, хранение и навигация остаются в приложении. Живой пример: «Размер DOM-окна».
|
||||
|
||||
Toolbar `menuWidth` controls inspector menu width (default 220 px, bounded 180–600 px); Dropdown retains viewport clamping. Tree `renderActions(node)` supports per-item information menus without duplicating the outliner. `defaultExpandedDepth` limits initial expansion; selecting an item still reveals and scrolls to its ancestors. BIM uses canonical `ruler` (dimension line), `section` (model/plane), and `isolate` (temporary visibility) glyphs.
|
||||
|
||||
Open Dropdown surfaces observe content size changes and recompute their viewport bounds, including asynchronous property/volume results. Information triggers open on hover or explicit pointer/keyboard activation with `show`. Do not open on focus alone: Escape restores trigger focus and must keep the menu closed.
|
||||
|
||||
|
||||
EditorDockLayout rounds only the external corners of its complete tiled area using the shared panel radius. A left stack has a rounded top-left on its first pane and bottom-left on its last; a bottom row has only the outer lower corners. Internal joins remain square. Corners recompute after docking, closing, resizing or restoring panels. Floating tools retain all four window corners. The primary viewport follows the same outside-edge rule.
|
||||
|
||||
Viewport-scoped Toolbar buttons use the same scene Glass V4 material as the top viewport controls, preserving pressed, disabled and keyboard states. Its rail remains transparent. Compact Tree information actions use `info-plain` at 14 px beside the existing eye.
|
||||
|
||||
Tree supports optional controlled `selectedIds` for multi-selection. Its selection callback includes keyboard modifiers and the Shift range across displayed rows only. Consumers own set semantics and geometry identities; existing single-selection callers remain unchanged. Pointer and keyboard selection share the same path. Visibility and information actions do not alter the selection. The living Tree example demonstrates Shift range, Ctrl add and Command toggle.
|
||||
|
||||
|
||||
ColorField screen sampling (owner direction, 2026-11-14): the shared palette includes a Pipette action. In secure browsers supporting EyeDropper, click “Цвет с экрана”, then any screen pixel, including another application or desktop. Escape cancels without a change. Sampling never starts on pointer leave, never captures a screenshot, and is aborted when the control closes, disables or unmounts. Unsupported browsers expose “Системная палитра”; desktop sampling there depends on the native browser/OS picker. Palette/HEX remain usable regardless. This explicit fallback is the approved exception to the old no-native-dialog rule.
|
||||
|
||||
Floating EditorDockLayout tools honor minimumSize on restore, all eight resize edges and keyboard resize. If the available viewport is smaller, they fit that viewport; Inspector fields stack below a 330px content width instead of clipping. Tool footer is separate from the scrolling body; a Button width="full" is the canonical adaptive bottom action. The catalog's scene editor example demonstrates minimum size, a ColorField and fixed reset footer.
|
||||
|
||||
EditorDockLayout: every floating or actively detached tool uses context="scene" Glass V4 (shared scene tint/blur); docking removes that context and retains tiled surface/corner rules. Applies to hierarchy, layers, settings and any other editor tool. No application tint/blur overrides.
|
||||
|
||||
@@ -51,3 +51,7 @@ hover, focus, disabled и pending принадлежат кнопке. `activity
|
||||
`rotate-clockwise` — поворот изображения по часовой стрелке. Применение: независимая ориентация объективов Insta360 в Центре наблюдения Mission Core, по запросу владельца 09.10.2026. Шаг задаёт приложение; подпись кнопки сообщает угол. Состояния и геометрия принадлежат каноническому `IconButton`.
|
||||
|
||||
`power` — штатное выключение компьютера. Запрошено владельцем Mission Core 04.11.2026 для шапки окна «Бортовой компьютер». Используется в стандартном `IconButton` с доступной подписью; недоступность и выполняемое действие блокируют кнопку. Нажатие открывает `ConfirmationModal`; сам glyph не запускает выключение. Живой каталог получает иконку из `registry/icons.json`.
|
||||
|
||||
BIM controls use `ruler` (dimension line with extension lines/arrows), `section` (model intersected by a plane), `isolate` (temporary visibility/glasses), `perspective`/`orthographic` (projection cubes), and `fit-view` (frame extents). `info-plain` is an unframed i for compact tree actions next to the visibility eye; use 14 px for both glyphs. They share the canonical stroke and accessible control behavior.
|
||||
|
||||
Semantic references: [Revit measurement](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-Model/files/GUID-65EA44EC-C777-4C97-8718-5783C3A80B0A.htm), [temporary hide/isolate](https://help.autodesk.com/cloudhelp/2014/ENU/Revit-LT/files/GUID-A5E51D5E-8E18-4834-8A2F-8B4E3E6379A1.htm), [section box](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-GetStarted/files/GUID-C9EA51CB-3214-4BD8-AD55-3BEB1CCD15B6.htm). Glyphs are original monochrome NODE.DC vectors; this does not claim copied Autodesk artwork or full Section Box functionality.
|
||||
|
||||
@@ -11,3 +11,5 @@ Visible hit regions have native tooltips, hover, keyboard focus, Enter/Space act
|
||||
Presentation props: `size` in CSS pixels (default 66), `face`, `text`, `edge`, `hover`, `hoverText`, `opacity`. Consumer preferences may persist these; omitted colors inherit theme tokens. Core exposes these under viewport settings → 3D-куб.
|
||||
|
||||
Face labels use the projected face-local right/up basis, including foreshortening and rotation; they never billboard towards the screen. `edgeOpacity` (0–1, default 1) independently controls structural grid/edge strokes without fading faces or labels.
|
||||
|
||||
`faceOpacity` (0–1, default 1) controls polygon fill only. It is independent of `edgeOpacity`, text and the legacy overall `opacity`; a transparent face remains a navigation target.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Интерфейс внутри viewport
|
||||
|
||||
Правило владельца от 14.11.2026. Любая подложка интерфейса поверх изображения viewport — общий **Glass V4**, тот же материал, что информационные плашки аппаратов. Правило одинаково для MapLibre/Cesium, IFC/BIM, point cloud/LAS, 3DGS, PlayCanvas, камер и replay; новые движки не создают новый материал.
|
||||
|
||||
## Применение
|
||||
|
||||
- Поиск, панели действий, легенды, статусы и плавающие плашки: `GlassMaterialSurface context="scene"`. `radius="panel"` для текста/поиска. У рейки круглых действий фон получают сами кнопки; общий контейнер остаётся прозрачным, без общей капсулы (уточнение владельца 14.11). На существующий семантический overlay разрешён DOM-контракт `className="nodedc-viewport-surface" data-glass-context="scene"`; позиционирование и радиус остаются у композиции.
|
||||
- `nodedc-viewport-controls` и совместимый `nodedc-scene-controls` сохраняют масштаб 0.7 и задают Glass V4 кнопкам, select и segmented. Нельзя оборачивать этим scope весь renderer ради изменения размеров текста.
|
||||
- Стекло меняет фон, а не opacity всей кнопки: иконки/текст сохраняют контраст. Общие scene tokens задают плотность 52% и blur 18px, отдельно от модальных окон. Настройки материала через публичный `material` contract; приложения не копируют blur/tint CSS.
|
||||
- Открытые Dropdown/Select/Window используют canonical floating Glass V4, в том числе при fullscreen portal. Hover, pressed, disabled, focus и видимость меню сохраняются. Активная кнопка может использовать существующую контрастную заливку: это состояние общего контрола.
|
||||
- Canvas, video, геометрия, текстуры/цвета модели, карта и содержимое изображения не покрываются стеклом. Полноэкранный пустой renderer/background не является плашкой. Обычный список, каталог и настройки за пределами viewport остаются matte.
|
||||
|
||||
## Эталон и проверка
|
||||
|
||||
Живой каталог → Glassy material: общий материал плашки и компактная панель управления над тем же фоном. Проверять на тёмном и светлом изображении, без наведения и при hover/focus, узком размере и fullscreen. Для BIM и центра наблюдения отдельно проверять реальные action rails; изменение CSS не является доказательством связи с устройством или работоспособности renderer.
|
||||
|
||||
Миграция начинается с BIM-карты/viewer и Центра наблюдения. Общий action scope охватывает существующие scene/map/replay controls; оставшиеся собственные подложки переводятся на тот же surface contract. Не создавать глобальную непрозрачную плашку вокруг всех viewports.
|
||||
|
||||
Уточнение 15.11.2026: все откреплённые панели `EditorDockLayout` (иерархия, слои, настройки и другие инструменты) автоматически получают `data-glass-context="scene"`. Материал действует уже во время отрыва/перетаскивания и после восстановления плавающего положения. Повторная стыковка возвращает материал и наружные углы tiled-панелей. Приложение не задаёт свои tint/blur/opacity.
|
||||
@@ -159,3 +159,15 @@ close without also closing the battery/detail window.
|
||||
|
||||
|
||||
Portal typography is self-contained: Window text base is md/13 px, its title is title/18 px, and explanatory/status paragraphs use Description/sm/12 px. This stays identical in centered and floating modes and is independent of the host body size.
|
||||
|
||||
`EditorWorkspace purpose="view"` reuses the same stable host and docking grammar for viewers. Back/close return the mounted view to its inline slot; no edit-completion action is shown. Optional `headerActions` keeps application actions in the fixed window header. The default `purpose="edit"` preserves existing editors. The living docking example demonstrates both purposes.
|
||||
|
||||
Dock tool headings inherit the focused drag-header foreground, including title and subtitle, so the canonical inverted keyboard-focus fill retains readable text.
|
||||
|
||||
Keyboard-focused dock headers keep their action/close glyphs on the inherited contrast color, as well as title/subtitle.
|
||||
|
||||
Tool minimumSize governs floating and docked geometry alike, including restored JSON, pointer and keyboard resize. Screen bounds take priority when smaller. Put fixed bottom actions in EditorDockTool.footer; never append them to scrollable inspector content.
|
||||
|
||||
The primary scene owns an isolated stacking context so its toolbars stay behind floating tools. A tool outer shell clips without scrolling; only its body scrolls, keeping header/footer fixed even when a field receives focus.
|
||||
|
||||
ColorField spectrum has no decorative perimeter stroke; retain its visible sampling marker and keyboard focus. UserProfileMenu variant=header owns its HeaderProfile surface; consumers must not wrap it in another HeaderProfile.
|
||||
|
||||
+3
-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 test:typography && npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock && npm run test:flat-theme && npm run test:mission-theme",
|
||||
"check": "npm run test:typography && npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock && npm run test:flat-theme && npm run test:mission-theme && npm run test:modal-size",
|
||||
"dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog",
|
||||
"serve": "node server/catalog-server.mjs",
|
||||
"validate:registry": "node scripts/validate-registry.mjs",
|
||||
@@ -49,7 +49,8 @@
|
||||
"test:typography": "node --test scripts/operational-typography.test.mjs",
|
||||
"prebuild": "npm run test:typography",
|
||||
"test:flat-theme": "node --test scripts/flat-theme.test.mjs",
|
||||
"test:mission-theme": "node --test scripts/mission-theme.test.mjs"
|
||||
"test:mission-theme": "node --test scripts/mission-theme.test.mjs",
|
||||
"test:modal-size": "node --test scripts/modal-size.test.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
|
||||
@@ -1038,7 +1038,7 @@ textarea.nodedc-field__control {
|
||||
position: relative;
|
||||
aspect-ratio: 1.5 / 1;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--nodedc-glass-outline);
|
||||
border: 0;
|
||||
border-radius: var(--nodedc-radius-control);
|
||||
outline: 0;
|
||||
background:
|
||||
@@ -3169,7 +3169,9 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
/* Keep the full hit area and keyboard focus cue without a visible divider. */
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator:not(:focus-visible)::before {
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator:not(:focus-visible)::before,
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"] > .nodedc-split-pane__separator[data-pointer-focus]::before,
|
||||
.nodedc-split-pane[data-separator-appearance="invisible"][data-dragging="true"] > .nodedc-split-pane__separator::before {
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
@@ -3567,7 +3569,11 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-inspector {
|
||||
container-type: inline-size;
|
||||
container-name: nodedc-inspector;
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
width: min(var(--nodedc-inspector-inner-width), 100%);
|
||||
gap: var(--nodedc-space-3);
|
||||
}
|
||||
@@ -3577,6 +3583,8 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-inspector__group {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--nodedc-space-3);
|
||||
}
|
||||
|
||||
@@ -3658,6 +3666,8 @@ textarea.nodedc-field__control {
|
||||
|
||||
.nodedc-inspector__section-content {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--nodedc-space-3);
|
||||
padding: var(--nodedc-space-3) 0 var(--nodedc-space-2);
|
||||
animation: nodedc-section-in var(--nodedc-duration-fast) ease;
|
||||
@@ -3755,7 +3765,7 @@ textarea.nodedc-field__control {
|
||||
display: grid;
|
||||
width: min(var(--nodedc-inspector-inner-width), 100%);
|
||||
min-height: var(--nodedc-control-height);
|
||||
grid-template-columns: var(--nodedc-inspector-label-width) var(--nodedc-inspector-control-width);
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, var(--nodedc-inspector-control-width));
|
||||
align-items: center;
|
||||
gap: var(--nodedc-inspector-control-gap);
|
||||
}
|
||||
@@ -4537,14 +4547,19 @@ textarea.nodedc-field__control {
|
||||
.nodedc-editor-workspace__body {position:relative;flex:1;min-height:0;min-width:0;overflow:hidden;}
|
||||
.nodedc-editor-dock {position:absolute;inset:0;overflow:auto;overscroll-behavior:contain;isolation:isolate;}
|
||||
.nodedc-editor-dock__canvas {position:relative;width:100%;height:100%;}
|
||||
.nodedc-editor-dock__primary {position:absolute;overflow:hidden;min-width:0;min-height:0;}
|
||||
.nodedc-editor-dock__primary {position:absolute;isolation:isolate;overflow:hidden;min-width:0;min-height:0;}
|
||||
.nodedc-editor-dock__tool {position:absolute;display:flex;flex-direction:column;box-sizing:border-box;min-width:0;min-height:0;}
|
||||
.nodedc-editor-dock__tool[hidden] {display:none;}
|
||||
.nodedc-editor-dock__tool:not([data-floating]) {border-radius:0;box-shadow:none;}
|
||||
.nodedc-editor-dock__tool::before {display:none;}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="top-left"] {border-top-left-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="top-right"] {border-top-right-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="bottom-right"] {border-bottom-right-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="bottom-left"] {border-bottom-left-radius:var(--nodedc-radius-panel);}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head {flex:none;cursor:grab;touch-action:none;user-select:none;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head:active {cursor:grabbing;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head:focus-visible {outline:2px solid var(--nodedc-text-primary);outline-offset:-3px;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__head:focus-visible :is(.nodedc-window__title,.nodedc-window__subtitle,.nodedc-window__actions,.nodedc-window__close,.nodedc-icon-button) {color:inherit;}
|
||||
.nodedc-editor-dock__body {flex:1;min-height:0;min-width:0;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;padding:0 var(--nodedc-space-3) var(--nodedc-space-3);}
|
||||
.nodedc-editor-dock__tool .nodedc-inspector {width:100%;max-width:none;}
|
||||
.nodedc-editor-dock__tool>.nodedc-window__footer {flex:none;}
|
||||
@@ -4572,7 +4587,7 @@ textarea.nodedc-field__control {
|
||||
|
||||
/* Structural cube edges communicate face/edge/corner hit zones. */
|
||||
.nodedc-navigation-cube { width: 66px; height: 66px; overflow: visible; user-select: none; }
|
||||
.nodedc-navigation-cube polygon { fill: var(--cube-face, var(--nodedc-surface-raised, #292929)); stroke: var(--cube-edge, var(--nodedc-text-muted, #888)); stroke-width: .55; stroke-opacity: var(--cube-edge-opacity, 1); }
|
||||
.nodedc-navigation-cube polygon { fill: var(--cube-face, var(--nodedc-surface-raised, #292929)); stroke: var(--cube-edge, var(--nodedc-text-muted, #888)); stroke-width: .55; stroke-opacity: var(--cube-edge-opacity, 1); fill-opacity:var(--cube-face-opacity,1); }
|
||||
.nodedc-navigation-cube text { fill: var(--cube-text, var(--nodedc-text-primary, #eee)); font: 600 9px var(--nodedc-font-family); pointer-events: none; }
|
||||
.nodedc-navigation-cube g { cursor: pointer; }
|
||||
.nodedc-navigation-cube g.is-hovered polygon, .nodedc-navigation-cube g:focus-visible polygon { fill: var(--cube-hover, var(--nodedc-control-selected-bg, #eee)); }
|
||||
@@ -4725,3 +4740,39 @@ textarea.nodedc-field__control {
|
||||
}
|
||||
|
||||
.nodedc-select[data-shape="pill"] :is(.nodedc-select__value,.nodedc-select__toggle) { border-radius: var(--nodedc-radius-circle); }
|
||||
|
||||
/* Owner canon 2026-11-14: all viewport-backed UI shares scene Glass V4.
|
||||
Geometry, disabled opacity, pressed selection and keyboard focus are retained.
|
||||
The DOM surface class is for existing semantic overlays, never the renderer. */
|
||||
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar__button:not([data-active="true"]),
|
||||
.nodedc-viewport-surface[data-glass-context="scene"],
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-icon-button:not([aria-pressed="true"]), .nodedc-button:is([data-variant="secondary"], [data-variant="ghost"]):not([aria-pressed="true"]), .nodedc-select__toggle, .nodedc-segmented, .nodedc-workspace-window__action:not([aria-pressed="true"])) {
|
||||
background: rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
|
||||
color: var(--nodedc-text-primary);
|
||||
backdrop-filter: blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
-webkit-backdrop-filter: blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation)) brightness(var(--nodedc-modal-glass-brightness));
|
||||
}
|
||||
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar__button:hover:not(:disabled):not([data-active="true"]),
|
||||
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-icon-button, .nodedc-button:is([data-variant="secondary"], [data-variant="ghost"]), .nodedc-workspace-window__action):hover:not(:disabled):not([aria-pressed="true"]) {
|
||||
background: color-mix(in srgb, var(--nodedc-text-primary) 12%, rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity)));
|
||||
}
|
||||
|
||||
.nodedc-tree__actions {display:flex;flex:none;align-items:center;}
|
||||
.nodedc-tree__actions .nodedc-icon-button {flex:0 0 24px;width:24px;height:24px;min-width:24px;padding:0;}
|
||||
|
||||
/* A backdrop root on the transparent rail would prevent button glass sampling the scene. */
|
||||
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar {will-change:transform;}
|
||||
|
||||
/* Floating inspectors may be narrower than the browser; respond to their own width. */
|
||||
@container nodedc-inspector (max-width: 329px) {
|
||||
.nodedc-control-row { grid-template-columns: minmax(0, 1fr); gap: var(--nodedc-space-2); }
|
||||
}
|
||||
.nodedc-editor-dock__tool.nodedc-glass-material { overflow: clip; }
|
||||
|
||||
/* Same thin scale as the vertical section rail, with one horizontal boundary. */
|
||||
.nodedc-range-rail { display: flex; flex-direction: column; gap: var(--nodedc-space-2); width: 100%; padding-block: var(--nodedc-space-2); }
|
||||
.nodedc-range-rail__value { text-align: center; color: var(--nodedc-text-primary); font-size: var(--nodedc-font-size-md); line-height: var(--nodedc-line-height-normal); font-weight: var(--nodedc-font-weight-medium); font-variant-numeric: tabular-nums; pointer-events: none; }
|
||||
.nodedc-range[data-variant="rail"] { height: calc(var(--nodedc-control-height) * 0.2); overflow: visible; border: 0; outline: 0; box-shadow: none; }
|
||||
.nodedc-range[data-variant="rail"] input[type="range"] { top: 50%; height: max(100%, 24px); transform: translateY(-50%); }
|
||||
.nodedc-range-rail:has(input:focus-visible) .nodedc-range-rail__value { text-decoration: underline; text-underline-offset: 2px; }
|
||||
.nodedc-range-rail[data-disabled] { opacity: var(--nodedc-disabled-opacity, 0.5); }
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
"version": "0.7.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist"
|
||||
"dist",
|
||||
"styles.css"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -11,7 +12,8 @@
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./styles.css": "./styles.css"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
|
||||
@@ -3,6 +3,8 @@ export * from "./applicationWorkspace.js";
|
||||
export * from "./floating.js";
|
||||
export * from "./mediaSource.js";
|
||||
export * from "./modal.js";
|
||||
export * from "./modalSize.js";
|
||||
export * from "./pathBar.js";
|
||||
export * from "./select.js";
|
||||
export * from "./shareLink.js";
|
||||
export * from "./toolbar.js";
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
export type ModalSize = { width: number; height: number };
|
||||
export function fitModalSize(size: ModalSize, viewport: ModalSize, minimum: ModalSize = { width: 320, height: 200 }): ModalSize {
|
||||
const fit = (value: number, available: number, min: number) => Math.max(Math.min(min, Math.max(1, available - 32)), Math.min(value, Math.max(1, available - 32)));
|
||||
return { width: fit(size.width, viewport.width, minimum.width), height: fit(size.height, viewport.height, minimum.height) };
|
||||
}
|
||||
/** Resize a centered DOM modal without changing its focus/layer controller.
|
||||
* Persistence belongs to the consumer; only completed user gestures commit.
|
||||
*/
|
||||
export function createModalSizeController({ dialog, initialSize, minimum, onSizeCommit }: {
|
||||
dialog: HTMLElement; initialSize: ModalSize; minimum?: ModalSize; onSizeCommit?: (size: ModalSize) => void;
|
||||
}) {
|
||||
const head = dialog.querySelector<HTMLElement>('.nodedc-window__head');
|
||||
const previous = { width: dialog.style.width, height: dialog.style.height, maxHeight: dialog.style.maxHeight, tab: head?.getAttribute('tabindex'), title: head?.getAttribute('title') };
|
||||
let desired = { ...initialSize };
|
||||
let gesture: { id: number; x: number; y: number; edge: string; size: ModalSize; before: ModalSize } | null = null;
|
||||
const viewport = () => ({ width: window.innerWidth, height: window.innerHeight });
|
||||
const visible = () => dialog.getClientRects().length > 0;
|
||||
const apply = (size = desired) => {
|
||||
const fitted = fitModalSize(size, viewport(), minimum);
|
||||
dialog.style.width = `${fitted.width}px`;
|
||||
dialog.style.height = `${fitted.height}px`;
|
||||
dialog.style.maxHeight = 'calc(100dvh - 2rem)';
|
||||
return fitted;
|
||||
};
|
||||
const handles = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map(edge => {
|
||||
const handle = document.createElement('div');
|
||||
handle.className = 'nodedc-window__resize'; handle.dataset.edge = edge; handle.setAttribute('aria-hidden', 'true');
|
||||
handle.addEventListener('pointerdown', event => {
|
||||
if (event.button !== 0 || gesture) return;
|
||||
const rect = dialog.getBoundingClientRect();
|
||||
gesture = { id: event.pointerId, x: event.clientX, y: event.clientY, edge, size: { width: rect.width, height: rect.height }, before: desired };
|
||||
handle.setPointerCapture(event.pointerId); event.preventDefault();
|
||||
});
|
||||
dialog.append(handle); return handle;
|
||||
});
|
||||
const move = (event: PointerEvent) => {
|
||||
if (!gesture || event.pointerId !== gesture.id) return;
|
||||
const { size, edge, x, y } = gesture;
|
||||
desired = apply({ width: size.width + (event.clientX - x) * (edge.includes('e') ? 2 : edge.includes('w') ? -2 : 0), height: size.height + (event.clientY - y) * (edge.includes('s') ? 2 : edge.includes('n') ? -2 : 0) });
|
||||
event.preventDefault();
|
||||
};
|
||||
const end = (event: PointerEvent) => {
|
||||
if (!gesture || event.pointerId !== gesture.id) return;
|
||||
const before = gesture.before; gesture = null;
|
||||
if (event.type === 'pointercancel') { desired = before; apply(); return; }
|
||||
if (desired.width !== before.width || desired.height !== before.height) onSizeCommit?.({ ...desired });
|
||||
};
|
||||
const key = (event: KeyboardEvent) => {
|
||||
if (event.target !== head || !event.shiftKey || !event.key.startsWith('Arrow')) return;
|
||||
event.preventDefault();
|
||||
const size = fitModalSize(desired, viewport(), minimum);
|
||||
desired = apply({ width: size.width + (event.key === 'ArrowRight' ? 20 : event.key === 'ArrowLeft' ? -20 : 0), height: size.height + (event.key === 'ArrowDown' ? 20 : event.key === 'ArrowUp' ? -20 : 0) });
|
||||
onSizeCommit?.({ ...desired });
|
||||
};
|
||||
const refresh = () => { if (visible() && !gesture) apply(); };
|
||||
if (head) { head.tabIndex = 0; head.title = 'Размер окна: Shift + стрелки. Мышью — за край или угол.'; head.addEventListener('keydown', key); }
|
||||
window.addEventListener('pointermove', move); window.addEventListener('pointerup', end); window.addEventListener('pointercancel', end); window.addEventListener('resize', refresh);
|
||||
apply();
|
||||
return {
|
||||
refresh,
|
||||
setSize(size: ModalSize) { if (!gesture) { desired = { ...size }; apply(); } },
|
||||
destroy() {
|
||||
window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', end); window.removeEventListener('pointercancel', end); window.removeEventListener('resize', refresh);
|
||||
head?.removeEventListener('keydown', key); handles.forEach(handle => handle.remove());
|
||||
for (const name of ['width', 'height', 'maxHeight'] as const) dialog.style[name] = previous[name];
|
||||
if (head) for (const [name, value] of [['tabindex', previous.tab], ['title', previous.title]]) { if (value == null) head.removeAttribute(name!); else head.setAttribute(name!, value); }
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export type PathBarItem = { label: string; path: string; kind: 'folder' | 'file'; current?: boolean };
|
||||
/** Compact Finder-style path row. Navigation and icon source belong to the app. */
|
||||
export function renderPathBar(target: HTMLElement, items: PathBarItem[], options: { onNavigate: (path: string) => void; icon: (kind: 'folder' | 'file') => Node }) {
|
||||
target.classList.add('nodedc-path-bar');
|
||||
target.setAttribute('role', 'navigation'); target.setAttribute('aria-label', 'Путь к файлу');
|
||||
const nodes: Node[] = [];
|
||||
items.forEach((item, index) => {
|
||||
if (index) { const separator = document.createElement('span'); separator.className = 'nodedc-path-bar__separator'; separator.textContent = '›'; separator.setAttribute('aria-hidden', 'true'); nodes.push(separator); }
|
||||
const part = document.createElement(item.kind === 'folder' ? 'button' : 'span');
|
||||
part.className = 'nodedc-path-bar__item'; part.title = item.path || item.label;
|
||||
if (item.current) part.setAttribute('aria-current', 'location');
|
||||
const icon = document.createElement('span'); icon.className = 'nodedc-path-bar__icon'; icon.setAttribute('aria-hidden', 'true'); icon.append(options.icon(item.kind));
|
||||
const text = document.createElement('span'); text.textContent = item.label;
|
||||
part.append(icon, text);
|
||||
if (part instanceof HTMLButtonElement) { part.type = 'button'; part.addEventListener('click', () => options.onNavigate(item.path)); }
|
||||
nodes.push(part);
|
||||
});
|
||||
target.replaceChildren(...nodes);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
.nodedc-path-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-1);
|
||||
overflow-x: auto;
|
||||
flex: none;
|
||||
padding: var(--nodedc-space-2) var(--nodedc-space-3);
|
||||
color: var(--nodedc-text-secondary);
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
background: var(--nodedc-surface-group);
|
||||
}
|
||||
.nodedc-path-bar__item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-1);
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
font-family: inherit;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.5;
|
||||
}
|
||||
button.nodedc-path-bar__item { cursor: pointer; }
|
||||
button.nodedc-path-bar__item:hover { color: var(--nodedc-text-primary); }
|
||||
button.nodedc-path-bar__item:focus-visible { outline: 2px solid var(--nodedc-text-primary); outline-offset: 2px; }
|
||||
.nodedc-path-bar__icon { display: inline-flex; color: var(--nodedc-text-primary); }
|
||||
.nodedc-path-bar__icon svg { width: 14px; height: 14px; }
|
||||
.nodedc-path-bar__separator { flex: none; color: var(--nodedc-text-muted); }
|
||||
@@ -126,6 +126,13 @@ export function Dropdown({
|
||||
updatePosition();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !surfaceRef.current) return;
|
||||
const observer = new ResizeObserver(updatePosition);
|
||||
observer.observe(surfaceRef.current);
|
||||
return () => observer.disconnect();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !getAnchorRect) return;
|
||||
let frame:number;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {InspectorSelectPolicyContext} from './InspectorContext.js';
|
||||
import {LoadingContext} from './LoadingContext.js';
|
||||
import {fitWindow,resizeWindow,windowResizeEdges,type ResizeEdge} from './windowGeometry.js';
|
||||
import {cn} from './cn.js';
|
||||
import {editorDockCorners} from './editorDockCorners.js';
|
||||
|
||||
export interface EditorDockTool {
|
||||
id:string;title:ReactNode;label:string;open:boolean;onClose:()=>void;content:ReactNode;
|
||||
@@ -38,7 +39,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
|
||||
const required=dockMinimum(visibleTree,minimums),area={...bounds,width:Math.max(bounds.width,required.width),height:Math.max(bounds.height,required.height)};
|
||||
const constrained=constrainDockTree(visibleTree,area,minimums)!;
|
||||
const rects=dockRects(constrained,area);
|
||||
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds);
|
||||
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds,tools.find(t=>t.id===id)?.minimumSize);
|
||||
const latest=useRef({value,onChange,rects,bounds,enabled,tools});latest.current={value,onChange,rects,bounds,enabled,tools};
|
||||
const activate=(id:string)=>setOrder(v=>[...v.filter(x=>x!==id),id]);
|
||||
useLayoutEffect(()=>{const v=viewport.current!;const measure=()=>setBounds({left:0,top:0,width:v.clientWidth,height:v.clientHeight});measure();const ro=new ResizeObserver(measure);ro.observe(v);return()=>ro.disconnect();},[]);
|
||||
@@ -56,8 +57,8 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
|
||||
const p=point(e),dx=p.x-g.x,dy=p.y-g.y;
|
||||
if(!g.moved&&Math.hypot(dx,dy)<6)return;
|
||||
g.moved=true;
|
||||
const b=latest.current.bounds;
|
||||
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b);
|
||||
const b=latest.current.bounds,minimum=latest.current.tools.find(t=>t.id===g.id)?.minimumSize;
|
||||
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b,minimum):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b,minimum);
|
||||
const visibleBounds={...b,left:viewport.current?.scrollLeft??0,top:viewport.current?.scrollTop??0};
|
||||
g.target=g.edge?null:editorDockTarget(visibleBounds,latest.current.rects,primaryId,g.id,p.x,p.y);
|
||||
setDrag({...g});e.preventDefault();
|
||||
@@ -84,7 +85,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
|
||||
else if(position)setKeyboard({id,target:{activeId:id,overId:keyboard.target?.overId??primaryId,position,scope:e.shiftKey||!keyboard.target?'workspace':keyboard.target.scope}});
|
||||
else return;
|
||||
}else if(e.key==='Enter'||e.key===' '){setKeyboard({id,target:null});activate(id);}
|
||||
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds)}});}
|
||||
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds,tools.find(t=>t.id===id)?.minimumSize):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds,tools.find(t=>t.id===id)?.minimumSize)}});}
|
||||
else return;
|
||||
e.preventDefault();e.stopPropagation();
|
||||
};
|
||||
@@ -97,11 +98,11 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
|
||||
return <div ref={viewport} className={cn('nodedc-editor-dock',className)} data-editing={enabled||undefined} data-dragging={!!drag||undefined}>
|
||||
<div ref={host} className="nodedc-editor-dock__canvas" style={{minWidth:required.width,minHeight:required.height}}>
|
||||
<EditorSplits tree={constrained} bounds={area} minimums={minimums} onResize={(path,ratio)=>onChange({...value,tree:mergeEditorDockRatios(value.tree,resizeDockSplit(constrained,path,ratio))})}/>
|
||||
<div className="nodedc-editor-dock__primary" data-editor-primary={primaryId} style={rects[primaryId]}>{primary}</div>
|
||||
<div className="nodedc-editor-dock__primary" data-editor-primary={primaryId} data-dock-corners={editorDockCorners(rects[primaryId],area)} style={rects[primaryId]}>{primary}</div>
|
||||
{tools.map(tool=>{
|
||||
const moving=drag?.id===tool.id,free=!rects[tool.id]||moving;
|
||||
const rect=moving?drag.current:rects[tool.id]??floatingRect(tool.id);
|
||||
return <div key={tool.id} className={cn('nodedc-editor-dock__tool nodedc-glass-material nodedc-ui-root',tool.className)} data-editor-tool={tool.id} data-floating={free||undefined} data-active={order.at(-1)===tool.id||undefined}
|
||||
return <div key={tool.id} className={cn('nodedc-editor-dock__tool nodedc-glass-material nodedc-ui-root',tool.className)} data-editor-tool={tool.id} data-floating={free||undefined} data-glass-context={free?'scene':undefined} data-dock-corners={free?undefined:editorDockCorners(rect,area)} data-active={order.at(-1)===tool.id||undefined}
|
||||
role="region" aria-label={tool.label} hidden={!enabled||!tool.open} style={{...rect,zIndex:moving?40:free?10+Math.max(0,order.indexOf(tool.id)):1}}
|
||||
onPointerDownCapture={()=>activate(tool.id)} onFocusCapture={()=>activate(tool.id)}>
|
||||
<header className="nodedc-window__head" tabIndex={0} aria-label={`Переместить · ${tool.label}`} aria-roledescription="Перемещаемая панель" onPointerDown={e=>begin(tool.id,e)} onKeyDown={e=>key(tool.id,e)}>
|
||||
|
||||
@@ -5,9 +5,9 @@ import {Icon} from './Icon.js';
|
||||
import {WindowSuspensionContext} from './WindowSuspensionContext.js';
|
||||
import {cn} from './cn.js';
|
||||
|
||||
export interface EditorWorkspaceProps {editing:boolean;title:ReactNode;subtitle?:ReactNode;onBack:()=>void;children:ReactNode;className?:string}
|
||||
export interface EditorWorkspaceProps {editing:boolean;title:ReactNode;subtitle?:ReactNode;onBack:()=>void;children:ReactNode;className?:string;purpose?:'edit'|'view';headerActions?:ReactNode}
|
||||
/** One mounted renderer moves between its original slot and a modeless editor window. */
|
||||
export function EditorWorkspace({editing,title,subtitle,onBack,children,className}:EditorWorkspaceProps){
|
||||
export function EditorWorkspace({editing,title,subtitle,onBack,children,className,purpose='edit',headerActions}:EditorWorkspaceProps){
|
||||
const suspend=useContext(WindowSuspensionContext);
|
||||
useLayoutEffect(()=>{if(editing)return suspend?.();},[editing,suspend]);
|
||||
const inline=useRef<HTMLDivElement>(null),[host]=useState(()=>document.createElement('div'));
|
||||
@@ -28,10 +28,11 @@ export function EditorWorkspace({editing,title,subtitle,onBack,children,classNam
|
||||
{editing&&<header className="nodedc-window__head nodedc-editor-workspace__head">
|
||||
<div className="nodedc-window__titles"><h1 id={titleId} className="nodedc-window__title">{title}</h1>{subtitle&&<p className="nodedc-window__subtitle">{subtitle}</p>}</div>
|
||||
<div className="nodedc-window__actions">
|
||||
<IconButton data-editor-back label="Вернуться из редактора сцены" onClick={onBack}><Icon name="chevron-left"/></IconButton>
|
||||
<IconButton label={expanded?'Восстановить окно редактора':'Развернуть окно редактора'} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton>
|
||||
<IconButton label="Завершить редактирование сцены" aria-pressed onClick={onBack}><Icon name="edit"/></IconButton>
|
||||
<IconButton label="Закрыть редактор сцены" onClick={onBack}><Icon name="close"/></IconButton>
|
||||
{headerActions}
|
||||
<IconButton data-editor-back label={purpose==='view'?'Вернуть просмотр в рабочую область':'Вернуться из редактора сцены'} onClick={onBack}><Icon name="chevron-left"/></IconButton>
|
||||
<IconButton label={expanded?(purpose==='view'?'Восстановить окно просмотра':'Восстановить окно редактора'):(purpose==='view'?'Развернуть окно просмотра':'Развернуть окно редактора')} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton>
|
||||
{purpose==='edit'&&<IconButton label="Завершить редактирование сцены" aria-pressed onClick={onBack}><Icon name="edit"/></IconButton>}
|
||||
<IconButton label={purpose==='view'?'Закрыть отдельное окно просмотра':'Закрыть редактор сцены'} onClick={onBack}><Icon name="close"/></IconButton>
|
||||
</div>
|
||||
</header>}
|
||||
<div className="nodedc-editor-workspace__body">{children}</div>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import {
|
||||
MousePointer2,
|
||||
Pipette,
|
||||
createLucideIcon,
|
||||
Glasses,
|
||||
Cuboid,
|
||||
Move,
|
||||
CirclePlus,
|
||||
Box,
|
||||
@@ -70,10 +74,26 @@ import {
|
||||
type LucideProps,
|
||||
} from "lucide-react";
|
||||
|
||||
// CAD vocabulary: dimension line, cutting plane and unframed information glyph.
|
||||
const DimensionLine = createLucideIcon('DimensionLine', [
|
||||
['path', {d:'M4 5v14M20 5v14M4 12h16M8 9l-4 3 4 3M16 9l4 3-4 3',key:'dimension'}],
|
||||
]);
|
||||
const SectionPlane = createLucideIcon('SectionPlane', [
|
||||
['path', {d:'m5 7 7-4 7 4v10l-7 4-7-4V7m0 0 7 4 7-4M12 11v10',key:'model'}],
|
||||
['path', {d:'m2 12 10-5 10 5-10 5-10-5Z',key:'plane'}],
|
||||
]);
|
||||
const InformationPlain = createLucideIcon('InformationPlain', [
|
||||
['path', {d:'M12 4h.01M10 9h2v11M9 20h6',key:'information'}],
|
||||
]);
|
||||
const icons = {
|
||||
pipette: Pipette,
|
||||
"add-point": CirclePlus,
|
||||
perspective: Box,
|
||||
orthographic: Scan,
|
||||
ruler: DimensionLine,
|
||||
section: SectionPlane,
|
||||
isolate: Glasses,
|
||||
perspective: Cuboid,
|
||||
orthographic: Box,
|
||||
"fit-view": Scan,
|
||||
select: MousePointer2,
|
||||
move: Move,
|
||||
pen: PenTool,
|
||||
@@ -110,6 +130,7 @@ const icons = {
|
||||
image: Image,
|
||||
inbox: Inbox,
|
||||
info: Info,
|
||||
"info-plain": InformationPlain,
|
||||
key: KeyRound,
|
||||
layers: Layers,
|
||||
list: ListChecks,
|
||||
|
||||
@@ -4,7 +4,7 @@ export interface NavigationCubeProps {
|
||||
/** Camera world quaternion, Y up. Directions point from target toward camera. */
|
||||
quaternion: readonly [number,number,number,number];
|
||||
onSelect: (direction:CubeDirection)=>void;
|
||||
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number;
|
||||
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number; faceOpacity?:number;
|
||||
disabled?:boolean;
|
||||
label?:string;
|
||||
}
|
||||
@@ -42,9 +42,9 @@ export function cubeRegions(quaternion:NavigationCubeProps["quaternion"]) {
|
||||
});
|
||||
}
|
||||
/** BIM-style face / edge / corner navigation, independent of the scene engine. */
|
||||
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1}:NavigationCubeProps) {
|
||||
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1,faceOpacity=1}:NavigationCubeProps) {
|
||||
const [hover,setHover]=useState<string|null>(null);
|
||||
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
|
||||
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-face-opacity":faceOpacity,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
|
||||
{cubeRegions(quaternion).map(r=><g key={r.id} role="button" aria-label={`Ракурс: ${r.label}`} aria-disabled={disabled}
|
||||
tabIndex={disabled?-1:0} className={hover===r.label?"is-hovered":""}
|
||||
onPointerEnter={()=>setHover(r.label)} onPointerLeave={()=>setHover(null)}
|
||||
|
||||
@@ -3,10 +3,16 @@ import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBa
|
||||
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Dropdown } from "./Dropdown.js";
|
||||
import { Button } from "./Button.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { Description } from "./Description.js";
|
||||
import { screenColorPicker } from "./screenColorPicker.js";
|
||||
|
||||
export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> {
|
||||
label: string;
|
||||
orientation?: "horizontal" | "vertical";
|
||||
/** Thin horizontal single-value rail; no containing surface or exact editor. */
|
||||
variant?: "field" | "rail";
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
@@ -69,6 +75,7 @@ export function RangeControl(props: RangeControlProps | RangeBandControlProps) {
|
||||
function SingleRangeControl({
|
||||
label,
|
||||
orientation = "horizontal",
|
||||
variant = "field",
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
@@ -155,6 +162,17 @@ function SingleRangeControl({
|
||||
}
|
||||
};
|
||||
|
||||
if (orientation === "horizontal" && variant === "rail") return (
|
||||
<div className={cn("nodedc-range-rail", className)} data-disabled={disabled || undefined}>
|
||||
<span className="nodedc-range-rail__value" aria-hidden="true">{displayValue}</span>
|
||||
<div ref={rootRef} className="nodedc-range" style={style} data-variant="rail">
|
||||
<input ref={rangeRef} {...props} type="range" value={value} min={min} max={safeMax} step={step}
|
||||
disabled={disabled} tabIndex={tabIndex} aria-label={label} aria-orientation="horizontal"
|
||||
aria-valuetext={displayValue} onChange={event => onChange(Number(event.target.value))}/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (orientation === "vertical") return (
|
||||
<div className="nodedc-range-scale" data-limit-side={limitSide} style={style}>
|
||||
<div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical">
|
||||
@@ -277,7 +295,27 @@ function hsvToHex({ h, s, v }: Hsv): string {
|
||||
|
||||
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, onBlur, onKeyDown, ...props }: ColorFieldProps) {
|
||||
const [draft, setDraft] = useState(value);
|
||||
const [paletteOpen, setPaletteOpen] = useState(false), [picking, setPicking] = useState(false), [pickError, setPickError] = useState(false);
|
||||
const nativePicker = useRef<HTMLInputElement>(null), sampling = useRef<AbortController | null>(null);
|
||||
const screenPicker = screenColorPicker();
|
||||
useEffect(() => () => { sampling.current?.abort(); }, []);
|
||||
useEffect(() => { if (disabled || !paletteOpen) { sampling.current?.abort(); sampling.current = null; setPicking(false); } }, [disabled, paletteOpen]);
|
||||
useEffect(() => setDraft(value), [value]);
|
||||
const sampleScreen = async () => {
|
||||
if (disabled || sampling.current) return;
|
||||
setPickError(false);
|
||||
if (!screenPicker) { nativePicker.current?.click(); return; }
|
||||
const controller = new AbortController(); sampling.current = controller; setPicking(true);
|
||||
try {
|
||||
// open() executes synchronously in this trusted click before the first await.
|
||||
const result = await new screenPicker().open({ signal: controller.signal });
|
||||
if (!controller.signal.aborted && parseHexColor(result.sRGBHex)) { setDraft(result.sRGBHex.toLowerCase()); onChange(result.sRGBHex.toLowerCase()); }
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted && !(error instanceof Error && error.name === 'AbortError')) setPickError(true);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) { setPicking(false); sampling.current = null; }
|
||||
}
|
||||
};
|
||||
const validColor = hexToHsv(value);
|
||||
const [hsv, setHsv] = useState<Hsv>(() => validColor ?? { h: 330, s: 82, v: 100 });
|
||||
const style = { "--nodedc-color-value": validColor ? hsvToHex(validColor) : hsvToHex(hsv) } as CSSProperties;
|
||||
@@ -302,6 +340,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
<div className={cn("nodedc-color-field", className)} style={style}>
|
||||
<Dropdown
|
||||
className="nodedc-color-field__dropdown"
|
||||
onOpenChange={setPaletteOpen}
|
||||
placement="bottom-start"
|
||||
minWidth={296}
|
||||
width={296}
|
||||
@@ -354,6 +393,10 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
<span>Оттенок</span>
|
||||
<input type="range" min={0} max={360} value={Math.round(hsv.h)} aria-label={`${label}: оттенок`} disabled={disabled} onChange={(event) => commit({ ...hsv, h: Number(event.target.value) })} />
|
||||
</label>
|
||||
<Button width="full" icon={<Icon name="pipette"/>} disabled={disabled} loading={picking} onClick={() => void sampleScreen()} title={screenPicker ? 'Выбрать цвет в любой точке экрана; Escape — отменить' : 'В этом браузере выбор цвета с экрана доступен через системную палитру, если она поддерживает пипетку'}>
|
||||
{screenPicker ? 'Цвет с экрана' : 'Системная палитра'}
|
||||
</Button>
|
||||
{pickError && <Description role="status">Не удалось включить пипетку. Повторите попытку.</Description>}
|
||||
<div className="nodedc-color-palette__presets" aria-label="Быстрые цвета">
|
||||
{palettePresets.map((preset) => (
|
||||
<button
|
||||
@@ -371,6 +414,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
||||
</div>
|
||||
</div>
|
||||
</Dropdown>
|
||||
<input ref={nativePicker} type="color" hidden tabIndex={-1} aria-hidden="true" disabled={disabled} value={validColor ? hsvToHex(validColor) : '#000000'} onChange={event => { setDraft(event.target.value); onChange(event.target.value); }}/>
|
||||
<input
|
||||
className="nodedc-color-field__text"
|
||||
{...props}
|
||||
|
||||
@@ -57,6 +57,7 @@ export function SplitPane({
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const activePointerIdRef = useRef<number | null>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [pointerFocus, setPointerFocus] = useState(false);
|
||||
const limits = normalizedLimits(minPrimarySize, minSecondarySize);
|
||||
const size = clamp(Number.isFinite(primarySize) ? primarySize : 50, limits.minimum, limits.maximum);
|
||||
const keyboardIncrement = Number.isFinite(step) && step > 0 ? step : 2;
|
||||
@@ -74,6 +75,7 @@ export function SplitPane({
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
|
||||
setPointerFocus(false);
|
||||
const multiplier = event.shiftKey ? 5 : 1;
|
||||
const decrement = orientation === "vertical" ? "ArrowLeft" : "ArrowUp";
|
||||
const increment = orientation === "vertical" ? "ArrowRight" : "ArrowDown";
|
||||
@@ -119,10 +121,13 @@ export function SplitPane({
|
||||
aria-valuemax={Math.round(limits.maximum)}
|
||||
aria-valuenow={Math.round(size)}
|
||||
aria-valuetext={`${Math.round(size)}% / ${Math.round(100 - size)}%`}
|
||||
data-pointer-focus={pointerFocus || undefined}
|
||||
onBlur={() => setPointerFocus(false)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button !== 0) return;
|
||||
event.currentTarget.focus();
|
||||
setPointerFocus(true);
|
||||
event.currentTarget.focus({ preventScroll: true });
|
||||
activePointerIdRef.current = event.pointerId;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
setDragging(true);
|
||||
|
||||
@@ -38,6 +38,8 @@ export interface ToolbarProps<T extends string = string> {
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
label?: string;
|
||||
/** Dropdown width; placement still clamps to the visible viewport. */
|
||||
menuWidth?: number;
|
||||
className?: string;
|
||||
/** Render inside a positioned viewport; edge reveal follows that viewport. */
|
||||
container?: HTMLElement;
|
||||
@@ -66,6 +68,7 @@ export function Toolbar<T extends string = string>({
|
||||
hideDelay = NODEDC_TOOLBAR_DEFAULTS.hideDelay,
|
||||
gap = NODEDC_TOOLBAR_DEFAULTS.gap,
|
||||
label = "Панель инструментов",
|
||||
menuWidth = 220,
|
||||
className,
|
||||
container,
|
||||
}: ToolbarProps<T>) {
|
||||
@@ -392,7 +395,7 @@ export function Toolbar<T extends string = string>({
|
||||
if(placement==="left")return {...b.toJSON(),left:t.left,right:t.left+pad,width:pad};
|
||||
if(placement==="bottom")return {...b.toJSON(),top:t.bottom-pad,bottom:t.bottom,height:pad};
|
||||
return {...b.toJSON(),top:t.top,bottom:t.top+pad,height:pad};
|
||||
}} width={220} trigger={button} onPointerDownOutside={event=>{
|
||||
}} width={Number.isFinite(menuWidth)?Math.max(180,Math.min(600,menuWidth)):220} trigger={button} onPointerDownOutside={event=>{
|
||||
const target=event.target as Element;
|
||||
// Dismiss a menu before a viewport tool can turn this same click into an edit.
|
||||
if(container?.contains(target)&&!target.closest('button,input,select,textarea,a,[role="button"],[role="tab"]')){
|
||||
|
||||
@@ -1,27 +1,49 @@
|
||||
import {useLayoutEffect,useRef,useState,type CSSProperties} from 'react';
|
||||
import {useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode} from 'react';
|
||||
import {treeSelectionRange} from './treeSelectionRange.js';
|
||||
import {Icon,type IconName} from './Icon.js';
|
||||
|
||||
export interface TreeNode {id:string;label:string;children?:TreeNode[];icon?:IconName;visible?:boolean}
|
||||
export interface TreeProps {nodes:TreeNode[];selected:string|null;onSelect:(id:string)=>void;onVisibilityChange?:(id:string,visible:boolean)=>void;label:string;query?:string;revealKey?:number}
|
||||
export interface TreeSelectionGesture {ctrlKey:boolean;metaKey:boolean;shiftKey:boolean;rangeIds:string[]}
|
||||
export interface TreeProps {nodes:TreeNode[];selected:string|null;selectedIds?:readonly string[];onSelect:(id:string,gesture:TreeSelectionGesture)=>void;onVisibilityChange?:(id:string,visible:boolean)=>void;label:string;query?:string;revealKey?:number;defaultExpandedDepth?:number;renderActions?:(node:TreeNode)=>ReactNode}
|
||||
|
||||
/** Compact outliner. Selection reveals ancestors without scrolling its host page. */
|
||||
export function Tree({nodes,selected,onSelect,onVisibilityChange,label,query='',revealKey}:TreeProps){
|
||||
const [collapsed,setCollapsed]=useState<Set<string>>(()=>new Set());
|
||||
export function Tree({nodes,selected,selectedIds,onSelect,onVisibilityChange,label,query='',revealKey,defaultExpandedDepth=Infinity,renderActions}:TreeProps){
|
||||
const [collapsed,setCollapsed]=useState<Map<string,boolean>>(()=>new Map());
|
||||
const [focus,setFocus]=useState<string|null>(null);
|
||||
const anchor=useRef<string|null>(null);
|
||||
const lastReveal=useRef<{selected:string;key:number|undefined}|null>(null),pendingReveal=useRef<string|null>(null);
|
||||
const disclosureScroll=useRef<number|null>(null);
|
||||
const host=useRef<HTMLDivElement>(null),elements=useRef(new Map<string,HTMLDivElement>());
|
||||
const parents=new Map<string,string>(),index=new Map<string,TreeNode>();
|
||||
const visit=(items:TreeNode[],parent?:string)=>{for(const item of items){index.set(item.id,item);if(parent)parents.set(item.id,parent);visit(item.children??[],item.id);}};visit(nodes);
|
||||
const ancestors=new Set<string>();let parent=selected?parents.get(selected):undefined;while(parent){ancestors.add(parent);parent=parents.get(parent);}
|
||||
const matches=(item:TreeNode):boolean=>!query||item.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())||!!item.children?.some(matches);
|
||||
const rows:{node:TreeNode;depth:number;open:boolean}[]=[];
|
||||
const flatten=(items:TreeNode[],depth=0)=>{for(const node of items){if(!matches(node))continue;const open=!!query||!collapsed.has(node.id);rows.push({node,depth,open});if(open)flatten(node.children??[],depth+1);}};flatten(nodes);
|
||||
const flatten=(items:TreeNode[],depth=0)=>{for(const node of items){if(!matches(node))continue;const open=!!query||!(collapsed.get(node.id)??depth>=defaultExpandedDepth);rows.push({node,depth,open});if(open)flatten(node.children??[],depth+1);}};flatten(nodes);
|
||||
const reveal=(id:string)=>{const target=elements.current.get(id),container=host.current;if(!target||!container)return;const row=target.getBoundingClientRect(),box=container.getBoundingClientRect();if(row.top<box.top)container.scrollTop-=box.top-row.top;else if(row.bottom>box.bottom)container.scrollTop+=row.bottom-box.bottom;};
|
||||
useLayoutEffect(()=>{if(selected){setFocus(selected);setCollapsed(old=>{if(![...ancestors].some(id=>old.has(id)))return old;const next=new Set(old);for(const id of ancestors)next.delete(id);return next;});}},[selected,revealKey]);
|
||||
useLayoutEffect(()=>{if(selected)reveal(selected);},[selected,revealKey,query,collapsed]);
|
||||
const toggle=(id:string)=>setCollapsed(old=>{const next=new Set(old);if(next.has(id))next.delete(id);else next.add(id);return next;});
|
||||
const select=(id:string)=>{setFocus(id);onSelect(id);elements.current.get(id)?.focus({preventScroll:true});reveal(id);};
|
||||
return <div ref={host} className="nodedc-tree" role="tree" aria-label={label}>
|
||||
{rows.map(({node,depth,open},position)=><div key={node.id} ref={element=>{if(element)elements.current.set(node.id,element);else elements.current.delete(node.id);}} role="treeitem" aria-level={depth+1} aria-selected={selected===node.id} aria-expanded={node.children?.length?open:undefined} tabIndex={(focus??selected??rows[0]?.node.id)===node.id?0:-1} className="nodedc-tree__row" style={{'--tree-depth':depth} as CSSProperties} title={node.label} onFocus={()=>setFocus(node.id)} onClick={()=>select(node.id)} onDoubleClick={()=>node.children?.length&&toggle(node.id)} onKeyDown={event=>{
|
||||
// Data/visibility refreshes are not a new selection. An unresolved external
|
||||
// selection may wait for async nodes, but a manual disclosure always wins.
|
||||
useLayoutEffect(()=>{
|
||||
if(!selected){lastReveal.current=null;pendingReveal.current=null;return;}
|
||||
if(lastReveal.current?.selected===selected&&lastReveal.current.key===revealKey)return;
|
||||
if(!index.has(selected))return;
|
||||
lastReveal.current={selected,key:revealKey};pendingReveal.current=selected;setFocus(selected);
|
||||
setCollapsed(old=>{if([...ancestors].every(id=>old.get(id)===false))return old;const next=new Map(old);for(const id of ancestors)next.set(id,false);return next;});
|
||||
},[selected,revealKey,nodes]);
|
||||
useLayoutEffect(()=>{
|
||||
if(disclosureScroll.current!==null){if(host.current)host.current.scrollTop=disclosureScroll.current;disclosureScroll.current=null;return;}
|
||||
const id=pendingReveal.current;if(id&&elements.current.has(id)){reveal(id);pendingReveal.current=null;}
|
||||
},[selected,revealKey,nodes,query,collapsed]);
|
||||
const toggle=(id:string)=>{
|
||||
pendingReveal.current=null;disclosureScroll.current=host.current?.scrollTop??null;
|
||||
setCollapsed(old=>{const next=new Map(old);const depth=rows.find(row=>row.node.id===id)?.depth??0;next.set(id,!(old.get(id)??depth>=defaultExpandedDepth));return next;});
|
||||
};
|
||||
const select=(id:string,event:{ctrlKey:boolean;metaKey:boolean;shiftKey:boolean})=>{setFocus(id);
|
||||
const rangeIds=event.shiftKey&&selectedIds?treeSelectionRange(rows.map(row=>row.node.id),anchor.current,id):[id];
|
||||
if(!event.shiftKey)anchor.current=id;
|
||||
onSelect(id,{ctrlKey:event.ctrlKey,metaKey:event.metaKey,shiftKey:event.shiftKey,rangeIds});elements.current.get(id)?.focus({preventScroll:true});reveal(id);};
|
||||
return <div ref={host} className="nodedc-tree" role="tree" aria-label={label} aria-multiselectable={selectedIds?true:undefined}>
|
||||
{rows.map(({node,depth,open},position)=><div key={node.id} ref={element=>{if(element)elements.current.set(node.id,element);else elements.current.delete(node.id);}} role="treeitem" aria-level={depth+1} aria-selected={selectedIds?selectedIds.includes(node.id):selected===node.id} aria-expanded={node.children?.length?open:undefined} tabIndex={(focus??selected??rows[0]?.node.id)===node.id?0:-1} className="nodedc-tree__row" style={{'--tree-depth':depth} as CSSProperties} title={node.label} onFocus={()=>setFocus(node.id)} onClick={event=>select(node.id,event)} onKeyDown={event=>{
|
||||
if(event.target!==event.currentTarget)return;
|
||||
let next:string|undefined;
|
||||
if(event.key==='ArrowDown')next=rows[Math.min(rows.length-1,position+1)]?.node.id;
|
||||
@@ -32,11 +54,12 @@ export function Tree({nodes,selected,onSelect,onVisibilityChange,label,query='',
|
||||
else if(event.key==='ArrowLeft'){if(open&&node.children?.length)toggle(node.id);else next=parents.get(node.id);}
|
||||
else if(event.key==='Enter'||event.key===' ')next=node.id;
|
||||
else return;
|
||||
event.preventDefault();event.stopPropagation();if(next)select(next);
|
||||
event.preventDefault();event.stopPropagation();if(next)select(next,event);
|
||||
}}>
|
||||
<span className="nodedc-tree__branch">{node.children?.length?<button type="button" tabIndex={-1} aria-label={`${open?'Свернуть':'Развернуть'} ${node.label}`} onClick={event=>{event.stopPropagation();toggle(node.id);}}><Icon name={open?'chevron-down':'chevron-right'} size={14}/></button>:null}</span>
|
||||
<Icon name={node.icon??(node.children?.length?'folder':'layers')} size={14}/>
|
||||
<span className="nodedc-tree__label">{node.label}</span>
|
||||
{renderActions&&<span className="nodedc-tree__actions" onClick={event=>event.stopPropagation()} onDoubleClick={event=>event.stopPropagation()}>{renderActions(node)}</span>}
|
||||
{onVisibilityChange&&node.visible!==undefined&&<button type="button" className="nodedc-tree__visibility" tabIndex={focus===node.id?0:-1} aria-label={`${node.visible?'Скрыть':'Показать'} ${node.label}`} aria-pressed={node.visible} onClick={event=>{event.stopPropagation();onVisibilityChange(node.id,!node.visible);}}><Icon name={node.visible?'eye':'eye-off'} size={14}/></button>}
|
||||
</div>)}
|
||||
</div>;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import type {DockRect} from '@nodedc/ui-core';
|
||||
/** Only corners on both outer edges are rounded; all internal seams stay square. */
|
||||
export function editorDockCorners(rect:DockRect,area:DockRect):string {
|
||||
const same=(a:number,b:number)=>Math.abs(a-b)<.01;
|
||||
const left=same(rect.left,area.left),top=same(rect.top,area.top);
|
||||
const right=same(rect.left+rect.width,area.left+area.width),bottom=same(rect.top+rect.height,area.top+area.height);
|
||||
return [top&&left?'top-left':'',top&&right?'top-right':'',bottom&&right?'bottom-right':'',bottom&&left?'bottom-left':''].filter(Boolean).join(' ');
|
||||
}
|
||||
@@ -48,7 +48,7 @@ export {KeyButton, type KeyButtonProps} from './KeyButton.js';
|
||||
|
||||
export type {DockMinimum, DockMinimums} from "@nodedc/ui-core";
|
||||
|
||||
export {Tree,type TreeNode,type TreeProps} from "./Tree.js";
|
||||
export {Tree,type TreeNode,type TreeProps,type TreeSelectionGesture} from "./Tree.js";
|
||||
|
||||
export * from "./ResizableViewport.js";
|
||||
export {useApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Screen sampling requires a secure context and an explicit trusted click. No screenshots are retained. */
|
||||
export type ScreenColorPicker = new () => { open(options: { signal: AbortSignal }): Promise<{ sRGBHex: string }> };
|
||||
export function screenColorPicker(): ScreenColorPicker | undefined {
|
||||
return (globalThis as typeof globalThis & { EyeDropper?: ScreenColorPicker }).EyeDropper;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Range follows displayed rows only; folded/filtered-out branches cannot leak in. */
|
||||
export function treeSelectionRange(rows:readonly string[],anchor:string|null,target:string):string[]{
|
||||
const a=rows.indexOf(anchor??target),b=rows.indexOf(target);
|
||||
return a<0||b<0?[target]:rows.slice(Math.min(a,b),Math.max(a,b)+1);
|
||||
}
|
||||
@@ -3,15 +3,16 @@ export type WindowRect = { left: number; top: number; width: number; height: num
|
||||
export type ResizeEdge = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
|
||||
export const windowResizeEdges: ResizeEdge[] = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];
|
||||
type Bounds = { width: number; height: number };
|
||||
const defaultMinimum: Bounds = { width: 320, height: 200 };
|
||||
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value));
|
||||
export function fitWindow(rect: WindowRect, bounds: Bounds): WindowRect {
|
||||
const width = clamp(rect.width, Math.min(320, bounds.width - 16), Math.max(1, bounds.width - 16));
|
||||
const height = clamp(rect.height, Math.min(200, bounds.height - 16), Math.max(1, bounds.height - 16));
|
||||
export function fitWindow(rect: WindowRect, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
|
||||
const width = clamp(rect.width, Math.max(1, Math.min(minimum.width, bounds.width - 16)), Math.max(1, bounds.width - 16));
|
||||
const height = clamp(rect.height, Math.max(1, Math.min(minimum.height, bounds.height - 16)), Math.max(1, bounds.height - 16));
|
||||
return { width, height, left: clamp(rect.left, 8, Math.max(8, bounds.width - width - 8)), top: clamp(rect.top, 8, Math.max(8, bounds.height - height - 8)) };
|
||||
}
|
||||
export function resizeWindow(rect: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds): WindowRect {
|
||||
const r = fitWindow(rect, bounds), right = r.left + r.width, bottom = r.top + r.height;
|
||||
const minWidth = Math.min(320, bounds.width - 16), minHeight = Math.min(200, bounds.height - 16);
|
||||
export function resizeWindow(rect: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
|
||||
const r = fitWindow(rect, bounds, minimum), right = r.left + r.width, bottom = r.top + r.height;
|
||||
const minWidth = Math.max(1, Math.min(minimum.width, bounds.width - 16)), minHeight = Math.max(1, Math.min(minimum.height, bounds.height - 16));
|
||||
const left = edge.includes('w') ? clamp(r.left + dx, 8, right - minWidth) : r.left;
|
||||
const top = edge.includes('n') ? clamp(r.top + dy, 8, bottom - minHeight) : r.top;
|
||||
const endX = edge.includes('e') ? clamp(right + dx, left + minWidth, bounds.width - 8) : right;
|
||||
|
||||
+61
-16
@@ -105,7 +105,8 @@
|
||||
"nodedc-glass",
|
||||
"nodedc-glass-material",
|
||||
"nodedc-map-glass",
|
||||
"nodedc-material-rim"
|
||||
"nodedc-material-rim",
|
||||
"nodedc-viewport-surface"
|
||||
],
|
||||
"summary": "Matte application surfaces, the Engine V4 modal material and the light translucent surface used over Cesium imagery. Scene overlays reuse V4 blur and tint with independent translucent density.",
|
||||
"anatomy": [
|
||||
@@ -137,7 +138,8 @@
|
||||
"Form collections use tone=group, the same neutral material as SettingsCard. tone=soft is a recessed secondary canvas, never a form-grid background.",
|
||||
"GlassMaterialSurface supports modal/Inspector floating material and explicit context=scene telemetry overlays over rendered imagery; ordinary panels remain matte. Optional material and radiusPx apply appearance to one instance without changing the global theme.",
|
||||
"MapGlassSurface is restricted to overlays over Cesium/map imagery and must match the map Toolbar translucency.",
|
||||
"Theme edges=flat removes decorative rims and active outlines across portals; keyboard focus uses contrasting fill without changing geometry."
|
||||
"Theme edges=flat removes decorative rims and active outlines across portals; keyboard focus uses contrasting fill without changing geometry.",
|
||||
"Owner 2026-11-14: all backed UI inside every map/3D/camera/replay viewport uses scene Glass V4, independent of renderer. Use GlassMaterialSurface context=scene or nodedc-viewport-surface for an existing semantic overlay. Never tint the renderer itself. See docs/VIEWPORT_UI.md."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -180,7 +182,9 @@
|
||||
"Destructive actions remain neutral until confirmation unless danger is the principal message.",
|
||||
"loading displays one centered indicator inside the initiating action, disables repeat activation and preserves dimensions and accessible name. Never place its spinner beside or below the action group.",
|
||||
"Primary tone=neutral is white when enabled and gray when disabled in every theme/accent; use it for accent-independent operator actions without local CSS overrides.",
|
||||
"nodedc-viewport-controls is the shared geometry context for every viewer toolbar: 0.7 times standard controls, including icons, fonts and rims. It normalizes legacy compact/dense variants, never compounds in nested groups, and excludes portaled menus/settings and scene content."
|
||||
"nodedc-viewport-controls is the shared geometry context for every viewer toolbar: 0.7 times standard controls, including icons, fonts and rims. It normalizes legacy compact/dense variants, never compounds in nested groups, and excludes portaled menus/settings and scene content.",
|
||||
"Viewport action scopes apply scene Glass V4 to normal backgrounds; selected/disabled/hover and focus semantics are preserved. No local nearly transparent substitutes.",
|
||||
"Viewport round action rails keep their group container transparent: glass belongs to each circle, not a shared capsule."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -308,7 +312,8 @@
|
||||
"The browser places the caret at the clicked character, preserves native drag or keyboard selection, and replaces the selected substring on typing without pointer-state interception.",
|
||||
"Editor foreground and caret switch automatically between theme text and on-accent tokens according to the actual fill edge beneath the value area.",
|
||||
"The editor has no separate background box and keeps focus across parent window rerenders and pointer leave.",
|
||||
"Editor keyboard events do not bubble into enclosing Window shortcuts."
|
||||
"Editor keyboard events do not bubble into enclosing Window shortcuts.",
|
||||
"variant=rail is the single-value horizontal counterpart of the thin vertical section scale: 0.2 control-height shaft, minimum 24 px transparent target, value above, native arrows/Home/End, disabled and value underline focus. No enclosing surface, glass, outline, shadow or exact-value editor. Consumer owns placement and visibility timing."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -328,12 +333,14 @@
|
||||
"hue slider",
|
||||
"quick colors",
|
||||
"portal palette",
|
||||
"keyboard spectrum adjustment"
|
||||
"keyboard spectrum adjustment",
|
||||
"explicit screen eyedropper with cancellation; system palette fallback when EyeDropper is unavailable"
|
||||
],
|
||||
"rules": [
|
||||
"Do not expose a browser-native color dialog as the product runtime UI.",
|
||||
"The palette owns choice geometry; the consumer owns color validation, persistence and domain reaction.",
|
||||
"HEX text keeps incomplete drafts; valid six-digit colors apply live, invalid drafts revert on blur/Escape, Enter commits; external undo updates the field."
|
||||
"HEX text keeps incomplete drafts; valid six-digit colors apply live, invalid drafts revert on blur/Escape, Enter commits; external undo updates the field.",
|
||||
"The themed palette remains primary. Screen sampling starts only on a trusted button click, never pointer leave; unsupported browsers expose an explicit system-palette fallback. No screenshots are captured or stored. Escape, closing or unmount cancels sampling without applying a color.",
|
||||
"Spectrum has no decorative perimeter border; sampling marker and keyboard focus remain visible."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -355,6 +362,7 @@
|
||||
"behavior": [
|
||||
"portal to active fullscreen element or document body",
|
||||
"viewport clamp",
|
||||
"content resize repositions an open dropdown within viewport bounds",
|
||||
"vertical flip",
|
||||
"capture-phase outside pointer close before scene tool interception",
|
||||
"optional outside-pointer consumer for editing viewports",
|
||||
@@ -420,7 +428,9 @@
|
||||
],
|
||||
"domPackage": "@nodedc/ui-dom",
|
||||
"domExports": [
|
||||
"createModalController"
|
||||
"createModalController",
|
||||
"createModalSizeController",
|
||||
"fitModalSize"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-overlay",
|
||||
@@ -437,7 +447,8 @@
|
||||
"modal-only body scroll lock",
|
||||
"optional bounded dragging for modeless inspectors",
|
||||
"move toggle: preserve mounted contents and current size; remove dimming, backdrop close, scroll lock and focus trap; header drag and eight invisible resize regions",
|
||||
"Escape and Tab belong to the focused or topmost visible modal; parent windows do not dismiss behind nested settings."
|
||||
"Escape and Tab belong to the focused or topmost visible modal; parent windows do not dismiss behind nested settings.",
|
||||
"DOM modal resizing shares eight canonical edge handles, centered viewport bounds and keyboard Shift+arrow control; onSizeCommit runs only for completed user changes."
|
||||
],
|
||||
"rules": [
|
||||
"headerActionsPlacement=before-close places context actions between the move toggle and close in both visual and keyboard order; the default preserves existing consumers.",
|
||||
@@ -537,7 +548,7 @@
|
||||
"behavior": [
|
||||
"controlled percentage",
|
||||
"optional resizable separator",
|
||||
"line or invisible separator appearance with retained keyboard focus",
|
||||
"line or invisible separator appearance with retained keyboard focus; pointer resize never paints the invisible divider",
|
||||
"pointer capture drag",
|
||||
"Arrow/Home/End keyboard sizing",
|
||||
"ARIA separator range",
|
||||
@@ -806,6 +817,8 @@
|
||||
"viewport container scope with local edge reveal",
|
||||
"native tooltips with keyboard shortcut hints",
|
||||
"optional canonical dropdown for toolbar item menus",
|
||||
"viewport-scoped buttons share scene Glass V4; the rail stays transparent",
|
||||
"bounded menuWidth for rich inspectors; default remains 220 px",
|
||||
"theme-independent geometry",
|
||||
"menus outside maximum magnified icon envelope",
|
||||
"bounded triangle intent corridor before sibling menu activation",
|
||||
@@ -1128,7 +1141,8 @@
|
||||
"The panel variant reuses AdminNavigationPanel pill, icon and theme tokens while retaining the same controlled accordion state and domain-owned content.",
|
||||
"A section action is a sibling IconButton before the disclosure chevron, never nested in the trigger. It does not toggle the section. Panel chevrons point down when collapsed and up when expanded.",
|
||||
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts.",
|
||||
"Default sections and optional header fields use the canonical 12 px spacing token; footer actions are centered with the same gap. Nested Inspectors retain this rhythm; the panel variant retains its compact row geometry."
|
||||
"Default sections and optional header fields use the canonical 12 px spacing token; footer actions are centered with the same gap. Nested Inspectors retain this rhythm; the panel variant retains its compact row geometry.",
|
||||
"Inspector responds to its own container width: fields stack below 330px and intrinsic tracks must not clip content."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1259,6 +1273,7 @@
|
||||
],
|
||||
"summary": "Renderer-independent BIM-style orientation cube; six faces, twelve edges, eight corners.",
|
||||
"behavior": [
|
||||
"independent faceOpacity, edgeOpacity and text colors; overall opacity remains compatible",
|
||||
"Tracks camera quaternion; never changes projection implicitly",
|
||||
"Visible regions support hover, focus, Enter/Space and disabled state",
|
||||
"Consumer owns camera navigation and coordinate conversion",
|
||||
@@ -1274,7 +1289,8 @@
|
||||
"exports": [
|
||||
"Tree",
|
||||
"TreeNode",
|
||||
"TreeProps"
|
||||
"TreeProps",
|
||||
"TreeSelectionGesture"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-tree",
|
||||
@@ -1282,14 +1298,19 @@
|
||||
],
|
||||
"summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.",
|
||||
"behavior": [
|
||||
"selection expands ancestors and scrolls only the tree container",
|
||||
"new external selection expands ancestors and scrolls only the tree container",
|
||||
"visibility/data refresh keeps disclosure state; arrow disclosure keeps scroll position; row double-click does not expand",
|
||||
"Arrow/Home/End navigation, disclosure and optional visibility actions",
|
||||
"long names ellipsize without growing row height",
|
||||
"filter retains matching ancestors"
|
||||
"filter retains matching ancestors",
|
||||
"optional renderActions slot composes canonical controls without selecting the row",
|
||||
"defaultExpandedDepth limits initial expansion; external selection reveals ancestors"
|
||||
],
|
||||
"rules": [
|
||||
"Use for object hierarchies; no nested ResourceRow cards.",
|
||||
"Host owns model identity and visibility; the tree owns navigation presentation."
|
||||
"Host owns model identity and visibility; the tree owns navigation presentation.",
|
||||
"Compact information uses info-plain at 14px beside the independent visibility eye.",
|
||||
"Optional controlled selectedIds and modifier/range callback support multiple selection; Shift ranges use displayed rows only. Existing single-selection consumers remain compatible."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1378,7 +1399,9 @@
|
||||
"behavior": [
|
||||
"four outer magnetic edges",
|
||||
"nested adjacent tool splits",
|
||||
"only exterior workspace corners are rounded; adjoining pane seams remain square and update after dock, resize or close",
|
||||
"drag header to detach over primary",
|
||||
"floating and dragged tools use canonical scene Glass V4; docking restores tiled surface context",
|
||||
"invisible resize regions",
|
||||
"controlled JSON layout",
|
||||
"stable mounted renderer",
|
||||
@@ -1393,7 +1416,9 @@
|
||||
"Hidden tools retain their docking placement and remembered floating rectangle. Viewport clamps never overwrite preferred geometry.",
|
||||
"EditorWorkspace keeps one mounted portal host, moves it atomically when supported, and restores its original slot on return. It never changes the source-view layout.",
|
||||
"The fixed editor header is outside docking bounds. Back, edit completion and close return to the original view.",
|
||||
"When opened inside Window, the editor suspends that overlay, backdrop and focus trap without unmounting; returning restores the same window."
|
||||
"When opened inside Window, the editor suspends that overlay, backdrop and focus trap without unmounting; returning restores the same window.",
|
||||
"EditorWorkspace purpose=view uses the same mounted host, return/fullscreen behavior and optional fixed headerActions; purpose=edit remains the compatible default.",
|
||||
"Tool minimumSize applies to floating restore, pointer and keyboard resize as well as docked splits; small screens clamp to available space. Footer remains outside the body scroller."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1444,6 +1469,26 @@
|
||||
"Content is descriptive, never a menu or interactive form.",
|
||||
"No new app-local tooltip geometry or layer management."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "path-bar",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-dom",
|
||||
"exports": [
|
||||
"renderPathBar",
|
||||
"PathBarItem"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-path-bar"
|
||||
],
|
||||
"summary": "Compact Finder-style path navigation with neutral folder icons, separators and native folder buttons.",
|
||||
"behavior": [
|
||||
"Application supplies items, icon factory and navigation callback.",
|
||||
"Current location uses aria-current; long paths scroll without wrapping."
|
||||
],
|
||||
"rules": [
|
||||
"Use ui-dom/styles.css, theme tokens and textContent labels; no application-local breadcrumb pills."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+8
-2
@@ -33,7 +33,8 @@
|
||||
"apps",
|
||||
"layers",
|
||||
"move",
|
||||
"power"
|
||||
"power",
|
||||
"pipette"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -54,6 +55,7 @@
|
||||
"sliders",
|
||||
"search",
|
||||
"orthographic",
|
||||
"fit-view",
|
||||
"perspective"
|
||||
]
|
||||
},
|
||||
@@ -79,7 +81,10 @@
|
||||
"curve",
|
||||
"undo",
|
||||
"redo",
|
||||
"add-point"
|
||||
"add-point",
|
||||
"ruler",
|
||||
"section",
|
||||
"isolate"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -94,6 +99,7 @@
|
||||
"check",
|
||||
"alert",
|
||||
"info",
|
||||
"info-plain",
|
||||
"activity",
|
||||
"lock",
|
||||
"key",
|
||||
|
||||
@@ -56,7 +56,8 @@
|
||||
"mapTemplate": "../docs/MAP_TEMPLATE.md",
|
||||
"icons": "../docs/ICONS.md",
|
||||
"consumption": "../docs/CONSUMPTION.md",
|
||||
"environmentSettings": "../docs/ENVIRONMENT_SETTINGS.md"
|
||||
"environmentSettings": "../docs/ENVIRONMENT_SETTINGS.md",
|
||||
"viewportUi": "../docs/VIEWPORT_UI.md"
|
||||
},
|
||||
"applicationManifestSchema": "schemas/application-manifest-v0.1.schema.json",
|
||||
"designProfileSchema": "schemas/design-profile-v0.1.schema.json",
|
||||
|
||||
@@ -54,3 +54,21 @@ test('repeated dock and float transitions retain unique tools and tile the full
|
||||
const free=dockEditorTool(state,'viewport',null,id,rect);assert.ok(!dockIds(free.tree).includes(id));assert.deepEqual(free.floating[id],rect);
|
||||
}
|
||||
});
|
||||
|
||||
import {editorDockCorners} from '../packages/ui-react/dist/editorDockCorners.js';
|
||||
test('left stacked panels round only the outer top and bottom; close restores both corners',()=>{
|
||||
const tree={axis:'x',ratio:25,first:{axis:'y',ratio:50,first:{id:'a'},second:{id:'b'}},second:{id:'viewport'}};
|
||||
const r=dockRects(tree,bounds);
|
||||
assert.equal(editorDockCorners(r.a,bounds),'top-left');assert.equal(editorDockCorners(r.b,bounds),'bottom-left');
|
||||
assert.equal(editorDockCorners(r.viewport,bounds),'top-right bottom-right');
|
||||
const remaining=dockRects(pruneDockTree(tree,['a','viewport']),bounds);
|
||||
assert.equal(editorDockCorners(remaining.a,bounds),'top-left bottom-left');
|
||||
});
|
||||
test('top and bottom rows retain square seams at every size and canvas origin',()=>{
|
||||
for(const position of ['top','bottom'])for(const area of [bounds,{left:80,top:45,width:713.5,height:528.3}]){
|
||||
const first=dockEditorTool(start,'viewport',{activeId:'a',overId:'viewport',position,scope:'workspace'},'a',rect);
|
||||
const split=dockEditorTool(first,'viewport',{activeId:'b',overId:'a',position:'right',scope:'panel'},'b',rect);
|
||||
const r=dockRects(split.tree,area);
|
||||
assert.equal(editorDockCorners(r.a,area),position+'-left');assert.equal(editorDockCorners(r.b,area),position+'-right');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fitModalSize, createModalSizeController } from '../packages/ui-dom/dist/modalSize.js';
|
||||
test('modal dimensions fit narrow and desktop screens without mutating preference', () => {
|
||||
const requested = { width: 1600, height: 900 };
|
||||
assert.deepEqual(fitModalSize(requested, { width: 375, height: 667 }), { width: 343, height: 635 });
|
||||
assert.deepEqual(fitModalSize(requested, { width: 1920, height: 1080 }), requested);
|
||||
assert.deepEqual(requested, { width: 1600, height: 900 });
|
||||
});
|
||||
test('only completed gestures commit; viewport fitting and cancellation preserve preference', () => {
|
||||
class Element extends EventTarget {
|
||||
style = { width: '', height: '', maxHeight: '' }; dataset = {}; attributes = new Map(); children = [];
|
||||
setAttribute(k,v) { this.attributes.set(k,v); } getAttribute(k) { return this.attributes.get(k) ?? null; } removeAttribute(k) { this.attributes.delete(k); }
|
||||
append(value) { this.children.push(value); } remove() {} setPointerCapture() {}
|
||||
getClientRects() { return [1]; } getBoundingClientRect() { return { width: parseFloat(this.style.width), height: parseFloat(this.style.height) }; }
|
||||
querySelector() { return head; }
|
||||
}
|
||||
const head = new Element(), dialog = new Element(), commits = [];
|
||||
const oldWindow = globalThis.window, oldDocument = globalThis.document;
|
||||
globalThis.window = Object.assign(new EventTarget(), { innerWidth: 1600, innerHeight: 1000 });
|
||||
globalThis.document = { createElement: () => new Element() };
|
||||
const dispatch = (target, type, values) => target.dispatchEvent(Object.assign(new Event(type, { cancelable: true }), values));
|
||||
try {
|
||||
const controller = createModalSizeController({ dialog, initialSize: { width: 800, height: 500 }, onSizeCommit: s => commits.push(s) });
|
||||
const edge = dialog.children.find(node => node.dataset.edge === 'se');
|
||||
dispatch(edge, 'pointerdown', {button: 0, pointerId: 1, clientX: 500, clientY: 500});
|
||||
dispatch(window, 'pointermove', {pointerId: 1, clientX: 650, clientY: 600});
|
||||
assert.equal(commits.length, 0);
|
||||
dispatch(window, 'pointerup', {pointerId: 1});
|
||||
assert.deepEqual(commits, [{width: 1100, height: 700}]);
|
||||
window.innerWidth = 500; window.innerHeight = 400; window.dispatchEvent(new Event('resize'));
|
||||
assert.equal(dialog.style.width, '468px'); assert.equal(commits.length, 1);
|
||||
window.innerWidth = 1600; window.innerHeight = 1000; window.dispatchEvent(new Event('resize'));
|
||||
assert.equal(dialog.style.width, '1100px');
|
||||
dispatch(edge, 'pointerdown', {button: 0, pointerId: 2, clientX: 500, clientY: 500});
|
||||
dispatch(window, 'pointermove', {pointerId: 2, clientX: 650, clientY: 600});
|
||||
dispatch(window, 'pointercancel', {pointerId: 2}); assert.equal(dialog.style.width, '1100px'); assert.equal(commits.length, 1);
|
||||
controller.destroy(); assert.equal(dialog.style.width, '');
|
||||
} finally { globalThis.window = oldWindow; globalThis.document = oldDocument; }
|
||||
});
|
||||
@@ -117,3 +117,15 @@ test("both boundaries move, clamp independently, separate after coincidence and
|
||||
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]);
|
||||
});
|
||||
|
||||
test("horizontal thin rail has one native boundary and a formatted value, without field chrome", () => {
|
||||
for(const disabled of [false,true]){
|
||||
const markup=renderToStaticMarkup(createElement(RangeControl,{variant:"rail",label:"Скорость",value:5,min:.1,max:100,step:.1,disabled,formatValue:n=>`${n} м/с`,onChange(){}}));
|
||||
assert.equal((markup.match(/type="range"/g)||[]).length,1);
|
||||
assert.match(markup,/aria-label="Скорость" aria-orientation="horizontal"/);
|
||||
assert.match(markup,/aria-valuetext="5 м\/с"/);
|
||||
assert.match(markup,/nodedc-range-rail__value/);
|
||||
assert.equal(markup.includes('disabled=""'),disabled);
|
||||
assert.doesNotMatch(markup,/nodedc-range__label|nodedc-range__editor|nodedc-glass/);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),assert=require('node:assert/strict');
|
||||
// Supply jsdom through the QA NODE_PATH when it is not installed locally.
|
||||
const root=process.env.DG_ROOT||path.resolve(__dirname,'..');
|
||||
const {JSDOM}=require('jsdom'),React=require(root+'/node_modules/react'),{act}=React,{createRoot}=require(root+'/node_modules/react-dom/client');
|
||||
const dom=new JSDOM('<div id="app"></div>',{pretendToBeVisual:true});
|
||||
for(const name of ['window','document','HTMLElement','Element','Node','Event','MouseEvent','KeyboardEvent'])global[name]=dom.window[name];global.IS_REACT_ACT_ENVIRONMENT=true;
|
||||
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'nodedc-tree-check-'));
|
||||
require(root+'/node_modules/esbuild').buildSync({entryPoints:[root+'/packages/ui-react/src/Tree.tsx'],outfile:scratch+'/tree.cjs',bundle:true,platform:'node',format:'cjs',external:['react','react/*'],jsx:'automatic'});
|
||||
const {Tree}=require(scratch+'/tree.cjs');
|
||||
HTMLElement.prototype.getBoundingClientRect=function(){
|
||||
const host=this.closest('[role=tree]');if(this===host)return{top:0,bottom:140,left:0,right:400,width:400,height:140};
|
||||
const i=host?[...host.querySelectorAll('[role=treeitem]')].indexOf(this):0,top=i*28-(host?.scrollTop||0);return{top,bottom:top+28,left:0,right:400,width:400,height:28};
|
||||
};
|
||||
let visible=true,selected='leaf99',revision=0,selectedCalls=0,available=true;
|
||||
const nodes=()=>[{id:'root',label:'Root',visible,children:available?Array.from({length:100},(_,i)=>({id:'leaf'+i,label:'Leaf '+i})):[]}];
|
||||
const ui=createRoot(document.getElementById('app'));
|
||||
const render=()=>act(async()=>ui.render(React.createElement(Tree,{nodes:nodes(),selected,revealKey:revision,label:'Tree test',defaultExpandedDepth:1,onSelect:()=>selectedCalls++,onVisibilityChange:(_,v)=>{visible=v;}})));
|
||||
const button=label=>[...document.querySelectorAll('button')].find(b=>b.getAttribute('aria-label')===label);
|
||||
const send=(target,type='click',props={})=>act(async()=>target.dispatchEvent(new MouseEvent(type,{bubbles:true,...props})));
|
||||
(async()=>{
|
||||
await render();const host=document.querySelector('[role=tree]');assert(host.scrollTop>0,'external leaf selection reveals the leaf');
|
||||
await send(button('Свернуть Root'));host.scrollTop=0;assert.equal(document.querySelectorAll('[role=treeitem]').length,1);
|
||||
await send(button('Скрыть Root'));await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,1,'visibility refresh cannot re-open selected ancestors');assert.equal(host.scrollTop,0);assert.equal(selectedCalls,0);
|
||||
await send(button('Развернуть Root'));assert.equal(document.querySelectorAll('[role=treeitem]').length,101);assert.equal(host.scrollTop,0,'disclosure must not reveal old selected leaf');
|
||||
await send(button('Свернуть Root'));await send(document.querySelector('[role=treeitem]'),'dblclick');assert.equal(document.querySelectorAll('[role=treeitem]').length,1,'only disclosure, not row double-click, expands');
|
||||
revision++;await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,101);assert(host.scrollTop>0,'explicit external reveal still works');
|
||||
selected='later';available=false;await render();selected='leaf99';await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,1);available=true;await render();assert.equal(document.querySelectorAll('[role=treeitem]').length,101);assert(host.scrollTop>0,'pending selection is revealed when async children arrive');
|
||||
await act(async()=>ui.unmount());console.log('PASS: 6 Tree DOM scenarios — visibility/disclosure independence, no disclosure scroll jump, eye does not select, row double-click does not expand, explicit reveal, async reveal.');
|
||||
})().catch(e=>{console.error(e);process.exitCode=1;}).finally(()=>{fs.rmSync(scratch,{recursive:true,force:true});dom.window.close();});
|
||||
@@ -0,0 +1,10 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {treeSelectionRange} from '../packages/ui-react/dist/treeSelectionRange.js';
|
||||
test('tree ranges include endpoints in both directions and only visible rows',()=>{
|
||||
const visible=['project','group','first','last','other'];
|
||||
assert.deepEqual(treeSelectionRange(visible,'first','last'),['first','last']);
|
||||
assert.deepEqual(treeSelectionRange(visible,'last','first'),['first','last']);
|
||||
assert.deepEqual(treeSelectionRange(visible,'filtered-out','last'),['last']);
|
||||
assert.deepEqual(treeSelectionRange(visible,null,'first'),['first']);
|
||||
});
|
||||
@@ -15,3 +15,15 @@ test('viewport shrink retains reachable header and fits small screens',()=>{
|
||||
assert.deepEqual(v,{left:8,top:8,width:264,height:164});
|
||||
assert.deepEqual(fitWindow(r,bounds),r);
|
||||
});
|
||||
|
||||
test('custom tool minimum applies to restored geometry and every resize edge',()=>{
|
||||
const minimum={width:380,height:280};
|
||||
const restored=fitWindow({...r,width:320,height:200},bounds,minimum);
|
||||
assert.equal(restored.width,380);assert.equal(restored.height,280);
|
||||
for(const edge of windowResizeEdges)for(const delta of [-3000,3000]){
|
||||
const resized=resizeWindow(r,edge,delta,delta,bounds,minimum);
|
||||
assert.ok(resized.width>=380&&resized.height>=280);
|
||||
}
|
||||
assert.deepEqual(fitWindow(r,{width:280,height:180},minimum),{left:8,top:8,width:264,height:164});
|
||||
const tiny=fitWindow(r,{width:10,height:10},minimum);assert.equal(tiny.width,1);assert.equal(tiny.height,1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user