From c9da20b59ce5514143b8ebb2114a6904f46e2614 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Tue, 1 Dec 2026 10:07:53 -0500 Subject: [PATCH] fix(VirtualGrid): backport 1.7.3 initial-setup fixes to 1.6 Brings src/primitives/VirtualGrid.tsx to its 1.7.3 state (B15 fixes from #72) and ports the matching contract tests: - an initial `selected` scrolls to its row and is applied once; the app's onSelectedChanged sees lastIdx === idx for that call, as with Row/Column - the node's `selected` is a child index into the window, set once, not the data index (autofocus with selected past the first window focused the wrong item; reactive selected back to row 0 left the grid scrolled) - last-row guard uses floor((count - 1) / perRow) - `this.selected` is written only when a child exists at the new index (a Down with nothing below lost the next Up) - one flex pass per window shift (layoutPending + onLayout wrapper, applyShift without a per-press closure) - `cursor` set in its own render effect instead of the props spread Co-Authored-By: Claude Opus 5.5 --- src/primitives/VirtualGrid.tsx | 124 +++++++++-- tests/contract-virtual-grid.test.tsx | 308 ++++++++++++++++++++++++--- 2 files changed, 378 insertions(+), 54 deletions(-) diff --git a/src/primitives/VirtualGrid.tsx b/src/primitives/VirtualGrid.tsx index c405a3c..afe94a5 100644 --- a/src/primitives/VirtualGrid.tsx +++ b/src/primitives/VirtualGrid.tsx @@ -52,15 +52,25 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { return Math.min(items().length, rawEnd); }); - const [slice, setSlice] = s.createSignal(items().slice(start(), end())); + const [slice, setSliceSignal] = s.createSignal(items().slice(start(), end())); + // Set when the window's items change, cleared by the grid's next flex pass + // (onLayout): a window shift lays the grid out only if nothing else has. + let layoutPending = false; + function setSlice(window: T[]) { + layoutPending = true; + setSliceSignal(window); + } let viewRef!: lngp.NavigableElement; function onVerticalNav(dir: -1 | 1): lngp.KeyHandler { return function () { const perRow = itemsPerRow(); + const count = items().length; const currentRowIndex = Math.floor(cursor() / perRow); - const maxRows = Math.floor(items().length / perRow); + // B15: the last row's index. floor(length / perRow) was one row late + // when the length is a multiple of perRow. + const maxRows = Math.floor((count - 1) / perRow); if ( currentRowIndex === 0 && dir === -1 @@ -69,19 +79,21 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { const selected = this.selected || 0; const offset = dir * perRow; - const newIndex = utils.clamp(selected + offset, 0, items().length - 1); - const lastIdx = selected; - this.selected = newIndex; - const active = this.children[this.selected]; + const newIndex = utils.clamp(selected + offset, 0, count - 1); + const active = this.children[newIndex]; + // B15: `selected` changes only when there is a child to move to. It was + // written first, so a Down with nothing below left it past the mounted + // children and the next Up was lost. if (active instanceof lng.ElementNode) { + this.selected = newIndex; active.setFocus(); chainedOnSelectedChanged.call( this as lngp.NavigableElement, - this.selected, + newIndex, this as lngp.NavigableElement, active, - lastIdx + selected ); return true; } @@ -91,9 +103,16 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { const onUp = onVerticalNav(-1); const onDown = onVerticalNav(1); + // B15: set by applySelected for the call that applies an initial + // `selected`. The app gets lastIdx === idx there (as Row and Column report + // a mount selection); internally there is no previous selection, so the + // scroll to that row runs. + let forceRowScroll = false; + const onSelectedChanged: lngp.OnSelectedChanged = function (_idx, elm, active, _lastIdx,) { let idx = _idx; - let lastIdx = _lastIdx; + let lastIdx = forceRowScroll ? undefined : _lastIdx; + forceRowScroll = false; const perRow = itemsPerRow(); const newRowIndex = Math.floor(idx / perRow); const prevRowIndex = Math.floor((lastIdx || 0) / perRow); @@ -103,9 +122,9 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { if (newRowIndex === prevRowIndex) return; // Read before the window changes: the post-mutation flex pass can run - // before the microtask below, and active.y read there is already the new - // layout, so the rows jumped a row instead of animating once the window slid. - const prevRowY = this.y + active.y; + // before applyShift, and active.y read there is already the new layout, + // so the rows jumped a row instead of animating once the window slid. + shiftPrevRowY = this.y + active.y; setSlice(items().slice(start(), end())); // this.selected is relative to the slice @@ -119,15 +138,51 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { props.onEndReached?.(); } - queueMicrotask(() => { - this.updateLayout(); - this.lng.y = prevRowY - active.y; - columnScroll(idx, elm, active, lastIdx); - }); + // `elm` is the grid (`this`): navigation calls it on itself. + shiftView = elm; + shiftActive = active; + shiftIdx = idx; + shiftLastIdx = lastIdx; + queueMicrotask(applyShift); }; + // The scroll after a row change, run in a microtask once the new window is + // mounted. One function for every press (no closure per press): the press + // stores what it needs here. + let shiftView!: lngp.NavigableElement; + let shiftActive!: lng.ElementNode; + let shiftIdx = 0; + let shiftLastIdx: number | undefined; + let shiftPrevRowY = 0; + function applyShift() { + const view = shiftView; + const active = shiftActive; + // One flex pass per window shift: lay out here only if the post-mutation + // layout has not already run since the window changed. + if (layoutPending) view.updateLayout(); + view.lng.y = shiftPrevRowY - active.y; + columnScroll(shiftIdx, view, active, shiftLastIdx); + } + const chainedOnSelectedChanged = lngp.chainFunctions(props.onSelectedChanged, onSelectedChanged)!; + // B15: an initial `selected` has not been applied (scrolled to) yet. It + // stays pending through runs that find no child (items still loading, or + // waiting for onEndReached) and is cleared by the run that applies it. + let initialSelectedPending = s.untrack(() => props.selected != null); + + function applySelected(active: lng.ElementNode, lastSelected: number) { + const idx = viewRef.selected; + if (initialSelectedPending) { + initialSelectedPending = false; + forceRowScroll = true; + lastSelected = idx; + } + chainedOnSelectedChanged.call(viewRef, idx, viewRef, active, lastSelected); + // Not consumed when the app's handler returned true and stopped the chain. + forceRowScroll = false; + } + let cachedSelected: number | undefined; const updateSelected = ([selected, _items]: [number?, any?]) => { if (!viewRef || selected == null) return; @@ -153,20 +208,20 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { // force focus as scrollToIndex is manually called active.setFocus(); } - chainedOnSelectedChanged.call(viewRef, viewRef.selected, viewRef, active, lastSelected); + applySelected(active, lastSelected); } else { setCursor(selected); setSlice(items().slice(start(), end())); queueMicrotask(() => { - viewRef.updateLayout(); + if (layoutPending) viewRef.updateLayout(); active = viewRef.children.find(x => x.item === item); if (active instanceof lng.ElementNode) { viewRef.selected = viewRef.children.indexOf(active); if (lng.hasFocus(viewRef)) { active.setFocus(); } - chainedOnSelectedChanged.call(viewRef, viewRef.selected, viewRef, active, lastSelected); + applySelected(active, lastSelected); } }); } @@ -205,13 +260,28 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { ); - return ( + // Clears layoutPending: the grid's flex pass has run since the window + // changed. The app's onLayout still runs, read when called. + function onLayout(this: lng.ElementNode, target: lng.ElementNode) { + layoutPending = false; + return props.onLayout?.call(this, target); + } + + // B15: `selected` on the node is a child index into the window, set once + // here and then by navigation and the selected effect. Passing the data + // index (`props.selected`) made the first forwardFocus pick the wrong child, + // and its reactive rewrite hid the previous child index from updateSelected. + const initialSelected = s.untrack(() => + Math.max(0, (props.selected || 0) - start()), + ); + + const view = ( { viewRef = el as lngp.NavigableElement; }, props.ref)} - selected={props.selected || 0} - cursor={cursor()} + selected={/* @once */ initialSelected} + onLayout={/* @once */ onLayout} onLeft={/* @once */ lngp.chainFunctions(props.onLeft, lngp.navigableHandleNavigation)} onRight={/* @once */ lngp.chainFunctions(props.onRight, lngp.navigableHandleNavigation)} onUp={/* @once */ lngp.chainFunctions(props.onUp, onUp)} @@ -225,4 +295,12 @@ export function VirtualGrid(props: VirtualGridProps): s.JSX.Element { {props.children} ); + + // `cursor` has an effect of its own: in the spread above, a cursor change + // (every press) re-ran every prop of the spread. + s.createRenderEffect(() => { + viewRef.cursor = cursor(); + }); + + return view; } diff --git a/tests/contract-virtual-grid.test.tsx b/tests/contract-virtual-grid.test.tsx index f6131ae..7ce8767 100644 --- a/tests/contract-virtual-grid.test.tsx +++ b/tests/contract-virtual-grid.test.tsx @@ -200,6 +200,87 @@ v.describe('VirtualGrid', () => { }, ); + v.it( + 'a row change lays the grid out once, a move within a row not at all (1.7)', + async () => { + let grid!: lng.ElementNode; + dispose = await mount(() => ( + + + {(item) => } + + + )); + // The grid's flex passes: updateLayout calls, from the post-mutation + // layout phase and from VirtualGrid itself. + let n = 0; + const updateLayout = grid.updateLayout; + grid.updateLayout = function (this: lng.ElementNode) { + n++; + return updateLayout.call(this); + }; + const passes: number[] = []; + for (const key of [ + 'ArrowRight', + 'ArrowDown', + 'ArrowDown', + 'ArrowDown', + 'ArrowLeft', + 'ArrowUp', + 'ArrowUp', + ]) { + n = 0; + await press(key); + passes.push(n); + } + // It was two per row change and none within a row. + v.expect(passes).toEqual([0, 1, 1, 1, 0, 1, 1]); + }, + ); + + v.it( + 'a press re-runs only the props that depend on the cursor: an unrelated prop getter is not read again (1.7)', + async () => { + let grid!: lng.ElementNode; + let reads = 0; + const probe = () => { + reads++; + return 1; + }; + dispose = await mount(() => ( + + + {(item) => } + + + )); + const before = reads; + await press('ArrowRight', 'ArrowDown', 'ArrowDown', 'ArrowUp'); + v.expect(grid.cursor).toBe(4); + // It was read again on every press: the cursor was in the spread. + v.expect(reads).toBe(before); + }, + ); + v.it('defaults: rows 1, buffer 2, scroll "always"', async () => { let grid!: lng.ElementNode; dispose = await mount(() => ( @@ -336,9 +417,11 @@ v.describe('VirtualGrid', () => { setSel(10); await flush(); v.expect(state()).toEqual(['g10', 4, 10, -60, '6-17', 0]); - // Current behaviour: lastIdx is the new data index (the `selected` prop - // already wrote it to the node), not the previous child index. - v.expect(calls).toEqual([[4, 'g10', 10]]); + // B15 (1.7): lastIdx is the previous child index, in the previous + // window (g0 was child 0 of 0-8). It was the new data index (10): the + // `selected` prop wrote it to the node before updateSelected read it, + // the cause of the B15 test below where the grid stays scrolled. + v.expect(calls).toEqual([[4, 'g10', 0]]); calls.length = 0; // Past the end: onEndReached (no threshold needed), focus stays. @@ -354,9 +437,12 @@ v.describe('VirtualGrid', () => { setItems(range(30)); await flush(); v.expect(state()).toEqual(['g25', 4, 25, -60, '21-29', 1]); + // B15 (1.7): lastIdx is the previous child index, in the previous + // window (g10 was child 4 of 6-17), not the data index (25) the + // `selected` prop wrote to the node. v.expect(calls).toEqual([ - [4, 'g25', 25], - [4, 'g25', 25], + [4, 'g25', 4], + [4, 'g25', 4], ]); await press('ArrowRight'); @@ -364,14 +450,13 @@ v.describe('VirtualGrid', () => { }, ); - // Today: with autofocus and selected={10}, the first forwardFocus runs - // before the selected effect and treats 10 as a child index of the initial - // window (items 6-17), i.e. item 16; the grid ends on g16 with cursor 16. - // `selected={props.selected || 0}` passes the data index straight to the - // node (VirtualGrid.tsx:210) and navigableForwardFocus reads it as a child - // index. Without autofocus (setFocus later) g10 is focused correctly. - v.it.skip( - 'BUG: autofocus with an initial selected past the first window focuses the wrong item (VirtualGrid.tsx:210)', + // B15 (fixed in 1.7): with autofocus and selected={10}, the first + // forwardFocus runs before the selected effect and treated 10 as a child + // index of the initial window (items 6-17), i.e. item 16: the grid ended on + // g16 with cursor 16. `selected={props.selected || 0}` passed the data + // index straight to the node; it now gets the child index (10 - 6 = 4). + v.it( + 'B15: autofocus with an initial selected past the first window focuses that item', async () => { let grid!: lng.ElementNode; dispose = await mount(() => ( @@ -391,17 +476,176 @@ v.describe('VirtualGrid', () => { )); - v.expect([focusedId(), grid.cursor]).toEqual(['g10', 10]); + // y: g10's row (row 1 of the window 6-17, 100 high) at the grid's + // start, the same y as reaching g10 by Down then Up. + v.expect([focusedId(), grid.cursor, grid.selected, grid.y]).toEqual([ + 'g10', + 10, + 4, + -60, + ]); + await press('ArrowDown', 'ArrowUp'); + v.expect([focusedId(), grid.cursor, grid.y]).toEqual(['g10', 10, -60]); }, ); - // Today: after selected 10 -> 1, g1 is focused with y still -60, so the - // top row is drawn 60px above the grid's start. updateSelected reads - // lastSelected from the node (VirtualGrid.tsx:145) after the reactive - // `selected` prop has overwritten it with the new value, so the row-change - // check in onSelectedChanged (line 103) sees no change and skips the scroll. - v.it.skip( - 'BUG: reactive selected back to the first row leaves the grid scrolled (VirtualGrid.tsx:145)', + v.it( + 'B15: an initial selected without autofocus: focusing the grid later focuses that item, scrolled to its row', + async () => { + let grid!: lng.ElementNode; + dispose = await mount(() => ( + + + {(item) => } + + + )); + grid.setFocus(); + await flush(); + v.expect([focusedId(), grid.cursor, grid.selected, grid.y]).toEqual([ + 'g10', + 10, + 4, + -60, + ]); + }, + ); + + for (const autofocus of [true, false]) { + v.it( + `B15: an initial selected applied when the items arrive after mount scrolls to its row (${autofocus ? 'autofocus' : 'focused later'})`, + async () => { + let grid!: lng.ElementNode; + const [items, setItems] = s.createSignal([]); + dispose = await mount(() => ( + + + {(item) => } + + + )); + setItems(range(20)); + await flush(); + if (!autofocus) { + grid.setFocus(); + await flush(); + } + // As with the items present at mount (and as in 1.6): g10's row at + // the grid's start. A mount run that found no child used to use up + // the initial scroll, leaving y at 40. + v.expect([focusedId(), grid.cursor, grid.selected, grid.y]).toEqual([ + 'g10', + 10, + 4, + -60, + ]); + }, + ); + } + + v.it( + 'B15: an initial selected past the end (onEndReached) scrolls to its row once the items arrive', + async () => { + let grid!: lng.ElementNode; + const [items, setItems] = s.createSignal(range(20)); + const onEndReached = v.vi.fn(); + dispose = await mount(() => ( + + + {(item) => } + + + )); + v.expect(onEndReached).toHaveBeenCalledTimes(1); + setItems(range(30)); + await flush(); + // Window 21-29: g25 is child 4, in its second row. + v.expect([focusedId(), grid.cursor, grid.selected, grid.y]).toEqual([ + 'g25', + 25, + 4, + -60, + ]); + }, + ); + + for (const selected of [10, 0]) { + v.it( + `B15: the mount call of onSelectedChanged for selected={${selected}} reports lastIdx === idx, as Row and Column do`, + async () => { + const calls: unknown[][] = []; + dispose = await mount(() => ( + + + calls.push([idx, active?.id, lastIdx]) + } + > + {(item) => } + + + )); + // Three calls on an autofocus mount with `selected` (forwardFocus and + // the selected effect), each with lastIdx === idx. B15 (1.7): for + // selected={10} they were child 10 / item 16 (see the B15 test + // above); selected={0} is unchanged. + const idx = selected === 10 ? 4 : 0; + const id = `g${selected}`; + v.expect(calls).toEqual([ + [idx, id, idx], + [idx, id, idx], + [idx, id, idx], + ]); + }, + ); + } + + // B15 (fixed in 1.7): after selected 10 -> 1, g1 was focused with y still + // -60, so the top row was drawn 60px above the grid's start. updateSelected + // read lastSelected from the node after the reactive `selected` prop had + // overwritten it with the new value, so the row-change check in + // onSelectedChanged saw no change and skipped the scroll. The prop no + // longer writes the node's `selected` after mount. + v.it( + 'B15: reactive selected back to the first row scrolls the grid back', async () => { let grid!: lng.ElementNode; const [sel, setSel] = s.createSignal(undefined); @@ -430,14 +674,14 @@ v.describe('VirtualGrid', () => { }, ); - // Today: Down from g17 (no item below it) bubbles but leaves `selected` at - // 8, past the 8 mounted children; the next Up computes 8 - 3 = 5, lands on - // g17 again and the press is lost. onVerticalNav writes this.selected - // (VirtualGrid.tsx:74) before checking that the child exists (line 77). - // Its last-row guard (line 63, maxRows = floor(length / columns)) is also - // one row late when length is a multiple of columns. - v.it.skip( - 'BUG: a Down with nothing below corrupts selected, so the next Up is lost (VirtualGrid.tsx:74)', + // B15 (fixed in 1.7): Down from g17 (no item below it) bubbled but left + // `selected` at 8, past the 8 mounted children; the next Up computed + // 8 - 3 = 5, landed on g17 again and the press was lost. onVerticalNav + // wrote this.selected before checking that the child exists. Its last-row + // guard (maxRows = floor(length / columns)) was also one row late when the + // length is a multiple of columns. + v.it( + 'B15: a Down with nothing below leaves selected alone, so the next Up moves up', async () => { let grid!: lng.ElementNode; dispose = await mount(() => ( @@ -477,8 +721,10 @@ v.describe('VirtualGrid', () => { const settle = async () => { for (let i = 0; i < 4; i++) await flush(); }; - v.vi.stubGlobal('requestAnimationFrame', (cb: (time: number) => void) => - setTimeout(() => cb(performance.now() + 1e6), 0), + v.vi.stubGlobal( + 'requestAnimationFrame', + (cb: (time: number) => void) => + setTimeout(() => cb(performance.now() + 1e6), 0), ); lng.Config.animationsEnabled = true; try {