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