From fdf0ab052bd469440dc65e37ae9f59ce0343a4ec Mon Sep 17 00:00:00 2001 From: cc Date: Thu, 3 Dec 2026 17:55:55 +0100 Subject: [PATCH] perf(tree): virtualize the file tree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/globals.css | 13 - src/components/filesystem.tsx | 729 +++++++++++++++++++--------------- 2 files changed, 409 insertions(+), 333 deletions(-) diff --git a/src/app/globals.css b/src/app/globals.css index 3629626..58a055a 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -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; -} diff --git a/src/components/filesystem.tsx b/src/components/filesystem.tsx index 691cf63..9a12d5a 100644 --- a/src/components/filesystem.tsx +++ b/src/components/filesystem.tsx @@ -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({}); +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(); + 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, + info: Map, +) { + 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(); + // 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 ( -
- {/* Icon and name: the first column. */} - + <> + {Array.from({ length: depth }, (_, d) => ( + + ))} + + ); +} + +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 ( + <> + {mark ? ( @@ -158,221 +230,18 @@ const FileItem = memo(function FileItem({ {name.slice(name.lastIndexOf("/") + 1)} - {marks.valueFor && ( + {showValue && ( )} -
+ ); }); -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 ( -
    - {folders.map(([key, value]) => ( - - ))} - {files.map(([key, value]) => ( -
  • - -
  • - ))} -
- ); -} - -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 ( -
  • - {/* 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. */} -
    - - {open && ( -
    -
    - {isShallow ? ( - Object.entries(item).map(([key, value]) => ( - - )) - ) : ( - - )} -
    -
    - )} -
    -
  • - ); -} - -/** - * 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) { - if (event.metaKey || event.ctrlKey || event.altKey) return; - const current = (event.target as HTMLElement).closest( - "[data-tree-row]", - ); - if (!current) return; - const rows = [ - ...event.currentTarget.querySelectorAll("[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( - ":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(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(null); + const focusRow = useCallback( + (index: number) => { + if (index < 0 || index >= rows.length) return; + const find = () => + listRef.current?.querySelector( + `[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) => { + if (event.metaKey || event.ctrlKey || event.altKey) return; + const el = (event.target as HTMLElement).closest( + "[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 ( - -
    - -
    -
    +
    + {virtualizer.getVirtualItems().map((item) => { + const row = rows[item.index]; + const top = item.start - scrollMargin; + if (row.kind === "folder") { + return ( +
    + + +
    + ); + } + const mark = status?.(row.id); + return ( +
    + + +
    + ); + })} +
    ); });