`);
+
+const TOUR_JSON = JSON.stringify([
+ {
+ id: 'plans',
+ selector: '#plans',
+ placement: 'bottom',
+ title: 'Plans',
+ body: 'Pick a plan.'
+ },
+ {
+ id: 'usage',
+ selector: '#usage',
+ placement: 'right',
+ title: 'Usage',
+ body: 'See usage.'
+ },
+ {
+ id: 'billing',
+ selector: '#billing',
+ placement: 'top',
+ title: 'Billing',
+ body: 'Manage billing.'
+ }
+]);
+
+export const TASKS = [
+ {
+ id: 'first-tour',
+ extensions: ['js', 'ts'],
+ html: FIRST_TOUR_PAGE,
+ prompt: `Add a three step product tour that starts as soon as the page loads.
+
+1. Title "Welcome". Text "Thanks for joining." Not attached to anything, in the middle of the screen. Button: "Next".
+2. Title "Projects". Text "Create projects here." Attached below \`#new-project\`. Buttons: "Back" and "Next".
+3. Title "Navigation". Text "Everything else lives here." Attached to the right of \`#sidebar\`. Buttons: "Back" and "Done". "Done" finishes the tour.`,
+ check: (d) => [
+ ['first step opens', () => d.expectStep('Welcome')],
+ ['default styling applied', () => d.expectStylesheet()],
+ ['first step centered', () => d.expectCentered('Welcome')],
+ [
+ 'Next advances',
+ async () => {
+ await d.click('Welcome', 'Next');
+ await d.expectStep('Projects');
+ }
+ ],
+ [
+ 'second step below target',
+ () => d.expectPlaced('Projects', '#new-project', 'bottom')
+ ],
+ [
+ 'Back returns',
+ async () => {
+ await d.click('Projects', 'Back');
+ await d.expectStep('Welcome');
+ await d.click('Welcome', 'Next');
+ await d.expectStep('Projects');
+ }
+ ],
+ [
+ 'third step right of target',
+ async () => {
+ await d.click('Projects', 'Next');
+ await d.expectStep('Navigation');
+ await d.expectPlaced('Navigation', '#sidebar', 'right');
+ }
+ ],
+ [
+ 'Done ends the tour',
+ async () => {
+ await d.click('Navigation', 'Done');
+ await d.expectNoStep();
+ }
+ ]
+ ]
+ },
+ {
+ id: 'modal-focus',
+ extensions: ['js', 'ts'],
+ html: MODAL_PAGE,
+ prompt: `Add a one step tour that starts on page load, explaining the \`#delete\` button before anyone uses it.
+
+The step has the title "Careful" and the text "This cannot be undone.", placed above the button. Everything on the page except the button should be dimmed, and the button itself must not be clickable while the tour is open. The user closes the step with a close "×" in its header or the Escape key. Whichever way it is closed, call \`window.onTourEnd('cancelled')\` once. There are no other buttons.`,
+ check: (d) => {
+ const overlay = '.shepherd-modal-overlay-container';
+ return [
+ ['step opens', () => d.expectStep('Careful')],
+ ['default styling applied', () => d.expectStylesheet()],
+ [
+ 'step above target',
+ () => d.expectPlaced('Careful', '#delete', 'top')
+ ],
+ [
+ 'page is dimmed',
+ () =>
+ poll(
+ () =>
+ d.page.locator(overlay).evaluate((el) => {
+ const style = getComputedStyle(el);
+ return (
+ el.classList.contains('shepherd-modal-is-visible') &&
+ style.position === 'fixed' &&
+ Number(style.opacity) > 0
+ );
+ }),
+ 'a visible, fixed overlay'
+ )
+ ],
+ [
+ 'overlay has an opening around the target',
+ () =>
+ poll(
+ () =>
+ d.page
+ .locator(`${overlay} path`)
+ .evaluate(
+ (el) =>
+ (el.getAttribute('d').match(/M/gi) ?? []).length >= 2
+ ),
+ 'a cut-out in the overlay path'
+ )
+ ],
+ [
+ 'target cannot be clicked',
+ async () => {
+ const box = await d.page.locator('#delete').boundingBox();
+ await d.page.mouse.click(
+ box.x + box.width / 2,
+ box.y + box.height / 2
+ );
+ const clicks = await d.page.evaluate(() => window.deleteClicks);
+ if (clicks) throw new Error('the target received the click');
+ }
+ ],
+ [
+ 'close icon ends the tour once',
+ async () => {
+ await d.step('Careful').locator('.shepherd-cancel-icon').click();
+ await d.expectNoStep();
+ const ended = await d.page.evaluate(() => window.tourEnded);
+ if (ended.join() !== 'cancelled') {
+ throw new Error(`onTourEnd calls: ${JSON.stringify(ended)}`);
+ }
+ }
+ ],
+ [
+ 'Escape ends the tour once',
+ async () => {
+ await d.page.reload();
+ await d.expectStep('Careful');
+ await poll(
+ () =>
+ d.page.evaluate(
+ () =>
+ document.activeElement?.closest('.shepherd-element') !==
+ null
+ ),
+ 'focus moved into the step'
+ );
+ await d.page.keyboard.press('Escape');
+ await d.expectNoStep();
+ const ended = await d.page.evaluate(() => window.tourEnded);
+ if (ended.join() !== 'cancelled') {
+ throw new Error(`onTourEnd calls: ${JSON.stringify(ended)}`);
+ }
+ }
+ ]
+ ];
+ }
+ },
+ {
+ id: 'shared-defaults',
+ extensions: ['js', 'ts'],
+ html: DEFAULTS_PAGE,
+ prompt: `Add a four step tour that starts on page load, with steps attached below \`#one\`, \`#two\`, \`#three\` and \`#four\`, titled "One", "Two", "Three" and "Four" (any text).
+
+These things hold for every step, so configure them once instead of repeating them: the step element has the CSS class \`acme-step\`, the page scrolls so the target is on screen, there is a close "×" in the header, and there is a "Next" button.
+
+Two exceptions: step "Two" has no close "×", and step "Four" has a "Finish" button that ends the tour instead of "Next".`,
+ check: (d) => {
+ const closeIcon = (title) =>
+ d.step(title).locator('.shepherd-cancel-icon').count();
+ const stepHas = async (title, selector, placed = true) => {
+ await d.expectStep(title);
+ const hasClass = await d
+ .step(title)
+ .evaluate((el) => el.classList.contains('acme-step'));
+ if (!hasClass) throw new Error(`"${title}" lacks acme-step`);
+ await d.expectInViewport(selector);
+ if (placed) await d.expectPlaced(title, selector, 'bottom');
+ };
+ return [
+ [
+ 'step One from defaults',
+ async () => {
+ await stepHas('One', '#one');
+ await d.expectStylesheet();
+ if ((await closeIcon('One')) !== 1) throw new Error('no ×');
+ }
+ ],
+ [
+ 'step Two overrides the close icon',
+ async () => {
+ await d.click('One', 'Next');
+ await stepHas('Two', '#two');
+ if ((await closeIcon('Two')) !== 0) throw new Error('has ×');
+ }
+ ],
+ [
+ 'step Three keeps the defaults',
+ async () => {
+ await d.click('Two', 'Next');
+ await stepHas('Three', '#three');
+ if ((await closeIcon('Three')) !== 1) throw new Error('no ×');
+ }
+ ],
+ [
+ 'step Four overrides the buttons',
+ async () => {
+ await d.click('Three', 'Next');
+ await stepHas('Four', '#four');
+ await d.expectNoButton('Four', 'Next');
+ }
+ ],
+ [
+ 'Finish ends the tour',
+ async () => {
+ await d.click('Four', 'Finish');
+ await d.expectNoStep();
+ }
+ ]
+ ];
+ }
+ },
+ {
+ id: 'async-targets',
+ extensions: ['js', 'ts'],
+ html: ASYNC_PAGE,
+ prompt: `Add a tour that starts on page load. Every attached step goes below its target and has a "Next" button, except the last, which has "Done". Step titles are given in quotes; any text.
+
+1. "Start", attached to \`#open-settings\`.
+2. "Panel", attached to \`#settings-panel\`. That element does not exist until the settings panel is opened with \`window.app.openSettings()\`, which returns a promise that resolves once it is rendered. Only open the panel when the tour reaches this step.
+3. "Live", attached to \`#live-widget\`. The app renders this element by itself, up to two seconds after the settings panel opens.
+4. "Legacy", attached to \`#legacy-banner\`. This element exists for some accounts only. When it is not on the page, the tour leaves this step out.
+5. "Bye", attached to \`#footer\`.`,
+ check: (d) => [
+ [
+ 'first step opens without opening settings',
+ async () => {
+ await d.expectStep('Start');
+ await d.expectStylesheet();
+ await d.expectPlaced('Start', '#open-settings', 'bottom');
+ const calls = await d.page.evaluate(() => window.app.calls);
+ if (calls !== 0) throw new Error(`openSettings called ${calls}x`);
+ }
+ ],
+ [
+ 'second step waits for its promise and attaches',
+ async () => {
+ await d.click('Start', 'Next');
+ await d.expectStep('Panel');
+ await d.expectPlaced('Panel', '#settings-panel', 'bottom');
+ const calls = await d.page.evaluate(() => window.app.calls);
+ if (calls !== 1) throw new Error(`openSettings called ${calls}x`);
+ }
+ ],
+ [
+ 'third step waits for a late element and attaches',
+ async () => {
+ await d.click('Panel', 'Next');
+ await d.expectStep('Live');
+ await d.expectPlaced('Live', '#live-widget', 'bottom');
+ }
+ ],
+ [
+ 'absent step is left out',
+ async () => {
+ await d.click('Live', 'Next');
+ await d.expectStep('Bye');
+ await d.expectPlaced('Bye', '#footer', 'bottom');
+ }
+ ],
+ [
+ 'Done ends the tour',
+ async () => {
+ await d.click('Bye', 'Done');
+ await d.expectNoStep();
+ }
+ ]
+ ]
+ },
+ {
+ id: 'events-persist',
+ extensions: ['js', 'ts'],
+ html: EVENTS_PAGE,
+ prompt: `Add a tour for first-time visitors that starts on page load. Once somebody has finished or dismissed it, it must not start again on later visits, including after a reload. Store that in \`localStorage\`.
+
+1. id \`menu\`, title "Menu", attached below \`#menu\`. It has no buttons. It moves on when the user clicks \`#menu\`.
+2. id \`item\`, title "Item", attached below \`#menu-item\`, with a "Done" button.
+
+Pressing Escape dismisses the tour.
+
+Report to analytics with \`window.analytics.track(name, props)\`:
+- each time a step is shown: \`track('tour_step', { id })\` with the step's id
+- when the tour ends: \`track('tour_finished', { outcome })\`, with \`'completed'\` after "Done" and \`'dismissed'\` after Escape.`,
+ check: (d) => {
+ const expectCalls = async (expected) => {
+ const calls = await d.page.evaluate(() => window.analytics.calls);
+ if (JSON.stringify(calls) !== JSON.stringify(expected)) {
+ throw new Error(`analytics calls: ${JSON.stringify(calls)}`);
+ }
+ };
+ return [
+ [
+ 'first step opens and is tracked',
+ async () => {
+ await d.expectStep('Menu');
+ await d.expectStylesheet();
+ await d.expectPlaced('Menu', '#menu', 'bottom');
+ await expectCalls([['tour_step', { id: 'menu' }]]);
+ }
+ ],
+ [
+ 'clicking the target advances',
+ async () => {
+ await d.page.locator('#menu').click();
+ await d.expectStep('Item');
+ await d.expectPlaced('Item', '#menu-item', 'bottom');
+ }
+ ],
+ [
+ 'completion is reported',
+ async () => {
+ await d.click('Item', 'Done');
+ await d.expectNoStep();
+ await expectCalls([
+ ['tour_step', { id: 'menu' }],
+ ['tour_step', { id: 'item' }],
+ ['tour_finished', { outcome: 'completed' }]
+ ]);
+ }
+ ],
+ [
+ 'does not restart after completing',
+ async () => {
+ await d.page.reload();
+ await d.stayClosed();
+ }
+ ],
+ [
+ 'dismissal is reported and remembered',
+ async () => {
+ await d.page.evaluate(() => localStorage.clear());
+ await d.page.reload();
+ await d.expectStep('Menu');
+ await poll(
+ () =>
+ d.page.evaluate(
+ () =>
+ document.activeElement?.closest('.shepherd-element') !==
+ null
+ ),
+ 'focus moved into the step'
+ );
+ await d.page.keyboard.press('Escape');
+ await d.expectNoStep();
+ await expectCalls([
+ ['tour_step', { id: 'menu' }],
+ ['tour_finished', { outcome: 'dismissed' }]
+ ]);
+ await d.page.reload();
+ await d.stayClosed();
+ }
+ ]
+ ];
+ }
+ },
+ {
+ id: 'react-strict',
+ extensions: ['tsx', 'jsx'],
+ html: REACT_PAGE,
+ entry: (solution) => `
+ import { StrictMode } from 'react';
+ import { createRoot } from 'react-dom/client';
+ import App from ${JSON.stringify(solution)};
+ createRoot(document.getElementById('root')).render(
+
+ );`,
+ entryExt: 'jsx',
+ prompt: `This is a React 19 app using the \`react-shepherd\` package, which is installed alongside \`shepherd.js\`. Write the \`App\` component as this module's default export. It is rendered into the page inside \`\`.
+
+\`App\` renders:
+- \`
A
\`
+- \`
B
\`
+- \`\`, which runs the tour from the beginning
+- \`\` and \`\`, a counter in React state that \`Bump\` increments
+
+The tour starts by itself when the app first mounts. Step "Step A" is below \`#a\` with a "Next" button, and step "Step B" is below \`#b\` with a "Done" button that ends it.`,
+ check: (d) => [
+ [
+ 'one step opens on mount',
+ async () => {
+ await d.expectStep('Step A');
+ await d.page.waitForTimeout(300);
+ await d.expectStep('Step A');
+ await d.expectStylesheet();
+ await d.expectPlaced('Step A', '#a', 'bottom');
+ }
+ ],
+ [
+ 'a re-render leaves the tour alone',
+ async () => {
+ await d.page.locator('#bump').click();
+ await poll(
+ async () => (await d.page.locator('#count').innerText()) === '1',
+ 'the counter updated'
+ );
+ await d.expectStep('Step A');
+ }
+ ],
+ [
+ 'tour survives a re-render and finishes',
+ async () => {
+ await d.click('Step A', 'Next');
+ await d.expectStep('Step B');
+ await d.expectPlaced('Step B', '#b', 'bottom');
+ await d.page.locator('#bump').click();
+ await d.expectStep('Step B');
+ await d.click('Step B', 'Done');
+ await d.expectNoStep();
+ }
+ ],
+ [
+ 'a re-render does not restart a finished tour',
+ async () => {
+ await d.page.locator('#bump').click();
+ await d.stayClosed();
+ }
+ ],
+ [
+ 'replay runs it again',
+ async () => {
+ await d.page.locator('#replay').click();
+ await d.expectStep('Step A');
+ await d.click('Step A', 'Next');
+ await d.expectStep('Step B');
+ await d.click('Step B', 'Done');
+ await d.expectNoStep();
+ }
+ ]
+ ]
+ },
+ {
+ id: 'typed-json',
+ extensions: ['ts'],
+ html: JSON_PAGE,
+ files: { '/tour.json': TOUR_JSON },
+ typecheck: true,
+ entry: (solution) => `
+ import { buildTour } from ${JSON.stringify(solution)};
+ const steps = await (await fetch('/tour.json')).json();
+ window.tour = buildTour(steps);
+ window.tour.start();`,
+ entryExt: 'js',
+ prompt: `Our CMS serves tours as JSON. Write a TypeScript module exporting this function, which must pass \`tsc --strict\`:
+
+\`\`\`ts
+export interface ProductStep {
+ id: string;
+ selector: string;
+ placement: 'top' | 'bottom' | 'left' | 'right';
+ title: string;
+ /** Trusted HTML from the CMS. */
+ body: string;
+}
+
+export function buildTour(steps: ProductStep[]): Tour;
+\`\`\`
+
+\`Tour\` is the type of a Shepherd tour. \`buildTour\` returns the tour, and the caller starts it. Each step attaches to its \`selector\` at its \`placement\`, and keeps its \`id\`. Every step except the first has a "Back" button. Every step except the last has a "Next" button. The last step has a "Done" button that ends the tour.`,
+ check: (d) => [
+ [
+ 'first step opens with its id and placement',
+ async () => {
+ await d.expectStep('Plans');
+ await d.expectStylesheet();
+ await d.expectPlaced('Plans', '#plans', 'bottom');
+ await d.expectNoButton('Plans', 'Back');
+ const id = await d.page.evaluate(
+ () => window.tour.getCurrentStep().id
+ );
+ if (id !== 'plans') throw new Error(`step id is ${id}`);
+ }
+ ],
+ [
+ 'body renders as HTML',
+ async () => {
+ await d.click('Plans', 'Next');
+ await d.expectStep('Usage');
+ await d.expectPlaced('Usage', '#usage', 'right');
+ const bold = await d.step('Usage').locator('b').count();
+ if (bold !== 1) throw new Error('body was not rendered as HTML');
+ }
+ ],
+ [
+ 'Back returns',
+ async () => {
+ await d.click('Usage', 'Back');
+ await d.expectStep('Plans');
+ await d.click('Plans', 'Next');
+ await d.expectStep('Usage');
+ }
+ ],
+ [
+ 'last step has Done, which ends the tour',
+ async () => {
+ await d.click('Usage', 'Next');
+ await d.expectStep('Billing');
+ await d.expectPlaced('Billing', '#billing', 'top');
+ await d.expectNoButton('Billing', 'Next');
+ await d.click('Billing', 'Done');
+ await d.expectNoStep();
+ }
+ ]
+ ]
+ },
+ {
+ id: 'script-tag',
+ extensions: ['html'],
+ prompt: `This site has no build step and no bundler. Write a complete HTML page containing \`\` and a one step tour that starts on page load: title "Buy now", text "Checkout is one click.", below \`#buy\`, with a "Got it" button that ends the tour.
+
+The \`shepherd.js\` package is served as is at \`/node_modules/shepherd.js/\`, so its files are at the same paths as on disk. The page has no other server support and no internet access.`,
+ check: (d) => [
+ ['step opens', () => d.expectStep('Buy now')],
+ ['default styling applied', () => d.expectStylesheet()],
+ ['step below target', () => d.expectPlaced('Buy now', '#buy', 'bottom')],
+ [
+ 'Got it ends the tour',
+ async () => {
+ await d.click('Buy now', 'Got it');
+ await d.expectNoStep();
+ }
+ ]
+ ]
+ }
+];
+
+export function promptFor(task) {
+ const file = `${task.id}.${task.extensions[0]}`;
+ const delivery =
+ task.extensions[0] === 'html'
+ ? `Write your answer to \`${file}\`.`
+ : `Write your answer to \`${file}\`${
+ task.extensions.length > 1
+ ? ` (or \`${task.id}.${task.extensions[1]}\`)`
+ : ''
+ }. It is compiled by a standard bundler that handles JavaScript, TypeScript, JSX and CSS imports, and it loads as a module script in the page below. You cannot edit the page.`;
+ const html = task.html
+ ? `\n\nThe page:\n\n\`\`\`html\n${task.html}\n\`\`\``
+ : '';
+ return `You are working in a project that has the \`shepherd.js\` npm package installed in \`node_modules\`. Treat this as production code.
+
+${task.prompt}
+
+${delivery}${html}
+`;
+}
From e585eae7129bc75a2e48f00732644bc1c5e2ce92 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 20:25:25 -0500
Subject: [PATCH 45/93] feat: export Tour and Step by name
import { Tour } from 'shepherd.js' failed to build, and require('shepherd.js')
had no Tour. Both now work. Costs 0 bytes gz in a consumer bundle.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/shepherd.ts | 16 +++++++++++-----
shepherd.js/test/unit/exports.spec.js | 15 +++++++++++++++
2 files changed, 26 insertions(+), 5 deletions(-)
create mode 100644 shepherd.js/test/unit/exports.spec.js
diff --git a/shepherd.js/src/shepherd.ts b/shepherd.js/src/shepherd.ts
index bcf75a3a2..f4608c302 100644
--- a/shepherd.js/src/shepherd.ts
+++ b/shepherd.js/src/shepherd.ts
@@ -1,11 +1,17 @@
-import { Shepherd, Tour } from './tour.ts';
-import { Step } from './step.ts';
+import { Shepherd, Tour as TourClass } from './tour.ts';
+import { Step as StepClass } from './step.ts';
-const NoOp = class {} as unknown as typeof Tour & typeof Step;
+const NoOp = class {} as unknown as typeof TourClass & typeof StepClass;
const isServerSide = typeof window === 'undefined';
-Shepherd.Step = isServerSide ? NoOp : Step;
-Shepherd.Tour = isServerSide ? NoOp : Tour;
+export const Step: typeof StepClass = isServerSide ? NoOp : StepClass;
+export type Step = StepClass;
+
+export const Tour: typeof TourClass = isServerSide ? NoOp : TourClass;
+export type Tour = TourClass;
+
+Shepherd.Step = Step;
+Shepherd.Tour = Tour;
export { ShepherdBase } from './tour.ts';
export default Shepherd;
diff --git a/shepherd.js/test/unit/exports.spec.js b/shepherd.js/test/unit/exports.spec.js
new file mode 100644
index 000000000..a40bf07f6
--- /dev/null
+++ b/shepherd.js/test/unit/exports.spec.js
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+import Shepherd, { Step, Tour } from '../../src/shepherd';
+
+describe('package exports', () => {
+ it('exposes Tour and Step as named exports, the same classes as on the default', () => {
+ expect(Tour).toBe(Shepherd.Tour);
+ expect(Step).toBe(Shepherd.Step);
+ });
+
+ it('builds a working tour from the named export', () => {
+ const tour = new Tour();
+ tour.addStep({ id: 'only', text: 'hi' });
+ expect(tour.getById('only')).toBeInstanceOf(Step);
+ });
+});
From f80192382ac91909ef8dcf276fdc963217da1ef7 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 20:26:50 -0500
Subject: [PATCH 46/93] feat: let button actions name a tour method
A step can be plain JSON and can be written before the tour exists, which removes
the need for this, bind, or a tour reference in the common case. action: 'next'
used to throw on render. Costs 10 bytes gz in a consumer bundle.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/components/shepherd-button.ts | 7 ++--
shepherd.js/src/step.ts | 33 +++++++++++++-----
.../unit/components/shepherd-button.spec.js | 34 ++++++++++++++++++-
3 files changed, 63 insertions(+), 11 deletions(-)
diff --git a/shepherd.js/src/components/shepherd-button.ts b/shepherd.js/src/components/shepherd-button.ts
index cc881f62b..d7bc67526 100644
--- a/shepherd.js/src/components/shepherd-button.ts
+++ b/shepherd.js/src/components/shepherd-button.ts
@@ -1,5 +1,5 @@
import { h } from '../utils/dom.ts';
-import { isFunction } from '../utils/type-check.ts';
+import { isFunction, isString } from '../utils/type-check.ts';
import type { Step, StepOptionsButton } from '../step.ts';
import './shepherd-button.css';
@@ -10,6 +10,9 @@ export function createShepherdButton(
const resolve = (option: unknown) =>
isFunction(option) ? option.call(step) : option;
const text = resolve(config.text);
+ const action = isString(config.action)
+ ? step.tour[config.action]
+ : config.action;
const btn = h('button', {
...config.attrs,
@@ -18,7 +21,7 @@ export function createShepherdButton(
config.secondary ? 'shepherd-button-secondary' : ''
}`,
disabled: resolve(config.disabled) || null,
- onclick: config.action ? config.action.bind(step.tour) : null,
+ onclick: action ? action.bind(step.tour) : null,
tabindex: '0',
type: 'button'
}) as HTMLButtonElement;
diff --git a/shepherd.js/src/step.ts b/shepherd.js/src/step.ts
index 037a01aa3..a6e996230 100644
--- a/shepherd.js/src/step.ts
+++ b/shepherd.js/src/step.ts
@@ -318,19 +318,36 @@ export interface StepOptionsAdvanceOn {
selector: string;
}
+/**
+ * The tour methods a button can run by name.
+ */
+export type StepButtonAction = 'back' | 'cancel' | 'complete' | 'next';
+
export interface StepOptionsButton {
/**
- * A function executed when the button is clicked on
- * It is automatically bound to the `tour` the step is associated with, so things like `this.next` will
- * work inside the action.
- * You can use action to skip steps or navigate to specific steps, with something like:
+ * What the button does when clicked. Either the name of a tour method, which
+ * keeps a tour definition plain JSON and works before the tour exists, or a
+ * function.
+ *
+ * A function is bound to the tour, so `this.next()` works inside a `function`
+ * or method. An arrow function does not get that binding, so `() => this.next()`
+ * fails; use `() => tour.next()` there.
+ *
+ * @example
* ```js
- * action() {
- * return this.show('some_step_name');
- * }
+ * buttons: [
+ * { text: 'Back', action: 'back', secondary: true },
+ * { text: 'Next', action: 'next' },
+ * {
+ * text: 'Skip to pricing',
+ * action() {
+ * return this.show('pricing');
+ * }
+ * }
+ * ]
* ```
*/
- action?: (this: Tour) => void;
+ action?: StepButtonAction | ((this: Tour) => void);
/**
* Additional HTML attributes to apply to the button element.
diff --git a/shepherd.js/test/unit/components/shepherd-button.spec.js b/shepherd.js/test/unit/components/shepherd-button.spec.js
index 79fa6a0f0..7785d1ff2 100644
--- a/shepherd.js/test/unit/components/shepherd-button.spec.js
+++ b/shepherd.js/test/unit/components/shepherd-button.spec.js
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createShepherdButton } from '../../../src/components/shepherd-button.ts';
describe('component/ShepherdButton', () => {
@@ -13,6 +13,38 @@ describe('component/ShepherdButton', () => {
container.remove();
});
+ describe('action', () => {
+ it.each(['back', 'cancel', 'complete', 'next'])(
+ 'runs the tour method named %s',
+ (name) => {
+ const tour = { [name]: vi.fn() };
+ const button = createShepherdButton({ action: name }, { tour });
+ container.appendChild(button);
+
+ button.click();
+
+ expect(tour[name]).toHaveBeenCalledTimes(1);
+ }
+ );
+
+ it('still binds a function to the tour', () => {
+ const tour = { next: vi.fn() };
+ const button = createShepherdButton(
+ {
+ action() {
+ this.next();
+ }
+ },
+ { tour }
+ );
+ container.appendChild(button);
+
+ button.click();
+
+ expect(tour.next).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe('disabled', () => {
it('should be enabled by default', () => {
const button = createShepherdButton({}, undefined);
From 7f2398fb5d44318ec4753ba30b89ded24c539361 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 20:28:36 -0500
Subject: [PATCH 47/93] fix: name the fix when a step target is missing
An invalid selector left a string in place of the element, which crashed in
getAttribute. It now counts as missing and shows centered. Costs 34 bytes gz.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/general.ts | 2 +-
shepherd.js/test/unit/utils/general.spec.js | 32 +++++++++++++++++++++
2 files changed, 33 insertions(+), 1 deletion(-)
diff --git a/shepherd.js/src/utils/general.ts b/shepherd.js/src/utils/general.ts
index 43ba7386e..3a72b6d4c 100644
--- a/shepherd.js/src/utils/general.ts
+++ b/shepherd.js/src/utils/general.ts
@@ -29,7 +29,7 @@ function locateAttachToElement(step: Step, logMissing?: boolean) {
if (!element && logMissing) {
console.error(
- `The element for this Shepherd step was not found ${attachTo.element}`
+ `Shepherd: attachTo.element not found: ${attachTo.element}. The step is centered instead. Fix the selector, or set waitForElement or skipMissingElement.`
);
}
}
diff --git a/shepherd.js/test/unit/utils/general.spec.js b/shepherd.js/test/unit/utils/general.spec.js
index 15a14a0dc..64871a7a6 100644
--- a/shepherd.js/test/unit/utils/general.spec.js
+++ b/shepherd.js/test/unit/utils/general.spec.js
@@ -96,6 +96,38 @@ describe('General Utils', function () {
spy.mockRestore();
});
+ it('names the selector and the fix when the target is missing', function () {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const step = new Step(
+ {},
+ { attachTo: { element: '.element-does-not-exist', on: 'bottom' } }
+ );
+
+ parseAttachTo(step);
+
+ const [message] = spy.mock.calls[0];
+ expect(message).toContain('.element-does-not-exist');
+ expect(message).toContain('waitForElement');
+ expect(message).toContain('skipMissingElement');
+
+ spy.mockRestore();
+ });
+
+ it('treats an invalid selector as a missing target', function () {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const step = new Step(
+ {},
+ { attachTo: { element: '#not[valid', on: 'bottom' } }
+ );
+
+ const { element } = parseAttachTo(step);
+
+ expect(element).toBeNull();
+ expect(spy.mock.calls[0][0]).toContain('#not[valid');
+
+ spy.mockRestore();
+ });
+
it('does not log a console.error when skipMissingElement is true', function () {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
const step = new Step(
From ea9132f3fe83eda5a6724502b94fee06c3ddbe54 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 21:46:32 -0500
Subject: [PATCH 48/93] feat: warn once when Shepherd's stylesheet is not
loaded
Forgetting the CSS import fails silently, and no type or schema can catch it.
The warning names the import. Costs 81 bytes gz.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/step.ts | 11 +++++
.../test/unit/stylesheet-warning.spec.js | 46 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 shepherd.js/test/unit/stylesheet-warning.spec.js
diff --git a/shepherd.js/src/step.ts b/shepherd.js/src/step.ts
index a6e996230..64a5e63dc 100644
--- a/shepherd.js/src/step.ts
+++ b/shepherd.js/src/step.ts
@@ -445,6 +445,8 @@ export interface StepOptionsWhen {
[key: string]: (this: Step) => void;
}
+let stylesheetChecked = false;
+
/**
* A class representing steps to be added to a tour.
* @extends {Evented}
@@ -774,6 +776,15 @@ export class Step extends Evented {
this.el = this._createTooltipContent();
+ if (!stylesheetChecked) {
+ stylesheetChecked = true;
+ if (getComputedStyle(this.el).zIndex === 'auto') {
+ console.warn(
+ "Shepherd: stylesheet not found. Add import 'shepherd.js/dist/css/shepherd.css'."
+ );
+ }
+ }
+
if (this.options.advanceOn) {
this._advanceOnCleanup = bindAdvance(this) ?? null;
}
diff --git a/shepherd.js/test/unit/stylesheet-warning.spec.js b/shepherd.js/test/unit/stylesheet-warning.spec.js
new file mode 100644
index 000000000..d37c1d7df
--- /dev/null
+++ b/shepherd.js/test/unit/stylesheet-warning.spec.js
@@ -0,0 +1,46 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+describe('missing stylesheet warning', () => {
+ let warn;
+
+ const showTwoSteps = async () => {
+ vi.resetModules();
+ const { default: Shepherd } = await import('../../src/shepherd');
+ const tour = new Shepherd.Tour();
+ tour.addStep({ id: 'one', text: 'one' });
+ tour.addStep({ id: 'two', text: 'two' });
+ await tour.start();
+ await tour.next();
+ tour.complete();
+ };
+
+ const stubZIndex = (zIndex) =>
+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({ zIndex });
+
+ beforeEach(() => {
+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('names the import, once per page, when the stylesheet is absent', async () => {
+ stubZIndex('auto');
+
+ await showTwoSteps();
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toContain(
+ 'shepherd.js/dist/css/shepherd.css'
+ );
+ });
+
+ it('stays quiet when the stylesheet is applied', async () => {
+ stubZIndex('9999');
+
+ await showTwoSteps();
+
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
From f2410fa2af9896c2e5e0cc9fb45723d67c4582ef Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 21:47:43 -0500
Subject: [PATCH 49/93] fix: make the server tour a real no-op
new Shepherd.Tour() on the server had no methods, so tour.addStep() at module
scope crashed server rendering, including in client components. Costs 31 bytes gz.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/shepherd.ts | 10 +++++++++-
shepherd.js/test/unit/server.spec.js | 11 +++++++++++
2 files changed, 20 insertions(+), 1 deletion(-)
diff --git a/shepherd.js/src/shepherd.ts b/shepherd.js/src/shepherd.ts
index f4608c302..a8c5bff24 100644
--- a/shepherd.js/src/shepherd.ts
+++ b/shepherd.js/src/shepherd.ts
@@ -1,7 +1,15 @@
import { Shepherd, Tour as TourClass } from './tour.ts';
import { Step as StepClass } from './step.ts';
-const NoOp = class {} as unknown as typeof TourClass & typeof StepClass;
+// Server rendering runs module-level tour setup, so every method must exist.
+const NoOp = class {
+ constructor() {
+ const noOp: object = new Proxy(this, {
+ get: (_target, key) => (key === 'then' ? undefined : () => noOp)
+ });
+ return noOp;
+ }
+} as unknown as typeof TourClass & typeof StepClass;
const isServerSide = typeof window === 'undefined';
export const Step: typeof StepClass = isServerSide ? NoOp : StepClass;
diff --git a/shepherd.js/test/unit/server.spec.js b/shepherd.js/test/unit/server.spec.js
index c05dcf6b9..efadfccdb 100644
--- a/shepherd.js/test/unit/server.spec.js
+++ b/shepherd.js/test/unit/server.spec.js
@@ -4,6 +4,17 @@
import { describe, expect, it } from 'vitest';
import Shepherd from '../../src/shepherd';
+import { TourNoOp } from '../../src/utils/general';
+
+describe('TourNoOp', function () {
+ it('accepts module-level tour setup without doing anything', async () => {
+ const tour = new TourNoOp();
+
+ tour.addStep({ text: 'hi' }).on('complete', () => {});
+
+ expect(await tour.start()).toBe(tour);
+ });
+});
describe('Server Side Render', function () {
describe('Tour constructor', function () {
From afda9d5cf51b07674c5bb1f62cbd7211a32e61c6 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 21:49:18 -0500
Subject: [PATCH 50/93] feat: warn about a button with no action
A misspelled action name or the old type: 'next' form rendered a dead button that
could strand the user, with no message. Costs 28 bytes gz.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/components/shepherd-button.ts | 3 +++
.../test/unit/components/shepherd-button.spec.js | 12 ++++++++++++
2 files changed, 15 insertions(+)
diff --git a/shepherd.js/src/components/shepherd-button.ts b/shepherd.js/src/components/shepherd-button.ts
index d7bc67526..e5c28d706 100644
--- a/shepherd.js/src/components/shepherd-button.ts
+++ b/shepherd.js/src/components/shepherd-button.ts
@@ -13,6 +13,9 @@ export function createShepherdButton(
const action = isString(config.action)
? step.tour[config.action]
: config.action;
+ if (!action) {
+ console.warn(`Shepherd: button "${text}" has no action.`);
+ }
const btn = h('button', {
...config.attrs,
diff --git a/shepherd.js/test/unit/components/shepherd-button.spec.js b/shepherd.js/test/unit/components/shepherd-button.spec.js
index 7785d1ff2..5ba39927c 100644
--- a/shepherd.js/test/unit/components/shepherd-button.spec.js
+++ b/shepherd.js/test/unit/components/shepherd-button.spec.js
@@ -27,6 +27,18 @@ describe('component/ShepherdButton', () => {
}
);
+ it.each([[{ text: 'Next' }], [{ text: 'Next', action: 'finish' }]])(
+ 'warns about a button that would do nothing: %j',
+ (config) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ createShepherdButton(config, { tour: {} });
+
+ expect(warn.mock.calls[0][0]).toContain('"Next" has no action');
+ warn.mockRestore();
+ }
+ );
+
it('still binds a function to the tour', () => {
const tour = { next: vi.fn() };
const button = createShepherdButton(
From 06108a12fe90e756a22503f8da4b3452a4cc37f5 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 21:55:32 -0500
Subject: [PATCH 51/93] docs: document every public type and member
Raises TSDoc coverage of the public declarations from 57% to 99%, with examples
where misuse is likely. Costs 0 bytes in a consumer bundle. The declarations grow
from about 6,400 to 7,800 tokens.
Co-Authored-By: Claude Opus 5.5
---
.../src/components/shepherd-element.ts | 9 ++
shepherd.js/src/components/shepherd-modal.ts | 28 +++++
shepherd.js/src/evented.ts | 12 ++
shepherd.js/src/shepherd.ts | 14 +++
shepherd.js/src/step.ts | 106 +++++++++++++++++-
shepherd.js/src/tour.ts | 78 ++++++++++++-
6 files changed, 241 insertions(+), 6 deletions(-)
diff --git a/shepherd.js/src/components/shepherd-element.ts b/shepherd.js/src/components/shepherd-element.ts
index c574381a3..df683fc48 100644
--- a/shepherd.js/src/components/shepherd-element.ts
+++ b/shepherd.js/src/components/shepherd-element.ts
@@ -16,8 +16,17 @@ export interface ShepherdElementOptions {
step: Step;
}
+/**
+ * A step's rendered element, with its teardown.
+ */
export interface ShepherdElementResult {
+ /**
+ * The step's `
diff --git a/landing/src/pages/index.astro b/landing/src/pages/index.astro
index 9117855e0..2ad649f22 100644
--- a/landing/src/pages/index.astro
+++ b/landing/src/pages/index.astro
@@ -160,7 +160,7 @@ Astro.response.headers.set(
// This should add the first tour step
steps: [
{
- text: '\n
\n Shepherd is a JavaScript library for guiding users through your app.\n It uses Floating UI,\n another open source library, to render dialogs for each tour "step".\n
\n \n
\n Among many things, Floating UI makes sure your steps never end up off screen or cropped by an overflow.\n (Try resizing your browser to see what we mean.)\n
\n',
+ text: '\n
\n Shepherd is a JavaScript library for guiding users through your app.\n It renders a dialog for each tour "step", positioned\n by its own small engine, with no dependencies.\n
\n \n
\n Among many things, it makes sure your steps never end up off screen or cropped by an overflow.\n (Try resizing your browser to see what we mean.)\n
\n',
attachTo: {
element: '.hero-welcome',
on: 'bottom'
diff --git a/shepherd.js/AGENTS.md b/shepherd.js/AGENTS.md
index 089f67a24..23b8630da 100644
--- a/shepherd.js/AGENTS.md
+++ b/shepherd.js/AGENTS.md
@@ -53,6 +53,9 @@ tour.start();
replaces the default for that option, so a step's `buttons` replace the default
buttons and its `cancelIcon` replaces the whole default object. Only `classes` and
`floatingUIOptions` combine.
+- **`floatingUIOptions`** takes Floating UI's `computePosition` config. Shepherd has its
+ own positioning and does not depend on Floating UI. To use middleware, install
+ `@floating-ui/dom` yourself: `floatingUIOptions: { middleware: [offset(12)] }`.
- **`scrollTo: true`** is needed to scroll a target into view. It is off by default.
- **`title` and `text` render as HTML.** Escape untrusted input.
- **`Shepherd.activeTour`** is empty until a tour starts. Do not read it while defining
@@ -88,8 +91,8 @@ from `step.complete()` and `step.cancel()`. Per-step events go in
you need to refer to them. To advance when the user does something on the page, use
`advanceOn: { selector: '#menu', event: 'click' }`.
-Escape and the arrow keys work once focus has moved into the step, about 300 ms after
-it shows.
+Escape and the arrow keys work once focus has moved into the step, one frame after
+it is positioned.
## React
diff --git a/shepherd.js/dev/index.html b/shepherd.js/dev/index.html
index 4eff10ec9..54f1c45be 100644
--- a/shepherd.js/dev/index.html
+++ b/shepherd.js/dev/index.html
@@ -133,12 +133,12 @@
Example
text: `
Shepherd is a JavaScript library for guiding users through your app.
- It uses Floating UI,
- another open source library, to render dialogs for each tour "step".
+ It renders a dialog for each tour "step", positioned
+ by its own small engine, with no dependencies.
- Among many things, Floating UI makes sure your steps never end up off screen or cropped by an overflow.
+ Among many things, it makes sure your steps never end up off screen or cropped by an overflow.
(Try resizing your browser to see what we mean.)
Shepherd is a JavaScript library for guiding users through your app.
- It uses Floating UI,
- another open source library, to render dialogs for each tour "step".
+ It renders a dialog for each tour "step", positioned
+ by its own small engine, with no dependencies.
- Among many things, Floating UI makes sure your steps never end up off screen or cropped by an overflow.
+ Among many things, it makes sure your steps never end up off screen or cropped by an overflow.
(Try resizing your browser to see what we mean.)
Shepherd is a JavaScript library for guiding users through your app.
- It uses Floating UI,
- another open source library, to render dialogs for each tour "step".
+ It renders a dialog for each tour "step", positioned
+ by its own small engine, with no dependencies.
- Among many things, Floating UI makes sure your steps never end up off screen or cropped by an overflow.
+ Among many things, it makes sure your steps never end up off screen or cropped by an overflow.
(Try resizing your browser to see what we mean.)
`,
attachTo: {
From 919851e1cdab7d1348fdefe2886ff7bd7f3b3409 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 21:57:16 -0500
Subject: [PATCH 57/93] feat: glide the modal opening between steps
The opening morphs from the previous target to the next instead of cutting,
in Chromium, Firefox and WebKit. CSS transitions on `d` do not run in WebKit,
so the path's numbers are tweened in the existing frame loop.
The path's transition-duration sets the length; the default stylesheet only
sets one under prefers-reduced-motion: no-preference.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/components/shepherd-modal.css | 7 +
shepherd.js/src/components/shepherd-modal.ts | 32 ++++-
.../unit/components/shepherd-modal.spec.js | 133 ++++++++++++++++++
3 files changed, 170 insertions(+), 2 deletions(-)
diff --git a/shepherd.js/src/components/shepherd-modal.css b/shepherd.js/src/components/shepherd-modal.css
index 56f625da2..09357cde0 100644
--- a/shepherd.js/src/components/shepherd-modal.css
+++ b/shepherd.js/src/components/shepherd-modal.css
@@ -27,3 +27,10 @@
.shepherd-modal-overlay-container.shepherd-modal-is-visible path {
pointer-events: all;
}
+
+/* Read by the modal to glide the opening between steps; nothing transitions. */
+@media (prefers-reduced-motion: no-preference) {
+ .shepherd-modal-overlay-container path {
+ transition: none 0.42s;
+ }
+}
diff --git a/shepherd.js/src/components/shepherd-modal.ts b/shepherd.js/src/components/shepherd-modal.ts
index a8cce7d2d..355b51a1d 100644
--- a/shepherd.js/src/components/shepherd-modal.ts
+++ b/shepherd.js/src/components/shepherd-modal.ts
@@ -74,12 +74,18 @@ export interface ShepherdModalAPI {
getElement: () => SVGElement;
}
+const PATH_NUMBER = /-?[\d.]+(e-\d+)?/g;
+
export function createShepherdModal(container: HTMLElement): ShepherdModalAPI {
let rafId: number | undefined;
- let currentPath: string | undefined;
+ let currentPath = '';
// Memoizes the chain of scroll parents of a highlighted element for the
// lifetime of a single step. Reset in `_cleanupStepEventListeners`.
let _stepScrollParents = new WeakMap();
+ let isClosed: boolean;
+ let glideFrom: string[];
+ let glideEnd: number;
+ let glideMs: number;
// Build SVG elements
const pathEl = document.createElementNS(SVG_NS, 'path');
@@ -94,7 +100,22 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI {
container.append(element);
function _updatePath(openings: OpeningProperty[]) {
- const d = makeOverlayPath(openings);
+ const to = makeOverlayPath(openings);
+ const left = (glideEnd - Date.now()) / glideMs;
+ let i = 0;
+
+ // Consecutive paths share a shape, so tweening their numbers morphs the
+ // opening. Keeping `-0` as written keeps it apart from the arc flag before
+ // it, or an interrupted glide would misread `00` as one number.
+ const d =
+ left > 0
+ ? to.replace(
+ PATH_NUMBER,
+ (n) =>
+ `${+n + (+(glideFrom[i++] || n) - +n) * left ** 3 || (+n ? 0 : n)}`
+ )
+ : to;
+
// Writing `d` invalidates layout even when the value is unchanged, and this
// runs every frame.
if (d !== currentPath) {
@@ -104,6 +125,8 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI {
}
function closeModalOpening() {
+ isClosed = true;
+ glideEnd = 0;
_updatePath([{ width: 0, height: 0, x: 0, y: 0, r: 0 }]);
}
@@ -189,6 +212,7 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI {
});
}
+ isClosed = false;
_updatePath(newOpenings);
} else {
closeModalOpening();
@@ -199,6 +223,10 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI {
_cleanupStepEventListeners();
if (step.tour.options.useModalOverlay) {
+ glideFrom = currentPath.match(PATH_NUMBER)!;
+ glideMs = parseFloat(getComputedStyle(pathEl).transitionDuration) * 1e3;
+ // A closed opening sits at the origin, with nowhere to glide from.
+ glideEnd = isClosed ? 0 : Date.now() + glideMs;
_styleForStep(step);
show();
} else {
diff --git a/shepherd.js/test/unit/components/shepherd-modal.spec.js b/shepherd.js/test/unit/components/shepherd-modal.spec.js
index 11bf08ae2..78e35c610 100644
--- a/shepherd.js/test/unit/components/shepherd-modal.spec.js
+++ b/shepherd.js/test/unit/components/shepherd-modal.spec.js
@@ -15,6 +15,139 @@ describe('components/ShepherdModal', () => {
container.remove();
});
+ describe('gliding between steps', () => {
+ const rect = (x, y, width, height) => ({
+ x,
+ y,
+ width,
+ height,
+ top: y,
+ left: x,
+ bottom: y + height,
+ right: x + width
+ });
+ let modal;
+ let now;
+
+ function makeStep(box, options = {}) {
+ const target = document.createElement('div');
+ target.getBoundingClientRect = () => box;
+ target.style.position = 'fixed';
+ document.body.append(target);
+ const tour = new Tour({ useModalOverlay: true });
+ const step = new Step(tour, { ...options });
+ step.target = target;
+ return step;
+ }
+
+ const path = () => modal.getElement().querySelector('path');
+ const settled = (x, y, width, height) =>
+ `M1024,768H0V0H1024V768ZM${x},${y}a0,0,0,0,0-0,0V${y + height}a0,0,0,0,0,0,0H${x + width}a0,0,0,0,0,0-0V${y}a0,0,0,0,0-0-0Z`;
+
+ beforeEach(() => {
+ now = 1000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ modal = createShepherdModal(container);
+ });
+
+ afterEach(() => {
+ modal.destroy();
+ vi.restoreAllMocks();
+ });
+
+ function setDuration(value) {
+ path().style.transitionDuration = value;
+ }
+
+ it('cuts straight to the target without a transition duration', () => {
+ modal.setupForStep(makeStep(rect(0, 0, 100, 100)));
+ modal.setupForStep(makeStep(rect(200, 300, 50, 50)));
+
+ expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50));
+ });
+
+ it('does not glide into the first opening', () => {
+ setDuration('1s');
+ modal.setupForStep(makeStep(rect(200, 300, 50, 50)));
+
+ expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50));
+ });
+
+ it('starts from the previous opening and lands exactly on the target', () => {
+ setDuration('1s');
+ modal.setupForStep(makeStep(rect(0, 0, 100, 100)));
+ const to = makeStep(rect(200, 300, 50, 50));
+ modal.setupForStep(to);
+
+ expect(path().getAttribute('d')).toBe(settled(0, 0, 100, 100));
+
+ now += 500;
+ modal.positionModal(0, 0, 0, 0, null, to.target);
+ const [, x, y] = path()
+ .getAttribute('d')
+ .match(/ZM([\d.]+),([\d.]+)/);
+ // 1 - 0.5^3 of the way there
+ expect(Number(x)).toBeCloseTo(175);
+ expect(Number(y)).toBeCloseTo(262.5);
+
+ now += 500;
+ modal.positionModal(0, 0, 0, 0, null, to.target);
+ expect(path().getAttribute('d')).toBe(settled(200, 300, 50, 50));
+ });
+
+ it('writes the path on every frame of a glide, then stops', () => {
+ setDuration('1s');
+ modal.setupForStep(makeStep(rect(0, 0, 100, 100)));
+ const to = makeStep(rect(200, 300, 50, 50));
+ modal.setupForStep(to);
+ const writePath = vi.spyOn(path(), 'setAttribute');
+ const frame = () => modal.positionModal(0, 0, 0, 0, null, to.target);
+
+ for (const expected of [1, 2, 3]) {
+ now += 250;
+ frame();
+ expect(writePath, 'mid glide').toHaveBeenCalledTimes(expected);
+ }
+
+ now += 250;
+ frame();
+ expect(writePath, 'landing').toHaveBeenCalledTimes(4);
+
+ now += 16;
+ frame();
+ frame();
+ expect(writePath, 'settled').toHaveBeenCalledTimes(4);
+ });
+
+ it('stays aligned when a zero-radius glide is interrupted', () => {
+ setDuration('1s');
+ modal.setupForStep(makeStep(rect(0, 0, 100, 100)));
+ const middle = makeStep(rect(200, 300, 50, 50));
+ modal.setupForStep(middle);
+ now += 500;
+ modal.positionModal(0, 0, 0, 0, null, middle.target);
+ const interrupted = path().getAttribute('d');
+ expect(interrupted).toContain('0,0,0-0,0');
+
+ const to = makeStep(rect(600, 500, 20, 20));
+ modal.setupForStep(to);
+ expect(path().getAttribute('d')).toBe(interrupted);
+
+ now += 1000;
+ modal.positionModal(0, 0, 0, 0, null, to.target);
+ expect(path().getAttribute('d')).toBe(settled(600, 500, 20, 20));
+ });
+
+ it('closes without gliding towards the origin', () => {
+ setDuration('1s');
+ modal.setupForStep(makeStep(rect(200, 300, 50, 50)));
+ modal.setupForStep(makeStep(rect(10, 10, 50, 50)));
+ modal.closeModalOpening();
+
+ expect(path().getAttribute('d')).toBe(settled(0, 0, 0, 0));
+ });
+ });
+
describe('closeModalOpening()', function () {
it('sets values back to 0', () => {
const modal = createShepherdModal(container);
From 549f588271f79b8c360c7b0a8fa2f4e664be2e88 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 21:57:16 -0500
Subject: [PATCH 58/93] feat: add an optional theme and shepherd.js/motion
dist/css/theme.css is a token-driven stylesheet with dark mode, entry
choreography and a landing ring. shepherd.js/motion exports glideSteps, which
moves the dialog with the opening, and stepProgress, which feeds the theme's
counter and bar. Neither ships unless imported.
dummy/motion.html demonstrates all of it.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/dummy/motion.html | 343 +++++++++++++++++++++++++++
shepherd.js/package.json | 10 +
shepherd.js/rollup.config.mjs | 45 ++++
shepherd.js/src/motion.ts | 75 ++++++
shepherd.js/src/theme.css | 239 +++++++++++++++++++
shepherd.js/test/unit/motion.spec.js | 111 +++++++++
6 files changed, 823 insertions(+)
create mode 100644 shepherd.js/dummy/motion.html
create mode 100644 shepherd.js/src/motion.ts
create mode 100644 shepherd.js/src/theme.css
create mode 100644 shepherd.js/test/unit/motion.spec.js
diff --git a/shepherd.js/dummy/motion.html b/shepherd.js/dummy/motion.html
new file mode 100644
index 000000000..fc8204c95
--- /dev/null
+++ b/shepherd.js/dummy/motion.html
@@ -0,0 +1,343 @@
+
+
+
+
+
+ Shepherd motion demo
+
+
+
+
+
+
+
+
+
+
North pasture
+
+
+
+
+
+
+
+
+
212Head
+
+ 41%Grazed this week
+
+
+ 18 mmRain since Monday
+
+
+
+
+
+
Next move
+
When
+
Head
+
+
+
+
+
River flat
+
Thursday
+
84
+
+
+
Top paddock
+
Saturday
+
128
+
+
+
+
+
South gate is closed. Nothing has passed it since Tuesday.
+
+
+
+
+
+
+
+
diff --git a/shepherd.js/package.json b/shepherd.js/package.json
index 5b8376f86..9986d692f 100644
--- a/shepherd.js/package.json
+++ b/shepherd.js/package.json
@@ -39,6 +39,16 @@
"default": "./dist/cjs/shepherd.cjs"
}
},
+ "./motion": {
+ "import": {
+ "types": "./dist/js/motion.d.mts",
+ "default": "./dist/js/motion.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/motion.d.cts",
+ "default": "./dist/cjs/motion.cjs"
+ }
+ },
"./dist/*": "./dist/*",
"./tour.schema.json": "./tour.schema.json"
},
diff --git a/shepherd.js/rollup.config.mjs b/shepherd.js/rollup.config.mjs
index 3787c63fe..1b5dc02be 100644
--- a/shepherd.js/rollup.config.mjs
+++ b/shepherd.js/rollup.config.mjs
@@ -192,5 +192,50 @@ export default [
}
}
]
+ },
+ // Opt-in extras: neither ships unless a consumer imports it
+ {
+ input: 'src/motion.ts',
+ output: [
+ { file: 'dist/js/motion.mjs', format: 'es' },
+ { file: 'dist/cjs/motion.cjs', format: 'cjs', exports: 'named' }
+ ],
+ plugins: [
+ nodeResolve({ extensions: ['.ts'] }),
+ babel({
+ extensions: ['.ts'],
+ babelHelpers: 'bundled',
+ presets: ['@babel/preset-typescript']
+ }),
+ ...(isDev ? [] : [terser()]),
+ {
+ name: 'Motion declarations',
+ closeBundle: () => {
+ const types = fs
+ .readFileSync('tmp/js/motion.d.ts', 'utf8')
+ .replace(/\/\/# sourceMappingURL.*/, '');
+ fs.writeFileSync(
+ 'dist/js/motion.d.mts',
+ types.replace('./shepherd.ts', './shepherd.mjs')
+ );
+ fs.writeFileSync(
+ 'dist/cjs/motion.d.cts',
+ types.replace('./shepherd.ts', './shepherd.cjs')
+ );
+ }
+ }
+ ]
+ },
+ {
+ input: 'src/theme.css',
+ output: { dir: 'tmp/theme' },
+ plugins: [
+ postcss({ minimize: !isDev, extract: 'theme.css' }),
+ {
+ name: 'Copy the theme to dist',
+ closeBundle: () =>
+ fs.copyFileSync('tmp/theme/theme.css', 'dist/css/theme.css')
+ }
+ ]
}
];
diff --git a/shepherd.js/src/motion.ts b/shepherd.js/src/motion.ts
new file mode 100644
index 000000000..542cab23b
--- /dev/null
+++ b/shepherd.js/src/motion.ts
@@ -0,0 +1,75 @@
+import type { Step, Tour } from './shepherd.ts';
+
+/**
+ * Glides each step's dialog from where the previous one sat instead of cutting
+ * to its new position, on the same curve as the modal overlay's opening.
+ *
+ * It animates the `translate` property, which composes with whatever positions
+ * the dialog, and does nothing under `prefers-reduced-motion: reduce`.
+ *
+ * @param tour The tour to animate.
+ * @param duration Length of the glide in milliseconds.
+ * @returns A function that stops gliding.
+ */
+export function glideSteps(tour: Tour, duration = 420) {
+ let from: DOMRect | undefined;
+
+ const onShow = ({ step }: { step: Step }) => {
+ step.once('show', () =>
+ requestAnimationFrame(() => {
+ const el = step.getElement();
+ if (
+ el &&
+ from?.width &&
+ !matchMedia('(prefers-reduced-motion: reduce)').matches
+ ) {
+ const to = el.getBoundingClientRect();
+ const dx = from.left + from.width / 2 - to.left - to.width / 2;
+ const dy = from.top + from.height / 2 - to.top - to.height / 2;
+ // Holding opacity at 1 reads as one dialog moving, not a new one fading.
+ el.animate(
+ { translate: [`${dx}px ${dy}px`, '0 0'], opacity: [1, 1] },
+ { duration, easing: 'cubic-bezier(0.33, 1, 0.68, 1)' }
+ );
+ }
+ })
+ );
+ step.once('before-hide', () => {
+ from = step.getElement()?.getBoundingClientRect();
+ });
+ };
+
+ const onStart = () => {
+ from = undefined;
+ };
+
+ tour.on('start', onStart);
+ tour.on('show', onShow);
+ return () => {
+ tour.off('start', onStart);
+ tour.off('show', onShow);
+ };
+}
+
+/**
+ * Exposes each step's position as the `--shepherd-step` and `--shepherd-steps`
+ * custom properties on its dialog, which `shepherd.js/dist/css/theme.css` draws
+ * as a counter and a progress bar.
+ *
+ * @param tour The tour to report progress for.
+ * @returns A function that stops updating the properties.
+ */
+export function stepProgress(tour: Tour) {
+ const onShow = ({ step }: { step: Step }) => {
+ step.once('show', () => {
+ const style = step.getElement()?.style;
+ style?.setProperty('--shepherd-step', `${tour.steps.indexOf(step) + 1}`);
+ style?.setProperty('--shepherd-steps', `${tour.steps.length}`);
+ });
+ };
+
+ tour.on('show', onShow);
+ return () => {
+ tour.off('show', onShow);
+ };
+}
diff --git a/shepherd.js/src/theme.css b/shepherd.js/src/theme.css
new file mode 100644
index 000000000..8872e27ee
--- /dev/null
+++ b/shepherd.js/src/theme.css
@@ -0,0 +1,239 @@
+/*
+ * Optional theme: import after shepherd.css. Every colour and dimension is a
+ * custom property, so restyling means overriding a token, not a selector. It
+ * follows the OS colour scheme; set `--shepherd-color-scheme` on :root to pin it.
+ * Pair it with `defaultStepOptions: { modalOverlayOpeningPadding: 8,
+ * modalOverlayOpeningRadius: 10 }` so the opening matches the surface.
+ */
+.shepherd-element,
+.shepherd-modal-overlay-container,
+.shepherd-target {
+ --shepherd-accent: #fa7fee;
+ --shepherd-on-accent: #16202d;
+ --shepherd-ink: light-dark(#16202d, #eef1f5);
+ --shepherd-muted: light-dark(#4f5b6a, #aab4c0);
+ --shepherd-surface: light-dark(#fff, #1b2635);
+ --shepherd-line: light-dark(rgb(22 32 45 / 0.12), rgb(255 255 255 / 0.14));
+ --shepherd-shade: #0b121c;
+ --shepherd-shade-opacity: 0.62;
+ --shepherd-radius: 14px;
+ --shepherd-gap: 16px;
+ --shepherd-ease: cubic-bezier(0.33, 1, 0.68, 1);
+}
+
+.shepherd-element {
+ background: var(--shepherd-surface);
+ border-radius: var(--shepherd-radius);
+ box-shadow:
+ 0 0 0 1px var(--shepherd-line),
+ 0 2px 6px rgb(11 18 28 / 0.14),
+ 0 18px 40px -12px rgb(11 18 28 / 0.42);
+ color: var(--shepherd-ink);
+ color-scheme: var(--shepherd-color-scheme, light dark);
+ max-width: 22.5rem;
+ transition: opacity 0.24s;
+}
+
+.shepherd-element[data-popper-placement^='bottom'] {
+ margin-top: var(--shepherd-gap);
+}
+
+.shepherd-element[data-popper-placement^='top'] {
+ margin-top: calc(-1 * var(--shepherd-gap));
+}
+
+.shepherd-element[data-popper-placement^='right'] {
+ margin-left: var(--shepherd-gap);
+}
+
+.shepherd-element[data-popper-placement^='left'] {
+ margin-left: calc(-1 * var(--shepherd-gap));
+}
+
+.shepherd-modal-overlay-container path {
+ fill: var(--shepherd-shade);
+}
+
+.shepherd-modal-overlay-container.shepherd-modal-is-visible {
+ opacity: var(--shepherd-shade-opacity);
+}
+
+.shepherd-arrow:before,
+.shepherd-element.shepherd-has-title[data-popper-placement^='bottom']
+ > .shepherd-arrow::before {
+ background: var(--shepherd-surface);
+}
+
+.shepherd-content {
+ border-radius: inherit;
+ overflow: hidden;
+ position: relative;
+}
+
+.shepherd-has-title .shepherd-content .shepherd-header {
+ background: none;
+ padding: 1.125rem 1.125rem 0;
+}
+
+.shepherd-title {
+ color: inherit;
+ font-size: 1.0625rem;
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ line-height: 1.3;
+ text-wrap: balance;
+}
+
+.shepherd-text {
+ color: var(--shepherd-muted);
+ font-size: 0.9375rem;
+ line-height: 1.5;
+ padding: 0.5rem 1.125rem 1.125rem;
+ text-wrap: pretty;
+}
+
+.shepherd-footer {
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0 1.125rem 1.125rem;
+}
+
+.shepherd-button {
+ background: var(--shepherd-accent);
+ border-radius: 8px;
+ color: var(--shepherd-on-accent);
+ font: inherit;
+ font-size: 0.875rem;
+ font-weight: 600;
+ margin: 0;
+ padding: 0.5rem 0.875rem;
+ transition:
+ filter 0.15s,
+ background-color 0.15s,
+ scale 0.15s;
+}
+
+.shepherd-button:not(:disabled):hover {
+ background: var(--shepherd-accent);
+ color: var(--shepherd-on-accent);
+ filter: brightness(1.06) saturate(1.1);
+}
+
+.shepherd-button:not(:disabled):active {
+ scale: 0.97;
+}
+
+.shepherd-button:focus-visible,
+.shepherd-cancel-icon:focus-visible {
+ outline: 2px solid var(--shepherd-ink);
+ outline-offset: 2px;
+}
+
+.shepherd-button.shepherd-button-secondary {
+ background: transparent;
+ box-shadow: inset 0 0 0 1px var(--shepherd-line);
+ color: var(--shepherd-ink);
+}
+
+.shepherd-button.shepherd-button-secondary:not(:disabled):hover {
+ background: var(--shepherd-line);
+ color: var(--shepherd-ink);
+ filter: none;
+}
+
+.shepherd-button:disabled {
+ opacity: 0.5;
+}
+
+.shepherd-cancel-icon,
+.shepherd-has-title .shepherd-content .shepherd-cancel-icon {
+ border-radius: 6px;
+ color: var(--shepherd-muted);
+ font-size: 1.5rem;
+ line-height: 1;
+ transition: color 0.15s;
+}
+
+.shepherd-cancel-icon:hover,
+.shepherd-has-title .shepherd-content .shepherd-cancel-icon:hover {
+ color: var(--shepherd-ink);
+}
+
+/* stepProgress() from shepherd.js/motion supplies the two counts. */
+.shepherd-element[style*='--shepherd-step'] .shepherd-footer::before {
+ color: var(--shepherd-muted);
+ content: counter(shepherd-step) ' / ' counter(shepherd-steps);
+ counter-reset: shepherd-step var(--shepherd-step) shepherd-steps
+ var(--shepherd-steps);
+ font-size: 0.8125rem;
+ font-variant-numeric: tabular-nums;
+ margin-right: auto;
+}
+
+.shepherd-element[style*='--shepherd-step'] .shepherd-content::after {
+ background: var(--shepherd-accent);
+ content: '';
+ height: 3px;
+ inset: 0 0 auto;
+ position: absolute;
+ transform: scaleX(calc(var(--shepherd-step) / var(--shepherd-steps)));
+ transform-origin: 0 0;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .shepherd-element {
+ transition:
+ opacity 0.24s,
+ scale 0.42s var(--shepherd-ease),
+ translate 0.42s var(--shepherd-ease);
+ }
+
+ @starting-style {
+ .shepherd-enabled.shepherd-element {
+ opacity: 0;
+ scale: 0.96;
+ }
+
+ .shepherd-enabled.shepherd-element[data-popper-placement^='bottom'] {
+ translate: 0 -8px;
+ }
+
+ .shepherd-enabled.shepherd-element[data-popper-placement^='top'] {
+ translate: 0 8px;
+ }
+
+ .shepherd-enabled.shepherd-element[data-popper-placement^='right'] {
+ translate: -8px 0;
+ }
+
+ .shepherd-enabled.shepherd-element[data-popper-placement^='left'] {
+ translate: 8px 0;
+ }
+
+ .shepherd-element[style*='--shepherd-step'] .shepherd-content::after {
+ transform: scaleX(
+ calc((var(--shepherd-step) - 1) / var(--shepherd-steps))
+ );
+ }
+ }
+
+ .shepherd-element[style*='--shepherd-step'] .shepherd-content::after {
+ transition: transform 0.42s var(--shepherd-ease);
+ }
+
+ .shepherd-target:not(body) {
+ animation: shepherd-landed 0.7s 0.3s var(--shepherd-ease);
+ }
+
+ @keyframes shepherd-landed {
+ from {
+ outline: 2px solid var(--shepherd-accent);
+ outline-offset: 2px;
+ }
+
+ to {
+ outline: 2px solid transparent;
+ outline-offset: 14px;
+ }
+ }
+}
diff --git a/shepherd.js/test/unit/motion.spec.js b/shepherd.js/test/unit/motion.spec.js
new file mode 100644
index 000000000..e96935ce1
--- /dev/null
+++ b/shepherd.js/test/unit/motion.spec.js
@@ -0,0 +1,111 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { glideSteps, stepProgress } from '../../src/motion.ts';
+import { Tour } from '../../src/tour';
+
+describe('motion', () => {
+ let tour;
+ let reduced;
+
+ beforeEach(() => {
+ reduced = false;
+ vi.stubGlobal('matchMedia', () => ({ matches: reduced }));
+ vi.stubGlobal('requestAnimationFrame', (callback) => {
+ callback(0);
+ return 1;
+ });
+ Element.prototype.animate = vi.fn();
+ tour = new Tour();
+ tour.addStep({ id: 'one', text: 'one' });
+ tour.addStep({ id: 'two', text: 'two' });
+ });
+
+ afterEach(() => {
+ if (tour.isActive()) {
+ tour.complete();
+ }
+ vi.unstubAllGlobals();
+ delete Element.prototype.animate;
+ });
+
+ describe('glideSteps', () => {
+ function rectEachElement() {
+ const original = Element.prototype.getBoundingClientRect;
+ let left = 0;
+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(
+ function () {
+ if (!this.classList?.contains('shepherd-element')) {
+ return original.call(this);
+ }
+ // Each element sits 100px right of the one created before it.
+ this.left ??= left++ * 100;
+ return { left: this.left, top: 0, width: 50, height: 50 };
+ }
+ );
+ }
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it('leaves the first step alone', () => {
+ rectEachElement();
+ glideSteps(tour);
+ tour.start();
+
+ expect(Element.prototype.animate).not.toHaveBeenCalled();
+ });
+
+ it('animates translate from the previous dialog to the new one', () => {
+ rectEachElement();
+ glideSteps(tour, 300);
+ tour.start();
+ tour.next();
+
+ expect(Element.prototype.animate).toHaveBeenCalledTimes(1);
+ const [keyframes, options] = Element.prototype.animate.mock.calls[0];
+ expect(keyframes.translate[0]).toMatch(/^-?\d+(\.\d+)?px 0px$/);
+ expect(keyframes.translate[1]).toBe('0 0');
+ expect(options.duration).toBe(300);
+ });
+
+ it('does nothing under reduced motion', () => {
+ rectEachElement();
+ reduced = true;
+ glideSteps(tour);
+ tour.start();
+ tour.next();
+
+ expect(Element.prototype.animate).not.toHaveBeenCalled();
+ });
+
+ it('does not glide from the last run when the tour restarts', () => {
+ rectEachElement();
+ glideSteps(tour);
+ tour.start();
+ tour.complete();
+ tour.start();
+
+ expect(Element.prototype.animate).not.toHaveBeenCalled();
+ });
+
+ it('stops when disposed', () => {
+ rectEachElement();
+ const stop = glideSteps(tour);
+ stop();
+ tour.start();
+ tour.next();
+
+ expect(Element.prototype.animate).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('stepProgress', () => {
+ it('exposes the position and count on each dialog', () => {
+ stepProgress(tour);
+ tour.start();
+ tour.next();
+
+ const { style } = tour.getCurrentStep().getElement();
+ expect(style.getPropertyValue('--shepherd-step')).toBe('2');
+ expect(style.getPropertyValue('--shepherd-steps')).toBe('2');
+ });
+ });
+});
From aa28ee4db08dabbe39eefaf0cc9473744bd4d5d3 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 23:37:07 -0500
Subject: [PATCH 59/93] refactor: stop resetting the overlay's frame id
Cancelling a frame that already ran does nothing, so the id does not need
clearing around each frame.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/components/shepherd-modal.ts | 2 --
1 file changed, 2 deletions(-)
diff --git a/shepherd.js/src/components/shepherd-modal.ts b/shepherd.js/src/components/shepherd-modal.ts
index 355b51a1d..4305c7ec3 100644
--- a/shepherd.js/src/components/shepherd-modal.ts
+++ b/shepherd.js/src/components/shepherd-modal.ts
@@ -257,7 +257,6 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI {
function _cleanupStepEventListeners() {
if (rafId) {
cancelAnimationFrame(rafId);
- rafId = undefined;
}
// Scroll parents are only memoized for the duration of a single step.
@@ -278,7 +277,6 @@ export function createShepherdModal(container: HTMLElement): ShepherdModalAPI {
const targetScrollParent = _cachedScrollParents(step.target)[0] ?? null;
const rafLoop = () => {
- rafId = undefined;
positionModal(
modalOverlayOpeningPadding,
modalOverlayOpeningRadius,
From 5cab018c741bd4c3844c2dfb910643765483f517 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 23:55:08 -0500
Subject: [PATCH 60/93] fix: await a custom platform's methods in the engine's
middleware
Floating UI lets any platform method return a promise, and the engine's own
flip, shift and arrow read them synchronously. A step with an async
getClippingRect got NaN coordinates, which the browser drops, so it sat
unpositioned.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/position.ts | 26 +++++++++++++-------------
1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index bf31838c0..d30893067 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -441,7 +441,7 @@ function getClippingRect({
};
}
-function detectOverflow(
+async function detectOverflow(
state: MiddlewareState,
{
boundary = 'clippingAncestors',
@@ -450,11 +450,11 @@ function detectOverflow(
altBoundary = false,
padding = 0
}: Record = {}
-): Record {
+): Promise> {
const { x, y, platform, rects, elements, strategy } = state;
const pad = (side: Side) =>
(typeof padding === 'number' ? padding : padding[side]) || 0;
- const clip: Rect = platform.getClippingRect({
+ const clip: Rect = await platform.getClippingRect({
element:
elements[
altBoundary
@@ -467,10 +467,10 @@ function detectOverflow(
rootBoundary,
strategy
});
- const offsetParent = platform.getOffsetParent(elements.floating);
- const scale: Coords = platform.getScale(offsetParent);
+ const offsetParent = await platform.getOffsetParent(elements.floating);
+ const scale: Coords = await platform.getScale(offsetParent);
const box: Rect =
- platform.convertOffsetParentRelativeRectToViewportRelativeRect({
+ await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
elements,
rect:
elementContext === 'floating'
@@ -630,7 +630,7 @@ function placementSearch(
return {
name,
options,
- fn(state: MiddlewareState): MiddlewareResult {
+ async fn(state: MiddlewareState): Promise {
const { placement, initialPlacement, middlewareData } = state;
const { platform, rects, elements } = state;
const { index = 0, overflows: previous = [] } =
@@ -645,11 +645,11 @@ function placementSearch(
return { reset: { placement: placements[0] as Placement } };
}
- const overflow = platform.detectOverflow(state);
+ const overflow = await platform.detectOverflow(state);
const [first, second] = alignmentSides(
placement,
rects,
- platform.isRTL(elements.floating)
+ await platform.isRTL(elements.floating)
);
const overflows: number[] = [
overflow[sideOf(placement)],
@@ -741,10 +741,10 @@ export function autoPlacement(options: {
export function shift(): Middleware {
return {
name: 'shift',
- fn(state: MiddlewareState): MiddlewareResult {
+ async fn(state: MiddlewareState): Promise {
const { x, y, placement, rects, middlewareData, platform } = state;
const { reference, floating } = rects;
- const overflow = platform.detectOverflow(state);
+ const overflow = await platform.detectOverflow(state);
const cross = sideAxis(placement);
const main = otherAxis(cross);
const fromOrigin = /^[tl]/.test(placement);
@@ -786,13 +786,13 @@ export function arrow(options: {
return {
name: 'arrow',
options,
- fn(state: MiddlewareState): MiddlewareResult {
+ async fn(state: MiddlewareState): Promise {
const { placement, rects, platform, elements, middlewareData } = state;
const { element, padding = 0 } = options;
const axis = otherAxis(sideAxis(placement));
const length = lengthOf(axis);
const start = state[axis];
- const arrowLength = platform.getDimensions(element)[length];
+ const arrowLength = (await platform.getDimensions(element))[length];
const free =
(axis === 'y'
? elements.floating.clientHeight
From 7b56de8c4b06cdd409ae25a798c6796614588420 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 23:58:09 -0500
Subject: [PATCH 61/93] fix: keep :modal when a browser lacks :popover-open
One unsupported selector invalidates a whole list, so in a browser without
:popover-open, a step in a modal dialog was treated as outside the top layer.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/position.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index d30893067..18dafb1d6 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -215,7 +215,8 @@ function isContainingBlock(style: CSSStyleDeclaration) {
function isTopLayer(element: Element) {
try {
- return element.matches(':popover-open,:modal');
+ // Apart, as a list fails whole. `:modal` shipped first in every browser.
+ return element.matches(':modal') || element.matches(':popover-open');
} catch {
return false;
}
From 39c46a7cdb14e6f22639744b92d9e109840d33f2 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 23:58:09 -0500
Subject: [PATCH 62/93] fix: report a step that could not be positioned, and
focus it anyway
A throwing platform or middleware rejected computePosition with nothing
listening, which left the step unpositioned and unfocused with only an
unhandled rejection to show for it.
Focus falls back to a timer because jsdom has no requestAnimationFrame unless
asked for one, which turned focusing into an unhandled rejection in consumers'
tests.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/floating-ui.ts | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/shepherd.js/src/utils/floating-ui.ts b/shepherd.js/src/utils/floating-ui.ts
index 75dd6ee98..8625ebd05 100644
--- a/shepherd.js/src/utils/floating-ui.ts
+++ b/shepherd.js/src/utils/floating-ui.ts
@@ -102,15 +102,21 @@ function setPosition(
target,
step.el as HTMLElement,
floatingUIOptions
- ).then(floatingUIposition(step, shouldCenter));
+ )
+ .then(floatingUIposition(step, shouldCenter))
+ .catch((error: unknown) => {
+ console.error('Shepherd: could not position a step.', error);
+ return step;
+ });
if (!shouldFocusAfterRender) {
return positionPromise;
}
return positionPromise.then((step: Step) => {
- // Focusing flushes layout, which the next frame does anyway.
- requestAnimationFrame(() => {
+ // Focusing flushes layout, which the next frame does anyway. jsdom only has
+ // frames when asked to.
+ (window.requestAnimationFrame || setTimeout)(() => {
if (step?.el) {
step.el.tabIndex = 0;
step.el.focus({ preventScroll: true });
From 67595f0140416740ba6067823862d737f7d18db9 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Thu, 5 Nov 2026 23:58:09 -0500
Subject: [PATCH 63/93] fix: let the position tracker stop on its own
A route change that unmounts a tour's element without ending the tour left its
heartbeat polling at 10 Hz forever. It now stops once the element has left the
page. A document with no layout, as in jsdom, stops too, since a timer that
reschedules itself makes a consumer's runAllTimers throw.
Also corrects the comment on scroll listeners: scroll events are not composed,
so a scroller in a shadow root or an intermediate iframe waits for the heartbeat.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/position.ts | 28 +++++++++----
shepherd.js/test/unit/fake-timers.spec.js | 32 +++++++++++++++
shepherd.js/test/unit/utils/position.spec.js | 43 ++++++++++++++++++++
3 files changed, 94 insertions(+), 9 deletions(-)
create mode 100644 shepherd.js/test/unit/fake-timers.spec.js
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index 18dafb1d6..c428eb01c 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -847,6 +847,7 @@ export function autoUpdate(
let last: string;
let quietFrames = 0;
let stopped = false;
+ let connected = false;
const check = () => {
const viewport = win.visualViewport;
@@ -870,23 +871,32 @@ export function autoUpdate(
const nextFrame = () => win.requestAnimationFrame?.(loop);
const loop = () => {
if (stopped) return;
+ // A tour abandoned by a route change has no other way to stop this. A
+ // container can attach late, so only leaving the page counts.
+ if (floating.isConnected) connected = true;
+ else if (connected) return stop();
check();
// A timer is the cheap heartbeat, since scheduling a frame makes one happen.
if (++quietFrames < 30) nextFrame();
- else setTimeout(loop, 100);
+ // Nothing moves without layout, as in jsdom, and a consumer's test suite
+ // calling `runAllTimers` would throw on a timer that never stops.
+ else if (htmlOf(floating).clientWidth) setTimeout(loop, 100);
+ };
+ const stop = () => {
+ stopped = true;
+ windows.forEach((target) =>
+ target.removeEventListener('scroll', check, true)
+ );
};
- // Scroll events capture, so this hears every scroller in these documents. The
- // same listener added twice is one listener when both are the same window.
+ // Scroll events capture, so this hears the scrollers in these documents, but
+ // they are not composed. One in a shadow root or an iframe in between waits
+ // for the heartbeat. The same listener added twice is one listener when both
+ // are the same window.
const windows = [win, getWindow(reference)];
windows.forEach((target) => target.addEventListener('scroll', check, true));
update();
nextFrame();
- return () => {
- stopped = true;
- windows.forEach((target) =>
- target.removeEventListener('scroll', check, true)
- );
- };
+ return stop;
}
diff --git a/shepherd.js/test/unit/fake-timers.spec.js b/shepherd.js/test/unit/fake-timers.spec.js
new file mode 100644
index 000000000..90e151ffb
--- /dev/null
+++ b/shepherd.js/test/unit/fake-timers.spec.js
@@ -0,0 +1,32 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { Tour } from '../../src/shepherd';
+
+// A consumer's test suite runs in a DOM with no layout and often calls
+// `runAllTimers`, which throws if a timer keeps rescheduling itself.
+describe('under fake timers', () => {
+ let tour;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ const target = document.createElement('div');
+ target.id = 'fake-timers-target';
+ document.body.append(target);
+ });
+
+ afterEach(() => {
+ tour.complete();
+ vi.useRealTimers();
+ document.getElementById('fake-timers-target').remove();
+ });
+
+ it('lets runAllTimers finish while a step is showing', () => {
+ tour = new Tour();
+ tour.addStep({
+ text: 'hi',
+ attachTo: { element: '#fake-timers-target', on: 'bottom' }
+ });
+ tour.start();
+
+ expect(() => vi.runAllTimers()).not.toThrow();
+ });
+});
diff --git a/shepherd.js/test/unit/utils/position.spec.js b/shepherd.js/test/unit/utils/position.spec.js
index 1b0a2339a..79d3022c1 100644
--- a/shepherd.js/test/unit/utils/position.spec.js
+++ b/shepherd.js/test/unit/utils/position.spec.js
@@ -362,6 +362,49 @@ describe('utils/position', () => {
scroller.remove();
});
+ it('stops on its own once the element leaves the page', async () => {
+ const { reference, floating, rect } = stubbedRects();
+ document.body.append(floating);
+ const removeListener = vi.spyOn(window, 'removeEventListener');
+ const update = vi.fn();
+
+ autoUpdate(reference, floating, update);
+ await nextFrames(2);
+ floating.remove();
+ await nextFrames(2);
+ const settled = update.mock.calls.length;
+
+ rect.y = 700;
+ window.dispatchEvent(new Event('scroll'));
+ await nextFrames(3);
+
+ expect(update).toHaveBeenCalledTimes(settled);
+ expect(removeListener).toHaveBeenCalledWith(
+ 'scroll',
+ expect.any(Function),
+ true
+ );
+ removeListener.mockRestore();
+ });
+
+ it('waits for a container that attaches late', async () => {
+ const { reference, floating, rect } = stubbedRects();
+ floating.remove();
+ const update = vi.fn();
+
+ const stop = autoUpdate(reference, floating, update);
+ await nextFrames(2);
+ document.body.append(floating);
+ await nextFrames(2);
+ const settled = update.mock.calls.length;
+
+ rect.y = 800;
+ await nextFrames(2);
+
+ expect(update).toHaveBeenCalledTimes(settled + 1);
+ stop();
+ });
+
it('still positions once where requestAnimationFrame does not exist', () => {
const { reference, floating } = stubbedRects();
const update = vi.fn();
From 3062dbf2b0405112793ec9cc7794f1870ea9195d Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Fri, 6 Nov 2026 00:06:40 -0500
Subject: [PATCH 64/93] fix: leave out an empty scrollbar gutter from the
viewport
With classic scrollbars, Chromium reserves a scrollbar-gutter: stable gutter
without taking it from the root's clientWidth while nothing overflows, so a step
near the right edge could sit under it. Floating UI spots this by comparing
to the root. This compares the root's own box, so a body narrower than the
root for any other reason does not count as a gutter.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/position.ts | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index c428eb01c..8e5248034 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -342,7 +342,7 @@ function rectInWindow(element: any, targetWindow: Window) {
function rootRect(node: any, rootBoundary: string): Rect {
const html = htmlOf(node);
- const { x } = html.getBoundingClientRect();
+ const { x, width: rootWidth } = html.getBoundingClientRect();
if (rootBoundary === 'document') {
const { body } = getDocument(node);
@@ -373,11 +373,17 @@ function rootRect(node: any, rootBoundary: string): Rect {
// WebKit's client coordinates are relative to the visual viewport, others'
// to the layout viewport.
const offset = !isWebKit() && viewport;
+ const left = x + html.scrollLeft;
+ // With no scrollbar to show, `scrollbar-gutter: stable` narrows the root without
+ // its `clientWidth` showing it. A root offset to the left has no such gutter.
+ const gutter = left > 0 ? 0 : html.clientWidth - rootWidth;
return {
- x: x + html.scrollLeft + (offset ? offset.offsetLeft : 0),
+ x: left + (offset ? offset.offsetLeft : 0),
y: offset ? offset.offsetTop : 0,
- width: viewport ? viewport.width : html.clientWidth,
+ width:
+ (viewport ? viewport.width : html.clientWidth) -
+ (gutter > 0 && gutter < 26 ? gutter : 0),
height: viewport ? viewport.height : html.clientHeight
};
}
From e281838b3795be56639894861cd21a4f507424b9 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Fri, 6 Nov 2026 00:20:26 -0500
Subject: [PATCH 65/93] docs: cover overlay motion, the theme and
shepherd.js/motion
Co-Authored-By: Claude Opus 5.5
---
docs-src/src/content/docs/guides/styling.md | 33 +++++++++++++++++++++
shepherd.js/AGENTS.md | 18 +++++++++++
shepherd.js/llms.txt | 2 ++
shepherd.js/src/tour.ts | 3 +-
4 files changed, 55 insertions(+), 1 deletion(-)
diff --git a/docs-src/src/content/docs/guides/styling.md b/docs-src/src/content/docs/guides/styling.md
index 7cb540147..c7f0984f6 100644
--- a/docs-src/src/content/docs/guides/styling.md
+++ b/docs-src/src/content/docs/guides/styling.md
@@ -7,6 +7,39 @@ title: Styling
Shepherd ships with some default styles, but we try to keep it minimal, so you do not have a ton to override.
You can also opt out of styles entirely, by not including the `shepherd.css` file.
+### Optional theme
+
+`shepherd.js/dist/css/theme.css` is a second stylesheet, with dark mode and entry motion. Import it after `shepherd.css`.
+Every color and dimension in it is a custom property, so you restyle it by overriding `--shepherd-accent` and its
+neighbors rather than selectors.
+
+```js
+import 'shepherd.js/dist/css/shepherd.css';
+import 'shepherd.js/dist/css/theme.css';
+```
+
+It pairs with `shepherd.js/motion`, which ships separately and only costs bytes if you import it. `glideSteps(tour)` moves
+the dialog between steps, and `stepProgress(tour)` feeds the theme's step counter and progress bar. Each returns a function
+that stops it.
+
+```js
+import { glideSteps, stepProgress } from 'shepherd.js/motion';
+
+glideSteps(tour);
+stepProgress(tour);
+```
+
+### Overlay motion
+
+With `useModalOverlay`, the opening glides from one target to the next. Its length comes from `transition-duration` on the
+overlay's path, 0.42s by default, and it cuts straight to the target under `prefers-reduced-motion: reduce`. To turn it off:
+
+```css
+.shepherd-modal-overlay-container path {
+ transition-duration: 0s;
+}
+```
+
### Custom Classes
If you'd like to change styles within your own CSS, you can pass custom class names to the tour instance —
diff --git a/shepherd.js/AGENTS.md b/shepherd.js/AGENTS.md
index 23b8630da..d8aa6be90 100644
--- a/shepherd.js/AGENTS.md
+++ b/shepherd.js/AGENTS.md
@@ -177,6 +177,24 @@ the output schema when a model generates a tour. Functions, such as
| `shepherd-theme-*.css` | `dist/css/shepherd.css` |
| `import { ShepherdTour } from 'react-shepherd'` | `useShepherd`, `ShepherdJourneyProvider` |
+## Motion and theming
+
+The overlay's opening glides between steps by default, and cuts straight there under
+`prefers-reduced-motion: reduce`. Set `transition-duration: 0s` on
+`.shepherd-modal-overlay-container path` to turn it off.
+
+Two extras ship separately, and cost nothing unless imported:
+
+```js
+import 'shepherd.js/dist/css/theme.css'; // After shepherd.css. Restyle it through --shepherd-* properties.
+import { glideSteps, stepProgress } from 'shepherd.js/motion';
+
+glideSteps(tour); // Moves the dialog with the opening.
+stepProgress(tour); // Feeds the theme's step counter and progress bar.
+```
+
+Each of those functions returns a function that stops it.
+
## Licensing
Free under AGPL-3.0 for open source and non-commercial use. Commercial products need a
diff --git a/shepherd.js/llms.txt b/shepherd.js/llms.txt
index 7d5587284..bd40623c8 100644
--- a/shepherd.js/llms.txt
+++ b/shepherd.js/llms.txt
@@ -28,6 +28,8 @@ tour.start();
- `dist/js/shepherd.d.mts`: types and option docs
- `dist/js/shepherd.mjs`: ES module with no global. Import it.
- `dist/css/shepherd.css`: the stylesheet
+- `dist/css/theme.css`: an optional theme, loaded after the stylesheet
+- `shepherd.js/motion`: optional `glideSteps` and `stepProgress`
## Links
diff --git a/shepherd.js/src/tour.ts b/shepherd.js/src/tour.ts
index abe0d141c..e9d756fed 100644
--- a/shepherd.js/src/tour.ts
+++ b/shepherd.js/src/tour.ts
@@ -108,7 +108,8 @@ export interface TourOptions {
* Set this on the tour, not on a step.
* Whether or not steps should be placed above a darkened
* modal overlay. If true, the overlay will create an opening around the target element so that it
- * can remain interactive
+ * can remain interactive. The opening glides between steps for the `transition-duration` set on
+ * the overlay's path, unless the user prefers reduced motion.
*/
useModalOverlay?: boolean;
}
From 26057fe8c95ca467de6758c9409a4281e4b710b9 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Fri, 6 Nov 2026 00:20:26 -0500
Subject: [PATCH 66/93] test: hold the positioning engine to stock Floating UI
in real browsers
Nothing else guards the engine against stock behavior now that the dependency
is gone. pnpm test:position positions the same DOM with both in Chromium, Firefox
and WebKit, in standards and quirks mode, and fails on a difference that is not
in known-differences.json. The README gives the reason for each family.
Three more scripts exercise the published dist: a consumer's own platform through
property mangling, a tour in a cross-origin iframe, and a tour in jsdom, which is
why jsdom is now a devDependency.
Co-Authored-By: Claude Opus 5.5
---
pnpm-lock.yaml | 74 +-
shepherd.js/package.json | 2 +
.../position-differential/cross-origin.mjs | 71 ++
.../position-differential/dist-platform.mjs | 112 +++
.../test/position-differential/fixtures.js | 840 ++++++++++++++++++
.../test/position-differential/jsdom.mjs | 61 ++
.../known-differences.json | 735 +++++++++++++++
.../test/position-differential/run.mjs | 422 +++++++++
shepherd.js/test/unit/fake-timers.spec.js | 4 +
.../test/unit/utils/floating-ui.spec.js | 13 +
shepherd.js/test/unit/utils/position.spec.js | 50 ++
11 files changed, 2331 insertions(+), 53 deletions(-)
create mode 100644 shepherd.js/test/position-differential/cross-origin.mjs
create mode 100644 shepherd.js/test/position-differential/dist-platform.mjs
create mode 100644 shepherd.js/test/position-differential/fixtures.js
create mode 100644 shepherd.js/test/position-differential/jsdom.mjs
create mode 100644 shepherd.js/test/position-differential/known-differences.json
create mode 100644 shepherd.js/test/position-differential/run.mjs
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c66e2f45f..a09f0d297 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -273,6 +273,9 @@ importers:
http-server:
specifier: ^14.1.1
version: 14.1.1(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)
+ jsdom:
+ specifier: ^27.4.0
+ version: 27.4.0(supports-color@8.1.1)
lodash:
specifier: ^4.18.1
version: 4.18.1
@@ -7907,8 +7910,7 @@ packages:
snapshots:
- '@acemir/cssom@0.9.31':
- optional: true
+ '@acemir/cssom@0.9.31': {}
'@adobe/css-tools@4.5.0': {}
@@ -7942,7 +7944,6 @@ snapshots:
'@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0)
'@csstools/css-tokenizer': 4.0.0
lru-cache: 11.5.3
- optional: true
'@asamuzakjp/dom-selector@6.8.1':
dependencies:
@@ -7951,10 +7952,8 @@ snapshots:
css-tree: 3.2.1
is-potential-custom-element-name: 1.0.1
lru-cache: 11.5.3
- optional: true
- '@asamuzakjp/nwsapi@2.3.9':
- optional: true
+ '@asamuzakjp/nwsapi@2.3.9': {}
'@astrojs/check@0.9.10(prettier-plugin-astro@0.14.1)(prettier@3.9.10)(typescript@5.9.3)':
dependencies:
@@ -9620,14 +9619,12 @@ snapshots:
'@colors/colors@1.5.0':
optional: true
- '@csstools/color-helpers@6.1.0':
- optional: true
+ '@csstools/color-helpers@6.1.0': {}
'@csstools/css-calc@3.3.0(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)':
dependencies:
'@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0)
'@csstools/css-tokenizer': 4.0.0
- optional: true
'@csstools/css-color-parser@4.1.10(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)':
dependencies:
@@ -9635,20 +9632,16 @@ snapshots:
'@csstools/css-calc': 3.3.0(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)
'@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0)
'@csstools/css-tokenizer': 4.0.0
- optional: true
'@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0)':
dependencies:
'@csstools/css-tokenizer': 4.0.0
- optional: true
'@csstools/css-syntax-patches-for-csstree@1.1.7(css-tree@3.2.1)':
optionalDependencies:
css-tree: 3.2.1
- optional: true
- '@csstools/css-tokenizer@4.0.0':
- optional: true
+ '@csstools/css-tokenizer@4.0.0': {}
'@ctrl/tinycolor@4.2.1': {}
@@ -9859,8 +9852,7 @@ snapshots:
'@eslint/core': 1.2.1
levn: 0.4.1
- '@exodus/bytes@1.15.1':
- optional: true
+ '@exodus/bytes@1.15.1': {}
'@expressive-code/core@0.44.2':
dependencies:
@@ -10343,7 +10335,7 @@ snapshots:
agent-base: 9.0.0
http-proxy-agent: 9.1.0(supports-color@8.1.1)
https-proxy-agent: 9.1.0(supports-color@8.1.1)
- lru-cache: 11.5.2
+ lru-cache: 11.5.3
socks-proxy-agent: 10.1.0(supports-color@8.1.1)
transitivePeerDependencies:
- kerberos
@@ -11910,7 +11902,6 @@ snapshots:
bidi-js@1.0.3:
dependencies:
require-from-string: 2.0.2
- optional: true
binary-extensions@2.3.0: {}
@@ -12040,7 +12031,7 @@ snapshots:
'@npmcli/fs': 6.0.0
fs-minipass: 3.0.3
glob: 13.0.6
- lru-cache: 11.5.2
+ lru-cache: 11.5.3
minipass: 7.1.3
minipass-collect: 2.0.1
minipass-flush: 1.0.7
@@ -12338,7 +12329,7 @@ snapshots:
css-tree@2.2.1:
dependencies:
mdn-data: 2.0.28
- source-map-js: 1.2.1
+ source-map-js: 1.2.2
css-tree@3.2.1:
dependencies:
@@ -12411,7 +12402,6 @@ snapshots:
'@csstools/css-syntax-patches-for-csstree': 1.1.7(css-tree@3.2.1)
css-tree: 3.2.1
lru-cache: 11.5.3
- optional: true
csstype@3.2.3: {}
@@ -12472,7 +12462,6 @@ snapshots:
dependencies:
whatwg-mimetype: 5.0.0
whatwg-url: 15.1.0
- optional: true
dayjs@1.11.23: {}
@@ -12496,8 +12485,7 @@ snapshots:
decamelize@1.2.0: {}
- decimal.js@10.6.0:
- optional: true
+ decimal.js@10.6.0: {}
decode-named-character-reference@1.3.0:
dependencies:
@@ -12657,8 +12645,7 @@ snapshots:
entities@7.0.1: {}
- entities@8.0.0:
- optional: true
+ entities@8.0.0: {}
env-paths@2.2.1: {}
@@ -13405,7 +13392,6 @@ snapshots:
'@exodus/bytes': 1.15.1
transitivePeerDependencies:
- '@noble/hashes'
- optional: true
html-escaper@2.0.2: {}
@@ -13447,7 +13433,6 @@ snapshots:
debug: 4.4.3(supports-color@8.1.1)
transitivePeerDependencies:
- supports-color
- optional: true
http-proxy-agent@9.1.0(supports-color@8.1.1):
dependencies:
@@ -13518,7 +13503,6 @@ snapshots:
debug: 4.4.3(supports-color@8.1.1)
transitivePeerDependencies:
- supports-color
- optional: true
https-proxy-agent@9.1.0(supports-color@8.1.1):
dependencies:
@@ -13673,8 +13657,7 @@ snapshots:
is-plain-obj@4.1.0: {}
- is-potential-custom-element-name@1.0.1:
- optional: true
+ is-potential-custom-element-name@1.0.1: {}
is-stream@2.0.1: {}
@@ -13809,7 +13792,6 @@ snapshots:
- bufferutil
- supports-color
- utf-8-validate
- optional: true
jsesc@3.1.0: {}
@@ -14901,7 +14883,6 @@ snapshots:
parse5@8.0.1:
dependencies:
entities: 8.0.0
- optional: true
path-browserify@1.0.1: {}
@@ -15669,7 +15650,6 @@ snapshots:
saxes@6.0.0:
dependencies:
xmlchars: 2.2.0
- optional: true
scheduler@0.27.0: {}
@@ -16070,8 +16050,7 @@ snapshots:
picocolors: 1.1.1
sax: 1.6.1
- symbol-tree@3.2.4:
- optional: true
+ symbol-tree@3.2.4: {}
systeminformation@5.33.1: {}
@@ -16125,8 +16104,7 @@ snapshots:
tldts-core@6.1.86: {}
- tldts-core@7.4.10:
- optional: true
+ tldts-core@7.4.10: {}
tldts@6.1.86:
dependencies:
@@ -16135,7 +16113,6 @@ snapshots:
tldts@7.4.10:
dependencies:
tldts-core: 7.4.10
- optional: true
tmp@0.2.7: {}
@@ -16152,14 +16129,12 @@ snapshots:
tough-cookie@6.0.2:
dependencies:
tldts: 7.4.10
- optional: true
tr46@0.0.3: {}
tr46@6.0.0:
dependencies:
punycode: 2.3.1
- optional: true
tree-kill@1.2.2: {}
@@ -16636,7 +16611,6 @@ snapshots:
w3c-xmlserializer@5.0.0:
dependencies:
xml-name-validator: 5.0.0
- optional: true
wait-on@9.1.0(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1):
dependencies:
@@ -16651,8 +16625,7 @@ snapshots:
webidl-conversions@3.0.1: {}
- webidl-conversions@8.0.1:
- optional: true
+ webidl-conversions@8.0.1: {}
webpack-virtual-modules@0.6.2: {}
@@ -16662,17 +16635,14 @@ snapshots:
whatwg-mimetype@3.0.0: {}
- whatwg-mimetype@4.0.0:
- optional: true
+ whatwg-mimetype@4.0.0: {}
- whatwg-mimetype@5.0.0:
- optional: true
+ whatwg-mimetype@5.0.0: {}
whatwg-url@15.1.0:
dependencies:
tr46: 6.0.0
webidl-conversions: 8.0.1
- optional: true
whatwg-url@5.0.0:
dependencies:
@@ -16754,13 +16724,11 @@ snapshots:
dependencies:
os-paths: 4.4.0
- xml-name-validator@5.0.0:
- optional: true
+ xml-name-validator@5.0.0: {}
xml-naming@0.3.0: {}
- xmlchars@2.2.0:
- optional: true
+ xmlchars@2.2.0: {}
xxhash-wasm@1.1.0: {}
diff --git a/shepherd.js/package.json b/shepherd.js/package.json
index 9986d692f..f373e9c12 100644
--- a/shepherd.js/package.json
+++ b/shepherd.js/package.json
@@ -74,6 +74,7 @@
"test": "vitest",
"test:all": "pnpm test:unit:ci && pnpm test:cy:ci",
"test:ci": "pnpm test:unit:ci && pnpm test:cy:ci",
+ "test:position": "node test/position-differential/run.mjs",
"test:cy:ci": "start-server-and-test start-test-server http://127.0.0.1:9002 cy:run:chrome",
"test:cy:watch": "start-server-and-test start-test-server http://127.0.0.1:9002 cy:open",
"test:unit": "vitest",
@@ -112,6 +113,7 @@
"globals": "^17.9.0",
"happy-dom": "^21.0.4",
"http-server": "^14.1.1",
+ "jsdom": "^27.4.0",
"lodash": "^4.18.1",
"playwright-core": "^1.64.1",
"postcss": "^8.5.26",
diff --git a/shepherd.js/test/position-differential/cross-origin.mjs b/shepherd.js/test/position-differential/cross-origin.mjs
new file mode 100644
index 000000000..a155ee310
--- /dev/null
+++ b/shepherd.js/test/position-differential/cross-origin.mjs
@@ -0,0 +1,71 @@
+// A tour inside a cross-origin iframe, where reading `window.frameElement` past
+// the frame's own document throws or returns null. Run `pnpm build` first.
+import process from 'node:process';
+import * as playwright from 'playwright-core';
+import { packageDir, serve } from '../../scripts/scorecard/lib.mjs';
+
+const server = await serve(packageDir);
+const { port } = new URL(server.url);
+let failed = false;
+
+async function runTour() {
+ const { default: Shepherd } = await import('/dist/js/shepherd.mjs');
+ const target = document.createElement('div');
+ target.className = 'target';
+ target.style.left = '300px';
+ target.style.top = '200px';
+ document.getElementById('page').append(target);
+ const tour = new Shepherd.Tour({ useModalOverlay: true });
+ tour.addStep({
+ text: 'hi',
+ arrow: true,
+ attachTo: { element: target, on: 'bottom' }
+ });
+ await tour.start();
+ const el = tour.getCurrentStep().el;
+ const start = performance.now();
+ while (!el.dataset.popperPlacement && performance.now() - start < 3000) {
+ await new Promise(requestAnimationFrame);
+ }
+ const rect = el.getBoundingClientRect();
+ window.scrollTo(0, 40);
+ await new Promise((done) => setTimeout(done, 100));
+ const after = el.getBoundingClientRect();
+ tour.complete();
+ return {
+ placement: el.dataset.popperPlacement,
+ y: rect.y,
+ yAfterScroll: after.y
+ };
+}
+
+for (const name of ['chromium', 'firefox', 'webkit']) {
+ const browser = await playwright[name].launch();
+ const page = await browser.newPage({
+ viewport: { width: 1000, height: 700 }
+ });
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ page.on('console', (message) => {
+ if (message.type() === 'error') errors.push(message.text());
+ });
+ // `localhost` and `127.0.0.1` are different origins for the same server.
+ await page.goto(`http://localhost:${port}/page.html`);
+ await page.evaluate((src) => {
+ const frame = document.createElement('iframe');
+ frame.src = src;
+ frame.style.cssText = 'width:800px;height:600px;border:0';
+ document.body.prepend(frame);
+ return new Promise((done) => {
+ frame.onload = done;
+ });
+ }, `http://127.0.0.1:${port}/page.html`);
+ const frame = page.frames().find((f) => f !== page.mainFrame());
+ const out = await frame.evaluate(runTour);
+ const follows = Math.abs(out.y - 40 - out.yAfterScroll) <= 1;
+ failed ||= errors.length > 0 || !out.placement || !follows;
+ console.log(name, JSON.stringify(out), 'errors:', JSON.stringify(errors));
+ await browser.close();
+}
+await server.close();
+process.exitCode = failed ? 1 : 0;
diff --git a/shepherd.js/test/position-differential/dist-platform.mjs b/shepherd.js/test/position-differential/dist-platform.mjs
new file mode 100644
index 000000000..ffa19b316
--- /dev/null
+++ b/shepherd.js/test/position-differential/dist-platform.mjs
@@ -0,0 +1,112 @@
+// The published build with a consumer's own @floating-ui/dom platform and
+// middleware, in real browsers. Guards `_c` against property mangling, which the
+// source-level differential cannot see. Run `pnpm build` first.
+import process from 'node:process';
+import { build } from 'esbuild';
+import * as playwright from 'playwright-core';
+import { packageDir, serve } from '../../scripts/scorecard/lib.mjs';
+
+const bundled = await build({
+ stdin: {
+ contents: `export * from '@floating-ui/dom';`,
+ resolveDir: packageDir,
+ loader: 'js'
+ },
+ bundle: true,
+ format: 'iife',
+ globalName: 'STOCK',
+ write: false,
+ target: 'es2020',
+ logLevel: 'error'
+});
+const STOCK = bundled.outputFiles[0].text;
+const server = await serve(packageDir);
+
+async function runScenarios() {
+ const { default: Shepherd } = await import('/dist/js/shepherd.mjs');
+ const pageEl = document.getElementById('page');
+ const run = async (floatingUIOptions, on) => {
+ const target = document.createElement('div');
+ target.className = 'target';
+ target.style.left = '880px';
+ target.style.top = '330px';
+ pageEl.replaceChildren(target);
+ const tour = new Shepherd.Tour();
+ tour.addStep({
+ text: 'hi',
+ arrow: true,
+ attachTo: { element: target, on },
+ floatingUIOptions
+ });
+ await tour.start();
+ const el = tour.getCurrentStep().el;
+ const start = performance.now();
+ while (!el.dataset.popperPlacement && performance.now() - start < 1500) {
+ await new Promise(requestAnimationFrame);
+ }
+ const rect = el.getBoundingClientRect();
+ const result = {
+ placement: el.dataset.popperPlacement ?? null,
+ x: rect.x,
+ y: rect.y
+ };
+ tour.complete();
+ return result;
+ };
+ const { platform, offset, flip, shift, hide, size, inline, autoPlacement } =
+ window.STOCK;
+ return {
+ engine: await run({}, 'right'),
+ stockPlatform: await run({ platform }, 'right'),
+ stockPlatformAuto: await run({ platform }, 'auto'),
+ shadowDomRecipe: await run(
+ {
+ platform: {
+ ...platform,
+ getOffsetParent: (element) => platform.getOffsetParent(element)
+ }
+ },
+ 'right'
+ ),
+ stockMiddleware: await run(
+ { middleware: [offset(12), flip(), shift(), hide(), size(), inline()] },
+ 'top'
+ ),
+ stockAutoPlacement: await run(
+ { middleware: [autoPlacement({ allowedPlacements: ['left', 'top'] })] },
+ 'bottom'
+ ),
+ partialPlatform: await run(
+ { platform: { getOffsetParent: platform.getOffsetParent } },
+ 'left'
+ )
+ };
+}
+
+let failed = false;
+for (const name of ['chromium', 'firefox', 'webkit']) {
+ const browser = await playwright[name].launch();
+ const page = await browser.newPage({
+ viewport: { width: 1000, height: 700 }
+ });
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ page.on('console', (message) => {
+ if (message.type() === 'error') errors.push(message.text());
+ });
+ await page.goto(`${server.url}/page.html`);
+ await page.addScriptTag({ content: STOCK });
+ const out = await page.evaluate(runScenarios);
+ const positioned = Object.values(out).every((result) => result.placement);
+ failed ||= errors.length > 0 || !positioned;
+ console.log(
+ name,
+ positioned ? 'all positioned' : 'NOT ALL POSITIONED',
+ 'errors:',
+ JSON.stringify([...new Set(errors)]).slice(0, 300)
+ );
+ console.log(' ', JSON.stringify(out));
+ await browser.close();
+}
+await server.close();
+process.exitCode = failed ? 1 : 0;
diff --git a/shepherd.js/test/position-differential/fixtures.js b/shepherd.js/test/position-differential/fixtures.js
new file mode 100644
index 000000000..0babb9b37
--- /dev/null
+++ b/shepherd.js/test/position-differential/fixtures.js
@@ -0,0 +1,840 @@
+// Runs inside the page. Each fixture builds a DOM and returns { reference, floating, arrow }.
+// fixedOnly skips the `absolute` strategy, keepPosition leaves the floating element's CSS position alone.
+function div(parent, text = '', tag = 'div') {
+ const e = (parent.ownerDocument || document).createElement(tag);
+ e.style.cssText = text;
+ parent.appendChild(e);
+ return e;
+}
+const REF = 'width:120px;height:40px;background:#ccd;';
+const FLOAT =
+ 'width:200.5px;height:90.25px;background:#fcc;position:absolute;left:0;top:0;';
+const ARROW = 'position:absolute;width:16px;height:16px;background:#000;';
+function mkFloating(parent, extra = '') {
+ const floating = div(parent, FLOAT + extra);
+ const arrow = div(floating, ARROW);
+ arrow.className = 'shepherd-arrow';
+ return { floating, arrow };
+}
+function svgEl(tag, attrs = {}) {
+ const e = document.createElementNS('http://www.w3.org/2000/svg', tag);
+ for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
+ return e;
+}
+function bigPage() {
+ div(
+ document.body,
+ 'height:3000px;width:100%;position:absolute;top:0;left:0;z-index:-1;pointer-events:none'
+ );
+}
+function classicBar() {
+ const style = document.createElement('style');
+ style.textContent =
+ '::-webkit-scrollbar{width:15px;height:15px;background:#eee}';
+ document.head.append(style);
+}
+const abs = (left, top) => `position:absolute;left:${left}px;top:${top}px;`;
+const CENTER = REF + abs(440, 330);
+const BOX = 'position:absolute;left:50px;top:80px;width:800px;height:500px;';
+
+window.FIXTURES = {
+ plain() {
+ const reference = div(document.body, CENTER);
+ return { reference, ...mkFloating(document.body) };
+ },
+ cornerTopLeft() {
+ const reference = div(document.body, REF + abs(0, 0));
+ return { reference, ...mkFloating(document.body) };
+ },
+ cornerBottomRight() {
+ const reference = div(
+ document.body,
+ REF + 'position:absolute;left:880px;top:660px'
+ );
+ return { reference, ...mkFloating(document.body) };
+ },
+ bodyMargin() {
+ document.body.style.margin = '37px 19px';
+ const reference = div(document.body, REF + 'margin:100px 0 0 300px');
+ return { reference, ...mkFloating(document.body) };
+ },
+ bodyNarrow() {
+ document.body.style.cssText = 'width:800px;margin:0 auto;';
+ const reference = div(document.body, REF + 'margin:200px 0 0 300px');
+ return { reference, ...mkFloating(document.body) };
+ },
+ bodySlightlyNarrow() {
+ document.body.style.cssText = 'width:calc(100% - 20px);margin:0;';
+ const reference = div(document.body, REF + 'margin:200px 0 0 860px');
+ return { reference, ...mkFloating(document.body) };
+ },
+ bodyPositioned() {
+ document.body.style.cssText = 'position:relative;margin:23px;';
+ const reference = div(document.body, REF + 'margin:100px 0 0 300px');
+ return { reference, ...mkFloating(document.body) };
+ },
+ htmlPositioned() {
+ document.documentElement.style.cssText = 'position:relative;margin:11px;';
+ const reference = div(document.body, REF + 'margin:100px 0 0 300px');
+ return { reference, ...mkFloating(document.body) };
+ },
+ htmlMarginBorder() {
+ document.documentElement.style.cssText =
+ 'margin:13px;border:7px solid red;';
+ const reference = div(document.body, REF + 'margin:100px 0 0 300px');
+ return { reference, ...mkFloating(document.body) };
+ },
+ bodyTransformed() {
+ document.body.style.cssText =
+ 'transform:translate(30px,40px);margin:5px;height:1500px;';
+ const reference = div(document.body, REF + 'margin:100px 0 0 300px');
+ return { reference, ...mkFloating(document.body) };
+ },
+ scrolled() {
+ bigPage();
+ const reference = div(document.body, REF + abs(440, 830));
+ const r = { reference, ...mkFloating(document.body) };
+ window.scrollTo(0, 500);
+ return r;
+ },
+ scrolledXY() {
+ div(
+ document.body,
+ 'position:absolute;left:0;top:0;width:4000px;height:4000px;z-index:-1'
+ );
+ const reference = div(document.body, REF + abs(1440, 1830));
+ const r = { reference, ...mkFloating(document.body) };
+ window.scrollTo(1000, 1500);
+ return r;
+ },
+ scrolledNearEdge() {
+ bigPage();
+ const reference = div(document.body, REF + abs(440, 510));
+ const r = { reference, ...mkFloating(document.body) };
+ window.scrollTo(0, 500);
+ return r;
+ },
+ rtl() {
+ document.documentElement.setAttribute('dir', 'rtl');
+ bigPage();
+ const reference = div(document.body, CENTER);
+ return { reference, ...mkFloating(document.body) };
+ },
+ rtlOverflowX() {
+ document.documentElement.setAttribute('dir', 'rtl');
+ div(document.body, 'width:3000px;height:10px');
+ const reference = div(
+ document.body,
+ REF + 'position:absolute;left:-600px;top:330px'
+ );
+ const r = { reference, ...mkFloating(document.body) };
+ window.scrollTo(-500, 0);
+ return r;
+ },
+ rtlFloatingOnly() {
+ const reference = div(document.body, CENTER);
+ const m = mkFloating(document.body);
+ m.floating.setAttribute('dir', 'rtl');
+ return { reference, ...m };
+ },
+ overflowParent() {
+ const host = div(
+ document.body,
+ 'position:absolute;left:300px;top:200px;width:400px;height:300px;overflow:auto'
+ );
+ const inner = div(host, 'position:relative;height:1200px;width:900px');
+ const reference = div(inner, REF + abs(140, 300));
+ host.scrollTop = 200;
+ return { reference, ...mkFloating(document.body) };
+ },
+ overflowParentBoth() {
+ const host = div(
+ document.body,
+ 'position:absolute;left:300px;top:200px;width:400px;height:300px;overflow:auto;border:5px solid red'
+ );
+ const inner = div(host, 'position:relative;height:1200px;width:900px');
+ const reference = div(inner, REF + abs(140, 300));
+ host.scrollTop = 200;
+ host.scrollLeft = 50;
+ return { reference, ...mkFloating(inner) };
+ },
+ overflowStaticWrapperEscaped() {
+ const host = div(
+ document.body,
+ 'overflow:hidden;width:300px;height:200px;margin:150px 0 0 300px'
+ );
+ const reference = div(host, REF);
+ return { reference, ...mkFloating(host) };
+ },
+ overflowPositionedWrapperClips() {
+ const host = div(
+ document.body,
+ 'position:relative;overflow:hidden;width:300px;height:200px;margin:150px 0 0 300px'
+ );
+ const reference = div(host, REF);
+ return { reference, ...mkFloating(host) };
+ },
+ overflowFixedEscapes() {
+ const host = div(
+ document.body,
+ 'overflow:hidden;width:300px;height:200px;margin:150px 0 0 300px;position:relative'
+ );
+ const reference = div(host, REF);
+ return {
+ reference,
+ ...mkFloating(host, 'position:fixed;'),
+ fixedOnly: true
+ };
+ },
+ overflowFixedInTransformClips() {
+ const host = div(
+ document.body,
+ 'overflow:hidden;width:300px;height:200px;margin:150px 0 0 300px;transform:translateX(5px)'
+ );
+ const reference = div(host, REF);
+ return {
+ reference,
+ ...mkFloating(host, 'position:fixed;'),
+ fixedOnly: true
+ };
+ },
+ overflowNested() {
+ const a = div(
+ document.body,
+ 'position:relative;overflow:hidden;width:500px;height:400px;margin:50px'
+ );
+ const b = div(
+ a,
+ 'position:relative;overflow:auto;width:300px;height:500px;margin:20px'
+ );
+ const reference = div(b, REF + 'margin:100px');
+ return { reference, ...mkFloating(b) };
+ },
+ htmlMarginOverflowParent() {
+ document.documentElement.style.margin = '11px';
+ const host = div(
+ document.body,
+ 'position:relative;overflow:hidden;width:300px;height:200px;margin:150px 0 0 300px'
+ );
+ const reference = div(host, REF);
+ return { reference, ...mkFloating(host) };
+ },
+ htmlMarginTransformed() {
+ document.documentElement.style.margin = '11px';
+ const c = div(
+ document.body,
+ BOX + 'transform:translate(10px,10px);overflow:hidden'
+ );
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c) };
+ },
+ overflowInline() {
+ const host = div(document.body, 'display:inline;overflow:hidden');
+ const reference = div(host, REF + 'margin:100px');
+ return { reference, ...mkFloating(host) };
+ },
+ overflowContents() {
+ const host = div(document.body, 'display:contents;overflow:hidden');
+ const reference = div(host, REF + 'margin:100px');
+ return { reference, ...mkFloating(host) };
+ },
+ bodyOverflowOwnScroller() {
+ document.documentElement.style.cssText = 'height:100%;overflow:hidden';
+ document.body.style.cssText = 'height:100%;overflow:auto;margin:0';
+ div(document.body, 'height:3000px');
+ const reference = div(document.body, REF + abs(300, 900));
+ const r = { reference, ...mkFloating(document.body) };
+ document.body.scrollTop = 600;
+ return r;
+ },
+ bodyOverflowPropagated() {
+ document.documentElement.style.cssText = 'height:100%';
+ document.body.style.cssText = 'height:100%;overflow:auto;margin:0';
+ div(document.body, 'height:3000px');
+ const reference = div(document.body, REF + abs(300, 900));
+ const r = { reference, ...mkFloating(document.body) };
+ window.scrollTo(0, 600);
+ return r;
+ },
+ htmlOverflowHidden() {
+ document.documentElement.style.cssText = 'overflow:hidden';
+ bigPage();
+ const reference = div(document.body, REF + abs(300, 300));
+ return { reference, ...mkFloating(document.body) };
+ },
+ transformedContainer() {
+ const c = div(document.body, BOX + 'transform:translate(10px,10px)');
+ const reference = div(document.body, CENTER);
+ return { reference, ...mkFloating(c) };
+ },
+ scaledContainer() {
+ const c = div(
+ document.body,
+ BOX + 'transform:scale(0.5);transform-origin:0 0'
+ );
+ const reference = div(document.body, CENTER);
+ return { reference, ...mkFloating(c) };
+ },
+ scaledBorderedContainer() {
+ const c = div(
+ document.body,
+ BOX + 'transform:scale(0.5);transform-origin:0 0;border:4px solid red'
+ );
+ const reference = div(document.body, CENTER);
+ return { reference, ...mkFloating(c) };
+ },
+ scaledNonUniformBoth() {
+ const c = div(
+ document.body,
+ BOX + 'transform:scale(1.5,0.75);transform-origin:0 0'
+ );
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c) };
+ },
+ scaleProperty() {
+ const c = div(document.body, BOX + 'scale:0.7;transform-origin:0 0');
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c) };
+ },
+ zoomedContainer() {
+ const c = div(document.body, BOX + 'zoom:1.5');
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c) };
+ },
+ fixedTarget() {
+ bigPage();
+ const reference = div(
+ document.body,
+ REF + 'position:fixed;left:440px;top:330px'
+ );
+ const r = { reference, ...mkFloating(document.body) };
+ window.scrollTo(0, 250);
+ return r;
+ },
+ fixedInFilter() {
+ const c = div(document.body, BOX + 'filter:blur(0)');
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c, 'position:fixed;'), fixedOnly: true };
+ },
+ fixedInWillChange() {
+ const c = div(document.body, BOX + 'will-change:transform');
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c, 'position:fixed;'), fixedOnly: true };
+ },
+ fixedInContainPaint() {
+ const c = div(document.body, BOX + 'contain:paint');
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c, 'position:fixed;'), fixedOnly: true };
+ },
+ fixedInPerspective() {
+ const c = div(document.body, BOX + 'perspective:100px');
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c, 'position:fixed;'), fixedOnly: true };
+ },
+ fixedInBackdrop() {
+ const c = div(document.body, BOX + 'backdrop-filter:blur(1px)');
+ const reference = div(c, REF + abs(140, 130));
+ return { reference, ...mkFloating(c, 'position:fixed;'), fixedOnly: true };
+ },
+ staticTd() {
+ const t = div(
+ document.body,
+ 'margin:150px 0 0 300px;border-collapse:collapse',
+ 'table'
+ );
+ const tr = div(t, '', 'tr');
+ const td = div(
+ tr,
+ 'width:300px;height:200px;padding:5px;position:static',
+ 'td'
+ );
+ const reference = div(td, REF);
+ return { reference, ...mkFloating(td) };
+ },
+ positionedTd() {
+ const t = div(document.body, 'margin:150px 0 0 300px;', 'table');
+ const tr = div(t, '', 'tr');
+ const td = div(
+ tr,
+ 'width:300px;height:200px;padding:5px;position:relative',
+ 'td'
+ );
+ const reference = div(td, REF);
+ return { reference, ...mkFloating(td) };
+ },
+ staticTdInPositioned() {
+ const wrap = div(document.body, 'position:relative;margin:100px');
+ const t = div(wrap, '', 'table');
+ const tr = div(t, '', 'tr');
+ const td = div(tr, 'width:300px;height:200px', 'td');
+ const reference = div(td, REF);
+ return { reference, ...mkFloating(td) };
+ },
+ staticFloatingInTd() {
+ const wrap = div(document.body, 'position:relative;margin:100px');
+ const t = div(wrap, '', 'table');
+ const tr = div(t, '', 'tr');
+ const td = div(tr, 'width:300px;height:200px', 'td');
+ const reference = div(td, REF);
+ const m = mkFloating(td, 'position:static;');
+ return { reference, ...m, keepPosition: true };
+ },
+ staticFloatingInBody() {
+ const reference = div(document.body, CENTER);
+ const m = mkFloating(document.body, 'position:static;');
+ return { reference, ...m, keepPosition: true };
+ },
+ svgReference() {
+ const s = svgEl('svg', { width: 400, height: 300 });
+ s.style.cssText = abs(300, 200);
+ document.body.appendChild(s);
+ const r = svgEl('rect', { x: 50, y: 60, width: 100, height: 40 });
+ s.appendChild(r);
+ return { reference: r, ...mkFloating(document.body) };
+ },
+ svgArrow() {
+ const reference = div(document.body, CENTER);
+ const m = mkFloating(document.body);
+ const s = svgEl('svg', { width: 16, height: 16, class: 'shepherd-arrow' });
+ s.style.cssText = 'position:absolute';
+ m.floating.appendChild(s);
+ m.arrow.remove();
+ m.arrow = s;
+ return { reference, ...m };
+ },
+ svgArrowNested() {
+ const reference = div(document.body, CENTER);
+ const m = mkFloating(document.body);
+ const wrap = div(
+ m.floating,
+ 'position:absolute;left:0;top:0;width:100px;height:50px'
+ );
+ const s = svgEl('svg', { width: 16, height: 16, class: 'shepherd-arrow' });
+ s.style.cssText = 'position:absolute';
+ wrap.appendChild(s);
+ m.arrow.remove();
+ m.arrow = s;
+ return { reference, ...m };
+ },
+ shadowReference() {
+ const h = div(document.body, abs(300, 200));
+ const root = h.attachShadow({ mode: 'open' });
+ const scroller = document.createElement('div');
+ scroller.style.cssText =
+ 'overflow:auto;width:300px;height:200px;position:relative';
+ root.appendChild(scroller);
+ const inner = div(scroller, 'height:800px');
+ const reference = div(inner, REF + 'margin-top:150px');
+ scroller.scrollTop = 100;
+ return { reference, ...mkFloating(document.body) };
+ },
+ shadowFloating() {
+ const h = div(document.body, abs(300, 200) + 'width:300px;height:200px');
+ const root = h.attachShadow({ mode: 'open' });
+ const reference = div(document.body, CENTER);
+ const wrap = document.createElement('div');
+ wrap.style.cssText =
+ 'position:relative;overflow:hidden;width:300px;height:200px';
+ root.appendChild(wrap);
+ return { reference, ...mkFloating(wrap) };
+ },
+ slotted() {
+ const h = div(document.body, abs(300, 200));
+ const root = h.attachShadow({ mode: 'open' });
+ const wrap = document.createElement('div');
+ wrap.style.cssText =
+ 'overflow:hidden;position:relative;width:400px;height:300px';
+ wrap.appendChild(document.createElement('slot'));
+ root.appendChild(wrap);
+ const reference = div(h, REF + 'margin:60px');
+ return { reference, ...mkFloating(h) };
+ },
+ popoverFloating() {
+ const reference = div(document.body, CENTER);
+ const m = mkFloating(document.body, 'margin:0;inset:auto;');
+ if (!m.floating.showPopover) return null;
+ m.floating.setAttribute('popover', 'manual');
+ m.floating.showPopover();
+ return { reference, ...m };
+ },
+ popoverInTransform() {
+ const c = div(
+ document.body,
+ BOX + 'transform:translate(10px,10px);overflow:hidden'
+ );
+ const reference = div(c, REF + abs(140, 130));
+ const m = mkFloating(c, 'margin:0;inset:auto;');
+ if (!m.floating.showPopover) return null;
+ m.floating.setAttribute('popover', 'manual');
+ m.floating.showPopover();
+ return { reference, ...m };
+ },
+ dialogModalFloating() {
+ const reference = div(document.body, CENTER);
+ const d = document.createElement('dialog');
+ d.style.cssText = FLOAT + 'margin:0;padding:0;border:0;';
+ const a = div(d, ARROW);
+ a.className = 'shepherd-arrow';
+ document.body.appendChild(d);
+ d.showModal();
+ return { reference, floating: d, arrow: a, closeDialog: d };
+ },
+ floatingInModalDialog() {
+ const d = document.createElement('dialog');
+ d.style.cssText = 'width:500px;height:400px;';
+ document.body.appendChild(d);
+ d.showModal();
+ const reference = div(d, REF + 'margin:50px');
+ return { reference, ...mkFloating(d), closeDialog: d };
+ },
+ fixedFloatingInModalInTransform() {
+ const w = div(
+ document.body,
+ 'transform:translate(10px,10px);' +
+ abs(30, 30) +
+ 'width:100px;height:100px'
+ );
+ const d = document.createElement('dialog');
+ d.style.cssText = 'width:500px;height:400px;';
+ w.appendChild(d);
+ d.showModal();
+ const reference = div(d, REF + 'margin:50px');
+ return {
+ reference,
+ ...mkFloating(d, 'position:fixed;'),
+ closeDialog: d,
+ fixedOnly: true
+ };
+ },
+ dialogNonModal() {
+ const d = document.createElement('dialog');
+ d.style.cssText = FLOAT + 'margin:0;padding:0;border:0;';
+ const a = div(d, ARROW);
+ a.className = 'shepherd-arrow';
+ document.body.appendChild(d);
+ d.show();
+ const reference = div(document.body, CENTER);
+ return { reference, floating: d, arrow: a };
+ },
+ classicScrollbar() {
+ classicBar();
+ document.documentElement.style.overflowY = 'scroll';
+ div(document.body, 'height:3000px');
+ const reference = div(document.body, REF + abs(880, 330));
+ return { reference, ...mkFloating(document.body) };
+ },
+ classicScrollbarRtl() {
+ classicBar();
+ document.documentElement.setAttribute('dir', 'rtl');
+ document.documentElement.style.overflowY = 'scroll';
+ div(document.body, 'height:3000px');
+ const reference = div(document.body, REF + abs(0, 330));
+ return { reference, ...mkFloating(document.body) };
+ },
+ scrollbarGutter() {
+ classicBar();
+ document.documentElement.style.cssText =
+ 'scrollbar-gutter:stable;overflow-y:auto';
+ const reference = div(document.body, REF + abs(880, 200));
+ return { reference, ...mkFloating(document.body) };
+ },
+ scrollbarGutterBoth() {
+ classicBar();
+ document.documentElement.style.cssText =
+ 'scrollbar-gutter:stable both-edges;overflow-y:auto';
+ const reference = div(document.body, REF + abs(880, 200));
+ return { reference, ...mkFloating(document.body) };
+ },
+ bodyNarrowerThanHtml() {
+ document.body.style.cssText = 'margin:0;width:calc(100% - 20px)';
+ div(document.body, 'position:relative;width:100%;height:3000px');
+ const reference = div(document.body, REF + abs(880, 330));
+ return { reference, ...mkFloating(document.body) };
+ },
+ gutterHidden() {
+ classicBar();
+ document.documentElement.style.cssText =
+ 'overflow:hidden;scrollbar-gutter:stable';
+ const reference = div(document.body, REF + abs(880, 200));
+ return { reference, ...mkFloating(document.body) };
+ },
+ gutterHiddenBoth() {
+ classicBar();
+ document.documentElement.style.cssText =
+ 'overflow:hidden;scrollbar-gutter:stable both-edges';
+ const reference = div(document.body, REF + abs(880, 200));
+ return { reference, ...mkFloating(document.body) };
+ },
+ gutterStable() {
+ document.documentElement.style.scrollbarGutter = 'stable';
+ const reference = div(
+ document.body,
+ REF + 'position:absolute;right:0;top:330px'
+ );
+ return { reference, ...mkFloating(document.body) };
+ },
+ gutterBoth() {
+ document.documentElement.style.scrollbarGutter = 'stable both-edges';
+ const reference = div(
+ document.body,
+ REF + 'position:absolute;right:0;top:330px'
+ );
+ return { reference, ...mkFloating(document.body) };
+ },
+ scrollbars() {
+ bigPage();
+ div(document.body, 'width:3000px;height:1px');
+ const reference = div(document.body, REF + abs(0, 330));
+ return { reference, ...mkFloating(document.body) };
+ },
+ stickyReference() {
+ bigPage();
+ const w = div(document.body, 'position:relative;height:2000px;width:100%');
+ const reference = div(
+ w,
+ REF + 'position:sticky;top:10px;margin-left:300px'
+ );
+ const r = { reference, ...mkFloating(document.body) };
+ window.scrollTo(0, 400);
+ return r;
+ },
+ zeroSizeReference() {
+ const reference = div(document.body, abs(440, 330) + 'width:0;height:0');
+ return { reference, ...mkFloating(document.body) };
+ },
+ hiddenReference() {
+ const reference = div(document.body, REF + 'display:none');
+ return { reference, ...mkFloating(document.body) };
+ },
+ hiddenFloating() {
+ const reference = div(document.body, CENTER);
+ return { reference, ...mkFloating(document.body, 'display:none;') };
+ },
+ detachedReference() {
+ const reference = document.createElement('div');
+ return { reference, ...mkFloating(document.body) };
+ },
+ tinyReference() {
+ const reference = div(
+ document.body,
+ abs(440, 330) + 'width:6px;height:6px;background:#000'
+ );
+ return { reference, ...mkFloating(document.body) };
+ },
+ hugeReference() {
+ const reference = div(
+ document.body,
+ abs(10, 10) + 'width:900px;height:600px;background:#000'
+ );
+ return { reference, ...mkFloating(document.body) };
+ },
+ bodyAsReference() {
+ return { reference: document.body, ...mkFloating(document.body) };
+ },
+ floatingInFlowRelative() {
+ const c = div(
+ document.body,
+ 'position:relative;border:6px solid red;padding:10px;margin:60px;width:600px;height:400px'
+ );
+ const reference = div(c, REF + 'margin:100px');
+ return { reference, ...mkFloating(c) };
+ },
+ iframeReference() {
+ const fr = document.createElement('iframe');
+ fr.style.cssText =
+ abs(100, 80) +
+ 'width:600px;height:400px;border:9px solid red;padding:6px;';
+ document.body.appendChild(fr);
+ const d = fr.contentDocument;
+ d.body.style.margin = '0';
+ const reference = div(d.body, REF + abs(200, 150));
+ return { reference, ...mkFloating(document.body) };
+ },
+ iframeScaled() {
+ const fr = document.createElement('iframe');
+ fr.style.cssText =
+ abs(100, 80) +
+ 'width:600px;height:400px;border:0;transform:scale(0.5);transform-origin:0 0';
+ document.body.appendChild(fr);
+ const d = fr.contentDocument;
+ d.body.style.margin = '0';
+ const reference = div(d.body, REF + abs(200, 150));
+ return { reference, ...mkFloating(document.body) };
+ },
+ iframeNested() {
+ const fr = document.createElement('iframe');
+ fr.style.cssText =
+ abs(50, 40) + 'width:800px;height:600px;border:3px solid red;';
+ document.body.appendChild(fr);
+ const d = fr.contentDocument;
+ d.body.style.margin = '0';
+ const fr2 = d.createElement('iframe');
+ fr2.style.cssText =
+ abs(60, 50) + 'width:500px;height:400px;border:5px solid blue;';
+ d.body.appendChild(fr2);
+ const d2 = fr2.contentDocument;
+ d2.body.style.margin = '0';
+ const reference = div(d2.body, REF + abs(100, 80));
+ return { reference, ...mkFloating(document.body) };
+ },
+ iframeBothInside() {
+ const fr = document.createElement('iframe');
+ fr.style.cssText = abs(100, 80) + 'width:700px;height:500px;border:0;';
+ document.body.appendChild(fr);
+ const d = fr.contentDocument;
+ d.body.style.margin = '0';
+ const reference = div(d.body, REF + abs(200, 150));
+ const m = mkFloating(d.body);
+ return { reference, ...m };
+ },
+ iframeScrolledReference() {
+ const fr = document.createElement('iframe');
+ fr.style.cssText = abs(100, 80) + 'width:600px;height:400px;border:0;';
+ document.body.appendChild(fr);
+ const d = fr.contentDocument;
+ d.body.style.margin = '0';
+ div(d.body, 'height:3000px');
+ const reference = div(d.body, REF + abs(200, 850));
+ fr.contentWindow.scrollTo(0, 700);
+ return { reference, ...mkFloating(document.body) };
+ }
+};
+
+// Mirrors the baseline getFloatingUIOptions() using stock middleware.
+window.stockOptions = function (FUI, on, reference, arrowEl, strategy, user) {
+ const hasAuto = on.includes('auto');
+ const edge = on.includes('-start') || on.includes('-end');
+ const middleware = [];
+ if (hasAuto) {
+ middleware.push(
+ FUI.autoPlacement({
+ crossAxis: true,
+ alignment: edge ? on.split('-').pop() : null
+ })
+ );
+ } else {
+ middleware.push(FUI.flip());
+ }
+ middleware.push(FUI.shift({ limiter: FUI.limitShift(), crossAxis: true }));
+ const options = { strategy };
+ if (!hasAuto) options.placement = on;
+ if (user.placement) options.placement = user.placement;
+ if (user.platform) options.platform = user.platform;
+ options.middleware = [...middleware, ...(user.middleware ?? [])];
+ if (!options.middleware.some((m) => m && m.name === 'arrow')) {
+ options.middleware.push(
+ FUI.arrow({ element: arrowEl, padding: edge ? 4 : 0 })
+ );
+ }
+ return options;
+};
+
+window.USER_CONFIGS = {
+ none: () => ({}),
+ offset: (F) => ({ middleware: [F.offset(12)] }),
+ offsetCross: (F) => ({
+ middleware: [F.offset({ mainAxis: 4, crossAxis: 8, alignmentAxis: 5 })]
+ }),
+ shiftPadding: (F) => ({ middleware: [F.shift({ padding: 24 })] }),
+ hideRef: (F) => ({ middleware: [F.hide()] }),
+ hideEscaped: (F) => ({ middleware: [F.hide({ strategy: 'escaped' })] }),
+ flipFallback: (F) => ({
+ middleware: [F.flip({ fallbackPlacements: ['left', 'right-start'] })]
+ }),
+ flipAxis: (F) => ({
+ middleware: [
+ F.flip({ fallbackAxisSideDirection: 'start', crossAxis: 'alignment' })
+ ]
+ }),
+ autoAllowed: (F) => ({
+ middleware: [F.autoPlacement({ allowedPlacements: ['top', 'left'] })]
+ }),
+ size: (F) => ({
+ middleware: [
+ F.size({
+ apply({ availableWidth, availableHeight, middlewareData }) {
+ middlewareData.sizeProbe = { availableWidth, availableHeight };
+ }
+ })
+ ]
+ }),
+ inline: (F) => ({ middleware: [F.inline()] }),
+ boundaryElement: (F, fx) => ({
+ middleware: [
+ F.flip({ boundary: fx.floating.parentElement }),
+ F.shift({ boundary: [fx.floating.parentElement] })
+ ]
+ }),
+ boundaryRect: (F) => ({
+ middleware: [
+ F.flip({ boundary: { x: 10, y: 10, width: 400, height: 300 } })
+ ]
+ }),
+ rootDocument: (F) => ({
+ middleware: [F.shift({ rootBoundary: 'document' })]
+ }),
+ rootLayout: (F) => ({
+ middleware: [
+ F.flip({ rootBoundary: 'layoutViewport' }),
+ F.shift({ rootBoundary: 'layoutViewport' })
+ ]
+ }),
+ rootRect: (F) => ({
+ middleware: [
+ F.shift({ rootBoundary: { x: 0, y: 0, width: 500, height: 500 } })
+ ]
+ }),
+ altBoundary: (F) => ({ middleware: [F.flip({ altBoundary: true })] }),
+ userArrow: (F, fx) => ({
+ middleware: [F.arrow({ element: fx.arrow, padding: 6 }), F.offset(3)]
+ }),
+ falsyEntries: (F) => ({ middleware: [false, F.offset(9), null, undefined] }),
+ platformSpread: (F) => ({ platform: { ...F.platform } }),
+ platformRecipe: (F) => ({
+ platform: {
+ ...F.platform,
+ getOffsetParent: (element) => F.platform.getOffsetParent(element)
+ }
+ }),
+ platformAsync: (F) => ({
+ platform: Object.fromEntries(
+ Object.entries(F.platform).map(([name, method]) => [
+ name,
+ async function (...args) {
+ return method.apply(this, args);
+ }
+ ])
+ )
+ })
+};
+
+// Stock middleware only, through the engine's computePosition. Everything in middlewareData is compared.
+window.RAW_CONFIGS = {
+ allReal: (F, on, fx) => [
+ F.offset({ mainAxis: 8, crossAxis: 3, alignmentAxis: 5 }),
+ on.startsWith('auto')
+ ? F.autoPlacement({
+ padding: 5,
+ alignment: on.includes('-') ? on.split('-').pop() : undefined
+ })
+ : F.flip({ padding: 5, fallbackAxisSideDirection: 'start' }),
+ F.shift({
+ padding: 5,
+ crossAxis: true,
+ limiter: F.limitShift({ offset: 4 })
+ }),
+ F.size({ padding: 4, apply() {} }),
+ F.arrow({ element: fx.arrow, padding: 6 }),
+ F.hide(),
+ F.hide({ strategy: 'escaped' })
+ ],
+ options: (F, on, fx) => [
+ F.flip({ rootBoundary: 'document', padding: { top: 3, left: 9 } }),
+ F.shift({ boundary: fx.floating.parentElement, crossAxis: true }),
+ F.shift({
+ rootBoundary: { x: 10, y: 10, width: 800, height: 600 },
+ altBoundary: true
+ }),
+ F.hide({ elementContext: 'reference', rootBoundary: 'document' })
+ ]
+};
diff --git a/shepherd.js/test/position-differential/jsdom.mjs b/shepherd.js/test/position-differential/jsdom.mjs
new file mode 100644
index 000000000..d2500b998
--- /dev/null
+++ b/shepherd.js/test/position-differential/jsdom.mjs
@@ -0,0 +1,61 @@
+// A consumer's unit tests often run tours in jsdom, which has no layout,
+// ResizeObserver or IntersectionObserver, and by default no
+// requestAnimationFrame. A tour must still run there without an unhandled
+// rejection. Run `pnpm build` first.
+import process from 'node:process';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { JSDOM } from 'jsdom';
+import { packageDir } from '../../scripts/scorecard/lib.mjs';
+
+const visual = process.argv.includes('--visual');
+const dom = new JSDOM(
+ '
},
{
title: 'Including',
- text: 'Including Shepherd is easy! Just include shepherd.js. The styles are bundled with the JS.',
+ text: 'Including Shepherd is easy! Just import shepherd.js and its stylesheet.',
attachTo: {
element: '.hero-including',
on: 'bottom'
diff --git a/shepherd.js/dummy/index.html b/shepherd.js/dummy/index.html
index aa37eebaf..2cf23714f 100644
--- a/shepherd.js/dummy/index.html
+++ b/shepherd.js/dummy/index.html
@@ -169,7 +169,7 @@
Example
},
{
title: 'Including',
- text: 'Including Shepherd is easy! Just include shepherd.js. The styles are bundled with the JS.',
+ text: 'Including Shepherd is easy! Just import shepherd.js and its stylesheet.',
attachTo: {
element: '.hero-including',
on: 'bottom'
diff --git a/shepherd.js/test/cypress/utils/default-steps.js b/shepherd.js/test/cypress/utils/default-steps.js
index 1adf7c7d1..e033a3ab6 100644
--- a/shepherd.js/test/cypress/utils/default-steps.js
+++ b/shepherd.js/test/cypress/utils/default-steps.js
@@ -33,7 +33,7 @@ export default function (shepherd) {
},
{
title: 'Including',
- text: 'Including Shepherd is easy! Just include shepherd.js. The styles are bundled with the JS.',
+ text: 'Including Shepherd is easy! Just import shepherd.js and its stylesheet.',
attachTo: {
element: '.hero-including',
on: 'bottom'
diff --git a/shepherd.js/test/llm-eval/run.mjs b/shepherd.js/test/llm-eval/run.mjs
index 1194fb0e9..9d6099ec7 100644
--- a/shepherd.js/test/llm-eval/run.mjs
+++ b/shepherd.js/test/llm-eval/run.mjs
@@ -1,4 +1,4 @@
-// Grades solution files by running them in a real browser. See README.md.
+// Grades solution files by running them in a real browser.
//
// node test/llm-eval/run.mjs [--pkg ] [--json ] [--task ]
// node test/llm-eval/run.mjs --write-prompts
From 6d91136d3c8497ac794666566331449bf9816b71 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Fri, 6 Nov 2026 00:39:48 -0500
Subject: [PATCH 69/93] docs: move the lifecycle check's sync commit forward
Every method in its table still exists, the scenarios still reach the rebuilt
tour, step and modal code, baseline.json is still empty, and all 16 mutants are
caught. Hiding a step now also stops its tracker, and the overlay glides between
steps, neither of which changes what the check's properties promise.
Co-Authored-By: Claude Opus 5.5
---
.claude/skills/verify-tour-lifecycle/SKILL.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.claude/skills/verify-tour-lifecycle/SKILL.md b/.claude/skills/verify-tour-lifecycle/SKILL.md
index 97c0d6216..4c9989ca7 100644
--- a/.claude/skills/verify-tour-lifecycle/SKILL.md
+++ b/.claude/skills/verify-tour-lifecycle/SKILL.md
@@ -24,12 +24,12 @@ Run the check if you changed any of these. The check was last confirmed to descr
| `shepherd.js/src/utils/general.ts` | `waitForAttachToElement`, `resolveAttachToElement` |
| `shepherd.js/src/components/shepherd-modal.ts` | `hide`, `show`, `destroy`, `setupForStep` |
-**Sync commit:** `cba285a53dd85d87c185ee6b04070f87b834b14b`
+**Sync commit:** `e281838b3795be56639894861cd21a4f507424b9`
To see what changed since then, run this from the repo root:
```sh
-git log --oneline cba285a53dd85d87c185ee6b04070f87b834b14b..HEAD -- shepherd.js/src/tour.ts shepherd.js/src/step.ts shepherd.js/src/utils/general.ts shepherd.js/src/components/shepherd-modal.ts
+git log --oneline e281838b3795be56639894861cd21a4f507424b9..HEAD -- shepherd.js/src/tour.ts shepherd.js/src/step.ts shepherd.js/src/utils/general.ts shepherd.js/src/components/shepherd-modal.ts
```
Move the sync commit forward only after you confirm the scenarios and this table still describe the code at the new commit. A passing run alone does not confirm that.
From f57e6d1cda5eb31a100b09f84c607c735730fc6d Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Fri, 6 Nov 2026 00:41:03 -0500
Subject: [PATCH 70/93] chore: stop ignoring every README under shepherd.js
The ignore rule for the README copied in at build time matched at any depth, so
the READMEs of the position differential and the LLM eval never got committed.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/.gitignore | 4 +-
shepherd.js/test/llm-eval/README.md | 70 +++++++++++++++++++
shepherd.js/test/llm-eval/run.mjs | 2 +-
.../test/position-differential/README.md | 67 ++++++++++++++++++
4 files changed, 140 insertions(+), 3 deletions(-)
create mode 100644 shepherd.js/test/llm-eval/README.md
create mode 100644 shepherd.js/test/position-differential/README.md
diff --git a/shepherd.js/.gitignore b/shepherd.js/.gitignore
index ef145c24c..8914b4850 100644
--- a/shepherd.js/.gitignore
+++ b/shepherd.js/.gitignore
@@ -20,5 +20,5 @@
errors.json
# Auto-generated from root during build
-README.md
-LICENSE.md
+/README.md
+/LICENSE.md
diff --git a/shepherd.js/test/llm-eval/README.md b/shepherd.js/test/llm-eval/README.md
new file mode 100644
index 000000000..2d8c54bbf
--- /dev/null
+++ b/shepherd.js/test/llm-eval/README.md
@@ -0,0 +1,70 @@
+# LLM eval
+
+Measures whether a coding agent with no prior context writes Shepherd code that
+works. Solutions are loaded in a real browser with Playwright and graded on what
+the page does. Nothing here reads or scores source code, and nothing is
+non-deterministic except the agent that wrote the solution.
+
+From `shepherd.js/`, after `pnpm build`:
+
+| Command | What it does |
+| ---------------------------------------------------------------- | ------------------------------------------------------------- |
+| `node test/llm-eval/run.mjs test/llm-eval/reference` | Grades the reference solutions. Must always be 8/8. |
+| `node test/llm-eval/run.mjs --json out.json` | Grades a directory of solutions. |
+| `node test/llm-eval/run.mjs --write-sandbox ` | Creates the directory a cold agent works in. |
+| `node test/llm-eval/run.mjs --write-prompts ` | Writes only the task prompts. |
+| `node test/llm-eval/mistakes.mjs --json out.json` | Records what each known mistake does. Needs no agent. |
+
+All of them take `--pkg ` to test another build, such as an older package
+extracted somewhere. `run.mjs` also takes `--task `.
+
+## Running it with cold agents
+
+Run the same steps for each build you are comparing, with the same model and at
+least 3 agents per task, because one run says little about a model's error rate.
+
+1. `node test/llm-eval/run.mjs --write-sandbox --pkg `. The sandbox
+ has `node_modules/` holding exactly what `npm pack` publishes, the prompts in
+ `prompts/`, and an empty `solutions/`.
+2. Start a new agent for each prompt, with its working directory set to the
+ sandbox, no access to this repository, and no network. Send it the prompt file
+ as is, and add no hints. Have it write to `solutions/`. It may read anything
+ in `node_modules/`.
+3. `node test/llm-eval/run.mjs /solutions --pkg --json out.json`.
+ Grade against the same build the agent saw.
+
+A solution is named `.`. A missing file counts as a failed task.
+
+Compare `passed` and the first failed check of each task between builds. The check
+names say which mistake happened, such as `default styling applied` for a
+forgotten stylesheet. Also compare `console`, which holds what the page printed.
+
+## Tasks
+
+| Task | The trap |
+| ----------------- | ------------------------------------------------------------------------ |
+| `first-tour` | The CSS import, button actions, `attachTo.on`, centered steps |
+| `modal-focus` | `useModalOverlay`, `canClickTarget`, `cancelIcon`, `cancel` once |
+| `shared-defaults` | `defaultStepOptions` inheritance, and overriding it per step |
+| `async-targets` | `beforeShowPromise`, `waitForElement`, `skipMissingElement` |
+| `events-persist` | `advanceOn`, tour events, restart after a reload |
+| `react-strict` | The current `react-shepherd` API, and StrictMode's double effect |
+| `typed-json` | The `Tour` type vs value, passing `tsc --strict`, data-driven steps |
+| `script-tag` | No bundler: `shepherd.mjs` is a module and defines no global |
+
+## Mistakes
+
+`mistakes.mjs` runs small programs that each contain one expected mistake, against
+a build, with no agent involved. Each ends up as:
+
+| Outcome | Meaning |
+| ---------------- | --------------------------------------------------------- |
+| `WORKS` | The tour behaves as the author meant, despite the mistake |
+| `DIAGNOSED` | It fails, and a message names the fix |
+| `LOUD-UNHELPFUL` | It fails with an error that does not name the fix |
+| `SILENT` | It fails with no error at all |
+| `BROKEN` | It fails, for a mistake with no message to judge |
+
+The `tsc` column means the compiler rejects the code. The `docs` column means the
+shipped `AGENTS.md` mentions the fix, which says only that the text is there, not
+that an agent reads it. The cold agent run measures that.
diff --git a/shepherd.js/test/llm-eval/run.mjs b/shepherd.js/test/llm-eval/run.mjs
index 9d6099ec7..1194fb0e9 100644
--- a/shepherd.js/test/llm-eval/run.mjs
+++ b/shepherd.js/test/llm-eval/run.mjs
@@ -1,4 +1,4 @@
-// Grades solution files by running them in a real browser.
+// Grades solution files by running them in a real browser. See README.md.
//
// node test/llm-eval/run.mjs [--pkg ] [--json ] [--task ]
// node test/llm-eval/run.mjs --write-prompts
diff --git a/shepherd.js/test/position-differential/README.md b/shepherd.js/test/position-differential/README.md
new file mode 100644
index 000000000..1c58bee38
--- /dev/null
+++ b/shepherd.js/test/position-differential/README.md
@@ -0,0 +1,67 @@
+# Position differential
+
+Shepherd has its own positioning engine, `src/utils/position.ts`, which replaced
+`@floating-ui/dom`. Nothing else in the repo holds the engine to stock behavior:
+the scorecard's goldens are frozen and cover 197 cases in one page shape, and unit
+tests run with no layout. This suite positions the same DOM with both, in real
+Chromium, Firefox and WebKit, and fails on a difference that is not recorded.
+
+```sh
+pnpm test:position
+```
+
+It takes about three minutes and needs no build. It reads `src/`, not `dist/`.
+
+## What it covers
+
+Every fixture in `fixtures.js` runs in standards and quirks mode, under both
+`strategy` values:
+
+- **Shepherd's wiring.** `getFloatingUIOptions` from `src/utils/floating-ui.ts`
+ against the options it used to build for stock. Each `USER_CONFIGS` entry adds
+ what a consumer might pass in `floatingUIOptions`: stock middleware, boundaries,
+ a `platform` spread from stock, and a `platform` whose methods are all async.
+- **Stock middleware alone.** `RAW_CONFIGS` runs only stock middleware through the
+ engine's `computePosition`, and compares all of `middlewareData`.
+- **The tracker.** `autoUpdate` must react to a window or ancestor scroll, a resize
+ of either element, a layout shift, a transform, and a shift after settling, and
+ must do nothing while idle or after cleanup.
+
+## Reading a failure
+
+A failure names the browser, mode, fixture and config, with the first case that
+differs and both results. Most likely the engine regressed, so follow that case.
+`--browser`, `--fixture` and `--config` narrow a run, and `--json` saves all of it.
+
+Only after you have read every new key and decided it is right:
+
+```sh
+node test/position-differential/run.mjs --update-known
+```
+
+## Known differences
+
+`known-differences.json` records how many cases differ per browser, mode, fixture
+and config. With no `floatingUIOptions`, a step can only reach the first row, the
+second row, and the gutter fixtures in the last row. The rest need a consumer's own
+boundary, or a DOM shape Shepherd does not build.
+
+| Fixtures or configs | Difference | Why it stays |
+| --- | --- | --- |
+| `bodySlightlyNarrow`, `bodyNarrowerThanHtml` | Stock treats a `` up to 25px narrower than the root as a scrollbar gutter and pulls the right edge in. The engine does not. | No gutter exists there. A real gutter is handled, by the root's own width. |
+| `scaledBorderedContainer` | Under a scaled, bordered offset parent, `auto` placements that tie can pick another side or alignment. | Stock adds that parent's border unscaled, so its overflow numbers are off by the border. Both results sit against the target and in view. |
+| `staticFloatingInTd`, `svgArrowNested` | The engine's arrow assumes the step is its offset parent. | `.shepherd-arrow` is always a direct child of a positioned step. A consumer's own `arrow()` is stock's. |
+| `rootLayout` config | The engine treats `rootBoundary: 'layoutViewport'` as `'viewport'`. | They differ only while pinch-zoomed, or in Firefox quirks mode and iframes. |
+| `rootRect`, `boundaryElement`, `boundaryRect`, `options` under `html*` and `gutter*Both` fixtures | A consumer's explicit `boundary` or `rootBoundary` is off by the root's left offset. | Needs both a custom boundary and a root offset by a margin or a left gutter. |
+| `hideRef`, `hideEscaped`, `size`, `allReal` under `bodyOverflowOwnScroller`, `htmlMarginOverflowParent` | Stock `hide` and `size` report other offsets. Position and placement match. | Same root offset, or stock's body-width gutter, in numbers only those middleware read. |
+| `scrolledXY`, `rtlOverflowX`, and gutter fixtures in quirks mode | Custom boundaries, or the gutter, against `` in quirks mode. | Quirks mode with horizontal scrolling or `scrollbar-gutter`. |
+
+## Other checks
+
+Each needs `pnpm build` first and exercises the published `dist`:
+
+```sh
+node test/position-differential/dist-platform.mjs # stock platform and middleware, through property mangling
+node test/position-differential/cross-origin.mjs # a tour inside a cross-origin iframe
+node test/position-differential/jsdom.mjs # a tour in jsdom, without and with --visual
+```
From aaa7a9dbedb7cd76166d304f6c36012e71d9b5ca Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Fri, 6 Nov 2026 00:50:42 -0500
Subject: [PATCH 71/93] docs: list the motion module in the API index
The docs build regenerates this file, and now finds src/motion.ts.
Co-Authored-By: Claude Opus 5.5
---
docs-src/src/content/docs/api/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/docs-src/src/content/docs/api/README.md b/docs-src/src/content/docs/api/README.md
index 874df4b70..7307d9638 100644
--- a/docs-src/src/content/docs/api/README.md
+++ b/docs-src/src/content/docs/api/README.md
@@ -8,6 +8,7 @@ title: "shepherd.js"
## Modules
- [evented](/api/evented/readme/)
+- [motion](/api/motion/readme/)
- [shepherd](/api/shepherd/readme/)
- [step](/api/step/readme/)
- [tour](/api/tour/readme/)
From 7eea6199360d5b34e182b2e08436621a20e5eb26 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 06:30:40 -0500
Subject: [PATCH 72/93] fix: keep the dist within ES2020 by avoiding a logical
assignment
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/position.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index 8e5248034..b4b5073ae 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -167,7 +167,8 @@ const isStatic = (element: Element) => styleOf(element).position === 'static';
let webKit: boolean | undefined;
const isWebKit = () =>
- (webKit ??=
+ webKit ??
+ (webKit =
typeof CSS !== 'undefined' &&
CSS.supports?.('-webkit-backdrop-filter', 'none'));
From fd3eade69ba6878445da84d41053b76051cff13b Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 07:52:16 -0500
Subject: [PATCH 73/93] feat!: replace floatingUIOptions with positionOptions
Shepherd positions steps itself, so consumer Floating UI middleware and
platforms no longer run. A step takes `positionOptions: { offset, padding,
strategy, flip }` instead, combined key by key with `defaultStepOptions`.
Passing `floatingUIOptions` logs a warning naming `positionOptions`.
The engine now measures the DOM once per position and runs its own
middleware on those numbers, which drops the platform indirection, the `_c`
cache reservation, consumer boundaries, and `merge.ts`.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/rollup.config.mjs | 8 +-
shepherd.js/src/step.ts | 89 +++-
shepherd.js/src/tour.ts | 2 +-
shepherd.js/src/utils/floating-ui.ts | 174 ++------
shepherd.js/src/utils/merge.ts | 32 --
shepherd.js/src/utils/position.test-d.ts | 50 +--
shepherd.js/src/utils/position.ts | 397 +++++++-----------
.../integration/positioning-strategy.cy.js | 4 +-
shepherd.js/test/unit/step.spec.js | 70 ++-
shepherd.js/test/unit/tour.spec.js | 178 ++++----
.../unit/utils/floating-ui-position.spec.js | 12 +-
.../test/unit/utils/floating-ui.spec.js | 210 +++++----
shepherd.js/test/unit/utils/general.spec.js | 48 +--
shepherd.js/test/unit/utils/merge.spec.js | 72 ----
shepherd.js/test/unit/utils/position.spec.js | 320 +++++++-------
15 files changed, 653 insertions(+), 1013 deletions(-)
delete mode 100644 shepherd.js/src/utils/merge.ts
delete mode 100644 shepherd.js/test/unit/utils/merge.spec.js
diff --git a/shepherd.js/rollup.config.mjs b/shepherd.js/rollup.config.mjs
index 1b5dc02be..ad22ac635 100644
--- a/shepherd.js/rollup.config.mjs
+++ b/shepherd.js/rollup.config.mjs
@@ -60,12 +60,8 @@ if (process.env.DEVELOPMENT) {
mangle: {
properties: {
regex: /^_[a-zA-Z]/,
- reserved: [
- // Called by test/cypress/integration/test.acceptance.cy.js
- '_getResolvedAttachToOptions',
- // Read by a `platform` spread from a consumer's `@floating-ui/dom`
- '_c'
- ]
+ // Called by test/cypress/integration/test.acceptance.cy.js
+ reserved: ['_getResolvedAttachToOptions']
}
}
})
diff --git a/shepherd.js/src/step.ts b/shepherd.js/src/step.ts
index 9702fa86a..e194a72b7 100644
--- a/shepherd.js/src/step.ts
+++ b/shepherd.js/src/step.ts
@@ -13,17 +13,12 @@ import {
uuid,
parseExtraHighlights
} from './utils/general.ts';
-import {
- setupTooltip,
- destroyTooltip,
- mergeTooltipConfig
-} from './utils/floating-ui.ts';
+import { setupTooltip, destroyTooltip } from './utils/floating-ui.ts';
import {
createShepherdElement,
type ShepherdElementResult
} from './components/shepherd-element.ts';
import { type Tour } from './tour.ts';
-import type { ComputePositionConfig } from './utils/position.ts';
/**
* The body of a step. Strings render as HTML, so escape untrusted input.
@@ -203,18 +198,17 @@ export interface StepOptions {
modalOverlayOpeningYOffset?: number;
/**
- * Extra positioning options, in the shape of Floating UI's
- * [computePosition config]{@link https://floating-ui.com/docs/computePosition}.
- * Shepherd positions steps itself and does not depend on `@floating-ui/dom`,
- * but middleware from your own install of it, such as `offset()`, runs as is.
+ * How the step is placed against its target: the gap, the distance kept from
+ * the edges, the CSS `position`, and whether it may flip. See
+ * {@link StepOptionsPosition}. Values from `defaultStepOptions` and the step
+ * combine key by key, so a step can change one and keep the rest.
*
- * This includes `strategy`, the CSS `position` used for the step element,
- * which defaults to `'absolute'`. Centered steps are always `position: fixed`
- * and ignore `strategy` -- a step counts as centered when it has no
- * `attachTo` at all, or when its `attachTo` is missing either `element` or
- * `on`.
+ * @example
+ * ```js
+ * positionOptions: { offset: 12, padding: 8 }
+ * ```
*/
- floatingUIOptions?: ComputePositionConfig;
+ positionOptions?: StepOptionsPosition;
/**
* Should the element be scrolled to when this step is shown?
@@ -321,6 +315,58 @@ export type PopperPlacement =
| 'left-start'
| 'left-end';
+/**
+ * How a step is placed against its target, set through
+ * {@link StepOptions.positionOptions}. Shepherd positions steps itself, with no
+ * dependency on Floating UI. These cover what its `offset()`, `flip()`,
+ * `shift()` and `strategy` were used for. A centered step, one whose `attachTo`
+ * lacks `element` or `on`, ignores all of them.
+ *
+ * @example
+ * ```js
+ * tour.addStep({
+ * text: 'Sticks to the header while the page scrolls.',
+ * attachTo: { element: '#header', on: 'bottom-start' },
+ * positionOptions: { offset: 12, padding: 16, strategy: 'fixed' }
+ * });
+ * ```
+ */
+export interface StepOptionsPosition {
+ /**
+ * The gap between the step and its target, in pixels. A number moves the step
+ * away from the target. `crossAxis` moves it along the side it sits on, toward
+ * the end of that side, with left and right swapped in right-to-left pages
+ * for `top` and `bottom` placements. The same as Floating UI's `offset()`.
+ *
+ * @defaultValue `0`. The arrow, when shown, makes up the visible gap.
+ */
+ offset?: number | { mainAxis?: number; crossAxis?: number };
+ /**
+ * The least distance, in pixels, kept between the step and the edges of the
+ * viewport and of any scrolling or clipping ancestor. It applies both when
+ * choosing a side, so a step flips sooner, and when sliding the step along
+ * its side to keep it in view.
+ *
+ * @defaultValue `0`
+ */
+ padding?: number;
+ /**
+ * The CSS `position` of the step element. Use `'fixed'` when the target is
+ * itself `position: fixed`, such as a sticky header.
+ *
+ * @defaultValue `'absolute'`
+ */
+ strategy?: 'absolute' | 'fixed';
+ /**
+ * Whether the step may move to the opposite side, or the opposite alignment,
+ * when `attachTo.on` would not fit. `false` keeps `attachTo.on` even when the
+ * step overflows. `auto` placements always choose their own side.
+ *
+ * @defaultValue `true`
+ */
+ flip?: boolean;
+}
+
/**
* Options for the arrow pointing at the target.
*/
@@ -847,9 +893,18 @@ export class Step extends Evented {
arrow: true,
...tourOptions,
...options,
- ...mergeTooltipConfig(tourOptions, options)
+ positionOptions: {
+ ...tourOptions.positionOptions,
+ ...options.positionOptions
+ }
};
+ if ('floatingUIOptions' in this.options) {
+ console.warn(
+ 'Shepherd: floatingUIOptions was removed. Use positionOptions: { offset, padding, strategy, flip }.'
+ );
+ }
+
this.options.classes = this._getClassOptions(options);
this.id = this.options.id || `step-${uuid()}`;
diff --git a/shepherd.js/src/tour.ts b/shepherd.js/src/tour.ts
index e9d756fed..156cf670e 100644
--- a/shepherd.js/src/tour.ts
+++ b/shepherd.js/src/tour.ts
@@ -68,7 +68,7 @@ export interface TourOptions {
* Default options for Steps ({@link Step#constructor}), created through `addStep`.
* A step's own value replaces the default for that option, even for objects such
* as `cancelIcon` and arrays such as `buttons`. Only `classes` and
- * `floatingUIOptions` combine.
+ * `positionOptions` combine, `positionOptions` key by key.
*/
defaultStepOptions?: StepOptions;
/**
diff --git a/shepherd.js/src/utils/floating-ui.ts b/shepherd.js/src/utils/floating-ui.ts
index 8625ebd05..b35dbd70d 100644
--- a/shepherd.js/src/utils/floating-ui.ts
+++ b/shepherd.js/src/utils/floating-ui.ts
@@ -1,19 +1,19 @@
import { shouldCenterStep } from './general.ts';
-import { merge } from './merge.ts';
import {
autoUpdate,
arrow,
computePosition,
flip,
autoPlacement,
+ offset,
shift,
- type ComputePositionConfig,
type ComputePositionResult,
type Middleware,
+ type PositionConfig,
type Placement,
type Alignment
} from './position.ts';
-import type { Step, StepOptions, StepOptionsAttachTo } from '../step.ts';
+import type { Step, StepOptionsAttachTo } from '../step.ts';
import { isHTMLElement } from './type-check.ts';
/**
@@ -21,7 +21,7 @@ import { isHTMLElement } from './type-check.ts';
*
* @param step The step instance
*/
-export function setupTooltip(step: Step): ComputePositionConfig {
+export function setupTooltip(step: Step): PositionConfig {
if (step.cleanup) {
step.cleanup();
}
@@ -29,7 +29,7 @@ export function setupTooltip(step: Step): ComputePositionConfig {
const attachToOptions = step._getResolvedAttachToOptions();
let target = attachToOptions.element as HTMLElement;
- const floatingUIOptions = getFloatingUIOptions(attachToOptions, step);
+ const config = getPositionConfig(attachToOptions, step);
const shouldCenter = shouldCenterStep(attachToOptions);
// Keep this function-local so every fresh step render gets one focus attempt.
let shouldFocusAfterRender = true;
@@ -47,7 +47,7 @@ export function setupTooltip(step: Step): ComputePositionConfig {
return;
}
- setPosition(target, step, floatingUIOptions, shouldCenter, {
+ setPosition(target, step, config, shouldCenter, {
shouldFocusAfterRender
});
shouldFocusAfterRender = false;
@@ -55,27 +55,7 @@ export function setupTooltip(step: Step): ComputePositionConfig {
step.target = attachToOptions.element as HTMLElement;
- return floatingUIOptions;
-}
-
-/**
- * Merge tooltip options handling nested keys.
- *
- * @param tourOptions - The default tour options.
- * @param options - Step specific options.
- *
- * @return {floatingUIOptions: FloatingUIOptions}
- */
-export function mergeTooltipConfig(
- tourOptions: StepOptions,
- options: StepOptions
-): { floatingUIOptions: ComputePositionConfig } {
- return {
- floatingUIOptions: merge(
- tourOptions.floatingUIOptions || {},
- options.floatingUIOptions || {}
- )
- };
+ return config;
}
/**
@@ -94,16 +74,16 @@ export function destroyTooltip(step: Step) {
function setPosition(
target: HTMLElement,
step: Step,
- floatingUIOptions: ComputePositionConfig,
+ config: PositionConfig,
shouldCenter: boolean,
{ shouldFocusAfterRender }: { shouldFocusAfterRender: boolean }
) {
const positionPromise = computePosition(
target,
step.el as HTMLElement,
- floatingUIOptions
+ config
)
- .then(floatingUIposition(step, shouldCenter))
+ .then(writePosition(step, shouldCenter))
.catch((error: unknown) => {
console.error('Shepherd: could not position a step.', error);
return step;
@@ -125,7 +105,7 @@ function setPosition(
});
}
-function floatingUIposition(step: Step, shouldCenter: boolean) {
+function writePosition(step: Step, shouldCenter: boolean) {
return ({
x,
y,
@@ -184,115 +164,47 @@ function placeArrow(
}
/**
- * Gets the `Floating UI` options from a set of base `attachTo` options
- * @param attachToOptions
+ * Builds the positioning config for a step from its `attachTo` and
+ * `positionOptions`.
+ *
+ * @param attachToOptions The step's resolved `attachTo`
* @param step The step instance
* @private
*/
-export function getFloatingUIOptions(
+export function getPositionConfig(
attachToOptions: StepOptionsAttachTo,
step: Step
-): ComputePositionConfig {
- const options: ComputePositionConfig = {
- strategy: 'absolute'
+): PositionConfig {
+ const {
+ offset: gap,
+ padding,
+ strategy = 'absolute',
+ flip: flips = true
+ } = step.options.positionOptions || {};
+ const on = attachToOptions.on || '';
+ const hasAutoPlacement = on.includes('auto');
+ const middleware: Middleware[] = [];
+ const config: PositionConfig = {
+ placement: on && !hasAutoPlacement ? (on as Placement) : 'bottom',
+ strategy,
+ middleware
};
- options.middleware = [];
-
- const arrowEl = addArrow(step);
+ if (shouldCenterStep(attachToOptions)) return config;
- const shouldCenter = shouldCenterStep(attachToOptions);
-
- const hasAutoPlacement = attachToOptions.on?.includes('auto');
-
- const hasEdgeAlignment =
- attachToOptions?.on?.includes('-start') ||
- attachToOptions?.on?.includes('-end');
-
- if (!shouldCenter) {
- if (hasAutoPlacement) {
- options.middleware.push(
- autoPlacement({
- alignment: hasEdgeAlignment
- ? (attachToOptions?.on?.split('-').pop() as Alignment)
- : null
- })
- );
- } else {
- options.middleware.push(flip());
- }
-
- options.middleware.push(shift());
-
- if (!hasAutoPlacement) options.placement = attachToOptions.on as Placement;
- }
-
- const mergedOptions: ComputePositionConfig = merge(
- options,
- step.options.floatingUIOptions || {}
- );
-
- // `arrow()` has to be the *last* middleware to run. `Floating UI` executes
- // middleware sequentially, threading `x`/`y` from one to the next, and
- // `arrow()` computes its offset from the coordinates as they stand on its own
- // turn. Any middleware that runs after it (a user supplied `offset()`,
- // `shift()`, etc.) moves the tooltip again and silently invalidates
- // `middlewareData.arrow`, which `placeArrow()` writes straight to the DOM.
- // Since user options are merged in above -- and `merge` concatenates
- // arrays -- Shepherd's arrow is appended afterwards rather than pushed in
- // before the merge.
- if (
- !shouldCenter &&
- arrowEl &&
- !hasArrowMiddleware(mergedOptions.middleware)
- ) {
- const arrowOptions =
- typeof step.options.arrow === 'object'
- ? step.options.arrow
- : { padding: 4 };
-
- mergedOptions.middleware = [
- ...(mergedOptions.middleware ?? []),
- arrow({
- element: arrowEl,
- padding: hasEdgeAlignment ? arrowOptions.padding : 0
- })
- ];
- }
-
- return mergedOptions;
-}
-
-/**
- * Type guard filtering out the falsy entries `Floating UI` allows in a
- * middleware array.
- *
- * @param middleware A single entry of a `middleware` array
- * @private
- */
-function isMiddleware(
- middleware: Middleware | false | null | undefined
-): middleware is Middleware {
- return Boolean(middleware);
-}
-
-/**
- * Determines whether a middleware array already contains an `arrow` middleware,
- * in which case the user's own arrow wins and Shepherd does not add its own.
- *
- * @param middleware The merged `middleware` array, which may contain falsy entries
- * @private
- */
-function hasArrowMiddleware(middleware: ComputePositionConfig['middleware']) {
- return Boolean(
- middleware?.some((item) => isMiddleware(item) && item.name === 'arrow')
- );
-}
+ const alignment = on.split('-')[1] as Alignment | undefined;
+ if (gap) middleware.push(offset(gap));
+ if (hasAutoPlacement) middleware.push(autoPlacement(alignment, padding));
+ else if (flips) middleware.push(flip(padding));
+ middleware.push(shift(padding));
-function addArrow(step: Step) {
- if (step.options.arrow && step.el) {
- return step.el.querySelector('.shepherd-arrow');
+ const arrowEl =
+ step.options.arrow && step.el?.querySelector('.shepherd-arrow');
+ if (isHTMLElement(arrowEl)) {
+ const arrowPadding =
+ typeof step.options.arrow === 'object' ? step.options.arrow.padding : 4;
+ middleware.push(arrow(arrowEl, alignment ? arrowPadding : 0));
}
- return false;
+ return config;
}
diff --git a/shepherd.js/src/utils/merge.ts b/shepherd.js/src/utils/merge.ts
deleted file mode 100644
index 54d80c4b4..000000000
--- a/shepherd.js/src/utils/merge.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-function isRecord(value: unknown): value is Record {
- if (!value || typeof value !== 'object') return false;
- const proto = Object.getPrototypeOf(value);
- // The second check accepts plain objects from another realm, such as an iframe.
- return !proto || !Object.getPrototypeOf(proto);
-}
-
-/**
- * Merges `floatingUIOptions`. Records merge recursively, arrays concatenate,
- * `undefined` never overrides a value, and anything else takes the last value.
- *
- * @param base The lower priority value
- * @param override The higher priority value
- * @return A new value, sharing any nested value only one side defined
- */
-export function merge(base: T, override: T): T {
- if (override === undefined) return base;
- if (Array.isArray(base) && Array.isArray(override)) {
- return [...base, ...override] as T;
- }
- if (!isRecord(base) || !isRecord(override)) return override;
-
- // Spreading first makes any `__proto__` key an own property, so the
- // assignment below writes to that property rather than the prototype.
- const merged: Record = { ...base, ...override };
- for (const key of Object.keys(override)) {
- if (Object.prototype.hasOwnProperty.call(base, key)) {
- merged[key] = merge(base[key], override[key]);
- }
- }
- return merged as T;
-}
diff --git a/shepherd.js/src/utils/position.test-d.ts b/shepherd.js/src/utils/position.test-d.ts
index be099705c..f2e702acb 100644
--- a/shepherd.js/src/utils/position.test-d.ts
+++ b/shepherd.js/src/utils/position.test-d.ts
@@ -1,37 +1,21 @@
-// Compile-time proof, checked by `tsc`, that a consumer's own Floating UI
-// middleware and config satisfy `floatingUIOptions` with no dependency on it.
-import {
- arrow,
- autoPlacement,
- flip,
- hide,
- inline,
- limitShift,
- offset,
- shift,
- size,
- type ComputePositionConfig as FloatingUIConfig
-} from '@floating-ui/dom';
-import type { StepOptions } from '../step.ts';
+// Compile-time checks, run by `tsc`, of what `positionOptions` accepts.
+import type { StepOptions, StepOptionsPosition } from '../step.ts';
-export const fromMiddleware: StepOptions['floatingUIOptions'] = {
+export const everyKey: StepOptionsPosition = {
+ offset: { mainAxis: 8, crossAxis: -4 },
+ padding: 16,
strategy: 'fixed',
- placement: 'left-start',
- middleware: [
- offset(8),
- flip({ padding: 4 }),
- shift({ limiter: limitShift() }),
- arrow({ element: document.body }),
- autoPlacement(),
- hide(),
- inline(),
- size(),
- false,
- null,
- undefined
- ]
+ flip: false
};
-export const fromConfig = (
- config: FloatingUIConfig
-): StepOptions['floatingUIOptions'] => config;
+export const onAStep: StepOptions = { positionOptions: { offset: 12 } };
+
+export const removed: StepOptions = {
+ // @ts-expect-error `floatingUIOptions` was replaced by `positionOptions`.
+ floatingUIOptions: { strategy: 'fixed' }
+};
+
+export const badStrategy: StepOptionsPosition = {
+ // @ts-expect-error Only `absolute` and `fixed`.
+ strategy: 'sticky'
+};
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index b4b5073ae..19f86592b 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -1,10 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any --
- This walks DOM nodes across realms and shadow roots, and implements Floating
- UI's platform contract, whose inputs are unions of elements and windows. */
+ This walks DOM nodes across realms and shadow roots, whose types are unions
+ of elements and windows. */
type Side = 'top' | 'right' | 'bottom' | 'left';
type Axis = 'x' | 'y';
type Coords = Record;
-type Strategy = NonNullable;
+type Strategy = 'absolute' | 'fixed';
/** The side of its target a step sits on, optionally aligned along that side. */
export type Placement = Side | `${Side}-${Alignment}`;
@@ -12,32 +12,17 @@ export type Placement = Side | `${Side}-${Alignment}`;
/** Which edge of its target a step lines up with. */
export type Alignment = 'start' | 'end';
-/**
- * One positioning step. Middleware from your own install of `@floating-ui/dom`,
- * such as `offset()`, has this shape.
- */
+/** One positioning step, run in order and rerun from the start on a reset. */
export interface Middleware {
- /** Identifies the middleware, and keys the data it shares with later ones. */
+ /** Keys the data it shares with later ones. */
name: string;
- /** The options the middleware was created with. */
- options?: any;
- /** Receives Floating UI's `MiddlewareState` and returns its `MiddlewareReturn`. */
- fn(state: any): any;
+ fn(state: MiddlewareState): MiddlewareResult;
}
-/**
- * Positioning options, in the shape of Floating UI's `computePosition` config.
- * Shepherd sets these from `attachTo`, and these extend or override them.
- */
-export interface ComputePositionConfig {
- /** Where the step sits relative to its target, overriding `attachTo.on`. */
- placement?: Placement;
- /** The CSS `position` of the step element. Defaults to `absolute`. */
- strategy?: 'absolute' | 'fixed';
- /** Runs in order after Shepherd's own middleware. Falsy entries are skipped. */
- middleware?: Array;
- /** Overrides how the DOM is measured, following Floating UI's `Platform`. */
- platform?: Record;
+export interface PositionConfig {
+ placement: Placement;
+ strategy: Strategy;
+ middleware: Middleware[];
}
interface Rect extends Coords {
@@ -50,23 +35,17 @@ interface ElementRects {
floating: Rect;
}
-/**
- * The state every middleware receives. It is Floating UI's `MiddlewareState`,
- * so middleware from a consumer's own `@floating-ui/dom` runs unchanged.
- */
-interface MiddlewareState extends Coords {
+/** Floating UI's `MiddlewareState`, less what only consumer middleware read. */
+interface MiddlewareState extends Coords, Measurements {
initialPlacement: Placement;
placement: Placement;
strategy: Strategy;
middlewareData: Record;
- rects: ElementRects;
- elements: { reference: any; floating: HTMLElement };
- platform: any;
}
interface MiddlewareResult extends Partial {
data?: Record;
- reset?: boolean | { placement?: Placement; rects?: boolean | ElementRects };
+ reset?: boolean | { placement: Placement };
}
export interface ComputePositionResult extends Coords {
@@ -282,7 +261,7 @@ function getScale(element: any): Coords {
/**
* Where `left: 0; top: 0` lands in client coordinates for an element with this
* offset parent. Mapping through one origin and scale in both directions keeps
- * `getElementRects` and overflow detection in the same coordinate space.
+ * the measured rects and overflow detection in the same coordinate space.
*/
function originOf(offsetParent: any, strategy: Strategy) {
if (isHTMLElement(offsetParent)) {
@@ -341,35 +320,9 @@ function rectInWindow(element: any, targetWindow: Window) {
return { x, y, width, height };
}
-function rootRect(node: any, rootBoundary: string): Rect {
+function viewportRect(node: any): Rect {
const html = htmlOf(node);
const { x, width: rootWidth } = html.getBoundingClientRect();
-
- if (rootBoundary === 'document') {
- const { body } = getDocument(node);
- const width = max(
- html.scrollWidth,
- html.clientWidth,
- body.scrollWidth,
- body.clientWidth
- );
- return {
- x:
- x +
- (styleOf(body).direction === 'rtl'
- ? max(html.clientWidth, body.clientWidth) - width
- : 0),
- y: -html.scrollTop,
- width,
- height: max(
- html.scrollHeight,
- html.clientHeight,
- body.scrollHeight,
- body.clientHeight
- )
- };
- }
-
const viewport = getWindow(node).visualViewport;
// WebKit's client coordinates are relative to the visual viewport, others'
// to the layout viewport.
@@ -408,10 +361,7 @@ function clippingAncestors(element: Element) {
});
}
-function clipRect(element: Element, clip: any): Rect {
- if (typeof clip === 'string') return rootRect(element, clip);
- if (!isElement(clip)) return clip;
-
+function clipRect(clip: Element): Rect {
const scale = getScale(clip);
const { x, y } = clip.getBoundingClientRect();
return {
@@ -422,22 +372,12 @@ function clipRect(element: Element, clip: any): Rect {
};
}
-function getClippingRect({
- element,
- boundary,
- rootBoundary
-}: {
- element: Element;
- boundary: any;
- rootBoundary: any;
-}): Rect {
- const clips: any[] =
- boundary === 'clippingAncestors'
- ? isTopLayer(element)
- ? []
- : clippingAncestors(element)
- : [].concat(boundary);
- const rects = [...clips, rootBoundary].map((clip) => clipRect(element, clip));
+/** The area visible through every clipping ancestor and the viewport. */
+function getClippingRect(element: Element): Rect {
+ const rects = [
+ ...(isTopLayer(element) ? [] : clippingAncestors(element).map(clipRect)),
+ viewportRect(element)
+ ];
const x = max(...rects.map((rect) => rect.x));
const y = max(...rects.map((rect) => rect.y));
@@ -449,93 +389,33 @@ function getClippingRect({
};
}
-async function detectOverflow(
- state: MiddlewareState,
- {
- boundary = 'clippingAncestors',
- rootBoundary = 'viewport',
- elementContext = 'floating',
- altBoundary = false,
- padding = 0
- }: Record = {}
-): Promise> {
- const { x, y, platform, rects, elements, strategy } = state;
- const pad = (side: Side) =>
- (typeof padding === 'number' ? padding : padding[side]) || 0;
- const clip: Rect = await platform.getClippingRect({
- element:
- elements[
- altBoundary
- ? elementContext === 'floating'
- ? 'reference'
- : 'floating'
- : (elementContext as 'floating')
- ],
- boundary,
- rootBoundary,
- strategy
- });
- const offsetParent = await platform.getOffsetParent(elements.floating);
- const scale: Coords = await platform.getScale(offsetParent);
- const box: Rect =
- await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
- elements,
- rect:
- elementContext === 'floating'
- ? { ...rects.floating, x, y }
- : rects.reference,
- offsetParent,
- strategy
- });
-
- return {
- top: (clip.y - box.y + pad('top')) / scale.y,
- bottom:
- (box.y + box.height - clip.y - clip.height + pad('bottom')) / scale.y,
- left: (clip.x - box.x + pad('left')) / scale.x,
- right: (box.x + box.width - clip.x - clip.width + pad('right')) / scale.x
- };
+/**
+ * Everything positioning reads from the DOM, read once per position. Nothing
+ * a middleware does moves the step's offset parent or clipping ancestors.
+ */
+export interface Measurements {
+ rects: ElementRects;
+ /** The visible area, in client coordinates. */
+ clip: Rect;
+ /** Where the offset parent's origin lands in client coordinates, and its scale. */
+ origin: Coords & { scale: Coords };
+ rtl: boolean;
+ floating: HTMLElement;
}
-const platform = {
- detectOverflow,
- getClippingRect,
- getOffsetParent,
- getDimensions,
- getScale,
- isElement,
- isRTL: (element: Element) => styleOf(element).direction === 'rtl',
- getClientRects: (element: Element) => element.getClientRects(),
- convertOffsetParentRelativeRectToViewportRelativeRect({
- rect,
- offsetParent,
- strategy
- }: {
- rect: Rect;
- offsetParent: Element | Window;
- strategy: Strategy;
- }): Rect {
- const { x, y, scale } = originOf(offsetParent, strategy);
- return {
- x: rect.x * scale.x + x,
- y: rect.y * scale.y + y,
- width: rect.width * scale.x,
- height: rect.height * scale.y
- };
- },
- async getElementRects(
- this: any,
- {
- reference,
- floating,
- strategy
- }: { reference: any; floating: HTMLElement; strategy: Strategy }
- ): Promise {
- const offsetParent = await this.getOffsetParent(floating);
- const { x, y, scale } = originOf(offsetParent, strategy);
- const rect = rectInWindow(reference, getWindow(offsetParent));
- const { width, height } = await this.getDimensions(floating);
- return {
+export function measure(
+ reference: Element,
+ floating: HTMLElement,
+ strategy: Strategy
+): Measurements {
+ const offsetParent = getOffsetParent(floating);
+ const origin = originOf(offsetParent, strategy);
+ const { x, y, scale } = origin;
+ const rect = rectInWindow(reference, getWindow(offsetParent));
+ const { width, height } = getDimensions(floating);
+
+ return {
+ rects: {
reference: {
x: (rect.x - x) / scale.x,
y: (rect.y - y) / scale.y,
@@ -543,48 +423,55 @@ const platform = {
height: rect.height / scale.y
},
floating: { x: 0, y: 0, width, height }
- };
- }
-};
+ },
+ clip: getClippingRect(floating),
+ origin,
+ rtl: styleOf(floating).direction === 'rtl',
+ floating
+ };
+}
-export async function computePosition(
- reference: Element,
- floating: HTMLElement,
- config: ComputePositionConfig
-): Promise {
- const {
- placement: initialPlacement = 'bottom',
- strategy = 'absolute',
- middleware = []
- } = config;
- // `_c` is the per-call cache of a `platform` spread from `@floating-ui/dom`.
- const merged: any = { ...platform, ...config.platform, _c: new Map() };
- const elements = { reference, floating };
+function detectOverflow(
+ { x, y, rects: { floating }, clip, origin }: MiddlewareState,
+ padding = 0
+): Record {
+ const { scale } = origin;
+ const left = x * scale.x + origin.x;
+ const top = y * scale.y + origin.y;
+
+ return {
+ top: (clip.y - top + padding) / scale.y,
+ bottom:
+ (top + floating.height * scale.y - clip.y - clip.height + padding) /
+ scale.y,
+ left: (clip.x - left + padding) / scale.x,
+ right:
+ (left + floating.width * scale.x - clip.x - clip.width + padding) /
+ scale.x
+ };
+}
+
+/** Runs the middleware against measurements taken by `measure`. */
+export function place(
+ measurements: Measurements,
+ { placement: initialPlacement, strategy, middleware }: PositionConfig
+): ComputePositionResult {
+ const { rects, rtl } = measurements;
const middlewareData: Record = {};
- const rtl = await merged.isRTL(floating);
- let rects: ElementRects = await merged.getElementRects({
- reference,
- floating,
- strategy
- });
let { x, y } = placementCoords(rects, initialPlacement, rtl);
let placement = initialPlacement;
let resets = 0;
for (let i = 0; i < middleware.length; i++) {
- const current = middleware[i];
- if (!current) continue;
-
- const result: MiddlewareResult = await current.fn({
+ const current = middleware[i] as Middleware;
+ const result = current.fn({
+ ...measurements,
x,
y,
initialPlacement,
placement,
strategy,
- middlewareData,
- rects,
- platform: merged,
- elements
+ middlewareData
});
x = result.x ?? x;
y = result.y ?? y;
@@ -597,13 +484,7 @@ export async function computePosition(
if (reset && resets < 50) {
resets++;
if (typeof reset === 'object') {
- placement = reset.placement || placement;
- if (reset.rects) {
- rects =
- reset.rects === true
- ? await merged.getElementRects({ reference, floating, strategy })
- : reset.rects;
- }
+ placement = reset.placement;
({ x, y } = placementCoords(rects, placement, rtl));
}
i = -1;
@@ -613,6 +494,14 @@ export async function computePosition(
return { x, y, placement, strategy, middlewareData };
}
+export async function computePosition(
+ reference: Element,
+ floating: HTMLElement,
+ config: PositionConfig
+): Promise {
+ return place(measure(reference, floating, config.strategy), config);
+}
+
function minBy(list: T[], key: (item: T) => number) {
return list.reduce(
(best, item) => (best && key(best) <= key(item) ? best : item),
@@ -622,6 +511,42 @@ function minBy(list: T[], key: (item: T) => number) {
const fits = (overflow: number) => overflow <= 0;
+/**
+ * Moves the element away from its reference along the side it sits on, and
+ * along that side by `crossAxis`. Floating UI's `offset()`, which `shift`'s
+ * limit reads back from `middlewareData.offset`.
+ */
+export function offset(
+ value: number | { mainAxis?: number; crossAxis?: number }
+): Middleware {
+ const { mainAxis = 0, crossAxis = 0 } =
+ typeof value === 'number' ? { mainAxis: value } : value;
+
+ return {
+ name: 'offset',
+ fn({ x, y, placement, middlewareData, rtl }) {
+ // After the arrow's nudge resets, the offset is already in `x` and `y`.
+ if (
+ placement === middlewareData['offset']?.placement &&
+ middlewareData['arrow']?.alignmentOffset
+ ) {
+ return {};
+ }
+ const axis = sideAxis(placement);
+ const delta = {
+ [axis]: /^[tl]/.test(placement) ? -mainAxis : mainAxis,
+ [otherAxis(axis)]: rtl && axis === 'y' ? -crossAxis : crossAxis
+ } as Coords;
+
+ return {
+ x: x + delta.x,
+ y: y + delta.y,
+ data: { ...delta, placement }
+ };
+ }
+ };
+}
+
/**
* Tries candidate placements in order, one reset at a time, recording how each
* overflows. `choose` picks among them once every candidate has been tried.
@@ -630,17 +555,15 @@ const fits = (overflow: number) => overflow <= 0;
*/
function placementSearch(
name: string,
- options: unknown,
+ padding: number | undefined,
flipping: boolean,
candidates: (initial: Placement) => Placement[],
choose: (attempts: Attempt[]) => Attempt | undefined
): Middleware {
return {
name,
- options,
- async fn(state: MiddlewareState): Promise {
- const { placement, initialPlacement, middlewareData } = state;
- const { platform, rects, elements } = state;
+ fn(state) {
+ const { placement, initialPlacement, middlewareData, rects, rtl } = state;
const { index = 0, overflows: previous = [] } =
middlewareData[name] || {};
const placements = candidates(initialPlacement);
@@ -653,12 +576,8 @@ function placementSearch(
return { reset: { placement: placements[0] as Placement } };
}
- const overflow = await platform.detectOverflow(state);
- const [first, second] = alignmentSides(
- placement,
- rects,
- await platform.isRTL(elements.floating)
- );
+ const overflow = detectOverflow(state, padding);
+ const [first, second] = alignmentSides(placement, rects, rtl);
const overflows: number[] = [
overflow[sideOf(placement)],
overflow[first],
@@ -681,10 +600,10 @@ function placementSearch(
};
}
-export function flip(): Middleware {
+export function flip(padding?: number): Middleware {
return placementSearch(
'flip',
- undefined,
+ padding,
true,
(initial) => {
const opposite = oppositeSide(initial);
@@ -708,10 +627,10 @@ export function flip(): Middleware {
);
}
-export function autoPlacement(options: {
- alignment: Alignment | null;
-}): Middleware {
- const { alignment } = options;
+export function autoPlacement(
+ alignment: Alignment | undefined,
+ padding?: number
+): Middleware {
const placements = (
alignment
? [alignment, OPPOSITES[alignment]].flatMap((align) =>
@@ -725,7 +644,7 @@ export function autoPlacement(options: {
return placementSearch(
'autoPlacement',
- options,
+ padding,
false,
() => placements,
(attempts) =>
@@ -744,15 +663,15 @@ export function autoPlacement(options: {
/**
* Keeps the element in view on both axes, stopping once it would detach from
* the reference. Floating UI spells this `shift({ limiter: limitShift(),
- * crossAxis: true })`.
+ * crossAxis: true, padding })`.
*/
-export function shift(): Middleware {
+export function shift(padding?: number): Middleware {
return {
name: 'shift',
- async fn(state: MiddlewareState): Promise {
- const { x, y, placement, rects, middlewareData, platform } = state;
+ fn(state) {
+ const { x, y, placement, rects, middlewareData } = state;
const { reference, floating } = rects;
- const overflow = await platform.detectOverflow(state);
+ const overflow = detectOverflow(state, padding);
const cross = sideAxis(placement);
const main = otherAxis(cross);
const fromOrigin = /^[tl]/.test(placement);
@@ -777,34 +696,24 @@ export function shift(): Middleware {
return {
...limited,
- data: {
- x: limited.x - x,
- y: limited.y - y,
- enabled: { x: true, y: true }
- }
+ data: { x: limited.x - x, y: limited.y - y }
};
}
};
}
-export function arrow(options: {
- element: Element;
- padding?: number;
-}): Middleware {
+export function arrow(element: HTMLElement, padding = 0): Middleware {
return {
name: 'arrow',
- options,
- async fn(state: MiddlewareState): Promise {
- const { placement, rects, platform, elements, middlewareData } = state;
- const { element, padding = 0 } = options;
+ fn(state) {
+ const { placement, rects, floating, middlewareData } = state;
const axis = otherAxis(sideAxis(placement));
const length = lengthOf(axis);
const start = state[axis];
- const arrowLength = (await platform.getDimensions(element))[length];
+ const arrowLength = getDimensions(element)[length];
const free =
- (axis === 'y'
- ? elements.floating.clientHeight
- : elements.floating.clientWidth) - arrowLength;
+ (axis === 'y' ? floating.clientHeight : floating.clientWidth) -
+ arrowLength;
// Padding large enough to push the arrow off center gets capped.
const edge = min(padding, free / 2 - 1);
const end = free - edge;
diff --git a/shepherd.js/test/cypress/integration/positioning-strategy.cy.js b/shepherd.js/test/cypress/integration/positioning-strategy.cy.js
index 94d717ac4..3872cfef9 100644
--- a/shepherd.js/test/cypress/integration/positioning-strategy.cy.js
+++ b/shepherd.js/test/cypress/integration/positioning-strategy.cy.js
@@ -36,14 +36,14 @@ describe('positioning strategy', () => {
});
};
- const startTour = (floatingUIOptions) => {
+ const startTour = (positionOptions) => {
const tour = setupTour(Shepherd, { scrollTo: false }, () => [
{
attachTo: { element: '.page-target', on: 'bottom' },
id: 'strategy',
title: 'Strategy step',
text: 'positioned against a target the page scrolls past',
- floatingUIOptions
+ positionOptions
}
]);
diff --git a/shepherd.js/test/unit/step.spec.js b/shepherd.js/test/unit/step.spec.js
index 42ef25682..d698364c5 100644
--- a/shepherd.js/test/unit/step.spec.js
+++ b/shepherd.js/test/unit/step.spec.js
@@ -3,7 +3,6 @@ import Shepherd from '../../src/shepherd';
import { Step } from '../../src/step';
import { Tour } from '../../src/tour';
import ResizeObserver from 'resize-observer-polyfill';
-import { offset } from '@floating-ui/dom';
// since importing non UMD, needs assignment
window.Shepherd = Shepherd;
@@ -27,15 +26,13 @@ describe('Tour | Step', () => {
});
describe('Shepherd.Step()', () => {
- const defaultOffsetMiddleware = offset({ mainAxis: 0, crossAxis: 32 });
- const fooMiddleware = { name: 'foo', options: 'bar', fn: (args) => args };
-
const instance = new Shepherd.Tour({
defaultStepOptions: {
classes: DEFAULT_STEP_CLASS,
scrollTo: true,
- floatingUIOptions: {
- middleware: [defaultOffsetMiddleware]
+ positionOptions: {
+ offset: { mainAxis: 0, crossAxis: 32 },
+ padding: 8
},
showOn,
when
@@ -53,9 +50,7 @@ describe('Tour | Step', () => {
}
],
id: 'test',
- floatingUIOptions: {
- middleware: [fooMiddleware]
- }
+ positionOptions: { offset: 16 }
});
const showTestStep = instance.addStep({
@@ -87,10 +82,6 @@ describe('Tour | Step', () => {
]
});
- const stepWithoutNameWithoutIdOffsetMiddleware = offset({
- mainAxis: 0,
- crossAxis: -32
- });
const stepWithoutNameWithoutId = instance.addStep({
attachTo: { element: 'body' },
highlightClass: 'highlight',
@@ -101,9 +92,7 @@ describe('Tour | Step', () => {
action: instance.next
}
],
- floatingUIOptions: {
- middleware: [stepWithoutNameWithoutIdOffsetMiddleware]
- }
+ positionOptions: { offset: { mainAxis: 0, crossAxis: -32 } }
});
const beforeShowPromise = () =>
@@ -129,7 +118,7 @@ describe('Tour | Step', () => {
'arrow',
'classes',
'scrollTo',
- 'floatingUIOptions',
+ 'positionOptions',
'showOn',
'when',
'attachTo',
@@ -167,30 +156,27 @@ describe('Tour | Step', () => {
id: 'test',
scrollTo: true,
text: 'This is a step for testing',
- floatingUIOptions: {
- middleware: [defaultOffsetMiddleware, fooMiddleware]
- },
+ positionOptions: { offset: 16, padding: 8 },
showOn,
when
});
});
- it('allows the step to override a previously defined modifier', () => {
- stepWithoutNameWithoutId.show();
- const offsetMiddleware =
- stepWithoutNameWithoutId.options.floatingUIOptions.middleware.filter(
- ({ name }) => name === 'offset'
- );
- const offsetResult = offsetMiddleware.reduce(
- (agg, current) => {
- agg.mainAxis += current.options.mainAxis;
- agg.crossAxis += current.options.crossAxis;
- return agg;
- },
- { mainAxis: 0, crossAxis: 0 }
- );
+ it('lets a step override one positionOptions key and keep the rest', () => {
+ expect(stepWithoutNameWithoutId.options.positionOptions).toEqual({
+ offset: { mainAxis: 0, crossAxis: -32 },
+ padding: 8
+ });
+ });
- expect(offsetResult).toEqual({ mainAxis: 0, crossAxis: 0 });
+ it('warns that floatingUIOptions was replaced', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ instance.addStep({ floatingUIOptions: { strategy: 'fixed' } });
+
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('positionOptions')
+ );
+ warn.mockRestore();
});
describe('.hide()', () => {
@@ -614,15 +600,11 @@ describe('Tour | Step', () => {
});
describe('correct operation of classes on body element when step not attached to an element', () => {
- const offsetMiddleware = offset({ crossAxis: 32 });
- const defaultCallback = (args) => args;
const instance = new Shepherd.Tour({
defaultStepOptions: {
classes: DEFAULT_STEP_CLASS,
scrollTo: true,
- floatingUIOptions: {
- middleware: [offsetMiddleware]
- },
+ positionOptions: { offset: { crossAxis: 32 } },
showOn,
when
}
@@ -638,9 +620,7 @@ describe('Tour | Step', () => {
}
],
id: 'test',
- floatingUIOptions: {
- middleware: [{ name: 'foo', options: 'bar', fn: defaultCallback }]
- }
+ positionOptions: { flip: false }
});
afterEach(() => {
@@ -1317,7 +1297,9 @@ describe('Tour | Step', () => {
await instance.start();
const onOneStep = live();
- expect(onOneStep, 'the shown step follows scrolling').toBeGreaterThan(0);
+ expect(onOneStep, 'the shown step follows scrolling').toBeGreaterThan(
+ 0
+ );
await instance.next();
await instance.next();
diff --git a/shepherd.js/test/unit/tour.spec.js b/shepherd.js/test/unit/tour.spec.js
index 075e97627..ff639818f 100644
--- a/shepherd.js/test/unit/tour.spec.js
+++ b/shepherd.js/test/unit/tour.spec.js
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import Shepherd from '../../src/shepherd';
import ResizeObserver from 'resize-observer-polyfill';
import { setupTooltip } from '../../src/utils/floating-ui';
-import { offset } from '@floating-ui/dom';
+import { place } from '../../src/utils/position';
const { Step } = Shepherd;
@@ -24,14 +24,10 @@ describe('Tour | Top-Level Class', function () {
show() {}
};
- const offsetMiddleware = offset({ crossAxis: 32 });
-
const defaultStepOptions = {
classes: DEFAULT_STEP_CLASS,
scrollTo: true,
- floatingUIOptions: {
- middleware: [offsetMiddleware]
- },
+ positionOptions: { offset: { crossAxis: 32 } },
showOn,
when
};
@@ -60,9 +56,7 @@ describe('Tour | Top-Level Class', function () {
expect(instance.options.defaultStepOptions).toEqual({
classes: DEFAULT_STEP_CLASS,
scrollTo: true,
- floatingUIOptions: {
- middleware: [offsetMiddleware]
- },
+ positionOptions: { offset: { crossAxis: 32 } },
showOn,
when
});
@@ -926,83 +920,79 @@ describe('Tour | Top-Level Class', function () {
});
});
- describe('floatingUIOptions', () => {
- it('applies the default modifiers from defaultStepOptions', function () {
+ describe('positionOptions', () => {
+ const names = ({ middleware }) => middleware.map(({ name }) => name);
+ let target;
+
+ beforeEach(() => {
+ target = document.createElement('div');
+ target.classList.add('modifiers-test');
+ document.body.appendChild(target);
+ });
+
+ afterEach(() => {
+ target.remove();
+ });
+
+ it('applies positionOptions from defaultStepOptions', function () {
instance = new Shepherd.Tour({ defaultStepOptions });
const step = instance.addStep({
+ attachTo: { element: '.modifiers-test', on: 'top' },
id: 'test',
title: 'This is a test step for our tour'
});
instance.start();
- const floatingUIOptions = setupTooltip(step);
- expect(floatingUIOptions.middleware.length).toBe(1);
+ const config = setupTooltip(step);
+ expect(names(config)).toEqual(['offset', 'flip', 'shift', 'arrow']);
+ expect(config.strategy).toBe('absolute');
});
- it('adds a step modifer to default modifiers', function () {
+ it("combines a step's positionOptions with the defaults key by key", function () {
instance = new Shepherd.Tour({ defaultStepOptions });
const step = instance.addStep({
+ attachTo: { element: '.modifiers-test', on: 'top' },
id: 'test',
title: 'This is a test step for our tour',
- floatingUIOptions: {
- middleware: [{ name: 'foo', options: 'bar', fn: (args) => args }]
- }
+ positionOptions: { strategy: 'fixed', flip: false }
});
instance.start();
- const floatingUIOptions = setupTooltip(step);
- expect(floatingUIOptions.middleware.length).toBe(2);
+ const config = setupTooltip(step);
+ expect(names(config)).toEqual(['offset', 'shift', 'arrow']);
+ expect(config.strategy).toBe('fixed');
});
- it('correctly changes modifiers when going from centered to attached', function () {
- const div = document.createElement('div');
- div.classList.add('modifiers-test');
- document.body.appendChild(div);
+ it('correctly changes middleware when going from centered to attached', function () {
instance = new Shepherd.Tour({ defaultStepOptions });
const centeredStep = instance.addStep({
id: 'centered',
- title: 'This is a centered step for our tour',
- floatingUIOptions: {
- middleware: [{ name: 'foo', options: 'bar', fn: (args) => args }]
- }
+ title: 'This is a centered step for our tour'
});
const attachedStep = instance.addStep({
attachTo: { element: '.modifiers-test', on: 'top' },
id: 'attached',
- title: 'This is an attached step for our tour',
- floatingUIOptions: {
- middleware: [{ name: 'foo', options: 'bar', fn: (args) => args }]
- }
+ title: 'This is an attached step for our tour'
});
instance.start();
- const centeredOptions = setupTooltip(centeredStep);
- const centeredMiddlewareNames = centeredOptions.middleware.map(
- ({ name }) => name
- );
- expect(centeredOptions.middleware.length).toBe(2);
- expect(centeredMiddlewareNames.includes('offset')).toBe(true);
- expect(centeredMiddlewareNames.includes('foo')).toBe(true);
- expect(centeredMiddlewareNames.includes('arrow')).toBe(false);
+ expect(names(setupTooltip(centeredStep))).toEqual([]);
instance.next();
- const options = setupTooltip(attachedStep);
- const middlewareNames = options.middleware.map(({ name }) => name);
- expect(options.middleware.length).toBe(5);
- expect(middlewareNames.includes('offset')).toBe(true);
- expect(middlewareNames.includes('foo')).toBe(true);
- expect(middlewareNames.includes('shift')).toBe(true);
- expect(middlewareNames.includes('arrow')).toBe(true);
-
- document.body.removeChild(div);
+ expect(names(setupTooltip(attachedStep))).toEqual([
+ 'offset',
+ 'flip',
+ 'shift',
+ 'arrow'
+ ]);
});
it('renders step in stepsContainer', () => {
@@ -1027,59 +1017,41 @@ describe('Tour | Top-Level Class', function () {
expect(stepsContainer.contains(stepElement)).toBe(true);
});
- it('adds autoPlacement middleware when attachTo.on is set to auto', () => {
- const div = document.createElement('div');
- div.classList.add('modifiers-test');
- document.body.appendChild(div);
- instance = new Shepherd.Tour();
-
- const step1 = instance.addStep({
- id: 'test',
- title: 'This is a test step for our tour',
- attachTo: { element: '.modifiers-test', on: 'auto' }
- });
-
- const step2 = instance.addStep({
- id: 'test',
- title: 'This is a test step for our tour',
- attachTo: { element: '.modifiers-test', on: 'auto-start' }
- });
-
- const step3 = instance.addStep({
- id: 'test',
- title: 'This is a test step for our tour',
- attachTo: { element: '.modifiers-test', on: 'auto-end' }
- });
-
- instance.start();
-
- const step1FloatingUIOptions = setupTooltip(step1);
- const step1MiddlewareNames = step1FloatingUIOptions.middleware.map(
- ({ name }) => name
- );
- const step1PlacementMiddleware = step1FloatingUIOptions.middleware.find(
- ({ name }) => name === 'autoPlacement'
- );
- expect(step1MiddlewareNames.includes('autoPlacement')).toBe(true);
- expect(step1MiddlewareNames.includes('flip')).toBe(false);
- expect(step1PlacementMiddleware.options.alignment).toBe(null);
-
- instance.next();
+ it.each([
+ ['auto', /^(top|right|bottom|left)$/],
+ ['auto-start', /-start$/],
+ ['auto-end', /-end$/]
+ ])(
+ 'chooses a side with autoPlacement for %s, keeping its alignment',
+ (on, expected) => {
+ instance = new Shepherd.Tour();
- const step2FloatingUIOptions = setupTooltip(step2);
- const step2PlacementMiddleware = step2FloatingUIOptions.middleware.find(
- ({ name }) => name === 'autoPlacement'
- );
- expect(step2PlacementMiddleware.options.alignment).toBe('start');
+ const step = instance.addStep({
+ id: 'test',
+ title: 'This is a test step for our tour',
+ attachTo: { element: '.modifiers-test', on }
+ });
- instance.next();
+ instance.start();
- const step3FloatingUIOptions = setupTooltip(step3);
- const step3PlacementMiddleware = step3FloatingUIOptions.middleware.find(
- ({ name }) => name === 'autoPlacement'
- );
- expect(step3PlacementMiddleware.options.alignment).toBe('end');
- });
+ const config = setupTooltip(step);
+ expect(names(config)).toEqual(['autoPlacement', 'shift', 'arrow']);
+ const { placement } = place(
+ {
+ rects: {
+ reference: { x: 450, y: 330, width: 100, height: 40 },
+ floating: { x: 0, y: 0, width: 300, height: 120 }
+ },
+ clip: { x: 0, y: 0, width: 1000, height: 700 },
+ origin: { x: 0, y: 0, scale: { x: 1, y: 1 } },
+ rtl: false,
+ floating: step.el
+ },
+ config
+ );
+ expect(placement).toMatch(expected);
+ }
+ );
describe('strategy', () => {
let target;
@@ -1108,14 +1080,14 @@ describe('Tour | Top-Level Class', function () {
await vi.waitFor(() => expect(step.el.style.position).toBe('absolute'));
});
- it('honors `strategy: fixed` from step floatingUIOptions', async () => {
+ it('honors `strategy: fixed` from step positionOptions', async () => {
instance = new Shepherd.Tour();
const step = instance.addStep({
id: 'test',
title: 'This is a test step for our tour',
attachTo: { element: '.strategy-test', on: 'top' },
- floatingUIOptions: { strategy: 'fixed' }
+ positionOptions: { strategy: 'fixed' }
});
instance.start();
@@ -1123,10 +1095,10 @@ describe('Tour | Top-Level Class', function () {
await vi.waitFor(() => expect(step.el.style.position).toBe('fixed'));
});
- it('honors `strategy: fixed` from defaultStepOptions floatingUIOptions', async () => {
+ it('honors `strategy: fixed` from defaultStepOptions positionOptions', async () => {
instance = new Shepherd.Tour({
defaultStepOptions: {
- floatingUIOptions: { strategy: 'fixed' }
+ positionOptions: { strategy: 'fixed' }
}
});
@@ -1153,7 +1125,7 @@ describe('Tour | Top-Level Class', function () {
const step = instance.addStep({
id: 'test',
title: 'This is a test step for our tour',
- floatingUIOptions: strategy ? { strategy } : {}
+ positionOptions: { strategy }
});
instance.start();
diff --git a/shepherd.js/test/unit/utils/floating-ui-position.spec.js b/shepherd.js/test/unit/utils/floating-ui-position.spec.js
index 2ec410b0b..0b84f4e67 100644
--- a/shepherd.js/test/unit/utils/floating-ui-position.spec.js
+++ b/shepherd.js/test/unit/utils/floating-ui-position.spec.js
@@ -124,7 +124,7 @@ describe('utils/floating-ui | position writing', function () {
const step = instance.addStep({
id: 'test',
attachTo: { element: '.position-test', on: 'top' },
- floatingUIOptions: { strategy: 'fixed' }
+ positionOptions: { strategy: 'fixed' }
});
instance.start();
@@ -152,10 +152,10 @@ describe('utils/floating-ui | position writing', function () {
it('takes the strategy from the resolved payload rather than the step options', async () => {
instance = new Shepherd.Tour();
- // No `floatingUIOptions` on the step at all. The CSS `position` still has
- // to follow what `computePosition` reports it used, because that payload —
- // not the raw user option — is what the returned coordinates are relative
- // to. Reading `step.options.floatingUIOptions.strategy` instead would write
+ // No `positionOptions.strategy` on the step at all. The CSS `position` still
+ // has to follow what `computePosition` reports it used, because that payload
+ // — not the raw user option — is what the returned coordinates are relative
+ // to. Reading `step.options.positionOptions.strategy` instead would write
// `absolute` here and reintroduce the coordinate-space mismatch.
const step = instance.addStep({
id: 'test',
@@ -164,7 +164,7 @@ describe('utils/floating-ui | position writing', function () {
instance.start();
- expect(step.options.floatingUIOptions?.strategy).toBeUndefined();
+ expect(step.options.positionOptions?.strategy).toBeUndefined();
await positionWith(step, {
x: 13,
diff --git a/shepherd.js/test/unit/utils/floating-ui.spec.js b/shepherd.js/test/unit/utils/floating-ui.spec.js
index c2168f5ad..9ba353b79 100644
--- a/shepherd.js/test/unit/utils/floating-ui.spec.js
+++ b/shepherd.js/test/unit/utils/floating-ui.spec.js
@@ -16,39 +16,66 @@ vi.mock('../../../src/utils/position.ts', async (importOriginal) => {
};
});
-import { arrow, offset, shift } from '@floating-ui/dom';
import { Step } from '../../../src/step';
import {
- getFloatingUIOptions,
+ getPositionConfig,
setupTooltip
} from '../../../src/utils/floating-ui';
+import { arrow, flip, place, shift } from '../../../src/utils/position';
describe('Floating UI Utils', function () {
let targetElement;
let stepElement;
- /**
- * Names of the middleware, in execution order. Falsy entries are preserved so
- * that ordering assertions still line up when the user passes them in.
- */
const middlewareNames = ({ middleware }) =>
- middleware.map((item) => (item ? item.name : item));
+ middleware.map(({ name }) => name);
const createStep = (options) => {
const step = new Step({}, { arrow: true, ...options });
- // `addArrow()` only returns the arrow element when the step is rendered.
+ // The arrow middleware is only added once the step is rendered.
step.el = stepElement;
return step;
};
+ const configFor = (options) => {
+ const step = createStep(options);
+ return getPositionConfig(step.options.attachTo, step);
+ };
+
+ /** Where the arrow lands for a narrow target by the viewport's left edge. */
+ const arrowAt = (config) =>
+ place(
+ {
+ rects: {
+ reference: { x: 2, y: 300, width: 4, height: 4 },
+ floating: { x: 0, y: 0, width: 300, height: 120 }
+ },
+ clip: { x: 0, y: 0, width: 1000, height: 700 },
+ origin: { x: 0, y: 0, scale: { x: 1, y: 1 } },
+ rtl: false,
+ floating: stepElement
+ },
+ config
+ ).middlewareData.arrow;
+
+ const arrowWithPadding = (placement, padding) =>
+ arrowAt({
+ placement,
+ strategy: 'absolute',
+ middleware: [flip(), shift(), arrow(stepElement.firstChild, padding)]
+ });
+
beforeEach(() => {
targetElement = document.createElement('div');
targetElement.classList.add('floating-ui-test');
document.body.appendChild(targetElement);
stepElement = document.createElement('div');
+ Object.defineProperty(stepElement, 'clientWidth', { value: 300 });
+ Object.defineProperty(stepElement, 'clientHeight', { value: 120 });
const arrowElement = document.createElement('div');
arrowElement.classList.add('shepherd-arrow');
+ arrowElement.style.cssText = 'width: 16px; height: 16px';
stepElement.appendChild(arrowElement);
document.body.appendChild(stepElement);
});
@@ -60,147 +87,99 @@ describe('Floating UI Utils', function () {
vi.restoreAllMocks();
});
- describe('getFloatingUIOptions()', function () {
- it('keeps user middleware and places the arrow middleware last', function () {
- const step = createStep({
- attachTo: { element: '.floating-ui-test', on: 'right' },
- floatingUIOptions: {
- middleware: [offset(16), shift({ padding: 32 })]
- }
+ describe('getPositionConfig()', function () {
+ it('flips, shifts, and places the arrow last by default', function () {
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test', on: 'right' }
});
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
+ expect(middlewareNames(config)).toEqual(['flip', 'shift', 'arrow']);
+ expect(config.placement).toBe('right');
+ expect(config.strategy).toBe('absolute');
+ });
- expect(middlewareNames(floatingUIOptions)).toEqual([
- 'flip',
- 'shift',
+ it('offsets before anything else measures the step', function () {
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test', on: 'right' },
+ positionOptions: { offset: 12 }
+ });
+
+ expect(middlewareNames(config)).toEqual([
'offset',
+ 'flip',
'shift',
'arrow'
]);
});
- it('does not append its own arrow when the user supplies one', function () {
- const userArrowElement = document.createElement('div');
- const step = createStep({
- attachTo: { element: '.floating-ui-test', on: 'right' },
- floatingUIOptions: {
- middleware: [arrow({ element: userArrowElement }), offset(16)]
- }
+ it('keeps attachTo.on when flip is false', function () {
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test', on: 'top' },
+ positionOptions: { flip: false }
});
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
-
- const names = middlewareNames(floatingUIOptions);
- expect(names).toEqual(['flip', 'shift', 'arrow', 'offset']);
- expect(names.filter((name) => name === 'arrow')).toHaveLength(1);
-
- const arrowMiddleware = floatingUIOptions.middleware.find(
- ({ name }) => name === 'arrow'
- );
- expect(arrowMiddleware.options.element).toBe(userArrowElement);
+ expect(middlewareNames(config)).toEqual(['shift', 'arrow']);
+ expect(config.placement).toBe('top');
});
- it('adds the default middleware when the user supplies none', function () {
- const step = createStep({
- attachTo: { element: '.floating-ui-test', on: 'right' }
+ it('chooses a side with autoPlacement for auto placements', function () {
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test', on: 'auto-start' },
+ positionOptions: { flip: false }
});
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
-
- expect(middlewareNames(floatingUIOptions)).toEqual([
- 'flip',
+ expect(middlewareNames(config)).toEqual([
+ 'autoPlacement',
'shift',
'arrow'
]);
- expect(floatingUIOptions.placement).toBe('right');
- expect(floatingUIOptions.strategy).toBe('absolute');
-
- const arrowMiddleware = floatingUIOptions.middleware.at(-1);
- expect(arrowMiddleware.options.element).toBe(
- stepElement.querySelector('.shepherd-arrow')
- );
- // Padding only applies to edge aligned placements.
- expect(arrowMiddleware.options.padding).toBe(0);
});
- it('passes the arrow padding through for edge aligned placements', function () {
- const step = createStep({
- arrow: { padding: 10 },
- attachTo: { element: '.floating-ui-test', on: 'right-start' }
+ it('passes strategy through', function () {
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test', on: 'right' },
+ positionOptions: { strategy: 'fixed' }
});
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
-
- const arrowMiddleware = floatingUIOptions.middleware.at(-1);
- expect(arrowMiddleware.name).toBe('arrow');
- expect(arrowMiddleware.options.padding).toBe(10);
+ expect(config.strategy).toBe('fixed');
});
- it('defaults the arrow padding for edge aligned placements', function () {
- const step = createStep({
- attachTo: { element: '.floating-ui-test', on: 'right-start' }
+ it('ignores the arrow padding for placements without an alignment', function () {
+ const config = configFor({
+ arrow: { padding: 40 },
+ attachTo: { element: '.floating-ui-test', on: 'bottom' }
});
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
-
- expect(floatingUIOptions.middleware.at(-1).options.padding).toBe(4);
+ expect(arrowAt(config)).toEqual(arrowWithPadding('bottom', 0));
+ expect(arrowAt(config)).not.toEqual(arrowWithPadding('bottom', 40));
});
- it('does not add any middleware for a centered step', function () {
- const step = createStep({
- attachTo: { element: '.floating-ui-test' },
- floatingUIOptions: {
- middleware: [offset(16)]
- }
+ it('passes the arrow padding through for edge aligned placements', function () {
+ const config = configFor({
+ arrow: { padding: 40 },
+ attachTo: { element: '.floating-ui-test', on: 'bottom-start' }
});
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
-
- expect(middlewareNames(floatingUIOptions)).toEqual(['offset']);
- expect(floatingUIOptions.placement).toBeUndefined();
+ expect(arrowAt(config)).toEqual(arrowWithPadding('bottom-start', 40));
+ expect(arrowAt(config)).not.toEqual(arrowWithPadding('bottom-start', 4));
});
- it('tolerates falsy entries in the user middleware', function () {
- const step = createStep({
- attachTo: { element: '.floating-ui-test', on: 'right' },
- floatingUIOptions: {
- middleware: [false, offset(16), null, undefined]
- }
+ it('defaults the arrow padding for edge aligned placements', function () {
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test', on: 'bottom-start' }
});
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
+ expect(arrowAt(config)).toEqual(arrowWithPadding('bottom-start', 4));
+ expect(arrowAt(config)).not.toEqual(arrowWithPadding('bottom-start', 0));
+ });
- expect(middlewareNames(floatingUIOptions)).toEqual([
- 'flip',
- 'shift',
- false,
- 'offset',
- null,
- undefined,
- 'arrow'
- ]);
+ it('adds no middleware for a centered step', function () {
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test' },
+ positionOptions: { offset: 16 }
+ });
+
+ expect(config.middleware).toEqual([]);
});
});
@@ -311,8 +290,7 @@ function createTooltipFixture() {
el: stepElement,
options: {
arrow: false,
- attachTo: { element: target, on: 'bottom' },
- floatingUIOptions: {}
+ attachTo: { element: target, on: 'bottom' }
},
shepherdElementComponent: {
element: stepElement
diff --git a/shepherd.js/test/unit/utils/general.spec.js b/shepherd.js/test/unit/utils/general.spec.js
index 64871a7a6..692af4335 100644
--- a/shepherd.js/test/unit/utils/general.spec.js
+++ b/shepherd.js/test/unit/utils/general.spec.js
@@ -7,7 +7,7 @@ import {
resolveAttachToElement,
waitForAttachToElement
} from '../../../src/utils/general';
-import { getFloatingUIOptions } from '../../../src/utils/floating-ui';
+import { getPositionConfig } from '../../../src/utils/floating-ui';
describe('General Utils', function () {
let optionsElement;
@@ -353,51 +353,15 @@ describe('General Utils', function () {
});
});
- describe('floatingUIOptions', function () {
- it('middleware options are passed in last', function () {
+ describe('positionOptions', function () {
+ it('positioning strategy defaults to absolute', function () {
const step = new Step(
{},
- {
- attachTo: { element: '.options-test', on: 'right' },
- floatingUIOptions: {
- middleware: [
- {
- name: 'preventOverflow',
- options: {
- altAxis: false
- }
- }
- ]
- }
- }
- );
-
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
- // Shepherd pushes in flip and shift by default, so this is 3rd
- expect(floatingUIOptions.middleware[2].options.altAxis).toBe(false);
- });
-
- it('positioning strategy is explicitly set', function () {
- const step = new Step(
- {},
- {
- attachTo: { element: '.options-test', on: 'center' },
- options: {
- floatingUIOptions: {
- strategy: 'absolute'
- }
- }
- }
+ { attachTo: { element: '.options-test', on: 'right' } }
);
- const floatingUIOptions = getFloatingUIOptions(
- step.options.attachTo,
- step
- );
- expect(floatingUIOptions.strategy).toBe('absolute');
+ const config = getPositionConfig(step.options.attachTo, step);
+ expect(config.strategy).toBe('absolute');
});
});
diff --git a/shepherd.js/test/unit/utils/merge.spec.js b/shepherd.js/test/unit/utils/merge.spec.js
deleted file mode 100644
index c5b6c3b35..000000000
--- a/shepherd.js/test/unit/utils/merge.spec.js
+++ /dev/null
@@ -1,72 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { merge } from '../../../src/utils/merge';
-
-describe('merge', () => {
- it('merges records recursively without mutating either side', () => {
- const base = { platform: { a: 1, b: 1 } };
- const override = { platform: { b: 2 }, strategy: 'fixed' };
-
- expect(merge(base, override)).toEqual({
- platform: { a: 1, b: 2 },
- strategy: 'fixed'
- });
- expect(base).toEqual({ platform: { a: 1, b: 1 } });
- expect(override).toEqual({ platform: { b: 2 }, strategy: 'fixed' });
- });
-
- it('concatenates arrays, base first, into a new array', () => {
- const base = { middleware: [1] };
- const override = { middleware: [2, [3]] };
- const merged = merge(base, override);
-
- expect(merged.middleware).toEqual([1, 2, [3]]);
- expect(merged.middleware).not.toBe(base.middleware);
- });
-
- it('shares a value only one side defined', () => {
- const middleware = [1];
-
- expect(merge({ middleware }, {}).middleware).toBe(middleware);
- expect(merge({}, { middleware }).middleware).toBe(middleware);
- });
-
- it('never lets undefined override a value, but keeps the key', () => {
- expect(merge({ a: 1 }, { a: undefined })).toEqual({ a: 1 });
-
- const merged = merge({}, { toString: undefined });
- expect(Object.keys(merged)).toEqual(['toString']);
- expect(merged.toString).toBeUndefined();
- });
-
- it('takes the last value when types differ', () => {
- expect(merge({ a: [1] }, { a: { b: 1 } })).toEqual({ a: { b: 1 } });
- expect(merge({ a: { b: 1 } }, { a: null })).toEqual({ a: null });
- });
-
- it('treats class instances as values rather than records', () => {
- class Boundary {
- x = 1;
- }
- const first = new Boundary();
- const second = new Boundary();
-
- expect(merge({ a: first }, { a: second }).a).toBe(second);
- });
-
- it('merges plain objects with a null prototype', () => {
- const base = Object.assign(Object.create(null), { a: 1 });
-
- expect(merge({ o: base }, { o: { b: 2 } }).o).toEqual({ a: 1, b: 2 });
- });
-
- it('does not pollute prototypes through a __proto__ key', () => {
- const merged = merge(
- JSON.parse('{"__proto__": {"a": 1}}'),
- JSON.parse('{"__proto__": {"polluted": true}}')
- );
-
- expect({}.polluted).toBeUndefined();
- expect(merged.polluted).toBeUndefined();
- expect(Object.getPrototypeOf(merged)).toBe(Object.prototype);
- });
-});
diff --git a/shepherd.js/test/unit/utils/position.spec.js b/shepherd.js/test/unit/utils/position.spec.js
index 3a337068c..2d08a3300 100644
--- a/shepherd.js/test/unit/utils/position.spec.js
+++ b/shepherd.js/test/unit/utils/position.spec.js
@@ -4,19 +4,18 @@ import {
autoPlacement as floatingAutoPlacement,
computePosition as floatingComputePosition,
flip as floatingFlip,
- hide,
limitShift,
- offset,
- platform as floatingPlatform,
- shift as floatingShift,
- size
+ offset as floatingOffset,
+ shift as floatingShift
} from '@floating-ui/dom';
import {
arrow,
autoPlacement,
autoUpdate,
- computePosition,
flip,
+ measure,
+ offset,
+ place,
shift
} from '../../../src/utils/position.ts';
@@ -54,9 +53,9 @@ const REFERENCES = [
const ARROW_PADDINGS = [0, 4, 40, 500];
/**
- * happy-dom has no layout, so geometry comes from a platform stub. Real
- * browsers are covered by the scorecard's parity goldens; this pins the
- * middleware logic against Floating UI's own for every placement.
+ * happy-dom has no layout, so the engine's math runs on given measurements and
+ * stock Floating UI on a platform returning the same ones. Real browsers are
+ * covered by the scorecard's parity goldens and `pnpm test:position`.
*/
function stubPlatform(reference, rtl, viewport = VIEWPORTS[0]) {
return {
@@ -75,6 +74,14 @@ function stubPlatform(reference, rtl, viewport = VIEWPORTS[0]) {
};
}
+const measurements = (floating, reference, rtl, viewport = VIEWPORTS[0]) => ({
+ rects: { reference, floating: { x: 0, y: 0, ...FLOATING } },
+ clip: viewport,
+ origin: { x: 0, y: 0, scale: { x: 1, y: 1 } },
+ rtl,
+ floating
+});
+
function elements() {
const reference = document.createElement('div');
const floating = document.createElement('div');
@@ -83,6 +90,9 @@ function elements() {
// The engine reads the free space for the arrow from `clientWidth`.
Object.defineProperty(floating, 'clientWidth', { value: FLOATING.width });
Object.defineProperty(floating, 'clientHeight', { value: FLOATING.height });
+ arrowElement.style.cssText = 'width: 16px; height: 16px';
+ Object.defineProperty(arrowElement, 'offsetWidth', { value: 16 });
+ Object.defineProperty(arrowElement, 'offsetHeight', { value: 16 });
return { reference, floating, arrowElement };
}
@@ -94,80 +104,125 @@ const outcome = ({ x, y, placement, middlewareData: { arrow: data } }) => ({
arrowY: data?.y
});
+/** Both engines, given the same geometry, with each side's own middleware. */
+async function bothWays({ reference, rtl, viewport, placement, ours, theirs }) {
+ const { reference: ref, floating, arrowElement } = elements();
+ const engine = place(measurements(floating, reference, rtl, viewport), {
+ placement: placement ?? 'bottom',
+ strategy: 'absolute',
+ middleware: ours(arrowElement)
+ });
+ const stock = await floatingComputePosition(ref, floating, {
+ placement,
+ platform: stubPlatform(reference, rtl, viewport),
+ middleware: theirs(arrowElement)
+ });
+ return [outcome(engine), outcome(stock)];
+}
+
+const stockShift = (options) =>
+ floatingShift({ limiter: limitShift(), crossAxis: true, ...options });
+
describe('utils/position', () => {
afterEach(() => {
vi.restoreAllMocks();
});
- describe('computePosition()', () => {
+ describe('place()', () => {
describe.each([false, true])('with rtl %s', (rtl) => {
describe.each(VIEWPORTS)('in a $width x $height viewport', (viewport) => {
it.each(REFERENCES)(
'matches Floating UI with flip, shift, and arrow for $x,$y',
async (reference) => {
- const { reference: ref, floating, arrowElement } = elements();
- const platform = stubPlatform(reference, rtl, viewport);
-
for (const placement of PLACEMENTS) {
for (const padding of ARROW_PADDINGS) {
- const ours = await computePosition(ref, floating, {
+ const [ours, theirs] = await bothWays({
+ reference,
+ rtl,
+ viewport,
placement,
- platform,
- middleware: [
- flip(),
- shift(),
- arrow({ element: arrowElement, padding })
+ ours: (element) => [flip(), shift(), arrow(element, padding)],
+ theirs: (element) => [
+ floatingFlip(),
+ stockShift(),
+ floatingArrow({ element, padding })
]
});
- const theirs = await floatingComputePosition(ref, floating, {
+ expect(ours, `${placement} ${padding}`).toEqual(theirs);
+ }
+ }
+ }
+ );
+
+ it.each(REFERENCES)(
+ 'matches Floating UI with offset first for $x,$y',
+ async (reference) => {
+ for (const placement of PLACEMENTS) {
+ for (const distance of [12, { mainAxis: 12, crossAxis: 7 }]) {
+ const [ours, theirs] = await bothWays({
+ reference,
+ rtl,
+ viewport,
placement,
- platform,
- middleware: [
+ ours: (element) => [
+ offset(distance),
+ flip(),
+ shift(),
+ arrow(element, 40)
+ ],
+ theirs: (element) => [
+ floatingOffset(distance),
floatingFlip(),
- floatingShift({ limiter: limitShift(), crossAxis: true }),
- floatingArrow({ element: arrowElement, padding })
+ stockShift(),
+ floatingArrow({ element, padding: 40 })
]
});
-
- expect(outcome(ours), `${placement} ${padding}`).toEqual(
- outcome(theirs)
- );
+ expect(
+ ours,
+ `${placement} ${JSON.stringify(distance)}`
+ ).toEqual(theirs);
}
}
}
);
it.each(REFERENCES)(
- 'matches Floating UI with a consumer offset for $x,$y',
+ 'matches Floating UI with padding for $x,$y',
async (reference) => {
- const { reference: ref, floating, arrowElement } = elements();
- const platform = stubPlatform(reference, rtl, viewport);
- const padding = 40;
-
for (const placement of PLACEMENTS) {
- const distance = { mainAxis: 12, crossAxis: 7 };
- const ours = await computePosition(ref, floating, {
+ const [ours, theirs] = await bothWays({
+ reference,
+ rtl,
+ viewport,
placement,
- platform,
- middleware: [
- flip(),
- shift(),
- offset(distance),
- arrow({ element: arrowElement, padding })
+ ours: (element) => [flip(24), shift(24), arrow(element, 4)],
+ theirs: (element) => [
+ floatingFlip({ padding: 24 }),
+ stockShift({ padding: 24 }),
+ floatingArrow({ element, padding: 4 })
]
});
- const theirs = await floatingComputePosition(ref, floating, {
+ expect(ours, placement).toEqual(theirs);
+ }
+ }
+ );
+
+ it.each(REFERENCES)(
+ 'matches Floating UI without flip for $x,$y',
+ async (reference) => {
+ for (const placement of PLACEMENTS) {
+ const [ours, theirs] = await bothWays({
+ reference,
+ rtl,
+ viewport,
placement,
- platform,
- middleware: [
- floatingFlip(),
- floatingShift({ limiter: limitShift(), crossAxis: true }),
- offset(distance),
- floatingArrow({ element: arrowElement, padding })
+ ours: (element) => [shift(), arrow(element, 4)],
+ theirs: (element) => [
+ stockShift(),
+ floatingArrow({ element, padding: 4 })
]
});
-
- expect(outcome(ours), placement).toEqual(outcome(theirs));
+ expect(ours, placement).toEqual(theirs);
}
}
);
@@ -176,137 +231,74 @@ describe('utils/position', () => {
it.each(REFERENCES)(
'matches Floating UI with autoPlacement for $x,$y',
async (reference) => {
- const { reference: ref, floating } = elements();
- const platform = stubPlatform(reference, rtl);
-
- for (const alignment of [null, 'start', 'end']) {
- const ours = await computePosition(ref, floating, {
- platform,
- middleware: [autoPlacement({ alignment }), shift()]
- });
- const theirs = await floatingComputePosition(ref, floating, {
- platform,
- middleware: [
- floatingAutoPlacement({ crossAxis: true, alignment }),
- floatingShift({ limiter: limitShift(), crossAxis: true })
- ]
- });
-
- expect(outcome(ours), String(alignment)).toEqual(outcome(theirs));
+ for (const alignment of [undefined, 'start', 'end']) {
+ for (const padding of [undefined, 24]) {
+ const [ours, theirs] = await bothWays({
+ reference,
+ rtl,
+ ours: () => [autoPlacement(alignment, padding), shift(padding)],
+ theirs: () => [
+ floatingAutoPlacement({
+ crossAxis: true,
+ alignment,
+ padding
+ }),
+ stockShift({ padding })
+ ]
+ });
+ expect(ours, `${alignment} ${padding}`).toEqual(theirs);
+ }
}
}
);
});
- it('runs real Floating UI middleware unchanged', async () => {
- const { reference: ref, floating } = elements();
- const platform = stubPlatform(REFERENCES[1], false);
- const middleware = () => [
- offset({ mainAxis: 12, crossAxis: 3 }),
- floatingFlip({ padding: 8, fallbackAxisSideDirection: 'start' }),
- floatingShift({ padding: 24 }),
- size({ padding: 4, apply() {} }),
- hide()
- ];
-
- const ours = await computePosition(ref, floating, {
- placement: 'top',
- platform,
- middleware: middleware()
- });
- const theirs = await floatingComputePosition(ref, floating, {
- placement: 'top',
- platform,
- middleware: middleware()
- });
-
- expect(ours).toEqual(theirs);
- });
-
- it("runs a platform spread from Floating UI's own", async () => {
- const { reference: ref, floating } = elements();
+ it('stops resetting a middleware that never settles', () => {
+ const { floating } = elements();
+ const fn = vi.fn(() => ({ reset: true }));
- const result = await computePosition(ref, floating, {
- placement: 'top',
- platform: { ...floatingPlatform },
- middleware: [flip(), shift()]
+ place(measurements(floating, REFERENCES[0], false), {
+ placement: 'bottom',
+ strategy: 'absolute',
+ middleware: [{ name: 'restless', fn }]
});
- expect(result.x).toBe(0);
- expect(result.y).toBe(0);
- });
-
- it('waits for a platform whose methods are async', async () => {
- const { reference: ref, floating, arrowElement } = elements();
- const sync = stubPlatform(REFERENCES[2], false);
- const asyncPlatform = Object.fromEntries(
- Object.entries(sync).map(([name, method]) => [
- name,
- async (...args) => method(...args)
- ])
- );
- const position = (platform) =>
- computePosition(ref, floating, {
- placement: 'bottom-start',
- platform,
- middleware: [
- flip(),
- shift(),
- arrow({ element: arrowElement, padding: 4 })
- ]
- });
-
- expect(outcome(await position(asyncPlatform))).toEqual(
- outcome(await position(sync))
- );
+ expect(fn).toHaveBeenCalledTimes(51);
});
+ });
- it('recognizes a modal dialog where :popover-open is not supported', async () => {
- const { reference: ref, floating } = elements();
+ describe('measure()', () => {
+ it('measures a modal dialog against the viewport where :popover-open is not supported', () => {
+ const { reference, floating } = elements();
+ const container = document.createElement('div');
+ container.style.transform = 'translateX(10px)';
+ container.append(floating);
+ document.body.append(container, reference);
+ vi.spyOn(container, 'getBoundingClientRect').mockReturnValue({
+ x: 100,
+ y: 100,
+ width: 500,
+ height: 500
+ });
+ vi.spyOn(reference, 'getBoundingClientRect').mockReturnValue({
+ x: 300,
+ y: 200,
+ width: 10,
+ height: 10
+ });
+ const inContainer = measure(reference, floating, 'absolute');
vi.spyOn(floating, 'matches').mockImplementation((selector) => {
if (selector.includes(':popover-open')) {
throw new DOMException('Unknown selector', 'SyntaxError');
}
return selector === ':modal';
});
- let offsetParent;
-
- await computePosition(ref, floating, {
- middleware: [
- {
- name: 'probe',
- fn({ platform }) {
- offsetParent = platform.getOffsetParent(floating);
- return {};
- }
- }
- ]
- });
-
- expect(offsetParent).toBe(window);
- });
-
- it('skips falsy middleware entries', async () => {
- const { reference: ref, floating } = elements();
- const result = await computePosition(ref, floating, {
- placement: 'bottom',
- platform: stubPlatform(REFERENCES[0], false),
- middleware: [false, null, undefined]
- });
+ const asModal = measure(reference, floating, 'absolute');
+ container.remove();
+ reference.remove();
- expect(result.placement).toBe('bottom');
- });
-
- it('stops resetting a middleware that never settles', async () => {
- const { reference: ref, floating } = elements();
- const fn = vi.fn(() => ({ reset: true }));
-
- await computePosition(ref, floating, {
- platform: stubPlatform(REFERENCES[0], false),
- middleware: [{ name: 'restless', fn }]
- });
-
- expect(fn).toHaveBeenCalledTimes(51);
+ expect(inContainer.rects.reference).toMatchObject({ x: 200, y: 100 });
+ expect(asModal.rects.reference).toMatchObject({ x: 300, y: 200 });
});
});
From 74e072cef2e35d1cad3f23112dd4e0c9bbc7994f Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 07:52:47 -0500
Subject: [PATCH 74/93] test(scorecard): score the positionOptions API change
The three option cases now pass `positionOptions` (`strategy: 'fixed'`,
`offset: 12`, `padding: 24`) instead of Floating UI middleware, against the
unchanged goldens. The API golden drops `StepOptions.floatingUIOptions` and
adds `StepOptions.positionOptions` and `StepOptionsPosition`, and picks up
names already exported before this change.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/scripts/scorecard/golden/api.json | 12 +++++++++++-
shepherd.js/scripts/scorecard/parity.mjs | 8 +++-----
2 files changed, 14 insertions(+), 6 deletions(-)
diff --git a/shepherd.js/scripts/scorecard/golden/api.json b/shepherd.js/scripts/scorecard/golden/api.json
index 22f59e117..856a98d12 100644
--- a/shepherd.js/scripts/scorecard/golden/api.json
+++ b/shepherd.js/scripts/scorecard/golden/api.json
@@ -29,6 +29,7 @@
"ShepherdModalAPI.setupForStep",
"ShepherdModalAPI.show",
"Step",
+ "Step$1",
"Step.cancel",
"Step.classPrefix",
"Step.cleanup",
@@ -47,6 +48,7 @@
"Step.target",
"Step.tour",
"Step.updateStepOptions",
+ "StepButtonAction",
"StepOptions",
"StepOptions.advanceOn",
"StepOptions.arrow",
@@ -58,7 +60,6 @@
"StepOptions.classes",
"StepOptions.data",
"StepOptions.extraHighlights",
- "StepOptions.floatingUIOptions",
"StepOptions.highlightClass",
"StepOptions.id",
"StepOptions.label",
@@ -66,6 +67,7 @@
"StepOptions.modalOverlayOpeningRadius",
"StepOptions.modalOverlayOpeningXOffset",
"StepOptions.modalOverlayOpeningYOffset",
+ "StepOptions.positionOptions",
"StepOptions.scrollTo",
"StepOptions.scrollToHandler",
"StepOptions.showOn",
@@ -95,10 +97,16 @@
"StepOptionsCancelIcon.attrs",
"StepOptionsCancelIcon.enabled",
"StepOptionsCancelIcon.label",
+ "StepOptionsPosition",
+ "StepOptionsPosition.flip",
+ "StepOptionsPosition.offset",
+ "StepOptionsPosition.padding",
+ "StepOptionsPosition.strategy",
"StepOptionsWhen",
"StepText",
"StringOrStringFunction",
"Tour",
+ "Tour$1",
"Tour.addStep",
"Tour.addSteps",
"Tour.back",
@@ -135,5 +143,7 @@
"TourOptions.stepsContainer",
"TourOptions.tourName",
"TourOptions.useModalOverlay",
+ "export:Step",
+ "export:Tour",
"export:default"
]
diff --git a/shepherd.js/scripts/scorecard/parity.mjs b/shepherd.js/scripts/scorecard/parity.mjs
index cfd49d498..99e774d0d 100644
--- a/shepherd.js/scripts/scorecard/parity.mjs
+++ b/shepherd.js/scripts/scorecard/parity.mjs
@@ -74,8 +74,6 @@ function buildCases() {
async function runCase(cfg) {
const { default: Shepherd } = await import('/dist/js/shepherd.mjs');
- const { offset, shift } =
- await import('/vendor/floating-ui-user-middleware.mjs');
const page = document.getElementById('page');
page.innerHTML = '';
page.removeAttribute('style');
@@ -150,13 +148,13 @@ async function runCase(cfg) {
if (cfg.context === 'noArrow') stepOptions.arrow = false;
if (cfg.context === 'arrowPadding') stepOptions.arrow = { padding: 16 };
if (cfg.context === 'strategyFixed') {
- stepOptions.floatingUIOptions = { strategy: 'fixed' };
+ stepOptions.positionOptions = { strategy: 'fixed' };
}
if (cfg.context === 'userOffset') {
- stepOptions.floatingUIOptions = { middleware: [offset(12)] };
+ stepOptions.positionOptions = { offset: 12 };
}
if (cfg.context === 'userShift') {
- stepOptions.floatingUIOptions = { middleware: [shift({ padding: 24 })] };
+ stepOptions.positionOptions = { padding: 24 };
}
if (cfg.context === 'centeredNoOn')
stepOptions.attachTo = { element: target };
From 579e29dab600a1e184b75cfda641350b1fe6d9d4 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 07:54:10 -0500
Subject: [PATCH 75/93] perf: position steps synchronously
With no consumer platform to await, nothing in positioning is async. The
step is written in the same task that measured it, and focus still moves one
frame later.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/floating-ui.ts | 98 ++++++++-----------
shepherd.js/src/utils/position.ts | 4 +-
.../unit/utils/floating-ui-position.spec.js | 4 +-
.../test/unit/utils/floating-ui.spec.js | 6 +-
4 files changed, 50 insertions(+), 62 deletions(-)
diff --git a/shepherd.js/src/utils/floating-ui.ts b/shepherd.js/src/utils/floating-ui.ts
index b35dbd70d..02c3a4841 100644
--- a/shepherd.js/src/utils/floating-ui.ts
+++ b/shepherd.js/src/utils/floating-ui.ts
@@ -78,75 +78,61 @@ function setPosition(
shouldCenter: boolean,
{ shouldFocusAfterRender }: { shouldFocusAfterRender: boolean }
) {
- const positionPromise = computePosition(
- target,
- step.el as HTMLElement,
- config
- )
- .then(writePosition(step, shouldCenter))
- .catch((error: unknown) => {
- console.error('Shepherd: could not position a step.', error);
- return step;
- });
-
- if (!shouldFocusAfterRender) {
- return positionPromise;
+ try {
+ writePosition(
+ step,
+ shouldCenter,
+ computePosition(target, step.el as HTMLElement, config)
+ );
+ } catch (error) {
+ console.error('Shepherd: could not position a step.', error);
}
- return positionPromise.then((step: Step) => {
+ if (shouldFocusAfterRender) {
// Focusing flushes layout, which the next frame does anyway. jsdom only has
// frames when asked to.
(window.requestAnimationFrame || setTimeout)(() => {
- if (step?.el) {
+ if (step.el) {
step.el.tabIndex = 0;
step.el.focus({ preventScroll: true });
}
});
- });
+ }
}
-function writePosition(step: Step, shouldCenter: boolean) {
- return ({
- x,
- y,
- strategy,
- placement,
- middlewareData
- }: ComputePositionResult) => {
- if (!step.el) {
- return step;
- }
-
- if (shouldCenter) {
- // `position: fixed` is intentional here and must NOT follow `strategy`.
- // Centering relies on `left`/`top: 50%` plus a `translate(-50%, -50%)`,
- // and those percentages have to resolve against the viewport. Under the
- // default `absolute` strategy they would resolve against the document
- // instead, placing the step at 50% of the *page* height so it scrolls
- // off screen. A step centers when it has no `attachTo`, or when its
- // `attachTo` is missing either `element` or `on` (see `shouldCenterStep`);
- // all of those are modal dialogs, so viewport centering is the correct
- // behavior regardless of `strategy`.
- Object.assign(step.el.style, {
- position: 'fixed',
- left: '50%',
- top: '50%',
- transform: 'translate(-50%, -50%)'
- });
- } else {
- Object.assign(step.el.style, {
- position: strategy,
- left: `${x}px`,
- top: `${y}px`
- });
- }
-
- step.el.dataset['popperPlacement'] = placement;
+function writePosition(
+ step: Step,
+ shouldCenter: boolean,
+ { x, y, strategy, placement, middlewareData }: ComputePositionResult
+) {
+ const el = step.el as HTMLElement;
+ if (shouldCenter) {
+ // `position: fixed` is intentional here and must NOT follow `strategy`.
+ // Centering relies on `left`/`top: 50%` plus a `translate(-50%, -50%)`,
+ // and those percentages have to resolve against the viewport. Under the
+ // default `absolute` strategy they would resolve against the document
+ // instead, placing the step at 50% of the *page* height so it scrolls
+ // off screen. A step centers when it has no `attachTo`, or when its
+ // `attachTo` is missing either `element` or `on` (see `shouldCenterStep`);
+ // all of those are modal dialogs, so viewport centering is the correct
+ // behavior regardless of `strategy`.
+ Object.assign(el.style, {
+ position: 'fixed',
+ left: '50%',
+ top: '50%',
+ transform: 'translate(-50%, -50%)'
+ });
+ } else {
+ Object.assign(el.style, {
+ position: strategy,
+ left: `${x}px`,
+ top: `${y}px`
+ });
+ }
- placeArrow(step.el, middlewareData);
+ el.dataset['popperPlacement'] = placement;
- return step;
- };
+ placeArrow(el, middlewareData);
}
function placeArrow(
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index 19f86592b..8ac4d9b86 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -494,11 +494,11 @@ export function place(
return { x, y, placement, strategy, middlewareData };
}
-export async function computePosition(
+export function computePosition(
reference: Element,
floating: HTMLElement,
config: PositionConfig
-): Promise {
+): ComputePositionResult {
return place(measure(reference, floating, config.strategy), config);
}
diff --git a/shepherd.js/test/unit/utils/floating-ui-position.spec.js b/shepherd.js/test/unit/utils/floating-ui-position.spec.js
index 0b84f4e67..66ad1a679 100644
--- a/shepherd.js/test/unit/utils/floating-ui-position.spec.js
+++ b/shepherd.js/test/unit/utils/floating-ui-position.spec.js
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import ResizeObserver from 'resize-observer-polyfill';
// happy-dom has no layout engine: every `getBoundingClientRect()` is 0x0 at the
-// origin, so a real `computePosition` call always resolves `{ x: 0, y: 0 }` and
+// origin, so a real `computePosition` call always returns `{ x: 0, y: 0 }` and
// no assertion about coordinates can fail. These tests therefore stub the
// positioning engine's boundary and assert what Shepherd writes to
// `step.el.style` for a given resolved position payload.
@@ -22,7 +22,7 @@ vi.mock('../../../src/utils/position.ts', async (importOriginal) => {
return {
...actual,
- computePosition: vi.fn(() => Promise.resolve({ ...floatingUI.position })),
+ computePosition: vi.fn(() => ({ ...floatingUI.position })),
// Run the position callback once, synchronously, rather than wiring up the
// scroll/resize observers that happy-dom cannot drive.
autoUpdate: vi.fn((_target, _element, update) => {
diff --git a/shepherd.js/test/unit/utils/floating-ui.spec.js b/shepherd.js/test/unit/utils/floating-ui.spec.js
index 9ba353b79..af3ae0780 100644
--- a/shepherd.js/test/unit/utils/floating-ui.spec.js
+++ b/shepherd.js/test/unit/utils/floating-ui.spec.js
@@ -196,7 +196,7 @@ describe('Floating UI Utils', function () {
return vi.fn();
}
);
- floatingUIMock.computePosition.mockResolvedValue({
+ floatingUIMock.computePosition.mockReturnValue({
middlewareData: {},
placement: 'bottom',
strategy: 'absolute',
@@ -238,7 +238,9 @@ describe('Floating UI Utils', function () {
it('reports a step it could not position, and still focuses it', async () => {
const { step, stepElement } = createTooltipFixture();
const cause = new Error('no platform');
- floatingUIMock.computePosition.mockRejectedValueOnce(cause);
+ floatingUIMock.computePosition.mockImplementationOnce(() => {
+ throw cause;
+ });
const consoleError = vi.spyOn(console, 'error');
setupTooltip(step);
From a705782b29e2f563f6ea6e393a3d774b8d0f7968 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 08:00:44 -0500
Subject: [PATCH 76/93] fix: position the arrow when it is an SVG or from
another realm
`getPositionConfig` checked the arrow with `instanceof HTMLElement`, which
fails for an SVG arrow and for a step rendered into an iframe's document.
The differential's `svgArrow` and `iframeBothInside` fixtures caught it.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/src/utils/floating-ui.ts | 2 +-
shepherd.js/src/utils/position.ts | 2 +-
shepherd.js/test/unit/utils/floating-ui.spec.js | 14 ++++++++++++++
3 files changed, 16 insertions(+), 2 deletions(-)
diff --git a/shepherd.js/src/utils/floating-ui.ts b/shepherd.js/src/utils/floating-ui.ts
index 02c3a4841..3900dd94a 100644
--- a/shepherd.js/src/utils/floating-ui.ts
+++ b/shepherd.js/src/utils/floating-ui.ts
@@ -186,7 +186,7 @@ export function getPositionConfig(
const arrowEl =
step.options.arrow && step.el?.querySelector('.shepherd-arrow');
- if (isHTMLElement(arrowEl)) {
+ if (arrowEl) {
const arrowPadding =
typeof step.options.arrow === 'object' ? step.options.arrow.padding : 4;
middleware.push(arrow(arrowEl, alignment ? arrowPadding : 0));
diff --git a/shepherd.js/src/utils/position.ts b/shepherd.js/src/utils/position.ts
index 8ac4d9b86..ddc3ba768 100644
--- a/shepherd.js/src/utils/position.ts
+++ b/shepherd.js/src/utils/position.ts
@@ -702,7 +702,7 @@ export function shift(padding?: number): Middleware {
};
}
-export function arrow(element: HTMLElement, padding = 0): Middleware {
+export function arrow(element: Element, padding = 0): Middleware {
return {
name: 'arrow',
fn(state) {
diff --git a/shepherd.js/test/unit/utils/floating-ui.spec.js b/shepherd.js/test/unit/utils/floating-ui.spec.js
index af3ae0780..638ccd4e1 100644
--- a/shepherd.js/test/unit/utils/floating-ui.spec.js
+++ b/shepherd.js/test/unit/utils/floating-ui.spec.js
@@ -173,6 +173,20 @@ describe('Floating UI Utils', function () {
expect(arrowAt(config)).not.toEqual(arrowWithPadding('bottom-start', 0));
});
+ it('positions an SVG arrow', function () {
+ const svgArrow = document.createElementNS(
+ 'http://www.w3.org/2000/svg',
+ 'svg'
+ );
+ svgArrow.classList.add('shepherd-arrow');
+ stepElement.replaceChildren(svgArrow);
+ const config = configFor({
+ attachTo: { element: '.floating-ui-test', on: 'right' }
+ });
+
+ expect(middlewareNames(config)).toEqual(['flip', 'shift', 'arrow']);
+ });
+
it('adds no middleware for a centered step', function () {
const config = configFor({
attachTo: { element: '.floating-ui-test' },
From 748f61c6147e344e2d1b845cc64cfa91b367d164 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 08:00:44 -0500
Subject: [PATCH 77/93] test(position): compare positionOptions against stock
middleware
Consumer middleware and platforms no longer run, so the differential drops
`USER_CONFIGS` and `RAW_CONFIGS` and instead runs each `positionOptions`
key against the stock middleware it stands for. `dist-platform.mjs`, which
guarded `_c` against mangling, becomes `dist-position.mjs`, which checks
each key through the built package. Known differences keep only the rows
a step can reach.
Co-Authored-By: Claude Opus 5.5
---
.../test/position-differential/README.md | 28 +-
.../position-differential/dist-platform.mjs | 112 ---
.../position-differential/dist-position.mjs | 100 +++
.../test/position-differential/fixtures.js | 147 +---
.../known-differences.json | 741 +++---------------
.../test/position-differential/run.mjs | 52 +-
6 files changed, 238 insertions(+), 942 deletions(-)
delete mode 100644 shepherd.js/test/position-differential/dist-platform.mjs
create mode 100644 shepherd.js/test/position-differential/dist-position.mjs
diff --git a/shepherd.js/test/position-differential/README.md b/shepherd.js/test/position-differential/README.md
index 1c58bee38..86f1aaf78 100644
--- a/shepherd.js/test/position-differential/README.md
+++ b/shepherd.js/test/position-differential/README.md
@@ -17,12 +17,11 @@ It takes about three minutes and needs no build. It reads `src/`, not `dist/`.
Every fixture in `fixtures.js` runs in standards and quirks mode, under both
`strategy` values:
-- **Shepherd's wiring.** `getFloatingUIOptions` from `src/utils/floating-ui.ts`
- against the options it used to build for stock. Each `USER_CONFIGS` entry adds
- what a consumer might pass in `floatingUIOptions`: stock middleware, boundaries,
- a `platform` spread from stock, and a `platform` whose methods are all async.
-- **Stock middleware alone.** `RAW_CONFIGS` runs only stock middleware through the
- engine's `computePosition`, and compares all of `middlewareData`.
+- **Shepherd's wiring.** `getPositionConfig` from `src/utils/floating-ui.ts`
+ against the stock middleware it stands for, built by `stockOptions`. Each
+ `POSITION_CONFIGS` entry is a `positionOptions` a consumer might pass:
+ `offset` maps to stock `offset()` first, `padding` to the `padding` of
+ `flip()`, `autoPlacement()` and `shift()`, and `flip: false` drops `flip()`.
- **The tracker.** `autoUpdate` must react to a window or ancestor scroll, a resize
of either element, a layout shift, a transform, and a shift after settling, and
must do nothing while idle or after cleanup.
@@ -42,26 +41,21 @@ node test/position-differential/run.mjs --update-known
## Known differences
`known-differences.json` records how many cases differ per browser, mode, fixture
-and config. With no `floatingUIOptions`, a step can only reach the first row, the
-second row, and the gutter fixtures in the last row. The rest need a consumer's own
-boundary, or a DOM shape Shepherd does not build.
+and config. Every `positionOptions` config hits the same rows as `none`, because
+the differences come from the page, not the options.
-| Fixtures or configs | Difference | Why it stays |
+| Fixtures | Difference | Why it stays |
| --- | --- | --- |
-| `bodySlightlyNarrow`, `bodyNarrowerThanHtml` | Stock treats a `` up to 25px narrower than the root as a scrollbar gutter and pulls the right edge in. The engine does not. | No gutter exists there. A real gutter is handled, by the root's own width. |
+| `bodySlightlyNarrow`, `bodyNarrowerThanHtml`, and the `scrollbarGutter`, `gutterHidden`, `gutterStable` fixtures in quirks mode | Stock treats a `` up to 25px narrower than the root as a scrollbar gutter and pulls the right edge in. The engine does not. | No gutter exists there. A real gutter is handled, by the root's own width. |
| `scaledBorderedContainer` | Under a scaled, bordered offset parent, `auto` placements that tie can pick another side or alignment. | Stock adds that parent's border unscaled, so its overflow numbers are off by the border. Both results sit against the target and in view. |
-| `staticFloatingInTd`, `svgArrowNested` | The engine's arrow assumes the step is its offset parent. | `.shepherd-arrow` is always a direct child of a positioned step. A consumer's own `arrow()` is stock's. |
-| `rootLayout` config | The engine treats `rootBoundary: 'layoutViewport'` as `'viewport'`. | They differ only while pinch-zoomed, or in Firefox quirks mode and iframes. |
-| `rootRect`, `boundaryElement`, `boundaryRect`, `options` under `html*` and `gutter*Both` fixtures | A consumer's explicit `boundary` or `rootBoundary` is off by the root's left offset. | Needs both a custom boundary and a root offset by a margin or a left gutter. |
-| `hideRef`, `hideEscaped`, `size`, `allReal` under `bodyOverflowOwnScroller`, `htmlMarginOverflowParent` | Stock `hide` and `size` report other offsets. Position and placement match. | Same root offset, or stock's body-width gutter, in numbers only those middleware read. |
-| `scrolledXY`, `rtlOverflowX`, and gutter fixtures in quirks mode | Custom boundaries, or the gutter, against `` in quirks mode. | Quirks mode with horizontal scrolling or `scrollbar-gutter`. |
+| `staticFloatingInTd`, `svgArrowNested` | The engine's arrow assumes the step is its offset parent. | `.shepherd-arrow` is always a direct child of a positioned step. |
## Other checks
Each needs `pnpm build` first and exercises the published `dist`:
```sh
-node test/position-differential/dist-platform.mjs # stock platform and middleware, through property mangling
+node test/position-differential/dist-position.mjs # each positionOptions key, through property mangling
node test/position-differential/cross-origin.mjs # a tour inside a cross-origin iframe
node test/position-differential/jsdom.mjs # a tour in jsdom, without and with --visual
```
diff --git a/shepherd.js/test/position-differential/dist-platform.mjs b/shepherd.js/test/position-differential/dist-platform.mjs
deleted file mode 100644
index ffa19b316..000000000
--- a/shepherd.js/test/position-differential/dist-platform.mjs
+++ /dev/null
@@ -1,112 +0,0 @@
-// The published build with a consumer's own @floating-ui/dom platform and
-// middleware, in real browsers. Guards `_c` against property mangling, which the
-// source-level differential cannot see. Run `pnpm build` first.
-import process from 'node:process';
-import { build } from 'esbuild';
-import * as playwright from 'playwright-core';
-import { packageDir, serve } from '../../scripts/scorecard/lib.mjs';
-
-const bundled = await build({
- stdin: {
- contents: `export * from '@floating-ui/dom';`,
- resolveDir: packageDir,
- loader: 'js'
- },
- bundle: true,
- format: 'iife',
- globalName: 'STOCK',
- write: false,
- target: 'es2020',
- logLevel: 'error'
-});
-const STOCK = bundled.outputFiles[0].text;
-const server = await serve(packageDir);
-
-async function runScenarios() {
- const { default: Shepherd } = await import('/dist/js/shepherd.mjs');
- const pageEl = document.getElementById('page');
- const run = async (floatingUIOptions, on) => {
- const target = document.createElement('div');
- target.className = 'target';
- target.style.left = '880px';
- target.style.top = '330px';
- pageEl.replaceChildren(target);
- const tour = new Shepherd.Tour();
- tour.addStep({
- text: 'hi',
- arrow: true,
- attachTo: { element: target, on },
- floatingUIOptions
- });
- await tour.start();
- const el = tour.getCurrentStep().el;
- const start = performance.now();
- while (!el.dataset.popperPlacement && performance.now() - start < 1500) {
- await new Promise(requestAnimationFrame);
- }
- const rect = el.getBoundingClientRect();
- const result = {
- placement: el.dataset.popperPlacement ?? null,
- x: rect.x,
- y: rect.y
- };
- tour.complete();
- return result;
- };
- const { platform, offset, flip, shift, hide, size, inline, autoPlacement } =
- window.STOCK;
- return {
- engine: await run({}, 'right'),
- stockPlatform: await run({ platform }, 'right'),
- stockPlatformAuto: await run({ platform }, 'auto'),
- shadowDomRecipe: await run(
- {
- platform: {
- ...platform,
- getOffsetParent: (element) => platform.getOffsetParent(element)
- }
- },
- 'right'
- ),
- stockMiddleware: await run(
- { middleware: [offset(12), flip(), shift(), hide(), size(), inline()] },
- 'top'
- ),
- stockAutoPlacement: await run(
- { middleware: [autoPlacement({ allowedPlacements: ['left', 'top'] })] },
- 'bottom'
- ),
- partialPlatform: await run(
- { platform: { getOffsetParent: platform.getOffsetParent } },
- 'left'
- )
- };
-}
-
-let failed = false;
-for (const name of ['chromium', 'firefox', 'webkit']) {
- const browser = await playwright[name].launch();
- const page = await browser.newPage({
- viewport: { width: 1000, height: 700 }
- });
- const errors = [];
- page.on('pageerror', (error) => errors.push(error.message));
- page.on('console', (message) => {
- if (message.type() === 'error') errors.push(message.text());
- });
- await page.goto(`${server.url}/page.html`);
- await page.addScriptTag({ content: STOCK });
- const out = await page.evaluate(runScenarios);
- const positioned = Object.values(out).every((result) => result.placement);
- failed ||= errors.length > 0 || !positioned;
- console.log(
- name,
- positioned ? 'all positioned' : 'NOT ALL POSITIONED',
- 'errors:',
- JSON.stringify([...new Set(errors)]).slice(0, 300)
- );
- console.log(' ', JSON.stringify(out));
- await browser.close();
-}
-await server.close();
-process.exitCode = failed ? 1 : 0;
diff --git a/shepherd.js/test/position-differential/dist-position.mjs b/shepherd.js/test/position-differential/dist-position.mjs
new file mode 100644
index 000000000..7851ced4b
--- /dev/null
+++ b/shepherd.js/test/position-differential/dist-position.mjs
@@ -0,0 +1,100 @@
+// The published build with each `positionOptions` key, in real browsers, so
+// property mangling cannot break what the source-level differential checks.
+// Run `pnpm build` first.
+import process from 'node:process';
+import * as playwright from 'playwright-core';
+import { packageDir, serve } from '../../scripts/scorecard/lib.mjs';
+
+const server = await serve(packageDir);
+
+async function runScenarios() {
+ const { default: Shepherd } = await import('/dist/js/shepherd.mjs');
+ const pageEl = document.getElementById('page');
+ const run = async (options, on, left = 440, top = 330) => {
+ const target = document.createElement('div');
+ target.className = 'target';
+ target.style.left = `${left}px`;
+ target.style.top = `${top}px`;
+ pageEl.replaceChildren(target);
+ const tour = new Shepherd.Tour();
+ tour.addStep({
+ text: 'hi',
+ arrow: true,
+ attachTo: { element: target, on },
+ ...options
+ });
+ await tour.start();
+ const el = tour.getCurrentStep().el;
+ const start = performance.now();
+ while (!el.dataset.popperPlacement && performance.now() - start < 1500) {
+ await new Promise(requestAnimationFrame);
+ }
+ const rect = el.getBoundingClientRect();
+ const result = {
+ placement: el.dataset.popperPlacement ?? null,
+ position: el.style.position,
+ x: Math.round(rect.x),
+ y: Math.round(rect.y),
+ bottom: Math.round(rect.bottom)
+ };
+ tour.complete();
+ return result;
+ };
+ const warnings = [];
+ const warn = console.warn;
+ console.warn = (...args) => warnings.push(args.join(' '));
+ const removed = await run(
+ { floatingUIOptions: { strategy: 'fixed' } },
+ 'bottom'
+ );
+ console.warn = warn;
+ return {
+ plain: await run({}, 'bottom'),
+ offset: await run({ positionOptions: { offset: 20 } }, 'bottom'),
+ fixed: await run({ positionOptions: { strategy: 'fixed' } }, 'bottom'),
+ atTop: await run({}, 'right', 440, 0),
+ padding: await run({ positionOptions: { padding: 40 } }, 'right', 440, 0),
+ flipped: await run({}, 'right', 880),
+ noFlip: await run({ positionOptions: { flip: false } }, 'right', 880),
+ removed,
+ warnings
+ };
+}
+
+const checks = {
+ 'offset moves the step 20px further': (r) => r.offset.y - r.plain.y === 20,
+ 'strategy fixed is written': (r) => r.fixed.position === 'fixed',
+ 'a step that does not fit on the right flips': (r) =>
+ r.flipped.placement === 'left',
+ 'flip: false keeps right': (r) => r.noFlip.placement === 'right',
+ 'padding keeps the step 40px from the edge': (r) =>
+ r.atTop.y < 39 && r.padding.y >= 39,
+ 'floatingUIOptions is ignored and names positionOptions': (r) =>
+ r.removed.position === 'absolute' &&
+ r.warnings.some((text) => text.includes('positionOptions'))
+};
+
+let failed = false;
+for (const name of ['chromium', 'firefox', 'webkit']) {
+ const browser = await playwright[name].launch();
+ const page = await browser.newPage({
+ viewport: { width: 1000, height: 700 }
+ });
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.goto(`${server.url}/page.html`);
+ const out = await page.evaluate(runScenarios);
+ const failures = Object.entries(checks)
+ .filter(([, check]) => !check(out))
+ .map(([label]) => label);
+ failed ||= errors.length > 0 || failures.length > 0;
+ console.log(
+ name,
+ failures.length ? `FAILED: ${failures.join('; ')}` : 'all checks pass',
+ errors.length ? `errors: ${errors.join('; ')}` : ''
+ );
+ if (failures.length) console.log(' ', JSON.stringify(out));
+ await browser.close();
+}
+await server.close();
+process.exitCode = failed ? 1 : 0;
diff --git a/shepherd.js/test/position-differential/fixtures.js b/shepherd.js/test/position-differential/fixtures.js
index 0babb9b37..d0f2f0db3 100644
--- a/shepherd.js/test/position-differential/fixtures.js
+++ b/shepherd.js/test/position-differential/fixtures.js
@@ -700,141 +700,38 @@ window.FIXTURES = {
}
};
-// Mirrors the baseline getFloatingUIOptions() using stock middleware.
-window.stockOptions = function (FUI, on, reference, arrowEl, strategy, user) {
+// What getPositionConfig() builds, in stock middleware.
+window.stockOptions = function (FUI, on, arrowEl, strategy, position) {
+ const { offset, padding, flip = true } = position;
const hasAuto = on.includes('auto');
const edge = on.includes('-start') || on.includes('-end');
const middleware = [];
+ if (offset) middleware.push(FUI.offset(offset));
if (hasAuto) {
middleware.push(
FUI.autoPlacement({
crossAxis: true,
- alignment: edge ? on.split('-').pop() : null
+ alignment: edge ? on.split('-').pop() : null,
+ padding
})
);
- } else {
- middleware.push(FUI.flip());
+ } else if (flip) {
+ middleware.push(FUI.flip({ padding }));
}
- middleware.push(FUI.shift({ limiter: FUI.limitShift(), crossAxis: true }));
- const options = { strategy };
- if (!hasAuto) options.placement = on;
- if (user.placement) options.placement = user.placement;
- if (user.platform) options.platform = user.platform;
- options.middleware = [...middleware, ...(user.middleware ?? [])];
- if (!options.middleware.some((m) => m && m.name === 'arrow')) {
- options.middleware.push(
- FUI.arrow({ element: arrowEl, padding: edge ? 4 : 0 })
- );
- }
- return options;
-};
-
-window.USER_CONFIGS = {
- none: () => ({}),
- offset: (F) => ({ middleware: [F.offset(12)] }),
- offsetCross: (F) => ({
- middleware: [F.offset({ mainAxis: 4, crossAxis: 8, alignmentAxis: 5 })]
- }),
- shiftPadding: (F) => ({ middleware: [F.shift({ padding: 24 })] }),
- hideRef: (F) => ({ middleware: [F.hide()] }),
- hideEscaped: (F) => ({ middleware: [F.hide({ strategy: 'escaped' })] }),
- flipFallback: (F) => ({
- middleware: [F.flip({ fallbackPlacements: ['left', 'right-start'] })]
- }),
- flipAxis: (F) => ({
- middleware: [
- F.flip({ fallbackAxisSideDirection: 'start', crossAxis: 'alignment' })
- ]
- }),
- autoAllowed: (F) => ({
- middleware: [F.autoPlacement({ allowedPlacements: ['top', 'left'] })]
- }),
- size: (F) => ({
- middleware: [
- F.size({
- apply({ availableWidth, availableHeight, middlewareData }) {
- middlewareData.sizeProbe = { availableWidth, availableHeight };
- }
- })
- ]
- }),
- inline: (F) => ({ middleware: [F.inline()] }),
- boundaryElement: (F, fx) => ({
- middleware: [
- F.flip({ boundary: fx.floating.parentElement }),
- F.shift({ boundary: [fx.floating.parentElement] })
- ]
- }),
- boundaryRect: (F) => ({
- middleware: [
- F.flip({ boundary: { x: 10, y: 10, width: 400, height: 300 } })
- ]
- }),
- rootDocument: (F) => ({
- middleware: [F.shift({ rootBoundary: 'document' })]
- }),
- rootLayout: (F) => ({
- middleware: [
- F.flip({ rootBoundary: 'layoutViewport' }),
- F.shift({ rootBoundary: 'layoutViewport' })
- ]
- }),
- rootRect: (F) => ({
- middleware: [
- F.shift({ rootBoundary: { x: 0, y: 0, width: 500, height: 500 } })
- ]
- }),
- altBoundary: (F) => ({ middleware: [F.flip({ altBoundary: true })] }),
- userArrow: (F, fx) => ({
- middleware: [F.arrow({ element: fx.arrow, padding: 6 }), F.offset(3)]
- }),
- falsyEntries: (F) => ({ middleware: [false, F.offset(9), null, undefined] }),
- platformSpread: (F) => ({ platform: { ...F.platform } }),
- platformRecipe: (F) => ({
- platform: {
- ...F.platform,
- getOffsetParent: (element) => F.platform.getOffsetParent(element)
- }
- }),
- platformAsync: (F) => ({
- platform: Object.fromEntries(
- Object.entries(F.platform).map(([name, method]) => [
- name,
- async function (...args) {
- return method.apply(this, args);
- }
- ])
- )
- })
+ middleware.push(
+ FUI.shift({ limiter: FUI.limitShift(), crossAxis: true, padding })
+ );
+ middleware.push(FUI.arrow({ element: arrowEl, padding: edge ? 4 : 0 }));
+ return { strategy, placement: hasAuto ? undefined : on, middleware };
};
-// Stock middleware only, through the engine's computePosition. Everything in middlewareData is compared.
-window.RAW_CONFIGS = {
- allReal: (F, on, fx) => [
- F.offset({ mainAxis: 8, crossAxis: 3, alignmentAxis: 5 }),
- on.startsWith('auto')
- ? F.autoPlacement({
- padding: 5,
- alignment: on.includes('-') ? on.split('-').pop() : undefined
- })
- : F.flip({ padding: 5, fallbackAxisSideDirection: 'start' }),
- F.shift({
- padding: 5,
- crossAxis: true,
- limiter: F.limitShift({ offset: 4 })
- }),
- F.size({ padding: 4, apply() {} }),
- F.arrow({ element: fx.arrow, padding: 6 }),
- F.hide(),
- F.hide({ strategy: 'escaped' })
- ],
- options: (F, on, fx) => [
- F.flip({ rootBoundary: 'document', padding: { top: 3, left: 9 } }),
- F.shift({ boundary: fx.floating.parentElement, crossAxis: true }),
- F.shift({
- rootBoundary: { x: 10, y: 10, width: 800, height: 600 },
- altBoundary: true
- }),
- F.hide({ elementContext: 'reference', rootBoundary: 'document' })
- ]
+// Each `positionOptions` a consumer can pass, other than `strategy`, which
+// every fixture runs both ways.
+window.POSITION_CONFIGS = {
+ none: {},
+ offset: { offset: 12 },
+ offsetCross: { offset: { mainAxis: 4, crossAxis: 8 } },
+ padding: { padding: 24 },
+ noFlip: { flip: false },
+ combined: { offset: 8, padding: 12, flip: false }
};
diff --git a/shepherd.js/test/position-differential/known-differences.json b/shepherd.js/test/position-differential/known-differences.json
index 94bd99724..1539c4710 100644
--- a/shepherd.js/test/position-differential/known-differences.json
+++ b/shepherd.js/test/position-differential/known-differences.json
@@ -1,735 +1,176 @@
{
"chromium standards": {
- "bodyNarrowerThanHtml/allReal": 12,
- "bodyNarrowerThanHtml/altBoundary": 6,
- "bodyNarrowerThanHtml/autoAllowed": 2,
- "bodyNarrowerThanHtml/boundaryRect": 8,
- "bodyNarrowerThanHtml/falsyEntries": 6,
- "bodyNarrowerThanHtml/flipAxis": 6,
- "bodyNarrowerThanHtml/flipFallback": 6,
- "bodyNarrowerThanHtml/hideEscaped": 12,
- "bodyNarrowerThanHtml/hideRef": 12,
- "bodyNarrowerThanHtml/inline": 6,
+ "bodyNarrowerThanHtml/combined": 8,
+ "bodyNarrowerThanHtml/noFlip": 8,
"bodyNarrowerThanHtml/none": 16,
"bodyNarrowerThanHtml/offset": 6,
"bodyNarrowerThanHtml/offsetCross": 6,
- "bodyNarrowerThanHtml/rootDocument": 6,
- "bodyNarrowerThanHtml/rootLayout": 6,
- "bodyNarrowerThanHtml/shiftPadding": 6,
- "bodyNarrowerThanHtml/size": 12,
- "bodyNarrowerThanHtml/userArrow": 6,
- "bodyOverflowOwnScroller/allReal": 12,
- "bodyOverflowOwnScroller/hideEscaped": 12,
- "bodyOverflowOwnScroller/hideRef": 12,
- "bodyOverflowOwnScroller/size": 12,
- "bodySlightlyNarrow/allReal": 12,
- "bodySlightlyNarrow/altBoundary": 2,
- "bodySlightlyNarrow/boundaryRect": 4,
- "bodySlightlyNarrow/falsyEntries": 2,
- "bodySlightlyNarrow/flipAxis": 2,
- "bodySlightlyNarrow/flipFallback": 2,
- "bodySlightlyNarrow/hideEscaped": 12,
- "bodySlightlyNarrow/hideRef": 12,
- "bodySlightlyNarrow/inline": 2,
+ "bodyNarrowerThanHtml/padding": 6,
+ "bodySlightlyNarrow/combined": 8,
+ "bodySlightlyNarrow/noFlip": 6,
"bodySlightlyNarrow/none": 4,
"bodySlightlyNarrow/offset": 2,
- "bodySlightlyNarrow/offsetCross": 2,
- "bodySlightlyNarrow/rootDocument": 2,
- "bodySlightlyNarrow/rootLayout": 2,
- "bodySlightlyNarrow/shiftPadding": 6,
- "bodySlightlyNarrow/size": 12,
- "bodySlightlyNarrow/userArrow": 2,
- "gutterBoth/boundaryElement": 4,
- "gutterBoth/options": 12,
- "gutterBoth/rootRect": 6,
- "gutterHiddenBoth/boundaryElement": 8,
- "gutterHiddenBoth/options": 12,
- "gutterHiddenBoth/rootRect": 6,
- "htmlMarginBorder/options": 12,
- "htmlMarginBorder/rootRect": 4,
- "htmlMarginOverflowParent/allReal": 6,
- "htmlMarginOverflowParent/boundaryElement": 4,
- "htmlMarginOverflowParent/hideEscaped": 6,
- "htmlMarginOverflowParent/hideRef": 6,
- "htmlMarginOverflowParent/options": 6,
- "htmlMarginOverflowParent/rootRect": 2,
- "htmlPositioned/options": 12,
- "htmlPositioned/rootRect": 4,
- "scaledBorderedContainer/allReal": 12,
- "scaledBorderedContainer/altBoundary": 4,
- "scaledBorderedContainer/autoAllowed": 4,
- "scaledBorderedContainer/boundaryElement": 12,
- "scaledBorderedContainer/boundaryRect": 2,
- "scaledBorderedContainer/falsyEntries": 4,
- "scaledBorderedContainer/flipAxis": 4,
- "scaledBorderedContainer/flipFallback": 4,
- "scaledBorderedContainer/hideEscaped": 12,
- "scaledBorderedContainer/hideRef": 12,
- "scaledBorderedContainer/inline": 4,
+ "bodySlightlyNarrow/offsetCross": 6,
+ "bodySlightlyNarrow/padding": 6,
+ "scaledBorderedContainer/combined": 4,
+ "scaledBorderedContainer/noFlip": 4,
"scaledBorderedContainer/none": 4,
"scaledBorderedContainer/offset": 4,
- "scaledBorderedContainer/offsetCross": 4,
- "scaledBorderedContainer/options": 12,
- "scaledBorderedContainer/rootDocument": 4,
- "scaledBorderedContainer/rootLayout": 4,
- "scaledBorderedContainer/rootRect": 8,
- "scaledBorderedContainer/shiftPadding": 4,
- "scaledBorderedContainer/size": 4,
- "scaledBorderedContainer/userArrow": 4,
- "scrollbarGutterBoth/boundaryElement": 8,
- "scrollbarGutterBoth/options": 12,
- "scrollbarGutterBoth/rootRect": 6,
- "staticFloatingInTd/altBoundary": 12,
- "staticFloatingInTd/autoAllowed": 12,
- "staticFloatingInTd/boundaryElement": 12,
- "staticFloatingInTd/boundaryRect": 12,
- "staticFloatingInTd/falsyEntries": 12,
- "staticFloatingInTd/flipAxis": 12,
- "staticFloatingInTd/flipFallback": 12,
- "staticFloatingInTd/hideEscaped": 12,
- "staticFloatingInTd/hideRef": 12,
- "staticFloatingInTd/inline": 12,
+ "scaledBorderedContainer/offsetCross": 2,
+ "scaledBorderedContainer/padding": 4,
+ "staticFloatingInTd/combined": 12,
+ "staticFloatingInTd/noFlip": 12,
"staticFloatingInTd/none": 30,
"staticFloatingInTd/offset": 12,
"staticFloatingInTd/offsetCross": 12,
- "staticFloatingInTd/platformAsync": 12,
- "staticFloatingInTd/platformRecipe": 12,
- "staticFloatingInTd/platformSpread": 12,
- "staticFloatingInTd/rootDocument": 12,
- "staticFloatingInTd/rootLayout": 12,
- "staticFloatingInTd/rootRect": 12,
- "staticFloatingInTd/shiftPadding": 12,
- "staticFloatingInTd/size": 12,
- "svgArrowNested/allReal": 12,
- "svgArrowNested/altBoundary": 12,
- "svgArrowNested/autoAllowed": 12,
- "svgArrowNested/boundaryElement": 12,
- "svgArrowNested/boundaryRect": 12,
- "svgArrowNested/falsyEntries": 12,
- "svgArrowNested/flipAxis": 12,
- "svgArrowNested/flipFallback": 12,
- "svgArrowNested/hideEscaped": 12,
- "svgArrowNested/hideRef": 12,
- "svgArrowNested/inline": 12,
+ "staticFloatingInTd/padding": 12,
+ "svgArrowNested/combined": 12,
+ "svgArrowNested/noFlip": 12,
"svgArrowNested/none": 30,
"svgArrowNested/offset": 12,
"svgArrowNested/offsetCross": 12,
- "svgArrowNested/platformAsync": 12,
- "svgArrowNested/platformRecipe": 12,
- "svgArrowNested/platformSpread": 12,
- "svgArrowNested/rootDocument": 12,
- "svgArrowNested/rootLayout": 12,
- "svgArrowNested/rootRect": 12,
- "svgArrowNested/shiftPadding": 12,
- "svgArrowNested/size": 12,
- "svgArrowNested/userArrow": 12
+ "svgArrowNested/padding": 12
},
"chromium quirks": {
- "gutterBoth/options": 12,
- "gutterBoth/rootLayout": 2,
- "gutterBoth/rootRect": 6,
- "gutterHidden/allReal": 12,
- "gutterHidden/altBoundary": 6,
- "gutterHidden/autoAllowed": 2,
- "gutterHidden/boundaryElement": 6,
- "gutterHidden/boundaryRect": 6,
- "gutterHidden/falsyEntries": 6,
- "gutterHidden/flipAxis": 6,
- "gutterHidden/flipFallback": 6,
- "gutterHidden/hideEscaped": 12,
- "gutterHidden/hideRef": 12,
- "gutterHidden/inline": 6,
+ "gutterHidden/combined": 8,
+ "gutterHidden/noFlip": 8,
"gutterHidden/none": 16,
"gutterHidden/offset": 6,
"gutterHidden/offsetCross": 6,
- "gutterHidden/options": 8,
- "gutterHidden/rootDocument": 6,
- "gutterHidden/rootLayout": 6,
- "gutterHidden/shiftPadding": 6,
- "gutterHidden/size": 12,
- "gutterHidden/userArrow": 6,
- "gutterHiddenBoth/options": 12,
- "gutterHiddenBoth/rootLayout": 6,
- "gutterHiddenBoth/rootRect": 6,
- "gutterStable/allReal": 12,
- "gutterStable/altBoundary": 2,
- "gutterStable/boundaryElement": 2,
- "gutterStable/boundaryRect": 6,
- "gutterStable/falsyEntries": 2,
- "gutterStable/flipAxis": 2,
- "gutterStable/flipFallback": 2,
- "gutterStable/hideEscaped": 12,
- "gutterStable/hideRef": 12,
- "gutterStable/inline": 2,
+ "gutterHidden/padding": 6,
+ "gutterStable/combined": 8,
+ "gutterStable/noFlip": 6,
"gutterStable/none": 4,
"gutterStable/offset": 2,
- "gutterStable/offsetCross": 2,
- "gutterStable/options": 6,
- "gutterStable/rootDocument": 2,
- "gutterStable/rootLayout": 6,
- "gutterStable/shiftPadding": 6,
- "gutterStable/size": 12,
- "gutterStable/userArrow": 2,
- "htmlMarginBorder/options": 12,
- "htmlMarginBorder/rootRect": 4,
- "htmlMarginOverflowParent/allReal": 6,
- "htmlMarginOverflowParent/boundaryElement": 4,
- "htmlMarginOverflowParent/hideEscaped": 6,
- "htmlMarginOverflowParent/hideRef": 6,
- "htmlMarginOverflowParent/options": 6,
- "htmlMarginOverflowParent/rootRect": 2,
- "htmlPositioned/options": 12,
- "htmlPositioned/rootRect": 4,
- "rtlOverflowX/boundaryElement": 6,
- "rtlOverflowX/flipFallback": 2,
- "rtlOverflowX/options": 12,
- "rtlOverflowX/rootRect": 6,
- "scaledBorderedContainer/allReal": 12,
- "scaledBorderedContainer/altBoundary": 4,
- "scaledBorderedContainer/autoAllowed": 4,
- "scaledBorderedContainer/boundaryElement": 12,
- "scaledBorderedContainer/boundaryRect": 2,
- "scaledBorderedContainer/falsyEntries": 4,
- "scaledBorderedContainer/flipAxis": 4,
- "scaledBorderedContainer/flipFallback": 4,
- "scaledBorderedContainer/hideEscaped": 12,
- "scaledBorderedContainer/hideRef": 12,
- "scaledBorderedContainer/inline": 4,
+ "gutterStable/offsetCross": 6,
+ "gutterStable/padding": 6,
+ "scaledBorderedContainer/combined": 4,
+ "scaledBorderedContainer/noFlip": 4,
"scaledBorderedContainer/none": 4,
"scaledBorderedContainer/offset": 4,
- "scaledBorderedContainer/offsetCross": 4,
- "scaledBorderedContainer/options": 12,
- "scaledBorderedContainer/rootDocument": 4,
- "scaledBorderedContainer/rootLayout": 4,
- "scaledBorderedContainer/rootRect": 8,
- "scaledBorderedContainer/shiftPadding": 4,
- "scaledBorderedContainer/size": 4,
- "scaledBorderedContainer/userArrow": 4,
- "scrollbarGutter/allReal": 12,
- "scrollbarGutter/altBoundary": 6,
- "scrollbarGutter/autoAllowed": 2,
- "scrollbarGutter/boundaryElement": 6,
- "scrollbarGutter/boundaryRect": 6,
- "scrollbarGutter/falsyEntries": 6,
- "scrollbarGutter/flipAxis": 6,
- "scrollbarGutter/flipFallback": 6,
- "scrollbarGutter/hideEscaped": 12,
- "scrollbarGutter/hideRef": 12,
- "scrollbarGutter/inline": 6,
+ "scaledBorderedContainer/offsetCross": 2,
+ "scaledBorderedContainer/padding": 4,
+ "scrollbarGutter/combined": 8,
+ "scrollbarGutter/noFlip": 8,
"scrollbarGutter/none": 16,
"scrollbarGutter/offset": 6,
"scrollbarGutter/offsetCross": 6,
- "scrollbarGutter/options": 8,
- "scrollbarGutter/rootDocument": 6,
- "scrollbarGutter/rootLayout": 6,
- "scrollbarGutter/shiftPadding": 6,
- "scrollbarGutter/size": 12,
- "scrollbarGutter/userArrow": 6,
- "scrollbarGutterBoth/options": 12,
- "scrollbarGutterBoth/rootLayout": 6,
- "scrollbarGutterBoth/rootRect": 6,
- "scrolledXY/boundaryElement": 8,
- "scrolledXY/options": 12,
- "scrolledXY/rootRect": 6,
- "staticFloatingInTd/altBoundary": 12,
- "staticFloatingInTd/autoAllowed": 12,
- "staticFloatingInTd/boundaryElement": 12,
- "staticFloatingInTd/boundaryRect": 12,
- "staticFloatingInTd/falsyEntries": 12,
- "staticFloatingInTd/flipAxis": 12,
- "staticFloatingInTd/flipFallback": 12,
- "staticFloatingInTd/hideEscaped": 12,
- "staticFloatingInTd/hideRef": 12,
- "staticFloatingInTd/inline": 12,
+ "scrollbarGutter/padding": 6,
+ "staticFloatingInTd/combined": 12,
+ "staticFloatingInTd/noFlip": 12,
"staticFloatingInTd/none": 30,
"staticFloatingInTd/offset": 12,
"staticFloatingInTd/offsetCross": 12,
- "staticFloatingInTd/platformAsync": 12,
- "staticFloatingInTd/platformRecipe": 12,
- "staticFloatingInTd/platformSpread": 12,
- "staticFloatingInTd/rootDocument": 12,
- "staticFloatingInTd/rootLayout": 12,
- "staticFloatingInTd/rootRect": 12,
- "staticFloatingInTd/shiftPadding": 12,
- "staticFloatingInTd/size": 12,
- "svgArrowNested/allReal": 12,
- "svgArrowNested/altBoundary": 12,
- "svgArrowNested/autoAllowed": 12,
- "svgArrowNested/boundaryElement": 12,
- "svgArrowNested/boundaryRect": 12,
- "svgArrowNested/falsyEntries": 12,
- "svgArrowNested/flipAxis": 12,
- "svgArrowNested/flipFallback": 12,
- "svgArrowNested/hideEscaped": 12,
- "svgArrowNested/hideRef": 12,
- "svgArrowNested/inline": 12,
+ "staticFloatingInTd/padding": 12,
+ "svgArrowNested/combined": 12,
+ "svgArrowNested/noFlip": 12,
"svgArrowNested/none": 30,
"svgArrowNested/offset": 12,
"svgArrowNested/offsetCross": 12,
- "svgArrowNested/platformAsync": 12,
- "svgArrowNested/platformRecipe": 12,
- "svgArrowNested/platformSpread": 12,
- "svgArrowNested/rootDocument": 12,
- "svgArrowNested/rootLayout": 12,
- "svgArrowNested/rootRect": 12,
- "svgArrowNested/shiftPadding": 12,
- "svgArrowNested/size": 12,
- "svgArrowNested/userArrow": 12
+ "svgArrowNested/padding": 12
},
"firefox standards": {
- "bodyNarrowerThanHtml/allReal": 12,
- "bodyNarrowerThanHtml/altBoundary": 6,
- "bodyNarrowerThanHtml/autoAllowed": 2,
- "bodyNarrowerThanHtml/boundaryRect": 8,
- "bodyNarrowerThanHtml/falsyEntries": 6,
- "bodyNarrowerThanHtml/flipAxis": 6,
- "bodyNarrowerThanHtml/flipFallback": 6,
- "bodyNarrowerThanHtml/hideEscaped": 12,
- "bodyNarrowerThanHtml/hideRef": 12,
- "bodyNarrowerThanHtml/inline": 6,
+ "bodyNarrowerThanHtml/combined": 8,
+ "bodyNarrowerThanHtml/noFlip": 8,
"bodyNarrowerThanHtml/none": 16,
"bodyNarrowerThanHtml/offset": 6,
"bodyNarrowerThanHtml/offsetCross": 6,
- "bodyNarrowerThanHtml/rootDocument": 6,
- "bodyNarrowerThanHtml/rootLayout": 6,
- "bodyNarrowerThanHtml/shiftPadding": 6,
- "bodyNarrowerThanHtml/size": 12,
- "bodyNarrowerThanHtml/userArrow": 6,
- "bodySlightlyNarrow/allReal": 12,
- "bodySlightlyNarrow/altBoundary": 2,
- "bodySlightlyNarrow/boundaryRect": 4,
- "bodySlightlyNarrow/falsyEntries": 2,
- "bodySlightlyNarrow/flipAxis": 2,
- "bodySlightlyNarrow/flipFallback": 2,
- "bodySlightlyNarrow/hideEscaped": 12,
- "bodySlightlyNarrow/hideRef": 12,
- "bodySlightlyNarrow/inline": 2,
+ "bodyNarrowerThanHtml/padding": 6,
+ "bodySlightlyNarrow/combined": 8,
+ "bodySlightlyNarrow/noFlip": 6,
"bodySlightlyNarrow/none": 4,
"bodySlightlyNarrow/offset": 2,
- "bodySlightlyNarrow/offsetCross": 2,
- "bodySlightlyNarrow/rootDocument": 2,
- "bodySlightlyNarrow/rootLayout": 2,
- "bodySlightlyNarrow/shiftPadding": 6,
- "bodySlightlyNarrow/size": 12,
- "bodySlightlyNarrow/userArrow": 2,
- "htmlMarginBorder/options": 12,
- "htmlMarginBorder/rootRect": 4,
- "htmlMarginOverflowParent/allReal": 6,
- "htmlMarginOverflowParent/boundaryElement": 4,
- "htmlMarginOverflowParent/hideEscaped": 6,
- "htmlMarginOverflowParent/hideRef": 6,
- "htmlMarginOverflowParent/options": 6,
- "htmlMarginOverflowParent/rootRect": 2,
- "htmlPositioned/options": 12,
- "htmlPositioned/rootRect": 4,
- "iframeBothInside/rootLayout": 10,
- "scaledBorderedContainer/allReal": 12,
- "scaledBorderedContainer/altBoundary": 4,
- "scaledBorderedContainer/autoAllowed": 4,
- "scaledBorderedContainer/boundaryElement": 12,
- "scaledBorderedContainer/boundaryRect": 2,
- "scaledBorderedContainer/falsyEntries": 4,
- "scaledBorderedContainer/flipAxis": 4,
- "scaledBorderedContainer/flipFallback": 4,
- "scaledBorderedContainer/hideEscaped": 12,
- "scaledBorderedContainer/hideRef": 12,
- "scaledBorderedContainer/inline": 4,
+ "bodySlightlyNarrow/offsetCross": 6,
+ "bodySlightlyNarrow/padding": 6,
+ "scaledBorderedContainer/combined": 4,
+ "scaledBorderedContainer/noFlip": 4,
"scaledBorderedContainer/none": 4,
"scaledBorderedContainer/offset": 4,
- "scaledBorderedContainer/offsetCross": 4,
- "scaledBorderedContainer/options": 12,
- "scaledBorderedContainer/rootDocument": 4,
- "scaledBorderedContainer/rootLayout": 4,
- "scaledBorderedContainer/rootRect": 8,
- "scaledBorderedContainer/shiftPadding": 4,
- "scaledBorderedContainer/size": 4,
- "scaledBorderedContainer/userArrow": 4,
- "staticFloatingInTd/altBoundary": 12,
- "staticFloatingInTd/autoAllowed": 12,
- "staticFloatingInTd/boundaryElement": 12,
- "staticFloatingInTd/boundaryRect": 12,
- "staticFloatingInTd/falsyEntries": 12,
- "staticFloatingInTd/flipAxis": 12,
- "staticFloatingInTd/flipFallback": 12,
- "staticFloatingInTd/hideEscaped": 12,
- "staticFloatingInTd/hideRef": 12,
- "staticFloatingInTd/inline": 12,
+ "scaledBorderedContainer/offsetCross": 2,
+ "scaledBorderedContainer/padding": 4,
+ "staticFloatingInTd/combined": 12,
+ "staticFloatingInTd/noFlip": 12,
"staticFloatingInTd/none": 30,
"staticFloatingInTd/offset": 12,
"staticFloatingInTd/offsetCross": 12,
- "staticFloatingInTd/platformAsync": 12,
- "staticFloatingInTd/platformRecipe": 12,
- "staticFloatingInTd/platformSpread": 12,
- "staticFloatingInTd/rootDocument": 12,
- "staticFloatingInTd/rootLayout": 12,
- "staticFloatingInTd/rootRect": 12,
- "staticFloatingInTd/shiftPadding": 12,
- "staticFloatingInTd/size": 12,
- "svgArrowNested/allReal": 12,
- "svgArrowNested/altBoundary": 12,
- "svgArrowNested/autoAllowed": 12,
- "svgArrowNested/boundaryElement": 12,
- "svgArrowNested/boundaryRect": 12,
- "svgArrowNested/falsyEntries": 12,
- "svgArrowNested/flipAxis": 12,
- "svgArrowNested/flipFallback": 12,
- "svgArrowNested/hideEscaped": 12,
- "svgArrowNested/hideRef": 12,
- "svgArrowNested/inline": 12,
+ "staticFloatingInTd/padding": 12,
+ "svgArrowNested/combined": 12,
+ "svgArrowNested/noFlip": 12,
"svgArrowNested/none": 30,
"svgArrowNested/offset": 12,
"svgArrowNested/offsetCross": 12,
- "svgArrowNested/platformAsync": 12,
- "svgArrowNested/platformRecipe": 12,
- "svgArrowNested/platformSpread": 12,
- "svgArrowNested/rootDocument": 12,
- "svgArrowNested/rootLayout": 12,
- "svgArrowNested/rootRect": 12,
- "svgArrowNested/shiftPadding": 12,
- "svgArrowNested/size": 12,
- "svgArrowNested/userArrow": 12
+ "svgArrowNested/padding": 12
},
"firefox quirks": {
- "bodyAsReference/rootLayout": 8,
- "bodyMargin/rootLayout": 6,
- "bodyNarrow/rootLayout": 8,
- "bodyPositioned/rootLayout": 8,
- "bodySlightlyNarrow/rootLayout": 8,
- "cornerBottomRight/rootLayout": 6,
- "cornerTopLeft/rootLayout": 8,
- "detachedReference/rootLayout": 6,
- "dialogModalFloating/rootLayout": 6,
- "dialogNonModal/rootLayout": 6,
- "fixedFloatingInModalInTransform/rootLayout": 5,
- "fixedInBackdrop/rootLayout": 5,
- "fixedInContainPaint/rootLayout": 5,
- "fixedInFilter/rootLayout": 5,
- "fixedInPerspective/rootLayout": 5,
- "fixedInWillChange/rootLayout": 5,
- "fixedTarget/rootLayout": 6,
- "floatingInModalDialog/rootLayout": 11,
- "gutterBoth/rootLayout": 8,
- "gutterHidden/rootLayout": 10,
- "gutterHiddenBoth/rootLayout": 10,
- "gutterStable/rootLayout": 8,
- "hiddenFloating/rootLayout": 8,
- "hiddenReference/rootLayout": 6,
- "htmlMarginBorder/options": 12,
- "htmlMarginBorder/rootLayout": 10,
- "htmlMarginBorder/rootRect": 4,
- "htmlMarginOverflowParent/allReal": 6,
- "htmlMarginOverflowParent/boundaryElement": 4,
- "htmlMarginOverflowParent/hideEscaped": 6,
- "htmlMarginOverflowParent/hideRef": 6,
- "htmlMarginOverflowParent/options": 6,
- "htmlMarginOverflowParent/rootRect": 2,
- "htmlMarginTransformed/rootLayout": 10,
- "htmlOverflowHidden/rootLayout": 10,
- "htmlPositioned/options": 12,
- "htmlPositioned/rootLayout": 10,
- "htmlPositioned/rootRect": 4,
- "hugeReference/rootLayout": 10,
- "iframeBothInside/rootLayout": 10,
- "iframeNested/rootLayout": 10,
- "iframeReference/rootLayout": 10,
- "iframeScaled/rootLayout": 10,
- "iframeScrolledReference/rootLayout": 10,
- "overflowParent/rootLayout": 10,
- "overflowParentBoth/rootLayout": 10,
- "plain/rootLayout": 6,
- "popoverFloating/rootLayout": 6,
- "popoverInTransform/rootLayout": 10,
- "positionedTd/rootLayout": 4,
- "rtl/rootLayout": 6,
- "rtlFloatingOnly/rootLayout": 6,
- "rtlOverflowX/boundaryElement": 6,
- "rtlOverflowX/flipFallback": 2,
- "rtlOverflowX/options": 12,
- "rtlOverflowX/rootLayout": 6,
- "rtlOverflowX/rootRect": 6,
- "scaleProperty/rootLayout": 10,
- "scaledBorderedContainer/allReal": 12,
- "scaledBorderedContainer/altBoundary": 4,
- "scaledBorderedContainer/autoAllowed": 4,
- "scaledBorderedContainer/boundaryElement": 12,
- "scaledBorderedContainer/boundaryRect": 2,
- "scaledBorderedContainer/falsyEntries": 4,
- "scaledBorderedContainer/flipAxis": 4,
- "scaledBorderedContainer/flipFallback": 4,
- "scaledBorderedContainer/hideEscaped": 12,
- "scaledBorderedContainer/hideRef": 12,
- "scaledBorderedContainer/inline": 4,
+ "scaledBorderedContainer/combined": 4,
+ "scaledBorderedContainer/noFlip": 4,
"scaledBorderedContainer/none": 4,
"scaledBorderedContainer/offset": 4,
- "scaledBorderedContainer/offsetCross": 4,
- "scaledBorderedContainer/options": 12,
- "scaledBorderedContainer/rootDocument": 4,
- "scaledBorderedContainer/rootLayout": 10,
- "scaledBorderedContainer/rootRect": 8,
- "scaledBorderedContainer/shiftPadding": 4,
- "scaledBorderedContainer/size": 4,
- "scaledBorderedContainer/userArrow": 4,
- "scaledContainer/rootLayout": 8,
- "scaledNonUniformBoth/rootLayout": 10,
- "scrollbarGutter/rootLayout": 10,
- "scrollbarGutterBoth/rootLayout": 10,
- "scrollbars/rootLayout": 8,
- "scrolled/rootLayout": 6,
- "scrolledNearEdge/rootLayout": 10,
- "scrolledXY/boundaryElement": 8,
- "scrolledXY/options": 12,
- "scrolledXY/rootLayout": 6,
- "scrolledXY/rootRect": 6,
- "shadowFloating/rootLayout": 5,
- "shadowReference/rootLayout": 10,
- "slotted/rootLayout": 11,
- "staticFloatingInBody/rootLayout": 6,
- "staticFloatingInTd/altBoundary": 12,
- "staticFloatingInTd/autoAllowed": 12,
- "staticFloatingInTd/boundaryElement": 12,
- "staticFloatingInTd/boundaryRect": 12,
- "staticFloatingInTd/falsyEntries": 12,
- "staticFloatingInTd/flipAxis": 12,
- "staticFloatingInTd/flipFallback": 12,
- "staticFloatingInTd/hideEscaped": 12,
- "staticFloatingInTd/hideRef": 12,
- "staticFloatingInTd/inline": 12,
+ "scaledBorderedContainer/offsetCross": 2,
+ "scaledBorderedContainer/padding": 4,
+ "staticFloatingInTd/combined": 12,
+ "staticFloatingInTd/noFlip": 12,
"staticFloatingInTd/none": 30,
"staticFloatingInTd/offset": 12,
"staticFloatingInTd/offsetCross": 12,
- "staticFloatingInTd/platformAsync": 12,
- "staticFloatingInTd/platformRecipe": 12,
- "staticFloatingInTd/platformSpread": 12,
- "staticFloatingInTd/rootDocument": 12,
- "staticFloatingInTd/rootLayout": 12,
- "staticFloatingInTd/rootRect": 12,
- "staticFloatingInTd/shiftPadding": 12,
- "staticFloatingInTd/size": 12,
- "staticTd/rootLayout": 4,
- "svgArrow/rootLayout": 6,
- "svgArrowNested/allReal": 12,
- "svgArrowNested/altBoundary": 12,
- "svgArrowNested/autoAllowed": 12,
- "svgArrowNested/boundaryElement": 12,
- "svgArrowNested/boundaryRect": 12,
- "svgArrowNested/falsyEntries": 12,
- "svgArrowNested/flipAxis": 12,
- "svgArrowNested/flipFallback": 12,
- "svgArrowNested/hideEscaped": 12,
- "svgArrowNested/hideRef": 12,
- "svgArrowNested/inline": 12,
+ "staticFloatingInTd/padding": 12,
+ "svgArrowNested/combined": 12,
+ "svgArrowNested/noFlip": 12,
"svgArrowNested/none": 30,
"svgArrowNested/offset": 12,
"svgArrowNested/offsetCross": 12,
- "svgArrowNested/platformAsync": 12,
- "svgArrowNested/platformRecipe": 12,
- "svgArrowNested/platformSpread": 12,
- "svgArrowNested/rootDocument": 12,
- "svgArrowNested/rootLayout": 12,
- "svgArrowNested/rootRect": 12,
- "svgArrowNested/shiftPadding": 12,
- "svgArrowNested/size": 12,
- "svgArrowNested/userArrow": 12,
- "svgReference/rootLayout": 10,
- "tinyReference/rootLayout": 10,
- "transformedContainer/rootLayout": 6,
- "zeroSizeReference/rootLayout": 10,
- "zoomedContainer/rootLayout": 10
+ "svgArrowNested/padding": 12
},
"webkit standards": {
- "bodyNarrowerThanHtml/allReal": 12,
- "bodyNarrowerThanHtml/altBoundary": 6,
- "bodyNarrowerThanHtml/autoAllowed": 2,
- "bodyNarrowerThanHtml/boundaryRect": 8,
- "bodyNarrowerThanHtml/falsyEntries": 6,
- "bodyNarrowerThanHtml/flipAxis": 6,
- "bodyNarrowerThanHtml/flipFallback": 6,
- "bodyNarrowerThanHtml/hideEscaped": 12,
- "bodyNarrowerThanHtml/hideRef": 12,
- "bodyNarrowerThanHtml/inline": 6,
+ "bodyNarrowerThanHtml/combined": 8,
+ "bodyNarrowerThanHtml/noFlip": 8,
"bodyNarrowerThanHtml/none": 16,
"bodyNarrowerThanHtml/offset": 6,
"bodyNarrowerThanHtml/offsetCross": 6,
- "bodyNarrowerThanHtml/rootDocument": 6,
- "bodyNarrowerThanHtml/rootLayout": 6,
- "bodyNarrowerThanHtml/shiftPadding": 6,
- "bodyNarrowerThanHtml/size": 12,
- "bodyNarrowerThanHtml/userArrow": 6,
- "bodySlightlyNarrow/allReal": 12,
- "bodySlightlyNarrow/altBoundary": 2,
- "bodySlightlyNarrow/boundaryRect": 4,
- "bodySlightlyNarrow/falsyEntries": 2,
- "bodySlightlyNarrow/flipAxis": 2,
- "bodySlightlyNarrow/flipFallback": 2,
- "bodySlightlyNarrow/hideEscaped": 12,
- "bodySlightlyNarrow/hideRef": 12,
- "bodySlightlyNarrow/inline": 2,
+ "bodyNarrowerThanHtml/padding": 6,
+ "bodySlightlyNarrow/combined": 8,
+ "bodySlightlyNarrow/noFlip": 6,
"bodySlightlyNarrow/none": 4,
"bodySlightlyNarrow/offset": 2,
- "bodySlightlyNarrow/offsetCross": 2,
- "bodySlightlyNarrow/rootDocument": 2,
- "bodySlightlyNarrow/rootLayout": 2,
- "bodySlightlyNarrow/shiftPadding": 6,
- "bodySlightlyNarrow/size": 12,
- "bodySlightlyNarrow/userArrow": 2,
- "htmlMarginBorder/options": 12,
- "htmlMarginBorder/rootRect": 4,
- "htmlMarginOverflowParent/allReal": 6,
- "htmlMarginOverflowParent/boundaryElement": 4,
- "htmlMarginOverflowParent/hideEscaped": 6,
- "htmlMarginOverflowParent/hideRef": 6,
- "htmlMarginOverflowParent/options": 6,
- "htmlMarginOverflowParent/rootRect": 2,
- "htmlPositioned/options": 12,
- "htmlPositioned/rootRect": 4,
- "scaledBorderedContainer/allReal": 12,
- "scaledBorderedContainer/altBoundary": 4,
- "scaledBorderedContainer/autoAllowed": 4,
- "scaledBorderedContainer/boundaryElement": 12,
- "scaledBorderedContainer/boundaryRect": 2,
- "scaledBorderedContainer/falsyEntries": 4,
- "scaledBorderedContainer/flipAxis": 4,
- "scaledBorderedContainer/flipFallback": 4,
- "scaledBorderedContainer/hideEscaped": 12,
- "scaledBorderedContainer/hideRef": 12,
- "scaledBorderedContainer/inline": 4,
+ "bodySlightlyNarrow/offsetCross": 6,
+ "bodySlightlyNarrow/padding": 6,
+ "scaledBorderedContainer/combined": 4,
+ "scaledBorderedContainer/noFlip": 4,
"scaledBorderedContainer/none": 4,
"scaledBorderedContainer/offset": 4,
- "scaledBorderedContainer/offsetCross": 4,
- "scaledBorderedContainer/options": 12,
- "scaledBorderedContainer/rootDocument": 4,
- "scaledBorderedContainer/rootLayout": 4,
- "scaledBorderedContainer/rootRect": 8,
- "scaledBorderedContainer/shiftPadding": 4,
- "scaledBorderedContainer/size": 4,
- "scaledBorderedContainer/userArrow": 4,
- "staticFloatingInTd/altBoundary": 12,
- "staticFloatingInTd/autoAllowed": 12,
- "staticFloatingInTd/boundaryElement": 12,
- "staticFloatingInTd/boundaryRect": 12,
- "staticFloatingInTd/falsyEntries": 12,
- "staticFloatingInTd/flipAxis": 12,
- "staticFloatingInTd/flipFallback": 12,
- "staticFloatingInTd/hideEscaped": 12,
- "staticFloatingInTd/hideRef": 12,
- "staticFloatingInTd/inline": 12,
+ "scaledBorderedContainer/offsetCross": 2,
+ "scaledBorderedContainer/padding": 4,
+ "staticFloatingInTd/combined": 12,
+ "staticFloatingInTd/noFlip": 12,
"staticFloatingInTd/none": 30,
"staticFloatingInTd/offset": 12,
"staticFloatingInTd/offsetCross": 12,
- "staticFloatingInTd/platformAsync": 12,
- "staticFloatingInTd/platformRecipe": 12,
- "staticFloatingInTd/platformSpread": 12,
- "staticFloatingInTd/rootDocument": 12,
- "staticFloatingInTd/rootLayout": 12,
- "staticFloatingInTd/rootRect": 12,
- "staticFloatingInTd/shiftPadding": 12,
- "staticFloatingInTd/size": 12,
- "svgArrowNested/allReal": 12,
- "svgArrowNested/altBoundary": 12,
- "svgArrowNested/autoAllowed": 12,
- "svgArrowNested/boundaryElement": 12,
- "svgArrowNested/boundaryRect": 12,
- "svgArrowNested/falsyEntries": 12,
- "svgArrowNested/flipAxis": 12,
- "svgArrowNested/flipFallback": 12,
- "svgArrowNested/hideEscaped": 12,
- "svgArrowNested/hideRef": 12,
- "svgArrowNested/inline": 12,
+ "staticFloatingInTd/padding": 12,
+ "svgArrowNested/combined": 12,
+ "svgArrowNested/noFlip": 12,
"svgArrowNested/none": 30,
"svgArrowNested/offset": 12,
"svgArrowNested/offsetCross": 12,
- "svgArrowNested/platformAsync": 12,
- "svgArrowNested/platformRecipe": 12,
- "svgArrowNested/platformSpread": 12,
- "svgArrowNested/rootDocument": 12,
- "svgArrowNested/rootLayout": 12,
- "svgArrowNested/rootRect": 12,
- "svgArrowNested/shiftPadding": 12,
- "svgArrowNested/size": 12,
- "svgArrowNested/userArrow": 12
+ "svgArrowNested/padding": 12
},
"webkit quirks": {
- "htmlMarginBorder/options": 12,
- "htmlMarginBorder/rootRect": 4,
- "htmlMarginOverflowParent/allReal": 6,
- "htmlMarginOverflowParent/boundaryElement": 4,
- "htmlMarginOverflowParent/hideEscaped": 6,
- "htmlMarginOverflowParent/hideRef": 6,
- "htmlMarginOverflowParent/options": 6,
- "htmlMarginOverflowParent/rootRect": 2,
- "htmlPositioned/options": 12,
- "htmlPositioned/rootRect": 4,
- "rtlOverflowX/boundaryElement": 6,
- "rtlOverflowX/flipFallback": 2,
- "rtlOverflowX/options": 12,
- "rtlOverflowX/rootRect": 6,
- "scaledBorderedContainer/allReal": 12,
- "scaledBorderedContainer/altBoundary": 4,
- "scaledBorderedContainer/autoAllowed": 4,
- "scaledBorderedContainer/boundaryElement": 12,
- "scaledBorderedContainer/boundaryRect": 2,
- "scaledBorderedContainer/falsyEntries": 4,
- "scaledBorderedContainer/flipAxis": 4,
- "scaledBorderedContainer/flipFallback": 4,
- "scaledBorderedContainer/hideEscaped": 12,
- "scaledBorderedContainer/hideRef": 12,
- "scaledBorderedContainer/inline": 4,
+ "scaledBorderedContainer/combined": 4,
+ "scaledBorderedContainer/noFlip": 4,
"scaledBorderedContainer/none": 4,
"scaledBorderedContainer/offset": 4,
- "scaledBorderedContainer/offsetCross": 4,
- "scaledBorderedContainer/options": 12,
- "scaledBorderedContainer/rootDocument": 4,
- "scaledBorderedContainer/rootLayout": 4,
- "scaledBorderedContainer/rootRect": 8,
- "scaledBorderedContainer/shiftPadding": 4,
- "scaledBorderedContainer/size": 4,
- "scaledBorderedContainer/userArrow": 4,
- "scrolledXY/boundaryElement": 8,
- "scrolledXY/options": 12,
- "scrolledXY/rootRect": 6,
- "staticFloatingInTd/altBoundary": 12,
- "staticFloatingInTd/autoAllowed": 12,
- "staticFloatingInTd/boundaryElement": 12,
- "staticFloatingInTd/boundaryRect": 12,
- "staticFloatingInTd/falsyEntries": 12,
- "staticFloatingInTd/flipAxis": 12,
- "staticFloatingInTd/flipFallback": 12,
- "staticFloatingInTd/hideEscaped": 12,
- "staticFloatingInTd/hideRef": 12,
- "staticFloatingInTd/inline": 12,
+ "scaledBorderedContainer/offsetCross": 2,
+ "scaledBorderedContainer/padding": 4,
+ "staticFloatingInTd/combined": 12,
+ "staticFloatingInTd/noFlip": 12,
"staticFloatingInTd/none": 30,
"staticFloatingInTd/offset": 12,
"staticFloatingInTd/offsetCross": 12,
- "staticFloatingInTd/platformAsync": 12,
- "staticFloatingInTd/platformRecipe": 12,
- "staticFloatingInTd/platformSpread": 12,
- "staticFloatingInTd/rootDocument": 12,
- "staticFloatingInTd/rootLayout": 12,
- "staticFloatingInTd/rootRect": 12,
- "staticFloatingInTd/shiftPadding": 12,
- "staticFloatingInTd/size": 12,
- "svgArrowNested/allReal": 12,
- "svgArrowNested/altBoundary": 12,
- "svgArrowNested/autoAllowed": 12,
- "svgArrowNested/boundaryElement": 12,
- "svgArrowNested/boundaryRect": 12,
- "svgArrowNested/falsyEntries": 12,
- "svgArrowNested/flipAxis": 12,
- "svgArrowNested/flipFallback": 12,
- "svgArrowNested/hideEscaped": 12,
- "svgArrowNested/hideRef": 12,
- "svgArrowNested/inline": 12,
+ "staticFloatingInTd/padding": 12,
+ "svgArrowNested/combined": 12,
+ "svgArrowNested/noFlip": 12,
"svgArrowNested/none": 30,
"svgArrowNested/offset": 12,
"svgArrowNested/offsetCross": 12,
- "svgArrowNested/platformAsync": 12,
- "svgArrowNested/platformRecipe": 12,
- "svgArrowNested/platformSpread": 12,
- "svgArrowNested/rootDocument": 12,
- "svgArrowNested/rootLayout": 12,
- "svgArrowNested/rootRect": 12,
- "svgArrowNested/shiftPadding": 12,
- "svgArrowNested/size": 12,
- "svgArrowNested/userArrow": 12
+ "svgArrowNested/padding": 12
}
}
diff --git a/shepherd.js/test/position-differential/run.mjs b/shepherd.js/test/position-differential/run.mjs
index c62c15205..0dcebbcd8 100644
--- a/shepherd.js/test/position-differential/run.mjs
+++ b/shepherd.js/test/position-differential/run.mjs
@@ -34,7 +34,7 @@ const bundle = async (contents, globalName) => {
const STOCK = await bundle(`export * from '@floating-ui/dom';`, 'STOCK');
const ENGINE = await bundle(
`export { computePosition, autoUpdate } from './src/utils/position.ts';
- export { getFloatingUIOptions } from './src/utils/floating-ui.ts';`,
+ export { getPositionConfig } from './src/utils/floating-ui.ts';`,
'ENGINE'
);
const FIXTURES = readFileSync(join(here, 'fixtures.js'), 'utf8');
@@ -70,7 +70,7 @@ const CORE_PLACEMENTS = [
'auto-end'
];
// Filled by the engine's own middleware only for what Shepherd reads, so stock's
-// bookkeeping under these names is not compared when the engine's ran.
+// bookkeeping under these names is not compared.
const ENGINE_MIDDLEWARE = ['flip', 'autoPlacement', 'shift'];
async function runFixture({
@@ -80,8 +80,7 @@ async function runFixture({
CORE_PLACEMENTS,
ENGINE_MIDDLEWARE
}) {
- const { STOCK, ENGINE, FIXTURES, USER_CONFIGS, RAW_CONFIGS, stockOptions } =
- window;
+ const { STOCK, ENGINE, FIXTURES, POSITION_CONFIGS, stockOptions } = window;
const round = (value) =>
JSON.parse(
JSON.stringify(value, (key, v) => {
@@ -102,13 +101,11 @@ async function runFixture({
return { threw: String(error.message).slice(0, 100) };
}
};
- const comparableData = (result, raw) => {
+ const comparableData = (result) => {
if (result.threw) return result.threw;
const data = { ...result.middlewareData };
- if (!raw) for (const key of ENGINE_MIDDLEWARE) delete data[key];
- if (data.arrow && !raw) {
- data.arrow = { x: data.arrow.x, y: data.arrow.y };
- }
+ for (const key of ENGINE_MIDDLEWARE) delete data[key];
+ if (data.arrow) data.arrow = { x: data.arrow.x, y: data.arrow.y };
return JSON.stringify(data);
};
@@ -116,7 +113,7 @@ async function runFixture({
if (!fx) return { name, skipped: true };
const { reference, floating, arrow } = fx;
const out = { name, cases: 0, differences: [] };
- const compare = (config, strategy, on, stock, engine, raw) => {
+ const compare = (config, strategy, on, stock, engine) => {
out.cases++;
if (stock.threw && engine.threw) return;
const dx = Math.abs(stock.x - engine.x);
@@ -126,8 +123,8 @@ async function runFixture({
dx > 0.01 ||
dy > 0.01 ||
stock.placement !== engine.placement;
- const stockData = comparableData(stock, raw);
- const engineData = comparableData(engine, raw);
+ const stockData = comparableData(stock);
+ const engineData = comparableData(engine);
if (coords || stockData !== engineData) {
out.differences.push({
config,
@@ -161,54 +158,33 @@ async function runFixture({
const strategies = fx.fixedOnly ? ['fixed'] : ['absolute', 'fixed'];
for (const strategy of strategies) {
if (!fx.keepPosition) floating.style.position = strategy;
- for (const [config, make] of Object.entries(USER_CONFIGS)) {
+ for (const [config, position] of Object.entries(POSITION_CONFIGS)) {
if (only && only !== config) continue;
for (const on of config === 'none' ? ALL_PLACEMENTS : CORE_PLACEMENTS) {
const stock = await attempt(() =>
STOCK.computePosition(
reference,
floating,
- stockOptions(STOCK, on, reference, arrow, strategy, make(STOCK, fx))
+ stockOptions(STOCK, on, arrow, strategy, position)
)
);
const engine = await attempt(() =>
ENGINE.computePosition(
reference,
floating,
- ENGINE.getFloatingUIOptions(
+ ENGINE.getPositionConfig(
{ element: reference, on },
{
options: {
arrow: true,
- floatingUIOptions: { strategy, ...make(STOCK, fx) }
+ positionOptions: { strategy, ...position }
},
el: floating
}
)
)
);
- compare(config, strategy, on, stock, engine, false);
- }
- }
- for (const [config, make] of Object.entries(RAW_CONFIGS)) {
- if (only && only !== config) continue;
- for (const on of CORE_PLACEMENTS) {
- const placement = on.startsWith('auto') ? undefined : on;
- const stock = await attempt(() =>
- STOCK.computePosition(reference, floating, {
- placement,
- strategy,
- middleware: make(STOCK, on, fx)
- })
- );
- const engine = await attempt(() =>
- ENGINE.computePosition(reference, floating, {
- placement,
- strategy,
- middleware: make(STOCK, on, fx)
- })
- );
- compare(config, strategy, on, stock, engine, true);
+ compare(config, strategy, on, stock, engine);
}
}
}
From 9752e61ffc001f40ada52c020d4ba0378c4ec269 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 08:01:43 -0500
Subject: [PATCH 78/93] test(llm-eval): add the floatingUIOptions mistake
Agents trained on Shepherd 15 code will still write floatingUIOptions. The
matrix checks the warning names positionOptions.
Co-Authored-By: Claude Opus 5.5
---
shepherd.js/test/llm-eval/mistakes.mjs | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/shepherd.js/test/llm-eval/mistakes.mjs b/shepherd.js/test/llm-eval/mistakes.mjs
index 7ad9bc62c..cae5728d2 100644
--- a/shepherd.js/test/llm-eval/mistakes.mjs
+++ b/shepherd.js/test/llm-eval/mistakes.mjs
@@ -245,6 +245,18 @@ tour.start();
if (visible !== 1) throw new Error('no visible overlay');
}
},
+ {
+ id: 'floating-ui-options',
+ why: 'Shepherd 15 and earlier took Floating UI config in floatingUIOptions, which positionOptions replaced.',
+ code: program({ step1: `floatingUIOptions: { strategy: 'fixed' },` }),
+ fix: /positionOptions/,
+ extra: async (d) => {
+ const position = await d
+ .step('First')
+ .evaluate((el) => getComputedStyle(el).position);
+ if (position !== 'fixed') throw new Error('the step is not fixed');
+ }
+ },
{
id: 'content-not-text',
why: 'Most tour libraries call the body content or description.',
From 6adef7aaf1d95f0c3bce5291d4ff09f1d4275861 Mon Sep 17 00:00:00 2001
From: Robert Wagner
Date: Sat, 7 Nov 2026 08:03:11 -0500
Subject: [PATCH 79/93] docs: document positionOptions and how to upgrade from
floatingUIOptions
The guides link to the generated StepOptionsPosition page for each field
instead of listing them, the cookbook's offset and strategy recipes use
positionOptions, and the install guide gains upgrade notes from Shepherd 15.
AGENTS.md, both llms.txt files, the homepage markdown and the READMEs say
there is no floatingUIOptions, and the tour schema accepts positionOptions.
Co-Authored-By: Claude Opus 5.5
---
README.md | 2 +
docs-src/src/content/docs/guides/install.mdx | 24 +++++++++
docs-src/src/content/docs/guides/usage.md | 19 +++----
docs-src/src/content/docs/recipes/cookbook.md | 53 +++++++++----------
landing/public/llms.txt | 3 ++
landing/src/lib/homepage-markdown.ts | 3 +-
shepherd.js/AGENTS.md | 12 +++--
shepherd.js/llms.txt | 3 ++
shepherd.js/tour.schema.json | 30 +++++++++++
9 files changed, 103 insertions(+), 46 deletions(-)
diff --git a/README.md b/README.md
index 62d4589e7..612d12f1a 100644
--- a/README.md
+++ b/README.md
@@ -61,6 +61,8 @@ tour.addStep({
tour.start();
```
+Steps position themselves with a small built-in engine. Tune the gap, edge distance and flipping with `positionOptions: { offset, padding, strategy, flip }`. Upgrading from Shepherd 15, which took Floating UI middleware in `floatingUIOptions`? See [the upgrade notes](https://docs.shepherdjs.dev/guides/install/#upgrading-from-shepherd-15).
+
Coding agents: read [`shepherd.js/AGENTS.md`](shepherd.js/AGENTS.md), which is also in the npm package.
### Shepherd Open Source Library
diff --git a/docs-src/src/content/docs/guides/install.mdx b/docs-src/src/content/docs/guides/install.mdx
index 39062cebf..7b8cd033f 100644
--- a/docs-src/src/content/docs/guides/install.mdx
+++ b/docs-src/src/content/docs/guides/install.mdx
@@ -71,3 +71,27 @@ We strive to make it easy to use Shepherd in all the major frameworks, and have
- [ember-shepherd](https://github.com/shipshapecode/ember-shepherd)
- [react-shepherd](https://github.com/shipshapecode/shepherd/tree/main/packages/react)
- [vue-shepherd](https://github.com/shipshapecode/vue-shepherd)
+
+## Upgrading from Shepherd 15
+
+Shepherd positions steps with its own engine and no longer runs Floating UI
+middleware or platforms. `floatingUIOptions` is replaced by `positionOptions`,
+which takes four keys. A step that still passes `floatingUIOptions` logs a
+warning and is positioned as if it had none.
+
+| Shepherd 15 | Now |
+| ------------------------------------------------------------ | ----------------------------------------------- |
+| `floatingUIOptions: { strategy: 'fixed' }` | `positionOptions: { strategy: 'fixed' }` |
+| `floatingUIOptions: { middleware: [offset(12)] }` | `positionOptions: { offset: 12 }` |
+| `offset({ mainAxis: 4, crossAxis: 8 })` | `positionOptions: { offset: { mainAxis: 4, crossAxis: 8 } }` |
+| `shift({ padding: 24 })` or `flip({ padding: 24 })` | `positionOptions: { padding: 24 }`, for both |
+| Removing `flip()` to keep a side | `positionOptions: { flip: false }` |
+| `placement` in `floatingUIOptions` | `attachTo.on` |
+| `hide()`, `size()`, `inline()`, custom middleware, `platform` | No replacement |
+
+Shepherd 15 ran a consumer's `offset()` after its own `flip()` and `shift()`.
+`offset` now runs first, as Floating UI recommends, so flipping and shifting
+account for the gap. Remove `@floating-ui/dom` from your
+dependencies if nothing else uses it. See
+[`StepOptionsPosition`](https://docs.shepherdjs.dev/api/step/interfaces/stepoptionsposition/)
+for each key.
diff --git a/docs-src/src/content/docs/guides/usage.md b/docs-src/src/content/docs/guides/usage.md
index d3c2c3468..305531c75 100644
--- a/docs-src/src/content/docs/guides/usage.md
+++ b/docs-src/src/content/docs/guides/usage.md
@@ -342,15 +342,11 @@ function will be called in the `before-show` phase.
- `modalOverlayOpeningRadius`: An amount of border radius to add around the
modal overlay opening. It can be either a number or an object with properties
`{ topLeft, bottomLeft, bottomRight, topRight }`
-- `floatingUIOptions`: Extra positioning options, in the shape of
- [Floating UI's `computePosition` config](https://floating-ui.com/docs/computePosition).
- Shepherd positions steps itself, but middleware from your own install of
- `@floating-ui/dom` runs as is. This includes
- `strategy`, which sets the CSS `position` of the step element and defaults to
- `'absolute'`. It can be set per-step or on `defaultStepOptions`. See
- [Floating UI's `strategy` documentation](https://floating-ui.com/docs/computePosition#strategy)
- for when `'fixed'` is the better choice. Note that steps without an `attachTo`
- element are always centered with `position: fixed` and ignore `strategy`.
+- `positionOptions`: How the step is placed against its target: `offset`,
+ `padding`, `strategy` and `flip`. Values from `defaultStepOptions` and the
+ step combine key by key. See
+ [`StepOptionsPosition`](https://docs.shepherdjs.dev/api/step/interfaces/stepoptionsposition/)
+ for each field, and the [cookbook](https://docs.shepherdjs.dev/recipes/cookbook/#offsets) for examples.
- `showOn`: A function that, when it returns true, will show the step. If it
returns false, the step will be skipped.
- `skipMissingElement`: A boolean. When true, a step whose `attachTo.element`
@@ -482,8 +478,9 @@ myTour.addStep({
```
You can also provide an options object, to configure the arrow's
-[padding](https://floating-ui.com/docs/arrow#padding). The padding is the
-closest the arrow will get to the edge of the step.
+[`padding`](https://docs.shepherdjs.dev/api/step/interfaces/stepoptionsarrow/).
+The padding is the closest the arrow will get to the edge of the step, and only
+applies to `-start` and `-end` placements.
```js
myTour.addStep({
diff --git a/docs-src/src/content/docs/recipes/cookbook.md b/docs-src/src/content/docs/recipes/cookbook.md
index 4958d2e5b..e406a93d7 100644
--- a/docs-src/src/content/docs/recipes/cookbook.md
+++ b/docs-src/src/content/docs/recipes/cookbook.md
@@ -35,31 +35,27 @@ Highlighted elements do not have to share a scroll container with the `attachTo`
### Offsets
-By default, steps are placed directly next to their target. However, if you need to apply some margin
-between them or if you need to fine tune the position according to some custom logic, you can use an offset middleware.
-
-Shepherd positions steps itself and has no dependency on Floating UI, but `floatingUIOptions.middleware` accepts
-[Floating UI middleware](https://floating-ui.com/docs/middleware) as is. Install `@floating-ui/dom` in your own project
-to use it. Only the middleware you import ends up in your bundle.
-
-For example:
+By default, steps are placed directly next to their target, with the arrow
+making up the gap. Set `positionOptions.offset` to add more space:
```js
-import { offset } from '@floating-ui/dom';
-
const tour = new Shepherd.Tour({
steps: [
{
...
- floatingUIOptions: {
- middleware: [offset({ mainAxis: 0, crossAxis: 12 })]
- }
+ positionOptions: { offset: 12 }
...
}
]
});
```
+A number moves the step away from its target. `{ mainAxis, crossAxis }` also
+slides it along the side it sits on. `padding` keeps the step that far from the
+edges of the viewport and of scrolling containers. See
+[`StepOptionsPosition`](https://docs.shepherdjs.dev/api/step/interfaces/stepoptionsposition/)
+for every field.
+
### Positioning strategy
Steps are positioned with `position: absolute` by default. Shepherd keeps
@@ -67,43 +63,42 @@ comparing a step's position with its target's, so the default already keeps a
step locked to its target while the page — or any scrolling ancestor of the
target — scrolls.
-If you need the step element to be `position: fixed` instead, set the `strategy`
-option. Floating UI recommends this when the target itself is
-`position: fixed`, or to escape a clipping ancestor; see
-[its `strategy` documentation](https://floating-ui.com/docs/computePosition#strategy)
-for the trade-offs.
-
-For example:
+Use `strategy: 'fixed'` when the target is itself `position: fixed`, such as a
+sticky header, so the step stays with it without being repositioned on every
+scroll:
```js
const tour = new Shepherd.Tour({
steps: [
{
...
- floatingUIOptions: {
- strategy: 'fixed'
- }
+ positionOptions: { strategy: 'fixed' }
...
}
]
});
```
-You can also set this once for every step via `defaultStepOptions`:
+You can also set this once for every step via `defaultStepOptions`. A step's own
+`positionOptions` change only the keys it sets:
```js
const tour = new Shepherd.Tour({
defaultStepOptions: {
- floatingUIOptions: {
- strategy: 'fixed'
- }
+ positionOptions: { strategy: 'fixed', offset: 8 }
}
});
```
Centered steps are always positioned in the viewport with `position: fixed`, so
-`strategy` has no effect on them. A step is centered when it has no `attachTo`
-at all, or when its `attachTo` is missing either `element` or `on`.
+`positionOptions` has no effect on them. A step is centered when it has no
+`attachTo` at all, or when its `attachTo` is missing either `element` or `on`.
+
+### Keeping a placement
+
+A step flips to the opposite side when `attachTo.on` would not fit. Set
+`positionOptions: { flip: false }` to keep the side you chose, for example when
+the opposite side would cover something the user needs to see.
### Progress Indicator
diff --git a/landing/public/llms.txt b/landing/public/llms.txt
index 003fc5005..ffa30aa2c 100644
--- a/landing/public/llms.txt
+++ b/landing/public/llms.txt
@@ -32,6 +32,9 @@ defines no global, so import it, including from a `
diff --git a/packages/react/README.md b/packages/react/README.md
index ee3df520d..e37f57e4a 100644
--- a/packages/react/README.md
+++ b/packages/react/README.md
@@ -20,7 +20,7 @@ npm install --save react-shepherd
### Via Provider/Context
```tsx
-import { useMemo } from 'react';
+import { useEffect, useMemo } from 'react';
import { ShepherdJourneyProvider, useShepherd } from 'react-shepherd';
import 'shepherd.js/dist/css/shepherd.css';
@@ -44,6 +44,14 @@ function Button() {
const Shepherd = useShepherd();
const tour = useMemo(() => new Shepherd.Tour(tourOptions), [Shepherd]);
+ // Ends the tour if this component unmounts while it is open.
+ useEffect(
+ () => () => {
+ if (tour.isActive()) tour.complete();
+ },
+ [tour]
+ );
+
return (