perf(tree): virtualize the file tree

Open folders flatten into rows with a depth and only the rows near the
viewport render (@tanstack/react-virtual, window scrolling, fixed row
height). Values still line up: each row is the same two-column grid with
the indent inside the first cell, and the name column's width is computed
from the longest visible name (monospace), capped at half the width.
Indent guides are drawn per row.

Keyboard navigation works by row index (scrolling a row in when needed,
counting quick presses from a pending target) and lands below the sticky
header. Used by both the find and files pages; the subgrid layout and the
content-visibility rule are gone.

At 4x CPU on com.apple.private.tcc.allow (788 rows): Expand all 292 →
49 ms, clearing the value filter 314 → 61 ms, resize 1.2 → 0.4 s, ~6x
fewer DOM nodes. Find-in-page only sees rendered rows; the filter
searches all of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ccandClaude Opus 5.5 committed 2026-12-03 17:55:55 +01:00
1 parent 36d9668b88
commit fdf0ab052b
2 files changed
+409 -333

No files matched your search

-13
View File
@@ -228,16 +228,3 @@
visibility: visible;
}
}
/*
* Off-screen value cells skip style, layout and paint (their chips, … button
* and its animation are most of an expanded tree's DOM). Only the value cell:
* content-visibility implies layout containment, which a subgrid row can't
* have, and size-contained name cells would stop counting toward the name
* column's width, so it would shift while scrolling. The value column's
* width comes from its track, so only the height needs a placeholder.
*/
.value-row {
content-visibility: auto;
contain-intrinsic-block-size: auto 1.25rem;
}
+409 -320
View File
@@ -1,3 +1,21 @@
"use client";
/**
* The file tree as a virtualized flat list.
*
* Open folders flatten into rows with a depth; only rows near the viewport
* are rendered (@tanstack/react-virtual, window scrolling, fixed row
* height), so expanding everything or changing a filter costs the same
* however large the tree is. Values still line up: every row is the same
* two-column grid, the indent sits inside the first cell, and the first
* column's width is computed from the longest visible name (names are
* monospace), capped at half the width. Indent guides are drawn per row.
*
* Trade-off: the browser's find-in-page only sees rendered rows; the page's
* filter searches all of them.
*/
import { useWindowVirtualizer } from "@tanstack/react-virtual";
import {
ChevronDown,
ChevronRight,
@@ -6,123 +24,177 @@ import {
Minus,
Plus,
} from "lucide-react";
import Link from "next/link";
import {
createContext,
memo,
useContext,
useEffect,
useId,
useCallback,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { ValuePreview } from "@/components/value-preview";
import filesToTree, { type TreeWithFullPath } from "@/lib/tree";
import Link from "next/link";
import { cn } from "@/lib/utils";
export type PathStatus = "added" | "removed";
/**
* Optional diff marks: which paths were gained/lost, and which OS a lost path
* should link to (it no longer exists in the current one).
*/
interface Marks {
status?: (path: string) => PathStatus | undefined;
osFor?: (path: string) => string | undefined;
/** Shows each binary's entitlement value next to its name. */
valueFor?: (path: string) => unknown;
/** Atoms to mark in the values (the active value filter). */
highlight?: readonly string[];
/** Clicking a value item toggles it in the value filter. */
onPickValue?: (atom: string) => void;
}
const MarksContext = createContext<Marks>({});
const ROW = 30; // px: a 28 px row and a 2 px gap
const HEADER = 72; // px covered at the top by the site header (rows' scroll-mt)
const INDENT = 25; // px per level: 24 px and the guide line's 1 px
const GUIDE_X = 16; // px: a folder's guide line, from its own left edge
const NO_HIGHLIGHT: readonly string[] = [];
/**
* With values, the tree is one grid of two columns (name, values) that every
* level shares through subgrid, so values line up at any depth: an indented
* level's margin, padding and border come out of the name column only.
*/
const COLUMNS =
"grid grid-cols-1 sm:grid-cols-[fit-content(50%)_minmax(0,1fr)]";
const SUBGRID = "col-span-full grid grid-cols-subgrid";
/** SUBGRID when the tree shows values, else nothing. */
function useSubgrid() {
return useContext(MarksContext).valueFor ? SUBGRID : "";
}
function countMarks(item: TreeWithFullPath, status: Marks["status"]) {
let added = 0;
let removed = 0;
if (!status) return { added, removed };
for (const value of Object.values(item)) {
if (typeof value === "string") {
const mark = status(value);
if (mark === "added") added++;
else if (mark === "removed") removed++;
} else {
const sub = countMarks(value, status);
added += sub.added;
removed += sub.removed;
}
}
return { added, removed };
}
function countItems(item: TreeWithFullPath): number {
let count = 0;
for (const value of Object.values(item)) {
if (typeof value === "string") {
count++;
} else {
count += countItems(value);
}
}
return count;
}
function getMaxDepth(item: TreeWithFullPath, current = 0): number {
let max = current;
for (const value of Object.values(item)) {
if (typeof value !== "string") {
max = Math.max(max, getMaxDepth(value, current + 1));
}
}
return max;
}
const FileItem = memo(function FileItem({
name,
fullPath,
os,
}: {
interface FolderRow {
kind: "folder";
id: string;
name: string;
fullPath: string;
os: string;
}) {
const marks = useContext(MarksContext);
const mark = marks.status?.(fullPath);
const linkOs = marks.osFor?.(fullPath) ?? os;
const columns = !!marks.valueFor;
depth: number;
count: number;
added: number;
removed: number;
open: boolean;
}
interface FileRow {
kind: "file";
id: string;
name: string;
depth: number;
}
type Row = FolderRow | FileRow;
interface FolderInfo {
count: number;
added: number;
removed: number;
}
/** Counts per folder id (its path), in one pass. */
function folderInfo(
tree: TreeWithFullPath,
status: ((path: string) => PathStatus | undefined) | undefined,
) {
const info = new Map<string, FolderInfo>();
const walk = (node: TreeWithFullPath, id: string): FolderInfo => {
const total = { count: 0, added: 0, removed: 0 };
for (const [name, child] of Object.entries(node)) {
if (typeof child === "string") {
total.count++;
const mark = status?.(child);
if (mark === "added") total.added++;
else if (mark === "removed") total.removed++;
} else {
const sub = walk(child, `${id}/${name}`);
total.count += sub.count;
total.added += sub.added;
total.removed += sub.removed;
}
}
info.set(id, total);
return total;
};
walk(tree, "");
return info;
}
function allFolders(tree: TreeWithFullPath, id = "", out: string[] = []) {
for (const [name, child] of Object.entries(tree)) {
if (typeof child !== "string") {
out.push(`${id}/${name}`);
allFolders(child, `${id}/${name}`, out);
}
}
return out;
}
/** Visible rows: folders then files per level, children of open folders. */
function flatten(
tree: TreeWithFullPath,
open: Set<string>,
info: Map<string, FolderInfo>,
) {
const rows: Row[] = [];
const walk = (node: TreeWithFullPath, id: string, depth: number) => {
const entries = Object.entries(node);
for (const [name, child] of entries) {
if (typeof child === "string") continue;
const folderId = `${id}/${name}`;
const isOpen = open.has(folderId);
const counts = info.get(folderId) ?? { count: 0, added: 0, removed: 0 };
rows.push({
kind: "folder",
id: folderId,
name,
depth,
open: isOpen,
...counts,
});
if (isOpen) walk(child, folderId, depth + 1);
}
for (const [name, child] of entries) {
if (typeof child === "string")
rows.push({ kind: "file", id: child, name, depth });
}
};
walk(tree, "", 0);
return rows;
}
function defaultOpen(tree: TreeWithFullPath, expandAll: boolean | null) {
if (expandAll === true) return new Set(allFolders(tree));
if (expandAll === false) return new Set<string>();
// Top-level folders open, as in the nested tree.
return new Set(
Object.entries(tree)
.filter(([, child]) => typeof child !== "string")
.map(([name]) => `/${name}`),
);
}
function Guides({ depth }: { depth: number }) {
return (
<div
className={cn(
"items-center py-1 px-1 rounded transition-colors",
columns ? SUBGRID : "flex gap-2",
mark === "added"
? "bg-emerald-50 text-emerald-800 hover:bg-emerald-100 dark:bg-emerald-950/30 dark:text-emerald-200 dark:hover:bg-emerald-950/50"
: mark === "removed"
? "bg-red-50 text-red-800 hover:bg-red-100 dark:bg-red-950/30 dark:text-red-200 dark:hover:bg-red-950/50"
: "hover:bg-accent",
)}
>
{/* Icon and name: the first column. */}
<span className="flex min-w-0 items-center gap-2">
<>
{Array.from({ length: depth }, (_, d) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: one per level
key={d}
aria-hidden
className="absolute inset-y-0 w-px bg-border"
style={{ left: d * INDENT + GUIDE_X }}
/>
))}
</>
);
}
const FileLine = memo(function FileLine({
row,
os,
mark,
linkOs,
value,
showValue,
highlight,
onPickValue,
}: {
row: FileRow;
os: string;
mark: PathStatus | undefined;
linkOs: string | undefined;
value: unknown;
showValue: boolean;
highlight: readonly string[];
onPickValue?: (atom: string) => void;
}) {
const { name, id: fullPath } = row;
return (
<>
<span
className="flex min-w-0 items-center gap-2"
// The row's own px-1 adds the 4 px a folder row has as pl-1.
style={{ paddingLeft: row.depth * INDENT }}
>
{mark ? (
<span
className={cn(
@@ -146,7 +218,7 @@ const FileItem = memo(function FileItem({
<Link
data-nav-item
data-tree-row
href={`/os/bin?path=${encodeURIComponent(fullPath)}&os=${linkOs}`}
href={`/os/bin?path=${encodeURIComponent(fullPath)}&os=${linkOs ?? os}`}
className="font-mono text-sm hover:underline truncate"
title={fullPath}
>
@@ -158,221 +230,18 @@ const FileItem = memo(function FileItem({
{name.slice(name.lastIndexOf("/") + 1)}
</Link>
</span>
{marks.valueFor && (
{showValue && (
<ValuePreview
value={marks.valueFor(fullPath)}
highlight={marks.highlight ?? NO_HIGHLIGHT}
onPick={marks.onPickValue}
value={value}
highlight={highlight}
onPick={onPickValue}
className="ml-3 hidden sm:flex"
/>
)}
</div>
</>
);
});
function Tree({
item,
os,
depth,
expandAll,
}: {
item: TreeWithFullPath;
os: string;
depth: number;
expandAll: boolean | null;
}) {
const entries = Object.entries(item);
const files = entries.filter(([, v]) => typeof v === "string");
const folders = entries.filter(([, v]) => typeof v !== "string");
const subgrid = useSubgrid();
return (
<ul className={cn("space-y-0.5", subgrid)}>
{folders.map(([key, value]) => (
<TreeFolder
key={key}
name={key}
item={value as TreeWithFullPath}
os={os}
depth={depth}
expandAll={expandAll}
/>
))}
{files.map(([key, value]) => (
<li key={value as string} className={subgrid}>
<FileItem name={key} fullPath={value as string} os={os} />
</li>
))}
</ul>
);
}
function TreeFolder({
name,
item,
os,
depth,
expandAll,
}: {
name: string;
item: TreeWithFullPath;
os: string;
depth: number;
expandAll: boolean | null;
}) {
const [open, setOpen] = useState(
expandAll === true || (expandAll === null && depth < 1),
);
const itemCount = countItems(item);
const marks = useContext(MarksContext);
const changed = useMemo(
() => countMarks(item, marks.status),
[item, marks.status],
);
const maxDepth = getMaxDepth(item);
const isShallow = maxDepth === 0;
const subgrid = useSubgrid();
const contentId = useId();
useEffect(() => {
if (expandAll !== null) {
setOpen(expandAll);
}
}, [expandAll]);
return (
<li className={subgrid}>
{/* A plain disclosure, not Radix Collapsible: its content measures
itself on every open (for animations this tree doesn't use), which
forced one synchronous layout per folder on Expand all. */}
<div className={subgrid} data-state={open ? "open" : "closed"}>
<button
type="button"
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-controls={contentId}
data-state={open ? "open" : "closed"}
data-nav-item
data-tree-row
data-tree-folder
className="col-span-full flex items-center gap-2 py-1 pl-1 w-full hover:bg-accent rounded transition-colors text-left group outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{open ? (
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
)}
<Folder className="h-4 w-4 shrink-0 text-folder" />
<span className="font-mono text-sm truncate">{name}</span>
<span className="ml-2 text-xs tabular-nums text-muted-foreground">
{itemCount}
</span>
{changed.added > 0 && (
<span className="text-xs tabular-nums text-emerald-700 dark:text-emerald-300">
+{changed.added}
</span>
)}
{changed.removed > 0 && (
<span className="text-xs tabular-nums text-red-700 dark:text-red-300">
−{changed.removed}
</span>
)}
</button>
{open && (
<div
id={contentId}
data-tree-content
data-state="open"
className={subgrid}
>
<div
className={cn(
isShallow
? "ml-6 mt-1 space-y-0.5"
: "ml-4 pl-2 border-l border-border",
subgrid,
)}
>
{isShallow ? (
Object.entries(item).map(([key, value]) => (
<FileItem
key={value as string}
name={key}
fullPath={value as string}
os={os}
/>
))
) : (
<Tree
item={item}
os={os}
depth={depth + 1}
expandAll={expandAll}
/>
)}
</div>
</div>
)}
</div>
</li>
);
}
/**
* Arrow keys over the tree's focusable rows (folder toggles and file links):
* ↑/↓ move, → opens a folder or steps into it, ← closes it or goes to the
* parent folder, Home/End jump. Same model as the keys page's namespace tree.
*/
function onTreeKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.metaKey || event.ctrlKey || event.altKey) return;
const current = (event.target as HTMLElement).closest<HTMLElement>(
"[data-tree-row]",
);
if (!current) return;
const rows = [
...event.currentTarget.querySelectorAll<HTMLElement>("[data-tree-row]"),
].filter((row) => row.getClientRects().length > 0);
const index = rows.indexOf(current);
const isFolder = current.hasAttribute("data-tree-folder");
const isOpen = current.getAttribute("data-state") === "open";
const parentFolder = () =>
current
.closest("[data-tree-content]")
?.parentElement?.querySelector<HTMLElement>(
":scope > [data-tree-folder]",
);
let next: HTMLElement | null | undefined;
switch (event.key) {
case "ArrowDown":
next = rows[index + 1];
break;
case "ArrowUp":
next = rows[index - 1];
break;
case "Home":
next = rows[0];
break;
case "End":
next = rows.at(-1);
break;
case "ArrowRight":
if (isFolder && !isOpen) current.click();
else if (isFolder) next = rows[index + 1];
else return;
break;
case "ArrowLeft":
if (isFolder && isOpen) current.click();
else next = parentFolder();
break;
default:
return;
}
event.preventDefault();
next?.focus();
next?.scrollIntoView({ block: "nearest" });
}
const FileSystem = memo(function FileSystem({
list,
os,
@@ -380,24 +249,244 @@ const FileSystem = memo(function FileSystem({
status,
osFor,
valueFor,
highlight,
highlight = NO_HIGHLIGHT,
onPickValue,
}: {
list: string[];
os: string;
expandAll?: boolean | null;
} & Marks) {
status?: (path: string) => PathStatus | undefined;
osFor?: (path: string) => string | undefined;
valueFor?: (path: string) => unknown;
highlight?: readonly string[];
onPickValue?: (atom: string) => void;
}) {
const tree = useMemo(() => filesToTree(list), [list]);
const marks = useMemo(
() => ({ status, osFor, valueFor, highlight, onPickValue }),
[status, osFor, valueFor, highlight, onPickValue],
const info = useMemo(() => folderInfo(tree, status), [tree, status]);
// Open folders: reset when the tree or Expand/Collapse all changes.
const [open, setOpen] = useState(() => defaultOpen(tree, expandAll));
const [openFor, setOpenFor] = useState({ tree, expandAll });
if (openFor.tree !== tree || openFor.expandAll !== expandAll) {
setOpenFor({ tree, expandAll });
setOpen(defaultOpen(tree, expandAll));
}
const toggle = useCallback((id: string) => {
setOpen((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}, []);
const rows = useMemo(() => flatten(tree, open, info), [tree, open, info]);
// Width of a monospace character, measured once.
const listRef = useRef<HTMLDivElement>(null);
const [charWidth, setCharWidth] = useState(8.4);
const [scrollMargin, setScrollMargin] = useState(0);
useLayoutEffect(() => {
const el = listRef.current;
if (!el) return;
const probe = document.createElement("span");
probe.className = "font-mono text-sm";
probe.style.cssText = "position:absolute;visibility:hidden;white-space:pre";
probe.textContent = "0".repeat(100);
el.append(probe);
setCharWidth(probe.getBoundingClientRect().width / 100);
probe.remove();
const measure = () =>
setScrollMargin(el.getBoundingClientRect().top + window.scrollY);
measure();
const observer = new ResizeObserver(measure);
observer.observe(document.body);
return () => observer.disconnect();
}, []);
// The name column: the widest visible file name with its indent.
const nameColumn = useMemo(() => {
let widest = 0;
for (const row of rows) {
if (row.kind !== "file") continue;
const width =
row.depth * INDENT + 4 + 16 + 8 + row.name.length * charWidth;
if (width > widest) widest = width;
}
return Math.ceil(widest + 4);
}, [rows, charWidth]);
const virtualizer = useWindowVirtualizer({
count: rows.length,
estimateSize: () => ROW,
overscan: 12,
scrollMargin,
// Rows scrolled to by the keyboard land below the site header.
scrollPaddingStart: HEADER,
});
// Keyboard: same model as the nested tree, by row index. A rendered row
// (nearly always: overscan) takes focus at once, so quick or repeated
// presses each move one row; otherwise scroll it in and focus next frame.
const pending = useRef<number | null>(null);
const focusRow = useCallback(
(index: number) => {
if (index < 0 || index >= rows.length) return;
const find = () =>
listRef.current?.querySelector<HTMLElement>(
`[data-index="${index}"] [data-tree-row]`,
);
const rendered = find();
if (rendered) {
rendered.focus();
// The row (with its scroll margin), not the control inside it.
rendered.closest("[data-index]")?.scrollIntoView({ block: "nearest" });
return;
}
// Keys pressed before it renders count from here, not the old row.
pending.current = index;
virtualizer.scrollToIndex(index, { align: "auto" });
requestAnimationFrame(() => {
find()?.focus();
pending.current = null;
});
},
[rows.length, virtualizer],
);
const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
const el = (event.target as HTMLElement).closest<HTMLElement>(
"[data-index]",
);
if (!el) return;
const index = pending.current ?? Number(el.dataset.index);
const row = rows[index];
switch (event.key) {
case "ArrowDown":
focusRow(index + 1);
break;
case "ArrowUp":
focusRow(index - 1);
break;
case "Home":
focusRow(0);
break;
case "End":
focusRow(rows.length - 1);
break;
case "ArrowRight":
if (row.kind !== "folder") return;
if (!row.open) toggle(row.id);
else focusRow(index + 1);
break;
case "ArrowLeft":
if (row.kind === "folder" && row.open) toggle(row.id);
else {
for (let i = index - 1; i >= 0; i--) {
if (rows[i].kind === "folder" && rows[i].depth < row.depth) {
focusRow(i);
break;
}
}
}
break;
default:
return;
}
event.preventDefault();
};
const showValue = !!valueFor;
return (
<MarksContext.Provider value={marks}>
<div onKeyDown={onTreeKeyDown} className={valueFor ? COLUMNS : undefined}>
<Tree item={tree} os={os} depth={0} expandAll={expandAll} />
</div>
</MarksContext.Provider>
<div
ref={listRef}
onKeyDown={onKeyDown}
className="relative"
style={{
height: virtualizer.getTotalSize(),
["--name-col" as string]: `${nameColumn}px`,
}}
>
{virtualizer.getVirtualItems().map((item) => {
const row = rows[item.index];
const top = item.start - scrollMargin;
if (row.kind === "folder") {
return (
<div
key={row.id}
data-index={item.index}
className="absolute inset-x-0 scroll-mt-[72px]"
style={{ top, height: ROW - 2 }}
>
<Guides depth={row.depth} />
<button
type="button"
onClick={() => toggle(row.id)}
aria-expanded={row.open}
data-nav-item
data-tree-row
data-tree-folder
data-state={row.open ? "open" : "closed"}
className="flex h-full w-full items-center gap-2 rounded text-left transition-colors hover:bg-accent outline-none focus-visible:ring-2 focus-visible:ring-ring"
style={{ paddingLeft: row.depth * INDENT + 4 }}
>
{row.open ? (
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
)}
<Folder className="h-4 w-4 shrink-0 text-folder" />
<span className="truncate font-mono text-sm">{row.name}</span>
<span className="ml-2 text-xs tabular-nums text-muted-foreground">
{row.count}
</span>
{row.added > 0 && (
<span className="text-xs tabular-nums text-emerald-700 dark:text-emerald-300">
+{row.added}
</span>
)}
{row.removed > 0 && (
<span className="text-xs tabular-nums text-red-700 dark:text-red-300">
−{row.removed}
</span>
)}
</button>
</div>
);
}
const mark = status?.(row.id);
return (
<div
key={row.id}
data-index={item.index}
className={cn(
"absolute inset-x-0 grid scroll-mt-[72px] items-center rounded px-1 transition-colors",
showValue
? "grid-cols-1 sm:grid-cols-[min(var(--name-col),50%)_minmax(0,1fr)]"
: "grid-cols-1",
mark === "added"
? "bg-emerald-50 text-emerald-800 hover:bg-emerald-100 dark:bg-emerald-950/30 dark:text-emerald-200 dark:hover:bg-emerald-950/50"
: mark === "removed"
? "bg-red-50 text-red-800 hover:bg-red-100 dark:bg-red-950/30 dark:text-red-200 dark:hover:bg-red-950/50"
: "hover:bg-accent",
)}
style={{ top, height: ROW - 2 }}
>
<Guides depth={row.depth} />
<FileLine
row={row}
os={os}
mark={mark}
linkOs={osFor?.(row.id)}
value={showValue ? valueFor?.(row.id) : undefined}
showValue={showValue}
highlight={highlight}
onPickValue={onPickValue}
/>
</div>
);
})}
</div>
);
});