squiffy-compiler 7.0.0-beta.6 → 7.0.0-beta.8

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.
Files changed (46) hide show
  1. package/dist/analyse.d.ts +12 -1
  2. package/dist/analyse.js +156 -9
  3. package/dist/compiler.d.ts +5 -3
  4. package/dist/compiler.js +3 -2
  5. package/dist/css-urls.d.ts +4 -0
  6. package/dist/css-urls.js +59 -0
  7. package/dist/emit.d.ts +18 -1
  8. package/dist/emit.js +46 -0
  9. package/dist/infix-expressions.d.ts +19 -0
  10. package/dist/infix-expressions.js +713 -0
  11. package/dist/language-service.d.ts +1 -0
  12. package/dist/language-service.js +34 -15
  13. package/dist/node.d.ts +2 -1
  14. package/dist/node.js +1 -0
  15. package/dist/parse.d.ts +4 -0
  16. package/dist/parse.js +29 -0
  17. package/dist/project.d.ts +31 -0
  18. package/dist/project.js +98 -0
  19. package/dist/quest/convert.js +67 -11
  20. package/dist/quest/scripts.js +13 -9
  21. package/dist/quest/text.js +17 -8
  22. package/dist/section-labels.d.ts +4 -0
  23. package/dist/section-labels.js +64 -0
  24. package/dist/setters.d.ts +4 -0
  25. package/dist/setters.js +11 -9
  26. package/dist/story-graph.d.ts +2 -0
  27. package/dist/story-graph.js +61 -16
  28. package/dist/syntax.d.ts +24 -3
  29. package/dist/templates.d.ts +6 -0
  30. package/dist/templates.js +128 -0
  31. package/dist/text.d.ts +3 -1
  32. package/dist/text.js +45 -11
  33. package/dist/twine/audio.d.ts +21 -0
  34. package/dist/twine/audio.js +80 -0
  35. package/dist/twine/convert.d.ts +45 -3
  36. package/dist/twine/convert.js +305 -37
  37. package/dist/twine/expression.d.ts +21 -1
  38. package/dist/twine/expression.js +105 -8
  39. package/dist/twine/harlowe.d.ts +9 -0
  40. package/dist/twine/harlowe.js +461 -86
  41. package/dist/twine/settings.d.ts +9 -0
  42. package/dist/twine/settings.js +322 -0
  43. package/dist/twine/sugarcube.d.ts +3 -0
  44. package/dist/twine/sugarcube.js +438 -114
  45. package/package.json +9 -2
  46. package/syntaxes/squiffy.tmLanguage.json +8 -3
@@ -75,6 +75,7 @@ export interface LanguageService {
75
75
  getProjectInfo(): Promise<ProjectInfo>;
76
76
  getAnalysis(): Promise<Analysis>;
77
77
  getDiagnostics(path: string): Promise<Diagnostic[]>;
78
+ getAllDiagnostics(): Promise<Diagnostic[]>;
78
79
  getDocumentSymbols(path: string): Promise<DocumentSymbol[]>;
79
80
  getDefinition(path: string, position: Position): Promise<Location | undefined>;
80
81
  getReferences(path: string, position: Position, includeDeclaration?: boolean): Promise<Location[]>;
@@ -8,8 +8,8 @@
8
8
  import { analyse, ParseCache } from "./analyse.js";
9
9
  import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME, storyFileList } from "./project.js";
10
10
  import { convertV5Syntax, findV5Syntax } from "./v5.js";
11
- import { findUnquotedText } from "./setters.js";
12
- import { buildStoryGraph, storyGraphDiagnostics } from "./story-graph.js";
11
+ import { findUnquotedText, splitWithOffsets } from "./setters.js";
12
+ import { buildStoryGraph, firstScreenSoundDiagnostics, storyGraphDiagnostics } from "./story-graph.js";
13
13
  const sameSymbol = (a, b) => a.kind == b.kind && a.name == b.name && (a.kind == "section" || a.section == b.section);
14
14
  const usageRange = (usage) => (usage.link ?? usage.embed ?? usage.goto ?? usage.deactivate).range;
15
15
  // Directives, for completion, with what they do
@@ -24,6 +24,11 @@ const DIRECTIVES = [
24
24
  ["clear", "Clears the screen"],
25
25
  ["repeat", "Lets the player click this passage's links again"],
26
26
  ["end", "Marks this section as an ending"],
27
+ ["music", "Plays music until it's changed, or stops it with @music stop"],
28
+ ["sound", "Plays a sound once, or stops the sounds playing with @sound stop"],
29
+ ["class", "Puts classes on the story while this section is shown, for its stylesheet"],
30
+ ["transition", "How this section or passage appears, such as @transition fade 1s"],
31
+ ["leave", "How the old text goes when this clears the screen, such as @leave fade 1s"],
27
32
  ["ui", "JavaScript for the story's user interface"],
28
33
  ];
29
34
  const contains = (range, pos) => comparePositions(range.start, pos) <= 0 && comparePositions(pos, range.end) <= 0;
@@ -41,8 +46,9 @@ function resolveName(target, has) {
41
46
  }
42
47
  // The name a broken link was trying to reach
43
48
  const intendedName = (target) => target.trim().split(",")[0].trim();
49
+ // The attribute a setter sets, e.g. gold in gold += 1, or hero.hp in hero.hp = 10 (#442)
44
50
  function attributeName(expression) {
45
- return expression.replace(/^\s*not\s+/, "").split(/[-+]?=/)[0].trim();
51
+ return /^\s*(?:not\s+)?(\w+(?:\.\w+)*)/.exec(expression)?.[1] ?? "";
46
52
  }
47
53
  function resolvePath(baseDir, relative) {
48
54
  const parts = baseDir ? baseDir.split("/") : [];
@@ -217,6 +223,14 @@ export function createLanguageService(options) {
217
223
  if (section.node)
218
224
  index.nodeNames.set(section.node, section.name);
219
225
  }
226
+ // An attribute, and for a value inside an object, the object too: hero.hp adds hero
227
+ const addAttribute = (name) => {
228
+ const parts = name.split(".");
229
+ for (let i = 1; i <= parts.length; i++) {
230
+ if (parts[i - 1])
231
+ index.attributes.add(parts.slice(0, i).join("."));
232
+ }
233
+ };
220
234
  for (const [path, file] of index.files) {
221
235
  for (const node of [file.preamble, ...file.sections]) {
222
236
  if (node.type == "snippet") {
@@ -226,11 +240,10 @@ export function createLanguageService(options) {
226
240
  for (const container of [node, ...node.passages]) {
227
241
  for (const link of container.links) {
228
242
  index.usages.push({ file: path, container, sectionNode: node, link });
229
- const setters = link.target.split(",").slice(1);
243
+ const comma = link.target.indexOf(",");
244
+ const setters = comma == -1 ? [] : splitWithOffsets(link.target.substring(comma + 1)).map(part => part.text);
230
245
  for (const setter of setters) {
231
- const name = attributeName(setter);
232
- if (name)
233
- index.attributes.add(name);
246
+ addAttribute(attributeName(setter));
234
247
  }
235
248
  }
236
249
  for (const embed of container.embeds) {
@@ -244,9 +257,7 @@ export function createLanguageService(options) {
244
257
  }
245
258
  for (const statement of container.body) {
246
259
  if (statement.type == "attribute") {
247
- const name = attributeName(statement.value);
248
- if (name)
249
- index.attributes.add(name);
260
+ addAttribute(attributeName(statement.value));
250
261
  }
251
262
  else if (statement.type == "js") {
252
263
  for (const match of statement.code.matchAll(/\bset\(\s*["']([^"']+)["']/g)) {
@@ -280,15 +291,16 @@ export function createLanguageService(options) {
280
291
  }
281
292
  function getGraph(index) {
282
293
  if (!index.graph) {
283
- const graph = buildStoryGraph({
294
+ const source = {
284
295
  files: index.files,
285
296
  sections: index.sections,
286
297
  nodeNames: index.nodeNames,
287
298
  usages: index.usages,
288
299
  start: index.analysis.start,
289
- resolve: usage => resolveUsage(index, usage),
290
- });
291
- index.graph = { graph, diagnostics: storyGraphDiagnostics(graph) };
300
+ resolve: (usage) => resolveUsage(index, usage),
301
+ };
302
+ const graph = buildStoryGraph(source);
303
+ index.graph = { graph, diagnostics: [...storyGraphDiagnostics(graph), ...firstScreenSoundDiagnostics(source)] };
292
304
  }
293
305
  return index.graph;
294
306
  }
@@ -472,6 +484,9 @@ export function createLanguageService(options) {
472
484
  const index = await getIndex();
473
485
  return allDiagnostics(index).filter(d => d.file == path);
474
486
  },
487
+ async getAllDiagnostics() {
488
+ return allDiagnostics(await getIndex());
489
+ },
475
490
  async getDocumentSymbols(path) {
476
491
  const index = await getIndex();
477
492
  const tree = await getFile(index, path);
@@ -590,7 +605,7 @@ export function createLanguageService(options) {
590
605
  .map(name => ({ label: name, kind: "passage", range: replace(typed) }));
591
606
  };
592
607
  let match;
593
- if ((match = /\{\{~?\s*embed\s+["']([^"']*)$/.exec(prefix))) {
608
+ if ((match = /\{\{~?\s*#?embed\s+["']([^"']*)$/.exec(prefix))) {
594
609
  return [...passageItems(match[1]), ...sectionItems(match[1])];
595
610
  }
596
611
  // {{seen "name"}}, (visits "name") etc., which take a section or passage (#377)
@@ -603,6 +618,10 @@ export function createLanguageService(options) {
603
618
  if ((match = /\{\{~?\s*deactivate\s+["']([^"']*)$/.exec(prefix))) {
604
619
  return passageItems(match[1]);
605
620
  }
621
+ // A text box that goes somewhere when Enter is pressed (#454)
622
+ if ((match = /<input\b[^>]*\sdata-(section|passage)\s*=\s*["']([^"']*)$/i.exec(prefix))) {
623
+ return match[1].toLowerCase() == "section" ? sectionItems(match[2]) : passageItems(match[2]);
624
+ }
606
625
  if ((match = /\[\[[^\]]*\]\]\(([^),]*)$/.exec(prefix))) {
607
626
  return sectionItems(match[1]);
608
627
  }
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type PageStrings, type Panel } from "./project.js";
1
+ import { type PageStrings, type Panel, type PlayerSetting } from "./project.js";
2
2
  export interface StoryOnDisk {
3
3
  mainFile: string;
4
4
  storyFiles?: string[];
@@ -10,6 +10,7 @@ export interface StoryOnDisk {
10
10
  saveButton?: boolean;
11
11
  projectId?: string;
12
12
  panels?: Panel[];
13
+ settings?: PlayerSetting[];
13
14
  }
14
15
  export declare class StoryNotFoundError extends Error {
15
16
  }
package/dist/node.js CHANGED
@@ -84,6 +84,7 @@ async function folderStory(projectFile, options) {
84
84
  ...(project.saveButton !== undefined ? { saveButton: project.saveButton } : {}),
85
85
  ...(project.id !== undefined ? { projectId: project.id } : {}),
86
86
  ...(project.panels !== undefined ? { panels: project.panels } : {}),
87
+ ...(project.settings !== undefined ? { settings: project.settings } : {}),
87
88
  };
88
89
  }
89
90
  // Finds the story to build from what the author gave: a folder with a squiffy.json in it, or a
package/dist/parse.d.ts CHANGED
@@ -13,5 +13,9 @@ export declare const lineRegexes: {
13
13
  js: RegExp;
14
14
  continue: RegExp;
15
15
  ui: RegExp;
16
+ music: RegExp;
17
+ sound: RegExp;
18
+ class: RegExp;
19
+ transition: RegExp;
16
20
  };
17
21
  export declare function parse(text: string, filename?: string): SquiffyFile;
package/dist/parse.js CHANGED
@@ -13,6 +13,10 @@ export const lineRegexes = {
13
13
  js: /^(\t| {4})(.*)$/,
14
14
  continue: /^\+\+\+(.*)$/,
15
15
  ui: /^@ui (.*)$/,
16
+ music: /^@music (.*)$/,
17
+ sound: /^@sound (.*)$/,
18
+ class: /^@class (.*)$/,
19
+ transition: /^@(transition|leave) (\S+)(?: (\S+))?$/,
16
20
  };
17
21
  // Parses one .squiffy file into a syntax tree. This never fails: problems such as a passage
18
22
  // with no section are reported by analyse(), which knows how the file fits into the story.
@@ -176,6 +180,31 @@ export function parse(text, filename) {
176
180
  else if (match.import) {
177
181
  add({ type: "import", pattern: match.import[1], patternRange: valueRange(i, match.import[1]), range });
178
182
  }
183
+ else if (match.music || match.sound) {
184
+ if (!passage)
185
+ haveSection = true;
186
+ const value = (match.music ?? match.sound)[1];
187
+ add({ type: "sound", directive: match.music ? "music" : "sound", value, valueRange: valueRange(i, value), range });
188
+ }
189
+ else if (match.class) {
190
+ if (!passage)
191
+ haveSection = true;
192
+ add({ type: "class", value: match.class[1], valueRange: valueRange(i, match.class[1]), range });
193
+ }
194
+ else if (match.transition) {
195
+ if (!passage)
196
+ haveSection = true;
197
+ const [, directive, value, time] = match.transition;
198
+ const start = line.indexOf(value, line.indexOf("@") + directive.length + 1);
199
+ add({
200
+ type: "transition",
201
+ directive: directive,
202
+ value,
203
+ valueRange: { start: { line: i, character: start }, end: { line: i, character: start + value.length } },
204
+ ...(time === undefined ? {} : { time }),
205
+ range,
206
+ });
207
+ }
179
208
  else if (match.attributes || match.unset) {
180
209
  haveSection = true;
181
210
  const value = (match.attributes ?? match.unset)[1];
package/dist/project.d.ts CHANGED
@@ -11,7 +11,32 @@ export interface ProjectFile {
11
11
  saveButton?: boolean;
12
12
  strings?: PageStrings;
13
13
  panels?: Panel[];
14
+ settings?: PlayerSetting[];
14
15
  }
16
+ export type PlayerSetting = PlayerSettingBase & {
17
+ type: "toggle";
18
+ default?: boolean;
19
+ } | PlayerSettingBase & {
20
+ type: "list";
21
+ options: PlayerSettingOption[];
22
+ default?: string;
23
+ } | PlayerSettingBase & {
24
+ type: "range";
25
+ min: number;
26
+ max: number;
27
+ step?: number;
28
+ default?: number;
29
+ };
30
+ interface PlayerSettingBase {
31
+ name: string;
32
+ label: string;
33
+ description?: string;
34
+ }
35
+ export interface PlayerSettingOption {
36
+ value: string;
37
+ label: string;
38
+ }
39
+ export declare const PLAYER_SETTING_TYPES: readonly ["toggle", "list", "range"];
15
40
  export declare const PANEL_ICONS: readonly ["bag", "person", "map", "help", "info", "list", "book", "star", "heart"];
16
41
  export type PanelIcon = typeof PANEL_ICONS[number];
17
42
  export interface Panel {
@@ -28,6 +53,8 @@ export declare const PAGE_STRINGS: {
28
53
  restartConfirm: string;
29
54
  switchToDark: string;
30
55
  switchToLight: string;
56
+ mute: string;
57
+ unmute: string;
31
58
  saves: string;
32
59
  saveName: string;
33
60
  save: string;
@@ -51,6 +78,8 @@ export declare const PAGE_STRINGS: {
51
78
  wrongStory: string;
52
79
  notASave: string;
53
80
  cantSave: string;
81
+ settings: string;
82
+ resetSettings: string;
54
83
  };
55
84
  export interface MapPositions {
56
85
  sections: Record<string, [number, number]>;
@@ -88,9 +117,11 @@ export declare function formatProjectFile(project: {
88
117
  map?: MapPositions;
89
118
  id?: string;
90
119
  panels?: Panel[];
120
+ settings?: PlayerSetting[];
91
121
  }): string;
92
122
  export declare function updateProjectFile(text: string, changes: {
93
123
  main?: string;
94
124
  exclude?: string[];
95
125
  map?: MapPositions;
96
126
  }): string | undefined;
127
+ export {};
package/dist/project.js CHANGED
@@ -12,6 +12,7 @@ export const PROJECT_FILENAME = "squiffy.json";
12
12
  export const PROJECT_FILE_VERSION = 1;
13
13
  // Where the project file's JSON schema is published
14
14
  export const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
15
+ export const PLAYER_SETTING_TYPES = ["toggle", "list", "range"];
15
16
  // The icons a panel's button can have. The runtime has the same list (PANEL_ICONS).
16
17
  export const PANEL_ICONS = ["bag", "person", "map", "help", "info", "list", "book", "star", "heart"];
17
18
  // The published page's text in English, which squiffy.json's "strings" can replace
@@ -21,6 +22,9 @@ export const PAGE_STRINGS = {
21
22
  restartConfirm: "Are you sure you want to restart?",
22
23
  switchToDark: "Switch to dark mode",
23
24
  switchToLight: "Switch to light mode",
25
+ // The mute button, for a story with music or sounds
26
+ mute: "Mute",
27
+ unmute: "Unmute",
24
28
  // The Saved games dialog, opened by the Save button. [name] and [time] are filled in.
25
29
  saves: "Saved games",
26
30
  saveName: "Name (optional)",
@@ -45,6 +49,9 @@ export const PAGE_STRINGS = {
45
49
  wrongStory: "This saved game is for a different story.",
46
50
  notASave: "This file isn't a saved game.",
47
51
  cantSave: "The game couldn't be saved. Try Save to file instead.",
52
+ // The Settings dialog, for a story with "settings"
53
+ settings: "Settings",
54
+ resetSettings: "Reset to defaults",
48
55
  };
49
56
  // Parses and checks a squiffy.json. An error is a sentence to show the author as is.
50
57
  export function parseProjectFile(text) {
@@ -107,6 +114,9 @@ export function parseProjectFile(text) {
107
114
  const panels = parsePanels(data.panels);
108
115
  if (typeof panels == "string")
109
116
  return fail(panels);
117
+ const settings = parseSettings(data.settings);
118
+ if (typeof settings == "string")
119
+ return fail(settings);
110
120
  const map = parseMapPositions(data.map);
111
121
  return {
112
122
  success: true,
@@ -118,6 +128,7 @@ export function parseProjectFile(text) {
118
128
  ...(saveButton !== undefined ? { saveButton } : {}),
119
129
  ...(strings !== undefined ? { strings: pickPageStrings(strings) } : {}),
120
130
  ...(panels !== undefined ? { panels } : {}),
131
+ ...(settings !== undefined ? { settings } : {}),
121
132
  },
122
133
  };
123
134
  }
@@ -159,6 +170,91 @@ function parsePanels(value) {
159
170
  }
160
171
  return panels;
161
172
  }
173
+ // squiffy.json's "settings", or an error to show the author
174
+ function parseSettings(value) {
175
+ if (value === undefined)
176
+ return undefined;
177
+ const example = "{ \"name\": \"warnings\", \"type\": \"toggle\", \"label\": \"Content warnings\" }";
178
+ if (!Array.isArray(value))
179
+ return `${PROJECT_FILENAME}'s "settings" should be a list, such as [${example}].`;
180
+ const settings = [];
181
+ const names = new Set();
182
+ for (const [i, item] of value.entries()) {
183
+ const which = `${PROJECT_FILENAME}'s setting ${i + 1}`;
184
+ if (!isObject(item))
185
+ return `${which} should be an object, such as ${example}.`;
186
+ const name = typeof item.name == "string" ? item.name.trim() : "";
187
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
188
+ return `${which} needs a "name" of letters, digits and underscores, such as "warnings", which the story reads as settings.warnings.`;
189
+ }
190
+ if (names.has(name))
191
+ return `${PROJECT_FILENAME} has more than one setting called "${name}".`;
192
+ names.add(name);
193
+ const label = typeof item.label == "string" && item.label.trim() ? item.label.trim() : name;
194
+ if (item.description !== undefined && typeof item.description != "string") {
195
+ return `${which}'s "description" should be text.`;
196
+ }
197
+ const base = {
198
+ name, label,
199
+ ...(typeof item.description == "string" && item.description.trim() ? { description: item.description.trim() } : {}),
200
+ };
201
+ const type = item.type ?? "toggle";
202
+ if (type == "toggle") {
203
+ if (item.default !== undefined && typeof item.default != "boolean") {
204
+ return `${which}'s "default" should be true or false.`;
205
+ }
206
+ settings.push({ ...base, type: "toggle", ...(item.default !== undefined ? { default: item.default } : {}) });
207
+ }
208
+ else if (type == "list") {
209
+ const options = Array.isArray(item.options) ? item.options.map(parseSettingOption) : null;
210
+ if (!options || !options.length || options.some(option => !option)) {
211
+ return `${which} needs "options" for the player to choose from, such as ["Small", "Medium", "Large"], or objects with a "value" and a "label".`;
212
+ }
213
+ const values = options.map(option => option.value);
214
+ if (new Set(values).size != values.length)
215
+ return `${which} has the same option more than once.`;
216
+ if (item.default !== undefined && !values.includes(item.default)) {
217
+ return `${which}'s "default" should be one of its options' values.`;
218
+ }
219
+ settings.push({
220
+ ...base, type: "list", options: options,
221
+ ...(item.default !== undefined ? { default: item.default } : {}),
222
+ });
223
+ }
224
+ else if (type == "range") {
225
+ const isNumber = (n) => typeof n == "number" && Number.isFinite(n);
226
+ if (!isNumber(item.min) || !isNumber(item.max) || item.min > item.max) {
227
+ return `${which} needs a "min" and a "max", such as "min": 1, "max": 5.`;
228
+ }
229
+ if (item.step !== undefined && (!isNumber(item.step) || item.step <= 0)) {
230
+ return `${which}'s "step" should be a number above 0.`;
231
+ }
232
+ if (item.default !== undefined && (!isNumber(item.default) || item.default < item.min || item.default > item.max)) {
233
+ return `${which}'s "default" should be a number from its "min" to its "max".`;
234
+ }
235
+ settings.push({
236
+ ...base, type: "range", min: item.min, max: item.max,
237
+ ...(item.step !== undefined ? { step: item.step } : {}),
238
+ ...(item.default !== undefined ? { default: item.default } : {}),
239
+ });
240
+ }
241
+ else {
242
+ return `${which}'s "type" should be ${PLAYER_SETTING_TYPES.map(t => `"${t}"`).join(", ")}.`;
243
+ }
244
+ }
245
+ return settings;
246
+ }
247
+ // A list setting's option: text, which is both its value and its label, or { value, label }
248
+ function parseSettingOption(option) {
249
+ if (typeof option == "string" && option.trim())
250
+ return { value: option.trim(), label: option.trim() };
251
+ if (typeof option == "number" || typeof option == "boolean")
252
+ return { value: String(option), label: String(option) };
253
+ if (!isObject(option) || typeof option.value != "string" || !option.value.trim())
254
+ return null;
255
+ const label = typeof option.label == "string" && option.label.trim() ? option.label.trim() : option.value.trim();
256
+ return { value: option.value.trim(), label };
257
+ }
162
258
  const EXAMPLE_ID = "0b7c6d9e-3f1a-4e2b-9c5d-8a7f6e5d4c3b";
163
259
  const isPosition = (value) => Array.isArray(value) && value.length == 2 && value.every(n => typeof n == "number" && Number.isFinite(n));
164
260
  const isObject = (value) => !!value && typeof value == "object" && !Array.isArray(value);
@@ -318,6 +414,8 @@ export function formatProjectFile(project) {
318
414
  json.exclude = project.exclude;
319
415
  if (project.panels?.length)
320
416
  json.panels = project.panels;
417
+ if (project.settings?.length)
418
+ json.settings = project.settings;
321
419
  const text = JSON.stringify(json, null, 2) + "\n";
322
420
  return project.map ? updateProjectFile(text, { map: project.map }) : text;
323
421
  }
@@ -22,6 +22,18 @@ function stringAttribute(o, name) {
22
22
  const value = o.attributes.get(name);
23
23
  return value?.type == "string" ? value.value : "";
24
24
  }
25
+ // Whether a script calls a function or command, such as "play sound", anywhere in it
26
+ function calls(statements, fn) {
27
+ return statements.some(s => {
28
+ switch (s.k) {
29
+ case "call": return s.fn == fn || calls(s.callback ?? [], fn);
30
+ case "if": return s.branches.some(b => calls(b.body, fn)) || calls(s.otherwise ?? [], fn);
31
+ case "firsttime": return calls(s.body, fn) || calls(s.otherwise ?? [], fn);
32
+ case "switch": return s.cases.some(c => calls(c.body, fn)) || calls(s.otherwise ?? [], fn);
33
+ default: return false;
34
+ }
35
+ });
36
+ }
25
37
  function booleanValue(value) {
26
38
  return value?.type == "boolean" ? value.value : undefined;
27
39
  }
@@ -81,9 +93,23 @@ function convertGame(game, options) {
81
93
  return { section: sectionNames.get(p.name) };
82
94
  };
83
95
  // Quest keeps flags and counters as attributes of the game. Most can keep their names.
96
+ const attributeNames = new Map();
97
+ const usedAttributeNames = new Set();
84
98
  const attribute = (questName) => {
85
99
  const trimmed = questName.trim();
86
- return reservedAttributes.has(trimmed) ? trimmed + "_" : trimmed;
100
+ let name = attributeNames.get(trimmed);
101
+ if (name !== undefined)
102
+ return name;
103
+ name = squiffyAttributeName(trimmed);
104
+ // Two Quest names that become the same Squiffy name are kept apart
105
+ if (name != trimmed) {
106
+ const base = name;
107
+ for (let i = 2; usedAttributeNames.has(name); i++)
108
+ name = `${base}_${i}`;
109
+ }
110
+ attributeNames.set(trimmed, name);
111
+ usedAttributeNames.add(name);
112
+ return name;
87
113
  };
88
114
  const startPage = (game.start && sectionNames.has(game.start) ? game.start : undefined) ?? storyPages[0]?.name;
89
115
  const title = game.game.name.replace(/\s+/g, " ").trim();
@@ -151,7 +177,19 @@ function convertGame(game, options) {
151
177
  newFirstTime: () => `firsttime_${++firstTimes}`,
152
178
  noteStyle: () => { styled = true; },
153
179
  });
154
- let hasSound = false;
180
+ // Quest stops every sound when the player goes to another page, unless the last page with a
181
+ // sound was set to continue playing it (game.continuesound). That's done at the start of each
182
+ // page, or in the master section if the script that runs on every page plays a sound, as
183
+ // Quest stops sounds before running it.
184
+ const pageSound = (p) => scriptOnlyPages.has(p.name) ? "" : stringAttribute(p, "sound").trim();
185
+ const playsSound = storyPages.some(p => pageSound(p))
186
+ || [...pageScripts.values(), roomEnter ?? []].some(statements => calls(statements, "play sound"));
187
+ const continuesSound = storyPages.some(p => pageSound(p) && booleanValue(p.attributes.get("continuesound")));
188
+ const continueAttribute = attribute("continuesound");
189
+ const stopSounds = !playsSound ? { directives: [], lines: [] }
190
+ : continuesSound ? { directives: [], lines: [`{{#unless ${attributeRef(continueAttribute)}}}{{stopsounds}}{{stopmusic}}{{/unless}}`] }
191
+ : { directives: ["@sound stop", "@music stop"], lines: [] };
192
+ const stopInMaster = !!roomEnter && calls(roomEnter, "play sound");
155
193
  const sections = [];
156
194
  for (const page of storyPages) {
157
195
  const section = sectionNames.get(page.name);
@@ -180,8 +218,8 @@ function convertGame(game, options) {
180
218
  assets.add(file);
181
219
  },
182
220
  };
183
- const lines = [];
184
- const directives = [];
221
+ const lines = stopInMaster ? [] : [...stopSounds.lines];
222
+ const directives = stopInMaster ? [] : [...stopSounds.directives];
185
223
  if (page.name == startPage) {
186
224
  const initial = [...dynamicLinks.values()].filter(l => l.initial !== undefined);
187
225
  const parts = [];
@@ -198,7 +236,7 @@ function convertGame(game, options) {
198
236
  // Quest shows the title once, when the game starts, and many gamebooks go back to
199
237
  // their first page to play again
200
238
  if (initial.length || parts.length) {
201
- lines.push(`{{#if (visits ${quote(section)}) = 1}}`, ...initial.map(l => `{{set ${quote(l.attribute)} ${print(linkValue(l, l.initial))}}}`), ...parts, "{{/if}}");
239
+ lines.push("{{#once}}", ...initial.map(l => `{{set ${quote(l.attribute)} ${print(linkValue(l, l.initial))}}}`), ...parts, "{{/once}}");
202
240
  }
203
241
  }
204
242
  const scriptOnly = scriptOnlyPages.has(page.name);
@@ -266,11 +304,17 @@ function convertGame(game, options) {
266
304
  if (youtube) {
267
305
  lines.push(`<iframe class="quest-youtube" width="560" height="315" src="https://www.youtube.com/embed/${encodeURIComponent(youtube)}" allowfullscreen></iframe>`, "");
268
306
  }
269
- const sound = stringAttribute(page, "sound").trim();
307
+ const sound = pageSound(page);
270
308
  if (sound) {
271
309
  ctx.asset(sound);
272
- hasSound = true;
273
- lines.push(`<audio src="${escapeAttribute(sound)}" autoplay></audio>`);
310
+ if (continuesSound) {
311
+ // After the sounds are stopped at the start of the page, which is in its text
312
+ const continues = booleanValue(page.attributes.get("continuesound")) ?? false;
313
+ lines.push(`{{sound ${quote(sound)}}}{{set ${quote(continueAttribute)} ${continues}}}`);
314
+ }
315
+ else {
316
+ directives.push(`@sound ${sound}`);
317
+ }
274
318
  }
275
319
  lines.push(convertQuestText(stringAttribute(page, "description"), ctx, "block"));
276
320
  const links = pageLinks();
@@ -299,6 +343,8 @@ function convertGame(game, options) {
299
343
  const master = [];
300
344
  if (clearLastPage)
301
345
  master.push("@clear");
346
+ if (stopInMaster)
347
+ master.push(...stopSounds.directives, ...stopSounds.lines);
302
348
  if (roomEnter) {
303
349
  const ctx = {
304
350
  section: "",
@@ -330,9 +376,6 @@ function convertGame(game, options) {
330
376
  addProblem({ text: setting, reason: `The game's "${setting}" script can't be converted yet: ${oneLine(value.value)}` });
331
377
  }
332
378
  }
333
- if (hasSound) {
334
- addProblem({ text: "sound", reason: "Each page's sound plays to the end. In Quest, it stopped when the player went to another page, unless the page was set to continue playing it." });
335
- }
336
379
  for (const file of game.javascript) {
337
380
  addProblem({ text: file, reason: "The game's JavaScript was written for Quest, so it isn't part of the story." });
338
381
  }
@@ -473,3 +516,16 @@ export function formatQuestProblems(result, sourceName) {
473
516
  }
474
517
  return lines.join("\n") + "\n";
475
518
  }
519
+ // A Squiffy attribute name for a Quest flag, counter or attribute name. A name that isn't one
520
+ // word is written [like this] in an expression, which can't have a comma (that makes it a list,
521
+ // [a, b]), a square or curly bracket, a quote or a backslash in it, or start with a digit, a - or
522
+ // a (. A dot would make it a path to a value inside an object. Quest lets a flag be called
523
+ // anything, so those are changed to _.
524
+ function squiffyAttributeName(name) {
525
+ if (reservedAttributes.has(name))
526
+ return name + "_";
527
+ let result = name.replace(/[,.[\]{}"'`\\]/g, "_");
528
+ if (/^[\d(-]/.test(result))
529
+ result = "_" + result;
530
+ return result;
531
+ }
@@ -70,19 +70,19 @@ class Converter {
70
70
  return lines;
71
71
  }
72
72
  case "firsttime": {
73
- // At the top of a page's script, it's the first time the page is shown. Anywhere
74
- // else, an attribute remembers whether it's run.
73
+ // {{#once}} remembers by where it is in the text. At the top of a page's script,
74
+ // that's the page. Anywhere else, the script may be shown from several places
75
+ // (a function, say), so it has a name to remember by.
75
76
  const lines = [];
76
77
  if (topLevel && this.ctx.page !== undefined && !this.ctx.inCallback) {
77
- lines.push(`{{#if (visits ${quote(this.ctx.section)}) = 1}}`, ...this.statements(s.body, false));
78
+ lines.push("{{#once}}", ...this.statements(s.body, false));
78
79
  }
79
80
  else {
80
- const attribute = this.ctx.newFirstTime();
81
- lines.push(`{{#unless ${attribute}}}`, `{{set ${quote(attribute)} true}}`, ...this.statements(s.body, false));
81
+ lines.push(`{{#once ${quote(this.ctx.newFirstTime())}}}`, ...this.statements(s.body, false));
82
82
  }
83
83
  if (s.otherwise)
84
84
  lines.push("{{else}}", ...this.statements(s.otherwise, false));
85
- lines.push(topLevel && this.ctx.page !== undefined && !this.ctx.inCallback ? "{{/if}}" : "{{/unless}}");
85
+ lines.push("{{/once}}");
86
86
  return lines;
87
87
  }
88
88
  case "switch": {
@@ -247,11 +247,15 @@ class Converter {
247
247
  return [];
248
248
  const file = this.text(args[0], "a sound");
249
249
  ctx.asset(file);
250
- const loop = args[2]?.k == "bool" && args[2].v ? " loop" : "";
251
- return [`<audio src="${escapeAttribute(file)}" autoplay${loop}></audio>`];
250
+ // A sound that loops is music. The story stops it, and any sounds, at the next page,
251
+ // as Quest did.
252
+ if (args[2]?.k == "bool" && args[2].v)
253
+ return [`{{music ${quote(file)}}}`];
254
+ return [`{{sound ${quote(file)}}}`];
252
255
  }
253
256
  case "stop sound":
254
- throw new Unconvertible("Squiffy can't stop a sound");
257
+ // Quest stops every sound, including one that loops, which is music here
258
+ return ["{{stopsounds}}{{stopmusic}}"];
255
259
  case "ShowYouTube":
256
260
  return this.show([`<iframe class="quest-youtube" width="560" height="315" src="https://www.youtube.com/embed/${encodeURIComponent(this.text(args[0], "a video"))}" allowfullscreen></iframe>`]);
257
261
  case "DisplayHttpLink": {