@vtex/ads-stories 0.4.0 → 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 (51) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +260 -28
  3. package/dist/cdn/vtex-ads-stories.js +1073 -20
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +4392 -315
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +198 -12
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +46 -5
  10. package/dist/esm/index.d.ts +198 -12
  11. package/dist/esm/index.js +2819 -291
  12. package/dist/esm/index.js.map +1 -1
  13. package/dist/esm/react.d.ts +46 -5
  14. package/package.json +21 -4
  15. package/src/cdn.ts +7 -3
  16. package/src/components/card/card.ts +101 -111
  17. package/src/components/card/index.ts +1 -1
  18. package/src/components/carousel/carousel.ts +670 -0
  19. package/src/components/carousel/index.ts +15 -0
  20. package/src/components/events/events-controller.ts +212 -0
  21. package/src/components/events/index.ts +6 -0
  22. package/src/components/icons/assets/caret-left-bold.svg +1 -0
  23. package/src/components/icons/assets/caret-right-bold.svg +1 -0
  24. package/src/components/icons/assets/caret-up-bold.svg +1 -0
  25. package/src/components/icons/index.ts +30 -9
  26. package/src/components/media/index.ts +3 -0
  27. package/src/components/media/media.ts +70 -0
  28. package/src/components/media/video-controller.ts +125 -0
  29. package/src/components/player/index.ts +6 -2
  30. package/src/components/player/player.ts +946 -134
  31. package/src/components/product/cta.ts +56 -0
  32. package/src/components/product/index.ts +20 -0
  33. package/src/components/product/price.ts +86 -0
  34. package/src/components/product/product.styles.ts +369 -0
  35. package/src/components/product/product.ts +235 -0
  36. package/src/index.ts +9 -1
  37. package/src/locales/en.ts +29 -0
  38. package/src/locales/es.ts +30 -0
  39. package/src/locales/index.ts +36 -0
  40. package/src/locales/pt.ts +29 -0
  41. package/src/locales/types.ts +24 -0
  42. package/src/react.ts +49 -7
  43. package/src/story/index.ts +5 -1
  44. package/src/story/story.ts +528 -93
  45. package/src/tag-name.ts +1 -0
  46. package/src/types.ts +8 -12
  47. package/src/utils/fetch-story.ts +113 -0
  48. package/src/utils/http-url.ts +12 -0
  49. package/src/utils/hydrate-products.ts +88 -0
  50. package/src/utils/send-event.ts +71 -0
  51. package/src/utils/with-timeout.ts +43 -0
package/dist/esm/index.js CHANGED
@@ -1,6 +1,27 @@
1
+ // src/story/story.ts
2
+ import { css as css5, html as html7, LitElement, nothing as nothing5 } from "lit";
3
+
4
+ // src/components/card/card.ts
5
+ import { css as css2, html as html4, nothing as nothing3 } from "lit";
6
+ import { ref as ref2 } from "lit/directives/ref.js";
7
+
8
+ // src/components/icons/index.ts
9
+ import {
10
+ unsafeHTML
11
+ } from "lit/directives/unsafe-html.js";
12
+
13
+ // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-left-bold.svg
14
+ var caret_left_bold_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M168.49,199.51a12,12,0,0,1-17,17l-80-80a12,12,0,0,1,0-17l80-80a12,12,0,0,1,17,17L97,128Z"/></svg>\n';
15
+
16
+ // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-right-bold.svg
17
+ var caret_right_bold_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z"/></svg>\n';
18
+
1
19
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/close.svg
2
20
  var close_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M205.66,194.34a8,8,0,0,1-11.32,11.32L128,139.31,61.66,205.66a8,8,0,0,1-11.32-11.32L116.69,128,50.34,61.66A8,8,0,0,1,61.66,50.34L128,116.69l66.34-66.35a8,8,0,0,1,11.32,11.32L139.31,128Z"/></svg>\n';
3
21
 
22
+ // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-up-bold.svg
23
+ var caret_up_bold_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z"/></svg>';
24
+
4
25
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/collapse.svg
5
26
  var collapse_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M152,96V48a8,8,0,0,1,16,0V88h40a8,8,0,0,1,0,16H160A8,8,0,0,1,152,96ZM96,152H48a8,8,0,0,0,0,16H88v40a8,8,0,0,0,16,0V160A8,8,0,0,0,96,152Zm112,0H160a8,8,0,0,0-8,8v48a8,8,0,0,0,16,0V168h40a8,8,0,0,0,0-16ZM96,40a8,8,0,0,0-8,8V88H48a8,8,0,0,0,0,16H96a8,8,0,0,0,8-8V48A8,8,0,0,0,96,40Z"/></svg>\n';
6
27
 
@@ -21,31 +42,761 @@ var speaker_high_fill_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox
21
42
 
22
43
  // src/components/icons/index.ts
23
44
  var icons = {
45
+ caretUp: caret_up_bold_default,
24
46
  close: close_default,
25
47
  collapse: collapse_default,
26
48
  expand: expand_default,
49
+ next: caret_right_bold_default,
27
50
  pause: pause_fill_default,
28
51
  play: play_fill_default,
52
+ previous: caret_left_bold_default,
29
53
  soundOff: speaker_x_fill_default,
30
54
  soundOn: speaker_high_fill_default
31
55
  };
32
- function createIcon(name) {
33
- const template = document.createElement("template");
34
- template.innerHTML = icons[name];
35
- const svg = template.content.firstElementChild;
36
- svg.classList.add("icon");
37
- svg.setAttribute("aria-hidden", "true");
38
- svg.setAttribute("focusable", "false");
39
- return svg;
56
+ var markup = Object.fromEntries(
57
+ Object.entries(icons).map(([name, svg]) => [
58
+ name,
59
+ svg.replace(
60
+ "<svg",
61
+ '<svg class="icon" aria-hidden="true" focusable="false"'
62
+ )
63
+ ])
64
+ );
65
+ function icon(name) {
66
+ return unsafeHTML(markup[name]);
67
+ }
68
+
69
+ // src/components/media/media.ts
70
+ import { html, nothing } from "lit";
71
+ import { ref } from "lit/directives/ref.js";
72
+
73
+ // src/utils/http-url.ts
74
+ function httpUrl(value) {
75
+ if (!value) return null;
76
+ try {
77
+ const { protocol } = new URL(value);
78
+ return protocol === "https:" || protocol === "http:" ? value : null;
79
+ } catch (e) {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ // src/components/media/media.ts
85
+ function prefersReducedMotion() {
86
+ var _a, _b;
87
+ return (_b = (_a = globalThis.matchMedia) == null ? void 0 : _a.call(globalThis, "(prefers-reduced-motion: reduce)").matches) != null ? _b : false;
88
+ }
89
+ function hasVideo(story, video) {
90
+ return !video.failed && httpUrl(story.media_url) !== null;
91
+ }
92
+ function renderMedia(story, video, { withVideo = true, loop = true, onEnded } = {}) {
93
+ const posterUrl = httpUrl(story.poster_url);
94
+ const mediaUrl = withVideo ? httpUrl(story.media_url) : null;
95
+ return html`
96
+ ${posterUrl ? html`<img class="poster" alt="" src=${posterUrl} />` : nothing}
97
+ ${mediaUrl && !video.failed ? html`
98
+ <video
99
+ class="video"
100
+ muted
101
+ playsinline
102
+ ?loop=${loop}
103
+ preload="metadata"
104
+ .muted=${true}
105
+ ?autoplay=${!prefersReducedMotion()}
106
+ poster=${posterUrl != null ? posterUrl : nothing}
107
+ src=${mediaUrl}
108
+ ${ref(video.ref)}
109
+ @play=${video.sync}
110
+ @pause=${video.sync}
111
+ @volumechange=${video.sync}
112
+ @error=${video.fail}
113
+ @ended=${onEnded}
114
+ ></video>
115
+ ` : nothing}
116
+ `;
117
+ }
118
+
119
+ // src/components/media/video-controller.ts
120
+ import { createRef } from "lit/directives/ref.js";
121
+ function playVideo(video) {
122
+ var _a;
123
+ (_a = video.play()) == null ? void 0 : _a.catch(() => void 0);
124
+ }
125
+ var VideoController = class {
126
+ constructor(host) {
127
+ this.host = host;
128
+ /** Bound to the <video> by renderMedia. */
129
+ this.ref = createRef();
130
+ this.paused = true;
131
+ // The video always starts muted: that is what browsers allow to autoplay.
132
+ this.muted = true;
133
+ /** The video could not load: only the cover is shown. */
134
+ this.failed = false;
135
+ /** Listener for the video's play, pause and volumechange events. */
136
+ this.sync = () => {
137
+ const video = this.ref.value;
138
+ if (!video) return;
139
+ this.paused = video.paused;
140
+ this.muted = video.muted;
141
+ this.host.requestUpdate();
142
+ };
143
+ /** Listener for the video's error event. */
144
+ this.fail = () => {
145
+ this.failed = true;
146
+ this.host.requestUpdate();
147
+ };
148
+ }
149
+ /** The rendered <video> is on the page and playing. */
150
+ get playing() {
151
+ const video = this.ref.value;
152
+ return !!video && video.isConnected && !video.paused;
153
+ }
154
+ /** For a new <video>, such as each time the player opens. */
155
+ reset() {
156
+ this.paused = true;
157
+ this.muted = true;
158
+ this.failed = false;
159
+ }
160
+ play() {
161
+ const video = this.ref.value;
162
+ if (video) playVideo(video);
163
+ }
164
+ pause() {
165
+ var _a;
166
+ (_a = this.ref.value) == null ? void 0 : _a.pause();
167
+ }
168
+ /** Plays again if the video plays on its own (see renderMedia). */
169
+ resume() {
170
+ const video = this.ref.value;
171
+ if (video == null ? void 0 : video.autoplay) playVideo(video);
172
+ }
173
+ togglePlayback() {
174
+ const video = this.ref.value;
175
+ if (!video) return;
176
+ if (video.paused) playVideo(video);
177
+ else video.pause();
178
+ }
179
+ mute() {
180
+ const video = this.ref.value;
181
+ if (video) video.muted = true;
182
+ }
183
+ /**
184
+ * Plays from the start, with the sound on if `withSound`. A new src starts
185
+ * there anyway; the same src (two Stories with one video) would otherwise
186
+ * go on where it was.
187
+ */
188
+ restart({ withSound = false } = {}) {
189
+ const video = this.ref.value;
190
+ if (!video) return;
191
+ video.currentTime = 0;
192
+ if (withSound) this.playWithSound();
193
+ else playVideo(video);
194
+ }
195
+ /**
196
+ * Plays with the sound on. A browser that blocks playing with sound (for
197
+ * example, without a recent tap) gets it muted instead: the video keeps
198
+ * playing, and the sound button offers to turn it on. Not if the video was
199
+ * replaced or removed meanwhile (the request then fails for that reason):
200
+ * it would play out of sight.
201
+ */
202
+ playWithSound() {
203
+ var _a;
204
+ const video = this.ref.value;
205
+ if (!video) return;
206
+ video.muted = false;
207
+ (_a = video.play()) == null ? void 0 : _a.catch((error) => {
208
+ const blocked = error instanceof DOMException && error.name === "NotAllowedError";
209
+ if (!blocked || this.ref.value !== video || !video.isConnected) return;
210
+ video.muted = true;
211
+ playVideo(video);
212
+ });
213
+ }
214
+ toggleMuted() {
215
+ const video = this.ref.value;
216
+ if (video) video.muted = !video.muted;
217
+ }
218
+ };
219
+
220
+ // src/components/product/product.ts
221
+ import { html as html2, nothing as nothing2 } from "lit";
222
+
223
+ // src/components/product/price.ts
224
+ var DEFAULT_LOCALE = "pt-BR";
225
+ var DEFAULT_CURRENCY = "BRL";
226
+ function toAmount(value) {
227
+ let amount = Number.NaN;
228
+ if (typeof value === "number") amount = value;
229
+ else if (typeof value === "string" && value.trim() !== "") {
230
+ amount = Number(value);
231
+ }
232
+ return Number.isFinite(amount) && amount > 0 ? amount : void 0;
233
+ }
234
+ function readProductPrice(metadata) {
235
+ const regular = toAmount(metadata == null ? void 0 : metadata.price);
236
+ const promotional = toAmount(metadata == null ? void 0 : metadata.promotional_price);
237
+ if (promotional !== void 0 && (regular === void 0 || promotional < regular)) {
238
+ return regular === void 0 ? { price: promotional } : { price: promotional, listPrice: regular };
239
+ }
240
+ return regular === void 0 ? void 0 : { price: regular };
241
+ }
242
+ function isLocale(locale) {
243
+ try {
244
+ return Intl.NumberFormat.supportedLocalesOf(locale).length > 0;
245
+ } catch (e) {
246
+ return false;
247
+ }
248
+ }
249
+ var intl = Intl;
250
+ function isCurrency(currency) {
251
+ var _a;
252
+ if (!/^[a-z]{3}$/i.test(currency)) return false;
253
+ const known = (_a = intl.supportedValuesOf) == null ? void 0 : _a.call(intl, "currency");
254
+ return known ? known.includes(currency.toUpperCase()) : true;
255
+ }
256
+ function priceFormatter(locale, currency) {
257
+ const format = new Intl.NumberFormat(
258
+ locale && isLocale(locale) ? locale : DEFAULT_LOCALE,
259
+ {
260
+ style: "currency",
261
+ currency: currency && isCurrency(currency) ? currency : DEFAULT_CURRENCY
262
+ }
263
+ );
264
+ return (amount) => format.format(amount);
265
+ }
266
+
267
+ // src/components/product/product.ts
268
+ function toCardProduct(story, format, labels, fetched) {
269
+ var _a, _b, _c, _d;
270
+ const product = story.product;
271
+ const name = (_a = product == null ? void 0 : product.product_name) == null ? void 0 : _a.trim();
272
+ if (!product || !name) return void 0;
273
+ const base = {
274
+ name,
275
+ imageUrl: (_b = httpUrl(product.image_url)) != null ? _b : void 0,
276
+ url: (_c = httpUrl(story.destination_url)) != null ? _c : void 0
277
+ };
278
+ if (fetched === "loading") {
279
+ return { ...base, label: labels.product(name), isLoading: true };
280
+ }
281
+ if ((fetched == null ? void 0 : fetched.available) === false) {
282
+ return {
283
+ ...base,
284
+ label: labels.product(name, labels.soldOut),
285
+ soldOut: labels.soldOut
286
+ };
287
+ }
288
+ const amounts = (_d = fetched == null ? void 0 : fetched.price) != null ? _d : readProductPrice(product.product_metadata);
289
+ const price = amounts && format(amounts.price);
290
+ const listPrice = (amounts == null ? void 0 : amounts.listPrice) === void 0 ? void 0 : format(amounts.listPrice);
291
+ return {
292
+ ...base,
293
+ price,
294
+ listPrice,
295
+ label: labels.product(name, price, listPrice)
296
+ };
297
+ }
298
+ var priceSkeleton = html2`
299
+ <span
300
+ class="product-price product-loading product-price-loading"
301
+ aria-hidden="true"
302
+ ></span>
303
+ `;
304
+ var addToCartSkeleton = html2`
305
+ <span
306
+ class="product-loading product-add-to-cart-loading"
307
+ aria-hidden="true"
308
+ ></span>
309
+ `;
310
+ function renderPrice({ isLoading, soldOut, price, listPrice }) {
311
+ if (isLoading) return priceSkeleton;
312
+ if (soldOut) {
313
+ return html2`<span class="product-price product-sold-out">${soldOut}</span>`;
314
+ }
315
+ if (!price) return nothing2;
316
+ return html2`
317
+ <span class="product-price">
318
+ <span>${price}</span>
319
+ ${listPrice ? html2`<s class="product-list-price">${listPrice}</s>` : nothing2}
320
+ </span>
321
+ `;
322
+ }
323
+ function renderSummary(product) {
324
+ return html2`
325
+ ${product.imageUrl ? html2`<img class="product-image" alt="" src=${product.imageUrl} />` : nothing2}
326
+ <span class="product-info">
327
+ <span class="product-name">${product.name}</span>
328
+ ${renderPrice(product)}
329
+ </span>
330
+ `;
331
+ }
332
+ function renderProduct(product, onSelect) {
333
+ return html2`
334
+ <button
335
+ type="button"
336
+ class="card-product"
337
+ aria-label=${product.label}
338
+ @click=${onSelect}
339
+ >
340
+ ${renderSummary(product)}
341
+ </button>
342
+ `;
343
+ }
344
+ function renderAddToCart({ isLoading, soldOut }, { labels }) {
345
+ if (isLoading) return addToCartSkeleton;
346
+ if (soldOut) {
347
+ return html2`
348
+ <button type="button" class="product-action product-unavailable" disabled>
349
+ ${labels.unavailable}
350
+ </button>
351
+ `;
352
+ }
353
+ return html2`
354
+ <button type="button" class="product-action product-add-to-cart">
355
+ ${labels.addToCart}
356
+ </button>
357
+ `;
358
+ }
359
+ function renderExpandableProduct(product, options) {
360
+ const { open } = options;
361
+ return html2`
362
+ <div class="card-product product-expandable" ?data-open=${open}>
363
+ <button
364
+ type="button"
365
+ class="product-summary"
366
+ aria-label=${product.label}
367
+ aria-expanded=${open ? "true" : "false"}
368
+ aria-controls=${options.panelId}
369
+ @click=${options.onToggle}
370
+ >
371
+ ${renderSummary(product)}
372
+ <span class="product-toggle">${icon("caretUp")}</span>
373
+ </button>
374
+ <div id=${options.panelId} class="product-panel" ?inert=${!open}>
375
+ <div class="product-actions">
376
+ ${renderAddToCart(product, options)}
377
+ ${product.url ? html2`
378
+ <a
379
+ class="product-action product-view"
380
+ href=${product.url}
381
+ target="_blank"
382
+ rel="noopener noreferrer"
383
+ >
384
+ ${options.labels.viewProduct}
385
+ </a>
386
+ ` : nothing2}
387
+ </div>
388
+ </div>
389
+ </div>
390
+ `;
391
+ }
392
+
393
+ // src/components/product/cta.ts
394
+ import { html as html3 } from "lit";
395
+ function toCardCta(story) {
396
+ var _a;
397
+ if (story.product) return void 0;
398
+ const label = (_a = story.call_to_action) == null ? void 0 : _a.trim();
399
+ const url = httpUrl(story.destination_url);
400
+ return label && url ? { label, url } : void 0;
401
+ }
402
+ function renderCta(cta, onSelect) {
403
+ const onClick = onSelect ? (event) => {
404
+ event.preventDefault();
405
+ onSelect();
406
+ } : void 0;
407
+ return html3`
408
+ <a
409
+ class="card-cta"
410
+ href=${cta.url}
411
+ target="_blank"
412
+ rel="noopener noreferrer"
413
+ @click=${onClick}
414
+ >
415
+ <span class="cta-label">${cta.label}</span>
416
+ ${icon("next")}
417
+ </a>
418
+ `;
40
419
  }
41
420
 
421
+ // src/components/product/product.styles.ts
422
+ import { css } from "lit";
423
+ var productStyles = css`
424
+ /* A glass pill at the bottom of the card, above its button: the product or
425
+ the call to action. */
426
+ .card-product,
427
+ .card-cta {
428
+ position: absolute;
429
+ right: 12px;
430
+ bottom: 12px;
431
+ left: 12px;
432
+ z-index: 1;
433
+ display: flex;
434
+ gap: 8px;
435
+ align-items: center;
436
+ box-sizing: border-box;
437
+ padding: 8px;
438
+ border: 0;
439
+ border-radius: 16px;
440
+ background: rgba(255, 255, 255, 0.15);
441
+ backdrop-filter: blur(5px);
442
+ color: #fff;
443
+ font: inherit;
444
+ text-align: left;
445
+ isolation: isolate;
446
+ transition: transform 0.2s ease;
447
+ }
448
+
449
+ /* The glass's tint and inner light, darker on hover. */
450
+ .card-product::before,
451
+ .card-cta::before {
452
+ position: absolute;
453
+ inset: 0;
454
+ z-index: -1;
455
+ border-radius: inherit;
456
+ background: rgba(0, 0, 0, 0.15);
457
+ box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);
458
+ content: "";
459
+ transition: background-color 0.2s ease;
460
+ }
461
+
462
+ button.card-product,
463
+ .card-cta {
464
+ cursor: pointer;
465
+ }
466
+
467
+ .card-product:focus-visible,
468
+ .card-cta:focus-visible {
469
+ outline: 2px solid #fff;
470
+ outline-offset: 2px;
471
+ }
472
+
473
+ @media (hover: hover) and (pointer: fine) {
474
+ .card-product:hover,
475
+ .card-cta:hover {
476
+ transform: translateY(-2px);
477
+ }
478
+
479
+ .card-product:hover::before,
480
+ .card-cta:hover::before {
481
+ background: rgba(0, 0, 0, 0.32);
482
+ }
483
+ }
484
+
485
+ /* A Story with a link: the pill is the call to action, its text centered
486
+ with a caret after it. */
487
+ .card-cta {
488
+ justify-content: center;
489
+ gap: 6px;
490
+ height: 48px;
491
+ padding: 0 16px;
492
+ font-size: 14px;
493
+ font-weight: 700;
494
+ line-height: 1;
495
+ text-decoration: none;
496
+ }
497
+
498
+ .cta-label {
499
+ min-width: 0;
500
+ overflow: hidden;
501
+ text-overflow: ellipsis;
502
+ white-space: nowrap;
503
+ }
504
+
505
+ .card-cta .icon {
506
+ flex: none;
507
+ width: 14px;
508
+ height: 14px;
509
+ }
510
+
511
+ /* In the player: the pill is a toggle, with the actions panel below. */
512
+ .product-expandable {
513
+ display: block;
514
+ padding: 0;
515
+ transition:
516
+ background-color 0.3s ease,
517
+ color 0.3s ease,
518
+ box-shadow 0.3s ease,
519
+ transform 0.2s ease;
520
+ }
521
+
522
+ .product-expandable::before {
523
+ transition:
524
+ opacity 0.3s ease,
525
+ background-color 0.2s ease;
526
+ }
527
+
528
+ .product-summary {
529
+ display: flex;
530
+ gap: 8px;
531
+ align-items: center;
532
+ box-sizing: border-box;
533
+ width: 100%;
534
+ padding: 8px;
535
+ border: 0;
536
+ border-radius: inherit;
537
+ background: transparent;
538
+ color: inherit;
539
+ font: inherit;
540
+ text-align: left;
541
+ cursor: pointer;
542
+ transition: padding 0.3s ease;
543
+ }
544
+
545
+ .product-summary:focus-visible {
546
+ outline: 2px solid currentColor;
547
+ outline-offset: 2px;
548
+ }
549
+
550
+ /* The caret points up while closed and down while open. */
551
+ .product-toggle {
552
+ display: grid;
553
+ flex: none;
554
+ margin-right: 4px;
555
+ opacity: 0.7;
556
+ transition:
557
+ transform 0.3s ease,
558
+ opacity 0.2s ease;
559
+ }
560
+
561
+ .product-toggle .icon {
562
+ width: 14px;
563
+ height: 14px;
564
+ }
565
+
566
+ .product-summary:hover .product-toggle {
567
+ opacity: 1;
568
+ }
569
+
570
+ /* Closed: 0 rows tall, so it grows smoothly when it opens. */
571
+ .product-panel {
572
+ display: grid;
573
+ grid-template-rows: 0fr;
574
+ transition: grid-template-rows 0.3s ease;
575
+ }
576
+
577
+ .product-actions {
578
+ display: grid;
579
+ gap: 8px;
580
+ min-height: 0;
581
+ overflow: hidden;
582
+ padding: 0 12px;
583
+ opacity: 0;
584
+ transition:
585
+ padding 0.3s ease,
586
+ opacity 0.2s ease;
587
+ }
588
+
589
+ .product-action {
590
+ display: flex;
591
+ align-items: center;
592
+ justify-content: center;
593
+ box-sizing: border-box;
594
+ height: 48px;
595
+ padding: 0 16px;
596
+ border: 1px solid var(--vtex-ads-story-color-accent, #1b75a8);
597
+ border-radius: 50px;
598
+ font: inherit;
599
+ font-size: 14px;
600
+ font-weight: 700;
601
+ text-decoration: none;
602
+ cursor: pointer;
603
+ transition: background-color 0.2s ease;
604
+ }
605
+
606
+ .product-action:focus-visible {
607
+ outline: 2px solid var(--vtex-ads-story-color-accent, #1b75a8);
608
+ outline-offset: 2px;
609
+ }
610
+
611
+ .product-add-to-cart {
612
+ background: var(--vtex-ads-story-color-accent, #1b75a8);
613
+ color: var(--vtex-ads-story-color-accent-contrast, #fff);
614
+ }
615
+
616
+ .product-add-to-cart:hover {
617
+ background: color-mix(
618
+ in srgb,
619
+ var(--vtex-ads-story-color-accent, #1b75a8) 85%,
620
+ #000
621
+ );
622
+ }
623
+
624
+ /* Sold out: add to cart, disabled and grayed. */
625
+ .product-unavailable {
626
+ border-color: transparent;
627
+ background: rgba(0, 0, 0, 0.06);
628
+ color: var(--vtex-ads-story-color-muted, #6b6b6b);
629
+ cursor: not-allowed;
630
+ }
631
+
632
+ .product-view {
633
+ background: var(--vtex-ads-story-color-surface, #fff);
634
+ color: var(--vtex-ads-story-color-accent, #1b75a8);
635
+ }
636
+
637
+ /* A light tint of the accent. */
638
+ .product-view:hover {
639
+ background: color-mix(
640
+ in srgb,
641
+ var(--vtex-ads-story-color-accent, #1b75a8) 8%,
642
+ var(--vtex-ads-story-color-surface, #fff)
643
+ );
644
+ }
645
+
646
+ /* Open: a solid card (white by default), without the glass. */
647
+ .product-expandable[data-open] {
648
+ background: var(--vtex-ads-story-color-surface, #fff);
649
+ color: var(--vtex-ads-story-color-text, #242424);
650
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
651
+ }
652
+
653
+ .product-expandable[data-open]::before {
654
+ opacity: 0;
655
+ }
656
+
657
+ .product-expandable[data-open] .product-price {
658
+ color: inherit;
659
+ }
660
+
661
+ .product-expandable[data-open] .product-list-price {
662
+ color: var(--vtex-ads-story-color-muted, #6b6b6b);
663
+ opacity: 1;
664
+ }
665
+
666
+ .product-expandable[data-open] .product-summary {
667
+ padding: 12px;
668
+ }
669
+
670
+ .product-expandable[data-open] .product-toggle {
671
+ transform: rotate(180deg);
672
+ }
673
+
674
+ .product-expandable[data-open] .product-panel {
675
+ grid-template-rows: 1fr;
676
+ }
677
+
678
+ .product-expandable[data-open] .product-actions {
679
+ padding: 0 12px 12px;
680
+ opacity: 1;
681
+ transition:
682
+ padding 0.3s ease,
683
+ opacity 0.25s ease 0.1s;
684
+ }
685
+
686
+ /* Open, it stays in place on hover. */
687
+ @media (hover: hover) and (pointer: fine) {
688
+ .product-expandable[data-open]:hover {
689
+ transform: none;
690
+ }
691
+ }
692
+
693
+ @media (prefers-reduced-motion: reduce) {
694
+ .card-product,
695
+ .card-product:hover,
696
+ .card-cta,
697
+ .card-cta:hover {
698
+ transform: none;
699
+ transition: none;
700
+ }
701
+
702
+ .card-product::before,
703
+ .card-cta::before,
704
+ .product-summary,
705
+ .product-toggle,
706
+ .product-panel,
707
+ .product-actions,
708
+ .product-expandable[data-open] .product-actions {
709
+ transition: none;
710
+ }
711
+ }
712
+
713
+ .product-image {
714
+ flex: none;
715
+ width: 60px;
716
+ height: 60px;
717
+ border-radius: 8px;
718
+ background: #fff;
719
+ object-fit: contain;
720
+ }
721
+
722
+ .product-info {
723
+ display: grid;
724
+ flex: 1;
725
+ gap: 4px;
726
+ min-width: 0;
727
+ font-size: 12px;
728
+ font-weight: 700;
729
+ line-height: 16px;
730
+ }
731
+
732
+ .product-name {
733
+ display: -webkit-box;
734
+ overflow: hidden;
735
+ -webkit-box-orient: vertical;
736
+ -webkit-line-clamp: 2;
737
+ overflow-wrap: anywhere;
738
+ }
739
+
740
+ .product-price {
741
+ display: flex;
742
+ flex-wrap: wrap;
743
+ gap: 0 6px;
744
+ }
745
+
746
+ .product-list-price {
747
+ font-weight: 400;
748
+ opacity: 0.5;
749
+ }
750
+
751
+ /* In place of the price, for a product that can't be bought. */
752
+ .product-sold-out {
753
+ font-weight: 700;
754
+ opacity: 0.75;
755
+ }
756
+
757
+ /* Placeholders while the product loads, pulsing gently. */
758
+ .product-loading {
759
+ background: currentColor;
760
+ opacity: 0.25;
761
+ animation: product-loading-pulse 1.2s ease-in-out infinite alternate;
762
+ }
763
+
764
+ @keyframes product-loading-pulse {
765
+ to {
766
+ opacity: 0.1;
767
+ }
768
+ }
769
+
770
+ /* The price's: a line its height (the info's line height). */
771
+ .product-price-loading {
772
+ width: 64px;
773
+ height: 16px;
774
+ border-radius: 4px;
775
+ }
776
+
777
+ /* The add to cart button's: its size and shape. */
778
+ .product-add-to-cart-loading {
779
+ display: block;
780
+ height: 48px;
781
+ border-radius: 50px;
782
+ }
783
+
784
+ @media (prefers-reduced-motion: reduce) {
785
+ .product-loading {
786
+ animation: none;
787
+ }
788
+ }
789
+ `;
790
+
42
791
  // src/components/card/card.ts
43
- var cardStyles = `
792
+ var cardStyles = css2`
793
+ /* 9:16 at the height its container gives it (--card-height, default
794
+ 500px). */
44
795
  .card {
45
796
  position: relative;
46
797
  box-sizing: border-box;
47
- width: calc(500px * 9 / 16);
48
- height: 500px;
798
+ width: calc(var(--card-height, 500px) * 9 / 16);
799
+ height: var(--card-height, 500px);
49
800
  overflow: hidden;
50
801
  border-radius: var(--vtex-ads-story-radius, 20px);
51
802
  background: #000;
@@ -126,110 +877,766 @@ var cardStyles = `
126
877
  cursor: pointer;
127
878
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.4));
128
879
  }
129
-
130
- .card-sound .icon {
131
- width: 20px;
132
- height: 20px;
880
+
881
+ .card-sound .icon {
882
+ width: 20px;
883
+ height: 20px;
884
+ }
885
+
886
+ /* With a mouse, the play button shows only on hover or keyboard focus.
887
+ Touch screens have no hover, so it stays visible there. */
888
+ @media (hover: hover) and (pointer: fine) {
889
+ .play {
890
+ opacity: 0;
891
+ transform: translate(-50%, -50%) scale(0.9);
892
+ }
893
+
894
+ .card:hover .play,
895
+ .card-open:focus-visible .play {
896
+ opacity: 1;
897
+ transform: translate(-50%, -50%);
898
+ }
899
+ }
900
+ `;
901
+ function renderSoundButton(video, options) {
902
+ return html4`
903
+ <button
904
+ type="button"
905
+ class="card-sound"
906
+ aria-label=${video.muted ? options.labels.soundOn : options.labels.soundOff}
907
+ @click=${() => video.toggleMuted()}
908
+ >
909
+ ${icon(video.muted ? "soundOff" : "soundOn")}
910
+ </button>
911
+ `;
912
+ }
913
+ function renderCard(story, video, options) {
914
+ var _a, _b;
915
+ const withVideo = (_a = options.withVideo) != null ? _a : true;
916
+ return html4`
917
+ <div
918
+ class="card"
919
+ ${ref2(options.ref)}
920
+ @click=${{ handleEvent: () => {
921
+ var _a2;
922
+ return (_a2 = options.onPress) == null ? void 0 : _a2.call(options);
923
+ }, capture: true }}
924
+ >
925
+ ${renderMedia(story, video, { withVideo })}
926
+ <button
927
+ type="button"
928
+ class="card-open"
929
+ ${ref2(options.openRef)}
930
+ aria-label=${options.label}
931
+ @click=${options.onSelect}
932
+ >
933
+ <span class="play" aria-hidden="true">${icon("play")}</span>
934
+ </button>
935
+ ${withVideo && hasVideo(story, video) && !video.paused ? renderSoundButton(video, options) : nothing3}
936
+ ${options.product ? renderProduct(
937
+ options.product,
938
+ (_b = options.onProductSelect) != null ? _b : options.onSelect
939
+ ) : nothing3}
940
+ ${options.cta ? renderCta(options.cta, options.onCtaSelect) : nothing3}
941
+ </div>
942
+ `;
943
+ }
944
+
945
+ // src/components/carousel/carousel.ts
946
+ import {
947
+ css as css3,
948
+ html as html5
949
+ } from "lit";
950
+ import { repeat } from "lit/directives/repeat.js";
951
+ import { styleMap } from "lit/directives/style-map.js";
952
+ var STAGE_HEIGHT = css3`500px`;
953
+ var SOLO_PADDING = css3`24px`;
954
+ var AUTO_ADVANCE_MS = 5e3;
955
+ var SWIPE_DISTANCE = 40;
956
+ var NARROW_SCREEN = css3`(max-width: 576px)`;
957
+ var VISIBLE_SIDE = 2;
958
+ var RENDERED_SIDE = VISIBLE_SIDE + 3;
959
+ var carouselStyles = css3`
960
+ .carousel {
961
+ position: relative;
962
+ box-sizing: border-box;
963
+ display: grid;
964
+ height: ${STAGE_HEIGHT};
965
+ place-items: center;
966
+ --card-height: ${STAGE_HEIGHT};
967
+ user-select: none;
968
+ }
969
+
970
+ .carousel[data-layout="solo"] {
971
+ padding: ${SOLO_PADDING};
972
+ border-radius: var(--vtex-ads-story-radius, 20px);
973
+ background: var(--vtex-ads-story-color-surface, #fafafa);
974
+ --card-height: calc(${STAGE_HEIGHT} - 2 * ${SOLO_PADDING});
975
+ }
976
+
977
+ .carousel[data-layout="solo"] .card {
978
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
979
+ }
980
+
981
+ .track {
982
+ position: absolute;
983
+ inset: 0;
984
+ overflow: hidden;
985
+ touch-action: pan-y;
986
+ }
987
+
988
+ /* Each slide starts centered, then moves by its own transform. */
989
+ .slide {
990
+ --ease: cubic-bezier(0.25, 1, 0.5, 1);
991
+ --duration: var(--slide-duration, 0.4s);
992
+ position: absolute;
993
+ top: 0;
994
+ left: 50%;
995
+ width: calc(${STAGE_HEIGHT} * 9 / 16);
996
+ height: 100%;
997
+ margin-left: calc(${STAGE_HEIGHT} * 9 / -32);
998
+ opacity: 0.5;
999
+ transition:
1000
+ transform var(--duration) var(--ease),
1001
+ opacity var(--duration) var(--ease),
1002
+ visibility 0s;
1003
+ }
1004
+
1005
+ .slide[data-active] {
1006
+ opacity: 1;
1007
+ }
1008
+
1009
+ /* Pair: --side is -1 for the first card, 1 for the second. The highlighted
1010
+ card sits 47.5% of its width off center, the other (scaled to 0.9)
1011
+ 52.5%, so the gap between them stays 8px. */
1012
+ .carousel[data-layout="pair"] .slide {
1013
+ --side: 1;
1014
+ --offset: 52.5%;
1015
+ --scale: 0.9;
1016
+ transform: translateX(calc(var(--side) * (var(--offset) + 4px)))
1017
+ scale(var(--scale));
1018
+ }
1019
+
1020
+ .carousel[data-layout="pair"] .slide[data-index="0"] {
1021
+ --side: -1;
1022
+ }
1023
+
1024
+ .carousel[data-layout="pair"] .slide[data-active] {
1025
+ --offset: 47.5%;
1026
+ --scale: 1;
1027
+ }
1028
+
1029
+ /* Rolling: --place is the slide's distance from the highlighted one, in
1030
+ cards, 8px apart. A hidden slide fades out, then stops being visible. */
1031
+ .carousel[data-layout="rolling"] .slide {
1032
+ transform: translateX(calc(var(--place) * (100% + 8px))) scale(0.9);
1033
+ }
1034
+
1035
+ .carousel[data-layout="rolling"] .slide[data-active] {
1036
+ transform: translateX(0) scale(1);
1037
+ }
1038
+
1039
+ .slide[data-hidden] {
1040
+ opacity: 0;
1041
+ visibility: hidden;
1042
+ transition:
1043
+ transform var(--duration) var(--ease),
1044
+ opacity var(--duration) var(--ease),
1045
+ visibility 0s var(--duration);
1046
+ }
1047
+
1048
+ /* Only the highlighted card opens the player, so only it shows play. Its
1049
+ sound is the only one to turn on: the others play muted, if at all. */
1050
+ .slide:not([data-active]) .play,
1051
+ .slide:not([data-active]) .card-sound {
1052
+ display: none;
1053
+ }
1054
+
1055
+ .arrow {
1056
+ position: absolute;
1057
+ top: 50%;
1058
+ z-index: 2;
1059
+ display: grid;
1060
+ width: 32px;
1061
+ height: 32px;
1062
+ place-items: center;
1063
+ padding: 0;
1064
+ border: 1px solid rgba(133, 133, 133, 0.3);
1065
+ border-radius: 50%;
1066
+ background: rgba(0, 0, 0, 0.3);
1067
+ backdrop-filter: blur(5px);
1068
+ color: #fff;
1069
+ cursor: pointer;
1070
+ transform: translateY(-50%);
1071
+ transition: background-color 0.2s;
1072
+ }
1073
+
1074
+ .arrow:hover {
1075
+ background: #262626;
1076
+ }
1077
+
1078
+ .arrow:disabled {
1079
+ cursor: default;
1080
+ opacity: 0.5;
1081
+ }
1082
+
1083
+ .arrow .icon {
1084
+ width: 16px;
1085
+ height: 16px;
1086
+ }
1087
+
1088
+ .arrow-previous {
1089
+ left: 3px;
1090
+ }
1091
+
1092
+ .arrow-next {
1093
+ right: 3px;
1094
+ }
1095
+
1096
+ @media ${NARROW_SCREEN} {
1097
+ .carousel[data-layout="solo"] {
1098
+ padding: 0;
1099
+ background: none;
1100
+ --card-height: ${STAGE_HEIGHT};
1101
+ }
1102
+
1103
+ .carousel[data-layout="solo"] .card {
1104
+ box-shadow: none;
1105
+ }
1106
+ }
1107
+
1108
+ @media (prefers-reduced-motion: reduce) {
1109
+ .slide,
1110
+ .slide[data-hidden] {
1111
+ transition: none;
1112
+ }
1113
+ }
1114
+ `;
1115
+ var wrap = (value, count) => (value % count + count) % count;
1116
+ function tracker(elements, slide) {
1117
+ let last;
1118
+ return (element) => {
1119
+ if (last) elements.delete(last);
1120
+ last = element;
1121
+ if (element) elements.set(element, slide);
1122
+ };
1123
+ }
1124
+ var CarouselController = class {
1125
+ constructor(host, options) {
1126
+ this.host = host;
1127
+ this.options = options;
1128
+ /**
1129
+ * Steps taken since the Stories loaded, back and forth, not wrapped: the
1130
+ * rolling layout keys its slides by it.
1131
+ */
1132
+ this.position = 0;
1133
+ /** Stories moved by the last step: longer jumps animate a bit slower. */
1134
+ this.distance = 1;
1135
+ this.count = 0;
1136
+ this.narrow = false;
1137
+ this.connected = false;
1138
+ this.hovered = false;
1139
+ this.focused = false;
1140
+ /** The rendered cards, as their cardRef reported them. */
1141
+ this.cards = /* @__PURE__ */ new Map();
1142
+ /** The rendered cards' focus targets, as their focusRef reported them. */
1143
+ this.focusTargets = /* @__PURE__ */ new Map();
1144
+ this.onMediaChange = (event) => {
1145
+ var _a, _b;
1146
+ const layout = this.layout;
1147
+ this.narrow = event.matches;
1148
+ if (this.layout === layout) return;
1149
+ (_b = (_a = this.options).onLayoutChange) == null ? void 0 : _b.call(_a);
1150
+ this.host.requestUpdate();
1151
+ };
1152
+ this.onPointerEnter = () => {
1153
+ this.hovered = true;
1154
+ this.syncTimer();
1155
+ };
1156
+ this.onPointerLeave = () => {
1157
+ this.hovered = false;
1158
+ this.syncTimer();
1159
+ };
1160
+ // Only keyboard focus stops the advance: a click also focuses the button
1161
+ // it hits, and the advance would then stay stopped after the pointer left.
1162
+ this.onFocusIn = (event) => {
1163
+ this.focused = event.target.matches(":focus-visible");
1164
+ this.syncTimer();
1165
+ };
1166
+ this.onFocusOut = (event) => {
1167
+ const carousel = event.currentTarget;
1168
+ const next = event.relatedTarget;
1169
+ if (!next || !carousel.contains(next)) this.focused = false;
1170
+ this.syncTimer();
1171
+ };
1172
+ // The release is listened for on the window: a mouse drag can end over an
1173
+ // arrow or off the carousel, where the track never gets the pointerup.
1174
+ this.onPointerDown = (event) => {
1175
+ this.endSwipe();
1176
+ this.swipe = { x: event.clientX, moved: false };
1177
+ globalThis.addEventListener("pointerup", this.onPointerUp);
1178
+ globalThis.addEventListener("pointercancel", this.onPointerCancel);
1179
+ };
1180
+ this.onPointerUp = (event) => {
1181
+ const { swipe } = this;
1182
+ this.removeSwipeListeners();
1183
+ if (!swipe) return;
1184
+ const distance = event.clientX - swipe.x;
1185
+ if (Math.abs(distance) > SWIPE_DISTANCE) {
1186
+ swipe.moved = true;
1187
+ this.step(distance < 0 ? 1 : -1);
1188
+ }
1189
+ };
1190
+ this.onPointerCancel = () => this.endSwipe();
1191
+ // A swipe ends with a click on the card under the pointer: it must not
1192
+ // open the player or select that card.
1193
+ this.onClickCapture = {
1194
+ handleEvent: (event) => {
1195
+ var _a;
1196
+ if ((_a = this.swipe) == null ? void 0 : _a.moved) {
1197
+ event.stopPropagation();
1198
+ event.preventDefault();
1199
+ }
1200
+ this.swipe = void 0;
1201
+ },
1202
+ capture: true
1203
+ };
1204
+ host.addController(this);
1205
+ }
1206
+ /** Index of the highlighted Story. */
1207
+ get active() {
1208
+ return this.count ? wrap(this.position, this.count) : 0;
1209
+ }
1210
+ get layout() {
1211
+ if (this.count < 2) return "solo";
1212
+ return this.count === 2 && !this.narrow ? "pair" : "rolling";
1213
+ }
1214
+ /** Key (see Slide) of the highlighted slide. */
1215
+ get activeKey() {
1216
+ if (this.layout === "rolling") return this.position;
1217
+ return this.active;
1218
+ }
1219
+ /**
1220
+ * The cards on screen, with their slide: not the hidden ones kept for the
1221
+ * slide in.
1222
+ */
1223
+ *visibleCards() {
1224
+ for (const [card, slide] of this.cards) {
1225
+ if (!slide.hidden) yield [card, slide];
1226
+ }
1227
+ }
1228
+ /** Moves the keyboard focus to the highlighted card, once rendered. */
1229
+ focusActive() {
1230
+ for (const [target, slide] of this.focusTargets) {
1231
+ if (slide.active && target instanceof HTMLElement) {
1232
+ target.focus();
1233
+ return;
1234
+ }
1235
+ }
1236
+ }
1237
+ hostConnected() {
1238
+ var _a, _b, _c, _d;
1239
+ this.connected = true;
1240
+ this.media = (_a = globalThis.matchMedia) == null ? void 0 : _a.call(globalThis, NARROW_SCREEN.toString());
1241
+ (_b = this.media) == null ? void 0 : _b.addEventListener("change", this.onMediaChange);
1242
+ this.narrow = (_d = (_c = this.media) == null ? void 0 : _c.matches) != null ? _d : false;
1243
+ this.syncTimer();
1244
+ }
1245
+ hostDisconnected() {
1246
+ var _a;
1247
+ this.connected = false;
1248
+ (_a = this.media) == null ? void 0 : _a.removeEventListener("change", this.onMediaChange);
1249
+ this.media = void 0;
1250
+ this.endSwipe();
1251
+ this.syncTimer();
1252
+ }
1253
+ // Whatever the host changed (the player opening, new Stories) may start or
1254
+ // stop the automatic advance.
1255
+ hostUpdated() {
1256
+ this.syncTimer();
1257
+ }
1258
+ /** For a new list of Stories: the first one gets the highlight. */
1259
+ reset(count) {
1260
+ this.count = count;
1261
+ this.position = 0;
1262
+ this.distance = 1;
1263
+ this.hovered = false;
1264
+ this.focused = false;
1265
+ this.restartTimer();
1266
+ }
1267
+ /**
1268
+ * Moves the highlight by `delta` Stories, wrapping around the ends. While
1269
+ * locked, only with `evenIfLocked` (for example, the player stepping to
1270
+ * the next Story it shows).
1271
+ */
1272
+ step(delta, { evenIfLocked = false } = {}) {
1273
+ var _a, _b, _c, _d;
1274
+ if (this.count < 2 || delta === 0) return;
1275
+ if (((_b = (_a = this.options).locked) == null ? void 0 : _b.call(_a)) && !evenIfLocked) return;
1276
+ const from = this.activeKey;
1277
+ this.position += delta;
1278
+ this.distance = Math.abs(delta);
1279
+ this.host.requestUpdate();
1280
+ (_d = (_c = this.options).onStep) == null ? void 0 : _d.call(_c, from, this.activeKey);
1281
+ this.restartTimer();
1282
+ }
1283
+ get shouldAdvance() {
1284
+ var _a, _b;
1285
+ return this.connected && this.count > 1 && !this.hovered && !this.focused && !((_b = (_a = this.options).locked) == null ? void 0 : _b.call(_a));
1286
+ }
1287
+ syncTimer() {
1288
+ if (this.shouldAdvance && !this.timer) {
1289
+ this.timer = setInterval(() => this.step(1), AUTO_ADVANCE_MS);
1290
+ } else if (!this.shouldAdvance && this.timer) {
1291
+ this.stopTimer();
1292
+ }
1293
+ }
1294
+ stopTimer() {
1295
+ clearInterval(this.timer);
1296
+ this.timer = void 0;
1297
+ }
1298
+ restartTimer() {
1299
+ this.stopTimer();
1300
+ this.syncTimer();
1301
+ }
1302
+ endSwipe() {
1303
+ this.removeSwipeListeners();
1304
+ this.swipe = void 0;
1305
+ }
1306
+ removeSwipeListeners() {
1307
+ globalThis.removeEventListener("pointerup", this.onPointerUp);
1308
+ globalThis.removeEventListener("pointercancel", this.onPointerCancel);
1309
+ }
1310
+ slide(fields) {
1311
+ const slide = {
1312
+ ...fields,
1313
+ cardRef: (element) => track(element),
1314
+ focusRef: (element) => trackFocus(element)
1315
+ };
1316
+ const track = tracker(this.cards, slide);
1317
+ const trackFocus = tracker(this.focusTargets, slide);
1318
+ return slide;
1319
+ }
1320
+ /** Pair: both Stories, each keyed by its index. */
1321
+ pairSlides() {
1322
+ const { active } = this;
1323
+ return [0, 1].map(
1324
+ (index) => this.slide({
1325
+ key: index,
1326
+ index,
1327
+ offset: index - active,
1328
+ active: index === active,
1329
+ hidden: false
1330
+ })
1331
+ );
1332
+ }
1333
+ /**
1334
+ * Rolling: the slides around the highlighted one, keyed by their position.
1335
+ * Up to VISIBLE_SIDE show on each side, fewer when there aren't enough
1336
+ * Stories to fill both sides without repeating: half on each side, the
1337
+ * extra one after it. With four, the Story opposite the highlighted one
1338
+ * shows at both ends; with two (narrow screens), the other one shows on
1339
+ * both sides.
1340
+ */
1341
+ rollingSlides() {
1342
+ const { count } = this;
1343
+ const even = count === 2 || count === 4;
1344
+ const before = even ? count / 2 : Math.floor((count - 1) / 2);
1345
+ const after = even ? count / 2 : count - 1 - before;
1346
+ const slides = [];
1347
+ for (let offset = -RENDERED_SIDE; offset <= RENDERED_SIDE; offset += 1) {
1348
+ slides.push(
1349
+ this.slide({
1350
+ key: this.position + offset,
1351
+ index: wrap(this.position + offset, count),
1352
+ offset,
1353
+ active: offset === 0,
1354
+ hidden: Math.abs(offset) > VISIBLE_SIDE || offset < -before || offset > after
1355
+ })
1356
+ );
1357
+ }
1358
+ return slides;
1359
+ }
1360
+ renderSlides(items, renderSlide) {
1361
+ const { layout } = this;
1362
+ const slides = layout === "pair" ? this.pairSlides() : this.rollingSlides();
1363
+ return repeat(
1364
+ slides,
1365
+ (slide) => `${layout}:${slide.key}`,
1366
+ (slide) => {
1367
+ const { index } = slide;
1368
+ return html5`
1369
+ <div
1370
+ class="slide"
1371
+ data-index=${index}
1372
+ ?data-active=${slide.active}
1373
+ ?data-hidden=${slide.hidden}
1374
+ ?inert=${slide.hidden}
1375
+ style=${styleMap({ "--place": String(slide.offset) })}
1376
+ >
1377
+ ${renderSlide(items[index], slide)}
1378
+ </div>
1379
+ `;
1380
+ }
1381
+ );
1382
+ }
1383
+ /**
1384
+ * One item: the card centered over the background. More: the cards in the
1385
+ * pair or rolling layout, with the arrows.
1386
+ */
1387
+ render(items, renderSlide, labels) {
1388
+ var _a, _b, _c;
1389
+ if (this.layout === "solo") {
1390
+ return html5`
1391
+ <div class="carousel" data-layout="solo">
1392
+ ${renderSlide(
1393
+ items[0],
1394
+ this.slide({
1395
+ key: 0,
1396
+ index: 0,
1397
+ offset: 0,
1398
+ active: true,
1399
+ hidden: false
1400
+ })
1401
+ )}
1402
+ </div>
1403
+ `;
1404
+ }
1405
+ const locked = (_c = (_b = (_a = this.options).locked) == null ? void 0 : _b.call(_a)) != null ? _c : false;
1406
+ return html5`
1407
+ <div
1408
+ class="carousel"
1409
+ data-layout=${this.layout}
1410
+ role="region"
1411
+ aria-roledescription=${labels.carouselRole}
1412
+ aria-label=${labels.carousel}
1413
+ @pointerenter=${this.onPointerEnter}
1414
+ @pointerleave=${this.onPointerLeave}
1415
+ @focusin=${this.onFocusIn}
1416
+ @focusout=${this.onFocusOut}
1417
+ >
1418
+ <div
1419
+ class="track"
1420
+ style=${styleMap({
1421
+ "--slide-duration": this.distance > 1 ? "0.52s" : "0.4s"
1422
+ })}
1423
+ @pointerdown=${this.onPointerDown}
1424
+ @click=${this.onClickCapture}
1425
+ >
1426
+ ${this.renderSlides(items, renderSlide)}
1427
+ </div>
1428
+ <button
1429
+ type="button"
1430
+ class="arrow arrow-previous"
1431
+ aria-label=${labels.previous}
1432
+ ?disabled=${locked}
1433
+ @click=${() => this.step(-1)}
1434
+ >
1435
+ ${icon("previous")}
1436
+ </button>
1437
+ <button
1438
+ type="button"
1439
+ class="arrow arrow-next"
1440
+ aria-label=${labels.next}
1441
+ ?disabled=${locked}
1442
+ @click=${() => this.step(1)}
1443
+ >
1444
+ ${icon("next")}
1445
+ </button>
1446
+ </div>
1447
+ `;
1448
+ }
1449
+ };
1450
+
1451
+ // src/tag-name.ts
1452
+ var TAG_NAME = "vtex-ads-story-carousel";
1453
+
1454
+ // src/utils/send-event.ts
1455
+ var CONTENT_TYPE = "text/plain;charset=utf-8";
1456
+ function sendEvent(url, { sessionId, userId }) {
1457
+ var _a, _b;
1458
+ const target = httpUrl(url);
1459
+ if (!target || globalThis.window === void 0) return false;
1460
+ const body = JSON.stringify(
1461
+ userId ? { session_id: sessionId, user_id: userId } : { session_id: sessionId }
1462
+ );
1463
+ try {
1464
+ const queued = (_b = (_a = globalThis.navigator) == null ? void 0 : _a.sendBeacon) == null ? void 0 : _b.call(
1465
+ _a,
1466
+ target,
1467
+ new Blob([body], { type: CONTENT_TYPE })
1468
+ );
1469
+ if (queued) return true;
1470
+ } catch (e) {
1471
+ }
1472
+ if (typeof globalThis.fetch !== "function") return false;
1473
+ globalThis.fetch(target, {
1474
+ method: "POST",
1475
+ headers: { "Content-Type": CONTENT_TYPE },
1476
+ body,
1477
+ keepalive: true,
1478
+ credentials: "omit"
1479
+ }).catch((error) => {
1480
+ console.error(`[${TAG_NAME}] Event request failed`, {
1481
+ url: target,
1482
+ error
1483
+ });
1484
+ });
1485
+ return true;
1486
+ }
1487
+
1488
+ // src/components/events/events-controller.ts
1489
+ var VIEW_THRESHOLD = 0.5;
1490
+ var VIEW_DURATION_MS = 2e3;
1491
+ var URL_FIELD = {
1492
+ impression: "impression_url",
1493
+ view: "view_url",
1494
+ click: "click_url"
1495
+ };
1496
+ var StoryEventsController = class {
1497
+ constructor(host, options) {
1498
+ this.host = host;
1499
+ this.options = options;
1500
+ this.sent = {
1501
+ impression: /* @__PURE__ */ new Set(),
1502
+ view: /* @__PURE__ */ new Set(),
1503
+ click: /* @__PURE__ */ new Set()
1504
+ };
1505
+ this.pendingImpressions = [];
1506
+ this.watched = /* @__PURE__ */ new Map();
1507
+ this.onIntersect = (entries) => {
1508
+ for (const entry of entries) {
1509
+ const watched = this.watched.get(entry.target);
1510
+ if (!watched) continue;
1511
+ watched.visible = entry.isIntersecting && entry.intersectionRatio >= VIEW_THRESHOLD;
1512
+ if (watched.visible) this.startTimer(watched);
1513
+ else this.stopTimer(watched);
1514
+ }
1515
+ };
1516
+ // A hidden page (another tab, minimized) breaks the 2 seconds: they start
1517
+ // over when it shows again.
1518
+ this.onVisibilityChange = () => {
1519
+ for (const watched of this.watched.values()) {
1520
+ if (document.hidden) this.stopTimer(watched);
1521
+ else if (watched.visible) this.startTimer(watched);
1522
+ }
1523
+ };
1524
+ host.addController(this);
1525
+ }
1526
+ hostConnected() {
1527
+ var _a;
1528
+ if (typeof IntersectionObserver === "function") {
1529
+ this.observer = new IntersectionObserver(this.onIntersect, {
1530
+ threshold: VIEW_THRESHOLD
1531
+ });
1532
+ }
1533
+ (_a = globalThis.document) == null ? void 0 : _a.addEventListener(
1534
+ "visibilitychange",
1535
+ this.onVisibilityChange
1536
+ );
1537
+ this.host.updateComplete.then(() => this.syncViewTargets());
1538
+ }
1539
+ hostDisconnected() {
1540
+ var _a, _b;
1541
+ (_a = globalThis.document) == null ? void 0 : _a.removeEventListener(
1542
+ "visibilitychange",
1543
+ this.onVisibilityChange
1544
+ );
1545
+ (_b = this.observer) == null ? void 0 : _b.disconnect();
1546
+ this.observer = void 0;
1547
+ for (const watched of this.watched.values()) clearTimeout(watched.timer);
1548
+ this.watched.clear();
1549
+ this.pendingImpressions = [];
1550
+ }
1551
+ hostUpdated() {
1552
+ const stories = this.pendingImpressions;
1553
+ if (stories.length && this.options.identity().sessionId) {
1554
+ this.pendingImpressions = [];
1555
+ for (const story of stories) this.send("impression", story);
1556
+ }
1557
+ this.syncViewTargets();
1558
+ }
1559
+ /**
1560
+ * The Stories the host renders next: their impressions go out once that
1561
+ * render is done, or, without a session yet, after the first render that
1562
+ * has one. Replaces Stories passed before and not sent yet.
1563
+ */
1564
+ impress(stories) {
1565
+ this.pendingImpressions = stories;
1566
+ }
1567
+ /** A touch on the Story: its click goes out, the first time only. */
1568
+ click(story) {
1569
+ this.send("click", story);
1570
+ }
1571
+ key(sessionId, story) {
1572
+ return `${sessionId}|${story.ad_id}`;
1573
+ }
1574
+ wasSent(kind, story) {
1575
+ const { sessionId } = this.options.identity();
1576
+ return !!sessionId && this.sent[kind].has(this.key(sessionId, story));
133
1577
  }
134
-
135
- /* With a mouse, the play button shows only on hover or keyboard focus.
136
- Touch screens have no hover, so it stays visible there. */
137
- @media (hover: hover) and (pointer: fine) {
138
- .play {
139
- opacity: 0;
140
- transform: translate(-50%, -50%) scale(0.9);
1578
+ send(kind, story) {
1579
+ const { sessionId, userId } = this.options.identity();
1580
+ if (!sessionId || this.wasSent(kind, story)) return;
1581
+ const success = sendEvent(story[URL_FIELD[kind]], { sessionId, userId });
1582
+ if (success) {
1583
+ this.sent[kind].add(this.key(sessionId, story));
141
1584
  }
142
-
143
- .card:hover .play,
144
- .card-open:focus-visible .play {
145
- opacity: 1;
146
- transform: translate(-50%, -50%);
1585
+ }
1586
+ // Watches the elements the host shows now, and stops watching the others,
1587
+ // dropping the time they had on screen.
1588
+ syncViewTargets() {
1589
+ const { observer } = this;
1590
+ if (!observer) return;
1591
+ const current = /* @__PURE__ */ new Map();
1592
+ for (const [element, story] of this.options.viewTargets()) {
1593
+ if (!this.wasSent("view", story)) current.set(element, story);
1594
+ }
1595
+ for (const [element, watched] of this.watched) {
1596
+ if (current.get(element) !== watched.story) {
1597
+ this.unwatch(element, watched);
1598
+ }
1599
+ }
1600
+ for (const [element, story] of current) {
1601
+ if (this.watched.has(element)) continue;
1602
+ this.watched.set(element, { story, visible: false });
1603
+ observer.observe(element);
147
1604
  }
148
1605
  }
149
- `;
150
- function httpUrl(value) {
151
- if (!value) return null;
152
- try {
153
- const { protocol } = new URL(value);
154
- return protocol === "https:" || protocol === "http:" ? value : null;
155
- } catch (e) {
156
- return null;
1606
+ startTimer(watched) {
1607
+ var _a;
1608
+ if (watched.timer || ((_a = globalThis.document) == null ? void 0 : _a.hidden)) return;
1609
+ watched.timer = setTimeout(() => {
1610
+ watched.timer = void 0;
1611
+ this.send("view", watched.story);
1612
+ if (this.wasSent("view", watched.story)) this.unwatchStory(watched.story);
1613
+ }, VIEW_DURATION_MS);
157
1614
  }
158
- }
159
- function prefersReducedMotion() {
160
- var _a2, _b;
161
- return (_b = (_a2 = globalThis.matchMedia) == null ? void 0 : _a2.call(globalThis, "(prefers-reduced-motion: reduce)").matches) != null ? _b : false;
162
- }
163
- function playVideo(video) {
164
- var _a2;
165
- (_a2 = video.play()) == null ? void 0 : _a2.catch(() => void 0);
166
- }
167
- function createVideo(src, poster) {
168
- const video = document.createElement("video");
169
- video.className = "video";
170
- video.muted = true;
171
- video.setAttribute("muted", "");
172
- video.setAttribute("playsinline", "");
173
- video.loop = true;
174
- video.preload = "metadata";
175
- video.autoplay = !prefersReducedMotion();
176
- if (poster) video.poster = poster;
177
- video.src = src;
178
- video.addEventListener("error", () => video.remove());
179
- return video;
180
- }
181
- function createSoundButton(video, options) {
182
- const button = document.createElement("button");
183
- button.type = "button";
184
- button.className = "card-sound";
185
- function sync() {
186
- button.setAttribute(
187
- "aria-label",
188
- video.muted ? options.soundOnLabel : options.soundOffLabel
189
- );
190
- button.replaceChildren(createIcon(video.muted ? "soundOff" : "soundOn"));
1615
+ stopTimer(watched) {
1616
+ clearTimeout(watched.timer);
1617
+ watched.timer = void 0;
191
1618
  }
192
- video.addEventListener("volumechange", sync);
193
- video.addEventListener("error", () => button.remove());
194
- button.addEventListener("click", () => {
195
- video.muted = !video.muted;
196
- });
197
- sync();
198
- return button;
199
- }
200
- function createCard(story, options) {
201
- const card = document.createElement("div");
202
- card.className = "card";
203
- const posterUrl = httpUrl(story.poster_url);
204
- if (posterUrl) {
205
- const poster = document.createElement("img");
206
- poster.className = "poster";
207
- poster.alt = "";
208
- poster.src = posterUrl;
209
- card.append(poster);
210
- }
211
- const mediaUrl = httpUrl(story.media_url);
212
- const video = mediaUrl ? createVideo(mediaUrl, posterUrl) : null;
213
- if (video) card.append(video);
214
- if (options) {
215
- const open = document.createElement("button");
216
- open.type = "button";
217
- open.className = "card-open";
218
- open.setAttribute("aria-label", options.label);
219
- const play = document.createElement("span");
220
- play.className = "play";
221
- play.setAttribute("aria-hidden", "true");
222
- play.append(createIcon("play"));
223
- open.append(play);
224
- open.addEventListener("click", options.onSelect);
225
- card.append(open);
226
- if (video) card.append(createSoundButton(video, options));
227
- }
228
- return card;
229
- }
1619
+ unwatch(element, watched) {
1620
+ var _a;
1621
+ this.stopTimer(watched);
1622
+ (_a = this.observer) == null ? void 0 : _a.unobserve(element);
1623
+ this.watched.delete(element);
1624
+ }
1625
+ unwatchStory(story) {
1626
+ for (const [element, watched] of this.watched) {
1627
+ if (watched.story.ad_id === story.ad_id) this.unwatch(element, watched);
1628
+ }
1629
+ }
1630
+ };
230
1631
 
231
1632
  // src/components/player/player.ts
232
- var playerStyles = `
1633
+ import { css as css4, html as html6, nothing as nothing4 } from "lit";
1634
+ import { createRef as createRef2, ref as ref3 } from "lit/directives/ref.js";
1635
+ import { repeat as repeat2 } from "lit/directives/repeat.js";
1636
+ import { styleMap as styleMap2 } from "lit/directives/style-map.js";
1637
+ var NEAR_GAP = 72;
1638
+ var FAR_GAP = 48;
1639
+ var playerStyles = css4`
233
1640
  .player {
234
1641
  position: fixed;
235
1642
  inset: auto 16px 16px auto;
@@ -262,12 +1669,28 @@ var playerStyles = `
262
1669
  background: transparent;
263
1670
  }
264
1671
 
1672
+ /* Focusable only to keep the focus in the player when its video is clicked
1673
+ (see render): no ring around the whole player. */
1674
+ .player:focus {
1675
+ outline: none;
1676
+ }
1677
+
265
1678
  .player-frame {
266
1679
  position: relative;
267
1680
  width: 100%;
268
1681
  height: 100%;
269
1682
  }
270
1683
 
1684
+ /* What moves in the expanded view, off center with two Stories and in the
1685
+ step animation: the video, its dimming and previous and next. Expand and
1686
+ close stay out of it: a transformed box becomes the one their fixed
1687
+ position, at the top right of the screen, is measured from. */
1688
+ .player-stage {
1689
+ position: relative;
1690
+ width: 100%;
1691
+ height: 100%;
1692
+ }
1693
+
271
1694
  .player .card {
272
1695
  width: 100%;
273
1696
  height: 100%;
@@ -314,6 +1737,26 @@ var playerStyles = `
314
1737
  height: 20px;
315
1738
  }
316
1739
 
1740
+ /* The product pill or the call to action. Their wrapper only stops clicks:
1741
+ the pill places itself. The product is larger than on the carousel card
1742
+ (as in the prototype). */
1743
+ .player-destination {
1744
+ display: contents;
1745
+ }
1746
+
1747
+ .player .product-info {
1748
+ font-size: 14px;
1749
+ }
1750
+
1751
+ .player .product-image {
1752
+ width: 72px;
1753
+ height: 72px;
1754
+ }
1755
+
1756
+ .player .product-price {
1757
+ color: rgba(255, 255, 255, 0.7);
1758
+ }
1759
+
317
1760
  /* Above the card: on narrow screens the expanded card can cover them. */
318
1761
  .player-controls {
319
1762
  position: absolute;
@@ -324,6 +1767,12 @@ var playerStyles = `
324
1767
  gap: 8px;
325
1768
  }
326
1769
 
1770
+ /* Previous and next Story, above the card's top left (mini player only). */
1771
+ .player-nav {
1772
+ right: auto;
1773
+ left: 0;
1774
+ }
1775
+
327
1776
  .player-button {
328
1777
  display: grid;
329
1778
  width: 36px;
@@ -377,6 +1826,116 @@ var playerStyles = `
377
1826
  height: 40px;
378
1827
  }
379
1828
 
1829
+ /* Expanded with more than one Story: the other Stories' covers beside the
1830
+ video, smaller and dimmed, as in the prototype. --side is -1 (before)
1831
+ or 1 (after), --beyond how many places past the nearest one. */
1832
+ .player[data-expanded] {
1833
+ --center-height: min(78vh, 720px);
1834
+ --side-height: min(38vh, 320px);
1835
+ --side-width: calc(var(--side-height) * 9 / 16);
1836
+ --center-half: calc(var(--center-height) * 9 / 32);
1837
+ --near-gap: ${NEAR_GAP}px;
1838
+ --far-gap: ${FAR_GAP}px;
1839
+ --near: calc(var(--center-half) + var(--near-gap) + var(--side-width) / 2);
1840
+ --pitch: calc(var(--side-width) + var(--far-gap));
1841
+ }
1842
+
1843
+ .player-neighbor {
1844
+ position: absolute;
1845
+ top: 50%;
1846
+ left: 50%;
1847
+ width: var(--side-width);
1848
+ height: var(--side-height);
1849
+ padding: 0;
1850
+ overflow: hidden;
1851
+ border: 0;
1852
+ border-radius: 16px;
1853
+ background: #111;
1854
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
1855
+ cursor: pointer;
1856
+ transform: translate(
1857
+ calc(-50% + var(--side) * var(--near) + var(--beyond) * var(--pitch)),
1858
+ -50%
1859
+ );
1860
+ }
1861
+
1862
+ .player-neighbor img {
1863
+ width: 100%;
1864
+ height: 100%;
1865
+ object-fit: cover;
1866
+ }
1867
+
1868
+ /* Fades out as the video arrives from a dimmed cover (see animateStep). */
1869
+ .player-dim {
1870
+ position: absolute;
1871
+ inset: 0;
1872
+ z-index: 3;
1873
+ border-radius: var(--vtex-ads-story-radius, 20px);
1874
+ background: rgba(0, 0, 0, 0.35);
1875
+ opacity: 0;
1876
+ pointer-events: none;
1877
+ }
1878
+
1879
+ .player-neighbor::after {
1880
+ position: absolute;
1881
+ inset: 0;
1882
+ background: rgba(0, 0, 0, 0.35);
1883
+ content: "";
1884
+ }
1885
+
1886
+ .player-neighbor:hover::after,
1887
+ .player-neighbor:focus-visible::after {
1888
+ background: rgba(0, 0, 0, 0.12);
1889
+ }
1890
+
1891
+ .player-neighbor:focus-visible {
1892
+ outline: 2px solid #fff;
1893
+ outline-offset: 2px;
1894
+ }
1895
+
1896
+ /* Two Stories: the video moves off center toward --pair-dir, and the other
1897
+ Story sits on the other side. */
1898
+ .player[data-pair] .player-stage {
1899
+ transform: translateX(
1900
+ calc(var(--pair-dir) * (var(--near-gap) + var(--side-width)) / 2)
1901
+ );
1902
+ }
1903
+
1904
+ .player[data-pair] .player-neighbor {
1905
+ transform: translate(
1906
+ calc(
1907
+ -50% + var(--pair-dir) * -1 * (var(--center-half) + var(--near-gap) / 2)
1908
+ ),
1909
+ -50%
1910
+ );
1911
+ }
1912
+
1913
+ /* Expanded previous and next: beside the video, centered on its height. */
1914
+ .player[data-expanded] .player-nav {
1915
+ position: static;
1916
+ display: contents;
1917
+ }
1918
+
1919
+ .player[data-expanded] .player-nav .player-button {
1920
+ position: absolute;
1921
+ top: 50%;
1922
+ z-index: 2;
1923
+ transform: translateY(-50%);
1924
+ }
1925
+
1926
+ .player[data-expanded] .player-previous {
1927
+ left: -56px;
1928
+ }
1929
+
1930
+ .player[data-expanded] .player-next {
1931
+ right: -56px;
1932
+ }
1933
+
1934
+ /* With two, the other Story's cover beside the video does that. */
1935
+ .player[data-expanded][data-pair] .player-nav {
1936
+ display: none;
1937
+ }
1938
+
380
1939
  @media (max-width: 576px) {
381
1940
  .player {
382
1941
  right: 12px;
@@ -384,6 +1943,18 @@ var playerStyles = `
384
1943
  height: 391px;
385
1944
  }
386
1945
 
1946
+ .player:not([data-expanded]) .product-image {
1947
+ width: 56px;
1948
+ height: 56px;
1949
+ }
1950
+
1951
+ /* "Adicionar ao carrinho" fits on one line in the narrow mini player. */
1952
+ .player:not([data-expanded]) .product-action {
1953
+ height: 40px;
1954
+ padding: 0 8px;
1955
+ font-size: 12px;
1956
+ }
1957
+
387
1958
  .player[data-expanded] {
388
1959
  background: #000;
389
1960
  }
@@ -406,6 +1977,28 @@ var playerStyles = `
406
1977
  top: 60px;
407
1978
  right: 12px;
408
1979
  }
1980
+
1981
+ /* No room for the other Stories' covers: previous and next go inside
1982
+ the video's edges instead, also with two. */
1983
+ .player-neighbor {
1984
+ display: none;
1985
+ }
1986
+
1987
+ .player[data-pair] .player-stage {
1988
+ transform: none;
1989
+ }
1990
+
1991
+ .player[data-expanded][data-pair] .player-nav {
1992
+ display: contents;
1993
+ }
1994
+
1995
+ .player[data-expanded] .player-previous {
1996
+ left: 12px;
1997
+ }
1998
+
1999
+ .player[data-expanded] .player-next {
2000
+ right: 12px;
2001
+ }
409
2002
  }
410
2003
 
411
2004
  @keyframes player-in {
@@ -421,138 +2014,765 @@ var playerStyles = `
421
2014
  }
422
2015
  }
423
2016
  `;
424
- function createButton(className, label, icon) {
425
- const button = document.createElement("button");
426
- button.type = "button";
427
- button.className = `player-button ${className}`;
428
- button.setAttribute("aria-label", label);
429
- button.append(createIcon(icon));
430
- return button;
2017
+ function neighborOffsets(count, active) {
2018
+ if (count < 2) return [];
2019
+ if (count === 2) return [active === 0 ? 1 : -1];
2020
+ const offsets = [];
2021
+ const shown = /* @__PURE__ */ new Set([0]);
2022
+ for (const offset of [-1, 1, -2, 2]) {
2023
+ const index = (offset % count + count) % count;
2024
+ if (!shown.has(index)) {
2025
+ shown.add(index);
2026
+ offsets.push(offset);
2027
+ }
2028
+ }
2029
+ return offsets;
431
2030
  }
432
- function supportsPopover(player) {
433
- return typeof player.showPopover === "function";
2031
+ var STEP_ANIMATION = {
2032
+ duration: 560,
2033
+ easing: "cubic-bezier(0.32, 0.72, 0, 1)"
2034
+ };
2035
+ var coverTransform = (x, scale = 1) => `translate(-50%, -50%) translateX(${x}px) scale(${scale})`;
2036
+ var fadeIn = (element) => element.animate([{ opacity: 0 }, { opacity: 1 }], {
2037
+ ...STEP_ANIMATION,
2038
+ pseudoElement: "::after"
2039
+ });
2040
+ function animateRailStep(frame, frameFrom, neighbors, { frameWidth, sideWidth }) {
2041
+ const placeX = (place) => {
2042
+ if (place === 0) return 0;
2043
+ const side = Math.sign(place);
2044
+ const near = frameWidth / 2 + NEAR_GAP + sideWidth / 2;
2045
+ return side * near + (place - side) * (sideWidth + FAR_GAP);
2046
+ };
2047
+ const ratio = sideWidth / frameWidth;
2048
+ const animations = [
2049
+ frame.animate(
2050
+ [
2051
+ { transform: `translateX(${placeX(frameFrom)}px) scale(${ratio})` },
2052
+ { transform: "none" }
2053
+ ],
2054
+ STEP_ANIMATION
2055
+ )
2056
+ ];
2057
+ for (const { element, offset, from } of neighbors) {
2058
+ const wasVideo = from === 0;
2059
+ animations.push(
2060
+ element.animate(
2061
+ [
2062
+ { transform: coverTransform(placeX(from), wasVideo ? 1 / ratio : 1) },
2063
+ { transform: coverTransform(placeX(offset)) }
2064
+ ],
2065
+ STEP_ANIMATION
2066
+ )
2067
+ );
2068
+ if (wasVideo) animations.push(fadeIn(element));
2069
+ }
2070
+ return animations;
434
2071
  }
435
- function showPlayer(player) {
436
- if (supportsPopover(player)) player.showPopover();
437
- else player.show();
2072
+ function animatePairStep(frame, neighbor, direction, { frameWidth, sideWidth }) {
2073
+ const videoX = (side) => side * (NEAR_GAP + sideWidth) / 2;
2074
+ const coverX = (side) => -side * (frameWidth + NEAR_GAP) / 2;
2075
+ const ratio = sideWidth / frameWidth;
2076
+ return [
2077
+ frame.animate(
2078
+ [
2079
+ { transform: `translateX(${coverX(-direction)}px) scale(${ratio})` },
2080
+ { transform: `translateX(${videoX(direction)}px)` }
2081
+ ],
2082
+ STEP_ANIMATION
2083
+ ),
2084
+ neighbor.animate(
2085
+ [
2086
+ { transform: coverTransform(videoX(-direction), 1 / ratio) },
2087
+ { transform: coverTransform(coverX(direction)) }
2088
+ ],
2089
+ STEP_ANIMATION
2090
+ ),
2091
+ fadeIn(neighbor)
2092
+ ];
438
2093
  }
439
- function playPlayer(player) {
440
- const video = player.querySelector("video");
441
- if (video) playVideo(video);
2094
+ var ARROW_STEPS = {
2095
+ ArrowLeft: -1,
2096
+ ArrowRight: 1
2097
+ };
2098
+ var isFreeArrowKey = (event) => !event.defaultPrevented && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;
2099
+ function supportsPopover(dialog) {
2100
+ return typeof dialog.showPopover === "function";
442
2101
  }
443
- function addVideoControls(player, card, video, options) {
444
- const toggle = document.createElement("button");
445
- toggle.type = "button";
446
- toggle.className = "play player-toggle";
447
- const sound = createButton("player-sound", "", "soundOff");
448
- function syncPlayback() {
449
- player.toggleAttribute("data-paused", video.paused);
450
- toggle.setAttribute(
451
- "aria-label",
452
- video.paused ? options.playLabel : options.pauseLabel
453
- );
454
- toggle.replaceChildren(createIcon(video.paused ? "play" : "pause"));
2102
+ var PlayerController = class {
2103
+ constructor(host, options) {
2104
+ this.host = host;
2105
+ this.options = options;
2106
+ /** Rendered and, once the host has updated, shown. */
2107
+ this.isOpen = false;
2108
+ this.expanded = false;
2109
+ /** The product panel is open. Closed again on a step and on opening. */
2110
+ this.productOpen = false;
2111
+ /** Switched modes at least once: only the first opening fades in. */
2112
+ this.switched = false;
2113
+ /** The dialog is showing, in the mode `expanded` says. */
2114
+ this.shown = false;
2115
+ this.dialog = createRef2();
2116
+ this.expandButton = createRef2();
2117
+ this.closeButton = createRef2();
2118
+ this.stage = createRef2();
2119
+ this.stageCardRef = createRef2();
2120
+ this.dim = createRef2();
2121
+ /** The covers beside the expanded video, by offset, as rendered. */
2122
+ this.neighborElements = /* @__PURE__ */ new Map();
2123
+ /** One ref callback per offset: a new one each render would detach it. */
2124
+ this.neighborRefs = /* @__PURE__ */ new Map();
2125
+ /** Rendered with previous and next (see PlayerRenderOptions). */
2126
+ this.navigation = false;
2127
+ /** Side the expanded video moved to with two Stories; 0 otherwise. */
2128
+ this.pairDirection = 0;
2129
+ /** The step animation running, cancelled by the next step. */
2130
+ this.animations = [];
2131
+ this.toggleExpanded = async () => {
2132
+ var _a;
2133
+ const dialog = this.dialog.value;
2134
+ if (!dialog) return;
2135
+ this.cancelAnimations();
2136
+ this.hide(dialog);
2137
+ this.expanded = !this.expanded;
2138
+ this.switched = true;
2139
+ this.host.requestUpdate();
2140
+ await this.host.updateComplete;
2141
+ if (!this.isOpen) return;
2142
+ this.show(dialog);
2143
+ (_a = this.expandButton.value) == null ? void 0 : _a.focus();
2144
+ };
2145
+ // Escape anywhere on the page, also in the mini player, which is not modal.
2146
+ this.onKeyDown = (event) => {
2147
+ if (event.key === "Escape") this.options.onClose();
2148
+ };
2149
+ // With the focus in the player and more than one Story, the arrows step, as
2150
+ // the previous and next buttons do. Only there: the mini player leaves the
2151
+ // page usable, and the page's own arrow keys (a gallery, a slider) keep
2152
+ // working.
2153
+ this.onPlayerKeyDown = (event) => {
2154
+ var _a, _b;
2155
+ const delta = ARROW_STEPS[event.key];
2156
+ if (!delta || !this.navigation || !isFreeArrowKey(event)) return;
2157
+ event.preventDefault();
2158
+ (_b = (_a = this.options).onStep) == null ? void 0 : _b.call(_a, delta);
2159
+ };
2160
+ // Clicks on the backdrop of the expanded view reach the dialog itself.
2161
+ this.onDialogClick = (event) => {
2162
+ if (this.expanded && event.target === event.currentTarget) {
2163
+ this.options.onClose();
2164
+ }
2165
+ };
2166
+ // Escape on a modal dialog would only hide it: close the player instead.
2167
+ this.onCancel = (event) => {
2168
+ event.preventDefault();
2169
+ this.options.onClose();
2170
+ };
2171
+ /**
2172
+ * Play/pause in the middle of the video and sound on/off at its top right.
2173
+ * They follow the video's own events, so a blocked autoplay shows as
2174
+ * paused.
2175
+ */
2176
+ this.toggleProduct = () => {
2177
+ this.productOpen = !this.productOpen;
2178
+ this.host.requestUpdate();
2179
+ };
2180
+ /**
2181
+ * A click on the video: closes the product panel when it is open, plays or
2182
+ * pauses the video otherwise.
2183
+ */
2184
+ this.onVideoClick = () => {
2185
+ if (this.productOpen) this.toggleProduct();
2186
+ else this.video.togglePlayback();
2187
+ };
2188
+ host.addController(this);
2189
+ this.video = new VideoController(host);
2190
+ }
2191
+ /** Open in the expanded view, a modal over the page. */
2192
+ get isExpanded() {
2193
+ return this.isOpen && this.expanded;
2194
+ }
2195
+ /** The card with the video, while the player is open. */
2196
+ get stageCard() {
2197
+ return this.isOpen ? this.stageCardRef.value : void 0;
2198
+ }
2199
+ hostDisconnected() {
2200
+ this.close();
2201
+ }
2202
+ /**
2203
+ * Opens the mini player, plays the video and focuses the close button.
2204
+ * With `productOpen`, the product panel shows open (the shopper chose the
2205
+ * product).
2206
+ */
2207
+ async open({ productOpen = false } = {}) {
2208
+ var _a;
2209
+ if (this.isOpen) return;
2210
+ document.addEventListener("keydown", this.onKeyDown);
2211
+ this.isOpen = true;
2212
+ this.expanded = false;
2213
+ this.productOpen = productOpen;
2214
+ this.switched = false;
2215
+ this.rendered = void 0;
2216
+ this.beforeStep = void 0;
2217
+ this.video.reset();
2218
+ this.host.requestUpdate();
2219
+ await this.host.updateComplete;
2220
+ const dialog = this.dialog.value;
2221
+ if (!this.isOpen || !dialog) return;
2222
+ this.show(dialog);
2223
+ this.video.play();
2224
+ (_a = this.closeButton.value) == null ? void 0 : _a.focus();
2225
+ }
2226
+ /** Hides the player now; the host removes it on its next update. */
2227
+ close() {
2228
+ if (!this.isOpen) return;
2229
+ document.removeEventListener("keydown", this.onKeyDown);
2230
+ this.cancelAnimations();
2231
+ const dialog = this.dialog.value;
2232
+ if (dialog) this.hide(dialog);
2233
+ this.isOpen = false;
2234
+ this.host.requestUpdate();
2235
+ }
2236
+ /**
2237
+ * After the host renders a different Story in the open player, `delta`
2238
+ * places from the previous one: its video starts from the top and plays,
2239
+ * with the sound as the shopper left it. A failed load of the previous
2240
+ * video doesn't hide the new one. The expanded view animates the step.
2241
+ */
2242
+ async showNext(delta = 0) {
2243
+ if (!this.isOpen) return;
2244
+ const withSound = !this.video.muted;
2245
+ this.video.failed = false;
2246
+ this.productOpen = false;
2247
+ this.host.requestUpdate();
2248
+ await this.host.updateComplete;
2249
+ if (!this.isOpen) return;
2250
+ this.video.restart({ withSound });
2251
+ this.animateStep(delta);
2252
+ }
2253
+ /** Stops a step animation still running, leaving the CSS layout. */
2254
+ cancelAnimations() {
2255
+ for (const animation of this.animations) animation.cancel();
2256
+ this.animations = [];
2257
+ }
2258
+ /**
2259
+ * The expanded step, as in the prototype: the video grows from the cover
2260
+ * of the Story it now shows, and the covers slide to their new places, the
2261
+ * previous Story's shrinking from the video's size. With two Stories, the
2262
+ * video and the other cover swap sides. Not with reduced motion, nor
2263
+ * without covers (narrow screens).
2264
+ */
2265
+ animateStep(delta) {
2266
+ var _a, _b;
2267
+ if (!this.expanded || delta === 0 || prefersReducedMotion()) return;
2268
+ const frame = this.stage.value;
2269
+ const dim = this.dim.value;
2270
+ if (!frame || !dim || typeof frame.animate !== "function") return;
2271
+ const { rendered, beforeStep } = this;
2272
+ const placeBefore = (story, fallback) => {
2273
+ var _a2;
2274
+ if (!story || !beforeStep) return fallback;
2275
+ if (story === beforeStep.story) return 0;
2276
+ const cover = beforeStep.neighbors.find((n) => n.story === story);
2277
+ return (_a2 = cover == null ? void 0 : cover.offset) != null ? _a2 : fallback;
2278
+ };
2279
+ const neighbors = [...this.neighborElements].map(([offset, element]) => {
2280
+ var _a2;
2281
+ return {
2282
+ offset,
2283
+ element,
2284
+ from: placeBefore(
2285
+ (_a2 = rendered == null ? void 0 : rendered.neighbors.find((n) => n.offset === offset)) == null ? void 0 : _a2.story,
2286
+ offset + delta
2287
+ )
2288
+ };
2289
+ });
2290
+ const sizes = {
2291
+ frameWidth: frame.offsetWidth,
2292
+ sideWidth: (_b = (_a = neighbors[0]) == null ? void 0 : _a.element.offsetWidth) != null ? _b : 0
2293
+ };
2294
+ if (!sizes.frameWidth || !sizes.sideWidth) return;
2295
+ this.cancelAnimations();
2296
+ this.animations = [
2297
+ dim.animate([{ opacity: 1 }, { opacity: 0 }], STEP_ANIMATION),
2298
+ ...this.pairDirection ? animatePairStep(
2299
+ frame,
2300
+ neighbors[0].element,
2301
+ this.pairDirection,
2302
+ sizes
2303
+ ) : animateRailStep(
2304
+ frame,
2305
+ placeBefore(rendered == null ? void 0 : rendered.story, delta),
2306
+ neighbors,
2307
+ sizes
2308
+ )
2309
+ ];
2310
+ }
2311
+ // Keeps neighborElements in step with the covers Lit renders.
2312
+ neighborRef(offset) {
2313
+ let callback = this.neighborRefs.get(offset);
2314
+ if (!callback) {
2315
+ callback = (element) => {
2316
+ if (element) this.neighborElements.set(offset, element);
2317
+ else this.neighborElements.delete(offset);
2318
+ };
2319
+ this.neighborRefs.set(offset, callback);
2320
+ }
2321
+ return callback;
2322
+ }
2323
+ // Mini: a manual popover, or a non-modal dialog without popover support.
2324
+ // Expanded: a modal dialog.
2325
+ // Already showing: a second expand click in the same task resumes after the
2326
+ // first one has shown the dialog, and showing it again would throw.
2327
+ show(dialog) {
2328
+ if (this.shown) return;
2329
+ if (this.expanded) dialog.showModal();
2330
+ else if (supportsPopover(dialog)) dialog.showPopover();
2331
+ else dialog.show();
2332
+ this.shown = true;
2333
+ }
2334
+ // A dialog can't be shown as a popover and as a modal at the same time, so
2335
+ // switching modes hides it first, the same way it was shown.
2336
+ hide(dialog) {
2337
+ if (!this.shown) return;
2338
+ if (!this.expanded && supportsPopover(dialog)) dialog.hidePopover();
2339
+ else dialog.close();
2340
+ this.shown = false;
2341
+ }
2342
+ /**
2343
+ * At the bottom of the video, the product pill, which opens the panel with
2344
+ * its actions, or the call to action of a link destination. Clicks on them
2345
+ * don't reach the video.
2346
+ */
2347
+ renderDestination({ product, cta, labels }) {
2348
+ let content;
2349
+ if (product) {
2350
+ content = renderExpandableProduct(product, {
2351
+ open: this.productOpen,
2352
+ onToggle: this.toggleProduct,
2353
+ panelId: "player-product-panel",
2354
+ labels
2355
+ });
2356
+ } else if (cta) {
2357
+ content = renderCta(cta);
2358
+ } else {
2359
+ return nothing4;
2360
+ }
2361
+ return html6`
2362
+ <div
2363
+ class="player-destination"
2364
+ @click=${(event) => event.stopPropagation()}
2365
+ >
2366
+ ${content}
2367
+ </div>
2368
+ `;
2369
+ }
2370
+ renderVideoControls(labels) {
2371
+ const { video } = this;
2372
+ const onToggle = (event) => {
2373
+ event.stopPropagation();
2374
+ video.togglePlayback();
2375
+ };
2376
+ const onSound = (event) => {
2377
+ event.stopPropagation();
2378
+ video.toggleMuted();
2379
+ };
2380
+ return html6`
2381
+ <button
2382
+ type="button"
2383
+ class="play player-toggle"
2384
+ aria-label=${video.paused ? labels.play : labels.pause}
2385
+ @click=${onToggle}
2386
+ >
2387
+ ${icon(video.paused ? "play" : "pause")}
2388
+ </button>
2389
+ <button
2390
+ type="button"
2391
+ class="player-button player-sound"
2392
+ aria-label=${video.muted ? labels.soundOn : labels.soundOff}
2393
+ @click=${onSound}
2394
+ >
2395
+ ${icon(video.muted ? "soundOff" : "soundOn")}
2396
+ </button>
2397
+ `;
2398
+ }
2399
+ /**
2400
+ * Previous and next Story: above the mini player's top left, beside the
2401
+ * expanded video.
2402
+ */
2403
+ renderNavigation(labels) {
2404
+ const { options } = this;
2405
+ const step = (delta) => () => {
2406
+ var _a;
2407
+ return (_a = options.onStep) == null ? void 0 : _a.call(options, delta);
2408
+ };
2409
+ return html6`
2410
+ <div class="player-controls player-nav">
2411
+ <button
2412
+ type="button"
2413
+ class="player-button player-previous"
2414
+ aria-label=${labels.previous}
2415
+ @click=${step(-1)}
2416
+ >
2417
+ ${icon("previous")}
2418
+ </button>
2419
+ <button
2420
+ type="button"
2421
+ class="player-button player-next"
2422
+ aria-label=${labels.next}
2423
+ @click=${step(1)}
2424
+ >
2425
+ ${icon("next")}
2426
+ </button>
2427
+ </div>
2428
+ `;
455
2429
  }
456
- function syncSound() {
457
- sound.setAttribute(
458
- "aria-label",
459
- video.muted ? options.soundOnLabel : options.soundOffLabel
2430
+ /** The other Stories' covers beside the expanded video. */
2431
+ renderNeighbors(neighbors, labels) {
2432
+ const { options } = this;
2433
+ return repeat2(
2434
+ neighbors,
2435
+ ({ offset }) => neighbors.length === 1 ? "single" : offset,
2436
+ ({ offset, story, label }) => {
2437
+ const poster = httpUrl(story.poster_url);
2438
+ const side = Math.sign(offset);
2439
+ return html6`
2440
+ <button
2441
+ type="button"
2442
+ class="player-neighbor"
2443
+ aria-label=${label != null ? label : labels.show}
2444
+ style=${styleMap2({
2445
+ "--side": String(side),
2446
+ "--beyond": String(offset - side)
2447
+ })}
2448
+ ${ref3(this.neighborRef(offset))}
2449
+ @click=${() => {
2450
+ var _a;
2451
+ return (_a = options.onStep) == null ? void 0 : _a.call(options, offset);
2452
+ }}
2453
+ >
2454
+ ${poster ? html6`<img alt="" src=${poster} />` : nothing4}
2455
+ </button>
2456
+ `;
2457
+ }
460
2458
  );
461
- sound.replaceChildren(createIcon(video.muted ? "soundOff" : "soundOn"));
462
2459
  }
463
- function togglePlayback() {
464
- if (video.paused) playVideo(video);
465
- else video.pause();
2460
+ /** Expand or collapse, and close: above the video, or at the top right. */
2461
+ renderWindowControls(labels) {
2462
+ const { options, expanded } = this;
2463
+ return html6`
2464
+ <div class="player-controls">
2465
+ <button
2466
+ type="button"
2467
+ class="player-button player-expand"
2468
+ aria-label=${expanded ? labels.collapse : labels.expand}
2469
+ ${ref3(this.expandButton)}
2470
+ @click=${this.toggleExpanded}
2471
+ >
2472
+ ${icon(expanded ? "collapse" : "expand")}
2473
+ </button>
2474
+ <button
2475
+ type="button"
2476
+ class="player-button player-close"
2477
+ aria-label=${labels.close}
2478
+ ${ref3(this.closeButton)}
2479
+ @click=${options.onClose}
2480
+ >
2481
+ ${icon("close")}
2482
+ </button>
2483
+ </div>
2484
+ `;
466
2485
  }
467
- video.addEventListener("play", syncPlayback);
468
- video.addEventListener("pause", syncPlayback);
469
- video.addEventListener("volumechange", syncSound);
470
- video.addEventListener("error", () => {
471
- toggle.remove();
472
- sound.remove();
473
- delete player.dataset.paused;
474
- });
475
- toggle.addEventListener("click", (event) => {
476
- event.stopPropagation();
477
- togglePlayback();
478
- });
479
- sound.addEventListener("click", (event) => {
480
- event.stopPropagation();
481
- video.muted = !video.muted;
482
- });
483
- card.addEventListener("click", () => {
484
- if (video.isConnected) togglePlayback();
485
- });
486
- syncPlayback();
487
- syncSound();
488
- card.append(toggle, sound);
489
- }
490
- function createPlayer(story, options) {
491
- const player = document.createElement("dialog");
492
- player.className = "player";
493
- player.setAttribute("popover", "manual");
494
- player.setAttribute("aria-label", options.label);
495
- const frame = document.createElement("div");
496
- frame.className = "player-frame";
497
- const controls = document.createElement("div");
498
- controls.className = "player-controls";
499
- const expand = createButton("player-expand", options.expandLabel, "expand");
500
- const close = createButton("player-close", options.closeLabel, "close");
501
- controls.append(expand, close);
502
- let expanded = false;
503
- function hide() {
504
- if (!expanded && supportsPopover(player)) player.hidePopover();
505
- else player.close();
506
- }
507
- expand.addEventListener("click", () => {
508
- hide();
509
- expanded = !expanded;
510
- player.toggleAttribute("data-expanded", expanded);
511
- player.dataset.switched = "";
512
- expand.setAttribute(
513
- "aria-label",
514
- expanded ? options.collapseLabel : options.expandLabel
2486
+ /**
2487
+ * The video with its controls and the product or call to action. With
2488
+ * `advances`, it plays once and moves on to the next Story when it ends;
2489
+ * otherwise it loops.
2490
+ */
2491
+ renderVideo(story, advances, destination) {
2492
+ const { video, options } = this;
2493
+ return html6`
2494
+ <div class="card" ${ref3(this.stageCardRef)} @click=${this.onVideoClick}>
2495
+ ${renderMedia(story, video, {
2496
+ loop: !advances,
2497
+ onEnded: advances ? () => {
2498
+ var _a;
2499
+ return (_a = options.onStep) == null ? void 0 : _a.call(options, 1);
2500
+ } : void 0
2501
+ })}
2502
+ ${hasVideo(story, video) ? this.renderVideoControls(destination.labels) : nothing4}
2503
+ ${this.renderDestination(destination)}
2504
+ </div>
2505
+ `;
2506
+ }
2507
+ /**
2508
+ * Keeps what this render shows, for the step animation: the covers beside
2509
+ * the video (only in the expanded view) and the side the video moves to
2510
+ * with two Stories. A new Story makes what was shown the animation's
2511
+ * start.
2512
+ */
2513
+ track(story, neighbors) {
2514
+ const shown = this.expanded ? neighbors : [];
2515
+ this.pairDirection = shown.length === 1 ? -Math.sign(shown[0].offset) : 0;
2516
+ if (this.rendered && story !== this.rendered.story) {
2517
+ this.beforeStep = this.rendered;
2518
+ }
2519
+ this.rendered = { story, neighbors: shown };
2520
+ return shown;
2521
+ }
2522
+ /**
2523
+ * The player <dialog> while it is open. Clicking the video also plays or
2524
+ * pauses it, and keeps the focus in the player (the dialog is focusable,
2525
+ * though not by Tab), so the arrow keys still step. With `navigation`
2526
+ * (more than one Story), it has previous and next buttons and arrow keys,
2527
+ * and the expanded view moves on when the video ends instead of looping.
2528
+ * The expanded view also shows the `neighbors` beside it.
2529
+ */
2530
+ render(story, {
2531
+ labels,
2532
+ navigation = false,
2533
+ neighbors = [],
2534
+ product,
2535
+ cta,
2536
+ onPress
2537
+ }) {
2538
+ if (!this.isOpen) return nothing4;
2539
+ const { video, expanded } = this;
2540
+ const shownNeighbors = this.track(story, neighbors);
2541
+ const pair = this.pairDirection !== 0;
2542
+ this.navigation = navigation;
2543
+ return html6`
2544
+ <dialog
2545
+ class="player"
2546
+ popover="manual"
2547
+ aria-label=${labels.player}
2548
+ ?data-expanded=${expanded}
2549
+ ?data-pair=${pair}
2550
+ style=${styleMap2({
2551
+ "--pair-dir": pair ? String(this.pairDirection) : void 0
2552
+ })}
2553
+ ?data-switched=${this.switched}
2554
+ ?data-paused=${hasVideo(story, video) && video.paused}
2555
+ tabindex="-1"
2556
+ ${ref3(this.dialog)}
2557
+ @click=${this.onDialogClick}
2558
+ @cancel=${this.onCancel}
2559
+ @keydown=${this.onPlayerKeyDown}
2560
+ >
2561
+ ${this.renderNeighbors(shownNeighbors, labels)}
2562
+ <div class="player-frame">
2563
+ ${this.renderWindowControls(labels)}
2564
+ <div
2565
+ class="player-stage"
2566
+ ${ref3(this.stage)}
2567
+ @click=${{
2568
+ handleEvent: (event) => {
2569
+ const card = this.stageCardRef.value;
2570
+ if (card == null ? void 0 : card.contains(event.target)) onPress == null ? void 0 : onPress();
2571
+ },
2572
+ capture: true
2573
+ }}
2574
+ >
2575
+ ${navigation ? this.renderNavigation(labels) : nothing4}
2576
+ ${this.renderVideo(story, navigation && expanded, {
2577
+ product,
2578
+ cta,
2579
+ labels
2580
+ })}
2581
+ <span class="player-dim" aria-hidden="true" ${ref3(this.dim)}></span>
2582
+ </div>
2583
+ </div>
2584
+ </dialog>
2585
+ `;
2586
+ }
2587
+ };
2588
+
2589
+ // src/utils/hydrate-products.ts
2590
+ import {
2591
+ hydrateAds,
2592
+ intelligentSearchAvailability,
2593
+ intelligentSearchFetcher,
2594
+ intelligentSearchMatcher,
2595
+ intelligentSearchPrice
2596
+ } from "@vtex/ads-core";
2597
+
2598
+ // src/utils/with-timeout.ts
2599
+ var withTimeout = (timeout, fallback, signal) => {
2600
+ const ms = timeout !== void 0 && Number.isFinite(timeout) && timeout > 0 ? timeout : fallback;
2601
+ const controller = new AbortController();
2602
+ const timer = setTimeout(
2603
+ () => controller.abort(
2604
+ new DOMException(`Timed out after ${ms} ms`, "TimeoutError")
2605
+ ),
2606
+ ms
2607
+ );
2608
+ const onAbort = () => controller.abort(signal == null ? void 0 : signal.reason);
2609
+ if (signal == null ? void 0 : signal.aborted) {
2610
+ onAbort();
2611
+ } else {
2612
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2613
+ }
2614
+ return {
2615
+ signal: controller.signal,
2616
+ clear: () => {
2617
+ clearTimeout(timer);
2618
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2619
+ }
2620
+ };
2621
+ };
2622
+
2623
+ // src/utils/hydrate-products.ts
2624
+ var DEFAULT_HYDRATION_TIMEOUT_MS = 5e3;
2625
+ var intelligentSearchHydration = {
2626
+ fetcher: intelligentSearchFetcher,
2627
+ matcher: intelligentSearchMatcher,
2628
+ price: intelligentSearchPrice,
2629
+ available: intelligentSearchAvailability
2630
+ };
2631
+ async function hydrateStoryProducts(placement, stories, hydration, identity, { signal, timeout } = {}) {
2632
+ var _a, _b;
2633
+ const products = /* @__PURE__ */ new Map();
2634
+ const limit = withTimeout(timeout, DEFAULT_HYDRATION_TIMEOUT_MS, signal);
2635
+ try {
2636
+ const hydrated = await hydrateAds(
2637
+ { stories: { [placement]: stories } },
2638
+ hydration.fetcher,
2639
+ (product, offer) => hydration.matcher(product, offer),
2640
+ identity,
2641
+ { signal: limit.signal }
515
2642
  );
516
- expand.replaceChildren(createIcon(expanded ? "collapse" : "expand"));
517
- if (expanded) player.showModal();
518
- else showPlayer(player);
519
- expand.focus();
520
- });
521
- close.addEventListener("click", options.onClose);
522
- player.addEventListener("click", (event) => {
523
- if (expanded && event.target === player) options.onClose();
524
- });
525
- player.addEventListener("cancel", (event) => {
526
- event.preventDefault();
527
- options.onClose();
528
- });
529
- const card = createCard(story);
530
- const video = card.querySelector("video");
531
- if (video) addVideoControls(player, card, video, options);
532
- frame.append(controls, card);
533
- player.append(frame);
534
- return player;
2643
+ for (const { story, product, offer } of (_a = hydrated.stories[placement]) != null ? _a : []) {
2644
+ if (!product || !offer) continue;
2645
+ const price = hydration.price(product, offer);
2646
+ const available = (_b = hydration.available) == null ? void 0 : _b.call(hydration, product, offer);
2647
+ products.set(story.ad_id, {
2648
+ ...price && { price },
2649
+ ...available !== void 0 && { available }
2650
+ });
2651
+ }
2652
+ } catch (error) {
2653
+ if (!limit.signal.aborted) {
2654
+ console.error(`[${TAG_NAME}] Product request failed`, error);
2655
+ }
2656
+ } finally {
2657
+ limit.clear();
2658
+ }
2659
+ return products;
535
2660
  }
536
2661
 
537
- // src/story/story.ts
538
- var TAG_NAME = "vtex-ads-story";
539
- var _a;
540
- var BaseElement = (_a = globalThis.HTMLElement) != null ? _a : Object;
541
- var styles = `
542
- :host {
543
- display: block;
544
- font-family: var(--vtex-ads-story-font-family, inherit);
545
- color: var(--vtex-ads-story-color-text, inherit);
2662
+ // src/utils/fetch-story.ts
2663
+ import { getRawAds } from "@vtex/ads-core";
2664
+ var DEFAULT_TIMEOUT_MS = 2e3;
2665
+ var DEFAULT_QUANTITY = 8;
2666
+ var toQuantity = (quantity) => quantity !== void 0 && Number.isFinite(quantity) && quantity >= 1 ? Math.floor(quantity) : DEFAULT_QUANTITY;
2667
+ async function fetchStories({
2668
+ publisherId,
2669
+ sessionId,
2670
+ placement,
2671
+ userId,
2672
+ accountName,
2673
+ channel,
2674
+ quantity
2675
+ }, { signal, timeout } = {}) {
2676
+ var _a;
2677
+ const onServer = globalThis.window === void 0;
2678
+ if (onServer || !publisherId || !sessionId || !placement) return [];
2679
+ const limit = withTimeout(timeout, DEFAULT_TIMEOUT_MS, signal);
2680
+ const count = toQuantity(quantity);
2681
+ try {
2682
+ const { stories } = await getRawAds(
2683
+ {
2684
+ identity: {
2685
+ accountName: accountName != null ? accountName : "",
2686
+ publisherId,
2687
+ sessionId,
2688
+ userId,
2689
+ channel
2690
+ },
2691
+ search: {},
2692
+ placements: {
2693
+ [placement]: { quantity: count, types: ["story"] }
2694
+ }
2695
+ },
2696
+ { signal: limit.signal }
2697
+ );
2698
+ return ((_a = stories[placement]) != null ? _a : []).slice(0, count);
2699
+ } catch (error) {
2700
+ if (!limit.signal.aborted) {
2701
+ console.error(`[${TAG_NAME}] Story request failed`, {
2702
+ placement,
2703
+ publisherId,
2704
+ error
2705
+ });
2706
+ }
2707
+ return [];
2708
+ } finally {
2709
+ limit.clear();
546
2710
  }
547
- ${cardStyles}
548
- ${playerStyles}
549
- `;
550
- var PLACEHOLDER_STORY = {
551
- poster_url: "https://dummyimage.com/1080x1920/e31c57/fff",
552
- media_url: "https://samplelib.com/mp4/sample-10s-vp9.mp4"
2711
+ }
2712
+
2713
+ // src/locales/en.ts
2714
+ var en = {
2715
+ watch: "Watch video",
2716
+ show: "Show video",
2717
+ carousel: "Videos",
2718
+ carouselRole: "carousel",
2719
+ previous: "Previous video",
2720
+ next: "Next video",
2721
+ player: "Video",
2722
+ expand: "Expand video",
2723
+ collapse: "Collapse video",
2724
+ close: "Close video",
2725
+ play: "Play video",
2726
+ pause: "Pause video",
2727
+ soundOn: "Turn sound on",
2728
+ soundOff: "Turn sound off",
2729
+ addToCart: "Add to cart",
2730
+ unavailable: "Product unavailable",
2731
+ soldOut: "Sold out",
2732
+ viewProduct: "View product",
2733
+ product: (name, price, listPrice) => {
2734
+ if (price && listPrice) return `${name}, was ${listPrice}, now ${price}`;
2735
+ return price ? `${name}, ${price}` : name;
2736
+ },
2737
+ position: (label, index, count) => count > 1 ? `${label} ${index + 1} of ${count}` : label
2738
+ };
2739
+
2740
+ // src/locales/es.ts
2741
+ var es = {
2742
+ watch: "Ver video",
2743
+ show: "Mostrar video",
2744
+ carousel: "Videos",
2745
+ carouselRole: "carrusel",
2746
+ previous: "Video anterior",
2747
+ next: "Video siguiente",
2748
+ player: "Video",
2749
+ expand: "Ampliar video",
2750
+ collapse: "Reducir video",
2751
+ close: "Cerrar video",
2752
+ play: "Reproducir video",
2753
+ pause: "Pausar video",
2754
+ soundOn: "Activar sonido",
2755
+ soundOff: "Desactivar sonido",
2756
+ addToCart: "Agregar al carrito",
2757
+ unavailable: "Producto no disponible",
2758
+ soldOut: "Agotado",
2759
+ viewProduct: "Ver producto",
2760
+ product: (name, price, listPrice) => {
2761
+ if (price && listPrice)
2762
+ return `${name}, antes ${listPrice}, ahora ${price}`;
2763
+ return price ? `${name}, ${price}` : name;
2764
+ },
2765
+ position: (label, index, count) => count > 1 ? `${label} ${index + 1} de ${count}` : label
553
2766
  };
554
- var LABELS = {
2767
+
2768
+ // src/locales/pt.ts
2769
+ var pt = {
555
2770
  watch: "Assistir v\xEDdeo",
2771
+ show: "Mostrar v\xEDdeo",
2772
+ carousel: "V\xEDdeos",
2773
+ carouselRole: "carrossel",
2774
+ previous: "V\xEDdeo anterior",
2775
+ next: "Pr\xF3ximo v\xEDdeo",
556
2776
  player: "V\xEDdeo",
557
2777
  expand: "Expandir v\xEDdeo",
558
2778
  collapse: "Reduzir v\xEDdeo",
@@ -560,89 +2780,397 @@ var LABELS = {
560
2780
  play: "Reproduzir v\xEDdeo",
561
2781
  pause: "Pausar v\xEDdeo",
562
2782
  soundOn: "Ativar som",
563
- soundOff: "Desativar som"
2783
+ soundOff: "Desativar som",
2784
+ addToCart: "Adicionar ao carrinho",
2785
+ unavailable: "Produto indispon\xEDvel",
2786
+ soldOut: "Esgotado",
2787
+ viewProduct: "Ver produto",
2788
+ product: (name, price, listPrice) => {
2789
+ if (price && listPrice) return `${name}, de ${listPrice} por ${price}`;
2790
+ return price ? `${name}, ${price}` : name;
2791
+ },
2792
+ position: (label, index, count) => count > 1 ? `${label} ${index + 1} de ${count}` : label
2793
+ };
2794
+
2795
+ // src/locales/index.ts
2796
+ var BY_LANGUAGE = /* @__PURE__ */ new Map([
2797
+ ["pt", pt],
2798
+ ["es", es],
2799
+ ["en", en]
2800
+ ]);
2801
+ function labelsFor(locale, overrides = {}) {
2802
+ var _a, _b, _c;
2803
+ const language = locale.split("-")[0].toLowerCase();
2804
+ const labels = (_a = BY_LANGUAGE.get(language)) != null ? _a : pt;
2805
+ const addToCart = (_b = overrides.addToCart) == null ? void 0 : _b.trim();
2806
+ const viewProduct = (_c = overrides.viewProduct) == null ? void 0 : _c.trim();
2807
+ return {
2808
+ ...labels,
2809
+ ...addToCart && { addToCart },
2810
+ ...viewProduct && { viewProduct }
2811
+ };
2812
+ }
2813
+
2814
+ // src/story/story.ts
2815
+ var REQUEST_PROPERTIES = [
2816
+ "publisherId",
2817
+ "sessionId",
2818
+ "placement",
2819
+ "userId",
2820
+ "accountName",
2821
+ "channel",
2822
+ "quantity",
2823
+ "hydration"
2824
+ ];
2825
+ var CHANNELS = /* @__PURE__ */ new Set(["site", "app"]);
2826
+ var isChannel = (value) => CHANNELS.has(value);
2827
+ var booleanConverter = {
2828
+ fromAttribute: (value) => typeof value === "string" && (value === "" || value.toLowerCase() === "true")
2829
+ };
2830
+ var channelConverter = {
2831
+ fromAttribute: (value) => isChannel(value) ? value : void 0
564
2832
  };
565
- var VtexAdsStoryElement = class extends BaseElement {
2833
+ var hydrationConverter = {
2834
+ fromAttribute: (value) => value === "none" ? "none" : void 0
2835
+ };
2836
+ var VtexAdsStoryCarouselElement = class extends LitElement {
566
2837
  constructor() {
567
- super(...arguments);
568
- this.player = null;
569
- this.onKeyDown = (event) => {
570
- if (event.key === "Escape") this.closePlayer();
571
- };
2838
+ super();
2839
+ /**
2840
+ * One per rendered card, by its key (see Slide): a Story can show in more
2841
+ * than one card, each with its own video.
2842
+ */
2843
+ this.cardVideos = /* @__PURE__ */ new Map();
2844
+ /** The sound was on when the highlight moved: the new card turns it on. */
2845
+ this.soundPending = false;
2846
+ this.carousel = new CarouselController(this, {
2847
+ onStep: (from, to) => this.leaveHighlight(from, to),
2848
+ // Every card is new: so are their videos. Behind an open player, the
2849
+ // new highlighted card stays on its cover, as after a step.
2850
+ onLayoutChange: () => {
2851
+ this.cardVideos.clear();
2852
+ if (this.player.isOpen) {
2853
+ this.afterRender = () => {
2854
+ var _a;
2855
+ return (_a = this.activeVideo) == null ? void 0 : _a.pause();
2856
+ };
2857
+ }
2858
+ },
2859
+ // The player shows the highlighted Story: the highlight stays on it.
2860
+ locked: () => this.player.isOpen
2861
+ });
2862
+ this.player = new PlayerController(this, {
2863
+ onStep: (delta) => this.stepInPlayer(delta),
2864
+ onClose: () => this.closePlayer()
2865
+ });
2866
+ // Added after the carousel and the player: its hostUpdated reads what
2867
+ // they rendered.
2868
+ this.events = new StoryEventsController(this, {
2869
+ identity: () => ({ sessionId: this.sessionId, userId: this.userId }),
2870
+ viewTargets: () => this.viewTargets()
2871
+ });
2872
+ // The highlighted card opens the player; another one takes the highlight.
2873
+ // Hidden cards, out of sight, show only their cover.
2874
+ this.renderSlide = (story, { key, index, offset, active, hidden, cardRef, focusRef }) => renderCard(story, this.videoFor(key), {
2875
+ label: this.labels.position(
2876
+ active ? this.labels.watch : this.labels.show,
2877
+ index,
2878
+ this.stories.length
2879
+ ),
2880
+ labels: this.labels,
2881
+ withVideo: active || this.inactiveAutoplay && !hidden,
2882
+ product: this.productOf(story),
2883
+ onSelect: active ? () => this.openPlayer() : () => this.carousel.step(offset),
2884
+ // On a card without the highlight, the product moves it, as the card.
2885
+ onProductSelect: active ? () => this.openPlayer({ productOpen: true }) : void 0,
2886
+ // On the highlighted card it follows the link; on another, it moves the
2887
+ // highlight.
2888
+ cta: toCardCta(story),
2889
+ onCtaSelect: active ? void 0 : () => this.carousel.step(offset),
2890
+ onPress: () => this.events.click(story),
2891
+ ref: cardRef,
2892
+ openRef: focusRef
2893
+ });
2894
+ this.inactiveAutoplay = false;
2895
+ this.stories = [];
572
2896
  }
573
- render() {
574
- var _a2;
575
- const container = (_a2 = this.shadowRoot) == null ? void 0 : _a2.querySelector(".root");
576
- if (!container) return;
577
- container.replaceChildren(
578
- createCard(PLACEHOLDER_STORY, {
579
- label: LABELS.watch,
580
- soundOnLabel: LABELS.soundOn,
581
- soundOffLabel: LABELS.soundOff,
582
- onSelect: () => this.openPlayer()
583
- })
584
- );
2897
+ // Lit keeps the card's DOM when the element is moved (removed and appended
2898
+ // again), but the browser pauses a removed video and doesn't autoplay it
2899
+ // again. resume() only plays a video that autoplays (not with reduced
2900
+ // motion), and does nothing on the first connection, before the render.
2901
+ // Not in VideoController.hostConnected: there, the player's video is still
2902
+ // in the DOM until the next update and would play for a moment.
2903
+ connectedCallback() {
2904
+ var _a;
2905
+ super.connectedCallback();
2906
+ for (const video of this.cardVideos.values()) video.resume();
2907
+ if ((_a = this.request) == null ? void 0 : _a.signal.aborted) void this.loadStory();
585
2908
  }
586
- cardVideo() {
587
- var _a2;
588
- return (_a2 = this.shadowRoot) == null ? void 0 : _a2.querySelector(
589
- ".root .card video"
590
- );
2909
+ // A request still pending when the element leaves the page is cancelled.
2910
+ disconnectedCallback() {
2911
+ var _a;
2912
+ super.disconnectedCallback();
2913
+ (_a = this.request) == null ? void 0 : _a.abort();
591
2914
  }
592
- openPlayer() {
593
- var _a2, _b;
594
- if (this.player || !this.shadowRoot) return;
595
- this.player = createPlayer(PLACEHOLDER_STORY, {
596
- label: LABELS.player,
597
- expandLabel: LABELS.expand,
598
- collapseLabel: LABELS.collapse,
599
- closeLabel: LABELS.close,
600
- playLabel: LABELS.play,
601
- pauseLabel: LABELS.pause,
602
- soundOnLabel: LABELS.soundOn,
603
- soundOffLabel: LABELS.soundOff,
604
- onClose: () => this.closePlayer()
2915
+ willUpdate(changed) {
2916
+ if (REQUEST_PROPERTIES.some((name) => changed.has(name))) {
2917
+ void this.loadStory();
2918
+ }
2919
+ }
2920
+ updated() {
2921
+ const afterRender = this.afterRender;
2922
+ this.afterRender = void 0;
2923
+ afterRender == null ? void 0 : afterRender();
2924
+ }
2925
+ // The strategy for the products' details, if any (see `hydration`).
2926
+ get activeHydration() {
2927
+ if (this.hydration === "none") return void 0;
2928
+ if (this.hydration) return this.hydration;
2929
+ return this.accountName ? intelligentSearchHydration : void 0;
2930
+ }
2931
+ /**
2932
+ * Requests the Story and shows it, then hydrates its products. Until the
2933
+ * Story arrives, and when there is none (see fetchStories), the element
2934
+ * renders nothing.
2935
+ */
2936
+ async loadStory() {
2937
+ var _a, _b, _c, _d, _e;
2938
+ (_a = this.request) == null ? void 0 : _a.abort();
2939
+ const request = new AbortController();
2940
+ this.request = request;
2941
+ this.player.close();
2942
+ this.showStories([]);
2943
+ if (!this.isConnected) {
2944
+ request.abort();
2945
+ return;
2946
+ }
2947
+ const stories = await fetchStories(this, {
2948
+ signal: request.signal,
2949
+ timeout: this.timeout
605
2950
  });
606
- this.shadowRoot.append(this.player);
607
- showPlayer(this.player);
608
- (_a2 = this.cardVideo()) == null ? void 0 : _a2.pause();
609
- playPlayer(this.player);
610
- document.addEventListener("keydown", this.onKeyDown);
611
- (_b = this.player.querySelector(".player-close")) == null ? void 0 : _b.focus();
2951
+ if (request.signal.aborted) return;
2952
+ const hydration = this.activeHydration;
2953
+ if (!hydration || !stories.some((story) => story.product)) {
2954
+ this.request = void 0;
2955
+ this.showStories(stories);
2956
+ return;
2957
+ }
2958
+ this.showStories(stories, "loading");
2959
+ const products = await hydrateStoryProducts(
2960
+ (_b = this.placement) != null ? _b : "",
2961
+ stories,
2962
+ hydration,
2963
+ {
2964
+ accountName: (_c = this.accountName) != null ? _c : "",
2965
+ publisherId: (_d = this.publisherId) != null ? _d : "",
2966
+ sessionId: (_e = this.sessionId) != null ? _e : "",
2967
+ userId: this.userId,
2968
+ channel: this.channel
2969
+ },
2970
+ { signal: request.signal, timeout: this.hydrationTimeout }
2971
+ );
2972
+ if (request.signal.aborted) return;
2973
+ this.request = void 0;
2974
+ this.products = products;
612
2975
  }
613
- // `removed`: the element is leaving the page, so there is no card to give
614
- // focus back to or to resume playing (it would play out of sight).
615
- closePlayer({ removed = false } = {}) {
616
- var _a2, _b;
617
- if (!this.player) return;
618
- document.removeEventListener("keydown", this.onKeyDown);
619
- this.player.remove();
620
- this.player = null;
621
- if (removed) return;
622
- const video = this.cardVideo();
623
- if (video == null ? void 0 : video.autoplay) playVideo(video);
624
- (_b = (_a2 = this.shadowRoot) == null ? void 0 : _a2.querySelector(".root .card-open")) == null ? void 0 : _b.focus();
2976
+ // Each card's video starts fresh: a failed load of an old one doesn't hide
2977
+ // it.
2978
+ showStories(stories, products) {
2979
+ this.products = products;
2980
+ this.cardVideos.clear();
2981
+ this.soundPending = false;
2982
+ this.afterRender = void 0;
2983
+ this.carousel.reset(stories.length);
2984
+ this.stories = stories;
2985
+ this.events.impress(stories);
625
2986
  }
626
- connectedCallback() {
627
- if (!this.shadowRoot) {
628
- const root = this.attachShadow({ mode: "open" });
629
- root.innerHTML = `<style>${styles}</style><div class="root"></div>`;
2987
+ /**
2988
+ * Where each Story is being watched: the cards on screen (not the hidden
2989
+ * ones kept for the slide in) and the open player's video, while their
2990
+ * video plays. A card showing only its cover doesn't count. Behind the
2991
+ * expanded player, a modal over the page, the cards are covered.
2992
+ */
2993
+ *viewTargets() {
2994
+ var _a;
2995
+ const { stories } = this;
2996
+ if (!this.player.isExpanded) {
2997
+ for (const [card, { key, index }] of this.carousel.visibleCards()) {
2998
+ const story = stories[index];
2999
+ if (story && ((_a = this.cardVideos.get(key)) == null ? void 0 : _a.playing)) yield [card, story];
3000
+ }
3001
+ }
3002
+ const stageCard = this.player.stageCard;
3003
+ const active = stories[this.carousel.active];
3004
+ if (stageCard && active && this.player.video.playing) {
3005
+ yield [stageCard, active];
630
3006
  }
631
- this.render();
632
3007
  }
633
- disconnectedCallback() {
634
- this.closePlayer({ removed: true });
3008
+ videoFor(key) {
3009
+ let video = this.cardVideos.get(key);
3010
+ if (!video) {
3011
+ video = new VideoController(this);
3012
+ this.cardVideos.set(key, video);
3013
+ }
3014
+ return video;
3015
+ }
3016
+ get activeVideo() {
3017
+ return this.cardVideos.get(this.carousel.activeKey);
635
3018
  }
3019
+ // The card losing the highlight goes quiet: muted if it keeps playing, or
3020
+ // back to its cover. Its next video then starts fresh. If its sound was
3021
+ // on, the sound moves to the new highlighted card, once its video renders.
3022
+ // With the player open (it stepped), the new card stays on its cover
3023
+ // behind it instead. Cards no longer rendered (the rolling layout drops
3024
+ // them as it moves) leave with their videos.
3025
+ leaveHighlight(from, to) {
3026
+ const video = this.cardVideos.get(from);
3027
+ this.soundPending || (this.soundPending = video !== void 0 && !video.muted);
3028
+ if (this.inactiveAutoplay) video == null ? void 0 : video.mute();
3029
+ else video == null ? void 0 : video.reset();
3030
+ if (this.player.isOpen) {
3031
+ this.soundPending = false;
3032
+ this.afterRender = () => this.videoFor(to).pause();
3033
+ } else if (this.soundPending) {
3034
+ this.afterRender = () => {
3035
+ this.soundPending = false;
3036
+ this.videoFor(to).playWithSound();
3037
+ };
3038
+ }
3039
+ for (const key of this.cardVideos.keys()) {
3040
+ if (Math.abs(key - to) > RENDERED_SIDE) this.cardVideos.delete(key);
3041
+ }
3042
+ }
3043
+ // The player's previous and next buttons: the highlight moves with the
3044
+ // Story the player shows.
3045
+ stepInPlayer(delta) {
3046
+ this.carousel.step(delta, { evenIfLocked: true });
3047
+ void this.player.showNext(delta);
3048
+ }
3049
+ // From the card's product, the player opens with the product panel open.
3050
+ openPlayer({ productOpen = false } = {}) {
3051
+ var _a;
3052
+ if (this.player.isOpen) return;
3053
+ (_a = this.activeVideo) == null ? void 0 : _a.pause();
3054
+ void this.player.open({ productOpen });
3055
+ }
3056
+ // The player also closes on its own when the element leaves the page,
3057
+ // without this: there is no card to give focus back to or to resume playing
3058
+ // (it would play out of sight).
3059
+ closePlayer() {
3060
+ if (!this.player.isOpen) return;
3061
+ this.player.close();
3062
+ for (const video of this.cardVideos.values()) video.resume();
3063
+ this.carousel.focusActive();
3064
+ }
3065
+ // Prices and texts follow the language of the closest element with a
3066
+ // `lang`, the element itself included, so a store can set one for the
3067
+ // widget alone. An empty `lang` (unknown) is skipped; none, or an unknown
3068
+ // one, falls back to pt-BR.
3069
+ get locale() {
3070
+ var _a, _b;
3071
+ return (_b = (_a = this.closest('[lang]:not([lang=""])')) == null ? void 0 : _a.lang) != null ? _b : DEFAULT_LOCALE;
3072
+ }
3073
+ get labels() {
3074
+ var _a;
3075
+ const { locale, labelAddToCart = "", labelViewProduct = "" } = this;
3076
+ const key = JSON.stringify([locale, labelAddToCart, labelViewProduct]);
3077
+ if (((_a = this.labelSet) == null ? void 0 : _a.key) !== key) {
3078
+ this.labelSet = {
3079
+ key,
3080
+ labels: labelsFor(locale, {
3081
+ addToCart: labelAddToCart,
3082
+ viewProduct: labelViewProduct
3083
+ })
3084
+ };
3085
+ }
3086
+ return this.labelSet.labels;
3087
+ }
3088
+ get formatPrice() {
3089
+ var _a, _b;
3090
+ const { locale } = this;
3091
+ const key = `${locale}|${(_a = this.currency) != null ? _a : ""}`;
3092
+ if (((_b = this.formatter) == null ? void 0 : _b.key) !== key) {
3093
+ this.formatter = { key, format: priceFormatter(locale, this.currency) };
3094
+ }
3095
+ return this.formatter.format;
3096
+ }
3097
+ productOf(story) {
3098
+ var _a;
3099
+ const fetched = this.products === "loading" ? "loading" : (_a = this.products) == null ? void 0 : _a.get(story.ad_id);
3100
+ return toCardProduct(story, this.formatPrice, this.labels, fetched);
3101
+ }
3102
+ render() {
3103
+ const { stories } = this;
3104
+ const index = this.carousel.active;
3105
+ const active = stories[index];
3106
+ if (!active) return nothing5;
3107
+ const neighbors = neighborOffsets(stories.length, index).map((offset) => {
3108
+ const neighbor = (index + offset + stories.length) % stories.length;
3109
+ return {
3110
+ offset,
3111
+ story: stories[neighbor],
3112
+ label: this.labels.position(this.labels.show, neighbor, stories.length)
3113
+ };
3114
+ });
3115
+ return html7`
3116
+ <div class="root">
3117
+ ${this.carousel.render(stories, this.renderSlide, this.labels)}
3118
+ </div>
3119
+ ${this.player.render(active, {
3120
+ labels: this.labels,
3121
+ navigation: stories.length > 1,
3122
+ neighbors,
3123
+ product: this.productOf(active),
3124
+ cta: toCardCta(active),
3125
+ onPress: () => this.events.click(active)
3126
+ })}
3127
+ `;
3128
+ }
3129
+ };
3130
+ VtexAdsStoryCarouselElement.properties = {
3131
+ publisherId: { attribute: "publisher-id" },
3132
+ sessionId: { attribute: "session-id" },
3133
+ placement: {},
3134
+ userId: { attribute: "user-id" },
3135
+ accountName: { attribute: "account-name" },
3136
+ channel: { converter: channelConverter },
3137
+ timeout: { type: Number },
3138
+ quantity: { type: Number },
3139
+ currency: {},
3140
+ labelAddToCart: { attribute: "label-add-to-cart" },
3141
+ labelViewProduct: { attribute: "label-view-product" },
3142
+ hydration: { converter: hydrationConverter },
3143
+ hydrationTimeout: { type: Number, attribute: "hydration-timeout" },
3144
+ inactiveAutoplay: {
3145
+ type: Boolean,
3146
+ attribute: "inactive-autoplay",
3147
+ converter: booleanConverter
3148
+ },
3149
+ stories: { state: true },
3150
+ products: { state: true }
636
3151
  };
637
- function defineVtexAdsStories() {
3152
+ VtexAdsStoryCarouselElement.styles = [
3153
+ css5`
3154
+ :host {
3155
+ display: block;
3156
+ font-family: var(--vtex-ads-story-font-family, inherit);
3157
+ color: var(--vtex-ads-story-color-text, inherit);
3158
+ }
3159
+ `,
3160
+ cardStyles,
3161
+ productStyles,
3162
+ carouselStyles,
3163
+ playerStyles
3164
+ ];
3165
+ function defineVtexAdsStoryCarousel() {
638
3166
  if (typeof customElements === "undefined") return;
639
3167
  if (customElements.get(TAG_NAME)) return;
640
- customElements.define(TAG_NAME, VtexAdsStoryElement);
3168
+ customElements.define(TAG_NAME, VtexAdsStoryCarouselElement);
641
3169
  }
642
3170
  export {
643
3171
  TAG_NAME,
644
- VtexAdsStoryElement,
645
- defineVtexAdsStories
3172
+ VtexAdsStoryCarouselElement,
3173
+ defineVtexAdsStoryCarousel
646
3174
  };
647
3175
  /*! Icons from Phosphor Icons (https://phosphoricons.com), MIT License, Copyright (c) 2023 Phosphor Icons */
648
3176
  //# sourceMappingURL=index.js.map