@vtex/ads-stories 0.4.1 → 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 (50) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +250 -26
  3. package/dist/cdn/vtex-ads-stories.js +986 -72
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +2911 -403
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +193 -8
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +45 -5
  10. package/dist/esm/index.d.ts +193 -8
  11. package/dist/esm/index.js +2528 -121
  12. package/dist/esm/index.js.map +1 -1
  13. package/dist/esm/react.d.ts +45 -5
  14. package/package.json +18 -4
  15. package/src/cdn.ts +7 -3
  16. package/src/components/card/card.ts +64 -12
  17. package/src/components/carousel/carousel.ts +670 -0
  18. package/src/components/carousel/index.ts +15 -0
  19. package/src/components/events/events-controller.ts +212 -0
  20. package/src/components/events/index.ts +6 -0
  21. package/src/components/icons/assets/caret-left-bold.svg +1 -0
  22. package/src/components/icons/assets/caret-right-bold.svg +1 -0
  23. package/src/components/icons/assets/caret-up-bold.svg +1 -0
  24. package/src/components/icons/index.ts +6 -0
  25. package/src/components/media/index.ts +2 -1
  26. package/src/components/media/media.ts +21 -17
  27. package/src/components/media/video-controller.ts +47 -0
  28. package/src/components/player/index.ts +6 -2
  29. package/src/components/player/player.ts +797 -48
  30. package/src/components/product/cta.ts +56 -0
  31. package/src/components/product/index.ts +20 -0
  32. package/src/components/product/price.ts +86 -0
  33. package/src/components/product/product.styles.ts +369 -0
  34. package/src/components/product/product.ts +235 -0
  35. package/src/index.ts +9 -1
  36. package/src/locales/en.ts +29 -0
  37. package/src/locales/es.ts +30 -0
  38. package/src/locales/index.ts +36 -0
  39. package/src/locales/pt.ts +29 -0
  40. package/src/locales/types.ts +24 -0
  41. package/src/react.ts +49 -7
  42. package/src/story/index.ts +5 -1
  43. package/src/story/story.ts +505 -47
  44. package/src/tag-name.ts +1 -0
  45. package/src/types.ts +8 -12
  46. package/src/utils/fetch-story.ts +113 -0
  47. package/src/utils/http-url.ts +12 -0
  48. package/src/utils/hydrate-products.ts +88 -0
  49. package/src/utils/send-event.ts +71 -0
  50. package/src/utils/with-timeout.ts +43 -0
@@ -1,33 +1,179 @@
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";
4
+ import {
5
+ CarouselController,
6
+ carouselStyles,
7
+ RENDERED_SIDE,
8
+ type Slide,
9
+ } from "../components/carousel";
10
+ import { StoryEventsController, type ViewTarget } from "../components/events";
3
11
  import { VideoController } from "../components/media";
4
- import { PlayerController, playerStyles } from "../components/player";
5
- import type { StoryMedia } from "../types";
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,
23
+ playerStyles,
24
+ } from "../components/player";
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";
6
35
 
7
- export const TAG_NAME = "vtex-ads-story";
36
+ export { TAG_NAME } from "../tag-name";
8
37
 
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",
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;
50
+
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);
55
+
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"),
64
+ };
65
+
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,
13
71
  };
14
72
 
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",
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,
26
78
  };
27
79
 
28
80
  // LitElement is importable where HTMLElement doesn't exist (SSR, Node): Lit
29
81
  // falls back to a minimal shim there.
30
- export class VtexAdsStoryElement extends LitElement {
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 },
104
+ };
105
+
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
+
31
177
  static readonly styles = [
32
178
  css`
33
179
  :host {
@@ -37,23 +183,59 @@ export class VtexAdsStoryElement extends LitElement {
37
183
  }
38
184
  `,
39
185
  cardStyles,
186
+ productStyles,
187
+ carouselStyles,
40
188
  playerStyles,
41
189
  ];
42
190
 
43
- private readonly cardVideo = new VideoController(this);
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
+ });
44
220
 
45
221
  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,
222
+ onStep: (delta) => this.stepInPlayer(delta),
54
223
  onClose: () => this.closePlayer(),
55
224
  });
56
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 = [];
237
+ }
238
+
57
239
  // Lit keeps the card's DOM when the element is moved (removed and appended
58
240
  // again), but the browser pauses a removed video and doesn't autoplay it
59
241
  // again. resume() only plays a video that autoplays (not with reduced
@@ -62,15 +244,190 @@ export class VtexAdsStoryElement extends LitElement {
62
244
  // in the DOM until the next update and would play for a moment.
63
245
  connectedCallback() {
64
246
  super.connectedCallback();
65
- this.cardVideo.resume();
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
+ }
263
+ }
264
+
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
+ }
277
+
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,
303
+ });
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
+ }
66
415
  }
67
416
 
68
- private openPlayer() {
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 } = {}) {
69
426
  if (this.player.isOpen) return;
70
427
 
71
428
  // While the player is open, the card behind it stops on its cover.
72
- this.cardVideo.pause();
73
- void this.player.open();
429
+ this.activeVideo?.pause();
430
+ void this.player.open({ productOpen });
74
431
  }
75
432
 
76
433
  // The player also closes on its own when the element leaves the page,
@@ -80,36 +437,137 @@ export class VtexAdsStoryElement extends LitElement {
80
437
  if (!this.player.isOpen) return;
81
438
 
82
439
  this.player.close();
83
- this.cardVideo.resume();
84
- this.renderRoot.querySelector<HTMLElement>(".root .card-open")?.focus();
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();
85
444
  }
86
445
 
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
+ };
452
+
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
+ }
462
+
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 };
466
+
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;
480
+ }
481
+
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) };
487
+ }
488
+ return this.formatter.format;
489
+ }
490
+
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);
495
+ }
496
+
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
+
87
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
+
88
543
  return html`
89
544
  <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
- })}
545
+ ${this.carousel.render(stories, this.renderSlide, this.labels)}
96
546
  </div>
97
- ${this.player.render(PLACEHOLDER_STORY)}
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
+ })}
98
555
  `;
99
556
  }
100
557
  }
101
558
 
102
- // Types `document.createElement("vtex-ads-story")` and `querySelector` results
103
- // 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.
104
562
  declare global {
105
563
  interface HTMLElementTagNameMap {
106
- "vtex-ads-story": VtexAdsStoryElement;
564
+ [TAG_NAME]: VtexAdsStoryCarouselElement;
107
565
  }
108
566
  }
109
567
 
110
- export function defineVtexAdsStories() {
568
+ export function defineVtexAdsStoryCarousel() {
111
569
  if (typeof customElements === "undefined") return;
112
570
  if (customElements.get(TAG_NAME)) return;
113
571
 
114
- customElements.define(TAG_NAME, VtexAdsStoryElement);
572
+ customElements.define(TAG_NAME, VtexAdsStoryCarouselElement);
115
573
  }
@@ -0,0 +1 @@
1
+ export const TAG_NAME = "vtex-ads-story-carousel";
package/src/types.ts CHANGED
@@ -1,14 +1,10 @@
1
+ import type { StoryAdDetail } from "@vtex/ads-core";
2
+
3
+ /** One Story from the ad API response, as returned by `@vtex/ads-core`. */
4
+ export type StoryAd = StoryAdDetail;
5
+
1
6
  /**
2
- * One Story from the ad API response. Field names follow the API; only the
3
- * fields the component reads so far are listed.
7
+ * What the card and the player show: the cover and the video. Both optional,
8
+ * so a Story missing either still renders what it has.
4
9
  */
5
- export interface StoryAd {
6
- ad_id: string;
7
- /** Cover image shown before the video plays. */
8
- poster_url?: string;
9
- /** The 9:16 MP4 the card and the player play. */
10
- media_url?: string;
11
- }
12
-
13
- /** What the card and the player show: the cover and the video. */
14
- export type StoryMedia = Pick<StoryAd, "poster_url" | "media_url">;
10
+ export type StoryMedia = Partial<Pick<StoryAd, "poster_url" | "media_url">>;