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,305 @@
1
+ // Converts the text of a Quest gamebook page, which is HTML with Quest's text processor commands
2
+ // in it ({if ...}, {once:...}, {page:...} and so on), into Squiffy text.
3
+ import { attributeRef, display, print, quote, Unconvertible } from "../twine/expression.js";
4
+ import { sectionLink, urlLink } from "../twine/convert.js";
5
+ // Finds the next {...} the way Quest does: the first {, and the } that matches it, counting the
6
+ // ones in between. Undefined if there isn't one.
7
+ function nextCommand(text, from) {
8
+ const start = text.indexOf("{", from);
9
+ if (start == -1)
10
+ return undefined;
11
+ let depth = 1;
12
+ for (let i = start + 1; i < text.length; i++) {
13
+ if (text[i] == "{")
14
+ depth++;
15
+ else if (text[i] == "}" && --depth == 0)
16
+ return { start, end: i };
17
+ }
18
+ return undefined;
19
+ }
20
+ export function convertQuestText(text, ctx, mode) {
21
+ let result = "";
22
+ let pos = 0;
23
+ text = text.replace(/\r\n?/g, "\n");
24
+ for (;;) {
25
+ const command = nextCommand(text, pos);
26
+ if (!command)
27
+ break;
28
+ result += literal(text.substring(pos, command.start), mode);
29
+ const inner = text.substring(command.start + 1, command.end);
30
+ try {
31
+ result += convertCommand(inner, ctx, mode);
32
+ }
33
+ catch (e) {
34
+ if (!(e instanceof Unconvertible))
35
+ throw e;
36
+ result += ctx.unconvertible(`{${inner}}`, `This couldn't be converted: ${e.message}.`);
37
+ }
38
+ pos = command.end + 1;
39
+ }
40
+ return result + literal(text.substring(pos), mode);
41
+ }
42
+ // The commands Quest's gamebook text processor has, in the order it tries them
43
+ const commands = [
44
+ "if ", "either ", "here ", "nothere ", "popup:", "i:", "b:", "s:", "u:", "colour:", "color:", "back:", "object:",
45
+ "command:", "page:", "exit:", "once:", "notfirst:", "random:", "rndalt:", "img:", "counter:", "select:", "eval:", "=",
46
+ ];
47
+ function convertCommand(section, ctx, mode) {
48
+ const command = commands.find(c => section.startsWith(c));
49
+ const nested = (t) => convertQuestText(t, ctx, mode);
50
+ switch (command) {
51
+ case "if ":
52
+ return convertIf(section, ctx, mode);
53
+ case "i:":
54
+ case "b:":
55
+ case "s:":
56
+ case "u:": {
57
+ const tag = section[0];
58
+ return `<${tag}>${nested(section.substring(2))}</${tag}>`;
59
+ }
60
+ case "colour:":
61
+ case "color:":
62
+ case "back:": {
63
+ // Quest splits these at every colon, not just the first two
64
+ const parts = section.split(":");
65
+ const colour = parts[1] ?? "";
66
+ const rest = parts.slice(2).join(":");
67
+ const property = command == "back:" ? "background-color" : "color";
68
+ return `<span style="${property}: ${escapeAttribute(colour.trim())}">${nested(rest)}</span>`;
69
+ }
70
+ case "command:":
71
+ case "page:":
72
+ return convertPageLink(section, ctx, mode);
73
+ case "once:":
74
+ return `{{#if ${print(visits(ctx))} = 1}}${nested(section.substring(5))}{{/if}}`;
75
+ case "notfirst:":
76
+ return `{{#if ${print(visits(ctx))} > 1}}${nested(section.substring(9))}{{/if}}`;
77
+ case "random:":
78
+ return convertRandom(section.substring(7), ctx);
79
+ case "img:": {
80
+ const file = section.substring(4).trim();
81
+ ctx.asset(file);
82
+ return `<img src="${escapeAttribute(file)}" alt="">`;
83
+ }
84
+ case "counter:":
85
+ // Quest shows 0 for a counter that hasn't been set, as adding 0 does
86
+ return `{{= ${attributeRef(ctx.attribute(section.substring(8)))} + 0}}`;
87
+ case "popup:": {
88
+ const parts = section.substring(6).split(":");
89
+ const link = parts[0];
90
+ const content = parts.slice(1).join(":");
91
+ if (!ctx.addPassage || mode == "inline") {
92
+ ctx.approximate(`{${section}}`, "Squiffy has no popups, and this one is in a link's text, so only its link text has been kept.");
93
+ return nested(link);
94
+ }
95
+ // A passage link shows the popup's text when it's clicked
96
+ const name = ctx.addPassage(link, convertQuestText(content, ctx, "block"));
97
+ return `[${nested(link).replace(/\]/g, "&#93;").replace(/\[/g, "&#91;")}](${name})`;
98
+ }
99
+ case "either ":
100
+ case "eval:":
101
+ case "=":
102
+ throw new Unconvertible("Quest expressions in text can't be converted yet");
103
+ case "here ":
104
+ case "nothere ":
105
+ case "object:":
106
+ case "exit:":
107
+ throw new Unconvertible("it's for Quest's text adventures, not gamebooks");
108
+ case "rndalt:":
109
+ case "select:":
110
+ throw new Unconvertible(`Squiffy has nothing like {${command}}`);
111
+ }
112
+ return convertOther(section, ctx, mode);
113
+ }
114
+ // {game.score} shows an attribute. Anything else in curly brackets is shown as it is.
115
+ function convertOther(section, ctx, mode) {
116
+ const dot = section.indexOf(".");
117
+ if (dot != -1) {
118
+ const object = section.substring(0, dot);
119
+ const attribute = section.substring(dot + 1);
120
+ if (object == "game" && /^[\w ]+$/.test(attribute)) {
121
+ return display({ k: "var", name: ctx.attribute(attribute) });
122
+ }
123
+ if (/^[\w ]+$/.test(object) && /^\w+$/.test(attribute) && (object == "player" || ctx.target(object))) {
124
+ return display({ k: "var", name: ctx.attribute(objectAttribute(object, attribute)) });
125
+ }
126
+ }
127
+ return literalBraces(convertQuestText(section, ctx, mode));
128
+ }
129
+ // Text Quest shows in curly brackets, as it doesn't know the command. They're written as
130
+ // entities, so Squiffy doesn't take them for Squiffy 5 commands.
131
+ function literalBraces(inner) {
132
+ return "&#123;" + inner + "&#125;";
133
+ }
134
+ // The Squiffy attribute for an attribute of the player or a page, such as player.strength. Flags
135
+ // and counters are attributes of the game, and keep their names.
136
+ export function objectAttribute(object, attribute) {
137
+ return object == "game" ? attribute : `${object}_${attribute}`;
138
+ }
139
+ function visits(ctx) {
140
+ return { k: "call", fn: "visits", args: [{ k: "str", v: ctx.section }] };
141
+ }
142
+ // {if flag:text}, {if not flag:text}, {if counter>5:text}, {if game.flag:text}, {if Page3.visited:text}
143
+ function convertIf(section, ctx, mode) {
144
+ const command = section.substring(3);
145
+ const colon = command.indexOf(":");
146
+ // Quest shows an {if} with no text as it is
147
+ if (colon == -1)
148
+ return literalBraces(convertQuestText(section, ctx, mode));
149
+ const text = convertQuestText(command.substring(colon + 1), ctx, mode);
150
+ const condition = command.substring(0, colon);
151
+ const operator = ["<=", ">=", "<>", "<", ">", "="].find(op => condition.includes(op));
152
+ let expr;
153
+ if (!operator) {
154
+ let name = condition.trim();
155
+ let negate = false;
156
+ if (name.startsWith("not ")) {
157
+ negate = true;
158
+ name = name.substring(4).trim();
159
+ }
160
+ expr = reference(name, ctx);
161
+ if (negate)
162
+ expr = { k: "not", e: expr };
163
+ }
164
+ else {
165
+ const index = condition.indexOf(operator);
166
+ const lhs = reference(condition.substring(0, index).trim(), ctx);
167
+ const rhsText = condition.substring(index + operator.length).trim();
168
+ const rhs = /^-?\d+(\.\d+)?$/.test(rhsText) ? { k: "num", v: Number(rhsText) } : { k: "str", v: rhsText };
169
+ expr = { k: "bin", op: operator == "<>" ? "!=" : operator, l: lhs, r: rhs };
170
+ }
171
+ return `{{#if ${print(expr)}}}${text}{{/if}}`;
172
+ }
173
+ // A flag or counter, game.attribute, or page.visited, in an {if}
174
+ function reference(name, ctx) {
175
+ const dot = name.indexOf(".");
176
+ if (dot == -1)
177
+ return { k: "var", name: ctx.attribute(name) };
178
+ const object = name.substring(0, dot).trim();
179
+ const attribute = name.substring(dot + 1).trim();
180
+ if (!/^\w+$/.test(attribute))
181
+ throw new Unconvertible(`Squiffy can't read ${name}`);
182
+ if (object == "game")
183
+ return { k: "var", name: ctx.attribute(attribute) };
184
+ const target = ctx.target(object);
185
+ if (attribute == "visited") {
186
+ if (target && "section" in target)
187
+ return { k: "call", fn: "seen", args: [{ k: "str", v: target.section }] };
188
+ if (!target) {
189
+ ctx.approximate(name, `There's no page called "${object}", so this is never true, as in Quest.`);
190
+ return { k: "bool", v: false };
191
+ }
192
+ }
193
+ if (object == "player" || target)
194
+ return { k: "var", name: ctx.attribute(objectAttribute(object, attribute)) };
195
+ throw new Unconvertible(`there's nothing called "${object}" in the game`);
196
+ }
197
+ // {page:Page2}, {page:Page2:text}, and {command:Page2:text}, which does the same in a gamebook
198
+ function convertPageLink(section, ctx, mode) {
199
+ let page = section.substring(section.indexOf(":") + 1);
200
+ let text = page;
201
+ const colon = page.indexOf(":");
202
+ if (colon != -1) {
203
+ text = page.substring(colon + 1);
204
+ page = page.substring(0, colon);
205
+ }
206
+ const linkText = convertQuestText(text, ctx, "inline");
207
+ if (mode == "inline") {
208
+ ctx.approximate(`{${section}}`, "This link is in a link's text, or one of a random choice, where Squiffy can't have a link, so only its text has been kept.");
209
+ return linkText;
210
+ }
211
+ const target = ctx.target(page);
212
+ if (!target) {
213
+ ctx.approximate(`{${section}}`, `There's no page called "${page}", so this isn't a link.`);
214
+ return linkText;
215
+ }
216
+ if ("url" in target)
217
+ return urlLink(linkText, target.url);
218
+ return sectionLink(linkText, target.section);
219
+ }
220
+ // Quest's Tsplit: splits at colons that aren't inside {...}
221
+ function splitItems(text) {
222
+ const items = [];
223
+ let depth = 0;
224
+ let start = 0;
225
+ for (let i = 0; i < text.length; i++) {
226
+ if (text[i] == "{")
227
+ depth++;
228
+ else if (text[i] == "}")
229
+ depth--;
230
+ else if (text[i] == ":" && depth <= 0) {
231
+ items.push(text.substring(start, i));
232
+ start = i + 1;
233
+ }
234
+ }
235
+ items.push(text.substring(start));
236
+ return items;
237
+ }
238
+ function convertRandom(text, ctx) {
239
+ const items = splitItems(text).map(item => {
240
+ const converted = convertQuestText(item, ctx, "inline");
241
+ if (/\{\{|\[\[/.test(converted))
242
+ throw new Unconvertible("Squiffy's {{random}} can't have links or other commands in its choices");
243
+ return converted;
244
+ });
245
+ return `{{random (array${items.map(i => " " + quote(i)).join("")})}}`;
246
+ }
247
+ function escapeAttribute(s) {
248
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;");
249
+ }
250
+ // Text from the page, with no commands in it, as Squiffy text. Quest's text is HTML, not
251
+ // Markdown, so anything Markdown would read is escaped, outside HTML tags. In a page's text,
252
+ // <br/> and line breaks become Squiffy lines, and two or more of them a new paragraph.
253
+ function literal(text, mode) {
254
+ if (!text)
255
+ return "";
256
+ let result = "";
257
+ let pos = 0;
258
+ for (const tag of text.matchAll(/<\/?[A-Za-z][^<>]*>/g)) {
259
+ result += prose(text.substring(pos, tag.index));
260
+ result += tag[0].replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{\{/g, "&#123;{").replace(/\}\}/g, "}&#125;");
261
+ pos = tag.index + tag[0].length;
262
+ }
263
+ result += prose(text.substring(pos));
264
+ if (mode == "inline")
265
+ return result.replace(/\s*\n\s*/g, " ");
266
+ return result.replace(/(?:[ \t]*(?:<br\s*\/?>|\n)[ \t]*)+/gi, breaks => {
267
+ const count = (breaks.match(/<br\s*\/?>|\n/gi) ?? []).length;
268
+ return count >= 2 ? "\n\n" : "\n";
269
+ });
270
+ }
271
+ function prose(text) {
272
+ let result = "";
273
+ for (let i = 0; i < text.length; i++) {
274
+ const c = text[i];
275
+ if (c == "*")
276
+ result += "&#42;";
277
+ else if (c == "`")
278
+ result += "&#96;";
279
+ else if (c == "~")
280
+ result += "&#126;";
281
+ else if (c == "\\")
282
+ result += "&#92;";
283
+ else if (c == "[")
284
+ result += "&#91;";
285
+ else if (c == "]")
286
+ result += "&#93;";
287
+ else if (c == "_" && !(/\w/.test(text[i - 1] ?? "") && /\w/.test(text[i + 1] ?? "")))
288
+ result += "&#95;";
289
+ // A { here has no }, so Quest shows it, and the rest of the text, as it is
290
+ else if (c == "{")
291
+ result += "&#123;";
292
+ else if (c == "}")
293
+ result += "&#125;";
294
+ else
295
+ result += c;
296
+ }
297
+ return result;
298
+ }
299
+ // Lines that Markdown would read as a heading, list or quote, which in Quest are just text
300
+ export function escapeLineStarts(text) {
301
+ return text.split("\n").map(line => line
302
+ .replace(/^(\s*)#/, "$1&#35;")
303
+ .replace(/^(\s*)([-+])(\s)/, (_, space, c, after) => `${space}${c == "-" ? "&#45;" : "&#43;"}${after}`)
304
+ .replace(/^(\s*\d+)\.(\s)/, "$1&#46;$2")).join("\n");
305
+ }
package/dist/setters.d.ts CHANGED
@@ -23,6 +23,10 @@ export interface AtAttribute {
23
23
  range: Range;
24
24
  }
25
25
  export declare function findAtAttributes(file: SquiffyFile): AtAttribute[];
26
+ export declare function splitWithOffsets(setters: string): {
27
+ text: string;
28
+ offset: number;
29
+ }[];
26
30
  export declare function attributesSetIn(file: SquiffyFile, text: string): Set<string>;
27
31
  export interface UnquotedText {
28
32
  text: string;
package/dist/setters.js CHANGED
@@ -251,8 +251,9 @@ export function findAtAttributes(file) {
251
251
  return result;
252
252
  }
253
253
  // Splits a list of setters with the rules of a story that uses expressions (as splitSetters in
254
- // runtime/src/infixExpressions.ts does): on commas outside quotes and brackets. Keeps offsets.
255
- function splitWithOffsets(setters) {
254
+ // runtime/src/infixExpressions.ts does): on commas outside quotes, brackets and objects. Keeps
255
+ // offsets.
256
+ export function splitWithOffsets(setters) {
256
257
  const result = [];
257
258
  let depth = 0;
258
259
  let quote = null;
@@ -267,9 +268,9 @@ function splitWithOffsets(setters) {
267
268
  }
268
269
  else if (c === "\"" || c === "'")
269
270
  quote = c;
270
- else if (c === "(")
271
+ else if (c === "(" || c === "[" || c === "{")
271
272
  depth++;
272
- else if (c === ")")
273
+ else if (c === ")" || c === "]" || c === "}")
273
274
  depth = Math.max(0, depth - 1);
274
275
  else if (i === setters.length || (c === "," && depth === 0)) {
275
276
  result.push({ text: setters.slice(start, i), offset: start });
@@ -344,7 +345,8 @@ export function findUnquotedText(file, isSet) {
344
345
  const result = [];
345
346
  for (const site of setterSites(file)) {
346
347
  // Only plain "=": text with +=, -=, *= or /= is an error whatever it's written as
347
- const match = /^(\s*)(\w+)(\s*=(?!=)\s*)(.*?)\s*$/.exec(site.text);
348
+ // The attribute can be a value inside an object, as in hero.name = Ann (#442)
349
+ const match = /^(\s*)(\w+(?:\.\w+)*)(\s*=(?!=)\s*)(.*?)\s*$/.exec(site.text);
348
350
  if (!match)
349
351
  continue;
350
352
  const [, leading, attribute, eq, value] = match;
@@ -373,6 +375,9 @@ export function findUnquotedText(file, isSet) {
373
375
  export const BUILT_IN_ATTRIBUTES = new Map([
374
376
  // #377: stories written before Squiffy counted turns often kept their own count called "turns"
375
377
  ["turns", "the number of links clicked in the story so far"],
378
+ // #56: and a story may have kept track of where the player had been
379
+ ["previous", "the section or passage the player saw just before this one"],
380
+ ["previous_section", "the section the player was in before this one"],
376
381
  ]);
377
382
  // Finds where a file sets one of the BUILT_IN_ATTRIBUTES: on the left of a setter, in @inc, @dec
378
383
  // and @unset, and as the quoted first argument of set, inc, dec or unset, which covers
@@ -1,5 +1,5 @@
1
1
  import type { Location } from "./language-service.js";
2
- import type { Diagnostic, EmbedNode, GotoNode, LinkNode, PassageNode, Position, SectionNode, SquiffyFile } from "./syntax.js";
2
+ import type { DeactivateNode, Diagnostic, EmbedNode, GotoNode, LinkNode, PassageNode, Position, SectionNode, SquiffyFile } from "./syntax.js";
3
3
  export interface StoryGraph {
4
4
  nodes: GraphNode[];
5
5
  edges: GraphEdge[];
@@ -40,6 +40,7 @@ export interface GraphUsage {
40
40
  link?: LinkNode;
41
41
  embed?: EmbedNode;
42
42
  goto?: GotoNode;
43
+ deactivate?: DeactivateNode;
43
44
  }
44
45
  export type GraphTarget = {
45
46
  kind: "section";
@@ -173,6 +173,8 @@ export function buildStoryGraph(source) {
173
173
  return ranges.some(r => comparePositions(r.start, position) <= 0 && comparePositions(position, r.end) <= 0);
174
174
  };
175
175
  for (const usage of source.usages) {
176
+ if (usage.deactivate)
177
+ continue;
176
178
  const from = containerIds.get(usage.container);
177
179
  // Not part of the story, or replaced by a later section or passage of the same name
178
180
  if (from === undefined)
package/dist/syntax.d.ts CHANGED
@@ -7,7 +7,7 @@ export interface Range {
7
7
  end: Position;
8
8
  }
9
9
  export type DiagnosticSeverity = "error" | "warning" | "hint";
10
- export type DiagnosticCode = "squiffy/passage-without-section" | "squiffy/text-in-ui-block" | "squiffy/content-before-section" | "squiffy/v5-syntax" | "squiffy/at-attribute" | "squiffy/unquoted-text" | "squiffy/built-in-attribute" | "squiffy/external-files-unavailable" | "squiffy/no-next-section" | "squiffy/unknown-embed" | "squiffy/unknown-goto" | "squiffy/unknown-section-link" | "squiffy/unknown-passage-link" | "squiffy/duplicate-section" | "squiffy/duplicate-passage" | "squiffy/not-in-main-file" | "squiffy/redundant-import" | "squiffy/project-file" | "squiffy/unreachable-section" | "squiffy/dead-end";
10
+ export type DiagnosticCode = "squiffy/passage-without-section" | "squiffy/text-in-ui-block" | "squiffy/content-before-section" | "squiffy/v5-syntax" | "squiffy/at-attribute" | "squiffy/unquoted-text" | "squiffy/built-in-attribute" | "squiffy/external-files-unavailable" | "squiffy/no-next-section" | "squiffy/unknown-embed" | "squiffy/unknown-goto" | "squiffy/unknown-deactivate" | "squiffy/unknown-section-link" | "squiffy/unknown-passage-link" | "squiffy/duplicate-section" | "squiffy/duplicate-passage" | "squiffy/not-in-main-file" | "squiffy/repeat-not-in-passage" | "squiffy/redundant-import" | "squiffy/project-file" | "squiffy/unreachable-section" | "squiffy/dead-end";
11
11
  export interface Diagnostic {
12
12
  file: string;
13
13
  range: Range;
@@ -35,6 +35,7 @@ export interface SectionNode {
35
35
  links: LinkNode[];
36
36
  embeds: EmbedNode[];
37
37
  gotos: GotoNode[];
38
+ deactivates: DeactivateNode[];
38
39
  }
39
40
  export interface PassageNode {
40
41
  type: "passage";
@@ -46,6 +47,7 @@ export interface PassageNode {
46
47
  links: LinkNode[];
47
48
  embeds: EmbedNode[];
48
49
  gotos: GotoNode[];
50
+ deactivates: DeactivateNode[];
49
51
  }
50
52
  export interface SnippetNode {
51
53
  type: "snippet";
@@ -111,10 +113,27 @@ export interface ClearNode {
111
113
  type: "clear";
112
114
  range: Range;
113
115
  }
116
+ export interface RepeatNode {
117
+ type: "repeat";
118
+ range: Range;
119
+ }
114
120
  export interface EndNode {
115
121
  type: "end";
116
122
  range: Range;
117
123
  }
124
+ export interface SoundNode {
125
+ type: "sound";
126
+ directive: "music" | "sound";
127
+ value: string;
128
+ valueRange: Range;
129
+ range: Range;
130
+ }
131
+ export interface ClassNode {
132
+ type: "class";
133
+ value: string;
134
+ valueRange: Range;
135
+ range: Range;
136
+ }
118
137
  export interface AttributeNode {
119
138
  type: "attribute";
120
139
  directive: "set" | "unset" | "inc" | "dec";
@@ -134,7 +153,7 @@ export interface TextNode {
134
153
  text: string;
135
154
  range: Range;
136
155
  }
137
- export type StatementNode = SeparatorNode | TitleNode | StartNode | ImportNode | UiBlockStartNode | UiFileNode | ClearNode | EndNode | AttributeNode | JsNode | TextNode;
156
+ export type StatementNode = SeparatorNode | TitleNode | StartNode | ImportNode | UiBlockStartNode | UiFileNode | ClearNode | RepeatNode | EndNode | AttributeNode | SoundNode | ClassNode | JsNode | TextNode;
138
157
  export interface LinkNode {
139
158
  type: "link";
140
159
  linkType: "section" | "passage";
@@ -150,6 +169,12 @@ export interface EmbedNode {
150
169
  range: Range;
151
170
  nameRange: Range;
152
171
  }
172
+ export interface DeactivateNode {
173
+ type: "deactivate";
174
+ name: string;
175
+ range: Range;
176
+ nameRange: Range;
177
+ }
153
178
  export interface GotoNode {
154
179
  type: "goto";
155
180
  name: string;
package/dist/text.d.ts CHANGED
@@ -16,6 +16,7 @@ export interface TextEmbed {
16
16
  nameEnd: number;
17
17
  }
18
18
  export type TextGoto = TextEmbed;
19
+ export type TextDeactivate = TextEmbed;
19
20
  export interface NoNextSection {
20
21
  display: string;
21
22
  start: number;
@@ -26,6 +27,7 @@ export interface TransformResult {
26
27
  links: TextLink[];
27
28
  embeds: TextEmbed[];
28
29
  gotos: TextGoto[];
30
+ deactivates: TextDeactivate[];
29
31
  noNextSection: NoNextSection[];
30
32
  }
31
33
  export declare const balancedTarget: string;
package/dist/text.js CHANGED
@@ -170,19 +170,27 @@ export function transformText(text, getNextSectionName, expressions = false) {
170
170
  };
171
171
  // Handlebars expressions can contain square brackets that aren't links, such as
172
172
  // {{someArray.[1]}} or {{someHelper "[x]"}}, so swap each one for a placeholder while
173
- // converting links. Text between block helpers like {{#if x}}...{{/if}} is still converted.
173
+ // converting links. Text between block helpers like {{#if x}}...{{/if}} is still converted. A
174
+ // comment ends at --}}, and can have }} and links in it before that.
174
175
  const mustaches = [];
175
- input.replace(/\{\{\{[\s\S]*?\}\}\}|\{\{[\s\S]*?\}\}/g, ([match]) => {
176
+ input.replace(/\{\{!--[\s\S]*?--\}\}|\{\{\{[\s\S]*?\}\}\}|\{\{[\s\S]*?\}\}/g, ([match]) => {
176
177
  mustaches.push(match);
177
178
  return `${mustaches.length - 1}`;
178
179
  });
179
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
+ };
180
187
  // A link's target, inside its (...). With expressions, a setter can have brackets in it, e.g.
181
188
  // [[Buy]](shop, gold -= (price - 1) * 2), so the target can contain balanced brackets, up to
182
189
  // three deep. Without, it ends at the first ")", as in Squiffy 6.
183
190
  const target = expressions ? balancedTarget : "(?:.*?)";
184
- // nextSectionLinkRegex matches [[text>]] - a link to the next section
185
- const nextSectionLinkRegex = /\[\[([^\]]*?)>\]\]/g;
191
+ // nextSectionLinkRegex matches [[text>]] - a link to the next section. Followed by a (target),
192
+ // it's a named link whose text ends with >, such as [[<i>Go in</i>]](cave).
193
+ const nextSectionLinkRegex = /\[\[([^\]]*?)>\]\](?!\()/g;
186
194
  input.replace(nextSectionLinkRegex, ([match, rawText], offset) => {
187
195
  const text = restore(rawText);
188
196
  const nextSectionName = getNextSectionName();
@@ -191,7 +199,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
191
199
  return `[[${text}]]`; // fallback
192
200
  }
193
201
  addLink({ linkType: "section", form: "next", text, target: "" }, offset, match.length, offset + 2 + rawText.length, 0);
194
- return `{{section "${escapeForHandlebarsString(nextSectionName)}" text="${escapeForHandlebarsString(text)}"}}`;
202
+ return converted(`{{section "${escapeForHandlebarsString(nextSectionName)}" text="${escapeForHandlebarsString(text)}"}}`);
195
203
  });
196
204
  // namedNextSectionLinkRegex matches [[text]](>) or [[text]](>, setter=value)
197
205
  // - a named link where target starts with >
@@ -207,7 +215,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
207
215
  addLink({ linkType: "section", form: "next", text, target: rest }, offset, match.length, offset + 2 + rawText.length + 4, rawRest.length);
208
216
  // rest could be empty or ", setter=value"
209
217
  const parsedName = getAdditionalLinkParameters(nextSectionName + rest, expressions);
210
- return `{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
218
+ return converted(`{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
211
219
  });
212
220
  // namedSectionLinkRegex matches:
213
221
  // open [[
@@ -222,7 +230,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
222
230
  const name = restore(rawName);
223
231
  addLink({ linkType: "section", form: "named", text, target: name }, offset, match.length, offset + 2 + rawText.length + 3, rawName.length);
224
232
  const parsedName = getAdditionalLinkParameters(name, expressions);
225
- return `{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
233
+ return converted(`{{section "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
226
234
  });
227
235
  // namedPassageLinkRegex matches:
228
236
  // not preceded by ! (to avoid matching image links like ![alt](src))
@@ -238,7 +246,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
238
246
  const name = restore(rawName);
239
247
  addLink({ linkType: "passage", form: "named", text, target: name }, offset, match.length, offset + 1 + rawText.length + 2, rawName.length);
240
248
  const parsedName = getAdditionalLinkParameters(name, expressions);
241
- return `{{passage "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`;
249
+ return converted(`{{passage "${escapeForHandlebarsString(parsedName.target)}" text="${escapeForHandlebarsString(text)}"${parsedName.additionalParameters}}}`);
242
250
  });
243
251
  // unnamedSectionLinkRegex matches:
244
252
  // open [[
@@ -248,7 +256,7 @@ export function transformText(text, getNextSectionName, expressions = false) {
248
256
  input.replace(unnamedSectionLinkRegex, ([match, rawName], offset) => {
249
257
  const name = restore(rawName);
250
258
  addLink({ linkType: "section", form: "unnamed", target: name }, offset, match.length, offset + 2, rawName.length);
251
- return `{{section "${escapeForHandlebarsString(name)}"}}`;
259
+ return converted(`{{section "${escapeForHandlebarsString(name)}"}}`);
252
260
  });
253
261
  // unnamedPassageLinkRegex matches:
254
262
  // not preceded by ! (to avoid matching image links like ![alt])
@@ -260,13 +268,14 @@ export function transformText(text, getNextSectionName, expressions = false) {
260
268
  input.replace(unnamedPassageLinkRegex, ([match, rawName, suffix], offset) => {
261
269
  const name = restore(rawName);
262
270
  addLink({ linkType: "passage", form: "unnamed", target: name }, offset, match.length - suffix.length, offset + 1, rawName.length);
263
- return `{{passage "${escapeForHandlebarsString(name)}"}}${suffix}`;
271
+ return converted(`{{passage "${escapeForHandlebarsString(name)}"}}`) + suffix;
264
272
  });
265
273
  input.replace(/(\d+)/g, ([, i]) => mustaches[Number(i)]);
266
- // Matches {{embed "name"}} or {{goto 'name'}} with a literal name.
267
- 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) => {
268
277
  const result = [];
269
- const regex = new RegExp(`\\{\\{~?\\s*${helper}\\s+(["'])(.*?)\\1`, "g");
278
+ const regex = new RegExp(`\\{\\{~?\\s*${block ? "#?" : ""}${helper}\\s+(["'])(.*?)\\1`, "g");
270
279
  let match;
271
280
  while ((match = regex.exec(input.value))) {
272
281
  const start = match.index;
@@ -283,8 +292,8 @@ export function transformText(text, getNextSectionName, expressions = false) {
283
292
  }
284
293
  return result;
285
294
  };
286
- embeds.push(...findNamed("embed"));
287
- return { output: input.value, links, embeds, gotos: findNamed("goto"), noNextSection };
295
+ embeds.push(...findNamed("embed", true));
296
+ return { output: input.value, links, embeds, gotos: findNamed("goto"), deactivates: findNamed("deactivate"), noNextSection };
288
297
  }
289
298
  // Returns a function that converts an offset into lines.join("\n") to a position in the source file.
290
299
  export function positionMapper(lines, lineLengths) {
@@ -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;