@vtex/ads-stories 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +44 -88
  3. package/dist/cdn/vtex-ads-stories.js +1313 -74
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +3744 -513
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +46 -15
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +51 -5
  10. package/dist/cjs/story-DAiAN9v-.d.cts +260 -0
  11. package/dist/esm/index.d.ts +46 -15
  12. package/dist/esm/index.js +3348 -217
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/react.d.ts +51 -5
  15. package/dist/esm/story-DAiAN9v-.d.ts +260 -0
  16. package/package.json +18 -4
  17. package/src/cdn.ts +7 -3
  18. package/src/commerce-events.ts +93 -0
  19. package/src/components/card/card.ts +79 -14
  20. package/src/components/carousel/carousel-skeleton.ts +113 -0
  21. package/src/components/carousel/carousel.ts +715 -0
  22. package/src/components/carousel/index.ts +22 -0
  23. package/src/components/events/events-controller.ts +222 -0
  24. package/src/components/events/index.ts +6 -0
  25. package/src/components/icons/assets/caret-left-bold.svg +1 -0
  26. package/src/components/icons/assets/caret-right-bold.svg +1 -0
  27. package/src/components/icons/assets/caret-up-bold.svg +1 -0
  28. package/src/components/icons/assets/minus.svg +1 -0
  29. package/src/components/icons/assets/plus.svg +1 -0
  30. package/src/components/icons/assets/trash.svg +1 -0
  31. package/src/components/icons/assets/warning-circle-fill.svg +1 -0
  32. package/src/components/icons/index.ts +14 -0
  33. package/src/components/media/index.ts +8 -1
  34. package/src/components/media/media.styles.ts +113 -0
  35. package/src/components/media/media.ts +124 -23
  36. package/src/components/media/video-controller.ts +127 -6
  37. package/src/components/player/index.ts +6 -2
  38. package/src/components/player/player.ts +824 -50
  39. package/src/components/product/cta.ts +56 -0
  40. package/src/components/product/index.ts +22 -0
  41. package/src/components/product/price.ts +86 -0
  42. package/src/components/product/product.styles.ts +426 -0
  43. package/src/components/product/product.ts +336 -0
  44. package/src/index.ts +17 -1
  45. package/src/locales/en.ts +39 -0
  46. package/src/locales/es.ts +40 -0
  47. package/src/locales/index.ts +36 -0
  48. package/src/locales/pt.ts +39 -0
  49. package/src/locales/types.ts +44 -0
  50. package/src/react.ts +55 -7
  51. package/src/story/index.ts +5 -1
  52. package/src/story/story.ts +679 -49
  53. package/src/tag-name.ts +1 -0
  54. package/src/types.ts +8 -12
  55. package/src/utils/fetch-story.ts +113 -0
  56. package/src/utils/hydrate-products.ts +112 -0
  57. package/src/utils/media-ready.ts +58 -0
  58. package/src/utils/safe-url.ts +36 -0
  59. package/src/utils/send-event.ts +71 -0
  60. package/src/utils/with-timeout.ts +43 -0
@@ -0,0 +1,715 @@
1
+ import {
2
+ css,
3
+ html,
4
+ type ReactiveController,
5
+ type ReactiveControllerHost,
6
+ type TemplateResult,
7
+ } from "lit";
8
+ import type { StoryLabels } from "../../locales";
9
+ import { repeat } from "lit/directives/repeat.js";
10
+ import { styleMap } from "lit/directives/style-map.js";
11
+ import { icon } from "../icons";
12
+
13
+ export const STAGE_HEIGHT = css`500px`;
14
+ const SOLO_PADDING = css`24px`;
15
+
16
+ export const AUTO_ADVANCE_MS = 5000;
17
+ export const MIN_SLIDE_DURATION_MS = 2000;
18
+ export const MAX_SLIDE_DURATION_MS = 120_000;
19
+
20
+ /**
21
+ * The time each Story stays highlighted: `ms` when it is a number from zero
22
+ * up (zero: no automatic advance), raised to MIN_SLIDE_DURATION_MS when
23
+ * smaller and capped at MAX_SLIDE_DURATION_MS, AUTO_ADVANCE_MS when it is
24
+ * missing, negative or not a number.
25
+ */
26
+ export const toSlideDuration = (ms?: number) => {
27
+ if (ms === undefined || !Number.isFinite(ms) || ms < 0) {
28
+ return AUTO_ADVANCE_MS;
29
+ }
30
+ if (ms === 0) {
31
+ return 0;
32
+ }
33
+ return Math.min(Math.max(ms, MIN_SLIDE_DURATION_MS), MAX_SLIDE_DURATION_MS);
34
+ };
35
+
36
+ /** How far a pointer must move, in pixels, to count as a swipe. */
37
+ export const SWIPE_DISTANCE = 40;
38
+
39
+ /** Screens this narrow have no room for two cards side by side. */
40
+ export const NARROW_SCREEN = css`(max-width: 576px)`;
41
+
42
+ /**
43
+ * Rolling layout: cards on each side of the highlighted one. Up to
44
+ * VISIBLE_SIDE show on each side; RENDERED_SIDE are kept in the DOM, the
45
+ * farther ones hidden, so a card slides in from its place instead of
46
+ * appearing.
47
+ */
48
+ export const VISIBLE_SIDE = 2;
49
+ export const RENDERED_SIDE = VISIBLE_SIDE + 3;
50
+
51
+ /**
52
+ * How the cards are laid out:
53
+ * - solo: one Story, the card centered over the background.
54
+ * - pair: two Stories side by side; moving only changes the highlight.
55
+ * - rolling: the highlighted card in the middle, the others on each side,
56
+ * all moving one place per step. Three or more Stories, or two on narrow
57
+ * screens.
58
+ */
59
+ export type CarouselLayout = "solo" | "pair" | "rolling";
60
+
61
+ /**
62
+ * The carousel stage: a band as tall as the card, as wide as the element's
63
+ * parent. The store sets the width on its own container.
64
+ *
65
+ * Solo: the card sits centered over a solid background with room around it:
66
+ * the card shrinks to fit the padding and gets a soft shadow. On narrow
67
+ * screens (576px or less) there is no room for it: the card shows alone at
68
+ * full height.
69
+ *
70
+ * Pair and rolling: the highlighted card is full size, the others smaller
71
+ * (0.9) and dimmed.
72
+ */
73
+ export const carouselStyles = css`
74
+ .carousel {
75
+ position: relative;
76
+ box-sizing: border-box;
77
+ display: grid;
78
+ height: ${STAGE_HEIGHT};
79
+ place-items: center;
80
+ --card-height: ${STAGE_HEIGHT};
81
+ user-select: none;
82
+ }
83
+
84
+ .carousel[data-layout="solo"] {
85
+ padding: ${SOLO_PADDING};
86
+ border-radius: var(--vtex-ads-story-radius, 20px);
87
+ background: var(--vtex-ads-story-color-surface, #fafafa);
88
+ --card-height: calc(${STAGE_HEIGHT} - 2 * ${SOLO_PADDING});
89
+ }
90
+
91
+ .carousel[data-layout="solo"] .card {
92
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
93
+ }
94
+
95
+ .track {
96
+ position: absolute;
97
+ inset: 0;
98
+ overflow: hidden;
99
+ touch-action: pan-y;
100
+ }
101
+
102
+ /* Each slide starts centered, then moves by its own transform. */
103
+ .slide {
104
+ --ease: cubic-bezier(0.25, 1, 0.5, 1);
105
+ --duration: var(--slide-duration, 0.4s);
106
+ position: absolute;
107
+ top: 0;
108
+ left: 50%;
109
+ width: calc(${STAGE_HEIGHT} * 9 / 16);
110
+ height: 100%;
111
+ margin-left: calc(${STAGE_HEIGHT} * 9 / -32);
112
+ opacity: 0.5;
113
+ transition:
114
+ transform var(--duration) var(--ease),
115
+ opacity var(--duration) var(--ease),
116
+ visibility 0s;
117
+ }
118
+
119
+ .slide[data-active] {
120
+ opacity: 1;
121
+ }
122
+
123
+ /* Pair: --side is -1 for the first card, 1 for the second. The highlighted
124
+ card sits 47.5% of its width off center, the other (scaled to 0.9)
125
+ 52.5%, so the gap between them stays 8px. */
126
+ .carousel[data-layout="pair"] .slide {
127
+ --side: 1;
128
+ --offset: 52.5%;
129
+ --scale: 0.9;
130
+ transform: translateX(calc(var(--side) * (var(--offset) + 4px)))
131
+ scale(var(--scale));
132
+ }
133
+
134
+ .carousel[data-layout="pair"] .slide[data-index="0"] {
135
+ --side: -1;
136
+ }
137
+
138
+ .carousel[data-layout="pair"] .slide[data-active] {
139
+ --offset: 47.5%;
140
+ --scale: 1;
141
+ }
142
+
143
+ /* Rolling: --place is the slide's distance from the highlighted one, in
144
+ cards, 8px apart. A hidden slide fades out, then stops being visible. */
145
+ .carousel[data-layout="rolling"] .slide {
146
+ transform: translateX(calc(var(--place) * (100% + 8px))) scale(0.9);
147
+ }
148
+
149
+ .carousel[data-layout="rolling"] .slide[data-active] {
150
+ transform: translateX(0) scale(1);
151
+ }
152
+
153
+ .slide[data-hidden] {
154
+ opacity: 0;
155
+ visibility: hidden;
156
+ transition:
157
+ transform var(--duration) var(--ease),
158
+ opacity var(--duration) var(--ease),
159
+ visibility 0s var(--duration);
160
+ }
161
+
162
+ /* Only the highlighted card opens the player, so only it shows play. Its
163
+ sound is the only one to turn on: the others play muted, if at all. */
164
+ .slide:not([data-active]) .play,
165
+ .slide:not([data-active]) .card-sound {
166
+ display: none;
167
+ }
168
+
169
+ .arrow {
170
+ position: absolute;
171
+ top: 50%;
172
+ z-index: 2;
173
+ display: grid;
174
+ width: 32px;
175
+ height: 32px;
176
+ place-items: center;
177
+ padding: 0;
178
+ border: 1px solid rgba(133, 133, 133, 0.3);
179
+ border-radius: 50%;
180
+ background: rgba(0, 0, 0, 0.3);
181
+ backdrop-filter: blur(5px);
182
+ color: #fff;
183
+ cursor: pointer;
184
+ transform: translateY(-50%);
185
+ transition: background-color 0.2s;
186
+ }
187
+
188
+ .arrow:hover {
189
+ background: #262626;
190
+ }
191
+
192
+ .arrow:disabled {
193
+ cursor: default;
194
+ opacity: 0.5;
195
+ }
196
+
197
+ .arrow .icon {
198
+ width: 16px;
199
+ height: 16px;
200
+ }
201
+
202
+ .arrow-previous {
203
+ left: 3px;
204
+ }
205
+
206
+ .arrow-next {
207
+ right: 3px;
208
+ }
209
+
210
+ @media ${NARROW_SCREEN} {
211
+ .carousel[data-layout="solo"] {
212
+ padding: 0;
213
+ background: none;
214
+ --card-height: ${STAGE_HEIGHT};
215
+ }
216
+
217
+ .carousel[data-layout="solo"] .card {
218
+ box-shadow: none;
219
+ }
220
+ }
221
+
222
+ @media (prefers-reduced-motion: reduce) {
223
+ .slide,
224
+ .slide[data-hidden] {
225
+ transition: none;
226
+ }
227
+ }
228
+ `;
229
+
230
+ export interface CarouselOptions {
231
+ /**
232
+ * Called when the highlight moves, before the host renders it, with the
233
+ * keys (see Slide) of the slide that loses it and the one that gets it.
234
+ * The host's updateComplete then resolves once the step is rendered.
235
+ */
236
+ onStep?: (from: number, to: number) => void;
237
+ /**
238
+ * Called when the layout changes (the screen got narrow or wide): every
239
+ * slide is new, with new keys.
240
+ */
241
+ onLayoutChange?: () => void;
242
+ /**
243
+ * While true, the highlight doesn't move, by hand or on its own (for
244
+ * example, while the player shows the highlighted Story).
245
+ */
246
+ locked?: () => boolean;
247
+ /**
248
+ * How long each Story stays highlighted before the next one, in
249
+ * milliseconds (see toSlideDuration). Read whenever the host updates.
250
+ */
251
+ slideDuration?: () => number | undefined;
252
+ /**
253
+ * Whether the person prefers reduced motion: no automatic advance then.
254
+ * Read once each time the host connects.
255
+ */
256
+ reducedMotion?: () => boolean;
257
+ }
258
+
259
+ /** One rendered card. */
260
+ export interface Slide {
261
+ /**
262
+ * Stays with the card while it moves, so state kept per card (such as its
263
+ * video) follows it. Unique among the rendered slides of a layout; the
264
+ * same Story can show in more than one slide.
265
+ */
266
+ key: number;
267
+ /** The Story's index in the list. */
268
+ index: number;
269
+ /** Places from the highlighted card: negative before it, positive after. */
270
+ offset: number;
271
+ /** Has the highlight. */
272
+ active: boolean;
273
+ /** Kept in the DOM out of sight, so it can slide in. */
274
+ hidden: boolean;
275
+ /**
276
+ * Pass to the card's element (renderCard's ref): the carousel then knows
277
+ * where each Story's card is (see visibleCards).
278
+ */
279
+ cardRef: (element?: Element) => void;
280
+ /**
281
+ * Pass to the card's element that takes the keyboard focus (renderCard's
282
+ * openRef; see focusActive).
283
+ */
284
+ focusRef: (element?: Element) => void;
285
+ }
286
+
287
+ /** Renders the card of one Story. */
288
+ export type RenderSlide<T> = (item: T, slide: Slide) => TemplateResult;
289
+
290
+ const wrap = (value: number, count: number) =>
291
+ ((value % count) + count) % count;
292
+
293
+ // A ref callback that keeps `elements` up to date. Each render passes new
294
+ // callbacks: lit calls the last render's with undefined, then the new one
295
+ // with the element, so an element dropped by the rolling layout or the host
296
+ // leaving the page leaves `elements`.
297
+ function tracker(elements: Map<Element, Slide>, slide: Slide) {
298
+ let last: Element | undefined;
299
+ return (element?: Element) => {
300
+ if (last) elements.delete(last);
301
+ last = element;
302
+ if (element) elements.set(element, slide);
303
+ };
304
+ }
305
+
306
+ /**
307
+ * The carousel around the Story cards: which Story has the highlight, the
308
+ * layout, the arrows, swipes and the automatic advance. Call reset() when
309
+ * the Stories change, and render() from the host's render.
310
+ *
311
+ * The highlight moves on its own every slide duration (AUTO_ADVANCE_MS by
312
+ * default, never with zero), except while the pointer is over the carousel,
313
+ * the keyboard focus is in it, it is locked, or the host is off the page.
314
+ * Never for people who prefer reduced motion: the highlight then moves only
315
+ * when they step it.
316
+ */
317
+ export class CarouselController implements ReactiveController {
318
+ /**
319
+ * Steps taken since the Stories loaded, back and forth, not wrapped: the
320
+ * rolling layout keys its slides by it.
321
+ */
322
+ private position = 0;
323
+ /** Stories moved by the last step: longer jumps animate a bit slower. */
324
+ private distance = 1;
325
+ private count = 0;
326
+ private narrow = false;
327
+ private media?: MediaQueryList;
328
+ private reducedMotion = false;
329
+ private connected = false;
330
+ private hovered = false;
331
+ private focused = false;
332
+ private timer?: ReturnType<typeof setInterval>;
333
+ /** The interval the running timer was started with. */
334
+ private timerMs = 0;
335
+ private swipe?: { x: number; moved: boolean };
336
+ /** The rendered cards, as their cardRef reported them. */
337
+ private readonly cards = new Map<Element, Slide>();
338
+ /** The rendered cards' focus targets, as their focusRef reported them. */
339
+ private readonly focusTargets = new Map<Element, Slide>();
340
+
341
+ constructor(
342
+ private readonly host: ReactiveControllerHost,
343
+ private readonly options: CarouselOptions,
344
+ ) {
345
+ host.addController(this);
346
+ }
347
+
348
+ /** Index of the highlighted Story. */
349
+ get active() {
350
+ return this.count ? wrap(this.position, this.count) : 0;
351
+ }
352
+
353
+ get layout(): CarouselLayout {
354
+ if (this.count < 2) return "solo";
355
+ return this.count === 2 && !this.narrow ? "pair" : "rolling";
356
+ }
357
+
358
+ /** Key (see Slide) of the highlighted slide. */
359
+ get activeKey() {
360
+ if (this.layout === "rolling") return this.position;
361
+ return this.active;
362
+ }
363
+
364
+ /**
365
+ * The cards on screen, with their slide: not the hidden ones kept for the
366
+ * slide in.
367
+ */
368
+ *visibleCards(): Generator<readonly [card: Element, slide: Slide]> {
369
+ for (const [card, slide] of this.cards) {
370
+ if (!slide.hidden) yield [card, slide];
371
+ }
372
+ }
373
+
374
+ /** Moves the keyboard focus to the highlighted card, once rendered. */
375
+ focusActive() {
376
+ for (const [target, slide] of this.focusTargets) {
377
+ if (slide.active && target instanceof HTMLElement) {
378
+ target.focus();
379
+ return;
380
+ }
381
+ }
382
+ }
383
+
384
+ hostConnected() {
385
+ this.connected = true;
386
+ this.media = globalThis.matchMedia?.(NARROW_SCREEN.toString());
387
+ this.media?.addEventListener("change", this.onMediaChange);
388
+ this.narrow = this.media?.matches ?? false;
389
+ this.reducedMotion = this.options.reducedMotion?.() ?? false;
390
+ this.syncTimer();
391
+ }
392
+
393
+ hostDisconnected() {
394
+ this.connected = false;
395
+ this.media?.removeEventListener("change", this.onMediaChange);
396
+ this.media = undefined;
397
+ this.endSwipe();
398
+ this.syncTimer();
399
+ }
400
+
401
+ // Whatever the host changed (the player opening, new Stories, the slide
402
+ // duration) may start, stop or restart the automatic advance.
403
+ hostUpdated() {
404
+ this.syncTimer();
405
+ }
406
+
407
+ /** For a new list of Stories: the first one gets the highlight. */
408
+ reset(count: number) {
409
+ this.count = count;
410
+ this.position = 0;
411
+ this.distance = 1;
412
+ // The carousel may leave the page now (the element renders nothing while
413
+ // it loads). Removing the element with the pointer or focus doesn't fire
414
+ // pointerleave or focusout, and the new one would never advance.
415
+ this.hovered = false;
416
+ this.focused = false;
417
+ this.restartTimer();
418
+ }
419
+
420
+ /**
421
+ * Moves the highlight by `delta` Stories, wrapping around the ends. While
422
+ * locked, only with `evenIfLocked` (for example, the player stepping to
423
+ * the next Story it shows).
424
+ */
425
+ step(delta: number, { evenIfLocked = false } = {}) {
426
+ if (this.count < 2 || delta === 0) return;
427
+ if (this.options.locked?.() && !evenIfLocked) return;
428
+
429
+ const from = this.activeKey;
430
+ this.position += delta;
431
+ this.distance = Math.abs(delta);
432
+
433
+ // The update is requested first, so onStep can wait for the render that
434
+ // shows the step (the host's updateComplete).
435
+ this.host.requestUpdate();
436
+ this.options.onStep?.(from, this.activeKey);
437
+ // A step by hand gives the new Story its full time.
438
+ this.restartTimer();
439
+ }
440
+
441
+ private get slideDuration() {
442
+ return toSlideDuration(this.options.slideDuration?.());
443
+ }
444
+
445
+ private get shouldAdvance() {
446
+ return (
447
+ this.slideDuration > 0 &&
448
+ !this.reducedMotion &&
449
+ this.connected &&
450
+ this.count > 1 &&
451
+ !this.hovered &&
452
+ !this.focused &&
453
+ !this.options.locked?.()
454
+ );
455
+ }
456
+
457
+ private syncTimer() {
458
+ const ms = this.slideDuration;
459
+ // A new duration starts over, with the full new time.
460
+ if (this.timer && this.timerMs !== ms) this.stopTimer();
461
+
462
+ if (this.shouldAdvance && !this.timer) {
463
+ this.timerMs = ms;
464
+ this.timer = setInterval(() => this.step(1), ms);
465
+ } else if (!this.shouldAdvance && this.timer) {
466
+ this.stopTimer();
467
+ }
468
+ }
469
+
470
+ private stopTimer() {
471
+ clearInterval(this.timer);
472
+ this.timer = undefined;
473
+ this.timerMs = 0;
474
+ }
475
+
476
+ private restartTimer() {
477
+ this.stopTimer();
478
+ this.syncTimer();
479
+ }
480
+
481
+ private readonly onMediaChange = (event: MediaQueryListEvent) => {
482
+ const layout = this.layout;
483
+ this.narrow = event.matches;
484
+ if (this.layout === layout) return;
485
+
486
+ this.options.onLayoutChange?.();
487
+ this.host.requestUpdate();
488
+ };
489
+
490
+ private readonly onPointerEnter = () => {
491
+ this.hovered = true;
492
+ this.syncTimer();
493
+ };
494
+
495
+ private readonly onPointerLeave = () => {
496
+ this.hovered = false;
497
+ this.syncTimer();
498
+ };
499
+
500
+ // Only keyboard focus stops the advance: a click also focuses the button
501
+ // it hits, and the advance would then stay stopped after the pointer left.
502
+ private readonly onFocusIn = (event: FocusEvent) => {
503
+ this.focused = (event.target as Element).matches(":focus-visible");
504
+ this.syncTimer();
505
+ };
506
+
507
+ private readonly onFocusOut = (event: FocusEvent) => {
508
+ const carousel = event.currentTarget as Element;
509
+ const next = event.relatedTarget as Node | null;
510
+ if (!next || !carousel.contains(next)) this.focused = false;
511
+ this.syncTimer();
512
+ };
513
+
514
+ // The release is listened for on the window: a mouse drag can end over an
515
+ // arrow or off the carousel, where the track never gets the pointerup.
516
+ private readonly onPointerDown = (event: PointerEvent) => {
517
+ this.endSwipe();
518
+ this.swipe = { x: event.clientX, moved: false };
519
+ globalThis.addEventListener("pointerup", this.onPointerUp);
520
+ globalThis.addEventListener("pointercancel", this.onPointerCancel);
521
+ };
522
+
523
+ private readonly onPointerUp = (event: PointerEvent) => {
524
+ const { swipe } = this;
525
+ this.removeSwipeListeners();
526
+ if (!swipe) return;
527
+
528
+ const distance = event.clientX - swipe.x;
529
+ if (Math.abs(distance) > SWIPE_DISTANCE) {
530
+ swipe.moved = true;
531
+ this.step(distance < 0 ? 1 : -1);
532
+ }
533
+ };
534
+
535
+ private readonly onPointerCancel = () => this.endSwipe();
536
+
537
+ private endSwipe() {
538
+ this.removeSwipeListeners();
539
+ this.swipe = undefined;
540
+ }
541
+
542
+ private removeSwipeListeners() {
543
+ globalThis.removeEventListener("pointerup", this.onPointerUp);
544
+ globalThis.removeEventListener("pointercancel", this.onPointerCancel);
545
+ }
546
+
547
+ // A swipe ends with a click on the card under the pointer: it must not
548
+ // open the player or select that card.
549
+ private readonly onClickCapture = {
550
+ handleEvent: (event: Event) => {
551
+ if (this.swipe?.moved) {
552
+ event.stopPropagation();
553
+ event.preventDefault();
554
+ }
555
+ this.swipe = undefined;
556
+ },
557
+ capture: true,
558
+ };
559
+
560
+ private slide(fields: Omit<Slide, "cardRef" | "focusRef">): Slide {
561
+ const slide: Slide = {
562
+ ...fields,
563
+ cardRef: (element) => track(element),
564
+ focusRef: (element) => trackFocus(element),
565
+ };
566
+ const track = tracker(this.cards, slide);
567
+ const trackFocus = tracker(this.focusTargets, slide);
568
+ return slide;
569
+ }
570
+
571
+ /** Pair: both Stories, each keyed by its index. */
572
+ private pairSlides(): Slide[] {
573
+ const { active } = this;
574
+ return [0, 1].map((index) =>
575
+ this.slide({
576
+ key: index,
577
+ index,
578
+ offset: index - active,
579
+ active: index === active,
580
+ hidden: false,
581
+ }),
582
+ );
583
+ }
584
+
585
+ /**
586
+ * Rolling: the slides around the highlighted one, keyed by their position.
587
+ * Up to VISIBLE_SIDE show on each side, fewer when there aren't enough
588
+ * Stories to fill both sides without repeating: half on each side, the
589
+ * extra one after it. With four, the Story opposite the highlighted one
590
+ * shows at both ends; with two (narrow screens), the other one shows on
591
+ * both sides.
592
+ */
593
+ private rollingSlides(): Slide[] {
594
+ const { count } = this;
595
+ const even = count === 2 || count === 4;
596
+ const before = even ? count / 2 : Math.floor((count - 1) / 2);
597
+ const after = even ? count / 2 : count - 1 - before;
598
+
599
+ const slides: Slide[] = [];
600
+ for (let offset = -RENDERED_SIDE; offset <= RENDERED_SIDE; offset += 1) {
601
+ slides.push(
602
+ this.slide({
603
+ key: this.position + offset,
604
+ index: wrap(this.position + offset, count),
605
+ offset,
606
+ active: offset === 0,
607
+ hidden:
608
+ Math.abs(offset) > VISIBLE_SIDE ||
609
+ offset < -before ||
610
+ offset > after,
611
+ }),
612
+ );
613
+ }
614
+ return slides;
615
+ }
616
+
617
+ private renderSlides<T>(items: readonly T[], renderSlide: RenderSlide<T>) {
618
+ const { layout } = this;
619
+ const slides = layout === "pair" ? this.pairSlides() : this.rollingSlides();
620
+
621
+ // The layout is part of the key: the same key in another layout is a new
622
+ // card, with a new video and controller (see onLayoutChange).
623
+ return repeat(
624
+ slides,
625
+ (slide) => `${layout}:${slide.key}`,
626
+ (slide) => {
627
+ const { index } = slide;
628
+ return html`
629
+ <div
630
+ class="slide"
631
+ data-index=${index}
632
+ ?data-active=${slide.active}
633
+ ?data-hidden=${slide.hidden}
634
+ ?inert=${slide.hidden}
635
+ style=${styleMap({ "--place": String(slide.offset) })}
636
+ >
637
+ ${renderSlide(items[index], slide)}
638
+ </div>
639
+ `;
640
+ },
641
+ );
642
+ }
643
+
644
+ /**
645
+ * One item: the card centered over the background. More: the cards in the
646
+ * pair or rolling layout, with the arrows.
647
+ */
648
+ render<T>(
649
+ items: readonly T[],
650
+ renderSlide: RenderSlide<T>,
651
+ labels: StoryLabels,
652
+ ) {
653
+ if (this.layout === "solo") {
654
+ return html`
655
+ <div class="carousel" data-layout="solo">
656
+ ${renderSlide(
657
+ items[0],
658
+ this.slide({
659
+ key: 0,
660
+ index: 0,
661
+ offset: 0,
662
+ active: true,
663
+ hidden: false,
664
+ }),
665
+ )}
666
+ </div>
667
+ `;
668
+ }
669
+
670
+ const locked = this.options.locked?.() ?? false;
671
+
672
+ return html`
673
+ <div
674
+ class="carousel"
675
+ data-layout=${this.layout}
676
+ role="region"
677
+ aria-roledescription=${labels.carouselRole}
678
+ aria-label=${labels.carousel}
679
+ @pointerenter=${this.onPointerEnter}
680
+ @pointerleave=${this.onPointerLeave}
681
+ @focusin=${this.onFocusIn}
682
+ @focusout=${this.onFocusOut}
683
+ >
684
+ <div
685
+ class="track"
686
+ style=${styleMap({
687
+ "--slide-duration": this.distance > 1 ? "0.52s" : "0.4s",
688
+ })}
689
+ @pointerdown=${this.onPointerDown}
690
+ @click=${this.onClickCapture}
691
+ >
692
+ ${this.renderSlides(items, renderSlide)}
693
+ </div>
694
+ <button
695
+ type="button"
696
+ class="arrow arrow-previous"
697
+ aria-label=${labels.previous}
698
+ ?disabled=${locked}
699
+ @click=${() => this.step(-1)}
700
+ >
701
+ ${icon("previous")}
702
+ </button>
703
+ <button
704
+ type="button"
705
+ class="arrow arrow-next"
706
+ aria-label=${labels.next}
707
+ ?disabled=${locked}
708
+ @click=${() => this.step(1)}
709
+ >
710
+ ${icon("next")}
711
+ </button>
712
+ </div>
713
+ `;
714
+ }
715
+ }