@rohal12/spindle 0.64.22 → 0.64.24

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.
@@ -1,5 +1,6 @@
1
1
  import {
2
- useMemo,
2
+ useCallback,
3
+ useContext,
3
4
  useEffect,
4
5
  useLayoutEffect,
5
6
  useRef,
@@ -14,12 +15,17 @@ import {
14
15
  InterfaceContext,
15
16
  useViewScope,
16
17
  } from '../markup/render';
17
- import { useStoryFields } from '../hooks/use-story-fields';
18
+ import {
19
+ LateMountContext,
20
+ OutgoingContext,
21
+ useStoryFields,
22
+ } from '../hooks/use-story-fields';
18
23
  import type { Passage as PassageData } from '../parser';
19
24
  import { sourceLocationOf } from '../utils/source-location';
20
25
  import { emitFromRender } from '../event-emitter';
21
26
  import { duringEntryRender } from '../triggers';
22
27
  import type { ComponentChildren } from 'preact';
28
+ import { memo } from 'preact/compat';
23
29
  import {
24
30
  EntryRenderContext,
25
31
  markPassageRendered,
@@ -52,21 +58,68 @@ export function renderPassageContent(passage: PassageData) {
52
58
  }
53
59
 
54
60
  /**
55
- * The content of a special passage shown with every passage (PassageHeader,
56
- * PassageFooter, PassageDone), or null. One that fails to render is logged
57
- * and left out, so it can't take the passage down with it.
61
+ * A passage's rendered content, drawn again only when the passage or its
62
+ * text changes (the props are compared shallowly, so a parent re-rendering
63
+ * with the same passage skips it).
64
+ *
65
+ * It is a component and not a vnode kept by `useMemo`. A kept vnode that is
66
+ * placed again carries Preact's links (its parent, its rendered children) to
67
+ * the tree it was first placed in. A navigation's tree reaches the kept vnode
68
+ * of the passage on its way out, so every tree held the one before it and
69
+ * none was ever freed. The `content` prop is only here so that an edit of
70
+ * the passage text in place draws it again.
71
+ */
72
+ const PassageBody = memo(function PassageBody({
73
+ passage,
74
+ }: {
75
+ passage: PassageData;
76
+ content: string;
77
+ }) {
78
+ try {
79
+ return <>{renderPassageContent(passage)}</>;
80
+ } catch (err) {
81
+ return (
82
+ <div class="error">
83
+ Error parsing passage &ldquo;{passage.name}&rdquo;
84
+ {sourceLocationOf(passage)}: {errorMessage(err)}
85
+ </div>
86
+ );
87
+ }
88
+ });
89
+
90
+ /**
91
+ * A special passage shown with every passage (PassageHeader, PassageFooter,
92
+ * PassageDone), in its wrapper; nothing if it has no content. One that fails
93
+ * to render is logged and left out, so it can't take the passage down with
94
+ * it. Memoized like PassageBody.
58
95
  */
59
- function renderSpecialPassage(passage: PassageData | undefined) {
60
- if (!passage) return null;
96
+ const SpecialPassage = memo(function SpecialPassage({
97
+ passage,
98
+ kind,
99
+ }: {
100
+ passage: PassageData;
101
+ content: string;
102
+ kind: 'header' | 'footer' | 'done';
103
+ }) {
104
+ let content: ComponentChildren;
61
105
  try {
62
- return renderPassageContent(passage);
106
+ content = renderPassageContent(passage);
63
107
  } catch (err) {
64
108
  console.error(`spindle: Error in ${passage.name}:`, err);
65
109
  return null;
66
110
  }
67
- }
111
+ if (!content) return null;
112
+ if (kind === 'done') {
113
+ return (
114
+ <EntryRenderBoundary>
115
+ <div hidden>{content}</div>
116
+ </EntryRenderBoundary>
117
+ );
118
+ }
119
+ return <div class={`passage-${kind}`}>{content}</div>;
120
+ });
68
121
 
69
- interface PassageProps {
122
+ export interface PassageProps {
70
123
  passage: PassageData;
71
124
  dataTransition?: string;
72
125
  /** The navigation this passage displays; omitted for placeholders. */
@@ -102,46 +155,27 @@ export function Passage({
102
155
  const isCodePassage = CODE_PASSAGES.has(passage.name);
103
156
  const [doneReady, setDoneReady] = useState(false);
104
157
 
105
- const content = useMemo(() => {
106
- try {
107
- return renderPassageContent(passage);
108
- } catch (err) {
109
- return (
110
- <div class="error">
111
- Error parsing passage &ldquo;{passage.name}&rdquo;
112
- {sourceLocationOf(passage)}: {errorMessage(err)}
113
- </div>
114
- );
115
- }
116
- }, [passage.content, passage.name]);
117
-
118
158
  // Code passages are shown without the special passages
119
159
  const special = (name: string) =>
120
160
  isCodePassage ? undefined : storyData?.passages.get(name);
121
- const headerPassage = special('PassageHeader');
122
- const footerPassage = special('PassageFooter');
161
+ const specialPassage = (name: string, kind: 'header' | 'footer' | 'done') => {
162
+ const found = special(name);
163
+ return found ? (
164
+ <SpecialPassage
165
+ passage={found}
166
+ content={found.content}
167
+ kind={kind}
168
+ />
169
+ ) : null;
170
+ };
123
171
  const donePassage = special('PassageDone');
124
172
 
125
- const headerContent = useMemo(
126
- () => renderSpecialPassage(headerPassage),
127
- [headerPassage?.content],
128
- );
129
- const footerContent = useMemo(
130
- () => renderSpecialPassage(footerPassage),
131
- [footerPassage?.content],
132
- );
133
-
134
173
  // Defer PassageDone to after DOM commit
135
174
  useEffect(() => {
136
175
  if (donePassage) setDoneReady(true);
137
176
  return () => setDoneReady(false);
138
177
  }, [passage.name]);
139
178
 
140
- const doneContent = useMemo(
141
- () => (doneReady ? renderSpecialPassage(donePassage) : null),
142
- [doneReady, donePassage?.content],
143
- );
144
-
145
179
  // Signal that this passage's DOM is committed (after descendants' layout
146
180
  // effects, before paint). Runs once per mount: PassageDisplay keys the
147
181
  // Passage so every navigation that shows a passage mounts a new one.
@@ -156,28 +190,42 @@ export function Passage({
156
190
  }
157
191
  }, [passage.name, navigationId]);
158
192
 
193
+ // The macros that mount after this passage was left must not run (see
194
+ // LateMountContext). Those of its first render are not late: that render
195
+ // may itself navigate away, and the macros after the navigation still run.
196
+ const hasLeft = useContext(OutgoingContext);
197
+ const committed = useRef(false);
198
+ useLayoutEffect(() => {
199
+ committed.current = true;
200
+ }, []);
201
+ const lateMount = useCallback(
202
+ () => committed.current && !!hasLeft?.(),
203
+ [hasLeft],
204
+ );
205
+
159
206
  const nobr = passage.tags.includes('nobr');
160
207
  const viewScope = useViewScope();
161
208
 
162
209
  const inner = (
163
210
  <InterfaceContext.Provider value={false}>
164
211
  <ViewScopeContext.Provider value={viewScope}>
165
- <div
166
- ref={elRef}
167
- class="passage"
168
- data-passage={passage.name}
169
- data-tags={passage.tags.join(' ')}
170
- data-transition={dataTransition}
171
- >
172
- {headerContent && <div class="passage-header">{headerContent}</div>}
173
- {content}
174
- {footerContent && <div class="passage-footer">{footerContent}</div>}
175
- {doneContent && (
176
- <EntryRenderBoundary>
177
- <div hidden>{doneContent}</div>
178
- </EntryRenderBoundary>
179
- )}
180
- </div>
212
+ <LateMountContext.Provider value={lateMount}>
213
+ <div
214
+ ref={elRef}
215
+ class="passage"
216
+ data-passage={passage.name}
217
+ data-tags={passage.tags.join(' ')}
218
+ data-transition={dataTransition}
219
+ >
220
+ {specialPassage('PassageHeader', 'header')}
221
+ <PassageBody
222
+ passage={passage}
223
+ content={passage.content}
224
+ />
225
+ {specialPassage('PassageFooter', 'footer')}
226
+ {doneReady && specialPassage('PassageDone', 'done')}
227
+ </div>
228
+ </LateMountContext.Provider>
181
229
  </ViewScopeContext.Provider>
182
230
  </InterfaceContext.Provider>
183
231
  );
@@ -7,7 +7,10 @@ import { defineMacro } from '../../define-macro';
7
7
  import { MacroError, logMacroError } from './MacroError';
8
8
  import { currentSourceLocation } from '../../utils/source-location';
9
9
  import { checkVariableName, ownValue } from '../../utils/namespace';
10
- import { PendingIterationContext } from '../../hooks/use-story-fields';
10
+ import {
11
+ LateMountContext,
12
+ PendingIterationContext,
13
+ } from '../../hooks/use-story-fields';
11
14
 
12
15
  /**
13
16
  * The previous output before the first successful evaluation. Distinct from
@@ -130,6 +133,8 @@ defineMacro({
130
133
  const name = target.slice(1);
131
134
  const localsUpdate = isLocal ? ctx.update : null;
132
135
  const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
136
+ // In a passage that was left it must not compute (see LateMountContext)
137
+ const tooLate = ctx.hooks.useContext(LateMountContext)?.() ?? false;
133
138
 
134
139
  const prevOutput = ctx.hooks.useRef<unknown>(UNSET);
135
140
  // The navigation the target was last checked in
@@ -151,7 +156,7 @@ defineMacro({
151
156
  const ran = ctx.hooks.useRef(false);
152
157
  if (!ran.current) {
153
158
  ran.current = true;
154
- compute();
159
+ if (!tooLate) compute();
155
160
  }
156
161
 
157
162
  // The merged values only decide when to recompute; computeAndApply reads
@@ -160,7 +165,7 @@ defineMacro({
160
165
  ctx.hooks.useLayoutEffect(() => {
161
166
  // A queued effect can outlive the loop state its locals belong to.
162
167
  // Let the owner reconcile first, dropping any removed iterations.
163
- if (!pendingIteration?.(useStoryStore.getState())) compute();
168
+ if (!tooLate && !pendingIteration?.(useStoryStore.getState())) compute();
164
169
  }, [ctx.merged, pendingIteration]);
165
170
 
166
171
  return null;
@@ -1,4 +1,5 @@
1
1
  import { useStoryStore } from '../../store';
2
+ import { LateMountContext } from '../../hooks/use-story-fields';
2
3
  import { defineMacro } from '../../define-macro';
3
4
  import { evaluatePassageName } from './macro-args';
4
5
  import { logMacroError, MacroError } from './MacroError';
@@ -10,7 +11,11 @@ defineMacro({
10
11
  render(_props, ctx) {
11
12
  // Boxed: anything can be thrown, including null and other falsy values
12
13
  const [failure, setFailure] = ctx.hooks.useState<{ error: unknown }>();
14
+ // Mounting in a passage that was left: it must not navigate (see
15
+ // LateMountContext)
16
+ const tooLate = ctx.hooks.useContext(LateMountContext)?.() ?? false;
13
17
  ctx.hooks.useLayoutEffect(() => {
18
+ if (tooLate) return;
14
19
  // Reported like an error in {do}: thrown out of an effect, it would
15
20
  // abort the rest of the render's effects (e.g. the session could not
16
21
  // be written because the state holds a function). The location is
@@ -1,6 +1,6 @@
1
1
  import { DisplayOnlyContext } from '../../display-only';
2
2
  import { useStoryStore } from '../../store';
3
- import { useStoryFields } from '../../hooks/use-story-fields';
3
+ import { LateMountContext, useStoryFields } from '../../hooks/use-story-fields';
4
4
  import { parseMarkup } from '../../markup/parse';
5
5
  import { NobrContext } from '../../markup/render';
6
6
  import { defineMacro } from '../../define-macro';
@@ -15,6 +15,9 @@ defineMacro({
15
15
  parameters: INCLUDE_PARAMETERS,
16
16
  render(_props, ctx) {
17
17
  const displayOnly = ctx.hooks.useContext(DisplayOnlyContext);
18
+ // Mounting in a passage that was left: it must not count (see
19
+ // LateMountContext)
20
+ const tooLate = ctx.hooks.useContext(LateMountContext)?.() ?? false;
18
21
  const { storyData } = useStoryFields('storyData');
19
22
 
20
23
  const { inline } = ctx.args;
@@ -42,9 +45,10 @@ defineMacro({
42
45
 
43
46
  // Count the inclusion when its content mounts or the passage changes,
44
47
  // not on every render (an unrelated variable update re-renders it)
48
+ // (tooLate is read when the effect runs for the content that mounted)
45
49
  const included = !failure && !!passage;
46
50
  ctx.hooks.useEffect(() => {
47
- if (included && !displayOnly) {
51
+ if (included && !displayOnly && !tooLate) {
48
52
  useStoryStore.getState().trackRender(passageName);
49
53
  }
50
54
  }, [included, passageName, displayOnly]);
@@ -1,4 +1,5 @@
1
- import { useRef } from 'preact/hooks';
1
+ import { useContext, useRef } from 'preact/hooks';
2
+ import { LateMountContext } from '../../hooks/use-story-fields';
2
3
  import { currentSourceLocation } from '../../utils/source-location';
3
4
  import { errorMessage } from '../../utils/error-message';
4
5
 
@@ -34,7 +35,8 @@ export function logMacroError(
34
35
  }
35
36
 
36
37
  /**
37
- * Run `effect` once, during the macro's first render. If it throws, the
38
+ * Run `effect` once, during the macro's first render, unless that is in a
39
+ * passage already left (see LateMountContext). If it throws, the
38
40
  * error is logged under `{macro rawArgs}` and shown in place of the macro
39
41
  * from then on; otherwise the macro renders nothing.
40
42
  */
@@ -42,8 +44,11 @@ export function useRunOnce(macro: string, rawArgs: string, effect: () => void) {
42
44
  // Unset until the effect has run. Boxed: anything can be thrown,
43
45
  // including null and other falsy values.
44
46
  const failure = useRef<{ error: unknown } | null | undefined>(undefined);
47
+ const lateMount = useContext(LateMountContext);
45
48
  if (failure.current === undefined) {
46
49
  failure.current = null;
50
+ // Mounting in a passage that was left: it must not run (see LateMountContext)
51
+ if (lateMount?.()) return null;
47
52
  const location = currentSourceLocation();
48
53
  try {
49
54
  effect();
@@ -11,7 +11,7 @@ import {
11
11
  FrozenStateContext,
12
12
  OutgoingContext,
13
13
  } from '../../hooks/use-story-fields';
14
- import { Passage, renderPassageContent } from '../Passage';
14
+ import { Passage, renderPassageContent, type PassageProps } from '../Passage';
15
15
  import { defineMacro } from '../../define-macro';
16
16
  import { resolveTransition, type ResolvedTransition } from '../../transition';
17
17
  import { skipString } from './arg-utils';
@@ -807,7 +807,13 @@ defineMacro({
807
807
  () => isOutgoing(useStoryStore.getState()),
808
808
  [isOutgoing],
809
809
  );
810
- const lastElement = useRef<preact.VNode | null>(null);
810
+ // What the passage on display was drawn with (see the render below):
811
+ // props, not the vnode, which a vnode of the next render could not
812
+ // be released from (the parent a vnode is placed under stays with it)
813
+ const lastShown = useRef<{
814
+ key: string;
815
+ props: PassageProps;
816
+ } | null>(null);
811
817
 
812
818
  // Container ref for snapshot insertion
813
819
  const containerRef = useRef<HTMLDivElement>(null);
@@ -1001,20 +1007,30 @@ defineMacro({
1001
1007
 
1002
1008
  // Between a navigation and the commit of its passage, the old passage is
1003
1009
  // still mounted. It must not execute against the destination's state, so
1004
- // it keeps the element and the state it last rendered with (#352).
1010
+ // it is drawn with what it was last drawn with (#352): the same props.
1005
1011
  const outgoing = !renderDeferred && displayed.id !== navigationId;
1006
- const passageElement =
1007
- outgoing && lastElement.current
1008
- ? lastElement.current
1009
- : effectivePassage && (
1010
- <Passage
1011
- passage={effectivePassage}
1012
- key={renderDeferred ? 'loading' : `nav-${displayed.id}`}
1013
- dataTransition={renderDeferred ? 'none' : resolvedTypeRef.current}
1014
- navigationId={renderDeferred ? undefined : displayed.id}
1015
- />
1016
- );
1017
- lastElement.current = passageElement || null;
1012
+ const shown =
1013
+ outgoing && lastShown.current
1014
+ ? lastShown.current
1015
+ : effectivePassage
1016
+ ? {
1017
+ key: renderDeferred ? 'loading' : `nav-${displayed.id}`,
1018
+ props: {
1019
+ passage: effectivePassage,
1020
+ dataTransition: renderDeferred
1021
+ ? 'none'
1022
+ : resolvedTypeRef.current,
1023
+ navigationId: renderDeferred ? undefined : displayed.id,
1024
+ },
1025
+ }
1026
+ : null;
1027
+ const passageElement = shown && (
1028
+ <Passage
1029
+ key={shown.key}
1030
+ {...shown.props}
1031
+ />
1032
+ );
1033
+ lastShown.current = shown;
1018
1034
 
1019
1035
  return (
1020
1036
  <div
@@ -34,6 +34,11 @@ import { DialogCloseContext } from '../PassageDialog';
34
34
  import { defineMacro } from '../../define-macro';
35
35
  import { errorMessage } from '../../utils/error-message';
36
36
 
37
+ /** How long a Delete button stays armed without a second press. */
38
+ const ARMED_DELETE_MS = 5000;
39
+ const ARMED_DELETE_LABEL = 'Press again to delete';
40
+ const ARMED_DELETE_HINT = 'Press again to delete this save';
41
+
37
42
  function relativeTime(iso: string): string {
38
43
  const diff = Date.now() - new Date(iso).getTime();
39
44
  const secs = Math.floor(diff / 1000);
@@ -71,6 +76,8 @@ export function SaveManagerContent({
71
76
  } | null>(null);
72
77
  const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());
73
78
  const [renamingId, setRenamingId] = useState<string | null>(null);
79
+ // The save whose Delete button has been pressed once (see handleDelete)
80
+ const [armedId, setArmedId] = useState<string | null>(null);
74
81
  const renameCancelled = useRef(false);
75
82
  const [renameValue, setRenameValue] = useState('');
76
83
  const renameInputRef = useRef<HTMLInputElement>(null);
@@ -137,6 +144,38 @@ export function SaveManagerContent({
137
144
  };
138
145
  }, []);
139
146
 
147
+ // While a Delete button is armed, anything else the player does (a press
148
+ // elsewhere, a key, Escape) or a pause puts it back. Blur and Tab are
149
+ // covered by the button's onBlur; the document listeners cover browsers
150
+ // that do not focus a button on click. Escape disarms only: the dialog
151
+ // stays open.
152
+ useEffect(() => {
153
+ if (armedId === null) return;
154
+ const disarm = () => setArmedId(null);
155
+ const onArmedButton = (e: Event) =>
156
+ e.target instanceof Element && !!e.target.closest('[data-armed]');
157
+ const onPointerDown = (e: Event) => {
158
+ if (!onArmedButton(e)) disarm();
159
+ };
160
+ const onKeyDown = (e: KeyboardEvent) => {
161
+ if (e.key === 'Escape') {
162
+ e.preventDefault();
163
+ e.stopPropagation();
164
+ disarm();
165
+ } else if (!onArmedButton(e)) {
166
+ disarm();
167
+ }
168
+ };
169
+ const timer = window.setTimeout(disarm, ARMED_DELETE_MS);
170
+ document.addEventListener('pointerdown', onPointerDown, true);
171
+ document.addEventListener('keydown', onKeyDown, true);
172
+ return () => {
173
+ clearTimeout(timer);
174
+ document.removeEventListener('pointerdown', onPointerDown, true);
175
+ document.removeEventListener('keydown', onKeyDown, true);
176
+ };
177
+ }, [armedId]);
178
+
140
179
  const toggleCollapse = (id: string) => {
141
180
  setCollapsed((prev) => {
142
181
  const next = new Set(prev);
@@ -229,8 +268,13 @@ export function SaveManagerContent({
229
268
  }
230
269
  };
231
270
 
271
+ /** The first press arms the button; a second press on it deletes. */
232
272
  const handleDelete = async (saveId: string) => {
233
- if (!confirm('Delete this save?')) return;
273
+ if (armedId !== saveId) {
274
+ setArmedId(saveId);
275
+ return;
276
+ }
277
+ setArmedId(null);
234
278
  await runAction('Save deleted', 'Failed to delete save', async () => {
235
279
  await deleteSaveById(saveId);
236
280
  // The save may have been held by a slot; hasSave() and QuickLoad
@@ -475,10 +519,34 @@ export function SaveManagerContent({
475
519
  </button>
476
520
  <button
477
521
  type="button"
478
- class="save-slot-action danger"
522
+ class={
523
+ armedId === save.meta.id
524
+ ? 'save-slot-action danger is-armed'
525
+ : 'save-slot-action danger'
526
+ }
527
+ data-armed={
528
+ armedId === save.meta.id ? 'true' : undefined
529
+ }
530
+ aria-label={
531
+ armedId === save.meta.id
532
+ ? ARMED_DELETE_HINT
533
+ : undefined
534
+ }
535
+ title={
536
+ armedId === save.meta.id
537
+ ? ARMED_DELETE_HINT
538
+ : undefined
539
+ }
479
540
  onClick={() => handleDelete(save.meta.id)}
541
+ onBlur={() =>
542
+ setArmedId((id) =>
543
+ id === save.meta.id ? null : id,
544
+ )
545
+ }
480
546
  >
481
- Delete
547
+ {armedId === save.meta.id
548
+ ? ARMED_DELETE_LABEL
549
+ : 'Delete'}
482
550
  </button>
483
551
  </div>
484
552
  </div>
@@ -517,6 +585,14 @@ export function SaveManagerContent({
517
585
  )}
518
586
  </div>
519
587
 
588
+ <div
589
+ class="saves-sr-only"
590
+ role="status"
591
+ aria-live="polite"
592
+ >
593
+ {armedId !== null ? ARMED_DELETE_HINT : ''}
594
+ </div>
595
+
520
596
  {status && (
521
597
  <div class={`saves-status ${status.type === 'error' ? 'error' : ''}`}>
522
598
  {status.text}
@@ -32,6 +32,19 @@ export const PendingIterationContext = createContext<
32
32
  */
33
33
  export const OutgoingContext = createContext<(() => boolean) | null>(null);
34
34
 
35
+ /**
36
+ * Tells the macros that run code as they mount ({set}, {do}, {unset},
37
+ * {goto}, {computed}, the count of an {include}) whether they come too late: the
38
+ * passage they belong to was on the page and has been left since. State
39
+ * that changed before the navigation can still render new content into the
40
+ * passage on its way out, and its code would run against the destination's
41
+ * state (#352, as #410 for timers). The macros that mount while the passage
42
+ * is first rendered are never late, whatever that render navigates. Null
43
+ * outside a displayed passage, and in a click body, which renders apart
44
+ * from the passage and runs as part of the click.
45
+ */
46
+ export const LateMountContext = createContext<(() => boolean) | null>(null);
47
+
35
48
  /**
36
49
  * Story state fields `keys`, re-rendering when any of them changes (as one
37
50
  * useStoryStore() selector per field would). The result keeps its identity
package/src/styles.css CHANGED
@@ -573,6 +573,25 @@ tw-storydata {
573
573
  background: rgba(239, 83, 80, 0.1);
574
574
  }
575
575
 
576
+ .save-slot-action.danger.is-armed {
577
+ color: #ef5350;
578
+ background: rgba(239, 83, 80, 0.15);
579
+ border-color: rgba(239, 83, 80, 0.5);
580
+ }
581
+
582
+ /* Read by screen readers, not shown: announces an armed Delete button */
583
+ .saves-sr-only {
584
+ position: absolute;
585
+ width: 1px;
586
+ height: 1px;
587
+ margin: -1px;
588
+ padding: 0;
589
+ overflow: hidden;
590
+ clip: rect(0, 0, 0, 0);
591
+ white-space: nowrap;
592
+ border: 0;
593
+ }
594
+
576
595
  .save-slot-new {
577
596
  display: flex;
578
597
  align-items: center;