feat(web): outliner rows render through one React tree with search and filters
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

Both Outliner surfaces (native workflow rows and the snapshot fallback) now
render through the shared OutlinerTreeView, so the hand-built tree markup in
App.tsx is gone. The toolbar gains a name search, and the filter popover at
the end of the toolbar narrows rows to visible or selected objects; collection
rows join a sidebar-filtered result only as ancestors, so the root cannot keep
every descendant visible. The treeview is keyed on its node set and restores
focus and scroll across that remount. A production spec exercises the search,
clear and filter round trip.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-30 03:12:32 +08:00
parent 8d9bb86f12
commit 3e97d5b645
3 changed files with 179 additions and 55 deletions

View File

@@ -2523,10 +2523,63 @@ function Outliner({ snapshot, areaId, onSelect, onToggleVisibility, onRefresh, o
const selectedIds = snapshot ? selectionFromSnapshot(snapshot) : new Set<string>();
const collectionRows = snapshot?.collections ?? [];
const [collapsed,setCollapsed]=useState<Set<string>>(new Set());
const [fallbackSearch,setFallbackSearch]=useState("");
const [treeSearch,setTreeSearch]=useState("");
/* Outliner filter popover: mirrors the desktop header filter toggles. */
const [outlinerFilterOpen,setOutlinerFilterOpen]=useState(false);
const [outlinerFilter,setOutlinerFilter]=useState({visible:false,selected:false});
const treeQuery = treeSearch.trim().toLocaleLowerCase();
const filterActive = outlinerFilter.visible || outlinerFilter.selected;
/* The filter popover covers the rows underneath it; let any press outside it
* dismiss it, the way the desktop header popup closes on mouse-down. */
const filterRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!outlinerFilterOpen) return;
const dismiss = (event: PointerEvent) => {
if (filterRef.current?.contains(event.target as Node)) return;
event.preventDefault();
event.stopPropagation();
setOutlinerFilterOpen(false);
};
document.addEventListener("pointerdown", dismiss, true);
return () => document.removeEventListener("pointerdown", dismiss, true);
}, [outlinerFilterOpen]);
/* Shared Outliner filter for both surfaces (native rows and snapshot rows):
* keep matches with their ancestors and the descendants of matches so the
* filtered list still forms a valid tree, and open ancestors so a match is
* reachable without leaving the search. */
const filterOutlinerRows = <T extends {id:string;label:string;depth:number;expanded:boolean;objectId?:string|null}>(rows: readonly T[]): T[] => {
if (!treeQuery && !filterActive) return [...rows];
const matches = new Set<string>();
for (const row of rows) {
if (treeQuery && !row.label.toLocaleLowerCase().includes(treeQuery)) continue;
/* A sidebar filter answers "which objects pass", not "which collections":
* collection rows join the result only as ancestors of a matching object.
* Letting them match on their own made the root a match and every
* descendant stayed visible. */
if (filterActive && !row.objectId) continue;
if (row.objectId) {
const node = nodeById.get(row.objectId);
if (outlinerFilter.visible && node && !node.visible) continue;
if (outlinerFilter.selected && !selectedIds.has(row.objectId)) continue;
}
matches.add(row.id);
}
const allowed = new Set(matches);
const openAncestors = new Set<string>();
const stack: Array<{depth:number;id:string}> = [];
for (const row of rows) {
while (stack.length && stack[stack.length-1].depth >= row.depth) stack.pop();
if (matches.has(row.id)) for (const parent of stack) { allowed.add(parent.id); openAncestors.add(parent.id); }
stack.push({depth: row.depth, id: row.id});
}
/* Descendants of a match stay visible, like desktop name filtering. */
let matchDepth = -1;
for (const row of rows) {
if (matchDepth >= 0 && row.depth > matchDepth) { allowed.add(row.id); continue; }
matchDepth = matches.has(row.id) ? row.depth : -1;
}
return rows.filter((row) => allowed.has(row.id)).map((row) => openAncestors.has(row.id) ? {...row, expanded: true} : row);
};
const workflow = snapshot?.editorWorkflow;
const workspace = workflow?.workspaces.find(item => item.id === workflow.context.workspaceId);
const nativeArea = workspace?.areas.find(item => item.editor === 'OUTLINER' &&
@@ -2597,10 +2650,14 @@ function Outliner({ snapshot, areaId, onSelect, onToggleVisibility, onRefresh, o
disabled: remapBusy || treeRenameBusy || !onRemap || !workspace?.writable || !menuTarget?.remapId ||
tree?.remapIds?.filter(id => id.id === menuTarget.remapId).length !== 1,
reason: 'Remap all local usages of this data-block to another one of the same type', action: openRemap}]} />
<input aria-label="搜索场景" placeholder="搜索场景" value={treeSearch} onChange={(event) => setTreeSearch(event.target.value)} />
{treeQuery ? <button type="button" aria-label="清除大纲搜索" onClick={() => setTreeSearch("")}>×</button> : null}
{onRefresh ? <button type="button" aria-label="刷新大纲树" onClick={() => onRefresh()}>↻</button> : null}
{onSelectAll ? <>{(['SELECT', 'DESELECT', 'INVERT', 'TOGGLE'] as const).map((operation, index) =>
<button type="button" key={operation} disabled={!tree} onClick={() => onSelectAll(operation)}>
{['全选', '清除', '反选', '切换'][index]}</button>)}</> : null}
{/* Topmost header slot, so the wider popover below it stays inside the area. */}
<div className="outliner-filter" ref={filterRef}><button type="button" aria-label="筛选" aria-expanded={outlinerFilterOpen} aria-pressed={filterActive} onClick={() => setOutlinerFilterOpen(open => !open)}>⌄</button>{outlinerFilterOpen ? <div className="outliner-filter-menu" role="menu"><label><input type="checkbox" checked={outlinerFilter.visible} onChange={(event) => setOutlinerFilter(current => ({ ...current, visible: event.target.checked }))} />只显示可见对象</label><label><input type="checkbox" checked={outlinerFilter.selected} onChange={(event) => setOutlinerFilter(current => ({ ...current, selected: event.target.checked }))} />只显示选中对象</label><button type="button" disabled={!filterActive} onClick={() => setOutlinerFilter({ visible: false, selected: false })}>清除筛选</button></div> : null}</div>
</div>
{!tree || !nativeArea ? <p role="status">Outliner context unavailable</p> : <>
{/* Desktop OUTLINER_OT_parent_clear: a drop on empty tree space clears the
@@ -2638,7 +2695,7 @@ function Outliner({ snapshot, areaId, onSelect, onToggleVisibility, onRefresh, o
event.preventDefault();
onReparent(ids, null, !event.altKey);
}}>
<OutlinerTreeView rows={tree?.rows ?? []}
<OutlinerTreeView rows={filterOutlinerRows(tree?.rows ?? [])}
onExpand={(rowId) => onToggleExpand?.(rowId, false, nativeArea.id)}
onSelect={(rowId) => onTreeSelect?.(rowId, false, false, nativeArea.id, false, false)}
renderRow={(row, nodeProps) => {
@@ -2818,67 +2875,70 @@ function Outliner({ snapshot, areaId, onSelect, onToggleVisibility, onRefresh, o
</form>
</DesktopDialog> : null}
</div>;
const fallbackQuery = fallbackSearch.trim().toLowerCase();
const fallbackAllowed = (() => {
if (!fallbackQuery) return null;
const allowed = new Set<string>();
const children = new Map<string, string[]>();
for (const node of snapshot?.nodes ?? []) if (node.parentId) children.set(node.parentId, [...(children.get(node.parentId) ?? []), node.id]);
for (const node of snapshot?.nodes ?? []) {
if (!node.name.toLowerCase().includes(fallbackQuery)) continue;
allowed.add(node.id);
let parent = node.parentId;
while (parent) { allowed.add(parent); parent = nodeById.get(parent)?.parentId ?? null; }
const stack = [...(children.get(node.id) ?? [])];
while (stack.length) { const id = stack.pop()!; allowed.add(id); stack.push(...(children.get(id) ?? [])); }
}
return allowed;
})();
const filterActive = outlinerFilter.visible || outlinerFilter.selected;
const allowedIds = (() => {
if (!filterActive) return fallbackAllowed;
const base = fallbackAllowed ?? new Set((snapshot?.nodes ?? []).map((node) => node.id));
const kept = new Set<string>();
for (const node of snapshot?.nodes ?? []) {
if (!base.has(node.id)) continue;
if (outlinerFilter.visible && !node.visible) continue;
if (outlinerFilter.selected && !selectedIds.has(node.id)) continue;
kept.add(node.id);
}
for (const id of [...kept]) { let parent = nodeById.get(id)?.parentId; while (parent) { kept.add(parent); parent = nodeById.get(parent)?.parentId ?? null; } }
return kept;
})();
const visibleCollections = allowedIds ? collectionRows.filter((collection) => collection.objectIds.some((id) => allowedIds.has(id))) : collectionRows;
/* Snapshot rows feed the same tree component the native Outliner uses, so
* both surfaces share one tree implementation (search and filtering
* included) instead of a second hand-built renderer. */
const rowsFor=(objectIds:string[])=>{
const members=new Set(objectIds),children=new Map<string,string[]>(),rows:{id:string;depth:number;hasChildren:boolean}[]=[],visited=new Set<string>();
for(const id of objectIds){const parent=nodeById.get(id)?.parentId;if(parent&&members.has(parent))children.set(parent,[...(children.get(parent)??[]),id]);}
const visit=(id:string,depth:number,hidden=false)=>{if(visited.has(id))return;visited.add(id);const childIds=children.get(id)??[];
if(!hidden&&(!allowedIds||allowedIds.has(id)))rows.push({id,depth,hasChildren:childIds.length>0});
for(const child of childIds)visit(child,depth+1,hidden||collapsed.has(id));
const visit=(id:string,depth:number)=>{if(visited.has(id))return;visited.add(id);const childIds=children.get(id)??[];
rows.push({id,depth,hasChildren:childIds.length>0});
for(const child of childIds)visit(child,depth+1);
};
for(const id of objectIds){const parent=nodeById.get(id)?.parentId;if(!parent||!members.has(parent))visit(id,0);}
for(const id of objectIds)if(!visited.has(id))visit(id,0);
return rows;
};
const fallbackRows = (() => {
type FallbackRow = {id:string;label:string;depth:number;expanded:boolean;selected:boolean;hasChildren:boolean;objectId?:string;collection?:boolean};
const rows: FallbackRow[] = [];
for (const collection of collectionRows) {
rows.push({id:`collection:${collection.id}`,label:collection.name,depth:0,expanded:true,selected:false,hasChildren:false,collection:true});
for (const row of rowsFor(collection.objectIds)) {
const node = nodeById.get(row.id);
if (!node) continue;
rows.push({id:node.id,label:node.name,depth:row.depth+1,expanded:!collapsed.has(node.id),selected:selectedIds.has(node.id),hasChildren:row.hasChildren,objectId:node.id});
}
}
const filtered = filterOutlinerRows(rows);
const groups: Array<{row: FallbackRow; children: FallbackRow[]}> = [];
for (const row of filtered) {
if (row.collection) groups.push({row, children: []});
else groups.at(-1)?.children.push(row);
}
return (treeQuery || filterActive ? groups.filter((group) => group.children.length > 0) : groups)
.flatMap((group) => [group.row, ...group.children]);
})();
return (
<div className="outliner-content">
<div className="outliner-tools">{!tree ? <><input aria-label="搜索场景" placeholder="搜索场景" value={fallbackSearch} onChange={(event) => setFallbackSearch(event.target.value)} />{fallbackQuery ? <button type="button" aria-label="清除大纲搜索" onClick={() => setFallbackSearch("")}>×</button> : null}</> : null}<div className="outliner-filter"><button type="button" aria-label="筛选" aria-expanded={outlinerFilterOpen} aria-pressed={filterActive} onClick={() => setOutlinerFilterOpen(open => !open)}>⌄</button>{outlinerFilterOpen ? <div className="outliner-filter-menu" role="menu"><label><input type="checkbox" checked={outlinerFilter.visible} onChange={(event) => setOutlinerFilter(current => ({ ...current, visible: event.target.checked }))} />只显示可见对象</label><label><input type="checkbox" checked={outlinerFilter.selected} onChange={(event) => setOutlinerFilter(current => ({ ...current, selected: event.target.checked }))} />只显示选中对象</label><button type="button" disabled={!filterActive} onClick={() => setOutlinerFilter({ visible: false, selected: false })}>清除筛选</button></div> : null}</div>{onRefresh ? <button type="button" aria-label="刷新大纲树" onClick={() => onRefresh()}>↻</button> : null}{onSelectAll ? <><button type="button" aria-label="全选大纲对象" onClick={() => onSelectAll('SELECT')}>全选</button><button type="button" aria-label="取消选择大纲对象" onClick={() => onSelectAll('DESELECT')}>清除</button><button type="button" aria-label="反选大纲对象" onClick={() => onSelectAll('INVERT')}>反选</button><button type="button" aria-label="切换大纲选择" onClick={() => onSelectAll('TOGGLE')}>切换</button></> : null}</div>
<div className="outliner-tree" role="tree" aria-label="场景层级" aria-multiselectable="true">
{visibleCollections.length === 0 ? <div className="tree-row collection" role="treeitem" aria-expanded="true"><span>▾</span><strong>{fallbackQuery ? "没有匹配的对象" : "Scene Collection"}</strong></div> : visibleCollections.map((collection, index) => (
<div key={collection.id}>
<div className={index === 0 ? "tree-row collection" : "tree-row"} role="treeitem" aria-expanded="true"><span>▾</span><span className="tree-icon">◈</span><strong>{collection.name}</strong></div>
<div role="group">
{rowsFor(collection.objectIds).map(({id:objectId,depth,hasChildren}) => {
const node = nodeById.get(objectId);
if (!node) return null;
return <div key={node.id} role="treeitem" aria-label={node.name} aria-level={depth+2} aria-expanded={hasChildren?!collapsed.has(node.id):undefined} aria-selected={selectedIds.has(node.id)} tabIndex={0} data-node-id={node.id} data-parent-id={node.parentId??''} data-data-id={node.dataId ?? ""} onClick={(event) => onSelect(node.id, event.ctrlKey || event.metaKey, event.shiftKey)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onSelect(node.id, event.ctrlKey || event.metaKey, event.shiftKey); } }} className={`tree-row child${selectedIds.has(node.id) ? " selected" : ""}`}>
<span className="tree-depth" aria-hidden="true">{'\u00a0\u00a0'.repeat(Math.min(depth,32))}</span>
{hasChildren?<button type="button" className="tree-expand" aria-label={`${collapsed.has(node.id)?'展开':'折叠'} ${node.name}`} onClick={event=>{event.stopPropagation();setCollapsed(current=>{const next=new Set(current);if(next.has(node.id))next.delete(node.id);else next.add(node.id);return next;});}}>{collapsed.has(node.id)?'▸':'▾'}</button>:<span>·</span>}
<span className={`tree-icon ${node.type.toLowerCase()}`}>△</span><span className="tree-node-name">{node.name}</span><button type="button" className="tree-action" aria-label={`${node.visible ? "隐藏" : "显示"} ${node.name}`} onClick={(event) => { event.stopPropagation(); onToggleVisibility(node.id, !node.visible); }}>{node.visible ? "◉" : "○"}</button></div>;
})}
</div>
</div>
))}
<div className="outliner-tools"><input aria-label="搜索场景" placeholder="搜索场景" value={treeSearch} onChange={(event) => setTreeSearch(event.target.value)} />{treeQuery ? <button type="button" aria-label="清除大纲搜索" onClick={() => setTreeSearch("")}>×</button> : null}{onRefresh ? <button type="button" aria-label="刷新大纲树" onClick={() => onRefresh()}>↻</button> : null}{onSelectAll ? <><button type="button" aria-label="全选大纲对象" onClick={() => onSelectAll('SELECT')}>全选</button><button type="button" aria-label="取消选择大纲对象" onClick={() => onSelectAll('DESELECT')}>清除</button><button type="button" aria-label="反选大纲对象" onClick={() => onSelectAll('INVERT')}>反选</button><button type="button" aria-label="切换大纲选择" onClick={() => onSelectAll('TOGGLE')}>切换</button></> : null}<div className="outliner-filter" ref={filterRef}><button type="button" aria-label="筛选" aria-expanded={outlinerFilterOpen} aria-pressed={filterActive} onClick={() => setOutlinerFilterOpen(open => !open)}>⌄</button>{outlinerFilterOpen ? <div className="outliner-filter-menu" role="menu"><label><input type="checkbox" checked={outlinerFilter.visible} onChange={(event) => setOutlinerFilter(current => ({ ...current, visible: event.target.checked }))} />只显示可见对象</label><label><input type="checkbox" checked={outlinerFilter.selected} onChange={(event) => setOutlinerFilter(current => ({ ...current, selected: event.target.checked }))} />只显示选中对象</label><button type="button" disabled={!filterActive} onClick={() => setOutlinerFilter({ visible: false, selected: false })}>清除筛选</button></div> : null}</div></div>
<div className="outliner-tree">
{fallbackRows.length === 0 ? <p role="status">{treeQuery || filterActive ? "没有匹配的对象" : "Scene Collection"}</p> : <OutlinerTreeView rows={fallbackRows} renderRow={(row, nodeProps) => {
const libraryRef = nodeProps.ref as ((element: HTMLDivElement | null) => void) | { current: HTMLDivElement | null } | undefined;
const attachRow = (element: HTMLDivElement | null) => {
if (typeof libraryRef === "function") libraryRef(element);
else if (libraryRef) libraryRef.current = element;
const treeItem = element?.closest('[role="treeitem"]');
if (treeItem) {
treeItem.setAttribute("aria-label", row.label);
treeItem.setAttribute("data-tree-row-id", row.id);
}
};
if (row.collection) return <div {...nodeProps} ref={attachRow} key={row.id} aria-label={row.label} className="tree-row collection"><span>▾</span><span className="tree-icon">◈</span><strong>{row.label}</strong></div>;
const node = row.objectId ? nodeById.get(row.objectId) : undefined;
if (!node) return null;
return <div {...nodeProps} ref={attachRow} key={row.id} aria-label={row.label} data-node-id={node.id} data-parent-id={node.parentId ?? ''} data-data-id={node.dataId ?? ''}
className={`tree-row child${row.selected ? ' selected' : ''}`}
onClick={(event) => { onSelect(node.id, event.ctrlKey || event.metaKey, event.shiftKey); }}>
<span className="tree-depth" aria-hidden="true">{'  '.repeat(Math.min(Math.max(row.depth - 1, 0), 32))}</span>
{row.hasChildren ? <button type="button" className="tree-expand" aria-label={`${row.expanded ? '折叠' : '展开'} ${row.label}`}
onClick={(event) => { event.stopPropagation(); setCollapsed((current) => { const next = new Set(current); if (next.has(node.id)) next.delete(node.id); else next.add(node.id); return next; }); }}>
{row.expanded ? '▾' : '▸'}</button> : <span>·</span>}
<span className={`tree-icon ${node.type.toLowerCase()}`}>△</span><span className="tree-node-name">{node.name}</span>
<button type="button" className="tree-action" aria-label={`${node.visible ? '隐藏' : '显示'} ${node.name}`}
onClick={(event) => { event.stopPropagation(); onToggleVisibility(node.id, !node.visible); }}>{node.visible ? '◉' : '○'}</button>
</div>;
}} />}
</div>
</div>
);

View File

@@ -1,4 +1,4 @@
import { useMemo, useRef, type ReactNode } from "react";
import { useLayoutEffect, useMemo, useRef, type ReactNode } from "react";
import TreeView from "react-accessible-treeview";
import {
buildOutlinerTreeData,
@@ -38,7 +38,30 @@ export function OutlinerTreeView<T extends OutlinerTreeSourceRow>({ rows, ariaLa
* rendered row, so keeping it in the set makes both passes agree. */
const expanded = useMemo(() => [OUTLINER_ROOT_ID, ...expandedRowIds(rows)], [rows]);
const selected = useMemo(() => selectedRowIds(rows), [rows]);
return <div className="outliner-tree-view" onPointerDownCapture={() => { selectSource.current = "pointer"; }} onKeyDownCapture={() => { selectSource.current = "keyboard"; }}>
/* The treeview is keyed on its node set so the library rebuilds its internal
* maps when branches appear or disappear. Keep the user's focus and scroll
* position across that remount; otherwise expanding a branch drops keyboard
* position back to the top of the tree. */
const containerRef = useRef<HTMLDivElement>(null);
const focusState = useRef<{ label: string | null; scrollTop: number }>({ label: null, scrollTop: 0 });
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
container.scrollTop = focusState.current.scrollTop;
const label = focusState.current.label;
if (!label) return;
const active = document.activeElement;
/* Do not steal focus back from another editor after the remount. */
if (active && active !== document.body && !container.contains(active)) return;
container.querySelector<HTMLElement>(`[role="treeitem"][aria-label="${CSS.escape(label)}"]`)?.focus();
}, [dataKey]);
return <div className="outliner-tree-view" ref={containerRef}
onFocusCapture={(event) => {
const row = (event.target as Element | null)?.closest('[role="treeitem"]');
if (row) focusState.current.label = row.getAttribute("aria-label") ?? focusState.current.label;
}}
onScroll={(event) => { focusState.current.scrollTop = event.currentTarget.scrollTop; }}
onPointerDownCapture={() => { selectSource.current = "pointer"; }} onKeyDownCapture={() => { selectSource.current = "keyboard"; }}>
<TreeView
key={dataKey}
data={data}