-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetect.js
98 lines (85 loc) · 1.91 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
const consoleLogPrefix = '[OD Debug Helper]';
/**
* Logs a message.
*
* @since 0.3.0
*
* @param {...*} message
*/
function log( ...message ) {
// eslint-disable-next-line no-console
console.log( consoleLogPrefix, ...message );
}
const inpData = [];
/**
* Initializes extension.
*
* @since 0.1.0
*/
export async function initialize( { onINP } ) {
onINP(
/**
* @param {INPMetric|INPMetricWithAttribution} metric
*/
( metric ) => {
if ( 'attribution' in metric ) {
inpData.push( {
value: metric.value,
rating: metric.rating,
interactionTarget: metric.attribution.interactionTarget,
xpath: createXPathSelector(
metric.attribution.interactionTargetElement
),
} );
}
}
);
}
// TODO: The resulting selector needs to be compatible with the one in PHP.
function createXPathSelector( element ) {
if ( ! element || element.nodeType !== Node.ELEMENT_NODE ) {
throw new Error( 'Invalid element provided.' );
}
let path = '';
let currentElement = element;
while ( currentElement ) {
// The `document` global doesn't have a tagName.
if ( ! currentElement.tagName ) {
break;
}
let elementName = currentElement.tagName;
let index = 1;
let siblings = currentElement.parentNode
? currentElement.parentNode.childNodes
: [];
for ( let i = 0; i < siblings.length; i++ ) {
const sibling = siblings[ i ];
if ( sibling === currentElement ) {
break;
}
if (
sibling.nodeType === Node.ELEMENT_NODE &&
sibling.tagName === elementName
) {
index++;
}
}
path = `/${ elementName }[${ index }]${ path }`;
currentElement = currentElement.parentNode;
}
return path;
}
/**
* Finalizes extension.
*
* @since 0.1.0
*/
export async function finalize( { extendRootData, isDebug } ) {
if ( Object.keys( inpData ).length === 0 ) {
return;
}
if ( isDebug ) {
log( 'Sending INP data:', inpData );
}
extendRootData( { inpData } );
}