@rohal12/spindle 0.52.8 → 0.53.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.
- package/README.md +2 -0
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +1886 -611
- package/package.json +5 -1
- package/src/class-registry.ts +252 -250
- package/src/components/App.tsx +2 -0
- package/src/components/RuntimeErrors.tsx +46 -0
- package/src/components/macros/Computed.tsx +5 -2
- package/src/components/macros/Do.tsx +3 -1
- package/src/components/macros/Goto.tsx +13 -3
- package/src/components/macros/MacroError.tsx +14 -7
- package/src/components/macros/SaveManager.tsx +2 -2
- package/src/markup/render.tsx +117 -53
- package/src/parser.ts +119 -13
- package/src/runtime-errors.ts +65 -0
- package/src/saves/format.ts +199 -0
- package/src/saves/save-manager.ts +45 -63
- package/src/saves/types.ts +71 -88
- package/src/store.ts +167 -87
- package/src/structural.ts +266 -57
- package/src/styles.css +45 -0
- package/src/utils/object-path.ts +13 -12
- package/src/utils/stable-key.ts +2 -1
- package/src/utils/value-kinds.ts +45 -0
- package/types/index.d.ts +32 -8
|
@@ -9,10 +9,12 @@ defineMacro({
|
|
|
9
9
|
const code = ctx.collectText(children);
|
|
10
10
|
|
|
11
11
|
ctx.hooks.useLayoutEffect(() => {
|
|
12
|
+
// Before the code runs: it may navigate away from this passage
|
|
13
|
+
const location = ctx.sourceLocation();
|
|
12
14
|
try {
|
|
13
15
|
ctx.mutate(code);
|
|
14
16
|
} catch (err) {
|
|
15
|
-
logMacroError('do', err);
|
|
17
|
+
logMacroError('do', err, location);
|
|
16
18
|
}
|
|
17
19
|
}, []);
|
|
18
20
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { useStoryStore } from '../../store';
|
|
2
2
|
import { defineMacro } from '../../define-macro';
|
|
3
3
|
import { evaluatePassageName } from './macro-args';
|
|
4
|
+
import { logMacroError } from './MacroError';
|
|
4
5
|
|
|
5
6
|
defineMacro({
|
|
6
7
|
name: 'goto',
|
|
@@ -8,9 +9,18 @@ defineMacro({
|
|
|
8
9
|
parameters: [{ name: 'passage', type: 'expression', required: true }],
|
|
9
10
|
render(_props, ctx) {
|
|
10
11
|
ctx.hooks.useLayoutEffect(() => {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
// Reported like an error in {do}: thrown out of an effect, it would
|
|
13
|
+
// abort the rest of the render's effects (e.g. the session could not
|
|
14
|
+
// be written because the state holds a function). The location is
|
|
15
|
+
// this passage's, taken before navigating away from it
|
|
16
|
+
const location = ctx.sourceLocation();
|
|
17
|
+
try {
|
|
18
|
+
useStoryStore
|
|
19
|
+
.getState()
|
|
20
|
+
.navigate(evaluatePassageName(ctx.args.passage, ctx.evaluate!));
|
|
21
|
+
} catch (err) {
|
|
22
|
+
logMacroError('goto', err, location);
|
|
23
|
+
}
|
|
14
24
|
}, []);
|
|
15
25
|
|
|
16
26
|
return null;
|
|
@@ -19,12 +19,18 @@ export function MacroError({
|
|
|
19
19
|
);
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Log an error in the macro `{label}` (its name, or name and arguments) at
|
|
24
|
+
* `location`, the source location of the macro's passage. Take it before
|
|
25
|
+
* running the code that failed (see currentSourceLocation): code that
|
|
26
|
+
* navigates changes the current passage.
|
|
27
|
+
*/
|
|
28
|
+
export function logMacroError(
|
|
29
|
+
label: string,
|
|
30
|
+
error: unknown,
|
|
31
|
+
location: string = currentSourceLocation(),
|
|
32
|
+
): void {
|
|
33
|
+
console.error(`spindle: Error in {${label}}${location}:`, error);
|
|
28
34
|
}
|
|
29
35
|
|
|
30
36
|
/**
|
|
@@ -38,11 +44,12 @@ export function useRunOnce(macro: string, rawArgs: string, effect: () => void) {
|
|
|
38
44
|
const failure = useRef<{ error: unknown } | null>();
|
|
39
45
|
if (failure.current === undefined) {
|
|
40
46
|
failure.current = null;
|
|
47
|
+
const location = currentSourceLocation();
|
|
41
48
|
try {
|
|
42
49
|
effect();
|
|
43
50
|
} catch (error) {
|
|
44
51
|
failure.current = { error };
|
|
45
|
-
logMacroError(`${macro} ${rawArgs}`, error);
|
|
52
|
+
logMacroError(`${macro} ${rawArgs}`, error, location);
|
|
46
53
|
}
|
|
47
54
|
}
|
|
48
55
|
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
renameSave,
|
|
18
18
|
exportSave,
|
|
19
19
|
importSave,
|
|
20
|
-
|
|
20
|
+
decodeSavePayload,
|
|
21
21
|
saveWithHooks,
|
|
22
22
|
type PlaythroughGroup,
|
|
23
23
|
} from '../../saves/save-manager';
|
|
@@ -160,7 +160,7 @@ export function SaveManagerContent() {
|
|
|
160
160
|
// Stored records hold serialized variables; the store expects live
|
|
161
161
|
// ones. The game moves to the save's playthrough.
|
|
162
162
|
loadFromPayload(
|
|
163
|
-
|
|
163
|
+
decodeSavePayload(save.payload),
|
|
164
164
|
undefined,
|
|
165
165
|
save.meta.playthroughId,
|
|
166
166
|
);
|
package/src/markup/render.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createContext } from 'preact';
|
|
1
|
+
import { createContext, type RefObject } from 'preact';
|
|
2
2
|
import { useContext, useLayoutEffect, useRef } from 'preact/hooks';
|
|
3
3
|
import { VarDisplay } from '../components/macros/VarDisplay';
|
|
4
4
|
import { ExprDisplay } from '../components/macros/ExprDisplay';
|
|
@@ -63,6 +63,8 @@ export const RawTextContext = createContext(false);
|
|
|
63
63
|
*/
|
|
64
64
|
const SvgContext = createContext(false);
|
|
65
65
|
|
|
66
|
+
const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
|
|
67
|
+
|
|
66
68
|
/** Elements whose content is literal text, not markdown. */
|
|
67
69
|
const PREFORMATTED_ELEMENTS = new Set(['pre', 'textarea']);
|
|
68
70
|
export const WidgetChildrenContext = createContext<ASTNode[] | null>(null);
|
|
@@ -139,31 +141,59 @@ function expandPlaceholderText(
|
|
|
139
141
|
);
|
|
140
142
|
}
|
|
141
143
|
|
|
144
|
+
/** An attribute: its name, value and value as written (see splitAttributes). */
|
|
145
|
+
type Attribute = [name: string, value: string, written: string];
|
|
146
|
+
|
|
142
147
|
/**
|
|
143
|
-
* An element whose attributes contain placeholders (a
|
|
144
|
-
* text or a link title). Each such attribute is
|
|
145
|
-
* the store and locals, so it follows its
|
|
148
|
+
* An element of markdown output whose attributes contain placeholders (a
|
|
149
|
+
* variable in image alt text or a link title). Each such attribute is
|
|
150
|
+
* evaluated as text against the store and locals, so it follows its
|
|
151
|
+
* variables as the component would.
|
|
146
152
|
*/
|
|
147
153
|
function PlaceholderAttributes({
|
|
148
154
|
tag,
|
|
149
|
-
props,
|
|
150
155
|
attributes,
|
|
156
|
+
placeholders,
|
|
157
|
+
svg,
|
|
151
158
|
children,
|
|
152
159
|
}: {
|
|
153
160
|
tag: string;
|
|
154
|
-
|
|
155
|
-
|
|
161
|
+
attributes: Attribute[];
|
|
162
|
+
placeholders: Record<string, ASTNode[]>;
|
|
163
|
+
svg: boolean;
|
|
156
164
|
children: preact.ComponentChildren[];
|
|
157
165
|
}) {
|
|
158
166
|
const scope = useTextScope();
|
|
159
|
-
const resolved: Record<string, string> = { ...props };
|
|
160
167
|
const errors: AttributeError[] = [];
|
|
161
|
-
|
|
168
|
+
const resolved = attributes.map(([name, value, written]): Attribute => {
|
|
169
|
+
const nodes = placeholders[name];
|
|
170
|
+
if (!nodes) return [name, value, written];
|
|
162
171
|
const result = renderText(nodes, scope);
|
|
163
|
-
resolved[name] = result.text;
|
|
164
172
|
for (const error of result.errors) errors.push([name, error]);
|
|
165
|
-
|
|
166
|
-
|
|
173
|
+
return [name, result.text, written];
|
|
174
|
+
});
|
|
175
|
+
const { props, direct } = splitAttributes(resolved, svg);
|
|
176
|
+
const ref = useDirectAttributes(direct);
|
|
177
|
+
return withAttributeErrors(
|
|
178
|
+
errors,
|
|
179
|
+
h(tag, ref ? { ...props, ref } : props, ...children),
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** An element of markdown output with attributes to set directly. */
|
|
184
|
+
function DirectAttributes({
|
|
185
|
+
tag,
|
|
186
|
+
props,
|
|
187
|
+
direct,
|
|
188
|
+
children,
|
|
189
|
+
}: {
|
|
190
|
+
tag: string;
|
|
191
|
+
props: Record<string, unknown>;
|
|
192
|
+
direct: [string, string][];
|
|
193
|
+
children: preact.ComponentChildren[];
|
|
194
|
+
}) {
|
|
195
|
+
const ref = useDirectAttributes(direct);
|
|
196
|
+
return h(tag, { ...props, ref }, ...children);
|
|
167
197
|
}
|
|
168
198
|
|
|
169
199
|
/** An error met while evaluating the named attribute. */
|
|
@@ -201,6 +231,19 @@ function placeholderIndex(node: Node | null, ph: Placeholders): number {
|
|
|
201
231
|
return parseInt(value.slice(prefix.length), 10);
|
|
202
232
|
}
|
|
203
233
|
|
|
234
|
+
/**
|
|
235
|
+
* Parse HTML into nodes without side effects. The content of a `<template>`
|
|
236
|
+
* belongs to a document with no browsing context, so parsing it fetches no
|
|
237
|
+
* images and media, runs no inline event handlers (`<img onerror>`) and
|
|
238
|
+
* constructs no custom elements. A detached `<div>` belongs to the page's
|
|
239
|
+
* document, which does all of these while parsing.
|
|
240
|
+
*/
|
|
241
|
+
export function parseHtmlInert(html: string): DocumentFragment {
|
|
242
|
+
const template = document.createElement('template');
|
|
243
|
+
template.innerHTML = html;
|
|
244
|
+
return template.content;
|
|
245
|
+
}
|
|
246
|
+
|
|
204
247
|
/**
|
|
205
248
|
* Convert an HTML string (from micromark) to Preact VNodes,
|
|
206
249
|
* replacing placeholder elements with pre-rendered components.
|
|
@@ -212,14 +255,15 @@ function htmlToPreact(
|
|
|
212
255
|
ph: Placeholders,
|
|
213
256
|
unwrapParagraphs = false,
|
|
214
257
|
): preact.ComponentChildren {
|
|
215
|
-
const
|
|
216
|
-
temp.innerHTML = html.trim();
|
|
258
|
+
const content = parseHtmlInert(html.trim());
|
|
217
259
|
if (unwrapParagraphs) {
|
|
218
|
-
for (const
|
|
219
|
-
|
|
260
|
+
for (const child of Array.from(content.childNodes)) {
|
|
261
|
+
if (child.nodeType === Node.ELEMENT_NODE && child.nodeName === 'P') {
|
|
262
|
+
(child as Element).replaceWith(...Array.from(child.childNodes));
|
|
263
|
+
}
|
|
220
264
|
}
|
|
221
265
|
}
|
|
222
|
-
const children = Array.from(
|
|
266
|
+
const children = Array.from(content.childNodes).map((child, i) =>
|
|
223
267
|
convertDomNode(child, i, ph),
|
|
224
268
|
);
|
|
225
269
|
return <>{children}</>;
|
|
@@ -252,17 +296,17 @@ function convertDomNode(
|
|
|
252
296
|
return ph.components[idx];
|
|
253
297
|
}
|
|
254
298
|
|
|
255
|
-
// Convert attributes
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
299
|
+
// Convert attributes, as author HTML's (see splitAttributes): markdown
|
|
300
|
+
// output holds raw HTML the passage tokenizer didn't take as a tag
|
|
301
|
+
const svg = el.namespaceURI === SVG_NAMESPACE;
|
|
302
|
+
const attributes: Attribute[] = [];
|
|
303
|
+
let placeholders: Record<string, ASTNode[]> | undefined;
|
|
304
|
+
for (const { name, value } of Array.from(el.attributes)) {
|
|
305
|
+
attributes.push([name, value, value]);
|
|
306
|
+
const parts = splitPlaceholderText(value, ph);
|
|
307
|
+
if (parts.every((part) => typeof part === 'string')) continue;
|
|
308
|
+
placeholders ??= {};
|
|
309
|
+
placeholders[name] = parts.map(
|
|
266
310
|
(part): ASTNode =>
|
|
267
311
|
typeof part === 'string'
|
|
268
312
|
? { type: 'text', value: part }
|
|
@@ -275,13 +319,26 @@ function convertDomNode(
|
|
|
275
319
|
convertDomNode(child, i, ph),
|
|
276
320
|
);
|
|
277
321
|
|
|
278
|
-
if (
|
|
322
|
+
if (placeholders) {
|
|
279
323
|
return (
|
|
280
324
|
<PlaceholderAttributes
|
|
325
|
+
key={key}
|
|
326
|
+
tag={tag}
|
|
327
|
+
attributes={attributes}
|
|
328
|
+
placeholders={placeholders}
|
|
329
|
+
svg={svg}
|
|
330
|
+
children={children}
|
|
331
|
+
/>
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
const { props, direct } = splitAttributes(attributes, svg);
|
|
335
|
+
if (direct.length > 0) {
|
|
336
|
+
return (
|
|
337
|
+
<DirectAttributes
|
|
281
338
|
key={key}
|
|
282
339
|
tag={tag}
|
|
283
340
|
props={props}
|
|
284
|
-
|
|
341
|
+
direct={direct}
|
|
285
342
|
children={children}
|
|
286
343
|
/>
|
|
287
344
|
);
|
|
@@ -395,9 +452,8 @@ function setRawAttribute(el: Element, name: string, value: string) {
|
|
|
395
452
|
el.setAttribute(name, value);
|
|
396
453
|
return;
|
|
397
454
|
}
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
const parsed = (template.content.firstChild as Element).attributes[0];
|
|
455
|
+
const parsed = (parseHtmlInert(`<i ${name}=""></i>`).firstChild as Element)
|
|
456
|
+
.attributes[0];
|
|
401
457
|
if (!parsed) return;
|
|
402
458
|
const attr = parsed.cloneNode() as Attr;
|
|
403
459
|
attr.value = value;
|
|
@@ -422,7 +478,7 @@ function setRawAttribute(el: Element, name: string, value: string) {
|
|
|
422
478
|
* `className` into `class`) are set directly instead.
|
|
423
479
|
*/
|
|
424
480
|
function splitAttributes(
|
|
425
|
-
attributes: [
|
|
481
|
+
attributes: Attribute[],
|
|
426
482
|
svg: boolean,
|
|
427
483
|
): { props: Record<string, unknown>; direct: [string, string][] } {
|
|
428
484
|
const props: Record<string, unknown> = {};
|
|
@@ -447,6 +503,27 @@ function splitAttributes(
|
|
|
447
503
|
return { props, direct };
|
|
448
504
|
}
|
|
449
505
|
|
|
506
|
+
/**
|
|
507
|
+
* Set the attributes `splitAttributes` leaves to set directly on the element
|
|
508
|
+
* given the returned ref (none if there are none), and remove them again
|
|
509
|
+
* when they change.
|
|
510
|
+
*/
|
|
511
|
+
function useDirectAttributes(
|
|
512
|
+
direct: [string, string][],
|
|
513
|
+
): RefObject<Element> | undefined {
|
|
514
|
+
const elementRef = useRef<Element>(null);
|
|
515
|
+
const directKey = JSON.stringify(direct);
|
|
516
|
+
useLayoutEffect(() => {
|
|
517
|
+
const el = elementRef.current;
|
|
518
|
+
if (!el || direct.length === 0) return;
|
|
519
|
+
for (const [name, value] of direct) setRawAttribute(el, name, value);
|
|
520
|
+
return () => {
|
|
521
|
+
for (const [name] of direct) el.removeAttribute(name);
|
|
522
|
+
};
|
|
523
|
+
}, [directKey]);
|
|
524
|
+
return direct.length > 0 ? elementRef : undefined;
|
|
525
|
+
}
|
|
526
|
+
|
|
450
527
|
const decodedAttributeText = new Map<string, string>();
|
|
451
528
|
|
|
452
529
|
/**
|
|
@@ -457,10 +534,10 @@ function decodeAttributeText(text: string): string {
|
|
|
457
534
|
if (!text.includes('&')) return text;
|
|
458
535
|
let decoded = decodedAttributeText.get(text);
|
|
459
536
|
if (decoded === undefined) {
|
|
460
|
-
const
|
|
461
|
-
template.innerHTML = `<i title="${text.replace(/"/g, '"')}"></i>`;
|
|
537
|
+
const html = `<i title="${text.replace(/"/g, '"')}"></i>`;
|
|
462
538
|
decoded =
|
|
463
|
-
(
|
|
539
|
+
(parseHtmlInert(html).firstChild as Element).getAttribute('title') ??
|
|
540
|
+
text;
|
|
464
541
|
decodedAttributeText.set(text, decoded);
|
|
465
542
|
}
|
|
466
543
|
return decoded;
|
|
@@ -532,24 +609,11 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
|
|
|
532
609
|
const isRawRoot = !inRaw && (isSvgRoot || PREFORMATTED_ELEMENTS.has(tag));
|
|
533
610
|
const errors: AttributeError[] = [];
|
|
534
611
|
const resolved = Object.entries(node.attributes).map(
|
|
535
|
-
([k, v]): [
|
|
536
|
-
k,
|
|
537
|
-
resolveAttributeValue(k, v, scope, errors),
|
|
538
|
-
v,
|
|
539
|
-
],
|
|
612
|
+
([k, v]): Attribute => [k, resolveAttributeValue(k, v, scope, errors), v],
|
|
540
613
|
);
|
|
541
614
|
const { props, direct } = splitAttributes(resolved, inSvg || isSvgRoot);
|
|
542
|
-
const
|
|
543
|
-
|
|
544
|
-
useLayoutEffect(() => {
|
|
545
|
-
const el = elementRef.current;
|
|
546
|
-
if (!el || direct.length === 0) return;
|
|
547
|
-
for (const [name, value] of direct) setRawAttribute(el, name, value);
|
|
548
|
-
return () => {
|
|
549
|
-
for (const [name] of direct) el.removeAttribute(name);
|
|
550
|
-
};
|
|
551
|
-
}, [directKey]);
|
|
552
|
-
if (direct.length > 0) props.ref = elementRef;
|
|
615
|
+
const ref = useDirectAttributes(direct);
|
|
616
|
+
if (ref) props.ref = ref;
|
|
553
617
|
const isInline = INLINE_ELEMENTS.has(tag);
|
|
554
618
|
// Inside SVG and preformatted elements, skip markdown processing entirely
|
|
555
619
|
// (see RawTextContext).
|
package/src/parser.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { tokenize } from './markup/tokenizer';
|
|
2
|
+
import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
|
|
3
|
+
|
|
1
4
|
export interface Passage {
|
|
2
5
|
pid: number;
|
|
3
6
|
name: string;
|
|
@@ -18,25 +21,128 @@ export interface StoryData {
|
|
|
18
21
|
userScript: string;
|
|
19
22
|
}
|
|
20
23
|
|
|
24
|
+
const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
|
|
25
|
+
|
|
26
|
+
/** HTML elements written without content or end tag, as innerHTML does. */
|
|
27
|
+
const VOID_ELEMENTS = new Set([
|
|
28
|
+
'area',
|
|
29
|
+
'base',
|
|
30
|
+
'basefont',
|
|
31
|
+
'bgsound',
|
|
32
|
+
'br',
|
|
33
|
+
'col',
|
|
34
|
+
'embed',
|
|
35
|
+
'frame',
|
|
36
|
+
'hr',
|
|
37
|
+
'img',
|
|
38
|
+
'input',
|
|
39
|
+
'keygen',
|
|
40
|
+
'link',
|
|
41
|
+
'meta',
|
|
42
|
+
'param',
|
|
43
|
+
'source',
|
|
44
|
+
'track',
|
|
45
|
+
'wbr',
|
|
46
|
+
]);
|
|
47
|
+
|
|
21
48
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
49
|
+
* The passage markup in the nodes of passage data.
|
|
50
|
+
*
|
|
51
|
+
* A compiler that HTML-escapes passage text (Twine, Tweego) leaves a text
|
|
52
|
+
* node whose text is the markup; a no-break space in it is U+00A0, which
|
|
53
|
+
* innerHTML writes as ` `. One that doesn't escape it leaves the
|
|
54
|
+
* browser's parse of it, whose elements are written back as markup here.
|
|
55
|
+
* innerHTML did that too, but its escaping can't be undone: a `"` in an
|
|
56
|
+
* attribute value is written `"`, and decoding that ends the value
|
|
57
|
+
* early, while text it leaves unescaped (in `<style>`, comments) would be
|
|
58
|
+
* decoded wrongly.
|
|
24
59
|
*/
|
|
25
|
-
function
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
.
|
|
29
|
-
|
|
30
|
-
.
|
|
31
|
-
|
|
60
|
+
function passageMarkup(parent: ParentNode): string {
|
|
61
|
+
let markup = '';
|
|
62
|
+
for (const node of Array.from(parent.childNodes)) {
|
|
63
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
64
|
+
markup += (node as Text).data;
|
|
65
|
+
} else if (node.nodeType === Node.COMMENT_NODE) {
|
|
66
|
+
markup += `<!--${(node as Comment).data}-->`;
|
|
67
|
+
} else if (node.nodeType === Node.ELEMENT_NODE) {
|
|
68
|
+
markup += elementMarkup(node as Element);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return markup;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** An element of passage data as markup (see passageMarkup). */
|
|
75
|
+
function elementMarkup(el: Element): string {
|
|
76
|
+
const name = el.localName;
|
|
77
|
+
let markup = `<${name}`;
|
|
78
|
+
for (const attr of Array.from(el.attributes)) {
|
|
79
|
+
markup += ` ${attr.name}=${quoteAttribute(attr.name, attr.value)}`;
|
|
80
|
+
}
|
|
81
|
+
markup += '>';
|
|
82
|
+
if (el.namespaceURI === HTML_NAMESPACE && VOID_ELEMENTS.has(name)) {
|
|
83
|
+
return markup;
|
|
84
|
+
}
|
|
85
|
+
const content =
|
|
86
|
+
name === 'template' ? (el as HTMLTemplateElement).content : el;
|
|
87
|
+
return `${markup}${passageMarkup(content)}</${name}>`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* An attribute value quoted so that the passage tokenizer reads it back:
|
|
92
|
+
* in double quotes, else single ones, else with the double quotes in its
|
|
93
|
+
* text written as `"`, which rendering decodes. Quotes inside markup in
|
|
94
|
+
* the value (`{print "a"}`) are code, and don't end it.
|
|
95
|
+
*/
|
|
96
|
+
function quoteAttribute(name: string, value: string): string {
|
|
97
|
+
const code = isCodeAttribute(name);
|
|
98
|
+
const probe = code ? 'on' : 'a';
|
|
99
|
+
const readsBack = (quoted: string) => {
|
|
100
|
+
const tokens = tokenize(`<i ${probe}=${quoted}>`);
|
|
101
|
+
const tag = tokens[0];
|
|
102
|
+
return (
|
|
103
|
+
tokens.length === 1 &&
|
|
104
|
+
tag?.type === 'html' &&
|
|
105
|
+
tag.attributes[probe] === quoted.slice(1, -1)
|
|
106
|
+
);
|
|
107
|
+
};
|
|
108
|
+
return (
|
|
109
|
+
[`"${value}"`, `'${value}'`].find(readsBack) ??
|
|
110
|
+
`"${escapeTextQuotes(value, code)}"`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* `value` with the double quotes in its text written as `"`, but not
|
|
116
|
+
* those in markup (`{print "a"}`) or, in a code attribute, in sigil
|
|
117
|
+
* references (see splitSigilTemplate), which are code.
|
|
118
|
+
*/
|
|
119
|
+
function escapeTextQuotes(value: string, code: boolean): string {
|
|
120
|
+
const escape = (text: string) => text.replace(/"/g, '"');
|
|
121
|
+
if (code) {
|
|
122
|
+
return splitSigilTemplate(value)
|
|
123
|
+
.map((part) =>
|
|
124
|
+
'text' in part
|
|
125
|
+
? escape(part.text)
|
|
126
|
+
: 'expr' in part
|
|
127
|
+
? `{${part.expr}}`
|
|
128
|
+
: part.verbatim,
|
|
129
|
+
)
|
|
130
|
+
.join('');
|
|
131
|
+
}
|
|
132
|
+
return tokenize(value, { text: true })
|
|
133
|
+
.map((token) => {
|
|
134
|
+
const source = value.slice(token.start, token.end);
|
|
135
|
+
return token.type === 'text' ? escape(source) : source;
|
|
136
|
+
})
|
|
137
|
+
.join('');
|
|
32
138
|
}
|
|
33
139
|
|
|
34
140
|
/**
|
|
35
141
|
* Parse <tw-storydata> and all <tw-passagedata> elements from the DOM.
|
|
36
142
|
*
|
|
37
|
-
*
|
|
38
|
-
* tags inside passage markup (e.g. <div> inside {button}) are
|
|
39
|
-
*
|
|
143
|
+
* Passage content is read with passageMarkup instead of textContent, so
|
|
144
|
+
* that HTML tags inside passage markup (e.g. <div> inside {button}) are
|
|
145
|
+
* preserved whether or not the compiler HTML-encoded them.
|
|
40
146
|
*/
|
|
41
147
|
export function parseStoryData(): StoryData {
|
|
42
148
|
const storyEl = document.querySelector('tw-storydata');
|
|
@@ -67,7 +173,7 @@ export function parseStoryData(): StoryData {
|
|
|
67
173
|
const tags = (el.getAttribute('tags') || '')
|
|
68
174
|
.split(/\s+/)
|
|
69
175
|
.filter((t) => t.length > 0);
|
|
70
|
-
const content =
|
|
176
|
+
const content = passageMarkup(el);
|
|
71
177
|
|
|
72
178
|
const metadata: Record<string, string> = {};
|
|
73
179
|
const skipAttrs = new Set(['pid', 'name', 'tags']);
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Runtime errors shown to the player on the page (see RuntimeErrors), for
|
|
2
|
+
// errors that would otherwise only reach the browser console.
|
|
3
|
+
|
|
4
|
+
import { errorMessage } from './utils/error-message';
|
|
5
|
+
|
|
6
|
+
/** A runtime error shown on the page until the player dismisses it. */
|
|
7
|
+
export interface RuntimeError {
|
|
8
|
+
/** Identifies the entry, for dismissing it. */
|
|
9
|
+
id: number;
|
|
10
|
+
/** What failed, for the player (e.g. "Could not save the game…"). */
|
|
11
|
+
context: string;
|
|
12
|
+
/** The error message, without the "spindle: " prefix. */
|
|
13
|
+
message: string;
|
|
14
|
+
/** How often the same error happened since it was shown. */
|
|
15
|
+
count: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
let errors: readonly RuntimeError[] = [];
|
|
19
|
+
let nextId = 1;
|
|
20
|
+
const listeners = new Set<() => void>();
|
|
21
|
+
|
|
22
|
+
function update(next: readonly RuntimeError[]): void {
|
|
23
|
+
errors = next;
|
|
24
|
+
for (const listener of listeners) listener();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Show `error` on the page, after `context` (what failed). The same error
|
|
29
|
+
* again, while it is shown, counts up instead of adding an entry. Logging
|
|
30
|
+
* it to the console is up to the caller.
|
|
31
|
+
*/
|
|
32
|
+
export function showRuntimeError(context: string, error: unknown): void {
|
|
33
|
+
const message = errorMessage(error).replace(/^spindle: /, '');
|
|
34
|
+
const same = errors.find(
|
|
35
|
+
(e) => e.context === context && e.message === message,
|
|
36
|
+
);
|
|
37
|
+
update(
|
|
38
|
+
same
|
|
39
|
+
? errors.map((e) => (e === same ? { ...e, count: e.count + 1 } : e))
|
|
40
|
+
: [...errors, { id: nextId++, context, message, count: 1 }],
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Remove the shown error `id`. */
|
|
45
|
+
export function dismissRuntimeError(id: number): void {
|
|
46
|
+
update(errors.filter((e) => e.id !== id));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Remove every shown error. */
|
|
50
|
+
export function clearRuntimeErrors(): void {
|
|
51
|
+
if (errors.length) update([]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The errors shown now, oldest first. */
|
|
55
|
+
export function getRuntimeErrors(): readonly RuntimeError[] {
|
|
56
|
+
return errors;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Call `listener` whenever the shown errors change; returns unsubscribe. */
|
|
60
|
+
export function subscribeRuntimeErrors(listener: () => void): () => void {
|
|
61
|
+
listeners.add(listener);
|
|
62
|
+
return () => {
|
|
63
|
+
listeners.delete(listener);
|
|
64
|
+
};
|
|
65
|
+
}
|