@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
@@ -1,28 +1,70 @@
1
1
  import { Button, Dialog } from "@digdir/designsystemet-react";
2
2
  import clsx from "clsx";
3
3
  import type React from "react";
4
- import { useState } from "react";
4
+ import { Fragment, useState } from "react";
5
5
  import { isVisible, type RevealState } from "../document/cues";
6
- import type { Block, ContentBlock, Timed } from "../document/schema";
6
+ import type { PartEffect } from "../document/effects";
7
+ import type {
8
+ Block,
9
+ BoxContentBlock,
10
+ CanvasItem,
11
+ ContentBlock,
12
+ ListItem,
13
+ SurfaceVariant,
14
+ Timed,
15
+ } from "../document/schema";
7
16
  import { getLocalizedString } from "../i18n";
8
17
  import { PlayIcon } from "../media/icons";
9
18
  import { VideoPlayer } from "../media/VideoPlayer";
10
19
  import type { ResolveAsset } from "../types";
11
20
  import { Markdown } from "./Markdown";
21
+ import { aspectRatio, type PartState, partStyle } from "./motion";
22
+ import { usePresence } from "./RevealMotion";
12
23
 
13
24
  export interface BlocksContext {
14
25
  reveal: RevealState;
15
26
  resolveAsset: ResolveAsset;
16
27
  subtitles: boolean;
17
28
  onSubtitlesChange(subtitles: boolean): void;
29
+ /** What the slide's effects do to each part they target, from `getPartEffects`. */
30
+ effects?: ReadonlyMap<string, PartEffect>;
31
+ /** The learner prefers reduced motion: parts change at once. */
32
+ calm?: boolean;
33
+ /** For an editor: every part is drawn whatever its timing, marked `is-unrevealed` when it would wait. */
34
+ revealAll?: boolean;
35
+ /** For an editor: drawn at each place a block can be added, before every shown block and at the end. */
36
+ renderInsert?(place: InsertPlace): React.ReactNode;
18
37
  }
19
38
 
20
- export function Blocks({ blocks, context }: { blocks: Array<Block | ContentBlock>; context: BlocksContext }) {
39
+ /** Where blocks stand: on the slide, in a column or in a box. */
40
+ export type InsertContainer = { kind: "slide" } | { kind: "column"; id: string } | { kind: "box"; id: string };
41
+
42
+ /** A place a block can be added: in a container, before the block at `index` (or at the end). */
43
+ export type InsertPlace = { container: InsertContainer; index: number };
44
+
45
+ export function Blocks({
46
+ blocks,
47
+ context,
48
+ container,
49
+ }: {
50
+ blocks: Array<Block | ContentBlock | BoxContentBlock>;
51
+ context: BlocksContext;
52
+ /** Where the blocks stand, for an editor's places to add one. */
53
+ container?: InsertContainer;
54
+ }) {
55
+ let insert = container && context.renderInsert ? context.renderInsert : null;
21
56
  return (
22
57
  <>
23
- {blocks.map((block) => (
24
- <BlockView key={block.id} block={block} context={context} />
58
+ {blocks.map((block, index) => (
59
+ <Fragment key={block.id}>
60
+ {/* An effect draws nothing, so it has no place of its own to add next to */}
61
+ {insert && container && block.type !== "effect" && (
62
+ <div className="ob-course-insert">{insert({ container, index })}</div>
63
+ )}
64
+ <BlockView block={block} context={context} />
65
+ </Fragment>
25
66
  ))}
67
+ {insert && container && <div className="ob-course-insert">{insert({ container, index: blocks.length })}</div>}
26
68
  </>
27
69
  );
28
70
  }
@@ -31,41 +73,88 @@ type Visibility = "shown" | "pending" | "gone";
31
73
 
32
74
  /**
33
75
  * A part that has not been revealed yet keeps its place, so the slide does not jump when it
34
- * appears. A part removed by `hideAt` gives its place up to whatever comes after it.
76
+ * appears. A part with `hideAt` is a passing one: it takes no place before it shows or after it
77
+ * has gone, so parts that replace each other in time stand in the same spot.
35
78
  */
36
- function getVisibility(part: Timed, reveal: RevealState): Visibility {
79
+ export function getVisibility(part: Timed, reveal: RevealState): Visibility {
37
80
  if (isVisible(part, reveal)) return "shown";
38
- if (part.hideAt && reveal.startedCues.has(part.hideAt)) return "gone";
39
- return "pending";
81
+ return part.hideAt ? "gone" : "pending";
82
+ }
83
+
84
+ function lookClasses(block: { caps?: boolean; shadow?: boolean }) {
85
+ return clsx(block.caps && "ob-course-look--caps", block.shadow && "ob-course-look--shadow");
86
+ }
87
+
88
+ /** A callout and a box share one surface, coloured by `data-color` and drawn by its variant. */
89
+ function surfaceClasses(className: string, block: { variant?: SurfaceVariant }) {
90
+ return clsx(className, "ob-course-surface", `ob-course-surface--${block.variant ?? "bordered"}`);
91
+ }
92
+
93
+ interface PartShown {
94
+ state: PartState;
95
+ /** Came into the page after the slide was first drawn, so it fades in. */
96
+ entering: boolean;
40
97
  }
41
98
 
42
- function partProps(part: Timed, visibility: Visibility, className: string) {
43
- let pending = visibility === "pending";
99
+ /**
100
+ * How a part is drawn now, or null when it is not in the page. A part that goes away fades out
101
+ * first (`leaving`); the slide lifts it out of the flow meanwhile.
102
+ */
103
+ function usePart(part: Timed, context: BlocksContext): PartShown | null {
104
+ let visibility = context.revealAll ? "shown" : getVisibility(part, context.reveal);
105
+ let presence = usePresence(visibility !== "gone", context.calm ?? false);
106
+ let inPage = presence !== "absent";
107
+ /*
108
+ * The view stays mounted while its part is out of the page, so a part that comes in later is one
109
+ * whose view saw it absent: it fades in. Parts there when the slide is drawn do not.
110
+ */
111
+ let [cameLate, setCameLate] = useState(false);
112
+ let [wasInPage, setWasInPage] = useState(inPage);
113
+ if (inPage !== wasInPage) {
114
+ setWasInPage(inPage);
115
+ if (inPage) setCameLate(true);
116
+ }
117
+ if (!inPage) return null;
118
+ let state: PartState = presence === "leaving" ? "leaving" : (visibility as "shown" | "pending");
119
+ // A part that waits keeps the fade for when it shows; the fade on mount would end unseen
120
+ return { state, entering: cameLate && state !== "pending" };
121
+ }
122
+
123
+ function partProps(part: Timed, shown: PartShown, className: string, context: BlocksContext, canvasAspect?: number) {
124
+ let hidden = shown.state !== "shown";
44
125
  return {
45
- className: clsx(className, pending && "is-pending"),
126
+ className: clsx(
127
+ className,
128
+ shown.state === "pending" && "is-pending",
129
+ shown.state === "leaving" && "is-leaving",
130
+ shown.entering && "is-entering",
131
+ context.revealAll && !isVisible(part, context.reveal) && "is-unrevealed",
132
+ ),
46
133
  "data-part": part.id,
47
- "aria-hidden": pending || undefined,
48
- inert: pending || undefined,
134
+ "aria-hidden": hidden || undefined,
135
+ inert: hidden || undefined,
136
+ style: partStyle({ effect: context.effects?.get(part.id), delay: part.delay, state: shown.state, canvasAspect }),
49
137
  };
50
138
  }
51
139
 
52
140
  function BlockView({ block, context }: { block: Block | ContentBlock; context: BlocksContext }) {
53
- let visibility = getVisibility(block, context.reveal);
54
- if (visibility === "gone") return null;
55
- let props = partProps(block, visibility, `ob-course-block ob-course-block--${block.type}`);
141
+ let shown = usePart(block, context);
142
+ // An effect shows nothing itself: it acts on its targets through `context.effects`
143
+ if (!shown || block.type === "effect") return null;
144
+ let props = partProps(block, shown, `ob-course-block ob-course-block--${block.type}`, context);
56
145
 
57
146
  switch (block.type) {
58
147
  case "heading": {
59
148
  let Tag = `h${(block.level ?? 1) + 1}` as "h2" | "h3" | "h4";
60
149
  return (
61
- <Tag {...props} className={clsx(props.className, `ob-course-heading--${block.level ?? 1}`)}>
62
- {block.text}
150
+ <Tag {...props} className={clsx(props.className, `ob-course-heading--${block.level ?? 1}`, lookClasses(block))}>
151
+ <Markdown inline>{block.text}</Markdown>
63
152
  </Tag>
64
153
  );
65
154
  }
66
155
  case "text":
67
156
  return (
68
- <div {...props}>
157
+ <div {...props} className={clsx(props.className, lookClasses(block))}>
69
158
  <Markdown>{block.text}</Markdown>
70
159
  </div>
71
160
  );
@@ -73,15 +162,7 @@ function BlockView({ block, context }: { block: Block | ContentBlock; context: B
73
162
  let Tag: React.ElementType = block.ordered ? "ol" : "ul";
74
163
  return (
75
164
  <Tag {...props}>
76
- {block.items.map((item) => {
77
- let itemVisibility = getVisibility(item, context.reveal);
78
- if (itemVisibility === "gone") return null;
79
- return (
80
- <li key={item.id} {...partProps(item, itemVisibility, "ob-course-list-item")}>
81
- <Markdown className="ob-course-markdown--inline">{item.text}</Markdown>
82
- </li>
83
- );
84
- })}
165
+ <ListItems nodes={nestItems(block.items)} context={context} />
85
166
  </Tag>
86
167
  );
87
168
  }
@@ -107,22 +188,43 @@ function BlockView({ block, context }: { block: Block | ContentBlock; context: B
107
188
  );
108
189
  case "callout":
109
190
  return (
110
- <div {...props} data-color={block.tone ?? "neutral"}>
191
+ <div {...props} className={surfaceClasses(props.className, block)} data-color={block.tone ?? "neutral"}>
111
192
  <Markdown>{block.text}</Markdown>
112
193
  </div>
113
194
  );
195
+ case "box":
196
+ return (
197
+ <div {...props} className={surfaceClasses(props.className, block)} data-color={block.tone ?? "neutral"}>
198
+ <Blocks blocks={block.blocks} context={context} container={{ kind: "box", id: block.id }} />
199
+ </div>
200
+ );
114
201
  case "video-link":
115
202
  return (
116
203
  <div {...props}>
117
204
  <VideoLink block={block} context={context} />
118
205
  </div>
119
206
  );
207
+ case "canvas":
208
+ return (
209
+ <div {...props}>
210
+ <div className="ob-course-canvas" data-color-scheme="light" style={{ aspectRatio: block.aspect ?? "16 / 9" }}>
211
+ {block.items.map((item) => (
212
+ <CanvasItemView key={item.id} item={item} aspect={aspectRatio(block.aspect)} context={context} />
213
+ ))}
214
+ </div>
215
+ </div>
216
+ );
120
217
  case "columns":
121
218
  return (
122
219
  <div {...props}>
123
220
  {block.columns.map((column) => (
124
- <div key={column.id} className="ob-course-column" data-part={column.id}>
125
- <Blocks blocks={column.blocks} context={context} />
221
+ <div
222
+ key={column.id}
223
+ className="ob-course-column"
224
+ data-part={column.id}
225
+ style={partStyle({ effect: context.effects?.get(column.id), state: "shown" })}
226
+ >
227
+ <Blocks blocks={column.blocks} context={context} container={{ kind: "column", id: column.id }} />
126
228
  </div>
127
229
  ))}
128
230
  </div>
@@ -130,6 +232,91 @@ function BlockView({ block, context }: { block: Block | ContentBlock; context: B
130
232
  }
131
233
  }
132
234
 
235
+ type ItemNode = { item: ListItem; children: ItemNode[] };
236
+
237
+ /** The flat items as a tree: an indented item belongs to the nearest item above it with a smaller indent. */
238
+ export function nestItems(items: ListItem[]): ItemNode[] {
239
+ let roots: ItemNode[] = [];
240
+ let path: ItemNode[] = [];
241
+ for (let item of items) {
242
+ // An item cannot be more than one level under the one above it
243
+ let depth = Math.min(item.indent ?? 0, path.length);
244
+ let node: ItemNode = { item, children: [] };
245
+ if (depth === 0) roots.push(node);
246
+ else path[depth - 1].children.push(node);
247
+ path.length = depth;
248
+ path.push(node);
249
+ }
250
+ return roots;
251
+ }
252
+
253
+ function ListItems({ nodes, context }: { nodes: ItemNode[]; context: BlocksContext }) {
254
+ return nodes.map((node) => <ListItemView key={node.item.id} node={node} context={context} />);
255
+ }
256
+
257
+ function ListItemView({ node: { item, children }, context }: { node: ItemNode; context: BlocksContext }) {
258
+ let shown = usePart(item, context);
259
+ if (!shown) return null;
260
+ return (
261
+ <li {...partProps(item, shown, "ob-course-list-item", context)}>
262
+ {/* Inline: a paragraph in an inline box puts the bullet on a line of its own in Safari */}
263
+ <Markdown inline className="ob-course-markdown--inline">
264
+ {item.text}
265
+ </Markdown>
266
+ {children.length > 0 && (
267
+ <ul className="ob-course-sublist">
268
+ <ListItems nodes={children} context={context} />
269
+ </ul>
270
+ )}
271
+ </li>
272
+ );
273
+ }
274
+
275
+ const PLACE_PROPERTIES = {
276
+ x: "left",
277
+ y: "top",
278
+ right: "right",
279
+ bottom: "bottom",
280
+ width: "width",
281
+ height: "height",
282
+ } as const;
283
+
284
+ function canvasPlace(item: CanvasItem): React.CSSProperties {
285
+ let style: Record<string, string> = {};
286
+ for (let [key, property] of Object.entries(PLACE_PROPERTIES)) {
287
+ let value = item[key as keyof typeof PLACE_PROPERTIES];
288
+ if (value != null) style[property] = `${value}%`;
289
+ }
290
+ return style;
291
+ }
292
+
293
+ function CanvasItemView({ item, aspect, context }: { item: CanvasItem; aspect: number; context: BlocksContext }) {
294
+ let shown = usePart(item, context);
295
+ if (!shown) return null;
296
+ let props = partProps(item, shown, `ob-course-canvas__item ob-course-canvas__${item.type}`, context, aspect);
297
+
298
+ if (item.type === "image") {
299
+ return (
300
+ <img
301
+ {...props}
302
+ style={{ ...canvasPlace(item), ...props.style }}
303
+ src={context.resolveAsset(item.src)}
304
+ alt={item.alt ?? ""}
305
+ />
306
+ );
307
+ }
308
+ return (
309
+ <div
310
+ {...props}
311
+ className={clsx(props.className, item.surface && `ob-course-canvas__text--${item.surface}`)}
312
+ data-color={item.tone}
313
+ style={{ ...canvasPlace(item), ...props.style, "--ob-course-canvas-size": item.size } as React.CSSProperties}
314
+ >
315
+ <Markdown>{item.text}</Markdown>
316
+ </div>
317
+ );
318
+ }
319
+
133
320
  function VideoLink({
134
321
  block,
135
322
  context,
@@ -0,0 +1,95 @@
1
+ import { render } from "@testing-library/react";
2
+ import { describe, expect, it } from "vitest";
3
+ import type { Block, Step } from "../document/schema";
4
+ import { StepView } from "./StepView";
5
+
6
+ let resolveAsset = (src: string) => src;
7
+
8
+ function slide(blocks: Block[]): Step {
9
+ return { schemaVersion: 2, type: "slide", blocks };
10
+ }
11
+
12
+ let box: Block = {
13
+ id: "box",
14
+ type: "box",
15
+ tone: "brand",
16
+ variant: "filled",
17
+ blocks: [
18
+ { id: "h", type: "heading", text: "Slik gjør du", level: 2 },
19
+ {
20
+ id: "l",
21
+ type: "list",
22
+ items: [
23
+ { id: "i1", text: "Ta på hjelm", reveal: "step" },
24
+ { id: "i2", text: "Sjekk [stroppen](https://example.com)", reveal: "step" },
25
+ ],
26
+ },
27
+ { id: "img", type: "image", src: "/media/course/a.png", size: "full" },
28
+ ],
29
+ };
30
+
31
+ describe("a box", () => {
32
+ it("draws its blocks inside a surface in its tone and variant", () => {
33
+ let { container } = render(<StepView step={slide([box])} resolveAsset={resolveAsset} />);
34
+
35
+ let element = container.querySelector('[data-part="box"]')!;
36
+ expect(element.classList).toContain("ob-course-block--box");
37
+ expect(element.classList).toContain("ob-course-surface");
38
+ expect(element.classList).toContain("ob-course-surface--filled");
39
+ expect(element.getAttribute("data-color")).toBe("brand");
40
+ expect(element.querySelector(':scope > h3[data-part="h"]')).not.toBeNull();
41
+ expect(element.querySelector(':scope > ul[data-part="l"] > li[data-part="i2"] a')).not.toBeNull();
42
+ expect(element.querySelector(':scope > figure[data-part="img"] img')).not.toBeNull();
43
+ });
44
+
45
+ it("is neutral and bordered by default, like a callout", () => {
46
+ let { container } = render(
47
+ <StepView
48
+ step={slide([
49
+ { id: "b", type: "box", blocks: [{ id: "t", type: "text", text: "Hei" }] },
50
+ { id: "c", type: "callout", text: "Husk" },
51
+ { id: "c2", type: "callout", text: "Husk", tone: "brand", variant: "filled" },
52
+ ])}
53
+ resolveAsset={resolveAsset}
54
+ />,
55
+ );
56
+
57
+ for (let id of ["b", "c"]) {
58
+ let element = container.querySelector(`[data-part="${id}"]`)!;
59
+ expect(element.getAttribute("data-color")).toBe("neutral");
60
+ expect(element.classList).toContain("ob-course-surface--bordered");
61
+ }
62
+ let filled = container.querySelector('[data-part="c2"]')!;
63
+ expect(filled.getAttribute("data-color")).toBe("brand");
64
+ expect(filled.classList).toContain("ob-course-surface--filled");
65
+ });
66
+
67
+ it("reveals its parts one by one, also in a column", () => {
68
+ let blocks: Block[] = [
69
+ {
70
+ id: "cols",
71
+ type: "columns",
72
+ columns: [
73
+ { id: "a", blocks: [box] },
74
+ { id: "b", blocks: [] },
75
+ ],
76
+ },
77
+ ];
78
+ let { container } = render(<StepView step={slide(blocks)} resolveAsset={resolveAsset} stepsShown={1} />);
79
+
80
+ expect(container.querySelector('.ob-course-column [data-part="box"]')).not.toBeNull();
81
+ expect(container.querySelector('[data-part="i1"]')!.classList).not.toContain("is-pending");
82
+ expect(container.querySelector('[data-part="i2"]')!.classList).toContain("is-pending");
83
+ });
84
+
85
+ it("hides its parts with it while it waits", () => {
86
+ let { container } = render(
87
+ <StepView step={slide([{ ...box, reveal: "step" } as Block])} resolveAsset={resolveAsset} stepsShown={0} />,
88
+ );
89
+
90
+ let element = container.querySelector('[data-part="box"]')!;
91
+ expect(element.classList).toContain("is-pending");
92
+ expect(element.getAttribute("aria-hidden")).toBe("true");
93
+ expect(element.hasAttribute("inert")).toBe(true);
94
+ });
95
+ });
@@ -0,0 +1,46 @@
1
+ import { renderToStaticMarkup } from "react-dom/server";
2
+ import { describe, expect, it } from "vitest";
3
+ import { Markdown } from "./Markdown";
4
+
5
+ function html(text: string) {
6
+ return renderToStaticMarkup(<Markdown>{text}</Markdown>);
7
+ }
8
+
9
+ describe("Markdown", () => {
10
+ it("draws the text tags, with Markdown inside them", () => {
11
+ expect(html("<big>**Støv**</big> som pustes inn")).toContain("<big><strong>Støv</strong></big> som pustes inn");
12
+ expect(html("H<sub>2</sub>O og <u>viktig</u>")).toContain("H<sub>2</sub>O og <u>viktig</u>");
13
+ });
14
+
15
+ it("drops the attributes of a text tag", () => {
16
+ let out = html('<big style="color:red" onclick="alert(1)">Stor</big>');
17
+ expect(out).toContain("<big>Stor</big>");
18
+ });
19
+
20
+ it("colours a span that names a theme colour, and nothing else about it", () => {
21
+ expect(html('Det er <span data-color="danger" style="font-size:9em">innånding</span> som er farlig')).toContain(
22
+ '<span class="ob-course-tone" data-color="danger">innånding</span>',
23
+ );
24
+ expect(html('<span data-color="brand">Ølen Betong</span>')).toContain(
25
+ '<span class="ob-course-tone" data-color="brand">Ølen Betong</span>',
26
+ );
27
+ expect(html('<span data-color="url(x)">tekst</span>')).not.toContain("url(x)");
28
+ });
29
+
30
+ it("writes a heading as one line", () => {
31
+ let out = renderToStaticMarkup(<Markdown inline>{"Støv er **ikke** bare støv"}</Markdown>);
32
+ expect(out).toContain("Støv er <strong>ikke</strong> bare støv");
33
+ expect(out).not.toContain("<p");
34
+ expect(out).not.toContain("<div");
35
+ });
36
+
37
+ it("wraps a single paragraph too, so its links and tags are styled", () => {
38
+ expect(html("[lenke](https://example.com)")).toMatch(/^<div class="ob-course-markdown"><p><a /);
39
+ });
40
+
41
+ it("leaves only the text of any other tag", () => {
42
+ let out = html('Før <iframe src="https://example.com"></iframe><script>alert(1)</script><form>skjema</form> etter');
43
+ expect(out).not.toMatch(/<(iframe|script|form)/);
44
+ expect(out).toContain("skjema");
45
+ });
46
+ });
@@ -1,17 +1,55 @@
1
1
  import MarkdownToJSX from "markdown-to-jsx";
2
+ import { createElement, Fragment } from "react";
3
+
4
+ /** What Markdown itself produces. */
5
+ const MARKDOWN_TAGS = new Set(
6
+ "p strong em del a ul ol li blockquote code pre br hr h1 h2 h3 h4 h5 h6 span div img table thead tbody tr th td input".split(
7
+ " ",
8
+ ),
9
+ );
10
+
11
+ /** The tags a text may use for what Markdown has no syntax for. They take no attributes. */
12
+ export const TEXT_TAGS = new Set(["big", "small", "u", "sup", "sub", "mark"]);
13
+
14
+ /** The colours a `<span data-color>` may name; they come from the theme. */
15
+ export const TEXT_TONES = new Set(["info", "success", "warning", "danger", "brand"]);
16
+
17
+ type ElementProps = (Record<string, unknown> & { key?: string | number }) | null;
2
18
 
3
19
  const OPTIONS = {
4
20
  forceBlock: true,
5
- // Course text is written in the editor, not as HTML; raw tags are shown as text.
6
- disableParsingRawHTML: true,
21
+ // A single paragraph is otherwise returned bare, without the element that carries the class
22
+ forceWrapper: true,
7
23
  overrides: {
8
24
  a: { props: { target: "_blank", rel: "noreferrer" } },
9
25
  },
26
+ // Course text is Markdown, not HTML: of the tags written into it only the few in TEXT_TAGS
27
+ // are drawn, and without their attributes, plus a span that names one of the theme's colours.
28
+ // Any other tag leaves just its text.
29
+ createElement(type: unknown, props: ElementProps, ...children: React.ReactNode[]) {
30
+ let tone = type === "span" ? props?.["data-color"] : undefined;
31
+ if (typeof tone === "string" && TEXT_TONES.has(tone)) {
32
+ return createElement("span", { key: props?.key, className: "ob-course-tone", "data-color": tone }, ...children);
33
+ }
34
+ // Any other span keeps its class (the wrapper of an inline text has one) and nothing else
35
+ if (type === "span") return createElement("span", { key: props?.key, className: props?.className }, ...children);
36
+ if (typeof type === "string" && TEXT_TAGS.has(type)) return createElement(type, { key: props?.key }, ...children);
37
+ if (typeof type === "string" && !MARKDOWN_TAGS.has(type)) {
38
+ return createElement(Fragment, { key: props?.key }, ...children);
39
+ }
40
+ return createElement(type as React.ElementType, props, ...children);
41
+ },
10
42
  };
11
43
 
12
- export function Markdown({ children, className }: { children: string; className?: string }) {
44
+ const INLINE_OPTIONS = { ...OPTIONS, forceBlock: false, forceInline: true };
45
+
46
+ /** `inline`: one line without paragraphs, for a heading. */
47
+ export function Markdown({ children, className, inline }: { children: string; className?: string; inline?: boolean }) {
13
48
  return (
14
- <MarkdownToJSX className={className ? `ob-course-markdown ${className}` : "ob-course-markdown"} options={OPTIONS}>
49
+ <MarkdownToJSX
50
+ className={className ? `ob-course-markdown ${className}` : "ob-course-markdown"}
51
+ options={(inline ? INLINE_OPTIONS : OPTIONS) as never}
52
+ >
15
53
  {children}
16
54
  </MarkdownToJSX>
17
55
  );
@@ -0,0 +1,82 @@
1
+ import { act, render } from "@testing-library/react";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { getRevealLeaders, getRevealSteps } from "../document/cues";
4
+ import { getPartEffects } from "../document/effects";
5
+ import type { Block } from "../document/schema";
6
+ import { Blocks, type BlocksContext } from "./Blocks";
7
+
8
+ let blocks: Block[] = [
9
+ { id: "s1", type: "text", text: "Scene 1", hideAt: "c1" },
10
+ { id: "s2", type: "text", text: "Scene 2", revealAt: "c1", hideAt: "c2" },
11
+ { id: "zoom", type: "effect", target: "s2", scale: 1.5, move: { y: -1 }, revealAt: "c1", duration: 500 },
12
+ { id: "label", type: "text", text: "Label", reveal: "with-previous", delay: 400 },
13
+ ];
14
+
15
+ function context(cues: string[]): BlocksContext {
16
+ let reveal = {
17
+ stepsShown: 0,
18
+ revealSteps: getRevealSteps(blocks),
19
+ startedCues: new Set(cues),
20
+ leaders: getRevealLeaders(blocks),
21
+ };
22
+ return {
23
+ reveal,
24
+ resolveAsset: (src) => src,
25
+ subtitles: false,
26
+ onSubtitlesChange() {},
27
+ effects: getPartEffects(blocks, reveal),
28
+ };
29
+ }
30
+
31
+ let part = (container: HTMLElement, id: string) => container.querySelector<HTMLElement>(`[data-part="${id}"]`);
32
+
33
+ describe("parts that replace each other", () => {
34
+ beforeEach(() => vi.useFakeTimers());
35
+ afterEach(() => vi.useRealTimers());
36
+
37
+ it("fades the outgoing part out before it leaves the page, and the incoming one in", () => {
38
+ let { container, rerender } = render(<Blocks blocks={blocks} context={context([])} />);
39
+ expect(part(container, "s1")?.className).not.toContain("is-entering");
40
+ expect(part(container, "s2")).toBeNull();
41
+
42
+ rerender(<Blocks blocks={blocks} context={context(["c1"])} />);
43
+ expect(part(container, "s1")).toHaveClass("is-leaving");
44
+ expect(part(container, "s1")).toHaveAttribute("aria-hidden", "true");
45
+ expect(part(container, "s2")).toHaveClass("is-entering");
46
+
47
+ act(() => vi.advanceTimersByTime(300));
48
+ expect(part(container, "s1")).toBeNull();
49
+ });
50
+
51
+ it("keeps nothing behind when the narration is scrubbed back during the fade", () => {
52
+ let { container, rerender } = render(<Blocks blocks={blocks} context={context([])} />);
53
+ rerender(<Blocks blocks={blocks} context={context(["c1"])} />);
54
+ rerender(<Blocks blocks={blocks} context={context([])} />);
55
+ expect(part(container, "s1")).not.toHaveClass("is-leaving");
56
+ expect(part(container, "s2")).toHaveClass("is-leaving");
57
+
58
+ act(() => vi.advanceTimersByTime(300));
59
+ expect(container.querySelectorAll("[data-part]")).toHaveLength(2);
60
+ expect(part(container, "s2")).toBeNull();
61
+ });
62
+ });
63
+
64
+ describe("effects and delays on parts", () => {
65
+ it("draws nothing for an effect and styles its target", () => {
66
+ let { container } = render(<Blocks blocks={blocks} context={context(["c1"])} />);
67
+ expect(part(container, "zoom")).toBeNull();
68
+ let target = part(container, "s2")!;
69
+ expect(target.style.scale).toBe("1.5");
70
+ expect(target.style.translate).toContain("-1 * var(--ob-course-em)");
71
+ expect(target.style.transition).toContain("translate 500ms ease");
72
+ });
73
+
74
+ it("shows a with-previous part with its leader, after its delay", () => {
75
+ let { container, rerender } = render(<Blocks blocks={blocks} context={context([])} />);
76
+ expect(part(container, "label")).toHaveClass("is-pending");
77
+ rerender(<Blocks blocks={blocks} context={context(["c1"])} />);
78
+ let label = part(container, "label")!;
79
+ expect(label).not.toHaveClass("is-pending");
80
+ expect(label.style.transition).toBe("opacity 300ms ease 400ms, visibility 0s linear 400ms");
81
+ });
82
+ });