@vtex/ads-stories 0.4.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,5 +1,8 @@
1
- import { createCard, playVideo } from "../card";
2
- import { createIcon, type IconName } from "../icons";
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";
3
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,
@@ -11,7 +14,7 @@ import type { StoryMedia } 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;
@@ -215,165 +218,225 @@ export interface PlayerOptions {
215
218
  pauseLabel: string;
216
219
  soundOnLabel: string;
217
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
+ */
218
225
  onClose: () => void;
219
226
  }
220
227
 
221
- function createButton(className: string, label: string, icon: IconName) {
222
- const button = document.createElement("button");
223
- button.type = "button";
224
- button.className = `player-button ${className}`;
225
- button.setAttribute("aria-label", label);
226
- button.append(createIcon(icon));
227
- return button;
228
- }
229
-
230
- function supportsPopover(player: HTMLDialogElement) {
231
- return typeof player.showPopover === "function";
232
- }
233
-
234
- /** Shows the player as the mini player. It must already be in the page. */
235
- export function showPlayer(player: HTMLDialogElement) {
236
- if (supportsPopover(player)) player.showPopover();
237
- else player.show();
238
- }
239
-
240
- /** Plays the player's video, if it has one. */
241
- export function playPlayer(player: HTMLDialogElement) {
242
- const video = player.querySelector("video");
243
- if (video) playVideo(video);
228
+ function supportsPopover(dialog: HTMLDialogElement) {
229
+ return typeof dialog.showPopover === "function";
244
230
  }
245
231
 
246
232
  /**
247
- * Play/pause in the middle of the video and sound on/off at its top right.
248
- * Clicking the video also plays or pauses it. The buttons follow the video's
249
- * own events, so a blocked autoplay shows as paused.
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.
250
237
  */
251
- function addVideoControls(
252
- player: HTMLDialogElement,
253
- card: HTMLElement,
254
- video: HTMLVideoElement,
255
- options: PlayerOptions,
256
- ) {
257
- // Not a .player-button: it keeps the card's larger glass look.
258
- const toggle = document.createElement("button");
259
- toggle.type = "button";
260
- toggle.className = "play player-toggle";
261
- const sound = createButton("player-sound", "", "soundOff");
262
-
263
- function syncPlayback() {
264
- player.toggleAttribute("data-paused", video.paused);
265
- toggle.setAttribute(
266
- "aria-label",
267
- video.paused ? options.playLabel : options.pauseLabel,
268
- );
269
- toggle.replaceChildren(createIcon(video.paused ? "play" : "pause"));
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);
270
259
  }
271
260
 
272
- function syncSound() {
273
- sound.setAttribute(
274
- "aria-label",
275
- video.muted ? options.soundOnLabel : options.soundOffLabel,
276
- );
277
- sound.replaceChildren(createIcon(video.muted ? "soundOff" : "soundOn"));
261
+ hostDisconnected() {
262
+ this.close();
278
263
  }
279
264
 
280
- function togglePlayback() {
281
- if (video.paused) playVideo(video);
282
- else video.pause();
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();
283
284
  }
284
285
 
285
- video.addEventListener("play", syncPlayback);
286
- video.addEventListener("pause", syncPlayback);
287
- video.addEventListener("volumechange", syncSound);
288
- // Without the video, the cover stays and there is nothing to control.
289
- video.addEventListener("error", () => {
290
- toggle.remove();
291
- sound.remove();
292
- delete player.dataset.paused;
293
- });
294
-
295
- toggle.addEventListener("click", (event) => {
296
- event.stopPropagation();
297
- togglePlayback();
298
- });
299
- sound.addEventListener("click", (event) => {
300
- event.stopPropagation();
301
- video.muted = !video.muted;
302
- });
303
- card.addEventListener("click", () => {
304
- if (video.isConnected) togglePlayback();
305
- });
306
-
307
- syncPlayback();
308
- syncSound();
309
- card.append(toggle, sound);
310
- }
311
-
312
- /**
313
- * The Story player. It opens as the mini player (see showPlayer); expand
314
- * switches to the expanded view, a modal dialog, and back. Clicking the
315
- * backdrop of the expanded view or pressing Escape in it closes the player.
316
- * The video starts muted (see playPlayer).
317
- */
318
- export function createPlayer(story: StoryMedia, options: PlayerOptions) {
319
- const player = document.createElement("dialog");
320
- player.className = "player";
321
- player.setAttribute("popover", "manual");
322
- player.setAttribute("aria-label", options.label);
286
+ /** Hides the player now; the host removes it on its next update. */
287
+ close() {
288
+ if (!this.isOpen) return;
323
289
 
324
- const frame = document.createElement("div");
325
- frame.className = "player-frame";
326
-
327
- const controls = document.createElement("div");
328
- controls.className = "player-controls";
329
-
330
- const expand = createButton("player-expand", options.expandLabel, "expand");
331
- const close = createButton("player-close", options.closeLabel, "close");
332
- controls.append(expand, close);
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
+ }
333
296
 
334
- let expanded = false;
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
+ }
335
308
 
336
309
  // A dialog can't be shown as a popover and as a modal at the same time, so
337
310
  // switching modes hides it first, the same way it was shown.
338
- function hide() {
339
- if (!expanded && supportsPopover(player)) player.hidePopover();
340
- 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;
341
316
  }
342
317
 
343
- expand.addEventListener("click", () => {
344
- hide();
345
- expanded = !expanded;
346
- player.toggleAttribute("data-expanded", expanded);
347
- player.dataset.switched = "";
348
- expand.setAttribute(
349
- "aria-label",
350
- expanded ? options.collapseLabel : options.expandLabel,
351
- );
352
- expand.replaceChildren(createIcon(expanded ? "collapse" : "expand"));
318
+ private readonly toggleExpanded = async () => {
319
+ const dialog = this.dialog.value;
320
+ if (!dialog) return;
321
+
322
+ this.hide(dialog);
323
+ this.expanded = !this.expanded;
324
+ this.switched = true;
325
+ this.host.requestUpdate();
326
+ await this.host.updateComplete;
353
327
 
354
- if (expanded) player.showModal();
355
- else showPlayer(player);
356
- expand.focus();
357
- });
328
+ if (!this.isOpen) return;
329
+ this.show(dialog);
330
+ this.expandButton.value?.focus();
331
+ };
358
332
 
359
- close.addEventListener("click", options.onClose);
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
+ };
360
337
 
361
338
  // Clicks on the backdrop of the expanded view reach the dialog itself.
362
- player.addEventListener("click", (event) => {
363
- if (expanded && event.target === player) options.onClose();
364
- });
339
+ private readonly onDialogClick = (event: Event) => {
340
+ if (this.expanded && event.target === event.currentTarget) {
341
+ this.options.onClose();
342
+ }
343
+ };
365
344
 
366
345
  // Escape on a modal dialog would only hide it: close the player instead.
367
- player.addEventListener("cancel", (event) => {
346
+ private readonly onCancel = (event: Event) => {
368
347
  event.preventDefault();
369
- options.onClose();
370
- });
371
-
372
- const card = createCard(story);
373
- const video = card.querySelector("video");
374
- if (video) addVideoControls(player, card, video, options);
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
+ }
375
388
 
376
- frame.append(controls, card);
377
- player.append(frame);
378
- 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
+ }
379
442
  }
@@ -1,27 +1,11 @@
1
- import { cardStyles, createCard, playVideo } from "../components/card";
2
- import {
3
- createPlayer,
4
- playerStyles,
5
- playPlayer,
6
- showPlayer,
7
- } from "../components/player";
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";
8
5
  import type { StoryMedia } from "../types";
9
6
 
10
7
  export const TAG_NAME = "vtex-ads-story";
11
8
 
12
- // Keeps the module importable where HTMLElement doesn't exist (SSR, Node).
13
- const BaseElement: typeof HTMLElement = globalThis.HTMLElement ?? Object;
14
-
15
- const styles = `
16
- :host {
17
- display: block;
18
- font-family: var(--vtex-ads-story-font-family, inherit);
19
- color: var(--vtex-ads-story-color-text, inherit);
20
- }
21
- ${cardStyles}
22
- ${playerStyles}
23
- `;
24
-
25
9
  // Temporary: rendered until the element reads Stories from the ad API.
26
10
  const PLACEHOLDER_STORY: StoryMedia = {
27
11
  poster_url: "https://dummyimage.com/1080x1920/e31c57/fff",
@@ -41,84 +25,77 @@ const LABELS = {
41
25
  soundOff: "Desativar som",
42
26
  };
43
27
 
44
- export class VtexAdsStoryElement extends BaseElement {
45
- private player: HTMLDialogElement | null = null;
46
-
47
- private readonly onKeyDown = (event: KeyboardEvent) => {
48
- if (event.key === "Escape") this.closePlayer();
49
- };
50
-
51
- private render() {
52
- const container = this.shadowRoot?.querySelector(".root");
53
- if (!container) return;
54
-
55
- container.replaceChildren(
56
- createCard(PLACEHOLDER_STORY, {
57
- label: LABELS.watch,
58
- soundOnLabel: LABELS.soundOn,
59
- soundOffLabel: LABELS.soundOff,
60
- onSelect: () => this.openPlayer(),
61
- }),
62
- );
63
- }
64
-
65
- private cardVideo() {
66
- return this.shadowRoot?.querySelector<HTMLVideoElement>(
67
- ".root .card video",
68
- );
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();
69
66
  }
70
67
 
71
68
  private openPlayer() {
72
- if (this.player || !this.shadowRoot) return;
69
+ if (this.player.isOpen) return;
73
70
 
74
- this.player = createPlayer(PLACEHOLDER_STORY, {
75
- label: LABELS.player,
76
- expandLabel: LABELS.expand,
77
- collapseLabel: LABELS.collapse,
78
- closeLabel: LABELS.close,
79
- playLabel: LABELS.play,
80
- pauseLabel: LABELS.pause,
81
- soundOnLabel: LABELS.soundOn,
82
- soundOffLabel: LABELS.soundOff,
83
- onClose: () => this.closePlayer(),
84
- });
85
- this.shadowRoot.append(this.player);
86
- showPlayer(this.player);
87
71
  // While the player is open, the card behind it stops on its cover.
88
- this.cardVideo()?.pause();
89
- playPlayer(this.player);
90
- document.addEventListener("keydown", this.onKeyDown);
91
-
92
- this.player.querySelector<HTMLElement>(".player-close")?.focus();
93
- }
94
-
95
- // `removed`: the element is leaving the page, so there is no card to give
96
- // focus back to or to resume playing (it would play out of sight).
97
- private closePlayer({ removed = false } = {}) {
98
- if (!this.player) return;
99
-
100
- document.removeEventListener("keydown", this.onKeyDown);
101
- this.player.remove();
102
- this.player = null;
103
- if (removed) return;
104
-
105
- const video = this.cardVideo();
106
- if (video?.autoplay) playVideo(video);
107
-
108
- this.shadowRoot?.querySelector<HTMLElement>(".root .card-open")?.focus();
72
+ this.cardVideo.pause();
73
+ void this.player.open();
109
74
  }
110
75
 
111
- connectedCallback() {
112
- if (!this.shadowRoot) {
113
- const root = this.attachShadow({ mode: "open" });
114
- root.innerHTML = `<style>${styles}</style><div class="root"></div>`;
115
- }
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;
116
81
 
117
- this.render();
82
+ this.player.close();
83
+ this.cardVideo.resume();
84
+ this.renderRoot.querySelector<HTMLElement>(".root .card-open")?.focus();
118
85
  }
119
86
 
120
- disconnectedCallback() {
121
- this.closePlayer({ removed: true });
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
+ `;
122
99
  }
123
100
  }
124
101