diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index b9c9ba8b9..38d030fb8 100755 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -12,7 +12,7 @@ concurrency: jobs: e2e: if: ( github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name ) && ( github.actor != 'dependabot[bot]' ) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - name: Setup Node diff --git a/assets/js/modules/__tests__/background.test.js b/assets/js/modules/__tests__/background.test.js index 9f10247d0..5b8549ed8 100644 --- a/assets/js/modules/__tests__/background.test.js +++ b/assets/js/modules/__tests__/background.test.js @@ -33,6 +33,7 @@ describe('optmlBackground', () => { mockObserver = { observe: jest.fn(), + unobserve: jest.fn(), disconnect: jest.fn() }; @@ -44,6 +45,44 @@ describe('optmlBackground', () => { }); describe('setupBackgroundImageObservation', () => { + test('issue 1216: keeps watching pending elements after the first one is lazyloaded', () => { + let classCallback; + const classObserverInstance = { observe: jest.fn(), disconnect: jest.fn() }; + global.MutationObserver = jest.fn((callback) => { + classCallback = callback; + return classObserverInstance; + }); + document.body.innerHTML = '
'; + const [first, second] = document.querySelectorAll('div'); + optmlDomUtils.getUniqueSelector.mockReturnValue('div.bg'); + optmlDomUtils.hasBackgroundImage.mockReturnValue(true); + + optmlBackground.setupBackgroundImageObservation([first, second], '.bg', new Map(), mockObserver); + + first.classList.add('optml-bg-lazyloaded'); + classCallback([{ target: first }]); + expect(classObserverInstance.disconnect).not.toHaveBeenCalled(); + + second.classList.add('optml-bg-lazyloaded'); + classCallback([{ target: second }]); + expect(mockObserver.observe).toHaveBeenCalledWith(first); + expect(mockObserver.observe).toHaveBeenCalledWith(second); + expect(classObserverInstance.disconnect).toHaveBeenCalledTimes(1); + }); + + test('issue 1216: re-observes a lazyloaded element so an already observed img gets a fresh callback', () => { + document.body.innerHTML = ''; + const img = document.querySelector('img'); + optmlDomUtils.getUniqueSelector.mockReturnValue('img.bg'); + optmlDomUtils.hasBackgroundImage.mockReturnValue(true); + + optmlBackground.setupBackgroundImageObservation([img], '.bg', new Map(), mockObserver); + + expect(mockObserver.unobserve).toHaveBeenCalledWith(img); + expect(mockObserver.observe).toHaveBeenCalledWith(img); + expect(mockObserver.unobserve.mock.invocationCallOrder[0]).toBeLessThan(mockObserver.observe.mock.invocationCallOrder[0]); + }); + test('should setup observation for elements', () => { document.body.innerHTML = `
@@ -294,6 +333,17 @@ describe('optmlBackground', () => { expect(result.selectorMap.get('.bg-element')).toEqual([]); }); + test('issue 1216: populates the provided selector map shared with the observer', () => { + document.body.innerHTML = '
'; + optmlDomUtils.getUniqueSelector.mockReturnValue('div.bg-element'); + const observerSelectorMap = new Map(); + + const result = optmlBackground.processBackgroundSelectors(['.bg-element'], mockObserver, observerSelectorMap); + + expect(result.selectorMap).toBe(observerSelectorMap); + expect(observerSelectorMap.get('.bg-element')).toEqual([]); + }); + test('should log warning for selectors with no elements', () => { const result = optmlBackground.processBackgroundSelectors(['.non-existent'], mockObserver); diff --git a/assets/js/modules/__tests__/dom-utils.test.js b/assets/js/modules/__tests__/dom-utils.test.js index 3a7031f74..1bb36abed 100644 --- a/assets/js/modules/__tests__/dom-utils.test.js +++ b/assets/js/modules/__tests__/dom-utils.test.js @@ -101,6 +101,20 @@ describe('optmlDomUtils', () => { expect(selector).toContain('another-class'); }); + test.each([ + ['only the lazyload class', 'optml-bg-lazyloaded'], + ['a whitespace-only class attribute', ' '], + ])('should return a valid selector for an element with %s', (_label, classAttribute) => { + document.body.innerHTML = '
'; + const element = document.querySelectorAll('#c > div')[1]; + element.setAttribute('class', classAttribute); + + const selector = optmlDomUtils.getUniqueSelector(element); + + expect(selector).toBe('#c > div:nth-of-type(2)'); + expect(document.querySelector(selector)).toBe(element); + }); + test('should handle element without classes', () => { document.body.innerHTML = '
'; const element = document.querySelector('div'); @@ -293,12 +307,15 @@ describe('optmlDomUtils', () => { describe('waitForPageLoad', () => { test('should resolve immediately if page is already loaded', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' }); + jest.useFakeTimers(); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForPageLoad(); - const endTime = Date.now(); + optmlDomUtils.waitForPageLoad().then(resolved); - expect(endTime - startTime).toBeLessThan(10); + // Flushes pending promises without letting any time pass. + await jest.advanceTimersByTimeAsync(0); + expect(resolved).toHaveBeenCalled(); + jest.useRealTimers(); }); test('should wait for load event if page not complete', async () => { @@ -329,54 +346,70 @@ describe('optmlDomUtils', () => { test('should fallback to setTimeout if requestIdleCallback not available', async () => { const originalRequestIdleCallback = global.requestIdleCallback; delete global.requestIdleCallback; + jest.useFakeTimers(); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForIdleTime(); - const endTime = Date.now(); + optmlDomUtils.waitForIdleTime().then(resolved); + + await jest.advanceTimersByTimeAsync(199); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); + jest.useRealTimers(); - expect(endTime - startTime).toBeGreaterThanOrEqual(200); - // Restore global.requestIdleCallback = originalRequestIdleCallback; }); }); describe('waitForViewportImages', () => { + // Fake timers: wall-clock timing can fire a millisecond early on a busy machine. + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + test('should resolve after delay if page already loaded', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' }); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForViewportImages(100); - const endTime = Date.now(); + optmlDomUtils.waitForViewportImages(100).then(resolved); - expect(endTime - startTime).toBeGreaterThanOrEqual(100); + await jest.advanceTimersByTimeAsync(99); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); }); test('should wait for load event and then delay', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'loading' }); + const resolved = jest.fn(); - const promise = optmlDomUtils.waitForViewportImages(50); - - // Simulate load event - setTimeout(() => { - window.dispatchEvent(new Event('load')); - }, 10); + optmlDomUtils.waitForViewportImages(50).then(resolved); - const startTime = Date.now(); - await promise; - const endTime = Date.now(); + await jest.advanceTimersByTimeAsync(1000); + expect(resolved).not.toHaveBeenCalled(); - expect(endTime - startTime).toBeGreaterThanOrEqual(50); + window.dispatchEvent(new Event('load')); + await jest.advanceTimersByTimeAsync(49); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); }); test('should use default delay of 1000ms', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' }); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForViewportImages(); - const endTime = Date.now(); + optmlDomUtils.waitForViewportImages().then(resolved); - expect(endTime - startTime).toBeGreaterThanOrEqual(1000); + await jest.advanceTimersByTimeAsync(999); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); }); }); }); diff --git a/assets/js/modules/__tests__/image-detector.test.js b/assets/js/modules/__tests__/image-detector.test.js index 91aba85d6..9c2841362 100644 --- a/assets/js/modules/__tests__/image-detector.test.js +++ b/assets/js/modules/__tests__/image-detector.test.js @@ -211,6 +211,73 @@ describe('optmlImageDetector', () => { // The observer is created successfully expect(observer).toBeInstanceOf(IntersectionObserver); }); + + test('issue 1216: records a background element under every watcher it matches', () => { + const selectorMap = new Map([ + ['[style*="background-image:url("]', []], + ['[style*="background-image"][style*="url("]', []] + ]); + document.body.innerHTML = '
'; + + const observer = optmlImageDetector.createIntersectionObserver([], selectorMap); + observer.callback([{ isIntersecting: true, target: document.querySelector('div') }]); + + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['div.hero']); + expect(selectorMap.get('[style*="background-image"][style*="url("]')).toEqual(['div.hero']); + }); + + test.each([ + ['with data-opt-id', ' data-opt-id="77"', [77]], + ['without data-opt-id', '', []] + ])('issue 1216: records an img background %s', (label, idAttribute, expectedImages) => { + const aboveTheFoldImages = []; + const selectorMap = new Map([['[style*="background-image:url("]', []]]); + document.body.innerHTML = ``; + + const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); + observer.callback([{ isIntersecting: true, target: document.querySelector('img') }]); + + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.bg']); + expect(aboveTheFoldImages).toEqual(expectedImages); + }); + }); + + describe('flushIntersectionObserver', () => { + test('records an element the observer has not reported before it is disconnected', async () => { + const aboveTheFoldImages = []; + const selectorMap = new Map([['[style*="background-image:url("]', []]]); + document.body.innerHTML = ''; + const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); + observer.takeRecords = jest.fn(() => [{ isIntersecting: true, target: document.querySelector('img') }]); + + await optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap); + + expect(aboveTheFoldImages).toEqual([9]); + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.late']); + }); + + test('records queued entries when no frame is rendered, as in a hidden tab', async () => { + jest.useFakeTimers(); + // Stubbed after the fake timers, which replace requestAnimationFrame too. + const requestAnimationFrameSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0); + try { + const aboveTheFoldImages = []; + const selectorMap = new Map([['[style*="background-image:url("]', []]]); + document.body.innerHTML = ''; + const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); + observer.takeRecords = jest.fn(() => [{ isIntersecting: true, target: document.querySelector('img') }]); + + const flushed = optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap); + await jest.advanceTimersByTimeAsync(100); + await flushed; + + expect(aboveTheFoldImages).toEqual([9]); + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.late']); + } finally { + requestAnimationFrameSpy.mockRestore(); + jest.useRealTimers(); + } + }); }); describe('observeOptimoleImages', () => { diff --git a/assets/js/modules/__tests__/main.test.js b/assets/js/modules/__tests__/main.test.js index 55c3f300f..f71b76514 100644 --- a/assets/js/modules/__tests__/main.test.js +++ b/assets/js/modules/__tests__/main.test.js @@ -70,6 +70,7 @@ jest.mock('../lcp.js', () => ({ jest.mock('../image-detector.js', () => ({ optmlImageDetector: { createIntersectionObserver: jest.fn(), + flushIntersectionObserver: jest.fn(), observeOptimoleImages: jest.fn(), detectImageDimensions: jest.fn(), cleanupBackgroundElements: jest.fn() @@ -265,6 +266,30 @@ describe('optmlMain', () => { expect(optmlImageDetector.detectImageDimensions).toHaveBeenCalledWith(mockImages); }); + test('sends dimensions of an image that finishes loading during the profiler waits', async () => { + const { optmlImageDetector: actualImageDetector } = jest.requireActual('../image-detector.js'); + document.body.innerHTML = ''; + const img = document.querySelector('img'); + let naturalWidth = 0; + Object.defineProperty(img, 'naturalWidth', { get: () => naturalWidth }); + Object.defineProperty(img, 'naturalHeight', { get: () => (naturalWidth ? 300 : 0) }); + optmlImageDetector.observeOptimoleImages.mockReturnValue({ + allOptimoleImages: [img], + observedElements: new Map() + }); + optmlImageDetector.detectImageDimensions.mockImplementation(images => actualImageDetector.detectImageDimensions(images)); + optmlSrcsetDetector.detectMissingSrcsets.mockImplementation(async () => { + setTimeout(() => { + naturalWidth = 400; + }, 0); + return { srcset: {}, crop: {} }; + }); + + const result = await optmlMain.runProfiling(); + + expect(result.m).toEqual({ 42: { w: 400, h: 300 } }); + }); + test('should detect missing srcsets', async () => { await optmlMain.runProfiling(); @@ -278,11 +303,89 @@ describe('optmlMain', () => { expect(optmlBackground.processBackgroundSelectors).toHaveBeenCalledWith( ['.hero', '.banner'], - mockObserver + mockObserver, + expect.any(Map) ); expect(optmlBackground.extractBackgroundImageUrls).toHaveBeenCalledWith(['.hero', '.banner']); }); + test('issue 1216: sends above-fold background selectors recorded by the observer with their URLs', async () => { + let observerSelectorMap; + let isLazyloaded = false; + + optmlImageDetector.createIntersectionObserver.mockImplementation((atfImages, selectorMap) => { + observerSelectorMap = selectorMap; + return mockObserver; + }); + + // Simulates the element being lazyloaded and then reported by the observer during the wait. + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap = new Map()) => { + selectorMap.set('.hero', []); + setTimeout(() => { + isLazyloaded = true; + observerSelectorMap.get('.hero')?.push('div.hero'); + }, 0); + return { selectorMap, pendingElements: 1 }; + }); + + optmlBackground.extractBackgroundImageUrls.mockImplementation(() => + new Map([['.hero', new Map(isLazyloaded ? [['div.hero', ['hero.jpg']]] : [])]]) + ); + + window.optimoleDataOptimizer.bgSelectors = ['.hero']; + + const result = await optmlMain.runProfiling(); + + expect(result.b).toEqual({ '.hero': { 'div.hero': ['hero.jpg'] } }); + }); + + test('issue 1216: sends at most three background URLs per element and for the LCP', async () => { + const urls = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']; + optmlLcp.detectLcpElement.mockResolvedValue({ + element: null, + imageId: null, + bgSelector: 'div.hero', + bgUrls: urls + }); + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + selectorMap.set('.hero', ['div.hero']); + return { selectorMap, pendingElements: 0 }; + }); + optmlBackground.extractBackgroundImageUrls.mockReturnValue(new Map([['.hero', new Map([['div.hero', urls]])]])); + window.optimoleDataOptimizer.bgSelectors = ['.hero']; + + const result = await optmlMain.runProfiling(); + + expect(result.b['.hero']['div.hero']).toEqual(['1.jpg', '2.jpg', '3.jpg']); + expect(result.l.u).toEqual(['1.jpg', '2.jpg', '3.jpg']); + }); + + test('issue 1216: sends at most 100 above-fold selectors per watcher', async () => { + const specificSelectors = Array.from({ length: 101 }, (value, index) => `div.tile:nth-of-type(${index + 1})`); + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + selectorMap.set('.tile', specificSelectors); + return { selectorMap, pendingElements: 0 }; + }); + window.optimoleDataOptimizer.bgSelectors = ['.tile']; + + const result = await optmlMain.runProfiling(); + + expect(Object.keys(result.b['.tile'])).toEqual(specificSelectors.slice(0, 100)); + }); + + test('issue 1216: sends at most 100 watchers', async () => { + const watchers = Array.from({ length: 101 }, (value, index) => `.bg-${index}`); + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + watchers.forEach(watcher => selectorMap.set(watcher, [])); + return { selectorMap, pendingElements: 0 }; + }); + window.optimoleDataOptimizer.bgSelectors = watchers; + + const result = await optmlMain.runProfiling(); + + expect(Object.keys(result.b)).toEqual(watchers.slice(0, 100)); + }); + test('should send data to API when images found', async () => { // Create a real image element and add to DOM document.body.innerHTML = ''; @@ -332,6 +435,22 @@ describe('optmlMain', () => { ); }); + test('records the observer entries still queued before disconnecting it', async () => { + const calls = []; + let observerArgs; + optmlImageDetector.createIntersectionObserver.mockImplementation((atfImages, selectorMap) => { + observerArgs = [atfImages, selectorMap]; + return mockObserver; + }); + optmlImageDetector.flushIntersectionObserver.mockImplementation(() => calls.push('flush')); + mockObserver.disconnect.mockImplementation(() => calls.push('disconnect')); + + await optmlMain.runProfiling(); + + expect(optmlImageDetector.flushIntersectionObserver).toHaveBeenCalledWith(mockObserver, ...observerArgs); + expect(calls).toEqual(['flush', 'disconnect']); + }); + test('should clean up event listeners after profiling', async () => { await optmlMain.runProfiling(); @@ -445,11 +564,9 @@ describe('optmlMain', () => { }); // Setup background - const selectorMap = new Map(); - selectorMap.set('.hero', ['div.hero']); - optmlBackground.processBackgroundSelectors.mockReturnValue({ - selectorMap, - pendingElements: 0 + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + selectorMap.set('.hero', ['div.hero']); + return { selectorMap, pendingElements: 0 }; }); const bgUrls = new Map(); diff --git a/assets/js/modules/background.js b/assets/js/modules/background.js index e77a9635e..c7470cac9 100644 --- a/assets/js/modules/background.js +++ b/assets/js/modules/background.js @@ -19,31 +19,45 @@ export const optmlBackground = { * @returns {number} Number of elements waiting for lazy load */ setupBackgroundImageObservation: function(elements, selector, selectorMap, observer) { + /** + * Observe a background element, re-observing so an element already observed as an Optimole image + * gets a fresh callback (its first one ran before it was marked as a background) + * @param {Element} element - Background element to observe + * @returns {void} + */ + const observeBackground = element => { + observer.unobserve(element); + observer.observe(element); + }; + + // Elements still waiting for the lazyload class + const elementsToWatch = new Set(); + // Create a single shared observer for all elements + // Only class changes are delivered (see attributeFilter below) const classObserver = new MutationObserver((mutations) => { - for (const mutation of mutations) { - if (mutation.type === 'attributes' && mutation.attributeName === 'class') { - const element = mutation.target; - - // Check if element now has the required class and a background image - if (element.classList.contains('optml-bg-lazyloaded') && - optmlDomUtils.hasBackgroundImage(element)) { - // Start observing for visibility - observer.observe(element); - - // Stop watching for class changes on this element - classObserver.disconnect(element); - - const specificSelector = element.getAttribute('data-optml-specific-selector'); - optmlLogger.info(`Background element "${specificSelector}" is now observable`); - } + mutations.forEach(({ target: element }) => { + // Check if element now has the required class and a background image + if (!elementsToWatch.has(element) || + !element.classList.contains('optml-bg-lazyloaded') || + !optmlDomUtils.hasBackgroundImage(element)) { + return; } - } + + // Start observing for visibility + observeBackground(element); + + // disconnect() stops watching every element, so wait until none is pending + elementsToWatch.delete(element); + if (elementsToWatch.size === 0) { + classObserver.disconnect(); + } + + const specificSelector = element.getAttribute('data-optml-specific-selector'); + optmlLogger.info(`Background element "${specificSelector}" is now observable`); + }); }); - // Process all elements at once - const elementsToWatch = []; - elements.forEach(element => { // Generate a specific selector for this element const specificSelector = optmlDomUtils.getUniqueSelector(element); @@ -55,15 +69,15 @@ export const optmlBackground = { // If already lazyloaded with background image, observe immediately if (element.classList.contains('optml-bg-lazyloaded') && optmlDomUtils.hasBackgroundImage(element)) { - observer.observe(element); + observeBackground(element); } else { // Otherwise, add to the list to watch for class changes - elementsToWatch.push(element); + elementsToWatch.add(element); } }); // Set up observation for class changes only on elements that need it - if (elementsToWatch.length > 0) { + if (elementsToWatch.size > 0) { elementsToWatch.forEach(element => { classObserver.observe(element, { attributes: true, attributeFilter: ['class'] }); }); @@ -75,7 +89,7 @@ export const optmlBackground = { }, 5000); } - return elementsToWatch.length; + return elementsToWatch.size; }, /** @@ -127,10 +141,10 @@ export const optmlBackground = { * Process background selectors and setup observation * @param {Array} bgSelectors - Array of CSS selectors * @param {IntersectionObserver} observer - Intersection observer instance - * @returns {Object} Object containing selectorMap and pendingElements count + * @param {Map>} [selectorMap] - Map the observer records above-fold selectors into; must be the same instance passed to the observer + * @returns {{selectorMap: Map>, pendingElements: number}} Object containing selectorMap and pendingElements count */ - processBackgroundSelectors: function(bgSelectors, observer) { - const selectorMap = new Map(); + processBackgroundSelectors: function(bgSelectors, observer, selectorMap = new Map()) { let pendingElements = 0; if (!bgSelectors || !Array.isArray(bgSelectors) || bgSelectors.length === 0) { diff --git a/assets/js/modules/dom-utils.js b/assets/js/modules/dom-utils.js index e7265438c..b4ed9d816 100644 --- a/assets/js/modules/dom-utils.js +++ b/assets/js/modules/dom-utils.js @@ -36,18 +36,13 @@ export const optmlDomUtils = { const tag = element.tagName.toLowerCase(); - // Optimize class name processing let className = ''; if (element.className && typeof element.className === 'string') { - // Only process if needed - if (element.className.includes('optml-bg-lazyloaded')) { - className = '.' + element.className.trim() - .split(/\s+/) - .filter(cls => cls !== 'optml-bg-lazyloaded') - .join('.'); - } else { - // Avoid unnecessary split/filter/join when no filtering needed - className = '.' + element.className.trim().replace(/\s+/g, '.'); + const classes = element.className.trim() + .split(/\s+/) + .filter(cls => cls && cls !== 'optml-bg-lazyloaded'); + if (classes.length > 0) { + className = '.' + classes.join('.'); } } diff --git a/assets/js/modules/image-detector.js b/assets/js/modules/image-detector.js index cb81f329c..675180e85 100644 --- a/assets/js/modules/image-detector.js +++ b/assets/js/modules/image-detector.js @@ -76,43 +76,83 @@ export const optmlImageDetector = { /** * Setup intersection observer for image detection * @param {Array} aboveTheFoldImages - Array to store above-fold image IDs - * @param {Map} selectorMap - Map for background selectors + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors * @returns {IntersectionObserver} Configured intersection observer */ createIntersectionObserver: function(aboveTheFoldImages, selectorMap) { return new IntersectionObserver(entries => { - entries.forEach(entry => { - if (entry.isIntersecting) { - const element = entry.target; - - // Handle img elements with data-opt-id - if (element.tagName === 'IMG') { - const id = parseInt(element.getAttribute('data-opt-id'), 10); - if (!isNaN(id) && !aboveTheFoldImages.includes(id)) { - aboveTheFoldImages.push(id); - } - } - // Handle background image elements - else if (element.hasAttribute('data-optml-bg-selector')) { - const baseSelector = element.getAttribute('data-optml-bg-selector'); - const specificSelector = element.getAttribute('data-optml-specific-selector'); - - if (baseSelector && specificSelector && selectorMap.has(baseSelector)) { - // Add this specific selector to the above-fold list for this base selector - const aboveTheFoldSelectors = selectorMap.get(baseSelector); - if (!aboveTheFoldSelectors.includes(specificSelector)) { - aboveTheFoldSelectors.push(specificSelector); - optmlLogger.info(`Element with selector "${specificSelector}" is above the fold`); - } - } - } - } - }); + this.recordIntersections(entries, aboveTheFoldImages, selectorMap); }, { threshold: 0.1 // Consider element visible when 10% is in viewport }); }, + /** + * Record the above-fold images and background elements of intersection entries + * @param {Array} entries - Entries reported by the observer + * @param {Array} aboveTheFoldImages - Array to store above-fold image IDs + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors + * @returns {void} + */ + recordIntersections: function(entries, aboveTheFoldImages, selectorMap) { + entries.forEach(entry => { + if (!entry.isIntersecting) { + return; + } + const element = entry.target; + + // Handle img elements with data-opt-id + if (element.tagName === 'IMG') { + const id = parseInt(element.getAttribute('data-opt-id'), 10); + if (!isNaN(id) && !aboveTheFoldImages.includes(id)) { + aboveTheFoldImages.push(id); + } + } + + // An img can also carry a background image, so this is checked independently. + if (element.hasAttribute('data-optml-bg-selector')) { + this.recordAboveFoldBackground(element, selectorMap); + } + }); + }, + + /** + * Record elements observed shortly before the observer is disconnected + * @param {IntersectionObserver} observer - Observer created by createIntersectionObserver + * @param {Array} aboveTheFoldImages - Array to store above-fold image IDs + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors + * @returns {Promise} Resolves once the queued entries are recorded + */ + flushIntersectionObserver: async function(observer, aboveTheFoldImages, selectorMap) { + // A new observation is computed only at the next rendering; hidden tabs render no frames, hence the timeout. + await Promise.race([ + new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))), + new Promise(resolve => setTimeout(resolve, 100)) + ]); + this.recordIntersections(observer.takeRecords(), aboveTheFoldImages, selectorMap); + }, + + /** + * Record a background element under every base selector it matches + * @param {Element} element - Above-the-fold background element + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors + * @returns {void} + */ + recordAboveFoldBackground: function(element, selectorMap) { + const specificSelector = element.getAttribute('data-optml-specific-selector'); + if (!specificSelector) { + return; + } + + // An element can match several watchers; each one needs it listed or the server hides it. + selectorMap.forEach((aboveTheFoldSelectors, baseSelector) => { + if (element.matches(baseSelector) && !aboveTheFoldSelectors.includes(specificSelector)) { + aboveTheFoldSelectors.push(specificSelector); + optmlLogger.info(`Element with selector "${specificSelector}" is above the fold`); + } + }); + }, + /** * Observe all images with data-opt-id attributes * @param {IntersectionObserver} observer - Intersection observer instance diff --git a/assets/js/modules/main.js b/assets/js/modules/main.js index ad0c7fb68..48acc6513 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -13,6 +13,11 @@ import { optmlLcp } from './lcp.js'; import { optmlImageDetector } from './image-detector.js'; import { optmlSrcsetDetector } from './srcset-detector.js'; +// The optimizations endpoint rejects the whole payload when these limits are exceeded. +const MAX_BG_URLS_PER_ELEMENT = 3; +const MAX_ABOVE_FOLD_SELECTORS_PER_WATCHER = 100; +const MAX_BG_WATCHERS = 100; + /** * Main detection functionality */ @@ -107,17 +112,12 @@ export const optmlMain = { const aboveTheFoldImages = []; // Create intersection observer - let selectorMap = new Map(); + const selectorMap = new Map(); const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); // Observe Optimole images const { allOptimoleImages } = optmlImageDetector.observeOptimoleImages(observer); - // Detect images with missing dimensions - const imageDimensionsData = optmlImageDetector.detectImageDimensions(allOptimoleImages); - - optmlLogger.info('Images with missing dimensions found:', Object.keys(imageDimensionsData).length); - // Detect images requiring srcset variations (non-lazyload images) const srcsetResult = await optmlSrcsetDetector.detectMissingSrcsets(); const srcsetData = srcsetResult.srcset; @@ -131,22 +131,29 @@ export const optmlMain = { let pendingElements = 0; if (bgSelectors && Array.isArray(bgSelectors) && bgSelectors.length > 0) { - const backgroundResult = optmlBackground.processBackgroundSelectors(bgSelectors, observer); - selectorMap = backgroundResult.selectorMap; + const backgroundResult = optmlBackground.processBackgroundSelectors(bgSelectors, observer, selectorMap); pendingElements = backgroundResult.pendingElements; - // Extract background image URLs - bgImageUrls = optmlBackground.extractBackgroundImageUrls(bgSelectors); - // Adjust wait time based on whether we have pending elements const waitTime = pendingElements > 0 ? 600 : 300; optmlLogger.info(`Waiting ${waitTime}ms for ${pendingElements} pending background elements`); await new Promise(resolve => setTimeout(resolve, waitTime)); + + // Extract after the wait so elements lazyloaded during it are included. + bgImageUrls = optmlBackground.extractBackgroundImageUrls(bgSelectors); } else { // Standard wait time if no background selectors await new Promise(resolve => setTimeout(resolve, 300)); } + // Elements lazyloaded at the end of the wait are not reported yet. + await optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap); + + // Read after the waits so images that finished loading during them have natural dimensions. + const imageDimensionsData = optmlImageDetector.detectImageDimensions(allOptimoleImages); + + optmlLogger.info('Images with missing dimensions found:', Object.keys(imageDimensionsData).length); + // Disconnect observer and clean up event listeners observer.disconnect(); window.removeEventListener('resize', resizeHandler); @@ -185,7 +192,7 @@ export const optmlMain = { l: { i: lcpData.imageId, s: lcpData.bgSelector, - u: lcpData.bgUrls + u: lcpData.bgUrls ? lcpData.bgUrls.slice(0, MAX_BG_URLS_PER_ELEMENT) : lcpData.bgUrls }, m: imageDimensionsData, // m for missing dimensions s: srcsetData, // s for srcset data @@ -221,20 +228,20 @@ export const optmlMain = { const processedBgSelectors = {}; // Process each selector that's present on the page - selectorMap.forEach((specificSelectors, baseSelector) => { + Array.from(selectorMap).slice(0, MAX_BG_WATCHERS).forEach(([baseSelector, specificSelectors]) => { // Initialize the object for this base selector processedBgSelectors[baseSelector] = {}; // For each specific selector, add its URLs if available - specificSelectors.forEach(specificSelector => { + specificSelectors.slice(0, MAX_ABOVE_FOLD_SELECTORS_PER_WATCHER).forEach(specificSelector => { // First, add the selector to indicate it's above the fold processedBgSelectors[baseSelector][specificSelector] = null; // Then, if we have URLs for this selector, add them if (bgImageUrls.has(baseSelector) && bgImageUrls.get(baseSelector).has(specificSelector)) { - processedBgSelectors[baseSelector][specificSelector] = - bgImageUrls.get(baseSelector).get(specificSelector); + processedBgSelectors[baseSelector][specificSelector] = + bgImageUrls.get(baseSelector).get(specificSelector).slice(0, MAX_BG_URLS_PER_ELEMENT); } }); }); diff --git a/assets/src/dashboard/parts/connected/help/index.js b/assets/src/dashboard/parts/connected/help/index.js index 3effea673..83cbba613 100644 --- a/assets/src/dashboard/parts/connected/help/index.js +++ b/assets/src/dashboard/parts/connected/help/index.js @@ -45,15 +45,15 @@ const DOCS_SECTION = [ items: [ { label: optimoleDashboardApp.strings.help.account_item_one, - value: 'https://docs.optimole.com/article/1134-how-optimole-counts-the-number-of-visitors' + value: optimoleDashboardApp.docs_links.visitors_count }, { label: optimoleDashboardApp.strings.help.account_item_two, - value: 'https://docs.optimole.com/article/1008-what-happens-if-i-exceed-plan-limits' + value: optimoleDashboardApp.docs_links.plan_limits }, { label: optimoleDashboardApp.strings.help.account_item_three, - value: 'https://docs.optimole.com/article/1133-visitors-based-plan' + value: optimoleDashboardApp.docs_links.visitors_plan } ] }, @@ -62,15 +62,15 @@ const DOCS_SECTION = [ items: [ { label: optimoleDashboardApp.strings.help.image_processing_item_one, - value: 'https://docs.optimole.com/article/1173-how-to-get-started-with-optimole-in-just-3-steps' + value: optimoleDashboardApp.docs_links.getting_started }, { label: optimoleDashboardApp.strings.help.image_processing_item_two, - value: 'https://docs.optimole.com/article/1068-how-optimole-can-serve-webp-images' + value: optimoleDashboardApp.docs_links.webp }, { label: optimoleDashboardApp.strings.help.image_processing_item_three, - value: 'https://docs.optimole.com/article/1475-adding-watermarks-to-your-images' + value: optimoleDashboardApp.docs_links.watermarks } ] }, @@ -79,15 +79,15 @@ const DOCS_SECTION = [ items: [ { label: optimoleDashboardApp.strings.help.api_item_one, - value: 'https://docs.optimole.com/article/1323-cloud-library-browsing' + value: optimoleDashboardApp.docs_links.cloud_library }, { label: optimoleDashboardApp.strings.help.api_item_two, - value: 'https://docs.optimole.com/article/1191-exclude-from-optimizing-or-lazy-loading' + value: optimoleDashboardApp.docs_links.exclusions }, { label: optimoleDashboardApp.strings.help.api_item_three, - value: 'https://docs.optimole.com/article/1307-custom-integration' + value: optimoleDashboardApp.docs_links.custom_integration } ] } @@ -134,7 +134,7 @@ const Help = () => {

{ optimoleDashboardApp.strings.help.section_two_title }

- { optimoleDashboardApp.strings.help.section_two_sub } + { optimoleDashboardApp.strings.help.section_two_sub }
diff --git a/assets/src/dashboard/parts/connected/settings/Watermark.js b/assets/src/dashboard/parts/connected/settings/Watermark.js index e42000a24..7e0efb54b 100644 --- a/assets/src/dashboard/parts/connected/settings/Watermark.js +++ b/assets/src/dashboard/parts/connected/settings/Watermark.js @@ -63,7 +63,7 @@ const Watermark = () => { className="border border-gray-300 text-gray-700 px-6 py-3 rounded-lg font-medium hover:bg-gray-50" target="_blank" rel="noopener noreferrer" - href="https://docs.optimole.com/article/1475-adding-watermarks-to-your-images" + href={ optimoleDashboardApp.docs_links.watermark_settings } > {options_strings.learn_more} diff --git a/assets/src/global.d.ts b/assets/src/global.d.ts index 541e9aeac..1b1163189 100644 --- a/assets/src/global.d.ts +++ b/assets/src/global.d.ts @@ -27,6 +27,7 @@ export interface IOptimoleDashboardApp { optimoleHome: string optimoleDashHome: string optimoleDashBilling: string + docs_links: DocsLinks days_since_install: string is_offload_media_available: string auto_connect: string @@ -38,6 +39,20 @@ export interface IOptimoleDashboardApp { report_issue_url: string } +export interface DocsLinks { + home: string + visitors_count: string + plan_limits: string + visitors_plan: string + getting_started: string + webp: string + watermarks: string + cloud_library: string + exclusions: string + custom_integration: string + watermark_settings: string +} + export interface Strings { optimole: string version: string diff --git a/assets/src/media/__tests__/admin-page.test.js b/assets/src/media/__tests__/admin-page.test.js new file mode 100644 index 000000000..fa041c329 --- /dev/null +++ b/assets/src/media/__tests__/admin-page.test.js @@ -0,0 +1,38 @@ +/** + * Tests for the Cloud Library admin page script. + */ + +jest.mock( '../scss/admin-page.scss', () => ({}) ); + +const SITE_URL = 'https://example.test'; + +describe( 'Cloud Library admin page (issue #1211)', () => { + let iframe; + let loader; + + beforeAll( () => { + window.optmlAdminPage = { siteUrl: SITE_URL }; + + // The script is printed in the head, before the iframe markup exists. + require( '../admin-page.js' ); + + document.body.innerHTML = '
'; + iframe = document.getElementById( 'om-dam' ); + loader = document.querySelector( '.om-dam-loader' ); + }); + + test( 'reveals the iframe when it loads after the script ran', () => { + iframe.dispatchEvent( new Event( 'load' ) ); + + expect( loader.style.display ).toBe( 'none' ); + expect( iframe.style.display ).toBe( '' ); + }); + + test( 'answers getUrl from an iframe added after the script ran', () => { + const postMessage = jest.spyOn( iframe.contentWindow, 'postMessage' ).mockImplementation( () => {}); + + window.dispatchEvent( new MessageEvent( 'message', { data: { type: 'om-dam', action: 'getUrl' }}) ); + + expect( postMessage ).toHaveBeenCalledWith({ siteUrl: SITE_URL, type: 'om-dam', context: 'browse' }, '*' ); + }); +}); diff --git a/assets/src/media/admin-page.js b/assets/src/media/admin-page.js index f861a2fa1..2d7a6692b 100644 --- a/assets/src/media/admin-page.js +++ b/assets/src/media/admin-page.js @@ -3,12 +3,16 @@ import './scss/admin-page.scss'; const { optmlAdminPage } = window; const { siteUrl } = optmlAdminPage; -const iframe = document.getElementById( 'om-dam' ); -iframe.addEventListener( 'load', function() { +// This runs in the head, before #om-dam exists: `load` does not bubble, so catch it in the capture phase. +document.addEventListener( 'load', function( event ) { + if ( 'om-dam' !== event.target.id ) { + return; + } + document.querySelector( '.om-dam-loader' ).style.display = 'none'; - iframe.style.display = ''; -}); + event.target.style.display = ''; +}, true ); window.addEventListener( 'message', function( event ) { if ( ! event.data ) { @@ -31,5 +35,5 @@ window.addEventListener( 'message', function( event ) { return; } - iframe.contentWindow.postMessage({ siteUrl, type: 'om-dam', context: 'browse' }, '*' ); + document.getElementById( 'om-dam' ).contentWindow.postMessage({ siteUrl, type: 'om-dam', context: 'browse' }, '*' ); }); diff --git a/inc/admin.php b/inc/admin.php index 0641d2599..0ebf66c64 100755 --- a/inc/admin.php +++ b/inc/admin.php @@ -717,7 +717,7 @@ public function add_notice_upgrade() { ?>

- @@ -772,6 +772,8 @@ public function should_show_upgrade() { /** * Build upgrade URL with current user's encoded email. * + * The URL is already localized, so callers must not pass it through tsdk_translate_link() again. + * * @return string Upgrade URL. */ public static function get_upgrade_base_link() { @@ -786,6 +788,42 @@ public static function get_upgrade_base_link() { return $base_url; } + /** + * Build a docs.optimole.com link with UTMs. + * + * Links go to the final docs URL: the old /article/ URLs redirect, and the redirect drops the UTMs. + * + * @param string $path Docs page path, e.g. 'wordpress-plugin/best-format'. + * @param string $campaign The feature the link explains (utm_campaign). + * @param string $medium Where the link is shown (utm_medium). + * + * @return string Docs URL with UTMs. + */ + public static function docs_url( $path, $campaign, $medium ) { + return tsdk_utmify( 'https://docs.optimole.com/' . ltrim( $path, '/' ), $campaign, $medium ); + } + + /** + * Get docs links used by the dashboard app. + * + * @return array Docs URLs with UTMs, by key. + */ + public static function get_dashboard_docs_links() { + return [ + 'home' => self::docs_url( '', 'documentation', 'help' ), + 'visitors_count' => self::docs_url( 'account/how-optimole-counts-the-number-of-visitors', 'visitors-count', 'help' ), + 'plan_limits' => self::docs_url( 'account/what-happens-if-i-exceed-plan-limits', 'plan-limits', 'help' ), + 'visitors_plan' => self::docs_url( 'account/visitors-based-plan', 'visitors-plan', 'help' ), + 'getting_started' => self::docs_url( 'wordpress-plugin/how-to-get-started-with-optimole-in-just-3-steps', 'getting-started', 'help' ), + 'webp' => self::docs_url( 'image-processing/how-optimole-can-serve-webp-images', 'webp', 'help' ), + 'watermarks' => self::docs_url( 'image-processing/adding-watermarks-to-your-images', 'watermark', 'help' ), + 'cloud_library' => self::docs_url( 'wordpress-plugin/cloud-library-browsing', 'cloud-library', 'help' ), + 'exclusions' => self::docs_url( 'wordpress-plugin/exclude-from-optimizing-or-lazy-loading', 'exclusions', 'help' ), + 'custom_integration' => self::docs_url( 'image-processing/how-to-use-the-custom-integration-in-optimole', 'custom-integration', 'help' ), + 'watermark_settings' => self::docs_url( 'image-processing/adding-watermarks-to-your-images', 'watermark', 'settings' ), + ]; + } + /** * Get contact URL. * @@ -1536,6 +1574,7 @@ private function localize_dashboard_app() { 'optimoleDashBilling' => tsdk_translate_link( 'https://dashboard.optimole.com/settings/billing', 'query' ), 'optimoleDashMetrics' => tsdk_translate_link( tsdk_utmify( 'https://dashboard.optimole.com/metrics', 'wp-plugin', 'shortcut' ) ), 'offload_upgrade_url' => tsdk_translate_link( tsdk_utmify( 'https://optimole.com/pricing/', 'offload' ) ), + 'docs_links' => self::get_dashboard_docs_links(), 'days_since_install' => round( ( time() - get_option( 'optimole_wp_install', 0 ) ) / DAY_IN_SECONDS ), 'is_offload_media_available' => $is_offload_media_available, 'auto_connect' => $auto_connect, @@ -1741,7 +1780,7 @@ public function get_bf_notices( $user_plan ) { '' . $promo_code . '', '' . __( '25% discount', 'optimole-wp' ) . '' ), - 'cta_link' => esc_url_raw( tsdk_utmify( tsdk_translate_link( self::get_upgrade_base_link() ), 'bfcm', 'sidebarnotice' ) ), + 'cta_link' => esc_url_raw( tsdk_utmify( self::get_upgrade_base_link(), 'bfcm', 'sidebarnotice' ) ), ]; // The banner shares the SDK dismissal, which resets every year. @@ -1864,13 +1903,13 @@ private function get_dashboard_strings() { '', '', number_format_i18n( 2000 ), - '', + '', '' ), 'account_needed_subtitle_3' => sprintf( /* translators: 1 is the starting anchor tag for the docs link, 2 is the ending anchor tag. */ __( 'Need help? %1$sGetting Started with Optimole%2$s', 'optimole-wp' ), - '', + '', '' ), 'account_needed_subtitle_2' => sprintf( @@ -1914,7 +1953,7 @@ private function get_dashboard_strings() { 'notice_disabled_account' => sprintf( /* translators: 1 anchor tag to pricing, 2 is the ending endin anchor tag, 3 is the bold tag start, 4 ending bold tag, 5 new line tag */ __( '%3$sYour account has been disabled due to exceeding quota.%4$s All images are being redirected to the original unoptimized URL. %5$sPlease %1$supgrade%2$s to re-activate the account.', 'optimole-wp' ), - '', + '', '', '', '', @@ -2014,7 +2053,7 @@ private function get_dashboard_strings() { 'best_format_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'When enabled, Optimole chooses the best format for your images, balancing quality with speed. It tries options like AVIF and WebP to keep visuals sharp and pages fast, though uncached images may take a bit longer to process. %1$sLearn more%2$s.', 'optimole-wp' ), - '', + '', '' ), 'add_filter' => __( 'Add filter', 'optimole-wp' ), @@ -2024,7 +2063,7 @@ private function get_dashboard_strings() { 'cache_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Clears all Optimole’s cached resources (images, JS, CSS). Useful if you made changes to your images and don\'t see those applying on your site. %1$sLearn more%2$s', 'optimole-wp' ), - '', + '', '' ), 'cache_title' => __( 'Clear Cached Resources', 'optimole-wp' ), @@ -2032,7 +2071,7 @@ private function get_dashboard_strings() { 'image_size_notice' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Use this option if you notice images are not cropped correctly after using Optimole. Add the affected image sizes here to automatically adjust and correct their cropping for optimal display. %1$sLearn more%2$s', 'optimole-wp' ), - '', + '', '' ), 'clear_cache_images' => __( 'Clear cached images', 'optimole-wp' ), @@ -2046,13 +2085,13 @@ private function get_dashboard_strings() { 'enable_avif_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Enable this to automatically convert images to the AVIF format on browsers that support it. This format provides quality images with reduced file sizes, and faster webpage loading. %1$sLearn more%2$s', 'optimole-wp' ), - '', + '', '' ), 'enable_bg_lazyload_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Apply lazy loading to CSS background images. The toggle below enables it globally. The selector list is optional and only needed to extend coverage if certain elements are missed. %1$sLearn more%2$s', 'optimole-wp' ), - '', + '', '' ), 'enable_bg_lazyload_title' => __( 'CSS Background Lazy Load', 'optimole-wp' ), @@ -2061,26 +2100,26 @@ private function get_dashboard_strings() { 'enable_noscript_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Enables fallback images for browsers that can\'t handle JavaScript-based lazy loading or related features. Disabling it may resolve conflicts with other plugins or configurations and decrease HTML page size. %1$sLearn more%2$s', 'optimole-wp' ), - '', + '', '' ), // translators: %s is the name of the html tag (e.g:

...

+ ' . self::IFRAME_PLACEHOLDER_CLASS . ''; const SVG_PLACEHOLDER = 'data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20#width#%20#height#%22%20width%3D%22#width#%22%20height%3D%22#height#%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22#width#%22%20height%3D%22#height#%22%20fill%3D%22#fill#%22%2F%3E%3C%2Fsvg%3E'; + /** + * What precedes a start tag attribute: whitespace or, as browsers allow, directly a quoted value. + */ + private const TAG_ATTRIBUTE_SEPARATOR = '(?:\s+|(?<=["\']))'; + /** + * One start tag attribute with its separator. + * + * A quoted value is matched whole, so text inside it is never read as an attribute. An iframe whose + * attribute value starts with a backslash is not matched, so JSON-escaped iframe markup is left as written. + */ + private const TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s"\'>\\\\][^\s>]*))?'; /** * If frame lazyload is present on page. * @@ -374,14 +385,16 @@ public function lazyload_video_replace( $content ) { $video_tags = []; $iframes = []; $videos = []; - preg_match_all( '#(?:\s*)?(?:\s*)?#is', $content, $iframes ); + // Only iframes with no fallback content; one with fallback text is left as written. + preg_match_all( '#(?:\s*)?(?:' . self::TAG_ATTRIBUTE . ')*)\s*/?>(?:\s*)?#i', $content, $iframes ); preg_match_all( '#(?:\s*)?.*?(?:\s*)?#is', $content, $videos ); + $iframe_count = count( $iframes[0] ); $video_tags = array_merge( $iframes[0], $videos[0] ); $search = []; $replace = []; - foreach ( $video_tags as $video_tag ) { + foreach ( $video_tags as $index => $video_tag ) { if ( ! $this->should_lazyload_iframe( $video_tag ) ) { continue; @@ -389,23 +402,12 @@ public function lazyload_video_replace( $content ) { if ( preg_match( "/ data-opt-src=['\"]/is", $video_tag ) ) { continue; } - $should_add_noscript = true; $original_tag = $video_tag; - // replace the src and add the data-opt-src attribute - if ( strpos( $video_tag, 'iframe' ) !== false ) { - $video_tag = preg_replace( '/iframe(.*?)src=/is', 'iframe$1 src="about:blank" data-opt-src=', $video_tag ); - } elseif ( strpos( $video_tag, 'video' ) !== false ) { - if ( strpos( $video_tag, 'source' ) !== false ) { - if ( strpos( $video_tag, 'preload' ) === false ) { - $video_tag = preg_replace( '/video(.*?)>/is', 'video$1 preload="metadata">', $video_tag, 1 ); - $should_add_noscript = false; - } else { - continue; - } - } else { - $video_tag = preg_replace( '/video(.*?)src=/is', 'video$1 data-opt-src=', $video_tag ); - } + $lazyloaded = $this->lazyload_media_element( $video_tag, $index < $iframe_count ); + if ( null === $lazyloaded ) { + continue; } + list( $video_tag, $should_add_noscript ) = $lazyloaded; if ( $this->should_add_noscript( $video_tag ) && $should_add_noscript ) { $video_tag .= ''; } @@ -419,6 +421,46 @@ public function lazyload_video_replace( $content ) { return $content; } + /** + * Move the src of a matched iframe or video to data-opt-src, or ask a sourced video to preload metadata only. + * + * @param string $element The iframe or video element. + * @param bool $is_iframe Whether the element was matched as an iframe. + * + * @return array{0: string, 1: bool}|null The element and whether it gets a noscript copy, or null to leave it untouched. + */ + private function lazyload_media_element( string $element, bool $is_iframe ): ?array { + if ( $is_iframe && strpos( $element, 'iframe' ) !== false ) { + return [ $this->replace_start_tag_src( $element, 'iframe', ' src="about:blank" data-opt-src' ), true ]; + } + if ( $is_iframe || strpos( $element, 'video' ) === false ) { + return [ $element, true ]; + } + if ( strpos( $element, 'source' ) === false ) { + return [ $this->replace_start_tag_src( $element, 'video', ' data-opt-src' ), true ]; + } + if ( strpos( $element, 'preload' ) !== false ) { + return null; + } + + return [ preg_replace( '#^((?:\s*)?(?:' . self::TAG_ATTRIBUTE . ')*)\s*/?)>#i', '$1 preload="metadata">', $element, 1 ) ?? $element, false ]; + } + + /** + * Replace the name of the src attribute in the element's start tag. + * + * @param string $element Element markup, starting with its start tag. + * @param string $tag_name The element's tag name. + * @param string $replacement Markup written in place of the attribute name, before its `=`. + * + * @return string The element, unchanged when its start tag has no src attribute. + */ + private function replace_start_tag_src( string $element, string $tag_name, string $replacement ): string { + $pattern = '#^((?:\s*)?<' . $tag_name . '(?>(?:(?!\s*src\s*=)' . self::TAG_ATTRIBUTE . ')*)' . self::TAG_ATTRIBUTE_SEPARATOR . ')src(?=\s*=)#i'; + + return preg_replace( $pattern, '$1' . $replacement, $element, 1 ) ?? $element; + } + /** * Check if the lazyload is allowed for this url. * diff --git a/inc/manager.php b/inc/manager.php index b55c2de33..3adb2f2f2 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -564,7 +564,7 @@ public function replace_content( $html, $partial = false ) { } $marker = Lazyload::get_marker(); - if ( ! empty( $personalized_bg_css ) && ( $start_pos = strpos( $html, $marker ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found + if ( null !== $personalized_bg_css && ( $start_pos = strpos( $html, $marker ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found // We replace the general bg css with the personalized one. if ( ( $end_pos = strpos( $html, $marker, $start_pos + strlen( $marker ) ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found $html = substr_replace( diff --git a/inc/rest.php b/inc/rest.php index 50e086529..c719d432a 100644 --- a/inc/rest.php +++ b/inc/rest.php @@ -9,6 +9,7 @@ use Optimole\Sdk\Resource\ImageProperty\ResizeTypeProperty; use Optimole\Sdk\ValueObject\Position; +use OptimoleWP\BgOptimizer\Lazyload; use OptimoleWP\PageProfiler\Profile; /** @@ -1013,7 +1014,7 @@ public function optimizations( WP_REST_Request $request ) { // save just the first 6 images, see https://github.com/Codeinwp/optimole-service/issues/1588#issuecomment-3357110865 $above_fold_images = array_slice( $above_fold_images, 0, 6 ); $above_fold_images = array_values( array_map( 'intval', array_filter( $above_fold_images, 'is_numeric' ) ) ); - if ( count( $bg_selectors ) > 100 ) { + if ( count( $bg_selectors ) > Lazyload::MAX_WATCHERS ) { return $this->response( 'Background selectors limit exceeded', 'error' ); } if ( $url === Profile::PLACEHOLDER ) { @@ -1026,7 +1027,7 @@ public function optimizations( WP_REST_Request $request ) { if ( ! in_array( $selector, $current_selectors, true ) ) { return $this->response( 'Invalid background selector', 'error' ); } - if ( count( $above_fold_bg_selectors ) > 100 ) { + if ( count( $above_fold_bg_selectors ) > Lazyload::MAX_ABOVE_FOLD_SELECTORS ) { return $this->response( 'Above fold background selectors limit exceeded', 'error' ); } $selector = strip_tags( $selector ); diff --git a/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index 0c57a65e2..15f8081f1 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -18,6 +18,21 @@ class Lazyload { */ const SAFE_SELECTOR_PATTERN = '/^(?:[\w\-#. >\x{00A0}-\x{10FFFF}]|:nth-of-type\(\d+\))+$/u'; + /** + * Most watchers the profiler reports per device; the frontend cuts the rest. + */ + const MAX_WATCHERS = 100; + + /** + * Most above-fold selectors the profiler reports per watcher; the frontend cuts the rest. + */ + const MAX_ABOVE_FOLD_SELECTORS = 100; + + /** + * Widest viewport in px the profiler counts as mobile (MOBILE_BREAKPOINT in device.js). + */ + private const DEVICE_BREAKPOINT = 600; + /** * Check whether a client-reported selector is a plain selector safe to embed in the stylesheet as-is. * @@ -46,9 +61,9 @@ public static function get_marker(): string { /** * Get the current personalized CSS for lazy loading. * - * @return string The personalized CSS. + * @return string|null The personalized CSS, or null when the general CSS must stay. */ - public static function get_current_personalized_css() { + public static function get_current_personalized_css(): ?string { return self::get_personalized_css( Profile::get_current_profile_data() ); } /** @@ -56,9 +71,9 @@ public static function get_current_personalized_css() { * * @param array $data Profile data. * - * @return string The personalized CSS. + * @return string|null The personalized CSS ('' hides nothing), or null when every device was voided and the general CSS must stay. */ - public static function get_personalized_css( $data ) { + public static function get_personalized_css( $data ): ?string { $lazyload_selectors = array_values( Optml_Lazyload_Replacer::get_background_lazyload_selectors() ); $lazyload_selectors = array_fill_keys( $lazyload_selectors, true ); $css_selectors = []; @@ -94,35 +109,27 @@ public static function get_personalized_css( $data ) { Links::add_link( [ 'url' => $url, 'priority' => 'high' ] ); } - $hide_rule = ' { background-image: none !important; }'; - $mobile = $css_selectors[ Profile::DEVICE_TYPE_MOBILE ]; - $desktop = $css_selectors[ Profile::DEVICE_TYPE_DESKTOP ]; - - // Keep the surviving rule scoped when the other device was voided. - if ( $tainted[ Profile::DEVICE_TYPE_MOBILE ] !== $tainted[ Profile::DEVICE_TYPE_DESKTOP ] ) { - if ( $tainted[ Profile::DEVICE_TYPE_MOBILE ] ) { - return empty( $desktop ) ? '' : '@media (min-width: 600px) { ' . implode( ',', $desktop ) . $hide_rule . ' }'; - } - return empty( $mobile ) ? '' : '@media (max-width: 600px) { ' . implode( ',', $mobile ) . $hide_rule . ' }'; + if ( ! in_array( false, $tainted, true ) ) { + return null; } - $mobile_selectors = implode( ',', $mobile ); - $desktop_selectors = implode( ',', $desktop ); + $hide_rule = ' { background-image: none !important; }'; + $mobile_selectors = implode( ',', $css_selectors[ Profile::DEVICE_TYPE_MOBILE ] ); + $desktop_selectors = implode( ',', $css_selectors[ Profile::DEVICE_TYPE_DESKTOP ] ); if ( $mobile_selectors === $desktop_selectors ) { - return empty( $mobile_selectors ) ? '' : $mobile_selectors . $hide_rule; + return $mobile_selectors === '' ? '' : $mobile_selectors . $hide_rule; } - // if any of those are empty, return the other one - if ( empty( $mobile_selectors ) ) { - return $desktop_selectors . $hide_rule; + + // A device without selectors hides nothing on purpose (voided or capped), so the other rule stays in its media query. + $media_queries = []; + if ( $mobile_selectors !== '' ) { + $media_queries[] = '@media (max-width: ' . self::DEVICE_BREAKPOINT . 'px) { ' . $mobile_selectors . $hide_rule . ' }'; } - if ( empty( $desktop_selectors ) ) { - return $mobile_selectors . $hide_rule; + if ( $desktop_selectors !== '' ) { + $media_queries[] = '@media (min-width: ' . ( self::DEVICE_BREAKPOINT + 1 ) . 'px) { ' . $desktop_selectors . $hide_rule . ' }'; } - - // generate media query for desktop and mobile - $media_query = '@media (max-width: 600px) { ' . $mobile_selectors . $hide_rule . ' } @media (min-width: 600px) { ' . $desktop_selectors . $hide_rule . ' }'; - return $media_query; + return implode( ' ', $media_queries ); } /** * Build the background-hide selectors for one device. @@ -139,15 +146,25 @@ private static function collect_device_selectors( array $personalized_selectors, if ( ! isset( $lazyload_selectors[ $selector ] ) ) { continue; } - if ( empty( $above_fold_selectors ) ) { - $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)'; + // A full list may have been cut, so hiding the watcher could delay unlisted above-fold elements. + if ( count( $above_fold_selectors ) >= self::MAX_ABOVE_FOLD_SELECTORS ) { continue; } + // One rule per watcher: a separate rule per element would still hide the watcher's other above-fold elements. + $exemptions = ''; foreach ( $above_fold_selectors as $above_fold_selector => $bg_urls ) { if ( ! self::is_safe_selector( $above_fold_selector ) ) { return null; } - $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(' . $above_fold_selector . '):not(.optml-bg-lazyloaded)'; + $exemptions .= ':not(' . $above_fold_selector . ')'; + } + $css_selectors[] = 'html ' . strip_tags( $selector ) . $exemptions . ':not(.optml-bg-lazyloaded)'; + } + + // This CSS replaces the generic one, so unlisted watchers keep it unless the watcher list may have been cut. + if ( count( $personalized_selectors ) < self::MAX_WATCHERS ) { + foreach ( array_keys( array_diff_key( $lazyload_selectors, $personalized_selectors ) ) as $selector ) { + $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)'; } } diff --git a/package-lock.json b/package-lock.json index 0c0a8ae61..62826add8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,7 +14,7 @@ "usehooks-ts": "^2.9.1" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.1", "@semantic-release/changelog": "^5.0.1", "@semantic-release/exec": "^5.0.0", "@semantic-release/git": "^9.0.0", @@ -3285,13 +3285,13 @@ } }, "node_modules/@playwright/test": { - "version": "1.50.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.50.1.tgz", - "integrity": "sha512-Jii3aBg+CEDpgnuDxEp/h7BimHcUTDlpEtce89xEumlJ5ef2hqepZ+PWp1DDpYC/VO9fmWVI1IlEaoI5fK9FXQ==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz", + "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.50.1" + "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" @@ -22408,13 +22408,13 @@ } }, "node_modules/playwright": { - "version": "1.50.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.50.1.tgz", - "integrity": "sha512-G8rwsOQJ63XG6BbKj2w5rHeavFjy5zynBA9zsJMMtBoe/Uf757oG12NXz6e6OirF7RCrTVAKFXbLmn1RbL7Qaw==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.50.1" + "playwright-core": "1.61.1" }, "bin": { "playwright": "cli.js" @@ -22439,9 +22439,9 @@ } }, "node_modules/playwright/node_modules/playwright-core": { - "version": "1.50.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.50.1.tgz", - "integrity": "sha512-ra9fsNWayuYumt+NiM069M6OkcRb1FZSK8bgi66AtpFoWkg2+y0bJSNmkFrWhMbEBbVKC/EruAHH3g0zmtwGmQ==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", "dev": true, "license": "Apache-2.0", "bin": { @@ -32765,12 +32765,12 @@ "dev": true }, "@playwright/test": { - "version": "1.50.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.50.1.tgz", - "integrity": "sha512-Jii3aBg+CEDpgnuDxEp/h7BimHcUTDlpEtce89xEumlJ5ef2hqepZ+PWp1DDpYC/VO9fmWVI1IlEaoI5fK9FXQ==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz", + "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==", "dev": true, "requires": { - "playwright": "1.50.1" + "playwright": "1.61.1" } }, "@pmmmwh/react-refresh-webpack-plugin": { @@ -47090,19 +47090,19 @@ } }, "playwright": { - "version": "1.50.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.50.1.tgz", - "integrity": "sha512-G8rwsOQJ63XG6BbKj2w5rHeavFjy5zynBA9zsJMMtBoe/Uf757oG12NXz6e6OirF7RCrTVAKFXbLmn1RbL7Qaw==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", "dev": true, "requires": { "fsevents": "2.3.2", - "playwright-core": "1.50.1" + "playwright-core": "1.61.1" }, "dependencies": { "playwright-core": { - "version": "1.50.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.50.1.tgz", - "integrity": "sha512-ra9fsNWayuYumt+NiM069M6OkcRb1FZSK8bgi66AtpFoWkg2+y0bJSNmkFrWhMbEBbVKC/EruAHH3g0zmtwGmQ==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", "dev": true } } diff --git a/package.json b/package.json index 7ae2996a0..f4ac7b606 100755 --- a/package.json +++ b/package.json @@ -49,7 +49,7 @@ "make-pot": "docker run --user root --rm --volume $(pwd):/var/www/html/optimole-wp wordpress:cli bash -c 'php -d memory_limit=512M $(which wp) --version --allow-root && wp i18n make-pot optimole-wp ./optimole-wp/languages/optimole-wp.pot --include=inc,assets/src --allow-root --domain=optimole-wp'" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.1", "@semantic-release/changelog": "^5.0.1", "@semantic-release/exec": "^5.0.0", "@semantic-release/git": "^9.0.0", diff --git a/tests/test-bg-selector.php b/tests/test-bg-selector.php index f03680e2e..f1cb2a3bc 100644 --- a/tests/test-bg-selector.php +++ b/tests/test-bg-selector.php @@ -127,9 +127,153 @@ public function test_personalized_css_drops_injected_selectors(): void { ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertStringNotContainsString( self::PAYLOAD, $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); + } + + /** + * Issue 1216: all above-fold elements of a watcher are exempted in one rule, since a separate + * rule per element would still hide the other elements. + */ + public function test_personalized_css_exempts_all_above_fold_elements_in_one_rule(): void { + $device_data = [ 'bg' => [ self::WATCHER => [ '#hero-a' => [], '#hero-b' => [] ] ] ]; + + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => $device_data, + Profile::DEVICE_TYPE_DESKTOP => $device_data, + ] + ); + + $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(#hero-a):not(#hero-b):not(.optml-bg-lazyloaded)', $css ); + $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(#hero-a):not(.optml-bg-lazyloaded)', $css ); + $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(#hero-b):not(.optml-bg-lazyloaded)', $css ); + } + + /** + * A watcher the profile does not list keeps its generic hide rule while the watcher list is below the cap. + */ + public function test_personalized_css_keeps_generic_rule_for_unlisted_watchers(): void { + $device_data = [ 'bg' => [ '.bg-0' => [ '#hero' => [] ] ] ]; + + $css = $this->get_css_with_watchers( 1, $device_data ); + + $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded)', $css ); + $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css ); + } + + /** + * When the profile lists the maximum number of watchers, the client may have cut others, so unlisted + * watchers get no hide rule. + */ + public function test_personalized_css_skips_unlisted_watchers_when_watcher_list_is_full(): void { + $watchers = array_map( + static function ( int $index ): string { + return '.bg-' . $index; + }, + range( 0, Lazyload::MAX_WATCHERS ) + ); + $bg = array_fill_keys( array_slice( $watchers, 0, Lazyload::MAX_WATCHERS ), [] ); + $bg['.bg-0'] = [ '#hero' => [] ]; + + $css = $this->get_css_with_watchers( Lazyload::MAX_WATCHERS + 1, [ 'bg' => $bg ] ); + + $this->assertStringNotContainsString( 'html .bg-' . Lazyload::MAX_WATCHERS . ':', $css ); + $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':', $css ); + $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css ); + $this->assertStringContainsString( 'html .bg-1:not(.optml-bg-lazyloaded)', $css ); + } + + /** + * A watcher whose above-fold list hit the cap may be missing above-fold elements, so it gets no hide rule. + */ + public function test_personalized_css_skips_watcher_with_full_above_fold_list(): void { + $above_fold = []; + foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) { + $above_fold[ '#hero-' . $index ] = []; + } + $device_data = [ + 'bg' => [ + '.bg-0' => $above_fold, + '.bg-1' => array_slice( $above_fold, 0, Lazyload::MAX_ABOVE_FOLD_SELECTORS - 1 ), + ], + ]; + + $css = $this->get_css_with_watchers( 2, $device_data ); + + $this->assertStringNotContainsString( 'html .bg-0:', $css ); + $this->assertStringContainsString( 'html .bg-1:not(#hero-1)', $css ); + } + + /** + * When one device's watcher hit the above-fold cap, the other device's hide rule stays in its media query. + */ + public function test_personalized_css_scopes_other_device_rule_when_one_device_is_capped(): void { + $above_fold = []; + foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) { + $above_fold[ '#hero-' . $index ] = []; + } + $only_watcher = static function (): array { + return [ '.bg-0' ]; + }; + add_filter( 'optml_lazyload_bg_selectors', $only_watcher ); + $this->reset_background_selectors(); + + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => [ 'bg' => [ '.bg-0' => $above_fold ] ], + Profile::DEVICE_TYPE_DESKTOP => [ 'bg' => [ '.bg-0' => array_slice( $above_fold, 0, Lazyload::MAX_ABOVE_FOLD_SELECTORS - 1 ) ] ], + ] + ); + remove_filter( 'optml_lazyload_bg_selectors', $only_watcher ); + + $this->assertIsString( $css ); + $this->assertStringStartsWith( '@media (min-width: 601px) { html .bg-0:not(#hero-1)', $css ); + $this->assertStringNotContainsString( 'max-width', $css ); + } + + /** + * The profiler counts a 600px viewport as mobile, so only the mobile rule applies there. + */ + public function test_personalized_css_device_media_queries_do_not_overlap(): void { + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => [ 'bg' => [ self::WATCHER => [ '#hero-mobile' => [] ] ] ], + Profile::DEVICE_TYPE_DESKTOP => [ 'bg' => [ self::WATCHER => [ '#hero-desktop' => [] ] ] ], + ] + ); + + $this->assertIsString( $css ); + $this->assertStringContainsString( '@media (max-width: 600px) { html ' . self::WATCHER . ':not(#hero-mobile)', $css ); + $this->assertStringContainsString( '@media (min-width: 601px) { html ' . self::WATCHER . ':not(#hero-desktop)', $css ); + } + + /** + * Build the personalized CSS for both devices with extra watchers .bg-0 … .bg-{count-1} registered. + * + * @param int $count Number of extra watchers to register. + * @param array $device_data Profile data used for both devices. + * + * @return string Personalized CSS. + */ + private function get_css_with_watchers( int $count, array $device_data ): string { + $add_watchers = static function ( array $selectors ) use ( $count ): array { + foreach ( range( 0, $count - 1 ) as $index ) { + $selectors[] = '.bg-' . $index; + } + return $selectors; + }; + add_filter( 'optml_lazyload_bg_selectors', $add_watchers ); + $this->reset_background_selectors(); + + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => $device_data, + Profile::DEVICE_TYPE_DESKTOP => $device_data, + ] + ); + remove_filter( 'optml_lazyload_bg_selectors', $add_watchers ); + + return $css; } /** @@ -151,8 +295,7 @@ public function test_personalized_css_drops_injected_lcp_selector(): void { ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); } /** @@ -175,8 +318,7 @@ public function test_personalized_css_drops_rule_when_any_selector_unsafe(): voi ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); } /** @@ -200,7 +342,7 @@ public function test_personalized_css_scopes_surviving_device_to_media_query(): $this->assertStringNotContainsString( 'background:red', $css ); $this->assertStringNotContainsString( self::PAYLOAD, $css ); // The surviving desktop rule must stay desktop-scoped and not apply on phones. - $this->assertStringStartsWith( '@media (min-width: 600px) {', $css ); + $this->assertStringStartsWith( '@media (min-width: 601px) {', $css ); $this->assertStringNotContainsString( '@media (max-width: 600px)', $css ); // The safe above-fold and LCP selectors are still rendered (the gating must not over-reject them). $this->assertStringContainsString( ':not(#hero):not(.optml-bg-lazyloaded)', $css ); diff --git a/tests/test-dam.php b/tests/test-dam.php index 6313bca56..94bbc17bf 100644 --- a/tests/test-dam.php +++ b/tests/test-dam.php @@ -136,6 +136,19 @@ public function test_iframe_url_all_cloud_sites_enabled() { $this->assertEmpty( $data['sites'] ); } + public function test_dashboard_page_renders_loader_before_iframe_issue_1211() { + ob_start(); + $this->dam->render_dashboard_page(); + $html = ob_get_clean(); + + $loader = strpos( $html, 'class="om-dam-loader"' ); + $iframe = strpos( $html, 'id="om-dam"' ); + + $this->assertNotFalse( $loader ); + $this->assertNotFalse( $iframe ); + $this->assertLessThan( $iframe, $loader ); + } + public function test_insert_attachments() { foreach ( $this->inserted_ids as $index => $id ) { $this->assertIsInt( $id ); diff --git a/tests/test-docs-links.php b/tests/test-docs-links.php new file mode 100644 index 000000000..84146f9be --- /dev/null +++ b/tests/test-docs-links.php @@ -0,0 +1,89 @@ +assertSame( + 'https://docs.optimole.com/wordpress-plugin/best-format?utm_source=wpadmin&utm_medium=settings&utm_campaign=best-format&utm_content=docsoptimolecomwordpress-pluginbest-format', + Optml_Admin::docs_url( 'wordpress-plugin/best-format', 'best-format', 'settings' ) + ); + } + + /** + * A settings description links to its current docs page with UTMs. + */ + public function test_settings_description_links_to_current_page() { + $strings = $this->get_dashboard_strings(); + + $this->assertStringContainsString( + 'href="https://docs.optimole.com/wordpress-plugin/best-format?utm_source=wpadmin&utm_medium=settings&utm_campaign=best-format&utm_content=docsoptimolecomwordpress-pluginbest-format"', + $strings['options_strings']['best_format_desc'] + ); + } + + /** + * No dashboard string links to an old /article/ URL, and every docs link has UTMs. + */ + public function test_no_string_uses_old_article_urls() { + $strings = wp_json_encode( $this->get_dashboard_strings(), JSON_UNESCAPED_SLASHES ); + + $this->assertStringNotContainsString( 'docs.optimole.com/article/', $strings ); + // Curly quotes make the browser read the target as a window named ”_blank”, so every click reuses one tab. + $this->assertStringNotContainsString( 'target=\u201d', $strings ); + preg_match_all( '#href=\\\\"(https://docs\.optimole\.com/[^"\\\\]*)#', $strings, $links ); + $this->assertNotEmpty( $links[1] ); + foreach ( $links[1] as $link ) { + $this->assertStringContainsString( 'utm_source=wpadmin', $link ); + } + } + + /** + * The dashboard app gets the Help tab and Watermark docs links with UTMs. + * + * @covers Optml_Admin::get_dashboard_docs_links + */ + public function test_dashboard_docs_links() { + $links = Optml_Admin::get_dashboard_docs_links(); + + $this->assertSame( + 'https://docs.optimole.com/image-processing/how-to-use-the-custom-integration-in-optimole?utm_source=wpadmin&utm_medium=help&utm_campaign=custom-integration&utm_content=docsoptimolecomimage-processinghow-to-use-the-custom-integration-in-optimole', + $links['custom_integration'] + ); + $this->assertStringContainsString( 'utm_medium=settings&utm_campaign=watermark', $links['watermark_settings'] ); + foreach ( $links as $link ) { + $this->assertStringStartsWith( 'https://docs.optimole.com/', $link ); + $this->assertStringNotContainsString( '/article/', $link ); + $this->assertStringContainsString( 'utm_source=wpadmin', $link ); + } + } + + /** + * Get the dashboard strings. + * + * @return array Dashboard strings. + */ + private function get_dashboard_strings() { + $method = new ReflectionMethod( Optml_Admin::class, 'get_dashboard_strings' ); + $method->setAccessible( true ); + + return $method->invoke( new Optml_Admin() ); + } +} diff --git a/tests/test-lazyload.php b/tests/test-lazyload.php index a7bded325..df06e0b05 100644 --- a/tests/test-lazyload.php +++ b/tests/test-lazyload.php @@ -516,6 +516,58 @@ public function test_lazyload_iframe_exclusion() { $this->assertStringNotContainsString( '