squiffy-compiler 7.0.0-beta.5 → 7.0.0-beta.7

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 (47) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +6 -0
  3. package/dist/analyse.js +101 -11
  4. package/dist/compiler.d.ts +9 -2
  5. package/dist/compiler.js +5 -2
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +13 -0
  9. package/dist/emit.js +45 -1
  10. package/dist/language-service.d.ts +1 -0
  11. package/dist/language-service.js +39 -13
  12. package/dist/node.d.ts +7 -1
  13. package/dist/node.js +16 -5
  14. package/dist/parse.d.ts +3 -0
  15. package/dist/parse.js +25 -2
  16. package/dist/project.d.ts +56 -0
  17. package/dist/project.js +148 -15
  18. package/dist/quest/aslx.d.ts +50 -0
  19. package/dist/quest/aslx.js +181 -0
  20. package/dist/quest/convert.d.ts +20 -0
  21. package/dist/quest/convert.js +504 -0
  22. package/dist/quest/script.d.ts +92 -0
  23. package/dist/quest/script.js +453 -0
  24. package/dist/quest/scripts.d.ts +24 -0
  25. package/dist/quest/scripts.js +505 -0
  26. package/dist/quest/text.d.ts +17 -0
  27. package/dist/quest/text.js +305 -0
  28. package/dist/setters.d.ts +4 -0
  29. package/dist/setters.js +10 -5
  30. package/dist/story-graph.d.ts +2 -1
  31. package/dist/story-graph.js +2 -0
  32. package/dist/syntax.d.ts +27 -2
  33. package/dist/text.d.ts +2 -0
  34. package/dist/text.js +24 -15
  35. package/dist/twine/audio.d.ts +21 -0
  36. package/dist/twine/audio.js +80 -0
  37. package/dist/twine/convert.d.ts +15 -1
  38. package/dist/twine/convert.js +217 -21
  39. package/dist/twine/expression.d.ts +26 -1
  40. package/dist/twine/expression.js +111 -6
  41. package/dist/twine/harlowe.d.ts +10 -0
  42. package/dist/twine/harlowe.js +417 -58
  43. package/dist/twine/sugarcube.d.ts +4 -0
  44. package/dist/twine/sugarcube.js +388 -86
  45. package/dist/v5.js +2 -1
  46. package/package.json +3 -2
  47. package/syntaxes/squiffy.tmLanguage.json +9 -4
@@ -0,0 +1,80 @@
1
+ // Converts Twine's sound to Squiffy's music and sound helpers (#444). Squiffy has two kinds of
2
+ // sound: music, which loops and carries on from one section to the next until it's changed, and
3
+ // sounds, which play once. A Twine track that's set to loop anywhere in the story is music, and
4
+ // any other is a sound.
5
+ import { quote, Unconvertible } from "./expression.js";
6
+ // The file a track plays: the one the story gives it, or the track name itself if that looks
7
+ // like a file, such as "rain.mp3"
8
+ export function trackFile(audio, track) {
9
+ const file = audio.files.get(track);
10
+ if (file !== undefined)
11
+ return file;
12
+ if (/\.\w{2,4}$/.test(track))
13
+ return track;
14
+ throw new Unconvertible(`a track ("${track}") that the story doesn't give a file for`);
15
+ }
16
+ // The best of a track's sources: MP3 plays in every browser
17
+ export function pickSource(sources) {
18
+ return sources.find(s => /\.mp3(\?|#|$)/i.test(s)) ?? sources[0];
19
+ }
20
+ // What a track does, as Squiffy: {{music}}, {{stopmusic}}, {{sound}}, {{stopsounds}}, or nothing
21
+ export function audioHelper(ctx, raw, audio, track, action) {
22
+ const looping = action.loop || audio.looping.has(track);
23
+ const fade = action.fade === undefined ? "" : ` fade=${action.fade}`;
24
+ if (action.stop) {
25
+ if (looping)
26
+ return `{{stopmusic${fade}}}`;
27
+ // Squiffy stops every sound playing once, which is the same thing if there's only one
28
+ const sounds = new Set([...audio.files.keys()].filter(t => !audio.looping.has(t)));
29
+ sounds.add(track);
30
+ if (sounds.size > 1) {
31
+ ctx.story.note("audio-stop-sound", raw, "Squiffy stops every sound that's playing once, not just one track, so these stop the others too");
32
+ }
33
+ return "{{stopsounds}}";
34
+ }
35
+ if (!action.play)
36
+ return "";
37
+ const file = quote(trackFile(audio, track));
38
+ if (looping) {
39
+ if (action.volume !== undefined && action.volume != 1) {
40
+ ctx.story.note("audio-music-volume", raw, "Squiffy plays music at full volume, so the music's volume has been left out");
41
+ }
42
+ return `{{music ${file}${fade}}}`;
43
+ }
44
+ const volume = action.volume !== undefined && action.volume != 1 ? ` volume=${Math.max(0, Math.min(1, action.volume))}` : "";
45
+ return `{{sound ${file}${volume}}}`;
46
+ }
47
+ // Stops every sound and the music, as <<masteraudio stop>> and (masteraudio: "stopall") do
48
+ export const STOP_ALL_AUDIO = "{{stopsounds}}{{stopmusic}}";
49
+ // A helper that can be a directive, @music or @sound, for the start of a passage, or null
50
+ export function audioDirective(helper) {
51
+ if (helper == "{{stopmusic}}")
52
+ return "@music stop";
53
+ if (helper == "{{stopsounds}}")
54
+ return "@sound stop";
55
+ const m = /^\{\{(music|sound) "([^"&{}]+)"\}\}$/.exec(helper);
56
+ if (!m || m[2].trim() != m[2] || m[2] == "stop")
57
+ return null;
58
+ return `@${m[1]} ${m[2]}`;
59
+ }
60
+ // Audio helpers as directives where they can be, at the start of a passage
61
+ export function leadingAudio(out, state) {
62
+ if (!state.leading)
63
+ return out;
64
+ const helpers = out.match(/\{\{[^{}]*\}\}/g) ?? [];
65
+ const directives = helpers.map(audioDirective);
66
+ if (helpers.join("") != out || directives.some(d => d === null)) {
67
+ state.leading = false;
68
+ return out;
69
+ }
70
+ for (const directive of directives) {
71
+ // Only the last @music counts, as in Harlowe stopping one track and playing another
72
+ if (directive.startsWith("@music ")) {
73
+ const earlier = state.directives.findIndex(d => d.startsWith("@music "));
74
+ if (earlier != -1)
75
+ state.directives.splice(earlier, 1);
76
+ }
77
+ state.directives.push(directive);
78
+ }
79
+ return "";
80
+ }
@@ -28,12 +28,14 @@ export interface PassageContext {
28
28
  fill: (content: ConvertedPassage | string) => void;
29
29
  };
30
30
  addSection(nameHint: string, content: ConvertedPassage | string): string;
31
+ fillSection(name: string, content: ConvertedPassage | string): void;
31
32
  newLabel(hint: string): string;
32
33
  }
33
34
  export interface ConvertedPassage {
34
35
  directives: string[];
35
36
  body: string;
36
37
  }
38
+ export declare const reservedAttributes: Set<string>;
37
39
  export declare class StoryContext {
38
40
  readonly twine: TwineStory;
39
41
  readonly problems: TwineConversionProblem[];
@@ -58,7 +60,16 @@ export declare class StoryContext {
58
60
  sectionForUnknown(passageName: string): string;
59
61
  uniqueSectionName(hint: string): string;
60
62
  newLabel(hint: string): string;
63
+ private readonly loops;
64
+ inLoop<T>(vars: Map<string, "item" | "index">, array: string | undefined, convert: () => T, numbers?: boolean): T;
65
+ linkBody<T>(convert: () => T): {
66
+ result: T;
67
+ setters: string[];
68
+ };
69
+ private loopVariable;
70
+ variable(name: string, temporary: boolean): Expr;
61
71
  attribute(name: string, temporary: boolean): string;
72
+ private attributeName;
62
73
  }
63
74
  export declare function sanitiseName(name: string): string;
64
75
  export declare function escapeText(text: string): string;
@@ -66,10 +77,13 @@ export declare function sectionLink(text: string | null, target: string, setters
66
77
  export declare function isUrl(target: string): boolean;
67
78
  export declare function urlLink(text: string, url: string): string;
68
79
  export declare function dynamicSectionLink(text: string, target: Expr, setters?: string[]): string;
69
- export declare function passageLink(text: string, target: string): string;
80
+ export declare function passageLink(text: string, target: string, setters?: string[]): string;
70
81
  export declare function setter(name: string, op: "=" | "+=" | "-=" | "*=" | "/=", value: Expr, inLink: boolean): string;
71
82
  export declare function comment(text: string): string;
72
83
  export declare function formatTwineProblems(result: TwineConversionResult, sourceName?: string): string;
73
84
  export declare function convertTwine(source: string, options?: TwineConversionOptions): TwineConversionResult;
74
85
  export declare function convertTwineStory(twine: TwineStory, options?: TwineConversionOptions): TwineConversionResult;
86
+ export declare function tagClasses(tags: string[]): string[];
87
+ export declare function convertTagSelectors(css: string): string;
88
+ export declare function usesOuterLoop(text: string): boolean;
75
89
  export declare function finishText(text: string): string;
@@ -4,17 +4,21 @@
4
4
  // editor write the files it returns. Anything that can't be converted is kept as a comment in
5
5
  // the story and listed as a problem, so the author can deal with it by hand.
6
6
  import { attributeRef, print, quote, Unconvertible } from "./expression.js";
7
- import { convertHarlowePassage } from "./harlowe.js";
7
+ import { convertHarlowePassage, harloweAudioPassages, harloweMacros } from "./harlowe.js";
8
8
  import { convertSugarCubePassage, convertSugarCubeWidgets, sugarCubeWidgets } from "./sugarcube.js";
9
9
  import { parseTwine } from "./story.js";
10
10
  import { formatProjectFile } from "../project.js";
11
11
  // The Squiffy names that would be read as a helper, rather than an attribute, in {{name}} and
12
12
  // expressions, and the ones Squiffy sets itself
13
- const reservedAttributes = new Set([
13
+ export const reservedAttributes = new Set([
14
14
  "get", "set", "unset", "inc", "dec", "seen", "visits", "at", "goto", "embed", "array", "random", "contains",
15
15
  "length", "append", "prepend", "pop", "remove", "section", "passage", "label", "replace", "rotate", "sequence",
16
16
  "live", "animate", "eq", "ne", "gt", "gte", "lt", "lte", "and", "or", "not", "add", "sub", "mul", "div", "mod",
17
- "if", "unless", "each", "with", "lookup", "log", "else", "this", "turns", "true", "false", "null", "undefined",
17
+ "round", "floor", "ceil", "abs", "min", "max", "upper", "lower", "capitalise", "capitalize", "cond",
18
+ "join", "sort", "shuffle", "slice", "first", "last", "indexof", "count", "range",
19
+ "if", "unless", "each", "with", "lookup", "log", "else", "this", "turns", "previous", "previous_section",
20
+ "true", "false", "null", "undefined", "music", "stopmusic", "sound", "stopsounds",
21
+ "addclass", "removeclass", "toggleclass", "hasclass", "content",
18
22
  ]);
19
23
  export class StoryContext {
20
24
  constructor(twine, passages) {
@@ -94,6 +98,15 @@ export class StoryContext {
94
98
  writable: true,
95
99
  value: new Map()
96
100
  });
101
+ // The loops being converted to {{#each}}, innermost last, with the Twine variables (with their
102
+ // $ or _) that stand for each one's item and position. numbers: its items are numbers, as in
103
+ // a loop that counts. A link's body (see linkBody) is an entry with setters, and no variables.
104
+ Object.defineProperty(this, "loops", {
105
+ enumerable: true,
106
+ configurable: true,
107
+ writable: true,
108
+ value: []
109
+ });
97
110
  for (const p of passages) {
98
111
  this.passagesByName.set(p.name, p);
99
112
  }
@@ -185,9 +198,68 @@ export class StoryContext {
185
198
  this.usedLabels.add(name);
186
199
  return name;
187
200
  }
201
+ inLoop(vars, array, convert, numbers = false) {
202
+ this.loops.push({ vars, array, numbers });
203
+ try {
204
+ return convert();
205
+ }
206
+ finally {
207
+ this.loops.pop();
208
+ }
209
+ }
210
+ // Converts the body of a link, which runs when it's clicked, after its loop has finished. In
211
+ // there, the loop's item and position are attributes, which the link sets to that item's (#448).
212
+ // Returns the setters for the link.
213
+ linkBody(convert) {
214
+ if (!this.loops.length || this.loops[this.loops.length - 1].setters)
215
+ return { result: convert(), setters: [] };
216
+ const setters = new Map();
217
+ this.loops.push({ vars: new Map(), setters });
218
+ try {
219
+ return { result: convert(), setters: [...setters.values()] };
220
+ }
221
+ finally {
222
+ this.loops.pop();
223
+ }
224
+ }
225
+ loopVariable(name, temporary) {
226
+ const key = (temporary ? "_" : "$") + name;
227
+ for (let i = this.loops.length - 1; i >= 0; i--) {
228
+ const loop = this.loops[i];
229
+ if (loop.setters) {
230
+ // In a link's body: the variables of the link's own loop are attributes now
231
+ const own = this.loops[i - 1];
232
+ const kind = own.vars.get(key);
233
+ if (kind) {
234
+ const attribute = this.attributeName(name, temporary);
235
+ // Like a link's other setters, an item is text, unless the loop counts
236
+ const value = kind == "index" ? "{{@index}}" : own.numbers ? "{{this}}" : "'{{this}}'";
237
+ loop.setters.set(attribute, `${attribute} = ${value}`);
238
+ return { k: "var", name: attribute };
239
+ }
240
+ if (this.loops.slice(0, i - 1).some(l => l.vars.has(key))) {
241
+ throw new Unconvertible("a link in a loop inside another loop that uses the outer loop's item");
242
+ }
243
+ return undefined;
244
+ }
245
+ const kind = loop.vars.get(key);
246
+ if (kind)
247
+ return { k: "loop", kind, up: this.loops.length - 1 - i, array: loop.array, numbers: loop.numbers };
248
+ }
249
+ return undefined;
250
+ }
251
+ // A Twine variable's value: its attribute, or inside a loop, the loop's item or position
252
+ variable(name, temporary) {
253
+ return this.loopVariable(name, temporary) ?? { k: "var", name: this.attribute(name, temporary) };
254
+ }
188
255
  // The Squiffy attribute for a Twine variable, given without its $ or _: a temporary (_)
189
256
  // variable keeps its name unless a story variable ($) has the same name
190
257
  attribute(name, temporary) {
258
+ if (this.loopVariable(name, temporary))
259
+ throw new Unconvertible("changing a loop's variable inside the loop");
260
+ return this.attributeName(name, temporary);
261
+ }
262
+ attributeName(name, temporary) {
191
263
  let result = name;
192
264
  if (temporary && this.permanentVars.has(name))
193
265
  result = "temp_" + name;
@@ -252,16 +324,19 @@ export function urlLink(text, url) {
252
324
  }
253
325
  // A link to a section whose name is worked out as the story runs
254
326
  export function dynamicSectionLink(text, target, setters = []) {
327
+ // quote() would break the {{this}} of a loop's item
328
+ if (setters.some(s => s.includes("{{")))
329
+ throw new Unconvertible("a link in a loop, to a passage worked out as the story runs, that sets a variable to the loop's item");
255
330
  const set = setters.length ? ` set=${quote(setters.join(", "))}` : "";
256
331
  return `{{section ${print(target)} text=${quote(text)}${set}}}`;
257
332
  }
258
- export function passageLink(text, target) {
333
+ export function passageLink(text, target, setters = []) {
259
334
  const linkText = text.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;");
260
- return `[${linkText}](${target})`;
335
+ return `[${linkText}](${[target, ...setters].join(", ")})`;
261
336
  }
262
337
  // A Squiffy setter, as in @set or a link, for name = value
263
338
  export function setter(name, op, value, inLink) {
264
- return `${attributeRef(name)} ${op} ${print(value, { preferSingle: inLink })}`;
339
+ return `${attributeRef(name)} ${op} ${print(value, { preferSingle: inLink, inLink })}`;
265
340
  }
266
341
  // A comment in the story, for Twine code that couldn't be converted. Handlebars comments can't
267
342
  // contain --}}, and line breaks would let the compiler read a line of it as something else.
@@ -269,8 +344,11 @@ export function comment(text) {
269
344
  const clean = text.replace(/--\}\}/g, "-- }}").replace(/\s*\n\s*/g, " ").trim();
270
345
  return `{{!-- Twine: ${clean} --}}`;
271
346
  }
347
+ // SugarCube's passages for its sidebar that become panels beside the story (#443), in the order
348
+ // SugarCube shows them, with the labels of the buttons they have on a narrow screen
349
+ const sugarCubePanels = { StoryBanner: "Banner", StoryCaption: "Status" };
272
350
  // Passages a format treats specially, which aren't part of the story as sections
273
- // (StoryCaption, StoryBanner and so on are kept, as their text might be included elsewhere)
351
+ // (StorySubtitle, StoryAuthor and so on are kept, as their text might be included elsewhere)
274
352
  const sugarCubeSpecial = new Set(["StoryMenu", "StoryInterface", "StoryShare", "StoryTitle", "StoryData", "StorySettings"]);
275
353
  // The problems as a text file, to keep with the converted story: the ones about the whole story,
276
354
  // then each passage's, in the order of the story
@@ -313,6 +391,7 @@ export function convertTwineStory(twine, options = {}) {
313
391
  const startup = [];
314
392
  const widgets = [];
315
393
  const skipped = [];
394
+ const panelPassages = [];
316
395
  const storyPassages = [];
317
396
  const seenNames = new Set();
318
397
  for (const p of twine.passages) {
@@ -330,6 +409,9 @@ export function convertTwineStory(twine, options = {}) {
330
409
  startup.push(p);
331
410
  else if (p.tags.some(t => t.startsWith("debug-")))
332
411
  skipped.push(p);
412
+ // The Harlowe Audio Library's tracks and settings, which are read where they're used
413
+ else if (harloweAudioPassages.has(p.name))
414
+ continue;
333
415
  else
334
416
  storyPassages.push(p);
335
417
  }
@@ -344,9 +426,11 @@ export function convertTwineStory(twine, options = {}) {
344
426
  widgets.push(p);
345
427
  else if (sugarCubeSpecial.has(p.name))
346
428
  skipped.push(p);
429
+ else if (p.name in sugarCubePanels)
430
+ panelPassages.push(p);
347
431
  else {
348
- if (["StoryCaption", "StoryBanner", "StorySubtitle", "StoryAuthor", "StoryDisplayTitle"].includes(p.name)) {
349
- problems.push({ passage: p.name, text: p.name, reason: "Squiffy has no sidebar or banner, so this passage is an ordinary section, which nothing links to." });
432
+ if (["StorySubtitle", "StoryAuthor", "StoryDisplayTitle"].includes(p.name)) {
433
+ problems.push({ passage: p.name, text: p.name, reason: "Squiffy has no sidebar, so this passage is an ordinary section, which nothing links to." });
350
434
  }
351
435
  storyPassages.push(p);
352
436
  }
@@ -363,10 +447,15 @@ export function convertTwineStory(twine, options = {}) {
363
447
  // Widgets become sections, which calls to them embed. They're named before anything's
364
448
  // converted, so calls know where they go.
365
449
  sugarCubeWidgets(story);
450
+ // Harlowe's custom macros (#450) too
451
+ if (harlowe)
452
+ harloweMacros(story);
366
453
  for (const p of skipped) {
367
454
  problems.push({
368
455
  passage: p.name, text: p.name,
369
- reason: p.name == "StoryMenu" ? "Squiffy has no sidebar, so this passage has been left out." : "This special passage has been left out.",
456
+ reason: p.name == "StoryMenu"
457
+ ? "Squiffy has no sidebar, so this passage has been left out. Its links go to passages, which a panel can't do, but a panel can show a passage in the master section [[]] from a button in the header: see \"panels\" in squiffy.json."
458
+ : "This special passage has been left out.",
370
459
  });
371
460
  }
372
461
  const context = (passage, section, extraPassages) => ({
@@ -392,13 +481,23 @@ export function convertTwineStory(twine, options = {}) {
392
481
  name = `${base} ${n}`;
393
482
  const index = extraPassages.length;
394
483
  extraPassages.push(`[${name}]:\n`);
395
- return { name, fill: content => extraPassages[index] = `[${name}]:\n${block(content)}` };
484
+ return {
485
+ name,
486
+ fill: content => {
487
+ // Left out, rather than empty, if it can't be converted
488
+ extraPassages[index] = "";
489
+ extraPassages[index] = `[${name}]:\n${generated(content)}`;
490
+ },
491
+ };
396
492
  },
397
493
  addSection(hint, content) {
398
494
  const name = story.uniqueSectionName(hint);
399
- story.extraSections.push(`[[${name}]]:\n${block(content)}`);
495
+ this.fillSection(name, content);
400
496
  return name;
401
497
  },
498
+ fillSection(name, content) {
499
+ story.extraSections.push(`[[${name}]]:\n${generated(content)}`);
500
+ },
402
501
  newLabel: hint => story.newLabel(hint),
403
502
  });
404
503
  const convert = (passage, section, extraPassages) => {
@@ -423,6 +522,24 @@ export function convertTwineStory(twine, options = {}) {
423
522
  if (converted.body.trim())
424
523
  master.body += converted.body.trim() + "\n";
425
524
  }
525
+ // SugarCube's sidebar passages, as panels beside the story, rendered again after each passage
526
+ sortPanelPassages(panelPassages);
527
+ const panels = [];
528
+ for (const p of panelPassages) {
529
+ const converted = convert(p, "", masterPassages);
530
+ let passageName = p.name;
531
+ for (let n = 2; masterPassages.some(text => text.startsWith(`[${passageName}]:\n`)); n++)
532
+ passageName = `${p.name} ${n}`;
533
+ const body = converted.body.trim();
534
+ if (converted.directives.length) {
535
+ story.addProblem({ passage: p.name, text: converted.directives.join(" "), reason: "A panel only shows its text, so this doesn't run." });
536
+ }
537
+ if (/\[\[|\]\(|\{\{(section|passage)\b/.test(body)) {
538
+ story.addProblem({ passage: p.name, text: p.name, reason: "This is a panel beside the story, where links don't work." });
539
+ }
540
+ masterPassages.push(`[${passageName}]:\n${finishText(body)}`.trimEnd());
541
+ panels.push({ passage: passageName, label: sugarCubePanels[p.name], position: "side" });
542
+ }
426
543
  // Passages that run once at the start
427
544
  const init = { directives: [], body: "" };
428
545
  for (const p of startup) {
@@ -438,6 +555,10 @@ export function convertTwineStory(twine, options = {}) {
438
555
  const extraPassages = [];
439
556
  const converted = convert(p, section, extraPassages);
440
557
  const directives = [...converted.directives];
558
+ // Its tags (#449), which Twine puts on the page for the stylesheet
559
+ const classes = footers.includes(p) ? [] : tagClasses(p.tags);
560
+ if (classes.length)
561
+ directives.push(`@class ${classes.join(" ")}`);
441
562
  let body = converted.body.trim();
442
563
  if (p.name == startPassage && (init.directives.length || init.body)) {
443
564
  directives.unshift(...init.directives);
@@ -446,7 +567,7 @@ export function convertTwineStory(twine, options = {}) {
446
567
  if (!footers.includes(p) && footerEmbeds.length) {
447
568
  body = (body + "\n" + footerEmbeds.join("\n")).trim();
448
569
  }
449
- sections.push([`[[${section}]]:\n${block({ directives, body })}`.trimEnd(), ...extraPassages].join("\n\n"));
570
+ sections.push([`[[${section}]]:\n${block({ directives, body })}`.trimEnd(), ...extraPassages.filter(p => p)].join("\n\n"));
450
571
  }
451
572
  for (const p of widgets) {
452
573
  const extraPassages = [];
@@ -461,7 +582,7 @@ export function convertTwineStory(twine, options = {}) {
461
582
  continue;
462
583
  }
463
584
  for (const w of converted) {
464
- sections.push([`[[${w.section}]]:\n${block(w.converted)}`, ...extraPassages].join("\n\n"));
585
+ sections.push([`[[${w.section}]]:\n${block(w.converted)}`, ...extraPassages.filter(p => p)].join("\n\n"));
465
586
  extraPassages.length = 0;
466
587
  }
467
588
  }
@@ -472,18 +593,25 @@ export function convertTwineStory(twine, options = {}) {
472
593
  if (startSection !== undefined)
473
594
  header.push(`@start ${startSection}`);
474
595
  if (twine.stylesheet) {
475
- files[`${name}.css`] = twine.stylesheet + "\n";
476
- header.push(`@import ${name}.css`);
596
+ // squiffy.json makes it part of the story
597
+ const stylesheet = convertTagSelectors(twine.stylesheet);
598
+ files[`${name}.css`] = stylesheet + "\n";
599
+ const tagRules = stylesheet != twine.stylesheet
600
+ ? " Its rules for passage tags now use the classes that @class puts on the story's element."
601
+ : "";
477
602
  problems.push({
478
603
  text: `${name}.css`,
479
- reason: `The story's stylesheet is in ${name}.css. Its rules for ${harlowe ? "Harlowe's elements (tw-story, tw-passage, tw-link and so on)" : "SugarCube's elements (#story, .passage, #ui-bar and so on)"} won't apply to Squiffy's, so check how it looks.`,
604
+ reason: `The story's stylesheet is in ${name}.css. Its rules for ${harlowe ? "Harlowe's elements (tw-story, tw-passage, tw-link and so on)" : "SugarCube's elements (#story, .passage, #ui-bar and so on)"} won't apply to Squiffy's, so check how it looks.${tagRules}`,
480
605
  });
481
606
  }
607
+ // The story's JavaScript is left out of it, as it was written for another story format
608
+ const exclude = [];
482
609
  if (twine.script) {
483
610
  files[`${name}.js`] = twine.script + "\n";
611
+ exclude.push(`${name}.js`);
484
612
  problems.push({
485
613
  text: `${name}.js`,
486
- reason: `The story's JavaScript is in ${name}.js, but it isn't part of the story yet, since it was written for ${twine.formatName || "Twine"}. To use it, change it to work with Squiffy, then add @ui ${name}.js at the top of ${name}.squiffy.`,
614
+ reason: `The story's JavaScript is in ${name}.js, but it isn't part of the story yet, since it was written for ${twine.formatName || "Twine"}. To use it, change it to work with Squiffy, then remove "${name}.js" from "exclude" in squiffy.json (in the editor, choose Include in story from its menu in the files list).`,
487
615
  });
488
616
  }
489
617
  const masterPassageText = masterPassages.length ? "\n\n" + masterPassages.join("\n\n") : "";
@@ -495,7 +623,7 @@ export function convertTwineStory(twine, options = {}) {
495
623
  ].filter(s => s.length).join("\n\n") + "\n";
496
624
  files[`${name}.squiffy`] = script;
497
625
  const map = mapPositions(sectionPassages, story);
498
- files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, ...(map ? { map } : {}) });
626
+ files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, exclude, panels, ...(map ? { map } : {}) });
499
627
  return {
500
628
  title: twine.title,
501
629
  format: `${twine.formatName} ${twine.formatVersion}`.trim(),
@@ -505,6 +633,11 @@ export function convertTwineStory(twine, options = {}) {
505
633
  problems: [...problems, ...story.noteProblems(), ...story.problems],
506
634
  };
507
635
  }
636
+ // SugarCube's sidebar passages in the order SugarCube shows them
637
+ function sortPanelPassages(passages) {
638
+ const order = Object.keys(sugarCubePanels);
639
+ passages.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name));
640
+ }
508
641
  // Where the sections go on the editor's story map, so it looks like the story's map in Twine.
509
642
  // Twine's boxes are 100 by 100, on a grid of 25, and usually 125 apart; the map's are short and
510
643
  // wide, up to 190 across, so the map is stretched sideways to keep them from overlapping (which
@@ -539,11 +672,74 @@ function unarranged(passages) {
539
672
  const columns = new Set(onGrid.map(([x]) => x));
540
673
  return columns.size == 10 && onGrid.length >= positions.length * 0.9;
541
674
  }
675
+ // Tags that mean something to Harlowe, SugarCube or Twine itself, rather than ones the story
676
+ // gave its passages
677
+ const SPECIAL_TAGS = new Set(["header", "footer", "startup", "widget", "nobr", "init", "stylesheet", "script"]);
678
+ // A passage's tags, which become @class (#449): Harlowe and SugarCube put them on the page
679
+ export function tagClasses(tags) {
680
+ return [...new Set(tags.filter(t => !SPECIAL_TAGS.has(t) && !t.startsWith("debug-") && !t.startsWith("Twine.")))];
681
+ }
682
+ // A class name in a CSS selector, escaped if it needs to be
683
+ function cssClass(name) {
684
+ if (/^-?[A-Za-z_][\w-]*$/.test(name))
685
+ return "." + name;
686
+ return "." + [...name].map((c, i) => {
687
+ if (/[\w-]/.test(c) && !(i == 0 && /\d/.test(c)))
688
+ return c;
689
+ if (/\d/.test(c))
690
+ return `\\${c.charCodeAt(0).toString(16)} `;
691
+ return "\\" + c;
692
+ }).join("");
693
+ }
694
+ // Rules for passage tags (#449), e.g. tw-story[tags~="dark"] in Harlowe or
695
+ // body[data-tags~="dark"] in SugarCube, become rules for the classes @class puts on the story's
696
+ // element, as do SugarCube's classes on the body (from tags, or <<addclass "body">>). In Twine,
697
+ // tw-story, html and body are the whole page, so they become body:has(.dark), and the passage
698
+ // becomes the story's element.
699
+ export function convertTagSelectors(css) {
700
+ return css
701
+ .replace(/(\b(?:tw-story|html|body)|tw-passage|\.passage|#passages|#story)?((?:\[\s*(?:data-)?tags\s*~=\s*(["']?)[^"'\]\s]+\3\s*\])+)/g, (_, element, attributes) => {
702
+ const classes = [...attributes.matchAll(/~=\s*(["']?)([^"'\]\s]+)\1/g)].map(m => cssClass(m[2])).join("");
703
+ return element && /^(?:tw-story|html|body)$/.test(element) ? `body:has(${classes})` : classes;
704
+ })
705
+ .replace(/(^|[\s,>+~(}])body((?:\.[\w-]+)+)/g, "$1body:has($2)");
706
+ }
542
707
  // The text of a section or passage: its directives, then its text
543
708
  function block(content) {
544
709
  const c = typeof content == "string" ? { directives: [], body: content } : content;
545
710
  return [...c.directives, finishText(c.body)].filter(l => l.length).join("\n");
546
711
  }
712
+ // A passage or section made for a link. It's shown on its own, after the link's loop has finished,
713
+ // so it can't use the loop's item or position: StoryContext.linkBody makes them attributes instead.
714
+ function generated(content) {
715
+ const c = typeof content == "string" ? { directives: [], body: content } : content;
716
+ // Directives are expressions, rather than text with {{...}} in it
717
+ if (c.directives.some(d => usesOuterLoop(`{{${d}}}`)) || usesOuterLoop(c.body)) {
718
+ throw new Unconvertible("a link in a loop that does more than set variables to the loop's item");
719
+ }
720
+ return block(c);
721
+ }
722
+ // Whether Squiffy text uses the item or position of a loop it isn't in
723
+ export function usesOuterLoop(text) {
724
+ let depth = 0;
725
+ // Comments keep the Twine code, which can have "this" in it
726
+ for (const tag of text.replace(/\{\{!--[\s\S]*?--\}\}/g, "").matchAll(/\{\{([\s\S]*?)\}\}/g)) {
727
+ // Text in quotes isn't a reference
728
+ const inner = tag[1].replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g, "\"\"");
729
+ if (inner.startsWith("/each")) {
730
+ depth--;
731
+ continue;
732
+ }
733
+ for (const ref of inner.matchAll(/(?<![\w$@.])((?:\.\.\/)*)this\b|@((?:\.\.\/)*)index\b/g)) {
734
+ const up = (ref[1] ?? ref[2] ?? "").length / 3;
735
+ if (up >= depth)
736
+ return true;
737
+ }
738
+ if (inner.startsWith("#each"))
739
+ depth++;
740
+ }
741
+ return false;
742
+ }
547
743
  // A name for a generated passage, from a link's text, which can have markup in it
548
744
  function sanitisePassageName(name) {
549
745
  const plain = name
@@ -562,9 +758,9 @@ function oneLine(text) {
562
758
  return line.length > 120 ? line.substring(0, 117) + "..." : line;
563
759
  }
564
760
  // Directives the compiler would read at the start of a line
565
- const directiveLine = /^@(title|import|start|set|unset|inc|dec|ui|clear|end)\b/;
761
+ const directiveLine = /^@(title|import|start|set|unset|inc|dec|ui|clear|end|class)\b/;
566
762
  // Lines that only hold helpers that write nothing
567
- const silentHelper = /\{\{(?:!--[\s\S]*?--|![^}]*|~?\s*(?:#if|#unless|else|\/if|\/unless|set|unset|inc|dec|goto|append|prepend|remove|#label|\/label|#replace|\/replace|#animate|\/animate)\b(?:[^{}]|\{\{[^{}]*\}\})*)\}\}/g;
763
+ const silentHelper = /\{\{(?:!--[\s\S]*?--|![^}]*|~?\s*(?:#if|#unless|else|\/if|\/unless|set|unset|inc|dec|goto|music|stopmusic|sound|stopsounds|addclass|removeclass|toggleclass|append|prepend|remove|#label|\/label|#replace|\/replace|#animate|\/animate)\b(?:[^{}]|\{\{[^{}]*\}\})*)\}\}/g;
568
764
  function isSilent(line) {
569
765
  return line.replace(silentHelper, "").trim() == "";
570
766
  }
@@ -1,4 +1,4 @@
1
- export type BinaryOp = "or" | "and" | "=" | "!=" | ">" | ">=" | "<" | "<=" | "+" | "-" | "*" | "/" | "%";
1
+ export type BinaryOp = "or" | "and" | "=" | "!=" | ">" | ">=" | "<" | "<=" | "contains" | "+" | "-" | "*" | "/" | "%";
2
2
  export type Expr = {
3
3
  k: "num";
4
4
  v: number;
@@ -24,6 +24,11 @@ export type Expr = {
24
24
  } | {
25
25
  k: "neg";
26
26
  e: Expr;
27
+ } | {
28
+ k: "cond";
29
+ test: Expr;
30
+ then: Expr;
31
+ otherwise: Expr;
27
32
  } | {
28
33
  k: "call";
29
34
  fn: string;
@@ -31,16 +36,36 @@ export type Expr = {
31
36
  } | {
32
37
  k: "array";
33
38
  items: Expr[];
39
+ } | {
40
+ k: "object";
41
+ entries: [string, Expr][];
42
+ } | {
43
+ k: "member";
44
+ e: Expr;
45
+ key: Expr;
46
+ } | {
47
+ k: "loop";
48
+ kind: "item" | "index";
49
+ up: number;
50
+ array?: string;
51
+ numbers?: boolean;
34
52
  };
35
53
  export declare class Unconvertible extends Error {
36
54
  }
37
55
  export interface PrintOptions {
38
56
  preferSingle?: boolean;
57
+ inLink?: boolean;
39
58
  }
40
59
  export declare function quote(text: string, options?: PrintOptions): string;
41
60
  export declare function attributeRef(name: string): string;
61
+ export declare function isDynamicTarget(name: string): boolean;
62
+ export declare function member(e: Expr, key: Expr): Expr;
63
+ export declare function targetName(e: Expr): string | null;
42
64
  export declare function print(e: Expr, options?: PrintOptions): string;
65
+ export declare function isListCall(e: Expr): boolean;
43
66
  export declare function isBoolean(e: Expr): boolean;
67
+ export declare function lengthOf(e: Expr): Expr;
68
+ export declare function conditional(values: Expr[], what: string): Expr;
44
69
  export declare function randomInteger(min: Expr, max: Expr): Expr;
45
70
  export declare function display(e: Expr): string;
46
71
  export declare class Tokens<T extends {