@rohal12/spindle 0.59.20 → 0.59.22

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.
@@ -6,6 +6,7 @@ import {
6
6
  LocalsValuesContext,
7
7
  NobrContext,
8
8
  InlineContext,
9
+ StructuralContext,
9
10
  WidgetChildrenContext,
10
11
  } from '../../markup/render';
11
12
  import type { ASTNode } from '../../markup/ast';
@@ -51,7 +52,7 @@ const frozenAlways = () => true;
51
52
  */
52
53
  export function useDetachedBody(): (children: ASTNode[]) => void {
53
54
  const updater = useContext(LocalsUpdateContext);
54
- const { nobr, inline } = useRenderOptions();
55
+ const { nobr, inline, structural } = useRenderOptions();
55
56
  const widgetChildren = useContext(WidgetChildrenContext);
56
57
  const repeat = useContext(RepeatContext);
57
58
  const closeDialog = useContext(DialogCloseContext);
@@ -85,17 +86,24 @@ export function useDetachedBody(): (children: ASTNode[]) => void {
85
86
  <LocalsValuesContext.Provider value={locals}>
86
87
  <NobrContext.Provider value={nobr}>
87
88
  <InlineContext.Provider value={inline}>
88
- <WidgetChildrenContext.Provider value={widgetChildren}>
89
- <RepeatContext.Provider value={repeat}>
90
- <DialogCloseContext.Provider value={closeDialog}>
91
- <ItemEditContext.Provider value={inIteration}>
92
- <OutgoingContext.Provider value={hasLeft}>
93
- {renderNodes(children, { nobr, inline, locals })}
94
- </OutgoingContext.Provider>
95
- </ItemEditContext.Provider>
96
- </DialogCloseContext.Provider>
97
- </RepeatContext.Provider>
98
- </WidgetChildrenContext.Provider>
89
+ <StructuralContext.Provider value={structural}>
90
+ <WidgetChildrenContext.Provider value={widgetChildren}>
91
+ <RepeatContext.Provider value={repeat}>
92
+ <DialogCloseContext.Provider value={closeDialog}>
93
+ <ItemEditContext.Provider value={inIteration}>
94
+ <OutgoingContext.Provider value={hasLeft}>
95
+ {renderNodes(children, {
96
+ nobr,
97
+ inline,
98
+ structural,
99
+ locals,
100
+ })}
101
+ </OutgoingContext.Provider>
102
+ </ItemEditContext.Provider>
103
+ </DialogCloseContext.Provider>
104
+ </RepeatContext.Provider>
105
+ </WidgetChildrenContext.Provider>
106
+ </StructuralContext.Provider>
99
107
  </InlineContext.Provider>
100
108
  </NobrContext.Provider>
101
109
  </LocalsValuesContext.Provider>
@@ -227,6 +227,10 @@ export function useModalFocus(
227
227
  (next ?? (backwards ? last : first)).focus();
228
228
  };
229
229
 
230
+ // The media element whose native controls Tab is stepping through
231
+ let steppingMedia: { el: HTMLMediaElement; backwards: boolean } | null =
232
+ null;
233
+
230
234
  const onKeyDown = (e: KeyboardEvent) => {
231
235
  if (!top()) return;
232
236
 
@@ -239,8 +243,21 @@ export function useModalFocus(
239
243
  }
240
244
 
241
245
  if (e.key !== 'Tab') return;
246
+ // The controls of a media element are in its user-agent shadow tree,
247
+ // where the element stays the active one: they step through them
248
+ // natively, and onFocusIn takes over where focus leaves the element
249
+ // (#444).
250
+ const active = document.activeElement;
251
+ if (active instanceof HTMLMediaElement && active.controls) {
252
+ steppingMedia = { el: active, backwards: e.shiftKey };
253
+ return;
254
+ }
242
255
  e.preventDefault();
243
- moveFocus(document.activeElement, e.shiftKey);
256
+ moveFocus(active, e.shiftKey);
257
+ };
258
+ // Clicking elsewhere ends the stepping through the controls
259
+ const onPointerDown = () => {
260
+ steppingMedia = null;
244
261
  };
245
262
 
246
263
  // Key events inside an embedded document never reach this one (#425).
@@ -290,6 +307,13 @@ export function useModalFocus(
290
307
  // document can't be reached, is brought back in.
291
308
  const onFocusIn = (e: FocusEvent) => {
292
309
  const target = e.target;
310
+ if (steppingMedia && target !== steppingMedia.el && top()) {
311
+ // Focus left the media controls: on to the modal's next control
312
+ const { el, backwards } = steppingMedia;
313
+ steppingMedia = null;
314
+ moveFocus(el, backwards);
315
+ return;
316
+ }
293
317
  if (!top() || !(target instanceof Node) || panel.contains(target)) return;
294
318
  if (target === document.body || target === document.documentElement) {
295
319
  return;
@@ -298,6 +322,22 @@ export function useModalFocus(
298
322
  };
299
323
 
300
324
  document.addEventListener('keydown', onKeyDown, { signal });
325
+ document.addEventListener('pointerdown', onPointerDown, {
326
+ capture: true,
327
+ signal,
328
+ });
329
+ // Focus that leaves the media element for nothing (past its last control,
330
+ // with no tab stop after it in the document) sends no focusin: the
331
+ // modal's next control takes it at once.
332
+ const onFocusOut = (e: FocusEvent) => {
333
+ const pending = steppingMedia;
334
+ if (!pending || e.target !== pending.el || e.relatedTarget || !top()) {
335
+ return;
336
+ }
337
+ steppingMedia = null;
338
+ moveFocus(pending.el, pending.backwards);
339
+ };
340
+ document.addEventListener('focusout', onFocusOut, { signal });
301
341
  document.addEventListener('focusin', onFocusIn, { signal });
302
342
  return () => {
303
343
  controller.abort();
@@ -4,6 +4,7 @@ import {
4
4
  LocalsValuesContext,
5
5
  NobrContext,
6
6
  RawTextContext,
7
+ StructuralContext,
7
8
  } from '../markup/render';
8
9
 
9
10
  /**
@@ -15,12 +16,14 @@ export function useRenderOptions(): {
15
16
  nobr: boolean;
16
17
  inline: boolean;
17
18
  raw: boolean;
19
+ structural: boolean;
18
20
  locals: Record<string, unknown>;
19
21
  } {
20
22
  return {
21
23
  nobr: useContext(NobrContext),
22
24
  inline: useContext(InlineContext),
23
25
  raw: useContext(RawTextContext),
26
+ structural: useContext(StructuralContext),
24
27
  locals: useContext(LocalsValuesContext),
25
28
  };
26
29
  }
@@ -52,6 +52,13 @@ export const InterfaceContext = createContext(false);
52
52
  * Macro and widget bodies read it so their content stays inline too.
53
53
  */
54
54
  export const InlineContext = createContext(false);
55
+ /**
56
+ * True while rendering the content of a structural HTML element (see
57
+ * STRUCTURAL_ELEMENTS) whose own children are all elements: macro and widget
58
+ * bodies read it so the elements they produce (the rows of a `{for}`) stay
59
+ * its direct children (#436). An element resets it for its own content.
60
+ */
61
+ export const StructuralContext = createContext(false);
55
62
  /**
56
63
  * True while rendering inside an element whose content is not markdown: SVG
57
64
  * (whose namespace `<p>` wrappers would break) and the preformatted `<pre>`
@@ -684,7 +691,13 @@ function leadingSummaryIndex(nodes: ASTNode[]): number {
684
691
 
685
692
  function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
686
693
  const scope = useTextScope();
687
- const { nobr, locals, raw: inRaw, inline: parentInline } = useRenderOptions();
694
+ const {
695
+ nobr,
696
+ locals,
697
+ raw: inRaw,
698
+ inline: parentInline,
699
+ structural: parentStructural,
700
+ } = useRenderOptions();
688
701
  const inSvg = useContext(SvgContext);
689
702
  const tag = node.tag.toLowerCase();
690
703
  const isSvgRoot = tag === 'svg';
@@ -704,6 +717,7 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
704
717
  // inline containers. The inline flag reaches nested macro/widget bodies via
705
718
  // InlineContext; a block element nested inside resets it.
706
719
  let children: preact.ComponentChildren = undefined;
720
+ let structural = false;
707
721
  if (node.children.length > 0) {
708
722
  if (inRaw || isRawRoot) {
709
723
  children = renderInlineNodes(node.children);
@@ -714,7 +728,7 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
714
728
  tag === 'details' ? leadingSummaryIndex(node.children) : -1;
715
729
  const body = (nodes: ASTNode[]) =>
716
730
  renderNodes(nodes, { nobr, locals, inline: isInline });
717
- const structural =
731
+ structural =
718
732
  STRUCTURAL_ELEMENTS.has(tag) &&
719
733
  node.children.every((n) => n.type !== 'text' || n.value.trim() === '');
720
734
  children = structural ? (
@@ -737,6 +751,13 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
737
751
  </InlineContext.Provider>
738
752
  );
739
753
  }
754
+ if (structural !== parentStructural) {
755
+ children = (
756
+ <StructuralContext.Provider value={structural}>
757
+ {children}
758
+ </StructuralContext.Provider>
759
+ );
760
+ }
740
761
  }
741
762
  }
742
763
  // The content of a foreignObject is HTML again, with HTML attributes
@@ -986,10 +1007,20 @@ export function renderNodes(
986
1007
  inline?: boolean;
987
1008
  /** Literal content (see RawTextContext): no markdown processing. */
988
1009
  raw?: boolean;
1010
+ /** Content of a structural element (see StructuralContext). */
1011
+ structural?: boolean;
989
1012
  },
990
1013
  ): preact.ComponentChildren {
991
1014
  if (nodes.length === 0) return null;
992
1015
  if (options?.raw) return renderInlineNodes(nodes);
1016
+ // Only elements and macros between the children of a table, a list...:
1017
+ // paragraphs would pull the elements they produce out of it (#436)
1018
+ if (
1019
+ options?.structural &&
1020
+ nodes.every((n) => n.type !== 'text' || n.value.trim() === '')
1021
+ ) {
1022
+ return nodes.filter((n) => n.type !== 'text').map(renderSingleNode);
1023
+ }
993
1024
 
994
1025
  // Skip the markdown pipeline when text nodes contain only whitespace.
995
1026
  // This eliminates ~97 redundant micromark + innerHTML calls per render
@@ -39,9 +39,10 @@ const EMAIL_AUTOLINK = /^<[a-zA-Z0-9.!#$%&'*+/=?^_`|~-]+@[a-zA-Z0-9](?:[a-zA-Z0-
39
39
 
40
40
  /**
41
41
  * A link's display text and target, from its text `inner` (at `at` in the
42
- * input), with where the target is written.
42
+ * input), with where the target is written. `indexOf(separator)` finds a
43
+ * separator that is written outside markup (see linkSeparatorIndex).
43
44
  */
44
- function parseLink(inner, at) {
45
+ function parseLink(inner, at, indexOf) {
45
46
  /** The trimmed text from `start` to `end` of inner, and where it is. */
46
47
  const part = (start, end) => {
47
48
  const raw = inner.slice(start, end);
@@ -50,7 +51,7 @@ function parseLink(inner, at) {
50
51
  return { value, start: from, end: from + value.length };
51
52
  };
52
53
  for (const [separator, targetFirst] of LINK_SEPARATORS) {
53
- const idx = inner.indexOf(separator);
54
+ const idx = indexOf(separator);
54
55
  if (idx === -1) continue;
55
56
  const before = part(0, idx);
56
57
  const after = part(idx + separator.length, inner.length);
@@ -168,6 +169,29 @@ let attrCode = false;
168
169
  /** The macro whose raw body is being read. */
169
170
  let rawName = '';
170
171
 
172
+ /**
173
+ * The index in `inner` (at `at` in the input) of the first `separator` that
174
+ * is not inside a {…} of the label: its code (`{if $a || $b}`, a string with
175
+ * a pipe) belongs to the label, not to the link's syntax.
176
+ */
177
+ function linkSeparatorIndex(inner, at, separator) {
178
+ for (let i = 0; i < inner.length; i++) {
179
+ const c = inner.charAt(i);
180
+ if (c === '\\' && /[{}]/.test(inner.charAt(i + 1))) {
181
+ i++;
182
+ } else if (c === LB) {
183
+ // Selectors, then a macro name or the sigil of a variable or expression
184
+ const head = /^(?:[.#][\w-]*)* ?(\/?[a-zA-Z][\w-]*|(?=[$_@%(!]))/.exec(inner.slice(i + 1));
185
+ if (!head) continue;
186
+ const close = hooks.closeBrace(input, at + i + 1 + head[0].length, at + i + 1);
187
+ // One that does not end inside the label is no markup of it
188
+ if (close !== -1 && close < at + inner.length) i = close - at;
189
+ } else if (inner.startsWith(separator, i)) {
190
+ return i;
191
+ }
192
+ }
193
+ return -1;
194
+ }
171
195
  function skipTo(end) {
172
196
  skipEnd = end;
173
197
  return end >= 0;
@@ -369,7 +393,7 @@ Literal
369
393
 
370
394
  LinkLexeme
371
395
  = &{ return !textMode; } "[[" s:Selectors at:Here inner:$LinkText "]]" {
372
- return withSelectors(lexeme('link', location(), parseLink(inner, at)), s);
396
+ return withSelectors(lexeme('link', location(), parseLink(inner, at, (separator) => linkSeparatorIndex(inner, at, separator))), s);
373
397
  }
374
398
  / &{ return !textMode; } "[[" { fail('Unclosed link: [[ without ]]', location()); }
375
399
 
@@ -88,6 +88,9 @@ export async function initSaveSystem(): Promise<void> {
88
88
 
89
89
  // --- Operation order ---
90
90
 
91
+ /** The browser lock every storage operation holds, across tabs. */
92
+ const OPERATION_LOCK = 'spindle-saves';
93
+
91
94
  /** Tail of the queue every storage operation runs through. */
92
95
  let operationQueue: Promise<unknown> = Promise.resolve();
93
96
 
@@ -105,7 +108,9 @@ let operationQueue: Promise<unknown> = Promise.resolve();
105
108
  * must never wait for another operation queued after it.
106
109
  */
107
110
  function inOrder<T>(op: () => Promise<T>): Promise<T> {
108
- const run = operationQueue.then(op);
111
+ // Under a lock shared by the tabs too: another tab deleting a save between
112
+ // an overwrite's read and write would leave the slot empty (#435)
113
+ const run = operationQueue.then(() => withTabLock(OPERATION_LOCK, op));
109
114
  operationQueue = run.catch(() => {});
110
115
  return run;
111
116
  }
@@ -332,6 +337,8 @@ async function createSaveNow(
332
337
 
333
338
  const record = storedRecord(meta, payload);
334
339
  await (await getBackend()).putSave(record);
340
+ // Save dialogs open in other tabs list it (#445)
341
+ announceSlots(ifid);
335
342
  return record;
336
343
  }
337
344
 
@@ -418,6 +425,8 @@ export function deleteSaveById(saveId: string): Promise<void> {
418
425
  if (!record) return;
419
426
 
420
427
  await emptySlotsHolding(record.meta.ifid, (id) => id === saveId);
428
+ // A save in no slot is gone from the other tabs' dialogs too (#445)
429
+ announceSlots(record.meta.ifid);
421
430
  });
422
431
  }
423
432
 
@@ -436,6 +445,7 @@ export function renameSave(saveId: string, newTitle: string): Promise<void> {
436
445
  },
437
446
  };
438
447
  await backend.putSave(updated);
448
+ announceSlots(updated.meta.ifid);
439
449
  });
440
450
  }
441
451
 
@@ -975,6 +985,7 @@ export function importSave(data: unknown, ifid: string): Promise<SaveRecord> {
975
985
  return inOrder(async () => {
976
986
  const record = await prepareImport(data, ifid);
977
987
  await (await getBackend()).putSave(record);
988
+ announceSlots(ifid);
978
989
  return record;
979
990
  });
980
991
  }
@@ -1100,6 +1111,8 @@ export function deletePlaythroughData(
1100
1111
  // Clear the slots that held deleted saves (pointer and slot index)
1101
1112
  const deletedSet = new Set(deletedSaveIds);
1102
1113
  await emptySlotsHolding(ifid, (id) => deletedSet.has(id));
1114
+ // Saves in no slot are gone from other tabs' dialogs too
1115
+ announceSlots(ifid);
1103
1116
 
1104
1117
  if (replacement && (await replacement.current) === playthroughId) {
1105
1118
  await startNewPlaythroughNow(ifid, replacement.id);
@@ -197,6 +197,16 @@ function lsDel(key: string): void {
197
197
  localStorage.removeItem(key);
198
198
  }
199
199
 
200
+ /** Put an item back as it was (`raw` null: absent); best effort. */
201
+ function lsRestore(key: string, raw: string | null): void {
202
+ try {
203
+ if (raw === null) localStorage.removeItem(key);
204
+ else localStorage.setItem(key, raw);
205
+ } catch {
206
+ // The quota forbids even the old value: nothing more to do
207
+ }
208
+ }
209
+
200
210
  function lsIndex(key: string): string[] {
201
211
  return lsGet<string[]>(key) ?? [];
202
212
  }
@@ -239,13 +249,22 @@ export function createLocalStorageBackend(): StorageBackend {
239
249
  // after a restart, under the new playthrough) leaves the old list
240
250
  const previous = lsGet<T>(`${prefix}${key}`);
241
251
  const lists = listsOf(value);
242
- if (previous !== undefined) {
243
- for (const list of listsOf(previous)) {
244
- if (!lists.includes(list)) lsIndexRemove(list, key);
245
- }
252
+ const obsolete =
253
+ previous === undefined
254
+ ? []
255
+ : listsOf(previous).filter((list) => !lists.includes(list));
256
+ // A write that fails (the quota) puts back what it changed: a record
257
+ // no index lists is neither shown nor cleared with its story (#443)
258
+ const touched = [`${prefix}${key}`, ...obsolete, ...lists];
259
+ const before = touched.map((k) => localStorage.getItem(k));
260
+ try {
261
+ for (const list of obsolete) lsIndexRemove(list, key);
262
+ lsSet(`${prefix}${key}`, value);
263
+ for (const list of lists) lsIndexAdd(list, key);
264
+ } catch (err) {
265
+ touched.forEach((k, i) => lsRestore(k, before[i] ?? null));
266
+ throw err;
246
267
  }
247
- lsSet(`${prefix}${key}`, value);
248
- for (const list of lists) lsIndexAdd(list, key);
249
268
  },
250
269
  async delete(key) {
251
270
  const record = lsGet<T>(`${prefix}${key}`);
package/src/store.ts CHANGED
@@ -674,6 +674,19 @@ let slotLoadApplying: number | null = null;
674
674
  /** The playthrough the slot load calling loadFromPayload leaves. */
675
675
  let slotLoadLeaving: Promise<string> | null = null;
676
676
 
677
+ /**
678
+ * Take a place in the order of replacements for a load that reads before it
679
+ * applies (the save dialog's): see isStateReplacementSuperseded.
680
+ */
681
+ export function issueStateReplacement(): number {
682
+ return ++stateReplacementsIssued;
683
+ }
684
+
685
+ /** Whether a replacement issued after `n` has been applied. */
686
+ export function isStateReplacementSuperseded(n: number): boolean {
687
+ return latestStateApplied > n;
688
+ }
689
+
677
690
  /** A replacement of the game state applied at its call. */
678
691
  function replaceStateNow(): void {
679
692
  applyReplacement(++stateReplacementsIssued);
@@ -976,11 +989,14 @@ export interface StoryState {
976
989
  * passed to the `beforeload`/`afterload` events. Pass the save's
977
990
  * `playthroughId` when loading a save: the game moves to that playthrough
978
991
  * (no change if it is the current one). Restoring the session passes none.
992
+ * `issued` is the place in the order of replacements a load that read
993
+ * before applying took at its call (see issueStateReplacement).
979
994
  */
980
995
  loadFromPayload: (
981
996
  payload: SavePayload,
982
997
  slot?: string,
983
998
  playthroughId?: string,
999
+ issued?: number,
984
1000
  ) => void;
985
1001
  getHistoryVariables: (index: number) => Record<string, unknown>;
986
1002
  setTransition: (config: TransitionConfig | null) => void;
@@ -1709,8 +1725,9 @@ export const useStoryStore = create<StoryState>()(
1709
1725
  payload: SavePayload,
1710
1726
  slot?: string,
1711
1727
  playthroughId?: string,
1728
+ issued?: number,
1712
1729
  ) => {
1713
- const applying = slotLoadApplying;
1730
+ const applying = slotLoadApplying ?? issued;
1714
1731
  slotLoadApplying = null;
1715
1732
  const leaving = slotLoadLeaving;
1716
1733
  slotLoadLeaving = null;
package/src/styles.css CHANGED
@@ -185,6 +185,17 @@ tw-storydata {
185
185
  font-size: 0.9em;
186
186
  }
187
187
 
188
+ @media (max-width: 600px) {
189
+ .story-menubar {
190
+ flex-wrap: wrap;
191
+ padding: 0.5em 0.75em;
192
+ }
193
+
194
+ .story-menubar .story-title {
195
+ flex: 1 1 100%;
196
+ }
197
+ }
198
+
188
199
  .story-title {
189
200
  flex: 1;
190
201
  font-weight: 600;