diff --git a/packages/baukasten/src/components/Tree/Tree.childMounting.test.tsx b/packages/baukasten/src/components/Tree/Tree.childMounting.test.tsx new file mode 100644 index 0000000..a5b0537 --- /dev/null +++ b/packages/baukasten/src/components/Tree/Tree.childMounting.test.tsx @@ -0,0 +1,1001 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { startTransition, useState } from 'react'; +import { render, screen, fireEvent, act } from '@testing-library/react'; +import { Tree, flattenTree } from './Tree'; +import type { TreeNodeData } from './Tree'; + +/** + * These tests pin the rendering contract, not the styling: that a collapsed + * branch produces no rows at all, and that a bounded tree mounts a slice rather + * than the whole visible list. + * + * jsdom has no layout engine, so the *exact* number of windowed rows is + * meaningless here. The assertions below only check that it is bounded and far + * below the total, which holds either way. + */ + +// ─── Test data ──────────────────────────────────────────────────────────────── + +const nodes: TreeNodeData[] = [ + { + id: 'src', + label: 'src', + children: [ + { id: 'src/a.ts', label: 'a.ts' }, + { + id: 'src/deep', + label: 'deep', + children: [{ id: 'src/deep/b.ts', label: 'b.ts' }], + }, + ], + }, + { id: 'readme', label: 'README.md' }, +]; + +/** Builds a perfectly balanced tree: `branching ^ depth` rows in total. */ +function makeTree(depth: number, branching: number, prefix = 'n'): TreeNodeData[] { + if (depth === 0) return []; + return Array.from({ length: branching }, (_, i) => { + const id = `${prefix}-${i}`; + const children = makeTree(depth - 1, branching, id); + return { id, label: id, ...(children.length ? { children } : {}) }; + }); +} + +/** A single folder holding `count` files — the shape windowing exists for. */ +function makeFlatFolder(count: number): TreeNodeData[] { + return [ + { + id: 'big', + label: 'big', + children: Array.from({ length: count }, (_, i) => ({ + id: `f${i}`, + label: `file-${i}.ts`, + })), + }, + ]; +} + +const rowCount = (container: HTMLElement) => + container.querySelectorAll('[data-tree-node-id]').length; + +// ─── Fake layout ────────────────────────────────────────────────────────────── + +/** + * jsdom has no layout engine, so every element measures 0×0 and nothing + * scrolls. Windowing cannot be exercised at all without standing in for the + * measurements `@tanstack/virtual-core` reads: + * + * · `offsetWidth` / `offsetHeight` — viewport size (it uses the offset + * properties, not `getBoundingClientRect`), + * · `scrollHeight` / `clientHeight` — scroll range, which caps + * `scrollToIndex`; at jsdom's zeros every target clamps to 0, + * · `scrollTop`, and a `scrollTo` that moves it and fires `scroll`. + * + * `scrollTo` fires synchronously where a browser would wait a frame. That keeps + * the tests free of waiting, at the price of React logging "flushSync was + * called from inside a lifecycle method" when a scroll lands mid-commit — an + * artefact of the stand-in, not of the component. + */ +const VIEWPORT_HEIGHT = 300; + +/** + * Height the fake layout reports for a row. Rows are measured now rather than + * given an imposed height, so this is what the virtualizer will believe — and + * tests can move it to stand in for a larger host font. + */ +let fakeRowHeight = 24; + +/** + * Descriptors displaced by {@link installFakeLayout}, so they can be put back + * exactly. `delete` is not good enough: jsdom defines `offsetHeight`, + * `scrollTo` and the rest itself, and deleting them takes the real + * implementations out with the stand-ins. + */ +const displaced: Array<[object, string, PropertyDescriptor | undefined]> = []; + +function patch(target: object, prop: string, descriptor: PropertyDescriptor) { + displaced.push([target, prop, Object.getOwnPropertyDescriptor(target, prop)]); + Object.defineProperty(target, prop, { configurable: true, ...descriptor }); +} + +/** + * A `ResizeObserver` that records what it was asked to watch, so a test can + * decide when the observation lands. + * + * The shared test setup stubs `ResizeObserver` out entirely, which leaves the + * virtualizer with only the measurement it takes as each row's ref attaches — + * and that runs inside React's commit, where the library's `flushSync` cannot + * flush. In a browser the real observer fires afterwards and the measurement + * settles; here nothing ever fires, so a measured height would never reach the + * scroll extent. {@link flushResizeObservers} stands in for that second pass. + */ +const observations = new Set<{ callback: ResizeObserverCallback; targets: Set }>(); + +class RecordingResizeObserver { + private readonly observation: { callback: ResizeObserverCallback; targets: Set }; + + constructor(callback: ResizeObserverCallback) { + this.observation = { callback, targets: new Set() }; + observations.add(this.observation); + } + + observe(target: Element) { + this.observation.targets.add(target); + } + + unobserve(target: Element) { + this.observation.targets.delete(target); + } + + disconnect() { + this.observation.targets.clear(); + observations.delete(this.observation); + } +} + +/** Deliver a resize for every observed element, at its current fake height. */ +function flushResizeObservers() { + for (const { callback, targets } of [...observations]) { + const entries = [...targets] + .filter((target) => target.isConnected) + .map((target) => ({ + target, + borderBoxSize: [ + { + blockSize: (target as HTMLElement).offsetHeight, + inlineSize: (target as HTMLElement).offsetWidth, + }, + ], + })); + if (entries.length > 0) { + callback(entries as unknown as ResizeObserverEntry[], {} as ResizeObserver); + } + } +} + +function installFakeLayout() { + // Rows report their own height and everything else reports the viewport's. + // A single global `offsetHeight` would tell the virtualizer that each row + // is a full viewport tall, and nothing would window. + patch(HTMLElement.prototype, 'offsetHeight', { + get(this: HTMLElement) { + return this.getAttribute('role') === 'treeitem' ? fakeRowHeight : VIEWPORT_HEIGHT; + }, + }); + patch(HTMLElement.prototype, 'offsetWidth', { get: () => 400 }); + patch(Element.prototype, 'clientHeight', { get: () => VIEWPORT_HEIGHT }); + patch(Element.prototype, 'scrollHeight', { + get(this: Element) { + const canvas = this.firstElementChild as HTMLElement | null; + const height = canvas?.style.height; + return height ? parseFloat(height) : VIEWPORT_HEIGHT; + }, + }); + patch(Element.prototype, 'scrollTop', { + get(this: Element & { __scrollTop?: number }) { + return this.__scrollTop ?? 0; + }, + set(this: Element & { __scrollTop?: number }, value: number) { + this.__scrollTop = value; + }, + }); + patch(Element.prototype, 'scrollTo', { + value: function (this: Element, ...args: unknown[]) { + const options = args[0] as ScrollToOptions | undefined; + if (options && typeof options === 'object' && typeof options.top === 'number') { + (this as Element & { __scrollTop?: number }).__scrollTop = options.top; + } + this.dispatchEvent(new Event('scroll')); + }, + writable: true, + }); + patch(globalThis, 'ResizeObserver', { value: RecordingResizeObserver, writable: true }); +} + +function removeFakeLayout() { + for (const [target, prop, original] of displaced.reverse()) { + if (original) { + Object.defineProperty(target, prop, original); + } else { + delete (target as Record)[prop]; + } + } + displaced.length = 0; + observations.clear(); + fakeRowHeight = 24; +} + +const allExpanded = (list: TreeNodeData[]): string[] => { + const keys: string[] = []; + const walk = (l: TreeNodeData[]) => { + for (const n of l) { + if (n.children?.length) { + keys.push(n.id); + walk(n.children); + } + } + }; + walk(list); + return keys; +}; + +// ─── Flattening ─────────────────────────────────────────────────────────────── + +describe('flattenTree', () => { + it('descends only into expanded branches', () => { + const { rows } = flattenTree(nodes, new Set(['src'])); + + expect(rows.map((r) => r.node.id)).toEqual(['src', 'src/a.ts', 'src/deep', 'readme']); + // `src/deep` is collapsed, so its child is never visited at all — + // this is what keeps the walk proportional to what is on screen. + expect(rows.some((r) => r.node.id === 'src/deep/b.ts')).toBe(false); + }); + + it('records the depth, parent and sibling position of each row', () => { + const { rows, indexById } = flattenTree(nodes, new Set(['src'])); + const deep = rows[indexById.get('src/deep')!]; + + expect(deep.depth).toBe(1); + expect(deep.parentIndex).toBe(indexById.get('src')); + expect(deep.posInSet).toBe(2); + expect(deep.setSize).toBe(2); + expect(deep.isLast).toBe(true); + }); + + it('sets a guide bit only for ancestors that still have a sibling below', () => { + // a (has sibling b) > a1 (last) > a1x + const data: TreeNodeData[] = [ + { + id: 'a', + label: 'a', + children: [{ id: 'a1', label: 'a1', children: [{ id: 'a1x', label: 'a1x' }] }], + }, + { id: 'b', label: 'b' }, + ]; + const { rows, indexById } = flattenTree(data, new Set(['a', 'a1'])); + + // `a` is at depth 0 and has `b` below it, so bit 0 is set for its + // descendants. `a1` is last among its siblings, so bit 1 is not. + // + // Bit 0 is recorded but never drawn — a column hangs one gutter left of + // its children and depth 0 has no gutter to its left, so root siblings + // go unconnected. It is set anyway so the rule "bit `d` means the + // ancestor at depth `d` continues" needs no special case. The rendering + // side of that is pinned in 'Tree edge guides' below. + const a1x = rows[indexById.get('a1x')!]; + expect(a1x.guideMask & (1 << 0)).not.toBe(0); + expect(a1x.guideMask & (1 << 1)).toBe(0); + }); +}); + +// ─── Mounting ───────────────────────────────────────────────────────────────── + +describe('Tree row mounting', () => { + it('does not render the children of a collapsed node', () => { + render(); + + expect(screen.getByText('src')).toBeInTheDocument(); + expect(screen.queryByText('a.ts')).not.toBeInTheDocument(); + expect(screen.queryByText('deep')).not.toBeInTheDocument(); + }); + + it('mounts one level per expanded ancestor, not the whole subtree', () => { + render(); + + expect(screen.getByText('a.ts')).toBeInTheDocument(); + expect(screen.getByText('deep')).toBeInTheDocument(); + expect(screen.queryByText('b.ts')).not.toBeInTheDocument(); + }); + + it('mounts children in the same commit as the expand', () => { + render(); + + fireEvent.click(screen.getByText('src')); + + expect(screen.getByText('a.ts')).toBeInTheDocument(); + }); + + it('drops children immediately on collapse', () => { + render(); + + fireEvent.click(screen.getByText('src')); + + // Nothing to wait for any more. The rows used to linger for up to + // 500ms so the height transition could play out; there is no height + // transition now, so keeping them would just be dead DOM. + expect(screen.queryByText('a.ts')).not.toBeInTheDocument(); + }); + + it('keeps the DOM proportional to visible rows rather than to the dataset', () => { + // 4 ^ 4 = 340 rows in total, 4 of them visible while everything is collapsed. + const { container } = render(); + + expect(rowCount(container)).toBe(4); + + fireEvent.click(screen.getByText('n-0')); + + expect(rowCount(container)).toBe(8); + }); +}); + +// ─── Windowing ──────────────────────────────────────────────────────────────── + +describe('Tree windowing', () => { + const BIG = 5000; + + beforeEach(installFakeLayout); + afterEach(removeFakeLayout); + + it('mounts every visible row when the tree has no bounded height', () => { + const { container } = render( + , + ); + + // Unbounded: the tree grows with its content, so there is no viewport + // to window against and the whole visible list is mounted. + expect(rowCount(container)).toBe(BIG + 1); + }); + + it('mounts a slice when given a bounded height', () => { + const { container } = render( + , + ); + + expect(rowCount(container)).toBeGreaterThan(0); + expect(rowCount(container)).toBeLessThan(100); + }); + + it('reserves the full scroll height even though most rows do not exist', () => { + const { container } = render( + , + ); + + // The scrollbar has to represent the whole list, not the mounted slice. + const canvas = container.querySelector('[role="presentation"]')!; + expect(canvas.style.height).toBe(`${(BIG + 1) * 24}px`); + }); + + it('fills the parent when asked, and windows against it', () => { + const { container } = render( + , + ); + + const tree = container.querySelector('[role="tree"]')!; + expect(tree.style.height).toBe('100%'); + expect(rowCount(container)).toBeLessThan(100); + }); + + it('mounts more rows as overscan grows', () => { + const props = { nodes: makeFlatFolder(BIG), defaultExpandedKeys: ['big'], maxHeight: 300 }; + + const tight = render(); + const tightCount = rowCount(tight.container); + tight.unmount(); + + const loose = render(); + + expect(rowCount(loose.container)).toBeGreaterThan(tightCount); + }); + + it('honours disableVirtualization even with a bounded height', () => { + const { container } = render( + , + ); + + expect(rowCount(container)).toBe(BIG + 1); + }); + + /** + * A bounded tree has to scroll whether or not its rows are windowed. + * `disableVirtualization` used to take the scroll area away with the + * windowing, which left `maxHeight` clipping every row below the fold with + * no way to reach them. + */ + it.each([ + ['maxHeight, windowed', { maxHeight: 300 }], + ['maxHeight, not windowed', { maxHeight: 300, disableVirtualization: true }], + ['fillHeight, windowed', { fillHeight: true }], + ['fillHeight, not windowed', { fillHeight: true, disableVirtualization: true }], + ])('scrolls when bounded by %s', (_label, boundingProps) => { + const { container } = render( + , + ); + + const tree = container.querySelector('[role="tree"]')!; + expect(getComputedStyle(tree).overflowY).toBe('auto'); + }); + + it('leaves an unbounded tree to grow instead of scroll', () => { + const { container } = render( + , + ); + + const tree = container.querySelector('[role="tree"]')!; + expect(getComputedStyle(tree).overflowY).not.toBe('auto'); + }); + + /** + * Rows used to be given the estimate as an exact inline height. That number + * comes from the rem-based spacing scale while the text inside is sized from + * `--vscode-font-size`, so on a host with a larger UI font the real row + * outgrew its slot and was squashed back into it. Rows are measured now, so + * a row taller than the estimate moves the scroll extent instead. + */ + it('reserves the measured row height, not the estimate', () => { + fakeRowHeight = 40; + + const { container } = render( + , + ); + + const rows = container.querySelectorAll('[role="treeitem"]'); + expect(rows.length).toBeGreaterThan(0); + for (const row of rows) { + expect(row.style.height).toBe(''); + expect(row.style.minHeight).toBe(''); + } + + act(() => flushResizeObservers()); + + // Every mounted row measured 40px, so the canvas has to have grown past + // the (BIG + 1) * 24 the estimate alone would have given it. + const canvas = container.querySelector('[role="presentation"]')!; + expect(parseFloat(canvas.style.height)).toBeGreaterThan((BIG + 1) * 24); + }); +}); + +// ─── Scale ──────────────────────────────────────────────────────────────────── + +describe('Tree at repository scale', () => { + // 11 + 121 + 1331 + 14641 = 16,104 nodes, in the shape of a source tree + // four directories deep. The reported case was a 14,000-file repository + // that mounted 26,993 elements and took 640ms to expand, rising to 887ms + // once several branches were open. + const repo = makeTree(4, 11); + const everyDirectory = allExpanded(repo); + + beforeEach(installFakeLayout); + afterEach(removeFakeLayout); + + it('mounts only the visible roots while collapsed', () => { + const { container } = render(); + + expect(rowCount(container)).toBe(11); + }); + + it('mounts a viewport-sized slice with every directory expanded', () => { + const { container } = render( + , + ); + + // Every one of the 16,104 rows is visible in the sense that no ancestor + // is collapsed; the point is that being visible no longer means being + // mounted. Measured here: 21 rows and 69 elements in total, against the + // 26,993 elements the recursive version put on the page for a + // comparable tree. + // + // 21 rather than ~17 because the fake layout reports a 300px viewport + // regardless of `maxHeight` — 12 rows plus 8 overscan. The bounds below + // are deliberately loose; what is being pinned is that the number does + // not scale with the dataset, not its exact value. + expect(rowCount(container)).toBeLessThan(50); + expect(container.querySelectorAll('*').length).toBeLessThan(300); + }); + + it('keeps the mounted set bounded after expanding another branch', () => { + const { container } = render(); + + fireEvent.click(screen.getByText('n-0')); + fireEvent.click(screen.getByText('n-0-0')); + fireEvent.click(screen.getByText('n-0-0-0')); + + // The cost of an expand used to grow with how much was already open, + // because every mounted row re-rendered. Nothing here grows. + expect(rowCount(container)).toBeLessThan(50); + }); +}); + +// ─── Re-render fan-out ──────────────────────────────────────────────────────── + +/** + * `expandIcon` is called once per row per render, and this one is defined at + * module scope so its identity never changes — an inline arrow would give the + * shared context a new value on every parent render and re-render every row, + * which is the very thing under test. + */ +const rendered: string[] = []; +const countingExpandIcon = ({ node }: { node: TreeNodeData }) => { + rendered.push(node.id); + return ; +}; + +describe('Tree re-render fan-out', () => { + it('re-renders only the affected rows when the selection changes', () => { + const data = makeFlatFolder(200); + render( + , + ); + + rendered.length = 0; + fireEvent.click(screen.getByText('file-100.ts')); + + // Selecting used to re-render every mounted row, because expansion and + // selection lived in the context each row subscribed to. Only the rows + // whose own `selected` / `tabbable` flags moved should render now: the + // newly selected row and whichever row previously held the tab stop. + expect(rendered.length).toBeGreaterThan(0); + expect(rendered.length).toBeLessThanOrEqual(4); + expect(rendered).toContain('f100'); + }); + + /** + * The same claim under windowing, where the row also holds a `measureRef`. + * That prop has to keep one identity across renders — the virtualizer's own + * bound method does, an inline arrow would not — or the memo stops holding + * and every mounted row renders again on each selection. + */ + it('re-renders only the affected rows while windowed', () => { + installFakeLayout(); + try { + render( + , + ); + + rendered.length = 0; + fireEvent.click(screen.getByText('file-2.ts')); + + expect(rendered.length).toBeGreaterThan(0); + expect(rendered.length).toBeLessThanOrEqual(4); + expect(rendered).toContain('f2'); + } finally { + removeFakeLayout(); + } + }); +}); + +// ─── Accessibility ──────────────────────────────────────────────────────────── + +describe('Tree flat ARIA', () => { + it('states level, position and set size on each row', () => { + render(); + + const src = screen.getByText('src').closest('[role="treeitem"]')!; + expect(src).toHaveAttribute('aria-level', '1'); + expect(src).toHaveAttribute('aria-posinset', '1'); + expect(src).toHaveAttribute('aria-setsize', '2'); + + const deep = screen.getByText('deep').closest('[role="treeitem"]')!; + expect(deep).toHaveAttribute('aria-level', '2'); + expect(deep).toHaveAttribute('aria-posinset', '2'); + expect(deep).toHaveAttribute('aria-setsize', '2'); + }); + + it('keeps treeitems directly under the tree in the accessibility tree', () => { + const { container } = render(); + + // The canvas is the only element between them and it is presentational, + // so `treeitem`'s required context role is still satisfied. + const canvas = container.querySelector('[role="tree"] > *')!; + expect(canvas).toHaveAttribute('role', 'presentation'); + expect(container.querySelector('[role="group"]')).toBeNull(); + }); +}); + +// ─── Keyboard navigation ────────────────────────────────────────────────────── + +describe('Tree keyboard navigation', () => { + const focusedId = () => document.activeElement?.getAttribute('data-tree-node-id'); + + it('moves down and up the flattened row order', () => { + const { container } = render(); + const tree = container.querySelector('[role="tree"]')!; + + // Nothing is focused yet, so the first ArrowDown lands on the first row + // rather than stepping past it. + fireEvent.keyDown(tree, { key: 'ArrowDown' }); + expect(focusedId()).toBe('src'); + + fireEvent.keyDown(tree, { key: 'ArrowDown' }); + expect(focusedId()).toBe('src/a.ts'); + + fireEvent.keyDown(tree, { key: 'ArrowDown' }); + expect(focusedId()).toBe('src/deep'); + + fireEvent.keyDown(tree, { key: 'ArrowUp' }); + expect(focusedId()).toBe('src/a.ts'); + }); + + it('moves to the parent with ArrowLeft on a row that cannot collapse', () => { + const { container } = render(); + const tree = container.querySelector('[role="tree"]')!; + + fireEvent.keyDown(tree, { key: 'ArrowDown' }); + fireEvent.keyDown(tree, { key: 'ArrowDown' }); + expect(focusedId()).toBe('src/a.ts'); + + // Previously a no-op: the row had no way to find its parent without + // searching the whole dataset, so the case was left unimplemented. + fireEvent.keyDown(tree, { key: 'ArrowLeft' }); + expect(focusedId()).toBe('src'); + }); + + it('collapses an expanded row with ArrowLeft before leaving it', () => { + const { container } = render(); + const tree = container.querySelector('[role="tree"]')!; + + fireEvent.keyDown(tree, { key: 'Home' }); + expect(focusedId()).toBe('src'); + + fireEvent.keyDown(tree, { key: 'ArrowLeft' }); + expect(screen.queryByText('a.ts')).not.toBeInTheDocument(); + }); + + it('expands with ArrowRight, then steps into the first child', () => { + const { container } = render(); + const tree = container.querySelector('[role="tree"]')!; + + fireEvent.keyDown(tree, { key: 'Home' }); + fireEvent.keyDown(tree, { key: 'ArrowRight' }); + expect(screen.getByText('a.ts')).toBeInTheDocument(); + + fireEvent.keyDown(tree, { key: 'ArrowRight' }); + expect(focusedId()).toBe('src/a.ts'); + }); + + it('jumps to the last visible row with End', () => { + const { container } = render(); + const tree = container.querySelector('[role="tree"]')!; + + fireEvent.keyDown(tree, { key: 'End' }); + expect(focusedId()).toBe('readme'); + }); + + // Its own block, so the prototype patches come back off even when an + // assertion throws part-way through. + describe('windowed', () => { + beforeEach(installFakeLayout); + afterEach(removeFakeLayout); + + it('scrolls a windowed row into the window before focusing it', () => { + const { container } = render( + , + ); + const tree = container.querySelector('[role="tree"]')!; + + // Row 5000 is nowhere near the mounted slice, so focusing it + // requires the virtualizer to bring it into the window first. + fireEvent.keyDown(tree, { key: 'End' }); + + expect(container.querySelector('[data-tree-row-index="5000"]')).not.toBeNull(); + expect(focusedId()).toBe('f4999'); + }); + }); + + it('runs a consumer onKeyDown without losing its own navigation', () => { + const onKeyDown = vi.fn(); + const { container } = render( + , + ); + const tree = container.querySelector('[role="tree"]')!; + + // The props spread sits after `onKeyDown` on the container, so a + // consumer handler used to replace the navigation outright. + fireEvent.keyDown(tree, { key: 'ArrowDown' }); + + expect(onKeyDown).toHaveBeenCalledTimes(1); + expect(focusedId()).toBe('src'); + }); + + it('lets a consumer claim a key by preventing default', () => { + const { container } = render( + e.preventDefault()} + />, + ); + const tree = container.querySelector('[role="tree"]')!; + + fireEvent.keyDown(tree, { key: 'ArrowDown' }); + + expect(focusedId()).toBeNull(); + }); +}); + +// ─── Edge guides ────────────────────────────────────────────────────────────── + +describe('Tree edge guides', () => { + it('draws no guide elements when edges are off', () => { + const { container } = render( + , + ); + + expect(container.querySelectorAll('[data-tree-guide]').length).toBe(0); + }); + + /** + * Root nodes are drawn without guides — they have no gutter to their left + * to hang a line in — so a continuing ancestor column only becomes visible + * from depth 2 down. Both cases below therefore branch at depth 1. + */ + const withMiddleSibling: TreeNodeData[] = [ + { + id: 'r', + label: 'r', + children: [ + { id: 'c1', label: 'c1', children: [{ id: 'g1', label: 'g1' }] }, + { id: 'c2', label: 'c2' }, + ], + }, + ]; + + const withoutMiddleSibling: TreeNodeData[] = [ + { + id: 'r', + label: 'r', + children: [{ id: 'c1', label: 'c1', children: [{ id: 'g1', label: 'g1' }] }], + }, + ]; + + it('draws one ancestor column per continuing branch, plus its own elbow', () => { + render( + , + ); + + // `g1` sits at depth 2 under `c1`, which still has `c2` below it — so + // c1's column has to run through g1's row to reach it. + const row = screen.getByText('g1').closest('[role="treeitem"]')!; + expect(row.querySelectorAll('[data-tree-guide="ancestor"]').length).toBe(1); + expect(row.querySelectorAll('[data-tree-guide="own"]').length).toBe(1); + expect(row.querySelectorAll('[data-tree-guide="elbow"]').length).toBe(1); + }); + + it('does not draw an ancestor column for a branch that has ended', () => { + render( + , + ); + + // `c1` is now the only child, so nothing continues past `g1`: it draws + // its own vertical and elbow and no ancestor column. + const row = screen.getByText('g1').closest('[role="treeitem"]')!; + expect(row.querySelectorAll('[data-tree-guide="ancestor"]').length).toBe(0); + expect(row.querySelectorAll('[data-tree-guide]').length).toBe(2); + }); + + /** + * Guides are drawn from `guideMask` rather than from the ancestors' own + * markup, precisely so a row can draw them while its ancestors are outside + * the window and unmounted. Windowing is the case that matters. + */ + it('draws the same guides when the ancestors are not mounted', () => { + installFakeLayout(); + try { + const { container } = render( + , + ); + + const row = screen.getByText('g1').closest('[role="treeitem"]')!; + expect(row.querySelectorAll('[data-tree-guide="ancestor"]').length).toBe(1); + expect(row.querySelectorAll('[data-tree-guide="elbow"]').length).toBe(1); + + const tree = container.querySelector('[role="tree"]')!; + expect(getComputedStyle(tree).overflowY).toBe('auto'); + } finally { + removeFakeLayout(); + } + }); +}); + +// ─── Controlled state ───────────────────────────────────────────────────────── + +describe('Tree controlled state', () => { + it('follows the expandedKeys prop and reports every change', () => { + const onExpandChange = vi.fn(); + const { rerender } = render( + , + ); + + expect(screen.queryByText('a.ts')).not.toBeInTheDocument(); + + // Controlled: clicking reports, but nothing opens until the prop moves. + fireEvent.click(screen.getByText('src')); + expect(onExpandChange).toHaveBeenCalledWith( + ['src'], + expect.objectContaining({ key: 'src', expanded: true }), + ); + expect(screen.queryByText('a.ts')).not.toBeInTheDocument(); + + rerender(); + expect(screen.getByText('a.ts')).toBeInTheDocument(); + }); + + it('follows the selectedKey prop and reports every change', () => { + const onSelect = vi.fn(); + const { rerender } = render( + , + ); + + fireEvent.click(screen.getByText('a.ts')); + expect(onSelect).toHaveBeenCalledWith( + 'src/a.ts', + expect.objectContaining({ id: 'src/a.ts' }), + ); + expect(screen.getByText('a.ts').closest('[role="treeitem"]')).toHaveAttribute( + 'aria-selected', + 'false', + ); + + rerender( + , + ); + expect(screen.getByText('a.ts').closest('[role="treeitem"]')).toHaveAttribute( + 'aria-selected', + 'true', + ); + }); + + /** + * The callbacks read the current expansion set through a ref. That ref is + * filled in an effect rather than during render, because a render started + * inside a transition can be abandoned — and a ref written by an abandoned + * render would make the next toggle compute from a state nobody committed. + */ + it('toggles correctly when the consumer defers state in a transition', () => { + const Deferred = () => { + const [keys, setKeys] = useState([]); + return ( + startTransition(() => setKeys(next))} + /> + ); + }; + + render(); + + act(() => { + fireEvent.click(screen.getByText('src')); + }); + expect(screen.getByText('deep')).toBeInTheDocument(); + + // The collapse has to be computed against the committed set, not + // against whatever a discarded render happened to leave behind. + act(() => { + fireEvent.click(screen.getByText('src')); + }); + expect(screen.queryByText('deep')).not.toBeInTheDocument(); + }); + + /** + * `expandedKeys` is compared by content, which is what lets a consumer + * derive it inline. The comparison adjusts state during render, so the two + * things worth pinning are that it settles rather than looping, and that a + * real change still gets through. + */ + describe('inline-derived expandedKeys', () => { + const Derived = ({ open }: { open: Record }) => { + const [, force] = useState(0); + // A fresh array identity on every render, by construction. + const keys = Object.keys(open).filter((key) => open[key]); + return ( + <> + + + + ); + }; + + it('settles instead of looping, and survives a parent re-render', () => { + render(); + expect(screen.getByText('a.ts')).toBeInTheDocument(); + + fireEvent.click(screen.getByText('rerender')); + + expect(screen.getByText('a.ts')).toBeInTheDocument(); + }); + + it('still applies a genuine change', () => { + const { rerender } = render(); + expect(screen.getByText('deep')).toBeInTheDocument(); + expect(screen.queryByText('b.ts')).not.toBeInTheDocument(); + + rerender(); + expect(screen.getByText('b.ts')).toBeInTheDocument(); + + rerender(); + expect(screen.queryByText('a.ts')).not.toBeInTheDocument(); + }); + }); +}); + +// ─── Custom expand icon ─────────────────────────────────────────────────────── + +describe('Tree custom expand icon', () => { + const iconFor = ({ hasChildren }: { hasChildren: boolean }) => ( + + ); + + it('does not put leaf ids into the expanded set', () => { + const onExpandChange = vi.fn(); + render( + , + ); + + // A leaf gets a custom icon too, and its wrapper is clickable. Toggling + // it would hand the consumer an id that nothing ever reads back. + fireEvent.click(screen.getAllByTestId('leaf-icon')[0]); + + expect(onExpandChange).not.toHaveBeenCalled(); + }); + + it('still toggles a branch', () => { + const onExpandChange = vi.fn(); + render( + , + ); + + fireEvent.click(screen.getAllByTestId('branch-icon')[0]); + + expect(onExpandChange).toHaveBeenCalledWith( + ['src'], + expect.objectContaining({ key: 'src', expanded: true }), + ); + }); +}); diff --git a/packages/baukasten/src/components/Tree/Tree.css.ts b/packages/baukasten/src/components/Tree/Tree.css.ts index 97f1749..c8f9a00 100644 --- a/packages/baukasten/src/components/Tree/Tree.css.ts +++ b/packages/baukasten/src/components/Tree/Tree.css.ts @@ -1,3 +1,4 @@ +import { style } from '@vanilla-extract/css'; import { recipe } from '@vanilla-extract/recipes'; /** @@ -41,3 +42,38 @@ export const treeContainer = recipe({ size: 'md', }, }); + +/** + * Added to the tree container whenever it has been given a bounded height — + * whether or not the rows inside it are windowed. A height cap without a + * scroller would simply clip everything below the fold out of reach. + * + * The container is itself the scroll viewport the windowing measures against, + * so there is no inner scroller: `getScrollElement` returns this element and + * its `clientHeight` decides how many rows exist at any moment. + */ +export const treeScrollArea = style({ + overflowY: 'auto', + overflowX: 'hidden', + // `flexDirection: column` on the container would otherwise let the canvas + // shrink below the total row height and confuse the scroll extent. + display: 'block', + // Hold the scrollbar's space open even while it is absent, so expanding a + // branch past the fold does not shunt every row sideways as it appears. + // Inert where scrollbars are drawn as overlays (macOS by default), which is + // exactly where there was no shift to correct. + scrollbarGutter: 'stable', +}); + +/** + * The element rows are placed inside. When windowed it is given the full height + * of every row, mounted or not, so the scrollbar reflects the whole list while + * only the visible slice exists. When not windowed the rows simply stack. + * + * `role="presentation"` matters: ARIA requires a `treeitem` to sit directly + * under its `tree`, and this div would otherwise break that chain. + */ +export const treeRowCanvas = style({ + position: 'relative', + width: '100%', +}); diff --git a/packages/baukasten/src/components/Tree/Tree.stories.tsx b/packages/baukasten/src/components/Tree/Tree.stories.tsx index c892e36..97a2d61 100644 --- a/packages/baukasten/src/components/Tree/Tree.stories.tsx +++ b/packages/baukasten/src/components/Tree/Tree.stories.tsx @@ -48,6 +48,38 @@ const meta = { description: 'Whether clicking the row toggles expansion', table: { defaultValue: { summary: 'true' } }, }, + maxHeight: { + control: 'text', + description: + 'Maximum height of the scroll area. Giving the tree a bounded height is what ' + + 'enables row windowing — only the rows in view are mounted.', + table: { defaultValue: { summary: 'undefined' } }, + }, + fillHeight: { + control: 'boolean', + description: + 'Fill the parent instead of growing with content. Also enables windowing; the ' + + 'parent must have a resolved height.', + table: { defaultValue: { summary: 'false' } }, + }, + estimatedRowHeight: { + control: 'number', + description: + 'Height assumed for a row that has not been measured yet. Defaults to the height ' + + 'implied by `size`; rows are measured once they mount, so this only affects how ' + + 'accurate the scroll extent is ahead of the reader.', + table: { defaultValue: { summary: 'from size' } }, + }, + overscan: { + control: { type: 'range', min: 0, max: 40, step: 2 }, + description: 'Rows rendered above and below the viewport', + table: { defaultValue: { summary: '8' } }, + }, + disableVirtualization: { + control: 'boolean', + description: 'Render every visible row instead of only the windowed slice', + table: { defaultValue: { summary: 'false' } }, + }, }, } satisfies Meta; @@ -723,6 +755,109 @@ export const WithActionButtons: Story = { }, }; +/** + * A tree far larger than the screen, windowed. + */ +export const LargeTree: Story = { + render: () => { + const LargeTreeDemo = () => { + // 12 + 144 + 1,728 + 20,736 = 22,620 nodes, four levels deep. + const nodes = React.useMemo(() => { + const build = (depth: number, prefix: string): TreeNodeData[] => + depth === 0 + ? [] + : Array.from({ length: 12 }, (_, i) => { + const id = `${prefix}/${i}`; + const children = build(depth - 1, id); + return { + id, + label: children.length ? `dir-${i}` : `file-${i}.ts`, + icon: , + ...(children.length ? { children } : {}), + }; + }); + return build(4, 'root'); + }, []); + + const [expandedKeys, setExpandedKeys] = useState([]); + const [mounted, setMounted] = useState(0); + const treeRef = React.useRef(null); + + // Read straight from the DOM after each commit — the count is the + // whole point of this story, and it should stay flat no matter how + // many branches are open. + React.useEffect(() => { + setMounted(treeRef.current?.querySelectorAll('[data-tree-node-id]').length ?? 0); + }, [expandedKeys]); + + const expandAll = useCallback(() => { + const keys: string[] = []; + const walk = (list: TreeNodeData[]) => { + for (const node of list) { + if (node.children?.length) { + keys.push(node.id); + walk(node.children); + } + } + }; + walk(nodes); + setExpandedKeys(keys); + }, [nodes]); + + return ( +
+
+ } + aria-label="Expand all" + onClick={expandAll} + /> + } + aria-label="Collapse all" + onClick={() => setExpandedKeys([])} + /> + + 22,620 nodes · {mounted} rows in the DOM + +
+ +
+ +
+
+ ); + }; + + return ; + }, + parameters: { + docs: { + description: { + story: + 'Expand All opens every one of the 22,620 nodes. The row count in the DOM does ' + + 'not move, because `maxHeight` bounds the scroll area and only the rows inside ' + + 'it (plus `overscan`) are mounted. Without a bounded height the same tree would ' + + 'mount every expanded row, and the component warns once past 500 of them.', + }, + }, + }, +}; + /** * Comprehensive showcase. */ diff --git a/packages/baukasten/src/components/Tree/Tree.tsx b/packages/baukasten/src/components/Tree/Tree.tsx index 9d2ad92..1afcfd1 100644 --- a/packages/baukasten/src/components/Tree/Tree.tsx +++ b/packages/baukasten/src/components/Tree/Tree.tsx @@ -1,6 +1,15 @@ -import React, { createContext, useContext, useCallback, useMemo, useState, useRef } from 'react'; +import React, { + createContext, + useContext, + useCallback, + useEffect, + useMemo, + useState, + useRef, +} from 'react'; +import { useVirtualizer } from '@tanstack/react-virtual'; import { type Size } from '../../styles'; -import { treeContainer } from './Tree.css'; +import { treeContainer, treeScrollArea, treeRowCanvas } from './Tree.css'; import { TreeNodeComponent } from './TreeNode'; // ─── Public types ──────────────────────────────────────────────────────────── @@ -53,7 +62,11 @@ export interface TreeProps extends Omit, 'o // ─── Expansion ────────────────────────────────────────────────────── /** - * Controlled expanded node keys + * Controlled expanded node keys. + * + * The array is compared by content, so deriving it inline — + * `Object.keys(map).filter(...)`, a spread of two lists — costs a comparison + * per render rather than a rebuild of the whole visible-row list. */ expandedKeys?: string[]; @@ -119,22 +132,78 @@ export interface TreeProps extends Omit, 'o * @default true */ expandOnClick?: boolean; + + // ─── Scrolling and windowing ──────────────────────────────────────── + + /** + * Maximum height of the tree's scroll area (e.g. `400`, `'50vh'`). + * + * Giving the tree a bounded height is what enables row windowing: only the + * rows inside the viewport (plus `overscan`) are mounted, so a 14,000-node + * tree costs the same as a 14-node one. Without it the tree grows to fit + * its content and every expanded row is mounted. + */ + maxHeight?: number | string; + + /** + * Make the tree fill its parent's height instead of growing with its + * content. Like `maxHeight`, this gives the tree a bounded viewport and so + * enables windowing. The parent must itself have a resolved height. + * @default false + */ + fillHeight?: boolean; + + /** + * Height in pixels to assume for a row that has not been measured yet. + * Defaults to the height implied by `size`. + * + * Rows are measured once mounted, so this only decides how accurate the + * scroll extent is before the reader has been anywhere near a given row. + * Set it if your rows are markedly taller than the default — a two-line + * `badge`, an oversized `icon` — to keep the scrollbar from resettling as + * they come into view. + */ + estimatedRowHeight?: number; + + /** + * Rows rendered above and below the viewport, to cover the gap between a + * scroll event and the re-render that follows it. + * @default 8 + */ + overscan?: number; + + /** + * Render every visible row instead of only the windowed slice, trading the + * memory back for the ability to Ctrl-F the whole tree or screenshot it in + * one piece. + * + * `maxHeight` and `fillHeight` still bound and scroll the tree when this is + * set; all that changes is how many of the rows inside exist at once. + * @default false + */ + disableVirtualization?: boolean; } // ─── Context ───────────────────────────────────────────────────────────────── +/** + * Everything a row needs that does *not* change when the user clicks. + * + * Every mounted row subscribes, so anything placed here re-renders all of them + * when it changes. Expansion and selection are deliberately absent — they reach + * a row as boolean props instead, so a selection re-renders only the two rows + * whose boolean flipped. + */ export interface TreeContextValue { size: Size; edgeStyle: TreeEdgeStyle; indentSize: number; selectable: boolean; expandOnClick: boolean; - expandedKeys: Set; - selectedKey: string | null; expandIcon?: (props: ExpandIconRenderProps) => React.ReactNode; toggleExpand: (key: string, node: TreeNodeData) => void; selectNode: (key: string, node: TreeNodeData) => void; - registerNode: (id: string, element: HTMLElement | null) => void; + focusRow: (index: number) => void; } const TreeContext = createContext({ @@ -143,47 +212,143 @@ const TreeContext = createContext({ indentSize: 20, selectable: true, expandOnClick: true, - expandedKeys: new Set(), - selectedKey: null, toggleExpand: () => {}, selectNode: () => {}, - registerNode: () => {}, + focusRow: () => {}, }); export const useTreeContext = () => useContext(TreeContext); -// ─── Helpers ───────────────────────────────────────────────────────────────── +// ─── Flattening ────────────────────────────────────────────────────────────── + +/** + * One visible row of the tree. + * + * Rows are a flat array rather than nested DOM because a node cannot be mounted + * independently of its ancestors' wrappers, which rules out windowing — and + * because index arithmetic over a flat list is what makes keyboard navigation + * O(1) per keypress rather than a walk of the dataset. + */ +export interface TreeFlatRow { + node: TreeNodeData; + /** 0 for a root node. */ + depth: number; + /** Index of this row's parent in the same array, or -1 for a root node. */ + parentIndex: number; + hasChildren: boolean; + /** True when this row is the last of its sibling group. */ + isLast: boolean; + /** 1-based position within the sibling group, for `aria-posinset`. */ + posInSet: number; + /** Size of the sibling group, for `aria-setsize`. */ + setSize: number; + /** + * Which ancestor columns still have a guide line running through them. + * + * Bit `d` is set when the ancestor at depth `d` has a sibling after it, so + * its line must continue past this row to reach it. A row can therefore + * draw every guide it needs without its ancestors being mounted, which + * under windowing they often are not. + * + * A mask rather than an array keeps the row's props primitive, so + * `React.memo` still holds when flattening rebuilds every row object. + * Guides are capped at {@link MAX_GUIDE_DEPTH}; deeper rows still render. + * + * Bit 0 is recorded but never drawn: a column hangs one gutter left of its + * children and depth 0 has none, so root siblings go unconnected. Setting + * it anyway keeps the rule uniform across depths. + */ + guideMask: number; +} + +/** Guides live in a 32-bit mask, so only the first 31 levels can carry one. */ +const MAX_GUIDE_DEPTH = 31; /** - * Collect all node IDs in depth-first order (for keyboard navigation). + * Walk the tree once, emitting a row for every node that is currently visible. + * A collapsed branch is skipped whole, so the cost tracks what is on screen + * rather than the size of `nodes`. */ -function flattenVisibleIds(nodes: TreeNodeData[], expandedKeys: Set): string[] { - const result: string[] = []; - const walk = (list: TreeNodeData[]) => { - for (const node of list) { - result.push(node.id); - if (node.children?.length && expandedKeys.has(node.id)) { - walk(node.children); +export function flattenTree( + nodes: TreeNodeData[], + expandedKeys: Set, +): { rows: TreeFlatRow[]; indexById: Map } { + const rows: TreeFlatRow[] = []; + const indexById = new Map(); + + const walk = (list: TreeNodeData[], depth: number, parentIndex: number, guideMask: number) => { + for (let i = 0; i < list.length; i++) { + const node = list[i]; + const isLast = i === list.length - 1; + const hasChildren = !!node.children?.length; + const index = rows.length; + + rows.push({ + node, + depth, + parentIndex, + hasChildren, + isLast, + posInSet: i + 1, + setSize: list.length, + guideMask, + }); + indexById.set(node.id, index); + + if (hasChildren && expandedKeys.has(node.id)) { + // This node's own column keeps its line only while a sibling + // remains below it to connect to. + const childMask = + !isLast && depth < MAX_GUIDE_DEPTH ? guideMask | (1 << depth) : guideMask; + walk(node.children!, depth + 1, index, childMask); } } }; - walk(nodes); - return result; + + walk(nodes, 0, -1, 0); + return { rows, indexById }; } /** - * Find a node by id in the tree data. + * A row's position in the flattened list, written by `TreeNode`. Focus + * management finds a row by it, and the virtualizer reads it back off a + * measured element to know which row it just measured. */ -function findNode(nodes: TreeNodeData[], id: string): TreeNodeData | undefined { - for (const node of nodes) { - if (node.id === id) return node; - if (node.children) { - const found = findNode(node.children, id); - if (found) return found; - } - } - return undefined; -} +const ROW_INDEX_ATTRIBUTE = 'data-tree-row-index'; + +/** + * Opening guess at a row's height, per size — the `minHeight` of each size + * variant in `TreeNode.css.ts`, resolved at a 16px root font. + * + * Only ever a guess: `minHeight` comes from the rem-based spacing scale, while + * the text inside is sized from `--bk-font-size-*`, which tracks the host + * editor's UI font. Past roughly a 14px host font the text outgrows the floor — + * at `xs` it already does at the default — so rows are measured once mounted + * and these numbers only stand in for rows the reader has not reached. + */ +const ROW_HEIGHT_BY_SIZE: Record = { + xs: 16, + sm: 20, + md: 24, + lg: 28, + xl: 32, +}; + +/** + * Row count past which an unbounded tree is worth warning about. Below it, + * growing with content is an ordinary thing to want and the warning is noise. + */ +const WINDOWING_ADVICE_THRESHOLD = 500; + +/** + * Whether a controlled `expandedKeys` array still holds the same keys. + * + * Order-sensitive, and deliberately so: comparing as sets would need a set to + * compare against, which is the allocation this exists to avoid. A reorder + * therefore rebuilds — one wasted rebuild, never a wrong answer. + */ +const sameKeys = (a: readonly string[] | undefined, b: readonly string[]): boolean => + a !== undefined && a.length === b.length && a.every((key, i) => key === b[i]); // ─── Component ─────────────────────────────────────────────────────────────── @@ -231,7 +396,14 @@ export const Tree: React.FC = ({ edgeStyle = 'none', indentSize = 20, expandOnClick = true, + maxHeight, + fillHeight = false, + estimatedRowHeight: estimatedRowHeightProp, + overscan = 8, + disableVirtualization = false, className, + style, + onKeyDown: onKeyDownProp, ...props }) => { // ── Expansion state (controlled / uncontrolled) ────────────────────── @@ -239,145 +411,258 @@ export const Tree: React.FC = ({ const [internalExpanded, setInternalExpanded] = useState>( () => new Set(defaultExpandedKeys), ); - const expandedKeys = useMemo( - () => (isExpandControlled ? new Set(controlledExpandedKeys) : internalExpanded), - [isExpandControlled, controlledExpandedKeys, internalExpanded], - ); - const toggleExpand = useCallback( - (key: string, node: TreeNodeData) => { - const isExpanded = expandedKeys.has(key); - const next = new Set(expandedKeys); - if (isExpanded) { - next.delete(key); - } else { - next.add(key); - } + // A controlled `expandedKeys` becomes a Set once per real change rather than + // once per render, so a consumer deriving the array inline pays a comparison + // instead of a rebuild of every visible row. + // + // Held in state, not a ref: React discards the update along with an + // abandoned render, so there is no phase to reason about. Adjusting state + // during render re-runs this component immediately, before committing — + // props are fixed for that pass, so the condition is false the second time + // through and it settles at once. + const [prevKeys, setPrevKeys] = useState(controlledExpandedKeys); + const [controlledSet, setControlledSet] = useState(() => new Set(controlledExpandedKeys)); + if ( + isExpandControlled && + controlledExpandedKeys !== prevKeys && + !sameKeys(prevKeys, controlledExpandedKeys) + ) { + setPrevKeys(controlledExpandedKeys); + setControlledSet(new Set(controlledExpandedKeys)); + } - if (!isExpandControlled) { - setInternalExpanded(next); - } - onExpandChange?.(Array.from(next), { - key, - expanded: !isExpanded, - node, - }); - }, - [expandedKeys, isExpandControlled, onExpandChange], - ); + const expandedKeys = isExpandControlled ? controlledSet : internalExpanded; // ── Selection state (controlled / uncontrolled) ───────────────────── const isSelectControlled = controlledSelectedKey !== undefined; const [internalSelected, setInternalSelected] = useState(defaultSelectedKey); - const selectedKey = isSelectControlled ? controlledSelectedKey : internalSelected; - - const selectNode = useCallback( - (key: string, node: TreeNodeData) => { - if (!selectable) return; - if (node.disabled) return; - if (!isSelectControlled) { - setInternalSelected(key); - } - onSelect?.(key, node); - }, - [selectable, isSelectControlled, onSelect], + const selectedKey = (isSelectControlled ? controlledSelectedKey : internalSelected) ?? null; + + // ── Latest-value refs ─────────────────────────────────────────────── + // `toggleExpand` and `selectNode` go into the shared context, so rebuilding + // them on every expansion or inline callback change would re-render every + // mounted row. Reading current values through refs keeps them stable. + // + // Filled in an effect, not during render: a concurrent render can be + // abandoned, and a consumer deferring `setExpandedKeys` into a transition + // would otherwise leave these holding an uncommitted expansion set. Effects + // flush before the next discrete event, so handlers still read fresh values. + const expandedRef = useRef(expandedKeys); + const callbacksRef = useRef({ onExpandChange, onSelect, selectable, expandOnClick }); + const controlledRef = useRef({ isExpandControlled, isSelectControlled }); + + useEffect(() => { + expandedRef.current = expandedKeys; + callbacksRef.current = { onExpandChange, onSelect, selectable, expandOnClick }; + controlledRef.current = { isExpandControlled, isSelectControlled }; + }); + + const toggleExpand = useCallback((key: string, node: TreeNodeData) => { + const current = expandedRef.current; + const isExpanded = current.has(key); + const next = new Set(current); + if (isExpanded) { + next.delete(key); + } else { + next.add(key); + } + + if (!controlledRef.current.isExpandControlled) { + setInternalExpanded(next); + } + callbacksRef.current.onExpandChange?.(Array.from(next), { + key, + expanded: !isExpanded, + node, + }); + }, []); + + const selectNode = useCallback((key: string, node: TreeNodeData) => { + if (!callbacksRef.current.selectable) return; + if (node.disabled) return; + if (!controlledRef.current.isSelectControlled) { + setInternalSelected(key); + } + callbacksRef.current.onSelect?.(key, node); + }, []); + + // ── Flattened visible rows ────────────────────────────────────────── + const { rows, indexById } = useMemo( + () => flattenTree(nodes, expandedKeys), + [nodes, expandedKeys], ); - // ── Node element registry (for keyboard focus management) ─────────── - const nodeElementsRef = useRef>(new Map()); + // ── Focus management ──────────────────────────────────────────────── + // Focus is tracked by row index rather than by holding element + // references, because under windowing the element for a given row comes + // and goes with scrolling. `pendingFocusRef` marks "we asked to focus this + // row and have not managed to yet"; the effect below retries after each + // render, scrolling the row into the window when it is not mounted. + const viewportRef = useRef(null); + const [focusedIndex, setFocusedIndex] = useState(-1); + const pendingFocusRef = useRef(false); + + const focusRow = useCallback((index: number) => { + setFocusedIndex(index); + pendingFocusRef.current = true; + }, []); - const registerNode = useCallback((id: string, element: HTMLElement | null) => { - if (element) { - nodeElementsRef.current.set(id, element); + // ── Windowing ─────────────────────────────────────────────────────── + // A window needs a viewport with a resolved height to measure against. + // Without one the tree grows to fit its rows, there is nothing to scroll, + // and every visible row is mounted. + const hasBoundedHeight = maxHeight !== undefined || fillHeight; + const isWindowed = !disableVirtualization && hasBoundedHeight; + const estimatedRowHeight = estimatedRowHeightProp ?? ROW_HEIGHT_BY_SIZE[size]; + + const virtualizer = useVirtualizer({ + count: rows.length, + getScrollElement: () => viewportRef.current, + estimateSize: useCallback(() => estimatedRowHeight, [estimatedRowHeight]), + overscan, + enabled: isWindowed, + // Reuse the index rows already carry rather than a duplicate `data-index`. + indexAttribute: ROW_INDEX_ATTRIBUTE, + // No `getItemKey`: a fresh key function each render would invalidate the + // measurement memo and rebuild all `count` entries. Index-keying is safe + // because tree rows are uniform in height. + }); + + const virtualRows = isWindowed ? virtualizer.getVirtualItems() : []; + + const hasWarnedRef = useRef(false); + useEffect(() => { + if ( + !disableVirtualization && + !hasBoundedHeight && + rows.length > WINDOWING_ADVICE_THRESHOLD && + !hasWarnedRef.current + ) { + hasWarnedRef.current = true; + console.warn( + `Tree: ${rows.length} rows are visible but the tree has no bounded height, so all of ` + + 'them are mounted. Set `maxHeight` or `fillHeight` to render only the rows in ' + + 'view, or set `disableVirtualization` to suppress this warning.', + ); + } + }, [disableVirtualization, hasBoundedHeight, rows.length]); + + // Which row indices are currently in the DOM. Virtual items are always a + // contiguous run, so this stays a range check rather than a scan. + const firstRendered = isWindowed ? (virtualRows[0]?.index ?? -1) : 0; + const lastRendered = isWindowed + ? (virtualRows[virtualRows.length - 1]?.index ?? -2) + : rows.length - 1; + const isRendered = (index: number) => index >= firstRendered && index <= lastRendered; + + useEffect(() => { + if (!pendingFocusRef.current) return; + if (focusedIndex < 0 || focusedIndex >= rows.length) { + pendingFocusRef.current = false; + return; + } + const el = viewportRef.current?.querySelector( + `[${ROW_INDEX_ATTRIBUTE}="${focusedIndex}"]`, + ); + if (el) { + pendingFocusRef.current = false; + el.focus(); + } else if (isWindowed) { + // Not mounted yet — bring it into the window and try again on the + // render that follows. + virtualizer.scrollToIndex(focusedIndex); } else { - nodeElementsRef.current.delete(id); + pendingFocusRef.current = false; } - }, []); + }); // ── Keyboard navigation ───────────────────────────────────────────── + // Every case below is index arithmetic on `rows`, so a keypress costs the + // same on a 20-row tree as on a 20,000-row one. const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { - const visibleIds = flattenVisibleIds(nodes, expandedKeys); - if (visibleIds.length === 0) return; + // Runs first so the consumer can claim a key with `preventDefault`; + // the props spread below would otherwise replace navigation outright. + onKeyDownProp?.(e); + if (e.defaultPrevented) return; + if (rows.length === 0) return; - const currentId = document.activeElement?.getAttribute('data-tree-node-id') ?? null; - const currentIndex = currentId ? visibleIds.indexOf(currentId) : -1; - - const focusNode = (id: string) => { - const el = nodeElementsRef.current.get(id); - el?.focus(); - }; + const active = document.activeElement; + const attr = active?.getAttribute(ROW_INDEX_ATTRIBUTE); + const currentIndex = attr !== null && attr !== undefined ? Number(attr) : focusedIndex; + const row = currentIndex >= 0 ? rows[currentIndex] : undefined; switch (e.key) { case 'ArrowDown': { e.preventDefault(); - const nextIdx = currentIndex < visibleIds.length - 1 ? currentIndex + 1 : 0; - focusNode(visibleIds[nextIdx]); + focusRow(currentIndex < rows.length - 1 ? currentIndex + 1 : 0); break; } case 'ArrowUp': { e.preventDefault(); - const prevIdx = currentIndex > 0 ? currentIndex - 1 : visibleIds.length - 1; - focusNode(visibleIds[prevIdx]); + focusRow(currentIndex > 0 ? currentIndex - 1 : rows.length - 1); break; } case 'ArrowRight': { e.preventDefault(); - if (currentId) { - const node = findNode(nodes, currentId); - if (node?.children?.length) { - if (!expandedKeys.has(currentId)) { - toggleExpand(currentId, node); - } else { - // Move focus to first child - const firstChildId = node.children[0].id; - focusNode(firstChildId); - } - } + if (!row?.hasChildren) break; + if (!expandedKeys.has(row.node.id)) { + toggleExpand(row.node.id, row.node); + } else { + // An expanded node's first child is always the next row. + focusRow(currentIndex + 1); } break; } case 'ArrowLeft': { e.preventDefault(); - if (currentId) { - const node = findNode(nodes, currentId); - if (node?.children?.length && expandedKeys.has(currentId)) { - toggleExpand(currentId, node); - } - // else could move focus to parent — not implemented here for simplicity + if (!row) break; + if (row.hasChildren && expandedKeys.has(row.node.id)) { + toggleExpand(row.node.id, row.node); + } else if (row.parentIndex >= 0) { + // Now expressible: the row knows where its parent sits. + focusRow(row.parentIndex); } break; } case 'Home': { e.preventDefault(); - focusNode(visibleIds[0]); + focusRow(0); break; } case 'End': { e.preventDefault(); - focusNode(visibleIds[visibleIds.length - 1]); + focusRow(rows.length - 1); break; } case 'Enter': case ' ': { e.preventDefault(); - if (currentId) { - const node = findNode(nodes, currentId); - if (node && !node.disabled) { - selectNode(currentId, node); - if (node.children?.length && expandOnClick) { - toggleExpand(currentId, node); - } - } + if (!row || row.node.disabled) break; + selectNode(row.node.id, row.node); + if (row.hasChildren && expandOnClick) { + toggleExpand(row.node.id, row.node); } break; } } }, - [nodes, expandedKeys, toggleExpand, selectNode, expandOnClick], + [ + rows, + focusedIndex, + expandedKeys, + toggleExpand, + selectNode, + expandOnClick, + focusRow, + onKeyDownProp, + ], ); // ── Context value ─────────────────────────────────────────────────── + // Nothing here changes when the user expands or selects, so the value is + // stable across interaction and rows are free to memoise on their props. const contextValue = useMemo( () => ({ size, @@ -385,12 +670,10 @@ export const Tree: React.FC = ({ indentSize, selectable, expandOnClick, - expandedKeys, - selectedKey: selectedKey ?? null, expandIcon, toggleExpand, selectNode, - registerNode, + focusRow, }), [ size, @@ -398,31 +681,80 @@ export const Tree: React.FC = ({ indentSize, selectable, expandOnClick, - expandedKeys, - selectedKey, expandIcon, toggleExpand, selectNode, - registerNode, + focusRow, ], ); - const containerClassName = className - ? `${treeContainer({ size })} ${className}` - : treeContainer({ size }); + // ── Roving tabindex ───────────────────────────────────────────────── + // Exactly one mounted row is tabbable. If the preferred row has scrolled out + // of the window, the nearest mounted one stands in, so the tree never drops + // out of the Tab order. + const selectedIndex = selectedKey !== null ? (indexById.get(selectedKey) ?? -1) : -1; + const preferredTabIndex = + focusedIndex >= 0 ? focusedIndex : selectedIndex >= 0 ? selectedIndex : 0; + const tabbableIndex = isRendered(preferredTabIndex) ? preferredTabIndex : firstRendered; + + // Keyed off the bounded height, not off windowing: a cap without a scroller + // clips the rows below it out of reach. + const containerClassName = [ + treeContainer({ size }), + hasBoundedHeight && treeScrollArea, + className, + ] + .filter(Boolean) + .join(' '); + + // Spread into primitives rather than passing `row` itself: flattening + // rebuilds every row object on each expand, which would make the memo inert. + const renderRow = (index: number, offsetTop?: number) => { + const row = rows[index]; + return ( + + ); + }; return (
- {nodes.map((node) => ( - - ))} +
+ {isWindowed + ? virtualRows.map((v) => renderRow(v.index, v.start)) + : rows.map((_, index) => renderRow(index))} +
); diff --git a/packages/baukasten/src/components/Tree/TreeNode.css.ts b/packages/baukasten/src/components/Tree/TreeNode.css.ts index 6e9c007..a79605c 100644 --- a/packages/baukasten/src/components/Tree/TreeNode.css.ts +++ b/packages/baukasten/src/components/Tree/TreeNode.css.ts @@ -2,19 +2,15 @@ import { recipe } from '@vanilla-extract/recipes'; import { style, globalStyle } from '@vanilla-extract/css'; /** - * Tree node wrapper — wraps the row + its children sub-tree. - */ -export const treeNodeWrapper = style({ - display: 'flex', - flexDirection: 'column', -}); - -/** - * Tree node row — the clickable/focusable horizontal strip. + * Tree node row — the clickable/focusable horizontal strip, and the whole of a + * node: rows are siblings in one flat list, so there is no per-node wrapper and + * no children container. `position: relative` lets a row draw its own guides. */ export const treeNodeRow = recipe({ base: { display: 'flex', + position: 'relative', + boxSizing: 'border-box', alignItems: 'center', borderRadius: 'var(--bk-radius-sm)', transition: 'var(--bk-transition-colors)', @@ -188,272 +184,83 @@ export const nodeBadge = style({ fontSize: '0.875em', }); -// ─── Children container with tree-edge guides ──────────────────────────────── +// ─── Windowed placement ────────────────────────────────────────────────────── /** - * Children wrapper — rendered beneath the parent row. - * Uses CSS Grid animation for smooth expand/collapse. + * Applied to a row only while the tree is windowed. The mounted rows are an + * arbitrary slice — row 4,000 may be the first — so they are lifted out of flow + * and placed by `translateY` rather than stacking at the top of the canvas. */ -export const childrenContainer = recipe({ - base: { - display: 'grid', - position: 'relative', - transition: - 'grid-template-rows var(--bk-transition-slow), opacity var(--bk-transition-base)', - }, - - variants: { - isOpen: { - true: { - gridTemplateRows: '1fr', - opacity: 1, - }, - false: { - gridTemplateRows: '0fr', - opacity: 0, - }, - }, - }, - - defaultVariants: { - isOpen: false, - }, -}); - -/** - * Inner children wrapper — required for CSS Grid animation. - */ -export const childrenInner = style({ - overflow: 'hidden', - minHeight: 0, +export const treeRowWindowed = style({ + position: 'absolute', + top: 0, + left: 0, }); // ─── Edge guide styles ─────────────────────────────────────────────────────── /** - * Each child node is wrapped in an edge-guide container that draws the - * connector lines from parent to child. The indent is applied here. - */ -export const edgeGuideContainer = recipe({ - base: { - position: 'relative', - }, - - variants: { - edgeStyle: { - solid: {}, - dashed: {}, - dotted: {}, - none: {}, - }, - }, - - defaultVariants: { - edgeStyle: 'solid', - }, -}); - -/** - * Vertical edge line for a single node's row. + * Vertical guide line, drawn as a real element inside the row it belongs to and + * positioned by an inline `left`. Rows are siblings rather than nested, so each + * one draws the ancestor columns passing through it. * - * `edgeGuideContainer` wraps ONLY the row, so its height equals one row. - * That lets the line be positioned with pure percentages, no row-height - * variable needed: - * - `top: -50%` reaches half a row up — to the parent / previous-sibling - * row centre (the previous wrapper is exactly one row above). - * - `height: 100%` ends the line at this row's own centre. - * - `height: 150%` extends it to this row's bottom, where the - * `edgeChildLine` (drawn on the children group) takes over. + * Worth knowing: with `dashed` / `dotted` the dash pattern restarts at each row + * boundary, since this is many one-row borders rather than one tall one. * - * `extendDown` is true only for an expanded parent that has a sibling - * below it — the one case where the line must continue past the row. + * `span: 'full'` runs the line through the whole row, for a column that + * continues below. `span: 'half'` stops at the vertical centre where the elbow + * meets it — the last-child corner. */ -export const edgeVerticalLine = recipe({ +export const edgeGuideVertical = recipe({ base: { - selectors: { - '&::before': { - content: '""', - position: 'absolute', - top: '-50%', - left: 'var(--bk-tree-indent-center)', - width: 0, - borderLeftWidth: 'var(--bk-border-width-1)', - borderLeftColor: 'var(--bk-tree-edge-color)', - }, - }, + position: 'absolute', + top: 0, + width: 0, + pointerEvents: 'none', + borderLeftWidth: 'var(--bk-border-width-1)', + borderLeftColor: 'var(--bk-tree-edge-color)', }, variants: { edgeStyle: { - solid: { - selectors: { - '&::before': { - borderLeftStyle: 'solid', - }, - }, - }, - dashed: { - selectors: { - '&::before': { - borderLeftStyle: 'dashed', - }, - }, - }, - dotted: { - selectors: { - '&::before': { - borderLeftStyle: 'dotted', - }, - }, - }, - none: { - selectors: { - '&::before': { - display: 'none', - }, - }, - }, - }, - extendDown: { - true: { - selectors: { - // Reach this row's bottom to meet the children-group line - '&::before': { - height: '150%', - }, - }, - }, - false: { - selectors: { - // Stop at this row's centre - '&::before': { - height: '100%', - }, - }, - }, - }, - }, - - defaultVariants: { - edgeStyle: 'solid', - extendDown: false, - }, -}); - -/** - * Horizontal connector from the vertical line to the node row. - * Drawn using an ::after pseudo-element. - */ -export const edgeHorizontalLine = recipe({ - base: { - selectors: { - '&::after': { - content: '""', - position: 'absolute', - top: '50%', - left: 'var(--bk-tree-indent-center)', - width: 'var(--bk-tree-branch-width)', - height: 0, - borderTopWidth: 'var(--bk-border-width-1)', - borderTopColor: 'var(--bk-tree-edge-color)', - }, + solid: { borderLeftStyle: 'solid' }, + dashed: { borderLeftStyle: 'dashed' }, + dotted: { borderLeftStyle: 'dotted' }, + none: { display: 'none' }, }, - }, - - variants: { - edgeStyle: { - solid: { - selectors: { - '&::after': { - borderTopStyle: 'solid', - }, - }, - }, - dashed: { - selectors: { - '&::after': { - borderTopStyle: 'dashed', - }, - }, - }, - dotted: { - selectors: { - '&::after': { - borderTopStyle: 'dotted', - }, - }, - }, - none: { - selectors: { - '&::after': { - display: 'none', - }, - }, - }, + span: { + full: { bottom: 0 }, + half: { height: '50%' }, }, }, defaultVariants: { edgeStyle: 'solid', + span: 'full', }, }); /** - * Vertical edge line drawn on a node's children group. - * - * `childrenContainer` spans the node's entire expanded subtree, so this - * `::before` carries the guide line *through* that subtree — from the - * node's row bottom down to its next sibling — keeping the line unbroken - * when a folder is expanded. Applied only to non-last nodes (a last node - * has no sibling below to connect to). Sits at the node's own indent - * column, so it reuses the same `--bk-tree-indent-center` value as the row. + * Horizontal connector running from a row's own guide column across to where + * its content begins. Width is supplied inline, because it depends on + * `indentSize` and on whether the row shows a chevron or only the spacer. */ -export const edgeChildLine = recipe({ +export const edgeGuideHorizontal = recipe({ base: { - selectors: { - '&::before': { - content: '""', - position: 'absolute', - top: 0, - bottom: 0, - left: 'var(--bk-tree-indent-center)', - width: 0, - borderLeftWidth: 'var(--bk-border-width-1)', - borderLeftColor: 'var(--bk-tree-edge-color)', - }, - }, + position: 'absolute', + top: '50%', + height: 0, + pointerEvents: 'none', + borderTopWidth: 'var(--bk-border-width-1)', + borderTopColor: 'var(--bk-tree-edge-color)', }, variants: { edgeStyle: { - solid: { - selectors: { - '&::before': { - borderLeftStyle: 'solid', - }, - }, - }, - dashed: { - selectors: { - '&::before': { - borderLeftStyle: 'dashed', - }, - }, - }, - dotted: { - selectors: { - '&::before': { - borderLeftStyle: 'dotted', - }, - }, - }, - none: { - selectors: { - '&::before': { - display: 'none', - }, - }, - }, + solid: { borderTopStyle: 'solid' }, + dashed: { borderTopStyle: 'dashed' }, + dotted: { borderTopStyle: 'dotted' }, + none: { display: 'none' }, }, }, diff --git a/packages/baukasten/src/components/Tree/TreeNode.tsx b/packages/baukasten/src/components/Tree/TreeNode.tsx index 596a554..9501242 100644 --- a/packages/baukasten/src/components/Tree/TreeNode.tsx +++ b/packages/baukasten/src/components/Tree/TreeNode.tsx @@ -1,32 +1,48 @@ -import React, { useCallback, useEffect, useRef } from 'react'; +import React, { useCallback } from 'react'; import { Icon } from '../Icon'; import { useTreeContext, type TreeNodeData } from './Tree'; import { - treeNodeWrapper, treeNodeRow, expandIconWrapper, expandIconSpacer, nodeIconWrapper, nodeLabel, nodeBadge, - childrenContainer, - childrenInner, - edgeGuideContainer, - edgeVerticalLine, - edgeHorizontalLine, - edgeChildLine, + treeRowWindowed, + edgeGuideVertical, + edgeGuideHorizontal, } from './TreeNode.css'; /** - * Props for the internal TreeNode component. + * Props for the internal row component. All primitives plus `node`, which is + * the consumer's own object and keeps its identity, so the `React.memo` below + * compares exactly. */ interface TreeNodeComponentProps { - /** The node data to render */ + /** Position in the flattened visible-row array. */ + index: number; node: TreeNodeData; - /** Current nesting depth (0 for root) */ + /** 0 for a root node. */ depth: number; - /** Whether this node is the last sibling in its group */ - isLast?: boolean; + hasChildren: boolean; + /** True when this row is the last of its sibling group. */ + isLast: boolean; + /** Bit `d` set when the ancestor at depth `d` still has a sibling below. */ + guideMask: number; + posInSet: number; + setSize: number; + expanded: boolean; + selected: boolean; + /** True for the single row that holds the tree's tab stop. */ + tabbable: boolean; + /** Distance from the top of the scroll canvas; set only when windowed. */ + offsetTop?: number; + /** + * Reports the row's real height back to the virtualizer; set only when + * windowed. Must be stable — the virtualizer's bound method is, an inline + * arrow would defeat the memo and re-attach on every render. + */ + measureRef?: (node: Element | null) => void; } /** @@ -39,13 +55,25 @@ const ROW_CONTENT_INSET = 8; /** * TreeNodeComponent (internal) * - * Recursively renders a tree node and its children. - * Draws edge guides when the tree has `edgeStyle` other than 'none'. + * Renders exactly one row. It has no knowledge of its children: they are + * separate rows in the same flat list. Guide lines are reconstructed from + * `guideMask` so a row can draw every ancestor column without its ancestors + * being mounted, which under windowing they frequently are not. */ -export const TreeNodeComponent: React.FC = ({ +const TreeNodeComponentImpl: React.FC = ({ + index, node, depth, - isLast = false, + hasChildren, + isLast, + guideMask, + posInSet, + setSize, + expanded, + selected, + tabbable, + offsetTop, + measureRef, }) => { const { size, @@ -53,24 +81,14 @@ export const TreeNodeComponent: React.FC = ({ indentSize, selectable, expandOnClick, - expandedKeys, - selectedKey, expandIcon: customExpandIcon, toggleExpand, selectNode, - registerNode, + focusRow, } = useTreeContext(); - const rowRef = useRef(null); - const hasChildren = !!(node.children && node.children.length > 0); - const isExpanded = expandedKeys.has(node.id); - const isSelected = selectedKey === node.id; - - // Register / unregister in the node-elements map - useEffect(() => { - registerNode(node.id, rowRef.current); - return () => registerNode(node.id, null); - }, [node.id, registerNode]); + const isExpanded = expanded; + const isSelected = selected; // ── Click handler ──────────────────────────────────────────────────── const handleRowClick = useCallback( @@ -78,6 +96,10 @@ export const TreeNodeComponent: React.FC = ({ if (node.disabled) return; e.stopPropagation(); + // Clicking a row makes it the tree's tab stop, so a later Tab + // returns here rather than to the top of the list. + focusRow(index); + if (selectable) { selectNode(node.id, node); } @@ -86,16 +108,21 @@ export const TreeNodeComponent: React.FC = ({ toggleExpand(node.id, node); } }, - [node, hasChildren, selectable, expandOnClick, selectNode, toggleExpand], + [node, index, hasChildren, selectable, expandOnClick, selectNode, toggleExpand, focusRow], ); const handleExpandClick = useCallback( (e: React.MouseEvent) => { if (node.disabled) return; + // A custom `expandIcon` is rendered for leaves too, and toggling one + // would put an id in `expandedKeys` that nothing ever reads — and + // hand it to the consumer's `onExpandChange` to store. Fall through + // to the row instead, so the click still selects. + if (!hasChildren) return; e.stopPropagation(); toggleExpand(node.id, node); }, - [node, toggleExpand], + [node, hasChildren, toggleExpand], ); // ── Expand icon ────────────────────────────────────────────────────── @@ -136,108 +163,111 @@ export const TreeNodeComponent: React.FC = ({ // ── Indent calculation ─────────────────────────────────────────────── const showEdges = edgeStyle !== 'none' && depth > 0; const indentPx = depth * indentSize; - // Center of the indent gutter (for edge lines), relative to the left of this node's row - // The indent center is at "parentIndent + indentSize/2" + // Centre of this row's own indent gutter — the column its elbow hangs + // from, and the column its children will hang their elbows one level + // right of. const indentCenterPx = (depth - 1) * indentSize + indentSize / 2; // Horizontal branch width from the vertical line to the node content. // Reaches from the indent gutter centre all the way to the row content, // which sits ROW_CONTENT_INSET past the indent edge. const branchWidthPx = indentSize / 2 + ROW_CONTENT_INSET; - // A leaf with no custom expand icon still renders an invisible 1em - // spacer where the chevron would sit. Extend the connector across that - // spacer so it ends where the chevron's right edge would be — the - // connector "stands in" for the missing chevron, leaving the same row - // gap before the icon that a chevron row has. + // A leaf without a custom icon renders an invisible 1em spacer where the + // chevron would sit; extend the connector across it so the gap before the + // icon matches a row that has a chevron. const hasSpacerOnly = !customExpandIcon && !hasChildren; const branchWidth = hasSpacerOnly ? `calc(${branchWidthPx}px + 1em)` : `${branchWidthPx}px`; - // ── CSS custom properties for edge positioning ────────────────────── - const edgeVars: React.CSSProperties = showEdges - ? ({ - '--bk-tree-indent-center': `${indentCenterPx}px`, - '--bk-tree-branch-width': branchWidth, - } as React.CSSProperties) - : {}; + // ── Edge guides ────────────────────────────────────────────────────── + // Drawn inside this row's own box: one vertical per continuing ancestor + // column, this row's own vertical, and the elbow across to the content. + // The row has no border, so absolute `left` offsets resolve against its + // left edge and line up with the indent whatever its `paddingLeft`. + const renderGuides = () => { + if (!showEdges) return null; + const guides: React.ReactNode[] = []; + + // An ancestor at depth `d` continues one gutter left of where its own + // children hang. Depth 0 has no gutter, so bit 0 is never drawn. + for (let ancestorDepth = 1; ancestorDepth < depth; ancestorDepth++) { + if ((guideMask & (1 << ancestorDepth)) === 0) continue; + guides.push( +