@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
@@ -1,10 +1,33 @@
1
1
  import { css, html, nothing } from "lit";
2
+ import type { StoryLabels } from "../../locales";
2
3
  import type { ReactiveController, ReactiveControllerHost } from "lit";
3
4
  import { createRef, ref } from "lit/directives/ref.js";
5
+ import { repeat } from "lit/directives/repeat.js";
6
+ import { styleMap } from "lit/directives/style-map.js";
4
7
  import { icon } from "../icons";
5
- import { hasVideo, renderMedia, VideoController } from "../media";
8
+ import {
9
+ hasVideo,
10
+ prefersReducedMotion,
11
+ renderMedia,
12
+ VideoController,
13
+ } from "../media";
14
+ import { httpUrl } from "../../utils/safe-url";
15
+ import {
16
+ renderCta,
17
+ renderExpandableProduct,
18
+ type CardCta,
19
+ type CardProduct,
20
+ type ProductCartActions,
21
+ } from "../product";
6
22
  import type { StoryMedia } from "../../types";
7
23
 
24
+ /**
25
+ * Expanded view gaps, in pixels: between the video and the nearest covers,
26
+ * and between covers. Shared by the CSS and the step animation.
27
+ */
28
+ export const NEAR_GAP = 72;
29
+ export const FAR_GAP = 48;
30
+
8
31
  // The player is a <dialog> shown in the top layer, so no store z-index,
9
32
  // overflow or transform can hide or move it.
10
33
  //
@@ -47,12 +70,28 @@ export const playerStyles = css`
47
70
  background: transparent;
48
71
  }
49
72
 
73
+ /* Focusable only to keep the focus in the player when its video is clicked
74
+ (see render): no ring around the whole player. */
75
+ .player:focus {
76
+ outline: none;
77
+ }
78
+
50
79
  .player-frame {
51
80
  position: relative;
52
81
  width: 100%;
53
82
  height: 100%;
54
83
  }
55
84
 
85
+ /* What moves in the expanded view, off center with two Stories and in the
86
+ step animation: the video, its dimming and previous and next. Expand and
87
+ close stay out of it: a transformed box becomes the one their fixed
88
+ position, at the top right of the screen, is measured from. */
89
+ .player-stage {
90
+ position: relative;
91
+ width: 100%;
92
+ height: 100%;
93
+ }
94
+
56
95
  .player .card {
57
96
  width: 100%;
58
97
  height: 100%;
@@ -99,6 +138,26 @@ export const playerStyles = css`
99
138
  height: 20px;
100
139
  }
101
140
 
141
+ /* The product pill or the call to action. Their wrapper only stops clicks:
142
+ the pill places itself. The product is larger than on the carousel card
143
+ (as in the prototype). */
144
+ .player-destination {
145
+ display: contents;
146
+ }
147
+
148
+ .player .product-info {
149
+ font-size: 14px;
150
+ }
151
+
152
+ .player .product-image {
153
+ width: 72px;
154
+ height: 72px;
155
+ }
156
+
157
+ .player .product-price {
158
+ color: rgba(255, 255, 255, 0.7);
159
+ }
160
+
102
161
  /* Above the card: on narrow screens the expanded card can cover them. */
103
162
  .player-controls {
104
163
  position: absolute;
@@ -109,6 +168,12 @@ export const playerStyles = css`
109
168
  gap: 8px;
110
169
  }
111
170
 
171
+ /* Previous and next Story, above the card's top left (mini player only). */
172
+ .player-nav {
173
+ right: auto;
174
+ left: 0;
175
+ }
176
+
112
177
  .player-button {
113
178
  display: grid;
114
179
  width: 36px;
@@ -162,6 +227,116 @@ export const playerStyles = css`
162
227
  height: 40px;
163
228
  }
164
229
 
230
+ /* Expanded with more than one Story: the other Stories' covers beside the
231
+ video, smaller and dimmed, as in the prototype. --side is -1 (before)
232
+ or 1 (after), --beyond how many places past the nearest one. */
233
+ .player[data-expanded] {
234
+ --center-height: min(78vh, 720px);
235
+ --side-height: min(38vh, 320px);
236
+ --side-width: calc(var(--side-height) * 9 / 16);
237
+ --center-half: calc(var(--center-height) * 9 / 32);
238
+ --near-gap: ${NEAR_GAP}px;
239
+ --far-gap: ${FAR_GAP}px;
240
+ --near: calc(var(--center-half) + var(--near-gap) + var(--side-width) / 2);
241
+ --pitch: calc(var(--side-width) + var(--far-gap));
242
+ }
243
+
244
+ .player-neighbor {
245
+ position: absolute;
246
+ top: 50%;
247
+ left: 50%;
248
+ width: var(--side-width);
249
+ height: var(--side-height);
250
+ padding: 0;
251
+ overflow: hidden;
252
+ border: 0;
253
+ border-radius: var(--vtex-ads-story-radius, 16px);
254
+ background: #111;
255
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
256
+ cursor: pointer;
257
+ transform: translate(
258
+ calc(-50% + var(--side) * var(--near) + var(--beyond) * var(--pitch)),
259
+ -50%
260
+ );
261
+ }
262
+
263
+ .player-neighbor img {
264
+ width: 100%;
265
+ height: 100%;
266
+ object-fit: cover;
267
+ }
268
+
269
+ /* Fades out as the video arrives from a dimmed cover (see animateStep). */
270
+ .player-dim {
271
+ position: absolute;
272
+ inset: 0;
273
+ z-index: 3;
274
+ border-radius: var(--vtex-ads-story-radius, 20px);
275
+ background: rgba(0, 0, 0, 0.35);
276
+ opacity: 0;
277
+ pointer-events: none;
278
+ }
279
+
280
+ .player-neighbor::after {
281
+ position: absolute;
282
+ inset: 0;
283
+ background: rgba(0, 0, 0, 0.35);
284
+ content: "";
285
+ }
286
+
287
+ .player-neighbor:hover::after,
288
+ .player-neighbor:focus-visible::after {
289
+ background: rgba(0, 0, 0, 0.12);
290
+ }
291
+
292
+ .player-neighbor:focus-visible {
293
+ outline: 2px solid #fff;
294
+ outline-offset: 2px;
295
+ }
296
+
297
+ /* Two Stories: the video moves off center toward --pair-dir, and the other
298
+ Story sits on the other side. */
299
+ .player[data-pair] .player-stage {
300
+ transform: translateX(
301
+ calc(var(--pair-dir) * (var(--near-gap) + var(--side-width)) / 2)
302
+ );
303
+ }
304
+
305
+ .player[data-pair] .player-neighbor {
306
+ transform: translate(
307
+ calc(
308
+ -50% + var(--pair-dir) * -1 * (var(--center-half) + var(--near-gap) / 2)
309
+ ),
310
+ -50%
311
+ );
312
+ }
313
+
314
+ /* Expanded previous and next: beside the video, centered on its height. */
315
+ .player[data-expanded] .player-nav {
316
+ position: static;
317
+ display: contents;
318
+ }
319
+
320
+ .player[data-expanded] .player-nav .player-button {
321
+ position: absolute;
322
+ top: 50%;
323
+ z-index: 2;
324
+ transform: translateY(-50%);
325
+ }
326
+
327
+ .player[data-expanded] .player-previous {
328
+ left: -56px;
329
+ }
330
+
331
+ .player[data-expanded] .player-next {
332
+ right: -56px;
333
+ }
334
+
335
+ /* With two, the other Story's cover beside the video does that. */
336
+ .player[data-expanded][data-pair] .player-nav {
337
+ display: none;
338
+ }
339
+
165
340
  @media (max-width: 576px) {
166
341
  .player {
167
342
  right: 12px;
@@ -169,6 +344,18 @@ export const playerStyles = css`
169
344
  height: 391px;
170
345
  }
171
346
 
347
+ .player:not([data-expanded]) .product-image {
348
+ width: 56px;
349
+ height: 56px;
350
+ }
351
+
352
+ /* "Adicionar ao carrinho" fits on one line in the narrow mini player. */
353
+ .player:not([data-expanded]) .product-action {
354
+ height: 40px;
355
+ padding: 0 8px;
356
+ font-size: 12px;
357
+ }
358
+
172
359
  .player[data-expanded] {
173
360
  background: #000;
174
361
  }
@@ -191,6 +378,28 @@ export const playerStyles = css`
191
378
  top: 60px;
192
379
  right: 12px;
193
380
  }
381
+
382
+ /* No room for the other Stories' covers: previous and next go inside
383
+ the video's edges instead, also with two. */
384
+ .player-neighbor {
385
+ display: none;
386
+ }
387
+
388
+ .player[data-pair] .player-stage {
389
+ transform: none;
390
+ }
391
+
392
+ .player[data-expanded][data-pair] .player-nav {
393
+ display: contents;
394
+ }
395
+
396
+ .player[data-expanded] .player-previous {
397
+ left: 12px;
398
+ }
399
+
400
+ .player[data-expanded] .player-next {
401
+ right: 12px;
402
+ }
194
403
  }
195
404
 
196
405
  @keyframes player-in {
@@ -208,16 +417,13 @@ export const playerStyles = css`
208
417
  `;
209
418
 
210
419
  export interface PlayerOptions {
211
- /** Accessible name of the player. */
212
- label: string;
213
- /** Accessible names of the buttons. */
214
- expandLabel: string;
215
- collapseLabel: string;
216
- closeLabel: string;
217
- playLabel: string;
218
- pauseLabel: string;
219
- soundOnLabel: string;
220
- soundOffLabel: string;
420
+ /**
421
+ * Called by the previous (-1) and next (1) buttons, by another Story's
422
+ * cover in the expanded view (its offset) and, in the expanded view, when
423
+ * the video ends (1). Show the Story it
424
+ * leads to with the next render(), then call showNext().
425
+ */
426
+ onStep?: (delta: number) => void;
221
427
  /**
222
428
  * Called by the close button, Escape and a click on the expanded view's
223
429
  * backdrop. Call close() from it.
@@ -225,6 +431,205 @@ export interface PlayerOptions {
225
431
  onClose: () => void;
226
432
  }
227
433
 
434
+ /** Another Story shown beside the expanded video. */
435
+ export interface PlayerNeighbor {
436
+ /** Places from the Story in the player: negative before, positive after. */
437
+ offset: number;
438
+ story: StoryMedia;
439
+ /**
440
+ * Accessible name of its cover, telling it apart from the others (default
441
+ * the `show` text).
442
+ */
443
+ label?: string;
444
+ }
445
+
446
+ export interface PlayerRenderOptions {
447
+ labels: StoryLabels;
448
+ /**
449
+ * More than one Story: previous and next buttons and, in the expanded
450
+ * view, the video moves on to the next Story when it ends.
451
+ */
452
+ navigation?: boolean;
453
+ /** The other Stories beside the expanded video (see neighborOffsets). */
454
+ neighbors?: readonly PlayerNeighbor[];
455
+ /** The Story's product, shown at the bottom of the video. */
456
+ product?: CardProduct;
457
+ /** The Story's call to action, for a link destination (no product). */
458
+ cta?: CardCta;
459
+ /**
460
+ * What the product's panel does with the cart: add to cart and plus keep
461
+ * the player open; minus is a trash with one left.
462
+ */
463
+ productActions?: ProductCartActions;
464
+ /**
465
+ * Called by any click on the video's card (the video, its play and sound
466
+ * buttons, the product and the call to action), before what that click
467
+ * does. Not by previous and next, the window buttons or the covers beside
468
+ * the video.
469
+ */
470
+ onPress?: () => void;
471
+ }
472
+
473
+ // What shows at the bottom of the video: one or the other.
474
+ type StoryDestination = Pick<
475
+ PlayerRenderOptions,
476
+ "product" | "cta" | "labels" | "productActions"
477
+ >;
478
+
479
+ /**
480
+ * Offsets of the Stories shown beside the expanded video, as in the
481
+ * prototype: one with two Stories, on the side away from the edge the
482
+ * highlighted one is on; otherwise the nearest ones, up to two per side, each
483
+ * Story once.
484
+ */
485
+ export function neighborOffsets(count: number, active: number): number[] {
486
+ if (count < 2) return [];
487
+ if (count === 2) return [active === 0 ? 1 : -1];
488
+
489
+ const offsets: number[] = [];
490
+ const shown = new Set([0]);
491
+ for (const offset of [-1, 1, -2, 2]) {
492
+ const index = ((offset % count) + count) % count;
493
+ if (!shown.has(index)) {
494
+ shown.add(index);
495
+ offsets.push(offset);
496
+ }
497
+ }
498
+ return offsets;
499
+ }
500
+
501
+ /** The prototype's expanded step: slow at the end, without bounce. */
502
+ export const STEP_ANIMATION: KeyframeAnimationOptions = {
503
+ duration: 560,
504
+ easing: "cubic-bezier(0.32, 0.72, 0, 1)",
505
+ };
506
+
507
+ /** Widths of the expanded view, in pixels, as rendered. */
508
+ interface StepSizes {
509
+ frameWidth: number;
510
+ sideWidth: number;
511
+ }
512
+
513
+ /** The Story in the player and the covers beside it, as rendered. */
514
+ interface ShownStories {
515
+ story: StoryMedia;
516
+ neighbors: readonly PlayerNeighbor[];
517
+ }
518
+
519
+ /** A cover beside the expanded video and its place (see PlayerNeighbor). */
520
+ interface RenderedNeighbor {
521
+ element: HTMLElement;
522
+ offset: number;
523
+ }
524
+
525
+ // Each cover is centered on the screen by translate(-50%, -50%), then moved.
526
+ const coverTransform = (x: number, scale = 1) =>
527
+ `translate(-50%, -50%) translateX(${x}px) scale(${scale})`;
528
+
529
+ const fadeIn = (element: HTMLElement) =>
530
+ element.animate([{ opacity: 0 }, { opacity: 1 }], {
531
+ ...STEP_ANIMATION,
532
+ pseudoElement: "::after",
533
+ });
534
+
535
+ /**
536
+ * Three or more Stories: the video comes from `frameFrom`, the place of the
537
+ * cover of the Story it now shows. Each cover comes from `from`, its Story's
538
+ * place before the step; the one that was the video, from the middle, at the
539
+ * video's size, its dimming fading in. The places match the CSS
540
+ * (--near, --pitch).
541
+ */
542
+ function animateRailStep(
543
+ frame: HTMLElement,
544
+ frameFrom: number,
545
+ neighbors: readonly (RenderedNeighbor & { from: number })[],
546
+ { frameWidth, sideWidth }: StepSizes,
547
+ ): Animation[] {
548
+ const placeX = (place: number) => {
549
+ if (place === 0) return 0;
550
+ const side = Math.sign(place);
551
+ const near = frameWidth / 2 + NEAR_GAP + sideWidth / 2;
552
+ return side * near + (place - side) * (sideWidth + FAR_GAP);
553
+ };
554
+ const ratio = sideWidth / frameWidth;
555
+
556
+ const animations = [
557
+ frame.animate(
558
+ [
559
+ { transform: `translateX(${placeX(frameFrom)}px) scale(${ratio})` },
560
+ { transform: "none" },
561
+ ],
562
+ STEP_ANIMATION,
563
+ ),
564
+ ];
565
+
566
+ for (const { element, offset, from } of neighbors) {
567
+ const wasVideo = from === 0;
568
+
569
+ animations.push(
570
+ element.animate(
571
+ [
572
+ { transform: coverTransform(placeX(from), wasVideo ? 1 / ratio : 1) },
573
+ { transform: coverTransform(placeX(offset)) },
574
+ ],
575
+ STEP_ANIMATION,
576
+ ),
577
+ );
578
+ if (wasVideo) animations.push(fadeIn(element));
579
+ }
580
+ return animations;
581
+ }
582
+
583
+ /**
584
+ * Two Stories: the video and the other cover swap sides. `direction` is the
585
+ * side the video ends on (--pair-dir). The places match the CSS.
586
+ */
587
+ function animatePairStep(
588
+ frame: HTMLElement,
589
+ neighbor: HTMLElement,
590
+ direction: number,
591
+ { frameWidth, sideWidth }: StepSizes,
592
+ ): Animation[] {
593
+ const videoX = (side: number) => (side * (NEAR_GAP + sideWidth)) / 2;
594
+ const coverX = (side: number) => (-side * (frameWidth + NEAR_GAP)) / 2;
595
+ const ratio = sideWidth / frameWidth;
596
+
597
+ return [
598
+ frame.animate(
599
+ [
600
+ { transform: `translateX(${coverX(-direction)}px) scale(${ratio})` },
601
+ { transform: `translateX(${videoX(direction)}px)` },
602
+ ],
603
+ STEP_ANIMATION,
604
+ ),
605
+ neighbor.animate(
606
+ [
607
+ { transform: coverTransform(videoX(-direction), 1 / ratio) },
608
+ { transform: coverTransform(coverX(direction)) },
609
+ ],
610
+ STEP_ANIMATION,
611
+ ),
612
+ fadeIn(neighbor),
613
+ ];
614
+ }
615
+
616
+ /** The keys that step to the previous (-1) and next (1) Story. */
617
+ const ARROW_STEPS: Readonly<Record<string, number>> = {
618
+ ArrowLeft: -1,
619
+ ArrowRight: 1,
620
+ };
621
+
622
+ /**
623
+ * Whether an arrow key press is free for the player: not already handled,
624
+ * and without a modifier (Alt+Left goes back in the browser).
625
+ */
626
+ const isFreeArrowKey = (event: KeyboardEvent) =>
627
+ !event.defaultPrevented &&
628
+ !event.altKey &&
629
+ !event.ctrlKey &&
630
+ !event.metaKey &&
631
+ !event.shiftKey;
632
+
228
633
  function supportsPopover(dialog: HTMLDialogElement) {
229
634
  return typeof dialog.showPopover === "function";
230
635
  }
@@ -232,7 +637,7 @@ function supportsPopover(dialog: HTMLDialogElement) {
232
637
  /**
233
638
  * The Story player, rendered by its host with render(). open() shows it as
234
639
  * 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
640
+ * back. The video plays with the sound on when the player opens. It closes on
236
641
  * its own when the host leaves the page.
237
642
  */
238
643
  export class PlayerController implements ReactiveController {
@@ -241,6 +646,19 @@ export class PlayerController implements ReactiveController {
241
646
  /** Rendered and, once the host has updated, shown. */
242
647
  isOpen = false;
243
648
  private expanded = false;
649
+
650
+ /** Open in the expanded view, a modal over the page. */
651
+ get isExpanded() {
652
+ return this.isOpen && this.expanded;
653
+ }
654
+
655
+ /** The card with the video, while the player is open. */
656
+ get stageCard(): Element | undefined {
657
+ return this.isOpen ? this.stageCardRef.value : undefined;
658
+ }
659
+
660
+ /** The product panel is open. Closed again on a step and on opening. */
661
+ private productOpen = false;
244
662
  /** Switched modes at least once: only the first opening fades in. */
245
663
  private switched = false;
246
664
  /** The dialog is showing, in the mode `expanded` says. */
@@ -249,6 +667,26 @@ export class PlayerController implements ReactiveController {
249
667
  private readonly dialog = createRef<HTMLDialogElement>();
250
668
  private readonly expandButton = createRef<HTMLButtonElement>();
251
669
  private readonly closeButton = createRef<HTMLButtonElement>();
670
+ private readonly stage = createRef<HTMLElement>();
671
+ private readonly stageCardRef = createRef<HTMLElement>();
672
+ private readonly dim = createRef<HTMLElement>();
673
+
674
+ /** The covers beside the expanded video, by offset, as rendered. */
675
+ private readonly neighborElements = new Map<number, HTMLElement>();
676
+ /** One ref callback per offset: a new one each render would detach it. */
677
+ private readonly neighborRefs = new Map<
678
+ number,
679
+ (element?: Element) => void
680
+ >();
681
+ /** Rendered with previous and next (see PlayerRenderOptions). */
682
+ private navigation = false;
683
+ /** Side the expanded video moved to with two Stories; 0 otherwise. */
684
+ private pairDirection = 0;
685
+ /** The Story and covers rendered, and those before the last step. */
686
+ private rendered?: ShownStories;
687
+ private beforeStep?: ShownStories;
688
+ /** The step animation running, cancelled by the next step. */
689
+ private animations: Animation[] = [];
252
690
 
253
691
  constructor(
254
692
  private readonly host: ReactiveControllerHost,
@@ -262,14 +700,22 @@ export class PlayerController implements ReactiveController {
262
700
  this.close();
263
701
  }
264
702
 
265
- /** Opens the mini player, plays the video and focuses the close button. */
266
- async open() {
703
+ /**
704
+ * Opens the mini player, plays the video with the sound on (muted if the
705
+ * browser blocks it) and focuses the close button.
706
+ * With `productOpen`, the product panel shows open (the shopper chose the
707
+ * product).
708
+ */
709
+ async open({ productOpen = false }: { productOpen?: boolean } = {}) {
267
710
  if (this.isOpen) return;
268
711
 
269
712
  document.addEventListener("keydown", this.onKeyDown);
270
713
  this.isOpen = true;
271
714
  this.expanded = false;
715
+ this.productOpen = productOpen;
272
716
  this.switched = false;
717
+ this.rendered = undefined;
718
+ this.beforeStep = undefined;
273
719
  this.video.reset();
274
720
  this.host.requestUpdate();
275
721
  await this.host.updateComplete;
@@ -279,7 +725,7 @@ export class PlayerController implements ReactiveController {
279
725
  if (!this.isOpen || !dialog) return;
280
726
 
281
727
  this.show(dialog);
282
- this.video.play();
728
+ this.video.playWithSound();
283
729
  this.closeButton.value?.focus();
284
730
  }
285
731
 
@@ -288,12 +734,114 @@ export class PlayerController implements ReactiveController {
288
734
  if (!this.isOpen) return;
289
735
 
290
736
  document.removeEventListener("keydown", this.onKeyDown);
737
+ this.cancelAnimations();
291
738
  const dialog = this.dialog.value;
292
739
  if (dialog) this.hide(dialog);
293
740
  this.isOpen = false;
294
741
  this.host.requestUpdate();
295
742
  }
296
743
 
744
+ /**
745
+ * After the host renders a different Story in the open player, `delta`
746
+ * places from the previous one: its video starts from the top and plays,
747
+ * with the sound as the shopper left it. A failed load of the previous
748
+ * video doesn't hide the new one. The expanded view animates the step.
749
+ */
750
+ async showNext(delta = 0) {
751
+ if (!this.isOpen) return;
752
+
753
+ // Read before the render: a Story without a video, or a video that
754
+ // failed, replaces the <video> with a new one, muted.
755
+ const withSound = !this.video.muted;
756
+ this.video.clearFailure();
757
+ // Another Story, another product: its panel starts closed.
758
+ this.productOpen = false;
759
+ this.host.requestUpdate();
760
+ await this.host.updateComplete;
761
+ if (!this.isOpen) return;
762
+
763
+ this.video.restart({ withSound });
764
+ this.animateStep(delta);
765
+ }
766
+
767
+ /** Stops a step animation still running, leaving the CSS layout. */
768
+ private cancelAnimations() {
769
+ for (const animation of this.animations) animation.cancel();
770
+ this.animations = [];
771
+ }
772
+
773
+ /**
774
+ * The expanded step, as in the prototype: the video grows from the cover
775
+ * of the Story it now shows, and the covers slide to their new places, the
776
+ * previous Story's shrinking from the video's size. With two Stories, the
777
+ * video and the other cover swap sides. Not with reduced motion, nor
778
+ * without covers (narrow screens).
779
+ */
780
+ private animateStep(delta: number) {
781
+ if (!this.expanded || delta === 0 || prefersReducedMotion()) return;
782
+
783
+ const frame = this.stage.value;
784
+ const dim = this.dim.value;
785
+ if (!frame || !dim || typeof frame.animate !== "function") return;
786
+
787
+ // Where each Story was before the step: the video (0), its cover's
788
+ // offset, or, if it wasn't shown, `fallback`. Read from the Stories, not
789
+ // from offset + delta: with wraparound (four Stories), a Story's offset
790
+ // can change by more or less than the step.
791
+ const { rendered, beforeStep } = this;
792
+ const placeBefore = (story: StoryMedia | undefined, fallback: number) => {
793
+ if (!story || !beforeStep) return fallback;
794
+ if (story === beforeStep.story) return 0;
795
+ const cover = beforeStep.neighbors.find((n) => n.story === story);
796
+ return cover?.offset ?? fallback;
797
+ };
798
+ const neighbors = [...this.neighborElements].map(([offset, element]) => ({
799
+ offset,
800
+ element,
801
+ from: placeBefore(
802
+ rendered?.neighbors.find((n) => n.offset === offset)?.story,
803
+ offset + delta,
804
+ ),
805
+ }));
806
+
807
+ const sizes = {
808
+ frameWidth: frame.offsetWidth,
809
+ sideWidth: neighbors[0]?.element.offsetWidth ?? 0,
810
+ };
811
+ if (!sizes.frameWidth || !sizes.sideWidth) return;
812
+
813
+ this.cancelAnimations();
814
+ this.animations = [
815
+ dim.animate([{ opacity: 1 }, { opacity: 0 }], STEP_ANIMATION),
816
+ ...(this.pairDirection
817
+ ? animatePairStep(
818
+ frame,
819
+ neighbors[0].element,
820
+ this.pairDirection,
821
+ sizes,
822
+ )
823
+ : animateRailStep(
824
+ frame,
825
+ placeBefore(rendered?.story, delta),
826
+ neighbors,
827
+ sizes,
828
+ )),
829
+ ];
830
+ }
831
+
832
+ // Keeps neighborElements in step with the covers Lit renders.
833
+ private neighborRef(offset: number) {
834
+ let callback = this.neighborRefs.get(offset);
835
+ if (!callback) {
836
+ callback = (element?: Element) => {
837
+ if (element) this.neighborElements.set(offset, element as HTMLElement);
838
+ else this.neighborElements.delete(offset);
839
+ };
840
+ this.neighborRefs.set(offset, callback);
841
+ }
842
+ return callback;
843
+ }
844
+
297
845
  // Mini: a manual popover, or a non-modal dialog without popover support.
298
846
  // Expanded: a modal dialog.
299
847
  // Already showing: a second expand click in the same task resumes after the
@@ -319,6 +867,8 @@ export class PlayerController implements ReactiveController {
319
867
  const dialog = this.dialog.value;
320
868
  if (!dialog) return;
321
869
 
870
+ // A step animation would go on moving the video in the other mode.
871
+ this.cancelAnimations();
322
872
  this.hide(dialog);
323
873
  this.expanded = !this.expanded;
324
874
  this.switched = true;
@@ -335,6 +885,19 @@ export class PlayerController implements ReactiveController {
335
885
  if (event.key === "Escape") this.options.onClose();
336
886
  };
337
887
 
888
+ // With the focus in the player and more than one Story, the arrows step, as
889
+ // the previous and next buttons do. Only there: the mini player leaves the
890
+ // page usable, and the page's own arrow keys (a gallery, a slider) keep
891
+ // working.
892
+ private readonly onPlayerKeyDown = (event: KeyboardEvent) => {
893
+ const delta = ARROW_STEPS[event.key];
894
+ if (!delta || !this.navigation || !isFreeArrowKey(event)) return;
895
+
896
+ // The arrow would also scroll the page.
897
+ event.preventDefault();
898
+ this.options.onStep?.(delta);
899
+ };
900
+
338
901
  // Clicks on the backdrop of the expanded view reach the dialog itself.
339
902
  private readonly onDialogClick = (event: Event) => {
340
903
  if (this.expanded && event.target === event.currentTarget) {
@@ -353,8 +916,70 @@ export class PlayerController implements ReactiveController {
353
916
  * They follow the video's own events, so a blocked autoplay shows as
354
917
  * paused.
355
918
  */
356
- private renderVideoControls() {
357
- const { video, options } = this;
919
+ private readonly toggleProduct = () => {
920
+ this.productOpen = !this.productOpen;
921
+ this.host.requestUpdate();
922
+ };
923
+
924
+ /**
925
+ * Loads the failed video again and, once it loads, plays it with the sound
926
+ * on (muted if the browser blocks it). Not if the player closed or stepped
927
+ * meanwhile, even back to the same Story: the retry then resolves false.
928
+ */
929
+ private readonly retryVideo = () => {
930
+ this.dialog.value?.focus();
931
+ void this.video.retry().then((loaded) => {
932
+ if (loaded) this.video.playWithSound();
933
+ });
934
+ };
935
+
936
+ /**
937
+ * A click on the video: closes the product panel when it is open, plays or
938
+ * pauses the video otherwise.
939
+ */
940
+ private readonly onVideoClick = () => {
941
+ if (this.productOpen) this.toggleProduct();
942
+ else this.video.togglePlayback();
943
+ };
944
+
945
+ /**
946
+ * At the bottom of the video, the product pill, which opens the panel with
947
+ * its actions, or the call to action of a link destination. Clicks on them
948
+ * don't reach the video.
949
+ */
950
+ private renderDestination({
951
+ product,
952
+ cta,
953
+ labels,
954
+ productActions,
955
+ }: StoryDestination) {
956
+ let content;
957
+ if (product) {
958
+ content = renderExpandableProduct(product, {
959
+ ...productActions,
960
+ labels,
961
+ open: this.productOpen,
962
+ onToggle: this.toggleProduct,
963
+ panelId: "player-product-panel",
964
+ });
965
+ } else if (cta) {
966
+ content = renderCta(cta);
967
+ } else {
968
+ return nothing;
969
+ }
970
+
971
+ return html`
972
+ <div
973
+ class="player-destination"
974
+ @click=${(event: Event) => event.stopPropagation()}
975
+ >
976
+ ${content}
977
+ </div>
978
+ `;
979
+ }
980
+
981
+ private renderVideoControls(labels: StoryLabels) {
982
+ const { video } = this;
358
983
 
359
984
  // Not a .player-button: it keeps the card's larger glass look.
360
985
  const onToggle = (event: Event) => {
@@ -370,7 +995,7 @@ export class PlayerController implements ReactiveController {
370
995
  <button
371
996
  type="button"
372
997
  class="play player-toggle"
373
- aria-label=${video.paused ? options.playLabel : options.pauseLabel}
998
+ aria-label=${video.paused ? labels.play : labels.pause}
374
999
  @click=${onToggle}
375
1000
  >
376
1001
  ${icon(video.paused ? "play" : "pause")}
@@ -378,7 +1003,7 @@ export class PlayerController implements ReactiveController {
378
1003
  <button
379
1004
  type="button"
380
1005
  class="player-button player-sound"
381
- aria-label=${video.muted ? options.soundOnLabel : options.soundOffLabel}
1006
+ aria-label=${video.muted ? labels.soundOn : labels.soundOff}
382
1007
  @click=${onSound}
383
1008
  >
384
1009
  ${icon(video.muted ? "soundOff" : "soundOn")}
@@ -386,54 +1011,203 @@ export class PlayerController implements ReactiveController {
386
1011
  `;
387
1012
  }
388
1013
 
1014
+ /**
1015
+ * Previous and next Story: above the mini player's top left, beside the
1016
+ * expanded video.
1017
+ */
1018
+ private renderNavigation(labels: StoryLabels) {
1019
+ const { options } = this;
1020
+ const step = (delta: number) => () => options.onStep?.(delta);
1021
+
1022
+ return html`
1023
+ <div class="player-controls player-nav">
1024
+ <button
1025
+ type="button"
1026
+ class="player-button player-previous"
1027
+ aria-label=${labels.previous}
1028
+ @click=${step(-1)}
1029
+ >
1030
+ ${icon("previous")}
1031
+ </button>
1032
+ <button
1033
+ type="button"
1034
+ class="player-button player-next"
1035
+ aria-label=${labels.next}
1036
+ @click=${step(1)}
1037
+ >
1038
+ ${icon("next")}
1039
+ </button>
1040
+ </div>
1041
+ `;
1042
+ }
1043
+
1044
+ /** The other Stories' covers beside the expanded video. */
1045
+ private renderNeighbors(
1046
+ neighbors: readonly PlayerNeighbor[],
1047
+ labels: StoryLabels,
1048
+ ) {
1049
+ const { options } = this;
1050
+
1051
+ // With two Stories, the single cover's offset flips between 1 and -1 on
1052
+ // each step: a stable key keeps its button, and the focus on it.
1053
+ return repeat(
1054
+ neighbors,
1055
+ ({ offset }) => (neighbors.length === 1 ? "single" : offset),
1056
+ ({ offset, story, label }) => {
1057
+ const poster = httpUrl(story.poster_url);
1058
+ const side = Math.sign(offset);
1059
+ return html`
1060
+ <button
1061
+ type="button"
1062
+ class="player-neighbor"
1063
+ aria-label=${label ?? labels.show}
1064
+ style=${styleMap({
1065
+ "--side": String(side),
1066
+ "--beyond": String(offset - side),
1067
+ })}
1068
+ ${ref(this.neighborRef(offset))}
1069
+ @click=${() => options.onStep?.(offset)}
1070
+ >
1071
+ ${poster ? html`<img alt="" src=${poster} />` : nothing}
1072
+ </button>
1073
+ `;
1074
+ },
1075
+ );
1076
+ }
1077
+
1078
+ /** Expand or collapse, and close: above the video, or at the top right. */
1079
+ private renderWindowControls(labels: StoryLabels) {
1080
+ const { options, expanded } = this;
1081
+
1082
+ return html`
1083
+ <div class="player-controls">
1084
+ <button
1085
+ type="button"
1086
+ class="player-button player-expand"
1087
+ aria-label=${expanded ? labels.collapse : labels.expand}
1088
+ ${ref(this.expandButton)}
1089
+ @click=${this.toggleExpanded}
1090
+ >
1091
+ ${icon(expanded ? "collapse" : "expand")}
1092
+ </button>
1093
+ <button
1094
+ type="button"
1095
+ class="player-button player-close"
1096
+ aria-label=${labels.close}
1097
+ ${ref(this.closeButton)}
1098
+ @click=${options.onClose}
1099
+ >
1100
+ ${icon("close")}
1101
+ </button>
1102
+ </div>
1103
+ `;
1104
+ }
1105
+
1106
+ /**
1107
+ * The video with its controls and the product or call to action. With
1108
+ * `advances`, it plays once and moves on to the next Story when it ends;
1109
+ * otherwise it loops.
1110
+ */
1111
+ private renderVideo(
1112
+ story: StoryMedia,
1113
+ advances: boolean,
1114
+ destination: StoryDestination,
1115
+ ) {
1116
+ const { video, options } = this;
1117
+
1118
+ return html`
1119
+ <div class="card" ${ref(this.stageCardRef)} @click=${this.onVideoClick}>
1120
+ ${renderMedia(story, video, {
1121
+ loop: !advances,
1122
+ onEnded: advances ? () => options.onStep?.(1) : undefined,
1123
+ labels: destination.labels,
1124
+ onRetry: this.retryVideo,
1125
+ })}
1126
+ ${hasVideo(story, video)
1127
+ ? this.renderVideoControls(destination.labels)
1128
+ : nothing}
1129
+ ${this.renderDestination(destination)}
1130
+ </div>
1131
+ `;
1132
+ }
1133
+
1134
+ /**
1135
+ * Keeps what this render shows, for the step animation: the covers beside
1136
+ * the video (only in the expanded view) and the side the video moves to
1137
+ * with two Stories. A new Story makes what was shown the animation's
1138
+ * start.
1139
+ */
1140
+ private track(story: StoryMedia, neighbors: readonly PlayerNeighbor[]) {
1141
+ const shown = this.expanded ? neighbors : [];
1142
+ this.pairDirection = shown.length === 1 ? -Math.sign(shown[0].offset) : 0;
1143
+
1144
+ if (this.rendered && story !== this.rendered.story) {
1145
+ this.beforeStep = this.rendered;
1146
+ }
1147
+ this.rendered = { story, neighbors: shown };
1148
+ return shown;
1149
+ }
1150
+
389
1151
  /**
390
1152
  * The player <dialog> while it is open. Clicking the video also plays or
391
- * pauses it.
1153
+ * pauses it, and keeps the focus in the player (the dialog is focusable,
1154
+ * though not by Tab), so the arrow keys still step. With `navigation`
1155
+ * (more than one Story), it has previous and next buttons and arrow keys,
1156
+ * and the expanded view moves on when the video ends instead of looping.
1157
+ * The expanded view also shows the `neighbors` beside it.
392
1158
  */
393
- render(story: StoryMedia) {
1159
+ render(
1160
+ story: StoryMedia,
1161
+ {
1162
+ navigation = false,
1163
+ neighbors = [],
1164
+ onPress,
1165
+ ...destination
1166
+ }: PlayerRenderOptions,
1167
+ ) {
1168
+ const { labels } = destination;
394
1169
  if (!this.isOpen) return nothing;
395
1170
 
396
- const { video, options, expanded } = this;
397
- const withVideo = hasVideo(story, video);
1171
+ const { video, expanded } = this;
1172
+ const shownNeighbors = this.track(story, neighbors);
1173
+ const pair = this.pairDirection !== 0;
1174
+ this.navigation = navigation;
398
1175
 
399
1176
  return html`
400
1177
  <dialog
401
1178
  class="player"
402
1179
  popover="manual"
403
- aria-label=${options.label}
1180
+ aria-label=${labels.player}
404
1181
  ?data-expanded=${expanded}
1182
+ ?data-pair=${pair}
1183
+ style=${styleMap({
1184
+ "--pair-dir": pair ? String(this.pairDirection) : undefined,
1185
+ })}
405
1186
  ?data-switched=${this.switched}
406
- ?data-paused=${withVideo && video.paused}
1187
+ ?data-paused=${hasVideo(story, video) && video.paused}
1188
+ tabindex="-1"
407
1189
  ${ref(this.dialog)}
408
1190
  @click=${this.onDialogClick}
409
1191
  @cancel=${this.onCancel}
1192
+ @keydown=${this.onPlayerKeyDown}
410
1193
  >
1194
+ ${this.renderNeighbors(shownNeighbors, labels)}
411
1195
  <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}
1196
+ ${this.renderWindowControls(labels)}
1197
+ <div
1198
+ class="player-stage"
1199
+ ${ref(this.stage)}
1200
+ @click=${{
1201
+ handleEvent: (event: Event) => {
1202
+ const card = this.stageCardRef.value;
1203
+ if (card?.contains(event.target as Node)) onPress?.();
1204
+ },
1205
+ capture: true,
1206
+ }}
1207
+ >
1208
+ ${navigation ? this.renderNavigation(labels) : nothing}
1209
+ ${this.renderVideo(story, navigation && expanded, destination)}
1210
+ <span class="player-dim" aria-hidden="true" ${ref(this.dim)}></span>
437
1211
  </div>
438
1212
  </div>
439
1213
  </dialog>