@vouchfor/embeds 0.0.0-experiment.279acaf → 0.0.0-experiment.29ac67c

Sign up to get free protection for your applications and to get access to all the features.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vouchfor/embeds",
3
- "version": "0.0.0-experiment.279acaf",
3
+ "version": "0.0.0-experiment.29ac67c",
4
4
  "license": "MIT",
5
5
  "author": "Aaron Williams",
6
6
  "main": "dist/es/embeds.js",
@@ -36,7 +36,7 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@lit/task": "^1.0.0",
39
- "@vouchfor/media-player": "0.0.0-experiment.279acaf",
39
+ "@vouchfor/media-player": "0.0.0-experiment.29ac67c",
40
40
  "uuid": "^9.0.1"
41
41
  },
42
42
  "peerDependencies": {
@@ -10,7 +10,17 @@ type EmbedArgs = EmbedProps & {
10
10
  showVouch?: boolean;
11
11
  };
12
12
 
13
- const _Embed = ({ vouchId, templateId, preload, autoplay, env, apiKey, controls, aspectRatio }: EmbedArgs) => {
13
+ const _Embed = ({
14
+ vouchId,
15
+ templateId,
16
+ questions,
17
+ preload,
18
+ autoplay,
19
+ env,
20
+ apiKey,
21
+ controls,
22
+ aspectRatio
23
+ }: EmbedArgs) => {
14
24
  return html`
15
25
  <div style="height: 100vh">
16
26
  <vouch-embed
@@ -18,10 +28,12 @@ const _Embed = ({ vouchId, templateId, preload, autoplay, env, apiKey, controls,
18
28
  apiKey=${ifDefined(apiKey)}
19
29
  vouchId=${ifDefined(vouchId)}
20
30
  templateId=${ifDefined(templateId)}
31
+ .questions=${questions}
21
32
  .controls=${controls}
22
33
  ?autoplay=${autoplay}
23
34
  preload=${ifDefined(preload)}
24
35
  aspectRatio=${ifDefined(aspectRatio)}
36
+ @error=${console.log}
25
37
  ></vouch-embed>
26
38
  </div>
27
39
  `;
@@ -43,6 +55,7 @@ const Embed: Story = {
43
55
  apiKey: 'TVik9uTMgE-PD25UTHIS6gyl0hMBWC7AT4dkpdlLBT4VIfDWZJrQiCk6Ak7m1',
44
56
  vouchId: '6JQEIPeStt',
45
57
  templateId: '357fc118-e179-4171-9446-ff2b8e9d1b29',
58
+ questions: [],
46
59
  aspectRatio: 0,
47
60
  preload: 'none',
48
61
  autoplay: false
@@ -9,7 +9,7 @@ import { getEnvUrls } from '~/utils/env';
9
9
 
10
10
  type EmbedHost = ReactiveControllerHost & Embed;
11
11
 
12
- type TaskDeps = [
12
+ type FetchTaskDeps = [
13
13
  EmbedProps['env'],
14
14
  EmbedProps['apiKey'],
15
15
  EmbedProps['data'],
@@ -17,10 +17,13 @@ type TaskDeps = [
17
17
  EmbedProps['templateId']
18
18
  ];
19
19
 
20
+ type FilterTaskDeps = [EmbedProps['data'], EmbedProps['questions']];
21
+
20
22
  class FetcherController {
21
23
  host: EmbedHost;
22
24
 
23
25
  private _fetching = false;
26
+ private _vouch: EmbedProps['data'];
24
27
 
25
28
  set fetching(value) {
26
29
  if (this._fetching !== value) {
@@ -45,7 +48,7 @@ class FetcherController {
45
48
  });
46
49
 
47
50
  const vouch = await res.json();
48
- this.host.dispatchEvent(new CustomEvent('vouch:loaded', { detail: vouchId }));
51
+ this.host.dispatchEvent(new CustomEvent('vouch:loaded', { detail: vouch?.id }));
49
52
 
50
53
  // HACK: we're currently using API Gateway caching on the embed API without any invalidation logic,
51
54
  // so to ensure that the cache stays up to date, whenever we detect a cache hit we trigger another
@@ -96,9 +99,9 @@ class FetcherController {
96
99
 
97
100
  constructor(host: EmbedHost) {
98
101
  this.host = host;
99
- new Task<TaskDeps, void>(
102
+ new Task<FetchTaskDeps, void>(
100
103
  this.host,
101
- async ([env, apiKey, data, vouchId, templateId]: TaskDeps) => {
104
+ async ([env, apiKey, data, vouchId, templateId]: FetchTaskDeps) => {
102
105
  try {
103
106
  host.vouch = undefined;
104
107
  host.template = undefined;
@@ -109,7 +112,7 @@ class FetcherController {
109
112
  this.fetching = true;
110
113
  template = await this.getTemplate(env, apiKey, templateId);
111
114
  }
112
- host.vouch = data;
115
+ this._vouch = data;
113
116
  host.template = template ?? data?.settings?.template?.instance;
114
117
  } else if (vouchId) {
115
118
  this.fetching = true;
@@ -118,7 +121,7 @@ class FetcherController {
118
121
  this.getVouch(env, apiKey, vouchId),
119
122
  templateId ? this.getTemplate(env, apiKey, templateId) : null
120
123
  ]);
121
- host.vouch = vouch;
124
+ this._vouch = vouch;
122
125
  host.template = template ?? vouch?.settings?.template?.instance;
123
126
  }
124
127
  } finally {
@@ -127,6 +130,22 @@ class FetcherController {
127
130
  },
128
131
  () => [host.env, host.apiKey, host.data, host.vouchId, host.templateId]
129
132
  );
133
+
134
+ // This second task is to be able to filter the vouch without fetching it again if only the questions changed
135
+ new Task<FilterTaskDeps, void>(
136
+ this.host,
137
+ ([vouch, questions]: FilterTaskDeps) => {
138
+ host.vouch = vouch
139
+ ? {
140
+ ...vouch,
141
+ questions: {
142
+ items: vouch?.questions.items.filter((_, index) => !questions?.length || questions?.includes(index + 1))
143
+ }
144
+ }
145
+ : undefined;
146
+ },
147
+ () => [this._vouch, host.questions]
148
+ );
130
149
  }
131
150
  }
132
151
 
@@ -1,18 +1,20 @@
1
+ import { TEMPLATE_VERSION } from '@vouchfor/canvas-video';
1
2
  import { v4 as uuidv4 } from 'uuid';
2
3
 
3
4
  import type { Embed } from '..';
4
5
  import type { VideoEventDetail } from '@vouchfor/media-player';
5
6
  import type { ReactiveController, ReactiveControllerHost } from 'lit';
6
7
 
8
+ import packageJson from '../../../../package.json';
7
9
  import { getEnvUrls } from '~/utils/env';
8
10
 
9
- // In seconds due to checking against node.currentTime
10
- const STREAMED_THROTTLE = 10;
11
+ const MINIMUM_SEND_THRESHOLD = 1;
11
12
 
12
13
  type EmbedHost = ReactiveControllerHost & Embed;
13
14
 
14
15
  type TrackingEvent = 'VOUCH_LOADED' | 'VOUCH_RESPONSE_VIEWED' | 'VIDEO_PLAYED' | 'VIDEO_STREAMED';
15
16
  type TrackingPayload = {
17
+ vouchId?: string;
16
18
  answerId?: string;
17
19
  streamStart?: number;
18
20
  streamEnd?: number;
@@ -45,13 +47,14 @@ class TrackingController implements ReactiveController {
45
47
  host.addController(this);
46
48
  }
47
49
 
48
- private _findVouchId() {
50
+ private _findVouchId(payload?: TrackingPayload) {
51
+ if (payload && 'vouchId' in payload) {
52
+ return payload.vouchId;
53
+ }
49
54
  if (this.host.vouch) {
50
- if ('uuid' in this.host.vouch) {
51
- return this.host.vouch.uuid;
52
- }
53
55
  return this.host.vouch.id;
54
56
  }
57
+ return null;
55
58
  }
56
59
 
57
60
  private _createVisitor = (visitorId: string) => {
@@ -125,12 +128,15 @@ class TrackingController implements ReactiveController {
125
128
  screenWidth: window.screen.width,
126
129
  referrer: document.referrer,
127
130
  currentUrl: location.href,
131
+ embedType: 'media-player-embed',
132
+ embedVersion: packageJson.version,
133
+ templateVersion: TEMPLATE_VERSION,
128
134
  ...utmParams
129
135
  };
130
136
  };
131
137
 
132
138
  private _sendTrackingEvent = (event: TrackingEvent, payload?: TrackingPayload) => {
133
- const vouchId = this._findVouchId();
139
+ const vouchId = this._findVouchId(payload);
134
140
 
135
141
  if (!vouchId || this.host.disableTracking) {
136
142
  return;
@@ -140,10 +146,13 @@ class TrackingController implements ReactiveController {
140
146
  const { client, tab, request, visitor } = this._getUids();
141
147
 
142
148
  navigator.sendBeacon(
143
- `${publicApiUrl}/api/events`,
149
+ `${publicApiUrl}/api/v2/events`,
144
150
  JSON.stringify({
145
151
  event,
146
- payload,
152
+ payload: {
153
+ ...payload,
154
+ vouchId
155
+ },
147
156
  context: {
148
157
  'x-uid-client': client,
149
158
  'x-uid-tab': tab,
@@ -155,6 +164,26 @@ class TrackingController implements ReactiveController {
155
164
  );
156
165
  };
157
166
 
167
+ private _streamEnded = () => {
168
+ if (this._currentlyPlayingVideo) {
169
+ const { id, key } = this._currentlyPlayingVideo;
170
+ // Don't send a tracking event when seeking backwards
171
+ if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
172
+ // Send a video streamed event any time the stream ends to capture the time between starting
173
+ // the video and the video stopping for any reason (pausing, deleting the embed node or closing the browser)
174
+ this._sendTrackingEvent('VIDEO_STREAMED', {
175
+ answerId: id,
176
+ streamStart: this._streamStartTime[key],
177
+ streamEnd: this._streamLatestTime[key]
178
+ });
179
+ }
180
+
181
+ // Make sure these events are only sent once by deleting the start and latest times
182
+ delete this._streamStartTime[key];
183
+ delete this._streamLatestTime[key];
184
+ }
185
+ };
186
+
158
187
  private _handleVouchLoaded = ({ detail: vouchId }: CustomEvent<string>) => {
159
188
  if (!vouchId) {
160
189
  return;
@@ -162,7 +191,7 @@ class TrackingController implements ReactiveController {
162
191
 
163
192
  // Only send loaded event once per session
164
193
  if (!this._hasLoaded[vouchId]) {
165
- this._sendTrackingEvent('VOUCH_LOADED');
194
+ this._sendTrackingEvent('VOUCH_LOADED', { vouchId });
166
195
  this._hasLoaded[vouchId] = true;
167
196
  }
168
197
  };
@@ -186,54 +215,60 @@ class TrackingController implements ReactiveController {
186
215
  this._answersViewed[key] = true;
187
216
  }
188
217
 
189
- this._streamStartTime[key] = node.currentTime;
190
- this._streamLatestTime[key] = node.currentTime;
191
- };
192
-
193
- private _handleVideoTimeUpdate = ({ detail: { id, key, node } }: CustomEvent<VideoEventDetail>) => {
194
- // We only want to count any time that the video is actually playing
195
- if (!this.host.paused) {
196
- this._currentlyPlayingVideo = { id, key, node };
218
+ if (!this._streamStartTime[key]) {
219
+ this._streamStartTime[key] = node.currentTime;
197
220
  this._streamLatestTime[key] = node.currentTime;
198
221
  }
222
+ };
199
223
 
224
+ private _handleVideoTimeUpdate = ({ detail: { id, key, node } }: CustomEvent<VideoEventDetail>) => {
200
225
  if (
201
- !node.paused &&
226
+ // We only want to count any time that the video is actually playing
202
227
  !this.host.paused &&
203
- // Only fire the video seeked event when this video is the active one
204
- id === this.host.scene?.video?.id &&
205
- // Throttle the frequency that we send streamed events while playing
206
- this._streamLatestTime[key] - this._streamStartTime[key] > STREAMED_THROTTLE
228
+ // Only update the latest time if this event fires for the currently active video
229
+ id === this.host.scene?.video?.id
207
230
  ) {
208
- this._sendTrackingEvent('VIDEO_STREAMED', {
209
- answerId: id,
210
- streamStart: this._streamStartTime[key],
211
- streamEnd: this._streamLatestTime[key]
212
- });
213
-
214
- this._streamStartTime[key] = node.currentTime;
231
+ this._currentlyPlayingVideo = { id, key, node };
232
+ this._streamLatestTime[key] = node.currentTime;
215
233
  }
216
234
  };
217
235
 
218
236
  private _handleVideoPause = ({ detail: { id, key } }: CustomEvent<VideoEventDetail>) => {
219
- // Don't send a tracking event when seeking backwards
220
- if (this._streamLatestTime[key] > this._streamStartTime[key]) {
221
- // Send a video streamed event any time the video pauses then reset the streamed state
222
- // We do this to capture the last bit of time that the video was played between the previous
223
- // stream event and the video being paused manually or stopping because it ended
237
+ if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
224
238
  this._sendTrackingEvent('VIDEO_STREAMED', {
225
239
  answerId: id,
226
240
  streamStart: this._streamStartTime[key],
227
241
  streamEnd: this._streamLatestTime[key]
228
242
  });
229
243
  }
230
- this._currentlyPlayingVideo = null;
231
244
  delete this._streamStartTime[key];
232
245
  delete this._streamLatestTime[key];
233
246
  };
234
247
 
248
+ private _pageUnloading = () => {
249
+ this._streamEnded();
250
+ // This will try to send the same stream event again so we delete the start and latest
251
+ // time in stream ended so that there is no times to send and the pause event does nothing
252
+ this.host.pause();
253
+ };
254
+
255
+ private _handleVisibilityChange = () => {
256
+ if (document.visibilityState === 'hidden') {
257
+ this._pageUnloading();
258
+ }
259
+ };
260
+
261
+ private _handlePageHide = () => {
262
+ this._pageUnloading();
263
+ };
264
+
235
265
  hostConnected() {
236
266
  requestAnimationFrame(() => {
267
+ if ('onvisibilitychange' in document) {
268
+ document.addEventListener('visibilitychange', this._handleVisibilityChange);
269
+ } else {
270
+ window.addEventListener('pagehide', this._handlePageHide);
271
+ }
237
272
  this.host.addEventListener('vouch:loaded', this._handleVouchLoaded);
238
273
  this.host.mediaPlayer?.addEventListener('play', this._handlePlay);
239
274
  this.host.mediaPlayer?.addEventListener('video:play', this._handleVideoPlay);
@@ -243,20 +278,12 @@ class TrackingController implements ReactiveController {
243
278
  }
244
279
 
245
280
  hostDisconnected() {
246
- if (this._currentlyPlayingVideo) {
247
- const { id, key } = this._currentlyPlayingVideo;
248
- if (this._streamLatestTime[key] > this._streamStartTime[key]) {
249
- // Send a video streamed event any time the video pauses then reset the streamed state
250
- // We do this to capture the last bit of time that the video was played between the previous
251
- // stream event and the video being paused manually or stopping because it ended
252
- this._sendTrackingEvent('VIDEO_STREAMED', {
253
- answerId: id,
254
- streamStart: this._streamStartTime[key],
255
- streamEnd: this._streamLatestTime[key]
256
- });
257
- }
281
+ this._streamEnded();
282
+ if ('onvisibilitychange' in document) {
283
+ document.removeEventListener('visibilitychange', this._handleVisibilityChange);
284
+ } else {
285
+ window.removeEventListener('pagehide', this._handlePageHide);
258
286
  }
259
-
260
287
  this.host.removeEventListener('vouch:loaded', this._handleVouchLoaded);
261
288
  this.host.mediaPlayer?.removeEventListener('play', this._handlePlay);
262
289
  this.host.mediaPlayer?.removeEventListener('video:play', this._handleVideoPlay);
@@ -1,9 +1,9 @@
1
- import { html, LitElement } from 'lit';
1
+ import { css, html, LitElement } from 'lit';
2
2
  import { customElement, property, state } from 'lit/decorators.js';
3
3
  import { ifDefined } from 'lit/directives/if-defined.js';
4
4
  import { createRef, ref } from 'lit/directives/ref.js';
5
5
 
6
- import type { Scene, TemplateInstance } from '@vouchfor/canvas-video';
6
+ import type { Scene, Scenes, TemplateInstance } from '@vouchfor/canvas-video';
7
7
  import type { MediaPlayer, MediaPlayerProps } from '@vouchfor/media-player';
8
8
  import type { Ref } from 'lit/directives/ref.js';
9
9
  import type { Environment } from '~/utils/env';
@@ -21,20 +21,31 @@ type EmbedProps = Pick<MediaPlayerProps, 'data' | 'aspectRatio' | 'preload' | 'a
21
21
  trackingSource?: string;
22
22
  vouchId?: string;
23
23
  templateId?: string;
24
+ // Index of the questions to include starting from 1
25
+ questions?: number[];
24
26
  };
25
27
 
26
28
  @customElement('vouch-embed')
27
29
  class Embed extends LitElement {
30
+ static styles = [
31
+ css`
32
+ :host {
33
+ display: flex;
34
+ }
35
+ `
36
+ ];
37
+
28
38
  private _mediaPlayerRef: Ref<MediaPlayer> = createRef();
29
39
 
30
- @property({ type: Object, attribute: 'data' }) data: EmbedProps['data'];
40
+ @property({ type: Object }) data: EmbedProps['data'];
31
41
  @property({ type: String }) vouchId: EmbedProps['vouchId'];
32
42
  @property({ type: String }) templateId: EmbedProps['templateId'];
43
+ @property({ type: Array }) questions: EmbedProps['questions'];
33
44
 
34
45
  @property({ type: String }) env: EmbedProps['env'] = 'prod';
35
46
  @property({ type: String }) apiKey: EmbedProps['apiKey'] = '';
36
47
  @property({ type: Boolean }) disableTracking: EmbedProps['disableTracking'] = false;
37
- @property({ type: String }) trackingSource: EmbedProps['trackingSource'] = 'embed';
48
+ @property({ type: String }) trackingSource: EmbedProps['trackingSource'] = 'embedded_player';
38
49
 
39
50
  @property({ type: Array }) controls: EmbedProps['controls'];
40
51
  @property({ type: String }) preload: EmbedProps['preload'] = 'auto';
@@ -149,6 +160,10 @@ class Embed extends LitElement {
149
160
  return this._mediaPlayerRef.value?.scenes ?? [];
150
161
  }
151
162
 
163
+ get sceneConfig(): Scenes | null {
164
+ return this._mediaPlayerRef.value?.sceneConfig ?? null;
165
+ }
166
+
152
167
  get videoState() {
153
168
  return this._mediaPlayerRef.value?.videoState;
154
169
  }
@@ -171,7 +186,7 @@ class Embed extends LitElement {
171
186
 
172
187
  render() {
173
188
  return html`
174
- <vmp-new-media-player
189
+ <vmp-media-player
175
190
  ${ref(this._mediaPlayerRef)}
176
191
  ${this.eventController.register()}
177
192
  ?autoplay=${this.autoplay}
@@ -181,7 +196,7 @@ class Embed extends LitElement {
181
196
  aspectRatio=${ifDefined(this.aspectRatio)}
182
197
  preload=${ifDefined(this.preload)}
183
198
  .controls=${this.controls}
184
- ></vmp-new-media-player>
199
+ ></vmp-media-player>
185
200
  `;
186
201
  }
187
202
  }
File without changes
File without changes
File without changes