@solidtv/solid 1.2.0 → 1.2.2

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 (50) hide show
  1. package/README.md +2 -2
  2. package/dist/src/core/activeElement.d.ts +20 -0
  3. package/dist/src/core/activeElement.js +21 -0
  4. package/dist/src/core/activeElement.js.map +1 -0
  5. package/dist/src/core/config.d.ts +14 -0
  6. package/dist/src/core/config.js +8 -0
  7. package/dist/src/core/config.js.map +1 -1
  8. package/dist/src/core/dom-renderer/domRenderer.d.ts +2 -2
  9. package/dist/src/core/dom-renderer/domRenderer.js +0 -1
  10. package/dist/src/core/dom-renderer/domRenderer.js.map +1 -1
  11. package/dist/src/core/elementNode.js +3 -3
  12. package/dist/src/core/elementNode.js.map +1 -1
  13. package/dist/src/core/focusManager.d.ts +12 -2
  14. package/dist/src/core/focusManager.js +20 -3
  15. package/dist/src/core/focusManager.js.map +1 -1
  16. package/dist/src/core/lightningInit.js +6 -3
  17. package/dist/src/core/lightningInit.js.map +1 -1
  18. package/dist/src/index.d.ts +2 -1
  19. package/dist/src/index.js +2 -1
  20. package/dist/src/index.js.map +1 -1
  21. package/dist/src/primitives/FadeInOut.jsx +1 -2
  22. package/dist/src/primitives/FadeInOut.jsx.map +1 -1
  23. package/dist/src/primitives/Rail.d.ts +27 -0
  24. package/dist/src/primitives/Rail.jsx +322 -0
  25. package/dist/src/primitives/Rail.jsx.map +1 -0
  26. package/dist/src/primitives/index.d.ts +1 -0
  27. package/dist/src/primitives/useFocusManager.d.ts +2 -1
  28. package/dist/src/primitives/useFocusManager.js +2 -1
  29. package/dist/src/primitives/useFocusManager.js.map +1 -1
  30. package/dist/src/primitives/useHold.d.ts +1 -1
  31. package/dist/src/primitives/useHold.js +1 -1
  32. package/dist/src/render.d.ts +6 -0
  33. package/dist/src/render.js +7 -1
  34. package/dist/src/render.js.map +1 -1
  35. package/dist/tsconfig.tsbuildinfo +1 -1
  36. package/docs/AI_CODING_GUIDELINES.md +7 -7
  37. package/package.json +2 -2
  38. package/src/core/activeElement.ts +24 -0
  39. package/src/core/config.ts +16 -0
  40. package/src/core/dom-renderer/domRenderer.ts +0 -1
  41. package/src/core/elementNode.ts +3 -3
  42. package/src/core/focusManager.ts +24 -6
  43. package/src/core/lightningInit.ts +6 -3
  44. package/src/index.ts +2 -1
  45. package/src/primitives/FadeInOut.tsx +2 -2
  46. package/src/primitives/Rail.tsx +401 -0
  47. package/src/primitives/index.ts +1 -0
  48. package/src/primitives/useFocusManager.ts +2 -2
  49. package/src/primitives/useHold.ts +1 -1
  50. package/src/render.ts +7 -1
@@ -6,7 +6,7 @@
6
6
 
7
7
  - **Environment:** TV app development over WebGL (not the DOM). No pointer input; interaction is directional (Up/Down/Left/Right).
8
8
  - **Reactivity:** Uses SolidTV primitives (`createSignal`, `createEffect`, `createMemo`).
9
- - **Primitives:** UI is built using custom components like `<View>`, `<Text>`, `<Row>`, `<Column>`.
9
+ - **Primitives:** UI is built using the intrinsic elements `<view>` and `<text>` (no import needed — they're registered with the renderer) plus layout components like `<Row>` and `<Column>` from `@solidtv/solid/primitives`.
10
10
  - **Patterns:** Always use functional components and modern TypeScript/JSX. Avoid classes.
11
11
  - **Assumption:** Always frame answers within the context of SolidTV + SolidTV TV environment.
12
12
 
@@ -76,7 +76,7 @@
76
76
 
77
77
  ```tsx
78
78
  // Missing dimensions, invalid colors, using styles, directional padding
79
- <View
79
+ <view
80
80
  style={{
81
81
  backgroundColor: 'red',
82
82
  paddingLeft: 20,
@@ -84,8 +84,8 @@
84
84
  display: 'flex',
85
85
  }}
86
86
  >
87
- <Text textColor="white">Hello</Text>
88
- </View>
87
+ <text textColor="white">Hello</text>
88
+ </view>
89
89
  ```
90
90
 
91
91
  **✅ Correct:**
@@ -94,7 +94,7 @@
94
94
  const [focused, setFocused] = createSignal(false);
95
95
 
96
96
  // Uses direct props, hex colors, clear dimensions, and focus tracking
97
- <View
97
+ <view
98
98
  width={400}
99
99
  height={200}
100
100
  color={focused() ? '#ffff00ff' : '#ff0000ff'}
@@ -103,6 +103,6 @@ const [focused, setFocused] = createSignal(false);
103
103
  display="flex"
104
104
  onFocusChanged={setFocused}
105
105
  >
106
- <Text color="#ffffffff">Hello</Text>
107
- </View>;
106
+ <text color="#ffffffff">Hello</text>
107
+ </view>;
108
108
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidtv/solid",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "SolidTV",
5
5
  "type": "module",
6
6
  "exports": {
@@ -109,7 +109,7 @@
109
109
  },
110
110
  "peerDependencies": {
111
111
  "@solidjs/router": "^0.16.1",
112
- "@solidtv/renderer": "^1.2.3",
112
+ "@solidtv/renderer": "^1.3.0",
113
113
  "solid-js": "*"
114
114
  },
115
115
  "peerDependenciesMeta": {},
@@ -0,0 +1,24 @@
1
+ import { createSignal } from 'solid-js';
2
+ import type { ElementNode } from './elementNode.js';
3
+
4
+ /**
5
+ * Generic active-element signal — intentionally decoupled from the focus
6
+ * manager so consumers can drive focus from their own focus-management logic.
7
+ *
8
+ * `setActiveElement` is the *raw* signal setter: it only updates the reactive
9
+ * value. It does NOT move focus state, fire `onFocus`/`onBlur`, or touch the
10
+ * focus path — that is the focus manager's job (`setActiveElementCore` in
11
+ * {@link ./focusManager.ts}).
12
+ *
13
+ * The built-in focus manager applies focus via `setActiveElementCore` and
14
+ * publishes the result through `Config.setActiveElement`, which defaults to
15
+ * this setter. A library shipping its own focus manager can read
16
+ * {@link activeElement}, reassign `Config.setActiveElement` (e.g. to inject a
17
+ * Solid owner context), or call `setActiveElement` directly — without depending
18
+ * on `focusManager.ts`. Because it is a terminal signal write (it never calls
19
+ * back into the focus manager), wiring it into `Config.setActiveElement` cannot
20
+ * recurse.
21
+ */
22
+ export const [activeElement, setActiveElement] = createSignal<
23
+ ElementNode | undefined
24
+ >(undefined);
@@ -9,6 +9,7 @@ import {
9
9
  type ElementNode,
10
10
  convertToShader as defaultConvertToShader,
11
11
  } from './elementNode.js';
12
+ import { setActiveElement as setActiveElementSignal } from './activeElement.js';
12
13
  import {
13
14
  DomRendererMainSettings,
14
15
  IRendererShader,
@@ -38,6 +39,12 @@ export const SHADERS_ENABLED =
38
39
  * at runtime (`Config.domRendererEnabled`). `Config.domRendererEnabled` is
39
40
  * mutable up until the renderer starts, so this is a function rather than a
40
41
  * constant.
42
+ *
43
+ * NOTE: do not use this to gate code paths whose dead-code elimination matters
44
+ * (e.g. branches that reference DOM-renderer-only modules). Bundlers don't
45
+ * inline this call, so the gated branch — and its imports — stay live. In
46
+ * those spots inline `DOM_RENDERING && Config.domRendererEnabled` so the
47
+ * `DOM_RENDERING` build constant can collapse the branch.
41
48
  */
42
49
  export const isDomRendererActive = () =>
43
50
  DOM_RENDERING && Config.domRendererEnabled;
@@ -57,6 +64,14 @@ export interface Config {
57
64
  animationsEnabled: boolean;
58
65
  fontSettings: Partial<TextProps>;
59
66
  rendererOptions?: Partial<RendererMainSettings> | DomRendererMainSettings;
67
+ /**
68
+ * Hook the focus manager calls to publish the active element. Defaults to
69
+ * writing the {@link activeElement} signal directly; a custom focus manager
70
+ * (or the built-in `useFocusManager`) may reassign this — e.g. to run the
71
+ * write inside a captured Solid owner context. This is the seam that keeps
72
+ * the `activeElement` signal decoupled from focus-manager logic.
73
+ */
74
+ setActiveElement: (elm: ElementNode) => void;
60
75
  focusStateKey: DollarString;
61
76
  lockStyles?: boolean;
62
77
  fontWeightAlias?: Record<string, number | string>;
@@ -78,6 +93,7 @@ export const Config: Config = {
78
93
  easing: 'ease-in-out',
79
94
  },
80
95
  convertToShader: defaultConvertToShader,
96
+ setActiveElement: (elm) => setActiveElementSignal(elm),
81
97
  fontSettings: {
82
98
  fontFamily: 'Ubuntu',
83
99
  fontSize: 100,
@@ -1137,7 +1137,6 @@ function updateDOMTextSize(node: DOMText, emitLoaded = true): void {
1137
1137
  w: node.w,
1138
1138
  h: node.h,
1139
1139
  },
1140
- trimmedHeight: node.h,
1141
1140
  };
1142
1141
  node.emit('loaded', payload);
1143
1142
  node.loaded = true;
@@ -55,7 +55,7 @@ import { assertTruthy } from '@solidtv/renderer/utils';
55
55
  import { NodeType, TextNode } from './nodeTypes.js';
56
56
  import {
57
57
  ForwardFocusHandler,
58
- setActiveElement,
58
+ setActiveElementCore,
59
59
  FocusNode,
60
60
  } from './focusManager.js';
61
61
  import { initClickInspector } from './clickInspector.js';
@@ -130,7 +130,7 @@ function runPostMutation() {
130
130
 
131
131
  // Phase 3: focus. setFocus() may have evaluated forwardFocus pre-render
132
132
  // (when no children existed yet); deferredFocusElement re-runs setFocus
133
- // here once the subtree has rendered, then setActiveElement is applied.
133
+ // here once the subtree has rendered, then setActiveElementCore is applied.
134
134
  if (deferredFocusElement !== null) {
135
135
  const el = deferredFocusElement;
136
136
  deferredFocusElement = null;
@@ -138,7 +138,7 @@ function runPostMutation() {
138
138
  } else if (nextActiveElement !== null) {
139
139
  const element = nextActiveElement;
140
140
  nextActiveElement = null;
141
- setActiveElement(element);
141
+ setActiveElementCore(element);
142
142
  }
143
143
  }
144
144
 
@@ -9,10 +9,10 @@ import type {
9
9
  KeyMap,
10
10
  } from './focusKeyTypes.js';
11
11
  import { isFunction } from './utils.js';
12
-
13
- export const [activeElement, setActiveElementSignal] = createSignal<
14
- ElementNode | undefined
15
- >(undefined);
12
+ import {
13
+ activeElement,
14
+ setActiveElement as setActiveElementSignal,
15
+ } from './activeElement.js';
16
16
 
17
17
  let _signalWrapper: (cb: () => void) => void = (cb) => cb();
18
18
 
@@ -204,14 +204,27 @@ export const printFocusHistory = (count: number): void => {
204
204
 
205
205
  // ---------------------------------------------------------------------------
206
206
 
207
- export const setActiveElement = (elm: ElementNode) => {
207
+ /**
208
+ * Built-in "apply focus" routine: diffs the focus path, fires
209
+ * `onFocus`/`onBlur`/`onFocusChanged`, records history, then publishes the
210
+ * active element through the `Config.setActiveElement` hook.
211
+ *
212
+ * This is what `ElementNode.setFocus()` ultimately invokes. It is intentionally
213
+ * *not* the public `setActiveElement` export — that name is the raw signal
214
+ * setter (see {@link ./activeElement.ts}). Keeping them separate is what stops
215
+ * a custom `Config.setActiveElement` (wired to a setter) from recursing back
216
+ * through the focus-path logic.
217
+ */
218
+ export const setActiveElementCore = (elm: ElementNode) => {
208
219
  const prev = activeElement();
209
220
  if (elm === prev) return;
210
221
  updateFocusPath(elm, prev);
211
222
  recordFocusHistory(elm, prev);
212
223
  // Reset key attribution so programmatic focus changes show '—' for key fields
213
224
  _pendingHistoryKey = { keyPressed: undefined, mappedKey: undefined };
214
- _signalWrapper(() => setActiveElementSignal(elm));
225
+ // Publish through the swappable hook rather than writing the signal directly,
226
+ // so the active-element signal stays decoupled from this focus manager.
227
+ Config.setActiveElement(elm);
215
228
  };
216
229
 
217
230
  export const [focusPath, setFocusPath] = createSignal<ElementNode[]>([]);
@@ -493,6 +506,11 @@ export const useFocusManager = (
493
506
  runWithOwner(owner, cb);
494
507
  };
495
508
  _signalWrapper = ownerContext;
509
+ // Drive the active-element signal inside this owner so its effect subscribers
510
+ // have a parent for cleanup. Consumers replacing the focus manager can wire
511
+ // Config.setActiveElement themselves instead of calling useFocusManager.
512
+ Config.setActiveElement = (elm) =>
513
+ ownerContext(() => setActiveElementSignal(elm));
496
514
 
497
515
  const delay = keyHoldOptions?.holdThreshold || DEFAULT_KEY_HOLD_THRESHOLD;
498
516
  const runKeyEvent = handleKeyEvents.bind(null, delay);
@@ -1,5 +1,5 @@
1
1
  import * as lng from '@solidtv/renderer';
2
- import { isDomRendererActive } from './config.js';
2
+ import { Config, DOM_RENDERING } from './config.js';
3
3
  import { DOMRendererMain, loadFontToDom } from './dom-renderer/domRenderer.js';
4
4
  import { DomRendererMainSettings } from './dom-renderer/domRendererTypes.js';
5
5
  import { FontLoadOptions } from './intrinsicTypes.js';
@@ -14,7 +14,9 @@ export function startLightningRenderer(
14
14
  options: lng.RendererMainSettings | DomRendererMainSettings,
15
15
  rootId: string | HTMLElement = 'app',
16
16
  ) {
17
- const enableDomRenderer = isDomRendererActive();
17
+ // Inlined (not isDomRendererActive()) so bundlers can fold DOM_RENDERING to
18
+ // false and drop the DOMRendererMain branch + import in WebGL builds.
19
+ const enableDomRenderer = DOM_RENDERING && Config.domRendererEnabled;
18
20
 
19
21
  renderer = enableDomRenderer
20
22
  ? new DOMRendererMain(options, rootId)
@@ -23,7 +25,8 @@ export function startLightningRenderer(
23
25
  }
24
26
 
25
27
  export async function loadFonts(fonts: FontLoadOptions[]) {
26
- const enableDomRenderer = isDomRendererActive();
28
+ // Inlined so the loadFontToDom branch + import tree-shake in WebGL builds.
29
+ const enableDomRenderer = DOM_RENDERING && Config.domRendererEnabled;
27
30
  await Promise.all(
28
31
  fonts.map((font) => {
29
32
  // WebGL — SDF
package/src/index.ts CHANGED
@@ -2,7 +2,8 @@ export type * from '@solidtv/solid/jsx-runtime';
2
2
  export * from './core/index.js';
3
3
  export type * from './core/index.js';
4
4
  export type { KeyHandler, KeyMap } from './core/focusManager.js';
5
- export { activeElement, setActiveElement } from './core/focusManager.js';
5
+ export { activeElement, setActiveElement } from './core/activeElement.js';
6
+ export { setActiveElementCore } from './core/focusManager.js';
6
7
  export * from './utils.js';
7
8
  export * from './render.js';
8
9
  export * from './types.js';
@@ -1,4 +1,4 @@
1
- import { ElementNode, NodeProps, View } from '@solidtv/solid';
1
+ import { ElementNode, NodeProps } from '@solidtv/solid';
2
2
  import { Show } from 'solid-js';
3
3
 
4
4
  interface Props {
@@ -52,7 +52,7 @@ export function FadeInOut(props: Props & NodeProps) {
52
52
 
53
53
  return (
54
54
  <Show when={props.when} keyed>
55
- <View {...props} onDestroy={onDestroy} onCreate={onCreate} />
55
+ <view {...props} onDestroy={onDestroy} onCreate={onCreate} />
56
56
  </Show>
57
57
  );
58
58
  }
@@ -0,0 +1,401 @@
1
+ import * as s from 'solid-js';
2
+ import * as lng from '@solidtv/solid';
3
+ import * as lngp from '@solidtv/solid/primitives';
4
+ import * as utils from '../utils.js';
5
+ import {
6
+ defaultTransitionBack,
7
+ defaultTransitionForward,
8
+ defaultTransitionDown,
9
+ defaultTransitionUp,
10
+ } from './utils/handleNavigation.js';
11
+
12
+ export type RailProps<T> = lng.NewOmit<lngp.RowProps, 'children'> & {
13
+ each: readonly T[] | undefined | null | false;
14
+ /** Uniform child size along the axis (width for Row, height for Column).
15
+ * If omitted, measured from the first laid-out child. */
16
+ itemSize?: number;
17
+ /** Space between items along the axis. Default 30. */
18
+ gap?: number;
19
+ /** Container size along the axis. If omitted, falls back to props.width/height,
20
+ * then measured from the rail's own layout. */
21
+ viewportSize?: number;
22
+ /** Extra items rendered outside the visible region on each side. Default 1. */
23
+ bufferSize?: number;
24
+ /** Window position where the focused item is pinned. Default 0. */
25
+ scrollIndex?: number;
26
+ wrap?: boolean;
27
+ onEndReached?: () => void;
28
+ /** Items from the end at which onEndReached first fires. Default 0. */
29
+ onEndReachedThreshold?: number;
30
+ /** Account for the focus-state scale when measuring item size. */
31
+ factorScale?: boolean;
32
+ children: (item: s.Accessor<T>, index: s.Accessor<number>) => s.JSX.Element;
33
+ };
34
+
35
+ function createRail<T>(
36
+ isRow: boolean,
37
+ props: RailProps<T>,
38
+ keyHandlers: Record<string, lng.KeyHandler>,
39
+ ) {
40
+ const axis: 'x' | 'y' = isRow ? 'x' : 'y';
41
+ const sizeKey: 'width' | 'height' = isRow ? 'width' : 'height';
42
+
43
+ const items = s.createMemo(() => props.each || []);
44
+ const itemCount = s.createMemo(() => items().length);
45
+ const gap = s.createMemo(() => props.gap ?? 30);
46
+ const bufferSize = s.createMemo(() => Math.max(0, props.bufferSize ?? 1));
47
+ const scrollIndex = s.createMemo(() => Math.max(0, props.scrollIndex ?? 0));
48
+
49
+ const [cursor, setCursor] = s.createSignal(props.selected ?? 0);
50
+ const [measuredItem, setMeasuredItem] = s.createSignal(0);
51
+ const [measuredViewport, setMeasuredViewport] = s.createSignal(0);
52
+
53
+ const itemSize = s.createMemo(() => props.itemSize ?? measuredItem());
54
+ // stride is only meaningful once item size is known; gap alone is not
55
+ // enough to space items, so treat unmeasured itemSize as "no stride yet"
56
+ // and let the bootstrap window in `windowLength` render a tiny slice for
57
+ // the first child to measure against.
58
+ const stride = s.createMemo(() => {
59
+ const is = itemSize();
60
+ return is > 0 ? is + gap() : 0;
61
+ });
62
+ const viewportSize = s.createMemo(
63
+ () =>
64
+ props.viewportSize ??
65
+ (props[sizeKey] as number | undefined) ??
66
+ measuredViewport(),
67
+ );
68
+
69
+ // displaySize = how many items fit in the viewport (uniform sizes).
70
+ // Returns 0 until both stride and viewport size are known.
71
+ const displaySize = s.createMemo(() => {
72
+ const st = stride();
73
+ const vp = viewportSize();
74
+ if (!st || !vp) return 0;
75
+ return Math.max(1, Math.ceil(vp / st));
76
+ });
77
+
78
+ // While unmeasured, behave as if displaySize === 1 so the bootstrap slice
79
+ // is positioned sensibly around the cursor instead of walking past the end.
80
+ const safeDisplaySize = s.createMemo(() => Math.max(1, displaySize()));
81
+
82
+ // Absolute index of the leftmost visible item. Pinning formula.
83
+ const visibleStart = s.createMemo(() => {
84
+ const total = itemCount();
85
+ if (total === 0) return 0;
86
+ const ds = safeDisplaySize();
87
+ if (props.wrap) return utils.mod(cursor() - scrollIndex(), total);
88
+ if (total <= ds) return 0;
89
+ return utils.clamp(cursor() - scrollIndex(), 0, total - ds);
90
+ });
91
+
92
+ // First rendered slot, includes leading buffer.
93
+ const windowStart = s.createMemo(() => {
94
+ const total = itemCount();
95
+ if (total === 0) return 0;
96
+ if (props.wrap) return utils.mod(visibleStart() - bufferSize(), total);
97
+ return Math.max(0, visibleStart() - bufferSize());
98
+ });
99
+
100
+ // Pool size = visible + leading + trailing buffer. Capped by total.
101
+ const windowLength = s.createMemo(() => {
102
+ const total = itemCount();
103
+ if (total === 0) return 0;
104
+ const len = safeDisplaySize() + 2 * bufferSize();
105
+ if (props.wrap) return Math.min(len, total);
106
+ return Math.min(len, total - windowStart());
107
+ });
108
+
109
+ const windowItems = s.createMemo(() => {
110
+ const len = windowLength();
111
+ if (len === 0) return [] as T[];
112
+ const start = windowStart();
113
+ const all = items();
114
+ if (props.wrap) {
115
+ const total = all.length;
116
+ return Array.from(
117
+ { length: len },
118
+ (_, i) => all[utils.mod(start + i, total)]!,
119
+ );
120
+ }
121
+ return all.slice(start, start + len);
122
+ });
123
+
124
+ // Slot of the focused item inside the rendered pool.
125
+ const windowSelected = s.createMemo(() => {
126
+ if (props.wrap) {
127
+ const total = itemCount();
128
+ if (total === 0) return 0;
129
+ return utils.mod(cursor() - windowStart(), total);
130
+ }
131
+ return cursor() - windowStart();
132
+ });
133
+
134
+ // Camera offset: keep visibleStart aligned to the viewport's leading edge.
135
+ const targetOffset = s.createMemo(() => -visibleStart() * stride());
136
+
137
+ // Total extent along the axis covered by the currently-rendered pool. The
138
+ // renderer culls children whose global rect falls outside their parent's
139
+ // strictBound, so we grow the rail's own bound to enclose all items in the
140
+ // pool (including buffer slots). Combined with `clipping={false}` this
141
+ // keeps off-viewport buffer items renderable as the camera slides.
142
+ const contentExtent = s.createMemo(() => {
143
+ const st = stride();
144
+ if (!st) return 0;
145
+ return (windowStart() + windowLength()) * st;
146
+ });
147
+
148
+ // Final width/height we hand to the underlying view along the axis.
149
+ // Always at least the user-supplied size so the rail occupies its slot in
150
+ // parent layout when the pool is short / unmeasured.
151
+ const railWidth = s.createMemo(() => {
152
+ if (!isRow) return props.width;
153
+ const userW = (props.width as number | undefined) ?? 0;
154
+ return Math.max(userW, contentExtent());
155
+ });
156
+ const railHeight = s.createMemo(() => {
157
+ if (isRow) return props.height;
158
+ const userH = (props.height as number | undefined) ?? 0;
159
+ return Math.max(userH, contentExtent());
160
+ });
161
+
162
+ let viewRef!: lngp.NavigableElement;
163
+ let cachedAnim: lng.IAnimationController | undefined;
164
+ let lastNavTime = 0;
165
+ let endFired = false;
166
+ let initialised = false;
167
+
168
+ function getAdaptiveDuration(duration: number = 250) {
169
+ const now = performance.now();
170
+ const delta = now - lastNavTime;
171
+ lastNavTime = now;
172
+ if (delta < duration) return delta;
173
+ return duration;
174
+ }
175
+
176
+ function applyOffset(target: number, animated: boolean) {
177
+ if (!viewRef) return;
178
+ if (cachedAnim && cachedAnim.state === 'running') cachedAnim.stop();
179
+ if (animated && lng.Config.animationsEnabled) {
180
+ cachedAnim = viewRef
181
+ .animate(
182
+ { [axis]: target },
183
+ {
184
+ ...viewRef.animationSettings,
185
+ duration: getAdaptiveDuration(viewRef.animationSettings?.duration),
186
+ },
187
+ )
188
+ .start();
189
+ } else {
190
+ viewRef.lng[axis] = target;
191
+ }
192
+ }
193
+
194
+ function scrollToIndex(this: lng.ElementNode, index: number) {
195
+ s.untrack(() => {
196
+ if (itemCount() === 0) return;
197
+ setCursor(utils.clamp(index, 0, itemCount() - 1));
198
+ if (!lng.hasFocus(viewRef)) viewRef.setFocus();
199
+ });
200
+ }
201
+
202
+ const onSelectedChanged: lngp.OnSelectedChanged = function (
203
+ idx,
204
+ elm,
205
+ active,
206
+ lastIdx,
207
+ ) {
208
+ if (props.onSelectedChanged) {
209
+ props.onSelectedChanged.call(this, idx, this, active, lastIdx);
210
+ }
211
+ if (idx === lastIdx) return;
212
+
213
+ const total = itemCount();
214
+ if (total === 0) return;
215
+
216
+ const poolLen = elm.children.length;
217
+ const rawDelta = idx - (lastIdx ?? 0);
218
+ let delta = rawDelta;
219
+ if (props.wrap && poolLen > 0) {
220
+ const half = poolLen / 2;
221
+ if (delta > half) delta = delta - poolLen;
222
+ else if (delta < -half) delta = delta + poolLen;
223
+ }
224
+
225
+ const next = props.wrap
226
+ ? utils.mod(cursor() + delta, total)
227
+ : utils.clamp(cursor() + delta, 0, total - 1);
228
+ setCursor(next);
229
+
230
+ if (props.onEndReached) {
231
+ const threshold = props.onEndReachedThreshold ?? 0;
232
+ const crossed = next >= total - 1 - threshold;
233
+ if (crossed && !endFired) {
234
+ endFired = true;
235
+ props.onEndReached();
236
+ } else if (!crossed && endFired) {
237
+ endFired = false;
238
+ }
239
+ }
240
+ };
241
+
242
+ // Animate the camera when visibleStart shifts; snap on first frame.
243
+ s.createEffect(() => {
244
+ const target = targetOffset();
245
+ if (!viewRef) return;
246
+ applyOffset(target, initialised);
247
+ initialised = true;
248
+ });
249
+
250
+ // Drive `selected` (and focus) imperatively. A `createMemo` would skip
251
+ // emitting when the computed slot value is unchanged across a window shift
252
+ // (e.g. cursor 3→4 with scrollIndex=0, windowStart 0→1 keeps slot=3), which
253
+ // leaves `el.selected` stuck at whatever selectChild just wrote during
254
+ // navigation. Tracking the underlying signals here forces a write every
255
+ // time cursor / window changes, overriding selectChild and keeping
256
+ // focus on the right slot as the pool slides.
257
+ s.createEffect(() => {
258
+ if (!viewRef) return;
259
+ const len = windowLength();
260
+ const ws = windowStart();
261
+ const c = cursor();
262
+ const sel = len === 0 ? 0 : utils.clamp(c - ws, 0, len - 1);
263
+ viewRef.selected = sel;
264
+ if (lng.hasFocus(viewRef) && viewRef.children[sel]) {
265
+ viewRef.children[sel].setFocus();
266
+ }
267
+ });
268
+
269
+ // Clamp cursor if the data shrinks; reset latch.
270
+ s.createEffect(
271
+ s.on(items, () => {
272
+ const total = itemCount();
273
+ if (total === 0) return;
274
+ if (cursor() >= total) setCursor(Math.max(0, total - 1));
275
+ endFired = false;
276
+ }),
277
+ );
278
+
279
+ // React to external `selected` changes.
280
+ s.createEffect(
281
+ s.on(
282
+ () => props.selected,
283
+ (sel) => {
284
+ if (sel == null) return;
285
+ const total = itemCount();
286
+ if (total === 0) return;
287
+ const safe = utils.clamp(sel, 0, total - 1);
288
+ if (safe !== cursor()) setCursor(safe);
289
+ },
290
+ { defer: true },
291
+ ),
292
+ );
293
+
294
+ const onContainerLayout = function (
295
+ this: lng.ElementNode,
296
+ el: lng.ElementNode,
297
+ ) {
298
+ if (props.viewportSize == null && props[sizeKey] == null) {
299
+ const v = (el[sizeKey] as number) || 0;
300
+ if (v && v !== measuredViewport()) setMeasuredViewport(v);
301
+ }
302
+ props.onLayout?.call(this, el);
303
+ };
304
+
305
+ // Position each user-rendered child directly (no wrapper view). We assign
306
+ // x/y on viewRef.children[i] reactively so the slots track the sliding
307
+ // window without an extra node per item.
308
+ s.createEffect(() => {
309
+ if (!viewRef) return;
310
+ const ws = windowStart();
311
+ const st = stride();
312
+ const children = viewRef.children;
313
+ for (let i = 0; i < children.length; i++) {
314
+ const c = children[i];
315
+ if (!c) continue;
316
+ const p = (ws + i) * st;
317
+ if (isRow) c.x = p;
318
+ else c.y = p;
319
+ }
320
+ });
321
+
322
+ // Measure item size from the first rendered child if not provided.
323
+ s.createEffect(() => {
324
+ if (props.itemSize != null) return;
325
+ // Track window changes so we re-measure if the first item swaps.
326
+ windowItems();
327
+ if (!viewRef) return;
328
+ const first = viewRef.children[0];
329
+ if (!first) return;
330
+ let raw = (first[sizeKey] as number) || 0;
331
+ if (props.factorScale) {
332
+ const focusStyle = first.style?.focus as lng.NodeStyles | undefined;
333
+ const scale = focusStyle?.scale ?? first.scale ?? 1;
334
+ raw = raw * scale;
335
+ }
336
+ if (raw && raw !== measuredItem()) setMeasuredItem(raw);
337
+ });
338
+
339
+ return (
340
+ <view
341
+ transitionLeft={isRow ? defaultTransitionBack : undefined}
342
+ transitionRight={isRow ? defaultTransitionForward : undefined}
343
+ transitionUp={!isRow ? defaultTransitionUp : undefined}
344
+ transitionDown={!isRow ? defaultTransitionDown : undefined}
345
+ {...props}
346
+ {...keyHandlers}
347
+ selected={0}
348
+ ref={lngp.chainRefs((el) => {
349
+ viewRef = el as lngp.NavigableElement;
350
+ }, props.ref)}
351
+ forwardFocus={/* @once */ lngp.navigableForwardFocus}
352
+ scrollToIndex={/* @once */ scrollToIndex}
353
+ onSelectedChanged={/* @once */ onSelectedChanged}
354
+ onLayout={onContainerLayout}
355
+ clipping={false}
356
+ width={railWidth()}
357
+ height={railHeight()}
358
+ >
359
+ <s.Index each={windowItems()}>
360
+ {(item, i) => {
361
+ const absIndex = s.createMemo(() => {
362
+ const total = itemCount();
363
+ if (props.wrap && total > 0) {
364
+ return utils.mod(windowStart() + i, total);
365
+ }
366
+ return windowStart() + i;
367
+ });
368
+ // No wrapper view: the user's element is positioned directly via
369
+ // an effect that writes x/y onto viewRef.children[i].
370
+ return props.children(item, absIndex);
371
+ }}
372
+ </s.Index>
373
+ </view>
374
+ );
375
+ }
376
+
377
+ export function RailRow<T>(props: RailProps<T>) {
378
+ return createRail(true, props, {
379
+ onLeft: lngp.chainFunctions(
380
+ props.onLeft,
381
+ lngp.handleNavigation('left'),
382
+ ) as lng.KeyHandler,
383
+ onRight: lngp.chainFunctions(
384
+ props.onRight,
385
+ lngp.handleNavigation('right'),
386
+ ) as lng.KeyHandler,
387
+ });
388
+ }
389
+
390
+ export function RailColumn<T>(props: RailProps<T>) {
391
+ return createRail(false, props, {
392
+ onUp: lngp.chainFunctions(
393
+ props.onUp,
394
+ lngp.handleNavigation('up'),
395
+ ) as lng.KeyHandler,
396
+ onDown: lngp.chainFunctions(
397
+ props.onDown,
398
+ lngp.handleNavigation('down'),
399
+ ) as lng.KeyHandler,
400
+ });
401
+ }
@@ -33,3 +33,4 @@ export { createBlurredImage } from './utils/createBlurredImage.js';
33
33
 
34
34
  export type * from './types.js';
35
35
  export type { KeyHandler } from '../core/focusManager.js';
36
+ export type { SpeechType } from './announcer/speech.js';