From fa72ad5eb6e8ff26e474f074f751bc0493f4159d Mon Sep 17 00:00:00 2001 From: Chuck Carpenter Date: Wed, 11 Nov 2026 16:26:06 +0100 Subject: [PATCH 1/5] Stop the modal overlay from polling every frame while idle The overlay ran a requestAnimationFrame loop for as long as a modal step was open, re-measuring its highlights 60 times a second on a still page. It now follows them through autoUpdate, the event-driven tracker steps already use, plus a ResizeObserver on their scroll parents, and only asks for frames while a glide between steps is running. In Chrome at 4x CPU throttle, an open tour on a still page goes from 300 frames and 88 ms of main-thread time per 5 s to 0 frames and 2.5 ms. Start, next, and scroll timings are unchanged. Costs about 85 bytes gz. Co-Authored-By: Claude Opus 5.5 --- shepherd.js/src/components/shepherd-modal.ts | 41 +++++-- shepherd.js/src/utils/position.ts | 2 +- .../unit/components/shepherd-modal.spec.js | 104 ++++++++++++++++-- 3 files changed, 130 insertions(+), 17 deletions(-) diff --git a/shepherd.js/src/components/shepherd-modal.ts b/shepherd.js/src/components/shepherd-modal.ts index 3e9b0f47b..821423b45 100644 --- a/shepherd.js/src/components/shepherd-modal.ts +++ b/shepherd.js/src/components/shepherd-modal.ts @@ -1,4 +1,5 @@ import { makeOverlayPath } from '../utils/overlay-path.ts'; +import { autoUpdate } from '../utils/position.ts'; import type { Step } from '../step.ts'; import './shepherd-modal.css'; @@ -78,6 +79,7 @@ const PATH_NUMBER = /-?[\d.]+(e-\d+)?/g; export function createShepherdModal(container: HTMLElement): ShepherdModalAPI { let rafId: number | undefined; + let stopTracking: (() => void)[] = []; let currentPath = ''; // Memoizes the chain of scroll parents of a highlighted element for the // lifetime of a single step. Reset in `_cleanupStepEventListeners`. @@ -122,7 +124,7 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI { : to; // Writing `d` invalidates layout even when the value is unchanged, and this - // runs every frame. + // runs every frame of a glide, a scroll or an animation. if (d !== currentPath) { currentPath = d; pathEl.setAttribute('d', d); @@ -300,6 +302,8 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI { if (rafId) { cancelAnimationFrame(rafId); } + stopTracking.forEach((stop) => stop()); + stopTracking = []; // Scroll parents are only memoized for the duration of a single step. _stepScrollParents = new WeakMap(); @@ -319,7 +323,7 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI { const iframeOffset = _getIframeOffset(step.target); const targetScrollParent = _cachedScrollParents(step.target)[0] ?? null; - const rafLoop = () => { + const update = () => positionModal( modalOverlayOpeningPadding, modalOverlayOpeningRadius, @@ -329,10 +333,30 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI { step.target, step._resolvedExtraHighlightElements ); - rafId = requestAnimationFrame(rafLoop); + // A glide tweens the path in script, so it needs every frame until it lands. + const glide = () => { + update(); + rafId = glideEnd > Date.now() ? requestAnimationFrame(glide) : undefined; }; - rafLoop(); + glide(); + + // Otherwise the opening only moves when a highlight does, which `autoUpdate` + // reports without polling, so an open tour on a still page does no work. + const highlights = [ + ...new Set([step.target, ...(step._resolvedExtraHighlightElements ?? [])]) + ].filter((el): el is HTMLElement => el?.nodeType === Node.ELEMENT_NODE); + stopTracking = highlights.map((el) => autoUpdate(el, element, update)); + + // A scroll parent that resizes crops a highlight without moving it. + if (typeof ResizeObserver === 'function' && highlights.length) { + const resizes = new ResizeObserver(update); + highlights + .flatMap((el) => _cachedScrollParents(el)) + .forEach((scrollParent) => resizes.observe(scrollParent)); + stopTracking.push(() => resizes.disconnect()); + } + touchStep = step; window.addEventListener('touchmove', _preventModalBodyTouch, { passive: false @@ -445,10 +469,11 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI { * * Resolving inline would be prohibitively expensive: the containment check in * `positionModal` is O(n^2) over the highlighted elements and runs on every - * animation frame, while each walk costs one `window.getComputedStyle` call - * per ancestor. The answer cannot change between frames of a step, so it is - * resolved once per element instead — matching the once-per-step contract the - * target already has in `_styleForStep`. + * frame of a glide or a scroll, while each walk costs one + * `window.getComputedStyle` call per ancestor. The answer cannot change + * between frames of a step, so it is resolved once per element instead — + * matching the once-per-step contract the target already has in + * `_styleForStep`. */ function _cachedScrollParents(el?: HTMLElement | null): HTMLElement[] { // `nodeType`, not `instanceof`, so a target in a same-origin iframe counts. diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts index 7ee4a3d74..19335489b 100644 --- a/shepherd.js/src/utils/position.ts +++ b/shepherd.js/src/utils/position.ts @@ -847,7 +847,7 @@ function observeMove(element: Element, onMove: () => void) { */ export function autoUpdate( reference: Element, - floating: HTMLElement, + floating: Element, update: () => void ) { const win = getWindow(floating); diff --git a/shepherd.js/test/unit/components/shepherd-modal.spec.js b/shepherd.js/test/unit/components/shepherd-modal.spec.js index 3d670b785..fe00c019d 100644 --- a/shepherd.js/test/unit/components/shepherd-modal.spec.js +++ b/shepherd.js/test/unit/components/shepherd-modal.spec.js @@ -200,6 +200,92 @@ describe('components/ShepherdModal', () => { expect(path().getAttribute('d')).toBe(settled(0, 0, 0, 0)); }); + + describe('between glides', () => { + let frames; + + beforeEach(() => { + frames = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation( + (callback) => frames.push(callback) + ); + }); + + function runFrames() { + const pending = frames; + frames = []; + pending.forEach((callback) => callback()); + } + + it('asks for no frames while the target stays still', () => { + modal.setupForStep(makeStep(rect(200, 300, 50, 50))); + + expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50)); + expect(frames).toHaveLength(0); + }); + + it('asks for frames until a glide lands, then stops', () => { + setDuration('1s'); + modal.setupForStep(makeStep(rect(0, 0, 100, 100))); + modal.setupForStep(makeStep(rect(200, 300, 50, 50))); + + for (let i = 0; i < 4; i++) { + expect(frames, 'mid glide').toHaveLength(1); + now += 250; + runFrames(); + } + + expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50)); + expect(frames, 'landed').toHaveLength(0); + }); + + it('follows a target that scrolls', () => { + const step = makeStep(rect(200, 300, 50, 50)); + modal.setupForStep(step); + + step.target.getBoundingClientRect = () => rect(200, 100, 50, 50); + window.dispatchEvent(new Event('scroll')); + + expect(path().getAttribute('d')).toBe(settled(200, 100, 50, 50)); + }); + + it('follows an extra highlight that scrolls on its own', () => { + const step = makeStep(rect(200, 300, 50, 50)); + const extra = document.createElement('div'); + extra.getBoundingClientRect = () => rect(400, 100, 20, 20); + document.body.append(extra); + step._resolvedExtraHighlightElements = [extra]; + modal.setupForStep(step); + + extra.getBoundingClientRect = () => rect(400, 40, 20, 20); + window.dispatchEvent(new Event('scroll')); + + expect(path().getAttribute('d')).toContain('M400,40'); + extra.remove(); + }); + + it('stops following once hidden', () => { + const step = makeStep(rect(200, 300, 50, 50)); + modal.setupForStep(step); + modal.hide(); + + step.target.getBoundingClientRect = () => rect(200, 100, 50, 50); + window.dispatchEvent(new Event('scroll')); + + expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50)); + }); + + it('follows only the newest step', () => { + const first = makeStep(rect(0, 0, 100, 100)); + modal.setupForStep(first); + modal.setupForStep(makeStep(rect(200, 300, 50, 50))); + + first.target.getBoundingClientRect = () => rect(10, 10, 100, 100); + window.dispatchEvent(new Event('scroll')); + + expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50)); + }); + }); }); describe('closeModalOpening()', function () { @@ -1511,11 +1597,8 @@ describe('components/ShepherdModal', () => { expect(modal.getElement()).not.toHaveClass('shepherd-modal-is-visible'); }); - it('useModalOverlay: true shows the modal and calls _styleForStep', () => { + it('useModalOverlay: true shows the modal and draws the opening', () => { const modal = createShepherdModal(container); - const rafSpy = vi - .spyOn(window, 'requestAnimationFrame') - .mockImplementation(() => 1); const targetEl = document.createElement('div'); container.appendChild(targetEl); @@ -1531,10 +1614,11 @@ describe('components/ShepherdModal', () => { modal.setupForStep(step); expect(modal.getElement()).toHaveClass('shepherd-modal-is-visible'); - // _styleForStep calls rafLoop which calls requestAnimationFrame - expect(rafSpy).toHaveBeenCalled(); + expect( + modal.getElement().querySelector('path').getAttribute('d') + ).toContain('ZM'); - rafSpy.mockRestore(); + modal.destroy(); }); }); @@ -1875,11 +1959,15 @@ describe('components/ShepherdModal', () => { // A target living in the document of `frameWindow`. Only the target's // ownerDocument is swapped: the modal container stays in the real // document, which is what decides where the frame walk has to stop. + // The opening follows the target by listening on its window and document. + const listens = { addEventListener() {}, removeEventListener() {} }; + function startStepInFrame(modal, frameWindow) { const targetEl = document.createElement('div'); container.appendChild(targetEl); + Object.assign(frameWindow, listens); Object.defineProperty(targetEl, 'ownerDocument', { - value: { defaultView: frameWindow }, + value: { defaultView: frameWindow, ...listens }, configurable: true }); From cac3a56f9d13c79d0718a8bd52c436eb30d0e21f Mon Sep 17 00:00:00 2001 From: Chuck Carpenter Date: Wed, 11 Nov 2026 16:42:00 +0100 Subject: [PATCH 2/5] Track scroll parents and stepless overlays without polling Review follow-ups: - A scroll parent can move or resize while its highlight stays put, cropping it differently. Scroll parents now go through autoUpdate alongside the highlights, replacing the ResizeObserver, which saw only resizes. - A step with nothing to highlight had no tracker, so a viewport resize left the old path in place. The overlay itself is now tracked in that case. Co-Authored-By: Claude Opus 5.5 --- shepherd.js/src/components/shepherd-modal.ts | 26 +++++----- .../unit/components/shepherd-modal.spec.js | 48 +++++++++++++++++++ 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/shepherd.js/src/components/shepherd-modal.ts b/shepherd.js/src/components/shepherd-modal.ts index 821423b45..7dd75eb5b 100644 --- a/shepherd.js/src/components/shepherd-modal.ts +++ b/shepherd.js/src/components/shepherd-modal.ts @@ -341,21 +341,23 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI { glide(); - // Otherwise the opening only moves when a highlight does, which `autoUpdate` - // reports without polling, so an open tour on a still page does no work. + // Otherwise the opening only changes when a highlight moves or resizes, or a + // scroll parent does, which crops it without moving it. `autoUpdate` reports + // those without polling, so an open tour on a still page does no work. + // With nothing to highlight, the overlay itself is tracked, since its path + // still has to follow the viewport. const highlights = [ ...new Set([step.target, ...(step._resolvedExtraHighlightElements ?? [])]) ].filter((el): el is HTMLElement => el?.nodeType === Node.ELEMENT_NODE); - stopTracking = highlights.map((el) => autoUpdate(el, element, update)); - - // A scroll parent that resizes crops a highlight without moving it. - if (typeof ResizeObserver === 'function' && highlights.length) { - const resizes = new ResizeObserver(update); - highlights - .flatMap((el) => _cachedScrollParents(el)) - .forEach((scrollParent) => resizes.observe(scrollParent)); - stopTracking.push(() => resizes.disconnect()); - } + const tracked = highlights.length + ? [ + ...new Set([ + ...highlights, + ...highlights.flatMap((el) => _cachedScrollParents(el)) + ]) + ] + : [element]; + stopTracking = tracked.map((el) => autoUpdate(el, element, update)); touchStep = step; window.addEventListener('touchmove', _preventModalBodyTouch, { diff --git a/shepherd.js/test/unit/components/shepherd-modal.spec.js b/shepherd.js/test/unit/components/shepherd-modal.spec.js index fe00c019d..436779f1b 100644 --- a/shepherd.js/test/unit/components/shepherd-modal.spec.js +++ b/shepherd.js/test/unit/components/shepherd-modal.spec.js @@ -264,6 +264,54 @@ describe('components/ShepherdModal', () => { extra.remove(); }); + it('follows a scroll parent that moves while its target stays put', () => { + const scroller = document.createElement('div'); + // happy-dom reports '' for overflow, which would make every ancestor a + // scroll parent. + const computedStyle = window.getComputedStyle.bind(window); + vi.spyOn(window, 'getComputedStyle').mockImplementation((el) => { + const style = computedStyle(el); + const overflow = el === scroller ? 'auto' : 'visible'; + return new Proxy(style, { + get: (target, key) => + /^overflow[XY]?$/.test(key) + ? overflow + : typeof target[key] === 'function' + ? target[key].bind(target) + : target[key] + }); + }); + scroller.getBoundingClientRect = () => rect(0, 0, 1000, 1000); + document.body.append(scroller); + const step = makeStep(rect(200, 300, 50, 50)); + step.target.style.position = ''; + scroller.append(step.target); + modal.setupForStep(step); + expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50)); + // The first check after setup always updates, so settle it first. + window.dispatchEvent(new Event('scroll')); + + scroller.getBoundingClientRect = () => rect(0, 0, 1000, 320); + window.dispatchEvent(new Event('scroll')); + + expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 20)); + scroller.remove(); + }); + + it('redraws a step with no target when the viewport resizes', () => { + const { innerWidth } = window; + const step = makeStep(rect(0, 0, 0, 0)); + step.target = undefined; + modal.setupForStep(step); + expect(path().getAttribute('d')).toMatch(/^M1024,768/); + + window.innerWidth = 1200; + window.dispatchEvent(new Event('resize')); + window.innerWidth = innerWidth; + + expect(path().getAttribute('d')).toMatch(/^M1200,768/); + }); + it('stops following once hidden', () => { const step = makeStep(rect(200, 300, 50, 50)); modal.setupForStep(step); From 8a1addefc97f049ce98e9b40a7ca44bbe1c26551 Mon Sep 17 00:00:00 2001 From: Chuck Carpenter Date: Wed, 11 Nov 2026 16:54:35 +0100 Subject: [PATCH 3/5] Re-arm move detection when a tracked element resizes observeMove watches an IntersectionObserver box sized to the element when it was made. After the element shrank, it could move within that stale box with no event and go unnoticed, so the overlay kept a scroll parent's old crop and a step kept following a shrunk target's old spot until something else woke the tracker. A ResizeObserver now rebuilds the box on every resize. tracker.mjs gains shrink and shiftAfterShrink; shiftAfterShrink got 0 updates in Chromium before this change and 1 after. Co-Authored-By: Claude Opus 5.5 --- shepherd.js/src/utils/position.ts | 8 ++++++++ shepherd.js/test/position/tracker.mjs | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts index 19335489b..903bda58f 100644 --- a/shepherd.js/src/utils/position.ts +++ b/shepherd.js/src/utils/position.ts @@ -826,11 +826,19 @@ function observeMove(element: Element, onMove: () => void) { const onResize = () => refresh(true); const win = getWindow(element); win.addEventListener('resize', onResize); + // The observer watches the box the element had when it was made, so an element + // that shrinks could then move within that old box without being noticed. + const resizes = + typeof ResizeObserver === 'function' + ? new ResizeObserver(onResize) + : undefined; + resizes?.observe(element); refresh(true); return () => { disposed = true; win.removeEventListener('resize', onResize); + resizes?.disconnect(); stop(); }; } diff --git a/shepherd.js/test/position/tracker.mjs b/shepherd.js/test/position/tracker.mjs index 5aa47e8af..f6a3e29f0 100644 --- a/shepherd.js/test/position/tracker.mjs +++ b/shepherd.js/test/position/tracker.mjs @@ -108,6 +108,13 @@ async function runTracker() { await measure('settledShift', () => { scroller.style.top = '150px'; }); + await measure('shrink', () => { + reference.style.height = '20px'; + }); + // Stays within the box the reference had before it shrank. + await measure('shiftAfterShrink', () => { + scroller.style.top = '155px'; + }); cleanup(); await measure('afterCleanup', () => { window.scrollTo(0, 80); From a8993d751d812496130cdf46505edff8800a8ac0 Mon Sep 17 00:00:00 2001 From: Chuck Carpenter Date: Wed, 11 Nov 2026 17:10:47 +0100 Subject: [PATCH 4/5] Track border-box and inline size changes without polling Review follow-ups: - ResizeObservers watched the content box, while check compares border boxes, so a fixed-size element losing its border went unnoticed. The reference, floating element and frames are now observed by border box. - An inline reference has no box for a ResizeObserver, so new text could shrink it, and then let it move within its old box, unnoticed. observeMove now watches an inline element's subtree for mutations and rechecks on each. tracker.mjs gains borderShrink, inlineTextShrink and inlineShiftAfterShrink, which got 0 updates in Chromium before this change and 1 after. Co-Authored-By: Claude Opus 5.5 --- shepherd.js/src/utils/position.ts | 21 +++++++- shepherd.js/test/position/tracker.mjs | 49 +++++++++++++++++-- .../unit/components/shepherd-modal.spec.js | 7 ++- 3 files changed, 69 insertions(+), 8 deletions(-) diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts index 903bda58f..ed0666bad 100644 --- a/shepherd.js/src/utils/position.ts +++ b/shepherd.js/src/utils/position.ts @@ -828,17 +828,32 @@ function observeMove(element: Element, onMove: () => void) { win.addEventListener('resize', onResize); // The observer watches the box the element had when it was made, so an element // that shrinks could then move within that old box without being noticed. + // `autoUpdate` reports the resize itself. const resizes = typeof ResizeObserver === 'function' ? new ResizeObserver(onResize) : undefined; - resizes?.observe(element); + resizes?.observe(element, { box: 'border-box' }); + // An inline element has no box for a ResizeObserver, so new text or attributes + // are the only sign that it changed size, and nothing else reports it. + const mutations = + typeof MutationObserver === 'function' && + styleOf(element).display === 'inline' + ? new MutationObserver(() => refresh()) + : undefined; + mutations?.observe(element, { + attributes: true, + characterData: true, + childList: true, + subtree: true + }); refresh(true); return () => { disposed = true; win.removeEventListener('resize', onResize); resizes?.disconnect(); + mutations?.disconnect(); stop(); }; } @@ -1011,8 +1026,10 @@ export function autoUpdate( typeof IntersectionObserver === 'function' ? chain.map((element) => observeMove(element, check)) : []; + // The border box, which is what `check` compares, so a border or padding change + // on a fixed-size element counts. [reference, floating, ...frames].forEach((element) => - resizes?.observe(element) + resizes?.observe(element, { box: 'border-box' }) ); const stop = () => { diff --git a/shepherd.js/test/position/tracker.mjs b/shepherd.js/test/position/tracker.mjs index f6a3e29f0..304fadf56 100644 --- a/shepherd.js/test/position/tracker.mjs +++ b/shepherd.js/test/position/tracker.mjs @@ -60,8 +60,23 @@ async function runTracker() { spacer.style.cssText = 'height:20px'; inner.append(spacer); const reference = document.createElement('div'); - reference.style.cssText = 'width:100px;height:40px;background:#ccd'; + reference.style.cssText = + 'width:100px;height:40px;background:#ccd;border:4px solid'; inner.append(reference); + // An inline reference, whose size no ResizeObserver reports. + const line = document.createElement('div'); + line.style.cssText = + 'position:absolute;left:500px;top:100px;white-space:nowrap'; + const lead = document.createTextNode('x'); + const inline = document.createElement('span'); + inline.textContent = 'a long inline reference'; + line.append(lead, inline); + page.append(line); + const inlineFloating = document.createElement('div'); + inlineFloating.style.cssText = + 'position:absolute;left:0;top:0;width:10px;height:10px'; + document.body.append(inlineFloating); + let inlineCount = 0; const floating = document.createElement('div'); floating.style.cssText = 'position:absolute;left:0;top:0;width:100px;height:50px;background:#fcc'; @@ -75,14 +90,19 @@ async function runTracker() { await new Promise((done) => setTimeout(done, 250)); }; const results = {}; - const measure = async (name, act) => { + const measure = async (name, act, read = () => count) => { await tick(); - const before = count; + const before = read(); act(); await tick(); - results[name] = count - before; + results[name] = read() - before; }; const cleanup = window.ENGINE.autoUpdate(reference, floating, () => count++); + const cleanupInline = window.ENGINE.autoUpdate( + inline, + inlineFloating, + () => inlineCount++ + ); results.initial = count; await measure('windowScroll', () => window.scrollTo(0, 37)); await measure('ancestorScroll', () => { @@ -115,7 +135,28 @@ async function runTracker() { await measure('shiftAfterShrink', () => { scroller.style.top = '155px'; }); + // Shrinks the border box and leaves the content box as it was. + await measure('borderShrink', () => { + reference.style.borderWidth = '0'; + }); + const readInline = () => inlineCount; + await measure( + 'inlineTextShrink', + () => { + inline.textContent = 'short'; + }, + readInline + ); + // Moves it within the box it had before its text shrank. + await measure( + 'inlineShiftAfterShrink', + () => { + lead.data = 'xx'; + }, + readInline + ); cleanup(); + cleanupInline(); await measure('afterCleanup', () => { window.scrollTo(0, 80); reference.style.width = '131px'; diff --git a/shepherd.js/test/unit/components/shepherd-modal.spec.js b/shepherd.js/test/unit/components/shepherd-modal.spec.js index 436779f1b..28db1fda4 100644 --- a/shepherd.js/test/unit/components/shepherd-modal.spec.js +++ b/shepherd.js/test/unit/components/shepherd-modal.spec.js @@ -2007,13 +2007,16 @@ describe('components/ShepherdModal', () => { // A target living in the document of `frameWindow`. Only the target's // ownerDocument is swapped: the modal container stays in the real // document, which is what decides where the frame walk has to stop. - // The opening follows the target by listening on its window and document. + // The opening follows the target by listening on its window and document, + // and reads its style from its window. const listens = { addEventListener() {}, removeEventListener() {} }; function startStepInFrame(modal, frameWindow) { const targetEl = document.createElement('div'); container.appendChild(targetEl); - Object.assign(frameWindow, listens); + Object.assign(frameWindow, listens, { + getComputedStyle: window.getComputedStyle.bind(window) + }); Object.defineProperty(targetEl, 'ownerDocument', { value: { defaultView: frameWindow, ...listens }, configurable: true From 0e2c58514be3b76595875032c79b0c33d3878cd2 Mon Sep 17 00:00:00 2001 From: Chuck Carpenter Date: Wed, 11 Nov 2026 17:13:38 +0100 Subject: [PATCH 5/5] Cover overlay tracking end to end in Cypress Runs the whole modal overlay in a real browser against changes that fire no scroll or resize event: a scroll parent moving past a target that stays put, a target losing its border, and an inline target whose text shrinks. A fourth test asserts that a tour on a still page requests no animation frames. Against main's build the tracking tests pass, since its loop measured every frame, and the frames test fails. Against this branch all four pass. overlayOpenings now also reads each opening's width. Co-Authored-By: Claude Opus 5.5 --- .../cypress/examples/overlay-tracking.html | 63 +++++++++ .../integration/overlay-tracking.cy.js | 127 ++++++++++++++++++ .../test/cypress/utils/overlay-openings.js | 18 ++- 3 files changed, 202 insertions(+), 6 deletions(-) create mode 100644 shepherd.js/test/cypress/examples/overlay-tracking.html create mode 100644 shepherd.js/test/cypress/integration/overlay-tracking.cy.js diff --git a/shepherd.js/test/cypress/examples/overlay-tracking.html b/shepherd.js/test/cypress/examples/overlay-tracking.html new file mode 100644 index 000000000..f0b8bf192 --- /dev/null +++ b/shepherd.js/test/cypress/examples/overlay-tracking.html @@ -0,0 +1,63 @@ + + + + + + + + + + +
+
+
+
+

xa long inline target

+ + diff --git a/shepherd.js/test/cypress/integration/overlay-tracking.cy.js b/shepherd.js/test/cypress/integration/overlay-tracking.cy.js new file mode 100644 index 000000000..58c6e18a4 --- /dev/null +++ b/shepherd.js/test/cypress/integration/overlay-tracking.cy.js @@ -0,0 +1,127 @@ +import setupTour from '../utils/setup-tour'; +import overlayOpenings from '../utils/overlay-openings'; + +// End-to-end guard for the overlay following its highlight without polling. +// Each change here fires no scroll or resize event, and what it does to the +// highlight depends on layout, which happy-dom does not implement. +describe('modal overlay tracking', () => { + let Shepherd, tour; + + beforeEach(() => { + Shepherd = null; + + cy.visit('/test/cypress/examples/overlay-tracking', { + onLoad(contentWindow) { + if (contentWindow.Shepherd) { + return (Shepherd = contentWindow.Shepherd); + } + } + }); + }); + + afterEach(() => { + tour?.complete(); + }); + + const startTour = (selector) => { + cy.document().then(() => { + tour = setupTour( + Shepherd, + { scrollTo: false }, + () => [ + { + attachTo: { element: selector, on: 'bottom' }, + id: 'tracking', + text: 'Tracking' + } + ], + { useModalOverlay: true } + ); + tour.start(); + }); + cy.wait(250); + }; + + it('re-crops when a scroll parent moves while its target stays put', () => { + cy.document().then((doc) => { + doc.querySelector('.scroller').scrollTop = 100; + }); + startTour('.in-scroller'); + + cy.document().then((doc) => { + const scroller = doc.querySelector('.scroller'); + const target = doc.querySelector('.in-scroller'); + const { top } = target.getBoundingClientRect(); + expect(overlayOpenings(doc)[0].height).to.be.closeTo(40, 1); + + // The scroller's top edge moves 20px past the target, and the content + // above the target moves up by as much, so only the crop changes. + const shift = top - scroller.getBoundingClientRect().top + 20; + scroller.style.top = `${100 + shift}px`; + doc.querySelector('.content').style.paddingTop = `${200 - shift}px`; + }); + cy.wait(150); + + cy.document().then((doc) => { + const target = doc.querySelector('.in-scroller').getBoundingClientRect(); + const [opening] = overlayOpenings(doc); + + expect(target.top).to.be.closeTo(200, 1); + expect(opening.y).to.be.closeTo(220, 1); + expect(opening.height).to.be.closeTo(20, 1); + }); + }); + + it('shrinks with a target that loses its border', () => { + startTour('.bordered'); + + cy.document().then((doc) => { + expect(overlayOpenings(doc)[0].height).to.be.closeTo(52, 1); + doc.querySelector('.bordered').style.borderWidth = '0'; + }); + cy.wait(150); + + cy.document().then((doc) => { + const [opening] = overlayOpenings(doc); + + expect(opening.height).to.be.closeTo(40, 1); + expect(opening.width).to.be.closeTo(120, 1); + }); + }); + + it('follows an inline target whose text shrinks', () => { + startTour('.inline'); + + cy.document().then((doc) => { + doc.querySelector('.inline').textContent = 'short'; + }); + cy.wait(150); + + cy.document().then((doc) => { + const target = doc.querySelector('.inline').getBoundingClientRect(); + const [opening] = overlayOpenings(doc); + + expect(opening.x).to.be.closeTo(target.left, 1); + expect(opening.width).to.be.closeTo(target.width, 1); + }); + }); + + it('asks for no frames while nothing moves', () => { + startTour('.bordered'); + cy.wait(1000); + + cy.window().then((win) => { + const { requestAnimationFrame } = win; + let frames = 0; + win.requestAnimationFrame = (callback) => { + frames++; + return requestAnimationFrame.call(win, callback); + }; + + cy.wait(1000).then(() => { + win.requestAnimationFrame = requestAnimationFrame; + expect(frames).to.equal(0); + }); + }); + }); +}); diff --git a/shepherd.js/test/cypress/utils/overlay-openings.js b/shepherd.js/test/cypress/utils/overlay-openings.js index ad1a2b5b7..cadbd2d08 100644 --- a/shepherd.js/test/cypress/utils/overlay-openings.js +++ b/shepherd.js/test/cypress/utils/overlay-openings.js @@ -2,11 +2,12 @@ * Reads the cutouts of the modal overlay back out of its svg path. * * The path is the full-viewport rect followed by one sub-path per opening, - * each starting `M{x + radius},{y}` and reaching its bottom edge with the - * first `V{y + height}`. Only valid for openings without a corner radius. + * each starting `M{x + radius},{y}`, reaching its bottom edge with the first + * `V{y + height}` and its right edge with the next `H{x + width}`. Only valid + * for openings without a corner radius. * * @param {Document} doc The document the overlay is rendered in - * @returns {{ x: number, y: number, height: number }[]} + * @returns {{ x: number, y: number, width: number, height: number }[]} */ export default function overlayOpenings(doc) { const d = doc @@ -18,9 +19,14 @@ export default function overlayOpenings(doc) { .slice(1) .filter(Boolean) .map((subPath) => { - const [, x, y, bottom] = subPath.match( - /^M([-\d.e]+),([-\d.e]+).*?V([-\d.e]+)/ + const [, x, y, bottom, right] = subPath.match( + /^M([-\d.e]+),([-\d.e]+).*?V([-\d.e]+).*?H([-\d.e]+)/ ); - return { x: Number(x), y: Number(y), height: Number(bottom) - Number(y) }; + return { + x: Number(x), + y: Number(y), + width: Number(right) - Number(x), + height: Number(bottom) - Number(y) + }; }); }