@rohal12/spindle 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.17.0",
3
+ "version": "0.18.1",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -47,7 +47,7 @@
47
47
  "docs:dev": "vitepress dev docs",
48
48
  "docs:build": "vitepress build docs",
49
49
  "docs:preview": "vitepress preview docs",
50
- "prepublishOnly": "bun run test && bun run build",
50
+ "prepublishOnly": "bun run build && bun run test",
51
51
  "prepare": "husky"
52
52
  },
53
53
  "dependencies": {
@@ -1,20 +1,36 @@
1
- import { useMemo } from 'preact/hooks';
1
+ import { useMemo, useEffect, useState } from 'preact/hooks';
2
2
  import { tokenize } from '../markup/tokenizer';
3
3
  import { buildAST } from '../markup/ast';
4
4
  import { renderNodes } from '../markup/render';
5
+ import { useStoryStore } from '../store';
5
6
  import type { Passage as PassageData } from '../parser';
6
7
  import { sourceLocationOf } from '../utils/source-location';
7
8
 
9
+ export function renderPassageContent(passage: PassageData) {
10
+ const tokens = tokenize(passage.content);
11
+ const ast = buildAST(tokens);
12
+ return renderNodes(ast);
13
+ }
14
+
8
15
  interface PassageProps {
9
16
  passage: PassageData;
10
17
  }
11
18
 
19
+ const CODE_PASSAGES = new Set([
20
+ 'PassageReady',
21
+ 'PassageHeader',
22
+ 'PassageFooter',
23
+ 'PassageDone',
24
+ ]);
25
+
12
26
  export function Passage({ passage }: PassageProps) {
27
+ const storyData = useStoryStore((s) => s.storyData);
28
+ const isCodePassage = CODE_PASSAGES.has(passage.name);
29
+ const [doneReady, setDoneReady] = useState(false);
30
+
13
31
  const content = useMemo(() => {
14
32
  try {
15
- const tokens = tokenize(passage.content);
16
- const ast = buildAST(tokens);
17
- return renderNodes(ast);
33
+ return renderPassageContent(passage);
18
34
  } catch (err) {
19
35
  return (
20
36
  <div class="error">
@@ -25,13 +41,62 @@ export function Passage({ passage }: PassageProps) {
25
41
  }
26
42
  }, [passage.content, passage.name]);
27
43
 
44
+ const headerPassage = isCodePassage
45
+ ? undefined
46
+ : storyData?.passages.get('PassageHeader');
47
+ const footerPassage = isCodePassage
48
+ ? undefined
49
+ : storyData?.passages.get('PassageFooter');
50
+ const donePassage = isCodePassage
51
+ ? undefined
52
+ : storyData?.passages.get('PassageDone');
53
+
54
+ const headerContent = useMemo(() => {
55
+ if (!headerPassage) return null;
56
+ try {
57
+ return renderPassageContent(headerPassage);
58
+ } catch (err) {
59
+ console.error('spindle: Error in PassageHeader:', err);
60
+ return null;
61
+ }
62
+ }, [headerPassage?.content]);
63
+
64
+ const footerContent = useMemo(() => {
65
+ if (!footerPassage) return null;
66
+ try {
67
+ return renderPassageContent(footerPassage);
68
+ } catch (err) {
69
+ console.error('spindle: Error in PassageFooter:', err);
70
+ return null;
71
+ }
72
+ }, [footerPassage?.content]);
73
+
74
+ // Defer PassageDone to after DOM commit
75
+ useEffect(() => {
76
+ if (donePassage) setDoneReady(true);
77
+ return () => setDoneReady(false);
78
+ }, [passage.name]);
79
+
80
+ const doneContent = useMemo(() => {
81
+ if (!doneReady || !donePassage) return null;
82
+ try {
83
+ return renderPassageContent(donePassage);
84
+ } catch (err) {
85
+ console.error('spindle: Error in PassageDone:', err);
86
+ return null;
87
+ }
88
+ }, [doneReady, donePassage?.content]);
89
+
28
90
  return (
29
91
  <div
30
92
  class="passage"
31
93
  data-passage={passage.name}
32
94
  data-tags={passage.tags.join(' ')}
33
95
  >
96
+ {headerContent && <div class="passage-header">{headerContent}</div>}
34
97
  {content}
98
+ {footerContent && <div class="passage-footer">{footerContent}</div>}
99
+ {doneContent && <div hidden>{doneContent}</div>}
35
100
  </div>
36
101
  );
37
102
  }
@@ -1,7 +1,7 @@
1
1
  import { useStoryStore } from '../store';
2
2
  import { tokenize } from '../markup/tokenizer';
3
3
  import { buildAST } from '../markup/ast';
4
- import { renderNodes } from '../markup/render';
4
+ import { renderInlineNodes } from '../markup/render';
5
5
 
6
6
  const DEFAULT_MARKUP =
7
7
  '<header class="story-menubar">{story-title}{back}{forward}{restart}{quicksave}{quickload}{saves}{settings}</header>\n{passage}';
@@ -16,7 +16,7 @@ export function StoryInterface() {
16
16
  try {
17
17
  const tokens = tokenize(markup);
18
18
  const ast = buildAST(tokens);
19
- return <>{renderNodes(ast)}</>;
19
+ return <>{renderInlineNodes(ast)}</>;
20
20
  } catch (err) {
21
21
  return (
22
22
  <span class="error">
@@ -11,10 +11,10 @@ function parseArgs(rawArgs: string): {
11
11
  } {
12
12
  // {link "text" "Passage"} or {link "text"}
13
13
  const parts: string[] = [];
14
- const re = /["']([^"']+)["']/g;
14
+ const re = /(["'])(.*?)\1/g;
15
15
  let m;
16
16
  while ((m = re.exec(rawArgs)) !== null) {
17
- parts.push(m[1]!);
17
+ parts.push(m[2]!);
18
18
  }
19
19
  if (parts.length >= 2) {
20
20
  return { display: parts[0]!, passage: parts[1]! };
@@ -1,5 +1,5 @@
1
1
  import { useStoryStore } from '../../store';
2
- import { Passage } from '../Passage';
2
+ import { Passage, renderPassageContent } from '../Passage';
3
3
  import { defineMacro } from '../../define-macro';
4
4
 
5
5
  defineMacro({
@@ -18,11 +18,21 @@ defineMacro({
18
18
  );
19
19
  }
20
20
 
21
+ const readyPassage = storyData?.passages.get('PassageReady');
22
+
21
23
  return (
22
24
  <div
23
25
  id={ctx.id ?? 'story'}
24
26
  class={ctx.className ?? 'story'}
25
27
  >
28
+ {readyPassage && (
29
+ <div
30
+ key={`ready-${currentPassage}`}
31
+ hidden
32
+ >
33
+ {renderPassageContent(readyPassage)}
34
+ </div>
35
+ )}
26
36
  <Passage
27
37
  passage={passage}
28
38
  key={currentPassage}
@@ -0,0 +1,8 @@
1
+ import { defineMacro } from '../../define-macro';
2
+
3
+ defineMacro({
4
+ name: 'span',
5
+ render({ children = [] }, ctx) {
6
+ return ctx.wrap(ctx.renderNodes(children));
7
+ },
8
+ });
@@ -32,22 +32,24 @@ defineMacro({
32
32
  return () => clearTimeout(timer);
33
33
  }, [visibleIndex, sections]);
34
34
 
35
- if (visibleIndex < 0) return null;
35
+ if (visibleIndex < 0) return ctx.wrap(null);
36
36
 
37
37
  const section = sections[visibleIndex]!;
38
38
  const content = ctx.renderNodes(section.nodes);
39
39
  const sectionClass = ctx.resolve!(section.className);
40
40
  const sectionId = ctx.resolve!(section.id);
41
41
 
42
- if (sectionClass || sectionId)
43
- return (
42
+ const inner =
43
+ sectionClass || sectionId ? (
44
44
  <span
45
45
  id={sectionId}
46
46
  class={sectionClass}
47
47
  >
48
48
  {content}
49
49
  </span>
50
+ ) : (
51
+ content
50
52
  );
51
- return <>{content}</>;
53
+ return ctx.wrap(inner);
52
54
  },
53
55
  });
package/src/expression.ts CHANGED
@@ -6,12 +6,12 @@ import { random, randomInt } from './prng';
6
6
  interface ExpressionFns {
7
7
  currentPassage: () => Passage | undefined;
8
8
  previousPassage: () => Passage | undefined;
9
- visited: (name: string) => number;
10
- hasVisited: (name: string) => boolean;
9
+ visited: (name?: string) => number;
10
+ hasVisited: (name?: string) => boolean;
11
11
  hasVisitedAny: (...names: string[]) => boolean;
12
12
  hasVisitedAll: (...names: string[]) => boolean;
13
- rendered: (name: string) => number;
14
- hasRendered: (name: string) => boolean;
13
+ rendered: (name?: string) => number;
14
+ hasRendered: (name?: string) => boolean;
15
15
  hasRenderedAny: (...names: string[]) => boolean;
16
16
  hasRenderedAll: (...names: string[]) => boolean;
17
17
  random: () => number;
@@ -191,15 +191,17 @@ export function buildExpressionFns() {
191
191
  return cachedFns;
192
192
  }
193
193
 
194
- const visited = (name: string): number => visitCounts[name] ?? 0;
195
- const hasVisited = (name: string): boolean => visited(name) > 0;
194
+ const visited = (name?: string): number =>
195
+ visitCounts[name ?? useStoryStore.getState().currentPassage] ?? 0;
196
+ const hasVisited = (name?: string): boolean => visited(name) > 0;
196
197
  const hasVisitedAny = (...names: string[]): boolean =>
197
198
  names.some((n) => visited(n) > 0);
198
199
  const hasVisitedAll = (...names: string[]): boolean =>
199
200
  names.every((n) => visited(n) > 0);
200
201
 
201
- const rendered = (name: string): number => renderCounts[name] ?? 0;
202
- const hasRendered = (name: string): boolean => rendered(name) > 0;
202
+ const rendered = (name?: string): number =>
203
+ renderCounts[name ?? useStoryStore.getState().currentPassage] ?? 0;
204
+ const hasRendered = (name?: string): boolean => rendered(name) > 0;
203
205
  const hasRenderedAny = (...names: string[]): boolean =>
204
206
  names.some((n) => rendered(n) > 0);
205
207
  const hasRenderedAll = (...names: string[]): boolean =>
package/src/index.tsx CHANGED
@@ -5,6 +5,7 @@ import { useStoryStore } from './store';
5
5
  import { installStoryAPI } from './story-api';
6
6
  import { resetIdCounters } from './action-registry';
7
7
  import { executeStoryInit } from './story-init';
8
+ import { loadSession } from './saves/save-manager';
8
9
  import {
9
10
  parseStoryVariables,
10
11
  validatePassages,
@@ -89,6 +90,12 @@ function boot() {
89
90
  // Execute StoryInit passage if it exists
90
91
  executeStoryInit();
91
92
 
93
+ // Restore session state if the page was refreshed
94
+ const sessionPayload = loadSession(storyData.ifid);
95
+ if (sessionPayload) {
96
+ useStoryStore.getState().loadFromPayload(sessionPayload);
97
+ }
98
+
92
99
  // Register widgets from passages tagged "widget"
93
100
  for (const [, passage] of storyData.passages) {
94
101
  if (passage.tags.includes('widget')) {
@@ -29,4 +29,5 @@ import '../components/macros/Checkbox';
29
29
  import '../components/macros/Radiobutton';
30
30
  import '../components/macros/Listbox';
31
31
  import '../components/macros/Cycle';
32
+ import '../components/macros/Span';
32
33
  import '../components/macros/PassageDisplay';
package/src/markup/ast.ts CHANGED
@@ -53,6 +53,7 @@ const BLOCK_MACROS = new Set([
53
53
  'repeat',
54
54
  'type',
55
55
  'widget',
56
+ 'span',
56
57
  ]);
57
58
 
58
59
  /** Map from branch macro name → required parent macro name */
@@ -299,6 +299,49 @@ export async function loadQuickSave(
299
299
  return loadSave(existingId);
300
300
  }
301
301
 
302
+ // --- Session Persistence (survives F5, cleared on tab close) ---
303
+
304
+ const SESSION_KEY_PREFIX = 'spindle.session.';
305
+
306
+ /**
307
+ * Write a pre-serialized session payload to sessionStorage.
308
+ * Callers are responsible for serializing variables (see persistSession in store.ts).
309
+ */
310
+ export function saveSession(ifid: string, data: unknown): void {
311
+ try {
312
+ sessionStorage.setItem(
313
+ `${SESSION_KEY_PREFIX}${ifid}`,
314
+ JSON.stringify(data),
315
+ );
316
+ } catch {
317
+ // sessionStorage unavailable or full — silently ignore
318
+ }
319
+ }
320
+
321
+ export function loadSession(ifid: string): SavePayload | undefined {
322
+ try {
323
+ const raw = sessionStorage.getItem(`${SESSION_KEY_PREFIX}${ifid}`);
324
+ if (!raw) return undefined;
325
+ const payload: SavePayload = JSON.parse(raw);
326
+ payload.variables = deserialize(payload.variables);
327
+ payload.history = payload.history.map((m) => ({
328
+ ...m,
329
+ variables: deserialize(m.variables),
330
+ }));
331
+ return payload;
332
+ } catch {
333
+ return undefined;
334
+ }
335
+ }
336
+
337
+ export function clearSession(ifid: string): void {
338
+ try {
339
+ sessionStorage.removeItem(`${SESSION_KEY_PREFIX}${ifid}`);
340
+ } catch {
341
+ // ignore
342
+ }
343
+ }
344
+
302
345
  // --- Export / Import ---
303
346
 
304
347
  export async function exportSave(
@@ -1,10 +1,17 @@
1
- import type { HistoryMoment } from '../store';
2
1
  import type { PRNGSnapshot } from '../prng';
3
2
 
3
+ /** History moment as persisted in saves (full variable snapshots). */
4
+ export interface SaveHistoryMoment {
5
+ passage: string;
6
+ variables: Record<string, unknown>;
7
+ timestamp: number;
8
+ prng?: PRNGSnapshot | null;
9
+ }
10
+
4
11
  export interface SavePayload {
5
12
  passage: string;
6
13
  variables: Record<string, unknown>;
7
- history: HistoryMoment[];
14
+ history: SaveHistoryMoment[];
8
15
  historyIndex: number;
9
16
  visitCounts?: Record<string, number>;
10
17
  renderCounts?: Record<string, number>;