Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release 1.0.8 #38

Merged
merged 7 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "wp-rocket-scripts",
"version": "1.0.7",
"version": "1.0.8",
"description": "Rocket main scripts packages",
"type": "module",
"main": "./src/BeaconEntryPoint.js",
Expand Down
8 changes: 7 additions & 1 deletion src/BeaconLcp.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,10 @@ class BeaconLcp {
element_info.bg_set = matches.map(m => m[1] ? { src: m[1].trim() } : {});
}

if (element_info.bg_set.length <= 0) {
return null;
}

if (element_info.bg_set.length > 0) {
element_info.src = element_info.bg_set[0].src;
if (element_info.type === "bg-img-set") {
Expand All @@ -165,7 +169,9 @@ class BeaconLcp {
}

_initWithFirstElementWithInfo(elements) {
const firstElementWithInfo = elements.find(item => item.elementInfo !== null);
const firstElementWithInfo = elements.find(item => {
return item.elementInfo !== null && (item.elementInfo.src || item.elementInfo.srcset);
});

if (!firstElementWithInfo) {
this.logger.logMessage("No LCP candidate found.");
Expand Down
28 changes: 27 additions & 1 deletion src/BeaconLrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,23 @@ class BeaconLrc {

_getLazyRenderElements() {
const elements = document.querySelectorAll('[data-rocket-location-hash]');
const svgUseTargets = this._getSvgUseTargets();

if (elements.length <= 0) {
return [];
}

const validElements = Array.from(elements).filter(element => !this._skipElement(element));
const validElements = Array.from(elements).filter(element => {
if (this._skipElement(element)) {
return false;
}
if (svgUseTargets.includes(element)) {
this.logger.logColoredMessage(`Element skipped because of SVG: ${element.tagName}`, 'orange');
return false;
}
return true;
});


return validElements.map(element => ({
element: element,
Expand Down Expand Up @@ -192,6 +203,21 @@ class BeaconLrc {
: 'No hash detected';
}

_getSvgUseTargets() {
const useElements = document.querySelectorAll('use');
const targets = new Set();

useElements.forEach(use => {
let parent = use.parentElement;
while (parent && parent !== document.body) {
targets.add(parent);
parent = parent.parentElement;
}
});

return Array.from(targets);
}

getResults() {
return this.lazyRenderElements;
}
Expand Down
6 changes: 6 additions & 0 deletions src/BeaconManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ class BeaconManager {
return;
}

if (BeaconUtils.isPageScrolled()) {
this.logger.logMessage('Bailing out because the page has been scrolled');
this._finalize();
return;
}

this.infiniteLoopId = setTimeout(() => {
this._handleInfiniteLoop();
}, 10000);
Expand Down
4 changes: 4 additions & 0 deletions src/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ class BeaconUtils {
);
}

static isPageScrolled() {
return window.pageYOffset > 0 || document.documentElement.scrollTop > 0;
}

}

export default BeaconUtils;
70 changes: 68 additions & 2 deletions test/BeaconLcp.test.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,41 @@
import assert from 'assert';
import BeaconLcp from '../src/BeaconLcp.js';
import node_fetch from 'node-fetch';
import sinon from 'sinon';
global.fetch = node_fetch;

describe('BeaconManager', function() {
let beacon;
let beacon,
mockLogger;

const config = { nonce: 'test', url: 'http://example.com', is_mobile: false };
beforeEach(function() {
beacon = new BeaconLcp(config);
mockLogger = { logMessage: function(message) {} };

beacon = new BeaconLcp(config, mockLogger);

global.window = {};
global.document = {};

global.window.getComputedStyle = sinon.stub().returns({
getPropertyValue: sinon.stub().returns('none'),
});

global.getComputedStyle = (element, pseudoElement) => {
return {
getPropertyValue: (prop) => {
if (prop === "background-image") {
return "none";
}
return "";
}
};
};
});

afterEach(function () {
sinon.restore();
delete global.window;
});

describe('#constructor()', function() {
Expand All @@ -30,4 +58,42 @@ describe('BeaconManager', function() {
});
});

describe('#_initWithFirstElementWithInfo()', function() {
it('should initialize performanceImages with the first valid element info', function() {
const elements = [
{ element: { nodeName: 'div' }, elementInfo: null }, // invalid, no elementInfo
{ element: { nodeName: 'img', src: 'http://example.com/image1.jpg' }, elementInfo: { type: 'img', src: 'http://example.com/image1.jpg' } },
{ element: { nodeName: 'img', src: 'http://example.com/image2.jpg' }, elementInfo: { type: 'img', src: 'http://example.com/image2.jpg' } },
];

beacon._initWithFirstElementWithInfo(elements);

assert.strictEqual(beacon.performanceImages.length, 1);
assert.strictEqual(beacon.performanceImages[0].src, 'http://example.com/image1.jpg');
assert.strictEqual(beacon.performanceImages[0].label, 'lcp');
});

it('should not initialize performanceImages if no valid element info is found', function() {
const elements = [
{ element: { nodeName: 'div' }, elementInfo: null },
{ element: { nodeName: 'div' }, elementInfo: null },
];

beacon._initWithFirstElementWithInfo(elements);

assert.strictEqual(beacon.performanceImages.length, 0);
});
});

describe('#_getElementInfo()', function() {
it('should return null when there are no valid background images', function() {
const element = {
nodeName: 'div'
};

const elementInfo = beacon._getElementInfo(element);

assert.strictEqual(elementInfo, null);
});
});
});
27 changes: 26 additions & 1 deletion test/BeaconLrc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('BeaconLrc', function() {
// Mocking document.querySelectorAll
global.document = {
querySelectorAll: (selector) => {
if (selector === '[data-rocket-location-hash]') {
if (selector === '[data-rocket-location-hash]' || selector === 'use') {
return mockElements;
}
return [];
Expand Down Expand Up @@ -148,6 +148,21 @@ describe('BeaconLrc', function() {
_skipElementStub.restore();
});

it('should skip elements with svg use', function() {
const _getElementDepthStub = sinon.stub(beaconLrc, '_getElementDepth');
_getElementDepthStub.returns(1);

const _svgElementStub = sinon.stub(beaconLrc, '_getSvgUseTargets');
_svgElementStub.returns([mockElements[2]]);

const elements = beaconLrc._getLazyRenderElements();
const skippedElement = elements.find(el => el.hash === 'hash3');
assert.strictEqual(skippedElement, undefined);

_getElementDepthStub.restore();
_svgElementStub.restore();
});

it('should return correct distance', () => {
const distance = beaconLrc._getElementDistance(mockElements[2]);
assert.strictEqual(distance, 600);
Expand Down Expand Up @@ -328,4 +343,14 @@ describe('BeaconLrc', function() {

window.getComputedStyle.restore();
})

it('should return the correct SVG use target elements', function() {
mockElements[0].parentElement = { tagName: 'svg', parentElement: null };
mockElements[1].parentElement = { tagName: 'div', parentElement: null };

const targets = beaconLrc._getSvgUseTargets();
assert.strictEqual(targets.length, 2);
assert.strictEqual(targets[0].tagName, 'svg');
assert.strictEqual(targets[1].tagName, 'div');
});
});
56 changes: 55 additions & 1 deletion test/BeaconManager.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,21 @@ describe('BeaconManager', function() {
let beacon;
const config = { nonce: 'test', url: 'http://example.com', is_mobile: false, status: {atf: true}, width_threshold: 100, height_threshold: 100 };
beforeEach(function() {
//Deep copy of config
// Deep copy of config
beacon = new BeaconManager(JSON.parse(JSON.stringify(config)));

// Mock window and document objects
global.window = {
pageYOffset: 0
};
global.document = {
documentElement: {
scrollTop: 0
},
querySelector: sinon.stub().returns({
setAttribute: sinon.spy()
})
};
});

describe('#constructor()', function() {
Expand Down Expand Up @@ -109,6 +122,47 @@ describe('BeaconManager', function() {
});
});

describe('#init()', function() {
let fetchStub;
let _isValidPreconditionsStub;
let isPageCachedStub;
let _finalizeStub;

beforeEach(function() {
// Stub the global fetch method
_isValidPreconditionsStub = sinon.stub(beacon, '_isValidPreconditions');
isPageCachedStub = sinon.stub(BeaconUtils, 'isPageCached');
_finalizeStub = sinon.stub(beacon, '_finalize');
fetchStub = sinon.stub(global, 'fetch').resolves({
json: () => Promise.resolve({ data: false })
});
});

afterEach(function() {
// Restore the original fetch method
_isValidPreconditionsStub.restore();
isPageCachedStub.restore();
_finalizeStub.restore();
fetchStub.restore();
});

it('should bail out if the page is scrolled', async function() {
// Mock _isValidPreconditions
_isValidPreconditionsStub.resolves(true);
isPageCachedStub.returns(false);

// Simulate page being scrolled
global.window.pageYOffset = 100;
global.document.documentElement.scrollTop = 100;

await beacon.init();

assert.strictEqual(_isValidPreconditionsStub.calledOnce, true);
assert.strictEqual(_finalizeStub.calledOnce, true);
assert.strictEqual(fetchStub.notCalled, true);
});
});

describe('#_isValidPreconditions()', function() {
it('should return true for desktop screensize larger than threshold', async function() {
// Mocking window properties and methods since they are used in _isValidPreconditions
Expand Down
Loading