@solidtv/solid 1.7.0-0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/src/core/elementNode.d.ts +19 -1
  2. package/dist/src/core/elementNode.js +127 -26
  3. package/dist/src/core/elementNode.js.map +1 -1
  4. package/dist/src/core/focusManager.js +15 -4
  5. package/dist/src/core/focusManager.js.map +1 -1
  6. package/dist/src/core/lightningInit.js +65 -3
  7. package/dist/src/core/lightningInit.js.map +1 -1
  8. package/dist/src/core/nodeTypes.d.ts +1 -1
  9. package/dist/src/core/nodeTypes.js +2 -3
  10. package/dist/src/core/nodeTypes.js.map +1 -1
  11. package/dist/src/primitives/Lazy.jsx +7 -1
  12. package/dist/src/primitives/Lazy.jsx.map +1 -1
  13. package/dist/src/primitives/Virtual.d.ts +4 -0
  14. package/dist/src/primitives/Virtual.jsx +192 -106
  15. package/dist/src/primitives/Virtual.jsx.map +1 -1
  16. package/dist/src/primitives/VirtualGrid.jsx +87 -18
  17. package/dist/src/primitives/VirtualGrid.jsx.map +1 -1
  18. package/dist/src/primitives/utils/handleNavigation.js +12 -5
  19. package/dist/src/primitives/utils/handleNavigation.js.map +1 -1
  20. package/dist/src/primitives/utils/withScrolling.js +63 -57
  21. package/dist/src/primitives/utils/withScrolling.js.map +1 -1
  22. package/dist/tsconfig.tsbuildinfo +1 -1
  23. package/package.json +12 -5
  24. package/src/core/elementNode.ts +143 -22
  25. package/src/core/focusManager.ts +12 -4
  26. package/src/core/lightningInit.ts +78 -4
  27. package/src/core/nodeTypes.ts +6 -3
  28. package/src/primitives/Lazy.tsx +8 -1
  29. package/src/primitives/Virtual.tsx +211 -117
  30. package/src/primitives/VirtualGrid.tsx +98 -21
  31. package/src/primitives/utils/handleNavigation.ts +12 -5
  32. package/src/primitives/utils/withScrolling.ts +63 -62
@@ -21,6 +21,10 @@ export type VirtualProps<T> = lng.NewOmit<lngp.RowProps, 'children'> & {
21
21
  onEndReached?: () => void;
22
22
  onEndReachedThreshold?: number;
23
23
  debugInfo?: boolean;
24
+ /**
25
+ * @deprecated No effect since 1.7: a window shift always moves the row by
26
+ * one unscaled slot (item size + gap), the distance flex moves the items.
27
+ */
24
28
  factorScale?: boolean;
25
29
  uniformSize?: boolean;
26
30
  children: (item: s.Accessor<T>, index: s.Accessor<number>) => s.JSX.Element;
@@ -73,23 +77,23 @@ function createVirtual<T>(
73
77
  atStart: boolean;
74
78
  cursor: number;
75
79
  };
76
- const [slice, setSlice] = s.createSignal<SliceState>({
80
+ const noItems: T[] = [];
81
+ // One state object, updated in place by computeSlice, so a press allocates
82
+ // no state. The mounted items have a signal of their own: <List> re-runs
83
+ // only when the window's items change, not on every press.
84
+ const slice: SliceState = {
77
85
  start: 0,
78
- slice: [],
86
+ slice: noItems,
79
87
  selected: 0,
80
88
  delta: 0,
81
89
  shiftBy: 0,
82
90
  atStart: true,
83
91
  cursor: 0,
84
- });
85
-
86
- function normalizeDeltaForWindow(delta: number, windowLen: number): number {
87
- if (!windowLen) return 0;
88
- const half = windowLen / 2;
89
- if (delta > half) return delta - windowLen;
90
- if (delta < -half) return delta + windowLen;
91
- return delta;
92
- }
92
+ };
93
+ const [sliceItems, setSliceItems] = s.createSignal<T[]>(noItems);
94
+ // Set when the window's items change, cleared by the row's next flex pass
95
+ // (onLayout): the window shift lays the row out only if nothing else has.
96
+ let layoutPending = false;
93
97
 
94
98
  function computeSize(selected: number = 0) {
95
99
  if (uniformSize() && cachedScaledSize) {
@@ -100,47 +104,65 @@ function createVirtual<T>(
100
104
  const prevSelectedChild = viewRef.children[selected];
101
105
 
102
106
  if (prevSelectedChild instanceof lng.ElementNode) {
103
- const itemSize = prevSelectedChild[dimension] || 0;
104
- const focusStyle = prevSelectedChild.style?.focus as lng.NodeStyles;
105
- const scale = focusStyle?.scale ?? prevSelectedChild.scale ?? 1;
106
- const scaledSize = itemSize * (props.factorScale ? scale : 1) + gap;
107
- cachedScaledSize = scaledSize;
108
- return scaledSize;
107
+ // B14: a shift moves the row by one slot, the item's unscaled size
108
+ // plus the gap: the distance flex moves the items when the window
109
+ // shifts (flex has no scale term). Shifting by a scaled size
110
+ // (`factorScale`, which read the scale from `style.focus` or the
111
+ // child's current `scale`) moved the focused item (scale - 1) * size
112
+ // further on every shift. `factorScale` no longer has an effect.
113
+ const slotSize = (prevSelectedChild[dimension] || 0) + gap;
114
+ cachedScaledSize = slotSize;
115
+ return slotSize;
109
116
  }
110
117
  }
111
118
  return 0;
112
119
  }
113
120
 
114
- function computeSlice(
115
- c: number,
121
+ function applySlice(
122
+ start: number,
123
+ windowItems: T[],
124
+ selected: number,
116
125
  delta: number,
117
- prev: SliceState,
126
+ shiftBy: number,
127
+ atStart: boolean,
128
+ c: number,
118
129
  ): SliceState {
130
+ const prevItems = slice.slice;
131
+ slice.start = start;
132
+ slice.slice = windowItems;
133
+ slice.selected = selected;
134
+ slice.delta = delta;
135
+ slice.shiftBy = shiftBy;
136
+ slice.atStart = atStart;
137
+ slice.cursor = c;
138
+ if (windowItems !== prevItems) {
139
+ layoutPending = true;
140
+ setSliceItems(windowItems);
141
+ }
142
+ return slice;
143
+ }
144
+
145
+ function computeSlice(c: number, delta: number): SliceState {
146
+ const prev = slice;
119
147
  const total = itemCount();
120
- if (total === 0)
121
- return {
122
- start: 0,
123
- slice: [],
124
- selected: 0,
125
- delta,
126
- shiftBy: 0,
127
- atStart: true,
128
- cursor: 0,
129
- };
148
+ if (total === 0) return applySlice(0, noItems, 0, delta, 0, true, 0);
130
149
 
131
150
  if (total <= props.displaySize) {
132
- return {
133
- start: 0,
134
- slice: items() as T[],
135
- selected: utils.clamp(c, 0, total - 1),
151
+ const clamped = utils.clamp(c, 0, total - 1);
152
+ return applySlice(
153
+ 0,
154
+ items() as T[],
155
+ clamped,
136
156
  delta,
137
- shiftBy: 0,
138
- atStart: c <= 0,
139
- cursor: utils.clamp(c, 0, total - 1),
140
- };
157
+ 0,
158
+ c <= 0,
159
+ clamped,
160
+ );
141
161
  }
142
162
 
143
163
  const length = props.displaySize + bufferSize();
164
+ // Items mounted: `length`, or fewer for none/center with wrap (below).
165
+ let windowLength = length;
144
166
  let start = prev.start;
145
167
  let selected = prev.selected;
146
168
  let atStart = prev.atStart;
@@ -328,32 +350,52 @@ function createVirtual<T>(
328
350
  }
329
351
  case 'none':
330
352
  default:
331
- start = 0;
332
- selected = c;
353
+ // B13: the window follows the cursor, keeping an item mounted on
354
+ // each side of it so the next press finds a child. The row itself
355
+ // does not scroll. VirtualRow does not implement "center": it
356
+ // behaves as "none".
357
+ start = prev.start;
358
+ if (effectiveWrap()) {
359
+ // A modular window, as in the other wrap modes: keep the cursor in
360
+ // slots 1 .. windowLength - 2, so an item is mounted on each side
361
+ // of it across the end of the data. Outside the window (a jump),
362
+ // the cursor goes to slot 1. With fewer items than `length` the
363
+ // window holds each item once (a longer one would mount an item
364
+ // twice).
365
+ windowLength = total < length ? total : length;
366
+ const slot = utils.mod(c - start, total);
367
+ if (slot < 1 || slot >= windowLength) {
368
+ start = utils.mod(c - 1, total);
369
+ } else if (slot > windowLength - 2) {
370
+ start = utils.mod(c + 2 - windowLength, total);
371
+ }
372
+ selected = utils.mod(c - start, total);
373
+ } else {
374
+ if (c + 1 >= start + length) {
375
+ start = c + 2 - length;
376
+ } else if (c - 1 < start) {
377
+ start = c - 1;
378
+ }
379
+ start = utils.clamp(start, 0, Math.max(0, total - length));
380
+ selected = c - start;
381
+ }
333
382
  shiftBy = 0;
334
383
  break;
335
384
  }
336
385
 
337
386
  let newSlice = prev.slice;
338
387
  if (start !== prev.start || newSlice.length === 0) {
339
- newSlice = effectiveWrap()
340
- ? (Array.from(
341
- { length },
342
- (_, i) => items()[utils.mod(start + i, total)],
343
- ) as T[])
344
- : items().slice(start, start + length);
388
+ const all = items();
389
+ if (effectiveWrap()) {
390
+ newSlice = new Array<T>(windowLength);
391
+ for (let i = 0; i < windowLength; i++) {
392
+ newSlice[i] = all[utils.mod(start + i, total)] as T;
393
+ }
394
+ } else {
395
+ newSlice = all.slice(start, start + windowLength) as T[];
396
+ }
345
397
  }
346
398
 
347
- const state: SliceState = {
348
- start,
349
- slice: newSlice,
350
- selected,
351
- delta,
352
- shiftBy,
353
- atStart,
354
- cursor: c,
355
- };
356
-
357
399
  if (props.debugInfo) {
358
400
  console.log(`[Virtual]`, {
359
401
  cursor: c,
@@ -361,11 +403,11 @@ function createVirtual<T>(
361
403
  start,
362
404
  selected,
363
405
  shiftBy,
364
- slice: state.slice,
406
+ slice: newSlice,
365
407
  });
366
408
  }
367
409
 
368
- return state;
410
+ return applySlice(start, newSlice, selected, delta, shiftBy, atStart, c);
369
411
  }
370
412
 
371
413
  let viewRef!: lngp.NavigableElement;
@@ -390,15 +432,69 @@ function createVirtual<T>(
390
432
  }
391
433
 
392
434
  let lastNavTime = 0;
393
- function getAdaptiveDuration(duration: number = 250) {
394
- const now = performance.now();
395
- const delta = now - lastNavTime;
396
- lastNavTime = now;
397
- if (delta < duration) return delta;
398
- return duration;
399
- }
400
435
 
401
436
  let originalPosition: number | undefined;
437
+
438
+ // The window shift after a press, run in a microtask once the new window
439
+ // is mounted. One function for every press (no closure per press): the
440
+ // press stores what it needs here.
441
+ let shiftView!: lng.ElementNode;
442
+ let shiftActive!: lng.ElementNode;
443
+ let shiftPrevChildPos = 0;
444
+ // The shift animation's props and settings, reused: renderer v2 and the
445
+ // DOM renderer copy both when they create the animation. The settings are
446
+ // copied again from the row's animationSettings on every shift, into a
447
+ // new object only when the row's settings object changes.
448
+ const shiftProps: Partial<lng.AnimateProps> = isRow ? { x: 0 } : { y: 0 };
449
+ let shiftSettings: lng.AnimationSettings = {};
450
+ let shiftSettingsFrom: lng.AnimationSettings | undefined;
451
+ function applyShift() {
452
+ const view = shiftView;
453
+ const active = shiftActive;
454
+ // One flex pass per window shift: lay out here only if the post-mutation
455
+ // layout has not already run since the window changed.
456
+ if (layoutPending) view.updateLayout();
457
+ const childSize = computeSize(slice.selected);
458
+
459
+ if (
460
+ cachedAnimationController &&
461
+ cachedAnimationController.state === 'running'
462
+ ) {
463
+ cachedAnimationController.stop();
464
+ }
465
+
466
+ if (lng.Config.animationsEnabled) {
467
+ view.lng[axis] = shiftPrevChildPos - active[axis];
468
+ targetPosition = view.lng[axis] + childSize * slice.shiftBy;
469
+ const settings = view.animationSettings;
470
+ if (settings !== shiftSettingsFrom) {
471
+ shiftSettings = {};
472
+ shiftSettingsFrom = settings;
473
+ }
474
+ for (const key in settings) {
475
+ (shiftSettings as Record<string, unknown>)[key] =
476
+ settings[key as keyof lng.AnimationSettings];
477
+ }
478
+ // The time since the last shift, up to the row's duration (250 by
479
+ // default). Inline, as the wrap delta below: a helper with one call
480
+ // site would be a closure per press under terser's default
481
+ // reduce_funcs.
482
+ const now = performance.now();
483
+ const sinceLast = now - lastNavTime;
484
+ lastNavTime = now;
485
+ const settingsDuration = settings?.duration;
486
+ const duration = settingsDuration === undefined ? 250 : settingsDuration;
487
+ shiftSettings.duration = sinceLast < duration ? sinceLast : duration;
488
+ shiftProps[axis] = targetPosition;
489
+ cachedAnimationController = view
490
+ .animate(shiftProps, shiftSettings)
491
+ .start();
492
+ } else {
493
+ view.lng[axis] =
494
+ shiftPrevChildPos - active[axis] + childSize * slice.shiftBy;
495
+ }
496
+ }
497
+
402
498
  const onSelectedChanged: lngp.OnSelectedChanged = function (
403
499
  _idx,
404
500
  elm,
@@ -420,59 +516,45 @@ function createVirtual<T>(
420
516
 
421
517
  const rawDelta = idx - (lastIdx ?? 0);
422
518
  const windowLen = elm?.children?.length ?? props.displaySize + bufferSize();
423
- const delta = effectiveWrap()
424
- ? normalizeDeltaForWindow(rawDelta, windowLen)
425
- : rawDelta;
426
-
427
- setCursor((c) => {
428
- const next = c + delta;
429
- return effectiveWrap()
430
- ? utils.mod(next, total)
431
- : utils.clamp(next, 0, total - 1);
432
- });
519
+ const wrap = effectiveWrap();
520
+ // With wrap, the shorter way round the window.
521
+ let delta = rawDelta;
522
+ if (wrap) {
523
+ if (!windowLen) {
524
+ delta = 0;
525
+ } else {
526
+ const half = windowLen / 2;
527
+ if (delta > half) {
528
+ delta -= windowLen;
529
+ } else if (delta < -half) {
530
+ delta += windowLen;
531
+ }
532
+ }
533
+ }
534
+
535
+ const next = s.untrack(cursor) + delta;
536
+ const c = wrap ? utils.mod(next, total) : utils.clamp(next, 0, total - 1);
537
+ setCursor(c);
433
538
 
434
- const newState = computeSlice(cursor(), delta, slice());
435
- setSlice(newState);
539
+ const newState = computeSlice(c, delta);
436
540
  elm.selected = newState.selected;
437
541
 
438
542
  if (!wrapUnlocked() && rawDelta > 0) setWrapUnlocked(true);
439
543
 
440
544
  if (
441
545
  props.onEndReachedThreshold !== undefined &&
442
- cursor() >= itemCount() - props.onEndReachedThreshold
546
+ c >= itemCount() - props.onEndReachedThreshold
443
547
  ) {
444
548
  props.onEndReached?.();
445
549
  }
446
550
 
447
551
  if (newState.shiftBy === 0) return;
448
552
 
449
- const prevChildPos = (targetPosition ?? this[axis]) + active[axis];
450
-
451
- queueMicrotask(() => {
452
- elm.updateLayout();
453
- const childSize = computeSize(slice().selected);
454
-
455
- if (
456
- cachedAnimationController &&
457
- cachedAnimationController.state === 'running'
458
- ) {
459
- cachedAnimationController.stop();
460
- }
461
-
462
- if (lng.Config.animationsEnabled) {
463
- this.lng[axis] = prevChildPos - active[axis];
464
- targetPosition = this.lng[axis] + childSize * slice().shiftBy;
465
- cachedAnimationController = this.animate(
466
- { [axis]: targetPosition },
467
- {
468
- ...this.animationSettings,
469
- duration: getAdaptiveDuration(this.animationSettings?.duration),
470
- },
471
- ).start();
472
- } else {
473
- this.lng[axis] = (prevChildPos - active[axis]) + childSize * slice().shiftBy;
474
- }
475
- });
553
+ // `elm` is the row (`this`): navigation calls it on itself.
554
+ shiftView = elm;
555
+ shiftActive = active;
556
+ shiftPrevChildPos = (targetPosition ?? this[axis]) + active[axis];
557
+ queueMicrotask(applyShift);
476
558
  };
477
559
 
478
560
  const updateSelected = ([sel, _items]: [number?, any?]) => {
@@ -480,11 +562,10 @@ function createVirtual<T>(
480
562
  const safeSel = utils.clamp(sel, 0, itemCount() - 1);
481
563
  const item = items()[safeSel];
482
564
  setCursor(safeSel);
483
- const newState = computeSlice(safeSel, 0, slice());
484
- setSlice(newState);
565
+ const shiftBy = computeSlice(safeSel, 0).shiftBy;
485
566
 
486
567
  queueMicrotask(() => {
487
- viewRef.updateLayout();
568
+ if (layoutPending) viewRef.updateLayout();
488
569
  const activeIndex = viewRef.children.findIndex((x) => x.item === item);
489
570
  if (activeIndex === -1) return;
490
571
  viewRef.selected = activeIndex;
@@ -492,9 +573,9 @@ function createVirtual<T>(
492
573
  viewRef.children[activeIndex]?.setFocus();
493
574
  }
494
575
 
495
- if (newState.shiftBy === 0) return;
576
+ if (shiftBy === 0) return;
496
577
 
497
- const childSize = computeSize(slice().selected);
578
+ const childSize = computeSize(slice.selected);
498
579
  // Original Position is offset to support scrollToIndex
499
580
  originalPosition = originalPosition ?? viewRef.lng[axis];
500
581
  targetPosition = targetPosition ?? viewRef.lng[axis];
@@ -517,7 +598,7 @@ function createVirtual<T>(
517
598
  }
518
599
  // offset just for wrap so we keep one item before
519
600
  queueMicrotask(() => {
520
- const childSize = computeSize(slice().selected);
601
+ const childSize = computeSize(slice.selected);
521
602
  viewRef.lng[axis] = (viewRef.lng[axis] || 0) + childSize * -1;
522
603
  // Original Position is offset to support scrollToIndex
523
604
  originalPosition = viewRef.lng[axis];
@@ -536,13 +617,18 @@ function createVirtual<T>(
536
617
  c = Math.max(0, itemCount() - 1);
537
618
  setCursor(c);
538
619
  }
539
- const newState = computeSlice(c, 0, slice());
540
- setSlice(newState);
541
- viewRef.selected = newState.selected;
620
+ viewRef.selected = computeSlice(c, 0).selected;
542
621
  }),
543
622
  );
544
623
 
545
- return (
624
+ // Clears layoutPending: the row's flex pass has run since the window
625
+ // changed. The app's onLayout still runs, read when called.
626
+ function onLayout(this: lng.ElementNode, target: lng.ElementNode) {
627
+ layoutPending = false;
628
+ return props.onLayout?.call(this, target);
629
+ }
630
+
631
+ const view = (
546
632
  <view
547
633
  transitionLeft={isRow ? defaultTransitionBack : undefined}
548
634
  transitionRight={isRow ? defaultTransitionForward : undefined}
@@ -555,10 +641,10 @@ function createVirtual<T>(
555
641
  }, props.ref)}
556
642
  wrap={effectiveWrap()}
557
643
  selected={selected()}
558
- cursor={cursor()}
559
644
  forwardFocus={/* @once */ lngp.navigableForwardFocus}
560
645
  scrollToIndex={/* @once */ scrollToIndex}
561
646
  onSelectedChanged={/* @once */ onSelectedChanged}
647
+ onLayout={/* @once */ onLayout}
562
648
  style={
563
649
  /* @once */ lng.combineStyles(
564
650
  props.style,
@@ -575,9 +661,17 @@ function createVirtual<T>(
575
661
  )
576
662
  }
577
663
  >
578
- <List each={slice().slice}>{props.children}</List>
664
+ <List each={sliceItems()}>{props.children}</List>
579
665
  </view>
580
666
  );
667
+
668
+ // `cursor` has an effect of its own: in the spread above, a cursor change
669
+ // (every press) re-ran every prop of the spread.
670
+ s.createRenderEffect(() => {
671
+ viewRef.cursor = cursor();
672
+ });
673
+
674
+ return view;
581
675
  }
582
676
 
583
677
  export function VirtualRow<T>(props: VirtualProps<T>) {
@@ -52,15 +52,25 @@ export function VirtualGrid<T>(props: VirtualGridProps<T>): s.JSX.Element {
52
52
  return Math.min(items().length, rawEnd);
53
53
  });
54
54
 
55
- const [slice, setSlice] = s.createSignal(items().slice(start(), end()));
55
+ const [slice, setSliceSignal] = s.createSignal(items().slice(start(), end()));
56
+ // Set when the window's items change, cleared by the grid's next flex pass
57
+ // (onLayout): a window shift lays the grid out only if nothing else has.
58
+ let layoutPending = false;
59
+ function setSlice(window: T[]) {
60
+ layoutPending = true;
61
+ setSliceSignal(window);
62
+ }
56
63
 
57
64
  let viewRef!: lngp.NavigableElement;
58
65
 
59
66
  function onVerticalNav(dir: -1 | 1): lngp.KeyHandler {
60
67
  return function () {
61
68
  const perRow = itemsPerRow();
69
+ const count = items().length;
62
70
  const currentRowIndex = Math.floor(cursor() / perRow);
63
- const maxRows = Math.floor(items().length / perRow);
71
+ // B15: the last row's index. floor(length / perRow) was one row late
72
+ // when the length is a multiple of perRow.
73
+ const maxRows = Math.floor((count - 1) / perRow);
64
74
 
65
75
  if (
66
76
  currentRowIndex === 0 && dir === -1
@@ -69,19 +79,21 @@ export function VirtualGrid<T>(props: VirtualGridProps<T>): s.JSX.Element {
69
79
 
70
80
  const selected = this.selected || 0;
71
81
  const offset = dir * perRow;
72
- const newIndex = utils.clamp(selected + offset, 0, items().length - 1);
73
- const lastIdx = selected;
74
- this.selected = newIndex;
75
- const active = this.children[this.selected];
82
+ const newIndex = utils.clamp(selected + offset, 0, count - 1);
83
+ const active = this.children[newIndex];
76
84
 
85
+ // B15: `selected` changes only when there is a child to move to. It was
86
+ // written first, so a Down with nothing below left it past the mounted
87
+ // children and the next Up was lost.
77
88
  if (active instanceof lng.ElementNode) {
89
+ this.selected = newIndex;
78
90
  active.setFocus();
79
91
  chainedOnSelectedChanged.call(
80
92
  this as lngp.NavigableElement,
81
- this.selected,
93
+ newIndex,
82
94
  this as lngp.NavigableElement,
83
95
  active,
84
- lastIdx
96
+ selected
85
97
  );
86
98
  return true;
87
99
  }
@@ -91,9 +103,16 @@ export function VirtualGrid<T>(props: VirtualGridProps<T>): s.JSX.Element {
91
103
  const onUp = onVerticalNav(-1);
92
104
  const onDown = onVerticalNav(1);
93
105
 
106
+ // B15: set by applySelected for the call that applies an initial
107
+ // `selected`. The app gets lastIdx === idx there (as Row and Column report
108
+ // a mount selection); internally there is no previous selection, so the
109
+ // scroll to that row runs.
110
+ let forceRowScroll = false;
111
+
94
112
  const onSelectedChanged: lngp.OnSelectedChanged = function (_idx, elm, active, _lastIdx,) {
95
113
  let idx = _idx;
96
- let lastIdx = _lastIdx;
114
+ let lastIdx = forceRowScroll ? undefined : _lastIdx;
115
+ forceRowScroll = false;
97
116
  const perRow = itemsPerRow();
98
117
  const newRowIndex = Math.floor(idx / perRow);
99
118
  const prevRowIndex = Math.floor((lastIdx || 0) / perRow);
@@ -115,16 +134,51 @@ export function VirtualGrid<T>(props: VirtualGridProps<T>): s.JSX.Element {
115
134
  props.onEndReached?.();
116
135
  }
117
136
 
118
- queueMicrotask(() => {
119
- const prevRowY = this.y + active.y;
120
- this.updateLayout();
121
- this.lng.y = prevRowY - active.y;
122
- columnScroll(idx, elm, active, lastIdx);
123
- });
137
+ // `elm` is the grid (`this`): navigation calls it on itself.
138
+ shiftView = elm;
139
+ shiftActive = active;
140
+ shiftIdx = idx;
141
+ shiftLastIdx = lastIdx;
142
+ queueMicrotask(applyShift);
124
143
  };
125
144
 
145
+ // The scroll after a row change, run in a microtask once the new window is
146
+ // mounted. One function for every press (no closure per press): the press
147
+ // stores what it needs here.
148
+ let shiftView!: lngp.NavigableElement;
149
+ let shiftActive!: lng.ElementNode;
150
+ let shiftIdx = 0;
151
+ let shiftLastIdx: number | undefined;
152
+ function applyShift() {
153
+ const view = shiftView;
154
+ const active = shiftActive;
155
+ const prevRowY = view.y + active.y;
156
+ // One flex pass per window shift: lay out here only if the post-mutation
157
+ // layout has not already run since the window changed.
158
+ if (layoutPending) view.updateLayout();
159
+ view.lng.y = prevRowY - active.y;
160
+ columnScroll(shiftIdx, view, active, shiftLastIdx);
161
+ }
162
+
126
163
  const chainedOnSelectedChanged = lngp.chainFunctions(props.onSelectedChanged, onSelectedChanged)!;
127
164
 
165
+ // B15: an initial `selected` has not been applied (scrolled to) yet. It
166
+ // stays pending through runs that find no child (items still loading, or
167
+ // waiting for onEndReached) and is cleared by the run that applies it.
168
+ let initialSelectedPending = s.untrack(() => props.selected != null);
169
+
170
+ function applySelected(active: lng.ElementNode, lastSelected: number) {
171
+ const idx = viewRef.selected;
172
+ if (initialSelectedPending) {
173
+ initialSelectedPending = false;
174
+ forceRowScroll = true;
175
+ lastSelected = idx;
176
+ }
177
+ chainedOnSelectedChanged.call(viewRef, idx, viewRef, active, lastSelected);
178
+ // Not consumed when the app's handler returned true and stopped the chain.
179
+ forceRowScroll = false;
180
+ }
181
+
128
182
  let cachedSelected: number | undefined;
129
183
  const updateSelected = ([selected, _items]: [number?, any?]) => {
130
184
  if (!viewRef || selected == null) return;
@@ -150,20 +204,20 @@ export function VirtualGrid<T>(props: VirtualGridProps<T>): s.JSX.Element {
150
204
  // force focus as scrollToIndex is manually called
151
205
  active.setFocus();
152
206
  }
153
- chainedOnSelectedChanged.call(viewRef, viewRef.selected, viewRef, active, lastSelected);
207
+ applySelected(active, lastSelected);
154
208
  } else {
155
209
  setCursor(selected);
156
210
  setSlice(items().slice(start(), end()));
157
211
 
158
212
  queueMicrotask(() => {
159
- viewRef.updateLayout();
213
+ if (layoutPending) viewRef.updateLayout();
160
214
  active = viewRef.children.find(x => x.item === item);
161
215
  if (active instanceof lng.ElementNode) {
162
216
  viewRef.selected = viewRef.children.indexOf(active);
163
217
  if (lng.hasFocus(viewRef)) {
164
218
  active.setFocus();
165
219
  }
166
- chainedOnSelectedChanged.call(viewRef, viewRef.selected, viewRef, active, lastSelected);
220
+ applySelected(active, lastSelected);
167
221
  }
168
222
  });
169
223
  }
@@ -202,13 +256,28 @@ export function VirtualGrid<T>(props: VirtualGridProps<T>): s.JSX.Element {
202
256
  );
203
257
 
204
258
 
205
- return (
259
+ // Clears layoutPending: the grid's flex pass has run since the window
260
+ // changed. The app's onLayout still runs, read when called.
261
+ function onLayout(this: lng.ElementNode, target: lng.ElementNode) {
262
+ layoutPending = false;
263
+ return props.onLayout?.call(this, target);
264
+ }
265
+
266
+ // B15: `selected` on the node is a child index into the window, set once
267
+ // here and then by navigation and the selected effect. Passing the data
268
+ // index (`props.selected`) made the first forwardFocus pick the wrong child,
269
+ // and its reactive rewrite hid the previous child index from updateSelected.
270
+ const initialSelected = s.untrack(() =>
271
+ Math.max(0, (props.selected || 0) - start()),
272
+ );
273
+
274
+ const view = (
206
275
  <view
207
276
  {...props}
208
277
  scroll={props.scroll || 'always'}
209
278
  ref={lngp.chainRefs(el => { viewRef = el as lngp.NavigableElement; }, props.ref)}
210
- selected={props.selected || 0}
211
- cursor={cursor()}
279
+ selected={/* @once */ initialSelected}
280
+ onLayout={/* @once */ onLayout}
212
281
  onLeft={/* @once */ lngp.chainFunctions(props.onLeft, lngp.navigableHandleNavigation)}
213
282
  onRight={/* @once */ lngp.chainFunctions(props.onRight, lngp.navigableHandleNavigation)}
214
283
  onUp={/* @once */ lngp.chainFunctions(props.onUp, onUp)}
@@ -222,4 +291,12 @@ export function VirtualGrid<T>(props: VirtualGridProps<T>): s.JSX.Element {
222
291
  <List each={slice()}>{props.children}</List>
223
292
  </view>
224
293
  );
294
+
295
+ // `cursor` has an effect of its own: in the spread above, a cursor change
296
+ // (every press) re-ran every prop of the spread.
297
+ s.createRenderEffect(() => {
298
+ viewRef.cursor = cursor();
299
+ });
300
+
301
+ return view;
225
302
  }