@rohal12/spindle 0.60.3 → 0.61.0

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 (55) hide show
  1. package/README.md +1 -1
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +18671 -18510
  4. package/dist/pkg/play-worker.js +181 -0
  5. package/dist/pkg/play.js +398 -0
  6. package/dist/pkg/story-variables.js +11016 -153
  7. package/package.json +19 -1
  8. package/src/action-registry.ts +43 -3
  9. package/src/components/PassageDialog.tsx +29 -27
  10. package/src/components/dialog-close-context.ts +5 -1
  11. package/src/components/macros/Button.tsx +3 -3
  12. package/src/components/macros/Checkbox.tsx +3 -2
  13. package/src/components/macros/Cycle.tsx +3 -4
  14. package/src/components/macros/Dialog.tsx +3 -3
  15. package/src/components/macros/Listbox.tsx +3 -4
  16. package/src/components/macros/MacroLink.tsx +3 -3
  17. package/src/components/macros/MenubarButtons.tsx +3 -3
  18. package/src/components/macros/PassageDisplay.tsx +14 -9
  19. package/src/components/macros/Radiobutton.tsx +3 -2
  20. package/src/components/macros/detached-body.tsx +1 -4
  21. package/src/components/macros/input-macro.ts +10 -8
  22. package/src/define-macro.ts +0 -4
  23. package/src/execute-mutation.ts +10 -6
  24. package/src/format/fenced-code.ts +59 -0
  25. package/src/format/format-passage.ts +100 -11
  26. package/src/headless.ts +25 -1
  27. package/src/hooks/use-action.ts +44 -4
  28. package/src/hooks/use-modal-focus.ts +1 -30
  29. package/src/markup/ast.ts +4 -3
  30. package/src/markup/pair.ts +22 -9
  31. package/src/markup/parse.ts +2 -0
  32. package/src/markup/validate.ts +5 -3
  33. package/src/observe/observable-text.ts +6 -24
  34. package/src/observe/observe.ts +4 -1
  35. package/src/play/index.ts +15 -0
  36. package/src/play/optional.ts +41 -0
  37. package/src/play/protocol.ts +35 -0
  38. package/src/play/resolve-story.ts +265 -0
  39. package/src/play/session.ts +253 -0
  40. package/src/play/worker.ts +169 -0
  41. package/src/registry.ts +36 -1
  42. package/src/runtime-errors.ts +5 -0
  43. package/src/saves/save-manager.ts +48 -7
  44. package/src/saves/storage.ts +3 -1
  45. package/src/saves/types.ts +1 -0
  46. package/src/store.ts +13 -6
  47. package/src/story-init.ts +6 -1
  48. package/src/structural.ts +126 -66
  49. package/src/tooling.ts +2 -0
  50. package/src/types-drift-check.ts +55 -0
  51. package/src/utils/element-visibility.ts +61 -0
  52. package/types/headless.d.ts +14 -0
  53. package/types/index.d.ts +2 -0
  54. package/types/play.d.ts +83 -0
  55. package/types/tooling.d.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.60.3",
3
+ "version": "0.61.0",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -36,6 +36,10 @@
36
36
  "./headless": {
37
37
  "types": "./types/headless.d.ts",
38
38
  "import": "./dist/pkg/headless.js"
39
+ },
40
+ "./play": {
41
+ "types": "./types/play.d.ts",
42
+ "import": "./dist/pkg/play.js"
39
43
  }
40
44
  },
41
45
  "files": [
@@ -43,6 +47,8 @@
43
47
  "dist/pkg/format.js",
44
48
  "dist/pkg/tooling.js",
45
49
  "dist/pkg/headless.js",
50
+ "dist/pkg/play.js",
51
+ "dist/pkg/play-worker.js",
46
52
  "dist/pkg/story-variables.js",
47
53
  "dist/pkg/macro-registry.json",
48
54
  "dist/pkg/macro-registry.js",
@@ -77,6 +83,18 @@
77
83
  "preact": "^11.0.1",
78
84
  "zustand": "^5.0.15"
79
85
  },
86
+ "peerDependencies": {
87
+ "@rohal12/twee-ts": "^1.18.2",
88
+ "happy-dom": "^20.14.6"
89
+ },
90
+ "peerDependenciesMeta": {
91
+ "@rohal12/twee-ts": {
92
+ "optional": true
93
+ },
94
+ "happy-dom": {
95
+ "optional": true
96
+ }
97
+ },
80
98
  "lint-staged": {
81
99
  "*": "prettier --write --ignore-unknown"
82
100
  },
@@ -1,3 +1,4 @@
1
+ import { isReaderVisible } from './utils/element-visibility';
1
2
  import { emit } from './event-emitter';
2
3
  import {
3
4
  checkFields,
@@ -123,6 +124,9 @@ interface Entry {
123
124
  action: StoryAction;
124
125
  /** The dialog the control renders in (its close function), if any. */
125
126
  dialog: (() => void) | null;
127
+ /** Its panel ref stays live across DOM commits without re-registering. */
128
+ panel: { readonly current: Element | null } | null;
129
+ element: { readonly current: Element | null } | null;
126
130
  }
127
131
 
128
132
  /**
@@ -176,9 +180,11 @@ export function generateActionId(
176
180
  export function registerAction(
177
181
  action: StoryAction,
178
182
  dialog: (() => void) | null = null,
183
+ panel: Entry['panel'] = null,
184
+ element: Entry['element'] = null,
179
185
  ): ActionRegistration {
180
186
  const id = action.id;
181
- const entry: Entry = { action, dialog };
187
+ const entry: Entry = { action, dialog, panel, element };
182
188
  const entries = actions.get(id);
183
189
  if (entries) {
184
190
  console.warn(
@@ -255,7 +261,7 @@ export function getDialogActions(dialog: () => void): StoryAction[] {
255
261
  return Array.from(actions.values())
256
262
  .map((entries) => entries[entries.length - 1]!)
257
263
  .filter((entry) => entry.dialog === dialog)
258
- .map((entry) => entry.action);
264
+ .map((entry) => effectiveAction(entry.action));
259
265
  }
260
266
 
261
267
  export function getAction(id: string): StoryAction | undefined {
@@ -264,7 +270,41 @@ export function getAction(id: string): StoryAction | undefined {
264
270
  }
265
271
 
266
272
  function listed(entries: Entry[]): StoryAction {
267
- return entries[entries.length - 1]!.action;
273
+ return effectiveAction(entries[entries.length - 1]!.action);
274
+ }
275
+
276
+ /** The live control for an action; author IDs need no selector escaping. */
277
+ function actionElements(id: string): Element[] {
278
+ if (typeof document === 'undefined') return [];
279
+ const entries = actions.get(id);
280
+ const entry = entries?.[entries.length - 1];
281
+ if (entry?.element) {
282
+ const control = entry.element.current;
283
+ return control ? [control] : [];
284
+ }
285
+ const panel = entry?.panel?.current ?? null;
286
+ return [...(panel ?? document).querySelectorAll('[data-action]')].filter(
287
+ (el) =>
288
+ el.getAttribute('data-action') === id &&
289
+ el.closest('.dialog-panel') === panel,
290
+ );
291
+ }
292
+
293
+ /** Effective native disability, including disabled fieldsets and legends. */
294
+ function effectiveAction(action: StoryAction): StoryAction {
295
+ const controls = actionElements(action.id);
296
+ return !action.disabled && controls.some((el) => el.matches(':disabled'))
297
+ ? { ...action, disabled: true }
298
+ : action;
299
+ }
300
+
301
+ /** Whether any connected instance of this action is visible to a reader. */
302
+ export function isActionVisible(action: StoryAction): boolean {
303
+ const elements = actionElements(action.id);
304
+ // Older custom actions need not associate a DOM control. Keep those
305
+ // registrations available; built-ins and associated custom controls are
306
+ // filtered against the live DOM.
307
+ return elements.length === 0 || elements.some(isReaderVisible);
268
308
  }
269
309
 
270
310
  export function clearActions(): void {
@@ -18,9 +18,9 @@ import { emitFromRender } from '../event-emitter';
18
18
  import { useModalFocus } from '../hooks/use-modal-focus';
19
19
  import { registerOpenDialog } from '../triggers';
20
20
  import { errorMessage } from '../utils/error-message';
21
- import { useAction } from '../hooks/use-action';
21
+ import { actionAttributes, useControlAction } from '../hooks/use-action';
22
22
 
23
- import { DialogCloseContext } from './dialog-close-context';
23
+ import { DialogCloseContext, DialogPanelContext } from './dialog-close-context';
24
24
 
25
25
  export { DialogCloseContext };
26
26
 
@@ -131,33 +131,35 @@ export function PassageDialog({
131
131
  return (
132
132
  <InterfaceContext.Provider value={false}>
133
133
  <DialogCloseContext.Provider value={stableOnClose}>
134
- <div
135
- class="dialog-overlay"
136
- onClick={handleBackdrop}
137
- >
134
+ <DialogPanelContext.Provider value={panelRef}>
138
135
  <div
139
- ref={panelRef}
140
- class={cls}
141
- role="dialog"
142
- data-dialog-passage={passageName}
143
- aria-modal="true"
144
- aria-label={label ?? passageName}
145
- tabIndex={-1}
136
+ class="dialog-overlay"
137
+ onClick={handleBackdrop}
146
138
  >
147
- {showCloseButton && (
148
- <DialogCloseButton
149
- dialogName={passageName ?? label ?? 'dialog'}
150
- passageName={passageName}
151
- onClose={stableOnClose}
152
- />
153
- )}
154
- <div class="dialog-body">
155
- <ViewScopeContext.Provider value={viewScope}>
156
- {content}
157
- </ViewScopeContext.Provider>
139
+ <div
140
+ ref={panelRef}
141
+ class={cls}
142
+ role="dialog"
143
+ data-dialog-passage={passageName}
144
+ aria-modal="true"
145
+ aria-label={label ?? passageName}
146
+ tabIndex={-1}
147
+ >
148
+ {showCloseButton && (
149
+ <DialogCloseButton
150
+ dialogName={passageName ?? label ?? 'dialog'}
151
+ passageName={passageName}
152
+ onClose={stableOnClose}
153
+ />
154
+ )}
155
+ <div class="dialog-body">
156
+ <ViewScopeContext.Provider value={viewScope}>
157
+ {content}
158
+ </ViewScopeContext.Provider>
159
+ </div>
158
160
  </div>
159
161
  </div>
160
- </div>
162
+ </DialogPanelContext.Provider>
161
163
  </DialogCloseContext.Provider>
162
164
  </InterfaceContext.Provider>
163
165
  );
@@ -176,7 +178,7 @@ function DialogCloseButton({
176
178
  passageName?: string;
177
179
  onClose: () => void;
178
180
  }) {
179
- useAction({
181
+ const action = useControlAction({
180
182
  type: 'close-dialog',
181
183
  key: dialogName,
182
184
  label: 'Close',
@@ -187,7 +189,7 @@ function DialogCloseButton({
187
189
  return (
188
190
  <button
189
191
  type="button"
190
- class="dialog-close"
192
+ {...actionAttributes(action, { cls: 'dialog-close' })}
191
193
  aria-label="Close"
192
194
  onClick={onClose}
193
195
  >
@@ -1,4 +1,4 @@
1
- import { createContext } from 'preact';
1
+ import { createContext, type RefObject } from 'preact';
2
2
 
3
3
  /**
4
4
  * The function that closes the dialog the content renders in, or null
@@ -8,3 +8,7 @@ import { createContext } from 'preact';
8
8
  * offer only the innermost dialog's actions.
9
9
  */
10
10
  export const DialogCloseContext = createContext<(() => void) | null>(null);
11
+
12
+ /** The dialog's own panel, for associating actions with its live controls. */
13
+ export const DialogPanelContext =
14
+ createContext<RefObject<Element | null> | null>(null);
@@ -1,3 +1,4 @@
1
+ import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
2
  import { defineMacro } from '../../define-macro';
2
3
  import { useDetachedBody } from './detached-body';
3
4
 
@@ -16,7 +17,7 @@ defineMacro({
16
17
  // {if}, {unwatch}, etc.) fire through the normal Preact pipeline.
17
18
  const handleClick = () => runBody(children);
18
19
 
19
- ctx.useAction({
20
+ const action = useControlAction({
20
21
  type: 'button',
21
22
  key: rawArgs,
22
23
  authorId: ctx.id,
@@ -27,8 +28,7 @@ defineMacro({
27
28
  return (
28
29
  <button
29
30
  type="button"
30
- id={ctx.id}
31
- class={ctx.cls}
31
+ {...actionAttributes(action, ctx)}
32
32
  onClick={handleClick}
33
33
  >
34
34
  {label}
@@ -1,3 +1,4 @@
1
+ import { actionAttributes } from '../../hooks/use-action';
1
2
  import { defineMacro } from '../../define-macro';
2
3
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
3
4
 
@@ -12,7 +13,7 @@ defineMacro({
12
13
  render(_props, ctx) {
13
14
  const label = ctx.args.label ?? '';
14
15
 
15
- const actionId = useVariableAction(ctx, {
16
+ const action = useVariableAction(ctx, {
16
17
  type: 'checkbox',
17
18
  label: label || ctx.varName || '',
18
19
  value: !!ctx.value,
@@ -26,7 +27,7 @@ defineMacro({
26
27
  >
27
28
  <input
28
29
  type="checkbox"
29
- data-action={actionId || undefined}
30
+ {...actionAttributes(action, {})}
30
31
  checked={!!ctx.value}
31
32
  onChange={(e) =>
32
33
  ctx.setValue!((e.target as HTMLInputElement).checked)
@@ -1,3 +1,4 @@
1
+ import { actionAttributes } from '../../hooks/use-action';
1
2
  import { defineMacro } from '../../define-macro';
2
3
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
3
4
 
@@ -18,7 +19,7 @@ defineMacro({
18
19
  ctx.setValue!(options[nextIndex]);
19
20
  };
20
21
 
21
- const actionId = useVariableAction(ctx, {
22
+ const action = useVariableAction(ctx, {
22
23
  type: 'cycle',
23
24
  label: ctx.value == null ? options[0] || '' : String(ctx.value),
24
25
  options,
@@ -34,9 +35,7 @@ defineMacro({
34
35
  return (
35
36
  <button
36
37
  type="button"
37
- id={ctx.id}
38
- data-action={actionId || undefined}
39
- class={ctx.cls}
38
+ {...actionAttributes(action, ctx)}
40
39
  onClick={handleClick}
41
40
  >
42
41
  {ctx.value == null ? options[0] || '' : String(ctx.value)}
@@ -1,3 +1,4 @@
1
+ import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
2
  import { defineMacro } from '../../define-macro';
2
3
  import { PassageDialog } from '../PassageDialog';
3
4
 
@@ -21,7 +22,7 @@ defineMacro({
21
22
  const openDialog = () => setOpen(true);
22
23
 
23
24
  // Its own type: the menubar's Saves and Settings are `dialog` (#540)
24
- ctx.useAction({
25
+ const action = useControlAction({
25
26
  type: 'open-dialog',
26
27
  key: rawArgs,
27
28
  authorId: ctx.id,
@@ -34,8 +35,7 @@ defineMacro({
34
35
  <>
35
36
  <button
36
37
  type="button"
37
- id={ctx.id}
38
- class={ctx.cls}
38
+ {...actionAttributes(action, ctx)}
39
39
  onClick={openDialog}
40
40
  >
41
41
  {label}
@@ -1,3 +1,4 @@
1
+ import { actionAttributes } from '../../hooks/use-action';
1
2
  import { defineMacro } from '../../define-macro';
2
3
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
3
4
  import { display } from './display';
@@ -11,7 +12,7 @@ defineMacro({
11
12
  render({ children = [] }, ctx) {
12
13
  const options = ctx.extractOptions(children);
13
14
 
14
- const actionId = useVariableAction(ctx, {
15
+ const action = useVariableAction(ctx, {
15
16
  type: 'listbox',
16
17
  label: ctx.varName!,
17
18
  options,
@@ -22,9 +23,7 @@ defineMacro({
22
23
 
23
24
  return (
24
25
  <select
25
- id={ctx.id}
26
- data-action={actionId || undefined}
27
- class={ctx.cls}
26
+ {...actionAttributes(action, ctx)}
28
27
  value={display(ctx.value)}
29
28
  onChange={(e) => ctx.setValue!((e.target as HTMLSelectElement).value)}
30
29
  >
@@ -1,3 +1,4 @@
1
+ import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
2
  import { useStoryStore } from '../../store';
2
3
  import { defineMacro } from '../../define-macro';
3
4
  import { useDetachedBody } from './detached-body';
@@ -48,7 +49,7 @@ defineMacro({
48
49
  perform();
49
50
  };
50
51
 
51
- ctx.useAction({
52
+ const action = useControlAction({
52
53
  type: 'link',
53
54
  key: passage || display,
54
55
  authorId: ctx.id,
@@ -68,8 +69,7 @@ defineMacro({
68
69
  }
69
70
  return (
70
71
  <a
71
- id={ctx.id}
72
- class={ctx.cls}
72
+ {...actionAttributes(action, ctx)}
73
73
  href="#"
74
74
  onClick={handleClick}
75
75
  >
@@ -1,3 +1,4 @@
1
+ import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
2
  import { useState } from 'preact/hooks';
2
3
  import { useStoryStore } from '../../store';
3
4
  import { useStoryFields } from '../../hooks/use-story-fields';
@@ -56,7 +57,7 @@ export function defineMenubarAction(config: MenubarActionConfig) {
56
57
  }
57
58
  : setup.perform;
58
59
 
59
- ctx.useAction({
60
+ const action = useControlAction({
60
61
  type: config.actionType,
61
62
  key: config.name,
62
63
  authorId: ctx.id,
@@ -69,8 +70,7 @@ export function defineMenubarAction(config: MenubarActionConfig) {
69
70
  <>
70
71
  <button
71
72
  type="button"
72
- id={ctx.id}
73
- class={cls}
73
+ {...actionAttributes(action, { id: ctx.id, cls })}
74
74
  onClick={perform}
75
75
  disabled={disabled}
76
76
  title={title}
@@ -146,7 +146,7 @@ function appendSnapshot(container: Element, snapshot: HTMLElement): void {
146
146
 
147
147
  /**
148
148
  * Create a snapshot clone of a .passage element for outgoing transitions.
149
- * - Strips `id` attributes from the clone tree
149
+ * - Strips IDs, action associations and event handlers from the clone tree
150
150
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
151
151
  * - Pauses/mutes any <audio>/<video>
152
152
  * - Copies what cloneNode leaves behind: canvas pixels, the state of form
@@ -159,6 +159,18 @@ function createSnapshot(
159
159
  transitionType: string,
160
160
  ): HTMLElement {
161
161
  const clone = passageEl.cloneNode(true) as HTMLElement;
162
+ // Resource events still fire on inert nodes. Remove handlers before any
163
+ // media copying or insertion can reload a resource in the destination state.
164
+ for (const el of [clone, ...clone.querySelectorAll('*')]) {
165
+ for (const attr of [...el.attributes]) {
166
+ if (
167
+ attr.name === 'id' ||
168
+ attr.name === 'data-action' ||
169
+ attr.name.toLowerCase().startsWith('on')
170
+ )
171
+ el.removeAttribute(attr.name);
172
+ }
173
+ }
162
174
  copyLiveState(passageEl, clone);
163
175
  pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
164
176
 
@@ -181,18 +193,11 @@ function createSnapshot(
181
193
  embedded.replaceWith(placeholder);
182
194
  });
183
195
 
184
- // Strip id attributes to avoid duplicates
185
- clone.removeAttribute('id');
186
- const idEls = clone.querySelectorAll('[id]');
187
- for (let i = 0; i < idEls.length; i++) {
188
- idEls[i]!.removeAttribute('id');
189
- }
190
-
191
196
  // Disable interaction
192
197
  clone.style.pointerEvents = 'none';
193
198
  clone.style.userSelect = 'none';
194
199
  // Visual only: out of the tab order and the accessibility tree, and its
195
- // controls (copied with their inline handlers) can not be activated
200
+ // controls cannot be activated
196
201
  clone.setAttribute('inert', '');
197
202
  clone.setAttribute('aria-hidden', 'true');
198
203
 
@@ -1,3 +1,4 @@
1
+ import { actionAttributes } from '../../hooks/use-action';
1
2
  import { defineMacro } from '../../define-macro';
2
3
  import { ViewScopeContext } from '../../markup/render';
3
4
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
@@ -17,7 +18,7 @@ defineMacro({
17
18
  // One group per variable in each view (see ViewScopeContext)
18
19
  const view = ctx.hooks.useContext(ViewScopeContext);
19
20
 
20
- const actionId = useVariableAction(ctx, {
21
+ const action = useVariableAction(ctx, {
21
22
  type: 'radiobutton',
22
23
  key: `$${ctx.varName}:${radioValue}`,
23
24
  label: label || radioValue,
@@ -32,7 +33,7 @@ defineMacro({
32
33
  <input
33
34
  type="radio"
34
35
  value={radioValue}
35
- data-action={actionId || undefined}
36
+ {...actionAttributes(action, {})}
36
37
  name={view ? `radio-${view}-${ctx.varName}` : `radio-${ctx.varName}`}
37
38
  checked={ctx.value === radioValue}
38
39
  onChange={() => ctx.setValue!(radioValue)}
@@ -110,7 +110,6 @@ export function useDetachedBody(): (children: ASTNode[]) => void {
110
110
  const inIteration = useContext(ItemEditContext);
111
111
  const hasLeft = useContext(OutgoingContext);
112
112
  const displayOnly = useContext(DisplayOnlyContext);
113
- const actionsDisabled = useContext(ActionsDisabledContext);
114
113
 
115
114
  const mounted = useRef<HTMLElement[]>([]);
116
115
  useEffect(() => {
@@ -156,9 +155,7 @@ export function useDetachedBody(): (children: ASTNode[]) => void {
156
155
  <ItemEditContext.Provider value={inIteration}>
157
156
  <OutgoingContext.Provider value={hasLeft}>
158
157
  <DisplayOnlyContext.Provider value={displayOnly}>
159
- <ActionsDisabledContext.Provider
160
- value={actionsDisabled}
161
- >
158
+ <ActionsDisabledContext.Provider value={true}>
162
159
  {renderNodes(children, {
163
160
  nobr,
164
161
  inline,
@@ -1,6 +1,10 @@
1
1
  import { h } from 'preact';
2
2
  import { defineMacro, type MacroContext } from '../../define-macro';
3
- import type { UseActionOptions } from '../../hooks/use-action';
3
+ import {
4
+ actionAttributes,
5
+ useControlAction,
6
+ type UseActionOptions,
7
+ } from '../../hooks/use-action';
4
8
  import { display } from './display';
5
9
 
6
10
  /** The story variable a `storeVar` macro binds: its first parameter. */
@@ -16,12 +20,12 @@ export const VARIABLE_PARAMETER = {
16
20
  * gives another.
17
21
  */
18
22
  export function useVariableAction(
19
- ctx: Pick<MacroContext, 'useAction' | 'id' | 'varName' | 'value'>,
23
+ ctx: Pick<MacroContext, 'id' | 'varName' | 'value'>,
20
24
  action: Omit<UseActionOptions, 'key' | 'authorId' | 'variable'> & {
21
25
  key?: string;
22
26
  },
23
- ): string {
24
- return ctx.useAction({
27
+ ): ReturnType<typeof useControlAction> {
28
+ return useControlAction({
25
29
  key: `$${ctx.varName}`,
26
30
  authorId: ctx.id,
27
31
  variable: ctx.varName,
@@ -54,7 +58,7 @@ export function defineInputMacro(
54
58
  render(_props, ctx) {
55
59
  const placeholder = ctx.args.placeholder ?? '';
56
60
 
57
- const actionId = useVariableAction(ctx, {
61
+ const action = useVariableAction(ctx, {
58
62
  type: name,
59
63
  label: placeholder || ctx.varName!,
60
64
  perform: (v) => ctx.setValue!(toValue(v)),
@@ -74,9 +78,7 @@ export function defineInputMacro(
74
78
 
75
79
  return h(type ? 'input' : 'textarea', {
76
80
  type,
77
- id: ctx.id,
78
- 'data-action': actionId || undefined,
79
- class: ctx.cls,
81
+ ...actionAttributes(action, ctx),
80
82
  value: shown,
81
83
  placeholder,
82
84
  onInput: (e: Event) => {
@@ -50,7 +50,6 @@ import {
50
50
  checkParameterTypes,
51
51
  registerMacro,
52
52
  registerMacroText,
53
- registerSubMacro,
54
53
  registerMacroMetadata,
55
54
  } from './registry';
56
55
  import type {
@@ -323,8 +322,5 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
323
322
  source,
324
323
  });
325
324
 
326
- if (config.subMacros) {
327
- for (const sub of config.subMacros) registerSubMacro(sub);
328
- }
329
325
  setDefinedBlockMacro(config.name, isBlock);
330
326
  }
@@ -22,6 +22,7 @@ import {
22
22
  relinkPath,
23
23
  pathKey,
24
24
  sharedPaths,
25
+ type ObjectPath,
25
26
  type PathChange,
26
27
  } from './structural';
27
28
  import { getByPath, setByPath } from './utils/object-path';
@@ -93,7 +94,7 @@ type Cloner = <T>(value: T) => T;
93
94
  */
94
95
  function clonerFor(
95
96
  target: object,
96
- paths?: ReadonlyMap<object, string[]>,
97
+ paths?: ReadonlyMap<object, ObjectPath>,
97
98
  ): Cloner {
98
99
  const seen = paths ? existingObjects(paths, target) : new Map();
99
100
  // Immer does not finalize a draft held as a Map key or Set member, so an
@@ -106,7 +107,7 @@ function clonerFor(
106
107
  const plain = currentDraft(copy) as object;
107
108
  // Where the object is in an entry of a Map or Set the path cannot be
108
109
  // written (see getByEntryPath): that entry keeps its own
109
- if (!path.some(isEntryKey)) {
110
+ if (path.every((segment): segment is string => !isEntryKey(segment))) {
110
111
  setByPath(target as Record<string, unknown>, path, plain);
111
112
  }
112
113
  seen.set(original, plain);
@@ -117,7 +118,7 @@ function clonerFor(
117
118
 
118
119
  /** One cloner per target copy, made when first used. */
119
120
  const clonersFor = (
120
- paths?: (target: object) => ReadonlyMap<object, string[]>,
121
+ paths?: (target: object) => ReadonlyMap<object, ObjectPath>,
121
122
  ) => {
122
123
  const made = new Map<object, Cloner>();
123
124
  return (target: object): Cloner => {
@@ -697,11 +698,14 @@ export function executeMutation(
697
698
  changesBetween(mergedLocals, localsClone, true).map((c) => c.path[0]!),
698
699
  );
699
700
  for (const group of sharedPaths(localsClone)) {
700
- if (group.some((path) => changed.has(path[0]!))) {
701
+ if (
702
+ group.some((path) => typeof path[0] === 'string' && changed.has(path[0]))
703
+ ) {
701
704
  // Not a value kept by reference (an unregistered class instance)
702
705
  for (const path of group) {
703
- if (localsClone[path[0]!] !== mergedLocals[path[0]!]) {
704
- changed.add(path[0]!);
706
+ const key = path[0];
707
+ if (typeof key === 'string' && localsClone[key] !== mergedLocals[key]) {
708
+ changed.add(key);
705
709
  }
706
710
  }
707
711
  }
@@ -0,0 +1,59 @@
1
+ import { parse, postprocess, preprocess } from 'micromark';
2
+ import { analyzeMarkup } from '../markup/parse';
3
+ import { markdownOptions } from '../markup/markdown';
4
+ import type { PairedNode } from '../markup/pair';
5
+
6
+ /** Source lines that belong to a fenced block in a runtime Markdown document. */
7
+ export function fencedCodeLines(
8
+ source: string,
9
+ isBlock: (name: string) => boolean,
10
+ ): Set<number> {
11
+ const found = new Set<number>();
12
+ // Most passages contain no fence; avoid parsing their Markdown again.
13
+ if (!/`{3}|~{3}/.test(source)) return found;
14
+ const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
15
+
16
+ function visit(nodes: PairedNode[]): void {
17
+ let markdown = '';
18
+ const spans: { start: number; end: number; node: PairedNode }[] = [];
19
+ for (const node of nodes) {
20
+ const start = markdown.length;
21
+ // The renderer substitutes non-text nodes before reading Markdown.
22
+ // Their bodies are separate documents, including each macro branch.
23
+ markdown +=
24
+ node.token.type === 'text'
25
+ ? node.token.value
26
+ : '<span data-tw=0:0></span>';
27
+ spans.push({ start, end: markdown.length, node });
28
+ if (
29
+ node.body &&
30
+ !(node.token.type === 'macro' && node.token.name === 'do')
31
+ ) {
32
+ visit(node.body.children);
33
+ for (const branch of node.body.branches) visit(branch.children);
34
+ }
35
+ }
36
+ const events = postprocess(
37
+ parse(markdownOptions())
38
+ .document()
39
+ .write(preprocess()(markdown, undefined, true)),
40
+ );
41
+ for (const [event, token] of events) {
42
+ if (event !== 'enter' || token.type !== 'codeFenced') continue;
43
+ for (const span of spans) {
44
+ const start = Math.max(token.start.offset, span.start);
45
+ const end = Math.min(token.end.offset, span.end);
46
+ if (start >= end) continue;
47
+ const text = span.node.token.type === 'text';
48
+ const a = text ? span.node.start + start - span.start : span.node.start;
49
+ const b = text ? span.node.start + end - span.start : span.node.end;
50
+ const first = source.slice(0, a).split('\n').length - 1;
51
+ const last = source.slice(0, Math.max(a, b - 1)).split('\n').length - 1;
52
+ for (let line = first; line <= last; line++) found.add(line);
53
+ }
54
+ }
55
+ }
56
+
57
+ visit(nodes);
58
+ return found;
59
+ }