@vtex/ads-stories 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +260 -28
  3. package/dist/cdn/vtex-ads-stories.js +1073 -20
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +4392 -315
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +198 -12
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +46 -5
  10. package/dist/esm/index.d.ts +198 -12
  11. package/dist/esm/index.js +2819 -291
  12. package/dist/esm/index.js.map +1 -1
  13. package/dist/esm/react.d.ts +46 -5
  14. package/package.json +21 -4
  15. package/src/cdn.ts +7 -3
  16. package/src/components/card/card.ts +101 -111
  17. package/src/components/card/index.ts +1 -1
  18. package/src/components/carousel/carousel.ts +670 -0
  19. package/src/components/carousel/index.ts +15 -0
  20. package/src/components/events/events-controller.ts +212 -0
  21. package/src/components/events/index.ts +6 -0
  22. package/src/components/icons/assets/caret-left-bold.svg +1 -0
  23. package/src/components/icons/assets/caret-right-bold.svg +1 -0
  24. package/src/components/icons/assets/caret-up-bold.svg +1 -0
  25. package/src/components/icons/index.ts +30 -9
  26. package/src/components/media/index.ts +3 -0
  27. package/src/components/media/media.ts +70 -0
  28. package/src/components/media/video-controller.ts +125 -0
  29. package/src/components/player/index.ts +6 -2
  30. package/src/components/player/player.ts +946 -134
  31. package/src/components/product/cta.ts +56 -0
  32. package/src/components/product/index.ts +20 -0
  33. package/src/components/product/price.ts +86 -0
  34. package/src/components/product/product.styles.ts +369 -0
  35. package/src/components/product/product.ts +235 -0
  36. package/src/index.ts +9 -1
  37. package/src/locales/en.ts +29 -0
  38. package/src/locales/es.ts +30 -0
  39. package/src/locales/index.ts +36 -0
  40. package/src/locales/pt.ts +29 -0
  41. package/src/locales/types.ts +24 -0
  42. package/src/react.ts +49 -7
  43. package/src/story/index.ts +5 -1
  44. package/src/story/story.ts +528 -93
  45. package/src/tag-name.ts +1 -0
  46. package/src/types.ts +8 -12
  47. package/src/utils/fetch-story.ts +113 -0
  48. package/src/utils/http-url.ts +12 -0
  49. package/src/utils/hydrate-products.ts +88 -0
  50. package/src/utils/send-event.ts +71 -0
  51. package/src/utils/with-timeout.ts +43 -0
@@ -1,138 +1,573 @@
1
- import { cardStyles, createCard, playVideo } from "../components/card";
1
+ import { css, html, LitElement, nothing, type PropertyValues } from "lit";
2
+ import type { Channel } from "@vtex/ads-core";
3
+ import { cardStyles, renderCard } from "../components/card";
2
4
  import {
3
- createPlayer,
5
+ CarouselController,
6
+ carouselStyles,
7
+ RENDERED_SIDE,
8
+ type Slide,
9
+ } from "../components/carousel";
10
+ import { StoryEventsController, type ViewTarget } from "../components/events";
11
+ import { VideoController } from "../components/media";
12
+ import {
13
+ DEFAULT_LOCALE,
14
+ priceFormatter,
15
+ productStyles,
16
+ toCardCta,
17
+ toCardProduct,
18
+ type FetchedProduct,
19
+ } from "../components/product";
20
+ import {
21
+ neighborOffsets,
22
+ PlayerController,
4
23
  playerStyles,
5
- playPlayer,
6
- showPlayer,
7
24
  } from "../components/player";
8
- import type { StoryMedia } from "../types";
25
+ import type { StoryAd } from "../types";
26
+ import {
27
+ hydrateStoryProducts,
28
+ intelligentSearchHydration,
29
+ type StoryHydration,
30
+ type StoryProductDetails,
31
+ } from "../utils/hydrate-products";
32
+ import { fetchStories } from "../utils/fetch-story";
33
+ import { labelsFor, type StoryLabels } from "../locales";
34
+ import { TAG_NAME } from "../tag-name";
9
35
 
10
- export const TAG_NAME = "vtex-ads-story";
36
+ export { TAG_NAME } from "../tag-name";
11
37
 
12
- // Keeps the module importable where HTMLElement doesn't exist (SSR, Node).
13
- const BaseElement: typeof HTMLElement = globalThis.HTMLElement ?? Object;
38
+ // The properties that make up the ad and product requests: a change to any of
39
+ // them fetches the Story again.
40
+ const REQUEST_PROPERTIES = [
41
+ "publisherId",
42
+ "sessionId",
43
+ "placement",
44
+ "userId",
45
+ "accountName",
46
+ "channel",
47
+ "quantity",
48
+ "hydration",
49
+ ] as const;
14
50
 
15
- const styles = `
16
- :host {
17
- display: block;
18
- font-family: var(--vtex-ads-story-font-family, inherit);
19
- color: var(--vtex-ads-story-color-text, inherit);
20
- }
21
- ${cardStyles}
22
- ${playerStyles}
23
- `;
51
+ const CHANNELS: ReadonlySet<Channel> = new Set(["site", "app"]);
52
+
53
+ const isChannel = (value: string | null): value is Channel =>
54
+ CHANNELS.has(value as Channel);
24
55
 
25
- // Temporary: rendered until the element reads Stories from the ad API.
26
- const PLACEHOLDER_STORY: StoryMedia = {
27
- poster_url: "https://dummyimage.com/1080x1920/e31c57/fff",
28
- media_url: "https://samplelib.com/mp4/sample-10s-vp9.mp4",
56
+ // Reads a boolean attribute: on only when present bare (`""`, as in HTML and
57
+ // React 19) or "true"; absent, "false" or any other value is off. React 18
58
+ // writes boolean props on custom elements as strings, so
59
+ // `inactive-autoplay={false}` arrives as inactive-autoplay="false".
60
+ const booleanConverter = {
61
+ fromAttribute: (value: string | null) =>
62
+ typeof value === "string" &&
63
+ (value === "" || value.toLowerCase() === "true"),
29
64
  };
30
65
 
31
- // Temporary: fixed texts until the store can set them by attribute.
32
- const LABELS = {
33
- watch: "Assistir vídeo",
34
- player: "Vídeo",
35
- expand: "Expandir vídeo",
36
- collapse: "Reduzir vídeo",
37
- close: "Fechar vídeo",
38
- play: "Reproduzir vídeo",
39
- pause: "Pausar vídeo",
40
- soundOn: "Ativar som",
41
- soundOff: "Desativar som",
66
+ // Reads the `channel` attribute. An unknown value leaves the property
67
+ // undefined, so it is not sent.
68
+ const channelConverter = {
69
+ fromAttribute: (value: string | null) =>
70
+ isChannel(value) ? value : undefined,
42
71
  };
43
72
 
44
- export class VtexAdsStoryElement extends BaseElement {
45
- private player: HTMLDialogElement | null = null;
73
+ // Reads the `hydration` attribute: only "none" means something there (no
74
+ // product request). A strategy is set as a property.
75
+ const hydrationConverter = {
76
+ fromAttribute: (value: string | null) =>
77
+ value === "none" ? ("none" as const) : undefined,
78
+ };
46
79
 
47
- private readonly onKeyDown = (event: KeyboardEvent) => {
48
- if (event.key === "Escape") this.closePlayer();
80
+ // LitElement is importable where HTMLElement doesn't exist (SSR, Node): Lit
81
+ // falls back to a minimal shim there.
82
+ export class VtexAdsStoryCarouselElement extends LitElement {
83
+ static readonly properties = {
84
+ publisherId: { attribute: "publisher-id" },
85
+ sessionId: { attribute: "session-id" },
86
+ placement: {},
87
+ userId: { attribute: "user-id" },
88
+ accountName: { attribute: "account-name" },
89
+ channel: { converter: channelConverter },
90
+ timeout: { type: Number },
91
+ quantity: { type: Number },
92
+ currency: {},
93
+ labelAddToCart: { attribute: "label-add-to-cart" },
94
+ labelViewProduct: { attribute: "label-view-product" },
95
+ hydration: { converter: hydrationConverter },
96
+ hydrationTimeout: { type: Number, attribute: "hydration-timeout" },
97
+ inactiveAutoplay: {
98
+ type: Boolean,
99
+ attribute: "inactive-autoplay",
100
+ converter: booleanConverter,
101
+ },
102
+ stories: { state: true },
103
+ products: { state: true },
49
104
  };
50
105
 
51
- private render() {
52
- const container = this.shadowRoot?.querySelector(".root");
53
- if (!container) return;
54
-
55
- container.replaceChildren(
56
- createCard(PLACEHOLDER_STORY, {
57
- label: LABELS.watch,
58
- soundOnLabel: LABELS.soundOn,
59
- soundOffLabel: LABELS.soundOff,
60
- onSelect: () => this.openPlayer(),
61
- }),
62
- );
106
+ /** Required. The publisher the ads are requested for. */
107
+ declare publisherId?: string;
108
+ /** Required. The store's session, also used to deduplicate events. */
109
+ declare sessionId?: string;
110
+ /** Required. The Story placement configured for the publisher. */
111
+ declare placement?: string;
112
+ declare userId?: string;
113
+ declare accountName?: string;
114
+ /** `site` or `app`. Any other attribute value is ignored. */
115
+ declare channel?: Channel;
116
+ /**
117
+ * Time limit for the ad request, in milliseconds (default 2000). Without a
118
+ * Story by then, the element renders nothing. A change applies to the next
119
+ * request; it doesn't request again.
120
+ */
121
+ declare timeout?: number;
122
+ /**
123
+ * How many Stories to ask for: the carousel positions (default 8). Missing,
124
+ * below 1 or not a number: the default.
125
+ */
126
+ declare quantity?: number;
127
+ /**
128
+ * Currency of the prices, as an ISO 4217 code ("BRL", "ARS"). Missing or
129
+ * invalid: BRL.
130
+ */
131
+ declare currency?: string;
132
+ /**
133
+ * The add to cart button's text. Missing or blank: the default in the
134
+ * element's language ("Adicionar ao carrinho").
135
+ */
136
+ declare labelAddToCart?: string;
137
+ /**
138
+ * The view product button's text. Missing or blank: the default in the
139
+ * element's language ("Ver produto").
140
+ */
141
+ declare labelViewProduct?: string;
142
+ /**
143
+ * Where the products' details (for now, their prices) come from. A
144
+ * strategy (fetcher, matcher and price reader) is set as a property; the
145
+ * attribute takes only "none", for no product request. Missing:
146
+ * Intelligent Search when `account-name` is set, no product request
147
+ * otherwise.
148
+ */
149
+ declare hydration?: StoryHydration | "none";
150
+ /**
151
+ * Time limit for the product request, in milliseconds (default 5000).
152
+ * Without the prices by then, the cards show the ad server's.
153
+ */
154
+ declare hydrationTimeout?: number;
155
+ /**
156
+ * With more than one Story, whether the cards without the highlight also
157
+ * play their video, muted. Off by default: they show only their cover, and
158
+ * only the highlighted card plays.
159
+ */
160
+ declare inactiveAutoplay: boolean;
161
+
162
+ /** The Stories shown: none while loading, on error or with none. */
163
+ declare private stories: StoryAd[];
164
+
165
+ /**
166
+ * The fetched products, by Story `ad_id`, or `"loading"` while the product
167
+ * request runs. Undefined without a product request.
168
+ */
169
+ declare private products?: Map<string, StoryProductDetails> | "loading";
170
+
171
+ /**
172
+ * Cancels the request in progress. Kept, already aborted, when leaving the
173
+ * page cancelled it, so connecting again requests once more.
174
+ */
175
+ private request?: AbortController;
176
+
177
+ static readonly styles = [
178
+ css`
179
+ :host {
180
+ display: block;
181
+ font-family: var(--vtex-ads-story-font-family, inherit);
182
+ color: var(--vtex-ads-story-color-text, inherit);
183
+ }
184
+ `,
185
+ cardStyles,
186
+ productStyles,
187
+ carouselStyles,
188
+ playerStyles,
189
+ ];
190
+
191
+ /**
192
+ * One per rendered card, by its key (see Slide): a Story can show in more
193
+ * than one card, each with its own video.
194
+ */
195
+ private readonly cardVideos = new Map<number, VideoController>();
196
+
197
+ /** The sound was on when the highlight moved: the new card turns it on. */
198
+ private soundPending = false;
199
+
200
+ /**
201
+ * What to do once the next render is on screen, when the new highlighted
202
+ * card's video exists (see leaveHighlight and onLayoutChange). A step
203
+ * taken before then replaces it.
204
+ */
205
+ private afterRender?: () => void;
206
+
207
+ private readonly carousel = new CarouselController(this, {
208
+ onStep: (from, to) => this.leaveHighlight(from, to),
209
+ // Every card is new: so are their videos. Behind an open player, the
210
+ // new highlighted card stays on its cover, as after a step.
211
+ onLayoutChange: () => {
212
+ this.cardVideos.clear();
213
+ if (this.player.isOpen) {
214
+ this.afterRender = () => this.activeVideo?.pause();
215
+ }
216
+ },
217
+ // The player shows the highlighted Story: the highlight stays on it.
218
+ locked: () => this.player.isOpen,
219
+ });
220
+
221
+ private readonly player = new PlayerController(this, {
222
+ onStep: (delta) => this.stepInPlayer(delta),
223
+ onClose: () => this.closePlayer(),
224
+ });
225
+
226
+ // Added after the carousel and the player: its hostUpdated reads what
227
+ // they rendered.
228
+ private readonly events = new StoryEventsController(this, {
229
+ identity: () => ({ sessionId: this.sessionId, userId: this.userId }),
230
+ viewTargets: () => this.viewTargets(),
231
+ });
232
+
233
+ constructor() {
234
+ super();
235
+ this.inactiveAutoplay = false;
236
+ this.stories = [];
63
237
  }
64
238
 
65
- private cardVideo() {
66
- return this.shadowRoot?.querySelector<HTMLVideoElement>(
67
- ".root .card video",
68
- );
239
+ // Lit keeps the card's DOM when the element is moved (removed and appended
240
+ // again), but the browser pauses a removed video and doesn't autoplay it
241
+ // again. resume() only plays a video that autoplays (not with reduced
242
+ // motion), and does nothing on the first connection, before the render.
243
+ // Not in VideoController.hostConnected: there, the player's video is still
244
+ // in the DOM until the next update and would play for a moment.
245
+ connectedCallback() {
246
+ super.connectedCallback();
247
+ for (const video of this.cardVideos.values()) video.resume();
248
+
249
+ // Moved while its request was pending: that request was cancelled.
250
+ if (this.request?.signal.aborted) void this.loadStory();
251
+ }
252
+
253
+ // A request still pending when the element leaves the page is cancelled.
254
+ disconnectedCallback() {
255
+ super.disconnectedCallback();
256
+ this.request?.abort();
257
+ }
258
+
259
+ protected willUpdate(changed: PropertyValues<this>) {
260
+ if (REQUEST_PROPERTIES.some((name) => changed.has(name))) {
261
+ void this.loadStory();
262
+ }
69
263
  }
70
264
 
71
- private openPlayer() {
72
- if (this.player || !this.shadowRoot) return;
265
+ protected updated() {
266
+ const afterRender = this.afterRender;
267
+ this.afterRender = undefined;
268
+ afterRender?.();
269
+ }
270
+
271
+ // The strategy for the products' details, if any (see `hydration`).
272
+ private get activeHydration(): StoryHydration | undefined {
273
+ if (this.hydration === "none") return undefined;
274
+ if (this.hydration) return this.hydration;
275
+ return this.accountName ? intelligentSearchHydration : undefined;
276
+ }
73
277
 
74
- this.player = createPlayer(PLACEHOLDER_STORY, {
75
- label: LABELS.player,
76
- expandLabel: LABELS.expand,
77
- collapseLabel: LABELS.collapse,
78
- closeLabel: LABELS.close,
79
- playLabel: LABELS.play,
80
- pauseLabel: LABELS.pause,
81
- soundOnLabel: LABELS.soundOn,
82
- soundOffLabel: LABELS.soundOff,
83
- onClose: () => this.closePlayer(),
278
+ /**
279
+ * Requests the Story and shows it, then hydrates its products. Until the
280
+ * Story arrives, and when there is none (see fetchStories), the element
281
+ * renders nothing.
282
+ */
283
+ private async loadStory() {
284
+ // A request still pending no longer matches the attributes.
285
+ this.request?.abort();
286
+ const request = new AbortController();
287
+ this.request = request;
288
+
289
+ // The Stories shown no longer match the request either.
290
+ this.player.close();
291
+ this.showStories([]);
292
+
293
+ // Off the page (an attribute changed just before the element was
294
+ // removed): keep the cancelled request, so connecting again requests.
295
+ if (!this.isConnected) {
296
+ request.abort();
297
+ return;
298
+ }
299
+
300
+ const stories = await fetchStories(this, {
301
+ signal: request.signal,
302
+ timeout: this.timeout,
84
303
  });
85
- this.shadowRoot.append(this.player);
86
- showPlayer(this.player);
304
+
305
+ // Cancelled meanwhile, by a newer request or by leaving the page: this
306
+ // response is not shown.
307
+ if (request.signal.aborted) return;
308
+
309
+ const hydration = this.activeHydration;
310
+ if (!hydration || !stories.some((story) => story.product)) {
311
+ this.request = undefined;
312
+ this.showStories(stories);
313
+ return;
314
+ }
315
+
316
+ // The carousel shows now; the products' details replace their
317
+ // placeholders later.
318
+ this.showStories(stories, "loading");
319
+ const products = await hydrateStoryProducts(
320
+ this.placement ?? "",
321
+ stories,
322
+ hydration,
323
+ {
324
+ accountName: this.accountName ?? "",
325
+ publisherId: this.publisherId ?? "",
326
+ sessionId: this.sessionId ?? "",
327
+ userId: this.userId,
328
+ channel: this.channel,
329
+ },
330
+ { signal: request.signal, timeout: this.hydrationTimeout },
331
+ );
332
+
333
+ if (request.signal.aborted) return;
334
+ this.request = undefined;
335
+ this.products = products;
336
+ }
337
+
338
+ // Each card's video starts fresh: a failed load of an old one doesn't hide
339
+ // it.
340
+ private showStories(stories: StoryAd[], products?: "loading") {
341
+ this.products = products;
342
+ this.cardVideos.clear();
343
+ this.soundPending = false;
344
+ this.afterRender = undefined;
345
+ this.carousel.reset(stories.length);
346
+ this.stories = stories;
347
+ this.events.impress(stories);
348
+ }
349
+
350
+ /**
351
+ * Where each Story is being watched: the cards on screen (not the hidden
352
+ * ones kept for the slide in) and the open player's video, while their
353
+ * video plays. A card showing only its cover doesn't count. Behind the
354
+ * expanded player, a modal over the page, the cards are covered.
355
+ */
356
+ private *viewTargets(): Generator<ViewTarget> {
357
+ const { stories } = this;
358
+
359
+ if (!this.player.isExpanded) {
360
+ for (const [card, { key, index }] of this.carousel.visibleCards()) {
361
+ const story = stories[index];
362
+ if (story && this.cardVideos.get(key)?.playing) yield [card, story];
363
+ }
364
+ }
365
+
366
+ const stageCard = this.player.stageCard;
367
+ const active = stories[this.carousel.active];
368
+ if (stageCard && active && this.player.video.playing) {
369
+ yield [stageCard, active];
370
+ }
371
+ }
372
+
373
+ private videoFor(key: number) {
374
+ let video = this.cardVideos.get(key);
375
+ if (!video) {
376
+ video = new VideoController(this);
377
+ this.cardVideos.set(key, video);
378
+ }
379
+ return video;
380
+ }
381
+
382
+ private get activeVideo(): VideoController | undefined {
383
+ return this.cardVideos.get(this.carousel.activeKey);
384
+ }
385
+
386
+ // The card losing the highlight goes quiet: muted if it keeps playing, or
387
+ // back to its cover. Its next video then starts fresh. If its sound was
388
+ // on, the sound moves to the new highlighted card, once its video renders.
389
+ // With the player open (it stepped), the new card stays on its cover
390
+ // behind it instead. Cards no longer rendered (the rolling layout drops
391
+ // them as it moves) leave with their videos.
392
+ private leaveHighlight(from: number, to: number) {
393
+ const video = this.cardVideos.get(from);
394
+ // Still pending: moved again before the last step rendered.
395
+ this.soundPending ||= video !== undefined && !video.muted;
396
+ if (this.inactiveAutoplay) video?.mute();
397
+ else video?.reset();
398
+
399
+ // The step requested its render before calling this: updated() runs the
400
+ // action once the new card is on screen.
401
+ if (this.player.isOpen) {
402
+ this.soundPending = false;
403
+ // Paused before it starts, its autoplay doesn't start either.
404
+ this.afterRender = () => this.videoFor(to).pause();
405
+ } else if (this.soundPending) {
406
+ this.afterRender = () => {
407
+ this.soundPending = false;
408
+ this.videoFor(to).playWithSound();
409
+ };
410
+ }
411
+
412
+ for (const key of this.cardVideos.keys()) {
413
+ if (Math.abs(key - to) > RENDERED_SIDE) this.cardVideos.delete(key);
414
+ }
415
+ }
416
+
417
+ // The player's previous and next buttons: the highlight moves with the
418
+ // Story the player shows.
419
+ private stepInPlayer(delta: number) {
420
+ this.carousel.step(delta, { evenIfLocked: true });
421
+ void this.player.showNext(delta);
422
+ }
423
+
424
+ // From the card's product, the player opens with the product panel open.
425
+ private openPlayer({ productOpen = false } = {}) {
426
+ if (this.player.isOpen) return;
427
+
87
428
  // While the player is open, the card behind it stops on its cover.
88
- this.cardVideo()?.pause();
89
- playPlayer(this.player);
90
- document.addEventListener("keydown", this.onKeyDown);
429
+ this.activeVideo?.pause();
430
+ void this.player.open({ productOpen });
431
+ }
432
+
433
+ // The player also closes on its own when the element leaves the page,
434
+ // without this: there is no card to give focus back to or to resume playing
435
+ // (it would play out of sight).
436
+ private closePlayer() {
437
+ if (!this.player.isOpen) return;
91
438
 
92
- this.player.querySelector<HTMLElement>(".player-close")?.focus();
439
+ this.player.close();
440
+ // The highlighted card, and with inactive-autoplay the others, which may
441
+ // have been highlighted and paused while the player stepped.
442
+ for (const video of this.cardVideos.values()) video.resume();
443
+ this.carousel.focusActive();
93
444
  }
94
445
 
95
- // `removed`: the element is leaving the page, so there is no card to give
96
- // focus back to or to resume playing (it would play out of sight).
97
- private closePlayer({ removed = false } = {}) {
98
- if (!this.player) return;
446
+ // The formatter for the current language and currency, made again only
447
+ // when either changes.
448
+ private formatter?: {
449
+ key: string;
450
+ format: (amount: number) => string;
451
+ };
99
452
 
100
- document.removeEventListener("keydown", this.onKeyDown);
101
- this.player.remove();
102
- this.player = null;
103
- if (removed) return;
453
+ // Prices and texts follow the language of the closest element with a
454
+ // `lang`, the element itself included, so a store can set one for the
455
+ // widget alone. An empty `lang` (unknown) is skipped; none, or an unknown
456
+ // one, falls back to pt-BR.
457
+ private get locale() {
458
+ return (
459
+ this.closest<HTMLElement>('[lang]:not([lang=""])')?.lang ?? DEFAULT_LOCALE
460
+ );
461
+ }
104
462
 
105
- const video = this.cardVideo();
106
- if (video?.autoplay) playVideo(video);
463
+ // The texts for the current language and label attributes, made again
464
+ // only when any of them changes.
465
+ private labelSet?: { key: string; labels: StoryLabels };
107
466
 
108
- this.shadowRoot?.querySelector<HTMLElement>(".root .card-open")?.focus();
467
+ private get labels() {
468
+ const { locale, labelAddToCart = "", labelViewProduct = "" } = this;
469
+ const key = JSON.stringify([locale, labelAddToCart, labelViewProduct]);
470
+ if (this.labelSet?.key !== key) {
471
+ this.labelSet = {
472
+ key,
473
+ labels: labelsFor(locale, {
474
+ addToCart: labelAddToCart,
475
+ viewProduct: labelViewProduct,
476
+ }),
477
+ };
478
+ }
479
+ return this.labelSet.labels;
109
480
  }
110
481
 
111
- connectedCallback() {
112
- if (!this.shadowRoot) {
113
- const root = this.attachShadow({ mode: "open" });
114
- root.innerHTML = `<style>${styles}</style><div class="root"></div>`;
482
+ private get formatPrice() {
483
+ const { locale } = this;
484
+ const key = `${locale}|${this.currency ?? ""}`;
485
+ if (this.formatter?.key !== key) {
486
+ this.formatter = { key, format: priceFormatter(locale, this.currency) };
115
487
  }
488
+ return this.formatter.format;
489
+ }
116
490
 
117
- this.render();
491
+ private productOf(story: StoryAd) {
492
+ const fetched: FetchedProduct =
493
+ this.products === "loading" ? "loading" : this.products?.get(story.ad_id);
494
+ return toCardProduct(story, this.formatPrice, this.labels, fetched);
118
495
  }
119
496
 
120
- disconnectedCallback() {
121
- this.closePlayer({ removed: true });
497
+ // The highlighted card opens the player; another one takes the highlight.
498
+ // Hidden cards, out of sight, show only their cover.
499
+ private readonly renderSlide = (
500
+ story: StoryAd,
501
+ { key, index, offset, active, hidden, cardRef, focusRef }: Slide,
502
+ ) =>
503
+ renderCard(story, this.videoFor(key), {
504
+ label: this.labels.position(
505
+ active ? this.labels.watch : this.labels.show,
506
+ index,
507
+ this.stories.length,
508
+ ),
509
+ labels: this.labels,
510
+ withVideo: active || (this.inactiveAutoplay && !hidden),
511
+ product: this.productOf(story),
512
+ onSelect: active
513
+ ? () => this.openPlayer()
514
+ : () => this.carousel.step(offset),
515
+ // On a card without the highlight, the product moves it, as the card.
516
+ onProductSelect: active
517
+ ? () => this.openPlayer({ productOpen: true })
518
+ : undefined,
519
+ // On the highlighted card it follows the link; on another, it moves the
520
+ // highlight.
521
+ cta: toCardCta(story),
522
+ onCtaSelect: active ? undefined : () => this.carousel.step(offset),
523
+ onPress: () => this.events.click(story),
524
+ ref: cardRef,
525
+ openRef: focusRef,
526
+ });
527
+
528
+ protected render() {
529
+ const { stories } = this;
530
+ const index = this.carousel.active;
531
+ const active = stories[index];
532
+ if (!active) return nothing;
533
+
534
+ const neighbors = neighborOffsets(stories.length, index).map((offset) => {
535
+ const neighbor = (index + offset + stories.length) % stories.length;
536
+ return {
537
+ offset,
538
+ story: stories[neighbor],
539
+ label: this.labels.position(this.labels.show, neighbor, stories.length),
540
+ };
541
+ });
542
+
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
+ `;
122
556
  }
123
557
  }
124
558
 
125
- // Types `document.createElement("vtex-ads-story")` and `querySelector` results
126
- // as VtexAdsStoryElement in any TypeScript project, no framework needed.
559
+ // Types `document.createElement("vtex-ads-story-carousel")` and
560
+ // `querySelector` results as VtexAdsStoryCarouselElement in any TypeScript
561
+ // project, no framework needed.
127
562
  declare global {
128
563
  interface HTMLElementTagNameMap {
129
- "vtex-ads-story": VtexAdsStoryElement;
564
+ [TAG_NAME]: VtexAdsStoryCarouselElement;
130
565
  }
131
566
  }
132
567
 
133
- export function defineVtexAdsStories() {
568
+ export function defineVtexAdsStoryCarousel() {
134
569
  if (typeof customElements === "undefined") return;
135
570
  if (customElements.get(TAG_NAME)) return;
136
571
 
137
- customElements.define(TAG_NAME, VtexAdsStoryElement);
572
+ customElements.define(TAG_NAME, VtexAdsStoryCarouselElement);
138
573
  }
@@ -0,0 +1 @@
1
+ export const TAG_NAME = "vtex-ads-story-carousel";