@solidtv/solid 1.3.4 → 1.3.6

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidtv/solid",
3
- "version": "1.3.4",
3
+ "version": "1.3.6",
4
4
  "description": "SolidTV",
5
5
  "type": "module",
6
6
  "exports": {
@@ -757,6 +757,16 @@ export interface ElementNode extends RendererNode, FocusNode {
757
757
  */
758
758
  onEvent?: OnEvent;
759
759
 
760
+ /**
761
+ * Callback event for when the element is clicked with a mouse.
762
+ * Triggered when `useMouse` is running.
763
+ */
764
+ onMouseClick?: (
765
+ this: ElementNode,
766
+ event: MouseEvent,
767
+ node: ElementNode,
768
+ ) => void;
769
+
760
770
  /**
761
771
  * The individual padding on each side of an element, acting as an override to the `padding` array property.
762
772
  * `paddingTop`, `paddingRight`, `paddingBottom`, `paddingLeft`.
@@ -1620,7 +1630,10 @@ export class ElementNode {
1620
1630
  }
1621
1631
 
1622
1632
  // Can you put effects on Text nodes? Need to confirm...
1623
- if (SHADERS_ENABLED && props.shader && !props.shader.program) {
1633
+ // A built shader node (WebGL, Canvas, or the DOM test fake) always has a
1634
+ // `shaderType`; a raw StyleEffects props object never does. Only convert
1635
+ // the latter — a built shader is already ready to render.
1636
+ if (SHADERS_ENABLED && props.shader && !('shaderType' in props.shader)) {
1624
1637
  props.shader = Config.convertToShader(node, props.shader);
1625
1638
  }
1626
1639
 
@@ -1649,6 +1662,23 @@ export class ElementNode {
1649
1662
  const isFlexRow =
1650
1663
  flexDirection === 'row' || flexDirection === 'row-reverse';
1651
1664
  flexFitsWidth = isFlexRow && node.flexBoundary !== 'fixed';
1665
+
1666
+ if (isDev && flexFitsWidth) {
1667
+ const needsWidthForJustify = [
1668
+ 'center',
1669
+ 'flex-end',
1670
+ 'space-between',
1671
+ 'space-around',
1672
+ 'space-evenly',
1673
+ ].includes(node.justifyContent as string);
1674
+
1675
+ if (needsWidthForJustify) {
1676
+ console.warn(
1677
+ `justifyContent '${node.justifyContent}' requires an explicit width on the flex container; without one it shrinks to fit its children and has no free space to distribute: `,
1678
+ this,
1679
+ );
1680
+ }
1681
+ }
1652
1682
  }
1653
1683
 
1654
1684
  if (node.flexGrow || flexFitsWidth) {
@@ -1675,7 +1705,7 @@ export class ElementNode {
1675
1705
  }
1676
1706
  }
1677
1707
 
1678
- if (SHADERS_ENABLED && props.shader && !props.shader.program) {
1708
+ if (SHADERS_ENABLED && props.shader && !('shaderType' in props.shader)) {
1679
1709
  props.shader = Config.convertToShader(node, props.shader);
1680
1710
  }
1681
1711
 
@@ -21,8 +21,9 @@ function scrollToIndex(
21
21
  index: number,
22
22
  options?: { noFocus?: boolean },
23
23
  ): void {
24
+ const lastSelected = this.selected;
24
25
  this.selected = index;
25
- scrollColumn(index, this);
26
+ scrollColumn(index, this, undefined, lastSelected === index ? undefined : lastSelected);
26
27
  if (!options?.noFocus) {
27
28
  this.children[index]?.setFocus();
28
29
  }
@@ -144,11 +144,17 @@ function createLazy<T>(
144
144
  const updateOffset = (_event: KeyboardEvent, container: lng.ElementNode) => {
145
145
  const maxOffset = props.each ? props.each.length : 0;
146
146
  const selected = container.selected || 0;
147
- const rendered = offset(); // == container.children.length
148
-
149
- // Already mounted everything, or still far enough from the rendered edge
150
- // that the buffer covers the next selection — no work to do.
151
- if (rendered >= maxOffset || selected < rendered - buffer()) return;
147
+ // The rendered edge is the actual child count, not offset(): the two
148
+ // diverge when an item renders empty (no node inserted) or renders
149
+ // multiple top-level nodes. `selected` indexes into children, so the
150
+ // proximity check must use child units.
151
+ const rendered = container.children.length;
152
+
153
+ // Already mounted everything (offset is in data units — a diverged child
154
+ // count must neither stop mounting early nor keep it running forever),
155
+ // or still far enough from the rendered edge that the buffer covers the
156
+ // next selection — no work to do.
157
+ if (offset() >= maxOffset || selected < rendered - buffer()) return;
152
158
 
153
159
  const bump = () => setOffset((prev) => Math.min(prev + 1, maxOffset));
154
160
 
@@ -19,9 +19,10 @@ const RowStyles: NodeStyles = {
19
19
  gap: 30,
20
20
  };
21
21
 
22
- function scrollToIndex(this: ElementNode, index: number, options?: {noFocus?: boolean}) {
22
+ function scrollToIndex(this: ElementNode, index: number, options?: { noFocus?: boolean }) {
23
+ const lastSelected = this.selected;
23
24
  this.selected = index;
24
- scrollRow(index, this);
25
+ scrollRow(index, this, undefined, lastSelected === index ? undefined : lastSelected);
25
26
  if (!options?.noFocus) {
26
27
  this.children[index]?.setFocus();
27
28
  }
@@ -15,6 +15,8 @@ export type VirtualProps<T> = lng.NewOmit<lngp.RowProps, 'children'> & {
15
15
  displaySize: number;
16
16
  bufferSize?: number;
17
17
  wrap?: boolean;
18
+ /** With `wrap`, defers wrap behavior until the first right press. Ignored when `selected` is non-zero at mount. */
19
+ skipInitialWrap?: boolean;
18
20
  scrollIndex?: number;
19
21
  onEndReached?: () => void;
20
22
  onEndReachedThreshold?: number;
@@ -38,11 +40,18 @@ function createVirtual<T>(
38
40
  const itemCount = s.createMemo(() => items().length);
39
41
  const scrollType = s.createMemo(() => props.scroll || 'auto');
40
42
 
43
+ const initiallyLocked =
44
+ !!props.skipInitialWrap &&
45
+ !!props.wrap &&
46
+ (props.selected ?? 0) === 0;
47
+ const [wrapUnlocked, setWrapUnlocked] = s.createSignal(!initiallyLocked);
48
+ const effectiveWrap = s.createMemo(() => !!props.wrap && wrapUnlocked());
49
+
41
50
  const selected = () => {
42
51
  if (itemCount() <= props.displaySize) {
43
52
  return utils.clamp(props.selected || 0, 0, Math.max(0, itemCount() - 1));
44
53
  }
45
- if (props.wrap) {
54
+ if (props.wrap && !initiallyLocked) {
46
55
  return Math.max(bufferSize(), scrollIndex());
47
56
  }
48
57
  return utils.clamp(props.selected || 0, 0, Math.max(0, itemCount() - 1));
@@ -139,7 +148,7 @@ function createVirtual<T>(
139
148
 
140
149
  switch (scrollType()) {
141
150
  case 'always':
142
- if (props.wrap) {
151
+ if (effectiveWrap()) {
143
152
  start = utils.mod(c - 1, total);
144
153
  selected = 1;
145
154
  } else {
@@ -163,7 +172,7 @@ function createVirtual<T>(
163
172
  break;
164
173
 
165
174
  case 'auto':
166
- if (props.wrap) {
175
+ if (effectiveWrap()) {
167
176
  if (delta === 0) {
168
177
  selected = scrollIndex() || 1;
169
178
  start = utils.mod(c - (scrollIndex() || 1), total);
@@ -252,7 +261,7 @@ function createVirtual<T>(
252
261
  1,
253
262
  props.displaySize + (atStart ? -1 : 0),
254
263
  );
255
- if (props.wrap) {
264
+ if (effectiveWrap()) {
256
265
  if (delta > 0) {
257
266
  if (prev.selected < startScrolling) {
258
267
  selected = prev.selected + 1;
@@ -327,11 +336,11 @@ function createVirtual<T>(
327
336
 
328
337
  let newSlice = prev.slice;
329
338
  if (start !== prev.start || newSlice.length === 0) {
330
- newSlice = props.wrap
339
+ newSlice = effectiveWrap()
331
340
  ? (Array.from(
332
- { length },
333
- (_, i) => items()[utils.mod(start + i, total)],
334
- ) as T[])
341
+ { length },
342
+ (_, i) => items()[utils.mod(start + i, total)],
343
+ ) as T[])
335
344
  : items().slice(start, start + length);
336
345
  }
337
346
 
@@ -411,13 +420,13 @@ function createVirtual<T>(
411
420
 
412
421
  const rawDelta = idx - (lastIdx ?? 0);
413
422
  const windowLen = elm?.children?.length ?? props.displaySize + bufferSize();
414
- const delta = props.wrap
423
+ const delta = effectiveWrap()
415
424
  ? normalizeDeltaForWindow(rawDelta, windowLen)
416
425
  : rawDelta;
417
426
 
418
427
  setCursor((c) => {
419
428
  const next = c + delta;
420
- return props.wrap
429
+ return effectiveWrap()
421
430
  ? utils.mod(next, total)
422
431
  : utils.clamp(next, 0, total - 1);
423
432
  });
@@ -426,6 +435,8 @@ function createVirtual<T>(
426
435
  setSlice(newState);
427
436
  elm.selected = newState.selected;
428
437
 
438
+ if (!wrapUnlocked() && rawDelta > 0) setWrapUnlocked(true);
439
+
429
440
  if (
430
441
  props.onEndReachedThreshold !== undefined &&
431
442
  cursor() >= itemCount() - props.onEndReachedThreshold
@@ -492,10 +503,10 @@ function createVirtual<T>(
492
503
  });
493
504
  };
494
505
 
495
- let doOnce = false;
506
+ let doOnce = initiallyLocked;
496
507
  s.createEffect(
497
- s.on([() => props.wrap, items], () => {
498
- if (!viewRef || itemCount() === 0 || !props.wrap || doOnce) return;
508
+ s.on([effectiveWrap, items], () => {
509
+ if (!viewRef || itemCount() === 0 || !effectiveWrap() || doOnce) return;
499
510
  doOnce = true;
500
511
  if (itemCount() <= props.displaySize) {
501
512
  queueMicrotask(() => {
@@ -542,6 +553,7 @@ function createVirtual<T>(
542
553
  ref={lngp.chainRefs((el) => {
543
554
  viewRef = el as lngp.NavigableElement;
544
555
  }, props.ref)}
556
+ wrap={effectiveWrap()}
545
557
  selected={selected()}
546
558
  cursor={cursor()}
547
559
  forwardFocus={/* @once */ lngp.navigableForwardFocus}
@@ -549,18 +561,18 @@ function createVirtual<T>(
549
561
  onSelectedChanged={/* @once */ onSelectedChanged}
550
562
  style={
551
563
  /* @once */ lng.combineStyles(
552
- props.style,
553
- component === lngp.Row
554
- ? {
555
- display: 'flex',
556
- gap: 30,
557
- }
558
- : {
559
- display: 'flex',
560
- flexDirection: 'column',
561
- gap: 30,
562
- },
563
- )
564
+ props.style,
565
+ component === lngp.Row
566
+ ? {
567
+ display: 'flex',
568
+ gap: 30,
569
+ }
570
+ : {
571
+ display: 'flex',
572
+ flexDirection: 'column',
573
+ gap: 30,
574
+ },
575
+ )
564
576
  }
565
577
  >
566
578
  <List each={slice().slice}>{props.children}</List>
@@ -3,8 +3,13 @@ import * as lng from '@solidtv/solid';
3
3
  import * as lngp from '@solidtv/solid/primitives';
4
4
  import { List } from '@solid-primitives/list';
5
5
  import * as utils from '../utils.js';
6
+ // Imported directly, not via lngp: this call runs at module init, and the
7
+ // barrel's withScrolling binding is not yet initialized when the barrel is
8
+ // the import entry (circular init — index.ts re-exports withScrolling after
9
+ // VirtualGrid).
10
+ import { withScrolling } from './utils/withScrolling.js';
6
11
 
7
- const columnScroll = lngp.withScrolling(false);
12
+ const columnScroll = withScrolling(false);
8
13
 
9
14
  const rowStyles: lng.NodeStyles = {
10
15
  display: 'flex',
@@ -17,7 +17,15 @@ type AriaLabel = { text: string; lang: string };
17
17
  const ARIA_PARENT_ID = 'aria-parent';
18
18
  let ariaLabelPhrases: AriaLabel[] = [];
19
19
 
20
- /* global SpeechSynthesisErrorEvent */
20
+ // An Error carrying the structured speech-synthesis error code (e.g.
21
+ // "interrupted", "canceled", "network"). We reject with this instead of the
22
+ // raw SpeechSynthesisErrorEvent so callers can classify the failure without
23
+ // depending on the SpeechSynthesisErrorEvent global, which isn't defined on
24
+ // every TV browser.
25
+ interface SpeechError extends Error {
26
+ error?: string;
27
+ }
28
+
21
29
  function flattenStrings(series: SpeechType[] = []): SpeechType[] {
22
30
  const flattenedSeries = [];
23
31
 
@@ -153,13 +161,50 @@ function speak(
153
161
  resolve();
154
162
  };
155
163
  utterance.onerror = (e) => {
156
- reject(new Error(`Speech synthesis error: ${e.error}`));
164
+ const error: SpeechError = new Error(
165
+ `Speech synthesis error: ${e.error}`,
166
+ );
167
+ // Preserve the code so speakSeries can tell benign interruptions
168
+ // ("interrupted"/"canceled") apart from real failures ("network", etc.).
169
+ error.error = e.error;
170
+ reject(error);
157
171
  };
158
172
  utterances.push(utterance);
159
173
  synth.speak(utterance);
160
174
  });
161
175
  }
162
176
 
177
+ /**
178
+ * @description Classify a caught speech error and apply back-off.
179
+ * Returns the retries remaining after handling. `interrupted`/`canceled` are
180
+ * benign — a newer announcement cancelled or replaced the in-flight one (see
181
+ * synth.cancel()), which happens constantly during directional navigation — so
182
+ * we stop retrying without surfacing them. `network` errors back off and retry.
183
+ * Anything else is genuinely unexpected and is rethrown.
184
+ */
185
+ async function handleSpeechError(
186
+ e: unknown,
187
+ retriesLeft: number,
188
+ totalRetries: number,
189
+ ): Promise<number> {
190
+ const code = (e as SpeechError | undefined)?.error;
191
+
192
+ if (code === 'network') {
193
+ retriesLeft--;
194
+ console.warn(
195
+ `Speech synthesis network error. Retries left: ${retriesLeft}`,
196
+ );
197
+ await delay(500 * (totalRetries - retriesLeft));
198
+ return retriesLeft;
199
+ }
200
+
201
+ if (code === 'canceled' || code === 'interrupted') {
202
+ return 0; // benign — stop retrying, don't propagate
203
+ }
204
+
205
+ throw e;
206
+ }
207
+
163
208
  function speakSeries(
164
209
  series: SpeechType,
165
210
  aria: boolean,
@@ -203,25 +248,11 @@ function speakSeries(
203
248
  else await speak(phrase, utterances, lang, voice);
204
249
  retriesLeft = 0; // Exit retry loop on success
205
250
  } catch (e) {
206
- if (e instanceof SpeechSynthesisErrorEvent) {
207
- if (e.error === 'network') {
208
- retriesLeft--;
209
- console.warn(
210
- `Speech synthesis network error. Retries left: ${retriesLeft}`,
211
- );
212
- await delay(500 * (totalRetries - retriesLeft));
213
- } else if (
214
- e.error === 'canceled' ||
215
- e.error === 'interrupted'
216
- ) {
217
- // Cancel or interrupt error (ignore)
218
- retriesLeft = 0;
219
- } else {
220
- throw new Error(`SpeechSynthesisErrorEvent: ${e.error}`);
221
- }
222
- } else {
223
- throw e;
224
- }
251
+ retriesLeft = await handleSpeechError(
252
+ e,
253
+ retriesLeft,
254
+ totalRetries,
255
+ );
225
256
  }
226
257
  }
227
258
  } else if (phrase instanceof SpeechSynthesisUtterance) {
@@ -241,25 +272,11 @@ function speakSeries(
241
272
  retriesLeft = 0; // Exit retry loop on success
242
273
  }
243
274
  } catch (e) {
244
- if (e instanceof SpeechSynthesisErrorEvent) {
245
- if (e.error === 'network') {
246
- retriesLeft--;
247
- console.warn(
248
- `Speech synthesis network error. Retries left: ${retriesLeft}`,
249
- );
250
- await delay(500 * (totalRetries - retriesLeft));
251
- } else if (
252
- e.error === 'canceled' ||
253
- e.error === 'interrupted'
254
- ) {
255
- // Cancel or interrupt error (ignore)
256
- retriesLeft = 0;
257
- } else {
258
- throw new Error(`SpeechSynthesisErrorEvent: ${e.error}`);
259
- }
260
- } else {
261
- throw e;
262
- }
275
+ retriesLeft = await handleSpeechError(
276
+ e,
277
+ retriesLeft,
278
+ totalRetries,
279
+ );
263
280
  }
264
281
  }
265
282
  } else if (typeof phrase === 'function') {
package/src/utils.ts CHANGED
@@ -7,7 +7,14 @@ const WEBGL_CONTEXT_IDS = [
7
7
  'experimental-webgl2',
8
8
  'experimental-webgl',
9
9
  ];
10
- let supportedWebglVersions: string[] | undefined;
10
+ // WebGL support never changes during a page's lifetime, so each distinct id
11
+ // list is probed exactly once and the result is cached forever. This is
12
+ // load-bearing on embedded TV boxes: every probe call creates a real WebGL
13
+ // context, and those boxes cap live contexts very low. Probing repeatedly (the
14
+ // old behavior bypassed the cache for any non-default argument) creates a new
15
+ // context each time, blows the page's context budget, and evicts the oldest
16
+ // context — the live render context — which then fails every createTexture.
17
+ const supportedWebglVersions = new Map<string, string[]>();
11
18
 
12
19
  /**
13
20
  * Converts a color string to a color number value.
@@ -90,14 +97,26 @@ export function mod(n: number, m: number): number {
90
97
  export function getWebglSupportedVersions(
91
98
  webglContextIds: string[] = WEBGL_CONTEXT_IDS,
92
99
  ): string[] {
93
- if (supportedWebglVersions && webglContextIds === WEBGL_CONTEXT_IDS) {
94
- return supportedWebglVersions;
100
+ // Cache per distinct id list. The previous version only cached the default
101
+ // list, so any caller passing its own array re-probed (and re-created a
102
+ // context) on every call — see the comment on `supportedWebglVersions`.
103
+ const cacheKey = webglContextIds.join('|');
104
+ const cached = supportedWebglVersions.get(cacheKey);
105
+ if (cached !== undefined) {
106
+ return cached;
95
107
  }
96
108
 
97
109
  const cv = document.createElement('canvas');
110
+ // A canvas locks to the first context type it hands out, so probing several
111
+ // ids on one canvas yields at most one live context. Capture it so we can
112
+ // release it below.
113
+ let probeContext: RenderingContext | null = null;
98
114
  const supports = webglContextIds.filter((id) => {
99
115
  try {
100
116
  const context = cv.getContext(id);
117
+ if (context !== null && probeContext === null) {
118
+ probeContext = context;
119
+ }
101
120
  return !!(
102
121
  context &&
103
122
  (context instanceof WebGLRenderingContext ||
@@ -110,10 +129,25 @@ export function getWebglSupportedVersions(
110
129
  }
111
130
  });
112
131
 
113
- if (webglContextIds === WEBGL_CONTEXT_IDS) {
114
- supportedWebglVersions = supports;
132
+ // Free the probe context immediately instead of leaking it until GC. Embedded
133
+ // TV browsers cap live WebGL contexts very low; a lingering probe burns one of
134
+ // those scarce slots and can trigger "too many active webgl contexts" — which
135
+ // evicts the oldest context (potentially the live render context). Guard with
136
+ // isContextLost(): if the browser already evicted this probe, loseContext()
137
+ // throws INVALID_OPERATION ("context already lost") and spams the console.
138
+ const probe = probeContext as RenderingContext | null;
139
+ if (
140
+ probe !== null &&
141
+ 'getExtension' in probe &&
142
+ (probe as WebGLRenderingContext).isContextLost() === false
143
+ ) {
144
+ (probe as WebGLRenderingContext)
145
+ .getExtension('WEBGL_lose_context')
146
+ ?.loseContext();
115
147
  }
116
148
 
149
+ supportedWebglVersions.set(cacheKey, supports);
150
+
117
151
  return supports;
118
152
  }
119
153