squiffy-runtime 6.0.0-beta.3 → 6.0.0-beta.4

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.
@@ -2,10 +2,10 @@ import { default as Handlebars } from 'handlebars';
2
2
  import { Section, Story } from './types.js';
3
3
  import { State } from './state.js';
4
4
  export declare class TextProcessor {
5
- story: Story;
5
+ getStory: () => Story;
6
6
  state: State;
7
7
  getCurrentSection: () => Section;
8
8
  handlebars: typeof Handlebars;
9
- constructor(story: Story, state: State, currentSection: () => Section);
9
+ constructor(story: () => Story, state: State, currentSection: () => Section);
10
10
  process(text: string, inline: boolean): string;
11
11
  }
package/dist/updater.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Story } from './types.js';
2
- export declare function updateStory(oldStory: Story, newStory: Story, outputElement: HTMLElement, ui: any, disableLink: (link: Element) => void, processAttributes: (attributes: string[]) => void): void;
1
+ import { Section, Story } from './types.js';
2
+ export declare function updateStory(oldStory: Story, newStory: Story, outputElement: HTMLElement, processText: (text: string, section: Section) => string, disableLink: (link: Element) => void, processAttributes: (attributes: string[]) => void): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "squiffy-runtime",
3
- "version": "6.0.0-beta.3",
3
+ "version": "6.0.0-beta.4",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/textadventures/squiffy.git",
@@ -36,9 +36,9 @@
36
36
  "@types/jsdom": "^30.0.0",
37
37
  "css.escape": "^1.5.1",
38
38
  "esbuild": "^0.28.2",
39
- "global-jsdom": "^29.0.0",
39
+ "global-jsdom": "^30.0.0",
40
40
  "jsdom": "^30.0.1",
41
- "squiffy-compiler": "^6.0.0-beta.3",
41
+ "squiffy-compiler": "^6.0.0-beta.4",
42
42
  "typescript": "^6.0.3",
43
43
  "vite": "^8.2.2",
44
44
  "vite-plugin-dts": "^5.1.0"
@@ -48,5 +48,5 @@
48
48
  "handlebars": "^4.7.10",
49
49
  "marked": "^18.0.11"
50
50
  },
51
- "gitHead": "d932cf0684a7fa941dc8097bcc430761949e07fb"
51
+ "gitHead": "3c52f3730cf2a7f59f3a5ac76db42abd7024fb83"
52
52
  }
package/src/animation.ts CHANGED
@@ -37,6 +37,10 @@ export class Animation {
37
37
  this.linkAnimations.set(link, fn);
38
38
  }
39
39
 
40
+ removeLinkAnimation(link: HTMLElement) {
41
+ this.linkAnimations.delete(link);
42
+ }
43
+
40
44
  runLinkAnimation(link: HTMLElement) {
41
45
  const fn = this.linkAnimations.get(link);
42
46
  if (fn) {
@@ -0,0 +1,187 @@
1
+ import { expect, test, describe } from "vitest";
2
+ import { rewriteInfixCondition, rewriteInfixExpressions } from "./infixExpressions.js";
3
+
4
+ describe("rewriteInfixCondition", () => {
5
+ test.each([
6
+ ["gender = \"male\"", "(eq gender \"male\")"],
7
+ ["gender == \"male\"", "(eq gender \"male\")"],
8
+ ["gender != \"male\"", "(ne gender \"male\")"],
9
+ ["score > 100", "(gt score 100)"],
10
+ ["score < 100", "(lt score 100)"],
11
+ ["score >= 100", "(gte score 100)"],
12
+ ["score <= 100", "(lte score 100)"],
13
+ ["a and b", "(and a b)"],
14
+ ["a && b", "(and a b)"],
15
+ ["a or b", "(or a b)"],
16
+ ["a || b", "(or a b)"],
17
+ ["not a", "(not a)"],
18
+ ["!a", "(not a)"],
19
+ ["! a", "(not a)"],
20
+ ["not not a", "(not (not a))"],
21
+ ])("operator: %s", (input, expected) => {
22
+ expect(rewriteInfixCondition(input)).toBe(expected);
23
+ });
24
+
25
+ test.each([
26
+ ["score>100", "(gt score 100)"],
27
+ ["gender=\"male\"", "(eq gender \"male\")"],
28
+ ["a&&b||c", "(or (and a b) c)"],
29
+ ["score>=-5", "(gte score -5)"],
30
+ ])("no spaces: %s", (input, expected) => {
31
+ expect(rewriteInfixCondition(input)).toBe(expected);
32
+ });
33
+
34
+ test.each([
35
+ ["a and b and c", "(and a b c)"],
36
+ ["a or b or c", "(or a b c)"],
37
+ ["a or b and c", "(or a (and b c))"],
38
+ ["a and b or c", "(or (and a b) c)"],
39
+ ["score > 100 and has_key", "(and (gt score 100) has_key)"],
40
+ ["x = 1 or y != 2 and z", "(or (eq x 1) (and (ne y 2) z))"],
41
+ ["not a and b", "(and (not a) b)"],
42
+ ["not a = b", "(not (eq a b))"],
43
+ ["not gender = \"male\"", "(not (eq gender \"male\"))"],
44
+ ["not score > 100 and has_key", "(and (not (gt score 100)) has_key)"],
45
+ ["!a = b", "(not (eq a b))"],
46
+ ["not a = b or not c", "(or (not (eq a b)) (not c))"],
47
+ ["(not a) = b", "(eq (not a) b)"],
48
+ ["a = (not b)", "(eq a (not b))"],
49
+ ["not (seen \"intro\") or count >= 3", "(or (not (seen \"intro\")) (gte count 3))"],
50
+ ])("precedence: %s", (input, expected) => {
51
+ expect(rewriteInfixCondition(input)).toBe(expected);
52
+ });
53
+
54
+ test.each([
55
+ ["(a or b) and c", "(and (or a b) c)"],
56
+ ["not (a = 1)", "(not (eq a 1))"],
57
+ ["((a))", null],
58
+ ["((a or b)) and c", "(and (or a b) c)"],
59
+ ["(score > 100) = true", "(eq (gt score 100) true)"],
60
+ ])("grouping: %s", (input, expected) => {
61
+ expect(rewriteInfixCondition(input)).toBe(expected);
62
+ });
63
+
64
+ test.each([
65
+ ["name = 'Bob'", "(eq name 'Bob')"],
66
+ ["name = \"a > b and c\"", "(eq name \"a > b and c\")"],
67
+ ["done = true", "(eq done true)"],
68
+ ["x = null", "(eq x null)"],
69
+ ["score > 1.5", "(gt score 1.5)"],
70
+ ["player.score > 10", "(gt player.score 10)"],
71
+ ["[my score] > 10", "(gt [my score] 10)"],
72
+ ["@index > 0", "(gt @index 0)"],
73
+ ["(length \"rounds\") > 0", "(gt (length \"rounds\") 0)"],
74
+ ["(contains \"inventory\" \"key\") and door = \"open\"", "(and (contains \"inventory\" \"key\") (eq door \"open\"))"],
75
+ ["(and a b) or c", "(or (and a b) c)"],
76
+ ["(at (array \"a\" \"b\")) or x", "(or (at (array \"a\" \"b\")) x)"],
77
+ ["(get (concat a b)) = 1", "(eq (get (concat a b)) 1)"],
78
+ ["(lookup obj key=1) = 2", "(eq (lookup obj key=1) 2)"],
79
+ ["(seen (x)) and y", "(and (seen x) y)"],
80
+ ])("operands: %s", (input, expected) => {
81
+ expect(rewriteInfixCondition(input)).toBe(expected);
82
+ });
83
+
84
+ test.each([
85
+ "has_key",
86
+ " has_key ",
87
+ "(eq gender \"male\")",
88
+ "(and (gt score 100) has_key)",
89
+ "(seen \"intro\")",
90
+ "(at (array \"start\" \"other\"))",
91
+ "x includeZero=true",
92
+ "(gt (length \"rounds\") 0)",
93
+ "\"string\"",
94
+ "42",
95
+ ])("passes through prefix syntax: %s", (input) => {
96
+ expect(rewriteInfixCondition(input)).toBeNull();
97
+ });
98
+
99
+ test("not with prefix syntax is equivalent", () => {
100
+ expect(rewriteInfixCondition("(not game_over)")).toBe("(not game_over)");
101
+ });
102
+
103
+ test("infix inside a helper's arguments", () => {
104
+ expect(rewriteInfixCondition("(foo (a > 1))")).toBe("(foo (gt a 1))");
105
+ });
106
+
107
+ test.each([
108
+ ["score >", "expected a value after '>'"],
109
+ ["a and", "expected a value after 'and'"],
110
+ ["a or", "expected a value after 'or'"],
111
+ ["not", "expected a value after 'not'"],
112
+ ["> 100", "expected a value before '>'"],
113
+ ["and b", "expected a value before 'and'"],
114
+ ["(a > 1", "expected ')' but found end of expression"],
115
+ ["a > 1)", "unexpected ')'"],
116
+ ["a > 1 b", "unexpected 'b'"],
117
+ ["1 < x < 10", "comparisons can't be chained"],
118
+ ["a = = b", "expected a value before '='"],
119
+ ["a > () ", "unexpected ')'"],
120
+ ["a = not b", "'not' must be inside parentheses here, e.g. (not value)"],
121
+ ["a = !b", "'!' must be inside parentheses here, e.g. (!value)"],
122
+ ])("error: %s", (input, message) => {
123
+ expect(() => rewriteInfixCondition(input)).toThrow(message);
124
+ });
125
+
126
+ test("error message includes the condition", () => {
127
+ expect(() => rewriteInfixCondition(" score > ")).toThrow("Invalid condition \"score >\": expected a value after '>'");
128
+ });
129
+
130
+ test("malformed prefix syntax is left for Handlebars to report", () => {
131
+ expect(rewriteInfixCondition("a b")).toBeNull();
132
+ expect(rewriteInfixCondition("(eq a")).toBeNull();
133
+ expect(rewriteInfixCondition("\"unterminated")).toBeNull();
134
+ });
135
+ });
136
+
137
+ describe("rewriteInfixExpressions", () => {
138
+ test("#if", () => {
139
+ expect(rewriteInfixExpressions("{{#if score > 100 and has_key}}yes{{/if}}"))
140
+ .toBe("{{#if (and (gt score 100) has_key)}}yes{{/if}}");
141
+ });
142
+
143
+ test("#unless", () => {
144
+ expect(rewriteInfixExpressions("{{#unless not (seen \"intro\") or count >= 3}}x{{/unless}}"))
145
+ .toBe("{{#unless (or (not (seen \"intro\")) (gte count 3))}}x{{/unless}}");
146
+ });
147
+
148
+ test("else if / else unless", () => {
149
+ expect(rewriteInfixExpressions("{{#if a = 1}}one{{else if a = 2}}two{{else unless a = 3}}not three{{else}}three{{/if}}"))
150
+ .toBe("{{#if (eq a 1)}}one{{else if (eq a 2)}}two{{else unless (eq a 3)}}not three{{else}}three{{/if}}");
151
+ });
152
+
153
+ test("whitespace control", () => {
154
+ expect(rewriteInfixExpressions("{{~#if a > 1~}}x{{~else if a < 0 ~}}y{{/if}}"))
155
+ .toBe("{{~#if (gt a 1)~}}x{{~else if (lt a 0)~}}y{{/if}}");
156
+ });
157
+
158
+ test("!x with no space after the helper name", () => {
159
+ expect(rewriteInfixExpressions("{{#if !x}}y{{/if}}")).toBe("{{#if (not x)}}y{{/if}}");
160
+ });
161
+
162
+ test("}} inside a string", () => {
163
+ expect(rewriteInfixExpressions("{{#if x = \"}}\"}}y{{/if}}")).toBe("{{#if (eq x \"}}\")}}y{{/if}}");
164
+ });
165
+
166
+ test("leaves prefix syntax and other text untouched", () => {
167
+ const text = "Score: {{score}}. {{#if (gt score 100)}}High{{/if}} {{#each items}}{{this}}{{/each}} a > b";
168
+ expect(rewriteInfixExpressions(text)).toBe(text);
169
+ });
170
+
171
+ test("leaves escaped mustaches untouched", () => {
172
+ expect(rewriteInfixExpressions("\\{{#if a > 1}}")).toBe("\\{{#if a > 1}}");
173
+ expect(rewriteInfixExpressions("\\\\{{#if a > 1}}x{{/if}}")).toBe("\\\\{{#if (gt a 1)}}x{{/if}}");
174
+ });
175
+
176
+ test("doesn't match helpers that only start with if", () => {
177
+ expect(rewriteInfixExpressions("{{#iffy a > 1}}")).toBe("{{#iffy a > 1}}");
178
+ });
179
+
180
+ test("multiline", () => {
181
+ expect(rewriteInfixExpressions("{{#if a > 1\n and b}}\nx\n{{/if}}")).toBe("{{#if (and (gt a 1) b)}}\nx\n{{/if}}");
182
+ });
183
+
184
+ test("throws for malformed infix", () => {
185
+ expect(() => rewriteInfixExpressions("{{#if score >}}x{{/if}}")).toThrow("Invalid condition \"score >\"");
186
+ });
187
+ });
@@ -0,0 +1,323 @@
1
+ // Rewrites infix conditions in {{#if}}, {{#unless}}, {{else if}} and {{else unless}}
2
+ // into the equivalent prefix helper calls, before the text reaches Handlebars. e.g.
3
+ // {{#if score > 100 and has_key}} -> {{#if (and (gt score 100) has_key)}}
4
+ //
5
+ // Precedence, from tightest to loosest: comparisons, not/!, and/&&, or/||. So "not" applies to
6
+ // a whole comparison, as it reads in English: not gender = "male" means not (gender = "male").
7
+ // Conditions that don't use any infix operator are passed through unchanged.
8
+
9
+ type TokenType = "op" | "(" | ")" | "value" | "ident";
10
+
11
+ interface Token {
12
+ type: TokenType;
13
+ text: string;
14
+ }
15
+
16
+ type Node =
17
+ | { kind: "raw", text: string }
18
+ | { kind: "call", name: string, args: Node[] };
19
+
20
+ const comparisonHelpers: Record<string, string> = {
21
+ "=": "eq",
22
+ "==": "eq",
23
+ "!=": "ne",
24
+ ">": "gt",
25
+ "<": "lt",
26
+ ">=": "gte",
27
+ "<=": "lte",
28
+ };
29
+
30
+ const symbolicOps = ["==", "!=", ">=", "<=", "&&", "||", "=", ">", "<", "!"];
31
+ const keywordOps = ["and", "or", "not"];
32
+ const literals = ["true", "false", "null", "undefined"];
33
+
34
+ // Characters that end an identifier/path. "[" starts a Handlebars literal segment,
35
+ // e.g. [my attribute], which may contain any of these.
36
+ const identTerminators = new Set([..." \t\r\n!\"'()<>=&|{}~"]);
37
+
38
+ class ExpressionError extends Error {}
39
+
40
+ function tokenize(expr: string): Token[] {
41
+ const tokens: Token[] = [];
42
+ let i = 0;
43
+ while (i < expr.length) {
44
+ const c = expr[i];
45
+ if (/\s/.test(c)) {
46
+ i++;
47
+ continue;
48
+ }
49
+ if (c === "(" || c === ")") {
50
+ tokens.push({ type: c, text: c });
51
+ i++;
52
+ continue;
53
+ }
54
+ if (c === "\"" || c === "'") {
55
+ let j = i + 1;
56
+ while (j < expr.length && expr[j] !== c) {
57
+ if (expr[j] === "\\") j++;
58
+ j++;
59
+ }
60
+ if (j >= expr.length) {
61
+ throw new ExpressionError("unterminated string");
62
+ }
63
+ tokens.push({ type: "value", text: expr.slice(i, j + 1) });
64
+ i = j + 1;
65
+ continue;
66
+ }
67
+ const op = symbolicOps.find(o => expr.startsWith(o, i));
68
+ if (op) {
69
+ tokens.push({ type: "op", text: op });
70
+ i += op.length;
71
+ continue;
72
+ }
73
+ let j = i;
74
+ while (j < expr.length && !identTerminators.has(expr[j])) {
75
+ if (expr[j] === "[") {
76
+ const close = expr.indexOf("]", j);
77
+ if (close === -1) {
78
+ throw new ExpressionError("missing ']'");
79
+ }
80
+ j = close;
81
+ }
82
+ j++;
83
+ }
84
+ if (j === i) {
85
+ throw new ExpressionError(`unexpected '${c}'`);
86
+ }
87
+ const word = expr.slice(i, j);
88
+ if (keywordOps.includes(word)) {
89
+ tokens.push({ type: "op", text: word });
90
+ } else if (literals.includes(word) || /^-?\d+(\.\d+)?$/.test(word)) {
91
+ tokens.push({ type: "value", text: word });
92
+ } else {
93
+ tokens.push({ type: "ident", text: word });
94
+ }
95
+ i = j;
96
+ }
97
+ return tokens;
98
+ }
99
+
100
+ class Parser {
101
+ private pos = 0;
102
+ usedInfix = false;
103
+
104
+ constructor(private tokens: Token[]) {}
105
+
106
+ private peek(offset = 0): Token | undefined {
107
+ return this.tokens[this.pos + offset];
108
+ }
109
+
110
+ private next(): Token {
111
+ return this.tokens[this.pos++];
112
+ }
113
+
114
+ private isOp(token: Token | undefined, ...ops: string[]) {
115
+ return token?.type === "op" && ops.includes(token.text);
116
+ }
117
+
118
+ private startsPrimary(token: Token | undefined) {
119
+ return token?.type === "ident" || token?.type === "value" || token?.type === "(";
120
+ }
121
+
122
+ private describe(token: Token | undefined) {
123
+ return token ? `'${token.text}'` : "end of expression";
124
+ }
125
+
126
+ // Top level: an expression, optionally followed by hash arguments (e.g. includeZero=true)
127
+ parseCondition(): Node[] {
128
+ const result = [this.parseOr()];
129
+ while (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
130
+ result.push(this.parseHashPair());
131
+ }
132
+ if (this.peek()) {
133
+ throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
134
+ }
135
+ return result;
136
+ }
137
+
138
+ private parseHashPair(): Node {
139
+ const key = this.next().text;
140
+ this.next(); // "="
141
+ return { kind: "raw", text: `${key}=${emit(this.parsePrimary())}` };
142
+ }
143
+
144
+ private parseOr(): Node {
145
+ return this.parseChain(["or", "||"], "or", () => this.parseAnd());
146
+ }
147
+
148
+ private parseAnd(): Node {
149
+ return this.parseChain(["and", "&&"], "and", () => this.parseNot());
150
+ }
151
+
152
+ private parseChain(ops: string[], helper: string, parseOperand: () => Node): Node {
153
+ const operands = [parseOperand()];
154
+ while (this.isOp(this.peek(), ...ops)) {
155
+ const op = this.next().text;
156
+ if (!this.peek()) {
157
+ throw new ExpressionError(`expected a value after '${op}'`);
158
+ }
159
+ operands.push(parseOperand());
160
+ }
161
+ if (operands.length === 1) return operands[0];
162
+ this.usedInfix = true;
163
+ return { kind: "call", name: helper, args: operands };
164
+ }
165
+
166
+ private parseNot(): Node {
167
+ if (this.isOp(this.peek(), "not", "!")) {
168
+ const op = this.next().text;
169
+ if (!this.peek()) {
170
+ throw new ExpressionError(`expected a value after '${op}'`);
171
+ }
172
+ this.usedInfix = true;
173
+ return { kind: "call", name: "not", args: [this.parseNot()] };
174
+ }
175
+ return this.parseComparison();
176
+ }
177
+
178
+ private parseComparison(): Node {
179
+ const left = this.parsePrimary();
180
+ const opToken = this.peek();
181
+ if (opToken?.type !== "op" || !(opToken.text in comparisonHelpers)) {
182
+ return left;
183
+ }
184
+ this.next();
185
+ if (!this.peek()) {
186
+ throw new ExpressionError(`expected a value after '${opToken.text}'`);
187
+ }
188
+ const right = this.parsePrimary();
189
+ const following = this.peek();
190
+ if (following?.type === "op" && following.text in comparisonHelpers) {
191
+ throw new ExpressionError(`comparisons can't be chained (at '${following.text}'), use "and" to combine them`);
192
+ }
193
+ this.usedInfix = true;
194
+ return { kind: "call", name: comparisonHelpers[opToken.text], args: [left, right] };
195
+ }
196
+
197
+ private parsePrimary(): Node {
198
+ const token = this.peek();
199
+ if (token?.type === "ident" || token?.type === "value") {
200
+ this.next();
201
+ return { kind: "raw", text: token.text };
202
+ }
203
+ if (token?.type === "(") {
204
+ this.next();
205
+ const node = this.isHelperCall() ? this.parseHelperCall() : this.parseOr();
206
+ if (this.peek()?.type !== ")") {
207
+ throw new ExpressionError(`expected ')' but found ${this.describe(this.peek())}`);
208
+ }
209
+ this.next();
210
+ return node;
211
+ }
212
+ if (this.isOp(token, "not", "!")) {
213
+ const example = token?.text === "!" ? "!value" : "not value";
214
+ throw new ExpressionError(`'${token?.text}' must be inside parentheses here, e.g. (${example})`);
215
+ }
216
+ if (token?.type === "op") {
217
+ throw new ExpressionError(`expected a value before '${token.text}'`);
218
+ }
219
+ throw new ExpressionError(token ? `unexpected ${this.describe(token)}` : "expected a value");
220
+ }
221
+
222
+ // Inside parentheses, decide between an existing prefix helper call like (seen "intro")
223
+ // or (and a b), and an infix group like (score > 100).
224
+ private isHelperCall() {
225
+ const first = this.peek();
226
+ const second = this.peek(1);
227
+ if (this.isOp(first, "and", "or")) return true;
228
+ return first?.type === "ident" && this.startsPrimary(second);
229
+ }
230
+
231
+ private parseHelperCall(): Node {
232
+ const name = this.next().text;
233
+ const args: Node[] = [];
234
+ while (this.peek() && this.peek()?.type !== ")") {
235
+ if (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
236
+ args.push(this.parseHashPair());
237
+ } else {
238
+ args.push(this.parsePrimary());
239
+ }
240
+ }
241
+ return { kind: "call", name, args };
242
+ }
243
+ }
244
+
245
+ function emit(node: Node): string {
246
+ if (node.kind === "raw") return node.text;
247
+ return `(${node.name} ${node.args.map(emit).join(" ")})`;
248
+ }
249
+
250
+ // Rewrites a single condition. Returns null if it doesn't use infix syntax.
251
+ export function rewriteInfixCondition(condition: string): string | null {
252
+ let tokens: Token[];
253
+ try {
254
+ tokens = tokenize(condition);
255
+ } catch {
256
+ // Leave anything we can't tokenize for Handlebars to report
257
+ return null;
258
+ }
259
+ const hasOperators = tokens.some(t => t.type === "op");
260
+ const parser = new Parser(tokens);
261
+ let nodes: Node[];
262
+ let error: ExpressionError | null = null;
263
+ try {
264
+ nodes = parser.parseCondition();
265
+ } catch (e) {
266
+ if (!hasOperators || !(e instanceof ExpressionError)) return null;
267
+ error = e;
268
+ nodes = [];
269
+ }
270
+ if (error) {
271
+ throw new Error(`Invalid condition "${condition.trim()}": ${error.message}`);
272
+ }
273
+ if (!parser.usedInfix) return null;
274
+ return nodes.map(emit).join(" ");
275
+ }
276
+
277
+ const blockStart = /(\\*)\{\{(~?\s*)(#if|#unless|else\s+if|else\s+unless)(?=[\s(!])/g;
278
+
279
+ // Finds the end of a mustache tag starting at `from`, skipping over quoted strings.
280
+ // Returns the index of the closing "}}" (or "~}}"), or -1.
281
+ function findTagEnd(text: string, from: number): number {
282
+ let quote: string | null = null;
283
+ for (let i = from; i < text.length; i++) {
284
+ const c = text[i];
285
+ if (quote) {
286
+ if (c === "\\") i++;
287
+ else if (c === quote) quote = null;
288
+ } else if (c === "\"" || c === "'") {
289
+ quote = c;
290
+ } else if (text.startsWith("~}}", i)) {
291
+ return i;
292
+ } else if (text.startsWith("}}", i)) {
293
+ return i;
294
+ }
295
+ }
296
+ return -1;
297
+ }
298
+
299
+ export function rewriteInfixExpressions(text: string): string {
300
+ if (!text.includes("{{")) return text;
301
+
302
+ let result = "";
303
+ let last = 0;
304
+ blockStart.lastIndex = 0;
305
+ let match: RegExpExecArray | null;
306
+ while ((match = blockStart.exec(text)) !== null) {
307
+ // An odd number of backslashes escapes the mustache
308
+ if (match[1].length % 2 === 1) continue;
309
+
310
+ const argStart = match.index + match[0].length;
311
+ const argEnd = findTagEnd(text, argStart);
312
+ if (argEnd === -1) break;
313
+
314
+ const condition = text.slice(argStart, argEnd);
315
+ const rewritten = rewriteInfixCondition(condition);
316
+ if (rewritten !== null) {
317
+ result += text.slice(last, argStart) + " " + rewritten;
318
+ last = argEnd;
319
+ }
320
+ blockStart.lastIndex = argEnd;
321
+ }
322
+ return result + text.slice(last);
323
+ }
@@ -48,6 +48,43 @@ export function AnimatePlugin(): SquiffyPlugin {
48
48
  // innerHTML after animation, users can still interact with the links.
49
49
  const originalContent = el.innerHTML;
50
50
 
51
+ // For trigger="link", the links in el that run the animation when clicked.
52
+ let triggerLinks: HTMLElement[] = [];
53
+ const registerTriggerLinks = () => {
54
+ for (const link of triggerLinks) {
55
+ squiffy.animation.removeLinkAnimation(link);
56
+ }
57
+ triggerLinks = [...el.querySelectorAll<HTMLElement>("a")];
58
+ for (const link of triggerLinks) {
59
+ squiffy.animation.addLinkAnimation(link, runAnimation);
60
+ }
61
+ };
62
+
63
+ const restoreContent = () => {
64
+ if (params.trigger !== "link") {
65
+ el.innerHTML = originalContent;
66
+ return;
67
+ }
68
+
69
+ // Restoring the content replaces the links, so carry over the state
70
+ // (e.g. "disabled" from the click that triggered the animation) to the new
71
+ // links, and make sure they still trigger the animation if re-enabled.
72
+ const oldLinks = triggerLinks;
73
+ el.innerHTML = originalContent;
74
+ registerTriggerLinks();
75
+ triggerLinks.forEach((link, i) => {
76
+ const oldLink = oldLinks[i];
77
+ if (!oldLink) return;
78
+ if (oldLink.classList.contains("disabled")) {
79
+ link.classList.add("disabled");
80
+ }
81
+ const tabindex = oldLink.getAttribute("tabindex");
82
+ if (tabindex !== null) {
83
+ link.setAttribute("tabindex", tabindex);
84
+ }
85
+ });
86
+ };
87
+
51
88
  const runAnimation = () => {
52
89
  if (params.loop) {
53
90
  squiffy.animation.runAnimation(params.name, el, params, () => {}, true);
@@ -62,7 +99,7 @@ export function AnimatePlugin(): SquiffyPlugin {
62
99
 
63
100
  squiffy.animation.runAnimation(params.name, el, params, () => {
64
101
  el.classList.remove("squiffy-animate");
65
- el.innerHTML = originalContent;
102
+ restoreContent();
66
103
  resolve();
67
104
  }, false);
68
105
  });
@@ -71,10 +108,7 @@ export function AnimatePlugin(): SquiffyPlugin {
71
108
  };
72
109
 
73
110
  if (params.trigger === "link") {
74
- const links = el.querySelectorAll("a");
75
- for (const link of links) {
76
- squiffy.animation.addLinkAnimation(link, runAnimation);
77
- }
111
+ registerTriggerLinks();
78
112
  } else {
79
113
  runAnimation();
80
114
  }