@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
@@ -0,0 +1,212 @@
1
+ import type { ReactiveController, ReactiveControllerHost } from "lit";
2
+ import type { StoryAd } from "../../types";
3
+ import { sendEvent, type EventIdentity } from "../../utils/send-event";
4
+
5
+ export const VIEW_THRESHOLD = 0.5;
6
+ export const VIEW_DURATION_MS = 2000;
7
+
8
+ type EventKind = "impression" | "view" | "click";
9
+
10
+ const URL_FIELD = {
11
+ impression: "impression_url",
12
+ view: "view_url",
13
+ click: "click_url",
14
+ } as const satisfies Record<EventKind, keyof StoryAd>;
15
+
16
+ /** An element that shows a Story, watched for the view. */
17
+ export type ViewTarget = readonly [element: Element, story: StoryAd];
18
+
19
+ export interface StoryEventsOptions {
20
+ /**
21
+ * The session and user the events are for, read when each one is sent.
22
+ * Without a session, nothing is sent.
23
+ */
24
+ identity: () => Partial<EventIdentity>;
25
+ /**
26
+ * The elements on which a Story can be seen right now, read after every
27
+ * render of the host. An element left out stops counting toward its view.
28
+ */
29
+ viewTargets: () => Iterable<ViewTarget>;
30
+ }
31
+
32
+ interface Watched {
33
+ story: StoryAd;
34
+ /** Last reported by the observer: at least VIEW_THRESHOLD on screen. */
35
+ visible: boolean;
36
+ timer?: ReturnType<typeof setTimeout>;
37
+ }
38
+
39
+ /**
40
+ * Sends a Story's impression, view and click URLs, each at most once per
41
+ * Story and session (the ad API's `session_id`):
42
+ *
43
+ * - impression: when the Story is rendered in the carousel (impress());
44
+ * - view: when one of its elements (see `viewTargets`) has stayed at least
45
+ * 50% on screen for 2 continuous seconds, with the page visible;
46
+ * - click: on the first touch on the Story (click()).
47
+ *
48
+ * Without IntersectionObserver, no view is sent. Leaving the page stops
49
+ * the views counting; nothing sent is sent again on return.
50
+ */
51
+ export class StoryEventsController implements ReactiveController {
52
+ private readonly sent: Record<EventKind, Set<string>> = {
53
+ impression: new Set(),
54
+ view: new Set(),
55
+ click: new Set(),
56
+ };
57
+
58
+ private pendingImpressions: readonly StoryAd[] = [];
59
+
60
+ private observer?: IntersectionObserver;
61
+ private readonly watched = new Map<Element, Watched>();
62
+
63
+ constructor(
64
+ private readonly host: ReactiveControllerHost,
65
+ private readonly options: StoryEventsOptions,
66
+ ) {
67
+ host.addController(this);
68
+ }
69
+
70
+ hostConnected() {
71
+ if (typeof IntersectionObserver === "function") {
72
+ this.observer = new IntersectionObserver(this.onIntersect, {
73
+ threshold: VIEW_THRESHOLD,
74
+ });
75
+ }
76
+ globalThis.document?.addEventListener(
77
+ "visibilitychange",
78
+ this.onVisibilityChange,
79
+ );
80
+ // Moved on the page: the cards rendered before are still there, but lit
81
+ // hands their refs back only after the controllers connect.
82
+ this.host.updateComplete.then(() => this.syncViewTargets());
83
+ }
84
+
85
+ hostDisconnected() {
86
+ globalThis.document?.removeEventListener(
87
+ "visibilitychange",
88
+ this.onVisibilityChange,
89
+ );
90
+ this.observer?.disconnect();
91
+ this.observer = undefined;
92
+ for (const watched of this.watched.values()) clearTimeout(watched.timer);
93
+ this.watched.clear();
94
+ // Stories that never rendered were never seen.
95
+ this.pendingImpressions = [];
96
+ }
97
+
98
+ hostUpdated() {
99
+ const stories = this.pendingImpressions;
100
+ if (stories.length && this.options.identity().sessionId) {
101
+ this.pendingImpressions = [];
102
+ for (const story of stories) this.send("impression", story);
103
+ }
104
+
105
+ this.syncViewTargets();
106
+ }
107
+
108
+ /**
109
+ * The Stories the host renders next: their impressions go out once that
110
+ * render is done, or, without a session yet, after the first render that
111
+ * has one. Replaces Stories passed before and not sent yet.
112
+ */
113
+ impress(stories: readonly StoryAd[]) {
114
+ this.pendingImpressions = stories;
115
+ }
116
+
117
+ /** A touch on the Story: its click goes out, the first time only. */
118
+ click(story: StoryAd) {
119
+ this.send("click", story);
120
+ }
121
+
122
+ private key(sessionId: string, story: StoryAd) {
123
+ return `${sessionId}|${story.ad_id}`;
124
+ }
125
+
126
+ private wasSent(kind: EventKind, story: StoryAd) {
127
+ const { sessionId } = this.options.identity();
128
+ return !!sessionId && this.sent[kind].has(this.key(sessionId, story));
129
+ }
130
+
131
+ private send(kind: EventKind, story: StoryAd) {
132
+ const { sessionId, userId } = this.options.identity();
133
+ if (!sessionId || this.wasSent(kind, story)) return;
134
+
135
+ const success = sendEvent(story[URL_FIELD[kind]], { sessionId, userId });
136
+ if (success) {
137
+ this.sent[kind].add(this.key(sessionId, story));
138
+ }
139
+ }
140
+
141
+ // Watches the elements the host shows now, and stops watching the others,
142
+ // dropping the time they had on screen.
143
+ private syncViewTargets() {
144
+ const { observer } = this;
145
+ if (!observer) return;
146
+
147
+ const current = new Map<Element, StoryAd>();
148
+ for (const [element, story] of this.options.viewTargets()) {
149
+ if (!this.wasSent("view", story)) current.set(element, story);
150
+ }
151
+
152
+ for (const [element, watched] of this.watched) {
153
+ if (current.get(element) !== watched.story) {
154
+ this.unwatch(element, watched);
155
+ }
156
+ }
157
+
158
+ for (const [element, story] of current) {
159
+ if (this.watched.has(element)) continue;
160
+ this.watched.set(element, { story, visible: false });
161
+ observer.observe(element);
162
+ }
163
+ }
164
+
165
+ private readonly onIntersect = (entries: IntersectionObserverEntry[]) => {
166
+ for (const entry of entries) {
167
+ const watched = this.watched.get(entry.target);
168
+ if (!watched) continue;
169
+
170
+ watched.visible =
171
+ entry.isIntersecting && entry.intersectionRatio >= VIEW_THRESHOLD;
172
+ if (watched.visible) this.startTimer(watched);
173
+ else this.stopTimer(watched);
174
+ }
175
+ };
176
+
177
+ // A hidden page (another tab, minimized) breaks the 2 seconds: they start
178
+ // over when it shows again.
179
+ private readonly onVisibilityChange = () => {
180
+ for (const watched of this.watched.values()) {
181
+ if (document.hidden) this.stopTimer(watched);
182
+ else if (watched.visible) this.startTimer(watched);
183
+ }
184
+ };
185
+
186
+ private startTimer(watched: Watched) {
187
+ if (watched.timer || globalThis.document?.hidden) return;
188
+ watched.timer = setTimeout(() => {
189
+ watched.timer = undefined;
190
+ this.send("view", watched.story);
191
+ // Its other elements no longer need watching.
192
+ if (this.wasSent("view", watched.story)) this.unwatchStory(watched.story);
193
+ }, VIEW_DURATION_MS);
194
+ }
195
+
196
+ private stopTimer(watched: Watched) {
197
+ clearTimeout(watched.timer);
198
+ watched.timer = undefined;
199
+ }
200
+
201
+ private unwatch(element: Element, watched: Watched) {
202
+ this.stopTimer(watched);
203
+ this.observer?.unobserve(element);
204
+ this.watched.delete(element);
205
+ }
206
+
207
+ private unwatchStory(story: StoryAd) {
208
+ for (const [element, watched] of this.watched) {
209
+ if (watched.story.ad_id === story.ad_id) this.unwatch(element, watched);
210
+ }
211
+ }
212
+ }
@@ -0,0 +1,6 @@
1
+ export {
2
+ StoryEventsController,
3
+ VIEW_DURATION_MS,
4
+ VIEW_THRESHOLD,
5
+ } from "./events-controller";
6
+ export type { StoryEventsOptions, ViewTarget } from "./events-controller";
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M168.49,199.51a12,12,0,0,1-17,17l-80-80a12,12,0,0,1,0-17l80-80a12,12,0,0,1,17,17L97,128Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z"/></svg>
@@ -9,7 +9,10 @@ import {
9
9
  // SVG files as downloaded from Phosphor: regular weight, or the weight in the
10
10
  // file name. They are bundled as text: `?raw` is handled by Vite in dev and
11
11
  // tests, and by the raw plugin in tsup.config.ts.
12
+ import previous from "./assets/caret-left-bold.svg?raw";
13
+ import next from "./assets/caret-right-bold.svg?raw";
12
14
  import close from "./assets/close.svg?raw";
15
+ import caretUp from "./assets/caret-up-bold.svg?raw";
13
16
  import collapse from "./assets/collapse.svg?raw";
14
17
  import expand from "./assets/expand.svg?raw";
15
18
  import pause from "./assets/pause-fill.svg?raw";
@@ -18,11 +21,14 @@ import soundOff from "./assets/speaker-x-fill.svg?raw";
18
21
  import soundOn from "./assets/speaker-high-fill.svg?raw";
19
22
 
20
23
  export const icons = {
24
+ caretUp,
21
25
  close,
22
26
  collapse,
23
27
  expand,
28
+ next,
24
29
  pause,
25
30
  play,
31
+ previous,
26
32
  soundOff,
27
33
  soundOn,
28
34
  };
@@ -1,2 +1,3 @@
1
- export { hasVideo, httpUrl, renderMedia } from "./media";
1
+ export { hasVideo, prefersReducedMotion, renderMedia } from "./media";
2
+ export type { MediaOptions } from "./media";
2
3
  export { playVideo, VideoController } from "./video-controller";
@@ -1,21 +1,10 @@
1
1
  import { html, nothing } from "lit";
2
2
  import { ref } from "lit/directives/ref.js";
3
3
  import type { StoryMedia } from "../../types";
4
+ import { httpUrl } from "../../utils/http-url";
4
5
  import type { VideoController } from "./video-controller";
5
6
 
6
- // Only absolute http(s) URLs reach the DOM. Relative and protocol-relative
7
- // ones ("/a.jpg", "//host/a.jpg") don't parse without a base, so they're out.
8
- export function httpUrl(value: string | undefined) {
9
- if (!value) return null;
10
- try {
11
- const { protocol } = new URL(value);
12
- return protocol === "https:" || protocol === "http:" ? value : null;
13
- } catch {
14
- return null;
15
- }
16
- }
17
-
18
- function prefersReducedMotion() {
7
+ export function prefersReducedMotion() {
19
8
  return (
20
9
  globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false
21
10
  );
@@ -26,13 +15,27 @@ export function hasVideo(story: StoryMedia, video: VideoController) {
26
15
  return !video.failed && httpUrl(story.media_url) !== null;
27
16
  }
28
17
 
18
+ export interface MediaOptions {
19
+ /** Whether the video shows over the cover (default true). */
20
+ withVideo?: boolean;
21
+ /** Whether the video loops (default true). */
22
+ loop?: boolean;
23
+ /** Called when a video that doesn't loop reaches its end. */
24
+ onEnded?: () => void;
25
+ }
26
+
29
27
  /**
30
28
  * The Story cover and, with a media_url, the video looping muted over it. If
31
- * the video can't load, it is removed and the cover underneath stays.
29
+ * the video can't load, it is removed and the cover underneath stays. With
30
+ * withVideo false, only the cover.
32
31
  */
33
- export function renderMedia(story: StoryMedia, video: VideoController) {
32
+ export function renderMedia(
33
+ story: StoryMedia,
34
+ video: VideoController,
35
+ { withVideo = true, loop = true, onEnded }: MediaOptions = {},
36
+ ) {
34
37
  const posterUrl = httpUrl(story.poster_url);
35
- const mediaUrl = httpUrl(story.media_url);
38
+ const mediaUrl = withVideo ? httpUrl(story.media_url) : null;
36
39
 
37
40
  // Muted and inline is what browsers, iOS included, allow to autoplay. The
38
41
  // muted attribute and property are both set, since browsers differ on
@@ -48,7 +51,7 @@ export function renderMedia(story: StoryMedia, video: VideoController) {
48
51
  class="video"
49
52
  muted
50
53
  playsinline
51
- loop
54
+ ?loop=${loop}
52
55
  preload="metadata"
53
56
  .muted=${true}
54
57
  ?autoplay=${!prefersReducedMotion()}
@@ -59,6 +62,7 @@ export function renderMedia(story: StoryMedia, video: VideoController) {
59
62
  @pause=${video.sync}
60
63
  @volumechange=${video.sync}
61
64
  @error=${video.fail}
65
+ @ended=${onEnded}
62
66
  ></video>
63
67
  `
64
68
  : nothing}
@@ -27,6 +27,12 @@ export class VideoController {
27
27
 
28
28
  constructor(private readonly host: ReactiveControllerHost) {}
29
29
 
30
+ /** The rendered <video> is on the page and playing. */
31
+ get playing() {
32
+ const video = this.ref.value;
33
+ return !!video && video.isConnected && !video.paused;
34
+ }
35
+
30
36
  /** For a new <video>, such as each time the player opens. */
31
37
  reset() {
32
38
  this.paused = true;
@@ -56,6 +62,47 @@ export class VideoController {
56
62
  else video.pause();
57
63
  }
58
64
 
65
+ mute() {
66
+ const video = this.ref.value;
67
+ if (video) video.muted = true;
68
+ }
69
+
70
+ /**
71
+ * Plays from the start, with the sound on if `withSound`. A new src starts
72
+ * there anyway; the same src (two Stories with one video) would otherwise
73
+ * go on where it was.
74
+ */
75
+ restart({ withSound = false } = {}) {
76
+ const video = this.ref.value;
77
+ if (!video) return;
78
+
79
+ video.currentTime = 0;
80
+ if (withSound) this.playWithSound();
81
+ else playVideo(video);
82
+ }
83
+
84
+ /**
85
+ * Plays with the sound on. A browser that blocks playing with sound (for
86
+ * example, without a recent tap) gets it muted instead: the video keeps
87
+ * playing, and the sound button offers to turn it on. Not if the video was
88
+ * replaced or removed meanwhile (the request then fails for that reason):
89
+ * it would play out of sight.
90
+ */
91
+ playWithSound() {
92
+ const video = this.ref.value;
93
+ if (!video) return;
94
+
95
+ video.muted = false;
96
+ video.play()?.catch((error: unknown) => {
97
+ const blocked =
98
+ error instanceof DOMException && error.name === "NotAllowedError";
99
+ if (!blocked || this.ref.value !== video || !video.isConnected) return;
100
+
101
+ video.muted = true;
102
+ playVideo(video);
103
+ });
104
+ }
105
+
59
106
  toggleMuted() {
60
107
  const video = this.ref.value;
61
108
  if (video) video.muted = !video.muted;
@@ -1,2 +1,6 @@
1
- export { PlayerController, playerStyles } from "./player";
2
- export type { PlayerOptions } from "./player";
1
+ export { neighborOffsets, PlayerController, playerStyles } from "./player";
2
+ export type {
3
+ PlayerNeighbor,
4
+ PlayerOptions,
5
+ PlayerRenderOptions,
6
+ } from "./player";