@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
@@ -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>
@@ -1,9 +1,18 @@
1
1
  /*! Icons from Phosphor Icons (https://phosphoricons.com), MIT License, Copyright (c) 2023 Phosphor Icons */
2
2
 
3
+ import type { DirectiveResult } from "lit/directive.js";
4
+ import {
5
+ unsafeHTML,
6
+ type UnsafeHTMLDirective,
7
+ } from "lit/directives/unsafe-html.js";
8
+
3
9
  // SVG files as downloaded from Phosphor: regular weight, or the weight in the
4
10
  // file name. They are bundled as text: `?raw` is handled by Vite in dev and
5
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";
6
14
  import close from "./assets/close.svg?raw";
15
+ import caretUp from "./assets/caret-up-bold.svg?raw";
7
16
  import collapse from "./assets/collapse.svg?raw";
8
17
  import expand from "./assets/expand.svg?raw";
9
18
  import pause from "./assets/pause-fill.svg?raw";
@@ -12,25 +21,37 @@ import soundOff from "./assets/speaker-x-fill.svg?raw";
12
21
  import soundOn from "./assets/speaker-high-fill.svg?raw";
13
22
 
14
23
  export const icons = {
24
+ caretUp,
15
25
  close,
16
26
  collapse,
17
27
  expand,
28
+ next,
18
29
  pause,
19
30
  play,
31
+ previous,
20
32
  soundOff,
21
33
  soundOn,
22
34
  };
23
35
 
24
36
  export type IconName = keyof typeof icons;
25
37
 
26
- /** Renders a bundled icon. It is decorative: name the control around it. */
27
- export function createIcon(name: IconName) {
28
- const template = document.createElement("template");
29
- template.innerHTML = icons[name];
38
+ // Each file as markup, marked decorative once so every render reuses it.
39
+ const markup = Object.fromEntries(
40
+ Object.entries(icons).map(([name, svg]) => [
41
+ name,
42
+ svg.replace(
43
+ "<svg",
44
+ '<svg class="icon" aria-hidden="true" focusable="false"',
45
+ ),
46
+ ]),
47
+ ) as Record<IconName, string>;
30
48
 
31
- const svg = template.content.firstElementChild as SVGSVGElement;
32
- svg.classList.add("icon");
33
- svg.setAttribute("aria-hidden", "true");
34
- svg.setAttribute("focusable", "false");
35
- return svg;
49
+ /**
50
+ * Renders a bundled icon in a Lit template. It is decorative: name the
51
+ * control around it. The markup only ever comes from the bundled files.
52
+ */
53
+ export function icon(
54
+ name: IconName,
55
+ ): DirectiveResult<typeof UnsafeHTMLDirective> {
56
+ return unsafeHTML(markup[name]);
36
57
  }
@@ -0,0 +1,3 @@
1
+ export { hasVideo, prefersReducedMotion, renderMedia } from "./media";
2
+ export type { MediaOptions } from "./media";
3
+ export { playVideo, VideoController } from "./video-controller";
@@ -0,0 +1,70 @@
1
+ import { html, nothing } from "lit";
2
+ import { ref } from "lit/directives/ref.js";
3
+ import type { StoryMedia } from "../../types";
4
+ import { httpUrl } from "../../utils/http-url";
5
+ import type { VideoController } from "./video-controller";
6
+
7
+ export function prefersReducedMotion() {
8
+ return (
9
+ globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false
10
+ );
11
+ }
12
+
13
+ /** Whether renderMedia shows a video for this Story right now. */
14
+ export function hasVideo(story: StoryMedia, video: VideoController) {
15
+ return !video.failed && httpUrl(story.media_url) !== null;
16
+ }
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
+
27
+ /**
28
+ * The Story cover and, with a media_url, the video looping muted over it. If
29
+ * the video can't load, it is removed and the cover underneath stays. With
30
+ * withVideo false, only the cover.
31
+ */
32
+ export function renderMedia(
33
+ story: StoryMedia,
34
+ video: VideoController,
35
+ { withVideo = true, loop = true, onEnded }: MediaOptions = {},
36
+ ) {
37
+ const posterUrl = httpUrl(story.poster_url);
38
+ const mediaUrl = withVideo ? httpUrl(story.media_url) : null;
39
+
40
+ // Muted and inline is what browsers, iOS included, allow to autoplay. The
41
+ // muted attribute and property are both set, since browsers differ on
42
+ // which one they read for autoplay. No autoplay for people who asked for
43
+ // reduced motion.
44
+ return html`
45
+ ${posterUrl
46
+ ? html`<img class="poster" alt="" src=${posterUrl} />`
47
+ : nothing}
48
+ ${mediaUrl && !video.failed
49
+ ? html`
50
+ <video
51
+ class="video"
52
+ muted
53
+ playsinline
54
+ ?loop=${loop}
55
+ preload="metadata"
56
+ .muted=${true}
57
+ ?autoplay=${!prefersReducedMotion()}
58
+ poster=${posterUrl ?? nothing}
59
+ src=${mediaUrl}
60
+ ${ref(video.ref)}
61
+ @play=${video.sync}
62
+ @pause=${video.sync}
63
+ @volumechange=${video.sync}
64
+ @error=${video.fail}
65
+ @ended=${onEnded}
66
+ ></video>
67
+ `
68
+ : nothing}
69
+ `;
70
+ }
@@ -0,0 +1,125 @@
1
+ import type { ReactiveControllerHost } from "lit";
2
+ import { createRef } from "lit/directives/ref.js";
3
+
4
+ /**
5
+ * Plays a video. A blocked play is ignored: the cover or the paused state
6
+ * stays.
7
+ */
8
+ export function playVideo(video: HTMLVideoElement) {
9
+ video.play()?.catch(() => undefined);
10
+ }
11
+
12
+ /**
13
+ * Follows one rendered <video> (see renderMedia) and re-renders its host when
14
+ * it plays, pauses, is muted or unmuted, or fails to load. The state comes
15
+ * from the video's own events, so a blocked autoplay shows as paused. It needs
16
+ * no lifecycle hooks: the browser pauses a video removed from the page.
17
+ */
18
+ export class VideoController {
19
+ /** Bound to the <video> by renderMedia. */
20
+ readonly ref = createRef<HTMLVideoElement>();
21
+
22
+ paused = true;
23
+ // The video always starts muted: that is what browsers allow to autoplay.
24
+ muted = true;
25
+ /** The video could not load: only the cover is shown. */
26
+ failed = false;
27
+
28
+ constructor(private readonly host: ReactiveControllerHost) {}
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
+
36
+ /** For a new <video>, such as each time the player opens. */
37
+ reset() {
38
+ this.paused = true;
39
+ this.muted = true;
40
+ this.failed = false;
41
+ }
42
+
43
+ play() {
44
+ const video = this.ref.value;
45
+ if (video) playVideo(video);
46
+ }
47
+
48
+ pause() {
49
+ this.ref.value?.pause();
50
+ }
51
+
52
+ /** Plays again if the video plays on its own (see renderMedia). */
53
+ resume() {
54
+ const video = this.ref.value;
55
+ if (video?.autoplay) playVideo(video);
56
+ }
57
+
58
+ togglePlayback() {
59
+ const video = this.ref.value;
60
+ if (!video) return;
61
+ if (video.paused) playVideo(video);
62
+ else video.pause();
63
+ }
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
+
106
+ toggleMuted() {
107
+ const video = this.ref.value;
108
+ if (video) video.muted = !video.muted;
109
+ }
110
+
111
+ /** Listener for the video's play, pause and volumechange events. */
112
+ readonly sync = () => {
113
+ const video = this.ref.value;
114
+ if (!video) return;
115
+ this.paused = video.paused;
116
+ this.muted = video.muted;
117
+ this.host.requestUpdate();
118
+ };
119
+
120
+ /** Listener for the video's error event. */
121
+ readonly fail = () => {
122
+ this.failed = true;
123
+ this.host.requestUpdate();
124
+ };
125
+ }
@@ -1,2 +1,6 @@
1
- export { createPlayer, playerStyles, playPlayer, showPlayer } 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";