@vtex/ads-stories 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +44 -88
  3. package/dist/cdn/vtex-ads-stories.js +1313 -74
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +3744 -513
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +46 -15
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +51 -5
  10. package/dist/cjs/story-DAiAN9v-.d.cts +260 -0
  11. package/dist/esm/index.d.ts +46 -15
  12. package/dist/esm/index.js +3348 -217
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/react.d.ts +51 -5
  15. package/dist/esm/story-DAiAN9v-.d.ts +260 -0
  16. package/package.json +18 -4
  17. package/src/cdn.ts +7 -3
  18. package/src/commerce-events.ts +93 -0
  19. package/src/components/card/card.ts +79 -14
  20. package/src/components/carousel/carousel-skeleton.ts +113 -0
  21. package/src/components/carousel/carousel.ts +715 -0
  22. package/src/components/carousel/index.ts +22 -0
  23. package/src/components/events/events-controller.ts +222 -0
  24. package/src/components/events/index.ts +6 -0
  25. package/src/components/icons/assets/caret-left-bold.svg +1 -0
  26. package/src/components/icons/assets/caret-right-bold.svg +1 -0
  27. package/src/components/icons/assets/caret-up-bold.svg +1 -0
  28. package/src/components/icons/assets/minus.svg +1 -0
  29. package/src/components/icons/assets/plus.svg +1 -0
  30. package/src/components/icons/assets/trash.svg +1 -0
  31. package/src/components/icons/assets/warning-circle-fill.svg +1 -0
  32. package/src/components/icons/index.ts +14 -0
  33. package/src/components/media/index.ts +8 -1
  34. package/src/components/media/media.styles.ts +113 -0
  35. package/src/components/media/media.ts +124 -23
  36. package/src/components/media/video-controller.ts +127 -6
  37. package/src/components/player/index.ts +6 -2
  38. package/src/components/player/player.ts +824 -50
  39. package/src/components/product/cta.ts +56 -0
  40. package/src/components/product/index.ts +22 -0
  41. package/src/components/product/price.ts +86 -0
  42. package/src/components/product/product.styles.ts +426 -0
  43. package/src/components/product/product.ts +336 -0
  44. package/src/index.ts +17 -1
  45. package/src/locales/en.ts +39 -0
  46. package/src/locales/es.ts +40 -0
  47. package/src/locales/index.ts +36 -0
  48. package/src/locales/pt.ts +39 -0
  49. package/src/locales/types.ts +44 -0
  50. package/src/react.ts +55 -7
  51. package/src/story/index.ts +5 -1
  52. package/src/story/story.ts +679 -49
  53. package/src/tag-name.ts +1 -0
  54. package/src/types.ts +8 -12
  55. package/src/utils/fetch-story.ts +113 -0
  56. package/src/utils/hydrate-products.ts +112 -0
  57. package/src/utils/media-ready.ts +58 -0
  58. package/src/utils/safe-url.ts +36 -0
  59. package/src/utils/send-event.ts +71 -0
  60. package/src/utils/with-timeout.ts +43 -0
package/dist/esm/index.js CHANGED
@@ -1,44 +1,73 @@
1
1
  // src/story/story.ts
2
- import { css as css3, html as html4, LitElement } from "lit";
2
+ import { css as css7, html as html8, LitElement, nothing as nothing5 } from "lit";
3
3
 
4
4
  // src/components/card/card.ts
5
- import { css, html as html2, nothing as nothing2 } from "lit";
5
+ import { css as css3, html as html4, nothing as nothing3 } from "lit";
6
+ import { ref as ref2 } from "lit/directives/ref.js";
6
7
 
7
8
  // src/components/icons/index.ts
8
9
  import {
9
10
  unsafeHTML
10
11
  } from "lit/directives/unsafe-html.js";
11
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
+
12
19
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/close.svg
13
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';
14
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
+
15
25
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/collapse.svg
16
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';
17
27
 
18
28
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/expand.svg
19
29
  var expand_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48V88a8,8,0,0,1-16,0V56H168a8,8,0,0,1,0-16h40A8,8,0,0,1,216,48ZM88,200H56V168a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H88a8,8,0,0,0,0-16Zm120-40a8,8,0,0,0-8,8v32H168a8,8,0,0,0,0,16h40a8,8,0,0,0,8-8V168A8,8,0,0,0,208,160ZM88,40H48a8,8,0,0,0-8,8V88a8,8,0,0,0,16,0V56H88a8,8,0,0,0,0-16Z"/></svg>\n';
20
30
 
31
+ // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/minus.svg
32
+ var minus_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128Z"/></svg>';
33
+
21
34
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/pause-fill.svg
22
35
  var pause_fill_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></svg>\n';
23
36
 
24
37
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/play-fill.svg
25
38
  var play_fill_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></svg>\n';
26
39
 
40
+ // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/plus.svg
41
+ var plus_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z"/></svg>';
42
+
27
43
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/speaker-x-fill.svg
28
44
  var speaker_x_fill_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M245.66,146.34a8,8,0,0,1-11.32,11.32L216,139.31l-18.34,18.35a8,8,0,0,1-11.32-11.32L204.69,128l-18.35-18.34a8,8,0,0,1,11.32-11.32L216,116.69l18.34-18.35a8,8,0,0,1,11.32,11.32L227.31,128ZM60,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H60a4,4,0,0,0,4-4V84A4,4,0,0,0,60,80Zm97.15-54.15a8,8,0,0,0-10-.16l-65.57,51A4,4,0,0,0,80,79.84v96.32a4,4,0,0,0,1.55,3.15l65.57,51a8,8,0,0,0,9,.56,8.29,8.29,0,0,0,3.91-7.18V32.25A8.27,8.27,0,0,0,157.12,25.85Z"/></svg>\n';
29
45
 
30
46
  // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/speaker-high-fill.svg
31
47
  var speaker_high_fill_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M160,32.25V223.69a8.29,8.29,0,0,1-3.91,7.18,8,8,0,0,1-9-.56l-65.57-51A4,4,0,0,1,80,176.16V79.84a4,4,0,0,1,1.55-3.15l65.57-51a8,8,0,0,1,10,.16A8.27,8.27,0,0,1,160,32.25ZM60,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H60a4,4,0,0,0,4-4V84A4,4,0,0,0,60,80Zm126.77,20.84a8,8,0,0,0-.72,11.3,24,24,0,0,1,0,31.72,8,8,0,1,0,12,10.58,40,40,0,0,0,0-52.88A8,8,0,0,0,186.74,100.84Zm40.89-26.17a8,8,0,1,0-11.92,10.66,64,64,0,0,1,0,85.34,8,8,0,1,0,11.92,10.66,80,80,0,0,0,0-106.66Z"/></svg>\n';
32
48
 
49
+ // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/trash.svg
50
+ var trash_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z"/></svg>';
51
+
52
+ // raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/warning-circle-fill.svg
53
+ var warning_circle_fill_default = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-8,56a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm8,104a12,12,0,1,1,12-12A12,12,0,0,1,128,184Z"/></svg>\n';
54
+
33
55
  // src/components/icons/index.ts
34
56
  var icons = {
57
+ caretUp: caret_up_bold_default,
35
58
  close: close_default,
36
59
  collapse: collapse_default,
37
60
  expand: expand_default,
61
+ minus: minus_default,
62
+ next: caret_right_bold_default,
38
63
  pause: pause_fill_default,
39
64
  play: play_fill_default,
65
+ plus: plus_default,
66
+ previous: caret_left_bold_default,
40
67
  soundOff: speaker_x_fill_default,
41
- soundOn: speaker_high_fill_default
68
+ soundOn: speaker_high_fill_default,
69
+ trash: trash_default,
70
+ warning: warning_circle_fill_default
42
71
  };
43
72
  var markup = Object.fromEntries(
44
73
  Object.entries(icons).map(([name, svg]) => [
@@ -56,6 +85,139 @@ function icon(name) {
56
85
  // src/components/media/media.ts
57
86
  import { html, nothing } from "lit";
58
87
  import { ref } from "lit/directives/ref.js";
88
+
89
+ // src/locales/en.ts
90
+ var en = {
91
+ watch: "Watch video",
92
+ show: "Show video",
93
+ carousel: "Videos",
94
+ carouselRole: "carousel",
95
+ previous: "Previous video",
96
+ next: "Next video",
97
+ player: "Video",
98
+ expand: "Expand video",
99
+ collapse: "Collapse video",
100
+ close: "Close video",
101
+ play: "Play video",
102
+ pause: "Pause video",
103
+ soundOn: "Turn sound on",
104
+ soundOff: "Turn sound off",
105
+ addToCart: "Add to cart",
106
+ cartQuantity: "Quantity in cart",
107
+ decreaseQuantity: "Decrease quantity",
108
+ removeFromCart: "Remove from cart",
109
+ increaseQuantity: "Increase quantity",
110
+ unavailable: "Product unavailable",
111
+ soldOut: "Sold out",
112
+ viewProduct: "View product",
113
+ videoUnavailable: "Video unavailable",
114
+ videoFailed: "Couldn't load the video",
115
+ retry: "Try again",
116
+ videoLoading: "Loading video",
117
+ product: (name, price, listPrice, soldOut) => {
118
+ let text = name;
119
+ if (price && listPrice) text = `${name}, was ${listPrice}, now ${price}`;
120
+ else if (price) text = `${name}, ${price}`;
121
+ return soldOut ? `${text}, ${soldOut}` : text;
122
+ },
123
+ position: (label, index, count) => count > 1 ? `${label} ${index + 1} of ${count}` : label
124
+ };
125
+
126
+ // src/locales/es.ts
127
+ var es = {
128
+ watch: "Ver video",
129
+ show: "Mostrar video",
130
+ carousel: "Videos",
131
+ carouselRole: "carrusel",
132
+ previous: "Video anterior",
133
+ next: "Video siguiente",
134
+ player: "Video",
135
+ expand: "Ampliar video",
136
+ collapse: "Reducir video",
137
+ close: "Cerrar video",
138
+ play: "Reproducir video",
139
+ pause: "Pausar video",
140
+ soundOn: "Activar sonido",
141
+ soundOff: "Desactivar sonido",
142
+ addToCart: "Agregar al carrito",
143
+ cartQuantity: "Cantidad en el carrito",
144
+ decreaseQuantity: "Disminuir cantidad",
145
+ removeFromCart: "Quitar del carrito",
146
+ increaseQuantity: "Aumentar cantidad",
147
+ unavailable: "Producto no disponible",
148
+ soldOut: "Agotado",
149
+ viewProduct: "Ver producto",
150
+ videoUnavailable: "Video no disponible",
151
+ videoFailed: "No se pudo cargar el video",
152
+ retry: "Intentar de nuevo",
153
+ videoLoading: "Cargando video",
154
+ product: (name, price, listPrice, soldOut) => {
155
+ let text = name;
156
+ if (price && listPrice)
157
+ text = `${name}, antes ${listPrice}, ahora ${price}`;
158
+ else if (price) text = `${name}, ${price}`;
159
+ return soldOut ? `${text}, ${soldOut}` : text;
160
+ },
161
+ position: (label, index, count) => count > 1 ? `${label} ${index + 1} de ${count}` : label
162
+ };
163
+
164
+ // src/locales/pt.ts
165
+ var pt = {
166
+ watch: "Assistir v\xEDdeo",
167
+ show: "Mostrar v\xEDdeo",
168
+ carousel: "V\xEDdeos",
169
+ carouselRole: "carrossel",
170
+ previous: "V\xEDdeo anterior",
171
+ next: "Pr\xF3ximo v\xEDdeo",
172
+ player: "V\xEDdeo",
173
+ expand: "Expandir v\xEDdeo",
174
+ collapse: "Reduzir v\xEDdeo",
175
+ close: "Fechar v\xEDdeo",
176
+ play: "Reproduzir v\xEDdeo",
177
+ pause: "Pausar v\xEDdeo",
178
+ soundOn: "Ativar som",
179
+ soundOff: "Desativar som",
180
+ addToCart: "Adicionar ao carrinho",
181
+ cartQuantity: "Quantidade no carrinho",
182
+ decreaseQuantity: "Diminuir quantidade",
183
+ removeFromCart: "Remover do carrinho",
184
+ increaseQuantity: "Aumentar quantidade",
185
+ unavailable: "Produto indispon\xEDvel",
186
+ soldOut: "Esgotado",
187
+ viewProduct: "Ver produto",
188
+ videoUnavailable: "V\xEDdeo indispon\xEDvel",
189
+ videoFailed: "N\xE3o foi poss\xEDvel carregar o v\xEDdeo",
190
+ retry: "Tentar de novo",
191
+ videoLoading: "Carregando v\xEDdeo",
192
+ product: (name, price, listPrice, soldOut) => {
193
+ let text = name;
194
+ if (price && listPrice) text = `${name}, de ${listPrice} por ${price}`;
195
+ else if (price) text = `${name}, ${price}`;
196
+ return soldOut ? `${text}, ${soldOut}` : text;
197
+ },
198
+ position: (label, index, count) => count > 1 ? `${label} ${index + 1} de ${count}` : label
199
+ };
200
+
201
+ // src/locales/index.ts
202
+ var BY_LANGUAGE = /* @__PURE__ */ new Map([
203
+ ["pt", pt],
204
+ ["es", es],
205
+ ["en", en]
206
+ ]);
207
+ function labelsFor(locale, overrides = {}) {
208
+ var _a, _b, _c;
209
+ const language = locale.split("-")[0].toLowerCase();
210
+ const labels = (_a = BY_LANGUAGE.get(language)) != null ? _a : pt;
211
+ const addToCart = (_b = overrides.addToCart) == null ? void 0 : _b.trim();
212
+ const viewProduct = (_c = overrides.viewProduct) == null ? void 0 : _c.trim();
213
+ return {
214
+ ...labels,
215
+ ...addToCart && { addToCart },
216
+ ...viewProduct && { viewProduct }
217
+ };
218
+ }
219
+
220
+ // src/utils/safe-url.ts
59
221
  function httpUrl(value) {
60
222
  if (!value) return null;
61
223
  try {
@@ -65,16 +227,82 @@ function httpUrl(value) {
65
227
  return null;
66
228
  }
67
229
  }
230
+ var STORE_BASE = "https://store.invalid";
231
+ function storePath(value) {
232
+ try {
233
+ const url = new URL(value, STORE_BASE);
234
+ if (url.origin !== STORE_BASE || url.pathname.startsWith("//")) {
235
+ return null;
236
+ }
237
+ return `${url.pathname}${url.search}${url.hash}`;
238
+ } catch (e) {
239
+ return null;
240
+ }
241
+ }
242
+ function destinationUrl(value) {
243
+ if (!value) return null;
244
+ return value.startsWith("/") ? storePath(value) : httpUrl(value);
245
+ }
246
+
247
+ // src/components/media/media.ts
248
+ var REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
68
249
  function prefersReducedMotion() {
69
250
  var _a, _b;
70
- return (_b = (_a = globalThis.matchMedia) == null ? void 0 : _a.call(globalThis, "(prefers-reduced-motion: reduce)").matches) != null ? _b : false;
251
+ return (_b = (_a = globalThis.matchMedia) == null ? void 0 : _a.call(globalThis, REDUCED_MOTION).matches) != null ? _b : false;
71
252
  }
72
253
  function hasVideo(story, video) {
73
- return !video.failed && httpUrl(story.media_url) !== null;
254
+ return !video.failed && !video.retrying && httpUrl(story.media_url) !== null;
255
+ }
256
+ function renderFailed(labels, onRetry) {
257
+ const retry = (event) => {
258
+ event.stopPropagation();
259
+ onRetry == null ? void 0 : onRetry();
260
+ };
261
+ return html`
262
+ <div class="media-status" ?data-retry=${!!onRetry}>
263
+ <span class="media-status-text">
264
+ ${icon("warning")}
265
+ ${onRetry ? labels.videoFailed : labels.videoUnavailable}
266
+ </span>
267
+ ${onRetry ? html`
268
+ <button type="button" class="media-retry" @click=${retry}>
269
+ ${labels.retry}
270
+ </button>
271
+ ` : nothing}
272
+ </div>
273
+ `;
274
+ }
275
+ function renderVideoLoading(labels) {
276
+ return html`
277
+ <div class="media-status">
278
+ <span class="media-status-text">
279
+ <span class="media-spinner" aria-hidden="true"></span>
280
+ ${labels.videoLoading}
281
+ </span>
282
+ </div>
283
+ `;
284
+ }
285
+ function renderStatus(video, labels, onRetry) {
286
+ if (video.failed) return renderFailed(labels, onRetry);
287
+ if (video.retrying) return renderVideoLoading(labels);
288
+ return nothing;
289
+ }
290
+ function renderNotice(video, { labels = pt, onRetry, announce = true }) {
291
+ return html`
292
+ <div
293
+ class="media-notice"
294
+ role=${announce ? "status" : nothing}
295
+ aria-hidden=${announce ? nothing : "true"}
296
+ >
297
+ ${renderStatus(video, labels, onRetry)}
298
+ </div>
299
+ `;
74
300
  }
75
- function renderMedia(story, video) {
301
+ function renderMedia(story, video, options = {}) {
302
+ const { withVideo = true, loop = true, onEnded, autoplay = true } = options;
76
303
  const posterUrl = httpUrl(story.poster_url);
77
- const mediaUrl = httpUrl(story.media_url);
304
+ const mediaUrl = withVideo ? httpUrl(story.media_url) : null;
305
+ const preload = autoplay ? "metadata" : "auto";
78
306
  return html`
79
307
  ${posterUrl ? html`<img class="poster" alt="" src=${posterUrl} />` : nothing}
80
308
  ${mediaUrl && !video.failed ? html`
@@ -82,22 +310,139 @@ function renderMedia(story, video) {
82
310
  class="video"
83
311
  muted
84
312
  playsinline
85
- loop
86
- preload="metadata"
313
+ ?loop=${loop}
314
+ preload=${preload}
87
315
  .muted=${true}
88
- ?autoplay=${!prefersReducedMotion()}
316
+ ?autoplay=${autoplay && !prefersReducedMotion()}
89
317
  poster=${posterUrl != null ? posterUrl : nothing}
90
318
  src=${mediaUrl}
91
319
  ${ref(video.ref)}
92
320
  @play=${video.sync}
93
321
  @pause=${video.sync}
94
322
  @volumechange=${video.sync}
323
+ @loadeddata=${video.loaded}
95
324
  @error=${video.fail}
325
+ @ended=${onEnded}
96
326
  ></video>
97
327
  ` : nothing}
328
+ ${mediaUrl ? renderNotice(video, options) : nothing}
98
329
  `;
99
330
  }
100
331
 
332
+ // src/components/media/media.styles.ts
333
+ import { css } from "lit";
334
+ var mediaStyles = css`
335
+ /* The live region the notice shows in, over the cover. Empty until the
336
+ video can't load or is loading again. Clicks go through to the card. */
337
+ .media-notice {
338
+ position: absolute;
339
+ inset: 0;
340
+ pointer-events: none;
341
+ }
342
+
343
+ /* The notice: a dimmed layer with the text in the middle. */
344
+ .media-status {
345
+ position: absolute;
346
+ inset: 0;
347
+ display: flex;
348
+ flex-direction: column;
349
+ gap: 12px;
350
+ align-items: center;
351
+ justify-content: center;
352
+ box-sizing: border-box;
353
+ padding: 16px;
354
+ background: rgba(0, 0, 0, 0.45);
355
+ color: #fff;
356
+ text-align: center;
357
+ pointer-events: none;
358
+ }
359
+
360
+ .media-status > * {
361
+ animation: media-status-in 0.4s ease-out both;
362
+ }
363
+
364
+ .media-status-text {
365
+ display: flex;
366
+ flex-direction: column;
367
+ gap: 8px;
368
+ align-items: center;
369
+ max-width: 100%;
370
+ font-size: 14px;
371
+ font-weight: 600;
372
+ line-height: 1.3;
373
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
374
+ }
375
+
376
+ .media-status-text .icon {
377
+ width: 18px;
378
+ height: 18px;
379
+ }
380
+
381
+ .media-status[data-retry] .media-status-text .icon {
382
+ width: 24px;
383
+ height: 24px;
384
+ }
385
+
386
+ .media-retry {
387
+ min-height: 36px;
388
+ padding: 0 16px;
389
+ border: 0;
390
+ border-radius: var(--_button-radius);
391
+ background: rgba(255, 255, 255, 0.15);
392
+ backdrop-filter: blur(4px);
393
+ box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);
394
+ color: #fff;
395
+ font: inherit;
396
+ font-size: 14px;
397
+ font-weight: 600;
398
+ cursor: pointer;
399
+ pointer-events: auto;
400
+ animation-delay: 0.06s;
401
+ }
402
+
403
+ .media-retry:focus-visible {
404
+ outline: 2px solid #fff;
405
+ outline-offset: 2px;
406
+ }
407
+
408
+ @media (hover: hover) and (pointer: fine) {
409
+ .media-retry:hover {
410
+ background: rgba(255, 255, 255, 0.25);
411
+ }
412
+ }
413
+
414
+ /* It spins with reduced motion too: a still ring wouldn't read as
415
+ loading. */
416
+ .media-spinner {
417
+ width: 24px;
418
+ height: 24px;
419
+ box-sizing: border-box;
420
+ border: 2px solid rgba(255, 255, 255, 0.35);
421
+ border-top-color: #fff;
422
+ border-radius: 50%;
423
+ animation: media-spin 0.8s linear infinite;
424
+ }
425
+
426
+ @keyframes media-status-in {
427
+ from {
428
+ opacity: 0;
429
+ transform: translateY(4px);
430
+ }
431
+ }
432
+
433
+ @keyframes media-spin {
434
+ to {
435
+ transform: rotate(360deg);
436
+ }
437
+ }
438
+
439
+ @media (prefers-reduced-motion: reduce) {
440
+ .media-status > :not(.media-spinner) {
441
+ animation: none;
442
+ }
443
+ }
444
+ `;
445
+
101
446
  // src/components/media/video-controller.ts
102
447
  import { createRef } from "lit/directives/ref.js";
103
448
  function playVideo(video) {
@@ -112,8 +457,7 @@ var VideoController = class {
112
457
  this.paused = true;
113
458
  // The video always starts muted: that is what browsers allow to autoplay.
114
459
  this.muted = true;
115
- /** The video could not load: only the cover is shown. */
116
- this.failed = false;
460
+ this.status = "playable";
117
461
  /** Listener for the video's play, pause and volumechange events. */
118
462
  this.sync = () => {
119
463
  const video = this.ref.value;
@@ -122,17 +466,78 @@ var VideoController = class {
122
466
  this.muted = video.muted;
123
467
  this.host.requestUpdate();
124
468
  };
469
+ /** Listener for the video's loadeddata event. */
470
+ this.loaded = () => {
471
+ this.settleReady(true);
472
+ if (!this.retrying) return;
473
+ this.status = "playable";
474
+ this.host.requestUpdate();
475
+ };
125
476
  /** Listener for the video's error event. */
126
477
  this.fail = () => {
127
- this.failed = true;
478
+ this.status = "failed";
479
+ this.settleReady(false);
128
480
  this.host.requestUpdate();
129
481
  };
482
+ this.waitForReady();
483
+ }
484
+ /**
485
+ * Resolves true once the video's first frame has loaded, or false if it
486
+ * fails. A new one for each new <video> (see reset).
487
+ */
488
+ get ready() {
489
+ return this.readyState;
490
+ }
491
+ /** The video could not load: the cover shows with a notice over it. */
492
+ get failed() {
493
+ return this.status === "failed";
494
+ }
495
+ /** A failed video is loading again (see retry), until it loads or fails. */
496
+ get retrying() {
497
+ return this.status === "retrying";
498
+ }
499
+ /** The rendered <video> is on the page and playing. */
500
+ get playing() {
501
+ const video = this.ref.value;
502
+ return !!video && video.isConnected && !video.paused;
130
503
  }
131
- /** For a new <video>, such as each time the player opens. */
504
+ /**
505
+ * For a new <video>, such as each time the player opens. A retry still
506
+ * loading resolves false.
507
+ */
132
508
  reset() {
509
+ this.cancelRetry();
133
510
  this.paused = true;
134
511
  this.muted = true;
135
- this.failed = false;
512
+ this.status = "playable";
513
+ this.waitForReady();
514
+ }
515
+ /**
516
+ * For the next Story's <video>: neither failed nor loading again (a retry
517
+ * still loading resolves false). Unlike reset, it keeps the playback and
518
+ * sound state.
519
+ */
520
+ clearFailure() {
521
+ if (this.retrying) {
522
+ this.cancelRetry();
523
+ this.waitForReady();
524
+ }
525
+ this.status = "playable";
526
+ this.host.requestUpdate();
527
+ }
528
+ /**
529
+ * Loads a failed video again: renderMedia renders a new <video> with a
530
+ * notice that it is loading, until it loads or fails. Resolves as `ready`
531
+ * does: false too if the video is replaced first (see reset and
532
+ * clearFailure), and at once for a video that didn't fail.
533
+ */
534
+ retry() {
535
+ if (this.retrying) return this.ready;
536
+ if (!this.failed) return Promise.resolve(false);
537
+ this.reset();
538
+ this.status = "retrying";
539
+ this.host.requestUpdate();
540
+ return this.ready;
136
541
  }
137
542
  play() {
138
543
  const video = this.ref.value;
@@ -153,153 +558,1721 @@ var VideoController = class {
153
558
  if (video.paused) playVideo(video);
154
559
  else video.pause();
155
560
  }
156
- toggleMuted() {
561
+ mute() {
157
562
  const video = this.ref.value;
158
- if (video) video.muted = !video.muted;
563
+ if (video) video.muted = true;
159
564
  }
160
- };
161
-
162
- // src/components/card/card.ts
163
- var cardStyles = css`
164
- .card {
165
- position: relative;
166
- box-sizing: border-box;
167
- width: calc(500px * 9 / 16);
168
- height: 500px;
169
- overflow: hidden;
170
- border-radius: var(--vtex-ads-story-radius, 20px);
171
- background: #000;
565
+ /**
566
+ * Plays from the start, with the sound on if `withSound`. A new src starts
567
+ * there anyway; the same src (two Stories with one video) would otherwise
568
+ * go on where it was.
569
+ */
570
+ restart({ withSound = false } = {}) {
571
+ const video = this.ref.value;
572
+ if (!video) return;
573
+ video.currentTime = 0;
574
+ if (withSound) this.playWithSound();
575
+ else playVideo(video);
172
576
  }
173
-
174
- /* The card's button covers it. The focus ring goes on the card, since the
175
- card's overflow would clip the button's own. */
176
- .card-open {
177
- position: absolute;
178
- inset: 0;
179
- width: 100%;
180
- height: 100%;
181
- padding: 0;
182
- border: 0;
183
- background: transparent;
184
- cursor: pointer;
577
+ /**
578
+ * Plays with the sound on. A browser that blocks playing with sound (for
579
+ * example, without a recent tap) gets it muted instead: the video keeps
580
+ * playing, and the sound button offers to turn it on. Not if the video was
581
+ * replaced or removed meanwhile (the request then fails for that reason):
582
+ * it would play out of sight.
583
+ */
584
+ playWithSound() {
585
+ var _a;
586
+ const video = this.ref.value;
587
+ if (!video) return;
588
+ video.muted = false;
589
+ (_a = video.play()) == null ? void 0 : _a.catch((error) => {
590
+ const blocked = error instanceof DOMException && error.name === "NotAllowedError";
591
+ if (!blocked || this.ref.value !== video || !video.isConnected) return;
592
+ video.muted = true;
593
+ playVideo(video);
594
+ });
185
595
  }
186
-
187
- .card-open:focus-visible {
188
- outline: none;
596
+ toggleMuted() {
597
+ const video = this.ref.value;
598
+ if (video) video.muted = !video.muted;
189
599
  }
190
-
191
- .card:has(> .card-open:focus-visible) {
192
- outline: auto;
600
+ // The video loading again is replaced: its retry resolves false.
601
+ cancelRetry() {
602
+ if (this.retrying) this.settleReady(false);
193
603
  }
194
-
195
- .poster,
196
- .video {
197
- position: absolute;
198
- inset: 0;
199
- width: 100%;
200
- height: 100%;
201
- object-fit: cover;
604
+ waitForReady() {
605
+ this.readyState = new Promise((settle) => this.settleReady = settle);
202
606
  }
607
+ };
203
608
 
204
- .play {
205
- position: absolute;
206
- top: 50%;
207
- left: 50%;
208
- display: grid;
209
- width: 66px;
210
- height: 66px;
211
- place-items: center;
212
- border-radius: 50%;
213
- background:
214
- linear-gradient(rgba(0, 0, 0, 0.06), rgba(0, 0, 0, 0.06)),
215
- rgba(255, 255, 255, 0.15);
216
- backdrop-filter: blur(2px);
217
- box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);
218
- transform: translate(-50%, -50%);
219
- transition:
220
- opacity 0.3s ease,
221
- transform 0.3s ease;
222
- }
609
+ // src/components/product/product.ts
610
+ import { html as html2, nothing as nothing2 } from "lit";
223
611
 
224
- /* The icon's triangle is 18px tall and already sits slightly right of its
225
- box, so it looks centered in the circle. */
226
- .play .icon {
227
- width: 22px;
228
- height: 22px;
229
- color: #fff;
612
+ // src/components/product/price.ts
613
+ var DEFAULT_LOCALE = "pt-BR";
614
+ var DEFAULT_CURRENCY = "BRL";
615
+ function toAmount(value) {
616
+ let amount = Number.NaN;
617
+ if (typeof value === "number") amount = value;
618
+ else if (typeof value === "string" && value.trim() !== "") {
619
+ amount = Number(value);
230
620
  }
231
-
232
- /* Sound on/off, at the top right of the card (as in the prototype). */
233
- .card-sound {
234
- position: absolute;
235
- top: 22px;
236
- right: 12px;
237
- z-index: 1;
238
- display: grid;
239
- width: 28px;
240
- height: 28px;
241
- place-items: center;
242
- padding: 0;
243
- border: 0;
244
- background: transparent;
245
- color: #fff;
246
- cursor: pointer;
247
- filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.4));
621
+ return Number.isFinite(amount) && amount > 0 ? amount : void 0;
622
+ }
623
+ function readProductPrice(metadata) {
624
+ const regular = toAmount(metadata == null ? void 0 : metadata.price);
625
+ const promotional = toAmount(metadata == null ? void 0 : metadata.promotional_price);
626
+ if (promotional !== void 0 && (regular === void 0 || promotional < regular)) {
627
+ return regular === void 0 ? { price: promotional } : { price: promotional, listPrice: regular };
248
628
  }
249
-
250
- .card-sound .icon {
251
- width: 20px;
252
- height: 20px;
629
+ return regular === void 0 ? void 0 : { price: regular };
630
+ }
631
+ function isLocale(locale) {
632
+ try {
633
+ return Intl.NumberFormat.supportedLocalesOf(locale).length > 0;
634
+ } catch (e) {
635
+ return false;
253
636
  }
254
-
255
- /* With a mouse, the play button shows only on hover or keyboard focus.
256
- Touch screens have no hover, so it stays visible there. */
257
- @media (hover: hover) and (pointer: fine) {
258
- .play {
259
- opacity: 0;
260
- transform: translate(-50%, -50%) scale(0.9);
637
+ }
638
+ var intl = Intl;
639
+ function isCurrency(currency) {
640
+ var _a;
641
+ if (!/^[a-z]{3}$/i.test(currency)) return false;
642
+ const known = (_a = intl.supportedValuesOf) == null ? void 0 : _a.call(intl, "currency");
643
+ return known ? known.includes(currency.toUpperCase()) : true;
644
+ }
645
+ function priceFormatter(locale, currency) {
646
+ const format = new Intl.NumberFormat(
647
+ locale && isLocale(locale) ? locale : DEFAULT_LOCALE,
648
+ {
649
+ style: "currency",
650
+ currency: currency && isCurrency(currency) ? currency : DEFAULT_CURRENCY
261
651
  }
652
+ );
653
+ return (amount) => format.format(amount);
654
+ }
262
655
 
263
- .card:hover .play,
264
- .card-open:focus-visible .play {
265
- opacity: 1;
266
- transform: translate(-50%, -50%);
267
- }
656
+ // src/components/product/product.ts
657
+ function toCardProduct(story, format, labels, fetched) {
658
+ var _a, _b, _c, _d, _e, _f;
659
+ const product = story.product;
660
+ const name = (_a = product == null ? void 0 : product.product_name) == null ? void 0 : _a.trim();
661
+ if (!product || !name) return void 0;
662
+ const base = {
663
+ name,
664
+ imageUrl: (_b = httpUrl(product.image_url)) != null ? _b : void 0,
665
+ url: (_c = destinationUrl(story.destination_url)) != null ? _c : void 0,
666
+ sku: ((_d = product.product_sku) == null ? void 0 : _d.trim()) || void 0,
667
+ seller: ((_e = product.seller_id) == null ? void 0 : _e.trim()) || void 0
668
+ };
669
+ if (fetched === "loading") {
670
+ return { ...base, label: labels.product(name), isLoading: true };
268
671
  }
672
+ const soldOut = (fetched == null ? void 0 : fetched.available) === false ? labels.soldOut : void 0;
673
+ const shown = (amounts2) => soldOut && (amounts2 == null ? void 0 : amounts2.price) === 0 ? void 0 : amounts2;
674
+ const amounts = (_f = shown(fetched == null ? void 0 : fetched.price)) != null ? _f : shown(readProductPrice(product.product_metadata));
675
+ const price = amounts && format(amounts.price);
676
+ const listPrice = (amounts == null ? void 0 : amounts.listPrice) === void 0 ? void 0 : format(amounts.listPrice);
677
+ return {
678
+ ...base,
679
+ price,
680
+ listPrice,
681
+ soldOut,
682
+ label: labels.product(name, price, listPrice, soldOut)
683
+ };
684
+ }
685
+ var priceSkeleton = html2`
686
+ <span
687
+ class="product-price product-loading product-price-loading"
688
+ aria-hidden="true"
689
+ ></span>
269
690
  `;
270
- function renderSoundButton(video, options) {
691
+ var addToCartSkeleton = html2`
692
+ <span
693
+ class="product-loading product-add-to-cart-loading"
694
+ aria-hidden="true"
695
+ ></span>
696
+ `;
697
+ function renderPrice({ isLoading, soldOut, price, listPrice }) {
698
+ if (isLoading) return priceSkeleton;
699
+ if (!price) {
700
+ return soldOut ? html2`<span class="product-price product-sold-out">${soldOut}</span>` : nothing2;
701
+ }
702
+ return html2`
703
+ <span class="product-price">
704
+ <span>${price}</span>
705
+ ${listPrice ? html2`<s class="product-list-price">${listPrice}</s>` : nothing2}
706
+ </span>
707
+ `;
708
+ }
709
+ function renderSummary(product) {
710
+ return html2`
711
+ ${product.imageUrl ? html2`<img class="product-image" alt="" src=${product.imageUrl} />` : nothing2}
712
+ <span class="product-info">
713
+ <span class="product-name">${product.name}</span>
714
+ ${renderPrice(product)}
715
+ </span>
716
+ `;
717
+ }
718
+ function renderProduct(product, onSelect) {
271
719
  return html2`
272
720
  <button
273
721
  type="button"
274
- class="card-sound"
275
- aria-label=${video.muted ? options.soundOnLabel : options.soundOffLabel}
276
- @click=${() => video.toggleMuted()}
722
+ class="card-product"
723
+ aria-label=${product.label}
724
+ @click=${onSelect}
277
725
  >
278
- ${icon(video.muted ? "soundOff" : "soundOn")}
726
+ ${renderSummary(product)}
279
727
  </button>
280
728
  `;
281
729
  }
282
- function renderCard(story, video, options) {
283
- return html2`
284
- <div class="card">
285
- ${renderMedia(story, video)}
730
+ var STEPPER_ADD_CLASS = "product-stepper-add";
731
+ var ADD_TO_CART_CLASS = "product-add-to-cart";
732
+ function focusCartAction(root, action) {
733
+ var _a;
734
+ const className = action === "stepper" ? STEPPER_ADD_CLASS : ADD_TO_CART_CLASS;
735
+ (_a = root.querySelector(`.${className}`)) == null ? void 0 : _a.focus();
736
+ }
737
+ function renderStepper(quantity, {
738
+ labels,
739
+ onAddToCart,
740
+ onRemoveFromCart
741
+ }) {
742
+ const last = quantity === 1;
743
+ return html2`
744
+ <div
745
+ class="product-action product-stepper"
746
+ role="group"
747
+ aria-label=${labels.cartQuantity}
748
+ >
749
+ <button
750
+ type="button"
751
+ class="product-stepper-button product-stepper-remove"
752
+ aria-label=${last ? labels.removeFromCart : labels.decreaseQuantity}
753
+ @click=${onRemoveFromCart}
754
+ >
755
+ ${icon(last ? "trash" : "minus")}
756
+ </button>
757
+ <span class="product-quantity">${quantity}</span>
758
+ <button
759
+ type="button"
760
+ class="product-stepper-button ${STEPPER_ADD_CLASS}"
761
+ aria-label=${labels.increaseQuantity}
762
+ @click=${onAddToCart}
763
+ >
764
+ ${icon("plus")}
765
+ </button>
766
+ </div>
767
+ `;
768
+ }
769
+ function renderAddToCart({ isLoading, soldOut, sku }, options) {
770
+ const { labels, onAddToCart, cartQuantity = 0 } = options;
771
+ if (!sku || !onAddToCart) return nothing2;
772
+ if (isLoading) return addToCartSkeleton;
773
+ if (soldOut) {
774
+ return html2`
775
+ <button type="button" class="product-action product-unavailable" disabled>
776
+ ${labels.unavailable}
777
+ </button>
778
+ `;
779
+ }
780
+ if (cartQuantity > 0) return renderStepper(cartQuantity, options);
781
+ return html2`
782
+ <button
783
+ type="button"
784
+ class="product-action ${ADD_TO_CART_CLASS}"
785
+ @click=${onAddToCart}
786
+ >
787
+ ${labels.addToCart}
788
+ </button>
789
+ `;
790
+ }
791
+ function renderCartStatus({ sku }, { labels, cartQuantity = 0, onAddToCart }) {
792
+ if (!sku || !onAddToCart) return nothing2;
793
+ return html2`
794
+ <span class="product-cart-status" role="status">
795
+ ${cartQuantity > 0 ? `${labels.cartQuantity}: ${cartQuantity}` : ""}
796
+ </span>
797
+ `;
798
+ }
799
+ function renderExpandableProduct(product, options) {
800
+ const { open } = options;
801
+ return html2`
802
+ <div class="card-product product-expandable" ?data-open=${open}>
803
+ <button
804
+ type="button"
805
+ class="product-summary"
806
+ aria-label=${product.label}
807
+ aria-expanded=${open ? "true" : "false"}
808
+ aria-controls=${options.panelId}
809
+ @click=${options.onToggle}
810
+ >
811
+ ${renderSummary(product)}
812
+ <span class="product-toggle">${icon("caretUp")}</span>
813
+ </button>
814
+ <div id=${options.panelId} class="product-panel" ?inert=${!open}>
815
+ <div class="product-actions">
816
+ ${renderCartStatus(product, options)}
817
+ ${renderAddToCart(product, options)}
818
+ ${product.url ? html2`
819
+ <a
820
+ class="product-action product-view"
821
+ href=${product.url}
822
+ target="_blank"
823
+ rel="noopener noreferrer"
824
+ >
825
+ ${options.labels.viewProduct}
826
+ </a>
827
+ ` : nothing2}
828
+ </div>
829
+ </div>
830
+ </div>
831
+ `;
832
+ }
833
+
834
+ // src/components/product/cta.ts
835
+ import { html as html3 } from "lit";
836
+ function toCardCta(story) {
837
+ var _a;
838
+ if (story.product) return void 0;
839
+ const label = (_a = story.call_to_action) == null ? void 0 : _a.trim();
840
+ const url = destinationUrl(story.destination_url);
841
+ return label && url ? { label, url } : void 0;
842
+ }
843
+ function renderCta(cta, onSelect) {
844
+ const onClick = onSelect ? (event) => {
845
+ event.preventDefault();
846
+ onSelect();
847
+ } : void 0;
848
+ return html3`
849
+ <a
850
+ class="card-cta"
851
+ href=${cta.url}
852
+ target="_blank"
853
+ rel="noopener noreferrer"
854
+ @click=${onClick}
855
+ >
856
+ <span class="cta-label">${cta.label}</span>
857
+ ${icon("next")}
858
+ </a>
859
+ `;
860
+ }
861
+
862
+ // src/components/product/product.styles.ts
863
+ import { css as css2 } from "lit";
864
+ var productStyles = css2`
865
+ /* A glass pill at the bottom of the card, above its button: the product or
866
+ the call to action. */
867
+ .card-product,
868
+ .card-cta {
869
+ position: absolute;
870
+ right: 12px;
871
+ bottom: 12px;
872
+ left: 12px;
873
+ z-index: 1;
874
+ display: flex;
875
+ gap: 8px;
876
+ align-items: center;
877
+ box-sizing: border-box;
878
+ padding: var(--_pill-inset);
879
+ border: 0;
880
+ border-radius: var(--_pill-radius);
881
+ background: rgba(255, 255, 255, 0.15);
882
+ backdrop-filter: blur(5px);
883
+ color: #fff;
884
+ font: inherit;
885
+ text-align: left;
886
+ isolation: isolate;
887
+ transition: transform 0.2s ease;
888
+ }
889
+
890
+ /* The glass's tint and inner light, darker on hover. */
891
+ .card-product::before,
892
+ .card-cta::before {
893
+ position: absolute;
894
+ inset: 0;
895
+ z-index: -1;
896
+ border-radius: inherit;
897
+ background: rgba(0, 0, 0, 0.15);
898
+ box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);
899
+ content: "";
900
+ transition: background-color 0.2s ease;
901
+ }
902
+
903
+ button.card-product,
904
+ .card-cta {
905
+ cursor: pointer;
906
+ }
907
+
908
+ .card-product:focus-visible,
909
+ .card-cta:focus-visible {
910
+ outline: 2px solid #fff;
911
+ outline-offset: 2px;
912
+ }
913
+
914
+ @media (hover: hover) and (pointer: fine) {
915
+ .card-product:hover,
916
+ .card-cta:hover {
917
+ transform: translateY(-2px);
918
+ }
919
+
920
+ .card-product:hover::before,
921
+ .card-cta:hover::before {
922
+ background: rgba(0, 0, 0, 0.32);
923
+ }
924
+ }
925
+
926
+ /* A Story with a link: the pill is the call to action, its text centered
927
+ with a caret after it. */
928
+ .card-cta {
929
+ justify-content: center;
930
+ gap: 6px;
931
+ height: 48px;
932
+ padding: 0 16px;
933
+ font-size: 14px;
934
+ font-weight: 700;
935
+ line-height: 1;
936
+ text-decoration: none;
937
+ }
938
+
939
+ .cta-label {
940
+ min-width: 0;
941
+ overflow: hidden;
942
+ text-overflow: ellipsis;
943
+ white-space: nowrap;
944
+ }
945
+
946
+ .card-cta .icon {
947
+ flex: none;
948
+ width: 14px;
949
+ height: 14px;
950
+ }
951
+
952
+ /* In the player: the pill is a toggle, with the actions panel below. */
953
+ .product-expandable {
954
+ display: block;
955
+ padding: 0;
956
+ transition:
957
+ background-color 0.3s ease,
958
+ color 0.3s ease,
959
+ box-shadow 0.3s ease,
960
+ transform 0.2s ease;
961
+ }
962
+
963
+ .product-expandable::before {
964
+ transition:
965
+ opacity 0.3s ease,
966
+ background-color 0.2s ease;
967
+ }
968
+
969
+ .product-summary {
970
+ display: flex;
971
+ gap: 8px;
972
+ align-items: center;
973
+ box-sizing: border-box;
974
+ width: 100%;
975
+ padding: var(--_pill-inset);
976
+ border: 0;
977
+ border-radius: inherit;
978
+ background: transparent;
979
+ color: inherit;
980
+ font: inherit;
981
+ text-align: left;
982
+ cursor: pointer;
983
+ transition: padding 0.3s ease;
984
+ }
985
+
986
+ .product-summary:focus-visible {
987
+ outline: 2px solid currentColor;
988
+ outline-offset: 2px;
989
+ }
990
+
991
+ /* The caret points up while closed and down while open. */
992
+ .product-toggle {
993
+ display: grid;
994
+ flex: none;
995
+ margin-right: 4px;
996
+ opacity: 0.7;
997
+ transition:
998
+ transform 0.3s ease,
999
+ opacity 0.2s ease;
1000
+ }
1001
+
1002
+ .product-toggle .icon {
1003
+ width: 14px;
1004
+ height: 14px;
1005
+ }
1006
+
1007
+ .product-summary:hover .product-toggle {
1008
+ opacity: 1;
1009
+ }
1010
+
1011
+ /* Closed: 0 rows tall, so it grows smoothly when it opens. */
1012
+ .product-panel {
1013
+ display: grid;
1014
+ grid-template-rows: 0fr;
1015
+ transition: grid-template-rows 0.3s ease;
1016
+ }
1017
+
1018
+ .product-actions {
1019
+ display: grid;
1020
+ gap: 8px;
1021
+ min-height: 0;
1022
+ overflow: hidden;
1023
+ padding: 0 12px;
1024
+ opacity: 0;
1025
+ transition:
1026
+ padding 0.3s ease,
1027
+ opacity 0.2s ease;
1028
+ }
1029
+
1030
+ .product-action {
1031
+ display: flex;
1032
+ align-items: center;
1033
+ justify-content: center;
1034
+ box-sizing: border-box;
1035
+ height: 48px;
1036
+ padding: 0 16px;
1037
+ border: 1px solid var(--vtex-ads-story-color-accent, #1b75a8);
1038
+ border-radius: var(--_button-radius);
1039
+ font: inherit;
1040
+ font-size: 14px;
1041
+ font-weight: 700;
1042
+ text-decoration: none;
1043
+ cursor: pointer;
1044
+ transition: background-color 0.2s ease;
1045
+ }
1046
+
1047
+ .product-action:focus-visible {
1048
+ outline: 2px solid var(--vtex-ads-story-color-accent, #1b75a8);
1049
+ outline-offset: 2px;
1050
+ }
1051
+
1052
+ .product-add-to-cart {
1053
+ background: var(--vtex-ads-story-color-accent, #1b75a8);
1054
+ color: var(--vtex-ads-story-color-accent-contrast, #fff);
1055
+ }
1056
+
1057
+ .product-add-to-cart:hover {
1058
+ background: color-mix(
1059
+ in srgb,
1060
+ var(--vtex-ads-story-color-accent, #1b75a8) 85%,
1061
+ #000
1062
+ );
1063
+ }
1064
+
1065
+ /* In the cart: the add to cart button's pill, with minus and plus at its
1066
+ ends and the quantity between them. */
1067
+ .product-stepper {
1068
+ justify-content: space-between;
1069
+ padding: 0;
1070
+ background: var(--vtex-ads-story-color-accent, #1b75a8);
1071
+ color: var(--vtex-ads-story-color-accent-contrast, #fff);
1072
+ cursor: auto;
1073
+ }
1074
+
1075
+ .product-stepper-button {
1076
+ display: grid;
1077
+ flex: none;
1078
+ place-items: center;
1079
+ width: 46px;
1080
+ height: 46px;
1081
+ padding: 0;
1082
+ border: 0;
1083
+ border-radius: var(--_button-radius);
1084
+ background: transparent;
1085
+ color: inherit;
1086
+ cursor: pointer;
1087
+ transition: background-color 0.2s ease;
1088
+ }
1089
+
1090
+ .product-stepper-button .icon {
1091
+ width: 18px;
1092
+ height: 18px;
1093
+ }
1094
+
1095
+ .product-stepper-button:hover {
1096
+ background: rgba(0, 0, 0, 0.15);
1097
+ }
1098
+
1099
+ .product-stepper-button:focus-visible {
1100
+ outline: 2px solid var(--vtex-ads-story-color-accent-contrast, #fff);
1101
+ outline-offset: -4px;
1102
+ }
1103
+
1104
+ .product-quantity {
1105
+ flex: 1;
1106
+ min-width: 0;
1107
+ font-size: 16px;
1108
+ text-align: center;
1109
+ }
1110
+
1111
+ .product-cart-status {
1112
+ position: absolute;
1113
+ width: 1px;
1114
+ height: 1px;
1115
+ margin: -1px;
1116
+ overflow: hidden;
1117
+ clip-path: inset(50%);
1118
+ white-space: nowrap;
1119
+ }
1120
+
1121
+ /* Sold out: add to cart, disabled and grayed. */
1122
+ .product-unavailable {
1123
+ border-color: transparent;
1124
+ background: rgba(0, 0, 0, 0.06);
1125
+ color: var(--vtex-ads-story-color-muted, #6b6b6b);
1126
+ cursor: not-allowed;
1127
+ }
1128
+
1129
+ .product-view {
1130
+ background: var(--vtex-ads-story-color-surface, #fff);
1131
+ color: var(--vtex-ads-story-color-accent, #1b75a8);
1132
+ }
1133
+
1134
+ /* A light tint of the accent. */
1135
+ .product-view:hover {
1136
+ background: color-mix(
1137
+ in srgb,
1138
+ var(--vtex-ads-story-color-accent, #1b75a8) 8%,
1139
+ var(--vtex-ads-story-color-surface, #fff)
1140
+ );
1141
+ }
1142
+
1143
+ /* Open: a solid card (white by default), without the glass. */
1144
+ .product-expandable[data-open] {
1145
+ background: var(--vtex-ads-story-color-surface, #fff);
1146
+ color: var(--vtex-ads-story-color-text, #242424);
1147
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
1148
+ }
1149
+
1150
+ .product-expandable[data-open]::before {
1151
+ opacity: 0;
1152
+ }
1153
+
1154
+ .product-expandable[data-open] .product-price {
1155
+ color: inherit;
1156
+ }
1157
+
1158
+ .product-expandable[data-open] .product-list-price {
1159
+ color: var(--vtex-ads-story-color-muted, #6b6b6b);
1160
+ opacity: 1;
1161
+ }
1162
+
1163
+ .product-expandable[data-open] .product-summary {
1164
+ padding: 12px;
1165
+ }
1166
+
1167
+ .product-expandable[data-open] .product-toggle {
1168
+ transform: rotate(180deg);
1169
+ }
1170
+
1171
+ .product-expandable[data-open] .product-panel {
1172
+ grid-template-rows: 1fr;
1173
+ }
1174
+
1175
+ .product-expandable[data-open] .product-actions {
1176
+ padding: 0 12px 12px;
1177
+ opacity: 1;
1178
+ transition:
1179
+ padding 0.3s ease,
1180
+ opacity 0.25s ease 0.1s;
1181
+ }
1182
+
1183
+ /* Open, it stays in place on hover. */
1184
+ @media (hover: hover) and (pointer: fine) {
1185
+ .product-expandable[data-open]:hover {
1186
+ transform: none;
1187
+ }
1188
+ }
1189
+
1190
+ @media (prefers-reduced-motion: reduce) {
1191
+ .card-product,
1192
+ .card-product:hover,
1193
+ .card-cta,
1194
+ .card-cta:hover {
1195
+ transform: none;
1196
+ transition: none;
1197
+ }
1198
+
1199
+ .card-product::before,
1200
+ .card-cta::before,
1201
+ .product-summary,
1202
+ .product-toggle,
1203
+ .product-panel,
1204
+ .product-actions,
1205
+ .product-expandable[data-open] .product-actions {
1206
+ transition: none;
1207
+ }
1208
+ }
1209
+
1210
+ /* Its corners follow the pill's, one inset in from them: 8px by default. */
1211
+ .product-image {
1212
+ flex: none;
1213
+ width: 60px;
1214
+ height: 60px;
1215
+ border-radius: max(0px, var(--_pill-radius) - var(--_pill-inset));
1216
+ background: #fff;
1217
+ object-fit: contain;
1218
+ }
1219
+
1220
+ .product-info {
1221
+ display: grid;
1222
+ flex: 1;
1223
+ gap: 4px;
1224
+ min-width: 0;
1225
+ font-size: 12px;
1226
+ font-weight: 700;
1227
+ line-height: 16px;
1228
+ }
1229
+
1230
+ .product-name {
1231
+ display: -webkit-box;
1232
+ overflow: hidden;
1233
+ -webkit-box-orient: vertical;
1234
+ -webkit-line-clamp: 2;
1235
+ overflow-wrap: anywhere;
1236
+ }
1237
+
1238
+ .product-price {
1239
+ display: flex;
1240
+ flex-wrap: wrap;
1241
+ gap: 0 6px;
1242
+ }
1243
+
1244
+ .product-list-price {
1245
+ font-weight: 400;
1246
+ opacity: 0.5;
1247
+ }
1248
+
1249
+ /* In place of the price, for a product that can't be bought. */
1250
+ .product-sold-out {
1251
+ font-weight: 700;
1252
+ opacity: 0.75;
1253
+ }
1254
+
1255
+ /* Placeholders while the product loads, pulsing gently. */
1256
+ .product-loading {
1257
+ background: currentColor;
1258
+ opacity: 0.25;
1259
+ animation: product-loading-pulse 1.2s ease-in-out infinite alternate;
1260
+ }
1261
+
1262
+ @keyframes product-loading-pulse {
1263
+ to {
1264
+ opacity: 0.1;
1265
+ }
1266
+ }
1267
+
1268
+ /* The price's: a line its height (the info's line height). */
1269
+ .product-price-loading {
1270
+ width: 64px;
1271
+ height: 16px;
1272
+ border-radius: 4px;
1273
+ }
1274
+
1275
+ /* The add to cart button's: its size and shape. */
1276
+ .product-add-to-cart-loading {
1277
+ display: block;
1278
+ height: 48px;
1279
+ border-radius: var(--_button-radius);
1280
+ }
1281
+
1282
+ @media (prefers-reduced-motion: reduce) {
1283
+ .product-loading {
1284
+ animation: none;
1285
+ }
1286
+ }
1287
+ `;
1288
+
1289
+ // src/components/card/card.ts
1290
+ var cardStyles = css3`
1291
+ /* 9:16 at the height its container gives it (--card-height, default
1292
+ 500px). */
1293
+ .card {
1294
+ position: relative;
1295
+ box-sizing: border-box;
1296
+ width: calc(var(--card-height, 500px) * 9 / 16);
1297
+ height: var(--card-height, 500px);
1298
+ overflow: hidden;
1299
+ border-radius: var(--vtex-ads-story-radius, 20px);
1300
+ background: #000;
1301
+ }
1302
+
1303
+ /* The card's button covers it. The focus ring goes on the card, since the
1304
+ card's overflow would clip the button's own. */
1305
+ .card-open {
1306
+ position: absolute;
1307
+ inset: 0;
1308
+ width: 100%;
1309
+ height: 100%;
1310
+ padding: 0;
1311
+ border: 0;
1312
+ background: transparent;
1313
+ cursor: pointer;
1314
+ }
1315
+
1316
+ .card-open:focus-visible {
1317
+ outline: none;
1318
+ }
1319
+
1320
+ .card:has(> .card-open:focus-visible) {
1321
+ outline: auto;
1322
+ }
1323
+
1324
+ .poster,
1325
+ .video {
1326
+ position: absolute;
1327
+ inset: 0;
1328
+ width: 100%;
1329
+ height: 100%;
1330
+ object-fit: cover;
1331
+ }
1332
+
1333
+ .play {
1334
+ position: absolute;
1335
+ top: 50%;
1336
+ left: 50%;
1337
+ display: grid;
1338
+ width: 66px;
1339
+ height: 66px;
1340
+ place-items: center;
1341
+ border-radius: 50%;
1342
+ background:
1343
+ linear-gradient(rgba(0, 0, 0, 0.06), rgba(0, 0, 0, 0.06)),
1344
+ rgba(255, 255, 255, 0.15);
1345
+ backdrop-filter: blur(2px);
1346
+ box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);
1347
+ transform: translate(-50%, -50%);
1348
+ transition:
1349
+ opacity 0.3s ease,
1350
+ transform 0.3s ease;
1351
+ }
1352
+
1353
+ /* The icon's triangle is 18px tall and already sits slightly right of its
1354
+ box, so it looks centered in the circle. */
1355
+ .play .icon {
1356
+ width: 22px;
1357
+ height: 22px;
1358
+ color: #fff;
1359
+ }
1360
+
1361
+ /* Sound on/off, at the top right of the card (as in the prototype). */
1362
+ .card-sound {
1363
+ position: absolute;
1364
+ top: 22px;
1365
+ right: 12px;
1366
+ z-index: 1;
1367
+ display: grid;
1368
+ width: 28px;
1369
+ height: 28px;
1370
+ place-items: center;
1371
+ padding: 0;
1372
+ border: 0;
1373
+ background: transparent;
1374
+ color: #fff;
1375
+ cursor: pointer;
1376
+ filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.4));
1377
+ }
1378
+
1379
+ .card-sound .icon {
1380
+ width: 20px;
1381
+ height: 20px;
1382
+ }
1383
+
1384
+ /* With a mouse, the play button shows only on hover or keyboard focus.
1385
+ Touch screens have no hover, so it stays visible there. */
1386
+ @media (hover: hover) and (pointer: fine) {
1387
+ .play {
1388
+ opacity: 0;
1389
+ transform: translate(-50%, -50%) scale(0.9);
1390
+ }
1391
+
1392
+ .card:hover .play,
1393
+ .card-open:focus-visible .play {
1394
+ opacity: 1;
1395
+ transform: translate(-50%, -50%);
1396
+ }
1397
+ }
1398
+ `;
1399
+ function renderSoundButton(video, options) {
1400
+ return html4`
1401
+ <button
1402
+ type="button"
1403
+ class="card-sound"
1404
+ aria-label=${video.muted ? options.labels.soundOn : options.labels.soundOff}
1405
+ @click=${() => video.toggleMuted()}
1406
+ >
1407
+ ${icon(video.muted ? "soundOff" : "soundOn")}
1408
+ </button>
1409
+ `;
1410
+ }
1411
+ function renderCard(story, video, options) {
1412
+ var _a, _b;
1413
+ const withVideo = (_a = options.withVideo) != null ? _a : true;
1414
+ return html4`
1415
+ <div
1416
+ class="card"
1417
+ ${ref2(options.ref)}
1418
+ @click=${{ handleEvent: () => {
1419
+ var _a2;
1420
+ return (_a2 = options.onPress) == null ? void 0 : _a2.call(options);
1421
+ }, capture: true }}
1422
+ >
1423
+ ${renderMedia(story, video, {
1424
+ withVideo,
1425
+ autoplay: options.autoplay,
1426
+ labels: options.labels,
1427
+ announce: false
1428
+ })}
286
1429
  <button
287
1430
  type="button"
288
1431
  class="card-open"
1432
+ ${ref2(options.openRef)}
289
1433
  aria-label=${options.label}
290
1434
  @click=${options.onSelect}
291
1435
  >
292
- <span class="play" aria-hidden="true">${icon("play")}</span>
1436
+ ${withVideo && video.failed ? nothing3 : html4`<span class="play" aria-hidden="true">${icon("play")}</span>`}
293
1437
  </button>
294
- ${hasVideo(story, video) && !video.paused ? renderSoundButton(video, options) : nothing2}
1438
+ ${withVideo && hasVideo(story, video) && !video.paused ? renderSoundButton(video, options) : nothing3}
1439
+ ${options.product ? renderProduct(
1440
+ options.product,
1441
+ (_b = options.onProductSelect) != null ? _b : options.onSelect
1442
+ ) : nothing3}
1443
+ ${options.cta ? renderCta(options.cta, options.onCtaSelect) : nothing3}
1444
+ </div>
1445
+ `;
1446
+ }
1447
+
1448
+ // src/components/carousel/carousel.ts
1449
+ import {
1450
+ css as css4,
1451
+ html as html5
1452
+ } from "lit";
1453
+ import { repeat } from "lit/directives/repeat.js";
1454
+ import { styleMap } from "lit/directives/style-map.js";
1455
+ var STAGE_HEIGHT = css4`500px`;
1456
+ var SOLO_PADDING = css4`24px`;
1457
+ var AUTO_ADVANCE_MS = 5e3;
1458
+ var MIN_SLIDE_DURATION_MS = 2e3;
1459
+ var MAX_SLIDE_DURATION_MS = 12e4;
1460
+ var toSlideDuration = (ms) => {
1461
+ if (ms === void 0 || !Number.isFinite(ms) || ms < 0) {
1462
+ return AUTO_ADVANCE_MS;
1463
+ }
1464
+ if (ms === 0) {
1465
+ return 0;
1466
+ }
1467
+ return Math.min(Math.max(ms, MIN_SLIDE_DURATION_MS), MAX_SLIDE_DURATION_MS);
1468
+ };
1469
+ var SWIPE_DISTANCE = 40;
1470
+ var NARROW_SCREEN = css4`(max-width: 576px)`;
1471
+ var VISIBLE_SIDE = 2;
1472
+ var RENDERED_SIDE = VISIBLE_SIDE + 3;
1473
+ var carouselStyles = css4`
1474
+ .carousel {
1475
+ position: relative;
1476
+ box-sizing: border-box;
1477
+ display: grid;
1478
+ height: ${STAGE_HEIGHT};
1479
+ place-items: center;
1480
+ --card-height: ${STAGE_HEIGHT};
1481
+ user-select: none;
1482
+ }
1483
+
1484
+ .carousel[data-layout="solo"] {
1485
+ padding: ${SOLO_PADDING};
1486
+ border-radius: var(--vtex-ads-story-radius, 20px);
1487
+ background: var(--vtex-ads-story-color-surface, #fafafa);
1488
+ --card-height: calc(${STAGE_HEIGHT} - 2 * ${SOLO_PADDING});
1489
+ }
1490
+
1491
+ .carousel[data-layout="solo"] .card {
1492
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
1493
+ }
1494
+
1495
+ .track {
1496
+ position: absolute;
1497
+ inset: 0;
1498
+ overflow: hidden;
1499
+ touch-action: pan-y;
1500
+ }
1501
+
1502
+ /* Each slide starts centered, then moves by its own transform. */
1503
+ .slide {
1504
+ --ease: cubic-bezier(0.25, 1, 0.5, 1);
1505
+ --duration: var(--slide-duration, 0.4s);
1506
+ position: absolute;
1507
+ top: 0;
1508
+ left: 50%;
1509
+ width: calc(${STAGE_HEIGHT} * 9 / 16);
1510
+ height: 100%;
1511
+ margin-left: calc(${STAGE_HEIGHT} * 9 / -32);
1512
+ opacity: 0.5;
1513
+ transition:
1514
+ transform var(--duration) var(--ease),
1515
+ opacity var(--duration) var(--ease),
1516
+ visibility 0s;
1517
+ }
1518
+
1519
+ .slide[data-active] {
1520
+ opacity: 1;
1521
+ }
1522
+
1523
+ /* Pair: --side is -1 for the first card, 1 for the second. The highlighted
1524
+ card sits 47.5% of its width off center, the other (scaled to 0.9)
1525
+ 52.5%, so the gap between them stays 8px. */
1526
+ .carousel[data-layout="pair"] .slide {
1527
+ --side: 1;
1528
+ --offset: 52.5%;
1529
+ --scale: 0.9;
1530
+ transform: translateX(calc(var(--side) * (var(--offset) + 4px)))
1531
+ scale(var(--scale));
1532
+ }
1533
+
1534
+ .carousel[data-layout="pair"] .slide[data-index="0"] {
1535
+ --side: -1;
1536
+ }
1537
+
1538
+ .carousel[data-layout="pair"] .slide[data-active] {
1539
+ --offset: 47.5%;
1540
+ --scale: 1;
1541
+ }
1542
+
1543
+ /* Rolling: --place is the slide's distance from the highlighted one, in
1544
+ cards, 8px apart. A hidden slide fades out, then stops being visible. */
1545
+ .carousel[data-layout="rolling"] .slide {
1546
+ transform: translateX(calc(var(--place) * (100% + 8px))) scale(0.9);
1547
+ }
1548
+
1549
+ .carousel[data-layout="rolling"] .slide[data-active] {
1550
+ transform: translateX(0) scale(1);
1551
+ }
1552
+
1553
+ .slide[data-hidden] {
1554
+ opacity: 0;
1555
+ visibility: hidden;
1556
+ transition:
1557
+ transform var(--duration) var(--ease),
1558
+ opacity var(--duration) var(--ease),
1559
+ visibility 0s var(--duration);
1560
+ }
1561
+
1562
+ /* Only the highlighted card opens the player, so only it shows play. Its
1563
+ sound is the only one to turn on: the others play muted, if at all. */
1564
+ .slide:not([data-active]) .play,
1565
+ .slide:not([data-active]) .card-sound {
1566
+ display: none;
1567
+ }
1568
+
1569
+ .arrow {
1570
+ position: absolute;
1571
+ top: 50%;
1572
+ z-index: 2;
1573
+ display: grid;
1574
+ width: 32px;
1575
+ height: 32px;
1576
+ place-items: center;
1577
+ padding: 0;
1578
+ border: 1px solid rgba(133, 133, 133, 0.3);
1579
+ border-radius: 50%;
1580
+ background: rgba(0, 0, 0, 0.3);
1581
+ backdrop-filter: blur(5px);
1582
+ color: #fff;
1583
+ cursor: pointer;
1584
+ transform: translateY(-50%);
1585
+ transition: background-color 0.2s;
1586
+ }
1587
+
1588
+ .arrow:hover {
1589
+ background: #262626;
1590
+ }
1591
+
1592
+ .arrow:disabled {
1593
+ cursor: default;
1594
+ opacity: 0.5;
1595
+ }
1596
+
1597
+ .arrow .icon {
1598
+ width: 16px;
1599
+ height: 16px;
1600
+ }
1601
+
1602
+ .arrow-previous {
1603
+ left: 3px;
1604
+ }
1605
+
1606
+ .arrow-next {
1607
+ right: 3px;
1608
+ }
1609
+
1610
+ @media ${NARROW_SCREEN} {
1611
+ .carousel[data-layout="solo"] {
1612
+ padding: 0;
1613
+ background: none;
1614
+ --card-height: ${STAGE_HEIGHT};
1615
+ }
1616
+
1617
+ .carousel[data-layout="solo"] .card {
1618
+ box-shadow: none;
1619
+ }
1620
+ }
1621
+
1622
+ @media (prefers-reduced-motion: reduce) {
1623
+ .slide,
1624
+ .slide[data-hidden] {
1625
+ transition: none;
1626
+ }
1627
+ }
1628
+ `;
1629
+ var wrap = (value, count) => (value % count + count) % count;
1630
+ function tracker(elements, slide) {
1631
+ let last;
1632
+ return (element) => {
1633
+ if (last) elements.delete(last);
1634
+ last = element;
1635
+ if (element) elements.set(element, slide);
1636
+ };
1637
+ }
1638
+ var CarouselController = class {
1639
+ constructor(host, options) {
1640
+ this.host = host;
1641
+ this.options = options;
1642
+ /**
1643
+ * Steps taken since the Stories loaded, back and forth, not wrapped: the
1644
+ * rolling layout keys its slides by it.
1645
+ */
1646
+ this.position = 0;
1647
+ /** Stories moved by the last step: longer jumps animate a bit slower. */
1648
+ this.distance = 1;
1649
+ this.count = 0;
1650
+ this.narrow = false;
1651
+ this.reducedMotion = false;
1652
+ this.connected = false;
1653
+ this.hovered = false;
1654
+ this.focused = false;
1655
+ /** The interval the running timer was started with. */
1656
+ this.timerMs = 0;
1657
+ /** The rendered cards, as their cardRef reported them. */
1658
+ this.cards = /* @__PURE__ */ new Map();
1659
+ /** The rendered cards' focus targets, as their focusRef reported them. */
1660
+ this.focusTargets = /* @__PURE__ */ new Map();
1661
+ this.onMediaChange = (event) => {
1662
+ var _a, _b;
1663
+ const layout = this.layout;
1664
+ this.narrow = event.matches;
1665
+ if (this.layout === layout) return;
1666
+ (_b = (_a = this.options).onLayoutChange) == null ? void 0 : _b.call(_a);
1667
+ this.host.requestUpdate();
1668
+ };
1669
+ this.onPointerEnter = () => {
1670
+ this.hovered = true;
1671
+ this.syncTimer();
1672
+ };
1673
+ this.onPointerLeave = () => {
1674
+ this.hovered = false;
1675
+ this.syncTimer();
1676
+ };
1677
+ // Only keyboard focus stops the advance: a click also focuses the button
1678
+ // it hits, and the advance would then stay stopped after the pointer left.
1679
+ this.onFocusIn = (event) => {
1680
+ this.focused = event.target.matches(":focus-visible");
1681
+ this.syncTimer();
1682
+ };
1683
+ this.onFocusOut = (event) => {
1684
+ const carousel = event.currentTarget;
1685
+ const next = event.relatedTarget;
1686
+ if (!next || !carousel.contains(next)) this.focused = false;
1687
+ this.syncTimer();
1688
+ };
1689
+ // The release is listened for on the window: a mouse drag can end over an
1690
+ // arrow or off the carousel, where the track never gets the pointerup.
1691
+ this.onPointerDown = (event) => {
1692
+ this.endSwipe();
1693
+ this.swipe = { x: event.clientX, moved: false };
1694
+ globalThis.addEventListener("pointerup", this.onPointerUp);
1695
+ globalThis.addEventListener("pointercancel", this.onPointerCancel);
1696
+ };
1697
+ this.onPointerUp = (event) => {
1698
+ const { swipe } = this;
1699
+ this.removeSwipeListeners();
1700
+ if (!swipe) return;
1701
+ const distance = event.clientX - swipe.x;
1702
+ if (Math.abs(distance) > SWIPE_DISTANCE) {
1703
+ swipe.moved = true;
1704
+ this.step(distance < 0 ? 1 : -1);
1705
+ }
1706
+ };
1707
+ this.onPointerCancel = () => this.endSwipe();
1708
+ // A swipe ends with a click on the card under the pointer: it must not
1709
+ // open the player or select that card.
1710
+ this.onClickCapture = {
1711
+ handleEvent: (event) => {
1712
+ var _a;
1713
+ if ((_a = this.swipe) == null ? void 0 : _a.moved) {
1714
+ event.stopPropagation();
1715
+ event.preventDefault();
1716
+ }
1717
+ this.swipe = void 0;
1718
+ },
1719
+ capture: true
1720
+ };
1721
+ host.addController(this);
1722
+ }
1723
+ /** Index of the highlighted Story. */
1724
+ get active() {
1725
+ return this.count ? wrap(this.position, this.count) : 0;
1726
+ }
1727
+ get layout() {
1728
+ if (this.count < 2) return "solo";
1729
+ return this.count === 2 && !this.narrow ? "pair" : "rolling";
1730
+ }
1731
+ /** Key (see Slide) of the highlighted slide. */
1732
+ get activeKey() {
1733
+ if (this.layout === "rolling") return this.position;
1734
+ return this.active;
1735
+ }
1736
+ /**
1737
+ * The cards on screen, with their slide: not the hidden ones kept for the
1738
+ * slide in.
1739
+ */
1740
+ *visibleCards() {
1741
+ for (const [card, slide] of this.cards) {
1742
+ if (!slide.hidden) yield [card, slide];
1743
+ }
1744
+ }
1745
+ /** Moves the keyboard focus to the highlighted card, once rendered. */
1746
+ focusActive() {
1747
+ for (const [target, slide] of this.focusTargets) {
1748
+ if (slide.active && target instanceof HTMLElement) {
1749
+ target.focus();
1750
+ return;
1751
+ }
1752
+ }
1753
+ }
1754
+ hostConnected() {
1755
+ var _a, _b, _c, _d, _e, _f, _g;
1756
+ this.connected = true;
1757
+ this.media = (_a = globalThis.matchMedia) == null ? void 0 : _a.call(globalThis, NARROW_SCREEN.toString());
1758
+ (_b = this.media) == null ? void 0 : _b.addEventListener("change", this.onMediaChange);
1759
+ this.narrow = (_d = (_c = this.media) == null ? void 0 : _c.matches) != null ? _d : false;
1760
+ this.reducedMotion = (_g = (_f = (_e = this.options).reducedMotion) == null ? void 0 : _f.call(_e)) != null ? _g : false;
1761
+ this.syncTimer();
1762
+ }
1763
+ hostDisconnected() {
1764
+ var _a;
1765
+ this.connected = false;
1766
+ (_a = this.media) == null ? void 0 : _a.removeEventListener("change", this.onMediaChange);
1767
+ this.media = void 0;
1768
+ this.endSwipe();
1769
+ this.syncTimer();
1770
+ }
1771
+ // Whatever the host changed (the player opening, new Stories, the slide
1772
+ // duration) may start, stop or restart the automatic advance.
1773
+ hostUpdated() {
1774
+ this.syncTimer();
1775
+ }
1776
+ /** For a new list of Stories: the first one gets the highlight. */
1777
+ reset(count) {
1778
+ this.count = count;
1779
+ this.position = 0;
1780
+ this.distance = 1;
1781
+ this.hovered = false;
1782
+ this.focused = false;
1783
+ this.restartTimer();
1784
+ }
1785
+ /**
1786
+ * Moves the highlight by `delta` Stories, wrapping around the ends. While
1787
+ * locked, only with `evenIfLocked` (for example, the player stepping to
1788
+ * the next Story it shows).
1789
+ */
1790
+ step(delta, { evenIfLocked = false } = {}) {
1791
+ var _a, _b, _c, _d;
1792
+ if (this.count < 2 || delta === 0) return;
1793
+ if (((_b = (_a = this.options).locked) == null ? void 0 : _b.call(_a)) && !evenIfLocked) return;
1794
+ const from = this.activeKey;
1795
+ this.position += delta;
1796
+ this.distance = Math.abs(delta);
1797
+ this.host.requestUpdate();
1798
+ (_d = (_c = this.options).onStep) == null ? void 0 : _d.call(_c, from, this.activeKey);
1799
+ this.restartTimer();
1800
+ }
1801
+ get slideDuration() {
1802
+ var _a, _b;
1803
+ return toSlideDuration((_b = (_a = this.options).slideDuration) == null ? void 0 : _b.call(_a));
1804
+ }
1805
+ get shouldAdvance() {
1806
+ var _a, _b;
1807
+ return this.slideDuration > 0 && !this.reducedMotion && this.connected && this.count > 1 && !this.hovered && !this.focused && !((_b = (_a = this.options).locked) == null ? void 0 : _b.call(_a));
1808
+ }
1809
+ syncTimer() {
1810
+ const ms = this.slideDuration;
1811
+ if (this.timer && this.timerMs !== ms) this.stopTimer();
1812
+ if (this.shouldAdvance && !this.timer) {
1813
+ this.timerMs = ms;
1814
+ this.timer = setInterval(() => this.step(1), ms);
1815
+ } else if (!this.shouldAdvance && this.timer) {
1816
+ this.stopTimer();
1817
+ }
1818
+ }
1819
+ stopTimer() {
1820
+ clearInterval(this.timer);
1821
+ this.timer = void 0;
1822
+ this.timerMs = 0;
1823
+ }
1824
+ restartTimer() {
1825
+ this.stopTimer();
1826
+ this.syncTimer();
1827
+ }
1828
+ endSwipe() {
1829
+ this.removeSwipeListeners();
1830
+ this.swipe = void 0;
1831
+ }
1832
+ removeSwipeListeners() {
1833
+ globalThis.removeEventListener("pointerup", this.onPointerUp);
1834
+ globalThis.removeEventListener("pointercancel", this.onPointerCancel);
1835
+ }
1836
+ slide(fields) {
1837
+ const slide = {
1838
+ ...fields,
1839
+ cardRef: (element) => track(element),
1840
+ focusRef: (element) => trackFocus(element)
1841
+ };
1842
+ const track = tracker(this.cards, slide);
1843
+ const trackFocus = tracker(this.focusTargets, slide);
1844
+ return slide;
1845
+ }
1846
+ /** Pair: both Stories, each keyed by its index. */
1847
+ pairSlides() {
1848
+ const { active } = this;
1849
+ return [0, 1].map(
1850
+ (index) => this.slide({
1851
+ key: index,
1852
+ index,
1853
+ offset: index - active,
1854
+ active: index === active,
1855
+ hidden: false
1856
+ })
1857
+ );
1858
+ }
1859
+ /**
1860
+ * Rolling: the slides around the highlighted one, keyed by their position.
1861
+ * Up to VISIBLE_SIDE show on each side, fewer when there aren't enough
1862
+ * Stories to fill both sides without repeating: half on each side, the
1863
+ * extra one after it. With four, the Story opposite the highlighted one
1864
+ * shows at both ends; with two (narrow screens), the other one shows on
1865
+ * both sides.
1866
+ */
1867
+ rollingSlides() {
1868
+ const { count } = this;
1869
+ const even = count === 2 || count === 4;
1870
+ const before = even ? count / 2 : Math.floor((count - 1) / 2);
1871
+ const after = even ? count / 2 : count - 1 - before;
1872
+ const slides = [];
1873
+ for (let offset = -RENDERED_SIDE; offset <= RENDERED_SIDE; offset += 1) {
1874
+ slides.push(
1875
+ this.slide({
1876
+ key: this.position + offset,
1877
+ index: wrap(this.position + offset, count),
1878
+ offset,
1879
+ active: offset === 0,
1880
+ hidden: Math.abs(offset) > VISIBLE_SIDE || offset < -before || offset > after
1881
+ })
1882
+ );
1883
+ }
1884
+ return slides;
1885
+ }
1886
+ renderSlides(items, renderSlide) {
1887
+ const { layout } = this;
1888
+ const slides = layout === "pair" ? this.pairSlides() : this.rollingSlides();
1889
+ return repeat(
1890
+ slides,
1891
+ (slide) => `${layout}:${slide.key}`,
1892
+ (slide) => {
1893
+ const { index } = slide;
1894
+ return html5`
1895
+ <div
1896
+ class="slide"
1897
+ data-index=${index}
1898
+ ?data-active=${slide.active}
1899
+ ?data-hidden=${slide.hidden}
1900
+ ?inert=${slide.hidden}
1901
+ style=${styleMap({ "--place": String(slide.offset) })}
1902
+ >
1903
+ ${renderSlide(items[index], slide)}
1904
+ </div>
1905
+ `;
1906
+ }
1907
+ );
1908
+ }
1909
+ /**
1910
+ * One item: the card centered over the background. More: the cards in the
1911
+ * pair or rolling layout, with the arrows.
1912
+ */
1913
+ render(items, renderSlide, labels) {
1914
+ var _a, _b, _c;
1915
+ if (this.layout === "solo") {
1916
+ return html5`
1917
+ <div class="carousel" data-layout="solo">
1918
+ ${renderSlide(
1919
+ items[0],
1920
+ this.slide({
1921
+ key: 0,
1922
+ index: 0,
1923
+ offset: 0,
1924
+ active: true,
1925
+ hidden: false
1926
+ })
1927
+ )}
1928
+ </div>
1929
+ `;
1930
+ }
1931
+ const locked = (_c = (_b = (_a = this.options).locked) == null ? void 0 : _b.call(_a)) != null ? _c : false;
1932
+ return html5`
1933
+ <div
1934
+ class="carousel"
1935
+ data-layout=${this.layout}
1936
+ role="region"
1937
+ aria-roledescription=${labels.carouselRole}
1938
+ aria-label=${labels.carousel}
1939
+ @pointerenter=${this.onPointerEnter}
1940
+ @pointerleave=${this.onPointerLeave}
1941
+ @focusin=${this.onFocusIn}
1942
+ @focusout=${this.onFocusOut}
1943
+ >
1944
+ <div
1945
+ class="track"
1946
+ style=${styleMap({
1947
+ "--slide-duration": this.distance > 1 ? "0.52s" : "0.4s"
1948
+ })}
1949
+ @pointerdown=${this.onPointerDown}
1950
+ @click=${this.onClickCapture}
1951
+ >
1952
+ ${this.renderSlides(items, renderSlide)}
1953
+ </div>
1954
+ <button
1955
+ type="button"
1956
+ class="arrow arrow-previous"
1957
+ aria-label=${labels.previous}
1958
+ ?disabled=${locked}
1959
+ @click=${() => this.step(-1)}
1960
+ >
1961
+ ${icon("previous")}
1962
+ </button>
1963
+ <button
1964
+ type="button"
1965
+ class="arrow arrow-next"
1966
+ aria-label=${labels.next}
1967
+ ?disabled=${locked}
1968
+ @click=${() => this.step(1)}
1969
+ >
1970
+ ${icon("next")}
1971
+ </button>
1972
+ </div>
1973
+ `;
1974
+ }
1975
+ };
1976
+
1977
+ // src/components/carousel/carousel-skeleton.ts
1978
+ import { css as css5, html as html6 } from "lit";
1979
+ import { styleMap as styleMap2 } from "lit/directives/style-map.js";
1980
+ var carouselSkeletonStyles = css5`
1981
+ .root {
1982
+ position: relative;
1983
+ }
1984
+
1985
+ .root[data-requesting] {
1986
+ height: ${STAGE_HEIGHT};
1987
+ }
1988
+
1989
+ .root[data-loading] .carousel {
1990
+ visibility: hidden;
1991
+ }
1992
+
1993
+ .skeleton {
1994
+ position: absolute;
1995
+ inset: 0;
1996
+ z-index: 2;
1997
+ box-sizing: border-box;
1998
+ overflow: hidden;
1999
+ pointer-events: none;
2000
+ transition:
2001
+ opacity 0.3s ease,
2002
+ visibility 0s;
2003
+ }
2004
+
2005
+ .skeleton[data-done] {
2006
+ opacity: 0;
2007
+ visibility: hidden;
2008
+ transition:
2009
+ opacity 0.3s ease,
2010
+ visibility 0s 0.3s;
2011
+ }
2012
+
2013
+ .skeleton-slide {
2014
+ position: absolute;
2015
+ top: 0;
2016
+ left: 50%;
2017
+ width: calc(${STAGE_HEIGHT} * 9 / 16);
2018
+ height: 100%;
2019
+ margin-left: calc(${STAGE_HEIGHT} * 9 / -32);
2020
+ transform: translateX(calc(var(--place) * (100% + 8px))) scale(0.9);
2021
+ }
2022
+
2023
+ .skeleton-slide[data-active] {
2024
+ transform: none;
2025
+ }
2026
+
2027
+ .skeleton-card {
2028
+ width: 100%;
2029
+ height: 100%;
2030
+ border-radius: var(--vtex-ads-story-radius, 20px);
2031
+ background: #ececec;
2032
+ animation: skeleton-pulse 1.2s ease-in-out infinite alternate;
2033
+ }
2034
+
2035
+ .skeleton[data-done] .skeleton-card {
2036
+ animation: none;
2037
+ }
2038
+
2039
+ @keyframes skeleton-pulse {
2040
+ to {
2041
+ background-color: #f6f6f6;
2042
+ }
2043
+ }
2044
+
2045
+ @media (prefers-reduced-motion: reduce) {
2046
+ .skeleton,
2047
+ .skeleton[data-done] {
2048
+ transition: none;
2049
+ }
2050
+
2051
+ .skeleton-card {
2052
+ animation: none;
2053
+ }
2054
+ }
2055
+ `;
2056
+ function renderCarouselSkeleton({ done }) {
2057
+ const places = Array.from(
2058
+ { length: VISIBLE_SIDE * 2 + 1 },
2059
+ (_, i) => i - VISIBLE_SIDE
2060
+ );
2061
+ return html6`
2062
+ <div class="skeleton" aria-hidden="true" ?data-done=${done}>
2063
+ ${places.map(
2064
+ (place) => html6`
2065
+ <div
2066
+ class="skeleton-slide"
2067
+ ?data-active=${place === 0}
2068
+ style=${styleMap2({ "--place": String(place) })}
2069
+ >
2070
+ <div class="skeleton-card"></div>
2071
+ </div>
2072
+ `
2073
+ )}
295
2074
  </div>
296
2075
  `;
297
2076
  }
298
2077
 
2078
+ // src/tag-name.ts
2079
+ var TAG_NAME = "vtex-ads-story-carousel";
2080
+
2081
+ // src/utils/send-event.ts
2082
+ var CONTENT_TYPE = "text/plain;charset=utf-8";
2083
+ function sendEvent(url, { sessionId, userId }) {
2084
+ var _a, _b;
2085
+ const target = httpUrl(url);
2086
+ if (!target || globalThis.window === void 0) return false;
2087
+ const body = JSON.stringify(
2088
+ userId ? { session_id: sessionId, user_id: userId } : { session_id: sessionId }
2089
+ );
2090
+ try {
2091
+ const queued = (_b = (_a = globalThis.navigator) == null ? void 0 : _a.sendBeacon) == null ? void 0 : _b.call(
2092
+ _a,
2093
+ target,
2094
+ new Blob([body], { type: CONTENT_TYPE })
2095
+ );
2096
+ if (queued) return true;
2097
+ } catch (e) {
2098
+ }
2099
+ if (typeof globalThis.fetch !== "function") return false;
2100
+ globalThis.fetch(target, {
2101
+ method: "POST",
2102
+ headers: { "Content-Type": CONTENT_TYPE },
2103
+ body,
2104
+ keepalive: true,
2105
+ credentials: "omit"
2106
+ }).catch((error) => {
2107
+ console.error(`[${TAG_NAME}] Event request failed`, {
2108
+ url: target,
2109
+ error
2110
+ });
2111
+ });
2112
+ return true;
2113
+ }
2114
+
2115
+ // src/components/events/events-controller.ts
2116
+ var VIEW_THRESHOLD = 0.5;
2117
+ var VIEW_DURATION_MS = 2e3;
2118
+ var URL_FIELD = {
2119
+ impression: "impression_url",
2120
+ view: "view_url",
2121
+ click: "click_url"
2122
+ };
2123
+ var StoryEventsController = class {
2124
+ constructor(host, options) {
2125
+ this.host = host;
2126
+ this.options = options;
2127
+ this.sent = {
2128
+ impression: /* @__PURE__ */ new Set(),
2129
+ view: /* @__PURE__ */ new Set(),
2130
+ click: /* @__PURE__ */ new Set()
2131
+ };
2132
+ this.pendingImpressions = [];
2133
+ this.connected = false;
2134
+ this.watched = /* @__PURE__ */ new Map();
2135
+ this.onIntersect = (entries) => {
2136
+ for (const entry of entries) {
2137
+ const watched = this.watched.get(entry.target);
2138
+ if (!watched) continue;
2139
+ watched.visible = entry.isIntersecting && entry.intersectionRatio >= VIEW_THRESHOLD;
2140
+ if (watched.visible) this.startTimer(watched);
2141
+ else this.stopTimer(watched);
2142
+ }
2143
+ };
2144
+ // A hidden page (another tab, minimized) breaks the 2 seconds: they start
2145
+ // over when it shows again.
2146
+ this.onVisibilityChange = () => {
2147
+ for (const watched of this.watched.values()) {
2148
+ if (document.hidden) this.stopTimer(watched);
2149
+ else if (watched.visible) this.startTimer(watched);
2150
+ }
2151
+ };
2152
+ host.addController(this);
2153
+ }
2154
+ hostConnected() {
2155
+ var _a;
2156
+ this.connected = true;
2157
+ if (typeof IntersectionObserver === "function") {
2158
+ this.observer = new IntersectionObserver(this.onIntersect, {
2159
+ threshold: VIEW_THRESHOLD
2160
+ });
2161
+ }
2162
+ (_a = globalThis.document) == null ? void 0 : _a.addEventListener(
2163
+ "visibilitychange",
2164
+ this.onVisibilityChange
2165
+ );
2166
+ this.host.updateComplete.then(() => {
2167
+ if (!this.connected) return;
2168
+ this.sendImpressions();
2169
+ this.syncViewTargets();
2170
+ });
2171
+ }
2172
+ hostDisconnected() {
2173
+ var _a, _b;
2174
+ this.connected = false;
2175
+ (_a = globalThis.document) == null ? void 0 : _a.removeEventListener(
2176
+ "visibilitychange",
2177
+ this.onVisibilityChange
2178
+ );
2179
+ (_b = this.observer) == null ? void 0 : _b.disconnect();
2180
+ this.observer = void 0;
2181
+ for (const watched of this.watched.values()) clearTimeout(watched.timer);
2182
+ this.watched.clear();
2183
+ }
2184
+ hostUpdated() {
2185
+ if (!this.connected) return;
2186
+ this.sendImpressions();
2187
+ this.syncViewTargets();
2188
+ }
2189
+ /**
2190
+ * The Stories the host shows next: their impressions go out once that
2191
+ * render is done, on the page, with a session (or after the first render
2192
+ * that has both). Replaces Stories passed before and not sent yet.
2193
+ */
2194
+ impress(stories) {
2195
+ this.pendingImpressions = stories;
2196
+ }
2197
+ sendImpressions() {
2198
+ const stories = this.pendingImpressions;
2199
+ if (!stories.length || !this.options.identity().sessionId) return;
2200
+ this.pendingImpressions = [];
2201
+ for (const story of stories) this.send("impression", story);
2202
+ }
2203
+ /** A touch on the Story: its click goes out, the first time only. */
2204
+ click(story) {
2205
+ this.send("click", story);
2206
+ }
2207
+ key(sessionId, story) {
2208
+ return `${sessionId}|${story.ad_id}`;
2209
+ }
2210
+ wasSent(kind, story) {
2211
+ const { sessionId } = this.options.identity();
2212
+ return !!sessionId && this.sent[kind].has(this.key(sessionId, story));
2213
+ }
2214
+ send(kind, story) {
2215
+ const { sessionId, userId } = this.options.identity();
2216
+ if (!sessionId || this.wasSent(kind, story)) return;
2217
+ const success = sendEvent(story[URL_FIELD[kind]], { sessionId, userId });
2218
+ if (success) {
2219
+ this.sent[kind].add(this.key(sessionId, story));
2220
+ }
2221
+ }
2222
+ // Watches the elements the host shows now, and stops watching the others,
2223
+ // dropping the time they had on screen.
2224
+ syncViewTargets() {
2225
+ const { observer } = this;
2226
+ if (!observer) return;
2227
+ const current = /* @__PURE__ */ new Map();
2228
+ for (const [element, story] of this.options.viewTargets()) {
2229
+ if (!this.wasSent("view", story)) current.set(element, story);
2230
+ }
2231
+ for (const [element, watched] of this.watched) {
2232
+ if (current.get(element) !== watched.story) {
2233
+ this.unwatch(element, watched);
2234
+ }
2235
+ }
2236
+ for (const [element, story] of current) {
2237
+ if (this.watched.has(element)) continue;
2238
+ this.watched.set(element, { story, visible: false });
2239
+ observer.observe(element);
2240
+ }
2241
+ }
2242
+ startTimer(watched) {
2243
+ var _a;
2244
+ if (watched.timer || ((_a = globalThis.document) == null ? void 0 : _a.hidden)) return;
2245
+ watched.timer = setTimeout(() => {
2246
+ watched.timer = void 0;
2247
+ this.send("view", watched.story);
2248
+ if (this.wasSent("view", watched.story)) this.unwatchStory(watched.story);
2249
+ }, VIEW_DURATION_MS);
2250
+ }
2251
+ stopTimer(watched) {
2252
+ clearTimeout(watched.timer);
2253
+ watched.timer = void 0;
2254
+ }
2255
+ unwatch(element, watched) {
2256
+ var _a;
2257
+ this.stopTimer(watched);
2258
+ (_a = this.observer) == null ? void 0 : _a.unobserve(element);
2259
+ this.watched.delete(element);
2260
+ }
2261
+ unwatchStory(story) {
2262
+ for (const [element, watched] of this.watched) {
2263
+ if (watched.story.ad_id === story.ad_id) this.unwatch(element, watched);
2264
+ }
2265
+ }
2266
+ };
2267
+
299
2268
  // src/components/player/player.ts
300
- import { css as css2, html as html3, nothing as nothing3 } from "lit";
301
- import { createRef as createRef2, ref as ref2 } from "lit/directives/ref.js";
302
- var playerStyles = css2`
2269
+ import { css as css6, html as html7, nothing as nothing4 } from "lit";
2270
+ import { createRef as createRef2, ref as ref3 } from "lit/directives/ref.js";
2271
+ import { repeat as repeat2 } from "lit/directives/repeat.js";
2272
+ import { styleMap as styleMap3 } from "lit/directives/style-map.js";
2273
+ var NEAR_GAP = 72;
2274
+ var FAR_GAP = 48;
2275
+ var playerStyles = css6`
303
2276
  .player {
304
2277
  position: fixed;
305
2278
  inset: auto 16px 16px auto;
@@ -332,12 +2305,28 @@ var playerStyles = css2`
332
2305
  background: transparent;
333
2306
  }
334
2307
 
2308
+ /* Focusable only to keep the focus in the player when its video is clicked
2309
+ (see render): no ring around the whole player. */
2310
+ .player:focus {
2311
+ outline: none;
2312
+ }
2313
+
335
2314
  .player-frame {
336
2315
  position: relative;
337
2316
  width: 100%;
338
2317
  height: 100%;
339
2318
  }
340
2319
 
2320
+ /* What moves in the expanded view, off center with two Stories and in the
2321
+ step animation: the video, its dimming and previous and next. Expand and
2322
+ close stay out of it: a transformed box becomes the one their fixed
2323
+ position, at the top right of the screen, is measured from. */
2324
+ .player-stage {
2325
+ position: relative;
2326
+ width: 100%;
2327
+ height: 100%;
2328
+ }
2329
+
341
2330
  .player .card {
342
2331
  width: 100%;
343
2332
  height: 100%;
@@ -384,6 +2373,26 @@ var playerStyles = css2`
384
2373
  height: 20px;
385
2374
  }
386
2375
 
2376
+ /* The product pill or the call to action. Their wrapper only stops clicks:
2377
+ the pill places itself. The product is larger than on the carousel card
2378
+ (as in the prototype). */
2379
+ .player-destination {
2380
+ display: contents;
2381
+ }
2382
+
2383
+ .player .product-info {
2384
+ font-size: 14px;
2385
+ }
2386
+
2387
+ .player .product-image {
2388
+ width: 72px;
2389
+ height: 72px;
2390
+ }
2391
+
2392
+ .player .product-price {
2393
+ color: rgba(255, 255, 255, 0.7);
2394
+ }
2395
+
387
2396
  /* Above the card: on narrow screens the expanded card can cover them. */
388
2397
  .player-controls {
389
2398
  position: absolute;
@@ -394,6 +2403,12 @@ var playerStyles = css2`
394
2403
  gap: 8px;
395
2404
  }
396
2405
 
2406
+ /* Previous and next Story, above the card's top left (mini player only). */
2407
+ .player-nav {
2408
+ right: auto;
2409
+ left: 0;
2410
+ }
2411
+
397
2412
  .player-button {
398
2413
  display: grid;
399
2414
  width: 36px;
@@ -447,6 +2462,116 @@ var playerStyles = css2`
447
2462
  height: 40px;
448
2463
  }
449
2464
 
2465
+ /* Expanded with more than one Story: the other Stories' covers beside the
2466
+ video, smaller and dimmed, as in the prototype. --side is -1 (before)
2467
+ or 1 (after), --beyond how many places past the nearest one. */
2468
+ .player[data-expanded] {
2469
+ --center-height: min(78vh, 720px);
2470
+ --side-height: min(38vh, 320px);
2471
+ --side-width: calc(var(--side-height) * 9 / 16);
2472
+ --center-half: calc(var(--center-height) * 9 / 32);
2473
+ --near-gap: ${NEAR_GAP}px;
2474
+ --far-gap: ${FAR_GAP}px;
2475
+ --near: calc(var(--center-half) + var(--near-gap) + var(--side-width) / 2);
2476
+ --pitch: calc(var(--side-width) + var(--far-gap));
2477
+ }
2478
+
2479
+ .player-neighbor {
2480
+ position: absolute;
2481
+ top: 50%;
2482
+ left: 50%;
2483
+ width: var(--side-width);
2484
+ height: var(--side-height);
2485
+ padding: 0;
2486
+ overflow: hidden;
2487
+ border: 0;
2488
+ border-radius: var(--vtex-ads-story-radius, 16px);
2489
+ background: #111;
2490
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
2491
+ cursor: pointer;
2492
+ transform: translate(
2493
+ calc(-50% + var(--side) * var(--near) + var(--beyond) * var(--pitch)),
2494
+ -50%
2495
+ );
2496
+ }
2497
+
2498
+ .player-neighbor img {
2499
+ width: 100%;
2500
+ height: 100%;
2501
+ object-fit: cover;
2502
+ }
2503
+
2504
+ /* Fades out as the video arrives from a dimmed cover (see animateStep). */
2505
+ .player-dim {
2506
+ position: absolute;
2507
+ inset: 0;
2508
+ z-index: 3;
2509
+ border-radius: var(--vtex-ads-story-radius, 20px);
2510
+ background: rgba(0, 0, 0, 0.35);
2511
+ opacity: 0;
2512
+ pointer-events: none;
2513
+ }
2514
+
2515
+ .player-neighbor::after {
2516
+ position: absolute;
2517
+ inset: 0;
2518
+ background: rgba(0, 0, 0, 0.35);
2519
+ content: "";
2520
+ }
2521
+
2522
+ .player-neighbor:hover::after,
2523
+ .player-neighbor:focus-visible::after {
2524
+ background: rgba(0, 0, 0, 0.12);
2525
+ }
2526
+
2527
+ .player-neighbor:focus-visible {
2528
+ outline: 2px solid #fff;
2529
+ outline-offset: 2px;
2530
+ }
2531
+
2532
+ /* Two Stories: the video moves off center toward --pair-dir, and the other
2533
+ Story sits on the other side. */
2534
+ .player[data-pair] .player-stage {
2535
+ transform: translateX(
2536
+ calc(var(--pair-dir) * (var(--near-gap) + var(--side-width)) / 2)
2537
+ );
2538
+ }
2539
+
2540
+ .player[data-pair] .player-neighbor {
2541
+ transform: translate(
2542
+ calc(
2543
+ -50% + var(--pair-dir) * -1 * (var(--center-half) + var(--near-gap) / 2)
2544
+ ),
2545
+ -50%
2546
+ );
2547
+ }
2548
+
2549
+ /* Expanded previous and next: beside the video, centered on its height. */
2550
+ .player[data-expanded] .player-nav {
2551
+ position: static;
2552
+ display: contents;
2553
+ }
2554
+
2555
+ .player[data-expanded] .player-nav .player-button {
2556
+ position: absolute;
2557
+ top: 50%;
2558
+ z-index: 2;
2559
+ transform: translateY(-50%);
2560
+ }
2561
+
2562
+ .player[data-expanded] .player-previous {
2563
+ left: -56px;
2564
+ }
2565
+
2566
+ .player[data-expanded] .player-next {
2567
+ right: -56px;
2568
+ }
2569
+
2570
+ /* With two, the other Story's cover beside the video does that. */
2571
+ .player[data-expanded][data-pair] .player-nav {
2572
+ display: none;
2573
+ }
2574
+
450
2575
  @media (max-width: 576px) {
451
2576
  .player {
452
2577
  right: 12px;
@@ -454,6 +2579,18 @@ var playerStyles = css2`
454
2579
  height: 391px;
455
2580
  }
456
2581
 
2582
+ .player:not([data-expanded]) .product-image {
2583
+ width: 56px;
2584
+ height: 56px;
2585
+ }
2586
+
2587
+ /* "Adicionar ao carrinho" fits on one line in the narrow mini player. */
2588
+ .player:not([data-expanded]) .product-action {
2589
+ height: 40px;
2590
+ padding: 0 8px;
2591
+ font-size: 12px;
2592
+ }
2593
+
457
2594
  .player[data-expanded] {
458
2595
  background: #000;
459
2596
  }
@@ -476,6 +2613,28 @@ var playerStyles = css2`
476
2613
  top: 60px;
477
2614
  right: 12px;
478
2615
  }
2616
+
2617
+ /* No room for the other Stories' covers: previous and next go inside
2618
+ the video's edges instead, also with two. */
2619
+ .player-neighbor {
2620
+ display: none;
2621
+ }
2622
+
2623
+ .player[data-pair] .player-stage {
2624
+ transform: none;
2625
+ }
2626
+
2627
+ .player[data-expanded][data-pair] .player-nav {
2628
+ display: contents;
2629
+ }
2630
+
2631
+ .player[data-expanded] .player-previous {
2632
+ left: 12px;
2633
+ }
2634
+
2635
+ .player[data-expanded] .player-next {
2636
+ right: 12px;
2637
+ }
479
2638
  }
480
2639
 
481
2640
  @keyframes player-in {
@@ -491,6 +2650,88 @@ var playerStyles = css2`
491
2650
  }
492
2651
  }
493
2652
  `;
2653
+ function neighborOffsets(count, active) {
2654
+ if (count < 2) return [];
2655
+ if (count === 2) return [active === 0 ? 1 : -1];
2656
+ const offsets = [];
2657
+ const shown = /* @__PURE__ */ new Set([0]);
2658
+ for (const offset of [-1, 1, -2, 2]) {
2659
+ const index = (offset % count + count) % count;
2660
+ if (!shown.has(index)) {
2661
+ shown.add(index);
2662
+ offsets.push(offset);
2663
+ }
2664
+ }
2665
+ return offsets;
2666
+ }
2667
+ var STEP_ANIMATION = {
2668
+ duration: 560,
2669
+ easing: "cubic-bezier(0.32, 0.72, 0, 1)"
2670
+ };
2671
+ var coverTransform = (x, scale = 1) => `translate(-50%, -50%) translateX(${x}px) scale(${scale})`;
2672
+ var fadeIn = (element) => element.animate([{ opacity: 0 }, { opacity: 1 }], {
2673
+ ...STEP_ANIMATION,
2674
+ pseudoElement: "::after"
2675
+ });
2676
+ function animateRailStep(frame, frameFrom, neighbors, { frameWidth, sideWidth }) {
2677
+ const placeX = (place) => {
2678
+ if (place === 0) return 0;
2679
+ const side = Math.sign(place);
2680
+ const near = frameWidth / 2 + NEAR_GAP + sideWidth / 2;
2681
+ return side * near + (place - side) * (sideWidth + FAR_GAP);
2682
+ };
2683
+ const ratio = sideWidth / frameWidth;
2684
+ const animations = [
2685
+ frame.animate(
2686
+ [
2687
+ { transform: `translateX(${placeX(frameFrom)}px) scale(${ratio})` },
2688
+ { transform: "none" }
2689
+ ],
2690
+ STEP_ANIMATION
2691
+ )
2692
+ ];
2693
+ for (const { element, offset, from } of neighbors) {
2694
+ const wasVideo = from === 0;
2695
+ animations.push(
2696
+ element.animate(
2697
+ [
2698
+ { transform: coverTransform(placeX(from), wasVideo ? 1 / ratio : 1) },
2699
+ { transform: coverTransform(placeX(offset)) }
2700
+ ],
2701
+ STEP_ANIMATION
2702
+ )
2703
+ );
2704
+ if (wasVideo) animations.push(fadeIn(element));
2705
+ }
2706
+ return animations;
2707
+ }
2708
+ function animatePairStep(frame, neighbor, direction, { frameWidth, sideWidth }) {
2709
+ const videoX = (side) => side * (NEAR_GAP + sideWidth) / 2;
2710
+ const coverX = (side) => -side * (frameWidth + NEAR_GAP) / 2;
2711
+ const ratio = sideWidth / frameWidth;
2712
+ return [
2713
+ frame.animate(
2714
+ [
2715
+ { transform: `translateX(${coverX(-direction)}px) scale(${ratio})` },
2716
+ { transform: `translateX(${videoX(direction)}px)` }
2717
+ ],
2718
+ STEP_ANIMATION
2719
+ ),
2720
+ neighbor.animate(
2721
+ [
2722
+ { transform: coverTransform(videoX(-direction), 1 / ratio) },
2723
+ { transform: coverTransform(coverX(direction)) }
2724
+ ],
2725
+ STEP_ANIMATION
2726
+ ),
2727
+ fadeIn(neighbor)
2728
+ ];
2729
+ }
2730
+ var ARROW_STEPS = {
2731
+ ArrowLeft: -1,
2732
+ ArrowRight: 1
2733
+ };
2734
+ var isFreeArrowKey = (event) => !event.defaultPrevented && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;
494
2735
  function supportsPopover(dialog) {
495
2736
  return typeof dialog.showPopover === "function";
496
2737
  }
@@ -501,6 +2742,8 @@ var PlayerController = class {
501
2742
  /** Rendered and, once the host has updated, shown. */
502
2743
  this.isOpen = false;
503
2744
  this.expanded = false;
2745
+ /** The product panel is open. Closed again on a step and on opening. */
2746
+ this.productOpen = false;
504
2747
  /** Switched modes at least once: only the first opening fades in. */
505
2748
  this.switched = false;
506
2749
  /** The dialog is showing, in the mode `expanded` says. */
@@ -508,10 +2751,24 @@ var PlayerController = class {
508
2751
  this.dialog = createRef2();
509
2752
  this.expandButton = createRef2();
510
2753
  this.closeButton = createRef2();
2754
+ this.stage = createRef2();
2755
+ this.stageCardRef = createRef2();
2756
+ this.dim = createRef2();
2757
+ /** The covers beside the expanded video, by offset, as rendered. */
2758
+ this.neighborElements = /* @__PURE__ */ new Map();
2759
+ /** One ref callback per offset: a new one each render would detach it. */
2760
+ this.neighborRefs = /* @__PURE__ */ new Map();
2761
+ /** Rendered with previous and next (see PlayerRenderOptions). */
2762
+ this.navigation = false;
2763
+ /** Side the expanded video moved to with two Stories; 0 otherwise. */
2764
+ this.pairDirection = 0;
2765
+ /** The step animation running, cancelled by the next step. */
2766
+ this.animations = [];
511
2767
  this.toggleExpanded = async () => {
512
2768
  var _a;
513
2769
  const dialog = this.dialog.value;
514
2770
  if (!dialog) return;
2771
+ this.cancelAnimations();
515
2772
  this.hide(dialog);
516
2773
  this.expanded = !this.expanded;
517
2774
  this.switched = true;
@@ -525,6 +2782,17 @@ var PlayerController = class {
525
2782
  this.onKeyDown = (event) => {
526
2783
  if (event.key === "Escape") this.options.onClose();
527
2784
  };
2785
+ // With the focus in the player and more than one Story, the arrows step, as
2786
+ // the previous and next buttons do. Only there: the mini player leaves the
2787
+ // page usable, and the page's own arrow keys (a gallery, a slider) keep
2788
+ // working.
2789
+ this.onPlayerKeyDown = (event) => {
2790
+ var _a, _b;
2791
+ const delta = ARROW_STEPS[event.key];
2792
+ if (!delta || !this.navigation || !isFreeArrowKey(event)) return;
2793
+ event.preventDefault();
2794
+ (_b = (_a = this.options).onStep) == null ? void 0 : _b.call(_a, delta);
2795
+ };
528
2796
  // Clicks on the backdrop of the expanded view reach the dialog itself.
529
2797
  this.onDialogClick = (event) => {
530
2798
  if (this.expanded && event.target === event.currentTarget) {
@@ -536,38 +2804,171 @@ var PlayerController = class {
536
2804
  event.preventDefault();
537
2805
  this.options.onClose();
538
2806
  };
2807
+ /**
2808
+ * Play/pause in the middle of the video and sound on/off at its top right.
2809
+ * They follow the video's own events, so a blocked autoplay shows as
2810
+ * paused.
2811
+ */
2812
+ this.toggleProduct = () => {
2813
+ this.productOpen = !this.productOpen;
2814
+ this.host.requestUpdate();
2815
+ };
2816
+ /**
2817
+ * Loads the failed video again and, once it loads, plays it with the sound
2818
+ * on (muted if the browser blocks it). Not if the player closed or stepped
2819
+ * meanwhile, even back to the same Story: the retry then resolves false.
2820
+ */
2821
+ this.retryVideo = () => {
2822
+ var _a;
2823
+ (_a = this.dialog.value) == null ? void 0 : _a.focus();
2824
+ void this.video.retry().then((loaded) => {
2825
+ if (loaded) this.video.playWithSound();
2826
+ });
2827
+ };
2828
+ /**
2829
+ * A click on the video: closes the product panel when it is open, plays or
2830
+ * pauses the video otherwise.
2831
+ */
2832
+ this.onVideoClick = () => {
2833
+ if (this.productOpen) this.toggleProduct();
2834
+ else this.video.togglePlayback();
2835
+ };
539
2836
  host.addController(this);
540
2837
  this.video = new VideoController(host);
541
2838
  }
2839
+ /** Open in the expanded view, a modal over the page. */
2840
+ get isExpanded() {
2841
+ return this.isOpen && this.expanded;
2842
+ }
2843
+ /** The card with the video, while the player is open. */
2844
+ get stageCard() {
2845
+ return this.isOpen ? this.stageCardRef.value : void 0;
2846
+ }
542
2847
  hostDisconnected() {
543
2848
  this.close();
544
2849
  }
545
- /** Opens the mini player, plays the video and focuses the close button. */
546
- async open() {
2850
+ /**
2851
+ * Opens the mini player, plays the video with the sound on (muted if the
2852
+ * browser blocks it) and focuses the close button.
2853
+ * With `productOpen`, the product panel shows open (the shopper chose the
2854
+ * product).
2855
+ */
2856
+ async open({ productOpen = false } = {}) {
547
2857
  var _a;
548
2858
  if (this.isOpen) return;
549
2859
  document.addEventListener("keydown", this.onKeyDown);
550
2860
  this.isOpen = true;
551
2861
  this.expanded = false;
2862
+ this.productOpen = productOpen;
552
2863
  this.switched = false;
2864
+ this.rendered = void 0;
2865
+ this.beforeStep = void 0;
553
2866
  this.video.reset();
554
2867
  this.host.requestUpdate();
555
2868
  await this.host.updateComplete;
556
2869
  const dialog = this.dialog.value;
557
2870
  if (!this.isOpen || !dialog) return;
558
2871
  this.show(dialog);
559
- this.video.play();
2872
+ this.video.playWithSound();
560
2873
  (_a = this.closeButton.value) == null ? void 0 : _a.focus();
561
2874
  }
562
2875
  /** Hides the player now; the host removes it on its next update. */
563
2876
  close() {
564
2877
  if (!this.isOpen) return;
565
2878
  document.removeEventListener("keydown", this.onKeyDown);
2879
+ this.cancelAnimations();
566
2880
  const dialog = this.dialog.value;
567
2881
  if (dialog) this.hide(dialog);
568
2882
  this.isOpen = false;
569
2883
  this.host.requestUpdate();
570
2884
  }
2885
+ /**
2886
+ * After the host renders a different Story in the open player, `delta`
2887
+ * places from the previous one: its video starts from the top and plays,
2888
+ * with the sound as the shopper left it. A failed load of the previous
2889
+ * video doesn't hide the new one. The expanded view animates the step.
2890
+ */
2891
+ async showNext(delta = 0) {
2892
+ if (!this.isOpen) return;
2893
+ const withSound = !this.video.muted;
2894
+ this.video.clearFailure();
2895
+ this.productOpen = false;
2896
+ this.host.requestUpdate();
2897
+ await this.host.updateComplete;
2898
+ if (!this.isOpen) return;
2899
+ this.video.restart({ withSound });
2900
+ this.animateStep(delta);
2901
+ }
2902
+ /** Stops a step animation still running, leaving the CSS layout. */
2903
+ cancelAnimations() {
2904
+ for (const animation of this.animations) animation.cancel();
2905
+ this.animations = [];
2906
+ }
2907
+ /**
2908
+ * The expanded step, as in the prototype: the video grows from the cover
2909
+ * of the Story it now shows, and the covers slide to their new places, the
2910
+ * previous Story's shrinking from the video's size. With two Stories, the
2911
+ * video and the other cover swap sides. Not with reduced motion, nor
2912
+ * without covers (narrow screens).
2913
+ */
2914
+ animateStep(delta) {
2915
+ var _a, _b;
2916
+ if (!this.expanded || delta === 0 || prefersReducedMotion()) return;
2917
+ const frame = this.stage.value;
2918
+ const dim = this.dim.value;
2919
+ if (!frame || !dim || typeof frame.animate !== "function") return;
2920
+ const { rendered, beforeStep } = this;
2921
+ const placeBefore = (story, fallback) => {
2922
+ var _a2;
2923
+ if (!story || !beforeStep) return fallback;
2924
+ if (story === beforeStep.story) return 0;
2925
+ const cover = beforeStep.neighbors.find((n) => n.story === story);
2926
+ return (_a2 = cover == null ? void 0 : cover.offset) != null ? _a2 : fallback;
2927
+ };
2928
+ const neighbors = [...this.neighborElements].map(([offset, element]) => {
2929
+ var _a2;
2930
+ return {
2931
+ offset,
2932
+ element,
2933
+ from: placeBefore(
2934
+ (_a2 = rendered == null ? void 0 : rendered.neighbors.find((n) => n.offset === offset)) == null ? void 0 : _a2.story,
2935
+ offset + delta
2936
+ )
2937
+ };
2938
+ });
2939
+ const sizes = {
2940
+ frameWidth: frame.offsetWidth,
2941
+ sideWidth: (_b = (_a = neighbors[0]) == null ? void 0 : _a.element.offsetWidth) != null ? _b : 0
2942
+ };
2943
+ if (!sizes.frameWidth || !sizes.sideWidth) return;
2944
+ this.cancelAnimations();
2945
+ this.animations = [
2946
+ dim.animate([{ opacity: 1 }, { opacity: 0 }], STEP_ANIMATION),
2947
+ ...this.pairDirection ? animatePairStep(
2948
+ frame,
2949
+ neighbors[0].element,
2950
+ this.pairDirection,
2951
+ sizes
2952
+ ) : animateRailStep(
2953
+ frame,
2954
+ placeBefore(rendered == null ? void 0 : rendered.story, delta),
2955
+ neighbors,
2956
+ sizes
2957
+ )
2958
+ ];
2959
+ }
2960
+ // Keeps neighborElements in step with the covers Lit renders.
2961
+ neighborRef(offset) {
2962
+ let callback = this.neighborRefs.get(offset);
2963
+ if (!callback) {
2964
+ callback = (element) => {
2965
+ if (element) this.neighborElements.set(offset, element);
2966
+ else this.neighborElements.delete(offset);
2967
+ };
2968
+ this.neighborRefs.set(offset, callback);
2969
+ }
2970
+ return callback;
2971
+ }
571
2972
  // Mini: a manual popover, or a non-modal dialog without popover support.
572
2973
  // Expanded: a modal dialog.
573
2974
  // Already showing: a second expand click in the same task resumes after the
@@ -588,12 +2989,41 @@ var PlayerController = class {
588
2989
  this.shown = false;
589
2990
  }
590
2991
  /**
591
- * Play/pause in the middle of the video and sound on/off at its top right.
592
- * They follow the video's own events, so a blocked autoplay shows as
593
- * paused.
2992
+ * At the bottom of the video, the product pill, which opens the panel with
2993
+ * its actions, or the call to action of a link destination. Clicks on them
2994
+ * don't reach the video.
594
2995
  */
595
- renderVideoControls() {
596
- const { video, options } = this;
2996
+ renderDestination({
2997
+ product,
2998
+ cta,
2999
+ labels,
3000
+ productActions
3001
+ }) {
3002
+ let content;
3003
+ if (product) {
3004
+ content = renderExpandableProduct(product, {
3005
+ ...productActions,
3006
+ labels,
3007
+ open: this.productOpen,
3008
+ onToggle: this.toggleProduct,
3009
+ panelId: "player-product-panel"
3010
+ });
3011
+ } else if (cta) {
3012
+ content = renderCta(cta);
3013
+ } else {
3014
+ return nothing4;
3015
+ }
3016
+ return html7`
3017
+ <div
3018
+ class="player-destination"
3019
+ @click=${(event) => event.stopPropagation()}
3020
+ >
3021
+ ${content}
3022
+ </div>
3023
+ `;
3024
+ }
3025
+ renderVideoControls(labels) {
3026
+ const { video } = this;
597
3027
  const onToggle = (event) => {
598
3028
  event.stopPropagation();
599
3029
  video.togglePlayback();
@@ -602,11 +3032,11 @@ var PlayerController = class {
602
3032
  event.stopPropagation();
603
3033
  video.toggleMuted();
604
3034
  };
605
- return html3`
3035
+ return html7`
606
3036
  <button
607
3037
  type="button"
608
3038
  class="play player-toggle"
609
- aria-label=${video.paused ? options.playLabel : options.pauseLabel}
3039
+ aria-label=${video.paused ? labels.play : labels.pause}
610
3040
  @click=${onToggle}
611
3041
  >
612
3042
  ${icon(video.paused ? "play" : "pause")}
@@ -614,57 +3044,193 @@ var PlayerController = class {
614
3044
  <button
615
3045
  type="button"
616
3046
  class="player-button player-sound"
617
- aria-label=${video.muted ? options.soundOnLabel : options.soundOffLabel}
3047
+ aria-label=${video.muted ? labels.soundOn : labels.soundOff}
618
3048
  @click=${onSound}
619
3049
  >
620
3050
  ${icon(video.muted ? "soundOff" : "soundOn")}
621
3051
  </button>
622
3052
  `;
623
3053
  }
3054
+ /**
3055
+ * Previous and next Story: above the mini player's top left, beside the
3056
+ * expanded video.
3057
+ */
3058
+ renderNavigation(labels) {
3059
+ const { options } = this;
3060
+ const step = (delta) => () => {
3061
+ var _a;
3062
+ return (_a = options.onStep) == null ? void 0 : _a.call(options, delta);
3063
+ };
3064
+ return html7`
3065
+ <div class="player-controls player-nav">
3066
+ <button
3067
+ type="button"
3068
+ class="player-button player-previous"
3069
+ aria-label=${labels.previous}
3070
+ @click=${step(-1)}
3071
+ >
3072
+ ${icon("previous")}
3073
+ </button>
3074
+ <button
3075
+ type="button"
3076
+ class="player-button player-next"
3077
+ aria-label=${labels.next}
3078
+ @click=${step(1)}
3079
+ >
3080
+ ${icon("next")}
3081
+ </button>
3082
+ </div>
3083
+ `;
3084
+ }
3085
+ /** The other Stories' covers beside the expanded video. */
3086
+ renderNeighbors(neighbors, labels) {
3087
+ const { options } = this;
3088
+ return repeat2(
3089
+ neighbors,
3090
+ ({ offset }) => neighbors.length === 1 ? "single" : offset,
3091
+ ({ offset, story, label }) => {
3092
+ const poster = httpUrl(story.poster_url);
3093
+ const side = Math.sign(offset);
3094
+ return html7`
3095
+ <button
3096
+ type="button"
3097
+ class="player-neighbor"
3098
+ aria-label=${label != null ? label : labels.show}
3099
+ style=${styleMap3({
3100
+ "--side": String(side),
3101
+ "--beyond": String(offset - side)
3102
+ })}
3103
+ ${ref3(this.neighborRef(offset))}
3104
+ @click=${() => {
3105
+ var _a;
3106
+ return (_a = options.onStep) == null ? void 0 : _a.call(options, offset);
3107
+ }}
3108
+ >
3109
+ ${poster ? html7`<img alt="" src=${poster} />` : nothing4}
3110
+ </button>
3111
+ `;
3112
+ }
3113
+ );
3114
+ }
3115
+ /** Expand or collapse, and close: above the video, or at the top right. */
3116
+ renderWindowControls(labels) {
3117
+ const { options, expanded } = this;
3118
+ return html7`
3119
+ <div class="player-controls">
3120
+ <button
3121
+ type="button"
3122
+ class="player-button player-expand"
3123
+ aria-label=${expanded ? labels.collapse : labels.expand}
3124
+ ${ref3(this.expandButton)}
3125
+ @click=${this.toggleExpanded}
3126
+ >
3127
+ ${icon(expanded ? "collapse" : "expand")}
3128
+ </button>
3129
+ <button
3130
+ type="button"
3131
+ class="player-button player-close"
3132
+ aria-label=${labels.close}
3133
+ ${ref3(this.closeButton)}
3134
+ @click=${options.onClose}
3135
+ >
3136
+ ${icon("close")}
3137
+ </button>
3138
+ </div>
3139
+ `;
3140
+ }
3141
+ /**
3142
+ * The video with its controls and the product or call to action. With
3143
+ * `advances`, it plays once and moves on to the next Story when it ends;
3144
+ * otherwise it loops.
3145
+ */
3146
+ renderVideo(story, advances, destination) {
3147
+ const { video, options } = this;
3148
+ return html7`
3149
+ <div class="card" ${ref3(this.stageCardRef)} @click=${this.onVideoClick}>
3150
+ ${renderMedia(story, video, {
3151
+ loop: !advances,
3152
+ onEnded: advances ? () => {
3153
+ var _a;
3154
+ return (_a = options.onStep) == null ? void 0 : _a.call(options, 1);
3155
+ } : void 0,
3156
+ labels: destination.labels,
3157
+ onRetry: this.retryVideo
3158
+ })}
3159
+ ${hasVideo(story, video) ? this.renderVideoControls(destination.labels) : nothing4}
3160
+ ${this.renderDestination(destination)}
3161
+ </div>
3162
+ `;
3163
+ }
3164
+ /**
3165
+ * Keeps what this render shows, for the step animation: the covers beside
3166
+ * the video (only in the expanded view) and the side the video moves to
3167
+ * with two Stories. A new Story makes what was shown the animation's
3168
+ * start.
3169
+ */
3170
+ track(story, neighbors) {
3171
+ const shown = this.expanded ? neighbors : [];
3172
+ this.pairDirection = shown.length === 1 ? -Math.sign(shown[0].offset) : 0;
3173
+ if (this.rendered && story !== this.rendered.story) {
3174
+ this.beforeStep = this.rendered;
3175
+ }
3176
+ this.rendered = { story, neighbors: shown };
3177
+ return shown;
3178
+ }
624
3179
  /**
625
3180
  * The player <dialog> while it is open. Clicking the video also plays or
626
- * pauses it.
3181
+ * pauses it, and keeps the focus in the player (the dialog is focusable,
3182
+ * though not by Tab), so the arrow keys still step. With `navigation`
3183
+ * (more than one Story), it has previous and next buttons and arrow keys,
3184
+ * and the expanded view moves on when the video ends instead of looping.
3185
+ * The expanded view also shows the `neighbors` beside it.
627
3186
  */
628
- render(story) {
629
- if (!this.isOpen) return nothing3;
630
- const { video, options, expanded } = this;
631
- const withVideo = hasVideo(story, video);
632
- return html3`
3187
+ render(story, {
3188
+ navigation = false,
3189
+ neighbors = [],
3190
+ onPress,
3191
+ ...destination
3192
+ }) {
3193
+ const { labels } = destination;
3194
+ if (!this.isOpen) return nothing4;
3195
+ const { video, expanded } = this;
3196
+ const shownNeighbors = this.track(story, neighbors);
3197
+ const pair = this.pairDirection !== 0;
3198
+ this.navigation = navigation;
3199
+ return html7`
633
3200
  <dialog
634
3201
  class="player"
635
3202
  popover="manual"
636
- aria-label=${options.label}
3203
+ aria-label=${labels.player}
637
3204
  ?data-expanded=${expanded}
3205
+ ?data-pair=${pair}
3206
+ style=${styleMap3({
3207
+ "--pair-dir": pair ? String(this.pairDirection) : void 0
3208
+ })}
638
3209
  ?data-switched=${this.switched}
639
- ?data-paused=${withVideo && video.paused}
640
- ${ref2(this.dialog)}
3210
+ ?data-paused=${hasVideo(story, video) && video.paused}
3211
+ tabindex="-1"
3212
+ ${ref3(this.dialog)}
641
3213
  @click=${this.onDialogClick}
642
3214
  @cancel=${this.onCancel}
3215
+ @keydown=${this.onPlayerKeyDown}
643
3216
  >
3217
+ ${this.renderNeighbors(shownNeighbors, labels)}
644
3218
  <div class="player-frame">
645
- <div class="player-controls">
646
- <button
647
- type="button"
648
- class="player-button player-expand"
649
- aria-label=${expanded ? options.collapseLabel : options.expandLabel}
650
- ${ref2(this.expandButton)}
651
- @click=${this.toggleExpanded}
652
- >
653
- ${icon(expanded ? "collapse" : "expand")}
654
- </button>
655
- <button
656
- type="button"
657
- class="player-button player-close"
658
- aria-label=${options.closeLabel}
659
- ${ref2(this.closeButton)}
660
- @click=${options.onClose}
661
- >
662
- ${icon("close")}
663
- </button>
664
- </div>
665
- <div class="card" @click=${() => video.togglePlayback()}>
666
- ${renderMedia(story, video)}
667
- ${withVideo ? this.renderVideoControls() : nothing3}
3219
+ ${this.renderWindowControls(labels)}
3220
+ <div
3221
+ class="player-stage"
3222
+ ${ref3(this.stage)}
3223
+ @click=${{
3224
+ handleEvent: (event) => {
3225
+ const card = this.stageCardRef.value;
3226
+ if (card == null ? void 0 : card.contains(event.target)) onPress == null ? void 0 : onPress();
3227
+ },
3228
+ capture: true
3229
+ }}
3230
+ >
3231
+ ${navigation ? this.renderNavigation(labels) : nothing4}
3232
+ ${this.renderVideo(story, navigation && expanded, destination)}
3233
+ <span class="player-dim" aria-hidden="true" ${ref3(this.dim)}></span>
668
3234
  </div>
669
3235
  </div>
670
3236
  </dialog>
@@ -672,38 +3238,291 @@ var PlayerController = class {
672
3238
  }
673
3239
  };
674
3240
 
3241
+ // src/utils/hydrate-products.ts
3242
+ import {
3243
+ hydrateAds,
3244
+ intelligentSearchAvailability,
3245
+ intelligentSearchFetcher,
3246
+ intelligentSearchMatcher,
3247
+ intelligentSearchPrice
3248
+ } from "@vtex/ads-core";
3249
+
3250
+ // src/utils/with-timeout.ts
3251
+ var withTimeout = (timeout, fallback, signal) => {
3252
+ const ms = timeout !== void 0 && Number.isFinite(timeout) && timeout > 0 ? timeout : fallback;
3253
+ const controller = new AbortController();
3254
+ const timer = setTimeout(
3255
+ () => controller.abort(
3256
+ new DOMException(`Timed out after ${ms} ms`, "TimeoutError")
3257
+ ),
3258
+ ms
3259
+ );
3260
+ const onAbort = () => controller.abort(signal == null ? void 0 : signal.reason);
3261
+ if (signal == null ? void 0 : signal.aborted) {
3262
+ onAbort();
3263
+ } else {
3264
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
3265
+ }
3266
+ return {
3267
+ signal: controller.signal,
3268
+ clear: () => {
3269
+ clearTimeout(timer);
3270
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
3271
+ }
3272
+ };
3273
+ };
3274
+
3275
+ // src/utils/hydrate-products.ts
3276
+ var DEFAULT_HYDRATION_TIMEOUT_MS = 5e3;
3277
+ var intelligentSearchHydration = {
3278
+ fetcher: intelligentSearchFetcher,
3279
+ matcher: intelligentSearchMatcher,
3280
+ price: intelligentSearchPrice,
3281
+ available: intelligentSearchAvailability
3282
+ };
3283
+ function toShownPrice(value) {
3284
+ const isAmount = (amount) => typeof amount === "number" && Number.isFinite(amount) && amount >= 0;
3285
+ if (!isAmount(value == null ? void 0 : value.price)) return void 0;
3286
+ const { price, listPrice } = value;
3287
+ return isAmount(listPrice) && listPrice > price ? { price, listPrice } : { price };
3288
+ }
3289
+ async function hydrateStoryProducts(placement, stories, hydration, identity, { signal, timeout } = {}) {
3290
+ var _a, _b;
3291
+ const products = /* @__PURE__ */ new Map();
3292
+ const limit = withTimeout(timeout, DEFAULT_HYDRATION_TIMEOUT_MS, signal);
3293
+ try {
3294
+ const hydrated = await hydrateAds(
3295
+ { stories: { [placement]: stories } },
3296
+ hydration.fetcher,
3297
+ (product, offer) => hydration.matcher(product, offer),
3298
+ identity,
3299
+ { signal: limit.signal }
3300
+ );
3301
+ for (const { story, product, offer } of (_a = hydrated.stories[placement]) != null ? _a : []) {
3302
+ if (!product || !offer) continue;
3303
+ try {
3304
+ const price = toShownPrice(hydration.price(product, offer));
3305
+ const available = (_b = hydration.available) == null ? void 0 : _b.call(hydration, product, offer);
3306
+ products.set(story.ad_id, {
3307
+ ...price && { price },
3308
+ ...available !== void 0 && { available }
3309
+ });
3310
+ } catch (error) {
3311
+ console.error(
3312
+ `[${TAG_NAME}] Product details failed for ad ${story.ad_id}`,
3313
+ error
3314
+ );
3315
+ }
3316
+ }
3317
+ } catch (error) {
3318
+ if (!limit.signal.aborted) {
3319
+ console.error(`[${TAG_NAME}] Product request failed`, error);
3320
+ }
3321
+ } finally {
3322
+ limit.clear();
3323
+ }
3324
+ return products;
3325
+ }
3326
+
3327
+ // src/utils/fetch-story.ts
3328
+ import { getRawAds } from "@vtex/ads-core";
3329
+ var DEFAULT_TIMEOUT_MS = 2e3;
3330
+ var DEFAULT_QUANTITY = 8;
3331
+ var toQuantity = (quantity) => quantity !== void 0 && Number.isFinite(quantity) && quantity >= 1 ? Math.floor(quantity) : DEFAULT_QUANTITY;
3332
+ async function fetchStories({
3333
+ publisherId,
3334
+ sessionId,
3335
+ placement,
3336
+ userId,
3337
+ accountName,
3338
+ channel,
3339
+ quantity
3340
+ }, { signal, timeout } = {}) {
3341
+ var _a;
3342
+ const onServer = globalThis.window === void 0;
3343
+ if (onServer || !publisherId || !sessionId || !placement) return [];
3344
+ const limit = withTimeout(timeout, DEFAULT_TIMEOUT_MS, signal);
3345
+ const count = toQuantity(quantity);
3346
+ try {
3347
+ const { stories } = await getRawAds(
3348
+ {
3349
+ identity: {
3350
+ accountName: accountName != null ? accountName : "",
3351
+ publisherId,
3352
+ sessionId,
3353
+ userId,
3354
+ channel
3355
+ },
3356
+ search: {},
3357
+ placements: {
3358
+ [placement]: { quantity: count, types: ["story"] }
3359
+ }
3360
+ },
3361
+ { signal: limit.signal }
3362
+ );
3363
+ return ((_a = stories[placement]) != null ? _a : []).slice(0, count);
3364
+ } catch (error) {
3365
+ if (!limit.signal.aborted) {
3366
+ console.error(`[${TAG_NAME}] Story request failed`, {
3367
+ placement,
3368
+ publisherId,
3369
+ error
3370
+ });
3371
+ }
3372
+ return [];
3373
+ } finally {
3374
+ limit.clear();
3375
+ }
3376
+ }
3377
+
3378
+ // src/utils/media-ready.ts
3379
+ var MEDIA_TIMEOUT = 3e3;
3380
+ function decodeImage(url) {
3381
+ if (typeof Image === "undefined") return Promise.resolve(true);
3382
+ const image = new Image();
3383
+ image.src = url;
3384
+ if (!image.decode) return Promise.resolve(true);
3385
+ return image.decode().then(
3386
+ () => true,
3387
+ () => false
3388
+ );
3389
+ }
3390
+ function firstReady(checks, signal) {
3391
+ if (!checks.length) return Promise.resolve();
3392
+ const limit = withTimeout(void 0, MEDIA_TIMEOUT, signal);
3393
+ return new Promise((resolve) => {
3394
+ const done = () => {
3395
+ limit.clear();
3396
+ resolve();
3397
+ };
3398
+ if (limit.signal.aborted) return done();
3399
+ limit.signal.addEventListener("abort", done, { once: true });
3400
+ let failed = 0;
3401
+ for (const check of checks) {
3402
+ check.then(
3403
+ (ready) => {
3404
+ if (ready || ++failed === checks.length) done();
3405
+ },
3406
+ () => {
3407
+ if (++failed === checks.length) done();
3408
+ }
3409
+ );
3410
+ }
3411
+ });
3412
+ }
3413
+
3414
+ // src/commerce-events.ts
3415
+ var ADD_TO_CART_EVENT = "vtex-ads-story:add-to-cart";
3416
+ var REMOVE_FROM_CART_EVENT = "vtex-ads-story:remove-from-cart";
3417
+ function cartEvent(type, { sku, seller }, quantity) {
3418
+ return new CustomEvent(type, {
3419
+ detail: { sku, ...seller && { seller }, quantity },
3420
+ bubbles: true,
3421
+ composed: true
3422
+ });
3423
+ }
3424
+ function addToCartEvent(item, quantity = 1) {
3425
+ return cartEvent(ADD_TO_CART_EVENT, item, quantity);
3426
+ }
3427
+ function removeFromCartEvent(item, quantity = 1) {
3428
+ return cartEvent(REMOVE_FROM_CART_EVENT, item, quantity);
3429
+ }
3430
+
675
3431
  // src/story/story.ts
676
- var TAG_NAME = "vtex-ads-story";
677
- var PLACEHOLDER_STORY = {
678
- poster_url: "https://dummyimage.com/1080x1920/e31c57/fff",
679
- media_url: "https://samplelib.com/mp4/sample-10s-vp9.mp4"
3432
+ var REQUEST_PROPERTIES = [
3433
+ "publisherId",
3434
+ "sessionId",
3435
+ "placement",
3436
+ "userId",
3437
+ "accountName",
3438
+ "channel",
3439
+ "quantity",
3440
+ "hydration"
3441
+ ];
3442
+ var CHANNELS = /* @__PURE__ */ new Set(["site", "app"]);
3443
+ var isChannel = (value) => CHANNELS.has(value);
3444
+ var booleanConverter = {
3445
+ fromAttribute: (value) => typeof value === "string" && (value === "" || value.toLowerCase() === "true")
680
3446
  };
681
- var LABELS = {
682
- watch: "Assistir v\xEDdeo",
683
- player: "V\xEDdeo",
684
- expand: "Expandir v\xEDdeo",
685
- collapse: "Reduzir v\xEDdeo",
686
- close: "Fechar v\xEDdeo",
687
- play: "Reproduzir v\xEDdeo",
688
- pause: "Pausar v\xEDdeo",
689
- soundOn: "Ativar som",
690
- soundOff: "Desativar som"
3447
+ var channelConverter = {
3448
+ fromAttribute: (value) => isChannel(value) ? value : void 0
691
3449
  };
692
- var VtexAdsStoryElement = class extends LitElement {
3450
+ var hydrationConverter = {
3451
+ fromAttribute: (value) => value === "none" ? "none" : void 0
3452
+ };
3453
+ var cartKey = ({ sku, seller }) => JSON.stringify([sku, seller != null ? seller : ""]);
3454
+ var VtexAdsStoryCarouselElement = class extends LitElement {
693
3455
  constructor() {
694
- super(...arguments);
695
- this.cardVideo = new VideoController(this);
3456
+ super();
3457
+ /**
3458
+ * How many of each SKU, from each seller (see cartKey), were added since
3459
+ * the player opened, for its stepper. It doesn't read the store's cart: it
3460
+ * counts the add and remove events sent, and starts over each time the
3461
+ * player opens, as the cart may have changed meanwhile.
3462
+ */
3463
+ this.cartQuantities = /* @__PURE__ */ new Map();
3464
+ /**
3465
+ * One per rendered card, by its key (see Slide): a Story can show in more
3466
+ * than one card, each with its own video.
3467
+ */
3468
+ this.cardVideos = /* @__PURE__ */ new Map();
3469
+ /** The sound was on when the highlight moved: the new card turns it on. */
3470
+ this.soundPending = false;
3471
+ this.carousel = new CarouselController(this, {
3472
+ onStep: (from, to) => this.leaveHighlight(from, to),
3473
+ // Every card is new: so are their videos. Behind an open player, the
3474
+ // new highlighted card stays on its cover, as after a step.
3475
+ onLayoutChange: () => {
3476
+ this.cardVideos.clear();
3477
+ if (this.player.isOpen) {
3478
+ this.afterRender = () => {
3479
+ var _a;
3480
+ return (_a = this.activeVideo) == null ? void 0 : _a.pause();
3481
+ };
3482
+ }
3483
+ },
3484
+ // The player shows the highlighted Story: the highlight stays on it.
3485
+ locked: () => this.player.isOpen || this.mediaLoading,
3486
+ slideDuration: () => this.slideDuration,
3487
+ reducedMotion: prefersReducedMotion
3488
+ });
696
3489
  this.player = new PlayerController(this, {
697
- label: LABELS.player,
698
- expandLabel: LABELS.expand,
699
- collapseLabel: LABELS.collapse,
700
- closeLabel: LABELS.close,
701
- playLabel: LABELS.play,
702
- pauseLabel: LABELS.pause,
703
- soundOnLabel: LABELS.soundOn,
704
- soundOffLabel: LABELS.soundOff,
3490
+ onStep: (delta) => this.stepInPlayer(delta),
705
3491
  onClose: () => this.closePlayer()
706
3492
  });
3493
+ // Added after the carousel and the player: its hostUpdated reads what
3494
+ // they rendered.
3495
+ this.events = new StoryEventsController(this, {
3496
+ identity: () => ({ sessionId: this.sessionId, userId: this.userId }),
3497
+ viewTargets: () => this.viewTargets()
3498
+ });
3499
+ // The highlighted card opens the player; another one takes the highlight.
3500
+ // Hidden cards, out of sight, show only their cover.
3501
+ this.renderSlide = (story, { key, index, offset, active, hidden, cardRef, focusRef }) => renderCard(story, this.videoFor(key), {
3502
+ label: this.labels.position(
3503
+ active ? this.labels.watch : this.labels.show,
3504
+ index,
3505
+ this.stories.length
3506
+ ),
3507
+ labels: this.labels,
3508
+ withVideo: active || this.inactiveAutoplay && !hidden,
3509
+ autoplay: !this.mediaLoading,
3510
+ product: this.productOf(story),
3511
+ onSelect: active ? () => this.openPlayer() : () => this.carousel.step(offset),
3512
+ // On a card without the highlight, the product moves it, as the card.
3513
+ onProductSelect: active ? () => this.openPlayer({ productOpen: true }) : void 0,
3514
+ // On the highlighted card it follows the link; on another, it moves the
3515
+ // highlight.
3516
+ cta: toCardCta(story),
3517
+ onCtaSelect: active ? void 0 : () => this.carousel.step(offset),
3518
+ onPress: () => this.events.click(story),
3519
+ ref: cardRef,
3520
+ openRef: focusRef
3521
+ });
3522
+ this.inactiveAutoplay = false;
3523
+ this.stories = [];
3524
+ this.requesting = false;
3525
+ this.mediaLoading = false;
707
3526
  }
708
3527
  // Lit keeps the card's DOM when the element is moved (removed and appended
709
3528
  // again), but the browser pauses a removed video and doesn't autoplay it
@@ -712,58 +3531,370 @@ var VtexAdsStoryElement = class extends LitElement {
712
3531
  // Not in VideoController.hostConnected: there, the player's video is still
713
3532
  // in the DOM until the next update and would play for a moment.
714
3533
  connectedCallback() {
3534
+ var _a;
715
3535
  super.connectedCallback();
716
- this.cardVideo.resume();
3536
+ for (const video of this.cardVideos.values()) video.resume();
3537
+ if ((_a = this.request) == null ? void 0 : _a.signal.aborted) void this.loadStory();
3538
+ }
3539
+ // A request still pending when the element leaves the page is cancelled.
3540
+ disconnectedCallback() {
3541
+ var _a, _b;
3542
+ super.disconnectedCallback();
3543
+ (_a = this.request) == null ? void 0 : _a.abort();
3544
+ (_b = this.mediaWait) == null ? void 0 : _b.abort();
3545
+ }
3546
+ willUpdate(changed) {
3547
+ if (REQUEST_PROPERTIES.some((name) => changed.has(name))) {
3548
+ void this.loadStory();
3549
+ }
3550
+ }
3551
+ updated() {
3552
+ const afterRender = this.afterRender;
3553
+ this.afterRender = void 0;
3554
+ afterRender == null ? void 0 : afterRender();
3555
+ }
3556
+ // The strategy for the products' details, if any (see `hydration`).
3557
+ get activeHydration() {
3558
+ if (this.hydration === "none") return void 0;
3559
+ if (this.hydration) return this.hydration;
3560
+ return this.accountName ? intelligentSearchHydration : void 0;
3561
+ }
3562
+ /**
3563
+ * Requests the Story and shows it, then hydrates its products. Until the
3564
+ * Story arrives, and when there is none (see fetchStories), the element
3565
+ * renders nothing.
3566
+ */
3567
+ async loadStory() {
3568
+ var _a, _b, _c, _d, _e;
3569
+ (_a = this.request) == null ? void 0 : _a.abort();
3570
+ const request = new AbortController();
3571
+ this.request = request;
3572
+ this.player.close();
3573
+ this.requesting = false;
3574
+ this.showStories([]);
3575
+ if (!this.isConnected) {
3576
+ request.abort();
3577
+ return;
3578
+ }
3579
+ this.requesting = Boolean(
3580
+ this.publisherId && this.sessionId && this.placement
3581
+ );
3582
+ const stories = await fetchStories(this, {
3583
+ signal: request.signal,
3584
+ timeout: this.timeout
3585
+ });
3586
+ if (request.signal.aborted) return;
3587
+ this.requesting = false;
3588
+ const hydration = this.activeHydration;
3589
+ if (!hydration || !stories.some((story) => story.product)) {
3590
+ this.request = void 0;
3591
+ this.showStories(stories);
3592
+ return;
3593
+ }
3594
+ this.showStories(stories, "loading");
3595
+ const products = await hydrateStoryProducts(
3596
+ (_b = this.placement) != null ? _b : "",
3597
+ stories,
3598
+ hydration,
3599
+ {
3600
+ accountName: (_c = this.accountName) != null ? _c : "",
3601
+ publisherId: (_d = this.publisherId) != null ? _d : "",
3602
+ sessionId: (_e = this.sessionId) != null ? _e : "",
3603
+ userId: this.userId,
3604
+ channel: this.channel
3605
+ },
3606
+ { signal: request.signal, timeout: this.hydrationTimeout }
3607
+ );
3608
+ if (request.signal.aborted) return;
3609
+ this.request = void 0;
3610
+ this.products = products;
3611
+ }
3612
+ // Each card's video starts fresh: a failed load of an old one doesn't hide
3613
+ // it.
3614
+ showStories(stories, products) {
3615
+ this.products = products;
3616
+ this.cardVideos.clear();
3617
+ this.soundPending = false;
3618
+ this.afterRender = void 0;
3619
+ this.carousel.reset(stories.length);
3620
+ this.stories = stories;
3621
+ void this.waitForFirstMedia(stories);
3622
+ }
3623
+ /**
3624
+ * Shows the cards once the first Story's cover or video is ready: whichever
3625
+ * loads first, or once both failed. Only then are the Stories impressed
3626
+ * and do their videos play, from the start.
3627
+ */
3628
+ async waitForFirstMedia(stories) {
3629
+ var _a, _b, _c;
3630
+ (_a = this.mediaWait) == null ? void 0 : _a.abort();
3631
+ const wait = new AbortController();
3632
+ this.mediaWait = wait;
3633
+ const cover = httpUrl((_b = stories[0]) == null ? void 0 : _b.poster_url);
3634
+ const video = httpUrl((_c = stories[0]) == null ? void 0 : _c.media_url);
3635
+ const checks = [];
3636
+ if (cover) checks.push(decodeImage(cover));
3637
+ if (video) checks.push(this.videoFor(this.carousel.activeKey).ready);
3638
+ this.mediaLoading = checks.length > 0;
3639
+ await firstReady(checks, wait.signal);
3640
+ if (this.mediaWait !== wait) return;
3641
+ this.mediaWait = void 0;
3642
+ this.mediaLoading = false;
3643
+ this.events.impress(stories);
3644
+ this.afterRender = () => {
3645
+ if (!this.isConnected) return;
3646
+ for (const cardVideo of this.cardVideos.values()) cardVideo.resume();
3647
+ };
3648
+ this.requestUpdate();
3649
+ }
3650
+ /**
3651
+ * Where each Story is being watched: the cards on screen (not the hidden
3652
+ * ones kept for the slide in) and the open player's video, while their
3653
+ * video plays. A card showing only its cover doesn't count. Behind the
3654
+ * expanded player, a modal over the page, the cards are covered.
3655
+ */
3656
+ *viewTargets() {
3657
+ var _a;
3658
+ const { stories } = this;
3659
+ if (this.mediaLoading) return;
3660
+ if (!this.player.isExpanded) {
3661
+ for (const [card, { key, index }] of this.carousel.visibleCards()) {
3662
+ const story = stories[index];
3663
+ if (story && ((_a = this.cardVideos.get(key)) == null ? void 0 : _a.playing)) yield [card, story];
3664
+ }
3665
+ }
3666
+ const stageCard = this.player.stageCard;
3667
+ const active = stories[this.carousel.active];
3668
+ if (stageCard && active && this.player.video.playing) {
3669
+ yield [stageCard, active];
3670
+ }
3671
+ }
3672
+ videoFor(key) {
3673
+ let video = this.cardVideos.get(key);
3674
+ if (!video) {
3675
+ video = new VideoController(this);
3676
+ this.cardVideos.set(key, video);
3677
+ }
3678
+ return video;
3679
+ }
3680
+ get activeVideo() {
3681
+ return this.cardVideos.get(this.carousel.activeKey);
3682
+ }
3683
+ // The card losing the highlight goes quiet: muted if it keeps playing, or
3684
+ // back to its cover. Its next video then starts fresh. If its sound was
3685
+ // on, the sound moves to the new highlighted card, once its video renders.
3686
+ // With the player open (it stepped), the new card stays on its cover
3687
+ // behind it instead. Cards no longer rendered (the rolling layout drops
3688
+ // them as it moves) leave with their videos.
3689
+ leaveHighlight(from, to) {
3690
+ const video = this.cardVideos.get(from);
3691
+ this.soundPending || (this.soundPending = video !== void 0 && !video.muted);
3692
+ if (this.inactiveAutoplay) video == null ? void 0 : video.mute();
3693
+ else video == null ? void 0 : video.reset();
3694
+ if (this.player.isOpen) {
3695
+ this.soundPending = false;
3696
+ this.afterRender = () => this.videoFor(to).pause();
3697
+ } else if (this.soundPending) {
3698
+ this.afterRender = () => {
3699
+ this.soundPending = false;
3700
+ this.videoFor(to).playWithSound();
3701
+ };
3702
+ }
3703
+ for (const key of this.cardVideos.keys()) {
3704
+ if (Math.abs(key - to) > RENDERED_SIDE) this.cardVideos.delete(key);
3705
+ }
3706
+ }
3707
+ // The player's previous and next buttons: the highlight moves with the
3708
+ // Story the player shows.
3709
+ stepInPlayer(delta) {
3710
+ this.carousel.step(delta, { evenIfLocked: true });
3711
+ void this.player.showNext(delta);
717
3712
  }
718
- openPlayer() {
3713
+ // From the card's product, the player opens with the product panel open.
3714
+ openPlayer({ productOpen = false } = {}) {
3715
+ var _a;
719
3716
  if (this.player.isOpen) return;
720
- this.cardVideo.pause();
721
- void this.player.open();
3717
+ this.cartQuantities.clear();
3718
+ (_a = this.activeVideo) == null ? void 0 : _a.pause();
3719
+ void this.player.open({ productOpen });
722
3720
  }
723
3721
  // The player also closes on its own when the element leaves the page,
724
3722
  // without this: there is no card to give focus back to or to resume playing
725
3723
  // (it would play out of sight).
726
3724
  closePlayer() {
727
- var _a;
728
3725
  if (!this.player.isOpen) return;
729
3726
  this.player.close();
730
- this.cardVideo.resume();
731
- (_a = this.renderRoot.querySelector(".root .card-open")) == null ? void 0 : _a.focus();
3727
+ for (const video of this.cardVideos.values()) video.resume();
3728
+ this.carousel.focusActive();
3729
+ }
3730
+ // Prices and texts follow the language of the closest element with a
3731
+ // `lang`, the element itself included, so a store can set one for the
3732
+ // widget alone. An empty `lang` (unknown) is skipped; none, or an unknown
3733
+ // one, falls back to pt-BR.
3734
+ get locale() {
3735
+ var _a, _b;
3736
+ return (_b = (_a = this.closest('[lang]:not([lang=""])')) == null ? void 0 : _a.lang) != null ? _b : DEFAULT_LOCALE;
3737
+ }
3738
+ get labels() {
3739
+ var _a;
3740
+ const { locale, labelAddToCart = "", labelViewProduct = "" } = this;
3741
+ const key = JSON.stringify([locale, labelAddToCart, labelViewProduct]);
3742
+ if (((_a = this.labelSet) == null ? void 0 : _a.key) !== key) {
3743
+ this.labelSet = {
3744
+ key,
3745
+ labels: labelsFor(locale, {
3746
+ addToCart: labelAddToCart,
3747
+ viewProduct: labelViewProduct
3748
+ })
3749
+ };
3750
+ }
3751
+ return this.labelSet.labels;
3752
+ }
3753
+ get formatPrice() {
3754
+ var _a, _b;
3755
+ const { locale } = this;
3756
+ const key = `${locale}|${(_a = this.currency) != null ? _a : ""}`;
3757
+ if (((_b = this.formatter) == null ? void 0 : _b.key) !== key) {
3758
+ this.formatter = { key, format: priceFormatter(locale, this.currency) };
3759
+ }
3760
+ return this.formatter.format;
3761
+ }
3762
+ productOf(story) {
3763
+ var _a;
3764
+ const fetched = this.products === "loading" ? "loading" : (_a = this.products) == null ? void 0 : _a.get(story.ad_id);
3765
+ return toCardProduct(story, this.formatPrice, this.labels, fetched);
732
3766
  }
733
3767
  render() {
734
- return html4`
735
- <div class="root">
736
- ${renderCard(PLACEHOLDER_STORY, this.cardVideo, {
737
- label: LABELS.watch,
738
- soundOnLabel: LABELS.soundOn,
739
- soundOffLabel: LABELS.soundOff,
740
- onSelect: () => this.openPlayer()
741
- })}
3768
+ const { stories } = this;
3769
+ const index = this.carousel.active;
3770
+ const active = stories[index];
3771
+ if (!active && !this.requesting) return nothing5;
3772
+ const loading = this.requesting || this.mediaLoading;
3773
+ return html8`
3774
+ <div
3775
+ class="root"
3776
+ ?data-loading=${loading}
3777
+ ?data-requesting=${this.requesting}
3778
+ >
3779
+ ${active ? this.carousel.render(stories, this.renderSlide, this.labels) : nothing5}
3780
+ ${renderCarouselSkeleton({ done: !loading })}
742
3781
  </div>
743
- ${this.player.render(PLACEHOLDER_STORY)}
3782
+ ${active ? this.renderPlayer(active) : nothing5}
744
3783
  `;
745
3784
  }
3785
+ renderPlayer(active) {
3786
+ const { stories } = this;
3787
+ const index = this.carousel.active;
3788
+ const neighbors = neighborOffsets(stories.length, index).map((offset) => {
3789
+ const neighbor = (index + offset + stories.length) % stories.length;
3790
+ return {
3791
+ offset,
3792
+ story: stories[neighbor],
3793
+ label: this.labels.position(this.labels.show, neighbor, stories.length)
3794
+ };
3795
+ });
3796
+ const product = this.productOf(active);
3797
+ return this.player.render(active, {
3798
+ labels: this.labels,
3799
+ navigation: stories.length > 1,
3800
+ neighbors,
3801
+ product,
3802
+ cta: toCardCta(active),
3803
+ productActions: this.cartActionsFor(product),
3804
+ onPress: () => this.events.click(active)
3805
+ });
3806
+ }
3807
+ cartActionsFor(product) {
3808
+ const sku = product == null ? void 0 : product.sku;
3809
+ if (!sku) return void 0;
3810
+ const item = { sku, seller: product.seller };
3811
+ return {
3812
+ cartQuantity: this.cartQuantities.get(cartKey(item)),
3813
+ onAddToCart: () => this.changeCart(item, 1),
3814
+ onRemoveFromCart: () => this.changeCart(item, -1)
3815
+ };
3816
+ }
3817
+ /**
3818
+ * Adds one of `item` to the stepper's count, or removes one, and tells the
3819
+ * store, which changes its cart: the element has none. When add to cart
3820
+ * and the stepper swap places, the focus moves to the one now shown.
3821
+ */
3822
+ changeCart(item, delta) {
3823
+ var _a;
3824
+ const key = cartKey(item);
3825
+ const before = (_a = this.cartQuantities.get(key)) != null ? _a : 0;
3826
+ const after = Math.max(0, before + delta);
3827
+ if (after === before) return;
3828
+ if (after > 0) this.cartQuantities.set(key, after);
3829
+ else this.cartQuantities.delete(key);
3830
+ this.requestUpdate();
3831
+ this.dispatchEvent(
3832
+ delta > 0 ? addToCartEvent(item) : removeFromCartEvent(item)
3833
+ );
3834
+ let swapped;
3835
+ if (before === 0) swapped = "stepper";
3836
+ else if (after === 0) swapped = "add";
3837
+ if (!swapped) return;
3838
+ const action = swapped;
3839
+ this.updateComplete.then(
3840
+ () => this.shadowRoot && focusCartAction(this.shadowRoot, action)
3841
+ );
3842
+ }
3843
+ };
3844
+ VtexAdsStoryCarouselElement.properties = {
3845
+ publisherId: { attribute: "publisher-id" },
3846
+ sessionId: { attribute: "session-id" },
3847
+ placement: {},
3848
+ userId: { attribute: "user-id" },
3849
+ accountName: { attribute: "account-name" },
3850
+ channel: { converter: channelConverter },
3851
+ timeout: { type: Number },
3852
+ quantity: { type: Number },
3853
+ currency: {},
3854
+ labelAddToCart: { attribute: "label-add-to-cart" },
3855
+ labelViewProduct: { attribute: "label-view-product" },
3856
+ hydration: { converter: hydrationConverter },
3857
+ hydrationTimeout: { type: Number, attribute: "hydration-timeout" },
3858
+ slideDuration: { type: Number, attribute: "slide-duration" },
3859
+ inactiveAutoplay: {
3860
+ type: Boolean,
3861
+ attribute: "inactive-autoplay",
3862
+ converter: booleanConverter
3863
+ },
3864
+ stories: { state: true },
3865
+ products: { state: true },
3866
+ requesting: { state: true },
3867
+ mediaLoading: { state: true }
746
3868
  };
747
- VtexAdsStoryElement.styles = [
748
- css3`
3869
+ VtexAdsStoryCarouselElement.styles = [
3870
+ css7`
749
3871
  :host {
750
3872
  display: block;
751
3873
  font-family: var(--vtex-ads-story-font-family, inherit);
752
3874
  color: var(--vtex-ads-story-color-text, inherit);
3875
+ --_pill-radius: var(--vtex-ads-story-radius, 16px);
3876
+ --_pill-inset: 8px;
3877
+ --_button-radius: var(--vtex-ads-story-radius, 999px);
753
3878
  }
754
3879
  `,
755
3880
  cardStyles,
3881
+ mediaStyles,
3882
+ productStyles,
3883
+ carouselStyles,
3884
+ carouselSkeletonStyles,
756
3885
  playerStyles
757
3886
  ];
758
- function defineVtexAdsStories() {
3887
+ function defineVtexAdsStoryCarousel() {
759
3888
  if (typeof customElements === "undefined") return;
760
3889
  if (customElements.get(TAG_NAME)) return;
761
- customElements.define(TAG_NAME, VtexAdsStoryElement);
3890
+ customElements.define(TAG_NAME, VtexAdsStoryCarouselElement);
762
3891
  }
763
3892
  export {
3893
+ ADD_TO_CART_EVENT,
3894
+ REMOVE_FROM_CART_EVENT,
764
3895
  TAG_NAME,
765
- VtexAdsStoryElement,
766
- defineVtexAdsStories
3896
+ VtexAdsStoryCarouselElement,
3897
+ defineVtexAdsStoryCarousel
767
3898
  };
768
3899
  /*! Icons from Phosphor Icons (https://phosphoricons.com), MIT License, Copyright (c) 2023 Phosphor Icons */
769
3900
  //# sourceMappingURL=index.js.map