Skip to content
Merged
113 changes: 86 additions & 27 deletions src/core/focusManager.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -10,8 +16,6 @@ import {
setActiveElement as setActiveElementSignal,
} from './activeElement.js';

let _signalWrapper: (cb: () => void) => void = (cb) => cb();

type KeyMapEntries = Record<KeyNameOrKeyCode, string>;

const keyMapEntries: KeyMapEntries = {
Expand Down Expand Up @@ -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
Expand All @@ -244,21 +269,45 @@ export const setActiveElementCore = (elm: ElementNode) => {

export const [focusPath, setFocusPath] = createSignal<ElementNode[]>([]);

// 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,
Expand All @@ -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,
Expand All @@ -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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down
38 changes: 29 additions & 9 deletions src/core/states.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,15 @@ export type NodeStates =
| Record<DollarString, boolean | undefined>;

export default class States extends Array<DollarString> {
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)) {
Expand All @@ -20,11 +28,10 @@ export default class States extends Array<DollarString> {
} 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;
Expand Down Expand Up @@ -97,7 +104,7 @@ export default class States extends Array<DollarString> {
} else {
const stateIndexToRemove = this.indexOf(state as DollarString);
if (stateIndexToRemove >= 0) {
this.splice(stateIndexToRemove, 1);
this.removeAt(stateIndexToRemove);
}
}
}
Expand All @@ -106,10 +113,23 @@ export default class States extends Array<DollarString> {
}

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;
}
}
44 changes: 35 additions & 9 deletions src/primitives/Grid.tsx
Original file line number Diff line number Diff line change
@@ -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<T> {
item: T
Expand Down Expand Up @@ -118,21 +118,39 @@ export function Grid<T>(props: GridProps<T>): 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 = (
<view
{...props}
ref={chainRefs(el => 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)}
>
<Index each={props.items}>
{(item, index) => (
Expand All @@ -148,4 +166,12 @@ export function Grid<T>(props: GridProps<T>): JSX.Element {
</Index>
</view>
);

// `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;
};
46 changes: 40 additions & 6 deletions src/primitives/utils/handleNavigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<object, TransitionObject>
>();

export function handleNavigation(
direction: 'up' | 'right' | 'down' | 'left',
): lng.KeyHandler {
Expand All @@ -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;
}
Expand Down
Loading
Loading