@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
@@ -1,59 +1,307 @@
1
- import { css, html, LitElement } from "lit";
1
+ import { css, html, LitElement, nothing, type PropertyValues } from "lit";
2
+ import type { Channel } from "@vtex/ads-core";
2
3
  import { cardStyles, renderCard } from "../components/card";
3
- import { VideoController } from "../components/media";
4
- import { PlayerController, playerStyles } from "../components/player";
5
- import type { StoryMedia } from "../types";
4
+ import {
5
+ CarouselController,
6
+ carouselSkeletonStyles,
7
+ carouselStyles,
8
+ RENDERED_SIDE,
9
+ renderCarouselSkeleton,
10
+ type Slide,
11
+ } from "../components/carousel";
12
+ import { StoryEventsController, type ViewTarget } from "../components/events";
13
+ import {
14
+ mediaStyles,
15
+ prefersReducedMotion,
16
+ VideoController,
17
+ } from "../components/media";
18
+ import {
19
+ DEFAULT_LOCALE,
20
+ focusCartAction,
21
+ priceFormatter,
22
+ productStyles,
23
+ toCardCta,
24
+ toCardProduct,
25
+ type CardProduct,
26
+ type FetchedProduct,
27
+ type ProductCartActions,
28
+ } from "../components/product";
29
+ import {
30
+ neighborOffsets,
31
+ PlayerController,
32
+ playerStyles,
33
+ } from "../components/player";
34
+ import type { StoryAd } from "../types";
35
+ import {
36
+ hydrateStoryProducts,
37
+ intelligentSearchHydration,
38
+ type StoryHydration,
39
+ type StoryProductDetails,
40
+ } from "../utils/hydrate-products";
41
+ import { fetchStories } from "../utils/fetch-story";
42
+ import { httpUrl } from "../utils/safe-url";
43
+ import { decodeImage, firstReady } from "../utils/media-ready";
44
+ import { labelsFor, type StoryLabels } from "../locales";
45
+ import {
46
+ addToCartEvent,
47
+ removeFromCartEvent,
48
+ type StoryCartItem,
49
+ } from "../commerce-events";
50
+ import { TAG_NAME } from "../tag-name";
6
51
 
7
- export const TAG_NAME = "vtex-ads-story";
52
+ export { TAG_NAME } from "../tag-name";
8
53
 
9
- // Temporary: rendered until the element reads Stories from the ad API.
10
- const PLACEHOLDER_STORY: StoryMedia = {
11
- poster_url: "https://dummyimage.com/1080x1920/e31c57/fff",
12
- media_url: "https://samplelib.com/mp4/sample-10s-vp9.mp4",
54
+ // The properties that make up the ad and product requests: a change to any of
55
+ // them fetches the Story again.
56
+ const REQUEST_PROPERTIES = [
57
+ "publisherId",
58
+ "sessionId",
59
+ "placement",
60
+ "userId",
61
+ "accountName",
62
+ "channel",
63
+ "quantity",
64
+ "hydration",
65
+ ] as const;
66
+
67
+ const CHANNELS: ReadonlySet<Channel> = new Set(["site", "app"]);
68
+
69
+ const isChannel = (value: string | null): value is Channel =>
70
+ CHANNELS.has(value as Channel);
71
+
72
+ // Reads a boolean attribute: on only when present bare (`""`, as in HTML and
73
+ // React 19) or "true"; absent, "false" or any other value is off. React 18
74
+ // writes boolean props on custom elements as strings, so
75
+ // `inactive-autoplay={false}` arrives as inactive-autoplay="false".
76
+ const booleanConverter = {
77
+ fromAttribute: (value: string | null) =>
78
+ typeof value === "string" &&
79
+ (value === "" || value.toLowerCase() === "true"),
13
80
  };
14
81
 
15
- // Temporary: fixed texts until the store can set them by attribute.
16
- const LABELS = {
17
- watch: "Assistir vídeo",
18
- player: "Vídeo",
19
- expand: "Expandir vídeo",
20
- collapse: "Reduzir vídeo",
21
- close: "Fechar vídeo",
22
- play: "Reproduzir vídeo",
23
- pause: "Pausar vídeo",
24
- soundOn: "Ativar som",
25
- soundOff: "Desativar som",
82
+ // Reads the `channel` attribute. An unknown value leaves the property
83
+ // undefined, so it is not sent.
84
+ const channelConverter = {
85
+ fromAttribute: (value: string | null) =>
86
+ isChannel(value) ? value : undefined,
26
87
  };
27
88
 
89
+ // Reads the `hydration` attribute: only "none" means something there (no
90
+ // product request). A strategy is set as a property.
91
+ const hydrationConverter = {
92
+ fromAttribute: (value: string | null) =>
93
+ value === "none" ? ("none" as const) : undefined,
94
+ };
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
+
28
100
  // LitElement is importable where HTMLElement doesn't exist (SSR, Node): Lit
29
101
  // falls back to a minimal shim there.
30
- export class VtexAdsStoryElement extends LitElement {
102
+ export class VtexAdsStoryCarouselElement extends LitElement {
103
+ static readonly properties = {
104
+ publisherId: { attribute: "publisher-id" },
105
+ sessionId: { attribute: "session-id" },
106
+ placement: {},
107
+ userId: { attribute: "user-id" },
108
+ accountName: { attribute: "account-name" },
109
+ channel: { converter: channelConverter },
110
+ timeout: { type: Number },
111
+ quantity: { type: Number },
112
+ currency: {},
113
+ labelAddToCart: { attribute: "label-add-to-cart" },
114
+ labelViewProduct: { attribute: "label-view-product" },
115
+ hydration: { converter: hydrationConverter },
116
+ hydrationTimeout: { type: Number, attribute: "hydration-timeout" },
117
+ slideDuration: { type: Number, attribute: "slide-duration" },
118
+ inactiveAutoplay: {
119
+ type: Boolean,
120
+ attribute: "inactive-autoplay",
121
+ converter: booleanConverter,
122
+ },
123
+ stories: { state: true },
124
+ products: { state: true },
125
+ requesting: { state: true },
126
+ mediaLoading: { state: true },
127
+ };
128
+
129
+ /** Required. The publisher the ads are requested for. */
130
+ declare publisherId?: string;
131
+ /** Required. The store's session, also used to deduplicate events. */
132
+ declare sessionId?: string;
133
+ /** Required. The Story placement configured for the publisher. */
134
+ declare placement?: string;
135
+ declare userId?: string;
136
+ declare accountName?: string;
137
+ /** `site` or `app`. Any other attribute value is ignored. */
138
+ declare channel?: Channel;
139
+ /**
140
+ * Time limit for the ad request, in milliseconds (default 2000). Without a
141
+ * Story by then, the element renders nothing. A change applies to the next
142
+ * request; it doesn't request again.
143
+ */
144
+ declare timeout?: number;
145
+ /**
146
+ * How many Stories to ask for: the carousel positions (default 8). Missing,
147
+ * below 1 or not a number: the default.
148
+ */
149
+ declare quantity?: number;
150
+ /**
151
+ * Currency of the prices, as an ISO 4217 code ("BRL", "ARS"). Missing or
152
+ * invalid: BRL.
153
+ */
154
+ declare currency?: string;
155
+ /**
156
+ * The add to cart button's text. Missing or blank: the default in the
157
+ * element's language ("Adicionar ao carrinho").
158
+ */
159
+ declare labelAddToCart?: string;
160
+ /**
161
+ * The view product button's text. Missing or blank: the default in the
162
+ * element's language ("Ver produto").
163
+ */
164
+ declare labelViewProduct?: string;
165
+ /**
166
+ * Where the products' details (for now, their prices) come from. A
167
+ * strategy (fetcher, matcher and price reader) is set as a property; the
168
+ * attribute takes only "none", for no product request. Missing:
169
+ * Intelligent Search when `account-name` is set, no product request
170
+ * otherwise.
171
+ */
172
+ declare hydration?: StoryHydration | "none";
173
+ /**
174
+ * Time limit for the product request, in milliseconds (default 5000).
175
+ * Without the prices by then, the cards show the ad server's.
176
+ */
177
+ declare hydrationTimeout?: number;
178
+ /**
179
+ * With more than one Story, whether the cards without the highlight also
180
+ * play their video, muted. Off by default: they show only their cover, and
181
+ * only the highlighted card plays.
182
+ */
183
+ declare inactiveAutoplay: boolean;
184
+ /**
185
+ * With more than one Story, how long each one stays highlighted before the
186
+ * next, in milliseconds (default 5000). Zero: the highlight moves only by
187
+ * hand. A change starts the time over; it doesn't request again.
188
+ */
189
+ declare slideDuration?: number;
190
+
191
+ /** The Stories shown: none while loading, on error or with none. */
192
+ declare private stories: StoryAd[];
193
+
194
+ /**
195
+ * The fetched products, by Story `ad_id`, or `"loading"` while the product
196
+ * request runs. Undefined without a product request.
197
+ */
198
+ declare private products?: Map<string, StoryProductDetails> | "loading";
199
+
200
+ /**
201
+ * The ad request is pending (and has what it needs to go out): a skeleton
202
+ * stands in for the carousel until the Stories arrive.
203
+ */
204
+ declare private requesting: boolean;
205
+
206
+ /**
207
+ * The first Story's media is still loading: a skeleton covers the cards
208
+ * until its cover or its video is ready (or MEDIA_TIMEOUT passes), so the
209
+ * first card doesn't show up piece by piece. Meanwhile, the cards load
210
+ * underneath, their videos without playing, and no event goes out.
211
+ */
212
+ declare private mediaLoading: boolean;
213
+
214
+ /**
215
+ * Cancels the wait for the media in progress: when other Stories replace
216
+ * its Stories, or the element leaves the page.
217
+ */
218
+ private mediaWait?: AbortController;
219
+
220
+ /**
221
+ * Cancels the request in progress. Kept, already aborted, when leaving the
222
+ * page cancelled it, so connecting again requests once more.
223
+ */
224
+ private request?: AbortController;
225
+
31
226
  static readonly styles = [
32
227
  css`
33
228
  :host {
34
229
  display: block;
35
230
  font-family: var(--vtex-ads-story-font-family, inherit);
36
231
  color: var(--vtex-ads-story-color-text, inherit);
232
+ --_pill-radius: var(--vtex-ads-story-radius, 16px);
233
+ --_pill-inset: 8px;
234
+ --_button-radius: var(--vtex-ads-story-radius, 999px);
37
235
  }
38
236
  `,
39
237
  cardStyles,
238
+ mediaStyles,
239
+ productStyles,
240
+ carouselStyles,
241
+ carouselSkeletonStyles,
40
242
  playerStyles,
41
243
  ];
42
244
 
43
- private readonly cardVideo = new VideoController(this);
245
+ /**
246
+ * How many of each SKU, from each seller (see cartKey), were added since
247
+ * the player opened, for its stepper. It doesn't read the store's cart: it
248
+ * counts the add and remove events sent, and starts over each time the
249
+ * player opens, as the cart may have changed meanwhile.
250
+ */
251
+ private readonly cartQuantities = new Map<string, number>();
252
+
253
+ /**
254
+ * One per rendered card, by its key (see Slide): a Story can show in more
255
+ * than one card, each with its own video.
256
+ */
257
+ private readonly cardVideos = new Map<number, VideoController>();
258
+
259
+ /** The sound was on when the highlight moved: the new card turns it on. */
260
+ private soundPending = false;
261
+
262
+ /**
263
+ * What to do once the next render is on screen, when the new highlighted
264
+ * card's video exists (see leaveHighlight and onLayoutChange). A step
265
+ * taken before then replaces it.
266
+ */
267
+ private afterRender?: () => void;
268
+
269
+ private readonly carousel = new CarouselController(this, {
270
+ onStep: (from, to) => this.leaveHighlight(from, to),
271
+ // Every card is new: so are their videos. Behind an open player, the
272
+ // new highlighted card stays on its cover, as after a step.
273
+ onLayoutChange: () => {
274
+ this.cardVideos.clear();
275
+ if (this.player.isOpen) {
276
+ this.afterRender = () => this.activeVideo?.pause();
277
+ }
278
+ },
279
+ // The player shows the highlighted Story: the highlight stays on it.
280
+ locked: () => this.player.isOpen || this.mediaLoading,
281
+ slideDuration: () => this.slideDuration,
282
+ reducedMotion: prefersReducedMotion,
283
+ });
44
284
 
45
285
  private readonly player = new PlayerController(this, {
46
- label: LABELS.player,
47
- expandLabel: LABELS.expand,
48
- collapseLabel: LABELS.collapse,
49
- closeLabel: LABELS.close,
50
- playLabel: LABELS.play,
51
- pauseLabel: LABELS.pause,
52
- soundOnLabel: LABELS.soundOn,
53
- soundOffLabel: LABELS.soundOff,
286
+ onStep: (delta) => this.stepInPlayer(delta),
54
287
  onClose: () => this.closePlayer(),
55
288
  });
56
289
 
290
+ // Added after the carousel and the player: its hostUpdated reads what
291
+ // they rendered.
292
+ private readonly events = new StoryEventsController(this, {
293
+ identity: () => ({ sessionId: this.sessionId, userId: this.userId }),
294
+ viewTargets: () => this.viewTargets(),
295
+ });
296
+
297
+ constructor() {
298
+ super();
299
+ this.inactiveAutoplay = false;
300
+ this.stories = [];
301
+ this.requesting = false;
302
+ this.mediaLoading = false;
303
+ }
304
+
57
305
  // Lit keeps the card's DOM when the element is moved (removed and appended
58
306
  // again), but the browser pauses a removed video and doesn't autoplay it
59
307
  // again. resume() only plays a video that autoplays (not with reduced
@@ -62,15 +310,233 @@ export class VtexAdsStoryElement extends LitElement {
62
310
  // in the DOM until the next update and would play for a moment.
63
311
  connectedCallback() {
64
312
  super.connectedCallback();
65
- this.cardVideo.resume();
313
+ for (const video of this.cardVideos.values()) video.resume();
314
+
315
+ // Moved while its request was pending: that request was cancelled.
316
+ if (this.request?.signal.aborted) void this.loadStory();
317
+ }
318
+
319
+ // A request still pending when the element leaves the page is cancelled.
320
+ disconnectedCallback() {
321
+ super.disconnectedCallback();
322
+ this.request?.abort();
323
+ this.mediaWait?.abort();
324
+ }
325
+
326
+ protected willUpdate(changed: PropertyValues<this>) {
327
+ if (REQUEST_PROPERTIES.some((name) => changed.has(name))) {
328
+ void this.loadStory();
329
+ }
66
330
  }
67
331
 
68
- private openPlayer() {
332
+ protected updated() {
333
+ const afterRender = this.afterRender;
334
+ this.afterRender = undefined;
335
+ afterRender?.();
336
+ }
337
+
338
+ // The strategy for the products' details, if any (see `hydration`).
339
+ private get activeHydration(): StoryHydration | undefined {
340
+ if (this.hydration === "none") return undefined;
341
+ if (this.hydration) return this.hydration;
342
+ return this.accountName ? intelligentSearchHydration : undefined;
343
+ }
344
+
345
+ /**
346
+ * Requests the Story and shows it, then hydrates its products. Until the
347
+ * Story arrives, and when there is none (see fetchStories), the element
348
+ * renders nothing.
349
+ */
350
+ private async loadStory() {
351
+ // A request still pending no longer matches the attributes.
352
+ this.request?.abort();
353
+ const request = new AbortController();
354
+ this.request = request;
355
+
356
+ // The Stories shown no longer match the request either.
357
+ this.player.close();
358
+ this.requesting = false;
359
+ this.showStories([]);
360
+
361
+ // Off the page (an attribute changed just before the element was
362
+ // removed): keep the cancelled request, so connecting again requests.
363
+ if (!this.isConnected) {
364
+ request.abort();
365
+ return;
366
+ }
367
+
368
+ this.requesting = Boolean(
369
+ this.publisherId && this.sessionId && this.placement,
370
+ );
371
+ const stories = await fetchStories(this, {
372
+ signal: request.signal,
373
+ timeout: this.timeout,
374
+ });
375
+
376
+ // Cancelled meanwhile, by a newer request or by leaving the page: this
377
+ // response is not shown.
378
+ if (request.signal.aborted) return;
379
+ this.requesting = false;
380
+
381
+ const hydration = this.activeHydration;
382
+ if (!hydration || !stories.some((story) => story.product)) {
383
+ this.request = undefined;
384
+ this.showStories(stories);
385
+ return;
386
+ }
387
+
388
+ // The carousel shows now; the products' details replace their
389
+ // placeholders later.
390
+ this.showStories(stories, "loading");
391
+ const products = await hydrateStoryProducts(
392
+ this.placement ?? "",
393
+ stories,
394
+ hydration,
395
+ {
396
+ accountName: this.accountName ?? "",
397
+ publisherId: this.publisherId ?? "",
398
+ sessionId: this.sessionId ?? "",
399
+ userId: this.userId,
400
+ channel: this.channel,
401
+ },
402
+ { signal: request.signal, timeout: this.hydrationTimeout },
403
+ );
404
+
405
+ if (request.signal.aborted) return;
406
+ this.request = undefined;
407
+ this.products = products;
408
+ }
409
+
410
+ // Each card's video starts fresh: a failed load of an old one doesn't hide
411
+ // it.
412
+ private showStories(stories: StoryAd[], products?: "loading") {
413
+ this.products = products;
414
+ this.cardVideos.clear();
415
+ this.soundPending = false;
416
+ this.afterRender = undefined;
417
+ this.carousel.reset(stories.length);
418
+ this.stories = stories;
419
+ void this.waitForFirstMedia(stories);
420
+ }
421
+
422
+ /**
423
+ * Shows the cards once the first Story's cover or video is ready: whichever
424
+ * loads first, or once both failed. Only then are the Stories impressed
425
+ * and do their videos play, from the start.
426
+ */
427
+ private async waitForFirstMedia(stories: StoryAd[]) {
428
+ this.mediaWait?.abort();
429
+ const wait = new AbortController();
430
+ this.mediaWait = wait;
431
+
432
+ const cover = httpUrl(stories[0]?.poster_url);
433
+ const video = httpUrl(stories[0]?.media_url);
434
+ const checks: Promise<boolean>[] = [];
435
+ if (cover) checks.push(decodeImage(cover));
436
+ // The first card's: the highlighted one, after carousel.reset().
437
+ if (video) checks.push(this.videoFor(this.carousel.activeKey).ready);
438
+
439
+ this.mediaLoading = checks.length > 0;
440
+ await firstReady(checks, wait.signal);
441
+ // Other Stories came meanwhile: they wait for their own media. Leaving
442
+ // the page ends the wait with the cards shown.
443
+ if (this.mediaWait !== wait) return;
444
+
445
+ this.mediaWait = undefined;
446
+ this.mediaLoading = false;
447
+ this.events.impress(stories);
448
+ this.afterRender = () => {
449
+ if (!this.isConnected) return;
450
+ for (const cardVideo of this.cardVideos.values()) cardVideo.resume();
451
+ };
452
+ // Without media to wait for, mediaLoading didn't change: nothing else
453
+ // asks for the render that sends the impressions.
454
+ this.requestUpdate();
455
+ }
456
+
457
+ /**
458
+ * Where each Story is being watched: the cards on screen (not the hidden
459
+ * ones kept for the slide in) and the open player's video, while their
460
+ * video plays. A card showing only its cover doesn't count. Behind the
461
+ * expanded player, a modal over the page, the cards are covered.
462
+ */
463
+ private *viewTargets(): Generator<ViewTarget> {
464
+ const { stories } = this;
465
+ if (this.mediaLoading) return;
466
+
467
+ if (!this.player.isExpanded) {
468
+ for (const [card, { key, index }] of this.carousel.visibleCards()) {
469
+ const story = stories[index];
470
+ if (story && this.cardVideos.get(key)?.playing) yield [card, story];
471
+ }
472
+ }
473
+
474
+ const stageCard = this.player.stageCard;
475
+ const active = stories[this.carousel.active];
476
+ if (stageCard && active && this.player.video.playing) {
477
+ yield [stageCard, active];
478
+ }
479
+ }
480
+
481
+ private videoFor(key: number) {
482
+ let video = this.cardVideos.get(key);
483
+ if (!video) {
484
+ video = new VideoController(this);
485
+ this.cardVideos.set(key, video);
486
+ }
487
+ return video;
488
+ }
489
+
490
+ private get activeVideo(): VideoController | undefined {
491
+ return this.cardVideos.get(this.carousel.activeKey);
492
+ }
493
+
494
+ // The card losing the highlight goes quiet: muted if it keeps playing, or
495
+ // back to its cover. Its next video then starts fresh. If its sound was
496
+ // on, the sound moves to the new highlighted card, once its video renders.
497
+ // With the player open (it stepped), the new card stays on its cover
498
+ // behind it instead. Cards no longer rendered (the rolling layout drops
499
+ // them as it moves) leave with their videos.
500
+ private leaveHighlight(from: number, to: number) {
501
+ const video = this.cardVideos.get(from);
502
+ // Still pending: moved again before the last step rendered.
503
+ this.soundPending ||= video !== undefined && !video.muted;
504
+ if (this.inactiveAutoplay) video?.mute();
505
+ else video?.reset();
506
+
507
+ // The step requested its render before calling this: updated() runs the
508
+ // action once the new card is on screen.
509
+ if (this.player.isOpen) {
510
+ this.soundPending = false;
511
+ // Paused before it starts, its autoplay doesn't start either.
512
+ this.afterRender = () => this.videoFor(to).pause();
513
+ } else if (this.soundPending) {
514
+ this.afterRender = () => {
515
+ this.soundPending = false;
516
+ this.videoFor(to).playWithSound();
517
+ };
518
+ }
519
+
520
+ for (const key of this.cardVideos.keys()) {
521
+ if (Math.abs(key - to) > RENDERED_SIDE) this.cardVideos.delete(key);
522
+ }
523
+ }
524
+
525
+ // The player's previous and next buttons: the highlight moves with the
526
+ // Story the player shows.
527
+ private stepInPlayer(delta: number) {
528
+ this.carousel.step(delta, { evenIfLocked: true });
529
+ void this.player.showNext(delta);
530
+ }
531
+
532
+ // From the card's product, the player opens with the product panel open.
533
+ private openPlayer({ productOpen = false } = {}) {
69
534
  if (this.player.isOpen) return;
70
535
 
536
+ this.cartQuantities.clear();
71
537
  // While the player is open, the card behind it stops on its cover.
72
- this.cardVideo.pause();
73
- void this.player.open();
538
+ this.activeVideo?.pause();
539
+ void this.player.open({ productOpen });
74
540
  }
75
541
 
76
542
  // The player also closes on its own when the element leaves the page,
@@ -80,36 +546,200 @@ export class VtexAdsStoryElement extends LitElement {
80
546
  if (!this.player.isOpen) return;
81
547
 
82
548
  this.player.close();
83
- this.cardVideo.resume();
84
- this.renderRoot.querySelector<HTMLElement>(".root .card-open")?.focus();
549
+ // The highlighted card, and with inactive-autoplay the others, which may
550
+ // have been highlighted and paused while the player stepped.
551
+ for (const video of this.cardVideos.values()) video.resume();
552
+ this.carousel.focusActive();
85
553
  }
86
554
 
555
+ // The formatter for the current language and currency, made again only
556
+ // when either changes.
557
+ private formatter?: {
558
+ key: string;
559
+ format: (amount: number) => string;
560
+ };
561
+
562
+ // Prices and texts follow the language of the closest element with a
563
+ // `lang`, the element itself included, so a store can set one for the
564
+ // widget alone. An empty `lang` (unknown) is skipped; none, or an unknown
565
+ // one, falls back to pt-BR.
566
+ private get locale() {
567
+ return (
568
+ this.closest<HTMLElement>('[lang]:not([lang=""])')?.lang ?? DEFAULT_LOCALE
569
+ );
570
+ }
571
+
572
+ // The texts for the current language and label attributes, made again
573
+ // only when any of them changes.
574
+ private labelSet?: { key: string; labels: StoryLabels };
575
+
576
+ private get labels() {
577
+ const { locale, labelAddToCart = "", labelViewProduct = "" } = this;
578
+ const key = JSON.stringify([locale, labelAddToCart, labelViewProduct]);
579
+ if (this.labelSet?.key !== key) {
580
+ this.labelSet = {
581
+ key,
582
+ labels: labelsFor(locale, {
583
+ addToCart: labelAddToCart,
584
+ viewProduct: labelViewProduct,
585
+ }),
586
+ };
587
+ }
588
+ return this.labelSet.labels;
589
+ }
590
+
591
+ private get formatPrice() {
592
+ const { locale } = this;
593
+ const key = `${locale}|${this.currency ?? ""}`;
594
+ if (this.formatter?.key !== key) {
595
+ this.formatter = { key, format: priceFormatter(locale, this.currency) };
596
+ }
597
+ return this.formatter.format;
598
+ }
599
+
600
+ private productOf(story: StoryAd) {
601
+ const fetched: FetchedProduct =
602
+ this.products === "loading" ? "loading" : this.products?.get(story.ad_id);
603
+ return toCardProduct(story, this.formatPrice, this.labels, fetched);
604
+ }
605
+
606
+ // The highlighted card opens the player; another one takes the highlight.
607
+ // Hidden cards, out of sight, show only their cover.
608
+ private readonly renderSlide = (
609
+ story: StoryAd,
610
+ { key, index, offset, active, hidden, cardRef, focusRef }: Slide,
611
+ ) =>
612
+ renderCard(story, this.videoFor(key), {
613
+ label: this.labels.position(
614
+ active ? this.labels.watch : this.labels.show,
615
+ index,
616
+ this.stories.length,
617
+ ),
618
+ labels: this.labels,
619
+ withVideo: active || (this.inactiveAutoplay && !hidden),
620
+ autoplay: !this.mediaLoading,
621
+ product: this.productOf(story),
622
+ onSelect: active
623
+ ? () => this.openPlayer()
624
+ : () => this.carousel.step(offset),
625
+ // On a card without the highlight, the product moves it, as the card.
626
+ onProductSelect: active
627
+ ? () => this.openPlayer({ productOpen: true })
628
+ : undefined,
629
+ // On the highlighted card it follows the link; on another, it moves the
630
+ // highlight.
631
+ cta: toCardCta(story),
632
+ onCtaSelect: active ? undefined : () => this.carousel.step(offset),
633
+ onPress: () => this.events.click(story),
634
+ ref: cardRef,
635
+ openRef: focusRef,
636
+ });
637
+
87
638
  protected render() {
639
+ const { stories } = this;
640
+ const index = this.carousel.active;
641
+ const active = stories[index];
642
+ if (!active && !this.requesting) return nothing;
643
+
644
+ const loading = this.requesting || this.mediaLoading;
645
+
88
646
  return html`
89
- <div class="root">
90
- ${renderCard(PLACEHOLDER_STORY, this.cardVideo, {
91
- label: LABELS.watch,
92
- soundOnLabel: LABELS.soundOn,
93
- soundOffLabel: LABELS.soundOff,
94
- onSelect: () => this.openPlayer(),
95
- })}
647
+ <div
648
+ class="root"
649
+ ?data-loading=${loading}
650
+ ?data-requesting=${this.requesting}
651
+ >
652
+ ${active
653
+ ? this.carousel.render(stories, this.renderSlide, this.labels)
654
+ : nothing}
655
+ ${renderCarouselSkeleton({ done: !loading })}
96
656
  </div>
97
- ${this.player.render(PLACEHOLDER_STORY)}
657
+ ${active ? this.renderPlayer(active) : nothing}
98
658
  `;
99
659
  }
660
+
661
+ private renderPlayer(active: StoryAd) {
662
+ const { stories } = this;
663
+ const index = this.carousel.active;
664
+ const neighbors = neighborOffsets(stories.length, index).map((offset) => {
665
+ const neighbor = (index + offset + stories.length) % stories.length;
666
+ return {
667
+ offset,
668
+ story: stories[neighbor],
669
+ label: this.labels.position(this.labels.show, neighbor, stories.length),
670
+ };
671
+ });
672
+
673
+ const product = this.productOf(active);
674
+
675
+ return this.player.render(active, {
676
+ labels: this.labels,
677
+ navigation: stories.length > 1,
678
+ neighbors,
679
+ product,
680
+ cta: toCardCta(active),
681
+ productActions: this.cartActionsFor(product),
682
+ onPress: () => this.events.click(active),
683
+ });
684
+ }
685
+
686
+ private cartActionsFor(
687
+ product?: CardProduct,
688
+ ): ProductCartActions | undefined {
689
+ const sku = product?.sku;
690
+ if (!sku) return undefined;
691
+
692
+ const item = { sku, seller: product.seller };
693
+ return {
694
+ cartQuantity: this.cartQuantities.get(cartKey(item)),
695
+ onAddToCart: () => this.changeCart(item, 1),
696
+ onRemoveFromCart: () => this.changeCart(item, -1),
697
+ };
698
+ }
699
+
700
+ /**
701
+ * Adds one of `item` to the stepper's count, or removes one, and tells the
702
+ * store, which changes its cart: the element has none. When add to cart
703
+ * and the stepper swap places, the focus moves to the one now shown.
704
+ */
705
+ private changeCart(item: StoryCartItem, delta: 1 | -1) {
706
+ const key = cartKey(item);
707
+ const before = this.cartQuantities.get(key) ?? 0;
708
+ const after = Math.max(0, before + delta);
709
+ if (after === before) return;
710
+
711
+ if (after > 0) this.cartQuantities.set(key, after);
712
+ else this.cartQuantities.delete(key);
713
+ this.requestUpdate();
714
+
715
+ this.dispatchEvent(
716
+ delta > 0 ? addToCartEvent(item) : removeFromCartEvent(item),
717
+ );
718
+
719
+ let swapped: "stepper" | "add" | undefined;
720
+ if (before === 0) swapped = "stepper";
721
+ else if (after === 0) swapped = "add";
722
+ if (!swapped) return;
723
+
724
+ const action = swapped;
725
+ this.updateComplete.then(
726
+ () => this.shadowRoot && focusCartAction(this.shadowRoot, action),
727
+ );
728
+ }
100
729
  }
101
730
 
102
- // Types `document.createElement("vtex-ads-story")` and `querySelector` results
103
- // as VtexAdsStoryElement in any TypeScript project, no framework needed.
731
+ // Types `document.createElement("vtex-ads-story-carousel")` and
732
+ // `querySelector` results as VtexAdsStoryCarouselElement in any TypeScript
733
+ // project, no framework needed.
104
734
  declare global {
105
735
  interface HTMLElementTagNameMap {
106
- "vtex-ads-story": VtexAdsStoryElement;
736
+ [TAG_NAME]: VtexAdsStoryCarouselElement;
107
737
  }
108
738
  }
109
739
 
110
- export function defineVtexAdsStories() {
740
+ export function defineVtexAdsStoryCarousel() {
111
741
  if (typeof customElements === "undefined") return;
112
742
  if (customElements.get(TAG_NAME)) return;
113
743
 
114
- customElements.define(TAG_NAME, VtexAdsStoryElement);
744
+ customElements.define(TAG_NAME, VtexAdsStoryCarouselElement);
115
745
  }