-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathdetect.js
424 lines (375 loc) · 12.3 KB
/
detect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/** @typedef {import("web-vitals").LCPMetric} LCPMetric */
const win = window;
const doc = win.document;
const consoleLogPrefix = '[Optimization Detective]';
const storageLockTimeSessionKey = 'odStorageLockTime';
/**
* Checks whether storage is locked.
*
* @param {number} currentTime - Current time in milliseconds.
* @param {number} storageLockTTL - Storage lock TTL in seconds.
* @return {boolean} Whether storage is locked.
*/
function isStorageLocked( currentTime, storageLockTTL ) {
if ( storageLockTTL === 0 ) {
return false;
}
try {
const storageLockTime = parseInt(
sessionStorage.getItem( storageLockTimeSessionKey )
);
return (
! isNaN( storageLockTime ) &&
currentTime < storageLockTime + storageLockTTL * 1000
);
} catch ( e ) {
return false;
}
}
/**
* Set the storage lock.
*
* @param {number} currentTime - Current time in milliseconds.
*/
function setStorageLock( currentTime ) {
try {
sessionStorage.setItem(
storageLockTimeSessionKey,
String( currentTime )
);
} catch ( e ) {}
}
/**
* Log a message.
*
* @param {...*} message
*/
function log( ...message ) {
// eslint-disable-next-line no-console
console.log( consoleLogPrefix, ...message );
}
/**
* Log a warning.
*
* @param {...*} message
*/
function warn( ...message ) {
// eslint-disable-next-line no-console
console.warn( consoleLogPrefix, ...message );
}
/**
* Log an error.
*
* @param {...*} message
*/
function error( ...message ) {
// eslint-disable-next-line no-console
console.error( consoleLogPrefix, ...message );
}
/**
* @typedef {Object} ElementMetrics
* @property {boolean} isLCP - Whether it is the LCP candidate.
* @property {boolean} isLCPCandidate - Whether it is among the LCP candidates.
* @property {string} xpath - XPath.
* @property {number} intersectionRatio - Intersection ratio.
* @property {DOMRectReadOnly} intersectionRect - Intersection rectangle.
* @property {DOMRectReadOnly} boundingClientRect - Bounding client rectangle.
*/
/**
* @typedef {Object} URLMetrics
* @property {string} url - URL of the page.
* @property {Object} viewport - Viewport.
* @property {number} viewport.width - Viewport width.
* @property {number} viewport.height - Viewport height.
* @property {ElementMetrics[]} elements - Metrics for the elements observed on the page.
*/
/**
* @typedef {Object} URLMetricsGroupStatus
* @property {number} minimumViewportWidth - Minimum viewport width.
* @property {boolean} complete - Whether viewport group is complete.
*/
/**
* Checks whether the URL metric(s) for the provided viewport width is needed.
*
* @param {number} viewportWidth - Current viewport width.
* @param {URLMetricsGroupStatus[]} urlMetricsGroupStatuses - Viewport group statuses.
* @return {boolean} Whether URL metrics are needed.
*/
function isViewportNeeded( viewportWidth, urlMetricsGroupStatuses ) {
let lastWasLacking = false;
for ( const {
minimumViewportWidth,
complete,
} of urlMetricsGroupStatuses ) {
if ( viewportWidth >= minimumViewportWidth ) {
lastWasLacking = ! complete;
} else {
break;
}
}
return lastWasLacking;
}
/**
* Gets the current time in milliseconds.
*
* @return {number} Current time in milliseconds.
*/
function getCurrentTime() {
return Date.now();
}
/**
* Detects the LCP element, loaded images, client viewport and store for future optimizations.
*
* @param {Object} args Args.
* @param {number} args.serveTime The serve time of the page in milliseconds from PHP via `microtime( true ) * 1000`.
* @param {number} args.detectionTimeWindow The number of milliseconds between now and when the page was first generated in which detection should proceed.
* @param {number} args.minViewportAspectRatio Minimum aspect ratio allowed for the viewport.
* @param {number} args.maxViewportAspectRatio Maximum aspect ratio allowed for the viewport.
* @param {boolean} args.isDebug Whether to show debug messages.
* @param {string} args.restApiEndpoint URL for where to send the detection data.
* @param {string} args.restApiNonce Nonce for writing to the REST API.
* @param {string} args.currentUrl Current URL.
* @param {string} args.urlMetricsSlug Slug for URL metrics.
* @param {string} args.urlMetricsNonce Nonce for URL metrics storage.
* @param {URLMetricsGroupStatus[]} args.urlMetricsGroupStatuses URL metrics group statuses.
* @param {number} args.storageLockTTL The TTL (in seconds) for the URL metric storage lock.
* @param {string} args.webVitalsLibrarySrc The URL for the web-vitals library.
* @param {Object} [args.urlMetricsGroupCollection] URL metrics group collection, when in debug mode.
*/
export default async function detect( {
serveTime,
detectionTimeWindow,
minViewportAspectRatio,
maxViewportAspectRatio,
isDebug,
restApiEndpoint,
restApiNonce,
currentUrl,
urlMetricsSlug,
urlMetricsNonce,
urlMetricsGroupStatuses,
storageLockTTL,
webVitalsLibrarySrc,
urlMetricsGroupCollection,
} ) {
const currentTime = getCurrentTime();
if ( isDebug ) {
log(
'Stored URL metrics group collection:',
urlMetricsGroupCollection
);
}
// Abort running detection logic if it was served in a cached page.
if ( currentTime - serveTime > detectionTimeWindow ) {
if ( isDebug ) {
warn(
'Aborted detection due to being outside detection time window.'
);
}
return;
}
// Abort if the current viewport is not among those which need URL metrics.
if ( ! isViewportNeeded( win.innerWidth, urlMetricsGroupStatuses ) ) {
if ( isDebug ) {
log( 'No need for URL metrics from the current viewport.' );
}
return;
}
// Abort if the viewport aspect ratio is not in a common range.
const aspectRatio = win.innerWidth / win.innerHeight;
if (
aspectRatio < minViewportAspectRatio ||
aspectRatio > maxViewportAspectRatio
) {
if ( isDebug ) {
warn(
`Viewport aspect ratio (${ aspectRatio }) is not in the accepted range of ${ minViewportAspectRatio } to ${ maxViewportAspectRatio }.`
);
}
return;
}
// Ensure the DOM is loaded (although it surely already is since we're executing in a module).
await new Promise( ( resolve ) => {
if ( doc.readyState !== 'loading' ) {
resolve();
} else {
doc.addEventListener( 'DOMContentLoaded', resolve, { once: true } );
}
} );
// Wait until the resources on the page have fully loaded.
await new Promise( ( resolve ) => {
if ( doc.readyState === 'complete' ) {
resolve();
} else {
win.addEventListener( 'load', resolve, { once: true } );
}
} );
// Wait yet further until idle.
if ( typeof requestIdleCallback === 'function' ) {
await new Promise( ( resolve ) => {
requestIdleCallback( resolve );
} );
}
// As an alternative to this, the od_print_detection_script() function can short-circuit if the
// od_is_url_metric_storage_locked() function returns true. However, the downside with that is page caching could
// result in metrics missed from being gathered when a user navigates around a site and primes the page cache.
if ( isStorageLocked( currentTime, storageLockTTL ) ) {
if ( isDebug ) {
warn( 'Aborted detection due to storage being locked.' );
}
return;
}
// Prevent detection when page is not scrolled to the initial viewport.
if ( doc.documentElement.scrollTop > 0 ) {
if ( isDebug ) {
warn(
'Aborted detection since initial scroll position of page is not at the top.'
);
}
return;
}
if ( isDebug ) {
log( 'Proceeding with detection' );
}
const breadcrumbedElements = doc.body.querySelectorAll( '[data-od-xpath]' );
/** @type {Map<HTMLElement, string>} */
const breadcrumbedElementsMap = new Map(
[ ...breadcrumbedElements ].map(
/**
* @param {HTMLElement} element
* @return {[HTMLElement, string]} Tuple of element and its XPath.
*/
( element ) => [ element, element.dataset.odXpath ]
)
);
/** @type {IntersectionObserverEntry[]} */
const elementIntersections = [];
/** @type {?IntersectionObserver} */
let intersectionObserver;
function disconnectIntersectionObserver() {
if ( intersectionObserver instanceof IntersectionObserver ) {
intersectionObserver.disconnect();
win.removeEventListener( 'scroll', disconnectIntersectionObserver ); // Clean up, even though this is registered with once:true.
}
}
// Wait for the intersection observer to report back on the initially-visible elements.
// Note that the first callback will include _all_ observed entries per <https://github.com/w3c/IntersectionObserver/issues/476>.
if ( breadcrumbedElementsMap.size > 0 ) {
await new Promise( ( resolve ) => {
intersectionObserver = new IntersectionObserver(
( entries ) => {
for ( const entry of entries ) {
elementIntersections.push( entry );
}
resolve();
},
{
root: null, // To watch for intersection relative to the device's viewport.
threshold: 0.0, // As soon as even one pixel is visible.
}
);
for ( const element of breadcrumbedElementsMap.keys() ) {
intersectionObserver.observe( element );
}
} );
// Stop observing as soon as the page scrolls since we only want initial-viewport elements.
win.addEventListener( 'scroll', disconnectIntersectionObserver, {
once: true,
passive: true,
} );
}
const { onLCP } = await import( webVitalsLibrarySrc );
/** @type {LCPMetric[]} */
const lcpMetricCandidates = [];
// Obtain at least one LCP candidate. More may be reported before the page finishes loading.
await new Promise( ( resolve ) => {
onLCP(
( metric ) => {
lcpMetricCandidates.push( metric );
resolve();
},
{
// This avoids needing to click to finalize LCP candidate. While this is helpful for testing, it also
// ensures that we always get an LCP candidate reported. Otherwise, the callback may never fire if the
// user never does a click or keydown, per <https://github.com/GoogleChrome/web-vitals/blob/07f6f96/src/onLCP.ts#L99-L107>.
reportAllChanges: true,
}
);
} );
// Stop observing.
disconnectIntersectionObserver();
if ( isDebug ) {
log( 'Detection is stopping.' );
}
/** @type {URLMetrics} */
const urlMetrics = {
url: currentUrl,
slug: urlMetricsSlug,
nonce: urlMetricsNonce,
viewport: {
width: win.innerWidth,
height: win.innerHeight,
},
elements: [],
};
const lcpMetric = lcpMetricCandidates.at( -1 );
for ( const elementIntersection of elementIntersections ) {
const xpath = breadcrumbedElementsMap.get( elementIntersection.target );
if ( ! xpath ) {
if ( isDebug ) {
error( 'Unable to look up XPath for element' );
}
continue;
}
const isLCP =
elementIntersection.target === lcpMetric?.entries[ 0 ]?.element;
/** @type {ElementMetrics} */
const elementMetrics = {
isLCP,
isLCPCandidate: !! lcpMetricCandidates.find(
( lcpMetricCandidate ) =>
lcpMetricCandidate.entries[ 0 ]?.element ===
elementIntersection.target
),
xpath,
intersectionRatio: elementIntersection.intersectionRatio,
intersectionRect: elementIntersection.intersectionRect,
boundingClientRect: elementIntersection.boundingClientRect,
};
urlMetrics.elements.push( elementMetrics );
}
if ( isDebug ) {
log( 'Current URL metrics:', urlMetrics );
}
// Yield to main before sending data to server to further break up task.
await new Promise( ( resolve ) => {
setTimeout( resolve, 0 );
} );
try {
const response = await fetch( restApiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': restApiNonce,
},
body: JSON.stringify( urlMetrics ),
} );
if ( response.status === 200 ) {
setStorageLock( getCurrentTime() );
}
if ( isDebug ) {
const body = await response.json();
if ( response.status === 200 ) {
log( 'Response:', body );
} else {
error( 'Failure:', body );
}
}
} catch ( err ) {
if ( isDebug ) {
error( err );
}
}
// Clean up.
breadcrumbedElementsMap.clear();
}