@rohal12/spindle 0.64.11 → 0.64.13

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": "@rohal12/spindle",
3
- "version": "0.64.11",
3
+ "version": "0.64.13",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -108,14 +108,14 @@
108
108
  "@vitest/coverage-v8": "^5.0.3",
109
109
  "codemirror": "^5.65.21",
110
110
  "fake-indexeddb": "^6.2.5",
111
- "fallow": "3.34.1",
111
+ "fallow": "3.36.0",
112
112
  "fast-check": "^4.10.2",
113
113
  "happy-dom": "^21.0.4",
114
114
  "husky": "^9.1.7",
115
115
  "js-yaml": "^5.4.3",
116
- "jscpd": "5.4.1",
116
+ "jscpd": "5.4.2",
117
117
  "lint-staged": "^17.6.0",
118
- "peggy": "5.1.0",
118
+ "peggy": "5.1.1",
119
119
  "playwright": "^1.64.0",
120
120
  "prettier": "^3.9.9",
121
121
  "typescript": "^7.0.2",
@@ -246,7 +246,7 @@ async function formatLf(
246
246
  if (region.type === 'script') {
247
247
  // Same-line <script>…</script> — leave as written
248
248
  if (region.lines.length === 1) {
249
- lines.push(...region.lines);
249
+ for (const line of region.lines) lines.push(line);
250
250
  continue;
251
251
  }
252
252
  // Inline <script> — format JS content between tags
@@ -259,7 +259,7 @@ async function formatLf(
259
259
  // Without Prettier, where it fails, or where it changed a Spindle
260
260
  // token (`{$a}` is an object literal to it), the region stays as written
261
261
  if (formatted === undefined || !sameSpindleTokens(innerCode, formatted)) {
262
- lines.push(...region.lines);
262
+ for (const line of region.lines) lines.push(line);
263
263
  continue;
264
264
  }
265
265
  lines.push(region.lines[0]!);
@@ -277,7 +277,7 @@ async function formatLf(
277
277
 
278
278
  if (region.type === 'svg') {
279
279
  // SVG block — leave untouched (Prettier would break rendering)
280
- lines.push(...region.lines);
280
+ for (const line of region.lines) lines.push(line);
281
281
  continue;
282
282
  }
283
283
 
@@ -293,7 +293,7 @@ async function formatLf(
293
293
  ) {
294
294
  for (let i = 0; i < region.lines.length; i++)
295
295
  preservedLines.add(lines.length + i);
296
- lines.push(...region.lines);
296
+ for (const line of region.lines) lines.push(line);
297
297
  continue;
298
298
  }
299
299
  // HTML block — placeholder substitution + Prettier
@@ -302,7 +302,7 @@ async function formatLf(
302
302
  // A later whole-line Spindle token may hide an SVG marker. Check
303
303
  // before that pass so a literal marker cannot stand in for it.
304
304
  if (!placeholdersIntact(svgPlaceholdered, svgTokens, SVG_PLACEHOLDERS)) {
305
- lines.push(...region.lines);
305
+ for (const line of region.lines) lines.push(line);
306
306
  continue;
307
307
  }
308
308
  const { text: placeholdered, tokens } =
@@ -320,7 +320,7 @@ async function formatLf(
320
320
  !placeholdersIntact(formatted, tokens, SPINDLE_PLACEHOLDERS) ||
321
321
  !placeholdersIntact(formatted, svgTokens, SVG_PLACEHOLDERS)
322
322
  ) {
323
- lines.push(...region.lines);
323
+ for (const line of region.lines) lines.push(line);
324
324
  continue;
325
325
  }
326
326
  // A token's line breaks are its payload: keep them out of the line steps below
@@ -722,7 +722,7 @@ function wrapLines(
722
722
  }
723
723
  // Keep a Markdown hard break on the last wrapped line
724
724
  if (line.endsWith(' ')) wrapped[wrapped.length - 1] += ' ';
725
- result.push(...wrapped);
725
+ for (const line of wrapped) result.push(line);
726
726
  }
727
727
 
728
728
  return result;
@@ -1,26 +1,13 @@
1
+ import { tokenizeMarkupTolerant } from '../markup/parse';
2
+ import type { HtmlToken } from '../markup/tokens';
3
+ import { sourceLines } from './source-lines';
4
+
1
5
  /** A run of a passage body that is formatted as one kind of content. */
2
6
  export interface Region {
3
7
  type: 'spindle' | 'html' | 'script' | 'svg';
4
8
  lines: string[];
5
9
  }
6
10
 
7
- const VOID_ELEMENTS = new Set([
8
- 'area',
9
- 'base',
10
- 'br',
11
- 'col',
12
- 'embed',
13
- 'hr',
14
- 'img',
15
- 'input',
16
- 'link',
17
- 'meta',
18
- 'param',
19
- 'source',
20
- 'track',
21
- 'wbr',
22
- ]);
23
-
24
11
  /**
25
12
  * Segment a passage body into regions: spindle (markdown/macros), html blocks, script blocks.
26
13
  */
@@ -32,6 +19,26 @@ export function segmentRegions(body: string): Region[] {
32
19
  }
33
20
  if (lines.length === 0) return [];
34
21
 
22
+ // Count only real tags: comments, attributes and macro strings can all
23
+ // contain tag-shaped text. Index once, including the opening region line.
24
+ const tags: HtmlToken[][] = lines.map(() => []);
25
+ const tagEndLines = lines.map((_, line) => line);
26
+ const lineAt = sourceLines(body);
27
+ for (const token of tokenizeMarkupTolerant(body).tokens) {
28
+ if (token.type !== 'html') continue;
29
+ const line = lineAt(token.start);
30
+ tags[line]!.push(token);
31
+ tagEndLines[line] = Math.max(tagEndLines[line]!, lineAt(token.end - 1));
32
+ }
33
+ const depthOnLine = (line: number, name: string) =>
34
+ tags[line]!.reduce(
35
+ (depth, token) =>
36
+ token.tag.toLowerCase() === name && !token.isSelfClose
37
+ ? depth + (token.isClose ? -1 : 1)
38
+ : depth,
39
+ 0,
40
+ );
41
+
35
42
  const regions: Region[] = [];
36
43
  let i = 0;
37
44
 
@@ -63,16 +70,13 @@ export function segmentRegions(body: string): Region[] {
63
70
  const tagMatch = trimmed.match(/^<([a-zA-Z][\w-]*)/);
64
71
  const tagName = tagMatch![1]!.toLowerCase();
65
72
 
66
- // Skip void elements on their own line — not a multi-line block
67
- if (VOID_ELEMENTS.has(tagName) && !lines[i + 1]?.trim().startsWith('<')) {
68
- pushSpindleLine(regions, line);
69
- i++;
70
- continue;
71
- }
72
-
73
- // Check if this is truly multi-line: does the tag close on the same line?
74
- const selfClosing = new RegExp(`</${tagName}\\s*>`, 'i');
75
- if (selfClosing.test(trimmed)) {
73
+ // All same-name openers must close, even when an inner one closes on
74
+ // the opening line. Self-closing tags do not increase the depth.
75
+ let depth = depthOnLine(i, tagName);
76
+ // A closed or void tag can still span lines. Never send its attribute
77
+ // continuation through prose indentation or split a closing tag.
78
+ let endLine = tagEndLines[i]!;
79
+ if (depth <= 0 && endLine === i) {
76
80
  pushSpindleLine(regions, line);
77
81
  i++;
78
82
  continue;
@@ -80,17 +84,11 @@ export function segmentRegions(body: string): Region[] {
80
84
 
81
85
  // Multi-line HTML block
82
86
  const htmlLines: string[] = [line];
83
- let depth = 1;
84
87
  i++;
85
- while (i < lines.length && depth > 0) {
88
+ while (i < lines.length && (depth > 0 || i <= endLine)) {
86
89
  htmlLines.push(lines[i]!);
87
- const opens = (
88
- lines[i]!.match(new RegExp(`<${tagName}(?:[\\s>]|$)`, 'gi')) ?? []
89
- ).length;
90
- const closes = (
91
- lines[i]!.match(new RegExp(`</${tagName}\\s*>`, 'gi')) ?? []
92
- ).length;
93
- depth += opens - closes;
90
+ endLine = Math.max(endLine, tagEndLines[i]!);
91
+ depth += depthOnLine(i, tagName);
94
92
  i++;
95
93
  }
96
94
  regions.push({ type: 'html', lines: htmlLines });
@@ -55,13 +55,36 @@ function tabIndexAttr(el: HTMLElement): number | null {
55
55
  return parseInt(raw, 10);
56
56
  }
57
57
 
58
+ /** Eligible radio stops in one DOM tree, including external form controls. */
59
+ function radioTabStops(root: ParentNode): Set<HTMLInputElement> {
60
+ const groups = new Map<
61
+ HTMLFormElement | null,
62
+ Map<string, HTMLInputElement>
63
+ >();
64
+ for (const radio of root.querySelectorAll<HTMLInputElement>(
65
+ 'input[type="radio"]',
66
+ )) {
67
+ if (!radio.name || (tabIndexAttr(radio) ?? 0) < 0 || !isAvailable(radio)) {
68
+ continue;
69
+ }
70
+ let names = groups.get(radio.form);
71
+ if (!names) groups.set(radio.form, (names = new Map()));
72
+ const stop = names.get(radio.name);
73
+ // First eligible checked member, otherwise first eligible member (#390).
74
+ if (!stop || (!stop.checked && radio.checked)) names.set(radio.name, radio);
75
+ }
76
+ return new Set([...groups.values()].flatMap((names) => [...names.values()]));
77
+ }
78
+
79
+ type RadioStops = Map<Node, Set<HTMLInputElement>>;
80
+
58
81
  /**
59
82
  * Whether the tab key can reach `el`, an available element (see
60
83
  * isAvailable): a negative tabindex only allows scripted focus, and of a
61
84
  * radio group the browser tabs to the checked member only (the first one
62
85
  * when none is checked), of the members it can reach.
63
86
  */
64
- function isTabStop(el: HTMLElement): boolean {
87
+ function isTabStop(el: HTMLElement, radioStops: RadioStops): boolean {
65
88
  const tabIndex = tabIndexAttr(el);
66
89
  if (tabIndex !== null && tabIndex < 0) return false;
67
90
  // Only an editing host takes focus of its own, not `contenteditable="false"`
@@ -89,22 +112,15 @@ function isTabStop(el: HTMLElement): boolean {
89
112
  // another realm's classes
90
113
  const input = el as HTMLInputElement;
91
114
  if (el.localName === 'input' && input.type === 'radio' && input.name) {
92
- const group = Array.from(
93
- // Form ownership does not imply DOM ancestry: `form="id"` controls
94
- // elsewhere in the same tree belong to the group too (#688).
95
- (el.getRootNode() as ParentNode).querySelectorAll<HTMLInputElement>(
96
- 'input[type="radio"]',
97
- ),
98
- ).filter(
99
- (r) =>
100
- r.name === input.name &&
101
- r.form === input.form &&
102
- // Of the members Tab can reach (#390)
103
- (tabIndexAttr(r) ?? 0) >= 0 &&
104
- isAvailable(r),
105
- );
106
- const stop = group.find((r) => r.checked) ?? group[0];
107
- return el === stop;
115
+ const tree = el.getRootNode();
116
+ let stops = radioStops.get(tree);
117
+ if (!stops) {
118
+ // Form ownership is independent of DOM ancestry (#688). Index the
119
+ // entire tree once, shared across shadow/slot tabindex scopes (#718).
120
+ stops = radioTabStops(tree as ParentNode);
121
+ radioStops.set(tree, stops);
122
+ }
123
+ return stops.has(input);
108
124
  }
109
125
  return true;
110
126
  }
@@ -114,7 +130,10 @@ function isTabStop(el: HTMLElement): boolean {
114
130
  * order Tab visits them: positive tabindexes first, ascending, then the
115
131
  * others in document order.
116
132
  */
117
- function focusables(root: ParentNode): HTMLElement[] {
133
+ function focusables(
134
+ root: ParentNode,
135
+ radioStops: RadioStops = new Map(),
136
+ ): HTMLElement[] {
118
137
  // Each shadow host/slot owns a separate tabindex scope. Sort the owners in
119
138
  // this scope, then expand their contents in place, as native Tab does.
120
139
  const scopes: { el: HTMLElement; stops: HTMLElement[] }[] = [];
@@ -122,7 +141,8 @@ function focusables(root: ParentNode): HTMLElement[] {
122
141
  for (const element of composedChildren(parent)) {
123
142
  const el = element as HTMLElement;
124
143
  const nested = el.shadowRoot ?? (el.localName === 'slot' ? el : null);
125
- const stop = el.matches(FOCUSABLE) && isAvailable(el) && isTabStop(el);
144
+ const stop =
145
+ el.matches(FOCUSABLE) && isAvailable(el) && isTabStop(el, radioStops);
126
146
  if (nested) {
127
147
  // A visibility:hidden host can contain explicitly visible controls.
128
148
  // Each stop checks its own visibility and its ancestors' subtree gates.
@@ -131,7 +151,7 @@ function focusables(root: ParentNode): HTMLElement[] {
131
151
  el,
132
152
  stops: [
133
153
  ...(stop && !el.shadowRoot?.delegatesFocus ? [el] : []),
134
- ...focusables(nested),
154
+ ...focusables(nested, radioStops),
135
155
  ],
136
156
  });
137
157
  } else {
package/src/js-lexer.ts CHANGED
@@ -371,7 +371,15 @@ function tokenizerAt(
371
371
  goal: JsGoal,
372
372
  { onComment, afterOperand = false }: TokenizerOptions = {},
373
373
  ): ParserState {
374
- const options = onComment ? { ...OPTIONS, onComment } : OPTIONS;
374
+ // Consumers use absolute offsets, never Acorn's token/node locations.
375
+ // Its error locations are computed separately from the source. Supplying
376
+ // a local starting location avoids its backwards newline-prefix search
377
+ // for every expression on a long passage line.
378
+ const options = {
379
+ ...OPTIONS,
380
+ startLocation: { line: 1, column: 0 },
381
+ onComment,
382
+ };
375
383
  const p = new SigilParser(options, src, start) as unknown as ParserState;
376
384
  if (goal === 'expression') p.type = tt.parenL;
377
385
  if (afterOperand) p.exprAllowed = false;
@@ -180,7 +180,7 @@ export function widgetDefinitions(
180
180
  open[open.length - 1]!.isBlock = true;
181
181
  }
182
182
  }
183
- done.push(...open);
183
+ for (const def of open) done.push(def);
184
184
  const defs: WidgetDefinition[] = [];
185
185
  for (const { token, isBlock, closeStart } of done) {
186
186
  try {
@@ -199,7 +199,8 @@ export function widgetDefinitions(
199
199
  // The {widget} macro reports a definition it cannot read
200
200
  }
201
201
  }
202
- found.push(...defs.sort((a, b) => a.start - b.start));
202
+ defs.sort((a, b) => a.start - b.start);
203
+ for (const def of defs) found.push(def);
203
204
  }
204
205
  return found;
205
206
  };