@olenbetong/synergi-course 2.0.0 → 2.1.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 (87) 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 +115 -14
  7. package/es/document/effects.d.ts +30 -0
  8. package/es/document/effects.js +74 -0
  9. package/es/document/schema.d.ts +924 -136
  10. package/es/document/schema.js +139 -5
  11. package/es/document/validate.d.ts +2 -1
  12. package/es/document/validate.js +73 -2
  13. package/es/index.d.ts +6 -2
  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 +58 -0
  19. package/es/player/CoursePlayer.js +27 -13
  20. package/es/player/useFullScreen.d.ts +17 -0
  21. package/es/player/useFullScreen.js +83 -0
  22. package/es/player/useMediaQuery.d.ts +7 -0
  23. package/es/player/useMediaQuery.js +16 -0
  24. package/es/steps/Blocks.d.ts +20 -1
  25. package/es/steps/Blocks.js +103 -22
  26. package/es/steps/Markdown.d.ts +7 -1
  27. package/es/steps/Markdown.js +31 -4
  28. package/es/steps/RevealMotion.d.ts +29 -0
  29. package/es/steps/RevealMotion.js +55 -0
  30. package/es/steps/SlideStepView.d.ts +5 -3
  31. package/es/steps/SlideStepView.js +38 -15
  32. package/es/steps/StepBodyProps.d.ts +7 -1
  33. package/es/steps/StepView.css +328 -12
  34. package/es/steps/StepView.d.ts +8 -2
  35. package/es/steps/StepView.js +2 -2
  36. package/es/steps/motion.d.ts +59 -0
  37. package/es/steps/motion.js +136 -0
  38. package/es/transitions/Transitions.css +114 -0
  39. package/es/transitions/plan.d.ts +66 -0
  40. package/es/transitions/plan.js +185 -0
  41. package/es/transitions/playStepTransition.d.ts +23 -0
  42. package/es/transitions/playStepTransition.js +131 -0
  43. package/es/types.d.ts +3 -1
  44. package/package.json +4 -4
  45. package/src/chrome/CategoryHeader.css +28 -0
  46. package/src/completion/CourseCompletion.css +53 -0
  47. package/src/completion/CourseCompletion.test.tsx +45 -0
  48. package/src/completion/CourseCompletion.tsx +98 -0
  49. package/src/document/cues.ts +142 -13
  50. package/src/document/document.test.ts +1 -1
  51. package/src/document/effects.ts +105 -0
  52. package/src/document/reveal.test.ts +263 -0
  53. package/src/document/schema.ts +161 -5
  54. package/src/document/validate.ts +77 -3
  55. package/src/index.ts +35 -0
  56. package/src/media/Media.css +16 -0
  57. package/src/media/icons.tsx +8 -0
  58. package/src/player/CoursePlayer.css +58 -0
  59. package/src/player/CoursePlayer.test.tsx +70 -6
  60. package/src/player/CoursePlayer.tsx +68 -17
  61. package/src/player/fullScreen.test.tsx +70 -0
  62. package/src/player/useFullScreen.ts +91 -0
  63. package/src/player/useMediaQuery.ts +21 -0
  64. package/src/steps/Blocks.test.ts +34 -0
  65. package/src/steps/Blocks.tsx +166 -26
  66. package/src/steps/Markdown.test.tsx +43 -0
  67. package/src/steps/Markdown.tsx +42 -4
  68. package/src/steps/Presence.test.tsx +82 -0
  69. package/src/steps/RevealMotion.ts +66 -0
  70. package/src/steps/SlideStepView.tsx +67 -17
  71. package/src/steps/StepBodyProps.ts +7 -1
  72. package/src/steps/StepView.css +328 -12
  73. package/src/steps/StepView.test.tsx +41 -0
  74. package/src/steps/StepView.tsx +9 -1
  75. package/src/steps/motion.test.ts +98 -0
  76. package/src/steps/motion.ts +178 -0
  77. package/src/steps/visibility.test.ts +24 -0
  78. package/src/transitions/Transitions.css +114 -0
  79. package/src/transitions/plan.ts +258 -0
  80. package/src/transitions/playStepTransition.ts +162 -0
  81. package/src/transitions/transitions.test.ts +274 -0
  82. package/src/types.ts +3 -1
  83. package/es/Transitions.css +0 -55
  84. package/es/Transitions.d.ts +0 -10
  85. package/es/Transitions.js +0 -24
  86. package/src/Transitions.css +0 -55
  87. package/src/Transitions.ts +0 -35
@@ -3,18 +3,25 @@ import clsx from "clsx";
3
3
  import type React from "react";
4
4
  import { 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 { Block, CanvasItem, ContentBlock, ListItem, Timed } from "../document/schema";
7
8
  import { getLocalizedString } from "../i18n";
8
9
  import { PlayIcon } from "../media/icons";
9
10
  import { VideoPlayer } from "../media/VideoPlayer";
10
11
  import type { ResolveAsset } from "../types";
11
12
  import { Markdown } from "./Markdown";
13
+ import { aspectRatio, type PartState, partStyle } from "./motion";
14
+ import { usePresence } from "./RevealMotion";
12
15
 
13
16
  export interface BlocksContext {
14
17
  reveal: RevealState;
15
18
  resolveAsset: ResolveAsset;
16
19
  subtitles: boolean;
17
20
  onSubtitlesChange(subtitles: boolean): void;
21
+ /** What the slide's effects do to each part they target, from `getPartEffects`. */
22
+ effects?: ReadonlyMap<string, PartEffect>;
23
+ /** The learner prefers reduced motion: parts change at once. */
24
+ calm?: boolean;
18
25
  }
19
26
 
20
27
  export function Blocks({ blocks, context }: { blocks: Array<Block | ContentBlock>; context: BlocksContext }) {
@@ -31,41 +38,82 @@ type Visibility = "shown" | "pending" | "gone";
31
38
 
32
39
  /**
33
40
  * 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.
41
+ * appears. A part with `hideAt` is a passing one: it takes no place before it shows or after it
42
+ * has gone, so parts that replace each other in time stand in the same spot.
35
43
  */
36
- function getVisibility(part: Timed, reveal: RevealState): Visibility {
44
+ export function getVisibility(part: Timed, reveal: RevealState): Visibility {
37
45
  if (isVisible(part, reveal)) return "shown";
38
- if (part.hideAt && reveal.startedCues.has(part.hideAt)) return "gone";
39
- return "pending";
46
+ return part.hideAt ? "gone" : "pending";
40
47
  }
41
48
 
42
- function partProps(part: Timed, visibility: Visibility, className: string) {
43
- let pending = visibility === "pending";
49
+ function lookClasses(block: { caps?: boolean; shadow?: boolean }) {
50
+ return clsx(block.caps && "ob-course-look--caps", block.shadow && "ob-course-look--shadow");
51
+ }
52
+
53
+ interface PartShown {
54
+ state: PartState;
55
+ /** Came into the page after the slide was first drawn, so it fades in. */
56
+ entering: boolean;
57
+ }
58
+
59
+ /**
60
+ * How a part is drawn now, or null when it is not in the page. A part that goes away fades out
61
+ * first (`leaving`); the slide lifts it out of the flow meanwhile.
62
+ */
63
+ function usePart(part: Timed, context: BlocksContext): PartShown | null {
64
+ let visibility = getVisibility(part, context.reveal);
65
+ let presence = usePresence(visibility !== "gone", context.calm ?? false);
66
+ let inPage = presence !== "absent";
67
+ /*
68
+ * The view stays mounted while its part is out of the page, so a part that comes in later is one
69
+ * whose view saw it absent: it fades in. Parts there when the slide is drawn do not.
70
+ */
71
+ let [cameLate, setCameLate] = useState(false);
72
+ let [wasInPage, setWasInPage] = useState(inPage);
73
+ if (inPage !== wasInPage) {
74
+ setWasInPage(inPage);
75
+ if (inPage) setCameLate(true);
76
+ }
77
+ if (!inPage) return null;
78
+ let state: PartState = presence === "leaving" ? "leaving" : (visibility as "shown" | "pending");
79
+ // A part that waits keeps the fade for when it shows; the fade on mount would end unseen
80
+ return { state, entering: cameLate && state !== "pending" };
81
+ }
82
+
83
+ function partProps(part: Timed, shown: PartShown, className: string, context: BlocksContext, canvasAspect?: number) {
84
+ let hidden = shown.state !== "shown";
44
85
  return {
45
- className: clsx(className, pending && "is-pending"),
86
+ className: clsx(
87
+ className,
88
+ shown.state === "pending" && "is-pending",
89
+ shown.state === "leaving" && "is-leaving",
90
+ shown.entering && "is-entering",
91
+ ),
46
92
  "data-part": part.id,
47
- "aria-hidden": pending || undefined,
48
- inert: pending || undefined,
93
+ "aria-hidden": hidden || undefined,
94
+ inert: hidden || undefined,
95
+ style: partStyle({ effect: context.effects?.get(part.id), delay: part.delay, state: shown.state, canvasAspect }),
49
96
  };
50
97
  }
51
98
 
52
99
  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}`);
100
+ let shown = usePart(block, context);
101
+ // An effect shows nothing itself: it acts on its targets through `context.effects`
102
+ if (!shown || block.type === "effect") return null;
103
+ let props = partProps(block, shown, `ob-course-block ob-course-block--${block.type}`, context);
56
104
 
57
105
  switch (block.type) {
58
106
  case "heading": {
59
107
  let Tag = `h${(block.level ?? 1) + 1}` as "h2" | "h3" | "h4";
60
108
  return (
61
- <Tag {...props} className={clsx(props.className, `ob-course-heading--${block.level ?? 1}`)}>
62
- {block.text}
109
+ <Tag {...props} className={clsx(props.className, `ob-course-heading--${block.level ?? 1}`, lookClasses(block))}>
110
+ <Markdown inline>{block.text}</Markdown>
63
111
  </Tag>
64
112
  );
65
113
  }
66
114
  case "text":
67
115
  return (
68
- <div {...props}>
116
+ <div {...props} className={clsx(props.className, lookClasses(block))}>
69
117
  <Markdown>{block.text}</Markdown>
70
118
  </div>
71
119
  );
@@ -73,15 +121,7 @@ function BlockView({ block, context }: { block: Block | ContentBlock; context: B
73
121
  let Tag: React.ElementType = block.ordered ? "ol" : "ul";
74
122
  return (
75
123
  <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
- })}
124
+ <ListItems nodes={nestItems(block.items)} context={context} />
85
125
  </Tag>
86
126
  );
87
127
  }
@@ -117,11 +157,26 @@ function BlockView({ block, context }: { block: Block | ContentBlock; context: B
117
157
  <VideoLink block={block} context={context} />
118
158
  </div>
119
159
  );
160
+ case "canvas":
161
+ return (
162
+ <div {...props}>
163
+ <div className="ob-course-canvas" data-color-scheme="light" style={{ aspectRatio: block.aspect ?? "16 / 9" }}>
164
+ {block.items.map((item) => (
165
+ <CanvasItemView key={item.id} item={item} aspect={aspectRatio(block.aspect)} context={context} />
166
+ ))}
167
+ </div>
168
+ </div>
169
+ );
120
170
  case "columns":
121
171
  return (
122
172
  <div {...props}>
123
173
  {block.columns.map((column) => (
124
- <div key={column.id} className="ob-course-column" data-part={column.id}>
174
+ <div
175
+ key={column.id}
176
+ className="ob-course-column"
177
+ data-part={column.id}
178
+ style={partStyle({ effect: context.effects?.get(column.id), state: "shown" })}
179
+ >
125
180
  <Blocks blocks={column.blocks} context={context} />
126
181
  </div>
127
182
  ))}
@@ -130,6 +185,91 @@ function BlockView({ block, context }: { block: Block | ContentBlock; context: B
130
185
  }
131
186
  }
132
187
 
188
+ type ItemNode = { item: ListItem; children: ItemNode[] };
189
+
190
+ /** The flat items as a tree: an indented item belongs to the nearest item above it with a smaller indent. */
191
+ export function nestItems(items: ListItem[]): ItemNode[] {
192
+ let roots: ItemNode[] = [];
193
+ let path: ItemNode[] = [];
194
+ for (let item of items) {
195
+ // An item cannot be more than one level under the one above it
196
+ let depth = Math.min(item.indent ?? 0, path.length);
197
+ let node: ItemNode = { item, children: [] };
198
+ if (depth === 0) roots.push(node);
199
+ else path[depth - 1].children.push(node);
200
+ path.length = depth;
201
+ path.push(node);
202
+ }
203
+ return roots;
204
+ }
205
+
206
+ function ListItems({ nodes, context }: { nodes: ItemNode[]; context: BlocksContext }) {
207
+ return nodes.map((node) => <ListItemView key={node.item.id} node={node} context={context} />);
208
+ }
209
+
210
+ function ListItemView({ node: { item, children }, context }: { node: ItemNode; context: BlocksContext }) {
211
+ let shown = usePart(item, context);
212
+ if (!shown) return null;
213
+ return (
214
+ <li {...partProps(item, shown, "ob-course-list-item", context)}>
215
+ {/* Inline: a paragraph in an inline box puts the bullet on a line of its own in Safari */}
216
+ <Markdown inline className="ob-course-markdown--inline">
217
+ {item.text}
218
+ </Markdown>
219
+ {children.length > 0 && (
220
+ <ul className="ob-course-sublist">
221
+ <ListItems nodes={children} context={context} />
222
+ </ul>
223
+ )}
224
+ </li>
225
+ );
226
+ }
227
+
228
+ const PLACE_PROPERTIES = {
229
+ x: "left",
230
+ y: "top",
231
+ right: "right",
232
+ bottom: "bottom",
233
+ width: "width",
234
+ height: "height",
235
+ } as const;
236
+
237
+ function canvasPlace(item: CanvasItem): React.CSSProperties {
238
+ let style: Record<string, string> = {};
239
+ for (let [key, property] of Object.entries(PLACE_PROPERTIES)) {
240
+ let value = item[key as keyof typeof PLACE_PROPERTIES];
241
+ if (value != null) style[property] = `${value}%`;
242
+ }
243
+ return style;
244
+ }
245
+
246
+ function CanvasItemView({ item, aspect, context }: { item: CanvasItem; aspect: number; context: BlocksContext }) {
247
+ let shown = usePart(item, context);
248
+ if (!shown) return null;
249
+ let props = partProps(item, shown, `ob-course-canvas__item ob-course-canvas__${item.type}`, context, aspect);
250
+
251
+ if (item.type === "image") {
252
+ return (
253
+ <img
254
+ {...props}
255
+ style={{ ...canvasPlace(item), ...props.style }}
256
+ src={context.resolveAsset(item.src)}
257
+ alt={item.alt ?? ""}
258
+ />
259
+ );
260
+ }
261
+ return (
262
+ <div
263
+ {...props}
264
+ className={clsx(props.className, item.surface && `ob-course-canvas__text--${item.surface}`)}
265
+ data-color={item.tone}
266
+ style={{ ...canvasPlace(item), ...props.style, "--ob-course-canvas-size": item.size } as React.CSSProperties}
267
+ >
268
+ <Markdown>{item.text}</Markdown>
269
+ </div>
270
+ );
271
+ }
272
+
133
273
  function VideoLink({
134
274
  block,
135
275
  context,
@@ -0,0 +1,43 @@
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="url(x)">tekst</span>')).not.toContain("url(x)");
25
+ });
26
+
27
+ it("writes a heading as one line", () => {
28
+ let out = renderToStaticMarkup(<Markdown inline>{"Støv er **ikke** bare støv"}</Markdown>);
29
+ expect(out).toContain("Støv er <strong>ikke</strong> bare støv");
30
+ expect(out).not.toContain("<p");
31
+ expect(out).not.toContain("<div");
32
+ });
33
+
34
+ it("wraps a single paragraph too, so its links and tags are styled", () => {
35
+ expect(html("[lenke](https://example.com)")).toMatch(/^<div class="ob-course-markdown"><p><a /);
36
+ });
37
+
38
+ it("leaves only the text of any other tag", () => {
39
+ let out = html('Før <iframe src="https://example.com"></iframe><script>alert(1)</script><form>skjema</form> etter');
40
+ expect(out).not.toMatch(/<(iframe|script|form)/);
41
+ expect(out).toContain("skjema");
42
+ });
43
+ });
@@ -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"]);
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
+ });
@@ -0,0 +1,66 @@
1
+ import { Component, type RefObject, useEffect, useState } from "react";
2
+ import { FADE_MS, getGlides, measureParts, type PartBox, pinLeaving, runGlides, unpinReturned } from "./motion";
3
+
4
+ /** Whether the learner asked for less motion. Read once per render; the setting rarely changes. */
5
+ export function prefersCalm() {
6
+ return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
7
+ }
8
+
9
+ /**
10
+ * A part that goes away stays for the length of its fade first. `leaving` lasts `FADE_MS`, then the
11
+ * part is absent; coming back in the meantime makes it present again at once, so stepping back or
12
+ * scrubbing the narration leaves nothing behind.
13
+ */
14
+ export function usePresence(present: boolean, calm: boolean): "present" | "leaving" | "absent" {
15
+ let [leaving, setLeaving] = useState(false);
16
+ let [wasPresent, setWasPresent] = useState(present);
17
+ if (present !== wasPresent) {
18
+ setWasPresent(present);
19
+ setLeaving(!present && !calm);
20
+ }
21
+
22
+ useEffect(() => {
23
+ if (!leaving) return;
24
+ let timer = setTimeout(() => setLeaving(false), FADE_MS);
25
+ return () => clearTimeout(timer);
26
+ }, [leaving]);
27
+
28
+ if (present) return "present";
29
+ return leaving ? "leaving" : "absent";
30
+ }
31
+
32
+ interface RevealMotionProps {
33
+ root: RefObject<HTMLElement | null>;
34
+ /** Names what is shown. A change of it with the same `source` is a reveal. */
35
+ signature: string;
36
+ /** The blocks: a change of them is an edit, or another step, and never glides. */
37
+ source: unknown;
38
+ calm: boolean;
39
+ }
40
+
41
+ /**
42
+ * Glides the parts a reveal pushed to another place, and lifts the parts that fade out out of the
43
+ * flow. Drawn inside the slide; it renders nothing. A class, since `getSnapshotBeforeUpdate` is
44
+ * where React lets a component read the page as it was just before a change is put in it.
45
+ */
46
+ export class RevealMotion extends Component<RevealMotionProps> {
47
+ getSnapshotBeforeUpdate(previous: RevealMotionProps): Map<string, PartBox> | null {
48
+ let element = this.props.root.current;
49
+ let reveal = previous.source === this.props.source && previous.signature !== this.props.signature;
50
+ return reveal && element ? measureParts(element) : null;
51
+ }
52
+
53
+ componentDidUpdate(_previous: RevealMotionProps, _state: unknown, before: Map<string, PartBox> | null) {
54
+ let element = this.props.root.current;
55
+ if (!element) return;
56
+ unpinReturned(element);
57
+ if (!before) return;
58
+ pinLeaving(element, before);
59
+ if (this.props.calm) return;
60
+ runGlides(element, getGlides(before, measureParts(element)));
61
+ }
62
+
63
+ render() {
64
+ return null;
65
+ }
66
+ }
@@ -1,15 +1,19 @@
1
1
  import clsx from "clsx";
2
- import { useEffect, useLayoutEffect, useMemo, useRef } from "react";
3
- import { getRevealSteps } from "../document/cues";
2
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { getRevealNavigation, getRevealState, getRevealSteps, getTimedParts } from "../document/cues";
4
+ import { getActiveEffects, getPartEffects } from "../document/effects";
4
5
  import type { SlideStep } from "../document/schema";
5
6
  import { Subtitles } from "../media/MediaControls";
6
7
  import { NarrationPlayer, useNarration } from "../media/Narration";
7
- import { Blocks, type BlocksContext } from "./Blocks";
8
+ import { Blocks, type BlocksContext, getVisibility } from "./Blocks";
8
9
  import type { StepBodyProps } from "./StepBodyProps";
10
+ import { prefersCalm, RevealMotion } from "./RevealMotion";
9
11
 
10
12
  /**
11
- * Blocks on a page. Done when every `reveal: "step"` part is shown and the narration, if any,
12
- * has played to the end (unless it is `required: false`).
13
+ * Blocks on a page. With narration, its cues show and hide the parts and the slide is done when it
14
+ * has played to the end (or at once when it is `required: false`); Next and Back go to the other
15
+ * steps. Without, Next shows the parts that wait for it, and the slide is done when no press would
16
+ * show anything more. The slide reports where Next and Back go with `onRevealNavigation`.
13
17
  */
14
18
  export function SlideStepView({
15
19
  step,
@@ -20,14 +24,26 @@ export function SlideStepView({
20
24
  onSubtitlesChange,
21
25
  onDoneChange,
22
26
  onMediaEnded,
27
+ onRevealNavigation,
23
28
  }: StepBodyProps & { step: SlideStep }) {
24
- let revealSteps = useMemo(() => getRevealSteps(step.blocks), [step.blocks]);
25
29
  let narration = step.narration;
30
+ // On a narrated slide only the narration shows and hides parts; Next goes to the next step
31
+ let narrated = narration != null;
32
+ let revealSteps = useMemo(() => getRevealSteps(step.blocks, narrated), [step.blocks, narrated]);
26
33
  let state = useNarration(narration, mode === "learn", onMediaEnded);
27
34
  let clock = state.clock;
28
35
 
36
+ let navigation = useMemo(
37
+ () => getRevealNavigation(step.blocks, stepsShown, clock.startedCues, narrated),
38
+ [step.blocks, stepsShown, clock.startedCues, narrated],
39
+ );
40
+ let { next, previous, presses, pressed } = navigation;
41
+ useLayoutEffect(() => {
42
+ onRevealNavigation?.({ next, previous, presses, pressed });
43
+ }, [next, previous, presses, pressed, onRevealNavigation]);
44
+
29
45
  let mustListen = narration != null && narration.required !== false;
30
- let done = stepsShown >= revealSteps.length && (!mustListen || clock.ended);
46
+ let done = next === null && (!mustListen || clock.ended);
31
47
  useLayoutEffect(() => {
32
48
  onDoneChange(done);
33
49
  }, [done, onDoneChange]);
@@ -45,14 +61,35 @@ export function SlideStepView({
45
61
  part?.scrollIntoView?.({ block: "nearest", behavior: calm ? "auto" : "smooth" });
46
62
  }, [stepsShown, revealSteps]);
47
63
 
48
- let context: BlocksContext = {
49
- reveal: { stepsShown, revealSteps, startedCues: clock.startedCues },
50
- resolveAsset,
51
- subtitles,
52
- onSubtitlesChange,
53
- };
64
+ let reveal = useMemo(
65
+ () => getRevealState(step.blocks, stepsShown, clock.startedCues, narrated),
66
+ [step.blocks, stepsShown, clock.startedCues, narrated],
67
+ );
68
+
69
+ // The effects that were shown before this change pick the timing of the parts they act on
70
+ let active = getActiveEffects(step.blocks, reveal);
71
+ let activeKey = [...active].join("\u0000");
72
+ let [effectsSeen, setEffectsSeen] = useState({ key: activeKey, active, previous: active });
73
+ if (effectsSeen.key !== activeKey) setEffectsSeen({ key: activeKey, active, previous: effectsSeen.active });
74
+ let effects = getPartEffects(step.blocks, reveal, effectsSeen.previous);
75
+
76
+ let calm = prefersCalm();
77
+
78
+ let signature = getTimedParts(step.blocks)
79
+ .map((part) => `${part.id}:${getVisibility(part, reveal)}`)
80
+ .join("|");
81
+
82
+ let context: BlocksContext = { reveal, resolveAsset, subtitles, onSubtitlesChange, effects, calm };
54
83
 
55
84
  let background = step.background ? resolveAsset(step.background) : undefined;
85
+ // A banner shows the image as a band of its own instead of behind the whole slide
86
+ let banner = step.layout === "banner" && background ? background : undefined;
87
+ if (banner) background = undefined;
88
+ let content = (
89
+ <div className="ob-course-slide__content">
90
+ <Blocks blocks={step.blocks} context={context} />
91
+ </div>
92
+ );
56
93
 
57
94
  return (
58
95
  <div
@@ -60,13 +97,26 @@ export function SlideStepView({
60
97
  className={clsx(
61
98
  "ob-course-slide",
62
99
  `ob-course-slide--${step.layout ?? "default"}`,
100
+ step.width && `ob-course-slide--${step.width}`,
63
101
  background && "ob-course-slide--background",
102
+ background && step.panel === false && "ob-course-slide--bare",
64
103
  )}
65
- style={background ? { backgroundImage: `url("${background}")` } : undefined}
66
104
  >
67
- <div className="ob-course-slide__content">
68
- <Blocks blocks={step.blocks} context={context} />
69
- </div>
105
+ <RevealMotion root={rootRef} signature={signature} source={step.blocks} calm={calm} />
106
+ {/* A layer of its own, so a transition can move the background apart from the blocks */}
107
+ {background && (
108
+ <div className="ob-course-slide__background" style={{ backgroundImage: `url("${background}")` }} />
109
+ )}
110
+ {banner ? (
111
+ <div className="ob-course-banner">
112
+ <div className="ob-course-banner__stage">
113
+ <img className="ob-course-banner__image" src={banner} alt="" />
114
+ {content}
115
+ </div>
116
+ </div>
117
+ ) : (
118
+ content
119
+ )}
70
120
  {narration && (
71
121
  <NarrationPlayer
72
122
  className="ob-course-slide__narration"
@@ -1,3 +1,4 @@
1
+ import type { RevealNavigation } from "../document/cues";
1
2
  import type { PlayerMode, QuizAdapter, ResolveAsset } from "../types";
2
3
 
3
4
  /** What the player hands every step type. */
@@ -6,7 +7,10 @@ export interface StepBodyProps {
6
7
  mode: PlayerMode;
7
8
  resolveAsset: ResolveAsset;
8
9
  quiz?: QuizAdapter;
9
- /** How many `reveal: "step"` parts of a slide are shown. */
10
+ /**
11
+ * How many `reveal: "step"` parts of a slide count as pressed, in document order. A press of
12
+ * Next may move it by more than one, past parts that would show nothing new.
13
+ */
10
14
  stepsShown: number;
11
15
  subtitles: boolean;
12
16
  onSubtitlesChange(subtitles: boolean): void;
@@ -14,4 +18,6 @@ export interface StepBodyProps {
14
18
  onDoneChange(done: boolean): void;
15
19
  /** The step's narration or video has played to its end; called again after each replay. */
16
20
  onMediaEnded?(): void;
21
+ /** A slide reports where Next and Back go from here, and the presses that show something. */
22
+ onRevealNavigation?(navigation: RevealNavigation): void;
17
23
  }