Skip to content

Commit 5f47f0a

Browse files
authored
Merge pull request #1895 from ShyamGadde/try/export-logging-func-to-ext
Expose the logging functions to client-side extensions and automatically account for the value of `isDebug`
2 parents c17a3a3 + 53b5f19 commit 5f47f0a

File tree

4 files changed

+173
-166
lines changed

4 files changed

+173
-166
lines changed

plugins/embed-optimizer/detect.js

Lines changed: 26 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* when it is submitted for storage.
77
*/
88

9-
const consoleLogPrefix = '[Embed Optimizer]';
9+
export const name = 'Embed Optimizer';
1010

1111
/**
1212
* @typedef {import("../optimization-detective/types.ts").URLMetric} URLMetric
@@ -16,28 +16,9 @@ const consoleLogPrefix = '[Embed Optimizer]';
1616
* @typedef {import("../optimization-detective/types.ts").FinalizeArgs} FinalizeArgs
1717
* @typedef {import("../optimization-detective/types.ts").FinalizeCallback} FinalizeCallback
1818
* @typedef {import("../optimization-detective/types.ts").ExtendedElementData} ExtendedElementData
19+
* @typedef {import("../optimization-detective/types.ts").LogFunction} LogFunction
1920
*/
2021

21-
/**
22-
* Logs a message.
23-
*
24-
* @param {...*} message
25-
*/
26-
function log( ...message ) {
27-
// eslint-disable-next-line no-console
28-
console.log( consoleLogPrefix, ...message );
29-
}
30-
31-
/**
32-
* Logs an error.
33-
*
34-
* @param {...*} message
35-
*/
36-
function error( ...message ) {
37-
// eslint-disable-next-line no-console
38-
console.error( consoleLogPrefix, ...message );
39-
}
40-
4122
/**
4223
* Embed element heights.
4324
*
@@ -51,19 +32,20 @@ const loadedElementContentRects = new Map();
5132
* @type {InitializeCallback}
5233
* @param {InitializeArgs} args Args.
5334
*/
54-
export async function initialize( { isDebug } ) {
35+
export async function initialize( { log: _log } ) {
36+
// eslint-disable-next-line no-console
37+
const log = _log || console.log; // TODO: Remove once Optimization Detective likely updated, or when strict version requirement added in od_init action.
38+
5539
/** @type NodeListOf<HTMLDivElement> */
5640
const embedWrappers = document.querySelectorAll(
5741
'.wp-block-embed > .wp-block-embed__wrapper[data-od-xpath]'
5842
);
5943

6044
for ( /** @type {HTMLElement} */ const embedWrapper of embedWrappers ) {
61-
monitorEmbedWrapperForResizes( embedWrapper, isDebug );
45+
monitorEmbedWrapperForResizes( embedWrapper, log );
6246
}
6347

64-
if ( isDebug ) {
65-
log( 'Loaded embed content rects:', loadedElementContentRects );
66-
}
48+
log( 'Loaded embed content rects:', loadedElementContentRects );
6749
}
6850

6951
/**
@@ -73,24 +55,29 @@ export async function initialize( { isDebug } ) {
7355
* @param {FinalizeArgs} args Args.
7456
*/
7557
export async function finalize( {
76-
isDebug,
58+
log: _log,
59+
error: _error,
7760
getElementData,
7861
extendElementData,
7962
} ) {
63+
/* eslint-disable no-console */
64+
// TODO: Remove once Optimization Detective likely updated, or when strict version requirement added in od_init action.
65+
const log = _log || console.log;
66+
const error = _error || console.error;
67+
/* eslint-enable no-console */
68+
8069
for ( const [ xpath, domRect ] of loadedElementContentRects.entries() ) {
8170
try {
8271
extendElementData( xpath, {
8372
resizedBoundingClientRect: domRect,
8473
} );
85-
if ( isDebug ) {
86-
const elementData = getElementData( xpath );
87-
log(
88-
`boundingClientRect for ${ xpath } resized:`,
89-
elementData.boundingClientRect,
90-
'=>',
91-
domRect
92-
);
93-
}
74+
const elementData = getElementData( xpath );
75+
log(
76+
`boundingClientRect for ${ xpath } resized:`,
77+
elementData.boundingClientRect,
78+
'=>',
79+
domRect
80+
);
9481
} catch ( err ) {
9582
error(
9683
`Failed to extend element data for ${ xpath } with resizedBoundingClientRect:`,
@@ -105,19 +92,17 @@ export async function finalize( {
10592
* Monitors embed wrapper for resizes.
10693
*
10794
* @param {HTMLDivElement} embedWrapper Embed wrapper DIV.
108-
* @param {boolean} isDebug Whether debug.
95+
* @param {LogFunction} log The function to call with log messages.
10996
*/
110-
function monitorEmbedWrapperForResizes( embedWrapper, isDebug ) {
97+
function monitorEmbedWrapperForResizes( embedWrapper, log ) {
11198
if ( ! ( 'odXpath' in embedWrapper.dataset ) ) {
11299
throw new Error( 'Embed wrapper missing data-od-xpath attribute.' );
113100
}
114101
const xpath = embedWrapper.dataset.odXpath;
115102
const observer = new ResizeObserver( ( entries ) => {
116103
const [ entry ] = entries;
117104
loadedElementContentRects.set( xpath, entry.contentRect );
118-
if ( isDebug ) {
119-
log( `Resized element ${ xpath }:`, entry.contentRect );
120-
}
105+
log( `Resized element ${ xpath }:`, entry.contentRect );
121106
} );
122107
observer.observe( embedWrapper, { box: 'content-box' } );
123108
}

plugins/image-prioritizer/detect.js

Lines changed: 26 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
* document has a tag with the same name, ID, and class.
1010
*/
1111

12-
const consoleLogPrefix = '[Image Prioritizer]';
12+
export const name = 'Image Prioritizer';
1313

1414
/**
1515
* Detected LCP external background image candidates.
@@ -29,20 +29,9 @@ const externalBackgroundImages = [];
2929
* @typedef {import("../optimization-detective/types.ts").InitializeArgs} InitializeArgs
3030
* @typedef {import("../optimization-detective/types.ts").FinalizeArgs} FinalizeArgs
3131
* @typedef {import("../optimization-detective/types.ts").FinalizeCallback} FinalizeCallback
32+
* @typedef {import("../optimization-detective/types.ts").LogFunction} LogFunction
3233
*/
3334

34-
/**
35-
* Logs a message.
36-
*
37-
* @since 0.3.0
38-
*
39-
* @param {...*} message
40-
*/
41-
function log( ...message ) {
42-
// eslint-disable-next-line no-console
43-
console.log( consoleLogPrefix, ...message );
44-
}
45-
4635
/**
4736
* Initializes extension.
4837
*
@@ -51,10 +40,13 @@ function log( ...message ) {
5140
* @type {InitializeCallback}
5241
* @param {InitializeArgs} args Args.
5342
*/
54-
export async function initialize( { isDebug, onLCP } ) {
43+
export async function initialize( { log: _log, onLCP } ) {
44+
// eslint-disable-next-line no-console
45+
const log = _log || console.log; // TODO: Remove once Optimization Detective likely updated, or when strict version requirement added in od_init action.
46+
5547
onLCP(
5648
( metric ) => {
57-
handleLCPMetric( metric, isDebug );
49+
handleLCPMetric( metric, log );
5850
},
5951
{
6052
// This avoids needing to click to finalize LCP candidate. While this is helpful for testing, it also
@@ -70,10 +62,10 @@ export async function initialize( { isDebug, onLCP } ) {
7062
*
7163
* @since 0.3.0
7264
*
73-
* @param {LCPMetric} metric - LCP Metric.
74-
* @param {boolean} isDebug - Whether in debug mode.
65+
* @param {LCPMetric} metric - LCP Metric.
66+
* @param {LogFunction} log - The function to call with log messages.
7567
*/
76-
function handleLCPMetric( metric, isDebug ) {
68+
function handleLCPMetric( metric, log ) {
7769
for ( const entry of metric.entries ) {
7870
// Look only for LCP entries that have a URL and a corresponding element which is not an IMG or VIDEO.
7971
if (
@@ -98,36 +90,26 @@ function handleLCPMetric( metric, isDebug ) {
9890

9991
// Skip URLs that are excessively long. This is the maxLength defined in image_prioritizer_add_element_item_schema_properties().
10092
if ( entry.url.length > 500 ) {
101-
if ( isDebug ) {
102-
log( `Skipping very long URL: ${ entry.url }` );
103-
}
93+
log( `Skipping very long URL: ${ entry.url }` );
10494
return;
10595
}
10696

10797
// Also skip Custom Elements which have excessively long tag names. This is the maxLength defined in image_prioritizer_add_element_item_schema_properties().
10898
if ( entry.element.tagName.length > 100 ) {
109-
if ( isDebug ) {
110-
log(
111-
`Skipping very long tag name: ${ entry.element.tagName }`
112-
);
113-
}
99+
log( `Skipping very long tag name: ${ entry.element.tagName }` );
114100
return;
115101
}
116102

117103
// Note that getAttribute() is used instead of properties so that null can be returned in case of an absent attribute.
118104
// The maxLengths are defined in image_prioritizer_add_element_item_schema_properties().
119105
const id = entry.element.getAttribute( 'id' );
120106
if ( typeof id === 'string' && id.length > 100 ) {
121-
if ( isDebug ) {
122-
log( `Skipping very long ID: ${ id }` );
123-
}
107+
log( `Skipping very long ID: ${ id }` );
124108
return;
125109
}
126110
const className = entry.element.getAttribute( 'class' );
127111
if ( typeof className === 'string' && className.length > 500 ) {
128-
if ( isDebug ) {
129-
log( `Skipping very long className: ${ className }` );
130-
}
112+
log( `Skipping very long className: ${ className }` );
131113
return;
132114
}
133115

@@ -141,12 +123,10 @@ function handleLCPMetric( metric, isDebug ) {
141123
class: className,
142124
};
143125

144-
if ( isDebug ) {
145-
log(
146-
'Detected external LCP background image:',
147-
externalBackgroundImage
148-
);
149-
}
126+
log(
127+
'Detected external LCP background image:',
128+
externalBackgroundImage
129+
);
150130

151131
externalBackgroundImages.push( externalBackgroundImage );
152132
}
@@ -160,20 +140,21 @@ function handleLCPMetric( metric, isDebug ) {
160140
* @type {FinalizeCallback}
161141
* @param {FinalizeArgs} args Args.
162142
*/
163-
export async function finalize( { extendRootData, isDebug } ) {
143+
export async function finalize( { extendRootData, log: _log } ) {
144+
// eslint-disable-next-line no-console
145+
const log = _log || console.log; // TODO: Remove once Optimization Detective likely updated, or when strict version requirement added in od_init action.
146+
164147
if ( externalBackgroundImages.length === 0 ) {
165148
return;
166149
}
167150

168151
// Get the last detected external background image which is going to be for the LCP element (or very likely will be).
169152
const lcpElementExternalBackgroundImage = externalBackgroundImages.pop();
170153

171-
if ( isDebug ) {
172-
log(
173-
'Sending external background image for LCP element:',
174-
lcpElementExternalBackgroundImage
175-
);
176-
}
154+
log(
155+
'Sending external background image for LCP element:',
156+
lcpElementExternalBackgroundImage
157+
);
177158

178159
extendRootData( { lcpElementExternalBackgroundImage } );
179160
}

0 commit comments

Comments
 (0)