@vtex/ads-stories 0.3.0 → 0.4.1

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.
@@ -1,6 +1,9 @@
1
- import { createCard } from "../card";
2
- import { createIcon, type IconName } from "../icons";
3
- import type { StoryAd } from "../../types";
1
+ import { css, html, nothing } from "lit";
2
+ import type { ReactiveController, ReactiveControllerHost } from "lit";
3
+ import { createRef, ref } from "lit/directives/ref.js";
4
+ import { icon } from "../icons";
5
+ import { hasVideo, renderMedia, VideoController } from "../media";
6
+ import type { StoryMedia } from "../../types";
4
7
 
5
8
  // The player is a <dialog> shown in the top layer, so no store z-index,
6
9
  // overflow or transform can hide or move it.
@@ -11,7 +14,7 @@ import type { StoryAd } from "../../types";
11
14
  // Expanded: a modal dialog (showModal), so the browser makes the page behind
12
15
  // it inert. The card is centered over a dark backdrop, with the controls at
13
16
  // the top right of the screen. On narrow screens it fills the screen.
14
- export const playerStyles = `
17
+ export const playerStyles = css`
15
18
  .player {
16
19
  position: fixed;
17
20
  inset: auto 16px 16px auto;
@@ -56,6 +59,46 @@ export const playerStyles = `
56
59
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
57
60
  }
58
61
 
62
+ .player .card:has(.video) {
63
+ cursor: pointer;
64
+ }
65
+
66
+ /* Play/pause reuses the card's glass .play button, as a real button. */
67
+ .player-toggle {
68
+ padding: 0;
69
+ border: 0;
70
+ color: #fff;
71
+ font: inherit;
72
+ cursor: pointer;
73
+ }
74
+
75
+ .player[data-paused] .player-toggle,
76
+ .player-toggle:focus-visible {
77
+ opacity: 1;
78
+ transform: translate(-50%, -50%);
79
+ }
80
+
81
+ /* On touch, tapping the video pauses it; the button shows while paused. */
82
+ @media (hover: none) {
83
+ .player:not([data-paused]) .player-toggle {
84
+ opacity: 0;
85
+ }
86
+ }
87
+
88
+ .player-sound {
89
+ position: absolute;
90
+ top: 12px;
91
+ right: 12px;
92
+ z-index: 1;
93
+ border-color: transparent;
94
+ background: rgba(0, 0, 0, 0.3);
95
+ }
96
+
97
+ .player-sound .icon {
98
+ width: 20px;
99
+ height: 20px;
100
+ }
101
+
59
102
  /* Above the card: on narrow screens the expanded card can cover them. */
60
103
  .player-controls {
61
104
  position: absolute;
@@ -140,8 +183,12 @@ export const playerStyles = `
140
183
  border-radius: 0;
141
184
  }
142
185
 
186
+ /* Below the sound button, at the top right of the video. Placed in the
187
+ video frame, not the screen: the frame is centered, so on screens
188
+ taller than 9:16 its top is below the screen's. */
143
189
  .player[data-expanded] .player-controls {
144
- top: 12px;
190
+ position: absolute;
191
+ top: 60px;
145
192
  right: 12px;
146
193
  }
147
194
  }
@@ -167,88 +214,229 @@ export interface PlayerOptions {
167
214
  expandLabel: string;
168
215
  collapseLabel: string;
169
216
  closeLabel: string;
217
+ playLabel: string;
218
+ pauseLabel: string;
219
+ soundOnLabel: string;
220
+ soundOffLabel: string;
221
+ /**
222
+ * Called by the close button, Escape and a click on the expanded view's
223
+ * backdrop. Call close() from it.
224
+ */
170
225
  onClose: () => void;
171
226
  }
172
227
 
173
- function createButton(className: string, label: string, icon: IconName) {
174
- const button = document.createElement("button");
175
- button.type = "button";
176
- button.className = `player-button ${className}`;
177
- button.setAttribute("aria-label", label);
178
- button.append(createIcon(icon));
179
- return button;
180
- }
181
-
182
- function supportsPopover(player: HTMLDialogElement) {
183
- return typeof player.showPopover === "function";
184
- }
185
-
186
- /** Shows the player as the mini player. It must already be in the page. */
187
- export function showPlayer(player: HTMLDialogElement) {
188
- if (supportsPopover(player)) player.showPopover();
189
- else player.show();
228
+ function supportsPopover(dialog: HTMLDialogElement) {
229
+ return typeof dialog.showPopover === "function";
190
230
  }
191
231
 
192
232
  /**
193
- * The Story player. It opens as the mini player (see showPlayer); expand
194
- * switches to the expanded view, a modal dialog, and back. Clicking the
195
- * backdrop of the expanded view or pressing Escape in it closes the player.
233
+ * The Story player, rendered by its host with render(). open() shows it as
234
+ * the mini player; expand switches to the expanded view, a modal dialog, and
235
+ * back. The video starts muted and plays when the player opens. It closes on
236
+ * its own when the host leaves the page.
196
237
  */
197
- export function createPlayer(story: StoryAd, options: PlayerOptions) {
198
- const player = document.createElement("dialog");
199
- player.className = "player";
200
- player.setAttribute("popover", "manual");
201
- player.setAttribute("aria-label", options.label);
238
+ export class PlayerController implements ReactiveController {
239
+ readonly video: VideoController;
240
+
241
+ /** Rendered and, once the host has updated, shown. */
242
+ isOpen = false;
243
+ private expanded = false;
244
+ /** Switched modes at least once: only the first opening fades in. */
245
+ private switched = false;
246
+ /** The dialog is showing, in the mode `expanded` says. */
247
+ private shown = false;
248
+
249
+ private readonly dialog = createRef<HTMLDialogElement>();
250
+ private readonly expandButton = createRef<HTMLButtonElement>();
251
+ private readonly closeButton = createRef<HTMLButtonElement>();
252
+
253
+ constructor(
254
+ private readonly host: ReactiveControllerHost,
255
+ private readonly options: PlayerOptions,
256
+ ) {
257
+ host.addController(this);
258
+ this.video = new VideoController(host);
259
+ }
202
260
 
203
- const frame = document.createElement("div");
204
- frame.className = "player-frame";
261
+ hostDisconnected() {
262
+ this.close();
263
+ }
205
264
 
206
- const controls = document.createElement("div");
207
- controls.className = "player-controls";
265
+ /** Opens the mini player, plays the video and focuses the close button. */
266
+ async open() {
267
+ if (this.isOpen) return;
268
+
269
+ document.addEventListener("keydown", this.onKeyDown);
270
+ this.isOpen = true;
271
+ this.expanded = false;
272
+ this.switched = false;
273
+ this.video.reset();
274
+ this.host.requestUpdate();
275
+ await this.host.updateComplete;
276
+
277
+ const dialog = this.dialog.value;
278
+ // Closed again before the host rendered it.
279
+ if (!this.isOpen || !dialog) return;
280
+
281
+ this.show(dialog);
282
+ this.video.play();
283
+ this.closeButton.value?.focus();
284
+ }
208
285
 
209
- const expand = createButton("player-expand", options.expandLabel, "expand");
210
- const close = createButton("player-close", options.closeLabel, "close");
211
- controls.append(expand, close);
286
+ /** Hides the player now; the host removes it on its next update. */
287
+ close() {
288
+ if (!this.isOpen) return;
212
289
 
213
- let expanded = false;
290
+ document.removeEventListener("keydown", this.onKeyDown);
291
+ const dialog = this.dialog.value;
292
+ if (dialog) this.hide(dialog);
293
+ this.isOpen = false;
294
+ this.host.requestUpdate();
295
+ }
296
+
297
+ // Mini: a manual popover, or a non-modal dialog without popover support.
298
+ // Expanded: a modal dialog.
299
+ // Already showing: a second expand click in the same task resumes after the
300
+ // first one has shown the dialog, and showing it again would throw.
301
+ private show(dialog: HTMLDialogElement) {
302
+ if (this.shown) return;
303
+ if (this.expanded) dialog.showModal();
304
+ else if (supportsPopover(dialog)) dialog.showPopover();
305
+ else dialog.show();
306
+ this.shown = true;
307
+ }
214
308
 
215
309
  // A dialog can't be shown as a popover and as a modal at the same time, so
216
310
  // switching modes hides it first, the same way it was shown.
217
- function hide() {
218
- if (!expanded && supportsPopover(player)) player.hidePopover();
219
- else player.close();
311
+ private hide(dialog: HTMLDialogElement) {
312
+ if (!this.shown) return;
313
+ if (!this.expanded && supportsPopover(dialog)) dialog.hidePopover();
314
+ else dialog.close();
315
+ this.shown = false;
220
316
  }
221
317
 
222
- expand.addEventListener("click", () => {
223
- hide();
224
- expanded = !expanded;
225
- player.toggleAttribute("data-expanded", expanded);
226
- player.dataset.switched = "";
227
- expand.setAttribute(
228
- "aria-label",
229
- expanded ? options.collapseLabel : options.expandLabel,
230
- );
231
- expand.replaceChildren(createIcon(expanded ? "collapse" : "expand"));
318
+ private readonly toggleExpanded = async () => {
319
+ const dialog = this.dialog.value;
320
+ if (!dialog) return;
232
321
 
233
- if (expanded) player.showModal();
234
- else showPlayer(player);
235
- expand.focus();
236
- });
322
+ this.hide(dialog);
323
+ this.expanded = !this.expanded;
324
+ this.switched = true;
325
+ this.host.requestUpdate();
326
+ await this.host.updateComplete;
237
327
 
238
- close.addEventListener("click", options.onClose);
328
+ if (!this.isOpen) return;
329
+ this.show(dialog);
330
+ this.expandButton.value?.focus();
331
+ };
332
+
333
+ // Escape anywhere on the page, also in the mini player, which is not modal.
334
+ private readonly onKeyDown = (event: KeyboardEvent) => {
335
+ if (event.key === "Escape") this.options.onClose();
336
+ };
239
337
 
240
338
  // Clicks on the backdrop of the expanded view reach the dialog itself.
241
- player.addEventListener("click", (event) => {
242
- if (expanded && event.target === player) options.onClose();
243
- });
339
+ private readonly onDialogClick = (event: Event) => {
340
+ if (this.expanded && event.target === event.currentTarget) {
341
+ this.options.onClose();
342
+ }
343
+ };
244
344
 
245
345
  // Escape on a modal dialog would only hide it: close the player instead.
246
- player.addEventListener("cancel", (event) => {
346
+ private readonly onCancel = (event: Event) => {
247
347
  event.preventDefault();
248
- options.onClose();
249
- });
348
+ this.options.onClose();
349
+ };
350
+
351
+ /**
352
+ * Play/pause in the middle of the video and sound on/off at its top right.
353
+ * They follow the video's own events, so a blocked autoplay shows as
354
+ * paused.
355
+ */
356
+ private renderVideoControls() {
357
+ const { video, options } = this;
358
+
359
+ // Not a .player-button: it keeps the card's larger glass look.
360
+ const onToggle = (event: Event) => {
361
+ event.stopPropagation();
362
+ video.togglePlayback();
363
+ };
364
+ const onSound = (event: Event) => {
365
+ event.stopPropagation();
366
+ video.toggleMuted();
367
+ };
368
+
369
+ return html`
370
+ <button
371
+ type="button"
372
+ class="play player-toggle"
373
+ aria-label=${video.paused ? options.playLabel : options.pauseLabel}
374
+ @click=${onToggle}
375
+ >
376
+ ${icon(video.paused ? "play" : "pause")}
377
+ </button>
378
+ <button
379
+ type="button"
380
+ class="player-button player-sound"
381
+ aria-label=${video.muted ? options.soundOnLabel : options.soundOffLabel}
382
+ @click=${onSound}
383
+ >
384
+ ${icon(video.muted ? "soundOff" : "soundOn")}
385
+ </button>
386
+ `;
387
+ }
250
388
 
251
- frame.append(controls, createCard(story));
252
- player.append(frame);
253
- return player;
389
+ /**
390
+ * The player <dialog> while it is open. Clicking the video also plays or
391
+ * pauses it.
392
+ */
393
+ render(story: StoryMedia) {
394
+ if (!this.isOpen) return nothing;
395
+
396
+ const { video, options, expanded } = this;
397
+ const withVideo = hasVideo(story, video);
398
+
399
+ return html`
400
+ <dialog
401
+ class="player"
402
+ popover="manual"
403
+ aria-label=${options.label}
404
+ ?data-expanded=${expanded}
405
+ ?data-switched=${this.switched}
406
+ ?data-paused=${withVideo && video.paused}
407
+ ${ref(this.dialog)}
408
+ @click=${this.onDialogClick}
409
+ @cancel=${this.onCancel}
410
+ >
411
+ <div class="player-frame">
412
+ <div class="player-controls">
413
+ <button
414
+ type="button"
415
+ class="player-button player-expand"
416
+ aria-label=${expanded
417
+ ? options.collapseLabel
418
+ : options.expandLabel}
419
+ ${ref(this.expandButton)}
420
+ @click=${this.toggleExpanded}
421
+ >
422
+ ${icon(expanded ? "collapse" : "expand")}
423
+ </button>
424
+ <button
425
+ type="button"
426
+ class="player-button player-close"
427
+ aria-label=${options.closeLabel}
428
+ ${ref(this.closeButton)}
429
+ @click=${options.onClose}
430
+ >
431
+ ${icon("close")}
432
+ </button>
433
+ </div>
434
+ <div class="card" @click=${() => video.togglePlayback()}>
435
+ ${renderMedia(story, video)}
436
+ ${withVideo ? this.renderVideoControls() : nothing}
437
+ </div>
438
+ </div>
439
+ </dialog>
440
+ `;
441
+ }
254
442
  }
@@ -1,26 +1,15 @@
1
- import { cardStyles, createCard } from "../components/card";
2
- import { createPlayer, playerStyles, showPlayer } from "../components/player";
3
- import type { StoryAd } from "../types";
1
+ import { css, html, LitElement } from "lit";
2
+ import { cardStyles, renderCard } from "../components/card";
3
+ import { VideoController } from "../components/media";
4
+ import { PlayerController, playerStyles } from "../components/player";
5
+ import type { StoryMedia } from "../types";
4
6
 
5
7
  export const TAG_NAME = "vtex-ads-story";
6
8
 
7
- // Keeps the module importable where HTMLElement doesn't exist (SSR, Node).
8
- const BaseElement: typeof HTMLElement = globalThis.HTMLElement ?? Object;
9
-
10
- const styles = `
11
- :host {
12
- display: block;
13
- font-family: var(--vtex-ads-story-font-family, inherit);
14
- color: var(--vtex-ads-story-color-text, inherit);
15
- }
16
- ${cardStyles}
17
- ${playerStyles}
18
- `;
19
-
20
9
  // Temporary: rendered until the element reads Stories from the ad API.
21
- const PLACEHOLDER_STORY: StoryAd = {
22
- ad_id: "placeholder",
10
+ const PLACEHOLDER_STORY: StoryMedia = {
23
11
  poster_url: "https://dummyimage.com/1080x1920/e31c57/fff",
12
+ media_url: "https://samplelib.com/mp4/sample-10s-vp9.mp4",
24
13
  };
25
14
 
26
15
  // Temporary: fixed texts until the store can set them by attribute.
@@ -30,67 +19,83 @@ const LABELS = {
30
19
  expand: "Expandir vídeo",
31
20
  collapse: "Reduzir vídeo",
32
21
  close: "Fechar vídeo",
22
+ play: "Reproduzir vídeo",
23
+ pause: "Pausar vídeo",
24
+ soundOn: "Ativar som",
25
+ soundOff: "Desativar som",
33
26
  };
34
27
 
35
- export class VtexAdsStoryElement extends BaseElement {
36
- private player: HTMLDialogElement | null = null;
37
-
38
- private readonly onKeyDown = (event: KeyboardEvent) => {
39
- if (event.key === "Escape") this.closePlayer();
40
- };
41
-
42
- private render() {
43
- const container = this.shadowRoot?.querySelector(".root");
44
- if (!container) return;
45
-
46
- container.replaceChildren(
47
- createCard(PLACEHOLDER_STORY, {
48
- label: LABELS.watch,
49
- onSelect: () => this.openPlayer(),
50
- }),
51
- );
28
+ // LitElement is importable where HTMLElement doesn't exist (SSR, Node): Lit
29
+ // falls back to a minimal shim there.
30
+ export class VtexAdsStoryElement extends LitElement {
31
+ static readonly styles = [
32
+ css`
33
+ :host {
34
+ display: block;
35
+ font-family: var(--vtex-ads-story-font-family, inherit);
36
+ color: var(--vtex-ads-story-color-text, inherit);
37
+ }
38
+ `,
39
+ cardStyles,
40
+ playerStyles,
41
+ ];
42
+
43
+ private readonly cardVideo = new VideoController(this);
44
+
45
+ private readonly player = new PlayerController(this, {
46
+ label: LABELS.player,
47
+ expandLabel: LABELS.expand,
48
+ collapseLabel: LABELS.collapse,
49
+ closeLabel: LABELS.close,
50
+ playLabel: LABELS.play,
51
+ pauseLabel: LABELS.pause,
52
+ soundOnLabel: LABELS.soundOn,
53
+ soundOffLabel: LABELS.soundOff,
54
+ onClose: () => this.closePlayer(),
55
+ });
56
+
57
+ // Lit keeps the card's DOM when the element is moved (removed and appended
58
+ // again), but the browser pauses a removed video and doesn't autoplay it
59
+ // again. resume() only plays a video that autoplays (not with reduced
60
+ // motion), and does nothing on the first connection, before the render.
61
+ // Not in VideoController.hostConnected: there, the player's video is still
62
+ // in the DOM until the next update and would play for a moment.
63
+ connectedCallback() {
64
+ super.connectedCallback();
65
+ this.cardVideo.resume();
52
66
  }
53
67
 
54
68
  private openPlayer() {
55
- if (this.player || !this.shadowRoot) return;
69
+ if (this.player.isOpen) return;
56
70
 
57
- this.player = createPlayer(PLACEHOLDER_STORY, {
58
- label: LABELS.player,
59
- expandLabel: LABELS.expand,
60
- collapseLabel: LABELS.collapse,
61
- closeLabel: LABELS.close,
62
- onClose: () => this.closePlayer(),
63
- });
64
- this.shadowRoot.append(this.player);
65
- showPlayer(this.player);
66
- document.addEventListener("keydown", this.onKeyDown);
67
-
68
- this.player.querySelector<HTMLElement>(".player-close")?.focus();
69
- }
70
-
71
- private closePlayer({ restoreFocus = true } = {}) {
72
- if (!this.player) return;
73
-
74
- document.removeEventListener("keydown", this.onKeyDown);
75
- this.player.remove();
76
- this.player = null;
77
-
78
- if (restoreFocus) {
79
- this.shadowRoot?.querySelector<HTMLElement>(".root .card")?.focus();
80
- }
71
+ // While the player is open, the card behind it stops on its cover.
72
+ this.cardVideo.pause();
73
+ void this.player.open();
81
74
  }
82
75
 
83
- connectedCallback() {
84
- if (!this.shadowRoot) {
85
- const root = this.attachShadow({ mode: "open" });
86
- root.innerHTML = `<style>${styles}</style><div class="root"></div>`;
87
- }
76
+ // The player also closes on its own when the element leaves the page,
77
+ // without this: there is no card to give focus back to or to resume playing
78
+ // (it would play out of sight).
79
+ private closePlayer() {
80
+ if (!this.player.isOpen) return;
88
81
 
89
- this.render();
82
+ this.player.close();
83
+ this.cardVideo.resume();
84
+ this.renderRoot.querySelector<HTMLElement>(".root .card-open")?.focus();
90
85
  }
91
86
 
92
- disconnectedCallback() {
93
- this.closePlayer({ restoreFocus: false });
87
+ protected render() {
88
+ return html`
89
+ <div class="root">
90
+ ${renderCard(PLACEHOLDER_STORY, this.cardVideo, {
91
+ label: LABELS.watch,
92
+ soundOnLabel: LABELS.soundOn,
93
+ soundOffLabel: LABELS.soundOff,
94
+ onSelect: () => this.openPlayer(),
95
+ })}
96
+ </div>
97
+ ${this.player.render(PLACEHOLDER_STORY)}
98
+ `;
94
99
  }
95
100
  }
96
101
 
package/src/types.ts CHANGED
@@ -6,4 +6,9 @@ export interface StoryAd {
6
6
  ad_id: string;
7
7
  /** Cover image shown before the video plays. */
8
8
  poster_url?: string;
9
+ /** The 9:16 MP4 the card and the player play. */
10
+ media_url?: string;
9
11
  }
12
+
13
+ /** What the card and the player show: the cover and the video. */
14
+ export type StoryMedia = Pick<StoryAd, "poster_url" | "media_url">;