@rohal12/spindle 0.59.29 → 0.59.30

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 +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +560 -272
  4. package/dist/pkg/macro-registry.js +19 -0
  5. package/dist/pkg/macro-registry.json +19 -0
  6. package/dist/pkg/story-variables.js +494 -90
  7. package/package.json +1 -1
  8. package/src/action-registry.ts +59 -5
  9. package/src/automation/load-yaml.ts +111 -20
  10. package/src/automation/runner.ts +15 -13
  11. package/src/automation/types.ts +7 -5
  12. package/src/class-registry.ts +8 -5
  13. package/src/code-check.ts +87 -20
  14. package/src/components/macros/Checkbox.tsx +5 -2
  15. package/src/components/macros/Cycle.tsx +1 -0
  16. package/src/components/macros/For.tsx +1 -7
  17. package/src/components/macros/Listbox.tsx +1 -0
  18. package/src/components/macros/MenubarButtons.tsx +6 -1
  19. package/src/components/macros/Nobr.tsx +1 -0
  20. package/src/components/macros/PassageDisplay.tsx +42 -0
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/SaveManager.tsx +19 -4
  23. package/src/components/macros/SettingsControls.tsx +19 -4
  24. package/src/components/macros/Span.tsx +1 -0
  25. package/src/components/macros/StoryTitle.tsx +1 -0
  26. package/src/components/macros/VarDisplay.tsx +2 -3
  27. package/src/components/macros/WidgetInvocation.tsx +5 -6
  28. package/src/components/macros/input-macro.ts +1 -0
  29. package/src/components/macros/locals-scope.tsx +19 -8
  30. package/src/components/macros/macro-args.ts +11 -3
  31. package/src/expression.ts +34 -18
  32. package/src/hooks/use-merged-locals.ts +17 -2
  33. package/src/hooks/use-modal-focus.ts +190 -129
  34. package/src/index.tsx +22 -12
  35. package/src/js-bindings.ts +332 -0
  36. package/src/js-lexer.ts +12 -3
  37. package/src/macro-discovery.ts +25 -22
  38. package/src/static-literal.ts +87 -16
  39. package/src/store.ts +4 -1
  40. package/src/story-api.ts +13 -4
  41. package/src/story-variables.ts +91 -28
  42. package/src/structural.ts +19 -15
  43. package/src/tooling.ts +21 -8
  44. package/src/transform.ts +22 -7
  45. package/src/utils/namespace.ts +4 -0
  46. package/src/utils/object-path.ts +2 -2
  47. package/src/utils/stable-key.ts +17 -6
  48. package/src/utils/value-kinds.ts +38 -1
  49. package/types/index.d.ts +12 -5
  50. package/types/tooling.d.ts +12 -2
@@ -76,9 +76,11 @@ function tabIndexAttr(el: HTMLElement): number | null {
76
76
  function isTabStop(el: HTMLElement): boolean {
77
77
  const tabIndex = tabIndexAttr(el);
78
78
  if (tabIndex !== null && tabIndex < 0) return false;
79
- // Only an editing host takes focus, not `contenteditable="false"` or
80
- // content nested in a host
79
+ // Only an editing host takes focus of its own, not `contenteditable="false"`
80
+ // or content nested in a host; an explicit tabindex makes any of them a
81
+ // stop (#507)
81
82
  if (
83
+ tabIndex === null &&
82
84
  el.hasAttribute('contenteditable') &&
83
85
  !el.matches('a[href], button, input, select, textarea, iframe, summary') &&
84
86
  (!el.isContentEditable || el.parentElement?.isContentEditable)
@@ -95,15 +97,18 @@ function isTabStop(el: HTMLElement): boolean {
95
97
  return tabIndex !== null;
96
98
  }
97
99
  }
98
- if (el instanceof HTMLInputElement && el.type === 'radio' && el.name) {
100
+ // localName, not instanceof: elements of an embedded document are of
101
+ // another realm's classes
102
+ const input = el as HTMLInputElement;
103
+ if (el.localName === 'input' && input.type === 'radio' && input.name) {
99
104
  const group = Array.from(
100
105
  (
101
- el.form ?? (el.getRootNode() as ParentNode)
106
+ input.form ?? (el.getRootNode() as ParentNode)
102
107
  ).querySelectorAll<HTMLInputElement>('input[type="radio"]'),
103
108
  ).filter(
104
109
  (r) =>
105
- r.name === el.name &&
106
- r.form === el.form &&
110
+ r.name === input.name &&
111
+ r.form === input.form &&
107
112
  // Of the members Tab can reach (#390)
108
113
  (tabIndexAttr(r) ?? 0) >= 0 &&
109
114
  isAvailable(r),
@@ -115,10 +120,11 @@ function isTabStop(el: HTMLElement): boolean {
115
120
  }
116
121
 
117
122
  /**
118
- * The elements of `root` in the order Tab visits them: positive tabindexes
119
- * first, ascending, then the others in document order.
123
+ * The elements of `root` (the dialog panel, or an embedded document) in the
124
+ * order Tab visits them: positive tabindexes first, ascending, then the
125
+ * others in document order.
120
126
  */
121
- function focusables(root: HTMLElement): HTMLElement[] {
127
+ function focusables(root: ParentNode): HTMLElement[] {
122
128
  const stops = Array.from(
123
129
  root.querySelectorAll<HTMLElement>(FOCUSABLE),
124
130
  ).filter((el) => isAvailable(el) && isTabStop(el));
@@ -158,20 +164,63 @@ const SEGMENTED_INPUTS = new Set([
158
164
 
159
165
  /** Whether the element has native tab stops inside it, in its shadow tree. */
160
166
  function hasNativeStops(el: Element | null): el is HTMLElement {
161
- if (el instanceof HTMLMediaElement) return el.controls;
167
+ if (!el) return false;
168
+ if (el.localName === 'audio' || el.localName === 'video') {
169
+ return (el as HTMLMediaElement).controls;
170
+ }
171
+ const input = el as HTMLInputElement;
162
172
  return (
163
- el instanceof HTMLInputElement &&
164
- SEGMENTED_INPUTS.has(el.type) &&
165
- !el.readOnly
173
+ el.localName === 'input' &&
174
+ SEGMENTED_INPUTS.has(input.type) &&
175
+ !input.readOnly
166
176
  );
167
177
  }
168
178
 
169
- /** The tab stops of an embedded document, in tab order. */
170
- function frameStops(doc: Document | null): HTMLElement[] {
171
- if (!doc) return [];
172
- return Array.from(doc.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
173
- (el) => isAvailable(el) && isTabStop(el),
174
- );
179
+ /** Whether `el` is an iframe element, of this realm or of an embedded one. */
180
+ function isFrame(el: Element): el is HTMLIFrameElement {
181
+ return el.localName === 'iframe';
182
+ }
183
+
184
+ /** The document of a frame, or null when it is not accessible. */
185
+ function frameDocument(frame: HTMLIFrameElement): Document | null {
186
+ try {
187
+ return frame.contentDocument;
188
+ } catch {
189
+ return null;
190
+ }
191
+ }
192
+
193
+ /** The iframe element that holds `doc`, null for the top document. */
194
+ function frameOf(doc: Document): HTMLElement | null {
195
+ try {
196
+ return doc.defaultView?.frameElement as HTMLElement | null;
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+
202
+ /**
203
+ * The stop after (or before) `from` among `items`, the tab stops of `root`,
204
+ * undefined past the end. `from` may be no stop of its own: then the next one
205
+ * in document order. Outside `root`, the first (or last) stop.
206
+ */
207
+ function nextStop(
208
+ items: HTMLElement[],
209
+ root: ParentNode,
210
+ from: Element | null,
211
+ backwards: boolean,
212
+ ): HTMLElement | undefined {
213
+ const at = from ? items.indexOf(from as HTMLElement) : -1;
214
+ if (at !== -1) return items[at + (backwards ? -1 : 1)];
215
+ if (from && from !== root && root.contains(from)) {
216
+ // Inside the root but not a tab stop: continue from its position
217
+ const after = (el: HTMLElement) =>
218
+ !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
219
+ return backwards
220
+ ? items.filter((el) => !after(el)).pop()
221
+ : items.find(after);
222
+ }
223
+ return backwards ? items[items.length - 1] : items[0];
175
224
  }
176
225
 
177
226
  export function useModalFocus(
@@ -184,9 +233,12 @@ export function useModalFocus(
184
233
  const panel = panelRef.current;
185
234
  if (!panel) return;
186
235
 
236
+ // A focusable SVG element (a link in an illustration) is an opener too
237
+ // (#483)
238
+ const focused = document.activeElement;
187
239
  const opener =
188
- document.activeElement instanceof HTMLElement
189
- ? document.activeElement
240
+ focused instanceof HTMLElement || focused instanceof SVGElement
241
+ ? focused
190
242
  : null;
191
243
  const entry: ModalEntry = { panel };
192
244
  openModals.push(entry);
@@ -220,32 +272,36 @@ export function useModalFocus(
220
272
 
221
273
  const top = () => openModals[openModals.length - 1]?.panel === panel;
222
274
 
223
- /**
224
- * Move focus to the next (or previous) modal control from `from`. The
225
- * order is computed here, never left to the browser: its positive-tabindex
226
- * sequence spans the whole document and would lead out of the modal
227
- * (#424). `from` may be an element of an embedded document, whose frame
228
- * element then stands in for it.
229
- */
230
275
  /** Focus `el`; a frame is entered at its first (or last) control (#460). */
231
276
  const enter = (el: HTMLElement, backwards: boolean) => {
232
- if (el instanceof HTMLIFrameElement) {
233
- let inner: HTMLElement[] = [];
234
- try {
235
- inner = frameStops(el.contentDocument);
236
- } catch {
237
- // Not accessible: the frame itself takes focus
238
- }
277
+ if (isFrame(el)) {
278
+ const doc = frameDocument(el);
279
+ const inner = doc ? focusables(doc) : [];
239
280
  const edge = backwards ? inner[inner.length - 1] : inner[0];
240
- if (edge) {
241
- edge.focus();
242
- return;
243
- }
281
+ // A frame inside the frame is entered in turn
282
+ if (edge) return enter(edge, backwards);
283
+ // Not accessible or without controls: the frame itself takes focus
244
284
  }
245
285
  el.focus();
246
286
  };
247
287
 
288
+ /**
289
+ * Move focus to the next (or previous) modal control from `from`. The
290
+ * order is computed here, never left to the browser: its positive-tabindex
291
+ * sequence spans the whole document and would lead out of the modal
292
+ * (#424). `from` is an element of the dialog, or of an embedded document;
293
+ * past the last control of a frame, focus goes on after the frame element
294
+ * in the document that holds it.
295
+ */
248
296
  const moveFocus = (from: Element | null, backwards: boolean) => {
297
+ const doc = from?.ownerDocument;
298
+ const frame = doc && doc !== document ? frameOf(doc) : null;
299
+ if (doc && frame) {
300
+ const next = nextStop(focusables(doc), doc, from, backwards);
301
+ if (next) enter(next, backwards);
302
+ else moveFocus(frame, backwards);
303
+ return;
304
+ }
249
305
  const items = focusables(panel);
250
306
  const first = items[0];
251
307
  const last = items[items.length - 1];
@@ -253,108 +309,75 @@ export function useModalFocus(
253
309
  panel.focus();
254
310
  return;
255
311
  }
256
- const at = from ? items.indexOf(from as HTMLElement) : -1;
257
- let next: HTMLElement | undefined;
258
- if (at !== -1) {
259
- next = items[at + (backwards ? -1 : 1)];
260
- } else if (from && from !== panel && panel.contains(from)) {
261
- // Inside the panel but not a tab stop: continue from its position
262
- const after = (el: HTMLElement) =>
263
- !!(
264
- from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING
265
- );
266
- next = backwards
267
- ? items.filter((el) => !after(el)).pop()
268
- : items.find(after);
269
- } else {
270
- next = backwards ? last : first;
271
- }
312
+ const next = nextStop(items, panel, from, backwards);
272
313
  enter(next ?? (backwards ? last : first), backwards);
273
314
  };
274
315
 
275
316
  // The element whose native inner controls (a media element's, a date
276
- // input's segments) Tab is stepping through
277
- let steppingNative: { el: HTMLElement; backwards: boolean } | null = null;
317
+ // input's segments) Tab is stepping through, and the element of the
318
+ // dialog it stands in for (its frame element, for one in an embedded
319
+ // document)
320
+ let steppingNative: {
321
+ el: HTMLElement;
322
+ from: Element;
323
+ backwards: boolean;
324
+ } | null = null;
278
325
 
279
- const onKeyDown = (e: KeyboardEvent) => {
280
- if (!top()) return;
326
+ // Key events inside an embedded document never reach this one (#425), so
327
+ // every document of the dialog, the top one and the frames in it (#508),
328
+ // gets the handler. Escape closes the dialog. Tab moves on natively
329
+ // within a frame and is taken over at its first and last controls; `frame`
330
+ // is the frame element of an embedded `doc`.
331
+ const keyHandler = (doc: Document, frame: HTMLElement | null) => {
332
+ return (e: KeyboardEvent) => {
333
+ if (!top()) return;
281
334
 
282
- if (e.key === 'Escape') {
283
- if (!dismissible) return;
284
- e.preventDefault();
285
- e.stopPropagation();
286
- onClose();
287
- return;
288
- }
335
+ if (e.key === 'Escape') {
336
+ if (!dismissible) return;
337
+ e.preventDefault();
338
+ e.stopPropagation();
339
+ onClose();
340
+ return;
341
+ }
289
342
 
290
- if (e.key !== 'Tab') return;
291
- // The controls of a media element and the segments of a date input are
292
- // in its user-agent shadow tree, where the element stays the active
293
- // one: they step through them natively, and onFocusIn takes over where
294
- // focus leaves the element (#444, #461).
295
- const active = document.activeElement;
296
- if (hasNativeStops(active)) {
297
- steppingNative = { el: active, backwards: e.shiftKey };
298
- return;
299
- }
300
- e.preventDefault();
301
- moveFocus(active, e.shiftKey);
343
+ if (e.key !== 'Tab') return;
344
+ const active = doc.activeElement;
345
+ if (frame) {
346
+ steppingNative = null;
347
+ const inner = focusables(doc);
348
+ const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
349
+ if (edge && active !== edge && active !== doc.body) return;
350
+ }
351
+ // The controls of a media element and the segments of a date input
352
+ // are in its user-agent shadow tree, where the element stays the
353
+ // active one: they step through them natively, and onFocusIn takes
354
+ // over where focus leaves the element (#444, #461, #506).
355
+ if (hasNativeStops(active)) {
356
+ steppingNative = {
357
+ el: active,
358
+ from: frame ?? active,
359
+ backwards: e.shiftKey,
360
+ };
361
+ return;
362
+ }
363
+ e.preventDefault();
364
+ moveFocus(frame ?? active, e.shiftKey);
365
+ };
302
366
  };
303
367
  // Clicking elsewhere ends the stepping through the controls
304
368
  const onPointerDown = () => {
305
369
  steppingNative = null;
306
370
  };
307
371
 
308
- // Key events inside an embedded document never reach this one (#425).
309
- // Escape closes the dialog from there too; Tab moves on natively within
310
- // the frame and is taken over at its first and last controls.
311
- const controller = new AbortController();
312
- const { signal } = controller;
313
- const frameDocs = new Map<HTMLIFrameElement, Document>();
314
- const attachFrame = (frame: HTMLIFrameElement) => {
315
- let doc: Document | null = null;
316
- try {
317
- doc = frame.contentDocument;
318
- } catch {
319
- // Not accessible
320
- }
321
- // Already listening to this document
322
- if (!doc || frameDocs.get(frame) === doc) return;
323
- frameDocs.set(frame, doc);
324
- const onFrameKeyDown = (e: KeyboardEvent) => {
325
- if (!top()) return;
326
- if (e.key !== 'Tab') return onKeyDown(e);
327
- const inner = frameStops(doc!);
328
- const active = doc!.activeElement;
329
- const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
330
- if (!edge || active === edge || active === doc!.body) {
331
- e.preventDefault();
332
- moveFocus(frame, e.shiftKey);
333
- }
334
- };
335
- doc.addEventListener('keydown', onFrameKeyDown, { signal });
336
- };
337
- const attachFrames = () => {
338
- panel.querySelectorAll('iframe').forEach(attachFrame);
339
- };
340
- // load doesn't bubble; a frame's document is replaced when it navigates
341
- const onLoad = (e: Event) => {
342
- if (e.target instanceof HTMLIFrameElement) attachFrame(e.target);
343
- };
344
- panel.addEventListener('load', onLoad, { capture: true, signal });
345
- const frames = new MutationObserver(attachFrames);
346
- frames.observe(panel, { childList: true, subtree: true });
347
- attachFrames();
348
-
349
372
  // Focus that lands outside the dialog anyway, e.g. leaving a frame whose
350
373
  // document can't be reached, is brought back in.
351
374
  const onFocusIn = (e: FocusEvent) => {
352
375
  const target = e.target;
353
376
  if (steppingNative && target !== steppingNative.el && top()) {
354
377
  // Focus left the media controls: on to the modal's next control
355
- const { el, backwards } = steppingNative;
378
+ const { from, backwards } = steppingNative;
356
379
  steppingNative = null;
357
- moveFocus(el, backwards);
380
+ moveFocus(from, backwards);
358
381
  return;
359
382
  }
360
383
  if (!top() || !(target instanceof Node) || panel.contains(target)) return;
@@ -364,11 +387,6 @@ export function useModalFocus(
364
387
  moveFocus(null, false);
365
388
  };
366
389
 
367
- document.addEventListener('keydown', onKeyDown, { signal });
368
- document.addEventListener('pointerdown', onPointerDown, {
369
- capture: true,
370
- signal,
371
- });
372
390
  // Focus that leaves the media element for nothing (past its last control,
373
391
  // with no tab stop after it in the document) sends no focusin: the
374
392
  // modal's next control takes it at once.
@@ -378,13 +396,56 @@ export function useModalFocus(
378
396
  return;
379
397
  }
380
398
  steppingNative = null;
381
- moveFocus(pending.el, pending.backwards);
399
+ moveFocus(pending.from, pending.backwards);
400
+ };
401
+
402
+ const controller = new AbortController();
403
+ const { signal } = controller;
404
+ // The listeners of the dialog's document and of each embedded one
405
+ const listen = (doc: Document, frame: HTMLElement | null) => {
406
+ doc.addEventListener('keydown', keyHandler(doc, frame), { signal });
407
+ doc.addEventListener('pointerdown', onPointerDown, {
408
+ capture: true,
409
+ signal,
410
+ });
411
+ doc.addEventListener('focusout', onFocusOut, { signal });
382
412
  };
383
- document.addEventListener('focusout', onFocusOut, { signal });
413
+ const frameDocs = new Map<HTMLIFrameElement, Document>();
414
+ const observers: MutationObserver[] = [];
415
+ const attachFrame = (frame: HTMLIFrameElement) => {
416
+ const doc = frameDocument(frame);
417
+ // Already listening to this document
418
+ if (!doc || frameDocs.get(frame) === doc) return;
419
+ frameDocs.set(frame, doc);
420
+ listen(doc, frame);
421
+ watchFrames(doc);
422
+ };
423
+ // Attach to the frames in `root`, now and as they come and navigate.
424
+ // load doesn't bubble; a frame's document is replaced when it navigates
425
+ const watchFrames = (root: HTMLElement | Document) => {
426
+ const attachAll = () =>
427
+ root.querySelectorAll('iframe').forEach(attachFrame);
428
+ root.addEventListener(
429
+ 'load',
430
+ (e) => {
431
+ if (e.target instanceof Node && isFrame(e.target as Element)) {
432
+ attachFrame(e.target as HTMLIFrameElement);
433
+ }
434
+ },
435
+ { capture: true, signal },
436
+ );
437
+ const observer = new MutationObserver(attachAll);
438
+ observer.observe(root, { childList: true, subtree: true });
439
+ observers.push(observer);
440
+ attachAll();
441
+ };
442
+ watchFrames(panel);
443
+
444
+ listen(document, null);
384
445
  document.addEventListener('focusin', onFocusIn, { signal });
385
446
  return () => {
386
447
  controller.abort();
387
- frames.disconnect();
448
+ observers.forEach((o) => o.disconnect());
388
449
  };
389
450
  }, [dismissible, onClose]);
390
451
  }
package/src/index.tsx CHANGED
@@ -76,6 +76,15 @@ function orStop<T>(parse: () => T, where = ''): T {
76
76
  }
77
77
  }
78
78
 
79
+ /**
80
+ * What reading arguments depends on, with the macros and widgets known now:
81
+ * the declared parameters of macros and what the parameters of widgets hold.
82
+ * (The markup and the variable references are read by the same.)
83
+ */
84
+ function knownParameters() {
85
+ return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
86
+ }
87
+
79
88
  /**
80
89
  * The undeclared variables the passages refer to, with the macros known now:
81
90
  * the input macros that bind a variable (registered by author JS or
@@ -88,7 +97,12 @@ function variableErrors(
88
97
  const storeVarMacros = getMacroRegistry()
89
98
  .filter((m) => m.storeVar)
90
99
  .map((m) => m.name);
91
- return validatePassages(storyData.passages, schema, storeVarMacros);
100
+ return validatePassages(
101
+ storyData.passages,
102
+ schema,
103
+ storeVarMacros,
104
+ knownParameters(),
105
+ );
92
106
  }
93
107
 
94
108
  /**
@@ -100,12 +114,11 @@ function markupErrors(
100
114
  storyData: StoryData,
101
115
  only: (passage: MarkupPassage) => boolean,
102
116
  ): string[] {
103
- const macros = getMacroRegistry();
104
117
  return validateMarkup(storyData.passages.values(), {
105
118
  isKnownMacro: (name) =>
106
119
  !!getMacro(name) || isSubMacro(name) || !!getWidget(name),
107
- macroNames: macros.map((m) => m.name),
108
- parametersOf: parameterLookup([...macros, ...widgetMacros()]),
120
+ macroNames: getMacroRegistry().map((m) => m.name),
121
+ parametersOf: knownParameters(),
109
122
  only,
110
123
  }).map(formatDiagnostic);
111
124
  }
@@ -265,13 +278,10 @@ export function boot() {
265
278
 
266
279
  render(<App />, root);
267
280
 
268
- const pending = getReadyPromise();
269
- if (pending) {
270
- // The event follows the render of the passage the story is at (#430)
271
- pending.then(passageShown).then(() => {
272
- document.dispatchEvent(new CustomEvent(':storyready'));
273
- });
274
- } else {
281
+ // The event follows the render of the passage the story is at: after
282
+ // `ready()` when rendering is deferred (#430), and after a `{goto}` made
283
+ // while the first passage rendered has shown its destination (#505)
284
+ (getReadyPromise() ?? Promise.resolve()).then(passageShown).then(() => {
275
285
  document.dispatchEvent(new CustomEvent(':storyready'));
276
- }
286
+ });
277
287
  }