Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4390d1350d | ||
|
|
fea966a3f0 | ||
|
|
8b49296efa | ||
|
|
70d5d8b385 | ||
|
|
cb49932706 | ||
|
|
5f93defabf |
@@ -250,6 +250,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const iconLabels: Record<IconName, string> = {
|
const iconLabels: Record<IconName, string> = {
|
||||||
|
pipette: "Пипетка",
|
||||||
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
|
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
|
||||||
power: "Питание",
|
power: "Питание",
|
||||||
move: "Свободное окно",
|
move: "Свободное окно",
|
||||||
@@ -1615,7 +1616,7 @@ export function CatalogApp() {
|
|||||||
</div>
|
</div>
|
||||||
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
|
<p className="catalog-preview__explanation">Rectangle, maximize, close и stacking остаются состоянием приложения; дизайн-система владеет одинаковой bounded-геометрией и доступным управлением.</p>
|
||||||
</Preview>
|
</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} />
|
<Switch label="Скрыть линию разделителя" checked={splitPaneInvisible} onChange={setSplitPaneInvisible} />
|
||||||
<div className="catalog-split-pane-demo">
|
<div className="catalog-split-pane-demo">
|
||||||
<SplitPane
|
<SplitPane
|
||||||
@@ -2374,7 +2375,7 @@ export function CatalogApp() {
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
|
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
|
||||||
<Tree defaultExpandedDepth={2} renderActions={node=><Dropdown width={320} trigger={({setTriggerRef,show,open})=><IconButton ref={setTriggerRef} label={`Информация: ${node.label}`} aria-expanded={open} onMouseEnter={show} onClick={show}><Icon name="info-plain" size={14}/></IconButton>}><Description>{node.label}</Description></Dropdown>} label="Пример дерева объектов" selected={treeSelected} selectedIds={treeSelectedIds} onSelect={(id,gesture)=>{setTreeSelected(id);setTreeSelectedIds(old=>gesture.shiftKey?gesture.rangeIds:gesture.metaKey?(old.includes(id)?old.filter(key=>key!==id):[...old,id]):gesture.ctrlKey?[...new Set([...old,id])]:[id]);}} onVisibilityChange={(_,visible)=>setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/>
|
<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>
|
||||||
<Window
|
<Window
|
||||||
open={inspectorOpen}
|
open={inspectorOpen}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
import {useState} from 'react';
|
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}){
|
export function EditorDockExample({inWindow=false}:{inWindow?:boolean}){
|
||||||
|
const [color,setColor]=useState('#292929');
|
||||||
const [modal,setModal]=useState(false),[purpose,setPurpose]=useState<'edit'|'view'>('edit');
|
const [modal,setModal]=useState(false),[purpose,setPurpose]=useState<'edit'|'view'>('edit');
|
||||||
const [editing,setEditing]=useState(false),[open,setOpen]=useState({objects:true,materials:true});
|
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:{}});
|
const [layout,setLayout]=useState<EditorDockState>({tree:{axis:'y',ratio:70,first:{axis:'x',ratio:25,first:{id:'objects'},second:{id:'viewport'}},second:{id:'materials'}},floating:{}});
|
||||||
return <>{!inWindow&&<><Button onClick={()=>setModal(true)}>Сцена в модальном окне</Button><Window open={modal} title="Просмотр сцены" onClose={()=>setModal(false)}><EditorDockExample inWindow/></Window></>}<Button onClick={()=>{setPurpose('edit');setOpen({objects:true,materials:true});setEditing(true);}}>Открыть редактор сцены</Button><Button onClick={()=>{setPurpose('view');setEditing(true);}}>Отдельное окно просмотра</Button><div style={{height:480}}>
|
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}>
|
<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>Закреплённая сцена</Description><Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button></div>}
|
<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>},
|
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>
|
</EditorWorkspace>
|
||||||
</div></>;
|
</div></>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -185,6 +185,8 @@ ConfirmationModal оборачивает Window и защищает async-confir
|
|||||||
|
|
||||||
## SplitPane
|
## SplitPane
|
||||||
|
|
||||||
|
Невидимый разделитель остаётся прозрачным при наведении и pointer-resize, даже после ввода в текстовом поле. Клавиатурное изменение размера сохраняет видимый focus cue.
|
||||||
|
|
||||||
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
|
`SplitPane` — контролируемая раскладка двух синхронных представлений с общей регулируемой границей. Приложение передаёт содержимое обеих панелей, процент primary-панели и callback изменения; дизайн-система владеет pointer capture, ограничениями размеров, focus-state и доступностью `role="separator"`.
|
||||||
|
|
||||||
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
|
Локальные toolbar и overlay каждого viewport являются содержимым соответствующей панели. Их нельзя позиционировать от общего workspace или вычислять по cursor/event-эвристике вложенного renderer. Если renderer хранит свою раскладку, приложение передаёт ему тот же controlled процент из `SplitPane`, чтобы renderer и локальный UI использовали одну геометрию.
|
||||||
@@ -509,6 +511,8 @@ The first optional Hold action controls the existing persisted `autoHide` settin
|
|||||||
|
|
||||||
### Tree · compact outliner
|
### 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.
|
`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.
|
`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.
|
||||||
@@ -579,3 +583,10 @@ EditorDockLayout rounds only the external corners of its complete tiled area usi
|
|||||||
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.
|
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.
|
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.
|
||||||
|
|||||||
@@ -15,3 +15,5 @@
|
|||||||
Живой каталог → Glassy material: общий материал плашки и компактная панель управления над тем же фоном. Проверять на тёмном и светлом изображении, без наведения и при hover/focus, узком размере и fullscreen. Для BIM и центра наблюдения отдельно проверять реальные action rails; изменение CSS не является доказательством связи с устройством или работоспособности renderer.
|
Живой каталог → Glassy material: общий материал плашки и компактная панель управления над тем же фоном. Проверять на тёмном и светлом изображении, без наведения и при hover/focus, узком размере и fullscreen. Для BIM и центра наблюдения отдельно проверять реальные action rails; изменение CSS не является доказательством связи с устройством или работоспособности renderer.
|
||||||
|
|
||||||
Миграция начинается с BIM-карты/viewer и Центра наблюдения. Общий action scope охватывает существующие scene/map/replay controls; оставшиеся собственные подложки переводятся на тот же surface contract. Не создавать глобальную непрозрачную плашку вокруг всех viewports.
|
Миграция начинается с BIM-карты/viewer и Центра наблюдения. Общий action scope охватывает существующие scene/map/replay controls; оставшиеся собственные подложки переводятся на тот же surface contract. Не создавать глобальную непрозрачную плашку вокруг всех viewports.
|
||||||
|
|
||||||
|
Уточнение 15.11.2026: все откреплённые панели `EditorDockLayout` (иерархия, слои, настройки и другие инструменты) автоматически получают `data-glass-context="scene"`. Материал действует уже во время отрыва/перетаскивания и после восстановления плавающего положения. Повторная стыковка возвращает материал и наружные углы tiled-панелей. Приложение не задаёт свои tint/blur/opacity.
|
||||||
|
|||||||
@@ -165,3 +165,9 @@ Portal typography is self-contained: Window text base is md/13 px, its title is
|
|||||||
Dock tool headings inherit the focused drag-header foreground, including title and subtitle, so the canonical inverted keyboard-focus fill retains readable text.
|
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.
|
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.
|
||||||
|
|||||||
@@ -1038,7 +1038,7 @@ textarea.nodedc-field__control {
|
|||||||
position: relative;
|
position: relative;
|
||||||
aspect-ratio: 1.5 / 1;
|
aspect-ratio: 1.5 / 1;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
border: 1px solid var(--nodedc-glass-outline);
|
border: 0;
|
||||||
border-radius: var(--nodedc-radius-control);
|
border-radius: var(--nodedc-radius-control);
|
||||||
outline: 0;
|
outline: 0;
|
||||||
background:
|
background:
|
||||||
@@ -3169,7 +3169,9 @@ textarea.nodedc-field__control {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Keep the full hit area and keyboard focus cue without a visible divider. */
|
/* 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;
|
background: transparent;
|
||||||
box-shadow: none;
|
box-shadow: none;
|
||||||
}
|
}
|
||||||
@@ -3567,7 +3569,11 @@ textarea.nodedc-field__control {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.nodedc-inspector {
|
.nodedc-inspector {
|
||||||
|
container-type: inline-size;
|
||||||
|
container-name: nodedc-inspector;
|
||||||
display: grid;
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
width: min(var(--nodedc-inspector-inner-width), 100%);
|
width: min(var(--nodedc-inspector-inner-width), 100%);
|
||||||
gap: var(--nodedc-space-3);
|
gap: var(--nodedc-space-3);
|
||||||
}
|
}
|
||||||
@@ -3577,6 +3583,8 @@ textarea.nodedc-field__control {
|
|||||||
|
|
||||||
.nodedc-inspector__group {
|
.nodedc-inspector__group {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
gap: var(--nodedc-space-3);
|
gap: var(--nodedc-space-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3658,6 +3666,8 @@ textarea.nodedc-field__control {
|
|||||||
|
|
||||||
.nodedc-inspector__section-content {
|
.nodedc-inspector__section-content {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
gap: var(--nodedc-space-3);
|
gap: var(--nodedc-space-3);
|
||||||
padding: var(--nodedc-space-3) 0 var(--nodedc-space-2);
|
padding: var(--nodedc-space-3) 0 var(--nodedc-space-2);
|
||||||
animation: nodedc-section-in var(--nodedc-duration-fast) ease;
|
animation: nodedc-section-in var(--nodedc-duration-fast) ease;
|
||||||
@@ -3755,7 +3765,7 @@ textarea.nodedc-field__control {
|
|||||||
display: grid;
|
display: grid;
|
||||||
width: min(var(--nodedc-inspector-inner-width), 100%);
|
width: min(var(--nodedc-inspector-inner-width), 100%);
|
||||||
min-height: var(--nodedc-control-height);
|
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;
|
align-items: center;
|
||||||
gap: var(--nodedc-inspector-control-gap);
|
gap: var(--nodedc-inspector-control-gap);
|
||||||
}
|
}
|
||||||
@@ -4537,7 +4547,7 @@ textarea.nodedc-field__control {
|
|||||||
.nodedc-editor-workspace__body {position:relative;flex:1;min-height:0;min-width:0;overflow:hidden;}
|
.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 {position:absolute;inset:0;overflow:auto;overscroll-behavior:contain;isolation:isolate;}
|
||||||
.nodedc-editor-dock__canvas {position:relative;width:100%;height:100%;}
|
.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 {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[hidden] {display:none;}
|
||||||
.nodedc-editor-dock__tool:not([data-floating]) {border-radius:0;box-shadow:none;}
|
.nodedc-editor-dock__tool:not([data-floating]) {border-radius:0;box-shadow:none;}
|
||||||
@@ -4752,3 +4762,9 @@ textarea.nodedc-field__control {
|
|||||||
|
|
||||||
/* A backdrop root on the transparent rail would prevent button glass sampling the scene. */
|
/* 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;}
|
.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; }
|
||||||
|
|||||||
@@ -39,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 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 constrained=constrainDockTree(visibleTree,area,minimums)!;
|
||||||
const rects=dockRects(constrained,area);
|
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 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]);
|
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();},[]);
|
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();},[]);
|
||||||
@@ -57,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;
|
const p=point(e),dx=p.x-g.x,dy=p.y-g.y;
|
||||||
if(!g.moved&&Math.hypot(dx,dy)<6)return;
|
if(!g.moved&&Math.hypot(dx,dy)<6)return;
|
||||||
g.moved=true;
|
g.moved=true;
|
||||||
const b=latest.current.bounds;
|
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):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b);
|
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};
|
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);
|
g.target=g.edge?null:editorDockTarget(visibleBounds,latest.current.rects,primaryId,g.id,p.x,p.y);
|
||||||
setDrag({...g});e.preventDefault();
|
setDrag({...g});e.preventDefault();
|
||||||
@@ -85,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 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 return;
|
||||||
}else if(e.key==='Enter'||e.key===' '){setKeyboard({id,target:null});activate(id);}
|
}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;
|
else return;
|
||||||
e.preventDefault();e.stopPropagation();
|
e.preventDefault();e.stopPropagation();
|
||||||
};
|
};
|
||||||
@@ -102,7 +102,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
|
|||||||
{tools.map(tool=>{
|
{tools.map(tool=>{
|
||||||
const moving=drag?.id===tool.id,free=!rects[tool.id]||moving;
|
const moving=drag?.id===tool.id,free=!rects[tool.id]||moving;
|
||||||
const rect=moving?drag.current:rects[tool.id]??floatingRect(tool.id);
|
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-dock-corners={free?undefined:editorDockCorners(rect,area)} 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}}
|
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)}>
|
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)}>
|
<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)}>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
MousePointer2,
|
MousePointer2,
|
||||||
|
Pipette,
|
||||||
createLucideIcon,
|
createLucideIcon,
|
||||||
Glasses,
|
Glasses,
|
||||||
Cuboid,
|
Cuboid,
|
||||||
@@ -85,6 +86,7 @@ const InformationPlain = createLucideIcon('InformationPlain', [
|
|||||||
['path', {d:'M12 4h.01M10 9h2v11M9 20h6',key:'information'}],
|
['path', {d:'M12 4h.01M10 9h2v11M9 20h6',key:'information'}],
|
||||||
]);
|
]);
|
||||||
const icons = {
|
const icons = {
|
||||||
|
pipette: Pipette,
|
||||||
"add-point": CirclePlus,
|
"add-point": CirclePlus,
|
||||||
ruler: DimensionLine,
|
ruler: DimensionLine,
|
||||||
section: SectionPlane,
|
section: SectionPlane,
|
||||||
|
|||||||
@@ -3,6 +3,10 @@ import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBa
|
|||||||
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
|
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
|
||||||
import { cn } from "./cn.js";
|
import { cn } from "./cn.js";
|
||||||
import { Dropdown } from "./Dropdown.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"> {
|
export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -277,7 +281,27 @@ function hsvToHex({ h, s, v }: Hsv): string {
|
|||||||
|
|
||||||
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, onBlur, onKeyDown, ...props }: ColorFieldProps) {
|
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, onBlur, onKeyDown, ...props }: ColorFieldProps) {
|
||||||
const [draft, setDraft] = useState(value);
|
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]);
|
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 validColor = hexToHsv(value);
|
||||||
const [hsv, setHsv] = useState<Hsv>(() => validColor ?? { h: 330, s: 82, v: 100 });
|
const [hsv, setHsv] = useState<Hsv>(() => validColor ?? { h: 330, s: 82, v: 100 });
|
||||||
const style = { "--nodedc-color-value": validColor ? hsvToHex(validColor) : hsvToHex(hsv) } as CSSProperties;
|
const style = { "--nodedc-color-value": validColor ? hsvToHex(validColor) : hsvToHex(hsv) } as CSSProperties;
|
||||||
@@ -302,6 +326,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
|||||||
<div className={cn("nodedc-color-field", className)} style={style}>
|
<div className={cn("nodedc-color-field", className)} style={style}>
|
||||||
<Dropdown
|
<Dropdown
|
||||||
className="nodedc-color-field__dropdown"
|
className="nodedc-color-field__dropdown"
|
||||||
|
onOpenChange={setPaletteOpen}
|
||||||
placement="bottom-start"
|
placement="bottom-start"
|
||||||
minWidth={296}
|
minWidth={296}
|
||||||
width={296}
|
width={296}
|
||||||
@@ -354,6 +379,10 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
|||||||
<span>Оттенок</span>
|
<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) })} />
|
<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>
|
</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="Быстрые цвета">
|
<div className="nodedc-color-palette__presets" aria-label="Быстрые цвета">
|
||||||
{palettePresets.map((preset) => (
|
{palettePresets.map((preset) => (
|
||||||
<button
|
<button
|
||||||
@@ -371,6 +400,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Dropdown>
|
</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
|
<input
|
||||||
className="nodedc-color-field__text"
|
className="nodedc-color-field__text"
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ export function SplitPane({
|
|||||||
const rootRef = useRef<HTMLDivElement>(null);
|
const rootRef = useRef<HTMLDivElement>(null);
|
||||||
const activePointerIdRef = useRef<number | null>(null);
|
const activePointerIdRef = useRef<number | null>(null);
|
||||||
const [dragging, setDragging] = useState(false);
|
const [dragging, setDragging] = useState(false);
|
||||||
|
const [pointerFocus, setPointerFocus] = useState(false);
|
||||||
const limits = normalizedLimits(minPrimarySize, minSecondarySize);
|
const limits = normalizedLimits(minPrimarySize, minSecondarySize);
|
||||||
const size = clamp(Number.isFinite(primarySize) ? primarySize : 50, limits.minimum, limits.maximum);
|
const size = clamp(Number.isFinite(primarySize) ? primarySize : 50, limits.minimum, limits.maximum);
|
||||||
const keyboardIncrement = Number.isFinite(step) && step > 0 ? step : 2;
|
const keyboardIncrement = Number.isFinite(step) && step > 0 ? step : 2;
|
||||||
@@ -74,6 +75,7 @@ export function SplitPane({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
|
const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
|
||||||
|
setPointerFocus(false);
|
||||||
const multiplier = event.shiftKey ? 5 : 1;
|
const multiplier = event.shiftKey ? 5 : 1;
|
||||||
const decrement = orientation === "vertical" ? "ArrowLeft" : "ArrowUp";
|
const decrement = orientation === "vertical" ? "ArrowLeft" : "ArrowUp";
|
||||||
const increment = orientation === "vertical" ? "ArrowRight" : "ArrowDown";
|
const increment = orientation === "vertical" ? "ArrowRight" : "ArrowDown";
|
||||||
@@ -119,10 +121,13 @@ export function SplitPane({
|
|||||||
aria-valuemax={Math.round(limits.maximum)}
|
aria-valuemax={Math.round(limits.maximum)}
|
||||||
aria-valuenow={Math.round(size)}
|
aria-valuenow={Math.round(size)}
|
||||||
aria-valuetext={`${Math.round(size)}% / ${Math.round(100 - size)}%`}
|
aria-valuetext={`${Math.round(size)}% / ${Math.round(100 - size)}%`}
|
||||||
|
data-pointer-focus={pointerFocus || undefined}
|
||||||
|
onBlur={() => setPointerFocus(false)}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
onPointerDown={(event) => {
|
onPointerDown={(event) => {
|
||||||
if (event.button !== 0) return;
|
if (event.button !== 0) return;
|
||||||
event.currentTarget.focus();
|
setPointerFocus(true);
|
||||||
|
event.currentTarget.focus({ preventScroll: true });
|
||||||
activePointerIdRef.current = event.pointerId;
|
activePointerIdRef.current = event.pointerId;
|
||||||
event.currentTarget.setPointerCapture(event.pointerId);
|
event.currentTarget.setPointerCapture(event.pointerId);
|
||||||
setDragging(true);
|
setDragging(true);
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ export function Tree({nodes,selected,selectedIds,onSelect,onVisibilityChange,lab
|
|||||||
const [collapsed,setCollapsed]=useState<Map<string,boolean>>(()=>new Map());
|
const [collapsed,setCollapsed]=useState<Map<string,boolean>>(()=>new Map());
|
||||||
const [focus,setFocus]=useState<string|null>(null);
|
const [focus,setFocus]=useState<string|null>(null);
|
||||||
const anchor=useRef<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 host=useRef<HTMLDivElement>(null),elements=useRef(new Map<string,HTMLDivElement>());
|
||||||
const parents=new Map<string,string>(),index=new Map<string,TreeNode>();
|
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 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);
|
||||||
@@ -19,15 +21,29 @@ export function Tree({nodes,selected,selectedIds,onSelect,onVisibilityChange,lab
|
|||||||
const rows:{node:TreeNode;depth:number;open:boolean}[]=[];
|
const rows:{node:TreeNode;depth:number;open:boolean}[]=[];
|
||||||
const flatten=(items:TreeNode[],depth=0)=>{for(const node of items){if(!matches(node))continue;const open=!!query||!(collapsed.get(node.id)??depth>=defaultExpandedDepth);rows.push({node,depth,open});if(open)flatten(node.children??[],depth+1);}};flatten(nodes);
|
const 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;};
|
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].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]);
|
// Data/visibility refreshes are not a new selection. An unresolved external
|
||||||
useLayoutEffect(()=>{if(selected)reveal(selected);},[selected,revealKey,query,collapsed]);
|
// selection may wait for async nodes, but a manual disclosure always wins.
|
||||||
const toggle=(id:string)=>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;});
|
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 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];
|
const rangeIds=event.shiftKey&&selectedIds?treeSelectionRange(rows.map(row=>row.node.id),anchor.current,id):[id];
|
||||||
if(!event.shiftKey)anchor.current=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);};
|
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}>
|
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)} onDoubleClick={()=>node.children?.length&&toggle(node.id)} onKeyDown={event=>{
|
{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;
|
if(event.target!==event.currentTarget)return;
|
||||||
let next:string|undefined;
|
let next:string|undefined;
|
||||||
if(event.key==='ArrowDown')next=rows[Math.min(rows.length-1,position+1)]?.node.id;
|
if(event.key==='ArrowDown')next=rows[Math.min(rows.length-1,position+1)]?.node.id;
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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 type ResizeEdge = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
|
||||||
export const windowResizeEdges: 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 };
|
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));
|
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value));
|
||||||
export function fitWindow(rect: WindowRect, bounds: Bounds): WindowRect {
|
export function fitWindow(rect: WindowRect, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
|
||||||
const width = clamp(rect.width, Math.min(320, bounds.width - 16), Math.max(1, bounds.width - 16));
|
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.min(200, bounds.height - 16), Math.max(1, bounds.height - 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)) };
|
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 {
|
export function resizeWindow(rect: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
|
||||||
const r = fitWindow(rect, bounds), right = r.left + r.width, bottom = r.top + r.height;
|
const r = fitWindow(rect, bounds, minimum), 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);
|
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 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 top = edge.includes('n') ? clamp(r.top + dy, 8, bottom - minHeight) : r.top;
|
||||||
const endX = edge.includes('e') ? clamp(right + dx, left + minWidth, bounds.width - 8) : right;
|
const endX = edge.includes('e') ? clamp(right + dx, left + minWidth, bounds.width - 8) : right;
|
||||||
|
|||||||
@@ -332,12 +332,14 @@
|
|||||||
"hue slider",
|
"hue slider",
|
||||||
"quick colors",
|
"quick colors",
|
||||||
"portal palette",
|
"portal palette",
|
||||||
"keyboard spectrum adjustment"
|
"keyboard spectrum adjustment",
|
||||||
|
"explicit screen eyedropper with cancellation; system palette fallback when EyeDropper is unavailable"
|
||||||
],
|
],
|
||||||
"rules": [
|
"rules": [
|
||||||
"Do not expose a browser-native color dialog as the product runtime UI.",
|
|
||||||
"The palette owns choice geometry; the consumer owns color validation, persistence and domain reaction.",
|
"The palette owns choice geometry; the consumer owns color validation, persistence and domain reaction.",
|
||||||
"HEX text keeps incomplete drafts; valid six-digit colors apply live, invalid drafts revert on blur/Escape, Enter commits; external undo updates the field."
|
"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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -545,7 +547,7 @@
|
|||||||
"behavior": [
|
"behavior": [
|
||||||
"controlled percentage",
|
"controlled percentage",
|
||||||
"optional resizable separator",
|
"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",
|
"pointer capture drag",
|
||||||
"Arrow/Home/End keyboard sizing",
|
"Arrow/Home/End keyboard sizing",
|
||||||
"ARIA separator range",
|
"ARIA separator range",
|
||||||
@@ -1138,7 +1140,8 @@
|
|||||||
"The panel variant reuses AdminNavigationPanel pill, icon and theme tokens while retaining the same controlled accordion state and domain-owned content.",
|
"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.",
|
"A section action is a sibling IconButton before the disclosure chevron, never nested in the trigger. It does not toggle the section. Panel chevrons point down when collapsed and up when expanded.",
|
||||||
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts.",
|
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts.",
|
||||||
"Default sections and optional header fields use the canonical 12 px spacing token; footer actions are centered with the same gap. Nested Inspectors retain this rhythm; the panel variant retains its compact row geometry."
|
"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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1294,7 +1297,8 @@
|
|||||||
],
|
],
|
||||||
"summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.",
|
"summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.",
|
||||||
"behavior": [
|
"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",
|
"Arrow/Home/End navigation, disclosure and optional visibility actions",
|
||||||
"long names ellipsize without growing row height",
|
"long names ellipsize without growing row height",
|
||||||
"filter retains matching ancestors",
|
"filter retains matching ancestors",
|
||||||
@@ -1396,6 +1400,7 @@
|
|||||||
"nested adjacent tool splits",
|
"nested adjacent tool splits",
|
||||||
"only exterior workspace corners are rounded; adjoining pane seams remain square and update after dock, resize or close",
|
"only exterior workspace corners are rounded; adjoining pane seams remain square and update after dock, resize or close",
|
||||||
"drag header to detach over primary",
|
"drag header to detach over primary",
|
||||||
|
"floating and dragged tools use canonical scene Glass V4; docking restores tiled surface context",
|
||||||
"invisible resize regions",
|
"invisible resize regions",
|
||||||
"controlled JSON layout",
|
"controlled JSON layout",
|
||||||
"stable mounted renderer",
|
"stable mounted renderer",
|
||||||
@@ -1411,7 +1416,8 @@
|
|||||||
"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.",
|
"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.",
|
"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."
|
"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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
+2
-1
@@ -33,7 +33,8 @@
|
|||||||
"apps",
|
"apps",
|
||||||
"layers",
|
"layers",
|
||||||
"move",
|
"move",
|
||||||
"power"
|
"power",
|
||||||
|
"pipette"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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();});
|
||||||
@@ -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(v,{left:8,top:8,width:264,height:164});
|
||||||
assert.deepEqual(fitWindow(r,bounds),r);
|
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