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.

perf(editor): the Content Browser mounted a tile per file in the folder

esenginee01ca7974e04
diff --git a/desktop/src/components/VirtualGrid.tsx b/desktop/src/components/VirtualGrid.tsx
new file mode 100644
index 000000000..37d9746e5
--- /dev/null
+++ b/desktop/src/components/VirtualGrid.tsx
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file VirtualGrid.tsx — a windowed auto-fill tile grid.
+ *
+ * The Content Browser's half of the virtualization {@link VirtualTree} does for
+ * the outliner: a folder is however many files the user put in it, and mounting a
+ * tile per entry is how opening one costs thousands of DOM nodes and an image
+ * decode apiece. Only the rows in the scroll window exist.
+ *
+ * Columns are computed, not observed. `repeat(auto-fill, minmax(T, 1fr))` fits the
+ * largest n where `n·T + (n-1)·gap ≤ W`, and each row here is laid out as
+ * `repeat(n, 1fr)` with the same gap — the same tiles at the same widths, but a
+ * number this component knows, so keyboard navigation can move by a row without
+ * asking the DOM where the rows happened to break.
+ *
+ * Row height is MEASURED from a real row rather than derived: a tile is a square
+ * thumbnail plus a name strip whose height is the stylesheet's business, and a
+ * virtualizer that guesses it drifts a row per screenful.
+ */
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
+import { useVirtualWindow } from './virtualWindow';
+
+interface VirtualGridProps<T> {
+ items: T[];
+ /** The scroller to window — the caller's, so it keeps its own event handlers. */
+ scrollRef: RefObject<HTMLDivElement | null>;
+ /** Minimum tile width in px — the `minmax()` floor. Ignored when `columns` is set. */
+ tileSize: number;
+ /** Gap between tiles in px; must match the stylesheet's. */
+ gap: number;
+ /** Fix the column count instead of fitting it to the width — `1` is a list. */
+ columns?: number;
+ /** Row height to assume for the first render only, before one is measured.
+ * Defaults to a square tile plus a name strip, which is what a grid row is. */
+ estimatedRowHeight?: number;
+ /** Rows kept rendered just outside the window. A grid row is a whole rowful of
+ * tiles, so the default is far smaller than a list's. */
+ overscan?: number;
+ /** Renders one tile; the returned element carries its own React key. */
+ renderItem: (item: T, index: number) => ReactNode;
+ /** ITEM index to scroll into view; paired with `scrollNonce`. */
+ scrollToIndex?: number;
+ scrollNonce?: number;
+ /** Reports the live column count, so a caller's arrow keys move by a real row. */
+ onColumns?: (columns: number) => void;
+}
+
+/** The width available to the grid — the scroller's content box, padding removed. */
+function useContentWidth(ref: RefObject<HTMLDivElement | null>): number {
+ const [width, setWidth] = useState(0);
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const update = (): void => {
+ const cs = getComputedStyle(el);
+ setWidth(Math.max(0, el.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight)));
+ };
+ update();
+ const ro = new ResizeObserver(update);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [ref]);
+ return width;
+}
+
+export function VirtualGrid<T>({
+ items,
+ scrollRef,
+ tileSize,
+ gap,
+ columns: fixedColumns,
+ estimatedRowHeight,
+ overscan = 2,
+ renderItem,
+ scrollToIndex,
+ scrollNonce,
+ onColumns,
+}: VirtualGridProps<T>) {
+ const width = useContentWidth(scrollRef);
+ const columns = fixedColumns ?? (width > 0 ? Math.max(1, Math.floor((width + gap) / (tileSize + gap))) : 1);
+
+ // Measured through a REF CALLBACK, not an effect: the probe is whichever row
+ // happens to be first in the window, so it is replaced by a different element
+ // every time the window moves. An effect keyed on anything else keeps observing
+ // the row that scrolled away — and a detached element reports zero, which sent
+ // the row height back to the estimate and the scrollbar to nonsense.
+ const [rowSize, setRowSize] = useState(0);
+ const observer = useRef<ResizeObserver | null>(null);
+ const probeRef = useCallback((el: HTMLDivElement | null) => {
+ observer.current?.disconnect();
+ observer.current = null;
+ if (!el) return;
+ // Never accept zero: a row mid-teardown has no height, and it is not news.
+ const measure = (): void => setRowSize((h) => el.offsetHeight || h);
+ measure();
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ observer.current = ro;
+ }, []);
+ useEffect(() => () => observer.current?.disconnect(), []);
+
+ const estimated = estimatedRowHeight ?? Math.floor((width - gap * (columns - 1)) / columns) + 30;
+ const rowHeight = Math.max(1, rowSize || estimated) + gap;
+
+ const rows = Math.ceil(items.length / columns);
+ const win = useVirtualWindow({
+ rows,
+ rowHeight,
+ overscan,
+ scrollRef,
+ scrollToIndex: scrollToIndex == null || scrollToIndex < 0 ? undefined : Math.floor(scrollToIndex / columns),
+ scrollNonce,
+ });
+
+ useEffect(() => onColumns?.(columns), [columns, onColumns]);
+
+ return (
+ <div ref={win.sizerRef} style={{ height: win.totalHeight, position: 'relative' }}>
+ {Array.from({ length: Math.max(0, win.end - win.start) }, (_, r) => {
+ const row = win.start + r;
+ const from = row * columns;
+ return (
+ <div
+ key={row}
+ ref={r === 0 ? probeRef : undefined}
+ style={{
+ display: 'grid',
+ // minmax(0, …), not a bare `1fr`: `1fr` floors each track at the
+ // tile's min-content, and a tile whose name does not wrap has a
+ // min-content as wide as the name — one long filename would widen
+ // every column and push the row past the scroller.
+ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
+ gap: `${gap}px`,
+ position: 'absolute',
+ top: row * rowHeight,
+ left: 0,
+ right: 0,
+ }}
+ >
+ {items.slice(from, from + columns).map((item, c) => renderItem(item, from + c))}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/desktop/src/components/VirtualTree.tsx b/desktop/src/components/VirtualTree.tsx
index 7605abd33..cfc5fad68 100644
--- a/desktop/src/components/VirtualTree.tsx
+++ b/desktop/src/components/VirtualTree.tsx
@@ -6,20 +6,15 @@
* 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.
+ * {@link buildOutlinerItems}); this owns no hierarchy — just the layout. Which
+ * rows are on screen is {@link useVirtualWindow}'s, shared with VirtualGrid.
* Shared by the editor + live-game 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';
+import type { HTMLAttributes, Key, ReactNode } from 'react';
+import { useVirtualWindow } from './virtualWindow';
interface VirtualTreeProps<T> extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
items: T[];
@@ -37,58 +32,22 @@ interface VirtualTreeProps<T> extends Omit<HTMLAttributes<HTMLDivElement>, 'chil
export function VirtualTree<T>({
items,
rowHeight,
- overscan = 8,
+ overscan,
renderRow,
getKey,
scrollToIndex,
scrollNonce,
- 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();
- }, []);
-
- // Controlled scroll-into-view (reveal-on-select / keyboard nav): only moves when
- // the target row is outside the window, so an in-view selection never jumps.
- useEffect(() => {
- const el = scrollRef.current;
- if (!el || scrollToIndex == null || scrollToIndex < 0) return;
- const top = scrollToIndex * rowHeight;
- const bottom = top + rowHeight;
- if (top < el.scrollTop) el.scrollTop = top;
- else if (bottom > el.scrollTop + el.clientHeight) el.scrollTop = bottom - el.clientHeight;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [scrollNonce]);
-
- 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);
+ const win = useVirtualWindow({ rows: items.length, rowHeight, overscan, scrollToIndex, scrollNonce });
return (
- <div
- ref={scrollRef}
- {...rest}
- onScroll={(e) => {
- setScrollTop(e.currentTarget.scrollTop);
- onScroll?.(e);
- }}
- >
+ <div ref={win.scrollRef} {...rest}>
{/* Virtualization sizer — presentational so it doesn't sit between a
role="tree" container and its role="treeitem" rows. */}
- <div role="presentation" style={{ height: total * rowHeight, position: 'relative' }}>
- {items.slice(start, end).map((item, i) => {
- const index = start + i;
+ <div ref={win.sizerRef} role="presentation" style={{ height: win.totalHeight, position: 'relative' }}>
+ {items.slice(win.start, win.end).map((item, i) => {
+ const index = win.start + i;
return (
<div
key={getKey(item, index)}
diff --git a/desktop/src/components/virtualWindow.ts b/desktop/src/components/virtualWindow.ts
new file mode 100644
index 000000000..16c284cd7
--- /dev/null
+++ b/desktop/src/components/virtualWindow.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file virtualWindow.ts — which rows are on screen, for every windowed panel.
+ *
+ * The one piece both {@link VirtualTree} and {@link VirtualGrid} need and neither
+ * should own: a scroll offset, a viewport height, and the row range they imply.
+ * Layout is the caller's — a tree lays one item per row, a grid lays a rowful —
+ * and this answers only "which rows, and how tall is the whole thing".
+ *
+ * Rows, not items: a grid's row is several tiles wide, so windowing in ROWS is
+ * what keeps the two callers on one implementation.
+ *
+ * The scroller may be the caller's own (the Content Browser's carries the
+ * keyboard, the click-to-deselect and the file drop), and the windowed area need
+ * not start at its top — so the distance between them is MEASURED rather than
+ * declared. A caller that gets that number wrong scrolls to the wrong row, and it
+ * is not a number anyone should have to keep in sync with a stylesheet.
+ */
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react';
+
+export interface VirtualWindowOptions {
+ /** Total rows in the list (items for a tree, item rows for a grid). */
+ rows: number;
+ rowHeight: number;
+ /** Rows kept rendered just outside the window (smooths fast scroll). */
+ overscan?: number;
+ /** Scroll into view (only if off-screen); paired with `scrollNonce`. */
+ scrollToIndex?: number;
+ /** Bump to re-trigger a scroll to the SAME index (controlled imperative scroll). */
+ scrollNonce?: number;
+ /** Scroller to window, when the caller owns it. Omitted ⇒ attach `scrollRef`. */
+ scrollRef?: RefObject<HTMLDivElement | null>;
+}
+
+export interface VirtualWindow {
+ /** Attach to the scrolling element (unless one was supplied). */
+ scrollRef: RefObject<HTMLDivElement | null>;
+ /** Attach to the full-height spacer the rows are positioned inside. */
+ sizerRef: RefObject<HTMLDivElement | null>;
+ /** Row range to render, overscan included (`end` exclusive). */
+ start: number;
+ end: number;
+ /** Height the spacer needs so the scrollbar matches the un-rendered whole. */
+ totalHeight: number;
+ /** Bring a row into view now, without waiting for a render (keyboard nav). */
+ scrollRowIntoView: (row: number) => void;
+}
+
+export function useVirtualWindow(opts: VirtualWindowOptions): VirtualWindow {
+ const { rows, rowHeight, overscan = 8, scrollToIndex, scrollNonce } = opts;
+ const ownRef = useRef<HTMLDivElement>(null);
+ const scrollRef = opts.scrollRef ?? ownRef;
+ const sizerRef = useRef<HTMLDivElement>(null);
+ const [scrollTop, setScrollTop] = useState(0);
+ const [viewH, setViewH] = useState(600);
+ // Distance from the scroller's content top to row 0 — the scroller's padding
+ // plus whatever it renders above the window (the list view's column header).
+ const [lead, setLead] = useState(0);
+
+ // A native listener, not React's onScroll: the scroller may be the caller's
+ // element, and there is nowhere to hand it a prop.
+ useLayoutEffect(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ const update = (): void => {
+ setViewH(el.clientHeight);
+ const sizer = sizerRef.current;
+ if (sizer) setLead(sizer.getBoundingClientRect().top - el.getBoundingClientRect().top + el.scrollTop);
+ };
+ const onScroll = (): void => setScrollTop(el.scrollTop);
+ update();
+ onScroll();
+ el.addEventListener('scroll', onScroll, { passive: true });
+ const ro = new ResizeObserver(update);
+ ro.observe(el);
+ if (sizerRef.current) ro.observe(sizerRef.current);
+ return () => {
+ el.removeEventListener('scroll', onScroll);
+ ro.disconnect();
+ };
+ }, [scrollRef]);
+
+ // Only moves when the target row is outside the window, so an in-view selection
+ // never jumps under the user.
+ const scrollRowIntoView = useCallback((row: number): void => {
+ const el = scrollRef.current;
+ if (!el || row < 0) return;
+ const top = lead + row * rowHeight;
+ const bottom = top + rowHeight;
+ if (top < el.scrollTop) el.scrollTop = top;
+ else if (bottom > el.scrollTop + el.clientHeight) el.scrollTop = bottom - el.clientHeight;
+ }, [scrollRef, lead, rowHeight]);
+
+ const latest = useRef(scrollRowIntoView);
+ latest.current = scrollRowIntoView;
+ useEffect(() => {
+ if (scrollToIndex != null) latest.current(scrollToIndex);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [scrollNonce]);
+
+ const above = Math.max(0, scrollTop - lead);
+ return {
+ scrollRef,
+ sizerRef,
+ start: Math.max(0, Math.floor(above / rowHeight) - overscan),
+ end: Math.min(rows, Math.ceil((above + viewH) / rowHeight) + overscan),
+ totalHeight: rows * rowHeight,
+ scrollRowIntoView,
+ };
+}
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index a17be9ee4..195939f1a 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -6,6 +6,7 @@ import { AssetIcon, assetTint } from '@/components/icons';
import { EmptyState } from '@/components/EmptyState';
import { IconButton } from '@/components/IconButton';
import { ConfirmDialog } from '@/components/ConfirmDialog';
+import { VirtualGrid } from '@/components/VirtualGrid';
import { SearchField } from '@/components/SearchField';
import { ContextMenu, type MenuItem } from '@/components/Menu';
import { useTooltip } from '@/components/Tooltip';
@@ -42,6 +43,10 @@ import type { AssetType } from '@/types';
const TILE_MIN = 64;
const TILE_MAX = 152;
const TILE_KEY = 'estella.content.tileSize';
+// Must match the `gap` on .cb-grid in content.css — the grid lays its own rows out.
+const GRID_GAP = 10;
+// Must match .lr in content.css — the first-render guess, before one is measured.
+const LIST_ROW_H = 30;
const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e));
@@ -446,14 +451,23 @@ export function ContentBrowser() {
);
const listLoading = searching ? scan.loading : dirLoading;
+ // Scrolling is by INDEX, not by finding the element: with the list windowed, the
+ // row being revealed is usually not in the DOM to be found.
+ const [scrollTo, setScrollTo] = useState<{ index: number; nonce: number }>({ index: -1, nonce: 0 });
+ const scrollNonce = useRef(0);
+ const revealIndex = useCallback(
+ (index: number) => setScrollTo({ index, nonce: ++scrollNonce.current }),
+ [],
+ );
+
useEffect(() => {
- if (!pendingReveal || !items.some((it) => it.path === pendingReveal)) return;
+ if (!pendingReveal) return;
+ const index = items.findIndex((it) => it.path === pendingReveal);
+ if (index < 0) return;
selectAsset(pendingReveal);
setPendingReveal(null);
- requestAnimationFrame(() => {
- document.querySelector(`[data-path="${CSS.escape(pendingReveal)}"]`)?.scrollIntoView({ block: 'nearest' });
- });
- }, [pendingReveal, items, selectAsset]);
+ revealIndex(index);
+ }, [pendingReveal, items, selectAsset, revealIndex]);
// Double-click: enter folders; otherwise dispatch through the per-type open
// table (scene/clip/tileset editors).
@@ -595,14 +609,10 @@ export function ContentBrowser() {
// consumed even with nothing selected, so it can never fall through to the
// global entity delete while the user is working in the browser.
const scrollRef = useRef<HTMLDivElement>(null);
- const gridColumns = () => {
- const tiles = scrollRef.current?.querySelectorAll<HTMLElement>('[data-path]');
- if (!tiles || tiles.length < 2) return 1;
- const top0 = tiles[0].offsetTop;
- let cols = 1;
- while (cols < tiles.length && tiles[cols].offsetTop === top0) cols++;
- return cols;
- };
+ // Reported by the grid, which decides the count rather than reading it back off
+ // the laid-out tiles — with only a window of them mounted, there is no longer a
+ // full first row to measure where the wrap fell.
+ const [gridColumns, setGridColumns] = useState(1);
const onGridKey = (e: React.KeyboardEvent) => {
const el = e.target as HTMLElement;
if (el.tagName === 'INPUT' || renaming != null) return; // typing / inline rename
@@ -613,11 +623,7 @@ export function ContentBrowser() {
// Shift+arrow grows the multi-selection to the new item; plain arrow replaces.
if (extend) selectAssets([...new Set([...selectedAssets, it.path])], it.path);
else selectAsset(it.path);
- requestAnimationFrame(() => {
- scrollRef.current
- ?.querySelector(`[data-path="${CSS.escape(it.path)}"]`)
- ?.scrollIntoView({ block: 'nearest' });
- });
+ revealIndex(items.indexOf(it));
};
switch (e.key) {
case 'ArrowLeft':
@@ -626,7 +632,7 @@ export function ContentBrowser() {
case 'ArrowDown': {
e.preventDefault();
e.stopPropagation(); // grid navigation, not the viewport's selection nudge
- const rowStep = view === 'grid' ? gridColumns() : 1;
+ const rowStep = view === 'grid' ? gridColumns : 1;
const step =
e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : e.key === 'ArrowDown' ? rowStep : -rowStep;
focusIndex(idx < 0 ? 0 : idx + step, e.shiftKey);
@@ -1224,9 +1230,9 @@ export function ContentBrowser() {
<EmptyState icon={Folder} title={t('cb.emptyFolderTitle')} hint={t('cb.emptyFolder')} />
)
) : view === 'grid' ? (
- <div className="cb-grid" style={{ ['--tile' as string]: `${tileSize}px` } as React.CSSProperties}>
- {listLoading &&
- Array.from({ length: 8 }, (_, i) => (
+ listLoading ? (
+ <div className="cb-grid" style={{ ['--tile' as string]: `${tileSize}px` } as React.CSSProperties}>
+ {Array.from({ length: 8 }, (_, i) => (
<div key={i} className="asset is-skel" aria-hidden="true">
<div className="th skel" />
<div className="nm">
@@ -1234,7 +1240,17 @@ export function ContentBrowser() {
</div>
</div>
))}
- {!listLoading && items.map((it) => {
+ </div>
+ ) : (
+ <VirtualGrid
+ items={items}
+ scrollRef={scrollRef}
+ tileSize={tileSize}
+ gap={GRID_GAP}
+ scrollToIndex={scrollTo.index}
+ scrollNonce={scrollTo.nonce}
+ onColumns={setGridColumns}
+ renderItem={(it) => {
const path = it.path;
const type: AssetType = it.isDir ? 'folder' : typeAt(path);
const isImg = !it.isDir && IMAGE_RE.test(it.name);
@@ -1296,8 +1312,9 @@ export function ContentBrowser() {
</div>
</div>
);
- })}
- </div>
+ }}
+ />
+ )
) : (
<div className="cb-list">
<div className="lh">
@@ -1315,7 +1332,17 @@ export function ContentBrowser() {
</span>
</div>
))}
- {!listLoading && items.map((it) => {
+ {!listLoading && (
+ <VirtualGrid
+ items={items}
+ scrollRef={scrollRef}
+ columns={1}
+ tileSize={0}
+ gap={0}
+ estimatedRowHeight={LIST_ROW_H}
+ scrollToIndex={scrollTo.index}
+ scrollNonce={scrollTo.nonce}
+ renderItem={(it) => {
const path = it.path;
const type: AssetType = it.isDir ? 'folder' : typeAt(path);
return (
@@ -1347,7 +1374,9 @@ export function ContentBrowser() {
<span className="c">{it.isDir ? '' : TYPE_CODE[type] || type}</span>
</div>
);
- })}
+ }}
+ />
+ )}
</div>
)}
</div>