diff --git a/src/core/focusManager.ts b/src/core/focusManager.ts index 91f0dc7..46fd191 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 = { @@ -230,8 +234,29 @@ 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; + // 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 +269,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 +322,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 +344,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 +722,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 +778,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/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/src/primitives/Grid.tsx b/src/primitives/Grid.tsx index 7ebe289..72b8eb5 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 { createSignal, createMemo, createEffect, createRenderEffect, 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,21 +118,39 @@ 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 ( + const view = ( gridRef = el, props.ref)} 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()} + y={/* @once */ untrack(scrollY)} > {(item, index) => ( @@ -148,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/src/primitives/utils/handleNavigation.ts b/src/primitives/utils/handleNavigation.ts index 17baca8..8ae63f1 100644 --- a/src/primitives/utils/handleNavigation.ts +++ b/src/primitives/utils/handleNavigation.ts @@ -129,6 +129,25 @@ 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 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 +>(); + export function handleNavigation( direction: 'up' | 'right' | 'down' | 'left', ): lng.KeyHandler { @@ -144,19 +163,34 @@ 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 - // (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 merged = { ...(directional as object), ...el._navBaseTransition }; + 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-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', () => { diff --git a/tests/contract-grid.test.tsx b/tests/contract-grid.test.tsx index 7b152a3..d3766e8 100644 --- a/tests/contract-grid.test.tsx +++ b/tests/contract-grid.test.tsx @@ -240,6 +240,90 @@ 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( + '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(() => ( diff --git a/tests/contract-row-column.test.tsx b/tests/contract-row-column.test.tsx index 2e8bdf9..e85f479 100644 --- a/tests/contract-row-column.test.tsx +++ b/tests/contract-row-column.test.tsx @@ -897,6 +897,89 @@ 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( + '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( + '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 () => { 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', () => {