` inside `.tip-magic-tour-footer`, so a `.tip-magic-tour-footer > .your-class` selector no longer matches. Layout is unchanged.
+- A step whose only feature is a `title` now renders the panel (a `role="dialog"`) instead of dropping the title.
+- A `content` step with no panel features is injected as HTML, as documented, without `tooltipOptions.html: true`. An explicit `html: false` (tour or step) still shows it as text.
+- `text` is rendered once-escaped everywhere, and button labels as text rather than markup.
+- Unmounting the component that called `useTour` takes a running tour down without calling `onEnd`.
+- `CurrentTourStep.content` (in `currentStep`, `onStepChange`, `onTargetMissing`) is `''` for a `body` step: React content has no HTML form.
+- A panel without a `title` is labelled by its message, so `aria-labelledby` is now always set on a tour dialog.
+- `start()` also returns `false` when the first step has nothing to show (an empty body and no panel features).
+- A step may be only its `image` or `video`, with no `text`, `body` or `content`; the video's type is exported as `TourVideo`, and `video.title` now names native videos too.
+- `mediaPlacement` (`TourOptions` and `TourStep`, type `TourMediaPlacement`) is new and defaults to `'top'`, the existing layout.
+- An anchored panel's height cap never drops below `--tip-magic-tour-min-height` (240px): with less room beside its target it flips to another side.
+- `TourStep.target` is optional: a step without one opens centered. `CurrentTourStep.target` is `undefined` for such a step, so code that reads it as a `string` must handle that.
+
+Type changes, for code that uses the exported context (`useTipMagicContext`, `TipMagicState`, `TipMagicAction`):
+
+- `TooltipState.content` and the `SHOW_TOOLTIP` / `MOVE_TOOLTIP` payloads' `content` widened from `string` to `ReactNode`. Writing a string still works; code that reads one and annotates it as `string` must widen or narrow with `typeof`.
+- `UPDATE_TOOLTIP_CONTENT` and `tooltip.updateContent` still take a `string`. Called while a tour runs, they replace the tour panel with that string.
+- `HIDE_TOOLTIP` and `END_FLOW` accept an optional `payload` (`onlyIfOwner`, `onlyIfSteps`), and `TooltipShowOptions` gains `owner` and `centered`; all additive.
+- `TooltipShowOptions.maxWidth` and `ParsedTooltipData.maxWidth` also accept `'none'` (let the content decide), which a centered step with an image uses. Code that reads `parsedData.maxWidth` as a `number` must handle it.
+
---
## Tip Advisor
diff --git a/package-lock.json b/package-lock.json
index 74044e1..b134af0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@galangel/react-tip-magic",
- "version": "1.3.0",
+ "version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@galangel/react-tip-magic",
- "version": "1.3.0",
+ "version": "1.4.0",
"license": "Apache-2.0",
"dependencies": {
"@floating-ui/react": "^0.27.16",
diff --git a/package.json b/package.json
index 1819732..259a22b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@galangel/react-tip-magic",
- "version": "1.3.0",
+ "version": "1.4.0",
"description": "A sophisticated, elegant, and performant tooltip library for React with an intelligent floating helper system.",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/src/Flows.mdx b/src/Flows.mdx
index 9f286fb..b79a477 100644
--- a/src/Flows.mdx
+++ b/src/Flows.mdx
@@ -80,6 +80,7 @@ const tour = useTour({
navigation: {...}, // Optional: Navigation configuration
progress: {...}, // Optional: Progress indicator options
focus: false, // Optional: Backdrop - boolean, or { block, dismissOnClick }
+ mediaPlacement: 'top', // Optional: Where media sits - 'top' | 'left' | 'right'
onStart: () => {}, // Optional: Called when tour starts
onEnd: (completed) => {}, // Optional: Called when tour ends
onStepChange: (step, direction) => {}, // Optional: Called on navigation
@@ -146,14 +147,25 @@ Each step in the `steps` array can have the following properties:
-\* Exactly one of `content` or `text` is required. The types enforce it: a step with
-neither, or with both, will not compile.
+\* At most one of `text`, `body` or `content`, and a step without one must have an `image`
+or a `video` - a step that is only media. The types enforce it: a step with nothing to
+show, or with two bodies, will not compile.
+
+### A step without a target opens centered
+
+A step that is not about any element - an announcement, a welcome, a closing note - leaves
+out `target`. It opens centered in the viewport and stays there as the page scrolls or
+resizes, with no arrow, and with the focus backdrop on (nothing is cut out of it). Set
+`focus: false` on the step or the tour to turn the backdrop off, or
+`focus: { dismissOnClick: true }` to let a click on it end the tour.
+
+```tsx
+const announcement = useTour({
+ steps: [
+ {
+ id: 'whats-new',
+ title: "What's new",
+ image: '/release.png',
+ body:
,
+ },
+ ],
+ navigation: { showControls: true, finishLabel: 'Got it' },
+ tooltipOptions: { maxWidth: 420 },
+});
+```
+
+A centered panel is at most 80% of the viewport's height
+(`--tip-magic-tour-centered-max-height`); its body scrolls past that.
+
+**Its image sets its width.** A centered step with an `image` or a native `video` takes
+the media's natural width, capped at 70% of the viewport (`--tip-magic-tour-centered-max-width`,
+and an explicit `tooltipOptions.maxWidth` if you set one); the title, body and footer wrap
+inside it. The media is never cropped or distorted: when it would leave too little height
+for the title, a few lines of body and the footer
+(`--tip-magic-tour-media-reserved-height`), it is scaled down uniformly. The panel is never
+narrower than 280px (`--tip-magic-tour-min-width`) - a smaller image is centered at its
+natural size, not stretched. The panel stays hidden until the media's size is known, so it
+does not open narrow and then widen. Without media, or with an embedded video, which has no
+size of its own, the width comes from `maxWidth` as for any tooltip.
+
+A step can also be only its media: `{ video: { src, title } }`, with no title or text.
+Its panel is named by `video.title` (default `'Tour video'`), and with nothing else in
+the panel the media may take nearly all of the 80% height. With
+`navigation: { showControls: false, showClose: false }` and
+`focus: { dismissOnClick: true }` it has no buttons at all: a click outside it or Escape
+closes it.
+
+Everything else works as for an anchored step: the same panel, media, `text` / `body` /
+`content`, navigation, progress, `autoFocus` and Escape. With no target there is nothing to
+highlight, scroll to or watch, so `onTargetMissing` never fires for it. Centered and
+anchored steps mix freely - a centered intro, anchored steps, a centered outro - and the
+arrow comes back for the anchored ones. Give a centered step an `id` if `steps` can change
+while it is on screen: with no target, it can only be told apart by its position.
+
+See the **[Announcement](?path=/story/tooltip-flow-tours--announcement)** story.
+
+### React content
+
+`body` takes any React node, so a step can render your own components - markdown, a
+link, a button with its own `onClick`:
+
+```tsx
+const tour = useTour({
+ steps: [
+ {
+ target: 'whats-new',
+ title: "What's new",
+ body:
,
+ },
+ ],
+});
+```
+
+The panel is React too, so its title, button labels and `text` are escaped by React; only
+`content` is injected as HTML.
+
+`body` renders inside `TipMagicProvider`, not inside the component that called `useTour`,
+so it sees only the context providers that wrap `TipMagicProvider`. Put providers the body
+needs (a theme, a router) above it.
+
+A running step follows changes to `steps`: re-render with a new `body` - release notes
+that arrived after `start()`, say - and the panel on screen updates in place, without
+moving focus or firing `onStepChange` again. A changed `placement` or other tooltip
+option is applied too, and the helper flow (`useTipMagic().helper`) follows the new list.
+
+When steps are added, removed or filtered out, the step on screen is found again by its
+`id`, or by its `target` when no other step shares it. If a `condition` filters out an
+earlier step, it stays on screen at its new position. If it is removed - or it has no `id`
+and shares its `target` with another step, so it cannot be told apart - the tour moves on
+to the step now at its place, with `onExit`, `onEnter` and `onStepChange` firing as for
+`next()`; if there is none, the tour ends. **Give steps an `id`, or unique targets, if
+`steps` can change while the tour runs.**
+
+A long body scrolls: `.tip-magic-tour-body` stops growing at
+`--tip-magic-tour-body-max-height` (`60vh` by default), and the panel shrinks the body
+further when there is less room beside the target.
### Dynamic Content
-Step content can be a function that receives step info:
+`body` and `content` can be functions that receive step info:
```tsx
{
target: 'sidebar',
- content: (step) => `Step ${step.index + 1} of ${step.total}: Welcome!`
+ body: (step) =>
}
```
@@ -377,6 +502,7 @@ Configure built-in navigation controls:
navigation: {
showControls: true, // Show Next/Back buttons in tooltip
showClose: true, // Show close (×) button
+ closeLabel: 'Close', // Accessible name of the close button
nextLabel: 'Next', // Custom label for Next button
backLabel: 'Back', // Custom label for Back button
finishLabel: 'Finish', // Label for last step's button
@@ -450,8 +576,9 @@ steps: [
];
```
-Steps that render as a plain tooltip rather than a dialog — no navigation controls, close
-button, media or progress — never move focus, whatever `autoFocus` is set to.
+Steps that render as a plain tooltip rather than a dialog — a `text` or `content` step
+with no title, navigation controls, close button, media or progress — never move focus,
+whatever `autoFocus` is set to. A `body` step always renders the panel.
---
@@ -570,7 +697,8 @@ Add images, GIFs, or videos to tour steps:
content: 'Watch how it works:',
video: {
src: 'https://www.youtube.com/embed/VIDEO_ID',
- type: 'embed'
+ type: 'embed',
+ title: 'Setting up alerts' // The iframe's accessible name (default: 'Tour video')
}
}
@@ -590,6 +718,36 @@ Add images, GIFs, or videos to tour steps:
---
+### Media Placement
+
+`mediaPlacement` puts a step's image or video above its text (`'top'`, the default) or in a
+column of its own to the `'left'` or `'right'` of it. Set it for the whole tour, and
+override it per step:
+
+```tsx
+const tour = useTour({
+ steps: [
+ { title: "What's new", image: '/release.png', body:
},
+ { target: 'search', title: 'Search', image: '/search.gif', text: 'Find anything' },
+ ],
+ mediaPlacement: 'left',
+});
+```
+
+Beside the text, the panel is two columns: the media, and a text column with the title,
+the body - which takes the height left and scrolls - and the buttons at the bottom. The
+close button stays at the panel's top-right corner. The text column takes up to half of
+the panel, between 280px (`--tip-magic-tour-min-width`) and 400px
+(`--tip-magic-tour-side-text-max-width`); the media gets the rest, keeping its aspect ratio
+and never taller than the panel may be. A centered panel stays within 70% of the viewport's
+width and 80% of its height; an anchored one within the viewport, the room beside its target
+and an explicit `maxWidth`.
+
+Below a 640px viewport the media goes back on top, and a step with no media, or with
+nothing but media, ignores the option.
+
+---
+
## Callbacks
Track tour events for analytics or custom behavior:
@@ -623,6 +781,9 @@ const tour = useTour({
});
```
+If the component that called `useTour` unmounts while the tour is running, the panel,
+backdrop and highlight are taken down without calling `onExit` or `onEnd`.
+
---
## Conditional Steps
@@ -711,10 +872,11 @@ Enable focus mode on key steps to draw attention without overwhelming users.
- Tooltips are keyboard accessible
- Respects `prefers-reduced-motion` for animations
-- Close button has proper ARIA labels
-- The tour panel is a `role="dialog"` labelled by the step title, and focus moves into it
- when a step opens so it is announced. Pick which element receives that focus with
- [`navigation.autoFocus`](#where-focus-lands)
+- The close button is named by `navigation.closeLabel` (default `'Close'`), and an embedded
+ video by `video.title` (default `'Tour video'`)
+- The tour panel is a `role="dialog"` labelled by the step title - or, for a step without
+ one, by its message - and focus moves into it when a step opens so it is announced. Pick
+ which element receives that focus with [`navigation.autoFocus`](#where-focus-lands)
- The panel is deliberately non-modal: the app behind it stays interactive and there is no
focus trap, so `Escape` always exits
- Focus returns to whatever held it before the tour when the tour ends
@@ -725,6 +887,9 @@ Enable focus mode on key steps to draw attention without overwhelming users.
- See the **[Simple Tour](?path=/story/tooltip-flow-tours--simple-tour)** story for a basic example
- See the **[Built-in Navigation](?path=/story/tooltip-flow-tours--built-in-navigation)** for in-tooltip controls
+- See the **[Auto Focus](?path=/story/tooltip-flow-tours--auto-focus)** story for where focus lands when a step opens
+- See the **[React Body](?path=/story/tooltip-flow-tours--react-body)** story for a step whose body is a React component
+- See the **[Announcement](?path=/story/tooltip-flow-tours--announcement)** story for a centered step without a target
- See the **[Focus Mode](?path=/story/tooltip-flow-tours--focus-mode)** for backdrop highlighting
- See the **[Always Visible Elements](?path=/story/tooltip-flow-tours--always-visible-elements)** for keeping elements accessible during focus
- See the **[Complete Tour](?path=/story/tooltip-flow-tours--complete-tour)** for a full-featured example
diff --git a/src/Properties.mdx b/src/Properties.mdx
index 48c0856..ef2ceb1 100644
--- a/src/Properties.mdx
+++ b/src/Properties.mdx
@@ -547,6 +547,10 @@ function MyComponent() {
Custom Content
+
diff --git a/src/Welcome.mdx b/src/Welcome.mdx
index 5a84b61..fc9ab15 100644
--- a/src/Welcome.mdx
+++ b/src/Welcome.mdx
@@ -131,7 +131,7 @@ Use the sidebar to learn more:
- **[The Tooltip](?path=/story/the-tooltip--the-tooltip)** — Interactive playground
- **[Keyboard Shortcuts](?path=/docs/tooltip-keyboard-shortcuts-documentation--docs)** — Displaying shortcuts
-- **[The Tour](?path=/story/the-tour--the-tour)** — Guided walkthroughs
+- **[The Tourtip](?path=/story/the-tourtip--the-tourtip)** — Guided walkthroughs
- **[Tip Advisor](?path=/docs/tooltip-tipadvisor-documentation--docs)** — Shortcut discovery
---
diff --git a/src/components/Tooltip/Tooltip.tsx b/src/components/Tooltip/Tooltip.tsx
index 66899dd..cf1c334 100644
--- a/src/components/Tooltip/Tooltip.tsx
+++ b/src/components/Tooltip/Tooltip.tsx
@@ -4,11 +4,13 @@ import {
flip,
offset,
shift,
+ size,
useFloating,
+ type Middleware,
type Placement,
} from '@floating-ui/react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { ANIMATION, CSS_CLASSES } from '../../constants';
+import { ANIMATION, CENTERED_ATTRIBUTE, CSS_CLASSES } from '../../constants';
import { useTipMagicContext } from '../../context/TipMagicContext';
import type { TooltipTransitionBehavior } from '../../types';
import { resolveAutoFocusTarget } from '../../utils/autoFocusTarget';
@@ -17,8 +19,28 @@ import {
buildTooltipClassNames,
getArrowStaticSide,
getArrowStyles,
+ getCenteredPosition,
} from '../../utils/tooltipStyles';
+/** Set from Floating UI's size() middleware, read by the tour panel's stylesheet */
+const AVAILABLE_HEIGHT_PROPERTY = '--tip-magic-available-height';
+
+/**
+ * Floating UI middleware that puts the tooltip in the middle of the viewport, for
+ * `centered` - with the `fixed` strategy, so it stays there as the page scrolls
+ */
+const centerInViewport: Middleware = {
+ name: 'centerInViewport',
+ fn: ({ rects }) =>
+ getCenteredPosition(
+ {
+ width: document.documentElement.clientWidth,
+ height: document.documentElement.clientHeight,
+ },
+ rects.floating
+ ),
+};
+
/**
* Content rendered from an HTML string.
*
@@ -48,23 +70,41 @@ export function Tooltip() {
const transitionBehavior: TooltipTransitionBehavior =
tooltip.parsedData?.transitionBehavior ?? config.transitionBehavior;
+ // A centered tooltip ignores its target's position, and has no arrow
+ const centered = tooltip.parsedData?.centered ?? false;
+
// Memoize middleware array to prevent unnecessary recalculations
const middleware = useMemo(
- () => [
- offset(config.offset),
- flip({
- fallbackAxisSideDirection: 'start',
- padding: 8,
- }),
- shift({ padding: 8 }),
- arrow({ element: arrowRef }),
- ],
- [config.offset]
+ () =>
+ centered
+ ? [centerInViewport]
+ : [
+ offset(config.offset),
+ flip({
+ fallbackAxisSideDirection: 'start',
+ padding: 8,
+ }),
+ shift({ padding: 8 }),
+ // Exposed as a variable rather than applied as max-height: only the tour panel
+ // knows which part of itself can shrink, and a plain tooltip should not clip
+ size({
+ padding: 8,
+ apply({ availableHeight, elements }) {
+ elements.floating.style.setProperty(
+ AVAILABLE_HEIGHT_PROPERTY,
+ `${Math.max(0, availableHeight)}px`
+ );
+ },
+ }),
+ arrow({ element: arrowRef }),
+ ],
+ [config.offset, centered]
);
// Floating UI setup
const { refs, floatingStyles, context, middlewareData, isPositioned } = useFloating({
placement,
+ strategy: centered ? 'fixed' : 'absolute',
open: tooltip.visible,
middleware,
whileElementsMounted: autoUpdate,
@@ -89,13 +129,24 @@ export function Tooltip() {
// Check group compatibility for move transitions
const groupsCompatible = areGroupsCompatible(tooltip.parsedData?.group, tooltip.previousGroup);
- // Determine if we should animate position (move behavior)
- const animatePosition = shouldAnimatePosition(
- hasBeenPositioned,
- tooltip.isTransitioning,
- transitionBehavior,
- groupsCompatible
- );
+ // Determine if we should animate position (move behavior). Never for a move between
+ // centered and anchored: they use different positioning strategies, so the transform
+ // would animate between two coordinate systems. Compared with where the tooltip last
+ // settled, since the new position only arrives a render or two into the move.
+ const settledCenteredRef = useRef(centered);
+ useEffect(() => {
+ if (!tooltip.isTransitioning) {
+ settledCenteredRef.current = centered;
+ }
+ }, [tooltip.isTransitioning, centered]);
+ const animatePosition =
+ settledCenteredRef.current === centered &&
+ shouldAnimatePosition(
+ hasBeenPositioned,
+ tooltip.isTransitioning,
+ transitionBehavior,
+ groupsCompatible
+ );
// Control visibility: show only after positioned, hide immediately when not visible
useEffect(() => {
@@ -181,7 +232,7 @@ export function Tooltip() {
const ellipsis = tooltip.parsedData?.ellipsis ?? false;
const maxLines = tooltip.parsedData?.maxLines ?? 1;
const textBreak = tooltip.parsedData?.textBreak ?? 'normal';
- const showArrow = tooltip.parsedData?.showArrow ?? true;
+ const showArrow = (tooltip.parsedData?.showArrow ?? true) && !centered;
// Build class names using utility
const classNames = buildTooltipClassNames({
@@ -219,14 +270,15 @@ export function Tooltip() {
} as React.CSSProperties
}
onTransitionEnd={handleTransitionEnd}
- data-placement={context.placement}
+ data-placement={centered ? undefined : context.placement}
+ {...{ [CENTERED_ATTRIBUTE]: centered ? '' : undefined }}
data-transition-behavior={transitionBehavior}
data-interactive={isInteractive ? '' : undefined}
// Opts the stylesheet's prefers-reduced-motion guards back out
data-tip-magic-motion={config.respectReducedMotion ? undefined : 'always'}
>
- {isHtmlContent ? (
+ {isHtmlContent && typeof mainContent === 'string' ? (
) : (
{mainContent}
diff --git a/src/components/Tooltip/__tests__/Tooltip.test.tsx b/src/components/Tooltip/__tests__/Tooltip.test.tsx
index 20abacd..4685eb7 100644
--- a/src/components/Tooltip/__tests__/Tooltip.test.tsx
+++ b/src/components/Tooltip/__tests__/Tooltip.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render } from '@testing-library/react';
+import { cleanup, render, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import { DEFAULT_OPTIONS } from '../../../constants';
import { TipMagicContext, type TipMagicContextValue } from '../../../context/TipMagicContext';
@@ -286,3 +286,54 @@ describe('HTML content is not rebuilt on every re-render', () => {
expect(document.getElementById('media')).toBeNull();
});
});
+
+describe('React node content', () => {
+ it('renders a node as React, even with html on', () => {
+ const base = createMockState().tooltip.parsedData as ParsedTooltipData;
+ const node = (
+
+ Bold
+
+ );
+
+ renderTooltip(createMockState({ content: node, parsedData: { ...base, html: true } }));
+
+ const rendered = document.querySelector('.tip-magic-text > #node');
+ expect(rendered?.textContent).toBe('Bold');
+ expect(rendered?.getAttribute('data-value')).toBe('
');
+ });
+});
+
+describe('available height', () => {
+ it('exposes the room beside the target as a variable, without clamping the tooltip', async () => {
+ renderTooltip(createMockState());
+ const element = document.querySelector('.tip-magic-tooltip') as HTMLElement;
+
+ await waitFor(() =>
+ expect(element.style.getPropertyValue('--tip-magic-available-height')).toMatch(/^\d+px$/)
+ );
+ expect(element.style.maxHeight).toBe('');
+ });
+});
+
+describe('centered', () => {
+ it('positions a centered tooltip fixed, with no arrow and no placement', async () => {
+ const base = createMockState().tooltip.parsedData as ParsedTooltipData;
+ renderTooltip(createMockState({ parsedData: { ...base, centered: true } }));
+ const element = document.querySelector('.tip-magic-tooltip') as HTMLElement;
+
+ await waitFor(() => expect(element.style.position).toBe('fixed'));
+ expect(element.hasAttribute('data-tip-magic-centered')).toBe(true);
+ expect(element.hasAttribute('data-placement')).toBe(false);
+ expect(element.querySelector('.tip-magic-arrow')).toBeNull();
+ });
+
+ it('leaves an anchored tooltip absolute, with its arrow', async () => {
+ renderTooltip(createMockState());
+ const element = document.querySelector('.tip-magic-tooltip') as HTMLElement;
+
+ await waitFor(() => expect(element.style.position).toBe('absolute'));
+ expect(element.hasAttribute('data-tip-magic-centered')).toBe(false);
+ expect(element.querySelector('.tip-magic-arrow')).not.toBeNull();
+ });
+});
diff --git a/src/constants/index.ts b/src/constants/index.ts
index f1ae5fb..b92911d 100644
--- a/src/constants/index.ts
+++ b/src/constants/index.ts
@@ -73,6 +73,11 @@ export const CSS_CLASSES = {
*/
export const PRIMARY_ACTION_ATTRIBUTE = 'data-tip-magic-primary';
+/**
+ * Set on the tooltip while it is centered in the viewport (`TooltipShowOptions.centered`)
+ */
+export const CENTERED_ATTRIBUTE = 'data-tip-magic-centered';
+
/**
* Default selector for tooltip targets
*/
diff --git a/src/context/TipMagicContext.tsx b/src/context/TipMagicContext.tsx
index 3ca259b..9badb3f 100644
--- a/src/context/TipMagicContext.tsx
+++ b/src/context/TipMagicContext.tsx
@@ -84,17 +84,23 @@ export type TipMagicAction =
type: 'SHOW_TOOLTIP';
payload: {
target: Element;
- content: string;
+ content: ReactNode;
parsedData: ParsedTooltipData;
+ owner?: object;
};
}
- | { type: 'HIDE_TOOLTIP' }
+ | {
+ type: 'HIDE_TOOLTIP';
+ /** Hide only while the tooltip is still this owner's - see `TooltipShowOptions.owner` */
+ payload?: { onlyIfOwner: object };
+ }
| {
type: 'MOVE_TOOLTIP';
payload: {
target: Element;
- content: string;
+ content: ReactNode;
parsedData: ParsedTooltipData;
+ owner?: object;
previousGroup?: string;
};
}
@@ -112,7 +118,11 @@ export type TipMagicAction =
| { type: 'NEXT_FLOW_STEP' }
| { type: 'PREV_FLOW_STEP' }
| { type: 'SET_FLOW_STEP'; payload: number }
- | { type: 'END_FLOW' };
+ | {
+ type: 'END_FLOW';
+ /** End only while the flow is still this one - it may be someone else's */
+ payload?: { onlyIfSteps: FlowStep[] };
+ };
/**
* Reducer for TipMagic state
@@ -128,11 +138,15 @@ export function tipMagicReducer(state: TipMagicState, action: TipMagicAction): T
target: action.payload.target,
content: action.payload.content,
parsedData: action.payload.parsedData,
+ owner: action.payload.owner,
isTransitioning: false,
},
};
case 'HIDE_TOOLTIP':
+ if (action.payload && state.tooltip.owner !== action.payload.onlyIfOwner) {
+ return state;
+ }
return {
...state,
tooltip: {
@@ -149,6 +163,7 @@ export function tipMagicReducer(state: TipMagicState, action: TipMagicAction): T
target: action.payload.target,
content: action.payload.content,
parsedData: action.payload.parsedData,
+ owner: action.payload.owner,
isTransitioning: true,
previousGroup: action.payload.previousGroup,
},
@@ -260,6 +275,9 @@ export function tipMagicReducer(state: TipMagicState, action: TipMagicAction): T
};
case 'END_FLOW':
+ if (action.payload && state.flow.steps !== action.payload.onlyIfSteps) {
+ return state;
+ }
return {
...state,
flow: initialFlowState,
diff --git a/src/hooks/useTooltipAPI.ts b/src/hooks/useTooltipAPI.ts
index 1c82b52..ec881f1 100644
--- a/src/hooks/useTooltipAPI.ts
+++ b/src/hooks/useTooltipAPI.ts
@@ -1,4 +1,4 @@
-import { useCallback, useMemo } from 'react';
+import { useCallback, useMemo, type ReactNode } from 'react';
import type { TipMagicAction } from '../context/TipMagicContext';
import type { ParsedTooltipData, TipMagicState, TooltipAPI, TooltipShowOptions } from '../types';
import { parseDataAttributes } from '../utils/parseDataAttributes';
@@ -32,7 +32,7 @@ export function useTooltipAPI(
const parsedData = parseDataAttributes(element);
// Handle string content or options object
- let tooltipContent: string;
+ let tooltipContent: ReactNode;
let options: TooltipShowOptions = {};
if (typeof contentOrOptions === 'string') {
@@ -52,7 +52,7 @@ export function useTooltipAPI(
// Merge parsed data with options (options take precedence)
const mergedData: ParsedTooltipData = {
...parsedData,
- content: tooltipContent,
+ ...(typeof tooltipContent === 'string' && { content: tooltipContent }),
...(options.placement !== undefined && { placement: options.placement }),
...(options.showDelay !== undefined && { delay: options.showDelay }),
...(options.hideDelay !== undefined && { hideDelay: options.hideDelay }),
@@ -74,6 +74,7 @@ export function useTooltipAPI(
...(options.role !== undefined && { role: options.role }),
...(options.ariaLabelledBy !== undefined && { ariaLabelledBy: options.ariaLabelledBy }),
...(options.autoFocus !== undefined && { autoFocus: options.autoFocus }),
+ ...(options.centered !== undefined && { centered: options.centered }),
};
if (state.tooltip.visible) {
@@ -88,6 +89,7 @@ export function useTooltipAPI(
target: element,
content: tooltipContent,
parsedData: mergedData,
+ owner: options.owner,
},
});
} else {
@@ -98,6 +100,7 @@ export function useTooltipAPI(
target: element,
content: tooltipContent,
parsedData: mergedData,
+ owner: options.owner,
},
});
}
@@ -108,6 +111,7 @@ export function useTooltipAPI(
target: element,
content: tooltipContent,
parsedData: mergedData,
+ owner: options.owner,
},
});
}
@@ -134,7 +138,7 @@ export function useTooltipAPI(
show: tooltipShow,
hide: tooltipHide,
isVisible: state.tooltip.visible,
- content: state.tooltip.content || null,
+ content: typeof state.tooltip.content === 'string' ? state.tooltip.content || null : null,
target: state.tooltip.target,
updateContent: tooltipUpdateContent,
}),
diff --git a/src/hooks/useTour/TourPanel.tsx b/src/hooks/useTour/TourPanel.tsx
new file mode 100644
index 0000000..92a092d
--- /dev/null
+++ b/src/hooks/useTour/TourPanel.tsx
@@ -0,0 +1,347 @@
+import { memo, useState, useSyncExternalStore, type CSSProperties } from 'react';
+import { PRIMARY_ACTION_ATTRIBUTE } from '../../constants';
+import type {
+ CurrentTourStep,
+ TourMediaPlacement,
+ TourNavigation,
+ TourStep,
+} from '../../types/tour';
+import { TOUR_ACTIONS, TOUR_CSS_CLASSES, TOUR_DATA_ATTRIBUTES } from './constants';
+import { getProgressRingGeometry, hasMessage, type TourPanelStore } from './utils';
+import type { ResolvedProgressOptions, ResolvedStepBody } from './utils';
+
+/**
+ * Props for {@link TourPanel}
+ */
+export interface TourPanelProps {
+ /** The step being shown - its title and media */
+ step: TourStep;
+ /** Where the step sits in the tour */
+ stepInfo: CurrentTourStep;
+ /** Navigation config, merged for this step */
+ navigation: Required;
+ /** The step's body, resolved */
+ body: ResolvedStepBody;
+ /** Progress config, merged for this step */
+ progress: ResolvedProgressOptions;
+ /** id for the title, which the panel's `aria-labelledby` points at */
+ titleId?: string;
+ /** id for the message, which labels the panel when the step has no title */
+ messageId?: string;
+ /** id for a video, which labels the panel when the step has neither title nor text */
+ mediaId?: string;
+ /** Whether the panel takes its width from its image or native video (a centered step) */
+ fitMedia?: boolean;
+ /** An explicit cap on the panel's width, in pixels, when it takes it from its media */
+ mediaMaxWidth?: number;
+ /** Where the media sits, resolved (default: `'top'`) */
+ mediaPlacement?: TourMediaPlacement;
+}
+
+type TourAction = (typeof TOUR_ACTIONS)[keyof typeof TOUR_ACTIONS];
+
+const EMBED_ALLOW =
+ 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
+
+const DEFAULT_EMBED_TITLE = 'Tour video';
+
+/** Read by the stylesheet to cap media that sets the panel's width */
+const MEDIA_MAX_WIDTH_PROPERTY = '--tip-magic-tour-media-max-width';
+
+/** Leaves custom progress markup laid out as direct children of the footer */
+const CUSTOM_PROGRESS_STYLE: CSSProperties = { display: 'contents' };
+
+/**
+ * Keep the `muted` attribute in step with the prop. React only sets the property, and iOS
+ * Safari's autoplay policy reads the attribute, which `defaultMuted` reflects.
+ */
+const markMuted = (video: HTMLVideoElement | null) => {
+ if (video) video.defaultMuted = true;
+};
+
+const markUnmuted = (video: HTMLVideoElement | null) => {
+ if (video) video.defaultMuted = false;
+};
+
+const actionAttribute = (action: TourAction) => ({ [TOUR_DATA_ATTRIBUTES.ACTION]: action });
+
+/**
+ * Markup from an HTML string.
+ *
+ * Memoised on its props so the subtree survives re-renders - see CLAUDE.md,
+ * "dangerouslySetInnerHTML is re-applied on every render".
+ */
+const RawHtml = memo(function RawHtml({
+ html,
+ id,
+ className,
+ style,
+}: {
+ html: string;
+ id?: string;
+ className?: string;
+ style?: CSSProperties;
+}) {
+ return (
+
+ );
+});
+
+interface TourMediaProps extends Pick {
+ /** id for a video, so the panel can be labelled by it */
+ id?: string;
+ /** Called once the media's size is known - loaded, or failed to */
+ onSized?: (src: string) => void;
+}
+
+function TourMedia({ image, video, id, onSized }: TourMediaProps) {
+ if (video) {
+ const {
+ src,
+ type = 'native',
+ autoplay = true,
+ loop = true,
+ muted = true,
+ title = DEFAULT_EMBED_TITLE,
+ } = video;
+
+ if (type === 'embed') {
+ return (
+
+
+
+ );
+ }
+
+ return (
+
+ {/* Keyed on src: React does not reload a whose changes */}
+ onSized?.(src)}
+ onError={() => onSized?.(src)}
+ >
+
+
+
+ );
+ }
+
+ if (image) {
+ return (
+
+
onSized?.(image)} onError={() => onSized?.(image)} />
+
+ );
+ }
+
+ return null;
+}
+
+function RingProgress({ currentStep, totalSteps }: { currentStep: number; totalSteps: number }) {
+ const { size, center, radius, circumference, dashOffset } = getProgressRingGeometry(
+ currentStep,
+ totalSteps
+ );
+
+ return (
+
+
+
+
+
+ {`${currentStep}/${totalSteps}`}
+
+ );
+}
+
+function TourProgressIndicator({
+ stepInfo,
+ progress,
+}: {
+ stepInfo: CurrentTourStep;
+ progress: ResolvedProgressOptions;
+}) {
+ const currentStep = stepInfo.index + 1;
+ const totalSteps = stepInfo.total;
+
+ if (progress.render) {
+ return (
+
+ );
+ }
+
+ if (progress.type === 'ring') {
+ return ;
+ }
+
+ return {`Step ${currentStep} of ${totalSteps}`}
;
+}
+
+function TourNav({
+ stepInfo,
+ navigation,
+}: {
+ stepInfo: CurrentTourStep;
+ navigation: Required;
+}) {
+ return (
+
+ {!stepInfo.isFirst && (
+
+ {navigation.backLabel}
+
+ )}
+
+ {stepInfo.isLast ? navigation.finishLabel : navigation.nextLabel}
+
+
+ );
+}
+
+function TourMessage({ body, id }: { body: ResolvedStepBody; id?: string }) {
+ if (body.kind === 'html') {
+ return ;
+ }
+
+ return (
+
+ {body.value}
+
+ );
+}
+
+/**
+ * The tour panel: header (title and close), media, the step's body, and a footer with
+ * progress and Back/Next/Finish.
+ *
+ * Its buttons carry `data-tour-action` rather than click handlers - `useTour` handles
+ * them by delegation on the document.
+ */
+export function TourPanel({
+ step,
+ stepInfo,
+ navigation,
+ body,
+ progress,
+ titleId,
+ messageId,
+ mediaId,
+ fitMedia = false,
+ mediaMaxWidth,
+ mediaPlacement = 'top',
+}: TourPanelProps) {
+ const hasHeader = !!step.title || navigation.showClose;
+
+ // A panel sized by its media is hidden until that size is known, so it does not open
+ // at its minimum width and then jump
+ const mediaSrc = step.video?.src ?? step.image;
+ const [sizedSrc, setSizedSrc] = useState();
+ const mediaLoading = fitMedia && mediaSrc !== sizedSrc;
+ const showMessage = hasMessage(body);
+ const mediaOnly =
+ fitMedia && !step.title && !showMessage && !navigation.showControls && !progress.show;
+ const mediaBeside = mediaPlacement !== 'top';
+ const showControls = navigation.showControls;
+ const showProgress = progress.show;
+
+ return (
+
+ {hasHeader && (
+
+ {step.title ? (
+
+ {step.title}
+
+ ) : (
+
+ )}
+ {navigation.showClose && (
+
+ ×
+
+ )}
+
+ )}
+
+ {showMessage && (
+
+
+
+ )}
+ {showProgress ? (
+
+
+ {showControls && }
+
+ ) : (
+ showControls &&
+ )}
+
+ );
+}
+
+/**
+ * The tour panel, rendering whatever props the store currently holds
+ *
+ * This is the element `useTour` hands the tooltip, so a running step can be updated in
+ * place - see `TourPanelStore`.
+ */
+export function LiveTourPanel({ store }: { store: TourPanelStore }) {
+ const props = useSyncExternalStore(store.subscribe, store.getSnapshot);
+ return props && ;
+}
diff --git a/src/hooks/useTour/__tests__/TourPanel.test.tsx b/src/hooks/useTour/__tests__/TourPanel.test.tsx
new file mode 100644
index 0000000..a96eddc
--- /dev/null
+++ b/src/hooks/useTour/__tests__/TourPanel.test.tsx
@@ -0,0 +1,576 @@
+import { act, cleanup, fireEvent, render } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { CurrentTourStep, TourNavigation, TourStep } from '../../../types/tour';
+import { DEFAULT_NAVIGATION } from '../constants';
+import { LiveTourPanel, TourPanel, type TourPanelProps } from '../TourPanel';
+import { createTourPanelStore, DEFAULT_PROGRESS, type ResolvedProgressOptions } from '../utils';
+
+afterEach(() => {
+ cleanup();
+});
+
+const STEP: TourStep = { target: 'step1', text: 'Message' };
+
+/** Second of three steps unless overridden */
+const STEP_INFO: CurrentTourStep = {
+ index: 1,
+ target: 'step1',
+ content: 'Message',
+ isFirst: false,
+ isLast: false,
+ total: 3,
+};
+
+function renderPanel(overrides: Partial = {}) {
+ const props: TourPanelProps = {
+ step: STEP,
+ stepInfo: STEP_INFO,
+ navigation: DEFAULT_NAVIGATION,
+ body: { kind: 'text', value: 'Message' },
+ progress: DEFAULT_PROGRESS,
+ ...overrides,
+ };
+ return render( ).container;
+}
+
+const withNav = (navigation: Partial): Required => ({
+ ...DEFAULT_NAVIGATION,
+ ...navigation,
+});
+
+const withProgress = (progress: Partial): ResolvedProgressOptions => ({
+ ...DEFAULT_PROGRESS,
+ show: true,
+ ...progress,
+});
+
+const query = (container: HTMLElement, selector: string) =>
+ container.querySelector(selector);
+
+describe('TourPanel', () => {
+ describe('header', () => {
+ it('renders the title with the supplied id, and the close button', () => {
+ const container = renderPanel({
+ step: { ...STEP, title: 'Welcome' },
+ titleId: 'tour-title-1',
+ });
+
+ const title = query(container, '.tip-magic-tour-title');
+ expect(title?.textContent).toBe('Welcome');
+ expect(title?.id).toBe('tour-title-1');
+
+ const close = query(container, '.tip-magic-tour-close');
+ expect(close?.getAttribute('data-tour-action')).toBe('close');
+ expect(close?.getAttribute('aria-label')).toBe('Close');
+ });
+
+ it('labels the close button with closeLabel', () => {
+ const container = renderPanel({ navigation: withNav({ closeLabel: 'Dismiss' }) });
+
+ expect(query(container, '.tip-magic-tour-close')?.getAttribute('aria-label')).toBe('Dismiss');
+ });
+
+ it('omits the id when none is supplied', () => {
+ const container = renderPanel({ step: { ...STEP, title: 'Welcome' } });
+
+ expect(query(container, '.tip-magic-tour-title')?.hasAttribute('id')).toBe(false);
+ });
+
+ it('renders the title as text', () => {
+ const container = renderPanel({ step: { ...STEP, title: ' ' } });
+
+ expect(query(container, '.raw')).toBeNull();
+ expect(query(container, '.tip-magic-tour-title')?.textContent).toBe(' ');
+ });
+
+ it('keeps the close button on the right when there is no title', () => {
+ const container = renderPanel();
+
+ const header = query(container, '.tip-magic-tour-header');
+ expect(header?.children).toHaveLength(2);
+ expect(header?.lastElementChild?.className).toBe('tip-magic-tour-close');
+ });
+
+ it('renders no header without a title or close button', () => {
+ const container = renderPanel({ navigation: withNav({ showClose: false }) });
+
+ expect(query(container, '.tip-magic-tour-header')).toBeNull();
+ });
+ });
+
+ describe('media', () => {
+ it('renders an image', () => {
+ const container = renderPanel({ step: { ...STEP, image: 'pic.gif' } });
+
+ const image = query(container, '.tip-magic-tour-image img') as HTMLImageElement;
+ expect(image.getAttribute('src')).toBe('pic.gif');
+ expect(image.getAttribute('alt')).toBe('');
+ });
+
+ it('renders a native video that autoplays, loops and is muted by default', () => {
+ const container = renderPanel({ step: { ...STEP, video: { src: 'clip.mp4' } } });
+
+ const video = query(container, '.tip-magic-tour-video video') as HTMLVideoElement;
+ expect(video.autoplay).toBe(true);
+ expect(video.loop).toBe(true);
+ expect(video.muted).toBe(true);
+ // iOS Safari's autoplay policy reads the attribute, which React never writes
+ expect(video.hasAttribute('muted')).toBe(true);
+ expect(video.defaultMuted).toBe(true);
+ expect(video.hasAttribute('playsinline')).toBe(true);
+ expect(video.querySelector('source')?.getAttribute('src')).toBe('clip.mp4');
+ expect(query(container, '.tip-magic-tour-video-embed')).toBeNull();
+ });
+
+ it('honours the native video flags', () => {
+ const container = renderPanel({
+ step: { ...STEP, video: { src: 'clip.mp4', autoplay: false, loop: false, muted: false } },
+ });
+
+ const video = query(container, 'video') as HTMLVideoElement;
+ expect(video.autoplay).toBe(false);
+ expect(video.loop).toBe(false);
+ expect(video.muted).toBe(false);
+ expect(video.hasAttribute('muted')).toBe(false);
+ });
+
+ it('drops the muted attribute when the same video is unmuted', () => {
+ const props: TourPanelProps = {
+ step: { ...STEP, video: { src: 'clip.mp4' } },
+ stepInfo: STEP_INFO,
+ navigation: DEFAULT_NAVIGATION,
+ body: { kind: 'text', value: 'Message' },
+ progress: DEFAULT_PROGRESS,
+ };
+ const { container, rerender } = render( );
+ const video = query(container, 'video') as HTMLVideoElement;
+ expect(video.hasAttribute('muted')).toBe(true);
+
+ rerender(
+
+ );
+
+ expect(query(container, 'video')).toBe(video);
+ expect(video.hasAttribute('muted')).toBe(false);
+ expect(video.defaultMuted).toBe(false);
+ expect(video.muted).toBe(false);
+
+ rerender( );
+
+ expect(video.hasAttribute('muted')).toBe(true);
+ });
+
+ it('renders an embed in an iframe with a semicolon-separated allow list', () => {
+ const container = renderPanel({
+ step: { ...STEP, video: { src: 'https://example.com/v', type: 'embed' } },
+ });
+
+ const iframe = query(container, '.tip-magic-tour-video.tip-magic-tour-video-embed iframe');
+ expect(iframe?.getAttribute('src')).toBe('https://example.com/v');
+ expect(iframe?.getAttribute('allow')).toMatch(/^accelerometer; autoplay;/);
+ expect(iframe?.hasAttribute('allowfullscreen')).toBe(true);
+ });
+
+ it('gives an embed an accessible name, defaulting to "Tour video"', () => {
+ const container = renderPanel({
+ step: { ...STEP, video: { src: 'https://example.com/v', type: 'embed' } },
+ });
+ expect(query(container, 'iframe')?.getAttribute('title')).toBe('Tour video');
+
+ cleanup();
+ const titled = renderPanel({
+ step: {
+ ...STEP,
+ video: { src: 'https://example.com/v', type: 'embed', title: 'Setting up alerts' },
+ },
+ });
+ expect(query(titled, 'iframe')?.getAttribute('title')).toBe('Setting up alerts');
+ });
+
+ it('prefers a video over an image', () => {
+ const container = renderPanel({
+ step: { ...STEP, image: 'pic.gif', video: { src: 'clip.mp4' } },
+ });
+
+ expect(query(container, '.tip-magic-tour-image')).toBeNull();
+ expect(query(container, 'video')).not.toBeNull();
+ });
+
+ it('keeps a src inside its attribute', () => {
+ const container = renderPanel({ step: { ...STEP, image: 'x.png" onerror="alert(1)' } });
+
+ const image = query(container, 'img');
+ expect(image?.hasAttribute('onerror')).toBe(false);
+ expect(image?.getAttribute('src')).toBe('x.png" onerror="alert(1)');
+ });
+
+ it('renders no media for a step without any', () => {
+ const container = renderPanel();
+
+ expect(query(container, '.tip-magic-tour-image, .tip-magic-tour-video')).toBeNull();
+ });
+ });
+
+ describe('message', () => {
+ it('renders text as text', () => {
+ const container = renderPanel({ body: { kind: 'text', value: 'Tom & Jerry ' } });
+
+ const message = query(container, '.tip-magic-tour-body > .tip-magic-tour-message');
+ expect(message?.textContent).toBe('Tom & Jerry ');
+ expect(message?.querySelector('b')).toBeNull();
+ });
+
+ it('puts the supplied id on the message, for the panel to be labelled by', () => {
+ const text = renderPanel({ messageId: 'tour-message-1' });
+ expect(query(text, '.tip-magic-tour-message')?.id).toBe('tour-message-1');
+
+ cleanup();
+ const html = renderPanel({
+ messageId: 'tour-message-1',
+ body: { kind: 'html', value: 'bold ' },
+ });
+ expect(query(html, '.tip-magic-tour-message')?.id).toBe('tour-message-1');
+ });
+
+ it('injects html content as HTML', () => {
+ const container = renderPanel({ body: { kind: 'html', value: 'bold ' } });
+
+ expect(query(container, '.tip-magic-tour-message .raw')?.textContent).toBe('bold');
+ });
+
+ it('renders a React body, and keeps its event handlers', () => {
+ const onClick = vi.fn();
+ const container = renderPanel({
+ body: {
+ kind: 'node',
+ value: (
+
+ Read the notes , then{' '}
+
+ act
+
+
+ ),
+ },
+ });
+
+ const message = query(container, '.tip-magic-tour-message');
+ expect(message?.querySelector('em')?.textContent).toBe('notes');
+
+ fireEvent.click(message?.querySelector('button') as HTMLElement);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('navigation', () => {
+ it('renders no buttons but Close when controls are off', () => {
+ const container = renderPanel();
+
+ expect(query(container, '.tip-magic-tour-nav')).toBeNull();
+ expect(container.querySelectorAll('button')).toHaveLength(1);
+ });
+
+ it('renders only Next on the first step', () => {
+ const container = renderPanel({
+ stepInfo: { ...STEP_INFO, index: 0, isFirst: true },
+ navigation: withNav({ showControls: true }),
+ });
+
+ expect(query(container, '.tip-magic-tour-btn-back')).toBeNull();
+ const next = query(container, '.tip-magic-tour-btn.tip-magic-tour-btn-next');
+ expect(next?.textContent).toBe('Next');
+ expect(next?.getAttribute('data-tour-action')).toBe('next');
+ });
+
+ it('renders Back and Next on a middle step', () => {
+ const container = renderPanel({ navigation: withNav({ showControls: true }) });
+
+ const back = query(container, '.tip-magic-tour-btn.tip-magic-tour-btn-back');
+ expect(back?.textContent).toBe('Back');
+ expect(back?.getAttribute('data-tour-action')).toBe('prev');
+ expect(query(container, '.tip-magic-tour-btn-next')?.textContent).toBe('Next');
+ });
+
+ it('renders Finish on the last step', () => {
+ const container = renderPanel({
+ stepInfo: { ...STEP_INFO, index: 2, isLast: true },
+ navigation: withNav({ showControls: true }),
+ });
+
+ const finish = query(container, '.tip-magic-tour-btn-next');
+ expect(finish?.textContent).toBe('Finish');
+ expect(finish?.getAttribute('data-tour-action')).toBe('finish');
+ });
+
+ it('renders custom labels as text', () => {
+ const container = renderPanel({
+ navigation: withNav({ showControls: true, nextLabel: 'Go ', backLabel: 'Up ' }),
+ });
+
+ const next = query(container, '.tip-magic-tour-btn-next');
+ expect(next?.textContent).toBe('Go ');
+ expect(next?.querySelector('b')).toBeNull();
+ expect(query(container, '.tip-magic-tour-btn-back')?.textContent).toBe('Up ');
+ });
+
+ it('renders a custom finish label as text', () => {
+ const container = renderPanel({
+ stepInfo: { ...STEP_INFO, index: 2, isLast: true },
+ navigation: withNav({ showControls: true, finishLabel: 'Done ' }),
+ });
+
+ expect(query(container, '.tip-magic-tour-btn-next')?.textContent).toBe('Done ');
+ });
+
+ it('gives every button an explicit type', () => {
+ const container = renderPanel({ navigation: withNav({ showControls: true }) });
+
+ const buttons = container.querySelectorAll('button');
+ expect(buttons).toHaveLength(3);
+ buttons.forEach((button) => expect(button.getAttribute('type')).toBe('button'));
+ });
+ });
+
+ describe('primary action marker', () => {
+ it('marks Next and nothing else', () => {
+ const container = renderPanel({ navigation: withNav({ showControls: true }) });
+
+ const marked = container.querySelectorAll('[data-tip-magic-primary]');
+ expect(marked).toHaveLength(1);
+ expect(marked[0].getAttribute('data-tour-action')).toBe('next');
+ });
+
+ it('marks Finish on the last step', () => {
+ const container = renderPanel({
+ stepInfo: { ...STEP_INFO, index: 2, isLast: true },
+ navigation: withNav({ showControls: true }),
+ });
+
+ expect(query(container, '[data-tip-magic-primary]')?.getAttribute('data-tour-action')).toBe(
+ 'finish'
+ );
+ });
+
+ it('never marks Close, even when it is the only button', () => {
+ const container = renderPanel();
+
+ expect(query(container, '.tip-magic-tour-close')).not.toBeNull();
+ expect(query(container, '[data-tip-magic-primary]')).toBeNull();
+ });
+ });
+
+ describe('progress', () => {
+ it('renders no footer without progress or controls', () => {
+ const container = renderPanel();
+
+ expect(query(container, '.tip-magic-tour-footer')).toBeNull();
+ });
+
+ it('renders the nav without a footer when there is no progress', () => {
+ const container = renderPanel({ navigation: withNav({ showControls: true }) });
+
+ expect(query(container, '.tip-magic-tour-footer')).toBeNull();
+ expect(query(container, '.tip-magic-tour-content > .tip-magic-tour-nav')).not.toBeNull();
+ });
+
+ it('renders step text progress in a footer', () => {
+ const container = renderPanel({ progress: withProgress({}) });
+
+ const progress = query(container, '.tip-magic-tour-footer > .tip-magic-tour-progress');
+ expect(progress?.textContent).toBe('Step 2 of 3');
+ expect(query(container, '.tip-magic-tour-nav')).toBeNull();
+ });
+
+ it('renders progress and the nav together in the footer', () => {
+ const container = renderPanel({
+ navigation: withNav({ showControls: true }),
+ progress: withProgress({}),
+ });
+
+ const footer = query(container, '.tip-magic-tour-footer');
+ expect(footer?.children[0].className).toBe('tip-magic-tour-progress');
+ expect(footer?.children[1].className).toBe('tip-magic-tour-nav');
+ });
+
+ it('renders a ring', () => {
+ const container = renderPanel({ progress: withProgress({ type: 'ring' }) });
+
+ const ring = query(container, '.tip-magic-tour-progress-ring');
+ expect(ring?.querySelector('.tip-magic-tour-progress-ring-bg')).not.toBeNull();
+ expect(ring?.querySelector('.tip-magic-tour-progress-ring-text')?.textContent).toBe('2/3');
+
+ const fill = ring?.querySelector('.tip-magic-tour-progress-ring-fill');
+ const circumference = Number(fill?.getAttribute('stroke-dasharray'));
+ expect(Number(fill?.getAttribute('stroke-dashoffset'))).toBeCloseTo(circumference / 3);
+ });
+
+ it('injects a custom render as HTML, ahead of the built-in types', () => {
+ const render = vi.fn(
+ ({ currentStep, totalSteps }: { currentStep: number; totalSteps: number }) =>
+ `${currentStep}-${totalSteps} `
+ );
+ const container = renderPanel({ progress: withProgress({ type: 'ring', render }) });
+
+ expect(render).toHaveBeenCalledWith({ currentStep: 2, totalSteps: 3 });
+ expect(query(container, '.tip-magic-tour-footer .custom')?.textContent).toBe('2-3');
+ expect(query(container, '.tip-magic-tour-progress-ring')).toBeNull();
+ });
+ });
+});
+
+describe('LiveTourPanel', () => {
+ const propsWith = (text: string): TourPanelProps => ({
+ step: STEP,
+ stepInfo: STEP_INFO,
+ navigation: DEFAULT_NAVIGATION,
+ body: { kind: 'text', value: text },
+ progress: DEFAULT_PROGRESS,
+ });
+
+ it('re-renders the same panel when the store is set', () => {
+ const store = createTourPanelStore();
+ store.set(propsWith('Before'));
+ const { container } = render( );
+ const panel = query(container, '.tip-magic-tour-content');
+
+ act(() => {
+ store.set(propsWith('After'));
+ });
+
+ expect(query(container, '.tip-magic-tour-message')?.textContent).toBe('After');
+ expect(query(container, '.tip-magic-tour-content')).toBe(panel);
+ });
+});
+
+describe('a panel sized by its media', () => {
+ const content = (container: HTMLElement) =>
+ container.querySelector('.tip-magic-tour-content') as HTMLElement;
+
+ it('marks itself, and stays marked loading until the image has loaded', () => {
+ const container = renderPanel({ step: { ...STEP, image: 'pic.png' }, fitMedia: true });
+
+ expect(content(container).hasAttribute('data-tip-magic-media-fit')).toBe(true);
+ expect(content(container).hasAttribute('data-tip-magic-media-loading')).toBe(true);
+
+ fireEvent.load(query(container, 'img') as HTMLElement);
+
+ expect(content(container).hasAttribute('data-tip-magic-media-loading')).toBe(false);
+ });
+
+ it('stops loading when the image fails, rather than staying hidden', () => {
+ const container = renderPanel({ step: { ...STEP, image: 'missing.png' }, fitMedia: true });
+
+ fireEvent.error(query(container, 'img') as HTMLElement);
+
+ expect(content(container).hasAttribute('data-tip-magic-media-loading')).toBe(false);
+ });
+
+ it("waits for a native video's metadata", () => {
+ const container = renderPanel({
+ step: { ...STEP, video: { src: 'clip.mp4' } },
+ fitMedia: true,
+ });
+ expect(content(container).hasAttribute('data-tip-magic-media-loading')).toBe(true);
+
+ fireEvent.loadedMetadata(query(container, 'video') as HTMLElement);
+
+ expect(content(container).hasAttribute('data-tip-magic-media-loading')).toBe(false);
+ });
+
+ it('loads again when the image changes in place', () => {
+ const props: TourPanelProps = {
+ step: { ...STEP, image: 'one.png' },
+ stepInfo: STEP_INFO,
+ navigation: DEFAULT_NAVIGATION,
+ body: { kind: 'text', value: 'Message' },
+ progress: DEFAULT_PROGRESS,
+ fitMedia: true,
+ };
+ const { container, rerender } = render( );
+ fireEvent.load(query(container, 'img') as HTMLElement);
+
+ rerender( );
+
+ expect(content(container).hasAttribute('data-tip-magic-media-loading')).toBe(true);
+ });
+
+ it('passes an explicit width cap to the stylesheet', () => {
+ const container = renderPanel({
+ step: { ...STEP, image: 'pic.png' },
+ fitMedia: true,
+ mediaMaxWidth: 600,
+ });
+
+ expect(content(container).style.getPropertyValue('--tip-magic-tour-media-max-width')).toBe(
+ '600px'
+ );
+ });
+
+ it('marks a panel that is nothing but its media', () => {
+ const mediaOnly = renderPanel({
+ step: { video: { src: 'clip.mp4' } },
+ body: { kind: 'html', value: '' },
+ fitMedia: true,
+ });
+ expect(content(mediaOnly).hasAttribute('data-tip-magic-media-only')).toBe(true);
+
+ cleanup();
+ const withText = renderPanel({ step: { ...STEP, image: 'pic.png' }, fitMedia: true });
+ expect(content(withText).hasAttribute('data-tip-magic-media-only')).toBe(false);
+ });
+
+ it('renders nothing but the media for a panel that is only media', () => {
+ const container = renderPanel({
+ step: { video: { src: 'clip.mp4' } },
+ body: { kind: 'html', value: '' },
+ navigation: withNav({ showClose: false }),
+ fitMedia: true,
+ });
+
+ expect(Array.from(content(container).children).map((child) => child.className)).toEqual([
+ 'tip-magic-tour-video',
+ ]);
+ expect(query(container, '.tip-magic-tour-header')).toBeNull();
+ expect(query(container, '.tip-magic-tour-body, .tip-magic-tour-message')).toBeNull();
+ expect(query(container, '.tip-magic-tour-footer, .tip-magic-tour-nav')).toBeNull();
+ });
+
+ it('leaves a panel that is not sized by its media unmarked', () => {
+ const container = renderPanel({ step: { ...STEP, image: 'pic.png' } });
+
+ expect(content(container).hasAttribute('data-tip-magic-media-fit')).toBe(false);
+ expect(content(container).hasAttribute('data-tip-magic-media-loading')).toBe(false);
+ });
+});
+
+describe('media placement', () => {
+ const content = (container: HTMLElement) =>
+ container.querySelector('.tip-magic-tour-content') as HTMLElement;
+
+ it.each(['left', 'right'] as const)('marks a panel with its media to the %s', (placement) => {
+ const container = renderPanel({
+ step: { ...STEP, title: 'News', image: 'pic.png' },
+ mediaPlacement: placement,
+ });
+
+ expect(content(container).getAttribute('data-tip-magic-media-placement')).toBe(placement);
+ });
+
+ it('leaves a panel with its media on top unmarked', () => {
+ const container = renderPanel({ step: { ...STEP, image: 'pic.png' }, mediaPlacement: 'top' });
+
+ expect(content(container).hasAttribute('data-tip-magic-media-placement')).toBe(false);
+ });
+
+ it('passes an explicit width cap to the stylesheet for media beside the text', () => {
+ const container = renderPanel({
+ step: { ...STEP, image: 'pic.png' },
+ mediaPlacement: 'left',
+ mediaMaxWidth: 700,
+ });
+
+ expect(content(container).style.getPropertyValue('--tip-magic-tour-media-max-width')).toBe(
+ '700px'
+ );
+ });
+});
diff --git a/src/hooks/useTour/__tests__/backdropManager.test.ts b/src/hooks/useTour/__tests__/backdropManager.test.ts
index 3865d77..78af7e7 100644
--- a/src/hooks/useTour/__tests__/backdropManager.test.ts
+++ b/src/hooks/useTour/__tests__/backdropManager.test.ts
@@ -35,6 +35,14 @@ describe('BackdropManager', () => {
});
describe('show', () => {
+ it('should show a backdrop with nothing elevated when there is no target', () => {
+ manager.show(null);
+
+ expect(document.querySelector(`.${TOUR_CSS_CLASSES.BACKDROP}`)).not.toBeNull();
+ expect(document.querySelector(`[${TOUR_DATA_ATTRIBUTES.FOCUS}]`)).toBeNull();
+ expect(manager.currentFocusTarget).toBeNull();
+ });
+
it('should create backdrop element in DOM', () => {
manager.show(targetElement);
diff --git a/src/hooks/useTour/__tests__/buildTourContent.test.ts b/src/hooks/useTour/__tests__/buildTourContent.test.ts
deleted file mode 100644
index 8690496..0000000
--- a/src/hooks/useTour/__tests__/buildTourContent.test.ts
+++ /dev/null
@@ -1,567 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import type { CurrentTourStep, TourNavigation, TourStep } from '../../../types/tour';
-import { DEFAULT_NAVIGATION, TOUR_CSS_CLASSES } from '../constants';
-import {
- buildFooterHtml,
- buildHeaderHtml,
- buildMediaHtml,
- buildNavHtml,
- buildProgressHtml,
- buildRingProgressHtml,
- buildStepsProgressHtml,
- buildTourContent,
-} from '../utils/buildTourContent';
-import type { ResolvedProgressOptions } from '../utils/tourNavigation';
-
-describe('buildTourContent utilities', () => {
- describe('buildMediaHtml', () => {
- it('should return empty string when no media', () => {
- const step: TourStep = { target: 'step1', content: 'Content' };
- expect(buildMediaHtml(step)).toBe('');
- });
-
- it('should build image HTML', () => {
- const step: TourStep = {
- target: 'step1',
- content: 'Content',
- image: 'https://example.com/image.png',
- };
-
- const result = buildMediaHtml(step);
- expect(result).toContain(TOUR_CSS_CLASSES.IMAGE);
- expect(result).toContain('src="https://example.com/image.png"');
- expect(result).toContain(' {
- const step: TourStep = {
- target: 'step1',
- content: 'Content',
- video: { src: 'video.mp4' },
- };
-
- const result = buildMediaHtml(step);
- expect(result).toContain(TOUR_CSS_CLASSES.VIDEO);
- expect(result).not.toContain(TOUR_CSS_CLASSES.VIDEO_EMBED);
- expect(result).toContain(' {
- const step: TourStep = {
- target: 'step1',
- content: 'Content',
- video: { src: 'video.mp4', autoplay: false },
- };
-
- const result = buildMediaHtml(step);
- expect(result).not.toContain('autoplay');
- expect(result).toContain('loop');
- expect(result).toContain('muted');
- });
-
- it('should build embed video HTML', () => {
- const step: TourStep = {
- target: 'step1',
- content: 'Content',
- video: { src: 'https://youtube.com/embed/abc', type: 'embed' },
- };
-
- const result = buildMediaHtml(step);
- expect(result).toContain(TOUR_CSS_CLASSES.VIDEO);
- expect(result).toContain(TOUR_CSS_CLASSES.VIDEO_EMBED);
- expect(result).toContain('