@vtex/ads-stories 0.5.0 → 0.8.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 (49) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +29 -297
  3. package/dist/cdn/vtex-ads-stories.js +438 -113
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +932 -189
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +42 -196
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +13 -3
  10. package/dist/cjs/story-Ba9J0rbL.d.cts +276 -0
  11. package/dist/esm/index.d.ts +42 -196
  12. package/dist/esm/index.js +956 -212
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/react.d.ts +13 -3
  15. package/dist/esm/story-Ba9J0rbL.d.ts +276 -0
  16. package/package.json +1 -1
  17. package/src/commerce-events.ts +93 -0
  18. package/src/components/card/card.ts +16 -3
  19. package/src/components/carousel/carousel-skeleton.ts +113 -0
  20. package/src/components/carousel/carousel.ts +53 -8
  21. package/src/components/carousel/index.ts +7 -0
  22. package/src/components/events/events-controller.ts +23 -13
  23. package/src/components/icons/assets/minus.svg +1 -0
  24. package/src/components/icons/assets/plus.svg +1 -0
  25. package/src/components/icons/assets/trash.svg +1 -0
  26. package/src/components/icons/assets/warning-circle-fill.svg +1 -0
  27. package/src/components/icons/index.ts +8 -0
  28. package/src/components/media/index.ts +7 -1
  29. package/src/components/media/media.styles.ts +113 -0
  30. package/src/components/media/media.ts +108 -11
  31. package/src/components/media/video-controller.ts +80 -6
  32. package/src/components/player/player.ts +42 -17
  33. package/src/components/product/cta.ts +3 -3
  34. package/src/components/product/index.ts +2 -0
  35. package/src/components/product/product.styles.ts +63 -6
  36. package/src/components/product/product.ts +130 -29
  37. package/src/index.ts +8 -0
  38. package/src/locales/en.ts +13 -3
  39. package/src/locales/es.ts +13 -3
  40. package/src/locales/index.ts +6 -0
  41. package/src/locales/pt.ts +13 -3
  42. package/src/locales/types.ts +22 -2
  43. package/src/react.ts +12 -2
  44. package/src/story/story.ts +218 -20
  45. package/src/utils/hydrate-products.ts +30 -6
  46. package/src/utils/media-ready.ts +58 -0
  47. package/src/utils/safe-url.ts +36 -0
  48. package/src/utils/send-event.ts +1 -1
  49. package/src/utils/http-url.ts +0 -12
package/src/locales/pt.ts CHANGED
@@ -17,12 +17,22 @@ export const pt: StoryLabels = {
17
17
  soundOn: "Ativar som",
18
18
  soundOff: "Desativar som",
19
19
  addToCart: "Adicionar ao carrinho",
20
+ cartQuantity: "Quantidade no carrinho",
21
+ decreaseQuantity: "Diminuir quantidade",
22
+ removeFromCart: "Remover do carrinho",
23
+ increaseQuantity: "Aumentar quantidade",
20
24
  unavailable: "Produto indisponível",
21
25
  soldOut: "Esgotado",
22
26
  viewProduct: "Ver produto",
23
- product: (name, price, listPrice) => {
24
- if (price && listPrice) return `${name}, de ${listPrice} por ${price}`;
25
- return price ? `${name}, ${price}` : name;
27
+ videoUnavailable: "Vídeo indisponível",
28
+ videoFailed: "Não foi possível carregar o vídeo",
29
+ retry: "Tentar de novo",
30
+ videoLoading: "Carregando vídeo",
31
+ product: (name, price, listPrice, soldOut) => {
32
+ let text = name;
33
+ if (price && listPrice) text = `${name}, de ${listPrice} por ${price}`;
34
+ else if (price) text = `${name}, ${price}`;
35
+ return soldOut ? `${text}, ${soldOut}` : text;
26
36
  },
27
37
  position: (label, index, count) =>
28
38
  count > 1 ? `${label} ${index + 1} de ${count}` : label,
@@ -14,11 +14,31 @@ export interface StoryLabels {
14
14
  soundOn: string;
15
15
  soundOff: string;
16
16
  addToCart: string;
17
+ cartQuantity: string;
18
+ decreaseQuantity: string;
19
+ removeFromCart: string;
20
+ increaseQuantity: string;
17
21
  unavailable: string;
18
22
  soldOut: string;
19
23
  viewProduct: string;
20
- /** The product button: "Tênis, de R$ 159,90 por R$ 129,90". */
21
- product: (name: string, price?: string, listPrice?: string) => string;
24
+ /** Over the card's cover when its video can't load. */
25
+ videoUnavailable: string;
26
+ /** Over the player's cover when its video can't load. */
27
+ videoFailed: string;
28
+ /** While the player loads the video. */
29
+ videoLoading: string;
30
+ /** The player's button to load the video again. */
31
+ retry: string;
32
+ /**
33
+ * The product button: "Tênis, de R$ 159,90 por R$ 129,90", followed by
34
+ * `soldOut` when the product can't be bought.
35
+ */
36
+ product: (
37
+ name: string,
38
+ price?: string,
39
+ listPrice?: string,
40
+ soldOut?: string,
41
+ ) => string;
22
42
  /** Tells the cards apart: "Mostrar vídeo 2 de 4". */
23
43
  position: (label: string, index: number, count: number) => string;
24
44
  }
package/src/react.ts CHANGED
@@ -33,10 +33,14 @@ export interface VtexAdsStoryCarouselAttributes {
33
33
  quantity?: number;
34
34
  /** Currency of the prices, ISO 4217 ("BRL"). Default BRL. */
35
35
  currency?: string;
36
- /** The add to cart button's text. Default in the element's language. */
36
+ /** Add to cart button's text. Default in the element's language. */
37
37
  "label-add-to-cart"?: string;
38
- /** The view product button's text. Default in the element's language. */
38
+ /** View product button's text. Default in the element's language. */
39
39
  "label-view-product"?: string;
40
+ /** Unavailable product button's text. Default in the element's language. */
41
+ "label-unavailable"?: string;
42
+ /** Sold out text. Default in the element's language. */
43
+ "label-sold-out"?: string;
40
44
  /**
41
45
  * "none": no product request. To set a strategy, assign the element's
42
46
  * `hydration` property. Missing: Intelligent Search with `account-name`.
@@ -49,6 +53,12 @@ export interface VtexAdsStoryCarouselAttributes {
49
53
  * their video, muted. Off by default.
50
54
  */
51
55
  "inactive-autoplay"?: boolean;
56
+ /**
57
+ * With more than one Story, how long each one stays highlighted, in
58
+ * milliseconds (default 5000). 0: no automatic advance. Never advances on
59
+ * its own for people who prefer reduced motion.
60
+ */
61
+ "slide-duration"?: number;
52
62
  }
53
63
 
54
64
  export type VtexAdsStoryCarouselProps = DetailedHTMLProps<
@@ -3,19 +3,28 @@ import type { Channel } from "@vtex/ads-core";
3
3
  import { cardStyles, renderCard } from "../components/card";
4
4
  import {
5
5
  CarouselController,
6
+ carouselSkeletonStyles,
6
7
  carouselStyles,
7
8
  RENDERED_SIDE,
9
+ renderCarouselSkeleton,
8
10
  type Slide,
9
11
  } from "../components/carousel";
10
12
  import { StoryEventsController, type ViewTarget } from "../components/events";
11
- import { VideoController } from "../components/media";
13
+ import {
14
+ mediaStyles,
15
+ prefersReducedMotion,
16
+ VideoController,
17
+ } from "../components/media";
12
18
  import {
13
19
  DEFAULT_LOCALE,
20
+ focusCartAction,
14
21
  priceFormatter,
15
22
  productStyles,
16
23
  toCardCta,
17
24
  toCardProduct,
25
+ type CardProduct,
18
26
  type FetchedProduct,
27
+ type ProductCartActions,
19
28
  } from "../components/product";
20
29
  import {
21
30
  neighborOffsets,
@@ -30,7 +39,14 @@ import {
30
39
  type StoryProductDetails,
31
40
  } from "../utils/hydrate-products";
32
41
  import { fetchStories } from "../utils/fetch-story";
42
+ import { httpUrl } from "../utils/safe-url";
43
+ import { decodeImage, firstReady } from "../utils/media-ready";
33
44
  import { labelsFor, type StoryLabels } from "../locales";
45
+ import {
46
+ addToCartEvent,
47
+ removeFromCartEvent,
48
+ type StoryCartItem,
49
+ } from "../commerce-events";
34
50
  import { TAG_NAME } from "../tag-name";
35
51
 
36
52
  export { TAG_NAME } from "../tag-name";
@@ -77,6 +93,10 @@ const hydrationConverter = {
77
93
  value === "none" ? ("none" as const) : undefined,
78
94
  };
79
95
 
96
+ // A cart line is a SKU from a seller: the stepper counts each pair apart.
97
+ const cartKey = ({ sku, seller }: StoryCartItem) =>
98
+ JSON.stringify([sku, seller ?? ""]);
99
+
80
100
  // LitElement is importable where HTMLElement doesn't exist (SSR, Node): Lit
81
101
  // falls back to a minimal shim there.
82
102
  export class VtexAdsStoryCarouselElement extends LitElement {
@@ -92,8 +112,11 @@ export class VtexAdsStoryCarouselElement extends LitElement {
92
112
  currency: {},
93
113
  labelAddToCart: { attribute: "label-add-to-cart" },
94
114
  labelViewProduct: { attribute: "label-view-product" },
115
+ labelUnavailable: { attribute: "label-unavailable" },
116
+ labelSoldOut: { attribute: "label-sold-out" },
95
117
  hydration: { converter: hydrationConverter },
96
118
  hydrationTimeout: { type: Number, attribute: "hydration-timeout" },
119
+ slideDuration: { type: Number, attribute: "slide-duration" },
97
120
  inactiveAutoplay: {
98
121
  type: Boolean,
99
122
  attribute: "inactive-autoplay",
@@ -101,6 +124,8 @@ export class VtexAdsStoryCarouselElement extends LitElement {
101
124
  },
102
125
  stories: { state: true },
103
126
  products: { state: true },
127
+ requesting: { state: true },
128
+ mediaLoading: { state: true },
104
129
  };
105
130
 
106
131
  /** Required. The publisher the ads are requested for. */
@@ -131,14 +156,24 @@ export class VtexAdsStoryCarouselElement extends LitElement {
131
156
  declare currency?: string;
132
157
  /**
133
158
  * The add to cart button's text. Missing or blank: the default in the
134
- * element's language ("Adicionar ao carrinho").
159
+ * element's language.
135
160
  */
136
161
  declare labelAddToCart?: string;
137
162
  /**
138
163
  * The view product button's text. Missing or blank: the default in the
139
- * element's language ("Ver produto").
164
+ * element's language.
140
165
  */
141
166
  declare labelViewProduct?: string;
167
+ /**
168
+ * The text of the disabled button for a product that can't be bought.
169
+ * Missing or blank: the default in the element's language.
170
+ */
171
+ declare labelUnavailable?: string;
172
+ /**
173
+ * The sold out text, shown with the price and read by screen readers.
174
+ * Missing or blank: the default in the element's language.
175
+ */
176
+ declare labelSoldOut?: string;
142
177
  /**
143
178
  * Where the products' details (for now, their prices) come from. A
144
179
  * strategy (fetcher, matcher and price reader) is set as a property; the
@@ -158,6 +193,12 @@ export class VtexAdsStoryCarouselElement extends LitElement {
158
193
  * only the highlighted card plays.
159
194
  */
160
195
  declare inactiveAutoplay: boolean;
196
+ /**
197
+ * With more than one Story, how long each one stays highlighted before the
198
+ * next, in milliseconds (default 5000). Zero: the highlight moves only by
199
+ * hand. A change starts the time over; it doesn't request again.
200
+ */
201
+ declare slideDuration?: number;
161
202
 
162
203
  /** The Stories shown: none while loading, on error or with none. */
163
204
  declare private stories: StoryAd[];
@@ -168,6 +209,26 @@ export class VtexAdsStoryCarouselElement extends LitElement {
168
209
  */
169
210
  declare private products?: Map<string, StoryProductDetails> | "loading";
170
211
 
212
+ /**
213
+ * The ad request is pending (and has what it needs to go out): a skeleton
214
+ * stands in for the carousel until the Stories arrive.
215
+ */
216
+ declare private requesting: boolean;
217
+
218
+ /**
219
+ * The first Story's media is still loading: a skeleton covers the cards
220
+ * until its cover or its video is ready (or MEDIA_TIMEOUT passes), so the
221
+ * first card doesn't show up piece by piece. Meanwhile, the cards load
222
+ * underneath, their videos without playing, and no event goes out.
223
+ */
224
+ declare private mediaLoading: boolean;
225
+
226
+ /**
227
+ * Cancels the wait for the media in progress: when other Stories replace
228
+ * its Stories, or the element leaves the page.
229
+ */
230
+ private mediaWait?: AbortController;
231
+
171
232
  /**
172
233
  * Cancels the request in progress. Kept, already aborted, when leaving the
173
234
  * page cancelled it, so connecting again requests once more.
@@ -180,14 +241,27 @@ export class VtexAdsStoryCarouselElement extends LitElement {
180
241
  display: block;
181
242
  font-family: var(--vtex-ads-story-font-family, inherit);
182
243
  color: var(--vtex-ads-story-color-text, inherit);
244
+ --_pill-radius: var(--vtex-ads-story-radius, 16px);
245
+ --_pill-inset: 8px;
246
+ --_button-radius: var(--vtex-ads-story-radius, 999px);
183
247
  }
184
248
  `,
185
249
  cardStyles,
250
+ mediaStyles,
186
251
  productStyles,
187
252
  carouselStyles,
253
+ carouselSkeletonStyles,
188
254
  playerStyles,
189
255
  ];
190
256
 
257
+ /**
258
+ * How many of each SKU, from each seller (see cartKey), were added since
259
+ * the player opened, for its stepper. It doesn't read the store's cart: it
260
+ * counts the add and remove events sent, and starts over each time the
261
+ * player opens, as the cart may have changed meanwhile.
262
+ */
263
+ private readonly cartQuantities = new Map<string, number>();
264
+
191
265
  /**
192
266
  * One per rendered card, by its key (see Slide): a Story can show in more
193
267
  * than one card, each with its own video.
@@ -215,7 +289,9 @@ export class VtexAdsStoryCarouselElement extends LitElement {
215
289
  }
216
290
  },
217
291
  // The player shows the highlighted Story: the highlight stays on it.
218
- locked: () => this.player.isOpen,
292
+ locked: () => this.player.isOpen || this.mediaLoading,
293
+ slideDuration: () => this.slideDuration,
294
+ reducedMotion: prefersReducedMotion,
219
295
  });
220
296
 
221
297
  private readonly player = new PlayerController(this, {
@@ -234,6 +310,8 @@ export class VtexAdsStoryCarouselElement extends LitElement {
234
310
  super();
235
311
  this.inactiveAutoplay = false;
236
312
  this.stories = [];
313
+ this.requesting = false;
314
+ this.mediaLoading = false;
237
315
  }
238
316
 
239
317
  // Lit keeps the card's DOM when the element is moved (removed and appended
@@ -254,6 +332,7 @@ export class VtexAdsStoryCarouselElement extends LitElement {
254
332
  disconnectedCallback() {
255
333
  super.disconnectedCallback();
256
334
  this.request?.abort();
335
+ this.mediaWait?.abort();
257
336
  }
258
337
 
259
338
  protected willUpdate(changed: PropertyValues<this>) {
@@ -288,6 +367,7 @@ export class VtexAdsStoryCarouselElement extends LitElement {
288
367
 
289
368
  // The Stories shown no longer match the request either.
290
369
  this.player.close();
370
+ this.requesting = false;
291
371
  this.showStories([]);
292
372
 
293
373
  // Off the page (an attribute changed just before the element was
@@ -297,6 +377,9 @@ export class VtexAdsStoryCarouselElement extends LitElement {
297
377
  return;
298
378
  }
299
379
 
380
+ this.requesting = Boolean(
381
+ this.publisherId && this.sessionId && this.placement,
382
+ );
300
383
  const stories = await fetchStories(this, {
301
384
  signal: request.signal,
302
385
  timeout: this.timeout,
@@ -305,6 +388,7 @@ export class VtexAdsStoryCarouselElement extends LitElement {
305
388
  // Cancelled meanwhile, by a newer request or by leaving the page: this
306
389
  // response is not shown.
307
390
  if (request.signal.aborted) return;
391
+ this.requesting = false;
308
392
 
309
393
  const hydration = this.activeHydration;
310
394
  if (!hydration || !stories.some((story) => story.product)) {
@@ -344,7 +428,42 @@ export class VtexAdsStoryCarouselElement extends LitElement {
344
428
  this.afterRender = undefined;
345
429
  this.carousel.reset(stories.length);
346
430
  this.stories = stories;
431
+ void this.waitForFirstMedia(stories);
432
+ }
433
+
434
+ /**
435
+ * Shows the cards once the first Story's cover or video is ready: whichever
436
+ * loads first, or once both failed. Only then are the Stories impressed
437
+ * and do their videos play, from the start.
438
+ */
439
+ private async waitForFirstMedia(stories: StoryAd[]) {
440
+ this.mediaWait?.abort();
441
+ const wait = new AbortController();
442
+ this.mediaWait = wait;
443
+
444
+ const cover = httpUrl(stories[0]?.poster_url);
445
+ const video = httpUrl(stories[0]?.media_url);
446
+ const checks: Promise<boolean>[] = [];
447
+ if (cover) checks.push(decodeImage(cover));
448
+ // The first card's: the highlighted one, after carousel.reset().
449
+ if (video) checks.push(this.videoFor(this.carousel.activeKey).ready);
450
+
451
+ this.mediaLoading = checks.length > 0;
452
+ await firstReady(checks, wait.signal);
453
+ // Other Stories came meanwhile: they wait for their own media. Leaving
454
+ // the page ends the wait with the cards shown.
455
+ if (this.mediaWait !== wait) return;
456
+
457
+ this.mediaWait = undefined;
458
+ this.mediaLoading = false;
347
459
  this.events.impress(stories);
460
+ this.afterRender = () => {
461
+ if (!this.isConnected) return;
462
+ for (const cardVideo of this.cardVideos.values()) cardVideo.resume();
463
+ };
464
+ // Without media to wait for, mediaLoading didn't change: nothing else
465
+ // asks for the render that sends the impressions.
466
+ this.requestUpdate();
348
467
  }
349
468
 
350
469
  /**
@@ -355,6 +474,7 @@ export class VtexAdsStoryCarouselElement extends LitElement {
355
474
  */
356
475
  private *viewTargets(): Generator<ViewTarget> {
357
476
  const { stories } = this;
477
+ if (this.mediaLoading) return;
358
478
 
359
479
  if (!this.player.isExpanded) {
360
480
  for (const [card, { key, index }] of this.carousel.visibleCards()) {
@@ -425,6 +545,7 @@ export class VtexAdsStoryCarouselElement extends LitElement {
425
545
  private openPlayer({ productOpen = false } = {}) {
426
546
  if (this.player.isOpen) return;
427
547
 
548
+ this.cartQuantities.clear();
428
549
  // While the player is open, the card behind it stops on its cover.
429
550
  this.activeVideo?.pause();
430
551
  void this.player.open({ productOpen });
@@ -465,14 +586,28 @@ export class VtexAdsStoryCarouselElement extends LitElement {
465
586
  private labelSet?: { key: string; labels: StoryLabels };
466
587
 
467
588
  private get labels() {
468
- const { locale, labelAddToCart = "", labelViewProduct = "" } = this;
469
- const key = JSON.stringify([locale, labelAddToCart, labelViewProduct]);
589
+ const {
590
+ locale,
591
+ labelAddToCart = "",
592
+ labelViewProduct = "",
593
+ labelUnavailable = "",
594
+ labelSoldOut = "",
595
+ } = this;
596
+ const key = JSON.stringify([
597
+ locale,
598
+ labelAddToCart,
599
+ labelViewProduct,
600
+ labelUnavailable,
601
+ labelSoldOut,
602
+ ]);
470
603
  if (this.labelSet?.key !== key) {
471
604
  this.labelSet = {
472
605
  key,
473
606
  labels: labelsFor(locale, {
474
607
  addToCart: labelAddToCart,
475
608
  viewProduct: labelViewProduct,
609
+ unavailable: labelUnavailable,
610
+ soldOut: labelSoldOut,
476
611
  }),
477
612
  };
478
613
  }
@@ -508,6 +643,7 @@ export class VtexAdsStoryCarouselElement extends LitElement {
508
643
  ),
509
644
  labels: this.labels,
510
645
  withVideo: active || (this.inactiveAutoplay && !hidden),
646
+ autoplay: !this.mediaLoading,
511
647
  product: this.productOf(story),
512
648
  onSelect: active
513
649
  ? () => this.openPlayer()
@@ -529,8 +665,28 @@ export class VtexAdsStoryCarouselElement extends LitElement {
529
665
  const { stories } = this;
530
666
  const index = this.carousel.active;
531
667
  const active = stories[index];
532
- if (!active) return nothing;
668
+ if (!active && !this.requesting) return nothing;
669
+
670
+ const loading = this.requesting || this.mediaLoading;
671
+
672
+ return html`
673
+ <div
674
+ class="root"
675
+ ?data-loading=${loading}
676
+ ?data-requesting=${this.requesting}
677
+ >
678
+ ${active
679
+ ? this.carousel.render(stories, this.renderSlide, this.labels)
680
+ : nothing}
681
+ ${renderCarouselSkeleton({ done: !loading })}
682
+ </div>
683
+ ${active ? this.renderPlayer(active) : nothing}
684
+ `;
685
+ }
533
686
 
687
+ private renderPlayer(active: StoryAd) {
688
+ const { stories } = this;
689
+ const index = this.carousel.active;
534
690
  const neighbors = neighborOffsets(stories.length, index).map((offset) => {
535
691
  const neighbor = (index + offset + stories.length) % stories.length;
536
692
  return {
@@ -540,19 +696,61 @@ export class VtexAdsStoryCarouselElement extends LitElement {
540
696
  };
541
697
  });
542
698
 
543
- return html`
544
- <div class="root">
545
- ${this.carousel.render(stories, this.renderSlide, this.labels)}
546
- </div>
547
- ${this.player.render(active, {
548
- labels: this.labels,
549
- navigation: stories.length > 1,
550
- neighbors,
551
- product: this.productOf(active),
552
- cta: toCardCta(active),
553
- onPress: () => this.events.click(active),
554
- })}
555
- `;
699
+ const product = this.productOf(active);
700
+
701
+ return this.player.render(active, {
702
+ labels: this.labels,
703
+ navigation: stories.length > 1,
704
+ neighbors,
705
+ product,
706
+ cta: toCardCta(active),
707
+ productActions: this.cartActionsFor(product),
708
+ onPress: () => this.events.click(active),
709
+ });
710
+ }
711
+
712
+ private cartActionsFor(
713
+ product?: CardProduct,
714
+ ): ProductCartActions | undefined {
715
+ const sku = product?.sku;
716
+ if (!sku) return undefined;
717
+
718
+ const item = { sku, seller: product.seller };
719
+ return {
720
+ cartQuantity: this.cartQuantities.get(cartKey(item)),
721
+ onAddToCart: () => this.changeCart(item, 1),
722
+ onRemoveFromCart: () => this.changeCart(item, -1),
723
+ };
724
+ }
725
+
726
+ /**
727
+ * Adds one of `item` to the stepper's count, or removes one, and tells the
728
+ * store, which changes its cart: the element has none. When add to cart
729
+ * and the stepper swap places, the focus moves to the one now shown.
730
+ */
731
+ private changeCart(item: StoryCartItem, delta: 1 | -1) {
732
+ const key = cartKey(item);
733
+ const before = this.cartQuantities.get(key) ?? 0;
734
+ const after = Math.max(0, before + delta);
735
+ if (after === before) return;
736
+
737
+ if (after > 0) this.cartQuantities.set(key, after);
738
+ else this.cartQuantities.delete(key);
739
+ this.requestUpdate();
740
+
741
+ this.dispatchEvent(
742
+ delta > 0 ? addToCartEvent(item) : removeFromCartEvent(item),
743
+ );
744
+
745
+ let swapped: "stepper" | "add" | undefined;
746
+ if (before === 0) swapped = "stepper";
747
+ else if (after === 0) swapped = "add";
748
+ if (!swapped) return;
749
+
750
+ const action = swapped;
751
+ this.updateComplete.then(
752
+ () => this.shadowRoot && focusCartAction(this.shadowRoot, action),
753
+ );
556
754
  }
557
755
  }
558
756
 
@@ -41,6 +41,23 @@ export interface StoryProductDetails {
41
41
  available?: boolean;
42
42
  }
43
43
 
44
+ // A price the card can show: an amount (0 included, as the strategy says),
45
+ // with the "from" price only when it is above it, as intelligentSearchPrice
46
+ // reads them. A store's own reader may return anything (a missing amount,
47
+ // NaN, a string): then the ad server's price shows instead.
48
+ function toShownPrice(
49
+ value: ProductPrice | undefined,
50
+ ): ProductPrice | undefined {
51
+ const isAmount = (amount: unknown): amount is number =>
52
+ typeof amount === "number" && Number.isFinite(amount) && amount >= 0;
53
+
54
+ if (!isAmount(value?.price)) return undefined;
55
+ const { price, listPrice } = value;
56
+ return isAmount(listPrice) && listPrice > price
57
+ ? { price, listPrice }
58
+ : { price };
59
+ }
60
+
44
61
  export interface HydrateProductsOptions {
45
62
  signal?: AbortSignal;
46
63
  timeout?: number;
@@ -67,12 +84,19 @@ export async function hydrateStoryProducts(
67
84
 
68
85
  for (const { story, product, offer } of hydrated.stories[placement] ?? []) {
69
86
  if (!product || !offer) continue;
70
- const price = hydration.price(product, offer);
71
- const available = hydration.available?.(product, offer);
72
- products.set(story.ad_id, {
73
- ...(price && { price }),
74
- ...(available !== undefined && { available }),
75
- });
87
+ try {
88
+ const price = toShownPrice(hydration.price(product, offer));
89
+ const available = hydration.available?.(product, offer);
90
+ products.set(story.ad_id, {
91
+ ...(price && { price }),
92
+ ...(available !== undefined && { available }),
93
+ });
94
+ } catch (error) {
95
+ console.error(
96
+ `[${TAG_NAME}] Product details failed for ad ${story.ad_id}`,
97
+ error,
98
+ );
99
+ }
76
100
  }
77
101
  } catch (error) {
78
102
  // As for the Story request: a cancelled or timed out request needs no
@@ -0,0 +1,58 @@
1
+ import { withTimeout } from "./with-timeout";
2
+
3
+ /** How long the first Story's media may take before it shows anyway, in ms. */
4
+ export const MEDIA_TIMEOUT = 3000;
5
+
6
+ /**
7
+ * Loads and decodes an image, so it paints at once when it shows. Resolves
8
+ * true once it is ready and false if it fails. Never rejects.
9
+ *
10
+ * Without `Image` or `decode` (SSR, old browsers, jsdom) there is nothing to
11
+ * wait for: it resolves true at once.
12
+ */
13
+ export function decodeImage(url: string): Promise<boolean> {
14
+ if (typeof Image === "undefined") return Promise.resolve(true);
15
+
16
+ const image = new Image();
17
+ image.src = url;
18
+ if (!image.decode) return Promise.resolve(true);
19
+ return image.decode().then(
20
+ () => true,
21
+ () => false,
22
+ );
23
+ }
24
+
25
+ /**
26
+ * Waits for the first of `checks` to be ready: resolves when one resolves
27
+ * true, when all resolved false (nothing left to wait for), after
28
+ * MEDIA_TIMEOUT, or when `signal` aborts. Never rejects.
29
+ */
30
+ export function firstReady(
31
+ checks: readonly Promise<boolean>[],
32
+ signal?: AbortSignal,
33
+ ): Promise<void> {
34
+ if (!checks.length) return Promise.resolve();
35
+
36
+ const limit = withTimeout(undefined, MEDIA_TIMEOUT, signal);
37
+
38
+ return new Promise<void>((resolve) => {
39
+ const done = () => {
40
+ limit.clear();
41
+ resolve();
42
+ };
43
+ if (limit.signal.aborted) return done();
44
+ limit.signal.addEventListener("abort", done, { once: true });
45
+
46
+ let failed = 0;
47
+ for (const check of checks) {
48
+ check.then(
49
+ (ready) => {
50
+ if (ready || ++failed === checks.length) done();
51
+ },
52
+ () => {
53
+ if (++failed === checks.length) done();
54
+ },
55
+ );
56
+ }
57
+ });
58
+ }
@@ -0,0 +1,36 @@
1
+ // Only absolute http(s) URLs reach the DOM or the network. Relative and
2
+ // protocol-relative ones ("/a.jpg", "//host/a.jpg") don't parse without a
3
+ // base, so they're out.
4
+ export function httpUrl(value: string | undefined) {
5
+ if (!value) return null;
6
+ try {
7
+ const { protocol } = new URL(value);
8
+ return protocol === "https:" || protocol === "http:" ? value : null;
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ const STORE_BASE = "https://store.invalid";
15
+
16
+ // A path on the store the Story runs in ("/product/p"), resolved the way the
17
+ // browser would, or null when it lands on another host ("//evil.com",
18
+ // "/\\evil.com", "/\t/evil.com").
19
+ function storePath(value: string) {
20
+ try {
21
+ const url = new URL(value, STORE_BASE);
22
+ if (url.origin !== STORE_BASE || url.pathname.startsWith("//")) {
23
+ return null;
24
+ }
25
+ return `${url.pathname}${url.search}${url.hash}`;
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ // A destination is an absolute http(s) URL or a path on the store the
32
+ // Story runs in.
33
+ export function destinationUrl(value: string | undefined) {
34
+ if (!value) return null;
35
+ return value.startsWith("/") ? storePath(value) : httpUrl(value);
36
+ }
@@ -1,4 +1,4 @@
1
- import { httpUrl } from "./http-url";
1
+ import { httpUrl } from "./safe-url";
2
2
  import { TAG_NAME } from "../tag-name";
3
3
 
4
4
  // A CORS-safelisted type: the browser sends the event without a preflight
@@ -1,12 +0,0 @@
1
- // Only absolute http(s) URLs reach the DOM or the network. Relative and
2
- // protocol-relative ones ("/a.jpg", "//host/a.jpg") don't parse without a
3
- // base, so they're out.
4
- export function httpUrl(value: string | undefined) {
5
- if (!value) return null;
6
- try {
7
- const { protocol } = new URL(value);
8
- return protocol === "https:" || protocol === "http:" ? value : null;
9
- } catch {
10
- return null;
11
- }
12
- }