squiffy-runtime 6.0.0-beta.2 → 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.
@@ -11,13 +11,14 @@ import { imports } from "./import.js";
11
11
  import { areInputsValid, setupInputValidation } from "./inputValidation.js";
12
12
 
13
13
  export type { SquiffyApi } from "./types.js";
14
+ export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
14
15
 
15
16
  export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> => {
16
17
  let story: Story;
17
18
  let currentSection: Section;
18
19
  let currentSectionElement: HTMLElement;
19
- let currentPassageElement: HTMLElement;
20
- let currentBlockOutputElement: HTMLElement;
20
+ let currentPassageElement: HTMLElement | null;
21
+ let currentBlockOutputElement: HTMLElement | null;
21
22
  let scrollPosition = 0;
22
23
  const emitter = new Emitter<SquiffyEventMap>();
23
24
  const transitions: (() => Promise<void>)[] = [];
@@ -358,6 +359,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
358
359
  if (story.uiJsIndex !== undefined) {
359
360
  runJs(story.uiJsIndex, {
360
361
  registerAnimation: animation.registerAnimation.bind(animation),
362
+ registerHelper: textProcessor.handlebars.registerHelper.bind(textProcessor.handlebars),
363
+ SafeString: textProcessor.handlebars.SafeString,
361
364
  });
362
365
  }
363
366
  };
@@ -390,28 +393,25 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
390
393
 
391
394
  function newSection(sectionName?: string) {
392
395
  if (currentSectionElement) {
393
- currentSectionElement.querySelectorAll("input").forEach(el => {
394
- const attribute = el.getAttribute("data-attribute") || el.id;
395
- if (attribute) set(attribute, el.value);
396
- el.disabled = true;
396
+ // Inputs we disable are marked with data-squiffy-disabled, so goBack() can re-enable them
397
+ // without touching any that the author disabled themselves.
398
+ currentSectionElement.querySelectorAll("input, textarea, select").forEach(el => {
399
+ const input = el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
400
+ const attribute = input.getAttribute("data-attribute") || input.id;
401
+ if (attribute) set(attribute, input.value);
402
+ if (!input.disabled) {
403
+ input.disabled = true;
404
+ input.setAttribute("data-squiffy-disabled", "");
405
+ }
397
406
  });
398
-
407
+
399
408
  currentSectionElement.querySelectorAll("[contenteditable]").forEach(el => {
400
409
  const attribute = el.getAttribute("data-attribute") || el.id;
401
410
  if (attribute) set(attribute, el.innerHTML);
402
- (el as HTMLElement).contentEditable = "false";
403
- });
404
-
405
- currentSectionElement.querySelectorAll("textarea").forEach(el => {
406
- const attribute = el.getAttribute("data-attribute") || el.id;
407
- if (attribute) set(attribute, el.value);
408
- el.disabled = true;
409
- });
410
-
411
- currentSectionElement.querySelectorAll("select").forEach(el => {
412
- const attribute = el.getAttribute("data-attribute") || el.id;
413
- if (attribute) set(attribute, el.value);
414
- el.disabled = true;
411
+ if (el.getAttribute("contenteditable") !== "false") {
412
+ el.setAttribute("contenteditable", "false");
413
+ el.setAttribute("data-squiffy-disabled", "");
414
+ }
415
415
  });
416
416
  }
417
417
 
@@ -462,6 +462,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
462
462
 
463
463
  function unClearScreen() {
464
464
  const clearStack = getClearStack();
465
+ if (!clearStack) return;
465
466
  for (const child of [...outputElement.children]) {
466
467
  if (child !== clearStack) {
467
468
  child.remove();
@@ -499,7 +500,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
499
500
 
500
501
  div.innerHTML = html;
501
502
  pluginManager.onWrite(div);
502
- currentBlockOutputElement.appendChild(div);
503
+ currentBlockOutputElement!.appendChild(div);
503
504
 
504
505
  // Setup validation for any new inputs that were just added
505
506
  setupInputValidation(currentSectionElement);
@@ -515,7 +516,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
515
516
  // do nothing
516
517
  }
517
518
  else if (settings.scroll === "element") {
518
- outputElement.lastElementChild.scrollIntoView({ block: "end", inline: "nearest", behavior: "smooth" });
519
+ outputElement.lastElementChild?.scrollIntoView({ block: "end", inline: "nearest", behavior: "smooth" });
519
520
  }
520
521
  else {
521
522
  let scrollTo = scrollPosition;
@@ -541,10 +542,25 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
541
542
  return;
542
543
  }
543
544
 
544
- updateStory(story, newStory, outputElement, ui, disableLink, (attrs) => processAttributes(attrs));
545
-
545
+ // Switch to the new story before re-rendering, so that text processing (e.g. {{embed}})
546
+ // sees sections that were added in this update.
547
+ const oldStory = story;
546
548
  story = newStory;
547
549
 
550
+ // When re-rendering a section or passage, {{embed}} should look up passages in the
551
+ // (new version of the) section being rendered.
552
+ const processTextInSection = (text: string, section: Section) => {
553
+ const previousSection = currentSection;
554
+ currentSection = section;
555
+ try {
556
+ return ui.processText(text, false);
557
+ } finally {
558
+ currentSection = previousSection;
559
+ }
560
+ };
561
+
562
+ updateStory(oldStory, newStory, outputElement, processTextInSection, disableLink, (attrs) => processAttributes(attrs));
563
+
548
564
  setCurrentSectionElement();
549
565
  setCurrentPassageElement();
550
566
  }
@@ -555,7 +571,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
555
571
  const allSectionElements = outputElement.querySelectorAll<HTMLElement>(".squiffy-output-section:last-child");
556
572
  currentSectionElement = allSectionElements[allSectionElements.length - 1];
557
573
  const sectionName = currentSectionElement.getAttribute("data-section");
558
- currentSection = story.sections[sectionName];
574
+ currentSection = story.sections[sectionName!];
559
575
  }
560
576
 
561
577
  function setCurrentPassageElement() {
@@ -574,12 +590,26 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
574
590
  return sectionPassageCount + clearStack.children.length;
575
591
  }
576
592
 
593
+ function enableInputs(sectionElement: Element) {
594
+ sectionElement.querySelectorAll("[data-squiffy-disabled]").forEach(el => {
595
+ if (el.hasAttribute("contenteditable")) {
596
+ el.setAttribute("contenteditable", "true");
597
+ }
598
+ else {
599
+ (el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement).disabled = false;
600
+ }
601
+ el.removeAttribute("data-squiffy-disabled");
602
+ });
603
+ }
604
+
577
605
  function canGoBack() {
578
606
  return getHistoryCount() > 1;
579
607
  }
580
608
 
581
609
  function goBack() {
582
- if (!canGoBack()) {
610
+ // Like link clicks, ignore this while transitions are running. The section or passage being shown
611
+ // hasn't written its undo log yet, and would write it to the wrong element once it resumed.
612
+ if (runningTransitions || !canGoBack()) {
583
613
  return;
584
614
  }
585
615
 
@@ -640,6 +670,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
640
670
 
641
671
  setCurrentSectionElement();
642
672
  setCurrentPassageElement();
673
+ enableInputs(currentSectionElement);
643
674
  }
644
675
 
645
676
  if (!canGoBack()) {
@@ -717,7 +748,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
717
748
  const get = state.get.bind(state);
718
749
  const set = state.set.bind(state);
719
750
 
720
- const textProcessor = new TextProcessor(story, state, () => currentSection);
751
+ const textProcessor = new TextProcessor(() => story, state, () => currentSection);
721
752
  const linkHandler = new LinkHandler();
722
753
 
723
754
  const getSectionText = (sectionName: string) => {
@@ -2,17 +2,18 @@ import * as marked from "marked";
2
2
  import Handlebars from "handlebars";
3
3
  import { Section, Story } from "./types.js";
4
4
  import { State } from "./state.js";
5
+ import { rewriteInfixExpressions } from "./infixExpressions.js";
5
6
 
6
7
  export class TextProcessor {
7
- story: Story;
8
+ getStory: () => Story;
8
9
  state: State;
9
10
  getCurrentSection: () => Section;
10
11
  handlebars: typeof Handlebars;
11
12
 
12
- constructor (story: Story,
13
+ constructor (story: () => Story,
13
14
  state: State,
14
15
  currentSection: () => Section) {
15
- this.story = story;
16
+ this.getStory = story;
16
17
  this.state = state;
17
18
  this.getCurrentSection = currentSection;
18
19
  this.handlebars = Handlebars.create();
@@ -21,8 +22,10 @@ export class TextProcessor {
21
22
  const currentSection = this.getCurrentSection();
22
23
  if (currentSection.passages && name in currentSection.passages) {
23
24
  return new Handlebars.SafeString(this.process(currentSection.passages[name].text || "", true));
24
- } else if (name in this.story.sections) {
25
- return new Handlebars.SafeString(this.process(this.story.sections[name].text || "", true));
25
+ }
26
+ const story = this.getStory();
27
+ if (name in story.sections) {
28
+ return new Handlebars.SafeString(this.process(story.sections[name].text || "", true));
26
29
  }
27
30
  });
28
31
 
@@ -174,20 +177,22 @@ export class TextProcessor {
174
177
  return result;
175
178
  };
176
179
 
180
+ const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
181
+
177
182
  this.handlebars.registerHelper("section", (section: string, options) => {
178
183
  const text = options.hash.text as string || section;
179
- return new Handlebars.SafeString(`<a class="squiffy-link link-section" data-section="${section}"${addAdditionalParameters(options)} role="link" tabindex="0">${text}</a>`);
184
+ return new Handlebars.SafeString(`<a class="squiffy-link link-section" data-section="${escapeAttr(section)}"${addAdditionalParameters(options)} role="link" tabindex="0">${text}</a>`);
180
185
  });
181
186
 
182
187
  this.handlebars.registerHelper("passage", (passage: string, options) => {
183
188
  const text = options.hash.text as string || passage;
184
- return new Handlebars.SafeString(`<a class="squiffy-link link-passage" data-passage="${passage}"${addAdditionalParameters(options)} role="link" tabindex="0">${text}</a>`);
189
+ return new Handlebars.SafeString(`<a class="squiffy-link link-passage" data-passage="${escapeAttr(passage)}"${addAdditionalParameters(options)} role="link" tabindex="0">${text}</a>`);
185
190
  });
186
191
  }
187
192
 
188
193
  process(text: string, inline: boolean) {
189
194
  try {
190
- const template = this.handlebars.compile(text);
195
+ const template = this.handlebars.compile(rewriteInfixExpressions(text));
191
196
  text = template(this.state.getStore());
192
197
 
193
198
  if (inline) {
package/src/updater.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Story } from "./types.js";
1
+ import { Section, Story } from "./types.js";
2
2
 
3
3
  function arraysEqual(a: string[] | undefined, b: string[] | undefined): boolean {
4
4
  if (!a && !b) return true;
@@ -10,7 +10,7 @@ function arraysEqual(a: string[] | undefined, b: string[] | undefined): boolean
10
10
  export function updateStory(oldStory: Story,
11
11
  newStory: Story,
12
12
  outputElement: HTMLElement,
13
- ui: any,
13
+ processText: (text: string, section: Section) => string,
14
14
  disableLink: (link: Element) => void,
15
15
  processAttributes: (attributes: string[]) => void) {
16
16
 
@@ -30,7 +30,7 @@ export function updateStory(oldStory: Story,
30
30
  // Record which passage links are disabled
31
31
  const disabledPassages = Array.from(element
32
32
  .querySelectorAll("a.link-passage.disabled"))
33
- .map((el: HTMLElement) => el.getAttribute("data-passage"));
33
+ .map((el: Element) => el.getAttribute("data-passage"));
34
34
 
35
35
  element.innerHTML = text;
36
36
 
@@ -49,7 +49,7 @@ export function updateStory(oldStory: Story,
49
49
  // section has been deleted
50
50
  for (const element of elements) {
51
51
  const parentOutputSection = element.closest(".squiffy-output-section");
52
- parentOutputSection.remove();
52
+ parentOutputSection?.remove();
53
53
  }
54
54
  }
55
55
  else {
@@ -65,7 +65,7 @@ export function updateStory(oldStory: Story,
65
65
  if (textChanged || attributesChanged) {
66
66
  // Re-render text (attributes may affect text output via helpers)
67
67
  for (const element of elements) {
68
- updateElementTextPreservingDisabledPassageLinks(element, ui.processText(newSection.text, false));
68
+ updateElementTextPreservingDisabledPassageLinks(element, processText(newSection.text || "", newSection));
69
69
  }
70
70
  }
71
71
  }
@@ -82,7 +82,7 @@ export function updateStory(oldStory: Story,
82
82
  // passage has been deleted
83
83
  for (const element of elements) {
84
84
  const parentOutputPassage = element.closest(".squiffy-output-passage");
85
- parentOutputPassage.remove();
85
+ parentOutputPassage?.remove();
86
86
  }
87
87
  }
88
88
  else {
@@ -98,7 +98,7 @@ export function updateStory(oldStory: Story,
98
98
  if (textChanged || attributesChanged) {
99
99
  // Re-render text (attributes may affect text output via helpers)
100
100
  for (const element of elements) {
101
- updateElementTextPreservingDisabledPassageLinks(element, ui.processText(newPassage.text, false));
101
+ updateElementTextPreservingDisabledPassageLinks(element, processText(newPassage.text || "", newStory.sections[existingSection]));
102
102
  }
103
103
  }
104
104
  }
package/vitest.config.ts CHANGED
@@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config";
3
3
  export default defineConfig({
4
4
  test: {
5
5
  globals: true,
6
- environment: "jsdom",
6
+ environment: "node",
7
7
  setupFiles: "./vitest.setup.ts",
8
8
  },
9
9
  });