fix(ui): separate tree visibility from disclosure and preserve scroll

This commit is contained in:
Codex
2026-11-15 12:33:42 +03:00
parent 8b49296efa
commit fea966a3f0
5 changed files with 54 additions and 6 deletions
+1 -1
View File
@@ -2375,7 +2375,7 @@ export function CatalogApp() {
) : null}
<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
open={inspectorOpen}
+2
View File
@@ -511,6 +511,8 @@ The first optional Hold action controls the existing persisted `autoHide` settin
### Tree · compact outliner
Visibility is independent of disclosure. Data/eye updates never re-open selected ancestors or scroll to an old selection. Disclosure uses its arrow (or ArrowLeft/ArrowRight), preserves the scroll position, and does not expand on row double-click. Only a new external selected ID/revealKey requests automatic reveal; asynchronous nodes can complete that pending request.
`Tree` accepts stable `TreeNode` IDs, a selected ID and `onSelect`, optional query and visibility callback. Rows stay on one line with ellipsis. Selection reveals ancestors and scrolls only the tree, avoiding page/camera jumps. Arrow keys, Home/End, Enter/Space support navigation. Use the canonical `Window resizable initialRect` for a movable object outliner.
`Window` end inspectors can opt into `resizable`; the same eight-edge geometry and header Shift+arrow keyboard sizing are used. Existing windows keep their defaults. `DraggableItem` also exposes `activator.attributes` and `activator.listeners` to attach directly to a tile button; separate handles remain the default for existing consumers.
+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 [focus,setFocus]=useState<string|null>(null);
const anchor=useRef<string|null>(null);
const lastReveal=useRef<{selected:string;key:number|undefined}|null>(null),pendingReveal=useRef<string|null>(null);
const disclosureScroll=useRef<number|null>(null);
const host=useRef<HTMLDivElement>(null),elements=useRef(new Map<string,HTMLDivElement>());
const parents=new Map<string,string>(),index=new Map<string,TreeNode>();
const visit=(items:TreeNode[],parent?:string)=>{for(const item of items){index.set(item.id,item);if(parent)parents.set(item.id,parent);visit(item.children??[],item.id);}};visit(nodes);
@@ -19,15 +21,29 @@ export function Tree({nodes,selected,selectedIds,onSelect,onVisibilityChange,lab
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 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]);
useLayoutEffect(()=>{if(selected)reveal(selected);},[selected,revealKey,query,collapsed]);
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;});
// Data/visibility refreshes are not a new selection. An unresolved external
// selection may wait for async nodes, but a manual disclosure always wins.
useLayoutEffect(()=>{
if(!selected){lastReveal.current=null;pendingReveal.current=null;return;}
if(lastReveal.current?.selected===selected&&lastReveal.current.key===revealKey)return;
if(!index.has(selected))return;
lastReveal.current={selected,key:revealKey};pendingReveal.current=selected;setFocus(selected);
setCollapsed(old=>{if([...ancestors].every(id=>old.get(id)===false))return old;const next=new Map(old);for(const id of ancestors)next.set(id,false);return next;});
},[selected,revealKey,nodes]);
useLayoutEffect(()=>{
if(disclosureScroll.current!==null){if(host.current)host.current.scrollTop=disclosureScroll.current;disclosureScroll.current=null;return;}
const id=pendingReveal.current;if(id&&elements.current.has(id)){reveal(id);pendingReveal.current=null;}
},[selected,revealKey,nodes,query,collapsed]);
const toggle=(id:string)=>{
pendingReveal.current=null;disclosureScroll.current=host.current?.scrollTop??null;
setCollapsed(old=>{const next=new Map(old);const depth=rows.find(row=>row.node.id===id)?.depth??0;next.set(id,!(old.get(id)??depth>=defaultExpandedDepth));return next;});
};
const select=(id:string,event:{ctrlKey:boolean;metaKey:boolean;shiftKey:boolean})=>{setFocus(id);
const rangeIds=event.shiftKey&&selectedIds?treeSelectionRange(rows.map(row=>row.node.id),anchor.current,id):[id];
if(!event.shiftKey)anchor.current=id;
onSelect(id,{ctrlKey:event.ctrlKey,metaKey:event.metaKey,shiftKey:event.shiftKey,rangeIds});elements.current.get(id)?.focus({preventScroll:true});reveal(id);};
return <div ref={host} className="nodedc-tree" role="tree" aria-label={label} aria-multiselectable={selectedIds?true:undefined}>
{rows.map(({node,depth,open},position)=><div key={node.id} ref={element=>{if(element)elements.current.set(node.id,element);else elements.current.delete(node.id);}} role="treeitem" aria-level={depth+1} aria-selected={selectedIds?selectedIds.includes(node.id):selected===node.id} aria-expanded={node.children?.length?open:undefined} tabIndex={(focus??selected??rows[0]?.node.id)===node.id?0:-1} className="nodedc-tree__row" style={{'--tree-depth':depth} as CSSProperties} title={node.label} onFocus={()=>setFocus(node.id)} onClick={event=>select(node.id,event)} 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;
let next:string|undefined;
if(event.key==='ArrowDown')next=rows[Math.min(rows.length-1,position+1)]?.node.id;
+2 -1
View File
@@ -1297,7 +1297,8 @@
],
"summary": "Compact hierarchical outliner with single-line rows, selection, visibility and keyboard navigation.",
"behavior": [
"selection expands ancestors and scrolls only the tree container",
"new external selection expands ancestors and scrolls only the tree container",
"visibility/data refresh keeps disclosure state; arrow disclosure keeps scroll position; row double-click does not expand",
"Arrow/Home/End navigation, disclosure and optional visibility actions",
"long names ellipsize without growing row height",
"filter retains matching ancestors",
+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();});