squiffy-compiler 7.0.0-beta.6 → 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.
package/dist/text.js CHANGED
@@ -178,6 +178,12 @@ export function transformText(text, getNextSectionName, expressions = false) {
178
178
  return `${mustaches.length - 1}`;
179
179
  });
180
180
  const restore = (s) => s.replace(/(\d+)/g, (_match, i) => mustaches[Number(i)]);
181
+ // A link once it's converted, kept out of the way of the patterns for later kinds of link, which
182
+ // would otherwise find links in its setters, such as the [1] in [[Go]](next, party[1].hp += 2)
183
+ const converted = (helper) => {
184
+ mustaches.push(helper);
185
+ return `${mustaches.length - 1}`;
186
+ };
181
187
  // A link's target, inside its (...). With expressions, a setter can have brackets in it, e.g.
182
188
  // [[Buy]](shop, gold -= (price - 1) * 2), so the target can contain balanced brackets, up to
183
189
  // three deep. Without, it ends at the first ")", as in Squiffy 6.
@@ -193,7 +199,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
193
199
  return `[[${text}]]`; // fallback
194
200
  }
195
201
  addLink({ linkType: "section", form: "next", text, target: "" }, offset, match.length, offset + 2 + rawText.length, 0);
196
- return `{{section "${escapeForHandlebarsString(nextSectionName)}" text="${escapeForHandlebarsString(text)}"}}`;
202
+ return converted(`{{section "${escapeForHandlebarsString(nextSectionName)}" text="${escapeForHandlebarsString(text)}"}}`);
197
203
  });
198
204
  // namedNextSectionLinkRegex matches [[text]](>) or [[text]](>, setter=value)
199
205
  // - a named link where target starts with >
@@ -209,7 +215,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
209
215
  addLink({ linkType: "section", form: "next", text, target: rest }, offset, match.length, offset + 2 + rawText.length + 4, rawRest.length);
210
216
  // rest could be empty or ", setter=value"
211
217
  const parsedName = getAdditionalLinkParameters(nextSectionName + rest, expressions);
212
- return `{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
218
+ return converted(`{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
213
219
  });
214
220
  // namedSectionLinkRegex matches:
215
221
  // open [[
@@ -224,7 +230,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
224
230
  const name = restore(rawName);
225
231
  addLink({ linkType: "section", form: "named", text, target: name }, offset, match.length, offset + 2 + rawText.length + 3, rawName.length);
226
232
  const parsedName = getAdditionalLinkParameters(name, expressions);
227
- return `{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
233
+ return converted(`{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
228
234
  });
229
235
  // namedPassageLinkRegex matches:
230
236
  // not preceded by ! (to avoid matching image links like ![alt](src))
@@ -240,7 +246,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
240
246
  const name = restore(rawName);
241
247
  addLink({ linkType: "passage", form: "named", text, target: name }, offset, match.length, offset + 1 + rawText.length + 2, rawName.length);
242
248
  const parsedName = getAdditionalLinkParameters(name, expressions);
243
- return `{{passage "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
249
+ return converted(`{{passage "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
244
250
  });
245
251
  // unnamedSectionLinkRegex matches:
246
252
  // open [[
@@ -250,7 +256,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
250
256
  input.replace(unnamedSectionLinkRegex, ([match, rawName], offset) => {
251
257
  const name = restore(rawName);
252
258
  addLink({ linkType: "section", form: "unnamed", target: name }, offset, match.length, offset + 2, rawName.length);
253
- return `{{section "${escapeForHandlebarsString(name)}"}}`;
259
+ return converted(`{{section "${escapeForHandlebarsString(name)}"}}`);
254
260
  });
255
261
  // unnamedPassageLinkRegex matches:
256
262
  // not preceded by ! (to avoid matching image links like ![alt])
@@ -262,13 +268,14 @@ export function transformText(text, getNextSectionName, expressions = false) {
262
268
  input.replace(unnamedPassageLinkRegex, ([match, rawName, suffix], offset) => {
263
269
  const name = restore(rawName);
264
270
  addLink({ linkType: "passage", form: "unnamed", target: name }, offset, match.length - suffix.length, offset + 1, rawName.length);
265
- return `{{passage "${escapeForHandlebarsString(name)}"}}${suffix}`;
271
+ return converted(`{{passage "${escapeForHandlebarsString(name)}"}}`) + suffix;
266
272
  });
267
273
  input.replace(/(\d+)/g, ([, i]) => mustaches[Number(i)]);
268
- // Matches {{embed "name"}} or {{goto 'name'}} with a literal name.
269
- const findNamed = (helper) => {
274
+ // Matches {{embed "name"}} or {{goto 'name'}} with a literal name. An embed can also be a
275
+ // block, {{#embed "name"}}...{{/embed}}, which wraps text (#450).
276
+ const findNamed = (helper, block = false) => {
270
277
  const result = [];
271
- const regex = new RegExp(`\\{\\{~?\\s*${helper}\\s+(["'])(.*?)\\1`, "g");
278
+ const regex = new RegExp(`\\{\\{~?\\s*${block ? "#?" : ""}${helper}\\s+(["'])(.*?)\\1`, "g");
272
279
  let match;
273
280
  while ((match = regex.exec(input.value))) {
274
281
  const start = match.index;
@@ -285,7 +292,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
285
292
  }
286
293
  return result;
287
294
  };
288
- embeds.push(...findNamed("embed"));
295
+ embeds.push(...findNamed("embed", true));
289
296
  return { output: input.value, links, embeds, gotos: findNamed("goto"), deactivates: findNamed("deactivate"), noNextSection };
290
297
  }
291
298
  // Returns a function that converts an offset into lines.join("\n") to a position in the source file.
@@ -0,0 +1,21 @@
1
+ import type { PassageContext } from "./convert.js";
2
+ export interface StoryAudio {
3
+ files: Map<string, string>;
4
+ looping: Set<string>;
5
+ }
6
+ export declare function trackFile(audio: StoryAudio, track: string): string;
7
+ export declare function pickSource(sources: string[]): string | undefined;
8
+ export interface AudioAction {
9
+ play: boolean;
10
+ stop: boolean;
11
+ loop: boolean;
12
+ fade?: number;
13
+ volume?: number;
14
+ }
15
+ export declare function audioHelper(ctx: PassageContext, raw: string, audio: StoryAudio, track: string, action: AudioAction): string;
16
+ export declare const STOP_ALL_AUDIO = "{{stopsounds}}{{stopmusic}}";
17
+ export declare function audioDirective(helper: string): string | null;
18
+ export declare function leadingAudio(out: string, state: {
19
+ leading: boolean;
20
+ directives: string[];
21
+ }): string;
@@ -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,6 +28,7 @@ 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 {
@@ -60,11 +61,15 @@ export declare class StoryContext {
60
61
  uniqueSectionName(hint: string): string;
61
62
  newLabel(hint: string): string;
62
63
  private readonly loops;
63
- get looping(): boolean;
64
- inLoop<T>(vars: Map<string, "item" | "index">, array: string | undefined, convert: () => T): T;
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
+ };
65
69
  private loopVariable;
66
70
  variable(name: string, temporary: boolean): Expr;
67
71
  attribute(name: string, temporary: boolean): string;
72
+ private attributeName;
68
73
  }
69
74
  export declare function sanitiseName(name: string): string;
70
75
  export declare function escapeText(text: string): string;
@@ -72,11 +77,13 @@ export declare function sectionLink(text: string | null, target: string, setters
72
77
  export declare function isUrl(target: string): boolean;
73
78
  export declare function urlLink(text: string, url: string): string;
74
79
  export declare function dynamicSectionLink(text: string, target: Expr, setters?: string[]): string;
75
- export declare function passageLink(text: string, target: string): string;
80
+ export declare function passageLink(text: string, target: string, setters?: string[]): string;
76
81
  export declare function setter(name: string, op: "=" | "+=" | "-=" | "*=" | "/=", value: Expr, inLink: boolean): string;
77
82
  export declare function comment(text: string): string;
78
83
  export declare function formatTwineProblems(result: TwineConversionResult, sourceName?: string): string;
79
84
  export declare function convertTwine(source: string, options?: TwineConversionOptions): TwineConversionResult;
80
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;
81
88
  export declare function usesOuterLoop(text: string): boolean;
82
89
  export declare function finishText(text: string): string;
@@ -4,7 +4,7 @@
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";
@@ -14,8 +14,11 @@ 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
+ "round", "floor", "ceil", "abs", "min", "max", "upper", "lower", "capitalise", "capitalize", "cond",
18
+ "join", "sort", "shuffle", "slice", "first", "last", "indexof", "count", "range",
17
19
  "if", "unless", "each", "with", "lookup", "log", "else", "this", "turns", "previous", "previous_section",
18
- "true", "false", "null", "undefined",
20
+ "true", "false", "null", "undefined", "music", "stopmusic", "sound", "stopsounds",
21
+ "addclass", "removeclass", "toggleclass", "hasclass", "content",
19
22
  ]);
20
23
  export class StoryContext {
21
24
  constructor(twine, passages) {
@@ -96,7 +99,8 @@ export class StoryContext {
96
99
  value: new Map()
97
100
  });
98
101
  // The loops being converted to {{#each}}, innermost last, with the Twine variables (with their
99
- // $ or _) that stand for each one's item and position
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.
100
104
  Object.defineProperty(this, "loops", {
101
105
  enumerable: true,
102
106
  configurable: true,
@@ -194,11 +198,8 @@ export class StoryContext {
194
198
  this.usedLabels.add(name);
195
199
  return name;
196
200
  }
197
- get looping() {
198
- return this.loops.length > 0;
199
- }
200
- inLoop(vars, array, convert) {
201
- this.loops.push({ vars, array });
201
+ inLoop(vars, array, convert, numbers = false) {
202
+ this.loops.push({ vars, array, numbers });
202
203
  try {
203
204
  return convert();
204
205
  }
@@ -206,12 +207,44 @@ export class StoryContext {
206
207
  this.loops.pop();
207
208
  }
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
+ }
209
225
  loopVariable(name, temporary) {
210
226
  const key = (temporary ? "_" : "$") + name;
211
227
  for (let i = this.loops.length - 1; i >= 0; i--) {
212
- const kind = this.loops[i].vars.get(key);
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);
213
246
  if (kind)
214
- return { k: "loop", kind, up: this.loops.length - 1 - i, array: this.loops[i].array };
247
+ return { k: "loop", kind, up: this.loops.length - 1 - i, array: loop.array, numbers: loop.numbers };
215
248
  }
216
249
  return undefined;
217
250
  }
@@ -224,6 +257,9 @@ export class StoryContext {
224
257
  attribute(name, temporary) {
225
258
  if (this.loopVariable(name, temporary))
226
259
  throw new Unconvertible("changing a loop's variable inside the loop");
260
+ return this.attributeName(name, temporary);
261
+ }
262
+ attributeName(name, temporary) {
227
263
  let result = name;
228
264
  if (temporary && this.permanentVars.has(name))
229
265
  result = "temp_" + name;
@@ -294,9 +330,9 @@ export function dynamicSectionLink(text, target, setters = []) {
294
330
  const set = setters.length ? ` set=${quote(setters.join(", "))}` : "";
295
331
  return `{{section ${print(target)} text=${quote(text)}${set}}}`;
296
332
  }
297
- export function passageLink(text, target) {
333
+ export function passageLink(text, target, setters = []) {
298
334
  const linkText = text.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;");
299
- return `[${linkText}](${target})`;
335
+ return `[${linkText}](${[target, ...setters].join(", ")})`;
300
336
  }
301
337
  // A Squiffy setter, as in @set or a link, for name = value
302
338
  export function setter(name, op, value, inLink) {
@@ -373,6 +409,9 @@ export function convertTwineStory(twine, options = {}) {
373
409
  startup.push(p);
374
410
  else if (p.tags.some(t => t.startsWith("debug-")))
375
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;
376
415
  else
377
416
  storyPassages.push(p);
378
417
  }
@@ -408,6 +447,9 @@ export function convertTwineStory(twine, options = {}) {
408
447
  // Widgets become sections, which calls to them embed. They're named before anything's
409
448
  // converted, so calls know where they go.
410
449
  sugarCubeWidgets(story);
450
+ // Harlowe's custom macros (#450) too
451
+ if (harlowe)
452
+ harloweMacros(story);
411
453
  for (const p of skipped) {
412
454
  problems.push({
413
455
  passage: p.name, text: p.name,
@@ -433,7 +475,6 @@ export function convertTwineStory(twine, options = {}) {
433
475
  return reserved.name;
434
476
  },
435
477
  reservePassage(hint) {
436
- const looping = story.looping;
437
478
  const base = sanitisePassageName(hint) || "more";
438
479
  let name = base;
439
480
  for (let n = 2; extraPassages.some(p => p.startsWith(`[${name}]:\n`)) || name == section; n++)
@@ -446,20 +487,17 @@ export function convertTwineStory(twine, options = {}) {
446
487
  // Left out, rather than empty, if it can't be converted
447
488
  extraPassages[index] = "";
448
489
  extraPassages[index] = `[${name}]:\n${generated(content)}`;
449
- if (looping) {
450
- story.addProblem({
451
- passage: passage.name, text: oneLine(hint),
452
- reason: "This link is in a loop, and every item's link goes to the same passage, so once one has been clicked, they all have.",
453
- });
454
- }
455
490
  },
456
491
  };
457
492
  },
458
493
  addSection(hint, content) {
459
494
  const name = story.uniqueSectionName(hint);
460
- story.extraSections.push(`[[${name}]]:\n${generated(content)}`);
495
+ this.fillSection(name, content);
461
496
  return name;
462
497
  },
498
+ fillSection(name, content) {
499
+ story.extraSections.push(`[[${name}]]:\n${generated(content)}`);
500
+ },
463
501
  newLabel: hint => story.newLabel(hint),
464
502
  });
465
503
  const convert = (passage, section, extraPassages) => {
@@ -517,6 +555,10 @@ export function convertTwineStory(twine, options = {}) {
517
555
  const extraPassages = [];
518
556
  const converted = convert(p, section, extraPassages);
519
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(" ")}`);
520
562
  let body = converted.body.trim();
521
563
  if (p.name == startPassage && (init.directives.length || init.body)) {
522
564
  directives.unshift(...init.directives);
@@ -552,10 +594,14 @@ export function convertTwineStory(twine, options = {}) {
552
594
  header.push(`@start ${startSection}`);
553
595
  if (twine.stylesheet) {
554
596
  // squiffy.json makes it part of the story
555
- files[`${name}.css`] = twine.stylesheet + "\n";
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
+ : "";
556
602
  problems.push({
557
603
  text: `${name}.css`,
558
- 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}`,
559
605
  });
560
606
  }
561
607
  // The story's JavaScript is left out of it, as it was written for another story format
@@ -626,13 +672,45 @@ function unarranged(passages) {
626
672
  const columns = new Set(onGrid.map(([x]) => x));
627
673
  return columns.size == 10 && onGrid.length >= positions.length * 0.9;
628
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
+ }
629
707
  // The text of a section or passage: its directives, then its text
630
708
  function block(content) {
631
709
  const c = typeof content == "string" ? { directives: [], body: content } : content;
632
710
  return [...c.directives, finishText(c.body)].filter(l => l.length).join("\n");
633
711
  }
634
- // A passage or section made for a link, e.g. one in a loop, which can't use the loop's item or
635
- // position: it's shown on its own, after the loop has finished
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.
636
714
  function generated(content) {
637
715
  const c = typeof content == "string" ? { directives: [], body: content } : content;
638
716
  // Directives are expressions, rather than text with {{...}} in it
@@ -680,9 +758,9 @@ function oneLine(text) {
680
758
  return line.length > 120 ? line.substring(0, 117) + "..." : line;
681
759
  }
682
760
  // Directives the compiler would read at the start of a line
683
- 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/;
684
762
  // Lines that only hold helpers that write nothing
685
- 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;
686
764
  function isSilent(line) {
687
765
  return line.replace(silentHelper, "").trim() == "";
688
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,11 +36,19 @@ 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;
34
46
  } | {
35
47
  k: "loop";
36
48
  kind: "item" | "index";
37
49
  up: number;
38
50
  array?: string;
51
+ numbers?: boolean;
39
52
  };
40
53
  export declare class Unconvertible extends Error {
41
54
  }
@@ -45,8 +58,14 @@ export interface PrintOptions {
45
58
  }
46
59
  export declare function quote(text: string, options?: PrintOptions): string;
47
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;
48
64
  export declare function print(e: Expr, options?: PrintOptions): string;
65
+ export declare function isListCall(e: Expr): boolean;
49
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;
50
69
  export declare function randomInteger(min: Expr, max: Expr): Expr;
51
70
  export declare function display(e: Expr): string;
52
71
  export declare class Tokens<T extends {