diff --git a/shepherd.js/src/components/shepherd-modal.ts b/shepherd.js/src/components/shepherd-modal.ts index 3e9b0f47b..7dd75eb5b 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,32 @@ 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 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); + 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, { passive: false @@ -445,10 +471,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..ed0666bad 100644 --- a/shepherd.js/src/utils/position.ts +++ b/shepherd.js/src/utils/position.ts @@ -826,11 +826,34 @@ 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. + // `autoUpdate` reports the resize itself. + const resizes = + typeof ResizeObserver === 'function' + ? new ResizeObserver(onResize) + : undefined; + 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(); }; } @@ -847,7 +870,7 @@ function observeMove(element: Element, onMove: () => void) { */ export function autoUpdate( reference: Element, - floating: HTMLElement, + floating: Element, update: () => void ) { const win = getWindow(floating); @@ -1003,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/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) + }; }); } diff --git a/shepherd.js/test/position/tracker.mjs b/shepherd.js/test/position/tracker.mjs index 5aa47e8af..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', () => { @@ -108,7 +128,35 @@ 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'; + }); + // 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 3d670b785..28db1fda4 100644 --- a/shepherd.js/test/unit/components/shepherd-modal.spec.js +++ b/shepherd.js/test/unit/components/shepherd-modal.spec.js @@ -200,6 +200,140 @@ 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('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); + 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 +1645,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 +1662,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 +2007,18 @@ 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, + // 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, { + getComputedStyle: window.getComputedStyle.bind(window) + }); Object.defineProperty(targetEl, 'ownerDocument', { - value: { defaultView: frameWindow }, + value: { defaultView: frameWindow, ...listens }, configurable: true });