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): UE5 path-folders — organizational folders orthogonal to parent

esengine64653074f2a2
diff --git a/desktop/src/engine/PrefabInstance.ts b/desktop/src/engine/PrefabInstance.ts
index 8e4b2c89f..649c25110 100644
--- a/desktop/src/engine/PrefabInstance.ts
+++ b/desktop/src/engine/PrefabInstance.ts
@@ -88,7 +88,14 @@ export async function expandScenePrefabs(
if (!prefab) continue; // unresolved prefab — skip (caller warns)
const { entities, rootId } = expandEntry(prefab, raw, allocateId);
for (const pe of entities) {
- out.push(toSceneEntity(pe));
+ const se = toSceneEntity(pe);
+ // The instance entry carries the outliner folder of its root (editor-only,
+ // dropped by the prefab core) — re-attach it so folders survive load.
+ if (pe.id === rootId) {
+ const folder = (raw as { folder?: string }).folder;
+ if (folder) (se as { folder?: string }).folder = folder;
+ }
+ out.push(se);
tags.push({
id: pe.id,
tag: { instanceRoot: rootId, prefabId: pe.prefabEntityId, prefab: pe.id === rootId ? raw.prefab : undefined },
@@ -129,7 +136,11 @@ export async function collapseScenePrefabs(
continue;
}
const processed = group.map((e) => toProcessed(e, tagOf(e.id)!.prefabId));
- out.push(collapseEntry(prefab, rootTag.prefab, processed, rootId, root.parent ?? null) as unknown as SceneEntity);
+ const entry = collapseEntry(prefab, rootTag.prefab, processed, rootId, root.parent ?? null) as unknown as SceneEntity;
+ // Carry the instance root's outliner folder onto the collapsed entry (lossless).
+ const folder = (root as { folder?: string }).folder;
+ if (folder) (entry as { folder?: string }).folder = folder;
+ out.push(entry);
}
return out;
}
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index c61a596fe..65f4fff3b 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -16,6 +16,7 @@ import {
hexToRgba,
prettyLabel,
} from './schema';
+import { normalizeFolder, folderParent, isFolderUnder, rebaseFolder } from '@/outliner/folders';
type SceneEntity = SceneData['entities'][number];
type SceneComponent = SceneEntity['components'][number];
@@ -451,6 +452,110 @@ export class SceneCommandsImpl {
);
}
+ // — Outliner folders (organizational paths; orthogonal to the transform parent) —
+ // Folders group ROOT entities. They live as an editor-only per-entity `folder`
+ // path + a scene-level explicit-folder list (so empties persist); all undoable.
+
+ /** Create an explicit (initially empty) folder. Undoable; no-op if it exists. */
+ createFolder(path: string): void {
+ const norm = normalizeFolder(path);
+ if (!norm) return;
+ const before = this.model.sceneFolders();
+ if (before.includes(norm)) return;
+ const after = [...before, norm];
+ this.model.setSceneFolders(after);
+ this.history.record('New Folder', () => this.model.setSceneFolders(after), () => this.model.setSceneFolders(before));
+ }
+
+ /**
+ * Rename/move a folder: re-root the folder (and its descendants) + every entity
+ * under it from `oldPath` to `newPath`, as one undo step. No-op if unchanged.
+ */
+ renameFolder(oldPath: string, newPath: string): void {
+ const o = normalizeFolder(oldPath);
+ const n = normalizeFolder(newPath);
+ if (!o || !n || o === n) return;
+
+ const beforeFolders = this.model.sceneFolders();
+ const afterFolders = [...new Set(beforeFolders.map((f) => rebaseFolder(f, o, n) ?? f))];
+ const edits = (this.model.current?.entities ?? [])
+ .map((e) => ({ id: e.id, before: this.model.folderOf(e.id) }))
+ .map((e) => ({ ...e, after: rebaseFolder(e.before, o, n) }))
+ .filter((e): e is { id: number; before: string; after: string } => e.after != null && e.after !== e.before);
+
+ const apply = (): void => {
+ this.model.setSceneFolders(afterFolders);
+ for (const e of edits) this.model.setFolder(e.id, e.after);
+ };
+ const revert = (): void => {
+ this.model.setSceneFolders(beforeFolders);
+ for (const e of edits) this.model.setFolder(e.id, e.before);
+ };
+ apply();
+ this.history.record('Rename Folder', apply, revert);
+ }
+
+ /**
+ * Delete a folder, moving its contents (entities + descendant folders) up to its
+ * parent (UE5 semantics — entities are never destroyed). One undo step.
+ */
+ deleteFolder(path: string): void {
+ const p = normalizeFolder(path);
+ if (!p) return;
+ const parent = folderParent(p);
+ const beforeFolders = this.model.sceneFolders();
+ const afterFolders = [
+ ...new Set(beforeFolders.filter((f) => f !== p).map((f) => (isFolderUnder(f, p) ? (rebaseFolder(f, p, parent) ?? parent) : f))),
+ ];
+ const edits = (this.model.current?.entities ?? [])
+ .map((e) => ({ id: e.id, before: this.model.folderOf(e.id) }))
+ .filter((e) => isFolderUnder(e.before, p))
+ .map((e) => ({ ...e, after: rebaseFolder(e.before, p, parent) ?? parent }));
+
+ const apply = (): void => {
+ this.model.setSceneFolders(afterFolders);
+ for (const e of edits) this.model.setFolder(e.id, e.after);
+ };
+ const revert = (): void => {
+ this.model.setSceneFolders(beforeFolders);
+ for (const e of edits) this.model.setFolder(e.id, e.before);
+ };
+ apply();
+ this.history.record('Delete Folder', apply, revert);
+ }
+
+ /**
+ * Move entities into a folder (`path: null` = scene root). Folders organize
+ * roots, so this also un-parents each entity (it becomes a root in the folder).
+ * One undo step; no-op for entities already there.
+ */
+ moveToFolder(sourceIds: readonly EntityId[], path: string | null): void {
+ const norm = path ? normalizeFolder(path) : '';
+ const records = sourceIds
+ .map((id) => {
+ const e = this.model.entityBySource(id);
+ return e ? { id, beforeParent: e.parent ?? null, beforeFolder: this.model.folderOf(id) } : null;
+ })
+ .filter((r): r is { id: number; beforeParent: number | null; beforeFolder: string } => !!r)
+ .filter((r) => r.beforeParent !== null || r.beforeFolder !== norm);
+ if (records.length === 0) return;
+
+ const apply = (): void => {
+ for (const r of records) {
+ this.model.setParent(r.id, null);
+ this.model.setFolder(r.id, norm);
+ }
+ };
+ const revert = (): void => {
+ for (const r of records) {
+ this.model.setFolder(r.id, r.beforeFolder);
+ this.model.setParent(r.id, r.beforeParent);
+ }
+ };
+ apply();
+ this.history.record(records.length > 1 ? `Move ${records.length} to Folder` : 'Move to Folder', apply, revert);
+ }
+
/** Add a component (with its registered/schema defaults) to an entity. Undoable. */
// Apply an add to the model and return its undo op, or null if it's a no-op
// (entity gone / component already present). Shared by the single + batch paths.
diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.ts
index 935f591f8..5377236d7 100644
--- a/desktop/src/engine/SceneModel.ts
+++ b/desktop/src/engine/SceneModel.ts
@@ -20,7 +20,11 @@ export type ModelEvent =
| { kind: 'componentChanged'; sourceId: number; type: string }
| { kind: 'componentRemoved'; sourceId: number; type: string }
| { kind: 'parentChanged'; sourceId: number }
- | { kind: 'nameChanged'; sourceId: number };
+ | { kind: 'nameChanged'; sourceId: number }
+ // An entity's outliner folder path changed (organizational; not a World/ECS change).
+ | { kind: 'folderChanged'; sourceId: number }
+ // The scene's explicit-folder set changed (create/rename/delete of a folder).
+ | { kind: 'foldersChanged' };
type Listener = (ev: ModelEvent) => void;
@@ -253,6 +257,44 @@ export class SceneModelImpl {
this.emit({ kind: 'parentChanged', sourceId });
}
+ // ── Outliner folders (organizational; orthogonal to the transform `parent`) ──
+ // A folder is a slash-delimited PATH stored as an editor-only per-entity field
+ // (`folder`) plus a scene-level list of explicit/empty folders (`folders`).
+ // Neither reaches the World (the Reconciler reads only components/parent/name)
+ // and both round-trip through save verbatim, so this stays lossless + ECS-free.
+ // Path semantics (prefixes, rename) live in the command/builder layer; the model
+ // only stores raw values. Storing `""` removes the field (cleaner JSON).
+
+ /** An entity's folder path, or `""` (scene root) when it has none. */
+ folderOf(sourceId: number): string {
+ const e = this.entityBySource(sourceId) as { folder?: string } | undefined;
+ return e?.folder ?? '';
+ }
+
+ /** Set an entity's folder path (`""` clears it). */
+ setFolder(sourceId: number, path: string): void {
+ const e = this.entityBySource(sourceId) as (SceneEntity & { folder?: string }) | undefined;
+ if (!e) return;
+ if (path) e.folder = path;
+ else delete e.folder;
+ this.emit({ kind: 'folderChanged', sourceId });
+ }
+
+ /** The scene's explicit folder list (so empty folders persist). */
+ sceneFolders(): string[] {
+ const d = this.data as (SceneData & { folders?: string[] }) | null;
+ return d?.folders ? [...d.folders] : [];
+ }
+
+ /** Replace the scene's explicit folder list (empty clears the field). */
+ setSceneFolders(paths: string[]): void {
+ if (!this.data) return;
+ const d = this.data as SceneData & { folders?: string[] };
+ if (paths.length) d.folders = [...paths];
+ else delete d.folders;
+ this.emit({ kind: 'foldersChanged' });
+ }
+
// ── Source↔runtime map (Reconciler-only writers) ─────────────────────────
/** Bind a source id to its current runtime entity (Reconciler, on spawn). */
diff --git a/desktop/src/outliner/OutlinerController.ts b/desktop/src/outliner/OutlinerController.ts
index 3b882d6ca..d236964a5 100644
--- a/desktop/src/outliner/OutlinerController.ts
+++ b/desktop/src/outliner/OutlinerController.ts
@@ -3,37 +3,42 @@
/**
* @file OutlinerController.ts — the outliner's headless view-state.
*
- * Owns the editor-tree state the SceneModel doesn't: which nodes are expanded and
+ * Owns the editor-tree state the SceneModel doesn't: which rows 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
+ * Expansion is keyed by stable string ITEM KEYS (`e<id>` for entities, `f:<path>`
+ * for folders), so one set covers both row kinds. 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`). 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';
+import { entityKey, folderKey } from './OutlinerModel';
+import { folderPrefixes, normalizeFolder, rebaseFolder } from './folders';
interface OutlinerState {
- /** Expanded node ids (entity source ids). */
- expanded: Set<EntityId>;
+ /** Expanded item keys (`e<id>` / `f:<path>`). */
+ expanded: Set<string>;
/** Live name filter (raw text; the builder trims/lowercases). */
query: string;
- /** Flip one node's expansion. */
- toggleExpanded: (id: EntityId) => void;
+ /** Flip one row's expansion (pass an item key). */
+ toggleExpanded: (key: string) => 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). */
+ setExpanded: (keys: string[]) => void;
+ /** Additively expand keys (reveal — keeps existing expansion). */
+ expand: (keys: string[]) => void;
+ /** Expand an entity's transform ancestors + folder path so it shows (reveal-on-select). */
revealEntity: (id: EntityId) => void;
+ /** Rewrite expanded folder keys when a folder is renamed/moved (keep it open). */
+ rebaseFolderKeys: (oldPath: string, newPath: string) => void;
setQuery: (query: string) => void;
- /** Prune a removed id (self-heal on the model's `entityRemoved`). */
+ /** Prune a removed entity's key (self-heal on the model's `entityRemoved`). */
dropId: (id: EntityId) => void;
/** Reset the view on a scene swap (the model's `reset`). */
reset: () => void;
@@ -42,32 +47,50 @@ interface OutlinerState {
/** 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>(),
+ expanded: new Set<string>(),
query: '',
- toggleExpanded: (id) =>
+ toggleExpanded: (key) =>
set((s) => {
const next = new Set(s.expanded);
- next.has(id) ? next.delete(id) : next.add(id);
+ next.has(key) ? next.delete(key) : next.add(key);
return { expanded: next };
}),
- setExpanded: (ids) => set({ expanded: new Set(ids) }),
- expand: (ids) =>
+ setExpanded: (keys) => set({ expanded: new Set(keys) }),
+ expand: (keys) =>
set((s) => {
const next = new Set(s.expanded);
- for (const id of ids) next.add(id);
+ for (const k of keys) next.add(k);
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;
+ // Climb the transform ancestors (expanding each so `id` becomes visible)
+ // up to the root, then expand that root's folder-path prefixes.
+ let cur: number | null = id;
+ let root = id;
const seen = new Set<number>();
while (cur != null && !seen.has(cur)) {
seen.add(cur);
- next.add(cur);
- cur = model.entityBySource(cur)?.parent ?? null;
+ const parent: number | null = model.entityBySource(cur)?.parent ?? null;
+ if (parent != null) next.add(entityKey(parent));
+ else root = cur;
+ cur = parent;
+ }
+ for (const pre of folderPrefixes(normalizeFolder(model.folderOf(root)))) next.add(folderKey(pre));
+ return { expanded: next };
+ }),
+ rebaseFolderKeys: (oldPath, newPath) =>
+ set((s) => {
+ const next = new Set<string>();
+ for (const k of s.expanded) {
+ if (!k.startsWith('f:')) {
+ next.add(k);
+ continue;
+ }
+ const rebased = rebaseFolder(k.slice(2), oldPath, newPath);
+ next.add(rebased != null ? folderKey(rebased) : k);
}
return { expanded: next };
}),
@@ -75,9 +98,10 @@ export function createOutlinerStore(model: SceneModelImpl) {
dropId: (id) =>
set((s) => {
- if (!s.expanded.has(id)) return s;
+ const k = entityKey(id);
+ if (!s.expanded.has(k)) return s;
const next = new Set(s.expanded);
- next.delete(id);
+ next.delete(k);
return { expanded: next };
}),
reset: () => set({ expanded: new Set(), query: '' }),
diff --git a/desktop/src/outliner/OutlinerModel.ts b/desktop/src/outliner/OutlinerModel.ts
index 208b7509b..9c8baf73f 100644
--- a/desktop/src/outliner/OutlinerModel.ts
+++ b/desktop/src/outliner/OutlinerModel.ts
@@ -3,43 +3,62 @@
/**
* @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.
+ * Flattens a SceneData into a render-ordered list of {@link OutlinerItem}s — a
+ * tagged union of `entity` and `folder` rows (UE5 path-folders) — honoring the
+ * expansion set (keyed by stable string item keys) + a name filter. The same
+ * builder feeds the editor tree and the always-expanded PIE "Game" tree.
*
- * 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.
+ * Folders are organizational PATHS (orthogonal to the transform `parent`): they
+ * group **root** entities only; a parented entity always nests under its parent.
+ * The folder tree is the union of every root's folder-path prefixes and the
+ * scene's explicit (incl. empty) folder list. Hierarchy among entities comes from
+ * {@link buildSceneTree} (derived from `parent`, robust to a drifted `children[]`),
+ * so this stays a pure projection.
*/
import type { SceneData } from 'esengine';
import type { SceneNode, EntityId } from '@/types';
import { buildSceneTree } from '@/engine/SceneQuery';
+import { ROOT_FOLDER, normalizeFolder, folderName, folderParent, folderPrefixes, isFolderUnder } from './folders';
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). */
+interface OutlinerItemBase {
+ /** Stable identity for React keys + the expansion set (`e<id>` / `f:<path>`). */
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;
+ parentKey: string | null;
+}
+export interface OutlinerEntityItem extends OutlinerItemBase {
+ kind: 'entity';
+ id: EntityId;
+ node: SceneNode;
+}
+export interface OutlinerFolderItem extends OutlinerItemBase {
+ kind: 'folder';
+ /** Full folder path. */
+ path: string;
+ /** Display name (last path segment). */
+ name: string;
+ /** Entity roots under this folder (recursive) — the row's count badge. */
+ count: number;
}
+export type OutlinerItem = OutlinerEntityItem | OutlinerFolderItem;
+
+/** Expansion/identity key for an entity row. */
+export const entityKey = (id: EntityId): string => `e${id}`;
+/** Expansion/identity key for a folder row. */
+export const folderKey = (path: string): string => `f:${path}`;
export interface BuildOutlinerOpts {
- /** Currently-expanded node ids. Ignored when `expandAll` (or a filter) is on. */
- expanded: ReadonlySet<EntityId>;
+ /** Expanded item keys. Ignored when `expandAll` (or a filter) is on. */
+ expanded: ReadonlySet<string>;
+ /** A root entity's folder path (`""` = scene root). Absent ⇒ no folders (PIE). */
+ folderOf?: (id: EntityId) => string;
+ /** The scene's explicit (incl. empty) folders, so empties still show. */
+ folders?: readonly string[];
/** Free-text name filter; matches + their ancestors survive (case-insensitive). */
query?: string;
/** Render every node expanded — the PIE tree, and implicitly while filtering. */
@@ -60,33 +79,70 @@ export function buildOutlinerItems(data: SceneData | null, opts: BuildOutlinerOp
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 folderOf = opts.folderOf ?? (() => ROOT_FOLDER);
+
+ // Group the shown roots by their folder path, and gather every folder to show:
+ // each root path's prefixes, plus the scene's explicit folders (only when not
+ // filtering — an explicit empty folder has no match to surface under a query).
+ const rootsByFolder = new Map<string, SceneNode[]>();
+ const allFolders = new Set<string>();
+ for (const root of shown) {
+ const path = normalizeFolder(folderOf(root.id));
+ (rootsByFolder.get(path) ?? rootsByFolder.set(path, []).get(path)!).push(root);
+ for (const pre of folderPrefixes(path)) allFolders.add(pre);
+ }
+ if (!q) for (const f of opts.folders ?? []) for (const pre of folderPrefixes(normalizeFolder(f))) allFolders.add(pre);
+
+ const childFolders = (path: string): string[] =>
+ [...allFolders].filter((p) => folderParent(p) === path).sort((a, b) => folderName(a).localeCompare(folderName(b)));
+ const countUnder = (path: string): number => {
+ let n = 0;
+ for (const [fp, arr] of rootsByFolder) if (isFolderUnder(fp, path)) n += arr.length;
+ return n;
+ };
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);
+
+ const emitEntity = (node: SceneNode, depth: number, parentKey: string | null): void => {
+ const hasChildren = !!node.children?.length;
+ const expanded = expandAll || opts.expanded.has(entityKey(node.id));
+ out.push({ kind: 'entity', key: entityKey(node.id), id: node.id, node, depth, hasChildren, expanded, parentKey });
+ if (hasChildren && expanded) for (const c of node.children!) emitEntity(c, depth + 1, entityKey(node.id));
+ };
+
+ // Emit the child folders of `path` (nested) then the entity roots directly in it.
+ const emitFolderContents = (path: string, depth: number, parentKey: string | null): void => {
+ for (const fp of childFolders(path)) {
+ const hasKids = childFolders(fp).length > 0 || (rootsByFolder.get(fp)?.length ?? 0) > 0;
+ const expanded = expandAll || opts.expanded.has(folderKey(fp));
+ out.push({ kind: 'folder', key: folderKey(fp), path: fp, name: folderName(fp), count: countUnder(fp), depth, hasChildren: hasKids, expanded, parentKey });
+ if (expanded) emitFolderContents(fp, depth + 1, folderKey(fp));
}
+ for (const root of rootsByFolder.get(path) ?? []) emitEntity(root, depth, parentKey);
};
- walk(shown, 0, null);
+
+ emitFolderContents(ROOT_FOLDER, 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[] = [];
+/** Every expandable key (folders + entity parents) — the auto-expand set for a fresh scene. */
+export function collectExpandableKeys(data: SceneData | null, opts?: Pick<BuildOutlinerOpts, 'folderOf' | 'folders'>): string[] {
+ const folderOf = opts?.folderOf ?? (() => ROOT_FOLDER);
+ const out: string[] = [];
+ const folders = new Set<string>();
const walk = (nodes: SceneNode[]): void => {
for (const n of nodes) {
if (n.children?.length) {
- out.push(n.id);
+ out.push(entityKey(n.id));
walk(n.children);
}
}
};
- walk(buildSceneTree(data));
+ const roots = buildSceneTree(data);
+ walk(roots);
+ for (const r of roots) for (const pre of folderPrefixes(normalizeFolder(folderOf(r.id)))) folders.add(pre);
+ for (const f of opts?.folders ?? []) for (const pre of folderPrefixes(normalizeFolder(f))) folders.add(pre);
+ for (const f of folders) out.push(folderKey(f));
return out;
}
diff --git a/desktop/src/outliner/OutlinerRow.tsx b/desktop/src/outliner/OutlinerRow.tsx
index 7399e565c..2a7d65f3a 100644
--- a/desktop/src/outliner/OutlinerRow.tsx
+++ b/desktop/src/outliner/OutlinerRow.tsx
@@ -5,12 +5,12 @@
*
* 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.
+ * visible rows ever renders or re-renders. Renders both row kinds (entity / folder);
+ * editor-only affordances (visibility toggle, rename, drag-drop) are gated on their
+ * handlers — 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 { ChevronRight, Eye, EyeOff, Lock, Folder, FolderOpen } from 'lucide-react';
import { NodeIcon } from '@/components/icons';
import type { EntityId, NodeKind } from '@/types';
import type { OutlinerItem } from './OutlinerModel';
@@ -30,37 +30,47 @@ const KIND_TYPE: Record<NodeKind, string> = {
export interface OutlinerRowProps {
item: OutlinerItem;
+ /** Entity selection highlight (folders never carry entity selection). */
selected: boolean;
renaming?: boolean;
isDrop?: boolean;
- /** Prefab-instance member — warm icon tint (editor only). */
+ /** Prefab-instance member — warm icon tint (entity rows 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;
+ onToggle: (key: string) => void;
+ onClick: (item: OutlinerItem, e: React.MouseEvent) => void;
+ onContextMenu?: (e: React.MouseEvent, item: OutlinerItem) => void;
+ onStartRename?: (item: OutlinerItem) => void;
+ onCommitRename?: (item: OutlinerItem, 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;
+ onDragStart?: (item: OutlinerItem, e: React.DragEvent) => void;
+ onDragOver?: (item: OutlinerItem, e: React.DragEvent) => void;
+ onDrop?: (item: OutlinerItem, e: React.DragEvent) => void;
}
export function OutlinerRow(props: OutlinerRowProps) {
const { item, selected, renaming, isDrop, prefab } = props;
- const { node, depth, hasChildren, expanded } = item;
+ const isFolder = item.kind === 'folder';
+ const { 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 name = item.kind === 'folder' ? item.name : item.node.name;
+ const visible = item.kind === 'entity' ? item.node.visible : true;
+ const locked = item.kind === 'entity' ? item.node.locked : false;
+
+ // Right column: entity type (prefab/kind + child count), or a folder's item count.
+ let typeLabel: string;
+ if (item.kind === 'folder') {
+ typeLabel = item.count > 0 ? String(item.count) : '';
+ } else {
+ const childCount = item.node.children?.length ?? 0;
+ const baseType = prefab ? 'Prefab' : (KIND_TYPE[item.node.kind] ?? 'Entity');
+ typeLabel = childCount > 0 ? `${baseType} · ${childCount}` : baseType;
+ }
const canRename = !!props.onCommitRename;
- const showVis = !!props.onToggleVisible;
+ const showVis = !!props.onToggleVisible && item.kind === 'entity';
const collapsible = props.collapsible !== false;
const showTwist = hasChildren && collapsible;
@@ -69,36 +79,41 @@ export function OutlinerRow(props: OutlinerRowProps) {
className={
`row${selected ? ' sel' : ''}` +
`${expanded ? ' open' : ''}` +
- `${node.visible ? '' : ' hidden'}` +
+ `${visible ? '' : ' hidden'}` +
`${prefab ? ' prefab' : ''}` +
+ `${isFolder ? ' folder' : ''}` +
`${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}
+ onClick={(e) => props.onClick(item, e)}
+ onContextMenu={props.onContextMenu ? (e) => props.onContextMenu!(e, item) : undefined}
+ onDragStart={props.onDragStart ? (e) => props.onDragStart!(item, e) : undefined}
+ onDragOver={props.onDragOver ? (e) => props.onDragOver!(item, e) : undefined}
+ onDrop={props.onDrop ? (e) => props.onDrop!(item, e) : undefined}
>
<span
className={`twist${showTwist ? '' : ' leaf'}`}
onClick={(e) => {
e.stopPropagation();
- if (showTwist) props.onToggle(node.id);
+ if (showTwist) props.onToggle(item.key);
}}
>
<ChevronRight size={9} strokeWidth={3} />
</span>
<span className="ricon">
- <NodeIcon kind={node.kind} />
+ {item.kind === 'folder' ? (
+ expanded ? <FolderOpen size={14} strokeWidth={1.85} /> : <Folder size={14} strokeWidth={1.85} />
+ ) : (
+ <NodeIcon kind={item.node.kind} />
+ )}
</span>
{renaming && canRename ? (
<input
className="rname-edit"
- defaultValue={node.name}
+ defaultValue={name}
autoFocus
spellCheck={false}
onClick={(e) => e.stopPropagation()}
@@ -106,18 +121,18 @@ export function OutlinerRow(props: OutlinerRowProps) {
onKeyDown={(e) => {
if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
else if (e.key === 'Escape') {
- e.currentTarget.value = node.name;
+ e.currentTarget.value = name;
e.currentTarget.blur();
}
}}
- onBlur={(e) => props.onCommitRename!(node.id, e.target.value)}
+ onBlur={(e) => props.onCommitRename!(item, e.target.value)}
/>
) : (
<span
className="rname"
- onDoubleClick={canRename && props.onStartRename ? () => props.onStartRename!(node.id) : undefined}
+ onDoubleClick={canRename && props.onStartRename ? () => props.onStartRename!(item) : undefined}
>
- {node.name}
+ {name}
</span>
)}
@@ -129,12 +144,12 @@ export function OutlinerRow(props: OutlinerRowProps) {
title="Toggle visibility"
onClick={(e) => {
e.stopPropagation();
- props.onToggleVisible!(node.id, !node.visible);
+ props.onToggleVisible!((item as { id: EntityId }).id, !visible);
}}
>
- {node.locked ? (
+ {locked ? (
<Lock size={12} strokeWidth={1.85} />
- ) : node.visible ? (
+ ) : visible ? (
<Eye size={13} strokeWidth={1.85} />
) : (
<EyeOff size={13} strokeWidth={1.85} />
diff --git a/desktop/src/outliner/folders.ts b/desktop/src/outliner/folders.ts
new file mode 100644
index 000000000..9f42b26a7
--- /dev/null
+++ b/desktop/src/outliner/folders.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file folders.ts — outliner folder-path helpers (UE5 path-folders).
+ *
+ * A folder is a slash-delimited PATH ("Enemies/Bosses"), not an entity — it
+ * organizes the outliner without touching the ECS/transform/gameplay (orthogonal
+ * to `parent`). Stored losslessly as a per-entity `folder` field + a scene-level
+ * list of explicit (incl. empty) folders. These pure helpers are the one place
+ * that knows the path grammar; the empty string is the implicit scene root.
+ */
+
+/** The implicit root — an entity with no `folder` (or `""`) sits at the scene root. */
+export const ROOT_FOLDER = '';
+
+/** Editor-only per-entity field (not in the engine `SceneEntityData`). */
+export interface EntityFolderField {
+ /** Slash-delimited folder path; absent/`""` = scene root. */
+ folder?: string;
+}
+
+/** Editor-only scene-level field carrying explicit (incl. empty) folders. */
+export interface SceneFoldersField {
+ folders?: string[];
+}
+
+/** Collapse `a//b/ /c` → `a/b/c`; drops empty/whitespace segments. */
+export function normalizeFolder(path: string | undefined): string {
+ if (!path) return ROOT_FOLDER;
+ return path
+ .split('/')
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0)
+ .join('/');
+}
+
+/** The last path segment (display name); `""` for the root. */
+export function folderName(path: string): string {
+ const p = normalizeFolder(path);
+ const i = p.lastIndexOf('/');
+ return i < 0 ? p : p.slice(i + 1);
+}
+
+/** The parent folder path; `""` for a top-level folder or the root. */
+export function folderParent(path: string): string {
+ const p = normalizeFolder(path);
+ const i = p.lastIndexOf('/');
+ return i < 0 ? ROOT_FOLDER : p.slice(0, i);
+}
+
+/** Join a parent path + a child name (`join("A", "B") === "A/B"`). */
+export function joinFolder(parent: string, name: string): string {
+ return normalizeFolder(parent ? `${parent}/${name}` : name);
+}
+
+/** Every ancestor path including the path itself: `"A/B/C"` → `["A","A/B","A/B/C"]`. */
+export function folderPrefixes(path: string): string[] {
+ const p = normalizeFolder(path);
+ if (!p) return [];
+ const segs = p.split('/');
+ const out: string[] = [];
+ let acc = '';
+ for (const s of segs) {
+ acc = acc ? `${acc}/${s}` : s;
+ out.push(acc);
+ }
+ return out;
+}
+
+/** True if `path` is `ancestor` or nested below it (prefix on a segment boundary). */
+export function isFolderUnder(path: string, ancestor: string): boolean {
+ const p = normalizeFolder(path);
+ const a = normalizeFolder(ancestor);
+ if (!a) return true; // everything is under the root
+ return p === a || p.startsWith(`${a}/`);
+}
+
+/**
+ * Re-root `path` from `oldBase` onto `newBase` (folder rename/move). Returns the
+ * rewritten path, or null if `path` isn't under `oldBase`.
+ */
+export function rebaseFolder(path: string, oldBase: string, newBase: string): string | null {
+ const p = normalizeFolder(path);
+ const o = normalizeFolder(oldBase);
+ if (!isFolderUnder(p, o)) return null;
+ const tail = o ? p.slice(o.length) : p ? `/${p}` : ''; // includes a leading '/' or ''
+ return normalizeFolder(`${newBase}${tail}`);
+}
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index 2367966d5..d5d230338 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -1,7 +1,7 @@
// 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 { Search, Plus } from 'lucide-react';
+import { Search, Plus, FolderPlus } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
import { EngineHost } from '@/engine/EngineHost';
@@ -12,18 +12,21 @@ import { PlayInspect } from '@/engine/PlayInspect';
import { ProjectStore } from '@/project/ProjectStore';
import { ContextMenu, type MenuItem } from '@/components/Menu';
import { VirtualTree } from '@/components/VirtualTree';
-import { buildOutlinerItems, collectExpandableIds } from '@/outliner/OutlinerModel';
+import { buildOutlinerItems, collectExpandableKeys, entityKey, folderKey, type OutlinerItem } from '@/outliner/OutlinerModel';
import { useOutliner } from '@/outliner/OutlinerController';
import { OutlinerRow } from '@/outliner/OutlinerRow';
+import { joinFolder, folderParent } from '@/outliner/folders';
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();
+const NO_EXPANSION: ReadonlySet<string> = new Set();
+
+const entityIds = (items: OutlinerItem[]): EntityId[] =>
+ items.filter((i): i is Extract<OutlinerItem, { kind: 'entity' }> => i.kind === 'entity').map((i) => i.id);
// 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.
+// view of the running realm, sharing the editor's virtualization. No folders.
function GameTree() {
const { snapshot, selection } = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getSnapshot);
const items = useMemo(() => buildOutlinerItems(snapshot, { expanded: NO_EXPANSION, expandAll: true }), [snapshot]);
@@ -47,10 +50,12 @@ function GameTree() {
renderRow={(it) => (
<OutlinerRow
item={it}
- selected={selection === it.id}
+ selected={it.kind === 'entity' && selection === it.id}
collapsible={false}
onToggle={() => {}}
- onClick={(id) => PlayInspect.select(id)}
+ onClick={(item) => {
+ if (item.kind === 'entity') PlayInspect.select(item.id);
+ }}
/>
)}
/>
@@ -71,34 +76,49 @@ export function Outliner() {
const initRef = useRef(false);
const dragIds = useRef<EntityId[] | null>(null);
- 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 [renaming, setRenaming] = useState<string | null>(null); // item key
+ const [dropId, setDropId] = useState<string | null>(null); // item key
+ const [ctx, setCtx] = useState<{ x: number; y: number; item: OutlinerItem } | null>(null);
const sceneCount = useMemo(
() => (engine.status === 'ready' ? (SceneModel.current?.entities.length ?? 0) : 0),
[engine.status, structRev],
);
const items = useMemo(
- () => (engine.status === 'ready' ? buildOutlinerItems(SceneModel.current, { expanded, query }) : []),
+ () =>
+ engine.status === 'ready'
+ ? buildOutlinerItems(SceneModel.current, {
+ expanded,
+ query,
+ folderOf: (id) => SceneModel.folderOf(id),
+ folders: SceneModel.sceneFolders(),
+ })
+ : [],
[engine.status, structRev, expanded, query],
);
- const flatIds = useMemo(() => items.map((i) => i.id), [items]);
+ const flatIds = useMemo(() => entityIds(items), [items]);
- // First time entities appear: expand groups, select the first root.
+ // First time entities appear: expand groups + folders, select the first entity.
useEffect(() => {
if (initRef.current || sceneCount === 0) return;
initRef.current = true;
- useOutliner.getState().setExpanded(collectExpandableIds(SceneModel.current));
+ useOutliner.getState().setExpanded(
+ collectExpandableKeys(SceneModel.current, { folderOf: (id) => SceneModel.folderOf(id), folders: SceneModel.sceneFolders() }),
+ );
if (useSelection.getState().selectedId == null) {
- const firstRoot = buildOutlinerItems(SceneModel.current, { expanded: NO_EXPANSION })[0]?.id;
- if (firstRoot != null) useSelection.getState().select(firstRoot);
+ const first = entityIds(buildOutlinerItems(SceneModel.current, { expanded: NO_EXPANSION, expandAll: true }))[0];
+ if (first != null) useSelection.getState().select(first);
}
}, [sceneCount]);
const select = (id: EntityId | null) => useSelection.getState().select(id);
- const onRowClick = (id: EntityId, e: React.MouseEvent) => {
+ const onRowClick = (item: OutlinerItem, e: React.MouseEvent) => {
+ if (item.kind === 'folder') {
+ toggleExpanded(item.key);
+ return;
+ }
+ const id = item.id;
const store = useSelection.getState();
if (e.metaKey || e.ctrlKey) {
store.toggleSelect(id);
@@ -114,18 +134,28 @@ export function Outliner() {
}
};
- const onContextMenu = (e: React.MouseEvent, id: EntityId) => {
+ const onContextMenu = (e: React.MouseEvent, item: OutlinerItem) => {
e.preventDefault();
- // Right-clicking outside the current selection selects just that entity;
- // right-clicking within it keeps the multi-selection.
- if (!useSelection.getState().selectedIds.has(id)) select(id);
- setCtx({ x: e.clientX, y: e.clientY, id });
+ if (item.kind === 'entity' && !useSelection.getState().selectedIds.has(item.id)) select(item.id);
+ setCtx({ x: e.clientX, y: e.clientY, item });
};
- const commitRename = (id: EntityId, name: string) => {
+
+ const onStartRename = (item: OutlinerItem) => setRenaming(item.key);
+ const commitRename = (item: OutlinerItem, name: string) => {
setRenaming(null);
const trimmed = name.trim();
- if (trimmed) SceneCommands.renameEntity(id, trimmed);
+ if (!trimmed) return;
+ if (item.kind === 'folder') {
+ const next = joinFolder(folderParent(item.path), trimmed);
+ if (next !== item.path) {
+ SceneCommands.renameFolder(item.path, next);
+ useOutliner.getState().rebaseFolderKeys(item.path, next);
+ }
+ } else {
+ SceneCommands.renameEntity(item.id, trimmed);
+ }
};
+
const addEntity = () => {
const id = SceneCommands.addEntity();
if (id != null) select(id);
@@ -135,7 +165,19 @@ export function Outliner() {
return ids.has(id) ? [...ids] : [id];
};
- // — Drag-to-reparent (entity rows) + drag-a-prefab-in (Content Browser) —
+ // Create a uniquely-named folder (optionally moving a selection into it), reveal
+ // it, and drop straight into rename — the UE5 "New Folder" gesture.
+ const newFolder = (parent: string, into: EntityId[] | null) => {
+ const existing = new Set(SceneModel.sceneFolders());
+ let path = joinFolder(parent, 'New Folder');
+ for (let i = 2; existing.has(path); i++) path = joinFolder(parent, `New Folder ${i}`);
+ SceneCommands.createFolder(path);
+ if (into?.length) SceneCommands.moveToFolder(into, path);
+ useOutliner.getState().expand([folderKey(path)]);
+ setRenaming(folderKey(path));
+ };
+
+ // — Drag-to-reparent / move-to-folder + drag-a-prefab-in (Content Browser) —
const ASSET_MIME = 'application/x-estella-asset';
const isAssetDrag = (e: React.DragEvent) => e.dataTransfer.types.includes(ASSET_MIME);
/** Instantiate a dropped `.esprefab` under `parent`. Returns true if handled. */
@@ -145,19 +187,18 @@ export function Outliner() {
void ProjectStore.instantiatePrefabFromPath(path, parent);
return true;
};
- const onDragStartRow = (id: EntityId, e: React.DragEvent) => {
- dragIds.current = selectionOrTarget(id);
+ const onDragStartRow = (item: OutlinerItem, e: React.DragEvent) => {
+ if (item.kind !== 'entity') return;
+ dragIds.current = selectionOrTarget(item.id);
e.dataTransfer.effectAllowed = 'move';
- e.dataTransfer.setData('text/plain', String(id));
+ e.dataTransfer.setData('text/plain', String(item.id));
};
- const onDragOverRow = (id: EntityId, e: React.DragEvent) => {
- // Either an in-progress entity reparent (move) or a Content-Browser asset
- // (copy) — both highlight the hovered row as the drop target.
+ const onDragOverRow = (item: OutlinerItem, e: React.DragEvent) => {
if (dragIds.current) e.dataTransfer.dropEffect = 'move';
else if (isAssetDrag(e)) e.dataTransfer.dropEffect = 'copy';
else return;
e.preventDefault();
- if (dropId !== id) setDropId(id);
+ if (dropId !== item.key) setDropId(item.key);
};
const reparent = (target: EntityId | null) => {
const ids = dragIds.current;
@@ -166,66 +207,93 @@ export function Outliner() {
if (!ids) return;
for (const child of ids) if (child !== target) SceneCommands.setParent(child, target);
};
- const onDropRow = (id: EntityId, e: React.DragEvent) => {
+ const moveToFolder = (path: string | null) => {
+ const ids = dragIds.current;
+ dragIds.current = null;
+ setDropId(null);
+ if (ids) SceneCommands.moveToFolder(ids, path);
+ };
+ const onDropRow = (item: OutlinerItem, e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setDropId(null);
- if (dropPrefabAsset(e, id)) return; // drop a prefab onto an entity = under it
- reparent(id);
+ if (item.kind === 'folder') {
+ if (dropPrefabAsset(e, null)) return; // prefab onto a folder → instantiate at root
+ moveToFolder(item.path);
+ return;
+ }
+ if (dropPrefabAsset(e, item.id)) return; // prefab onto an entity = under it
+ reparent(item.id);
};
- // Empty-space drag-drop (un-parent to root / instantiate a prefab at the root).
+ // Empty-space drop = move to the scene root (un-parent + clear folder).
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);
+ moveToFolder(null);
};
- const ctxItems: MenuItem[] = ctx
- ? [
- { label: 'Rename', shortcut: 'F2', onClick: () => setRenaming(ctx.id) },
- {
- label: 'Duplicate',
- shortcut: '⌘D',
- onClick: () => {
- const d = SceneCommands.duplicateEntity(ctx.id);
- if (d != null) select(d);
- },
+ const ctxItems: MenuItem[] = useMemo(() => {
+ if (!ctx) return [];
+ if (ctx.item.kind === 'folder') {
+ const path = ctx.item.path;
+ const sel = [...useSelection.getState().selectedIds];
+ return [
+ { label: 'Rename', shortcut: 'F2', onClick: () => setRenaming(folderKey(path)) },
+ { label: 'New Subfolder', onClick: () => newFolder(path, null) },
+ ...(sel.length ? [{ label: 'Move Selection Here', onClick: () => SceneCommands.moveToFolder(sel, path) } as MenuItem] : []),
+ { sep: true },
+ { label: 'Delete Folder', onClick: () => SceneCommands.deleteFolder(path) },
+ ];
+ }
+ const id = ctx.item.id;
+ return [
+ { label: 'Rename', shortcut: 'F2', onClick: () => setRenaming(entityKey(id)) },
+ {
+ label: 'Duplicate',
+ shortcut: '⌘D',
+ onClick: () => {
+ const d = SceneCommands.duplicateEntity(id);
+ if (d != null) select(d);
},
- { label: 'Create Prefab', onClick: () => void ProjectStore.createPrefabFromEntity(ctx.id) },
- {
- label: 'Delete',
- shortcut: '⌫',
- onClick: () => {
- selectionOrTarget(ctx.id).forEach((i) => SceneCommands.deleteEntity(i));
- select(null);
- },
+ },
+ { label: 'Create Prefab', onClick: () => void ProjectStore.createPrefabFromEntity(id) },
+ {
+ label: 'Delete',
+ shortcut: '⌫',
+ onClick: () => {
+ selectionOrTarget(id).forEach((i) => SceneCommands.deleteEntity(i));
+ select(null);
},
- { sep: true },
- { label: 'Unparent', onClick: () => selectionOrTarget(ctx.id).forEach((i) => SceneCommands.setParent(i, null)) },
- { label: 'Add Entity', onClick: addEntity },
- ]
- : [];
+ },
+ { sep: true },
+ { label: 'New Folder from Selection', onClick: () => newFolder('', selectionOrTarget(id)) },
+ { label: 'Move to Root', onClick: () => SceneCommands.moveToFolder(selectionOrTarget(id), null) },
+ { label: 'Unparent', onClick: () => selectionOrTarget(id).forEach((i) => SceneCommands.setParent(i, null)) },
+ { label: 'Add Entity', onClick: addEntity },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [ctx]);
// While playing, a UE5-style world picker switches the outliner (+ Details)
// between the edit scene and the live running game.
const gameMode = inspectWorld === 'game';
- const renderRow = (it: (typeof items)[number]) => (
+ const renderRow = (it: OutlinerItem) => (
<OutlinerRow
item={it}
- selected={selectedIds.has(it.id)}
- renaming={renaming === it.id}
- isDrop={dropId === it.id}
- prefab={SceneModel.prefabTag(it.id) != null}
- draggable
+ selected={it.kind === 'entity' && selectedIds.has(it.id)}
+ renaming={renaming === it.key}
+ isDrop={dropId === it.key}
+ prefab={it.kind === 'entity' && SceneModel.prefabTag(it.id) != null}
+ draggable={it.kind === 'entity'}
onToggle={toggleExpanded}
onClick={onRowClick}
onContextMenu={onContextMenu}
- onStartRename={setRenaming}
+ onStartRename={onStartRename}
onCommitRename={commitRename}
onToggleVisible={(id, visible) => SceneCommands.setEntityVisible(id, visible)}
onDragStart={onDragStartRow}
@@ -260,6 +328,9 @@ export function Outliner() {
onChange={(e) => setQuery(e.target.value)}
/>
</div>
+ <button type="button" className="pbtn" title="New folder" onClick={() => newFolder('', null)}>
+ <FolderPlus size={15} strokeWidth={2} />
+ </button>
<button type="button" className="pbtn" title="Add entity" onClick={addEntity}>
<Plus size={15} strokeWidth={2} />
</button>
diff --git a/desktop/src/theme/outliner.css b/desktop/src/theme/outliner.css
index 4345c36c9..7e3d7adeb 100644
--- a/desktop/src/theme/outliner.css
+++ b/desktop/src/theme/outliner.css
@@ -92,6 +92,11 @@
.row.sel .rvis:hover { color: #fff; }
.row.hidden .rname { color: var(--text-mute); }
+/* Folder rows (organizational path-folders) — read a touch stronger than entities. */
+.row.folder .ricon { color: var(--info-warm); }
+.row.sel.folder .ricon { color: #fff; }
+.row.folder .rname { color: var(--text); }
+
/* World picker (UE5): switch the Outliner/Details between edit + live game. */
.world-pick { display: flex; gap: 2px; padding: 6px 8px; border-bottom: 1px solid var(--border); flex-shrink: 0; }
.world-pick button { flex: 1; height: 24px; font-size: var(--fs-xs); color: var(--text-mute); background: var(--srf-3); border-radius: var(--r-sm); transition: color var(--t-fast), background var(--t-fast); }
diff --git a/desktop/tests/outliner-folders.test.ts b/desktop/tests/outliner-folders.test.ts
new file mode 100644
index 000000000..4dc866032
--- /dev/null
+++ b/desktop/tests/outliner-folders.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Outliner path-folders (REARCH_OUTLINER.md P2). Folders are organizational
+ * PATHS — a per-entity `folder` field + a scene-level explicit-folder list,
+ * orthogonal to the transform `parent`, lossless through save. Covers the
+ * pure path grammar, the undoable folder commands, and the serialize
+ * round-trip. Model+command only (no World — folders never reach the ECS).
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import type { SceneData } from 'esengine';
+import { EditorSession } from '@/engine/EditorSession';
+import {
+ normalizeFolder,
+ folderName,
+ folderParent,
+ joinFolder,
+ folderPrefixes,
+ isFolderUnder,
+ rebaseFolder,
+} from '@/outliner/folders';
+
+describe('folder path helpers', () => {
+ it('normalizeFolder collapses separators + trims segments', () => {
+ expect(normalizeFolder('a//b/ /c')).toBe('a/b/c');
+ expect(normalizeFolder(' ')).toBe('');
+ expect(normalizeFolder(undefined)).toBe('');
+ });
+ it('name / parent', () => {
+ expect(folderName('A/B/C')).toBe('C');
+ expect(folderParent('A/B/C')).toBe('A/B');
+ expect(folderParent('A')).toBe('');
+ expect(joinFolder('A/B', 'C')).toBe('A/B/C');
+ expect(joinFolder('', 'C')).toBe('C');
+ });
+ it('prefixes / containment', () => {
+ expect(folderPrefixes('A/B/C')).toEqual(['A', 'A/B', 'A/B/C']);
+ expect(folderPrefixes('')).toEqual([]);
+ expect(isFolderUnder('A/B/C', 'A/B')).toBe(true);
+ expect(isFolderUnder('A/BC', 'A/B')).toBe(false); // segment boundary, not a string prefix
+ expect(isFolderUnder('A', '')).toBe(true);
+ });
+ it('rebaseFolder re-roots a path (rename/move)', () => {
+ expect(rebaseFolder('A/B/C', 'A/B', 'X')).toBe('X/C');
+ expect(rebaseFolder('A/B', 'A/B', 'X/Y')).toBe('X/Y');
+ expect(rebaseFolder('Q', 'A/B', 'X')).toBeNull(); // not under the base
+ });
+});
+
+const ent = (id: number, parent: number | null) => ({ id, name: `E${id}`, parent, children: [] as number[], components: [] as unknown[] });
+const scene = (): SceneData =>
+ ({ version: '1.0', name: 'folders', entities: [ent(1, null), ent(2, null), ent(3, null)] }) as unknown as SceneData;
+
+describe('SceneCommands folders (undoable)', () => {
+ let S: EditorSession;
+ beforeEach(() => {
+ S = EditorSession.create();
+ S.model.adopt(scene(), new Map());
+ });
+
+ it('createFolder adds an explicit folder; undo removes it', () => {
+ S.commands.createFolder('Enemies');
+ expect(S.model.sceneFolders()).toContain('Enemies');
+ S.history.undo();
+ expect(S.model.sceneFolders()).not.toContain('Enemies');
+ });
+
+ it('moveToFolder sets the path; undo restores; no-op when already there', () => {
+ S.commands.moveToFolder([1, 2], 'Enemies/Bosses');
+ expect(S.model.folderOf(1)).toBe('Enemies/Bosses');
+ expect(S.model.folderOf(2)).toBe('Enemies/Bosses');
+ S.history.undo();
+ expect(S.model.folderOf(1)).toBe('');
+ expect(S.model.folderOf(2)).toBe('');
+ });
+
+ it('renameFolder re-roots the folder + every entity under it; undo reverts', () => {
+ S.commands.moveToFolder([1], 'A/B');
+ S.commands.moveToFolder([2], 'A');
+ S.commands.createFolder('A/Empty');
+ S.commands.renameFolder('A', 'World');
+ expect(S.model.folderOf(1)).toBe('World/B');
+ expect(S.model.folderOf(2)).toBe('World');
+ expect(S.model.sceneFolders()).toContain('World/Empty');
+ S.history.undo();
+ expect(S.model.folderOf(1)).toBe('A/B');
+ expect(S.model.sceneFolders()).toContain('A/Empty');
+ });
+
+ it('deleteFolder moves contents up to the parent (entities survive); undo reverts', () => {
+ S.commands.moveToFolder([1], 'A/B');
+ S.commands.createFolder('A/B/C');
+ S.commands.deleteFolder('A/B');
+ expect(S.model.folderOf(1)).toBe('A'); // moved up one level
+ expect(S.model.sceneFolders()).toContain('A/C'); // descendant folder re-homed
+ expect(S.model.sceneFolders()).not.toContain('A/B');
+ S.history.undo();
+ expect(S.model.folderOf(1)).toBe('A/B');
+ expect(S.model.sceneFolders()).toContain('A/B/C');
+ });
+
+ it('folders round-trip through serialize (lossless, editor-only)', () => {
+ S.commands.moveToFolder([1], 'Enemies');
+ S.commands.createFolder('Empty/Leaf');
+ const out = S.model.serialize() as SceneData & { folders?: string[] };
+ const e1 = out.entities.find((e) => e.id === 1) as { folder?: string };
+ expect(e1.folder).toBe('Enemies');
+ expect(out.folders).toContain('Empty/Leaf');
+ // The World projection never sees folders — they're not components/parent/name.
+ });
+});
diff --git a/desktop/tests/outliner-model.test.ts b/desktop/tests/outliner-model.test.ts
index 070ed6b3d..e9e278166 100644
--- a/desktop/tests/outliner-model.test.ts
+++ b/desktop/tests/outliner-model.test.ts
@@ -2,14 +2,20 @@
// 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`).
+ * Flattens a SceneData to render-ordered rows (entity | folder) honoring a
+ * string-keyed expansion set + a name filter; folders group ROOT entities
+ * by path (orthogonal to the transform `parent`). Pure projection.
*/
import { describe, it, expect } from 'vitest';
import type { SceneData } from 'esengine';
import type { EntityId } from '@/types';
-import { buildOutlinerItems, collectExpandableIds } from '@/outliner/OutlinerModel';
+import {
+ buildOutlinerItems,
+ collectExpandableKeys,
+ entityKey,
+ folderKey,
+ type OutlinerItem,
+} from '@/outliner/OutlinerModel';
const ent = (id: number, parent: number | null) => ({ id, name: `E${id}`, parent, children: [], components: [] as unknown[] });
@@ -19,44 +25,100 @@ 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);
+const keys = (items: OutlinerItem[]) => items.map((i) => i.key);
-describe('buildOutlinerItems', () => {
+describe('buildOutlinerItems — entities', () => {
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' });
+ expect(keys(items)).toEqual(['e1']);
+ expect(items[0]).toMatchObject({ kind: 'entity', depth: 0, hasChildren: true, expanded: false, parentKey: null });
});
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]);
+ expect(keys(buildOutlinerItems(scene(), { expanded: new Set([entityKey(1)]) }))).toEqual(['e1', 'e2', 'e5']);
+ expect(keys(buildOutlinerItems(scene(), { expanded: new Set([entityKey(1), entityKey(2)]) }))).toEqual(['e1', 'e2', 'e3', 'e5']);
});
- 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('depth + parentKey track the hierarchy', () => {
+ const items = buildOutlinerItems(scene(), { expanded: new Set([entityKey(1), entityKey(2)]) });
+ const byKey = new Map(items.map((i) => [i.key, i]));
+ expect(byKey.get('e2')).toMatchObject({ depth: 1, parentKey: 'e1' });
+ expect(byKey.get('e3')).toMatchObject({ depth: 2, parentKey: 'e2' });
+ expect(byKey.get('e5')).toMatchObject({ depth: 1, parentKey: 'e1' });
});
- it('expandAll renders the whole tree regardless of the expansion set (PIE)', () => {
- expect(itemIds(scene(), [], { expandAll: true })).toEqual([1, 2, 3, 5]);
+ it('expandAll renders the whole tree regardless of expansion (PIE)', () => {
+ expect(keys(buildOutlinerItems(scene(), { expanded: new Set(), expandAll: true }))).toEqual(['e1', 'e2', 'e3', 'e5']);
});
- 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('a query keeps matches + ancestors and force-expands', () => {
+ expect(keys(buildOutlinerItems(scene(), { expanded: new Set(), query: 'E3' }))).toEqual(['e1', 'e2', 'e3']);
+ expect(buildOutlinerItems(scene(), { expanded: new Set(), query: 'nope' })).toEqual([]);
});
it('null data → empty list', () => {
expect(buildOutlinerItems(null, { expanded: new Set() })).toEqual([]);
});
+});
+
+// Roots 1 / 10 / 11; 1→"Enemies", 10→"Enemies/Bosses", 11→root. 2 is a child of 1.
+function folderScene(): { data: SceneData; folderOf: (id: EntityId) => string } {
+ const data = {
+ version: '1.0',
+ name: 'folders',
+ entities: [ent(1, null), ent(2, 1), ent(10, null), ent(11, null)],
+ } as unknown as SceneData;
+ const map: Record<number, string> = { 1: 'Enemies', 10: 'Enemies/Bosses', 11: '' };
+ return { data, folderOf: (id) => map[id] ?? '' };
+}
+
+describe('buildOutlinerItems — folders', () => {
+ it('groups root entities under nested folder rows (orthogonal to parent)', () => {
+ const { data, folderOf } = folderScene();
+ const items = buildOutlinerItems(data, { expanded: new Set(), folderOf, expandAll: true });
+ expect(keys(items)).toEqual([
+ folderKey('Enemies'),
+ folderKey('Enemies/Bosses'),
+ 'e10', // root inside Enemies/Bosses
+ 'e1', // root inside Enemies
+ 'e2', // child of 1 (transform parent), one level deeper
+ 'e11', // scene-root entity (no folder)
+ ]);
+ });
+
+ it('folder rows carry name, recursive count, depth, parentKey', () => {
+ const { data, folderOf } = folderScene();
+ const items = buildOutlinerItems(data, { expanded: new Set(), folderOf, expandAll: true });
+ const byKey = new Map(items.map((i) => [i.key, i]));
+ expect(byKey.get(folderKey('Enemies'))).toMatchObject({ kind: 'folder', name: 'Enemies', count: 2, depth: 0, parentKey: null });
+ expect(byKey.get(folderKey('Enemies/Bosses'))).toMatchObject({ name: 'Bosses', count: 1, depth: 1, parentKey: folderKey('Enemies') });
+ expect(byKey.get('e10')).toMatchObject({ depth: 2, parentKey: folderKey('Enemies/Bosses') });
+ expect(byKey.get('e11')).toMatchObject({ depth: 0, parentKey: null });
+ });
+
+ it('a collapsed folder hides its contents', () => {
+ const { data, folderOf } = folderScene();
+ // Only "Enemies" open → Bosses shows collapsed (e10 hidden), e1 collapsed (e2 hidden).
+ const items = buildOutlinerItems(data, { expanded: new Set([folderKey('Enemies')]), folderOf });
+ expect(keys(items)).toEqual([folderKey('Enemies'), folderKey('Enemies/Bosses'), 'e1', 'e11']);
+ });
+
+ it('explicit empty folders still show (no query)', () => {
+ const { data, folderOf } = folderScene();
+ const items = buildOutlinerItems(data, { expanded: new Set(), folderOf, folders: ['Empty/Leaf'], expandAll: true });
+ const folders = items.filter((i) => i.kind === 'folder').map((i) => i.key);
+ expect(folders).toContain(folderKey('Empty'));
+ expect(folders).toContain(folderKey('Empty/Leaf'));
+ expect(items.find((i) => i.key === folderKey('Empty/Leaf'))).toMatchObject({ count: 0, hasChildren: false });
+ });
- it('collectExpandableIds = every node that has children', () => {
- expect(ids(collectExpandableIds(scene())).sort()).toEqual([1, 2]);
+ it('collectExpandableKeys = entity parents + every folder', () => {
+ const { data, folderOf } = folderScene();
+ const ks = new Set(collectExpandableKeys(data, { folderOf, folders: ['Empty'] }));
+ expect(ks).toContain(entityKey(1)); // has child 2
+ expect(ks).toContain(folderKey('Enemies'));
+ expect(ks).toContain(folderKey('Enemies/Bosses'));
+ expect(ks).toContain(folderKey('Empty'));
+ expect(ks.has(entityKey(10))).toBe(false); // leaf, not expandable
});
});