@rohal12/spindle 0.59.28 → 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.
- package/README.md +1 -0
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +718 -300
- package/dist/pkg/macro-registry.js +19 -0
- package/dist/pkg/macro-registry.json +19 -0
- package/dist/pkg/story-variables.js +731 -234
- package/package.json +1 -1
- package/src/action-registry.ts +59 -5
- package/src/automation/load-yaml.ts +111 -20
- package/src/automation/runner.ts +15 -13
- package/src/automation/types.ts +7 -5
- package/src/class-registry.ts +8 -5
- package/src/code-check.ts +187 -24
- package/src/components/macros/Checkbox.tsx +5 -2
- package/src/components/macros/Cycle.tsx +1 -0
- package/src/components/macros/For.tsx +1 -7
- package/src/components/macros/Listbox.tsx +1 -0
- package/src/components/macros/MenubarButtons.tsx +6 -1
- package/src/components/macros/Nobr.tsx +1 -0
- package/src/components/macros/PassageDisplay.tsx +42 -0
- package/src/components/macros/Radiobutton.tsx +1 -0
- package/src/components/macros/SaveManager.tsx +19 -4
- package/src/components/macros/SettingsControls.tsx +19 -4
- package/src/components/macros/Span.tsx +1 -0
- package/src/components/macros/StoryTitle.tsx +1 -0
- package/src/components/macros/VarDisplay.tsx +2 -3
- package/src/components/macros/Widget.tsx +2 -0
- package/src/components/macros/WidgetInvocation.tsx +5 -6
- package/src/components/macros/arg-utils.ts +58 -21
- package/src/components/macros/input-macro.ts +1 -0
- package/src/components/macros/locals-scope.tsx +19 -8
- package/src/components/macros/macro-args.ts +11 -3
- package/src/expression.ts +34 -18
- package/src/hooks/use-merged-locals.ts +17 -2
- package/src/hooks/use-modal-focus.ts +190 -129
- package/src/index.tsx +23 -13
- package/src/js-bindings.ts +332 -0
- package/src/js-lexer.ts +12 -3
- package/src/macro-discovery.ts +25 -22
- package/src/static-literal.ts +87 -16
- package/src/store.ts +31 -2
- package/src/story-api.ts +15 -5
- package/src/story-variables.ts +91 -28
- package/src/structural.ts +19 -15
- package/src/tooling.ts +36 -10
- package/src/transform.ts +22 -7
- package/src/utils/namespace.ts +4 -0
- package/src/utils/object-path.ts +2 -2
- package/src/utils/stable-key.ts +17 -6
- package/src/utils/value-kinds.ts +38 -1
- package/src/widgets/register-widget-def.ts +7 -8
- package/src/widgets/widget-def.ts +41 -4
- package/src/widgets/widget-registry.ts +14 -0
- package/types/index.d.ts +12 -5
- package/types/tooling.d.ts +12 -2
package/src/store.ts
CHANGED
|
@@ -53,11 +53,15 @@ import {
|
|
|
53
53
|
deepClone,
|
|
54
54
|
existingObjects,
|
|
55
55
|
locateObjects,
|
|
56
|
+
deepEqual,
|
|
56
57
|
mergesWith,
|
|
58
|
+
pathKey,
|
|
57
59
|
shareEqual,
|
|
60
|
+
underChange,
|
|
58
61
|
type PathChange,
|
|
59
62
|
} from './structural';
|
|
60
63
|
import { getByPath } from './utils/object-path';
|
|
64
|
+
import { isIndexKey } from './utils/value-kinds';
|
|
61
65
|
import { noPassageError, showRuntimeError } from './runtime-errors';
|
|
62
66
|
import {
|
|
63
67
|
snapshotPRNG,
|
|
@@ -771,6 +775,14 @@ function loadedEntryMoment(
|
|
|
771
775
|
return moment;
|
|
772
776
|
}
|
|
773
777
|
|
|
778
|
+
/** The variable paths `Story.set` writes while a save's hooks run. */
|
|
779
|
+
let hookWrites: Map<string, string[]> | null = null;
|
|
780
|
+
|
|
781
|
+
/** Note that `path` of the variables was written (see keepHookWrites). */
|
|
782
|
+
export function recordHookWrite(path: string[]): void {
|
|
783
|
+
hookWrites?.set(pathKey(path), path);
|
|
784
|
+
}
|
|
785
|
+
|
|
774
786
|
/**
|
|
775
787
|
* Write the changes between `before` and `after` (the live variables around
|
|
776
788
|
* the `beforesave` hooks) into the payload's snapshot of the saved moment. A
|
|
@@ -788,10 +800,22 @@ function keepHookWrites(
|
|
|
788
800
|
payload: SavePayload,
|
|
789
801
|
before: Record<string, unknown>,
|
|
790
802
|
after: Record<string, unknown>,
|
|
803
|
+
written: readonly string[][],
|
|
791
804
|
): void {
|
|
792
805
|
const moment = payload.history[payload.historyIndex];
|
|
793
806
|
if (!moment) return;
|
|
794
807
|
const changes = changesBetween(before, after, true);
|
|
808
|
+
const keys = new Set(changes.map((c) => pathKey(c.path)));
|
|
809
|
+
// A write of the live value is no change to the live store, but the
|
|
810
|
+
// snapshot can still hold another one: an earlier save's hooks wrote the
|
|
811
|
+
// live value, which this moment's snapshot does not have (#479)
|
|
812
|
+
for (const path of written) {
|
|
813
|
+
if (underChange(path, keys)) continue;
|
|
814
|
+
keys.add(pathKey(path));
|
|
815
|
+
const value = getByPath(after, path);
|
|
816
|
+
if (deepEqual(getByPath(moment.variables, path), value)) continue;
|
|
817
|
+
changes.push({ path, deleted: false, value });
|
|
818
|
+
}
|
|
795
819
|
if (changes.length === 0) return;
|
|
796
820
|
// A copy of its own, so the writes keep the snapshot's references (which
|
|
797
821
|
// the history shares with other moments) as they are
|
|
@@ -842,7 +866,9 @@ function writeKey(
|
|
|
842
866
|
change?: PathChange,
|
|
843
867
|
): void {
|
|
844
868
|
const deleted = change?.deleted ?? false;
|
|
845
|
-
|
|
869
|
+
// The elements of an array and its length; its other keys are the fields of
|
|
870
|
+
// a subclass instance (#490)
|
|
871
|
+
if (Array.isArray(holder) && (key === 'length' || isIndexKey(key))) {
|
|
846
872
|
const index = Number(key);
|
|
847
873
|
if (deleted) {
|
|
848
874
|
// A hole stays where it was; anything else was cut off
|
|
@@ -1714,9 +1740,12 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1714
1740
|
|
|
1715
1741
|
beginSave: () => {
|
|
1716
1742
|
const before = get().variables;
|
|
1743
|
+
const writes = new Map<string, string[]>();
|
|
1744
|
+
hookWrites = writes;
|
|
1717
1745
|
return () => {
|
|
1746
|
+
if (hookWrites === writes) hookWrites = null;
|
|
1718
1747
|
const payload = get().getSavePayload();
|
|
1719
|
-
keepHookWrites(payload, before, get().variables);
|
|
1748
|
+
keepHookWrites(payload, before, get().variables, [...writes.values()]);
|
|
1720
1749
|
return payload;
|
|
1721
1750
|
};
|
|
1722
1751
|
},
|
package/src/story-api.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useStoryStore, trackRuntimeUnsub } from './store';
|
|
1
|
+
import { useStoryStore, trackRuntimeUnsub, recordHookWrite } from './store';
|
|
2
2
|
import type { StoryState, VariableNamespaces } from './store';
|
|
3
3
|
import {
|
|
4
4
|
on as emitterOn,
|
|
@@ -34,7 +34,13 @@ import { defineMacro } from './define-macro';
|
|
|
34
34
|
import type { MacroDefinition } from './define-macro';
|
|
35
35
|
import { getMacroRegistry as _getMacroRegistry } from './registry';
|
|
36
36
|
import type { MacroMetadata } from './registry';
|
|
37
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
getActions,
|
|
39
|
+
getAction,
|
|
40
|
+
performRegisteredAction,
|
|
41
|
+
settleRunningActions,
|
|
42
|
+
type StoryAction,
|
|
43
|
+
} from './action-registry';
|
|
38
44
|
import { getRenderedNavigationId } from './passage-render-state';
|
|
39
45
|
import {
|
|
40
46
|
initPRNG,
|
|
@@ -156,7 +162,7 @@ export interface StoryAPI {
|
|
|
156
162
|
readonly backend: 'indexeddb' | 'localstorage' | 'memory';
|
|
157
163
|
};
|
|
158
164
|
getActions(): StoryAction[];
|
|
159
|
-
performAction(id: string, value?: unknown): void
|
|
165
|
+
performAction(id: string, value?: unknown): void | Promise<void>;
|
|
160
166
|
on<E extends StoryEvent>(
|
|
161
167
|
event: E,
|
|
162
168
|
callback: StoryEventCallback<E>,
|
|
@@ -299,6 +305,7 @@ function createStoryAPI(): StoryAPI {
|
|
|
299
305
|
for (const [name] of entries) {
|
|
300
306
|
const { isTransient, key } = parseName(name);
|
|
301
307
|
warnIfUndeclared(isTransient, key);
|
|
308
|
+
if (!isTransient) recordHookWrite(key.split('.'));
|
|
302
309
|
}
|
|
303
310
|
// One store update for all keys, so watchers see them together. Made
|
|
304
311
|
// while mutation code runs ({do}, ctx.mutate, watcher run actions), it
|
|
@@ -410,7 +417,7 @@ function createStoryAPI(): StoryAPI {
|
|
|
410
417
|
return getActions();
|
|
411
418
|
},
|
|
412
419
|
|
|
413
|
-
performAction(id: string, value?: unknown): void {
|
|
420
|
+
performAction(id: string, value?: unknown): void | Promise<void> {
|
|
414
421
|
const action = getAction(id);
|
|
415
422
|
if (!action) {
|
|
416
423
|
throw new Error(`spindle: Action "${id}" not found.`);
|
|
@@ -418,7 +425,7 @@ function createStoryAPI(): StoryAPI {
|
|
|
418
425
|
if (action.disabled) {
|
|
419
426
|
throw new Error(`spindle: Action "${id}" is disabled.`);
|
|
420
427
|
}
|
|
421
|
-
action
|
|
428
|
+
return performRegisteredAction(action, value);
|
|
422
429
|
},
|
|
423
430
|
|
|
424
431
|
on<E extends StoryEvent>(
|
|
@@ -434,6 +441,9 @@ function createStoryAPI(): StoryAPI {
|
|
|
434
441
|
},
|
|
435
442
|
|
|
436
443
|
async waitForActions(): Promise<StoryAction[]> {
|
|
444
|
+
// An action that finishes later (QuickLoad) has not changed what the
|
|
445
|
+
// checks below look at until it has (#504)
|
|
446
|
+
await settleRunningActions();
|
|
437
447
|
await new Promise<void>((resolve) => {
|
|
438
448
|
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
|
439
449
|
});
|
package/src/story-variables.ts
CHANGED
|
@@ -19,8 +19,10 @@ import {
|
|
|
19
19
|
sigilExpressions,
|
|
20
20
|
parseOrError,
|
|
21
21
|
pieceOffset,
|
|
22
|
+
widgetPieces,
|
|
22
23
|
withParseCache,
|
|
23
24
|
type ParametersOf,
|
|
25
|
+
type Piece,
|
|
24
26
|
} from './code-check';
|
|
25
27
|
import { getMacroParameters, type ParameterDef } from './registry';
|
|
26
28
|
import {
|
|
@@ -29,7 +31,11 @@ import {
|
|
|
29
31
|
type ArgSpans,
|
|
30
32
|
} from './components/macros/macro-args';
|
|
31
33
|
import { NOT_MARKUP } from './markup/validate';
|
|
32
|
-
import {
|
|
34
|
+
import {
|
|
35
|
+
createNamespace,
|
|
36
|
+
isArrayIndex,
|
|
37
|
+
variableNameError,
|
|
38
|
+
} from './utils/namespace';
|
|
33
39
|
import { staticLiteral, type LiteralShape } from './static-literal';
|
|
34
40
|
import { parse } from 'acorn';
|
|
35
41
|
|
|
@@ -437,6 +443,11 @@ function checkReference(
|
|
|
437
443
|
|
|
438
444
|
// Primitives expose their wrapper's built-ins (length, toUpperCase,
|
|
439
445
|
// toFixed, etc.). Keep validating past properties of primitive type.
|
|
446
|
+
// Strings also have the character at each index below their length,
|
|
447
|
+
// which the empty sample has none of (the default may not be the value)
|
|
448
|
+
if (current.type === 'string' && isArrayIndex(part)) {
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
440
451
|
const sample = PRIMITIVE_SAMPLES[current.type];
|
|
441
452
|
if (sample && part in sample) {
|
|
442
453
|
const member: unknown = sample[part as keyof typeof sample];
|
|
@@ -495,14 +506,41 @@ type Emit = (ref: VariableReference) => void;
|
|
|
495
506
|
|
|
496
507
|
const NO_STORE_VAR_MACROS: ReadonlySet<string> = new Set();
|
|
497
508
|
|
|
498
|
-
/** A
|
|
509
|
+
/** A `.field` path written right after a reference, which may be empty. */
|
|
510
|
+
const FIELD_PATH_RE = /(?:\.\w+)*/y;
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* The reference to variable `name`, which JavaScript reads at `[start, end)`
|
|
514
|
+
* of `code` (the sigil and the name as written, which may be spelled with
|
|
515
|
+
* escapes), with the dot path written after it.
|
|
516
|
+
*/
|
|
499
517
|
function referenceAt(
|
|
500
518
|
code: string,
|
|
519
|
+
sigil: string,
|
|
520
|
+
name: string,
|
|
521
|
+
start: number,
|
|
522
|
+
end: number,
|
|
523
|
+
at: At,
|
|
524
|
+
): VariableReference {
|
|
525
|
+
FIELD_PATH_RE.lastIndex = end;
|
|
526
|
+
const fields = FIELD_PATH_RE.exec(code)![0];
|
|
527
|
+
return {
|
|
528
|
+
sigil: sigil as '$' | '%',
|
|
529
|
+
name,
|
|
530
|
+
path: fields ? fields.slice(1).split('.') : [],
|
|
531
|
+
start: at(start),
|
|
532
|
+
end: at(end + fields.length),
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** A reference written at `index` of `term`, a `variable` parameter as written. */
|
|
537
|
+
function termReferenceAt(
|
|
538
|
+
term: string,
|
|
501
539
|
index: number,
|
|
502
540
|
at: At,
|
|
503
541
|
): VariableReference | undefined {
|
|
504
542
|
VAR_PATH_RE.lastIndex = index;
|
|
505
|
-
const match = VAR_PATH_RE.exec(
|
|
543
|
+
const match = VAR_PATH_RE.exec(term);
|
|
506
544
|
if (!match) return undefined;
|
|
507
545
|
const [name, ...path] = match[2]!.split('.');
|
|
508
546
|
return {
|
|
@@ -562,8 +600,7 @@ function scanCode(
|
|
|
562
600
|
}
|
|
563
601
|
for (const ref of parsed.refs) {
|
|
564
602
|
if (ref.sigil !== '$' && ref.sigil !== '%') continue;
|
|
565
|
-
|
|
566
|
-
if (found) emit(found);
|
|
603
|
+
emit(referenceAt(code, ref.sigil, ref.name, ref.start, ref.end, at));
|
|
567
604
|
}
|
|
568
605
|
}
|
|
569
606
|
|
|
@@ -577,10 +614,9 @@ function scanCodeLeniently(
|
|
|
577
614
|
lexJs(
|
|
578
615
|
code,
|
|
579
616
|
{
|
|
580
|
-
variable(sigil,
|
|
617
|
+
variable(sigil, name, index, _nesting, end) {
|
|
581
618
|
if (sigil !== '$' && sigil !== '%') return;
|
|
582
|
-
|
|
583
|
-
if (found) emit(found);
|
|
619
|
+
emit(referenceAt(code, sigil, name, index, end, at));
|
|
584
620
|
},
|
|
585
621
|
// Strings, regex literals and comments hold no references
|
|
586
622
|
literal() {},
|
|
@@ -589,21 +625,44 @@ function scanCodeLeniently(
|
|
|
589
625
|
);
|
|
590
626
|
}
|
|
591
627
|
|
|
628
|
+
/** Report the references in the pieces of code and markup text of arguments. */
|
|
629
|
+
function scanPieces(
|
|
630
|
+
pieces: Iterable<Piece>,
|
|
631
|
+
at: At,
|
|
632
|
+
emit: Emit,
|
|
633
|
+
options: ReferenceOptions,
|
|
634
|
+
): void {
|
|
635
|
+
for (const piece of pieces) {
|
|
636
|
+
const pieceAt: At = (i) => at(pieceOffset(piece, i));
|
|
637
|
+
if (piece.kind === 'code') {
|
|
638
|
+
scanCode(piece.code, pieceAt, emit, piece.goal);
|
|
639
|
+
} else if (piece.kind === 'text') {
|
|
640
|
+
scanInterpolations(piece.text, pieceAt, emit, {
|
|
641
|
+
...options,
|
|
642
|
+
storeVarMacros: NO_STORE_VAR_MACROS,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
592
648
|
/**
|
|
593
649
|
* Report the references in the arguments of a macro by what its parameters
|
|
594
650
|
* say each holds (see ParameterDef.holds): code is scanned as code and
|
|
595
651
|
* markup as markup, but literal text (a placeholder, a passage name) holds
|
|
596
652
|
* none. A macro without declared parameters, or arguments that do not
|
|
597
|
-
* parse, are scanned as code.
|
|
653
|
+
* parse, are scanned as code. The arguments of a widget that declares what
|
|
654
|
+
* some parameters hold are also read by those (see widgetPieces).
|
|
598
655
|
*/
|
|
599
656
|
function scanArgs(
|
|
600
657
|
token: Extract<Token, { type: 'macro' }>,
|
|
601
|
-
|
|
658
|
+
parametersOf: ParametersOf,
|
|
602
659
|
at: At,
|
|
603
660
|
emit: Emit,
|
|
604
661
|
options: ReferenceOptions,
|
|
605
662
|
): void {
|
|
606
663
|
if (!token.rawArgs) return;
|
|
664
|
+
const params = parametersOf(token.name);
|
|
665
|
+
let byParameters = false;
|
|
607
666
|
if (params) {
|
|
608
667
|
if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) {
|
|
609
668
|
scanVariableParameters(token, params, at, emit);
|
|
@@ -611,22 +670,23 @@ function scanArgs(
|
|
|
611
670
|
const pieces = [
|
|
612
671
|
...argPieces(token.rawArgs, token.argsStart, params, token.name, ''),
|
|
613
672
|
];
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
673
|
+
byParameters = !pieces.some((piece) => piece.kind === 'argument-error');
|
|
674
|
+
if (byParameters) scanPieces(pieces, at, emit, options);
|
|
675
|
+
}
|
|
676
|
+
// The arguments of a widget are code: the strings among them hold none,
|
|
677
|
+
// but those that declare they hold code or markup are scanned as that
|
|
678
|
+
if (!byParameters) {
|
|
679
|
+
scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
|
|
680
|
+
}
|
|
681
|
+
const widget = parametersOf.widget?.(token.name);
|
|
682
|
+
if (widget) {
|
|
683
|
+
scanPieces(
|
|
684
|
+
widgetPieces(token.rawArgs, token.argsStart, widget, token.name, ''),
|
|
685
|
+
at,
|
|
686
|
+
emit,
|
|
687
|
+
options,
|
|
688
|
+
);
|
|
628
689
|
}
|
|
629
|
-
scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
|
|
630
690
|
}
|
|
631
691
|
|
|
632
692
|
/**
|
|
@@ -650,7 +710,7 @@ function scanVariableParameters(
|
|
|
650
710
|
for (const param of params) {
|
|
651
711
|
const span = spans.get(param);
|
|
652
712
|
if (param.type !== 'variable' || !span) continue;
|
|
653
|
-
const ref =
|
|
713
|
+
const ref = termReferenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) =>
|
|
654
714
|
at(token.argsStart + span[0] + i),
|
|
655
715
|
);
|
|
656
716
|
if (ref) emit(ref);
|
|
@@ -733,7 +793,7 @@ function collectTokenRefs(
|
|
|
733
793
|
else scanInterpolations(value, valueIn, emit, options);
|
|
734
794
|
}
|
|
735
795
|
} else if (token.type === 'macro' && !token.isClose) {
|
|
736
|
-
scanArgs(token, parametersOf
|
|
796
|
+
scanArgs(token, parametersOf, at, emit, options);
|
|
737
797
|
// Selectors (`{.{$cls} button}`) are interpolated when rendered
|
|
738
798
|
scanSelectors(content, token, at, emit, options);
|
|
739
799
|
|
|
@@ -804,7 +864,10 @@ export function collectVariableReferences(
|
|
|
804
864
|
options,
|
|
805
865
|
),
|
|
806
866
|
);
|
|
807
|
-
|
|
867
|
+
// The scan visits a macro's arguments before its selectors, and bindings
|
|
868
|
+
// after its arguments: the order of the source is the contract. (Stable,
|
|
869
|
+
// so references written at one place keep the order they were found in.)
|
|
870
|
+
return found.sort((a, b) => a.start - b.start);
|
|
808
871
|
}
|
|
809
872
|
|
|
810
873
|
/**
|
package/src/structural.ts
CHANGED
|
@@ -22,6 +22,8 @@ import {
|
|
|
22
22
|
mapEntries,
|
|
23
23
|
mapGet,
|
|
24
24
|
mapSet,
|
|
25
|
+
regExpParts,
|
|
26
|
+
regExpText,
|
|
25
27
|
setMembers,
|
|
26
28
|
} from './utils/value-kinds';
|
|
27
29
|
|
|
@@ -116,10 +118,7 @@ export function deepClone<T>(value: T, options: DeepCloneOptions = {}): T {
|
|
|
116
118
|
return builtin(val, new Date(Date.prototype.getTime.call(val)));
|
|
117
119
|
}
|
|
118
120
|
if (val instanceof RegExp) {
|
|
119
|
-
const copy = new RegExp(
|
|
120
|
-
Reflect.get(RegExp.prototype, 'source', val) as string,
|
|
121
|
-
Reflect.get(RegExp.prototype, 'flags', val) as string,
|
|
122
|
-
);
|
|
121
|
+
const copy = new RegExp(...regExpParts(val));
|
|
123
122
|
copy.lastIndex = val.lastIndex; // the scanning cursor of g/y patterns
|
|
124
123
|
return builtin(val, copy);
|
|
125
124
|
}
|
|
@@ -406,9 +405,8 @@ function equalBuiltin(
|
|
|
406
405
|
);
|
|
407
406
|
}
|
|
408
407
|
if (a instanceof RegExp) {
|
|
409
|
-
const text = RegExp.prototype.toString;
|
|
410
408
|
return (
|
|
411
|
-
|
|
409
|
+
regExpText(a) === regExpText(b as RegExp) &&
|
|
412
410
|
a.lastIndex === (b as RegExp).lastIndex &&
|
|
413
411
|
equalExtraKeys(a, b, assumed)
|
|
414
412
|
);
|
|
@@ -473,14 +471,18 @@ const BUILTIN_PROTOS: ReadonlySet<object | null> = new Set([
|
|
|
473
471
|
]);
|
|
474
472
|
|
|
475
473
|
/**
|
|
476
|
-
*
|
|
477
|
-
*
|
|
474
|
+
* The extra keys (see extraKeys) of a built-in that is an instance of a
|
|
475
|
+
* subclass: those are part of its value. A plain built-in has none.
|
|
478
476
|
*/
|
|
477
|
+
function subclassFields(obj: object): string[] {
|
|
478
|
+
return BUILTIN_PROTOS.has(Object.getPrototypeOf(obj) as object | null)
|
|
479
|
+
? []
|
|
480
|
+
: extraKeys(obj);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Equality of the fields (see subclassFields) of two built-ins of one class. */
|
|
479
484
|
function equalExtraKeys(a: object, b: object, assumed: Pairs): boolean {
|
|
480
|
-
return (
|
|
481
|
-
BUILTIN_PROTOS.has(Object.getPrototypeOf(a) as object | null) ||
|
|
482
|
-
equalKeys(a, b, assumed, extraKeys)
|
|
483
|
-
);
|
|
485
|
+
return equalKeys(a, b, assumed, subclassFields);
|
|
484
486
|
}
|
|
485
487
|
|
|
486
488
|
/** `assumed` tracks the pairs of objects met (see Pairs). */
|
|
@@ -619,6 +621,8 @@ export function keyChanges(
|
|
|
619
621
|
}
|
|
620
622
|
};
|
|
621
623
|
|
|
624
|
+
// Elements are compared by index, then the fields of a subclass instance
|
|
625
|
+
// (#490) like the keys of an object
|
|
622
626
|
if (Array.isArray(after)) {
|
|
623
627
|
const b = before as unknown as unknown[];
|
|
624
628
|
const a = after as unknown[];
|
|
@@ -648,14 +652,14 @@ export function keyChanges(
|
|
|
648
652
|
if (a.length > next) {
|
|
649
653
|
changes.push({ key: 'length', kind: 'holes', after: a.length - next });
|
|
650
654
|
}
|
|
651
|
-
return changes;
|
|
652
655
|
}
|
|
653
656
|
|
|
654
|
-
|
|
657
|
+
const keysOf = Array.isArray(after) ? subclassFields : Object.keys;
|
|
658
|
+
for (const key of keysOf(after)) {
|
|
655
659
|
if (hasOwn(before, key)) compare(key, before[key], after[key]);
|
|
656
660
|
else changes.push({ key, kind: 'added', after: after[key] });
|
|
657
661
|
}
|
|
658
|
-
for (const key of
|
|
662
|
+
for (const key of keysOf(before)) {
|
|
659
663
|
if (!hasOwn(after, key)) changes.push({ key, kind: 'deleted' });
|
|
660
664
|
}
|
|
661
665
|
return changes;
|
package/src/tooling.ts
CHANGED
|
@@ -20,7 +20,6 @@ import {
|
|
|
20
20
|
type Piece,
|
|
21
21
|
} from './code-check';
|
|
22
22
|
import {
|
|
23
|
-
blockWidgetNames,
|
|
24
23
|
widgetDefinitions as readWidgetDefinitions,
|
|
25
24
|
type WidgetDefinition,
|
|
26
25
|
} from './widgets/widget-def';
|
|
@@ -32,6 +31,7 @@ import {
|
|
|
32
31
|
type VariableReference,
|
|
33
32
|
} from './story-variables';
|
|
34
33
|
import type { ParameterDef } from './registry';
|
|
34
|
+
import type { WidgetDef } from './widgets/widget-def';
|
|
35
35
|
|
|
36
36
|
export { parseDeclarations, parseStoryVariables } from './story-variables';
|
|
37
37
|
export { discoverMacros } from './macro-discovery';
|
|
@@ -156,6 +156,12 @@ export interface ToolingMacro {
|
|
|
156
156
|
* Its declared parameters: their types tell which arguments are code, and
|
|
157
157
|
* what a `string` or `text` argument holds (see ParameterDef.holds).
|
|
158
158
|
*/
|
|
159
|
+
/**
|
|
160
|
+
* For a widget: its `@` parameters and what the ones that declare it hold
|
|
161
|
+
* (`@target:passage`, see WidgetDef), so that a call is checked like the
|
|
162
|
+
* call of a macro whose `string` parameter has that `holds`.
|
|
163
|
+
*/
|
|
164
|
+
widget?: Pick<WidgetDef, 'params' | 'holds'>;
|
|
159
165
|
parameters?: readonly ParameterDef[];
|
|
160
166
|
/** Whether it resolves markup: its strings hold markup by default. */
|
|
161
167
|
interpolate?: boolean;
|
|
@@ -177,10 +183,17 @@ export function validateStoryMarkup(
|
|
|
177
183
|
const list = [...passages];
|
|
178
184
|
const all = [...macros];
|
|
179
185
|
const known = new Set<string>();
|
|
180
|
-
|
|
186
|
+
// The calls of widgets that declare what their arguments hold are checked
|
|
187
|
+
const widgets = readWidgetDefinitions(list, parameterLookup(all));
|
|
181
188
|
const blocks = new Set(
|
|
182
|
-
|
|
189
|
+
widgets
|
|
190
|
+
.filter((def) => def.block && def.closeStart !== undefined)
|
|
191
|
+
.map((def) => def.name.toLowerCase()),
|
|
183
192
|
);
|
|
193
|
+
const parametersOf = parameterLookup([
|
|
194
|
+
...all,
|
|
195
|
+
...definedWidgetMacros(widgets),
|
|
196
|
+
]);
|
|
184
197
|
for (const macro of all) {
|
|
185
198
|
const name = macro.name.toLowerCase();
|
|
186
199
|
known.add(name);
|
|
@@ -198,6 +211,11 @@ export function validateStoryMarkup(
|
|
|
198
211
|
});
|
|
199
212
|
}
|
|
200
213
|
|
|
214
|
+
/** The widgets as macros that declare what their parameters hold. */
|
|
215
|
+
function definedWidgetMacros(widgets: readonly WidgetDefinition[]) {
|
|
216
|
+
return widgets.map((widget) => ({ name: widget.name, widget }));
|
|
217
|
+
}
|
|
218
|
+
|
|
201
219
|
/** Whether a macro takes a body, among `macros` and the built-in ones. */
|
|
202
220
|
function blockLookup(macros: readonly ToolingMacro[]) {
|
|
203
221
|
const blocks = new Set(
|
|
@@ -261,15 +279,24 @@ export function widgetDefinitions(
|
|
|
261
279
|
/** Passages tagged so hold code or styles, not markup. */
|
|
262
280
|
const NOT_MARKUP_TAGS = ['script', 'stylesheet'];
|
|
263
281
|
|
|
264
|
-
/**
|
|
265
|
-
|
|
282
|
+
/**
|
|
283
|
+
* What reading the variable references of markup depends on: the `macros`,
|
|
284
|
+
* and the widgets of the `passages` that are given (the calls of those that
|
|
285
|
+
* declare what their parameters hold are read by them).
|
|
286
|
+
*/
|
|
287
|
+
function referenceOptions(
|
|
288
|
+
macros: Iterable<ToolingMacro>,
|
|
289
|
+
all = false,
|
|
290
|
+
passages: readonly MarkupPassage[] = [],
|
|
291
|
+
) {
|
|
266
292
|
const list = [...macros];
|
|
293
|
+
const widgets = readWidgetDefinitions(passages, parameterLookup(list));
|
|
267
294
|
return {
|
|
268
295
|
all,
|
|
269
296
|
storeVarMacros: new Set(
|
|
270
297
|
list.filter((m) => m.storeVar).map((m) => m.name.toLowerCase()),
|
|
271
298
|
),
|
|
272
|
-
parametersOf: parameterLookup(list),
|
|
299
|
+
parametersOf: parameterLookup([...list, ...definedWidgetMacros(widgets)]),
|
|
273
300
|
tolerant: true,
|
|
274
301
|
};
|
|
275
302
|
}
|
|
@@ -313,11 +340,10 @@ export function validateVariableReferences(
|
|
|
313
340
|
declarations: VariableDeclarations,
|
|
314
341
|
macros: Iterable<ToolingMacro> = [],
|
|
315
342
|
): VariableDiagnostic[] {
|
|
343
|
+
const list = [...passages];
|
|
316
344
|
return checkVariableReferences(
|
|
317
|
-
|
|
318
|
-
(p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t)),
|
|
319
|
-
),
|
|
345
|
+
list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))),
|
|
320
346
|
declarations,
|
|
321
|
-
referenceOptions(macros),
|
|
347
|
+
referenceOptions(macros, false, list),
|
|
322
348
|
);
|
|
323
349
|
}
|
package/src/transform.ts
CHANGED
|
@@ -9,19 +9,34 @@ import { variableNameError } from './utils/namespace';
|
|
|
9
9
|
|
|
10
10
|
const TRANSFORM_CACHE_MAX = 500;
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
12
|
+
/**
|
|
13
|
+
* The identifiers generated code reads the namespaces through, and the
|
|
14
|
+
* compiled function takes them under (see src/expression.ts). Authored
|
|
15
|
+
* JavaScript may declare identifiers of its own (`const variables = {}` in
|
|
16
|
+
* a helper), so these are ones it cannot: an identifier that starts with
|
|
17
|
+
* `_` or `$` and has more word characters after it is a sigil reference,
|
|
18
|
+
* and the lexer refuses to declare one (`__variables` is the temporary
|
|
19
|
+
* variable `_variables`, rewritten like any other). No declaration or
|
|
20
|
+
* parameter of the author's can then capture a reference or clash with the
|
|
21
|
+
* generated bindings.
|
|
22
|
+
*/
|
|
23
|
+
export const BINDINGS: Record<Sigil, string> = {
|
|
24
|
+
$: '__variables',
|
|
25
|
+
_: '__temporary',
|
|
26
|
+
'@': '__locals',
|
|
27
|
+
'%': '__transient',
|
|
17
28
|
};
|
|
18
29
|
|
|
30
|
+
/** The identifier the functions that compiled code may call come under. */
|
|
31
|
+
export const FNS_BINDING = '__fns';
|
|
32
|
+
|
|
19
33
|
/** Ends with an identifier character. */
|
|
20
34
|
const IDENT_END_RE = /[\p{ID_Continue}$\u200c\u200d]$/u;
|
|
21
35
|
|
|
22
36
|
/**
|
|
23
37
|
* Transform expression: $var → variables["var"], _var → temporary["var"],
|
|
24
|
-
* @var → locals["var"], %var → transient["var"]
|
|
38
|
+
* @var → locals["var"], %var → transient["var"], where `variables` and the
|
|
39
|
+
* others stand for the generated names in BINDINGS.
|
|
25
40
|
* The lexer (`lexJs`) finds the references: only in code (string, template
|
|
26
41
|
* and regex literal text and comments are left untouched), only where an
|
|
27
42
|
* identifier starts (not in `a$b`, nor as the property name in `obj._x`),
|
|
@@ -45,7 +60,7 @@ export function transform(expr: string, goal: JsGoal = 'expression'): string {
|
|
|
45
60
|
if (ref.shorthand) result += `${ref.name}: `;
|
|
46
61
|
// `typeof%x` needs a space once `%x` turns into an identifier.
|
|
47
62
|
else if (IDENT_END_RE.test(result.slice(-2))) result += ' ';
|
|
48
|
-
result += `${
|
|
63
|
+
result += `${BINDINGS[ref.sigil]}["${ref.name}"]`;
|
|
49
64
|
at = ref.end;
|
|
50
65
|
}
|
|
51
66
|
result += expr.slice(at);
|
package/src/utils/namespace.ts
CHANGED
|
@@ -38,6 +38,10 @@ export function checkVariableName(name: string, label = name): void {
|
|
|
38
38
|
if (error) throw new TypeError(`spindle: ${error}`);
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
+
/** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
|
|
42
|
+
export const isArrayIndex = (key: string): boolean =>
|
|
43
|
+
/^(?:0|[1-9]\d*)$/.test(key);
|
|
44
|
+
|
|
41
45
|
/** Whether `obj` holds `key` as an own property. */
|
|
42
46
|
export const hasOwn = (obj: object, key: PropertyKey): boolean =>
|
|
43
47
|
Object.prototype.hasOwnProperty.call(obj, key);
|
package/src/utils/object-path.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { current as draftState, isDraft, original } from 'immer';
|
|
2
2
|
import { registeredClassName } from '../class-registry';
|
|
3
|
-
import { hasOwn } from './namespace';
|
|
3
|
+
import { hasOwn, isArrayIndex } from './namespace';
|
|
4
4
|
import { atomicName } from './value-kinds';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -36,7 +36,7 @@ export function getByPath(obj: object, segments: readonly string[]): unknown {
|
|
|
36
36
|
|
|
37
37
|
/** Array indices ("0", "1", …) and "length": the keys an array holds. */
|
|
38
38
|
const isArrayKey = (key: string): boolean =>
|
|
39
|
-
key === 'length' ||
|
|
39
|
+
key === 'length' || isArrayIndex(key);
|
|
40
40
|
|
|
41
41
|
/**
|
|
42
42
|
* Built-ins whose content is not their properties: a property written into
|