@rohal12/spindle 0.64.31 → 0.64.33

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.31",
3
+ "version": "0.64.33",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -55,7 +55,11 @@ import {
55
55
  type PassageTarget,
56
56
  } from './components/macros/macro-args';
57
57
  import { subMacroParameters } from './components/macros/option-utils';
58
- import { readPassageBody, splitArgSpans } from './components/macros/arg-utils';
58
+ import {
59
+ readPassageBody,
60
+ readWholeQuoted,
61
+ splitArgSpans,
62
+ } from './components/macros/arg-utils';
59
63
  import { effectiveNamedDefinitions, NameMap } from './utils/macro-names';
60
64
  import { hasOwn } from './utils/namespace';
61
65
  import { isBuiltinBlockMacro, isRawMacro } from './markup/ast';
@@ -111,13 +115,14 @@ export interface PieceBase {
111
115
  * For the code or text of a quoted string with escapes (a `\"`), whose
112
116
  * characters are not where `offset` plus their index says: the offset of
113
117
  * each character in the source, and of the end of the text, so that
114
- * `sourceOffsets[i]` is where character `i` of `code` or `text` is. Absent
118
+ * `sourceOffsets[i]` is where character `i` of `code`, `text` or a passage
119
+ * `name` is. The final entry maps the end boundary. Absent
115
120
  * when `offset + i` is (see {@link pieceOffset}).
116
121
  */
117
122
  sourceOffsets?: readonly number[];
118
123
  }
119
124
 
120
- /** Where character `index` of the code or text of `piece` is in the source. */
125
+ /** Where boundary `index` of a piece's code, text or name is in the source. */
121
126
  export function pieceOffset(piece: PieceBase, index: number): number {
122
127
  return piece.sourceOffsets?.[index] ?? piece.offset + index;
123
128
  }
@@ -128,7 +133,9 @@ function extentOf(piece: Piece): number {
128
133
  ? piece.code.length
129
134
  : piece.kind === 'text'
130
135
  ? piece.text.length
131
- : piece.length;
136
+ : piece.kind === 'passage'
137
+ ? piece.name.length
138
+ : piece.length;
132
139
  }
133
140
 
134
141
  /** A piece found in a markup that is written out, for an error to point at. */
@@ -167,6 +174,12 @@ interface MacroPiece extends LabeledPiece {
167
174
  export interface PassagePiece extends MacroPiece {
168
175
  kind: 'passage';
169
176
  name: string;
177
+ /**
178
+ * Decoded name boundaries in the original source, including the end before
179
+ * closing quotes. Quotes/escapes do not change the whole-argument offset
180
+ * and length. Both UTF-16 units of a code-point escape map to its start.
181
+ */
182
+ sourceOffsets?: readonly number[];
170
183
  /** A known navigation target, rather than included/dialog content. */
171
184
  navigation?: true;
172
185
  }
@@ -383,6 +396,7 @@ export function parameterLookup(
383
396
  ]).map((macro) => [macro.name, macro]),
384
397
  );
385
398
  lookup.pairing = {
399
+ isStandalone: (name) => widgets.has(name) || sources.get(name) === 'user',
386
400
  isBlock: (name) =>
387
401
  definitions.get(name)?.block ?? isBuiltinBlockMacro(name),
388
402
  isRaw: (name) => isRawMacro(name, widgets.has(name)),
@@ -530,13 +544,26 @@ export function* codeAndText(
530
544
  if (close > t + 1) {
531
545
  const text = src.slice(token.end, tokens[close]!.start);
532
546
  const written = text.trim();
547
+ const at = token.end + text.indexOf(written);
548
+ const nameValue = readPassageBody(written);
549
+ const sourceOffsets =
550
+ readWholeQuoted(written) !== null
551
+ ? escapeOffsets(
552
+ written.slice(1, -1),
553
+ at + 1,
554
+ nameValue,
555
+ 'quotes',
556
+ true,
557
+ )
558
+ : undefined;
533
559
  yield {
534
560
  kind: 'passage',
535
- name: readPassageBody(written),
536
- offset: token.end + text.indexOf(written),
561
+ name: nameValue,
562
+ offset: at,
537
563
  length: written.length,
538
564
  macro: name,
539
565
  label: src.slice(token.start, token.end),
566
+ ...(sourceOffsets && { sourceOffsets }),
540
567
  };
541
568
  }
542
569
  }
@@ -702,7 +729,7 @@ function nestedPiece(
702
729
  ): Piece {
703
730
  const offset = toRoot(piece.offset);
704
731
  const nested = { offset, nested: true as const, where };
705
- if (piece.kind === 'passage' || piece.kind === 'argument-error') {
732
+ if (piece.kind === 'argument-error') {
706
733
  const length = toRoot(piece.offset + piece.length) - offset;
707
734
  return { ...piece, ...nested, length };
708
735
  }
@@ -712,9 +739,15 @@ function nestedPiece(
712
739
  : toRoot(piece.offset + extent) - offset !== extent
713
740
  ? Array.from({ length: extent + 1 }, (_, i) => toRoot(piece.offset + i))
714
741
  : undefined;
715
- return sourceOffsets
742
+ const mapped = sourceOffsets
716
743
  ? { ...piece, ...nested, sourceOffsets }
717
744
  : { ...piece, ...nested };
745
+ return mapped.kind === 'passage'
746
+ ? {
747
+ ...mapped,
748
+ length: toRoot(piece.offset + mapped.length) - offset,
749
+ }
750
+ : mapped;
718
751
  }
719
752
 
720
753
  /** How the string of an argument is unescaped, which its escapes depend on. */
@@ -754,13 +787,15 @@ function escapeAt(
754
787
  * written as `raw` from `at` on (its escapes are those of `escapes`), is in
755
788
  * the source, and where the text ends. A character that an escape stands for
756
789
  * is where the escape begins. None when the text is where its length says, or
757
- * is not that string.
790
+ * is not that string. With `includeLinear`, return the map even without
791
+ * escapes (a passage piece's offset includes the opening quote).
758
792
  */
759
793
  export function escapeOffsets(
760
794
  raw: string,
761
795
  at: number,
762
796
  value: string,
763
797
  escapes: Escapes,
798
+ includeLinear = false,
764
799
  ): number[] | undefined {
765
800
  const offsets: number[] = [];
766
801
  let escaped = false;
@@ -778,8 +813,16 @@ export function escapeOffsets(
778
813
  escaped = true;
779
814
  i += escape.length;
780
815
  }
816
+ // A trailing line continuation emits no character but still moves the
817
+ // decoded string's end boundary to the closing quote.
818
+ while (raw[i] === '\\') {
819
+ const escape = escapeAt(raw, i, escapes);
820
+ if (!escape || escape.text.length !== 0) break;
821
+ escaped = true;
822
+ i += escape.length;
823
+ }
781
824
  offsets.push(at + i);
782
- return escaped ? offsets : undefined;
825
+ return escaped || includeLinear ? offsets : undefined;
783
826
  }
784
827
 
785
828
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
@@ -894,13 +937,24 @@ function* valuePieces(
894
937
  const [start, end] = span;
895
938
  const written = args.slice(start, end);
896
939
  /** The name as written (quotes included), at the argument. */
897
- const passage = (passageName: string): PassagePiece => ({
940
+ const passage = (
941
+ passageName: string,
942
+ at: number,
943
+ mode: Escapes = escapes,
944
+ ): PassagePiece => ({
898
945
  kind: 'passage',
899
946
  name: passageName,
900
947
  offset: offset + start,
901
948
  length: end - start,
902
949
  macro: name,
903
950
  label,
951
+ sourceOffsets: escapeOffsets(
952
+ args.slice(at - offset),
953
+ at,
954
+ passageName,
955
+ mode,
956
+ true,
957
+ ),
904
958
  ...(navigation.includes(param.name) && { navigation: true as const }),
905
959
  });
906
960
  const goal = codeGoal(param);
@@ -908,7 +962,7 @@ function* valuePieces(
908
962
  // A name written out, else an expression naming one
909
963
  const target = passageTarget(value);
910
964
  if (target.kind === 'name') {
911
- yield passage(target.name);
965
+ yield passage(target.name, offset + start + 1, 'javascript');
912
966
  continue;
913
967
  }
914
968
  }
@@ -949,7 +1003,7 @@ function* valuePieces(
949
1003
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
950
1004
  yield piece;
951
1005
  } else if (holds === 'passage') {
952
- yield passage(value);
1006
+ yield passage(value, at);
953
1007
  } else if (holds === 'markup') {
954
1008
  const piece = textPiece(
955
1009
  value,
@@ -13,12 +13,16 @@ defineMacro({
13
13
  render(_props, ctx) {
14
14
  const label = ctx.args.label ?? '';
15
15
 
16
- const action = useVariableAction(ctx, {
17
- type: 'checkbox',
18
- label: label || ctx.varName || '',
19
- value: !!ctx.value,
20
- perform: (v) => ctx.setValue!(v !== undefined ? !!v : !ctx.getValue!()),
21
- });
16
+ const action = useVariableAction(
17
+ ctx,
18
+ {
19
+ type: 'checkbox',
20
+ label: label || ctx.varName || '',
21
+ value: !!ctx.value,
22
+ perform: (v) => ctx.setValue!(v !== undefined ? !!v : !ctx.getValue!()),
23
+ },
24
+ (control) => (control as HTMLInputElement).checked,
25
+ );
22
26
 
23
27
  return (
24
28
  <label
@@ -13,14 +13,18 @@ defineMacro({
13
13
  render({ children = [] }, ctx) {
14
14
  const options = ctx.extractOptions(children);
15
15
 
16
- const action = useVariableAction(ctx, {
17
- type: 'listbox',
18
- label: ctx.varName!,
19
- options,
20
- perform: (v) => {
21
- if (v !== undefined) ctx.setValue!(String(v));
16
+ const action = useVariableAction(
17
+ ctx,
18
+ {
19
+ type: 'listbox',
20
+ label: ctx.varName!,
21
+ options,
22
+ perform: (v) => {
23
+ if (v !== undefined) ctx.setValue!(String(v));
24
+ },
22
25
  },
23
- });
26
+ (control) => control.value,
27
+ );
24
28
 
25
29
  return (
26
30
  <select
@@ -17,13 +17,32 @@ defineMacro({
17
17
  const label = ctx.args.label ?? '';
18
18
  // One group per variable in each view (see ViewScopeContext)
19
19
  const view = ctx.hooks.useContext(ViewScopeContext);
20
+ const initialValue = ctx.hooks.useRef(ctx.value);
20
21
 
21
- const action = useVariableAction(ctx, {
22
- type: 'radiobutton',
23
- key: `$${ctx.varName}:${radioValue}`,
24
- label: label || radioValue,
25
- perform: () => ctx.setValue!(radioValue),
26
- });
22
+ const action = useVariableAction(
23
+ ctx,
24
+ {
25
+ type: 'radiobutton',
26
+ key: `$${ctx.varName}:${radioValue}`,
27
+ label: label || radioValue,
28
+ perform: () => ctx.setValue!(radioValue),
29
+ },
30
+ (control) => {
31
+ const radio = control as HTMLInputElement;
32
+ const group = radio.form?.elements.namedItem(radio.name) as
33
+ RadioNodeList | HTMLInputElement | null;
34
+ const selected =
35
+ group &&
36
+ ('length' in group
37
+ ? (Array.from(group).find(
38
+ (node) => (node as HTMLInputElement).checked,
39
+ ) as HTMLInputElement | undefined)
40
+ : group.checked
41
+ ? group
42
+ : undefined);
43
+ return selected ? selected.value : initialValue.current;
44
+ },
45
+ );
27
46
 
28
47
  return (
29
48
  <label
@@ -1,5 +1,8 @@
1
1
  import { h } from 'preact';
2
+ import { useCallback, useLayoutEffect, useRef, useState } from 'preact/hooks';
2
3
  import { defineMacro, type MacroContext } from '../../define-macro';
4
+ import { useStoryStore } from '../../store';
5
+ import { subscribeVariableWrites } from '../../utils/variable-writes';
3
6
  import {
4
7
  actionAttributes,
5
8
  useControlAction,
@@ -14,24 +17,195 @@ export const VARIABLE_PARAMETER = {
14
17
  required: true,
15
18
  } as const;
16
19
 
20
+ type FormControl = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
21
+
22
+ interface ResetReader {
23
+ element: FormControl;
24
+ prepare: () => {
25
+ read: (snapshot: FormControl) => () => void;
26
+ off: () => void;
27
+ };
28
+ }
29
+ const formResets = new WeakMap<
30
+ HTMLFormElement,
31
+ {
32
+ readers: Set<ResetReader>;
33
+ reset: (event: Event) => void;
34
+ }
35
+ >();
36
+
37
+ /** Read every reset value before any binding write can trigger a rerender. */
38
+ function subscribeFormReset(
39
+ form: HTMLFormElement,
40
+ read: ResetReader,
41
+ ): () => void {
42
+ let subscription = formResets.get(form);
43
+ if (!subscription) {
44
+ const readers = new Set<ResetReader>();
45
+ const reset = (event: Event) => {
46
+ const pending = Array.from(readers, (reader) => ({
47
+ reader,
48
+ ...reader.prepare(),
49
+ }));
50
+ // Trusted reset events can run microtasks before their default action.
51
+ // A task sees the native values and the final cancellation state.
52
+ setTimeout(() => {
53
+ for (const { off } of pending) off();
54
+ if (event.defaultPrevented) return;
55
+ // An unrelated store write can already have rerendered the live
56
+ // controls. Let a detached form recover their native defaults,
57
+ // including number sanitization, select fallback and radio groups.
58
+ const snapshot = form.ownerDocument.createElement('form');
59
+ const restoreDefaults = snapshot.reset.bind(snapshot);
60
+ const controls = pending.map(({ reader, read }) => {
61
+ const element = reader.element.cloneNode(true) as FormControl;
62
+ element.removeAttribute('form');
63
+ snapshot.appendChild(element);
64
+ return { read, element };
65
+ });
66
+ restoreDefaults();
67
+ const commits = controls.map(({ read, element }) => read(element));
68
+ for (const commit of commits) commit();
69
+ }, 0);
70
+ };
71
+ subscription = { readers, reset };
72
+ formResets.set(form, subscription);
73
+ form.addEventListener('reset', subscription.reset);
74
+ }
75
+ const { readers, reset } = subscription;
76
+ readers.add(read);
77
+ return () => {
78
+ readers.delete(read);
79
+ if (readers.size === 0) {
80
+ form.removeEventListener('reset', reset);
81
+ formResets.delete(form);
82
+ }
83
+ };
84
+ }
85
+
86
+ /** Native defaults belong to the binding's initial rendered control value. */
87
+ function setResetDefault(control: FormControl): void {
88
+ if (control.tagName === 'SELECT') {
89
+ const options = Array.from((control as HTMLSelectElement).options);
90
+ const selected = options.map((option) => option.selected);
91
+ options.forEach((option, i) => (option.defaultSelected = selected[i]!));
92
+ } else if (
93
+ control.tagName === 'INPUT' &&
94
+ ['checkbox', 'radio'].includes((control as HTMLInputElement).type)
95
+ ) {
96
+ (control as HTMLInputElement).defaultChecked = (
97
+ control as HTMLInputElement
98
+ ).checked;
99
+ } else {
100
+ (control as HTMLInputElement | HTMLTextAreaElement).defaultValue =
101
+ control.value;
102
+ }
103
+ }
104
+
17
105
  /**
18
106
  * Register the automation action of a macro bound to a story variable: keyed
19
107
  * by the variable (or `key`), with the variable's value unless `action`
20
108
  * gives another.
21
109
  */
22
110
  export function useVariableAction(
23
- ctx: Pick<MacroContext, 'id' | 'varName' | 'value'>,
111
+ ctx: Pick<MacroContext, 'id' | 'varName' | 'value' | 'setValue' | 'getValue'>,
24
112
  action: Omit<UseActionOptions, 'key' | 'authorId' | 'variable'> & {
25
113
  key?: string;
26
114
  },
115
+ onReset?: (control: FormControl) => unknown,
27
116
  ): ReturnType<typeof useControlAction> {
28
- return useControlAction({
117
+ const registered = useControlAction({
29
118
  key: `$${ctx.varName}`,
30
119
  authorId: ctx.id,
31
120
  variable: ctx.varName,
32
121
  value: ctx.value,
33
122
  ...action,
34
123
  });
124
+ const control = useRef<FormControl | null>(null);
125
+ const [, refresh] = useState(0);
126
+ const initialized = useRef<FormControl | null>(null);
127
+ const subscription = useRef<{
128
+ element: FormControl;
129
+ form: HTMLFormElement;
130
+ off: () => void;
131
+ } | null>(null);
132
+ const resetValue = useRef({
133
+ read: onReset,
134
+ set: ctx.setValue,
135
+ get: ctx.getValue,
136
+ name: ctx.varName,
137
+ });
138
+ resetValue.current = {
139
+ read: onReset,
140
+ set: ctx.setValue,
141
+ get: ctx.getValue,
142
+ name: ctx.varName,
143
+ };
144
+ const ref = useCallback(
145
+ (element: Element | null) => {
146
+ control.current = element as FormControl | null;
147
+ registered.ref(element);
148
+ },
149
+ [registered.ref],
150
+ );
151
+ // Reattach after commits in case the control's form owner changed.
152
+ useLayoutEffect(() => {
153
+ const element = control.current;
154
+ const form = element?.form;
155
+ if (
156
+ subscription.current?.element === element &&
157
+ subscription.current?.form === form
158
+ )
159
+ return;
160
+ subscription.current?.off();
161
+ subscription.current = null;
162
+ if (!element || !onReset) return;
163
+ if (initialized.current !== element) {
164
+ setResetDefault(element);
165
+ initialized.current = element;
166
+ }
167
+ if (!form) return;
168
+ subscription.current = {
169
+ element,
170
+ form,
171
+ off: subscribeFormReset(form, {
172
+ element,
173
+ prepare: () => {
174
+ const before = resetValue.current.get!();
175
+ let changed = false;
176
+ const offWrite = subscribeVariableWrites(
177
+ resetValue.current.name!.split('.'),
178
+ () => (changed = true),
179
+ );
180
+ const offStore = useStoryStore.subscribe(() => {
181
+ changed ||= !Object.is(resetValue.current.get!(), before);
182
+ });
183
+ return {
184
+ off: () => {
185
+ offWrite();
186
+ offStore();
187
+ },
188
+ read: (snapshot) => {
189
+ // Decide before any reset commits, including other controls of
190
+ // this binding. No-op writes and changes away and back count too.
191
+ const value = changed
192
+ ? undefined
193
+ : resetValue.current.read!(snapshot);
194
+ return () => {
195
+ if (control.current !== element || element.form !== form)
196
+ return;
197
+ // A trusted reset may have undone a handler's earlier render.
198
+ if (changed) refresh((version) => version + 1);
199
+ else resetValue.current.set!(value);
200
+ };
201
+ },
202
+ };
203
+ },
204
+ }),
205
+ };
206
+ });
207
+ useLayoutEffect(() => () => subscription.current?.off(), []);
208
+ return { ...registered, ref };
35
209
  }
36
210
 
37
211
  /**
@@ -56,13 +230,7 @@ export function defineInputMacro(
56
230
  { name: 'placeholder', type: 'string', holds: 'text' },
57
231
  ],
58
232
  render(_props, ctx) {
59
- const placeholder = ctx.args.placeholder ?? '';
60
-
61
- const action = useVariableAction(ctx, {
62
- type: name,
63
- label: placeholder || ctx.varName!,
64
- perform: (v) => ctx.setValue!(toValue(v)),
65
- });
233
+ const { placeholder = '' } = ctx.args;
66
234
 
67
235
  // What the reader last typed. A number input reports an unfinished
68
236
  // number ("-", "2e") as an empty value, so the text is kept for as
@@ -76,6 +244,19 @@ export function defineInputMacro(
76
244
  ? typed.current
77
245
  : display(ctx.value);
78
246
 
247
+ const action = useVariableAction(
248
+ ctx,
249
+ {
250
+ type: name,
251
+ label: placeholder || ctx.varName!,
252
+ perform: (v) => ctx.setValue!(toValue(v)),
253
+ },
254
+ (control) => {
255
+ typed.current = control.value;
256
+ return toValue(control.value);
257
+ },
258
+ );
259
+
79
260
  return h(type ? 'input' : 'textarea', {
80
261
  type,
81
262
  ...actionAttributes(action, ctx),
@@ -278,17 +278,36 @@ function readGroup(
278
278
  let [text, at] = trimmed(src ?? '', srcAt);
279
279
  // A lone word is the passage of {include inline}, not its flag
280
280
  const alone = !params.some((p) => p.type !== 'flag' && p.required);
281
- for (const flag of params.filter((p) => p.type === 'flag')) {
282
- const rest = src === null ? null : takeFlag(text, flag.name, alone);
283
- args[flag.name] = rest !== null;
284
- if (rest) {
285
- const flagSpan: Span =
286
- rest[0] > 0
287
- ? [0, text.indexOf(flag.name) + flag.name.length]
288
- : [text.lastIndexOf(flag.name), text.length];
289
- toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
290
- [text, at] = trimmed(slice(text, rest), at + rest[0]);
281
+ const flags = params.filter((p) => p.type === 'flag');
282
+ for (const flag of flags) args[flag.name] = false;
283
+ const byName = new Map(flags.map((flag) => [flag.name, flag]));
284
+ // Consume from the boundaries in source order, independently of declaration
285
+ // order. Prefer the trailing flag when a required lone argument must remain.
286
+ while (text && byName.size) {
287
+ const parts = terms(text);
288
+ if (parts.length === 0) break;
289
+ let changed = false;
290
+ for (const name of [
291
+ slice(text, parts[parts.length - 1]!),
292
+ slice(text, parts[0]!),
293
+ ]) {
294
+ const flag = byName.get(name);
295
+ if (!flag || args[flag.name]) continue;
296
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
297
+ if (rest) {
298
+ args[flag.name] = true;
299
+ byName.delete(flag.name);
300
+ changed = true;
301
+ const flagSpan: Span =
302
+ rest[0] > 0
303
+ ? [0, text.indexOf(flag.name) + flag.name.length]
304
+ : [text.lastIndexOf(flag.name), text.length];
305
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
306
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
307
+ break;
308
+ }
291
309
  }
310
+ if (!changed) break;
292
311
  }
293
312
  const positional = params.filter((p) => p.type !== 'flag');
294
313
  if (positional.length === 0) return;
@@ -47,6 +47,7 @@ import {
47
47
  displayOnlyError,
48
48
  } from './display-only';
49
49
  import { NameSet } from './utils/macro-names';
50
+ import { notifyVariableWrite } from './utils/variable-writes';
50
51
  import {
51
52
  checkParameterTypes,
52
53
  registerMacro,
@@ -254,6 +255,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
254
255
  ctx.setValue = displayOnly
255
256
  ? refuse
256
257
  : (value: unknown) => {
258
+ notifyVariableWrite(segments);
257
259
  // The commit mutation code uses, which keeps the references among
258
260
  // variables: a write to a draft copies only the path written, and
259
261
  // other variables sharing the object would keep the old one.