5 Commits
16 changed files with 356 additions and 59 deletions
+5 -2
View File
@@ -1356,6 +1356,7 @@ export function CatalogApp() {
<> <>
<ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow> <ControlRow label="Цвет"><ColorField value={lightColor} onChange={setLightColor} /></ControlRow>
<RangeControl label="Яркость" value={brightness} min={0} max={100} formatValue={(value) => `${value}%`} onChange={setBrightness} /> <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 }} 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> <div style={{ height: 180, display: 'flex', justifyContent: 'flex-end' }} title="Шкала справа: границы слева; фокус подчёркивает выбранную границу"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={sliceBand} min={-1.2} max={51.5} step="any" formatValue={(value) => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={(value) => value.toFixed(1).replace('.', ',')} onChange={setSliceBand} /></div>
<RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} exactValueBounds={{ min: 0 }} formatValue={(value) => `${value}%`} onChange={setGlowDistance} /> <RangeControl label="Дистанция свечения" value={glowDistance} min={0} max={200} exactValueBounds={{ min: 0 }} formatValue={(value) => `${value}%`} onChange={setGlowDistance} />
@@ -1616,7 +1617,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
@@ -2221,6 +2222,8 @@ export function CatalogApp() {
eyebrow="NODE.DC" eyebrow="NODE.DC"
title={studioContext === "applications" ? "Applications" : studioContext === "pages" ? "Page Library" : "Visual Library"} title={studioContext === "applications" ? "Applications" : studioContext === "pages" ? "Page Library" : "Visual Library"}
closeLabel="Закрыть Module Foundry" closeLabel="Закрыть Module Foundry"
collapseLabel="Свернуть панель навигации"
expandLabel="Развернуть панель навигации"
navigationLabel={studioContext === "applications" ? "Application Drafts" : studioContext === "pages" ? "Page Templates" : "Разделы Visual Library"} navigationLabel={studioContext === "applications" ? "Application Drafts" : studioContext === "pages" ? "Page Templates" : "Разделы Visual Library"}
onClose={closeGuideline} onClose={closeGuideline}
headerActions={studioContext === "applications" ? ( headerActions={studioContext === "applications" ? (
@@ -2375,7 +2378,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 -1
View File
@@ -7,7 +7,7 @@ export function EditorDockExample({inWindow=false}:{inWindow?:boolean}){
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:'Материалы',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>}/>}]}/> {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>
+27
View File
@@ -58,6 +58,8 @@ FieldFrame объединяет label, control, hint и description. `labelPlace
## RangeControl ## 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. Вертикальная шкала занимает `0.2 × --nodedc-control-height` (9.2 px при 46 px), вдвое тоньше предыдущей. Прозрачная область захвата не уже 24 px.
Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. `min/max` задают только рабочий диапазон перетаскивания; ручной ввод по умолчанию принимает любое конечное число и не меняет геометрию ползунка. Опциональный `exactValueBounds` независимо задаёт жёсткие границы ручного ввода: например, `{ min: 0 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком. Pill-range с заполнением акцентным цветом, встроенной подписью и значением. Домен определяет min/max/step и формат числа. `min/max` задают только рабочий диапазон перетаскивания; ручной ввод по умолчанию принимает любое конечное число и не меняет геометрию ползунка. Опциональный `exactValueBounds` независимо задаёт жёсткие границы ручного ввода: например, `{ min: 0 }` сохраняет неотрицательное значение, но не ограничивает верхнюю границу ползунком.
@@ -185,6 +187,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 использовали одну геометрию.
@@ -316,6 +320,25 @@ setup-команды, сохранение, API и права принадлеж
`AdminNavigationPanel` поддерживает сортируемые route-items через общий Drag & Drop contract. Приложение передаёт новый порядок id, а панель использует каноническую шеститочечную ручку Engine. Порядок не хранится отдельно внутри navigation-компонента. `AdminNavigationPanel` поддерживает сортируемые route-items через общий Drag & Drop contract. Приложение передаёт новый порядок id, а панель использует каноническую шеститочечную ручку Engine. Порядок не хранится отдельно внутри navigation-компонента.
### Сворачивание левой навигации — общий стандарт
Все левые `AdminNavigationPanel` имеют круглую стрелку рядом с крестиком.
В компактном состоянии остаются круги с иконками и стрелка вправо: заголовок,
подписи, крестик и вторичные действия скрыты, в том числе от клавиатурного фокуса.
Иконки сохраняют доступные имена, выбранный маршрут и Tooltip при наведении/фокусе.
Раскрытие возвращает контекстные селекторы, сортировку и дополнительные действия.
`ApplicationShell` синхронно сжимает колонку до `4.55rem` и расширяет рабочую область
на канонической кривой анимации оболочки; содержимое workspace не перемонтируется.
Состояние общее для переходов между разделами и открытия/закрытия рабочих поверхностей.
Для управляемого состояния: `navigationCollapsed`, `onNavigationCollapsedChange`;
начальное — `defaultNavigationCollapsed`. Без shell панель поддерживает `collapsed`,
`defaultCollapsed`, `onCollapsedChange`. Приоритет внутри shell принадлежит shell.
Библиотека не пишет в localStorage: долговременная персонализация принадлежит приложению.
`collapseLabel`/`expandLabel` локализуют подписи. Footer с каноническим
`nodedc-admin-panel__nav-icon` сохраняет только этот круг. Right/end panel не сужается.
Reduced motion отключает анимацию. На узком экране сохраняется один активный экран.
## ApplicationSidePanel ## ApplicationSidePanel
`ApplicationSidePanel` — правая application-level пара к `AdminNavigationPanel`. `ApplicationSidePanel` — правая application-level пара к `AdminNavigationPanel`.
@@ -509,6 +532,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.
@@ -584,3 +609,5 @@ Tree supports optional controlled `selectedIds` for multi-selection. Its selecti
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. 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. 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.
+2
View File
@@ -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.
+97 -8
View File
@@ -1570,14 +1570,21 @@ textarea.nodedc-field__control {
--nodedc-app-page-pad: 1.25rem; --nodedc-app-page-pad: 1.25rem;
--nodedc-app-panel-gap: 1.25rem; --nodedc-app-panel-gap: 1.25rem;
--nodedc-app-nav-width: clamp(20.75rem, 19.5vw, 22rem); --nodedc-app-nav-width: clamp(20.75rem, 19.5vw, 22rem);
--nodedc-app-nav-current-width: var(--nodedc-app-nav-width);
--nodedc-app-nav-rail-width: 4.55rem;
--nodedc-app-navigation-motion: 440ms cubic-bezier(0.22, 1, 0.36, 1);
--nodedc-app-content-width: calc( --nodedc-app-content-width: calc(
100vw - (var(--nodedc-app-page-pad) * 2) - (var(--nodedc-app-panel-gap) * 2) - (var(--nodedc-app-nav-width) * 2) 100vw - (var(--nodedc-app-page-pad) * 2) - (var(--nodedc-app-panel-gap) * 2) - var(--nodedc-app-nav-current-width) - var(--nodedc-app-nav-width)
); );
min-height: 100vh; min-height: 100vh;
overflow: hidden; overflow: hidden;
background: var(--nodedc-canvas); background: var(--nodedc-canvas);
} }
.nodedc-app-shell[data-navigation-collapsed="true"] {
--nodedc-app-nav-current-width: var(--nodedc-app-nav-rail-width);
}
.nodedc-app-shell__main { .nodedc-app-shell__main {
position: relative; position: relative;
height: calc(100vh - var(--nodedc-app-header-height)); height: calc(100vh - var(--nodedc-app-header-height));
@@ -1612,13 +1619,14 @@ textarea.nodedc-field__control {
.nodedc-app-shell__navigation { .nodedc-app-shell__navigation {
left: var(--nodedc-app-page-pad); left: var(--nodedc-app-page-pad);
width: var(--nodedc-app-nav-width); width: var(--nodedc-app-nav-current-width);
transition: width var(--nodedc-app-navigation-motion);
} }
.nodedc-app-shell__content { .nodedc-app-shell__content {
left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-width) + var(--nodedc-app-panel-gap)); left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-current-width) + var(--nodedc-app-panel-gap));
width: max(32rem, var(--nodedc-app-content-width)); width: max(32rem, var(--nodedc-app-content-width));
transition: width 500ms cubic-bezier(0.22, 1, 0.36, 1), right 500ms cubic-bezier(0.22, 1, 0.36, 1); transition: left var(--nodedc-app-navigation-motion), width var(--nodedc-app-navigation-motion), right var(--nodedc-app-navigation-motion);
} }
.nodedc-app-shell__end-panel { .nodedc-app-shell__end-panel {
@@ -1643,12 +1651,12 @@ textarea.nodedc-field__control {
} }
.nodedc-app-shell[data-navigation-open="true"] .nodedc-app-shell__stage { .nodedc-app-shell[data-navigation-open="true"] .nodedc-app-shell__stage {
padding-left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-width) + var(--nodedc-app-panel-gap)); padding-left: calc(var(--nodedc-app-page-pad) + var(--nodedc-app-nav-current-width) + var(--nodedc-app-panel-gap));
} }
.nodedc-app-shell[data-content-open="true"]:not([data-content-expanded="true"]) .nodedc-app-shell__stage { .nodedc-app-shell[data-content-open="true"]:not([data-content-expanded="true"]) .nodedc-app-shell__stage {
padding-left: calc( padding-left: calc(
var(--nodedc-app-page-pad) + var(--nodedc-app-nav-width) + var(--nodedc-app-panel-gap) + var(--nodedc-app-page-pad) + var(--nodedc-app-nav-current-width) + var(--nodedc-app-panel-gap) +
max(32rem, var(--nodedc-app-content-width)) + var(--nodedc-app-panel-gap) max(32rem, var(--nodedc-app-content-width)) + var(--nodedc-app-panel-gap)
); );
} }
@@ -2130,7 +2138,7 @@ textarea.nodedc-field__control {
padding-right: 3rem; padding-right: 3rem;
} }
.nodedc-admin-panel__sortable-row > .nodedc-drag-handle { .nodedc-admin-panel__sortable-row > span > .nodedc-drag-handle {
position: absolute; position: absolute;
top: 50%; top: 50%;
right: 0.72rem; right: 0.72rem;
@@ -2167,6 +2175,72 @@ textarea.nodedc-field__control {
opacity: 0.82; opacity: 0.82;
} }
/* Shared collapsible left navigation; the right application panel is independent. */
.nodedc-admin-panel--navigation {
--nodedc-app-nav-rail-width: 4.55rem;
transition: width var(--nodedc-app-navigation-motion, 440ms cubic-bezier(0.22, 1, 0.36, 1));
}
.nodedc-admin-panel--navigation .nodedc-admin-panel__head { min-height: 3.55rem; }
.nodedc-admin-panel__titles { min-width: 0; padding-right: 4.5rem; }
.nodedc-admin-panel__titles,
.nodedc-admin-panel__item-label,
.nodedc-admin-panel--navigation .nodedc-admin-context__body,
.nodedc-admin-panel--navigation .nodedc-admin-panel__footer > :not(.nodedc-admin-panel__nav-icon) {
transition: opacity 160ms ease;
}
.nodedc-admin-panel__item-label { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.nodedc-admin-panel__extra-actions { display: contents; }
.nodedc-admin-panel__extra-actions:empty { display: none; }
.nodedc-admin-panel__extra-actions > .nodedc-icon-button { width: 2.92rem; height: 2.92rem; flex-basis: 2.92rem; }
.nodedc-admin-panel__context-area { display: grid; gap: .48rem; }
.nodedc-admin-panel--navigation .nodedc-admin-panel__item-tooltip { display: block; width: 100%; min-width: 0; }
.nodedc-admin-panel--navigation [hidden] { display: none; }
.nodedc-admin-panel--navigation[data-collapsed="true"] { width: var(--nodedc-app-nav-rail-width); }
.nodedc-admin-panel--navigation .nodedc-admin-context__main { width: 100%; }
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__titles { height: 0; }
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__titles,
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__item-label,
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-context__body,
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__footer > :not(.nodedc-admin-panel__nav-icon) {
opacity: 0;
pointer-events: none;
width: 0;
overflow: hidden;
padding: 0;
}
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__head-actions {
left: 0; right: 0; justify-content: center;
}
.nodedc-admin-panel--navigation[data-collapsed="true"] :is(.nodedc-admin-panel__nav-item, .nodedc-admin-panel__footer, .nodedc-admin-context__main) {
justify-content: center; gap: 0; padding-inline: 0;
}
.nodedc-admin-panel--navigation[data-collapsed="true"] :is(.nodedc-admin-panel__nav-item, .nodedc-admin-panel__footer, .nodedc-admin-context) {
background: transparent; box-shadow: none;
}
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-context { grid-template-columns: minmax(0, 1fr); }
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-icon {
position: static; transform: none;
}
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon,
.nodedc-admin-panel--navigation .nodedc-admin-context__main:focus-visible .nodedc-admin-context__icon {
background: var(--nodedc-glass-control-hover); color: var(--nodedc-text-primary);
}
.nodedc-admin-panel--navigation[data-collapsed="true"] :is(.nodedc-admin-panel__nav-item, .nodedc-admin-context__main):focus-visible {
background: transparent; box-shadow: none;
}
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon,
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-context__main:focus-visible .nodedc-admin-context__icon {
background: var(--nodedc-text-primary); color: var(--nodedc-canvas);
}
.nodedc-admin-panel--navigation[data-collapsed="true"] .nodedc-admin-panel__nav-item:focus-visible .nodedc-admin-panel__nav-icon > svg { color: inherit; }
@media (prefers-reduced-motion: reduce) {
.nodedc-admin-panel--navigation,
.nodedc-admin-panel--navigation *,
.nodedc-app-shell__navigation,
.nodedc-app-shell__content,
.nodedc-app-shell__stage { transition: none; animation: none; }
}
.nodedc-dropdown-anchor { .nodedc-dropdown-anchor {
display: inline-flex; display: inline-flex;
} }
@@ -3169,7 +3243,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;
} }
@@ -3874,6 +3950,11 @@ textarea.nodedc-field__control {
width: auto; width: auto;
} }
.nodedc-app-shell[data-navigation-collapsed="true"] .nodedc-app-shell__navigation {
right: auto;
width: var(--nodedc-app-nav-rail-width);
}
.nodedc-app-shell[data-end-panel-open="true"] .nodedc-app-shell__content { .nodedc-app-shell[data-end-panel-open="true"] .nodedc-app-shell__content {
opacity: 0; opacity: 0;
pointer-events: none; pointer-events: none;
@@ -4766,3 +4847,11 @@ textarea.nodedc-field__control {
.nodedc-control-row { grid-template-columns: minmax(0, 1fr); gap: var(--nodedc-space-2); } .nodedc-control-row { grid-template-columns: minmax(0, 1fr); gap: var(--nodedc-space-2); }
} }
.nodedc-editor-dock__tool.nodedc-glass-material { overflow: clip; } .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); }
+56 -34
View File
@@ -1,4 +1,7 @@
import type { HTMLAttributes, ReactNode } from "react"; import {useContext, useState, type HTMLAttributes, type ReactNode} from "react";
import {IconButton} from "./Button.js";
import {NavigationPanelState} from "./NavigationPanelState.js";
import {Tooltip} from "./Tooltip.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import { SortableList } from "./DragDrop.js"; import { SortableList } from "./DragDrop.js";
import { Icon } from "./Icon.js"; import { Icon } from "./Icon.js";
@@ -31,6 +34,12 @@ export interface AdminNavigationPanelProps extends Omit<HTMLAttributes<HTMLEleme
activeId?: string; activeId?: string;
footer?: ReactNode; footer?: ReactNode;
closeLabel?: string; closeLabel?: string;
collapseLabel?: string;
expandLabel?: string;
/** Standalone state. Inside ApplicationShell, use its navigationCollapsed API. */
collapsed?: boolean;
defaultCollapsed?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
navigationLabel?: string; navigationLabel?: string;
onClose: () => void; onClose: () => void;
onItemChange: (id: string) => void; onItemChange: (id: string) => void;
@@ -47,6 +56,11 @@ export function AdminNavigationPanel({
activeId, activeId,
footer, footer,
closeLabel = "Закрыть администрирование", closeLabel = "Закрыть администрирование",
collapseLabel = "Свернуть панель навигации",
expandLabel = "Развернуть панель навигации",
collapsed: controlledCollapsed,
defaultCollapsed = false,
onCollapsedChange,
navigationLabel = "Разделы администрирования", navigationLabel = "Разделы администрирования",
onClose, onClose,
onItemChange, onItemChange,
@@ -54,40 +68,66 @@ export function AdminNavigationPanel({
className, className,
...props ...props
}: AdminNavigationPanelProps) { }: AdminNavigationPanelProps) {
const shell = useContext(NavigationPanelState);
const [localCollapsed, setLocalCollapsed] = useState(defaultCollapsed);
const collapsed = shell?.collapsed ?? controlledCollapsed ?? localCollapsed;
const toggleCollapsed = () => {
const next = !collapsed;
if (shell) shell.onCollapsedChange(next);
else if (controlledCollapsed === undefined) setLocalCollapsed(next);
onCollapsedChange?.(next);
};
const renderItem = (item: AdminNavigationItem) => (
<Tooltip content={item.label} disabled={!collapsed} placement="right-start" className="nodedc-admin-panel__item-tooltip">
<button type="button" className="nodedc-admin-panel__nav-item"
aria-label={item.label} aria-current={activeId === item.id ? "page" : undefined}
data-active={activeId === item.id ? "true" : undefined} onClick={() => onItemChange(item.id)}>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">{item.icon ?? <Icon name="grid" />}</span>
<span className="nodedc-admin-panel__item-label" aria-hidden={collapsed || undefined}>{item.label}</span>
</button>
</Tooltip>
);
return ( return (
<aside className={cn("nodedc-admin-panel", className)} data-has-contexts={contexts.length > 0 || contextSlot ? "true" : undefined} {...props}> <aside className={cn("nodedc-admin-panel", "nodedc-admin-panel--navigation", className)} data-collapsed={collapsed ? "true" : undefined} data-has-contexts={contexts.length > 0 || contextSlot ? "true" : undefined} {...props}>
<header className="nodedc-admin-panel__head"> <header className="nodedc-admin-panel__head">
<div> <div className="nodedc-admin-panel__titles" aria-hidden={collapsed || undefined}>
<p>{eyebrow}</p> <p>{eyebrow}</p>
<h2>{title}</h2> <h2>{title}</h2>
</div> </div>
<div className="nodedc-admin-panel__head-actions"> <div className="nodedc-admin-panel__head-actions">
{headerActions} <span className="nodedc-admin-panel__extra-actions" hidden={collapsed}>{headerActions}</span>
<button type="button" className="nodedc-admin-panel__close" aria-label={closeLabel} onClick={onClose}> <IconButton label={collapsed ? expandLabel : collapseLabel} aria-expanded={!collapsed}
className="nodedc-admin-panel__collapse" onClick={toggleCollapsed}>
<Icon name={collapsed ? "chevron-right" : "chevron-left"} />
</IconButton>
<button hidden={collapsed} type="button" className="nodedc-admin-panel__close" aria-label={closeLabel} onClick={onClose}>
<Icon name="close" size={16} strokeWidth={1.6} /> <Icon name="close" size={16} strokeWidth={1.6} />
</button> </button>
</div> </div>
</header> </header>
{contextSlot ? <div className="nodedc-admin-panel__context-slot">{contextSlot}</div> : null} {contexts.length > 0 || contextSlot ? <div className="nodedc-admin-panel__context-area">
{contextSlot ? <div className="nodedc-admin-panel__context-slot" hidden={collapsed}>{contextSlot}</div> : null}
{contexts.length > 0 ? <div className="nodedc-admin-panel__contexts"> {contexts.length > 0 ? <div className="nodedc-admin-panel__contexts">
{contexts.map((context) => ( {contexts.map((context) => (
<div className="nodedc-admin-panel__context-group" key={context.id}> <div className="nodedc-admin-panel__context-group" key={context.id}>
{context.groupLabel ? <span className="nodedc-admin-panel__group-label">{context.groupLabel}</span> : null} {context.groupLabel ? <span className="nodedc-admin-panel__group-label" hidden={collapsed}>{context.groupLabel}</span> : null}
<div <div
className={cn("nodedc-admin-context", context.onToggle && "nodedc-admin-context--split")} className={cn("nodedc-admin-context", context.onToggle && "nodedc-admin-context--split")}
data-active={context.active ? "true" : undefined} data-active={context.active ? "true" : undefined}
> >
<button type="button" className="nodedc-admin-context__main" onClick={context.onSelect}> <Tooltip content={context.label} disabled={!collapsed} placement="right-start" className="nodedc-admin-panel__item-tooltip">
<span className="nodedc-admin-context__icon" aria-hidden="true">{context.icon}</span> <button type="button" className="nodedc-admin-context__main" aria-label={context.label} onClick={context.onSelect ?? context.onToggle}>
<span className="nodedc-admin-context__body"> <span className="nodedc-admin-context__icon" aria-hidden="true">{context.icon ?? <Icon name="grid" />}</span>
<span className="nodedc-admin-context__body" aria-hidden={collapsed || undefined}>
<strong>{context.label}</strong> <strong>{context.label}</strong>
{context.description ? <small>{context.description}</small> : null} {context.description ? <small>{context.description}</small> : null}
</span> </span>
</button> </button>
</Tooltip>
{context.onToggle ? ( {context.onToggle ? (
<button type="button" className="nodedc-admin-context__toggle" aria-label={`Выбрать: ${context.label}`} onClick={context.onToggle}> <button hidden={collapsed} type="button" className="nodedc-admin-context__toggle" aria-label={`Выбрать: ${context.label}`} onClick={context.onToggle}>
<span className="nodedc-select-trigger__chevron" aria-hidden="true" /> <span className="nodedc-select-trigger__chevron" aria-hidden="true" />
</button> </button>
) : null} ) : null}
@@ -95,20 +135,10 @@ export function AdminNavigationPanel({
</div> </div>
))} ))}
</div> : null} </div> : null}
</div> : null}
<nav className="nodedc-admin-panel__nav" aria-label={navigationLabel}> <nav className="nodedc-admin-panel__nav" aria-label={navigationLabel}>
{items.filter((item) => !item.sortable).map((item) => ( {items.filter((item) => !item.sortable).map((item) => <div key={item.id}>{renderItem(item)}</div>)}
<button
key={item.id}
type="button"
className="nodedc-admin-panel__nav-item"
data-active={activeId === item.id ? "true" : undefined}
onClick={() => onItemChange(item.id)}
>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">{item.icon}</span>
<span>{item.label}</span>
</button>
))}
{items.some((item) => item.sortable) ? ( {items.some((item) => item.sortable) ? (
<SortableList <SortableList
className="nodedc-admin-panel__sortable-nav" className="nodedc-admin-panel__sortable-nav"
@@ -118,23 +148,15 @@ export function AdminNavigationPanel({
> >
{(item, { handle }) => ( {(item, { handle }) => (
<div className="nodedc-admin-panel__sortable-row"> <div className="nodedc-admin-panel__sortable-row">
<button {renderItem(item)}
type="button" <span hidden={collapsed}>{handle}</span>
className="nodedc-admin-panel__nav-item"
data-active={activeId === item.id ? "true" : undefined}
onClick={() => onItemChange(item.id)}
>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">{item.icon}</span>
<span>{item.label}</span>
</button>
{handle}
</div> </div>
)} )}
</SortableList> </SortableList>
) : null} ) : null}
</nav> </nav>
{footer ? <footer className="nodedc-admin-panel__footer">{footer}</footer> : null} {footer ? <footer className="nodedc-admin-panel__footer" aria-hidden={collapsed || undefined}>{footer}</footer> : null}
</aside> </aside>
); );
} }
+18 -2
View File
@@ -1,4 +1,5 @@
import type { HTMLAttributes, ReactNode } from "react"; import {useCallback, useMemo, useState, type HTMLAttributes, type ReactNode} from "react";
import {NavigationPanelState} from "./NavigationPanelState.js";
import { cn } from "./cn.js"; import { cn } from "./cn.js";
import {ApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js"; import {ApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js";
import { Icon, type IconName } from "./Icon.js"; import { Icon, type IconName } from "./Icon.js";
@@ -10,6 +11,10 @@ export interface ApplicationShellProps extends Omit<HTMLAttributes<HTMLDivElemen
content?: ReactNode; content?: ReactNode;
endPanel?: ReactNode; endPanel?: ReactNode;
navigationOpen?: boolean; navigationOpen?: boolean;
/** Shared across navigation routes; closing a workspace does not reset it. */
navigationCollapsed?: boolean;
defaultNavigationCollapsed?: boolean;
onNavigationCollapsedChange?: (collapsed: boolean) => void;
contentOpen?: boolean; contentOpen?: boolean;
contentExpanded?: boolean; contentExpanded?: boolean;
endPanelOpen?: boolean; endPanelOpen?: boolean;
@@ -22,16 +27,27 @@ export function ApplicationShell({
content, content,
endPanel, endPanel,
navigationOpen = false, navigationOpen = false,
navigationCollapsed,
defaultNavigationCollapsed = false,
onNavigationCollapsedChange,
contentOpen = false, contentOpen = false,
contentExpanded = false, contentExpanded = false,
endPanelOpen = false, endPanelOpen = false,
className, className,
...props ...props
}: ApplicationShellProps) { }: ApplicationShellProps) {
const [localCollapsed, setLocalCollapsed] = useState(defaultNavigationCollapsed);
const collapsed = navigationCollapsed ?? localCollapsed;
const onCollapsedChange = useCallback((next: boolean) => {
if (navigationCollapsed === undefined) setLocalCollapsed(next);
onNavigationCollapsedChange?.(next);
}, [navigationCollapsed, onNavigationCollapsedChange]);
const navigationState = useMemo(() => ({collapsed, onCollapsedChange}), [collapsed, onCollapsedChange]);
return ( return (
<div <div
className={cn("nodedc-app-shell", className)} className={cn("nodedc-app-shell", className)}
data-navigation-open={navigationOpen ? "true" : undefined} data-navigation-open={navigationOpen ? "true" : undefined}
data-navigation-collapsed={collapsed ? "true" : undefined}
data-content-open={contentOpen ? "true" : undefined} data-content-open={contentOpen ? "true" : undefined}
data-content-expanded={contentOpen && contentExpanded ? "true" : undefined} data-content-expanded={contentOpen && contentExpanded ? "true" : undefined}
data-end-panel-open={endPanelOpen ? "true" : undefined} data-end-panel-open={endPanelOpen ? "true" : undefined}
@@ -40,7 +56,7 @@ export function ApplicationShell({
{header} {header}
<main className="nodedc-app-shell__main"> <main className="nodedc-app-shell__main">
<div className="nodedc-app-shell__stage">{stage}</div> <div className="nodedc-app-shell__stage">{stage}</div>
{navigationOpen && navigation ? <div className="nodedc-app-shell__navigation">{navigation}</div> : null} {navigationOpen && navigation ? <div className="nodedc-app-shell__navigation"><NavigationPanelState.Provider value={navigationState}>{navigation}</NavigationPanelState.Provider></div> : null}
{contentOpen && content ? <div className="nodedc-app-shell__content">{content}</div> : null} {contentOpen && content ? <div className="nodedc-app-shell__content">{content}</div> : null}
{endPanel ? <div className="nodedc-app-shell__end-panel">{endPanel}</div> : null} {endPanel ? <div className="nodedc-app-shell__end-panel">{endPanel}</div> : null}
</main> </main>
+1 -1
View File
@@ -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)}>
@@ -0,0 +1,7 @@
import {createContext} from "react";
/** The shell owns rail width and panel presentation as one state. */
export const NavigationPanelState = createContext<{
collapsed: boolean;
onCollapsedChange: (collapsed: boolean) => void;
} | null>(null);
+14
View File
@@ -11,6 +11,8 @@ 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;
orientation?: "horizontal" | "vertical"; orientation?: "horizontal" | "vertical";
/** Thin horizontal single-value rail; no containing surface or exact editor. */
variant?: "field" | "rail";
value: number; value: number;
min: number; min: number;
max: number; max: number;
@@ -73,6 +75,7 @@ export function RangeControl(props: RangeControlProps | RangeBandControlProps) {
function SingleRangeControl({ function SingleRangeControl({
label, label,
orientation = "horizontal", orientation = "horizontal",
variant = "field",
value, value,
min, min,
max, max,
@@ -159,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 ( if (orientation === "vertical") return (
<div className="nodedc-range-scale" data-limit-side={limitSide} style={style}> <div className="nodedc-range-scale" data-limit-side={limitSide} style={style}>
<div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical"> <div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical">
+6 -1
View File
@@ -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);
+20 -4
View File
@@ -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;
+13 -6
View File
@@ -312,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.", "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.", "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.", "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."
] ]
}, },
{ {
@@ -547,7 +548,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",
@@ -778,6 +779,7 @@
"rules": [ "rules": [
"The bottom Launcher service rail is product-specific and is not part of the general application template.", "The bottom Launcher service rail is product-specific and is not part of the general application template.",
"Desktop page gap is 20 px and navigation width follows the Launcher 332–352 px range.", "Desktop page gap is 20 px and navigation width follows the Launcher 332–352 px range.",
"Shared navigationCollapsed state contracts the left column to a 4.55rem icon rail, preserves workspace identity and leaves the end column full-width. Width and content offset animate together with reduced-motion support.",
"Applications supply routes, profile data, stage media and panel content without changing shell geometry.", "Applications supply routes, profile data, stage media and panel content without changing shell geometry.",
"Light panels use the SEO white surface and shadow tokens rather than a dark shell with inverted text.", "Light panels use the SEO white surface and shadow tokens rather than a dark shell with inverted text.",
"A layout-level save action belongs to ApplicationPanel.utilityActions and is never duplicated inside individual content cards.", "A layout-level save action belongs to ApplicationPanel.utilityActions and is never duplicated inside individual content cards.",
@@ -866,10 +868,10 @@
"domContract": [ "domContract": [
"nodedc-admin-panel" "nodedc-admin-panel"
], ],
"summary": "Hub-derived left administration panel with context selectors, route navigation, close action and footer identity.", "summary": "Shared collapsible left administration panel with context selectors, accessible icon rail, route navigation and footer identity.",
"anatomy": [ "anatomy": [
"eyebrow and title", "eyebrow and title",
"close action", "collapse/expand and close actions",
"workspace context", "workspace context",
"company context", "company context",
"route items", "route items",
@@ -878,7 +880,10 @@
"rules": [ "rules": [
"The panel shell, full-bleed pills and icon circles are library geometry; routes and identity data remain application-owned.", "The panel shell, full-bleed pills and icon circles are library geometry; routes and identity data remain application-owned.",
"The desktop panel follows the Launcher 332–352 px width range with a 21.6 px shell radius and a 20 px page gap.", "The desktop panel follows the Launcher 332–352 px width range with a 21.6 px shell radius and a 20 px page gap.",
"Active route state uses the active surface and icon contrast from the theme." "Active route state uses the active surface and icon contrast from the theme.",
"All left navigation panels collapse to the shared 4.55rem icon rail; title, labels, close and secondary actions disappear. Icon names and hover/focus tooltips remain.",
"ApplicationShell owns synchronized rail/content width and route-independent collapse state without remounting the workspace. Right panels retain their width.",
"Use shell navigationCollapsed/onNavigationCollapsedChange for controlled state; standalone panels accept collapsed/onCollapsedChange. Respect reduced motion."
] ]
}, },
{ {
@@ -1297,7 +1302,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",
@@ -1399,6 +1405,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",
+48
View File
@@ -0,0 +1,48 @@
const fs = require('node:fs'), path = require('node:path'), os = require('node:os'), assert = require('node:assert/strict');
const root = process.env.DG_ROOT || path.resolve(__dirname, '..');
const {JSDOM} = require('jsdom'), React = require(root + '/node_modules/react'), {act} = React;
const {createRoot} = require(root + '/node_modules/react-dom/client');
const dom = new JSDOM('<div id="app"></div>', {pretendToBeVisual: true});
for (const name of ['window','document','HTMLElement','Element','Node','Event','MouseEvent','KeyboardEvent','CustomEvent']) global[name] = dom.window[name];
global.ResizeObserver = class {observe() {} disconnect() {}};
global.IS_REACT_ACT_ENVIRONMENT = true;
HTMLElement.prototype.getBoundingClientRect = () => ({top: 20, bottom: 60, left: 20, right: 80, width: 60, height: 40});
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'nodedc-sidebar-'));
require(root + '/node_modules/esbuild').buildSync({stdin: {contents: `export {AdminNavigationPanel} from './AdminNavigationPanel.tsx'; export {ApplicationShell} from './ApplicationShell.tsx';`, resolveDir: root + '/packages/ui-react/src'}, outfile: scratch + '/sidebar.cjs', bundle: true, platform: 'node', format: 'cjs', external: ['react','react/*','react-dom','react-dom/*'], jsx: 'automatic'});
const {ApplicationShell, AdminNavigationPanel} = require(scratch + '/sidebar.cjs');
const ui = createRoot(document.getElementById('app')), h = React.createElement;
let selected = 'one', section = 'Data', open = true, mounts = 0, closes = 0, notified = [];
function Workspace() {React.useEffect(() => {mounts++;}, []); return h('input', {defaultValue: 'keep draft', 'aria-label': 'Draft'});}
const panel = () => h(AdminNavigationPanel, {key: section, title: section, onClose: () => closes++, closeLabel: 'Close navigation', activeId: selected, onItemChange: id => selected = id, contexts: [{id: 'context', label: 'Context', onToggle: () => {}, icon: 'C'}], headerActions: h('button', null, 'Extra'), items: [{id: 'one', label: 'One', icon: '1'}, {id: 'two', label: 'Two', icon: '2', sortable: true}], onItemsReorder: () => {}});
const render = (extra = {}) => act(async () => ui.render(h(ApplicationShell, {header: null, stage: null, navigation: panel(), navigationOpen: open, contentOpen: true, contentExpanded: true, content: h(Workspace), endPanel: h('div', {'data-testid': 'right'}, 'Right'), onNavigationCollapsedChange: value => notified.push(value), ...extra})));
const button = label => [...document.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === label);
const click = el => act(async () => el.dispatchEvent(new MouseEvent('click', {bubbles: true})));
const shell = () => document.querySelector('.nodedc-app-shell');
(async () => {
await render(); const draft = document.querySelector('input'); draft.value = 'unsaved text';
await click(button('Свернуть панель навигации'));
assert.equal(shell().dataset.navigationCollapsed, 'true');
assert.equal(document.querySelector('aside').dataset.collapsed, 'true');
assert.equal(button('Развернуть панель навигации').getAttribute('aria-expanded'), 'false');
assert(button('Close navigation').hidden); assert.equal(closes, 0);
assert(button('Выбрать: Context').hidden); assert(document.querySelector('.nodedc-admin-panel__extra-actions').hidden);
assert.equal(button('One').getAttribute('aria-current'), 'page');
await click(button('Two')); assert.equal(selected, 'two');
section = 'System'; await render(); assert.equal(document.querySelector('aside').dataset.collapsed, 'true', 'new root uses retained shell state');
open = false; await render(); open = true; await render(); assert.equal(document.querySelector('aside').dataset.collapsed, 'true', 'close/reopen preserves rail');
await act(async () => button('Two').focus()); assert.equal(document.querySelector('[role=tooltip]').textContent, 'Two');
await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape', bubbles: true})));
assert.equal(document.querySelector('[role=tooltip]'), null); assert.equal(closes, 0, 'Escape closes tooltip only');
await click(button('Развернуть панель навигации')); assert.equal(shell().dataset.navigationCollapsed, undefined);
assert.equal(button('Close navigation').hidden, false);
assert.equal(mounts, 1); assert.equal(document.querySelector('input'), draft); assert.equal(draft.value, 'unsaved text');
assert.deepEqual(notified, [true, false]);
await render({navigationCollapsed: false}); await click(button('Свернуть панель навигации'));
assert.equal(shell().dataset.navigationCollapsed, undefined, 'controlled shell awaits owner acceptance');
await render({navigationCollapsed: true}); assert.equal(document.querySelector('aside').dataset.collapsed, 'true');
assert.equal(document.querySelector('[data-testid=right]').textContent, 'Right');
await act(async () => ui.render(h(AdminNavigationPanel, {title: 'Standalone', items: [], onClose: () => {}, onItemChange: () => {}, defaultCollapsed: true})));
assert(button('Развернуть панель навигации')); await click(button('Развернуть панель навигации')); assert(button('Свернуть панель навигации'));
await act(async () => ui.unmount());
console.log('PASS: shared/standalone/controlled collapse, root and reopen persistence, hidden actions, icon navigation, accessible names and Escape tooltip, workspace remains mounted with its draft.');
})().catch(e => {console.error(e); process.exitCode = 1;}).finally(() => {fs.rmSync(scratch, {recursive: true, force: true}); dom.window.close();});
+12
View File
@@ -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, 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]); 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/);
}
});
+29
View File
@@ -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();});