@olenbetong/synergi-course 2.0.0 → 2.2.0

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 (96) hide show
  1. package/es/chrome/CategoryHeader.css +28 -0
  2. package/es/completion/CourseCompletion.css +53 -0
  3. package/es/completion/CourseCompletion.d.ts +32 -0
  4. package/es/completion/CourseCompletion.js +60 -0
  5. package/es/document/cues.d.ts +51 -6
  6. package/es/document/cues.js +117 -14
  7. package/es/document/effects.d.ts +30 -0
  8. package/es/document/effects.js +76 -0
  9. package/es/document/schema.d.ts +2722 -346
  10. package/es/document/schema.js +172 -5
  11. package/es/document/validate.d.ts +2 -1
  12. package/es/document/validate.js +83 -16
  13. package/es/index.d.ts +8 -3
  14. package/es/index.js +6 -2
  15. package/es/media/Media.css +16 -0
  16. package/es/media/icons.d.ts +1 -0
  17. package/es/media/icons.js +3 -0
  18. package/es/player/CoursePlayer.css +76 -0
  19. package/es/player/CoursePlayer.js +28 -13
  20. package/es/player/PlayerBars.d.ts +32 -0
  21. package/es/player/PlayerBars.js +14 -0
  22. package/es/player/useFullScreen.d.ts +17 -0
  23. package/es/player/useFullScreen.js +83 -0
  24. package/es/player/useMediaQuery.d.ts +7 -0
  25. package/es/player/useMediaQuery.js +16 -0
  26. package/es/steps/Blocks.d.ts +43 -3
  27. package/es/steps/Blocks.js +114 -26
  28. package/es/steps/Markdown.d.ts +7 -1
  29. package/es/steps/Markdown.js +31 -4
  30. package/es/steps/QuizStepView.d.ts +2 -1
  31. package/es/steps/QuizStepView.js +20 -10
  32. package/es/steps/RevealMotion.d.ts +29 -0
  33. package/es/steps/RevealMotion.js +55 -0
  34. package/es/steps/SlideStepView.d.ts +5 -3
  35. package/es/steps/SlideStepView.js +43 -10
  36. package/es/steps/StepBodyProps.d.ts +16 -1
  37. package/es/steps/StepView.css +390 -16
  38. package/es/steps/StepView.d.ts +36 -4
  39. package/es/steps/StepView.js +21 -5
  40. package/es/steps/motion.d.ts +59 -0
  41. package/es/steps/motion.js +136 -0
  42. package/es/transitions/Transitions.css +114 -0
  43. package/es/transitions/plan.d.ts +66 -0
  44. package/es/transitions/plan.js +185 -0
  45. package/es/transitions/playStepTransition.d.ts +23 -0
  46. package/es/transitions/playStepTransition.js +131 -0
  47. package/es/types.d.ts +16 -3
  48. package/package.json +4 -4
  49. package/src/chrome/CategoryHeader.css +28 -0
  50. package/src/completion/CourseCompletion.css +53 -0
  51. package/src/completion/CourseCompletion.test.tsx +45 -0
  52. package/src/completion/CourseCompletion.tsx +98 -0
  53. package/src/document/box.test.ts +234 -0
  54. package/src/document/cues.ts +143 -13
  55. package/src/document/document.test.ts +1 -1
  56. package/src/document/effects.ts +106 -0
  57. package/src/document/reveal.test.ts +263 -0
  58. package/src/document/schema.ts +203 -5
  59. package/src/document/validate.ts +88 -18
  60. package/src/index.ts +46 -1
  61. package/src/media/Media.css +16 -0
  62. package/src/media/icons.tsx +8 -0
  63. package/src/player/CoursePlayer.css +76 -0
  64. package/src/player/CoursePlayer.test.tsx +70 -6
  65. package/src/player/CoursePlayer.tsx +91 -60
  66. package/src/player/PlayerBars.tsx +106 -0
  67. package/src/player/fullScreen.test.tsx +70 -0
  68. package/src/player/useFullScreen.ts +91 -0
  69. package/src/player/useMediaQuery.ts +21 -0
  70. package/src/steps/Blocks.test.ts +34 -0
  71. package/src/steps/Blocks.tsx +219 -32
  72. package/src/steps/Box.test.tsx +95 -0
  73. package/src/steps/Markdown.test.tsx +46 -0
  74. package/src/steps/Markdown.tsx +42 -4
  75. package/src/steps/Presence.test.tsx +82 -0
  76. package/src/steps/QuizStepView.test.tsx +79 -0
  77. package/src/steps/QuizStepView.tsx +34 -12
  78. package/src/steps/RevealMotion.ts +66 -0
  79. package/src/steps/SlideStepView.tsx +74 -12
  80. package/src/steps/StepBodyProps.ts +16 -1
  81. package/src/steps/StepView.css +390 -16
  82. package/src/steps/StepView.test.tsx +157 -0
  83. package/src/steps/StepView.tsx +108 -19
  84. package/src/steps/motion.test.ts +98 -0
  85. package/src/steps/motion.ts +178 -0
  86. package/src/steps/visibility.test.ts +24 -0
  87. package/src/transitions/Transitions.css +114 -0
  88. package/src/transitions/plan.ts +258 -0
  89. package/src/transitions/playStepTransition.ts +162 -0
  90. package/src/transitions/transitions.test.ts +274 -0
  91. package/src/types.ts +16 -3
  92. package/es/Transitions.css +0 -55
  93. package/es/Transitions.d.ts +0 -10
  94. package/es/Transitions.js +0 -24
  95. package/src/Transitions.css +0 -55
  96. package/src/Transitions.ts +0 -35
@@ -0,0 +1,131 @@
1
+ import "./Transitions.css";
2
+ import { flushSync } from "react-dom";
3
+ import { planStepTransition, } from "./plan";
4
+ /** One view transition runs at a time in a document, so one is tracked for the whole module. */
5
+ let running = null;
6
+ function noop() { }
7
+ function toStep(step) {
8
+ if (step == null)
9
+ return null;
10
+ return "document" in step ? step : { document: step };
11
+ }
12
+ function canAnimate() {
13
+ if (typeof document === "undefined" || typeof document.startViewTransition !== "function")
14
+ return false;
15
+ return !(typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches);
16
+ }
17
+ function findBox(scope) {
18
+ if (!scope)
19
+ return null;
20
+ return scope.matches(".ob-course-step") ? scope : scope.querySelector(".ob-course-step");
21
+ }
22
+ function findTarget(box, target) {
23
+ let element;
24
+ switch (target.kind) {
25
+ case "step":
26
+ element = box;
27
+ break;
28
+ case "header":
29
+ element = box.querySelector(".ob-course-category-header");
30
+ break;
31
+ case "content":
32
+ element = box.querySelector(".ob-course-slide__content");
33
+ break;
34
+ case "background":
35
+ element = box.querySelector(".ob-course-slide__background, .ob-course-banner");
36
+ break;
37
+ case "part":
38
+ element = box.querySelector(`[data-part="${CSS.escape(target.id)}"]`);
39
+ // A part waiting for its cue or its press of Next, or fading out, is not on show: nothing to animate
40
+ if (element?.closest(".is-pending, .is-leaving"))
41
+ element = null;
42
+ break;
43
+ }
44
+ return element instanceof HTMLElement ? element : null;
45
+ }
46
+ /**
47
+ * Runs `run`, the change of step, inside a view transition: the outgoing step's `exit`
48
+ * transitions animate what it showed, the incoming step's `enter` transitions what it shows, and
49
+ * the category band stays or slides. Names are set on the elements inside `scope` only for as
50
+ * long as the transition runs, so other steps on the page (an editor's previews) are never part
51
+ * of it. A transition still running is skipped first. Without the API, or when the learner
52
+ * prefers reduced motion, `run` is called at once.
53
+ *
54
+ * Resolves when the transition has finished.
55
+ */
56
+ export function playStepTransition(run, options) {
57
+ if (!canAnimate()) {
58
+ run();
59
+ return Promise.resolve();
60
+ }
61
+ if (running) {
62
+ let previous = running;
63
+ running = null;
64
+ previous.transition.skipTransition();
65
+ // The change it was making must be in the page before this one names what is there
66
+ let start = () => {
67
+ previous.cleanup();
68
+ return startTransition(run, options);
69
+ };
70
+ return previous.transition.updateCallbackDone.then(start, start);
71
+ }
72
+ return startTransition(run, options);
73
+ }
74
+ function startTransition(run, { scope, from, to, direction = "forward" }) {
75
+ let plan = planStepTransition({ from: toStep(from), to: toStep(to), direction });
76
+ if (plan.duration === 0 || !findBox(scope)) {
77
+ run();
78
+ return Promise.resolve();
79
+ }
80
+ let style = document.createElement("style");
81
+ style.dataset.obCourseTransition = "";
82
+ style.textContent = plan.css;
83
+ document.head.append(style);
84
+ let named = [];
85
+ let name = (side) => {
86
+ let box = findBox(scope);
87
+ if (!box)
88
+ return;
89
+ for (let target of plan.names.filter((item) => item.side === side)) {
90
+ let element = findTarget(box, target.target);
91
+ if (!element)
92
+ continue;
93
+ element.style.setProperty("view-transition-name", target.name);
94
+ named.push(element);
95
+ }
96
+ };
97
+ let unname = () => {
98
+ for (let element of named)
99
+ element.style.removeProperty("view-transition-name");
100
+ named = [];
101
+ };
102
+ let entry;
103
+ let cleaned = false;
104
+ let skip = () => entry.transition.skipTransition();
105
+ let cleanup = () => {
106
+ if (cleaned)
107
+ return;
108
+ cleaned = true;
109
+ unname();
110
+ style.remove();
111
+ document.documentElement.removeEventListener("pointerdown", skip);
112
+ if (running === entry)
113
+ running = null;
114
+ };
115
+ name("old");
116
+ let transition = document.startViewTransition(() => {
117
+ if (running !== entry) {
118
+ // Skipped for a newer change before it got here: only the change itself is still owed
119
+ flushSync(run);
120
+ return;
121
+ }
122
+ unname();
123
+ flushSync(run);
124
+ name("new");
125
+ });
126
+ entry = { transition, cleanup };
127
+ running = entry;
128
+ // The page takes no clicks while a transition runs, so a click ends it instead
129
+ document.documentElement.addEventListener("pointerdown", skip);
130
+ return transition.finished.then(cleanup, cleanup).then(noop);
131
+ }
package/es/types.d.ts CHANGED
@@ -5,8 +5,10 @@ export interface PlayerLanguage {
5
5
  }
6
6
  export interface PlayerCourse {
7
7
  title: string;
8
- /** The learner's language. `null` until the learner has chosen one. */
8
+ /** The learner's language. `null` for the main language, and until the learner has chosen one. */
9
9
  cultureId: string | null;
10
+ /** The course's main language: the one a learner without a stored language takes the course in. */
11
+ mainCultureId?: string | null;
10
12
  /** The languages the course can be taken in. */
11
13
  languages: PlayerLanguage[];
12
14
  }
@@ -62,7 +64,10 @@ export interface QuizQuestion {
62
64
  text: string;
63
65
  /** Several options may be right: shown as checkboxes instead of radio buttons. */
64
66
  multiple: boolean;
65
- /** Already answered in this attempt. Set when an open attempt is resumed; the quiz continues at the first question without it. */
67
+ /**
68
+ * Already answered in this attempt. Set when an open attempt is resumed; the quiz continues at the first question
69
+ * without it. With `retryUntilCorrect`, only a correct answer counts, so a question last answered wrong is asked again.
70
+ */
66
71
  answered?: boolean;
67
72
  options: QuizOption[];
68
73
  }
@@ -70,13 +75,19 @@ export interface QuizAttempt {
70
75
  attemptId: string;
71
76
  /** Percent of correct answers needed to pass. `null` means every answer must be correct. */
72
77
  passPercent: number | null;
78
+ /**
79
+ * Each question must be answered correctly before the next one: a wrong answer only says so, and the learner
80
+ * answers the same question again. The attempt passes once every question is right; `passPercent` is not used.
81
+ */
82
+ retryUntilCorrect?: boolean;
73
83
  questions: QuizQuestion[];
74
84
  /** The learner has passed this quiz before; the player shows it as passed without asking again. */
75
85
  alreadyPassed?: boolean;
76
86
  }
77
87
  export interface QuizAnswerResult {
78
88
  correct: boolean;
79
- explanation?: string;
89
+ /** Left out after a wrong answer when the quiz has `retryUntilCorrect`; the player then never shows one. */
90
+ explanation?: string | null;
80
91
  }
81
92
  export interface QuizResult {
82
93
  passed: boolean;
@@ -84,6 +95,8 @@ export interface QuizResult {
84
95
  correctCount: number;
85
96
  questionCount: number;
86
97
  passPercent: number | null;
98
+ /** The quiz had to be answered correctly question by question, so a passed attempt is every question right. */
99
+ retryUntilCorrect?: boolean;
87
100
  /** The ids of the must-be-correct questions that were answered wrong. */
88
101
  missedRequired: string[];
89
102
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@olenbetong/synergi-course",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "Course player: steps described as content, shown responsively",
5
5
  "type": "module",
6
6
  "exports": {
@@ -20,7 +20,7 @@
20
20
  "author": "Bjørnar Vister Hansen",
21
21
  "license": "MIT",
22
22
  "dependencies": {
23
- "@olenbetong/appframe-core": "^2.16.1",
23
+ "@olenbetong/appframe-core": "^2.16.2",
24
24
  "@valibot/to-json-schema": "^1.8.0",
25
25
  "@vimeo/player": "^2.30.4",
26
26
  "clsx": "^2.1.1",
@@ -53,8 +53,8 @@
53
53
  },
54
54
  "scripts": {
55
55
  "dev": "vite",
56
- "build": "pnpm run build:tsc && pnpm test && pnpm run build:css",
57
- "build:tsc": "node --no-warnings ../../scripts/clean.ts ./es ./dist && tsc -p tsconfig.build.json",
56
+ "build": "pnpm run build:tsc && pnpm run build:css && pnpm test",
57
+ "build:tsc": "node --no-warnings ../../scripts/clean.ts ./dist && tsc -p tsconfig.build.json && node --no-warnings ../../scripts/prune-output.ts ./es ./src",
58
58
  "build:css": "node scripts/copyAssets.mjs",
59
59
  "lint": "oxlint .",
60
60
  "format": "oxfmt . && oxlint --fix .",
@@ -92,3 +92,31 @@
92
92
  display: none;
93
93
  }
94
94
  }
95
+
96
+ /* On a phone on its side the band is one slim line: the subtitle goes beside the title. */
97
+ @media (orientation: landscape) and (max-height: 500px) {
98
+ .ob-course-category-header {
99
+ padding-block: 0.2rem;
100
+ font-size: 0.75rem;
101
+ }
102
+
103
+ .ob-course-category-header__titles {
104
+ display: flex;
105
+ flex-wrap: wrap;
106
+ align-items: baseline;
107
+ column-gap: 0.75em;
108
+ }
109
+
110
+ .ob-course-category-header__title {
111
+ font-size: 1.15em;
112
+ }
113
+
114
+ .ob-course-category-header__image {
115
+ width: 1.75em;
116
+ height: 1.75em;
117
+ }
118
+
119
+ .ob-course-category-header__logo {
120
+ max-height: 1.75em;
121
+ }
122
+ }
@@ -0,0 +1,53 @@
1
+ .ob-course-completion {
2
+ display: grid;
3
+ place-items: center;
4
+ height: 100%;
5
+ padding: var(--ds-size-6) var(--ds-size-4);
6
+ overflow: auto;
7
+ }
8
+
9
+ .ob-course-completion__panel {
10
+ display: flex;
11
+ flex-direction: column;
12
+ align-items: center;
13
+ gap: var(--ds-size-6);
14
+ width: min(100%, 44rem);
15
+ text-align: center;
16
+ font-size: 1.25rem;
17
+ }
18
+
19
+ .ob-course-completion__actions {
20
+ display: flex;
21
+ flex-wrap: wrap;
22
+ justify-content: center;
23
+ gap: var(--ds-size-3);
24
+ }
25
+
26
+ /*
27
+ * The course's own completion text, written for the old full-page completion article. Keep it inside the
28
+ * panel: the old texts lift themselves with negative top margins and rely on Bootstrap's text-center.
29
+ */
30
+ .ob-course-completion__text {
31
+ overflow-wrap: anywhere;
32
+
33
+ & > * {
34
+ margin-block-start: 0 !important;
35
+ }
36
+
37
+ & :where(p) {
38
+ margin-block: 0 var(--ds-size-3);
39
+ }
40
+
41
+ & :where(img, video) {
42
+ max-width: 100%;
43
+ height: auto;
44
+ }
45
+
46
+ & :where(a) {
47
+ color: var(--ds-color-brand-text-subtle);
48
+ }
49
+
50
+ & :where(.text-center) {
51
+ text-align: center;
52
+ }
53
+ }
@@ -0,0 +1,45 @@
1
+ import { render, screen } from "@testing-library/react";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ import { CourseCompletion, hasCompletionText, sanitizeCompletionHtml } from "./CourseCompletion";
5
+
6
+ describe("sanitizeCompletionHtml", () => {
7
+ it("keeps ordinary markup", () => {
8
+ let html = '<p class="text-center"><big>Gratulerer!</big> Les <a href="/hms">mer</a>.</p><img src="/x.png" alt="">';
9
+ expect(sanitizeCompletionHtml(html)).toBe(html);
10
+ });
11
+
12
+ it("removes scripts, embedded objects and event handlers", () => {
13
+ let html =
14
+ '<p onclick="alert(1)">Hei</p><script>alert(2)</script><object data="/x"></object><img src="/x.png" onerror="alert(3)">';
15
+ expect(sanitizeCompletionHtml(html)).toBe('<p>Hei</p><img src="/x.png">');
16
+ });
17
+
18
+ it("removes script links, also when the scheme is broken up", () => {
19
+ let html =
20
+ '<a href="javascript:alert(1)">a</a><a href=" java\tscript:alert(1)">b</a><a href="data:text/html,x">c</a>';
21
+ expect(sanitizeCompletionHtml(html)).toBe("<a>a</a><a>b</a><a>c</a>");
22
+ });
23
+
24
+ it("keeps image data", () => {
25
+ let html = '<img src="data:image/png;base64,AAAA">';
26
+ expect(sanitizeCompletionHtml(html)).toBe(html);
27
+ });
28
+ });
29
+
30
+ describe("CourseCompletion", () => {
31
+ it("shows the default text when the completion text is blank", () => {
32
+ render(<CourseCompletion title="HMS" html={" \n "} emptyText="Du har fullført kurset." />);
33
+ expect(screen.getByText("Du har fullført kurset.")).toBeInTheDocument();
34
+ expect(hasCompletionText(" ")).toBe(false);
35
+ });
36
+
37
+ it("shows the completion text, sanitized when asked", () => {
38
+ let { container } = render(
39
+ <CourseCompletion title="HMS" html={'<p onclick="x()">Gratulerer!</p>'} emptyText="Standard" sanitize />,
40
+ );
41
+ expect(screen.getByText("Gratulerer!")).toBeInTheDocument();
42
+ expect(container.querySelector("[onclick]")).toBeNull();
43
+ expect(screen.queryByText("Standard")).toBeNull();
44
+ });
45
+ });
@@ -0,0 +1,98 @@
1
+ import { Heading, Paragraph } from "@digdir/designsystemet-react";
2
+ import clsx from "clsx";
3
+ import type { ReactNode } from "react";
4
+ import { useMemo } from "react";
5
+
6
+ import "./CourseCompletion.css";
7
+
8
+ export interface CourseCompletionProps {
9
+ /** The course's title, the screen's heading. */
10
+ title: ReactNode;
11
+ /** The course's completion text (HTML written by the course editors). Blank counts as none. */
12
+ html?: string | null;
13
+ /** What the learner reads when the course has no completion text. */
14
+ emptyText: ReactNode;
15
+ /** The buttons under the text (the diploma, back to the course list). */
16
+ actions?: ReactNode;
17
+ /**
18
+ * Strip scripts, event handlers, embedded frames and `javascript:` links before showing the
19
+ * text. For an editor's preview of text being written; the player shows the saved text as it is.
20
+ */
21
+ sanitize?: boolean;
22
+ className?: string;
23
+ }
24
+
25
+ /** Whether the completion text has anything to show; the course feed treats blank text as none. */
26
+ export function hasCompletionText(html: string | null | undefined): html is string {
27
+ return !!html?.trim();
28
+ }
29
+
30
+ const REMOVED_ELEMENTS = "script, iframe, frame, frameset, object, embed, base, meta, link, form";
31
+ const URL_ATTRIBUTES = new Set(["href", "src", "action", "formaction", "xlink:href", "srcdoc"]);
32
+
33
+ /**
34
+ * The completion text without anything that runs code: script and frame elements, `on*`
35
+ * attributes and `javascript:` (or `data:` outside images) URLs. Parsed in an inert document, so
36
+ * nothing in it runs or loads while it is cleaned.
37
+ */
38
+ export function sanitizeCompletionHtml(html: string): string {
39
+ let document = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");
40
+ for (let element of document.body.querySelectorAll(REMOVED_ELEMENTS)) element.remove();
41
+ for (let element of document.body.querySelectorAll("*")) {
42
+ // A copy, since removing attributes changes the live list
43
+ for (let attribute of Array.from(element.attributes)) {
44
+ let name = attribute.name.toLowerCase();
45
+ if (name.startsWith("on")) {
46
+ element.removeAttribute(attribute.name);
47
+ } else if (URL_ATTRIBUTES.has(name)) {
48
+ // Browsers skip control characters and spaces in a scheme ("java\tscript:")
49
+ let value = [...attribute.value]
50
+ .filter((char) => char.charCodeAt(0) > 32)
51
+ .join("")
52
+ .toLowerCase();
53
+ let imageData = value.startsWith("data:image/") && name === "src" && element.tagName === "IMG";
54
+ if (
55
+ name === "srcdoc" ||
56
+ value.startsWith("javascript:") ||
57
+ value.startsWith("vbscript:") ||
58
+ (value.startsWith("data:") && !imageData)
59
+ ) {
60
+ element.removeAttribute(attribute.name);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ return document.body.innerHTML;
66
+ }
67
+
68
+ /**
69
+ * The screen a learner sees when the course is completed: the title, the course's completion
70
+ * text (or the default text) and the actions. The completion texts were written for the old
71
+ * full-page completion article; the stylesheet keeps them inside the panel.
72
+ */
73
+ export function CourseCompletion({ title, html, emptyText, actions, sanitize, className }: CourseCompletionProps) {
74
+ let shown = useMemo(() => {
75
+ if (!hasCompletionText(html)) return null;
76
+ return sanitize ? sanitizeCompletionHtml(html) : html;
77
+ }, [html, sanitize]);
78
+
79
+ return (
80
+ <div className={clsx("ob-course-completion", className)}>
81
+ <div className="ob-course-completion__panel">
82
+ <Heading level={1} data-size="xl">
83
+ {title}
84
+ </Heading>
85
+ {shown !== null ? (
86
+ <div
87
+ className="ob-course-completion__text ds-paragraph"
88
+ // oxlint-disable-next-line react/no-danger -- written by the course editors; sanitize for previews
89
+ dangerouslySetInnerHTML={{ __html: shown }}
90
+ />
91
+ ) : (
92
+ <Paragraph data-size="lg">{emptyText}</Paragraph>
93
+ )}
94
+ {actions && <div className="ob-course-completion__actions">{actions}</div>}
95
+ </div>
96
+ </div>
97
+ );
98
+ }
@@ -0,0 +1,234 @@
1
+ import { safeParse } from "valibot";
2
+ import { describe, expect, it } from "vitest";
3
+ import {
4
+ getRevealLeaders,
5
+ getRevealNavigation,
6
+ getRevealSteps,
7
+ getTimedParts,
8
+ isVisible,
9
+ type RevealState,
10
+ } from "./cues";
11
+ import { getEffectBlocks, getPartEffects } from "./effects";
12
+ import { type Block, type BoxBlock, blockSchema, boxBlockSchema, contentBlockSchema, type SlideStep } from "./schema";
13
+ import { validateStep } from "./validate";
14
+
15
+ function issuesOf(input: unknown) {
16
+ let result = validateStep(input);
17
+ return result.ok ? [] : result.issues;
18
+ }
19
+
20
+ function stateOf(blocks: Block[], stepsShown: number, ...cues: string[]): RevealState {
21
+ return {
22
+ stepsShown,
23
+ revealSteps: getRevealSteps(blocks),
24
+ startedCues: new Set(cues),
25
+ leaders: getRevealLeaders(blocks),
26
+ };
27
+ }
28
+
29
+ function shownIds(blocks: Block[], state: RevealState) {
30
+ return getTimedParts(blocks)
31
+ .filter((part) => isVisible(part, state))
32
+ .map((part) => part.id);
33
+ }
34
+
35
+ let steps: Block = {
36
+ id: "box",
37
+ type: "box",
38
+ tone: "brand",
39
+ variant: "filled",
40
+ blocks: [
41
+ { id: "h", type: "heading", text: "Slik gjør du", level: 2 },
42
+ {
43
+ id: "l",
44
+ type: "list",
45
+ ordered: true,
46
+ items: [
47
+ { id: "i1", text: "Ta på hjelm", reveal: "step" },
48
+ { id: "i2", text: "Sjekk stroppen", reveal: "step" },
49
+ ],
50
+ },
51
+ ],
52
+ };
53
+
54
+ let slide = (blocks: Block[], cues?: string[]): SlideStep => ({
55
+ schemaVersion: 2,
56
+ type: "slide",
57
+ ...(cues && { narration: { media: { src: "/media/course/a.m4a" }, cues: cues.map((id, start) => ({ id, start })) } }),
58
+ blocks,
59
+ });
60
+
61
+ describe("the box schema", () => {
62
+ it("accepts a box with a heading and a list, in every tone and variant", () => {
63
+ expect(safeParse(boxBlockSchema, steps).success).toBe(true);
64
+ for (let tone of ["neutral", "info", "success", "warning", "danger", "brand"]) {
65
+ for (let variant of ["bordered", "filled", undefined]) {
66
+ expect(safeParse(blockSchema, { id: "b", type: "box", tone, variant, blocks: [] }).success).toBe(true);
67
+ }
68
+ }
69
+ });
70
+
71
+ it("stands at the top level and in a column", () => {
72
+ expect(issuesOf(slide([steps]))).toEqual([]);
73
+ expect(safeParse(contentBlockSchema, steps).success).toBe(true);
74
+ let inColumn = {
75
+ id: "cols",
76
+ type: "columns",
77
+ columns: [
78
+ { id: "a", blocks: [steps] },
79
+ { id: "b", blocks: [] },
80
+ ],
81
+ };
82
+ expect(issuesOf(slide([inColumn as Block]))).toEqual([]);
83
+ });
84
+
85
+ it("holds no box, callout, columns or canvas", () => {
86
+ let nested = [
87
+ { id: "inner", type: "box", blocks: [] },
88
+ { id: "inner", type: "callout", text: "Nei" },
89
+ {
90
+ id: "inner",
91
+ type: "columns",
92
+ columns: [
93
+ { id: "a", blocks: [] },
94
+ { id: "b", blocks: [] },
95
+ ],
96
+ },
97
+ { id: "inner", type: "canvas", items: [] },
98
+ ];
99
+ for (let child of nested) {
100
+ let result = safeParse(boxBlockSchema, { id: "box", type: "box", blocks: [child] });
101
+ expect(result.success, child.type).toBe(false);
102
+ }
103
+ });
104
+
105
+ it("refuses an unknown variant or tone", () => {
106
+ expect(issuesOf(slide([{ ...steps, variant: "dotted" } as never])).map((issue) => issue.path)).toEqual([
107
+ "blocks.0.variant",
108
+ ]);
109
+ expect(issuesOf(slide([{ ...steps, tone: "purple" } as never])).map((issue) => issue.path)).toEqual([
110
+ "blocks.0.tone",
111
+ ]);
112
+ });
113
+
114
+ it("gives a callout a variant and the brand tone, and a canvas text the brand tone", () => {
115
+ let blocks = [
116
+ { id: "c", type: "callout", text: "Husk", tone: "brand", variant: "filled" },
117
+ { id: "k", type: "canvas", items: [{ id: "t", type: "text", text: "Hei", surface: "frame", tone: "brand" }] },
118
+ ];
119
+ expect(issuesOf(slide(blocks as Block[]))).toEqual([]);
120
+ });
121
+ });
122
+
123
+ describe("revealing the parts of a box", () => {
124
+ it("walks a box in document order, its list items included", () => {
125
+ let blocks: Block[] = [{ id: "top", type: "text", text: "Før", reveal: "step" }, steps];
126
+ expect(getTimedParts(blocks).map((part) => part.id)).toEqual(["top", "box", "h", "l", "i1", "i2"]);
127
+ expect(getRevealSteps(blocks)).toEqual(["top", "i1", "i2"]);
128
+ expect(shownIds(blocks, stateOf(blocks, 1))).toEqual(["top", "box", "h", "l"]);
129
+ expect(shownIds(blocks, stateOf(blocks, 2))).toEqual(["top", "box", "h", "l", "i1"]);
130
+ expect(getRevealNavigation(blocks, 0, new Set()).presses).toBe(3);
131
+ });
132
+
133
+ it("walks a box in a column", () => {
134
+ let blocks: Block[] = [
135
+ {
136
+ id: "cols",
137
+ type: "columns",
138
+ columns: [
139
+ { id: "a", blocks: [steps] },
140
+ { id: "b", blocks: [{ id: "t", type: "text", text: "Etter", reveal: "step" }] },
141
+ ],
142
+ },
143
+ ];
144
+ expect(getRevealSteps(blocks)).toEqual(["i1", "i2", "t"]);
145
+ expect(shownIds(blocks, stateOf(blocks, 1))).toEqual(["cols", "box", "h", "l", "i1"]);
146
+ });
147
+
148
+ it("lets a part in a box follow its cues, go with the part above it, and go away", () => {
149
+ let blocks: Block[] = [
150
+ {
151
+ id: "box",
152
+ type: "box",
153
+ revealAt: "c1",
154
+ blocks: [
155
+ { id: "a", type: "text", text: "A", reveal: "with-previous" },
156
+ { id: "b", type: "text", text: "B", revealAt: "c2", hideAt: "c3" },
157
+ ],
158
+ },
159
+ ];
160
+ expect(shownIds(blocks, stateOf(blocks, 0))).toEqual([]);
161
+ expect(shownIds(blocks, stateOf(blocks, 0, "c1"))).toEqual(["box", "a"]);
162
+ expect(shownIds(blocks, stateOf(blocks, 0, "c1", "c2"))).toEqual(["box", "a", "b"]);
163
+ expect(shownIds(blocks, stateOf(blocks, 0, "c1", "c2", "c3"))).toEqual(["box", "a"]);
164
+ });
165
+
166
+ it("finds the effects in a box, in a column too, and what they act on", () => {
167
+ let blocks: Block[] = [
168
+ { id: "t", type: "text", text: "T" },
169
+ {
170
+ id: "cols",
171
+ type: "columns",
172
+ columns: [
173
+ {
174
+ id: "a",
175
+ blocks: [{ id: "box", type: "box", blocks: [{ id: "e", type: "effect", target: "t", move: { x: 1 } }] }],
176
+ },
177
+ { id: "b", blocks: [] },
178
+ ],
179
+ },
180
+ ];
181
+ expect(getEffectBlocks(blocks).map((effect) => effect.id)).toEqual(["e"]);
182
+ expect(getPartEffects(blocks, stateOf(blocks, 0)).get("t")?.x).toBe(1);
183
+ });
184
+ });
185
+
186
+ describe("validating a box", () => {
187
+ it("checks the ids, cues, delays and effect targets of its parts, in a column too", () => {
188
+ let box = (id: string): BoxBlock => ({
189
+ id,
190
+ type: "box",
191
+ blocks: [
192
+ { id: "h", type: "heading", text: "Overskrift", revealAt: "nope" },
193
+ { id: `${id}-t`, type: "text", text: "Tekst", delay: 100 },
194
+ { id: `${id}-e`, type: "effect", target: "missing" },
195
+ { id: `${id}-v`, type: "video-link", label: "Se", media: { src: "/m.mp4", start: 5, end: 2 } },
196
+ ],
197
+ });
198
+ let issues = issuesOf(
199
+ slide(
200
+ [
201
+ box("b1"),
202
+ {
203
+ id: "cols",
204
+ type: "columns",
205
+ columns: [
206
+ { id: "a", blocks: [box("b2")] },
207
+ { id: "b", blocks: [] },
208
+ ],
209
+ },
210
+ ],
211
+ ["c1"],
212
+ ),
213
+ );
214
+ expect(issues.map((issue) => issue.path).sort()).toEqual(
215
+ [
216
+ "blocks.0.blocks.0.revealAt",
217
+ "blocks.0.blocks.1.delay",
218
+ "blocks.0.blocks.2.target",
219
+ "blocks.0.blocks.3.media.end",
220
+ "blocks.1.columns.0.blocks.0.blocks.0.id",
221
+ "blocks.1.columns.0.blocks.0.blocks.0.revealAt",
222
+ "blocks.1.columns.0.blocks.0.blocks.1.delay",
223
+ "blocks.1.columns.0.blocks.0.blocks.2.target",
224
+ "blocks.1.columns.0.blocks.0.blocks.3.media.end",
225
+ ].sort(),
226
+ );
227
+ });
228
+
229
+ it("lets an effect and a transition target a part in a box", () => {
230
+ let step = slide([steps, { id: "e", type: "effect", target: ["h", "i1"], scale: 2 }]);
231
+ step.transitions = [{ on: "enter", effect: "fade", target: "i2" }];
232
+ expect(issuesOf(step)).toEqual([]);
233
+ });
234
+ });