@vtex/ads-stories 0.4.1 → 0.7.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 (60) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +44 -88
  3. package/dist/cdn/vtex-ads-stories.js +1313 -74
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +3744 -513
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +46 -15
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +51 -5
  10. package/dist/cjs/story-DAiAN9v-.d.cts +260 -0
  11. package/dist/esm/index.d.ts +46 -15
  12. package/dist/esm/index.js +3348 -217
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/react.d.ts +51 -5
  15. package/dist/esm/story-DAiAN9v-.d.ts +260 -0
  16. package/package.json +18 -4
  17. package/src/cdn.ts +7 -3
  18. package/src/commerce-events.ts +93 -0
  19. package/src/components/card/card.ts +79 -14
  20. package/src/components/carousel/carousel-skeleton.ts +113 -0
  21. package/src/components/carousel/carousel.ts +715 -0
  22. package/src/components/carousel/index.ts +22 -0
  23. package/src/components/events/events-controller.ts +222 -0
  24. package/src/components/events/index.ts +6 -0
  25. package/src/components/icons/assets/caret-left-bold.svg +1 -0
  26. package/src/components/icons/assets/caret-right-bold.svg +1 -0
  27. package/src/components/icons/assets/caret-up-bold.svg +1 -0
  28. package/src/components/icons/assets/minus.svg +1 -0
  29. package/src/components/icons/assets/plus.svg +1 -0
  30. package/src/components/icons/assets/trash.svg +1 -0
  31. package/src/components/icons/assets/warning-circle-fill.svg +1 -0
  32. package/src/components/icons/index.ts +14 -0
  33. package/src/components/media/index.ts +8 -1
  34. package/src/components/media/media.styles.ts +113 -0
  35. package/src/components/media/media.ts +124 -23
  36. package/src/components/media/video-controller.ts +127 -6
  37. package/src/components/player/index.ts +6 -2
  38. package/src/components/player/player.ts +824 -50
  39. package/src/components/product/cta.ts +56 -0
  40. package/src/components/product/index.ts +22 -0
  41. package/src/components/product/price.ts +86 -0
  42. package/src/components/product/product.styles.ts +426 -0
  43. package/src/components/product/product.ts +336 -0
  44. package/src/index.ts +17 -1
  45. package/src/locales/en.ts +39 -0
  46. package/src/locales/es.ts +40 -0
  47. package/src/locales/index.ts +36 -0
  48. package/src/locales/pt.ts +39 -0
  49. package/src/locales/types.ts +44 -0
  50. package/src/react.ts +55 -7
  51. package/src/story/index.ts +5 -1
  52. package/src/story/story.ts +679 -49
  53. package/src/tag-name.ts +1 -0
  54. package/src/types.ts +8 -12
  55. package/src/utils/fetch-story.ts +113 -0
  56. package/src/utils/hydrate-products.ts +112 -0
  57. package/src/utils/media-ready.ts +58 -0
  58. package/src/utils/safe-url.ts +36 -0
  59. package/src/utils/send-event.ts +71 -0
  60. package/src/utils/with-timeout.ts +43 -0
@@ -0,0 +1,22 @@
1
+ export {
2
+ AUTO_ADVANCE_MS,
3
+ CarouselController,
4
+ carouselStyles,
5
+ MAX_SLIDE_DURATION_MS,
6
+ MIN_SLIDE_DURATION_MS,
7
+ NARROW_SCREEN,
8
+ RENDERED_SIDE,
9
+ SWIPE_DISTANCE,
10
+ toSlideDuration,
11
+ VISIBLE_SIDE,
12
+ } from "./carousel";
13
+ export {
14
+ carouselSkeletonStyles,
15
+ renderCarouselSkeleton,
16
+ } from "./carousel-skeleton";
17
+ export type {
18
+ CarouselLayout,
19
+ CarouselOptions,
20
+ RenderSlide,
21
+ Slide,
22
+ } from "./carousel";
@@ -0,0 +1,222 @@
1
+ import type { ReactiveController, ReactiveControllerHost } from "lit";
2
+ import type { StoryAd } from "../../types";
3
+ import { sendEvent, type EventIdentity } from "../../utils/send-event";
4
+
5
+ export const VIEW_THRESHOLD = 0.5;
6
+ export const VIEW_DURATION_MS = 2000;
7
+
8
+ type EventKind = "impression" | "view" | "click";
9
+
10
+ const URL_FIELD = {
11
+ impression: "impression_url",
12
+ view: "view_url",
13
+ click: "click_url",
14
+ } as const satisfies Record<EventKind, keyof StoryAd>;
15
+
16
+ /** An element that shows a Story, watched for the view. */
17
+ export type ViewTarget = readonly [element: Element, story: StoryAd];
18
+
19
+ export interface StoryEventsOptions {
20
+ /**
21
+ * The session and user the events are for, read when each one is sent.
22
+ * Without a session, nothing is sent.
23
+ */
24
+ identity: () => Partial<EventIdentity>;
25
+ /**
26
+ * The elements on which a Story can be seen right now, read after every
27
+ * render of the host. An element left out stops counting toward its view.
28
+ */
29
+ viewTargets: () => Iterable<ViewTarget>;
30
+ }
31
+
32
+ interface Watched {
33
+ story: StoryAd;
34
+ /** Last reported by the observer: at least VIEW_THRESHOLD on screen. */
35
+ visible: boolean;
36
+ timer?: ReturnType<typeof setTimeout>;
37
+ }
38
+
39
+ /**
40
+ * Sends a Story's impression, view and click URLs, each at most once per
41
+ * Story and session (the ad API's `session_id`):
42
+ *
43
+ * - impression: when the Story is rendered in the carousel (impress());
44
+ * - view: when one of its elements (see `viewTargets`) has stayed at least
45
+ * 50% on screen for 2 continuous seconds, with the page visible;
46
+ * - click: on the first touch on the Story (click()).
47
+ *
48
+ * Without IntersectionObserver, no view is sent. Leaving the page stops
49
+ * the views counting; nothing sent is sent again on return.
50
+ */
51
+ export class StoryEventsController implements ReactiveController {
52
+ private readonly sent: Record<EventKind, Set<string>> = {
53
+ impression: new Set(),
54
+ view: new Set(),
55
+ click: new Set(),
56
+ };
57
+
58
+ private pendingImpressions: readonly StoryAd[] = [];
59
+ private connected = false;
60
+
61
+ private observer?: IntersectionObserver;
62
+ private readonly watched = new Map<Element, Watched>();
63
+
64
+ constructor(
65
+ private readonly host: ReactiveControllerHost,
66
+ private readonly options: StoryEventsOptions,
67
+ ) {
68
+ host.addController(this);
69
+ }
70
+
71
+ hostConnected() {
72
+ this.connected = true;
73
+ if (typeof IntersectionObserver === "function") {
74
+ this.observer = new IntersectionObserver(this.onIntersect, {
75
+ threshold: VIEW_THRESHOLD,
76
+ });
77
+ }
78
+ globalThis.document?.addEventListener(
79
+ "visibilitychange",
80
+ this.onVisibilityChange,
81
+ );
82
+ // Moved on the page: the cards rendered before are still there, but lit
83
+ // hands their refs back only after the controllers connect. Impressions
84
+ // that came while off the page go out now.
85
+ this.host.updateComplete.then(() => {
86
+ if (!this.connected) return;
87
+ this.sendImpressions();
88
+ this.syncViewTargets();
89
+ });
90
+ }
91
+
92
+ hostDisconnected() {
93
+ this.connected = false;
94
+ globalThis.document?.removeEventListener(
95
+ "visibilitychange",
96
+ this.onVisibilityChange,
97
+ );
98
+ this.observer?.disconnect();
99
+ this.observer = undefined;
100
+ for (const watched of this.watched.values()) clearTimeout(watched.timer);
101
+ this.watched.clear();
102
+ }
103
+
104
+ hostUpdated() {
105
+ if (!this.connected) return;
106
+ this.sendImpressions();
107
+ this.syncViewTargets();
108
+ }
109
+
110
+ /**
111
+ * The Stories the host shows next: their impressions go out once that
112
+ * render is done, on the page, with a session (or after the first render
113
+ * that has both). Replaces Stories passed before and not sent yet.
114
+ */
115
+ impress(stories: readonly StoryAd[]) {
116
+ this.pendingImpressions = stories;
117
+ }
118
+
119
+ private sendImpressions() {
120
+ const stories = this.pendingImpressions;
121
+ if (!stories.length || !this.options.identity().sessionId) return;
122
+
123
+ this.pendingImpressions = [];
124
+ for (const story of stories) this.send("impression", story);
125
+ }
126
+
127
+ /** A touch on the Story: its click goes out, the first time only. */
128
+ click(story: StoryAd) {
129
+ this.send("click", story);
130
+ }
131
+
132
+ private key(sessionId: string, story: StoryAd) {
133
+ return `${sessionId}|${story.ad_id}`;
134
+ }
135
+
136
+ private wasSent(kind: EventKind, story: StoryAd) {
137
+ const { sessionId } = this.options.identity();
138
+ return !!sessionId && this.sent[kind].has(this.key(sessionId, story));
139
+ }
140
+
141
+ private send(kind: EventKind, story: StoryAd) {
142
+ const { sessionId, userId } = this.options.identity();
143
+ if (!sessionId || this.wasSent(kind, story)) return;
144
+
145
+ const success = sendEvent(story[URL_FIELD[kind]], { sessionId, userId });
146
+ if (success) {
147
+ this.sent[kind].add(this.key(sessionId, story));
148
+ }
149
+ }
150
+
151
+ // Watches the elements the host shows now, and stops watching the others,
152
+ // dropping the time they had on screen.
153
+ private syncViewTargets() {
154
+ const { observer } = this;
155
+ if (!observer) return;
156
+
157
+ const current = new Map<Element, StoryAd>();
158
+ for (const [element, story] of this.options.viewTargets()) {
159
+ if (!this.wasSent("view", story)) current.set(element, story);
160
+ }
161
+
162
+ for (const [element, watched] of this.watched) {
163
+ if (current.get(element) !== watched.story) {
164
+ this.unwatch(element, watched);
165
+ }
166
+ }
167
+
168
+ for (const [element, story] of current) {
169
+ if (this.watched.has(element)) continue;
170
+ this.watched.set(element, { story, visible: false });
171
+ observer.observe(element);
172
+ }
173
+ }
174
+
175
+ private readonly onIntersect = (entries: IntersectionObserverEntry[]) => {
176
+ for (const entry of entries) {
177
+ const watched = this.watched.get(entry.target);
178
+ if (!watched) continue;
179
+
180
+ watched.visible =
181
+ entry.isIntersecting && entry.intersectionRatio >= VIEW_THRESHOLD;
182
+ if (watched.visible) this.startTimer(watched);
183
+ else this.stopTimer(watched);
184
+ }
185
+ };
186
+
187
+ // A hidden page (another tab, minimized) breaks the 2 seconds: they start
188
+ // over when it shows again.
189
+ private readonly onVisibilityChange = () => {
190
+ for (const watched of this.watched.values()) {
191
+ if (document.hidden) this.stopTimer(watched);
192
+ else if (watched.visible) this.startTimer(watched);
193
+ }
194
+ };
195
+
196
+ private startTimer(watched: Watched) {
197
+ if (watched.timer || globalThis.document?.hidden) return;
198
+ watched.timer = setTimeout(() => {
199
+ watched.timer = undefined;
200
+ this.send("view", watched.story);
201
+ // Its other elements no longer need watching.
202
+ if (this.wasSent("view", watched.story)) this.unwatchStory(watched.story);
203
+ }, VIEW_DURATION_MS);
204
+ }
205
+
206
+ private stopTimer(watched: Watched) {
207
+ clearTimeout(watched.timer);
208
+ watched.timer = undefined;
209
+ }
210
+
211
+ private unwatch(element: Element, watched: Watched) {
212
+ this.stopTimer(watched);
213
+ this.observer?.unobserve(element);
214
+ this.watched.delete(element);
215
+ }
216
+
217
+ private unwatchStory(story: StoryAd) {
218
+ for (const [element, watched] of this.watched) {
219
+ if (watched.story.ad_id === story.ad_id) this.unwatch(element, watched);
220
+ }
221
+ }
222
+ }
@@ -0,0 +1,6 @@
1
+ export {
2
+ StoryEventsController,
3
+ VIEW_DURATION_MS,
4
+ VIEW_THRESHOLD,
5
+ } from "./events-controller";
6
+ export type { StoryEventsOptions, ViewTarget } from "./events-controller";
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M168.49,199.51a12,12,0,0,1-17,17l-80-80a12,12,0,0,1,0-17l80-80a12,12,0,0,1,17,17L97,128Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-8,56a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm8,104a12,12,0,1,1,12-12A12,12,0,0,1,128,184Z"/></svg>
@@ -9,22 +9,36 @@ import {
9
9
  // SVG files as downloaded from Phosphor: regular weight, or the weight in the
10
10
  // file name. They are bundled as text: `?raw` is handled by Vite in dev and
11
11
  // tests, and by the raw plugin in tsup.config.ts.
12
+ import previous from "./assets/caret-left-bold.svg?raw";
13
+ import next from "./assets/caret-right-bold.svg?raw";
12
14
  import close from "./assets/close.svg?raw";
15
+ import caretUp from "./assets/caret-up-bold.svg?raw";
13
16
  import collapse from "./assets/collapse.svg?raw";
14
17
  import expand from "./assets/expand.svg?raw";
18
+ import minus from "./assets/minus.svg?raw";
15
19
  import pause from "./assets/pause-fill.svg?raw";
16
20
  import play from "./assets/play-fill.svg?raw";
21
+ import plus from "./assets/plus.svg?raw";
17
22
  import soundOff from "./assets/speaker-x-fill.svg?raw";
18
23
  import soundOn from "./assets/speaker-high-fill.svg?raw";
24
+ import trash from "./assets/trash.svg?raw";
25
+ import warning from "./assets/warning-circle-fill.svg?raw";
19
26
 
20
27
  export const icons = {
28
+ caretUp,
21
29
  close,
22
30
  collapse,
23
31
  expand,
32
+ minus,
33
+ next,
24
34
  pause,
25
35
  play,
36
+ plus,
37
+ previous,
26
38
  soundOff,
27
39
  soundOn,
40
+ trash,
41
+ warning,
28
42
  };
29
43
 
30
44
  export type IconName = keyof typeof icons;
@@ -1,2 +1,9 @@
1
- export { hasVideo, httpUrl, renderMedia } from "./media";
1
+ export {
2
+ hasVideo,
3
+ prefersReducedMotion,
4
+ REDUCED_MOTION,
5
+ renderMedia,
6
+ } from "./media";
7
+ export type { MediaOptions } from "./media";
8
+ export { mediaStyles } from "./media.styles";
2
9
  export { playVideo, VideoController } from "./video-controller";
@@ -0,0 +1,113 @@
1
+ import { css } from "lit";
2
+
3
+ export const mediaStyles = css`
4
+ /* The live region the notice shows in, over the cover. Empty until the
5
+ video can't load or is loading again. Clicks go through to the card. */
6
+ .media-notice {
7
+ position: absolute;
8
+ inset: 0;
9
+ pointer-events: none;
10
+ }
11
+
12
+ /* The notice: a dimmed layer with the text in the middle. */
13
+ .media-status {
14
+ position: absolute;
15
+ inset: 0;
16
+ display: flex;
17
+ flex-direction: column;
18
+ gap: 12px;
19
+ align-items: center;
20
+ justify-content: center;
21
+ box-sizing: border-box;
22
+ padding: 16px;
23
+ background: rgba(0, 0, 0, 0.45);
24
+ color: #fff;
25
+ text-align: center;
26
+ pointer-events: none;
27
+ }
28
+
29
+ .media-status > * {
30
+ animation: media-status-in 0.4s ease-out both;
31
+ }
32
+
33
+ .media-status-text {
34
+ display: flex;
35
+ flex-direction: column;
36
+ gap: 8px;
37
+ align-items: center;
38
+ max-width: 100%;
39
+ font-size: 14px;
40
+ font-weight: 600;
41
+ line-height: 1.3;
42
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
43
+ }
44
+
45
+ .media-status-text .icon {
46
+ width: 18px;
47
+ height: 18px;
48
+ }
49
+
50
+ .media-status[data-retry] .media-status-text .icon {
51
+ width: 24px;
52
+ height: 24px;
53
+ }
54
+
55
+ .media-retry {
56
+ min-height: 36px;
57
+ padding: 0 16px;
58
+ border: 0;
59
+ border-radius: var(--_button-radius);
60
+ background: rgba(255, 255, 255, 0.15);
61
+ backdrop-filter: blur(4px);
62
+ box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);
63
+ color: #fff;
64
+ font: inherit;
65
+ font-size: 14px;
66
+ font-weight: 600;
67
+ cursor: pointer;
68
+ pointer-events: auto;
69
+ animation-delay: 0.06s;
70
+ }
71
+
72
+ .media-retry:focus-visible {
73
+ outline: 2px solid #fff;
74
+ outline-offset: 2px;
75
+ }
76
+
77
+ @media (hover: hover) and (pointer: fine) {
78
+ .media-retry:hover {
79
+ background: rgba(255, 255, 255, 0.25);
80
+ }
81
+ }
82
+
83
+ /* It spins with reduced motion too: a still ring wouldn't read as
84
+ loading. */
85
+ .media-spinner {
86
+ width: 24px;
87
+ height: 24px;
88
+ box-sizing: border-box;
89
+ border: 2px solid rgba(255, 255, 255, 0.35);
90
+ border-top-color: #fff;
91
+ border-radius: 50%;
92
+ animation: media-spin 0.8s linear infinite;
93
+ }
94
+
95
+ @keyframes media-status-in {
96
+ from {
97
+ opacity: 0;
98
+ transform: translateY(4px);
99
+ }
100
+ }
101
+
102
+ @keyframes media-spin {
103
+ to {
104
+ transform: rotate(360deg);
105
+ }
106
+ }
107
+
108
+ @media (prefers-reduced-motion: reduce) {
109
+ .media-status > :not(.media-spinner) {
110
+ animation: none;
111
+ }
112
+ }
113
+ `;
@@ -1,38 +1,136 @@
1
1
  import { html, nothing } from "lit";
2
2
  import { ref } from "lit/directives/ref.js";
3
+ import { pt, type StoryLabels } from "../../locales";
4
+ import { icon } from "../icons";
3
5
  import type { StoryMedia } from "../../types";
6
+ import { httpUrl } from "../../utils/safe-url";
4
7
  import type { VideoController } from "./video-controller";
5
8
 
6
- // Only absolute http(s) URLs reach the DOM. Relative and protocol-relative
7
- // ones ("/a.jpg", "//host/a.jpg") don't parse without a base, so they're out.
8
- export function httpUrl(value: string | undefined) {
9
- if (!value) return null;
10
- try {
11
- const { protocol } = new URL(value);
12
- return protocol === "https:" || protocol === "http:" ? value : null;
13
- } catch {
14
- return null;
15
- }
16
- }
9
+ /** Media query for people who asked the system for less motion. */
10
+ export const REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
17
11
 
18
- function prefersReducedMotion() {
19
- return (
20
- globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false
21
- );
12
+ export function prefersReducedMotion() {
13
+ return globalThis.matchMedia?.(REDUCED_MOTION).matches ?? false;
22
14
  }
23
15
 
24
- /** Whether renderMedia shows a video for this Story right now. */
16
+ /**
17
+ * Whether renderMedia shows a playable video for this Story right now: not
18
+ * one that failed or is loading again.
19
+ */
25
20
  export function hasVideo(story: StoryMedia, video: VideoController) {
26
- return !video.failed && httpUrl(story.media_url) !== null;
21
+ return !video.failed && !video.retrying && httpUrl(story.media_url) !== null;
22
+ }
23
+
24
+ export interface MediaOptions {
25
+ /** Whether the video shows over the cover (default true). */
26
+ withVideo?: boolean;
27
+ /** Whether the video loops (default true). */
28
+ loop?: boolean;
29
+ /** Called when a video that doesn't loop reaches its end. */
30
+ onEnded?: () => void;
31
+ /**
32
+ * Whether the video plays on its own (default true; never with reduced
33
+ * motion). Without it, the video loads in full but waits to be played.
34
+ */
35
+ autoplay?: boolean;
36
+ /**
37
+ * The texts of the notice over the cover when the video can't load
38
+ * (default Portuguese, as the element's).
39
+ */
40
+ labels?: StoryLabels;
41
+ /**
42
+ * Whether screen readers announce the notice (default true). Off where
43
+ * several can show at once, as on the cards.
44
+ */
45
+ announce?: boolean;
46
+ /**
47
+ * Offers to load a failed video again (see VideoController.retry), with a
48
+ * button in the notice. Without it, the notice only says the video is
49
+ * unavailable.
50
+ */
51
+ onRetry?: () => void;
52
+ }
53
+
54
+ // What the notice says, and the retry button when there is one. The button
55
+ // is inside the card, which plays or pauses on a click: the click stops here.
56
+ function renderFailed(labels: StoryLabels, onRetry?: () => void) {
57
+ const retry = (event: Event) => {
58
+ event.stopPropagation();
59
+ onRetry?.();
60
+ };
61
+
62
+ return html`
63
+ <div class="media-status" ?data-retry=${!!onRetry}>
64
+ <span class="media-status-text">
65
+ ${icon("warning")}
66
+ ${onRetry ? labels.videoFailed : labels.videoUnavailable}
67
+ </span>
68
+ ${onRetry
69
+ ? html`
70
+ <button type="button" class="media-retry" @click=${retry}>
71
+ ${labels.retry}
72
+ </button>
73
+ `
74
+ : nothing}
75
+ </div>
76
+ `;
77
+ }
78
+
79
+ function renderVideoLoading(labels: StoryLabels) {
80
+ return html`
81
+ <div class="media-status">
82
+ <span class="media-status-text">
83
+ <span class="media-spinner" aria-hidden="true"></span>
84
+ ${labels.videoLoading}
85
+ </span>
86
+ </div>
87
+ `;
88
+ }
89
+
90
+ // The notice over the cover, if the video failed or is loading again.
91
+ function renderStatus(
92
+ video: VideoController,
93
+ labels: StoryLabels,
94
+ onRetry?: () => void,
95
+ ) {
96
+ if (video.failed) return renderFailed(labels, onRetry);
97
+ if (video.retrying) return renderVideoLoading(labels);
98
+ return nothing;
99
+ }
100
+
101
+ // A live region is announced when its content changes, not when it is
102
+ // added with it: it stays for as long as there is a video, empty until a
103
+ // notice shows.
104
+ function renderNotice(
105
+ video: VideoController,
106
+ { labels = pt, onRetry, announce = true }: MediaOptions,
107
+ ) {
108
+ return html`
109
+ <div
110
+ class="media-notice"
111
+ role=${announce ? "status" : nothing}
112
+ aria-hidden=${announce ? nothing : "true"}
113
+ >
114
+ ${renderStatus(video, labels, onRetry)}
115
+ </div>
116
+ `;
27
117
  }
28
118
 
29
119
  /**
30
120
  * The Story cover and, with a media_url, the video looping muted over it. If
31
- * the video can't load, it is removed and the cover underneath stays.
121
+ * the video can't load, it is removed and the cover underneath stays, with a
122
+ * notice over it (and a retry button with `onRetry`). With withVideo false,
123
+ * only the cover.
32
124
  */
33
- export function renderMedia(story: StoryMedia, video: VideoController) {
125
+ export function renderMedia(
126
+ story: StoryMedia,
127
+ video: VideoController,
128
+ options: MediaOptions = {},
129
+ ) {
130
+ const { withVideo = true, loop = true, onEnded, autoplay = true } = options;
34
131
  const posterUrl = httpUrl(story.poster_url);
35
- const mediaUrl = httpUrl(story.media_url);
132
+ const mediaUrl = withVideo ? httpUrl(story.media_url) : null;
133
+ const preload = autoplay ? "metadata" : "auto";
36
134
 
37
135
  // Muted and inline is what browsers, iOS included, allow to autoplay. The
38
136
  // muted attribute and property are both set, since browsers differ on
@@ -48,19 +146,22 @@ export function renderMedia(story: StoryMedia, video: VideoController) {
48
146
  class="video"
49
147
  muted
50
148
  playsinline
51
- loop
52
- preload="metadata"
149
+ ?loop=${loop}
150
+ preload=${preload}
53
151
  .muted=${true}
54
- ?autoplay=${!prefersReducedMotion()}
152
+ ?autoplay=${autoplay && !prefersReducedMotion()}
55
153
  poster=${posterUrl ?? nothing}
56
154
  src=${mediaUrl}
57
155
  ${ref(video.ref)}
58
156
  @play=${video.sync}
59
157
  @pause=${video.sync}
60
158
  @volumechange=${video.sync}
159
+ @loadeddata=${video.loaded}
61
160
  @error=${video.fail}
161
+ @ended=${onEnded}
62
162
  ></video>
63
163
  `
64
164
  : nothing}
165
+ ${mediaUrl ? renderNotice(video, options) : nothing}
65
166
  `;
66
167
  }