Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(outliner): unify editor/PIE tree on a virtualized, headless-controlled path

esengine81373edf3700
diff --git a/desktop/src/components/VirtualTree.tsx b/desktop/src/components/VirtualTree.tsx
new file mode 100644
index 000000000..d4d8c2e92
--- /dev/null
+++ b/desktop/src/components/VirtualTree.tsx
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file VirtualTree.tsx — a windowed fixed-height list.
+ *
+ * Renders only the rows in the scroll window (plus overscan) over a spacer sized
+ * to the full list, so a tree of thousands of entities stays a handful of DOM
+ * nodes. The list MUST already be flattened to render order (see
+ * {@link buildOutlinerItems}); this owns no hierarchy — just the scroll window.
+ * Shared by the editor + PIE outliner trees (one virtualization path).
+ *
+ * Extra props (className / onDragOver / onDrop / …) spread onto the scroll
+ * container, so the outliner can attach empty-space drag-drop to it.
+ */
+import {
+ useEffect,
+ useRef,
+ useState,
+ type HTMLAttributes,
+ type Key,
+ type ReactNode,
+} from 'react';
+
+interface VirtualTreeProps<T> extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
+ items: T[];
+ rowHeight: number;
+ /** Rows kept rendered just outside the window (smooths fast scroll). */
+ overscan?: number;
+ renderRow: (item: T, index: number) => ReactNode;
+ getKey: (item: T, index: number) => Key;
+}
+
+export function VirtualTree<T>({
+ items,
+ rowHeight,
+ overscan = 8,
+ renderRow,
+ getKey,
+ onScroll,
+ ...rest
+}: VirtualTreeProps<T>) {
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const [scrollTop, setScrollTop] = useState(0);
+ const [viewH, setViewH] = useState(600);
+
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ const update = () => setViewH(el.clientHeight);
+ update();
+ const ro = new ResizeObserver(update);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ const total = items.length;
+ const start = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
+ const end = Math.min(total, Math.ceil((scrollTop + viewH) / rowHeight) + overscan);
+
+ return (
+ <div
+ ref={scrollRef}
+ {...rest}
+ onScroll={(e) => {
+ setScrollTop(e.currentTarget.scrollTop);
+ onScroll?.(e);
+ }}
+ >
+ <div style={{ height: total * rowHeight, position: 'relative' }}>
+ {items.slice(start, end).map((item, i) => {
+ const index = start + i;
+ return (
+ <div
+ key={getKey(item, index)}
+ style={{ position: 'absolute', top: index * rowHeight, left: 0, right: 0, height: rowHeight }}
+ >
+ {renderRow(item, index)}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/desktop/src/outliner/OutlinerController.ts b/desktop/src/outliner/OutlinerController.ts
new file mode 100644
index 000000000..3b882d6ca
--- /dev/null
+++ b/desktop/src/outliner/OutlinerController.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file OutlinerController.ts — the outliner's headless view-state.
+ *
+ * Owns the editor-tree state the SceneModel doesn't: which nodes are expanded and
+ * the search query. Kept OUT of the React panel so the tree is testable headless
+ * and (later) drivable by EditorControlSurface / the editor MCP — the panel is a
+ * thin renderer over this + {@link buildOutlinerItems}.
+ *
+ * Model-anchored self-healing (mirrors selectionStore): expansion is pruned when
+ * an entity is removed (`entityRemoved`) and the whole view resets on a scene swap
+ * (`reset`), so the expansion set can never accumulate dead ids. One per
+ * EditorSession; the default instance binds the app's SceneModel.
+ */
+import { create } from 'zustand';
+import { SceneModel, SceneModelImpl } from '@/engine/SceneModel';
+import type { EntityId } from '@/types';
+
+interface OutlinerState {
+ /** Expanded node ids (entity source ids). */
+ expanded: Set<EntityId>;
+ /** Live name filter (raw text; the builder trims/lowercases). */
+ query: string;
+
+ /** Flip one node's expansion. */
+ toggleExpanded: (id: EntityId) => void;
+ /** Replace the whole expansion set (e.g. first-load auto-expand). */
+ setExpanded: (ids: EntityId[]) => void;
+ /** Additively expand ids (reveal — keeps existing expansion). */
+ expand: (ids: EntityId[]) => void;
+ /** Expand every ancestor of an entity so it becomes visible (reveal-on-select). */
+ revealEntity: (id: EntityId) => void;
+ setQuery: (query: string) => void;
+
+ /** Prune a removed id (self-heal on the model's `entityRemoved`). */
+ dropId: (id: EntityId) => void;
+ /** Reset the view on a scene swap (the model's `reset`). */
+ reset: () => void;
+}
+
+/** Build an outliner controller bound to a model. One per EditorSession. */
+export function createOutlinerStore(model: SceneModelImpl) {
+ const useStore = create<OutlinerState>((set) => ({
+ expanded: new Set<EntityId>(),
+ query: '',
+
+ toggleExpanded: (id) =>
+ set((s) => {
+ const next = new Set(s.expanded);
+ next.has(id) ? next.delete(id) : next.add(id);
+ return { expanded: next };
+ }),
+ setExpanded: (ids) => set({ expanded: new Set(ids) }),
+ expand: (ids) =>
+ set((s) => {
+ const next = new Set(s.expanded);
+ for (const id of ids) next.add(id);
+ return { expanded: next };
+ }),
+ revealEntity: (id) =>
+ set((s) => {
+ const next = new Set(s.expanded);
+ // Walk parents (not the node itself — revealing means its ancestors open).
+ let cur = model.entityBySource(id)?.parent ?? null;
+ const seen = new Set<number>();
+ while (cur != null && !seen.has(cur)) {
+ seen.add(cur);
+ next.add(cur);
+ cur = model.entityBySource(cur)?.parent ?? null;
+ }
+ return { expanded: next };
+ }),
+ setQuery: (query) => set({ query }),
+
+ dropId: (id) =>
+ set((s) => {
+ if (!s.expanded.has(id)) return s;
+ const next = new Set(s.expanded);
+ next.delete(id);
+ return { expanded: next };
+ }),
+ reset: () => set({ expanded: new Set(), query: '' }),
+ }));
+
+ model.subscribe((ev) => {
+ if (ev.kind === 'entityRemoved') useStore.getState().dropId(ev.sourceId);
+ else if (ev.kind === 'reset') useStore.getState().reset();
+ });
+
+ return useStore;
+}
+
+/** The app's default-session outliner controller. Other sessions build their own. */
+export const useOutliner = createOutlinerStore(SceneModel);
diff --git a/desktop/src/outliner/OutlinerModel.ts b/desktop/src/outliner/OutlinerModel.ts
new file mode 100644
index 000000000..208b7509b
--- /dev/null
+++ b/desktop/src/outliner/OutlinerModel.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file OutlinerModel.ts — the ONE outliner tree builder.
+ *
+ * Flattens a SceneData into a render-ordered list of {@link OutlinerItem}s,
+ * honoring the expansion set + a name filter. The same builder feeds the editor
+ * tree (the model SceneData) and the live PIE "Game" tree (a PlayInspect
+ * snapshot) — one path, virtualization-ready (the list IS the render order, so a
+ * windowed list renders only the visible slice). This replaces the panel's old
+ * recursive `<Row>` walk + its separate PIE flatten.
+ *
+ * Hierarchy comes from {@link buildSceneTree} (derived from each entity's
+ * `parent`, robust to a drifted `children[]`), so this stays a pure projection.
+ * The item shape is folder-aware (`kind`) for the path-folder phase; P1 emits
+ * only `entity` items.
+ */
+import type { SceneData } from 'esengine';
+import type { SceneNode, EntityId } from '@/types';
+import { buildSceneTree } from '@/engine/SceneQuery';
+
+export type OutlinerItemKind = 'entity' | 'folder';
+
+/** One row of the flattened outliner — a tree node placed at render order/depth. */
+export interface OutlinerItem {
+ /** Entity source id (editor) or realm runtime id (PIE). */
+ id: EntityId;
+ /** Stable React key (`e<id>`; folders later carry a path-derived key). */
+ key: string;
+ kind: OutlinerItemKind;
+ /** The view-model node (name / kind / visible / locked / children). */
+ node: SceneNode;
+ depth: number;
+ hasChildren: boolean;
+ /** Whether this node's children are shown (drives the twist + the walk). */
+ expanded: boolean;
+ parentId: EntityId | null;
+}
+
+export interface BuildOutlinerOpts {
+ /** Currently-expanded node ids. Ignored when `expandAll` (or a filter) is on. */
+ expanded: ReadonlySet<EntityId>;
+ /** Free-text name filter; matches + their ancestors survive (case-insensitive). */
+ query?: string;
+ /** Render every node expanded — the PIE tree, and implicitly while filtering. */
+ expandAll?: boolean;
+}
+
+/** Keep a node if its name matches, or any descendant does (matches + ancestors). */
+function filterNode(node: SceneNode, q: string): SceneNode | null {
+ if (node.name.toLowerCase().includes(q)) return node;
+ const kids = (node.children ?? [])
+ .map((c) => filterNode(c, q))
+ .filter((n): n is SceneNode => n != null);
+ return kids.length ? { ...node, children: kids } : null;
+}
+
+/** Flatten a SceneData to render-ordered outliner rows (the single tree builder). */
+export function buildOutlinerItems(data: SceneData | null, opts: BuildOutlinerOpts): OutlinerItem[] {
+ const roots = buildSceneTree(data);
+ const q = opts.query?.trim().toLowerCase() ?? '';
+ const shown = q ? roots.map((n) => filterNode(n, q)).filter((n): n is SceneNode => n != null) : roots;
+ // A live filter force-expands so every surviving match is visible.
+ const expandAll = !!opts.expandAll || !!q;
+
+ const out: OutlinerItem[] = [];
+ const walk = (nodes: SceneNode[], depth: number, parentId: EntityId | null): void => {
+ for (const node of nodes) {
+ const hasChildren = !!node.children?.length;
+ const expanded = expandAll || opts.expanded.has(node.id);
+ out.push({ id: node.id, key: `e${node.id}`, kind: 'entity', node, depth, hasChildren, expanded, parentId });
+ if (hasChildren && expanded) walk(node.children!, depth + 1, node.id);
+ }
+ };
+ walk(shown, 0, null);
+ return out;
+}
+
+/** All node ids that have children — the auto-expand set for a freshly-loaded scene. */
+export function collectExpandableIds(data: SceneData | null): EntityId[] {
+ const out: EntityId[] = [];
+ const walk = (nodes: SceneNode[]): void => {
+ for (const n of nodes) {
+ if (n.children?.length) {
+ out.push(n.id);
+ walk(n.children);
+ }
+ }
+ };
+ walk(buildSceneTree(data));
+ return out;
+}
diff --git a/desktop/src/outliner/OutlinerRow.tsx b/desktop/src/outliner/OutlinerRow.tsx
new file mode 100644
index 000000000..7399e565c
--- /dev/null
+++ b/desktop/src/outliner/OutlinerRow.tsx
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file OutlinerRow.tsx — the ONE outliner row, shared by the editor + PIE trees.
+ *
+ * Purely presentational: selection / rename / drop / prefab state arrive as props
+ * (it does NOT subscribe to any store), so with virtualization only the ~window of
+ * visible rows ever renders or re-renders. Editor-only affordances (visibility
+ * toggle, rename, drag-drop) are gated on their handlers being present — the PIE
+ * tree passes none and gets a click-to-select read-only row.
+ */
+import type React from 'react';
+import { ChevronRight, Eye, EyeOff, Lock } from 'lucide-react';
+import { NodeIcon } from '@/components/icons';
+import type { EntityId, NodeKind } from '@/types';
+import type { OutlinerItem } from './OutlinerModel';
+
+/** Entity kind → the label shown in the outliner's right-hand "Type" column. */
+const KIND_TYPE: Record<NodeKind, string> = {
+ camera: 'Camera',
+ sprite: 'Sprite',
+ spine: 'Spine',
+ physics: 'Physics',
+ ui: 'UI',
+ audio: 'Audio',
+ group: 'Group',
+ light: 'Light',
+ empty: 'Entity',
+};
+
+export interface OutlinerRowProps {
+ item: OutlinerItem;
+ selected: boolean;
+ renaming?: boolean;
+ isDrop?: boolean;
+ /** Prefab-instance member — warm icon tint (editor only). */
+ prefab?: boolean;
+ /** When false, the twist is hidden + non-interactive (the always-expanded PIE tree). */
+ collapsible?: boolean;
+ onToggle: (id: EntityId) => void;
+ onClick: (id: EntityId, e: React.MouseEvent) => void;
+ onContextMenu?: (e: React.MouseEvent, id: EntityId) => void;
+ onStartRename?: (id: EntityId) => void;
+ onCommitRename?: (id: EntityId, name: string) => void;
+ onToggleVisible?: (id: EntityId, visible: boolean) => void;
+ draggable?: boolean;
+ onDragStart?: (id: EntityId, e: React.DragEvent) => void;
+ onDragOver?: (id: EntityId, e: React.DragEvent) => void;
+ onDrop?: (id: EntityId, e: React.DragEvent) => void;
+}
+
+export function OutlinerRow(props: OutlinerRowProps) {
+ const { item, selected, renaming, isDrop, prefab } = props;
+ const { node, depth, hasChildren, expanded } = item;
+
+ // Right-column type: prefab instances read "Prefab", others by kind, suffixed
+ // with the child count when it has any.
+ const childCount = node.children?.length ?? 0;
+ const baseType = prefab ? 'Prefab' : (KIND_TYPE[node.kind] ?? 'Entity');
+ const typeLabel = childCount > 0 ? `${baseType} · ${childCount}` : baseType;
+
+ const canRename = !!props.onCommitRename;
+ const showVis = !!props.onToggleVisible;
+ const collapsible = props.collapsible !== false;
+ const showTwist = hasChildren && collapsible;
+
+ return (
+ <div
+ className={
+ `row${selected ? ' sel' : ''}` +
+ `${expanded ? ' open' : ''}` +
+ `${node.visible ? '' : ' hidden'}` +
+ `${prefab ? ' prefab' : ''}` +
+ `${isDrop ? ' drop' : ''}`
+ }
+ style={{ paddingLeft: depth * 14 }}
+ draggable={props.draggable && !renaming}
+ onClick={(e) => props.onClick(node.id, e)}
+ onContextMenu={props.onContextMenu ? (e) => props.onContextMenu!(e, node.id) : undefined}
+ onDragStart={props.onDragStart ? (e) => props.onDragStart!(node.id, e) : undefined}
+ onDragOver={props.onDragOver ? (e) => props.onDragOver!(node.id, e) : undefined}
+ onDrop={props.onDrop ? (e) => props.onDrop!(node.id, e) : undefined}
+ >
+ <span
+ className={`twist${showTwist ? '' : ' leaf'}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (showTwist) props.onToggle(node.id);
+ }}
+ >
+ <ChevronRight size={9} strokeWidth={3} />
+ </span>
+
+ <span className="ricon">
+ <NodeIcon kind={node.kind} />
+ </span>
+
+ {renaming && canRename ? (
+ <input
+ className="rname-edit"
+ defaultValue={node.name}
+ autoFocus
+ spellCheck={false}
+ onClick={(e) => e.stopPropagation()}
+ onFocus={(e) => e.target.select()}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
+ else if (e.key === 'Escape') {
+ e.currentTarget.value = node.name;
+ e.currentTarget.blur();
+ }
+ }}
+ onBlur={(e) => props.onCommitRename!(node.id, e.target.value)}
+ />
+ ) : (
+ <span
+ className="rname"
+ onDoubleClick={canRename && props.onStartRename ? () => props.onStartRename!(node.id) : undefined}
+ >
+ {node.name}
+ </span>
+ )}
+
+ <span className="rtype">{typeLabel}</span>
+
+ {showVis && (
+ <span
+ className="rvis"
+ title="Toggle visibility"
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onToggleVisible!(node.id, !node.visible);
+ }}
+ >
+ {node.locked ? (
+ <Lock size={12} strokeWidth={1.85} />
+ ) : node.visible ? (
+ <Eye size={13} strokeWidth={1.85} />
+ ) : (
+ <EyeOff size={13} strokeWidth={1.85} />
+ )}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index 4d9b04c6a..2367966d5 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -1,227 +1,34 @@
// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
-import { ChevronRight, Eye, EyeOff, Lock, Search, Plus } from 'lucide-react';
+import { Search, Plus } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
import { EngineHost } from '@/engine/EngineHost';
import { SceneStore } from '@/engine/SceneStore';
-import { SceneQuery, buildSceneTree } from '@/engine/SceneQuery';
import { SceneCommands } from '@/engine/SceneCommands';
import { SceneModel } from '@/engine/SceneModel';
import { PlayInspect } from '@/engine/PlayInspect';
import { ProjectStore } from '@/project/ProjectStore';
-import { NodeIcon } from '@/components/icons';
import { ContextMenu, type MenuItem } from '@/components/Menu';
-import type { SceneNode, EntityId, NodeKind } from '@/types';
-
-// Entity kind → the label shown in the outliner's right-hand "Type" column.
-const KIND_TYPE: Record<NodeKind, string> = {
- camera: 'Camera',
- sprite: 'Sprite',
- spine: 'Spine',
- physics: 'Physics',
- ui: 'UI',
- audio: 'Audio',
- group: 'Group',
- light: 'Light',
- empty: 'Entity',
-};
-
-interface RowProps {
- node: SceneNode;
- depth: number;
- forceExpand: boolean;
- renaming: EntityId | null;
- dropId: EntityId | null;
- onStartRename: (id: EntityId) => void;
- onCommitRename: (id: EntityId, name: string) => void;
- onContextMenu: (e: React.MouseEvent, id: EntityId) => void;
- onRowClick: (id: EntityId, e: React.MouseEvent) => void;
- onDragStartRow: (id: EntityId, e: React.DragEvent) => void;
- onDragOverRow: (id: EntityId, e: React.DragEvent) => void;
- onDropRow: (id: EntityId, e: React.DragEvent) => void;
-}
-
-function Row(props: RowProps) {
- const { node, depth, forceExpand, renaming, dropId } = props;
- const selectedIds = useSelection((s) => s.selectedIds);
- const expanded = useEditorStore((s) => s.expanded);
- const toggleExpanded = useEditorStore((s) => s.toggleExpanded);
-
- const hasChildren = !!node.children?.length;
- const isOpen = forceExpand || expanded.has(node.id);
- const isSelected = selectedIds.has(node.id);
- const isRenaming = renaming === node.id;
- // Prefab-instance members read with a warm icon tint (mirrors the inspector's
- // prefab ribbon) so instances are distinguishable in the tree (real tag data).
- const isPrefab = SceneModel.prefabTag(node.id) != null;
-
- // Right-column type label: prefab instances read "Prefab", others by kind,
- // each suffixed with the child count when it has any (real data).
- const childCount = node.children?.length ?? 0;
- const baseType = isPrefab ? 'Prefab' : (KIND_TYPE[node.kind] ?? 'Entity');
- const typeLabel = childCount > 0 ? `${baseType} · ${childCount}` : baseType;
-
- return (
- <>
- <div
- className={
- `row${isSelected ? ' sel' : ''}` +
- `${isOpen ? ' open' : ''}` +
- `${node.visible ? '' : ' hidden'}` +
- `${isPrefab ? ' prefab' : ''}` +
- `${dropId === node.id ? ' drop' : ''}`
- }
- style={{ paddingLeft: depth * 14 }}
- draggable={!isRenaming}
- onClick={(e) => props.onRowClick(node.id, e)}
- onContextMenu={(e) => props.onContextMenu(e, node.id)}
- onDragStart={(e) => props.onDragStartRow(node.id, e)}
- onDragOver={(e) => props.onDragOverRow(node.id, e)}
- onDrop={(e) => props.onDropRow(node.id, e)}
- >
- <span
- className={`twist${hasChildren ? '' : ' leaf'}`}
- onClick={(e) => {
- e.stopPropagation();
- if (hasChildren) toggleExpanded(node.id);
- }}
- >
- <ChevronRight size={9} strokeWidth={3} />
- </span>
-
- <span className="ricon">
- <NodeIcon kind={node.kind} />
- </span>
-
- {isRenaming ? (
- <input
- className="rname-edit"
- defaultValue={node.name}
- autoFocus
- spellCheck={false}
- onClick={(e) => e.stopPropagation()}
- onFocus={(e) => e.target.select()}
- onKeyDown={(e) => {
- if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
- else if (e.key === 'Escape') {
- e.currentTarget.value = node.name;
- e.currentTarget.blur();
- }
- }}
- onBlur={(e) => props.onCommitRename(node.id, e.target.value)}
- />
- ) : (
- <span className="rname" onDoubleClick={() => props.onStartRename(node.id)}>
- {node.name}
- </span>
- )}
-
- <span className="rtype">{typeLabel}</span>
-
- <span
- className="rvis"
- title="Toggle visibility"
- onClick={(e) => {
- e.stopPropagation();
- SceneCommands.setEntityVisible(node.id, !node.visible);
- }}
- >
- {node.locked ? (
- <Lock size={12} strokeWidth={1.85} />
- ) : node.visible ? (
- <Eye size={13} strokeWidth={1.85} />
- ) : (
- <EyeOff size={13} strokeWidth={1.85} />
- )}
- </span>
- </div>
-
- {hasChildren &&
- isOpen &&
- node.children!.map((child) => (
- <Row key={child.id} {...props} node={child} depth={depth + 1} />
- ))}
- </>
- );
-}
-
-// Keep a node if its name matches, or any descendant does (matches + ancestors).
-function filterNode(node: SceneNode, q: string): SceneNode | null {
- if (node.name.toLowerCase().includes(q)) return node;
- const kids = (node.children ?? [])
- .map((c) => filterNode(c, q))
- .filter((n): n is SceneNode => n != null);
- return kids.length ? { ...node, children: kids } : null;
-}
-
-// Flatten the visible tree (respecting expansion) into render order — for shift-range select.
-function flatVisible(nodes: SceneNode[], expanded: Set<EntityId>, forceExpand: boolean, out: EntityId[]) {
- for (const n of nodes) {
- out.push(n.id);
- if ((forceExpand || expanded.has(n.id)) && n.children?.length) {
- flatVisible(n.children, expanded, forceExpand, out);
- }
- }
-}
-
-// One row of the live "Game" tree (UE5 PIE world): a read-only view of a running
-// realm entity; click selects into PlayInspect, which Details inspects/edits live.
-const GAME_ROW_H = 24; // must match .row height in outliner.css
-
-function GameRowFlat({ node, depth, selection }: { node: SceneNode; depth: number; selection: EntityId | null }) {
- return (
- <div
- className={`row${selection === node.id ? ' sel' : ''}`}
- style={{ paddingLeft: depth * 14, height: GAME_ROW_H }}
- onClick={() => PlayInspect.select(node.id)}
- >
- <span className="twist leaf">
- <ChevronRight size={9} strokeWidth={3} />
- </span>
- <span className="ricon">
- <NodeIcon kind={node.kind} />
- </span>
- <span className="rname">{node.name}</span>
- <span className="rtype">{KIND_TYPE[node.kind] ?? 'Entity'}</span>
- </div>
- );
-}
-
-// Virtualized: a stress scene can hold thousands of live entities, and the
-// snapshot refreshes a few times a second — rendering every row as a DOM node
-// would peg the editor's main thread. Flatten to render order (the game view is
-// always-expanded) and render only the rows in the scroll window.
+import { VirtualTree } from '@/components/VirtualTree';
+import { buildOutlinerItems, collectExpandableIds } from '@/outliner/OutlinerModel';
+import { useOutliner } from '@/outliner/OutlinerController';
+import { OutlinerRow } from '@/outliner/OutlinerRow';
+import type { EntityId } from '@/types';
+
+// Must match .row height in outliner.css — the fixed row size the virtual list windows by.
+const ROW_H = 24;
+const NO_EXPANSION: ReadonlySet<EntityId> = new Set();
+
+// One row of the live "Game" tree (UE5 PIE world): a read-only, always-expanded
+// view of the running realm. A stress scene can hold thousands of live entities
+// refreshed a few times a second, so it shares the editor's virtualization.
function GameTree() {
const { snapshot, selection } = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getSnapshot);
- const tree = useMemo(() => buildSceneTree(snapshot), [snapshot]);
- const flat = useMemo(() => {
- const out: { node: SceneNode; depth: number }[] = [];
- const walk = (nodes: SceneNode[], depth: number): void => {
- for (const n of nodes) {
- out.push({ node: n, depth });
- if (n.children?.length) walk(n.children, depth + 1);
- }
- };
- walk(tree, 0);
- return out;
- }, [tree]);
+ const items = useMemo(() => buildOutlinerItems(snapshot, { expanded: NO_EXPANSION, expandAll: true }), [snapshot]);
- const scrollRef = useRef<HTMLDivElement>(null);
- const [scrollTop, setScrollTop] = useState(0);
- const [viewH, setViewH] = useState(600);
- useEffect(() => {
- const el = scrollRef.current;
- if (!el) return;
- const update = () => setViewH(el.clientHeight);
- update();
- const ro = new ResizeObserver(update);
- ro.observe(el);
- return () => ro.disconnect();
- }, []);
-
- if (flat.length === 0) {
+ if (items.length === 0) {
return (
<div className="pbody">
<div className="empty">
@@ -231,74 +38,63 @@ function GameTree() {
</div>
);
}
-
- const OVERSCAN = 8;
- const total = flat.length;
- const start = Math.max(0, Math.floor(scrollTop / GAME_ROW_H) - OVERSCAN);
- const end = Math.min(total, Math.ceil((scrollTop + viewH) / GAME_ROW_H) + OVERSCAN);
-
return (
- <div ref={scrollRef} className="pbody" onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}>
- <div style={{ height: total * GAME_ROW_H, position: 'relative' }}>
- {flat.slice(start, end).map(({ node, depth }, i) => (
- <div key={node.id} style={{ position: 'absolute', top: (start + i) * GAME_ROW_H, left: 0, right: 0 }}>
- <GameRowFlat node={node} depth={depth} selection={selection} />
- </div>
- ))}
- </div>
- </div>
+ <VirtualTree
+ className="pbody"
+ items={items}
+ rowHeight={ROW_H}
+ getKey={(it) => it.key}
+ renderRow={(it) => (
+ <OutlinerRow
+ item={it}
+ selected={selection === it.id}
+ collapsible={false}
+ onToggle={() => {}}
+ onClick={(id) => PlayInspect.select(id)}
+ />
+ )}
+ />
);
}
export function Outliner() {
const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);
const structRev = useSyncExternalStore(SceneStore.subscribe, SceneStore.getStructureRevision);
- const expanded = useEditorStore((s) => s.expanded);
+ const expanded = useOutliner((s) => s.expanded);
+ const query = useOutliner((s) => s.query);
+ const setQuery = useOutliner((s) => s.setQuery);
+ const toggleExpanded = useOutliner((s) => s.toggleExpanded);
+ const selectedIds = useSelection((s) => s.selectedIds);
const isPlaying = useEditorStore((s) => s.isPlaying);
const inspectWorld = useEditorStore((s) => s.inspectWorld);
const setInspectWorld = useEditorStore((s) => s.setInspectWorld);
const initRef = useRef(false);
const dragIds = useRef<EntityId[] | null>(null);
- const [query, setQuery] = useState('');
const [renaming, setRenaming] = useState<EntityId | null>(null);
const [dropId, setDropId] = useState<EntityId | null>(null);
const [ctx, setCtx] = useState<{ x: number; y: number; id: EntityId } | null>(null);
- const tree = useMemo(
- () => (engine.status === 'ready' ? SceneQuery.readSceneTree() : []),
+ const sceneCount = useMemo(
+ () => (engine.status === 'ready' ? (SceneModel.current?.entities.length ?? 0) : 0),
[engine.status, structRev],
);
-
- const q = query.trim().toLowerCase();
- const shown = useMemo(
- () => (q ? tree.map((n) => filterNode(n, q)).filter((n): n is SceneNode => n != null) : tree),
- [tree, q],
+ const items = useMemo(
+ () => (engine.status === 'ready' ? buildOutlinerItems(SceneModel.current, { expanded, query }) : []),
+ [engine.status, structRev, expanded, query],
);
- const flatIds = useMemo(() => {
- const out: EntityId[] = [];
- flatVisible(shown, expanded, !!q, out);
- return out;
- }, [shown, expanded, q]);
+ const flatIds = useMemo(() => items.map((i) => i.id), [items]);
// First time entities appear: expand groups, select the first root.
useEffect(() => {
- if (initRef.current || tree.length === 0) return;
+ if (initRef.current || sceneCount === 0) return;
initRef.current = true;
- const parents: EntityId[] = [];
- const walk = (nodes: SceneNode[]) =>
- nodes.forEach((n) => {
- if (n.children?.length) {
- parents.push(n.id);
- walk(n.children);
- }
- });
- walk(tree);
- useEditorStore.getState().setExpanded(parents);
+ useOutliner.getState().setExpanded(collectExpandableIds(SceneModel.current));
if (useSelection.getState().selectedId == null) {
- useSelection.getState().select(tree[0].id);
+ const firstRoot = buildOutlinerItems(SceneModel.current, { expanded: NO_EXPANSION })[0]?.id;
+ if (firstRoot != null) useSelection.getState().select(firstRoot);
}
- }, [tree]);
+ }, [sceneCount]);
const select = (id: EntityId | null) => useSelection.getState().select(id);
@@ -378,6 +174,16 @@ export function Outliner() {
reparent(id);
};
+ // Empty-space drag-drop (un-parent to root / instantiate a prefab at the root).
+ const onBodyDragOver = (e: React.DragEvent) => {
+ if (dragIds.current || isAssetDrag(e)) e.preventDefault();
+ };
+ const onBodyDrop = (e: React.DragEvent) => {
+ e.preventDefault();
+ if (dropPrefabAsset(e, null)) return;
+ reparent(null);
+ };
+
const ctxItems: MenuItem[] = ctx
? [
{ label: 'Rename', shortcut: 'F2', onClick: () => setRenaming(ctx.id) },
@@ -408,6 +214,26 @@ export function Outliner() {
// between the edit scene and the live running game.
const gameMode = inspectWorld === 'game';
+ const renderRow = (it: (typeof items)[number]) => (
+ <OutlinerRow
+ item={it}
+ selected={selectedIds.has(it.id)}
+ renaming={renaming === it.id}
+ isDrop={dropId === it.id}
+ prefab={SceneModel.prefabTag(it.id) != null}
+ draggable
+ onToggle={toggleExpanded}
+ onClick={onRowClick}
+ onContextMenu={onContextMenu}
+ onStartRename={setRenaming}
+ onCommitRename={commitRename}
+ onToggleVisible={(id, visible) => SceneCommands.setEntityVisible(id, visible)}
+ onDragStart={onDragStartRow}
+ onDragOver={onDragOverRow}
+ onDrop={onDropRow}
+ />
+ );
+
return (
<div className="panel">
{isPlaying && (
@@ -424,68 +250,52 @@ export function Outliner() {
<GameTree />
) : (
<>
- <div className="phead">
- <div className="search">
- <Search size={13} strokeWidth={1.85} />
- <input
- placeholder="Search entities"
- spellCheck={false}
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- />
- </div>
- <button type="button" className="pbtn" title="Add entity" onClick={addEntity}>
- <Plus size={15} strokeWidth={2} />
- </button>
- </div>
- {tree.length > 0 && (
- <div className="outliner-cols">
- <span className="c-name">Name</span>
- <span className="c-type">Type</span>
- <span className="c-vis" />
- </div>
- )}
- <div
- className="pbody"
- onDragOver={(e) => {
- if (dragIds.current || isAssetDrag(e)) e.preventDefault();
- }}
- onDrop={(e) => {
- e.preventDefault();
- if (dropPrefabAsset(e, null)) return; // drop a prefab into empty space = scene root
- reparent(null); // drop an entity into empty space = un-parent to the scene root
- }}
- >
- {tree.length === 0 ? (
- <div className="empty">
- <Search size={22} strokeWidth={1.4} />
- <p>{engine.status === 'ready' ? 'No entities in scene.' : 'Waiting for engine…'}</p>
+ <div className="phead">
+ <div className="search">
+ <Search size={13} strokeWidth={1.85} />
+ <input
+ placeholder="Search entities"
+ spellCheck={false}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </div>
+ <button type="button" className="pbtn" title="Add entity" onClick={addEntity}>
+ <Plus size={15} strokeWidth={2} />
+ </button>
</div>
- ) : shown.length === 0 ? (
- <div className="empty">
- <Search size={22} strokeWidth={1.4} />
- <p>No entities match “{query}”.</p>
- </div>
- ) : (
- shown.map((node) => (
- <Row
- key={node.id}
- node={node}
- depth={0}
- forceExpand={!!q}
- renaming={renaming}
- dropId={dropId}
- onStartRename={setRenaming}
- onCommitRename={commitRename}
- onContextMenu={onContextMenu}
- onRowClick={onRowClick}
- onDragStartRow={onDragStartRow}
- onDragOverRow={onDragOverRow}
- onDropRow={onDropRow}
+ {sceneCount > 0 && (
+ <div className="outliner-cols">
+ <span className="c-name">Name</span>
+ <span className="c-type">Type</span>
+ <span className="c-vis" />
+ </div>
+ )}
+ {sceneCount === 0 ? (
+ <div className="pbody" onDragOver={onBodyDragOver} onDrop={onBodyDrop}>
+ <div className="empty">
+ <Search size={22} strokeWidth={1.4} />
+ <p>{engine.status === 'ready' ? 'No entities in scene.' : 'Waiting for engine…'}</p>
+ </div>
+ </div>
+ ) : items.length === 0 ? (
+ <div className="pbody" onDragOver={onBodyDragOver} onDrop={onBodyDrop}>
+ <div className="empty">
+ <Search size={22} strokeWidth={1.4} />
+ <p>No entities match “{query}”.</p>
+ </div>
+ </div>
+ ) : (
+ <VirtualTree
+ className="pbody"
+ items={items}
+ rowHeight={ROW_H}
+ getKey={(it) => it.key}
+ renderRow={renderRow}
+ onDragOver={onBodyDragOver}
+ onDrop={onBodyDrop}
/>
- ))
- )}
- </div>
+ )}
</>
)}
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index 1a5827f1e..323b3a135 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -1,20 +1,16 @@
// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { create } from 'zustand';
-import type { EntityId, ToolMode } from '@/types';
+import type { ToolMode } from '@/types';
// Global editor UI state (tools, viewport toggles, play state, launcher gate).
-// Entity selection lives in its own engine-anchored store — see selectionStore.ts.
+// Entity selection lives in its own engine-anchored store — see selectionStore.ts;
+// outliner tree state (expansion / search) lives in the OutlinerController.
interface EditorState {
// Active manipulation tool (select / move / rotate / scale).
tool: ToolMode;
setTool: (tool: ToolMode) => void;
- // Expanded nodes in the outliner tree.
- expanded: Set<EntityId>;
- toggleExpanded: (id: EntityId) => void;
- setExpanded: (ids: EntityId[]) => void;
-
// Play-in-editor state.
isPlaying: boolean;
isPaused: boolean;
@@ -68,15 +64,6 @@ export const useEditorStore = create<EditorState>((set) => ({
tool: 'move',
setTool: (tool) => set({ tool }),
- expanded: new Set<EntityId>(),
- toggleExpanded: (id) =>
- set((s) => {
- const next = new Set(s.expanded);
- next.has(id) ? next.delete(id) : next.add(id);
- return { expanded: next };
- }),
- setExpanded: (ids) => set({ expanded: new Set(ids) }),
-
isPlaying: false,
isPaused: false,
togglePlay: () =>
diff --git a/desktop/tests/outliner-model.test.ts b/desktop/tests/outliner-model.test.ts
new file mode 100644
index 000000000..070ed6b3d
--- /dev/null
+++ b/desktop/tests/outliner-model.test.ts
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file buildOutlinerItems — the ONE outliner tree builder (REARCH_OUTLINER.md).
+ * Flattens a SceneData to render-ordered rows honoring expansion + filter;
+ * the same builder feeds the editor tree and the always-expanded PIE tree.
+ * Pure projection over the model hierarchy (derived from `parent`).
+ */
+import { describe, it, expect } from 'vitest';
+import type { SceneData } from 'esengine';
+import type { EntityId } from '@/types';
+import { buildOutlinerItems, collectExpandableIds } from '@/outliner/OutlinerModel';
+
+const ent = (id: number, parent: number | null) => ({ id, name: `E${id}`, parent, children: [], components: [] as unknown[] });
+
+// 1 ─┬ 2 ── 3 (root 1 with a nested branch and a flat child)
+// └ 5
+function scene(): SceneData {
+ return { version: '1.0', name: 'tree', entities: [ent(1, null), ent(2, 1), ent(3, 2), ent(5, 1)] } as unknown as SceneData;
+}
+
+const ids = (set: Iterable<EntityId>) => [...set];
+const itemIds = (data: SceneData, expanded: number[], opts?: { expandAll?: boolean; query?: string }) =>
+ buildOutlinerItems(data, { expanded: new Set(expanded), ...opts }).map((i) => i.id);
+
+describe('buildOutlinerItems', () => {
+ it('collapsed roots: only top-level nodes, marked hasChildren', () => {
+ const items = buildOutlinerItems(scene(), { expanded: new Set() });
+ expect(items.map((i) => i.id)).toEqual([1]);
+ expect(items[0]).toMatchObject({ depth: 0, hasChildren: true, expanded: false, parentId: null, kind: 'entity' });
+ });
+
+ it('expanding a node reveals exactly its direct children (one level)', () => {
+ expect(itemIds(scene(), [1])).toEqual([1, 2, 5]); // 2 is collapsed → 3 stays hidden
+ expect(itemIds(scene(), [1, 2])).toEqual([1, 2, 3, 5]);
+ });
+
+ it('depth + parentId track the hierarchy', () => {
+ const items = buildOutlinerItems(scene(), { expanded: new Set([1, 2]) });
+ const byId = new Map(items.map((i) => [i.id, i]));
+ expect(byId.get(2)).toMatchObject({ depth: 1, parentId: 1 });
+ expect(byId.get(3)).toMatchObject({ depth: 2, parentId: 2 });
+ expect(byId.get(5)).toMatchObject({ depth: 1, parentId: 1 });
+ });
+
+ it('expandAll renders the whole tree regardless of the expansion set (PIE)', () => {
+ expect(itemIds(scene(), [], { expandAll: true })).toEqual([1, 2, 3, 5]);
+ });
+
+ it('a query keeps matches + their ancestors and force-expands', () => {
+ expect(itemIds(scene(), [], { query: 'E3' })).toEqual([1, 2, 3]); // 5 doesn't match → dropped
+ expect(itemIds(scene(), [], { query: 'nope' })).toEqual([]);
+ });
+
+ it('null data → empty list', () => {
+ expect(buildOutlinerItems(null, { expanded: new Set() })).toEqual([]);
+ });
+
+ it('collectExpandableIds = every node that has children', () => {
+ expect(ids(collectExpandableIds(scene())).sort()).toEqual([1, 2]);
+ });
+});