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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +3 -0
  3. package/dist/analyse.js +73 -12
  4. package/dist/compiler.d.ts +12 -2
  5. package/dist/compiler.js +6 -2
  6. package/dist/emit.d.ts +6 -0
  7. package/dist/emit.js +17 -1
  8. package/dist/language-service.js +36 -5
  9. package/dist/node.d.ts +8 -1
  10. package/dist/node.js +19 -5
  11. package/dist/parse.js +18 -2
  12. package/dist/project.d.ts +56 -0
  13. package/dist/project.js +159 -17
  14. package/dist/quest/aslx.d.ts +50 -0
  15. package/dist/quest/aslx.js +181 -0
  16. package/dist/quest/convert.d.ts +20 -0
  17. package/dist/quest/convert.js +475 -0
  18. package/dist/quest/script.d.ts +92 -0
  19. package/dist/quest/script.js +453 -0
  20. package/dist/quest/scripts.d.ts +24 -0
  21. package/dist/quest/scripts.js +501 -0
  22. package/dist/quest/text.d.ts +17 -0
  23. package/dist/quest/text.js +305 -0
  24. package/dist/setters.d.ts +6 -0
  25. package/dist/setters.js +43 -0
  26. package/dist/story-graph.d.ts +3 -1
  27. package/dist/story-graph.js +12 -3
  28. package/dist/syntax.d.ts +22 -2
  29. package/dist/text.d.ts +4 -0
  30. package/dist/text.js +28 -21
  31. package/dist/twine/convert.d.ts +82 -0
  32. package/dist/twine/convert.js +744 -0
  33. package/dist/twine/expression.d.ts +68 -0
  34. package/dist/twine/expression.js +215 -0
  35. package/dist/twine/harlowe.d.ts +18 -0
  36. package/dist/twine/harlowe.js +1912 -0
  37. package/dist/twine/story.d.ts +24 -0
  38. package/dist/twine/story.js +231 -0
  39. package/dist/twine/sugarcube.d.ts +34 -0
  40. package/dist/twine/sugarcube.js +1621 -0
  41. package/dist/v5.js +2 -1
  42. package/package.json +3 -2
  43. package/syntaxes/squiffy.tmLanguage.json +1 -1
@@ -0,0 +1,744 @@
1
+ // Converts a Twine story (#378) into a Squiffy story: each passage becomes a section, and the
2
+ // passage's macros, in Harlowe or SugarCube, become Squiffy's {{...}} helpers, @set and links.
3
+ // Like the Squiffy 5 converter (v5.ts), this is a pure function with no I/O: the CLI and the
4
+ // editor write the files it returns. Anything that can't be converted is kept as a comment in
5
+ // the story and listed as a problem, so the author can deal with it by hand.
6
+ import { attributeRef, print, quote, Unconvertible } from "./expression.js";
7
+ import { convertHarlowePassage } from "./harlowe.js";
8
+ import { convertSugarCubePassage, convertSugarCubeWidgets, sugarCubeWidgets } from "./sugarcube.js";
9
+ import { parseTwine } from "./story.js";
10
+ import { formatProjectFile } from "../project.js";
11
+ // The Squiffy names that would be read as a helper, rather than an attribute, in {{name}} and
12
+ // expressions, and the ones Squiffy sets itself
13
+ export const reservedAttributes = new Set([
14
+ "get", "set", "unset", "inc", "dec", "seen", "visits", "at", "goto", "embed", "array", "random", "contains",
15
+ "length", "append", "prepend", "pop", "remove", "section", "passage", "label", "replace", "rotate", "sequence",
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", "previous", "previous_section",
18
+ "true", "false", "null", "undefined",
19
+ ]);
20
+ export class StoryContext {
21
+ constructor(twine, passages) {
22
+ Object.defineProperty(this, "twine", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: twine
27
+ });
28
+ Object.defineProperty(this, "problems", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: []
33
+ });
34
+ // Twine passage name -> Squiffy section name
35
+ Object.defineProperty(this, "sectionNames", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: new Map()
40
+ });
41
+ Object.defineProperty(this, "usedSectionNames", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: new Set()
46
+ });
47
+ Object.defineProperty(this, "usedLabels", {
48
+ enumerable: true,
49
+ configurable: true,
50
+ writable: true,
51
+ value: new Set()
52
+ });
53
+ // Sections added by the converter, as Squiffy text, to go at the end of the story
54
+ Object.defineProperty(this, "extraSections", {
55
+ enumerable: true,
56
+ configurable: true,
57
+ writable: true,
58
+ value: []
59
+ });
60
+ Object.defineProperty(this, "permanentVars", {
61
+ enumerable: true,
62
+ configurable: true,
63
+ writable: true,
64
+ value: new Set()
65
+ });
66
+ Object.defineProperty(this, "passagesByName", {
67
+ enumerable: true,
68
+ configurable: true,
69
+ writable: true,
70
+ value: new Map()
71
+ });
72
+ Object.defineProperty(this, "problemKeys", {
73
+ enumerable: true,
74
+ configurable: true,
75
+ writable: true,
76
+ value: new Set()
77
+ });
78
+ Object.defineProperty(this, "trimmed", {
79
+ enumerable: true,
80
+ configurable: true,
81
+ writable: true,
82
+ value: void 0
83
+ });
84
+ Object.defineProperty(this, "cache", {
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ value: new Map()
89
+ });
90
+ // Problems that are the same wherever they happen, listed once for the story, with the code
91
+ // they happened for
92
+ Object.defineProperty(this, "notes", {
93
+ enumerable: true,
94
+ configurable: true,
95
+ writable: true,
96
+ value: new Map()
97
+ });
98
+ // 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
100
+ Object.defineProperty(this, "loops", {
101
+ enumerable: true,
102
+ configurable: true,
103
+ writable: true,
104
+ value: []
105
+ });
106
+ for (const p of passages) {
107
+ this.passagesByName.set(p.name, p);
108
+ }
109
+ // Passages keep their names where they can: a name that's only taken once it's been
110
+ // tidied up (Room [1] and Room (1)) gets a number, avoiding every other passage's name
111
+ const wanted = passages.map(p => sanitiseName(p.name) || "Untitled");
112
+ const counts = new Map();
113
+ for (const name of wanted)
114
+ counts.set(name, (counts.get(name) ?? 0) + 1);
115
+ passages.forEach((p, n) => {
116
+ if (counts.get(wanted[n]) == 1) {
117
+ this.sectionNames.set(p.name, wanted[n]);
118
+ this.usedSectionNames.add(wanted[n]);
119
+ }
120
+ });
121
+ // Then the passages whose names were already right, then the rest
122
+ passages.forEach((p, n) => {
123
+ if (!this.sectionNames.has(p.name) && p.name == wanted[n] && !this.usedSectionNames.has(p.name)) {
124
+ this.sectionNames.set(p.name, p.name);
125
+ this.usedSectionNames.add(p.name);
126
+ }
127
+ });
128
+ for (const p of passages) {
129
+ if (!this.sectionNames.has(p.name))
130
+ this.sectionNames.set(p.name, this.uniqueSectionName(p.name));
131
+ }
132
+ }
133
+ // Records a problem, once for each passage
134
+ addProblem(problem) {
135
+ const key = `${problem.passage}\u0000${problem.text}\u0000${problem.reason}`;
136
+ if (this.problemKeys.has(key))
137
+ return;
138
+ this.problemKeys.add(key);
139
+ this.problems.push(problem);
140
+ }
141
+ notePermanentVar(name) {
142
+ this.permanentVars.add(name);
143
+ }
144
+ // The Squiffy section for a Twine passage, or undefined if there's no such passage
145
+ sectionFor(passageName) {
146
+ // Twine passage names can start or end with spaces, which links often leave out
147
+ return this.sectionNames.get(passageName) ?? this.trimmedNames().get(passageName.trim());
148
+ }
149
+ trimmedNames() {
150
+ if (!this.trimmed) {
151
+ this.trimmed = new Map();
152
+ for (const [name, section] of this.sectionNames) {
153
+ if (!this.trimmed.has(name.trim()))
154
+ this.trimmed.set(name.trim(), section);
155
+ }
156
+ }
157
+ return this.trimmed;
158
+ }
159
+ // A value worked out once for the story, e.g. by a format's converter
160
+ cached(key, make) {
161
+ if (!this.cache.has(key))
162
+ this.cache.set(key, make());
163
+ return this.cache.get(key);
164
+ }
165
+ note(key, text, reason) {
166
+ let note = this.notes.get(key);
167
+ if (!note) {
168
+ note = { reason, texts: new Set() };
169
+ this.notes.set(key, note);
170
+ }
171
+ note.texts.add(text);
172
+ }
173
+ noteProblems() {
174
+ return [...this.notes.values()].map(n => ({ text: [...n.texts].join(", "), reason: n.reason + "." }));
175
+ }
176
+ // A Squiffy section name for a passage name that isn't known (a broken link): it's
177
+ // tidied up the same way, so the editor shows the broken link as it was meant
178
+ sectionForUnknown(passageName) {
179
+ return this.sectionFor(passageName) ?? sanitiseName(passageName);
180
+ }
181
+ uniqueSectionName(hint) {
182
+ const base = sanitiseName(hint) || "Untitled";
183
+ let name = base;
184
+ for (let n = 2; this.usedSectionNames.has(name); n++)
185
+ name = `${base} ${n}`;
186
+ this.usedSectionNames.add(name);
187
+ return name;
188
+ }
189
+ newLabel(hint) {
190
+ const base = hint.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").substring(0, 24) || "label";
191
+ let name = base;
192
+ for (let n = 2; this.usedLabels.has(name); n++)
193
+ name = `${base}-${n}`;
194
+ this.usedLabels.add(name);
195
+ return name;
196
+ }
197
+ get looping() {
198
+ return this.loops.length > 0;
199
+ }
200
+ inLoop(vars, array, convert) {
201
+ this.loops.push({ vars, array });
202
+ try {
203
+ return convert();
204
+ }
205
+ finally {
206
+ this.loops.pop();
207
+ }
208
+ }
209
+ loopVariable(name, temporary) {
210
+ const key = (temporary ? "_" : "$") + name;
211
+ for (let i = this.loops.length - 1; i >= 0; i--) {
212
+ const kind = this.loops[i].vars.get(key);
213
+ if (kind)
214
+ return { k: "loop", kind, up: this.loops.length - 1 - i, array: this.loops[i].array };
215
+ }
216
+ return undefined;
217
+ }
218
+ // A Twine variable's value: its attribute, or inside a loop, the loop's item or position
219
+ variable(name, temporary) {
220
+ return this.loopVariable(name, temporary) ?? { k: "var", name: this.attribute(name, temporary) };
221
+ }
222
+ // The Squiffy attribute for a Twine variable, given without its $ or _: a temporary (_)
223
+ // variable keeps its name unless a story variable ($) has the same name
224
+ attribute(name, temporary) {
225
+ if (this.loopVariable(name, temporary))
226
+ throw new Unconvertible("changing a loop's variable inside the loop");
227
+ let result = name;
228
+ if (temporary && this.permanentVars.has(name))
229
+ result = "temp_" + name;
230
+ if (reservedAttributes.has(result))
231
+ result += "_";
232
+ return result;
233
+ }
234
+ }
235
+ const reservedSectionChars = /[[\]{}|"]/g;
236
+ // Twine allows anything in a passage name, but in Squiffy some characters would break a link,
237
+ // e.g. [[text]](a, b) sets an attribute b, and ] or | would end the link early
238
+ export function sanitiseName(name) {
239
+ let result = name
240
+ .replace(/\[/g, "(").replace(/\]/g, ")")
241
+ .replace(/\{/g, "(").replace(/\}/g, ")")
242
+ .replace(reservedSectionChars, "")
243
+ .replace(/,/g, "")
244
+ .replace(/\s+/g, " ")
245
+ .trim();
246
+ // A name ending in > would be a link to the next section
247
+ result = result.replace(/>+$/, "").trim();
248
+ // Brackets in a link's target have to balance
249
+ let depth = 0;
250
+ let balanced = true;
251
+ for (const c of result) {
252
+ if (c == "(")
253
+ depth++;
254
+ else if (c == ")" && --depth < 0)
255
+ balanced = false;
256
+ }
257
+ if (!balanced || depth != 0)
258
+ result = result.replace(/[()]/g, "").replace(/\s+/g, " ").trim();
259
+ // @ at the start of a passage name means something to Squiffy, so keep sections clear of it
260
+ if (result.startsWith("@"))
261
+ result = result.substring(1).trim();
262
+ return result;
263
+ }
264
+ // Text that came from the story, made safe to put in Squiffy text: square brackets would be
265
+ // links, {{ a helper, and some characters at the start of a line mean something to the compiler
266
+ export function escapeText(text) {
267
+ return text
268
+ .replace(/\[/g, "&#91;")
269
+ .replace(/\]/g, "&#93;")
270
+ .replace(/\{\{/g, "&#123;{")
271
+ .replace(/\}\}/g, "}&#125;");
272
+ }
273
+ // A link to a section. text is Squiffy text (already escaped); target is a Squiffy section name.
274
+ export function sectionLink(text, target, setters = []) {
275
+ const linkText = text == null ? null : text.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;");
276
+ if (setters.length == 0 && (linkText == null || linkText == target) && !target.endsWith(">")) {
277
+ return `[[${target}]]`;
278
+ }
279
+ return `[[${linkText ?? target}]](${[target, ...setters].join(", ")})`;
280
+ }
281
+ // A link to a web page, from a Twine link like [[https://example.com]]
282
+ export function isUrl(target) {
283
+ return /^(https?|mailto):/i.test(target.trim());
284
+ }
285
+ export function urlLink(text, url) {
286
+ const href = url.trim().replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\[/g, "%5B").replace(/\]/g, "%5D");
287
+ return `<a href="${href}" target="_blank">${text}</a>`;
288
+ }
289
+ // A link to a section whose name is worked out as the story runs
290
+ export function dynamicSectionLink(text, target, setters = []) {
291
+ // quote() would break the {{this}} of a loop's item
292
+ if (setters.some(s => s.includes("{{")))
293
+ 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");
294
+ const set = setters.length ? ` set=${quote(setters.join(", "))}` : "";
295
+ return `{{section ${print(target)} text=${quote(text)}${set}}}`;
296
+ }
297
+ export function passageLink(text, target) {
298
+ const linkText = text.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;");
299
+ return `[${linkText}](${target})`;
300
+ }
301
+ // A Squiffy setter, as in @set or a link, for name = value
302
+ export function setter(name, op, value, inLink) {
303
+ return `${attributeRef(name)} ${op} ${print(value, { preferSingle: inLink, inLink })}`;
304
+ }
305
+ // A comment in the story, for Twine code that couldn't be converted. Handlebars comments can't
306
+ // contain --}}, and line breaks would let the compiler read a line of it as something else.
307
+ export function comment(text) {
308
+ const clean = text.replace(/--\}\}/g, "-- }}").replace(/\s*\n\s*/g, " ").trim();
309
+ return `{{!-- Twine: ${clean} --}}`;
310
+ }
311
+ // SugarCube's passages for its sidebar that become panels beside the story (#443), in the order
312
+ // SugarCube shows them, with the labels of the buttons they have on a narrow screen
313
+ const sugarCubePanels = { StoryBanner: "Banner", StoryCaption: "Status" };
314
+ // Passages a format treats specially, which aren't part of the story as sections
315
+ // (StorySubtitle, StoryAuthor and so on are kept, as their text might be included elsewhere)
316
+ const sugarCubeSpecial = new Set(["StoryMenu", "StoryInterface", "StoryShare", "StoryTitle", "StoryData", "StorySettings"]);
317
+ // The problems as a text file, to keep with the converted story: the ones about the whole story,
318
+ // then each passage's, in the order of the story
319
+ export function formatTwineProblems(result, sourceName) {
320
+ const lines = [
321
+ `Converted ${sourceName ?? "a Twine story"}${result.format ? ` (${result.format})` : ""} to Squiffy: ${result.passages} passage${result.passages == 1 ? "" : "s"}.`,
322
+ "",
323
+ ];
324
+ if (result.problems.length == 0) {
325
+ lines.push("Everything was converted.");
326
+ return lines.join("\n") + "\n";
327
+ }
328
+ lines.push(`${result.problems.length} thing${result.problems.length == 1 ? "" : "s"} couldn't be converted exactly. Where something couldn't be converted at all, the story has the`, "Twine code in a comment, {{!-- Twine: ... --}}, so you can search for \"Twine:\" to find them.", "");
329
+ let passage = "\u0000";
330
+ for (const p of result.problems) {
331
+ if (p.passage !== passage) {
332
+ passage = p.passage;
333
+ lines.push(passage === undefined ? "The whole story:" : `${passage}:`);
334
+ }
335
+ lines.push(` ${p.text}`, ` ${p.reason}`);
336
+ }
337
+ return lines.join("\n") + "\n";
338
+ }
339
+ export function convertTwine(source, options = {}) {
340
+ return convertTwineStory(parseTwine(source), options);
341
+ }
342
+ export function convertTwineStory(twine, options = {}) {
343
+ const name = options.name ?? "story";
344
+ const harlowe = twine.format == "harlowe";
345
+ const problems = [];
346
+ if (twine.format == "other") {
347
+ problems.push({
348
+ text: twine.formatName,
349
+ reason: `The story uses the ${twine.formatName} story format. Only Harlowe and SugarCube stories can be converted, so its passages have been converted as if it were SugarCube.`,
350
+ });
351
+ }
352
+ // Passages that are part of every passage, or that run at the start, rather than sections
353
+ const headers = [];
354
+ const footers = [];
355
+ const startup = [];
356
+ const widgets = [];
357
+ const skipped = [];
358
+ const panelPassages = [];
359
+ const storyPassages = [];
360
+ const seenNames = new Set();
361
+ for (const p of twine.passages) {
362
+ if (seenNames.has(p.name)) {
363
+ problems.push({ passage: p.name, text: p.name, reason: "There's more than one passage with this name. Only the first has been converted." });
364
+ continue;
365
+ }
366
+ seenNames.add(p.name);
367
+ if (harlowe) {
368
+ if (p.tags.includes("header"))
369
+ headers.push(p);
370
+ else if (p.tags.includes("footer"))
371
+ footers.push(p);
372
+ else if (p.tags.includes("startup"))
373
+ startup.push(p);
374
+ else if (p.tags.some(t => t.startsWith("debug-")))
375
+ skipped.push(p);
376
+ else
377
+ storyPassages.push(p);
378
+ }
379
+ else {
380
+ if (p.name == "PassageHeader" || p.name == "PassageReady")
381
+ headers.push(p);
382
+ else if (p.name == "PassageFooter" || p.name == "PassageDone")
383
+ footers.push(p);
384
+ else if (p.name == "StoryInit")
385
+ startup.push(p);
386
+ else if (p.tags.includes("widget"))
387
+ widgets.push(p);
388
+ else if (sugarCubeSpecial.has(p.name))
389
+ skipped.push(p);
390
+ else if (p.name in sugarCubePanels)
391
+ panelPassages.push(p);
392
+ else {
393
+ if (["StorySubtitle", "StoryAuthor", "StoryDisplayTitle"].includes(p.name)) {
394
+ problems.push({ passage: p.name, text: p.name, reason: "Squiffy has no sidebar, so this passage is an ordinary section, which nothing links to." });
395
+ }
396
+ storyPassages.push(p);
397
+ }
398
+ }
399
+ }
400
+ // Footers are embedded at the end of every section, so they need sections of their own
401
+ const sectionPassages = [...storyPassages, ...footers];
402
+ // Temporary variables keep their names unless a story variable has the same name
403
+ const story = new StoryContext(twine, sectionPassages);
404
+ for (const p of twine.passages) {
405
+ for (const m of p.text.matchAll(/\$([A-Za-z_]\w*)/g))
406
+ story.notePermanentVar(m[1]);
407
+ }
408
+ // Widgets become sections, which calls to them embed. They're named before anything's
409
+ // converted, so calls know where they go.
410
+ sugarCubeWidgets(story);
411
+ for (const p of skipped) {
412
+ problems.push({
413
+ passage: p.name, text: p.name,
414
+ reason: p.name == "StoryMenu"
415
+ ? "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."
416
+ : "This special passage has been left out.",
417
+ });
418
+ }
419
+ const context = (passage, section, extraPassages) => ({
420
+ story,
421
+ passage,
422
+ section,
423
+ unconvertible(text, reason) {
424
+ story.addProblem({ passage: passage.name, text: oneLine(text), reason });
425
+ return comment(text);
426
+ },
427
+ approximate(text, reason) {
428
+ story.addProblem({ passage: passage.name, text: oneLine(text), reason });
429
+ },
430
+ addPassage(hint, content) {
431
+ const reserved = this.reservePassage(hint);
432
+ reserved.fill(content);
433
+ return reserved.name;
434
+ },
435
+ reservePassage(hint) {
436
+ const looping = story.looping;
437
+ const base = sanitisePassageName(hint) || "more";
438
+ let name = base;
439
+ for (let n = 2; extraPassages.some(p => p.startsWith(`[${name}]:\n`)) || name == section; n++)
440
+ name = `${base} ${n}`;
441
+ const index = extraPassages.length;
442
+ extraPassages.push(`[${name}]:\n`);
443
+ return {
444
+ name,
445
+ fill: content => {
446
+ // Left out, rather than empty, if it can't be converted
447
+ extraPassages[index] = "";
448
+ 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
+ },
456
+ };
457
+ },
458
+ addSection(hint, content) {
459
+ const name = story.uniqueSectionName(hint);
460
+ story.extraSections.push(`[[${name}]]:\n${generated(content)}`);
461
+ return name;
462
+ },
463
+ newLabel: hint => story.newLabel(hint),
464
+ });
465
+ const convert = (passage, section, extraPassages) => {
466
+ const ctx = context(passage, section, extraPassages);
467
+ try {
468
+ return harlowe ? convertHarlowePassage(passage.text, ctx) : convertSugarCubePassage(passage.text, ctx);
469
+ }
470
+ catch (e) {
471
+ if (!(e instanceof Unconvertible))
472
+ throw e;
473
+ return { directives: [], body: ctx.unconvertible(passage.text, `This passage couldn't be converted: ${e.message}.`) };
474
+ }
475
+ };
476
+ const startPassage = twine.start && story.sectionFor(twine.start) ? twine.start : storyPassages[0]?.name;
477
+ const startSection = startPassage === undefined ? undefined : story.sectionFor(startPassage);
478
+ // The master section: one screen per passage, as in Twine, and the header passages
479
+ const masterPassages = [];
480
+ const master = { directives: ["@clear"], body: "" };
481
+ for (const p of headers) {
482
+ const converted = convert(p, "", masterPassages);
483
+ master.directives.push(...converted.directives);
484
+ if (converted.body.trim())
485
+ master.body += converted.body.trim() + "\n";
486
+ }
487
+ // SugarCube's sidebar passages, as panels beside the story, rendered again after each passage
488
+ sortPanelPassages(panelPassages);
489
+ const panels = [];
490
+ for (const p of panelPassages) {
491
+ const converted = convert(p, "", masterPassages);
492
+ let passageName = p.name;
493
+ for (let n = 2; masterPassages.some(text => text.startsWith(`[${passageName}]:\n`)); n++)
494
+ passageName = `${p.name} ${n}`;
495
+ const body = converted.body.trim();
496
+ if (converted.directives.length) {
497
+ story.addProblem({ passage: p.name, text: converted.directives.join(" "), reason: "A panel only shows its text, so this doesn't run." });
498
+ }
499
+ if (/\[\[|\]\(|\{\{(section|passage)\b/.test(body)) {
500
+ story.addProblem({ passage: p.name, text: p.name, reason: "This is a panel beside the story, where links don't work." });
501
+ }
502
+ masterPassages.push(`[${passageName}]:\n${finishText(body)}`.trimEnd());
503
+ panels.push({ passage: passageName, label: sugarCubePanels[p.name], position: "side" });
504
+ }
505
+ // Passages that run once at the start
506
+ const init = { directives: [], body: "" };
507
+ for (const p of startup) {
508
+ const converted = convert(p, startSection ?? "", []);
509
+ init.directives.push(...converted.directives);
510
+ if (converted.body.trim())
511
+ init.body += converted.body.trim() + "\n";
512
+ }
513
+ const footerEmbeds = footers.map(p => `{{embed ${quote(story.sectionFor(p.name))}}}`);
514
+ const sections = [];
515
+ for (const p of sectionPassages) {
516
+ const section = story.sectionFor(p.name);
517
+ const extraPassages = [];
518
+ const converted = convert(p, section, extraPassages);
519
+ const directives = [...converted.directives];
520
+ let body = converted.body.trim();
521
+ if (p.name == startPassage && (init.directives.length || init.body)) {
522
+ directives.unshift(...init.directives);
523
+ body = (init.body + body).trim();
524
+ }
525
+ if (!footers.includes(p) && footerEmbeds.length) {
526
+ body = (body + "\n" + footerEmbeds.join("\n")).trim();
527
+ }
528
+ sections.push([`[[${section}]]:\n${block({ directives, body })}`.trimEnd(), ...extraPassages.filter(p => p)].join("\n\n"));
529
+ }
530
+ for (const p of widgets) {
531
+ const extraPassages = [];
532
+ let converted;
533
+ try {
534
+ converted = convertSugarCubeWidgets(p.text, context(p, "", extraPassages));
535
+ }
536
+ catch (e) {
537
+ if (!(e instanceof Unconvertible))
538
+ throw e;
539
+ problems.push({ passage: p.name, text: p.name, reason: `This widget passage couldn't be converted: ${e.message}.` });
540
+ continue;
541
+ }
542
+ for (const w of converted) {
543
+ sections.push([`[[${w.section}]]:\n${block(w.converted)}`, ...extraPassages.filter(p => p)].join("\n\n"));
544
+ extraPassages.length = 0;
545
+ }
546
+ }
547
+ const files = {};
548
+ const header = [];
549
+ if (twine.title)
550
+ header.push(`@title ${twine.title.replace(/\s+/g, " ").trim()}`);
551
+ if (startSection !== undefined)
552
+ header.push(`@start ${startSection}`);
553
+ if (twine.stylesheet) {
554
+ // squiffy.json makes it part of the story
555
+ files[`${name}.css`] = twine.stylesheet + "\n";
556
+ problems.push({
557
+ 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.`,
559
+ });
560
+ }
561
+ // The story's JavaScript is left out of it, as it was written for another story format
562
+ const exclude = [];
563
+ if (twine.script) {
564
+ files[`${name}.js`] = twine.script + "\n";
565
+ exclude.push(`${name}.js`);
566
+ problems.push({
567
+ text: `${name}.js`,
568
+ 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).`,
569
+ });
570
+ }
571
+ const masterPassageText = masterPassages.length ? "\n\n" + masterPassages.join("\n\n") : "";
572
+ const script = [
573
+ header.join("\n"),
574
+ `[[]]:\n${block(master)}${masterPassageText}`,
575
+ ...sections,
576
+ ...story.extraSections,
577
+ ].filter(s => s.length).join("\n\n") + "\n";
578
+ files[`${name}.squiffy`] = script;
579
+ const map = mapPositions(sectionPassages, story);
580
+ files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, exclude, panels, ...(map ? { map } : {}) });
581
+ return {
582
+ title: twine.title,
583
+ format: `${twine.formatName} ${twine.formatVersion}`.trim(),
584
+ files,
585
+ main: `${name}.squiffy`,
586
+ passages: sectionPassages.length,
587
+ problems: [...problems, ...story.noteProblems(), ...story.problems],
588
+ };
589
+ }
590
+ // SugarCube's sidebar passages in the order SugarCube shows them
591
+ function sortPanelPassages(passages) {
592
+ const order = Object.keys(sugarCubePanels);
593
+ passages.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name));
594
+ }
595
+ // Where the sections go on the editor's story map, so it looks like the story's map in Twine.
596
+ // Twine's boxes are 100 by 100, on a grid of 25, and usually 125 apart; the map's are short and
597
+ // wide, up to 190 across, so the map is stretched sideways to keep them from overlapping (which
598
+ // leaves only a handful overlapping in real games). Undefined if the story's passages have no
599
+ // places on the map, or have never been arranged.
600
+ const MAP_STRETCH = 1.6;
601
+ function mapPositions(passages, story) {
602
+ const placed = passages.filter(p => p.position);
603
+ if (!placed.length || unarranged(story.twine.passages))
604
+ return undefined;
605
+ const centres = placed.map(p => {
606
+ const [w, h] = p.size ?? [100, 100];
607
+ return { name: story.sectionFor(p.name), x: p.position[0] + w / 2, y: p.position[1] + h / 2 };
608
+ });
609
+ const left = Math.min(...centres.map(c => c.x));
610
+ const top = Math.min(...centres.map(c => c.y));
611
+ const sections = {};
612
+ for (const c of centres)
613
+ sections[c.name] = [Math.round((c.x - left) * MAP_STRETCH), Math.round(c.y - top)];
614
+ return { sections, passages: {} };
615
+ }
616
+ // Whether the passages are where Twine or Tweego put them when the story was made from Twee
617
+ // without positions: in rows of ten, 125 apart. A map like that says nothing about the story, and
618
+ // the editor's own layout is better. It still counts if the author's moved one or two.
619
+ function unarranged(passages) {
620
+ const positions = passages.flatMap(p => p.position ? [p.position] : []);
621
+ if (positions.length < 10)
622
+ return false;
623
+ const left = Math.min(...positions.map(p => p[0]));
624
+ const top = Math.min(...positions.map(p => p[1]));
625
+ const onGrid = positions.filter(([x, y]) => (x - left) % 125 == 0 && (y - top) % 125 == 0 && x - left < 1250);
626
+ const columns = new Set(onGrid.map(([x]) => x));
627
+ return columns.size == 10 && onGrid.length >= positions.length * 0.9;
628
+ }
629
+ // The text of a section or passage: its directives, then its text
630
+ function block(content) {
631
+ const c = typeof content == "string" ? { directives: [], body: content } : content;
632
+ return [...c.directives, finishText(c.body)].filter(l => l.length).join("\n");
633
+ }
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
636
+ function generated(content) {
637
+ const c = typeof content == "string" ? { directives: [], body: content } : content;
638
+ // Directives are expressions, rather than text with {{...}} in it
639
+ if (c.directives.some(d => usesOuterLoop(`{{${d}}}`)) || usesOuterLoop(c.body)) {
640
+ throw new Unconvertible("a link in a loop that does more than set variables to the loop's item");
641
+ }
642
+ return block(c);
643
+ }
644
+ // Whether Squiffy text uses the item or position of a loop it isn't in
645
+ export function usesOuterLoop(text) {
646
+ let depth = 0;
647
+ // Comments keep the Twine code, which can have "this" in it
648
+ for (const tag of text.replace(/\{\{!--[\s\S]*?--\}\}/g, "").matchAll(/\{\{([\s\S]*?)\}\}/g)) {
649
+ // Text in quotes isn't a reference
650
+ const inner = tag[1].replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g, "\"\"");
651
+ if (inner.startsWith("/each")) {
652
+ depth--;
653
+ continue;
654
+ }
655
+ for (const ref of inner.matchAll(/(?<![\w$@.])((?:\.\.\/)*)this\b|@((?:\.\.\/)*)index\b/g)) {
656
+ const up = (ref[1] ?? ref[2] ?? "").length / 3;
657
+ if (up >= depth)
658
+ return true;
659
+ }
660
+ if (inner.startsWith("#each"))
661
+ depth++;
662
+ }
663
+ return false;
664
+ }
665
+ // A name for a generated passage, from a link's text, which can have markup in it
666
+ function sanitisePassageName(name) {
667
+ const plain = name
668
+ .replace(/\{\{[\s\S]*?\}\}/g, "")
669
+ .replace(/\([\w-]+:[^()]*(\([^()]*\)[^()]*)*\)/g, "")
670
+ .replace(/<[^>]*>|&#?\w+;|''|\/\/|[*_~^]/g, "")
671
+ .replace(/[$_]\w+/g, "")
672
+ .replace(/[[\]]/g, " ");
673
+ let result = sanitiseName(plain).replace(/:/g, "").trim();
674
+ if (result.length > 40)
675
+ result = result.substring(0, 40).replace(/\s+\S*$/, "");
676
+ return result.trim();
677
+ }
678
+ function oneLine(text) {
679
+ const line = text.replace(/\s+/g, " ").trim();
680
+ return line.length > 120 ? line.substring(0, 117) + "..." : line;
681
+ }
682
+ // 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/;
684
+ // 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;
686
+ function isSilent(line) {
687
+ return line.replace(silentHelper, "").trim() == "";
688
+ }
689
+ // Markdown that starts a block, which can't be joined to the line before with <br>
690
+ function isBlockLine(line) {
691
+ return /^(#{1,6}\s|[*+-]\s|\d+\.\s|<hr>|<\/?(div|p|ul|ol|li|table|tr|td|th|h\d|blockquote|pre|center|section|article|br)\b)/i.test(line)
692
+ || /<\/(div|p|ul|ol|table|h\d|blockquote|pre|center|section|article)>\s*$/i.test(line);
693
+ }
694
+ // Tidies converted passage text into lines the compiler reads as text. In Twine, each line
695
+ // break in a passage is a line break in the story, but in Markdown a single line break is just a
696
+ // space, so lines that follow each other get a <br>.
697
+ export function finishText(text) {
698
+ const lines = text.replace(/\r/g, "").split("\n").map(line => {
699
+ let l = line.trim();
700
+ if (/^-{3,}$/.test(l))
701
+ return "<hr>";
702
+ if (directiveLine.test(l))
703
+ l = "&#64;" + l.substring(1);
704
+ if (l.startsWith("+++"))
705
+ l = "&#43;" + l.substring(1);
706
+ if (l.startsWith(">"))
707
+ l = "&gt;" + l.substring(1);
708
+ // A link on its own followed by a colon would be read as a section or passage header
709
+ if (/^\[.*\]:$/.test(l))
710
+ l = l.substring(0, l.length - 1) + "&#58;";
711
+ return l;
712
+ });
713
+ // Collapse runs of blank lines
714
+ const collapsed = [];
715
+ for (const line of lines) {
716
+ if (line == "" && (collapsed.length == 0 || collapsed[collapsed.length - 1] == ""))
717
+ continue;
718
+ collapsed.push(line);
719
+ }
720
+ while (collapsed.length && collapsed[collapsed.length - 1] == "")
721
+ collapsed.pop();
722
+ for (let i = 0; i < collapsed.length - 1; i++) {
723
+ const line = collapsed[i];
724
+ if (line == "" || isSilent(line) || isBlockLine(line) || line.endsWith("<br>"))
725
+ continue;
726
+ // The next line that writes something, if it's straight after this one
727
+ let j = i + 1;
728
+ while (j < collapsed.length && collapsed[j] != "" && isSilent(collapsed[j]))
729
+ j++;
730
+ if (j >= collapsed.length || collapsed[j] == "" || isBlockLine(collapsed[j]))
731
+ continue;
732
+ collapsed[i] = line + "<br>";
733
+ }
734
+ // A backslash before {{ would stop Handlebars reading it as a helper
735
+ return tidyMarkup(collapsed.join("\n")).replace(/\\(?=\{\{)/g, "&#92;");
736
+ }
737
+ // Turns simple HTML emphasis into Markdown, which is easier to read and edit
738
+ function tidyMarkup(text) {
739
+ return text
740
+ .replace(/<b>([^<>*\n\s](?:[^<>*\n]*[^<>*\n\s])?)<\/b>/g, "**$1**")
741
+ .replace(/<strong>([^<>*\n\s](?:[^<>*\n]*[^<>*\n\s])?)<\/strong>/g, "**$1**")
742
+ .replace(/<i>([^<>*_\n\s](?:[^<>*_\n]*[^<>*_\n\s])?)<\/i>/g, "_$1_")
743
+ .replace(/<em>([^<>*_\n\s](?:[^<>*_\n]*[^<>*_\n\s])?)<\/em>/g, "_$1_");
744
+ }