diff --git a/web/app/src/app/App.tsx b/web/app/src/app/App.tsx index b0cdbcd2d..9b9322fd7 100644 --- a/web/app/src/app/App.tsx +++ b/web/app/src/app/App.tsx @@ -2523,10 +2523,63 @@ function Outliner({ snapshot, areaId, onSelect, onToggleVisibility, onRefresh, o const selectedIds = snapshot ? selectionFromSnapshot(snapshot) : new Set(); const collectionRows = snapshot?.collections ?? []; const [collapsed,setCollapsed]=useState>(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(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 = (rows: readonly T[]): T[] => { + if (!treeQuery && !filterActive) return [...rows]; + const matches = new Set(); + 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(); + 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}]} /> + setTreeSearch(event.target.value)} /> + {treeQuery ? : null} {onRefresh ? : null} {onSelectAll ? <>{(['SELECT', 'DESELECT', 'INVERT', 'TOGGLE'] as const).map((operation, index) => )} : null} + {/* Topmost header slot, so the wider popover below it stays inside the area. */} +
{outlinerFilterOpen ?
: null}
{!tree || !nativeArea ?

Outliner context unavailable

: <> {/* 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); }}> - 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 : null} ; - const fallbackQuery = fallbackSearch.trim().toLowerCase(); - const fallbackAllowed = (() => { - if (!fallbackQuery) return null; - const allowed = new Set(); - const children = new Map(); - 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(); - 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(),rows:{id:string;depth:number;hasChildren:boolean}[]=[],visited=new Set(); 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 (
-
{!tree ? <> setFallbackSearch(event.target.value)} />{fallbackQuery ? : null} : null}
{outlinerFilterOpen ?
: null}
{onRefresh ? : null}{onSelectAll ? <> : null}
-
- {visibleCollections.length === 0 ?
▾{fallbackQuery ? "没有匹配的对象" : "Scene Collection"}
: visibleCollections.map((collection, index) => ( -
-
▾◈{collection.name}
-
- {rowsFor(collection.objectIds).map(({id:objectId,depth,hasChildren}) => { - const node = nodeById.get(objectId); - if (!node) return null; - return
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" : ""}`}> - - {hasChildren?:·} - △{node.name}
; - })} -
-
- ))} +
setTreeSearch(event.target.value)} />{treeQuery ? : null}{onRefresh ? : null}{onSelectAll ? <> : null}
{outlinerFilterOpen ?
: null}
+
+ {fallbackRows.length === 0 ?

{treeQuery || filterActive ? "没有匹配的对象" : "Scene Collection"}

: { + 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
▾◈{row.label}
; + const node = row.objectId ? nodeById.get(row.objectId) : undefined; + if (!node) return null; + return
{ onSelect(node.id, event.ctrlKey || event.metaKey, event.shiftKey); }}> + + {row.hasChildren ? : ·} + △{node.name} + +
; + }} />}
); diff --git a/web/app/src/app/ui/OutlinerTreeView.tsx b/web/app/src/app/ui/OutlinerTreeView.tsx index 4145eefb5..b30859b5e 100644 --- a/web/app/src/app/ui/OutlinerTreeView.tsx +++ b/web/app/src/app/ui/OutlinerTreeView.tsx @@ -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({ 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
{ 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(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(`[role="treeitem"][aria-label="${CSS.escape(label)}"]`)?.focus(); + }, [dataKey]); + return
{ + 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"; }}> { } } }); + + test("searches, filters and clears rows through the shared tree", async ({ page }) => { + await page.goto("/?ui=web"); + await page.locator('[data-testid="blend-file-input"]').setInputFiles(BASIC_SCENE); + await expect(page.locator(".blender-app")).toHaveAttribute("data-project-id", /.+/, { timeout: 60_000 }); + await expect(page.getByText(/Engine: SceneIR/).first()).toBeVisible({ timeout: 60_000 }); + + const webTools = page.locator('[data-testid="native-web-tools-toggle"]'); + if (await webTools.count()) await webTools.click(); + + const tree = page.locator(".outliner-tree").first(); + await expect(tree).toBeVisible({ timeout: 20_000 }); + const items = page.getByRole("treeitem"); + await expect.poll(async () => items.count(), { timeout: 20_000 }).toBeGreaterThan(0); + const before = await items.count(); + + const search = page.locator('input[aria-label="搜索场景"]').first(); + await expect(search).toBeVisible(); + const target = await items.last().getAttribute("aria-label"); + expect(target).toBeTruthy(); + await search.fill(target!); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBeLessThan(before); + await expect(page.locator(`[role="treeitem"][aria-label="${target}"]`).first()).toBeVisible(); + + await page.locator('button[aria-label="清除大纲搜索"]').first().click(); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBe(before); + + await page.locator(".tree-node-name").last().click(); + await expect.poll(async () => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 15_000 }).toBeGreaterThan(0); + + const filterToggle = page.locator('button[aria-label="筛选"]').first(); + await filterToggle.click(); + const filterMenu = page.locator(".outliner-filter-menu").first(); + await expect(filterMenu).toBeVisible(); + await filterMenu.locator('input[type="checkbox"]').nth(1).check(); + await expect(filterToggle).toHaveAttribute("aria-pressed", "true"); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBeLessThan(before); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBeGreaterThan(0); + await filterMenu.getByRole("button", { name: "清除筛选" }).click(); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBe(before); + }); });