From a86d7fc59185b45db55fe8b217d68763fad85194 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:04:27 -0400 Subject: [PATCH 1/8] perf(primitives): reuse the merged Row/Column transition per direction handleNavigation merged transitionLeft/Right/Up/Down into `transition` with a new object (and a `{}` when unset) on every press. The merged objects are now cached by base transition, then by directional transition (WeakMaps), so a press allocates nothing and the node keeps the same `transition` object while the direction and the base do. A new base from the app still gives new merged objects. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4a044c327168e2939d0c357b779fd368db74a1f7) --- src/primitives/utils/handleNavigation.ts | 42 +++++++++++++++++++++--- tests/contract-row-column.test.tsx | 36 ++++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/primitives/utils/handleNavigation.ts b/src/primitives/utils/handleNavigation.ts index 17baca8..3baa084 100644 --- a/src/primitives/utils/handleNavigation.ts +++ b/src/primitives/utils/handleNavigation.ts @@ -129,6 +129,36 @@ type NavWithTransitionCache = lngp.NavigableElement & { _navLastMerged?: object; }; +type TransitionObject = Exclude< + lng.ElementNode['transition'], + boolean | undefined +>; + +// The base when `transition` is not an object (unset, true or false). +const noTransition = {}; +// Merged transitions by base transition, then by directional transition. +// A press reuses the merged object for its direction instead of allocating +// one, so the node's `transition` (and the settings object animateProp gets) +// stays the same while the direction and the base do. +const mergedTransitions = new WeakMap< + object, + WeakMap +>(); + +function mergedTransition(directional: object, base: object): TransitionObject { + let byDirectional = mergedTransitions.get(base); + if (byDirectional === undefined) { + byDirectional = new WeakMap(); + mergedTransitions.set(base, byDirectional); + } + let merged = byDirectional.get(directional); + if (merged === undefined) { + merged = { ...directional, ...base } as TransitionObject; + byDirectional.set(directional, merged); + } + return merged; +} + export function handleNavigation( direction: 'up' | 'right' | 'down' | 'left', ): lng.KeyHandler { @@ -144,10 +174,11 @@ export function handleNavigation( : el.transitionRight; if (directional) { + const transition = el.transition; const current = - typeof el.transition === 'object' && el.transition !== null - ? el.transition - : {}; + typeof transition === 'object' && transition !== null + ? transition + : noTransition; // Re-snapshot the developer-supplied transition whenever el.transition // doesn't match our last merge — that means it was set externally @@ -156,7 +187,10 @@ export function handleNavigation( el._navBaseTransition = current; } - const merged = { ...(directional as object), ...el._navBaseTransition }; + const merged = mergedTransition( + directional as object, + el._navBaseTransition!, + ); el.transition = merged; el._navLastMerged = merged; } diff --git a/tests/contract-row-column.test.tsx b/tests/contract-row-column.test.tsx index 2e8bdf9..4921117 100644 --- a/tests/contract-row-column.test.tsx +++ b/tests/contract-row-column.test.tsx @@ -897,6 +897,42 @@ v.describe('Row and Column: transitions and throttleInput', () => { }, ); + v.it( + 'the merged transition is one object per direction and base `transition`, not one per press (1.7)', + async () => { + let row!: lng.ElementNode; + const [base, setBase] = s.createSignal(); + dispose = await mount(() => ( + + + {items(6)} + + + )); + await press('ArrowRight'); + const right = row.transition; + await press('ArrowRight'); + v.expect(row.transition).toBe(right); + await press('ArrowLeft'); + const left = row.transition; + v.expect(left).not.toBe(right); + await press('ArrowLeft', 'ArrowRight'); + v.expect(row.transition).toBe(right); + + // A new base transition from the app gives new merged objects, again + // one per direction. + setBase({ alpha: true }); + await press('ArrowRight'); + const right2 = row.transition; + v.expect(right2).toEqual({ + x: { duration: 180, easing: 'cubic-bezier(0.2, 0, 0, 1)' }, + alpha: true, + }); + await press('ArrowRight'); + v.expect(row.transition).toBe(right2); + }, + ); + v.it( 'throttleInput on a Row: the same key within the window is dropped; another key is not', async () => { From 57ae724c9fbc527eb71541b1371d0ee94db9341c Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:18:29 -0400 Subject: [PATCH 2/8] fix(primitives): Rows without a transition keep their own merged transition The merged-transition cache keyed every Row without a `transition` object by one shared sentinel, so those Rows shared one merged object per direction and an app mutating `row.transition` in place would have changed it for all of them. Without a base object the cache is now keyed by the element. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit d911c85833067eef3b2d79a4fe00b1f3c9861fee) --- src/primitives/utils/handleNavigation.ts | 23 +++++++++++++++-------- tests/contract-row-column.test.tsx | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/primitives/utils/handleNavigation.ts b/src/primitives/utils/handleNavigation.ts index 3baa084..4213c65 100644 --- a/src/primitives/utils/handleNavigation.ts +++ b/src/primitives/utils/handleNavigation.ts @@ -136,20 +136,25 @@ type TransitionObject = Exclude< // The base when `transition` is not an object (unset, true or false). const noTransition = {}; -// Merged transitions by base transition, then by directional transition. -// A press reuses the merged object for its direction instead of allocating -// one, so the node's `transition` (and the settings object animateProp gets) -// stays the same while the direction and the base do. +// Merged transitions by base transition (by element when there is no base +// object, so Rows without a `transition` do not share one), then by +// directional transition. A press reuses the merged object for its direction +// instead of allocating one, so the node's `transition` (and the settings +// object animateProp gets) stays the same while the direction and the base do. const mergedTransitions = new WeakMap< object, WeakMap >(); -function mergedTransition(directional: object, base: object): TransitionObject { - let byDirectional = mergedTransitions.get(base); +function mergedTransition( + directional: object, + base: object, + key: object, +): TransitionObject { + let byDirectional = mergedTransitions.get(key); if (byDirectional === undefined) { byDirectional = new WeakMap(); - mergedTransitions.set(base, byDirectional); + mergedTransitions.set(key, byDirectional); } let merged = byDirectional.get(directional); if (merged === undefined) { @@ -187,9 +192,11 @@ export function handleNavigation( el._navBaseTransition = current; } + const base = el._navBaseTransition!; const merged = mergedTransition( directional as object, - el._navBaseTransition!, + base, + base === noTransition ? el : base, ); el.transition = merged; el._navLastMerged = merged; diff --git a/tests/contract-row-column.test.tsx b/tests/contract-row-column.test.tsx index 4921117..959ef91 100644 --- a/tests/contract-row-column.test.tsx +++ b/tests/contract-row-column.test.tsx @@ -933,6 +933,25 @@ v.describe('Row and Column: transitions and throttleInput', () => { }, ); + v.it( + 'Rows without a `transition` do not share a merged transition object (1.7)', + async () => { + let r0!: lng.ElementNode; + let r1!: lng.ElementNode; + dispose = await mount(() => ( + + + {items(3)} + {items(3)} + + + )); + await press('ArrowRight', 'ArrowDown', 'ArrowRight'); + v.expect(r0.transition).toEqual(r1.transition); + v.expect(r0.transition).not.toBe(r1.transition); + }, + ); + v.it( 'throttleInput on a Row: the same key within the window is dropped; another key is not', async () => { From b50d552acf0a2a16e619da3487fe983872877b8b Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:59:17 -0400 Subject: [PATCH 3/8] fix(primitives): cache Row/Column merged transitions per element Rows given the same base `transition` object shared the merged objects, so an in-place edit of one Row's `transition` reached the others. The cache is now per element, rebuilt when the element's base `transition` object changes. An in-place edit of the base after a press in that direction is not picked up (it was re-spread on every press): assign a new object. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 058070aa03263782a363d964f7982679ff70d9b6) --- src/primitives/utils/handleNavigation.ts | 55 +++++++++++------------- tests/contract-row-column.test.tsx | 28 ++++++++++++ 2 files changed, 52 insertions(+), 31 deletions(-) diff --git a/src/primitives/utils/handleNavigation.ts b/src/primitives/utils/handleNavigation.ts index 4213c65..8ae63f1 100644 --- a/src/primitives/utils/handleNavigation.ts +++ b/src/primitives/utils/handleNavigation.ts @@ -136,34 +136,18 @@ type TransitionObject = Exclude< // The base when `transition` is not an object (unset, true or false). const noTransition = {}; -// Merged transitions by base transition (by element when there is no base -// object, so Rows without a `transition` do not share one), then by -// directional transition. A press reuses the merged object for its direction -// instead of allocating one, so the node's `transition` (and the settings -// object animateProp gets) stays the same while the direction and the base do. +// Merged transitions per element, then per directional transition. A press +// reuses the merged object for its direction instead of allocating one, so +// the node's `transition` (and the settings object animateProp gets) stays +// the same while the direction and the base do. Per element, so an in-place +// edit of one Row's `transition` never reaches another Row; the cache is +// rebuilt when the element's base `transition` object changes (an in-place +// edit of the same base object is not picked up: assign a new object). const mergedTransitions = new WeakMap< object, WeakMap >(); -function mergedTransition( - directional: object, - base: object, - key: object, -): TransitionObject { - let byDirectional = mergedTransitions.get(key); - if (byDirectional === undefined) { - byDirectional = new WeakMap(); - mergedTransitions.set(key, byDirectional); - } - let merged = byDirectional.get(directional); - if (merged === undefined) { - merged = { ...directional, ...base } as TransitionObject; - byDirectional.set(directional, merged); - } - return merged; -} - export function handleNavigation( direction: 'up' | 'right' | 'down' | 'left', ): lng.KeyHandler { @@ -187,17 +171,26 @@ export function handleNavigation( // Re-snapshot the developer-supplied transition whenever el.transition // doesn't match our last merge — that means it was set externally - // (initial render or a reactive update), not by this handler. - if (current !== el._navLastMerged) { + // (initial render or a reactive update), not by this handler — and it + // is not the base the cache was built from. + let byDirectional = mergedTransitions.get(el); + if ( + current !== el._navLastMerged && + (current !== el._navBaseTransition || byDirectional === undefined) + ) { el._navBaseTransition = current; + byDirectional = new WeakMap(); + mergedTransitions.set(el, byDirectional); } - const base = el._navBaseTransition!; - const merged = mergedTransition( - directional as object, - base, - base === noTransition ? el : base, - ); + let merged = byDirectional!.get(directional as object); + if (merged === undefined) { + merged = { + ...(directional as object), + ...el._navBaseTransition, + } as TransitionObject; + byDirectional!.set(directional as object, merged); + } el.transition = merged; el._navLastMerged = merged; } diff --git a/tests/contract-row-column.test.tsx b/tests/contract-row-column.test.tsx index 959ef91..e85f479 100644 --- a/tests/contract-row-column.test.tsx +++ b/tests/contract-row-column.test.tsx @@ -952,6 +952,34 @@ v.describe('Row and Column: transitions and throttleInput', () => { }, ); + v.it( + 'Rows given the same `transition` object do not share a merged transition object (1.7)', + async () => { + let r0!: lng.ElementNode; + let r1!: lng.ElementNode; + const shared = { alpha: true }; + dispose = await mount(() => ( + + + + {items(3)} + + + {items(3)} + + + + )); + await press('ArrowRight', 'ArrowDown', 'ArrowRight'); + v.expect(r0.transition).toEqual({ + x: { duration: 180, easing: 'cubic-bezier(0.2, 0, 0, 1)' }, + alpha: true, + }); + v.expect(r0.transition).toEqual(r1.transition); + v.expect(r0.transition).not.toBe(r1.transition); + }, + ); + v.it( 'throttleInput on a Row: the same key within the window is dropped; another key is not', async () => { From 0f4bc9dfd263050b6c506900ff0918e0b9f95cfc Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:04:37 -0400 Subject: [PATCH 4/8] perf(primitives): create Grid's key and focus handlers once Grid built onUp/onDown/onLeft/onRight/onFocus inline in its spread, which re-runs on every vertical move (for `y`), so each move made five new functions and wrote them to the node. They are now created once; each reads the app's handler of the same name when called, so a reactive one still runs first and still stops the Grid's move by returning true. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 1f25922c205743b0f2e5ebcce380d24363d1aa7f) --- src/primitives/Grid.tsx | 30 +++++++++++++++++----- tests/contract-grid.test.tsx | 50 ++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/src/primitives/Grid.tsx b/src/primitives/Grid.tsx index 7ebe289..bf4ef1d 100644 --- a/src/primitives/Grid.tsx +++ b/src/primitives/Grid.tsx @@ -1,6 +1,6 @@ import { createSignal, createMemo, createEffect, JSX, untrack, Index } from "solid-js"; import { type NodeProps, ElementNode, NewOmit, hasFocus } from "@solidtv/solid"; -import { chainFunctions, chainRefs } from "./utils/chainFunctions.js"; +import { chainRefs } from "./utils/chainFunctions.js"; export interface GridItemProps { item: T @@ -118,6 +118,24 @@ export function Grid(props: GridProps): JSX.Element { props.scroll === "none" ? props.y ?? 0 : -Math.floor(focusedIndex() / columns()) * totalHeight() + (props.y || 0) ); + // Created once. The spread below re-runs on every vertical move (for `y`), + // and handlers built inline in it were new functions each time. Each runs + // the app's handler of the same name first (read when called, so a reactive + // one still applies) and stops if it returns true. + type HandlerName = "onUp" | "onDown" | "onLeft" | "onRight" | "onFocus"; + function chainProp(name: HandlerName, own: () => boolean) { + return function (this: ElementNode, a: unknown, b: unknown, c: unknown, d?: unknown) { + const user = props[name] as ((...args: unknown[]) => unknown) | undefined; + if (typeof user === "function" && user.call(this, a, b, c, d) === true) return true; + return own(); + }; + } + const onUp = chainProp("onUp", () => moveFocus(-columns())); + const onDown = chainProp("onDown", () => moveFocus(columns())); + const onLeft = chainProp("onLeft", () => handleHorizontalFocus(-1)); + const onRight = chainProp("onRight", () => handleHorizontalFocus(1)); + const onFocus = chainProp("onFocus", () => handleHorizontalFocus(0)); + let gridRef!: ElementNode; return ( (props: GridProps): JSX.Element { transition={/* @once */ { y: true }} height={totalHeight() * rows()} scrollToIndex={/* @once */ scrollToIndex} - onUp={chainFunctions(props.onUp, () => moveFocus(-columns()))} - onDown={chainFunctions(props.onDown, () => moveFocus(columns()))} - onLeft={chainFunctions(props.onLeft, () => handleHorizontalFocus(-1))} - onRight={chainFunctions(props.onRight, () => handleHorizontalFocus(1))} - onFocus={chainFunctions(props.onFocus, () => handleHorizontalFocus(0))} + onUp={/* @once */ onUp} + onDown={/* @once */ onDown} + onLeft={/* @once */ onLeft} + onRight={/* @once */ onRight} + onFocus={/* @once */ onFocus} strictBounds={false} y={scrollY()} > diff --git a/tests/contract-grid.test.tsx b/tests/contract-grid.test.tsx index 7b152a3..ec5da65 100644 --- a/tests/contract-grid.test.tsx +++ b/tests/contract-grid.test.tsx @@ -240,6 +240,56 @@ v.describe('Grid', () => { }, ); + v.it( + 'the key and focus handlers are created once, not again on every vertical move (1.7); a reactive user handler still runs first', + async () => { + let grid!: lng.ElementNode; + const calls: string[] = []; + const [onDown, setOnDown] = s.createSignal<() => boolean>(() => { + calls.push('first'); + return false; + }); + dispose = await mount(() => ( + + + {Cell} + + + )); + const names = ['onUp', 'onDown', 'onLeft', 'onRight', 'onFocus']; + const handlers = names.map((n) => grid[n]); + await press('ArrowDown', 'ArrowDown', 'ArrowUp'); + v.expect(names.map((n, i) => grid[n] === handlers[i])).toEqual([ + true, + true, + true, + true, + true, + ]); + v.expect([focusedId(), grid.y]).toEqual(['g3', -50]); + v.expect(calls).toEqual(['first', 'first']); + + // A new user handler replaces the old one; returning true stops the + // Grid's own move. + setOnDown(() => () => { + calls.push('second'); + return true; + }); + await flush(); + await press('ArrowDown'); + v.expect(calls).toEqual(['first', 'first', 'second']); + v.expect(focusedId()).toBe('g3'); + }, + ); + v.it('scroll="none": y does not follow the focused row', async () => { let grid!: lng.ElementNode; dispose = await mount(() => ( From 805c5011b7c940c3c097935fde097d35f26df2d5 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:20:20 -0400 Subject: [PATCH 5/8] perf(primitives): Grid writes y from its own effect `y={scrollY()}` sat in Grid's spread, so every vertical move (a focusedIndex change) re-ran every prop of the spread. The spread now takes the initial y once and an effect of its own writes the changes. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 728fcb5759243295390fe2d6c2e100043e78fbc0) --- src/primitives/Grid.tsx | 14 +++++++++++--- tests/contract-grid.test.tsx | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/primitives/Grid.tsx b/src/primitives/Grid.tsx index bf4ef1d..72b8eb5 100644 --- a/src/primitives/Grid.tsx +++ b/src/primitives/Grid.tsx @@ -1,4 +1,4 @@ -import { createSignal, createMemo, createEffect, JSX, untrack, Index } from "solid-js"; +import { createSignal, createMemo, createEffect, createRenderEffect, JSX, untrack, Index } from "solid-js"; import { type NodeProps, ElementNode, NewOmit, hasFocus } from "@solidtv/solid"; import { chainRefs } from "./utils/chainFunctions.js"; @@ -137,7 +137,7 @@ export function Grid(props: GridProps): JSX.Element { const onFocus = chainProp("onFocus", () => handleHorizontalFocus(0)); let gridRef!: ElementNode; - return ( + const view = ( gridRef = el, props.ref)} @@ -150,7 +150,7 @@ export function Grid(props: GridProps): JSX.Element { onRight={/* @once */ onRight} onFocus={/* @once */ onFocus} strictBounds={false} - y={scrollY()} + y={/* @once */ untrack(scrollY)} > {(item, index) => ( @@ -166,4 +166,12 @@ export function Grid(props: GridProps): JSX.Element { ); + + // `y` has an effect of its own: in the spread above, every vertical move + // (a focusedIndex change) re-ran every prop of the spread. + createRenderEffect(() => { + gridRef.y = scrollY(); + }); + + return view; }; diff --git a/tests/contract-grid.test.tsx b/tests/contract-grid.test.tsx index ec5da65..d3766e8 100644 --- a/tests/contract-grid.test.tsx +++ b/tests/contract-grid.test.tsx @@ -290,6 +290,40 @@ v.describe('Grid', () => { }, ); + v.it( + 'a vertical move re-runs only the props that depend on it: 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(() => ( + + + {Cell} + + + )); + const before = reads; + await press('ArrowDown', 'ArrowDown', 'ArrowUp'); + v.expect([focusedId(), grid.y]).toEqual(['g3', -40]); + // It was read again on every vertical move: `y` was in the spread. + v.expect(reads).toBe(before); + }, + ); + v.it('scroll="none": y does not follow the focused row', async () => { let grid!: lng.ElementNode; dispose = await mount(() => ( From 631a82c1bc815087e70bf0517d9ddb9986e95017 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:06:53 -0400 Subject: [PATCH 6/8] perf(states): no States construction per remove; fix B2 - static get [Symbol.species]() returns Array: Array methods (slice, splice, filter, ...) build a plain Array instead of running the States constructor with a length as its callback (MIGRATION 2.5). - remove() shifts in place instead of splice; so does merge(). - B2: remove('focus') removes '$focus', as has('focus') matches it, so toggle('focus') while '$focus' is on turns it off. - onChange is a declared field assigned in the constructor (no class field emit), and the object form no longer uses Object.entries (Chrome 47 floor). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 14e84c763efb60ddf00d01039600e27dbaba3057) --- src/core/states.ts | 38 ++++++++++++++++++++++++++-------- tests/contract-states.test.tsx | 36 ++++++++++++++++++++++---------- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/src/core/states.ts b/src/core/states.ts index f2be9fe..d37438a 100644 --- a/src/core/states.ts +++ b/src/core/states.ts @@ -6,7 +6,15 @@ export type NodeStates = | Record; export default class States extends Array { - private onChange: () => void; + // Assigned in the constructor, not a class field (no field emit). + declare private onChange: () => void; + + // Array methods (slice, splice, filter, …) build a plain Array, not a + // States: building a States ran this constructor with a length as its + // callback, once per remove(). + static override get [Symbol.species]() { + return Array; + } constructor(callback: () => void, initialState: NodeStates = {}) { if (isArray(initialState)) { @@ -20,11 +28,10 @@ export default class States extends Array { } else if (isString(initialState)) { super(initialState); // Assert as DollarString } else { - super( - ...Object.entries(initialState) - .filter(([_key, value]) => value) - .map(([key]) => key as DollarString), // Assert as DollarString - ); + super(); + for (const key in initialState) { + if (initialState[key as DollarString]) this.push(key as DollarString); + } } this.onChange = callback; @@ -97,7 +104,7 @@ export default class States extends Array { } else { const stateIndexToRemove = this.indexOf(state as DollarString); if (stateIndexToRemove >= 0) { - this.splice(stateIndexToRemove, 1); + this.removeAt(stateIndexToRemove); } } } @@ -106,10 +113,23 @@ export default class States extends Array { } remove(state: DollarString) { - const stateIndexToRemove = this.indexOf(state); + let stateIndexToRemove = this.indexOf(state); + // remove('focus') removes '$focus', as has('focus') matches it (B2). + if (stateIndexToRemove < 0 && state.charCodeAt(0) !== 36) { + stateIndexToRemove = this.indexOf(('$' + state) as DollarString); + } if (stateIndexToRemove >= 0) { - this.splice(stateIndexToRemove, 1); + this.removeAt(stateIndexToRemove); this.onChange(); } } + + // Shift in place: splice would allocate the array of removed entries. + private removeAt(index: number) { + const last = this.length - 1; + for (let i = index; i < last; i++) { + this[i] = this[i + 1]!; + } + this.length = last; + } } diff --git a/tests/contract-states.test.tsx b/tests/contract-states.test.tsx index 7780aa0..5c31a82 100644 --- a/tests/contract-states.test.tsx +++ b/tests/contract-states.test.tsx @@ -282,17 +282,17 @@ v.describe('contract: state keys with and without $', () => { }, ); - v.it('remove() is strict: remove("focus") leaves "$focus" on', () => { - // Pinned as is: `has("focus")` is true here, yet `remove("focus")` does - // not remove "$focus". + v.it('remove("focus") removes "$focus", as has("focus") matches it', () => { + // B2 (fixed in 1.7): before, remove() was strict: `has("focus")` was true + // here, yet `remove("focus")` left "$focus" on. let node!: lng.ElementNode; const dispose = renderer.render(() => ( )); node.states.add('$focus'); node.states.remove(bare('focus')); - v.expect(statesOf(node)).toEqual(['$focus']); - v.expect(node.color).toBe(BLUE); + v.expect(statesOf(node)).toEqual([]); + v.expect(node.color).toBe(RED); dispose(); }); @@ -329,12 +329,11 @@ v.describe('contract: state keys with and without $', () => { }, ); - // BUG: toggle("focus") while "$focus" is on does nothing. toggle() asks - // has("focus") (true: has() accepts the bare name), then calls - // remove("focus"), which is strict and finds nothing to remove - // (src/core/states.ts:60-61 in toggle, :94 in remove). A toggle must - // change the state. - v.it.skip('toggle("focus") while "$focus" is on turns it off', () => { + // B2 (fixed in 1.7): toggle("focus") while "$focus" was on did nothing. + // toggle() asked has("focus") (true: has() accepts the bare name), then + // called remove("focus"), which was strict and found nothing to remove. A + // toggle must change the state. + v.it('toggle("focus") while "$focus" is on turns it off', () => { let node!: lng.ElementNode; const dispose = renderer.render(() => ( @@ -345,6 +344,21 @@ v.describe('contract: state keys with and without $', () => { v.expect(node.color).toBe(RED); dispose(); }); + + // Changed in 1.7 (MIGRATION 2.5): States no longer builds a States for + // Array methods' results (one was built per remove()). + v.it('Array methods on states return plain arrays', () => { + let node!: lng.ElementNode; + const dispose = renderer.render(() => ( + + )); + const copy = node.states.slice(); + v.expect(copy).toEqual(['$a', '$b']); + v.expect(copy.constructor).toBe(Array); + v.expect(node.states.filter(() => true).constructor).toBe(Array); + v.expect(node.states).toBeInstanceOf(Array); + dispose(); + }); }); v.describe('contract: $state blocks inside style apply and undo', () => { From ddbebdea82a049b6f6d26cd491f610d39ec0cf96 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:07:23 -0400 Subject: [PATCH 7/8] perf(focus): O(depth) focus-path diff; one reactive flush per focus change - updateFocusPath stamps each node of the new path with a generation; a node of the previous path without the stamp lost focus (no indexOf diff). The path is built in a reused buffer and published as a copy, since focusPath readers keep the array. A focus callback that calls setActiveElementCore re-entrantly gets its own array, and the outer change falls back to the scan, as before (pinned by a new test). - 5.1: setActiveElementCore runs the focus phase (callbacks, setFocusPath, Config.setActiveElement) in one batch: callback order is unchanged; effects triggered by their signal writes run once, after the last callback (new contract test). - No closure per focus change: the batch, and Config.setActiveElement as useFocusManager installs it, read module variables. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 560717fd55dbc0abd919e96126ec9a8ca22589da) --- src/core/focusManager.ts | 105 ++++++++++++++++++++++++++-------- tests/contract-focus.test.tsx | 99 ++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+), 25 deletions(-) diff --git a/src/core/focusManager.ts b/src/core/focusManager.ts index 91f0dc7..dd98aa9 100644 --- a/src/core/focusManager.ts +++ b/src/core/focusManager.ts @@ -1,4 +1,10 @@ -import { createSignal, getOwner, onCleanup, runWithOwner } from 'solid-js'; +import { + batch, + createSignal, + getOwner, + onCleanup, + runWithOwner, +} from 'solid-js'; import { Config, isDev } from './config.js'; import { IRendererNode } from './dom-renderer/domRendererTypes.js'; export type * from './focusKeyTypes.js'; @@ -10,8 +16,6 @@ import { setActiveElement as setActiveElementSignal, } from './activeElement.js'; -let _signalWrapper: (cb: () => void) => void = (cb) => cb(); - type KeyMapEntries = Record; const keyMapEntries: KeyMapEntries = { @@ -232,6 +236,23 @@ export const printFocusHistory = (count: number): void => { export const setActiveElementCore = (elm: ElementNode) => { const prev = activeElement(); if (elm === prev) return; + _focusTarget = elm; + _focusPrev = prev; + // The whole focus phase runs in one batch (5.1): the callbacks keep their + // order, and the effects their signal writes trigger, like those of + // focusPath and the active element, run once, after the last of them. + batch(applyFocus); +}; + +// The focus change setActiveElementCore hands to applyFocus, so the batch +// takes no closure. applyFocus reads both on entry. +let _focusTarget: ElementNode | undefined; +let _focusPrev: ElementNode | undefined; + +const applyFocus = (): void => { + const elm = _focusTarget!; + const prev = _focusPrev; + _focusTarget = _focusPrev = undefined; updateFocusPath(elm, prev); recordFocusHistory(elm, prev); // Reset key attribution so programmatic focus changes show '—' for key fields @@ -244,21 +265,45 @@ export const setActiveElementCore = (elm: ElementNode) => { export const [focusPath, setFocusPath] = createSignal([]); +// Each focus change takes a new generation and stamps it on every node of the +// new path; a node of the previous path without that stamp lost focus. O(depth), +// no membership scan. +let focusGen = 0; +// The new path is built here, leaf first, then published as a copy: the +// signal's value must be a fresh array per change, since readers keep it. +const pathBuffer: ElementNode[] = []; +// True while updateFocusPath runs. A focus callback that calls +// setActiveElementCore re-enters it: the inner change builds its own array, +// and the outer one, whose stamps it overwrote, falls back to a scan. +let updatingPath = false; + const updateFocusPath = ( currentFocusedElm: ElementNode, prevFocusedElm: ElementNode | undefined, ) => { + const nested = updatingPath; + updatingPath = true; + try { + buildFocusPath(currentFocusedElm, prevFocusedElm, nested ? [] : pathBuffer); + } finally { + updatingPath = nested; + } +}; + +const buildFocusPath = ( + currentFocusedElm: ElementNode, + prevFocusedElm: ElementNode | undefined, + fp: ElementNode[], +) => { + const focusKey = Config.focusStateKey; + const gen = ++focusGen; + let length = 0; let current: ElementNode | undefined = currentFocusedElm; - // fp escapes through the focusPath signal, so it must be a fresh array; the - // membership test below runs on paths of a handful of elements every single - // keypress, where a linear scan beats allocating and hashing a Set. - const fp: ElementNode[] = []; while (current) { - if ( - !current.states.has(Config.focusStateKey) || - current === currentFocusedElm - ) { - current.states.add(Config.focusStateKey); + current._focusGen = gen; + const states = current.states; + if (!states.has(focusKey) || current === currentFocusedElm) { + states.add(focusKey); current.onFocus?.call( current, currentFocusedElm, @@ -273,15 +318,17 @@ const updateFocusPath = ( current, ); } - fp.push(current); + fp[length++] = current; current = current.parent; } + fp.length = length; const prevFp = focusPath(); for (let i = 0; i < prevFp.length; i++) { const elm = prevFp[i]!; - if (fp.indexOf(elm) === -1) { - elm.states.remove(Config.focusStateKey); + // focusGen moves on only when a callback changed focus re-entrantly. + if (focusGen === gen ? elm._focusGen !== gen : fp.indexOf(elm) === -1) { + elm.states.remove(focusKey); elm.onBlur?.call(elm, currentFocusedElm, prevFocusedElm!, elm); elm.onFocusChanged?.call( elm, @@ -293,11 +340,12 @@ const updateFocusPath = ( } } + const newFp = fp.slice(); if (Config.focusDebug) { - addFocusDebug(prevFp, fp); + addFocusDebug(prevFp, newFp); } - _signalWrapper(() => setFocusPath(fp)); + setFocusPath(newFp); }; let lastGlobalKeyPressTime = 0; @@ -670,6 +718,14 @@ export interface KeyEventTarget { ): void; } +// The element Config.setActiveElement (as useFocusManager sets it) hands to +// publishActiveElement, so a focus change allocates no closure. +let _activeToPublish: ElementNode | undefined; + +const publishActiveElement = (): void => { + setActiveElementSignal(_activeToPublish); +}; + // The key event being dispatched, handed to dispatchKeyDown/dispatchKeyUp so // that a key event allocates no closure. Each takes it on entry, so a handler // that raises another key event cannot disturb the one in progress. @@ -718,18 +774,17 @@ export const useFocusManager = ( // can run inside it — needed for programmatic .setFocus(), post-mutation // focus, and any effect subscribers that rely on onCleanup. const owner = getOwner(); - const ownerContext = (cb: () => void) => { - runWithOwner(owner, cb); - }; - _signalWrapper = ownerContext; // Drive the active-element signal inside this owner so its effect subscribers // have a parent for cleanup. Consumers replacing the focus manager can wire // Config.setActiveElement themselves instead of calling useFocusManager. - Config.setActiveElement = (elm) => - ownerContext(() => setActiveElementSignal(elm)); + Config.setActiveElement = (elm) => { + _activeToPublish = elm; + runWithOwner(owner, publishActiveElement); + _activeToPublish = undefined; + }; - // One listener per event type, run inside the owner like ownerContext, - // with no closure per event. + // One listener per event type, run inside the owner like the active-element + // signal above, with no closure per event. const keyPressHandler = (event: KeyEventLike) => { _dispatchEvent = event; runWithOwner(owner, dispatchKeyDown); diff --git a/tests/contract-focus.test.tsx b/tests/contract-focus.test.tsx index 64a0872..49627ae 100644 --- a/tests/contract-focus.test.tsx +++ b/tests/contract-focus.test.tsx @@ -10,6 +10,7 @@ import { type ElementNode, activeElement as coreActiveElement, setActiveElement, + setActiveElementCore, } from '@solidtv/solid'; import { activeElement, focusPath, Row } from '@solidtv/solid/primitives'; import { flush, mount, recorder } from './contract-focus-helpers.js'; @@ -249,6 +250,104 @@ v.describe('contract: onFocus / onBlur / onFocusChanged order', () => { dispose(); }, ); + + // Changed in 1.7 (decision 5.1, MIGRATION 2.1): the focus phase runs in one + // batch. Before, each signal write in a focus callback flushed on its own, + // so this effect ran twice, in between the callbacks. + v.it( + 'signals written in onFocus and onFocusChanged drive one effect run per focus change, after the last callback', + async () => { + const [a, setA] = createSignal(0); + const [b, setB] = createSignal(0); + const log: string[] = []; + const n = {} as Record<'A' | 'B', ElementNode>; + const { dispose } = await mount(() => { + createEffect( + on([a, b], ([x, y]) => log.push(`effect ${x},${y}`), { + defer: true, + }), + ); + return ( + + log.push('A.onBlur')} + /> + { + log.push('B.onFocus'); + setA(a() + 1); + }} + onFocusChanged={() => { + log.push('B.onFocusChanged'); + setB(b() + 1); + }} + /> + + ); + }); + log.length = 0; + await focus(n.B); + v.expect(log).toEqual([ + 'B.onFocus', + 'B.onFocusChanged', + 'A.onBlur', + 'effect 1,1', + ]); + dispose(); + }, + ); + + v.it( + "setActiveElementCore called from an ancestor's onFocus: the inner change runs whole, then the outer one finishes and wins (current behaviour)", + async () => { + const { log, n, dispose } = await mountTree(); + await focus(n.C); + log.clear(); + let nested = false; + n.P1.onFocus = function () { + log.calls.push({ + node: 'P1', + owner: 'P1', + handler: 'onFocus', + self: this, + args: [], + }); + if (!nested) { + nested = true; + setActiveElementCore(n.A); + } + }; + await focus(n.B); + v.expect(log.order()).toEqual([ + 'B.onFocus', + 'B.onFocusChanged(true)', + 'P1.onFocus', + 'A.onFocus', + 'A.onFocusChanged(true)', + 'C.onBlur', + 'C.onFocusChanged(false)', + 'P2.onBlur', + 'P2.onFocusChanged(false)', + 'P1.onFocusChanged(true)', + 'A.onBlur', + 'A.onFocusChanged(false)', + ]); + v.expect(activeElement()).toBe(n.B); + v.expect(focusPath()).toEqual([n.B, n.P1, n.G, renderer.rootNode]); + for (const id of ['B', 'P1', 'G'] as const) { + v.expect(hasFocusState(n[id]), id).toBe(true); + } + for (const id of ['A', 'C', 'P2'] as const) { + v.expect(hasFocusState(n[id]), id).toBe(false); + } + dispose(); + }, + ); }); v.describe('contract: focus state', () => { From 7b48626a8d9f12b779f9f5f93f0ab37a345d2c77 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sun, 4 Oct 2026 01:32:12 -0400 Subject: [PATCH 8/8] perf(focus): setActiveElementCore has no local, so terser inlines it without an IIFE Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 3ebfa37f4221ef7ccf06ace60d369e99672c8cff) --- src/core/focusManager.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/core/focusManager.ts b/src/core/focusManager.ts index dd98aa9..46fd191 100644 --- a/src/core/focusManager.ts +++ b/src/core/focusManager.ts @@ -234,10 +234,14 @@ export const printFocusHistory = (count: number): void => { * through the focus-path logic. */ export const setActiveElementCore = (elm: ElementNode) => { - const prev = activeElement(); - if (elm === prev) return; + // No local: terser inlines this single-use function into its caller, and a + // block-scoped local there would make it an IIFE (a closure per change). + _focusPrev = activeElement(); + if (elm === _focusPrev) { + _focusPrev = undefined; + return; + } _focusTarget = elm; - _focusPrev = prev; // The whole focus phase runs in one batch (5.1): the callbacks keep their // order, and the effects their signal writes trigger, like those of // focusPath and the active element, run once, after the last of them.