squiffy-runtime 7.0.0-beta.4 → 7.0.0-beta.6
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/dist/events.d.ts +1 -0
- package/dist/panels.d.ts +14 -0
- package/dist/panels.test.d.ts +1 -0
- package/dist/preview-host.d.ts +2 -1
- package/dist/preview-host.js +4 -1
- package/dist/preview-host.js.map +2 -2
- package/dist/preview-html.js +1 -1
- package/dist/preview-protocol.d.ts +4 -0
- package/dist/saveSlots.d.ts +16 -0
- package/dist/saves.test.d.ts +1 -0
- package/dist/savesDialog.d.ts +43 -0
- package/dist/savesDialog.test.d.ts +1 -0
- package/dist/squiffy.page.css +46 -22
- package/dist/squiffy.preview.html +612 -109
- package/dist/squiffy.runtime.css +476 -9
- package/dist/squiffy.runtime.d.ts +9 -1
- package/dist/squiffy.runtime.global.js +113 -72
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +4146 -3460
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +4 -0
- package/dist/textProcessor.d.ts +5 -0
- package/dist/types.d.ts +32 -0
- package/package.json +3 -3
- package/src/__snapshots__/squiffy.runtime.test.ts.snap +21 -21
- package/src/events.ts +1 -0
- package/src/panels.test.ts +201 -0
- package/src/panels.ts +187 -0
- package/src/plugins/plugins.test.ts +42 -0
- package/src/plugins/replaceLabel.ts +6 -2
- package/src/preview-host.test.ts +5 -1
- package/src/preview-host.ts +9 -3
- package/src/preview-protocol.ts +6 -2
- package/src/preview.test.ts +71 -3
- package/src/preview.ts +74 -13
- package/src/saveSlots.ts +159 -0
- package/src/saves.test.ts +199 -0
- package/src/savesDialog.test.ts +290 -0
- package/src/savesDialog.ts +499 -0
- package/src/squiffy.page.css +46 -22
- package/src/squiffy.runtime.css +476 -9
- package/src/squiffy.runtime.test.ts +890 -4
- package/src/squiffy.runtime.ts +322 -17
- package/src/state.ts +34 -4
- package/src/textProcessor.ts +76 -9
- package/src/types.ts +57 -1
- package/vite.preview.config.ts +7 -0
package/src/panels.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Panels (#14, #443): passages in the master section that are always to hand, rendered again with
|
|
2
|
+
// the attributes as they are whenever the story moves on, e.g. the player's stats, inventory or
|
|
3
|
+
// a map. A "side" panel is shown beside the story, and a "button" panel is shown in a dialog,
|
|
4
|
+
// opened by a button in the header. Neither is part of the story's text, so they don't count as
|
|
5
|
+
// moves for Back or saved games. On a screen too narrow for a side panel, it has a button too.
|
|
6
|
+
//
|
|
7
|
+
// const panels = createPanels(squiffyApi, {
|
|
8
|
+
// panels: story.panels,
|
|
9
|
+
// buttons: document.getElementById("squiffy-header"),
|
|
10
|
+
// side: document.getElementById("squiffy-container"),
|
|
11
|
+
// });
|
|
12
|
+
|
|
13
|
+
import { PANEL_ICONS, type Panel, type PanelIcon, type SquiffyApi } from "./types.js";
|
|
14
|
+
|
|
15
|
+
export interface PanelsOptions {
|
|
16
|
+
// From the story's squiffy.json "panels" (story.panels)
|
|
17
|
+
panels: Panel[];
|
|
18
|
+
// Where the panels' buttons go: at the start of this element, e.g. the page's header
|
|
19
|
+
buttons: HTMLElement;
|
|
20
|
+
// Where side panels go: an <aside class="squiffy-panels-side"> is added at the end of this
|
|
21
|
+
// element, which gets the class squiffy-has-side, so its CSS can make room. Without it,
|
|
22
|
+
// side panels only have their buttons.
|
|
23
|
+
side?: HTMLElement;
|
|
24
|
+
// The dialog's text, for a story in another language: "close". Anything left out is in English.
|
|
25
|
+
strings?: Partial<Record<string, string>>;
|
|
26
|
+
// Where the dialog goes in the page: the end of the body by default
|
|
27
|
+
container?: HTMLElement;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface Panels {
|
|
31
|
+
// Renders the panels again, e.g. after changing an attribute from outside the story
|
|
32
|
+
refresh: () => void;
|
|
33
|
+
// Opens a panel's dialog, by its passage name
|
|
34
|
+
open: (passage: string) => void;
|
|
35
|
+
// Takes the panels, their buttons and their dialog off the page
|
|
36
|
+
dispose: () => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const ICON_CLOSE = "<path d=\"M18 6 6 18M6 6l12 12\"/>";
|
|
40
|
+
|
|
41
|
+
// Lucide icons (ISC licence), as are the page's other buttons
|
|
42
|
+
const ICONS: Record<PanelIcon, string> = {
|
|
43
|
+
bag: "<path d=\"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z\"/><path d=\"M8 10h8\"/><path d=\"M8 18h8\"/><path d=\"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6\"/><path d=\"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2\"/>",
|
|
44
|
+
person: "<path d=\"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2\"/><circle cx=\"12\" cy=\"7\" r=\"4\"/>",
|
|
45
|
+
map: "<path d=\"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z\"/><path d=\"M15 5.764v15\"/><path d=\"M9 3.236v15\"/>",
|
|
46
|
+
help: "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3\"/><path d=\"M12 17h.01\"/>",
|
|
47
|
+
info: "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 16v-4\"/><path d=\"M12 8h.01\"/>",
|
|
48
|
+
list: "<path d=\"M3 6h.01M3 12h.01M3 18h.01M8 6h13M8 12h13M8 18h13\"/>",
|
|
49
|
+
book: "<path d=\"M12 7v14\"/><path d=\"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z\"/>",
|
|
50
|
+
star: "<path d=\"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z\"/>",
|
|
51
|
+
heart: "<path d=\"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z\"/>",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const svg = (paths: string) => `<svg viewBox="0 0 24 24" aria-hidden="true">${paths}</svg>`;
|
|
55
|
+
|
|
56
|
+
let dialogCount = 0;
|
|
57
|
+
|
|
58
|
+
export function createPanels(api: SquiffyApi, options: PanelsOptions): Panels {
|
|
59
|
+
const close = typeof options.strings?.close == "string" ? options.strings.close : "Close";
|
|
60
|
+
const id = `squiffy-panel-${++dialogCount}`;
|
|
61
|
+
const cleanups: (() => void)[] = [];
|
|
62
|
+
|
|
63
|
+
// The dialog that button panels are shown in, one at a time
|
|
64
|
+
const dialog = document.createElement("dialog");
|
|
65
|
+
dialog.className = "squiffy-panel-dialog";
|
|
66
|
+
dialog.setAttribute("aria-labelledby", `${id}-heading`);
|
|
67
|
+
dialog.innerHTML = `
|
|
68
|
+
<div class="squiffy-panel-dialog-header">
|
|
69
|
+
<h2 id="${id}-heading"></h2>
|
|
70
|
+
<button type="button" class="squiffy-panel-dialog-close">${svg(ICON_CLOSE)}</button>
|
|
71
|
+
</div>
|
|
72
|
+
<div class="squiffy-panel squiffy-panel-dialog-content"></div>`;
|
|
73
|
+
const heading = dialog.querySelector("h2")!;
|
|
74
|
+
const closeButton = dialog.querySelector<HTMLButtonElement>(".squiffy-panel-dialog-close")!;
|
|
75
|
+
closeButton.title = close;
|
|
76
|
+
closeButton.setAttribute("aria-label", close);
|
|
77
|
+
closeButton.addEventListener("click", () => dialog.close());
|
|
78
|
+
const content = dialog.querySelector<HTMLDivElement>(".squiffy-panel-dialog-content")!;
|
|
79
|
+
// Clicking the backdrop closes it too
|
|
80
|
+
dialog.addEventListener("click", event => {
|
|
81
|
+
if (event.target === dialog) dialog.close();
|
|
82
|
+
});
|
|
83
|
+
(options.container ?? document.body).appendChild(dialog);
|
|
84
|
+
cleanups.push(() => dialog.remove());
|
|
85
|
+
// The panel the dialog is showing
|
|
86
|
+
let shown: Panel | null = null;
|
|
87
|
+
|
|
88
|
+
const panels = options.panels.filter(panel => panel && typeof panel.passage == "string");
|
|
89
|
+
|
|
90
|
+
// The side panels, beside the story
|
|
91
|
+
const sidePanels = options.side ? panels.filter(panel => panel.position == "side") : [];
|
|
92
|
+
const sideSections = new Map<Panel, HTMLElement>();
|
|
93
|
+
let aside: HTMLElement | null = null;
|
|
94
|
+
if (sidePanels.length && options.side) {
|
|
95
|
+
aside = document.createElement("aside");
|
|
96
|
+
aside.className = "squiffy-panels-side";
|
|
97
|
+
for (const panel of sidePanels) {
|
|
98
|
+
const section = document.createElement("section");
|
|
99
|
+
section.className = "squiffy-panel";
|
|
100
|
+
section.dataset.passage = panel.passage;
|
|
101
|
+
section.setAttribute("aria-label", panel.label || panel.passage);
|
|
102
|
+
aside.appendChild(section);
|
|
103
|
+
sideSections.set(panel, section);
|
|
104
|
+
}
|
|
105
|
+
const side = options.side;
|
|
106
|
+
side.appendChild(aside);
|
|
107
|
+
side.classList.add("squiffy-has-side");
|
|
108
|
+
cleanups.push(() => {
|
|
109
|
+
aside!.remove();
|
|
110
|
+
side.classList.remove("squiffy-has-side");
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// A button for each panel, in the order they're listed, before anything already in the header.
|
|
115
|
+
// A side panel's button is only shown on screens too narrow for the panel.
|
|
116
|
+
const first = options.buttons.firstChild;
|
|
117
|
+
for (const panel of panels) {
|
|
118
|
+
const label = panel.label || panel.passage;
|
|
119
|
+
const button = document.createElement("button");
|
|
120
|
+
button.type = "button";
|
|
121
|
+
button.className = "squiffy-header-button squiffy-panel-button";
|
|
122
|
+
if (panel.position == "side" && sideSections.has(panel)) button.classList.add("squiffy-panel-side-button");
|
|
123
|
+
button.dataset.passage = panel.passage;
|
|
124
|
+
button.setAttribute("aria-haspopup", "dialog");
|
|
125
|
+
const icon = panel.icon && (PANEL_ICONS as readonly string[]).includes(panel.icon) ? ICONS[panel.icon] : null;
|
|
126
|
+
if (icon) {
|
|
127
|
+
button.innerHTML = svg(icon);
|
|
128
|
+
button.title = label;
|
|
129
|
+
button.setAttribute("aria-label", label);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
button.classList.add("squiffy-panel-text-button");
|
|
133
|
+
button.textContent = label;
|
|
134
|
+
}
|
|
135
|
+
button.addEventListener("click", () => open(panel));
|
|
136
|
+
options.buttons.insertBefore(button, first);
|
|
137
|
+
cleanups.push(() => button.remove());
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function open(panel: Panel) {
|
|
141
|
+
shown = panel;
|
|
142
|
+
heading.textContent = panel.label || panel.passage;
|
|
143
|
+
content.innerHTML = api.renderPassage(panel.passage);
|
|
144
|
+
if (!dialog.open) dialog.showModal();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function refresh() {
|
|
148
|
+
for (const [panel, section] of sideSections) {
|
|
149
|
+
section.innerHTML = api.renderPassage(panel.passage);
|
|
150
|
+
// Text that comes out empty, e.g. from an {{#if}}, hides the panel
|
|
151
|
+
section.hidden = !section.textContent?.trim() && !section.querySelector("img, svg, video, canvas, iframe");
|
|
152
|
+
}
|
|
153
|
+
if (aside) aside.hidden = [...sideSections.values()].every(section => section.hidden);
|
|
154
|
+
if (dialog.open && shown) content.innerHTML = api.renderPassage(shown.passage);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Rendered again once whatever changed has finished changing, rather than after every attribute
|
|
158
|
+
let queued = false;
|
|
159
|
+
const queueRefresh = () => {
|
|
160
|
+
if (queued) return;
|
|
161
|
+
queued = true;
|
|
162
|
+
queueMicrotask(() => {
|
|
163
|
+
queued = false;
|
|
164
|
+
if (!disposed) refresh();
|
|
165
|
+
});
|
|
166
|
+
};
|
|
167
|
+
for (const event of ["set", "navigated", "storyUpdated"] as const) {
|
|
168
|
+
cleanups.push(api.on(event, queueRefresh));
|
|
169
|
+
}
|
|
170
|
+
dialog.addEventListener("close", () => { shown = null; });
|
|
171
|
+
|
|
172
|
+
let disposed = false;
|
|
173
|
+
refresh();
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
refresh,
|
|
177
|
+
open(passage: string) {
|
|
178
|
+
const panel = panels.find(p => p.passage == passage);
|
|
179
|
+
if (panel) open(panel);
|
|
180
|
+
},
|
|
181
|
+
dispose() {
|
|
182
|
+
disposed = true;
|
|
183
|
+
if (dialog.open) dialog.close();
|
|
184
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
|
@@ -220,6 +220,48 @@ Your score is {{#label "score"}}0{{/label}}.
|
|
|
220
220
|
expect(labelSpans[0].classList.contains("fade-in")).toBe(false);
|
|
221
221
|
});
|
|
222
222
|
|
|
223
|
+
test("Replace plugin: replaces the latest label, in a section visited again after the screen is cleared", async () => {
|
|
224
|
+
const script = `
|
|
225
|
+
[[]]:
|
|
226
|
+
@clear
|
|
227
|
+
|
|
228
|
+
[[room]]:
|
|
229
|
+
The box is {{#label "box"}}closed{{/label}}. [Open it](open) or [[go out]](outside).
|
|
230
|
+
|
|
231
|
+
[open]:
|
|
232
|
+
{{#replace "box"}}open{{/replace}}
|
|
233
|
+
|
|
234
|
+
[[outside]]:
|
|
235
|
+
You're outside. [[Go back in]](room)
|
|
236
|
+
`;
|
|
237
|
+
|
|
238
|
+
const { squiffyApi, element } = await initScript(script);
|
|
239
|
+
await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='outside']")!);
|
|
240
|
+
await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='room']")!);
|
|
241
|
+
|
|
242
|
+
expect(element.querySelectorAll(".squiffy-label-box").length).toBe(2);
|
|
243
|
+
const links = element.querySelectorAll<HTMLElement>("a.squiffy-link[data-passage='open']");
|
|
244
|
+
await squiffyApi.clickLink(links[links.length - 1]);
|
|
245
|
+
const labels = element.querySelectorAll(".squiffy-label-box");
|
|
246
|
+
expect(labels[0].textContent).toBe("closed");
|
|
247
|
+
expect(labels[1].textContent).toBe("open");
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
test("Replace plugin: replace with only a label in it", async () => {
|
|
251
|
+
const script = `
|
|
252
|
+
The box is {{#label "box"}}closed{{/label}}. [Open it](open)
|
|
253
|
+
|
|
254
|
+
[open]:
|
|
255
|
+
{{#replace "box"}}{{#label "lid"}}open{{/label}}{{/replace}}
|
|
256
|
+
`;
|
|
257
|
+
|
|
258
|
+
const { squiffyApi, element } = await initScript(script);
|
|
259
|
+
await squiffyApi.clickLink(findPassageLink(element, "open")!);
|
|
260
|
+
|
|
261
|
+
expect(element.querySelector(".squiffy-label-box")?.innerHTML).toBe("<span class=\"squiffy-label-lid\">open</span>");
|
|
262
|
+
expect(element.querySelector(".squiffy-error")).toBeNull();
|
|
263
|
+
});
|
|
264
|
+
|
|
223
265
|
// ===== RotateSequencePlugin Tests =====
|
|
224
266
|
|
|
225
267
|
test("Sequence plugin: click through sequence", async () => {
|
|
@@ -11,8 +11,12 @@ export function ReplaceLabel() : SquiffyPlugin {
|
|
|
11
11
|
return new Handlebars.SafeString(`<span class="squiffy-label-${name}">${options.fn(this)}</span>`);
|
|
12
12
|
});
|
|
13
13
|
squiffy.registerHelper("replace", function(this: any, name: string, options) {
|
|
14
|
-
|
|
15
|
-
const
|
|
14
|
+
// A block that's only another helper, such as {{#label}}, gives that helper's SafeString
|
|
15
|
+
const result = String(options.fn(this));
|
|
16
|
+
// The latest label with the name: when a section is visited again, or the screen's been
|
|
17
|
+
// cleared, earlier ones can still be in the output (in the clear stack, hidden)
|
|
18
|
+
const labels = squiffy.outputElement.querySelectorAll<HTMLElement>(`.squiffy-label-${name}`);
|
|
19
|
+
const element = labels[labels.length - 1];
|
|
16
20
|
if (element) {
|
|
17
21
|
const isBlock = result.includes("\n\n");
|
|
18
22
|
const html = isBlock
|
package/src/preview-host.test.ts
CHANGED
|
@@ -31,10 +31,12 @@ describe("preview host", () => {
|
|
|
31
31
|
]);
|
|
32
32
|
|
|
33
33
|
host.update("x");
|
|
34
|
+
host.update("y", ["body { color: red; }"]);
|
|
34
35
|
host.restart();
|
|
35
36
|
host.back();
|
|
36
37
|
expect(sent.slice(2)).toEqual([
|
|
37
38
|
{ channel: PREVIEW_CHANNEL, type: "update", js: "x" },
|
|
39
|
+
{ channel: PREVIEW_CHANNEL, type: "update", js: "y", css: ["body { color: red; }"] },
|
|
38
40
|
{ channel: PREVIEW_CHANNEL, type: "restart" },
|
|
39
41
|
{ channel: PREVIEW_CHANNEL, type: "back" },
|
|
40
42
|
]);
|
|
@@ -61,7 +63,7 @@ describe("preview host", () => {
|
|
|
61
63
|
const { channel, receive } = fakeChannel();
|
|
62
64
|
const handlers = {
|
|
63
65
|
onReady: vi.fn(), onLoaded: vi.fn(), onAttributeSet: vi.fn(), onCanGoBackChanged: vi.fn(),
|
|
64
|
-
onNavigated: vi.fn(), onRuntimeError: vi.fn(),
|
|
66
|
+
onNavigated: vi.fn(), onThemeFixed: vi.fn(), onRuntimeError: vi.fn(),
|
|
65
67
|
};
|
|
66
68
|
const host = createPreviewHost(channel, handlers);
|
|
67
69
|
receive({ type: "navigated", section: "not ours" });
|
|
@@ -73,6 +75,7 @@ describe("preview host", () => {
|
|
|
73
75
|
{ type: "attributeSet", name: "score", value: 2 },
|
|
74
76
|
{ type: "canGoBackChanged", canGoBack: true },
|
|
75
77
|
{ type: "navigated", section: "s", passage: "p" },
|
|
78
|
+
{ type: "themeFixed", fixed: true },
|
|
76
79
|
{ type: "runtimeError", message: "oops", stack: "at x" },
|
|
77
80
|
]) {
|
|
78
81
|
receive({ channel: PREVIEW_CHANNEL, ...message });
|
|
@@ -83,6 +86,7 @@ describe("preview host", () => {
|
|
|
83
86
|
expect(handlers.onCanGoBackChanged).toHaveBeenCalledWith(true);
|
|
84
87
|
expect(handlers.onNavigated).toHaveBeenCalledOnce();
|
|
85
88
|
expect(handlers.onNavigated).toHaveBeenCalledWith("s", "p");
|
|
89
|
+
expect(handlers.onThemeFixed).toHaveBeenCalledWith(true);
|
|
86
90
|
expect(handlers.onRuntimeError).toHaveBeenCalledWith("oops", "at x");
|
|
87
91
|
|
|
88
92
|
host.dispose();
|
package/src/preview-host.ts
CHANGED
|
@@ -31,6 +31,8 @@ export interface PreviewHandlers {
|
|
|
31
31
|
onAttributeSet?(name: string, value: unknown): void;
|
|
32
32
|
onCanGoBackChanged?(canGoBack: boolean): void;
|
|
33
33
|
onNavigated?(section: string, passage?: string): void;
|
|
34
|
+
// Whether the story's own CSS sets its color-scheme, so setTheme() makes no difference
|
|
35
|
+
onThemeFixed?(fixed: boolean): void;
|
|
34
36
|
onRuntimeError?(message: string, stack?: string): void;
|
|
35
37
|
}
|
|
36
38
|
|
|
@@ -39,8 +41,9 @@ export interface PreviewHost {
|
|
|
39
41
|
readonly ready: Promise<void>;
|
|
40
42
|
// Starts a story, replacing any that's running
|
|
41
43
|
load(story: PreviewStory, options?: { startAt?: StartAt }): void;
|
|
42
|
-
// Hot-updates the running story, keeping its state
|
|
43
|
-
|
|
44
|
+
// Hot-updates the running story, keeping its state. css, if given, replaces the story's own
|
|
45
|
+
// stylesheets; its scripts only change with load().
|
|
46
|
+
update(js: string, css?: string[]): void;
|
|
44
47
|
restart(): void;
|
|
45
48
|
back(): void;
|
|
46
49
|
// Sets the assets the story can use. Send these before load().
|
|
@@ -112,6 +115,9 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
|
|
|
112
115
|
case "navigated":
|
|
113
116
|
handlers.onNavigated?.(message.section, message.passage);
|
|
114
117
|
break;
|
|
118
|
+
case "themeFixed":
|
|
119
|
+
handlers.onThemeFixed?.(message.fixed);
|
|
120
|
+
break;
|
|
115
121
|
case "runtimeError":
|
|
116
122
|
handlers.onRuntimeError?.(message.message, message.stack);
|
|
117
123
|
break;
|
|
@@ -121,7 +127,7 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
|
|
|
121
127
|
return {
|
|
122
128
|
ready,
|
|
123
129
|
load: (story, options = {}) => send({ type: "load", story, ...(options.startAt ? { startAt: options.startAt } : {}) }),
|
|
124
|
-
update: js => send({ type: "update", js }),
|
|
130
|
+
update: (js, css) => send({ type: "update", js, ...(css ? { css } : {}) }),
|
|
125
131
|
restart: () => send({ type: "restart" }),
|
|
126
132
|
back: () => send({ type: "back" }),
|
|
127
133
|
setAssets: assets => send({ type: "assets", assets }),
|
package/src/preview-protocol.ts
CHANGED
|
@@ -33,8 +33,9 @@ export type PreviewTheme = "light" | "dark" | "system";
|
|
|
33
33
|
export type HostMessage =
|
|
34
34
|
// Starts a story, replacing any that's running. Send assets first.
|
|
35
35
|
| { type: "load"; story: PreviewStory; startAt?: StartAt }
|
|
36
|
-
// Hot-updates the running story, keeping its state
|
|
37
|
-
|
|
36
|
+
// Hot-updates the running story, keeping its state. css, if given, replaces the story's own
|
|
37
|
+
// stylesheets. Its scripts can't be replaced in a running story: that needs a load.
|
|
38
|
+
| { type: "update"; js: string; css?: string[] }
|
|
38
39
|
| { type: "restart" }
|
|
39
40
|
| { type: "back" }
|
|
40
41
|
// Replaces the assets the story can use
|
|
@@ -48,6 +49,9 @@ export type PreviewMessage =
|
|
|
48
49
|
| { type: "ready" }
|
|
49
50
|
// A story from a load message has started
|
|
50
51
|
| { type: "loaded" }
|
|
52
|
+
// Whether the story's own CSS sets its color-scheme, e.g. ":root { color-scheme: light; }",
|
|
53
|
+
// so the theme message makes no difference. Sent each time a story is loaded, before "loaded".
|
|
54
|
+
| { type: "themeFixed"; fixed: boolean }
|
|
51
55
|
// An attribute was set. Internal attributes, whose names start with "_", aren't sent.
|
|
52
56
|
| { type: "attributeSet"; name: string; value: unknown }
|
|
53
57
|
| { type: "canGoBackChanged"; canGoBack: boolean }
|
package/src/preview.test.ts
CHANGED
|
@@ -3,7 +3,7 @@ import globalJsdom from "global-jsdom";
|
|
|
3
3
|
import { compile } from "squiffy-compiler";
|
|
4
4
|
import { createPreview } from "./preview.js";
|
|
5
5
|
import type { PreviewMessage } from "./preview-protocol.js";
|
|
6
|
-
import type { Story } from "./types.js";
|
|
6
|
+
import type { Panel, Story } from "./types.js";
|
|
7
7
|
|
|
8
8
|
beforeAll(() => {
|
|
9
9
|
vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
|
|
@@ -31,8 +31,8 @@ afterEach(() => {
|
|
|
31
31
|
});
|
|
32
32
|
|
|
33
33
|
// The compiled story module, as a host would send it
|
|
34
|
-
const compileJs = async (script: string) => {
|
|
35
|
-
const result = await compile({ script });
|
|
34
|
+
const compileJs = async (script: string, panels?: Panel[]) => {
|
|
35
|
+
const result = await compile({ script, panels });
|
|
36
36
|
if (!result.success) throw new Error("Compile failed");
|
|
37
37
|
return result.getJs();
|
|
38
38
|
};
|
|
@@ -70,7 +70,10 @@ describe("preview", () => {
|
|
|
70
70
|
|
|
71
71
|
expect(element.textContent).toContain("Welcome.");
|
|
72
72
|
expect(messages).toEqual([
|
|
73
|
+
{ type: "themeFixed", fixed: false },
|
|
73
74
|
{ type: "canGoBackChanged", canGoBack: false },
|
|
75
|
+
// The story-wide turn count (#377), which isn't internal, so it's reported
|
|
76
|
+
{ type: "attributeSet", name: "turns", value: 0 },
|
|
74
77
|
{ type: "attributeSet", name: "score", value: 1 },
|
|
75
78
|
{ type: "navigated", section: "start" },
|
|
76
79
|
{ type: "loaded" },
|
|
@@ -80,6 +83,9 @@ describe("preview", () => {
|
|
|
80
83
|
element.querySelector<HTMLElement>("a[data-passage='look']")!.click();
|
|
81
84
|
await vi.waitFor(() => expect(messages.some(m => m.type == "navigated")).toBe(true));
|
|
82
85
|
expect(messages).toEqual([
|
|
86
|
+
{ type: "attributeSet", name: "turns", value: 1 },
|
|
87
|
+
// Where the player was before (#56), which isn't internal either
|
|
88
|
+
{ type: "attributeSet", name: "previous", value: "start" },
|
|
83
89
|
{ type: "attributeSet", name: "looked", value: true },
|
|
84
90
|
{ type: "canGoBackChanged", canGoBack: true },
|
|
85
91
|
{ type: "navigated", section: "start", passage: "look" },
|
|
@@ -139,6 +145,35 @@ describe("preview", () => {
|
|
|
139
145
|
expect(element.textContent).toContain("Welcome.");
|
|
140
146
|
});
|
|
141
147
|
|
|
148
|
+
test("hot updates replace the story's stylesheets, keeping its state", async () => {
|
|
149
|
+
const { preview, element, messages } = setUp();
|
|
150
|
+
const js = await compileJs(script);
|
|
151
|
+
const styles = () => [...document.head.querySelectorAll("style")].map(s => s.textContent);
|
|
152
|
+
const fixed = () => messages.filter(m => m.type == "themeFixed");
|
|
153
|
+
await preview.receive({ type: "load", story: { js, css: ["body { color: red; }", "p { margin: 0; }"] } });
|
|
154
|
+
element.querySelector<HTMLElement>("a[data-section='cellar']")!.click();
|
|
155
|
+
await vi.waitFor(() => expect(element.textContent).toContain("It's dark"));
|
|
156
|
+
|
|
157
|
+
messages.length = 0;
|
|
158
|
+
await preview.receive({ type: "update", js, css: ["body { color: blue; }"] });
|
|
159
|
+
// After the preview's own (empty) theme style
|
|
160
|
+
expect(styles()).toEqual(["", "body { color: blue; }"]);
|
|
161
|
+
expect(element.textContent).toContain("It's dark");
|
|
162
|
+
expect(fixed()).toEqual([{ type: "themeFixed", fixed: false }]);
|
|
163
|
+
|
|
164
|
+
// A stylesheet that sets color-scheme
|
|
165
|
+
messages.length = 0;
|
|
166
|
+
await preview.receive({ type: "update", js, css: [":root { color-scheme: light; }"] });
|
|
167
|
+
expect(fixed()).toEqual([{ type: "themeFixed", fixed: true }]);
|
|
168
|
+
|
|
169
|
+
// The same stylesheets again, or none given, change nothing
|
|
170
|
+
messages.length = 0;
|
|
171
|
+
await preview.receive({ type: "update", js, css: [":root { color-scheme: light; }"] });
|
|
172
|
+
await preview.receive({ type: "update", js });
|
|
173
|
+
expect(styles()).toEqual(["", ":root { color-scheme: light; }"]);
|
|
174
|
+
expect(fixed()).toEqual([]);
|
|
175
|
+
});
|
|
176
|
+
|
|
142
177
|
test("adds the story's stylesheets, replacing the previous story's", async () => {
|
|
143
178
|
const { preview } = setUp();
|
|
144
179
|
const js = await compileJs(script);
|
|
@@ -160,6 +195,39 @@ describe("preview", () => {
|
|
|
160
195
|
expect(styles()[0]).toBe("");
|
|
161
196
|
});
|
|
162
197
|
|
|
198
|
+
test("says whether the story's stylesheets set its color-scheme", async () => {
|
|
199
|
+
const { preview, messages } = setUp();
|
|
200
|
+
const js = await compileJs(script);
|
|
201
|
+
const fixed = () => messages.filter(m => m.type == "themeFixed");
|
|
202
|
+
|
|
203
|
+
await preview.receive({ type: "theme", theme: "dark" });
|
|
204
|
+
await preview.receive({ type: "load", story: { js, css: ["body { color: red; }"] } });
|
|
205
|
+
expect(fixed()).toEqual([{ type: "themeFixed", fixed: false }]);
|
|
206
|
+
|
|
207
|
+
messages.length = 0;
|
|
208
|
+
await preview.receive({ type: "load", story: { js, css: [":root { color-scheme: light; }"] } });
|
|
209
|
+
expect(fixed()).toEqual([{ type: "themeFixed", fixed: true }]);
|
|
210
|
+
// Finding out doesn't change the theme the host set
|
|
211
|
+
expect(document.head.querySelector("style")!.textContent).toBe(":root { color-scheme: dark; }");
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test("shows the story's panels, and shows them again when they change", async () => {
|
|
215
|
+
const { preview, element } = setUp();
|
|
216
|
+
const panelScript = "[[]]:\n\n[status]:\nScore: {{score}}\n\n" + script;
|
|
217
|
+
await preview.receive({ type: "load", story: { js: await compileJs(panelScript, [{ passage: "status", label: "Status", position: "side" }]) } });
|
|
218
|
+
expect(element.querySelector(".squiffy-preview-header button.squiffy-panel-button")!.textContent).toBe("Status");
|
|
219
|
+
expect(element.querySelector(".squiffy-preview-body > aside section")!.innerHTML).toBe("<p>Score: 1</p>");
|
|
220
|
+
|
|
221
|
+
await preview.receive({ type: "update", js: await compileJs(panelScript, [{ passage: "status", label: "Score" }]) });
|
|
222
|
+
expect(element.querySelector("aside")).toBeNull();
|
|
223
|
+
expect([...element.querySelectorAll("button.squiffy-panel-button")].map(b => b.textContent)).toEqual(["Score"]);
|
|
224
|
+
|
|
225
|
+
// A new story has no panels left over
|
|
226
|
+
await preview.receive({ type: "load", story: { js: await compileJs(script) } });
|
|
227
|
+
expect(element.querySelector("button.squiffy-panel-button")).toBeNull();
|
|
228
|
+
expect(document.querySelectorAll("dialog.squiffy-panel-dialog")).toHaveLength(0);
|
|
229
|
+
});
|
|
230
|
+
|
|
163
231
|
test("reports errors", async () => {
|
|
164
232
|
const messages: PreviewMessage[] = [];
|
|
165
233
|
const preview = createPreview({
|
package/src/preview.ts
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// page itself (preview.main.ts) connects this to postMessage; it's separate so it can be tested.
|
|
3
3
|
|
|
4
4
|
import { init } from "./squiffy.runtime.js";
|
|
5
|
+
import { createPanels, type Panels } from "./panels.js";
|
|
5
6
|
import type { HostMessage, PreviewAssets, PreviewMessage, PreviewStory } from "./preview-protocol.js";
|
|
6
|
-
import type { SquiffyApi, Story } from "./types.js";
|
|
7
|
+
import type { Panel, SquiffyApi, Story } from "./types.js";
|
|
7
8
|
|
|
8
9
|
export interface PreviewOptions {
|
|
9
10
|
// Where to show the story
|
|
@@ -47,11 +48,19 @@ function errorMessage(error: unknown): PreviewMessage {
|
|
|
47
48
|
export function createPreview(options: PreviewOptions) {
|
|
48
49
|
const loadModule = options.loadModule ?? importFromBlob;
|
|
49
50
|
let api: SquiffyApi | undefined;
|
|
51
|
+
// The story's panels (squiffy.json's "panels"), shown as on the published page: their buttons
|
|
52
|
+
// in a bar above the story, and side panels beside it if the preview is wide enough
|
|
53
|
+
let panels: Panels | undefined;
|
|
54
|
+
let panelsJson = "";
|
|
55
|
+
let panelButtons: HTMLElement | undefined;
|
|
56
|
+
let panelSide: HTMLElement | undefined;
|
|
50
57
|
// Each load gets a new number, so a slow load that's been replaced doesn't start
|
|
51
58
|
let loadCount = 0;
|
|
52
59
|
const assetUrls = new Map<string, string>();
|
|
53
60
|
const objectUrls: string[] = [];
|
|
54
|
-
|
|
61
|
+
// The story's own stylesheets and scripts
|
|
62
|
+
let styles: HTMLStyleElement[] = [];
|
|
63
|
+
let scripts: HTMLScriptElement[] = [];
|
|
55
64
|
// Sets the theme. It's added before any of the story's own stylesheets, so they can override it.
|
|
56
65
|
const themeStyle = document.createElement("style");
|
|
57
66
|
document.head.appendChild(themeStyle);
|
|
@@ -66,6 +75,19 @@ export function createPreview(options: PreviewOptions) {
|
|
|
66
75
|
}
|
|
67
76
|
};
|
|
68
77
|
|
|
78
|
+
// Whether the story's stylesheets set color-scheme themselves: if they do, the story looks the
|
|
79
|
+
// same whichever theme the preview is set to
|
|
80
|
+
function themeIsFixed(): boolean {
|
|
81
|
+
const theme = themeStyle.textContent;
|
|
82
|
+
const schemeFor = (scheme: string) => {
|
|
83
|
+
themeStyle.textContent = `:root { color-scheme: ${scheme}; }`;
|
|
84
|
+
return getComputedStyle(document.documentElement).getPropertyValue("color-scheme");
|
|
85
|
+
};
|
|
86
|
+
const fixed = schemeFor("light") == schemeFor("dark");
|
|
87
|
+
themeStyle.textContent = theme;
|
|
88
|
+
return fixed;
|
|
89
|
+
}
|
|
90
|
+
|
|
69
91
|
const resolveAssetUrl = (path: string) => assetUrls.get(normalisePath(path)) ?? path;
|
|
70
92
|
|
|
71
93
|
function setAssets(assets: PreviewAssets) {
|
|
@@ -82,14 +104,27 @@ export function createPreview(options: PreviewOptions) {
|
|
|
82
104
|
}
|
|
83
105
|
}
|
|
84
106
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
107
|
+
// Replaces the story's stylesheets, where the old ones were, so they stay before its scripts
|
|
108
|
+
// (which may add styles of their own). Returns false if they haven't changed.
|
|
109
|
+
function setStyles(css: string[]): boolean {
|
|
110
|
+
if (css.length == styles.length && css.every((text, i) => styles[i].textContent == text)) return false;
|
|
111
|
+
const before = styles[0] ?? scripts[0] ?? null;
|
|
112
|
+
const added = css.map(text => {
|
|
88
113
|
const style = document.createElement("style");
|
|
89
|
-
style.textContent =
|
|
90
|
-
document.head.
|
|
91
|
-
|
|
92
|
-
}
|
|
114
|
+
style.textContent = text;
|
|
115
|
+
document.head.insertBefore(style, before);
|
|
116
|
+
return style;
|
|
117
|
+
});
|
|
118
|
+
for (const style of styles) style.remove();
|
|
119
|
+
styles = added;
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function addStoryFiles(story: PreviewStory) {
|
|
124
|
+
for (const element of [...styles, ...scripts]) element.remove();
|
|
125
|
+
styles = [];
|
|
126
|
+
scripts = [];
|
|
127
|
+
setStyles(story.css ?? []);
|
|
93
128
|
for (const js of story.scripts ?? []) {
|
|
94
129
|
const script = document.createElement("script");
|
|
95
130
|
const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
|
|
@@ -99,7 +134,7 @@ export function createPreview(options: PreviewOptions) {
|
|
|
99
134
|
document.head.appendChild(script);
|
|
100
135
|
});
|
|
101
136
|
URL.revokeObjectURL(url);
|
|
102
|
-
|
|
137
|
+
scripts.push(script);
|
|
103
138
|
}
|
|
104
139
|
}
|
|
105
140
|
|
|
@@ -110,10 +145,19 @@ export function createPreview(options: PreviewOptions) {
|
|
|
110
145
|
await addStoryFiles(message.story);
|
|
111
146
|
const { story } = await loadModule(message.story.js);
|
|
112
147
|
if (thisLoad != loadCount) return;
|
|
113
|
-
|
|
148
|
+
send({ type: "themeFixed", fixed: themeIsFixed() });
|
|
149
|
+
|
|
150
|
+
panels?.dispose();
|
|
151
|
+
panels = undefined;
|
|
152
|
+
panelsJson = "";
|
|
153
|
+
panelButtons = document.createElement("div");
|
|
154
|
+
panelButtons.className = "squiffy-preview-header";
|
|
155
|
+
panelSide = document.createElement("div");
|
|
156
|
+
panelSide.className = "squiffy-preview-body";
|
|
114
157
|
const container = document.createElement("div");
|
|
115
158
|
container.className = "squiffy-preview-story";
|
|
116
|
-
|
|
159
|
+
panelSide.appendChild(container);
|
|
160
|
+
options.element.append(panelButtons, panelSide);
|
|
117
161
|
|
|
118
162
|
const newApi = await init({
|
|
119
163
|
element: container,
|
|
@@ -132,11 +176,21 @@ export function createPreview(options: PreviewOptions) {
|
|
|
132
176
|
if (thisLoad == loadCount) send({ type: "navigated", ...e });
|
|
133
177
|
});
|
|
134
178
|
api = newApi;
|
|
179
|
+
setPanels(story.panels);
|
|
135
180
|
send({ type: "canGoBackChanged", canGoBack: false });
|
|
136
181
|
await newApi.begin(message.startAt);
|
|
137
182
|
if (thisLoad == loadCount) send({ type: "loaded" });
|
|
138
183
|
}
|
|
139
184
|
|
|
185
|
+
// Shows the story's panels, or shows them again if they've changed
|
|
186
|
+
function setPanels(list: Panel[] | undefined) {
|
|
187
|
+
const json = JSON.stringify(list ?? []);
|
|
188
|
+
if (!api || !panelButtons || json == panelsJson) return;
|
|
189
|
+
panelsJson = json;
|
|
190
|
+
panels?.dispose();
|
|
191
|
+
panels = list?.length ? createPanels(api, { panels: list, buttons: panelButtons, side: panelSide }) : undefined;
|
|
192
|
+
}
|
|
193
|
+
|
|
140
194
|
async function receive(message: HostMessage) {
|
|
141
195
|
try {
|
|
142
196
|
switch (message.type) {
|
|
@@ -144,7 +198,14 @@ export function createPreview(options: PreviewOptions) {
|
|
|
144
198
|
await load(message);
|
|
145
199
|
break;
|
|
146
200
|
case "update":
|
|
147
|
-
if (api)
|
|
201
|
+
if (!api) break;
|
|
202
|
+
// A stylesheet can change whether the story sets its own color-scheme
|
|
203
|
+
if (message.css && setStyles(message.css)) send({ type: "themeFixed", fixed: themeIsFixed() });
|
|
204
|
+
{
|
|
205
|
+
const { story } = await loadModule(message.js);
|
|
206
|
+
api.update(story);
|
|
207
|
+
setPanels(story.panels);
|
|
208
|
+
}
|
|
148
209
|
break;
|
|
149
210
|
case "restart":
|
|
150
211
|
api?.restart();
|