Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(lab): add Tour (product-tour / NUX walkthrough) (#4579)

freddymeta12db2a1d7e5d
diff --git a/apps/storybook/stories/Tour.stories.tsx b/apps/storybook/stories/Tour.stories.tsx
new file mode 100644
index 0000000000..72f9773621
--- /dev/null
+++ b/apps/storybook/stories/Tour.stories.tsx
@@ -0,0 +1,190 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useRef, useState} from 'react';
+import {Tour, TourStep} from '@astryxdesign/lab';
+import type {LayerAlignment, LayerPlacement} from '@astryxdesign/core/Layer';
+import {Button} from '@astryxdesign/core/Button';
+import {Heading} from '@astryxdesign/core/Heading';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
+import {Theme, defineTheme} from '@astryxdesign/core/theme';
+
+const meta: Meta<typeof Tour> = {
+ title: 'Lab/Tour',
+ component: Tour,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'fullscreen',
+ },
+ decorators: [
+ Story => (
+ <div style={{minHeight: 480, padding: 32}}>
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof Tour>;
+
+export const Showcase: Story = {
+ render: () => {
+ const [isActive, setIsActive] = useState(false);
+ const saveRef = useRef<HTMLButtonElement>(null);
+ const shareRef = useRef<HTMLButtonElement>(null);
+ const settingsRef = useRef<HTMLButtonElement>(null);
+
+ return (
+ <VStack gap={4}>
+ <HStack gap={2}>
+ <Button ref={saveRef} variant="secondary" label="Save" />
+ <Button ref={shareRef} variant="secondary" label="Share" />
+ <Button ref={settingsRef} variant="secondary" label="Settings" />
+ </HStack>
+
+ <Button label="Start tour" onClick={() => setIsActive(true)} />
+
+ <Tour
+ isActive={isActive}
+ hasBackdrop
+ isStepCountShown
+ onDismiss={() => setIsActive(false)}>
+ <TourStep targetRef={saveRef} heading="Save your work">
+ Changes save automatically to the cloud as you go.
+ </TourStep>
+ <TourStep targetRef={shareRef} heading="Share with your team">
+ Invite teammates and manage access from here.
+ </TourStep>
+ <TourStep targetRef={settingsRef} heading="Tune your setup">
+ Adjust preferences and defaults in Settings.
+ </TourStep>
+ </Tour>
+ </VStack>
+ );
+ },
+};
+
+export const WithoutBackdrop: Story = {
+ render: () => {
+ const [isActive, setIsActive] = useState(false);
+ const targetRef = useRef<HTMLButtonElement>(null);
+
+ return (
+ <VStack gap={4}>
+ <Heading level={3}>Feature callout</Heading>
+ <Text type="body">
+ A single-step tour with no dimmed background — a lightweight
+ coachmark.
+ </Text>
+ <Button ref={targetRef} variant="secondary" label="New feature" />
+ <Button label="Highlight it" onClick={() => setIsActive(true)} />
+
+ <Tour isActive={isActive} onDismiss={() => setIsActive(false)}>
+ <TourStep
+ targetRef={targetRef}
+ heading="Try the new feature"
+ placement="below">
+ We just shipped this — click to explore.
+ </TourStep>
+ </Tour>
+ </VStack>
+ );
+ },
+};
+
+// A scoped theme with a vivid magenta accent. Because the highlight is promoted
+// into the top layer IN PLACE (not portaled out of the tree), it stays inside
+// this <Theme> subtree and the ring inherits the scoped accent — verifying the
+// tour is themeable, not just under the root theme.
+const magentaTheme = defineTheme({
+ name: 'tour-magenta-demo',
+ tokens: {
+ '--color-accent': ['#D6006E', '#FF4FA3'],
+ },
+});
+
+export const ScopedTheme: Story = {
+ name: 'Themed ring (scoped theme)',
+ render: () => {
+ const [isActive, setIsActive] = useState(false);
+ const targetRef = useRef<HTMLButtonElement>(null);
+
+ return (
+ <Theme theme={magentaTheme} mode="light">
+ <VStack gap={4}>
+ <Heading level={3}>Scoped theme</Heading>
+ <Text type="body">
+ This subtree uses a scoped theme with a magenta accent. The
+ highlight ring picks it up because the overlay is promoted in place,
+ inside the Theme — not portaled to the body.
+ </Text>
+ <Button ref={targetRef} variant="secondary" label="New feature" />
+ <Button label="Highlight it" onClick={() => setIsActive(true)} />
+
+ <Tour
+ isActive={isActive}
+ hasBackdrop
+ onDismiss={() => setIsActive(false)}>
+ <TourStep targetRef={targetRef} heading="Themed highlight">
+ The ring uses this theme&apos;s accent color.
+ </TourStep>
+ </Tour>
+ </VStack>
+ </Theme>
+ );
+ },
+};
+
+// Interactive placement + alignment. Use the Controls panel to move the callout
+// to any side of the centered target and align it start / center / end along
+// that side. Args here drive the TourStep (not the Tour controller), so this
+// story is typed against its own arg shape.
+interface PlacementArgs {
+ placement: LayerPlacement;
+ alignment: LayerAlignment;
+}
+
+export const Placement: StoryObj<PlacementArgs> = {
+ name: 'Placement & alignment',
+ argTypes: {
+ placement: {
+ control: 'select',
+ options: ['above', 'below', 'start', 'end'],
+ description: 'Which side of the target the callout sits on',
+ },
+ alignment: {
+ control: 'select',
+ options: ['start', 'center', 'end'],
+ description: 'How the callout aligns along the placement side',
+ },
+ },
+ args: {
+ placement: 'below',
+ alignment: 'center',
+ },
+ render: ({placement, alignment}: PlacementArgs) => {
+ const [isActive, setIsActive] = useState(true);
+ const targetRef = useRef<HTMLButtonElement>(null);
+
+ return (
+ <VStack gap={4} align="center" justify="center" style={{minHeight: 460}}>
+ <Button ref={targetRef} variant="secondary" label="Target" />
+ {!isActive && (
+ <Button label="Show step" onClick={() => setIsActive(true)} />
+ )}
+ <Tour isActive={isActive} onDismiss={() => setIsActive(false)}>
+ <TourStep
+ targetRef={targetRef}
+ heading="Positioned callout"
+ placement={placement}
+ alignment={alignment}>
+ placement=&quot;{placement}&quot; · alignment=&quot;{alignment}
+ &quot;
+ </TourStep>
+ </Tour>
+ </VStack>
+ );
+ },
+};
diff --git a/packages/lab/src/Tour/Tour.doc.mjs b/packages/lab/src/Tour/Tour.doc.mjs
new file mode 100644
index 0000000000..956149f1ef
--- /dev/null
+++ b/packages/lab/src/Tour/Tour.doc.mjs
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+
+export const docs = {
+ name: 'Tour',
+ displayName: 'Tour',
+ category: 'Feedback & Status',
+ keywords: ["tour","nux","onboarding","walkthrough","product tour","coachmark","spotlight","guide","feature step","step"],
+ description:
+ 'A guided product tour (NUX / onboarding). Tour is a controller that steps a user through a sequence of spotlight callouts anchored to elements on the page. It renders no chrome itself — it owns the active-step state and shares it with declaratively-nested TourStep children (step order follows the children). Experimental: lands in lab first (facebook/astryx#4239).',
+ components: [
+ {
+ name: 'Tour',
+ displayName: 'Tour',
+ description:
+ 'Controller for a guided tour. Coordinates the active step among its TourStep children, exposes advance / retreat / complete / dismiss, and optionally dims the page around the active step (spotlight cutout). Controlled via isActive — the consumer owns "has this user seen the tour?".',
+ props: [
+ {
+ name: 'isActive',
+ type: 'boolean',
+ description:
+ 'Whether the tour is running. When false nothing renders and the tour resets to the first step, so it restarts cleanly next time it becomes active.',
+ required: true,
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description:
+ 'The tour steps — TourStep elements. Step order follows their order here; only the active step renders its callout.',
+ slotElements: [{__element: 'TourStep', props: {heading: 'Step'}, children: 'Step body'}],
+ },
+ {
+ name: 'onDismiss',
+ type: '(source: TourDismissSource) => void',
+ description:
+ "Called on every exit, with the reason ('backdrop' | 'escape' | 'close' | 'skip' | 'complete'). The consumer flips isActive to false in response, and can branch on the source to distinguish a successful finish from an early exit.",
+ required: true,
+ },
+ {
+ name: 'hasBackdrop',
+ type: 'boolean',
+ description:
+ 'Dim the page around the active step as a spotlight cutout — the target stays lit while everything else darkens. Use for modal-style steps that demand focus; leave off for a lightweight coachmark that only rings the target.',
+ default: 'false',
+ },
+ {
+ name: 'isStepCountShown',
+ type: 'boolean',
+ description: 'Show the step count ("2 of 5") in each step.',
+ default: 'false',
+ },
+ ],
+ },
+ {
+ name: 'TourStep',
+ displayName: 'Tour Step',
+ description:
+ 'A single spotlight step. Highlights a target element with a ring drawn as a separate overlay (the target is never restyled) and renders a callout anchored to it (via the core Popover), with a heading, body, optional step progress, and back / next / close controls. Registers with the parent Tour on mount and renders its callout only while active.',
+ props: [
+ {
+ name: 'targetRef',
+ type: 'RefObject<HTMLElement>',
+ description:
+ "Ref to the element this step points at. The callout anchors to it like a Popover trigger; it must be a <button> or [role=\"button\"] element (Popover's anchorRef contract).",
+ required: true,
+ },
+ {
+ name: 'heading',
+ type: 'ReactNode',
+ description: 'Step heading.',
+ required: true,
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description: 'Step body content.',
+ },
+ {
+ name: 'placement',
+ type: "'above' | 'below' | 'start' | 'end'",
+ description: 'Which side of the target the callout sits on.',
+ default: "'below'",
+ },
+ {
+ name: 'alignment',
+ type: "'start' | 'center' | 'end'",
+ description:
+ 'How the callout aligns along the placement side (e.g. with placement="below": start left-aligns under the target, center centers, end right-aligns).',
+ default: "'start'",
+ },
+ ],
+ },
+ ],
+ usage: {
+ description:
+ 'Use a Tour to introduce a feature or onboard a user through a few key parts of the UI. Compose it from TourStep children, each pointing at an element via targetRef; the Tour advances through them with Next/Back and ends on Done. It is controlled — keep isActive in your own state and persist "has seen this tour" yourself (the component only reports dismissal via onDismiss). Built on the existing Popover/Layer anchoring and overlay tokens rather than a bespoke positioning engine.',
+ bestPractices: [
+ { guidance: true, description: 'Keep tours short — a few high-value steps. Long tours get skipped.' },
+ { guidance: true, description: 'Persist completion yourself (from onDismiss) so a user does not see the same tour on every visit.' },
+ { guidance: true, description: 'Point each step at a stable, visible element; ensure the target is on-screen before its step becomes active.' },
+ { guidance: false, description: 'Gate essential, must-see information behind a tour step — users can dismiss it; put critical info inline.' },
+ { guidance: false, description: 'Use a tour as a substitute for clear UI — fix confusing interfaces rather than narrating them.' },
+ ],
+ },
+};
diff --git a/packages/lab/src/Tour/Tour.test.tsx b/packages/lab/src/Tour/Tour.test.tsx
new file mode 100644
index 0000000000..a80ddd629f
--- /dev/null
+++ b/packages/lab/src/Tour/Tour.test.tsx
@@ -0,0 +1,261 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tour.test.tsx
+ * @input Uses vitest, @testing-library/react, @testing-library/user-event, Tour + TourStep
+ * @output Unit tests for the Tour controller: step registration/order, advance,
+ * dismiss reasons, reset, backdrop, and useTour.
+ * @position Testing; validates Tour.tsx / TourStep.tsx behavior
+ *
+ * SYNC: When Tour.tsx / TourStep.tsx change, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi, beforeAll} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {useRef, useState} from 'react';
+import {Tour} from './Tour';
+import {TourStep} from './TourStep';
+import {useTour} from './useTour';
+
+// jsdom does not implement <dialog> showModal/close, which the Popover the
+// steps render on relies on.
+beforeAll(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+// A small harness: two targets + a two-step tour, isActive controlled locally
+// so onDismiss can turn it off like a real consumer.
+function TwoStepTour({
+ hasBackdrop = false,
+ isStepCountShown = false,
+ onDismiss,
+}: {
+ hasBackdrop?: boolean;
+ isStepCountShown?: boolean;
+ onDismiss?: (source: string) => void;
+}) {
+ const [isActive, setIsActive] = useState(true);
+ const aRef = useRef<HTMLButtonElement>(null);
+ const bRef = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button type="button" ref={aRef}>
+ Target A
+ </button>
+ <button type="button" ref={bRef}>
+ Target B
+ </button>
+ <Tour
+ isActive={isActive}
+ hasBackdrop={hasBackdrop}
+ isStepCountShown={isStepCountShown}
+ onDismiss={source => {
+ onDismiss?.(source);
+ if (source !== 'skip') {
+ setIsActive(false);
+ }
+ }}>
+ <TourStep targetRef={aRef} heading="First">
+ First body
+ </TourStep>
+ <TourStep targetRef={bRef} heading="Second">
+ Second body
+ </TourStep>
+ </Tour>
+ </>
+ );
+}
+
+describe('Tour', () => {
+ it('shows only the first step initially', () => {
+ render(<TwoStepTour />);
+ expect(screen.getByText('First')).toBeInTheDocument();
+ expect(screen.queryByText('Second')).not.toBeInTheDocument();
+ });
+
+ it('advances to the next step on Next', () => {
+ render(<TwoStepTour />);
+ fireEvent.click(screen.getByText('Next'));
+ expect(screen.queryByText('First')).not.toBeInTheDocument();
+ expect(screen.getByText('Second')).toBeInTheDocument();
+ });
+
+ it('goes back on Back', () => {
+ render(<TwoStepTour />);
+ fireEvent.click(screen.getByText('Next'));
+ fireEvent.click(screen.getByText('Back'));
+ expect(screen.getByText('First')).toBeInTheDocument();
+ });
+
+ it('hides Back on the first step', () => {
+ render(<TwoStepTour />);
+ expect(screen.queryByText('Back')).not.toBeInTheDocument();
+ });
+
+ it('labels the final step action "Done" and earlier steps "Next"', () => {
+ render(<TwoStepTour />);
+ expect(screen.getByText('Next')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Next'));
+ expect(screen.getByText('Done')).toBeInTheDocument();
+ });
+
+ it('dismisses with "complete" when advancing past the last step', () => {
+ const onDismiss = vi.fn();
+ render(<TwoStepTour onDismiss={onDismiss} />);
+ fireEvent.click(screen.getByText('Next')); // → step 2
+ fireEvent.click(screen.getByText('Done')); // → complete
+ expect(onDismiss).toHaveBeenCalledWith('complete');
+ // Tour turned off — no step content remains.
+ expect(screen.queryByText('First')).not.toBeInTheDocument();
+ expect(screen.queryByText('Second')).not.toBeInTheDocument();
+ });
+
+ it('shows step count when isStepCountShown is set', () => {
+ render(<TwoStepTour isStepCountShown />);
+ expect(screen.getByText('1 of 2')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Next'));
+ expect(screen.getByText('2 of 2')).toBeInTheDocument();
+ });
+
+ it('does not show step count by default', () => {
+ render(<TwoStepTour />);
+ expect(screen.queryByText('1 of 2')).not.toBeInTheDocument();
+ });
+
+ it('renders a highlight overlay for the active step; backdrop only when set', () => {
+ const {rerender} = render(<TwoStepTour />);
+ // Highlight always present for the active step.
+ expect(screen.getByTestId('tour-highlight')).toBeInTheDocument();
+ // No dim without hasBackdrop — a plain coachmark rings the target only.
+ expect(screen.queryByTestId('tour-backdrop')).not.toBeInTheDocument();
+ rerender(<TwoStepTour hasBackdrop />);
+ expect(screen.getByTestId('tour-highlight')).toBeInTheDocument();
+ expect(screen.getByTestId('tour-backdrop')).toBeInTheDocument();
+ });
+
+ it('dismisses with "backdrop" when the backdrop is clicked', () => {
+ const onDismiss = vi.fn();
+ render(<TwoStepTour hasBackdrop onDismiss={onDismiss} />);
+ fireEvent.click(screen.getByTestId('tour-backdrop'));
+ expect(onDismiss).toHaveBeenCalledWith('backdrop');
+ });
+
+ it('does not restyle the target element (highlight is a separate overlay)', () => {
+ render(<TwoStepTour hasBackdrop />);
+ // The consumer's targets keep their own classes untouched — the ring is
+ // drawn by the overlay, not by mutating the target (which loses the
+ // cascade to the target's own styles).
+ expect(screen.getByText('Target A').className).toBe('');
+ expect(screen.getByText('Target B').className).toBe('');
+ });
+
+ it('moves the highlight across steps and clears it when the tour ends', () => {
+ render(<TwoStepTour hasBackdrop />);
+ expect(screen.getByTestId('tour-highlight')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Next')); // → last step
+ expect(screen.getByTestId('tour-highlight')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Done')); // → complete, tour off
+ expect(screen.queryByTestId('tour-highlight')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('tour-backdrop')).not.toBeInTheDocument();
+ });
+
+ it('renders nothing when isActive is false', () => {
+ function Inactive() {
+ const aRef = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button type="button" ref={aRef}>
+ T
+ </button>
+ <Tour isActive={false} onDismiss={() => {}}>
+ <TourStep targetRef={aRef} heading="Hidden">
+ Body
+ </TourStep>
+ </Tour>
+ </>
+ );
+ }
+ render(<Inactive />);
+ expect(screen.queryByText('Hidden')).not.toBeInTheDocument();
+ });
+
+ it('a TourStep outside a Tour renders nothing', () => {
+ function Orphan() {
+ const ref = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button type="button" ref={ref}>
+ T
+ </button>
+ <TourStep targetRef={ref} heading="Orphan">
+ Body
+ </TourStep>
+ </>
+ );
+ }
+ render(<Orphan />);
+ expect(screen.queryByText('Orphan')).not.toBeInTheDocument();
+ });
+});
+
+describe('useTour', () => {
+ it('returns null outside a Tour', () => {
+ let value: ReturnType<typeof useTour> = {} as ReturnType<typeof useTour>;
+ function Probe() {
+ value = useTour();
+ return null;
+ }
+ render(<Probe />);
+ expect(value).toBeNull();
+ });
+
+ it('reports step position and first/last inside a Tour', () => {
+ const seen: Array<{index: number; first: boolean; last: boolean}> = [];
+ function Probe() {
+ const t = useTour();
+ if (t) {
+ seen.push({
+ index: t.activeStepIndex,
+ first: t.isFirstStep,
+ last: t.isLastStep,
+ });
+ }
+ return null;
+ }
+ function Harness() {
+ const aRef = useRef<HTMLButtonElement>(null);
+ const bRef = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button type="button" ref={aRef}>
+ A
+ </button>
+ <button type="button" ref={bRef}>
+ B
+ </button>
+ <Tour isActive onDismiss={() => {}}>
+ <Probe />
+ <TourStep targetRef={aRef} heading="A">
+ a
+ </TourStep>
+ <TourStep targetRef={bRef} heading="B">
+ b
+ </TourStep>
+ </Tour>
+ </>
+ );
+ }
+ render(<Harness />);
+ const last = seen[seen.length - 1];
+ expect(last.index).toBe(0);
+ expect(last.first).toBe(true);
+ expect(last.last).toBe(false);
+ });
+});
diff --git a/packages/lab/src/Tour/Tour.tsx b/packages/lab/src/Tour/Tour.tsx
new file mode 100644
index 0000000000..22d94fb37e
--- /dev/null
+++ b/packages/lab/src/Tour/Tour.tsx
@@ -0,0 +1,171 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Tour.tsx
+ * @input Uses React state/refs, TourContext
+ * @output Exports Tour controller component and TourProps
+ * @position Lab experiment (facebook/astryx#4239); controller consumed by index.ts
+ *
+ * Tour is the controller for a product-tour / NUX walkthrough. It renders no
+ * visible chrome of its own — it owns the tour state (active step, advance /
+ * retreat / complete / dismiss) and shares it with declaratively-nested
+ * `<TourStep>` children through context. Steps register on mount, so the step
+ * ORDER is taken from the children in document order (no step array to keep in
+ * sync with the markup).
+ *
+ * The behavior (a controller plus spotlight feature steps, an `isActive`
+ * switch, dismiss-with-reason, and step progress) is composed from Astryx
+ * primitives. Each step anchors its callout via Popover and draws its own
+ * highlight/backdrop (see TourStep) — the controller owns no chrome.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Tour/TourStep.tsx
+ * - /packages/lab/src/Tour/TourContext.ts
+ * - /packages/lab/src/Tour/useTour.ts
+ * - /packages/lab/src/Tour/Tour.doc.mjs (props table, features)
+ * - /packages/lab/src/Tour/Tour.test.tsx (tests for new/changed behavior)
+ * - /packages/lab/src/Tour/index.ts (exports if types change)
+ */
+
+import {useCallback, useEffect, useMemo, useState, type ReactNode} from 'react';
+import {
+ TourContext,
+ type TourDismissSource,
+ type TourContextValue,
+} from './TourContext';
+
+export interface TourProps {
+ /**
+ * Whether the tour is running. When false, nothing renders and step state
+ * resets — the tour restarts from the first step next time it becomes active.
+ * (Controlled: the consumer owns "has this user seen the tour?".)
+ */
+ isActive: boolean;
+ /**
+ * The tour's steps — `<TourStep>` elements. Step order is taken from their
+ * order here; only the active step renders its callout.
+ */
+ children?: ReactNode;
+ /**
+ * Called when the tour is dismissed, with the reason. Fires for every exit,
+ * including completing the last step (`source === 'complete'`). The consumer
+ * flips `isActive` to false in response, and can branch on the source to tell
+ * a successful finish apart from an early skip/backdrop/escape.
+ */
+ onDismiss: (source: TourDismissSource) => void;
+ /**
+ * Dim the page around the active step's target (a spotlight cutout — the
+ * target stays lit, everything else darkens). Use for modal-style steps that
+ * demand focus; leave off for a lightweight coachmark that only rings the
+ * target.
+ * @default false
+ */
+ hasBackdrop?: boolean;
+ /**
+ * Show the step count ("2 of 5") in each step.
+ * @default false
+ */
+ isStepCountShown?: boolean;
+}
+
+/**
+ * Controller for a guided product tour. Renders no chrome; coordinates the
+ * active step among its `<TourStep>` children.
+ *
+ * @example
+ * ```
+ * const [isActive, setIsActive] = useState(true);
+ * const saveRef = useRef(null);
+ * const shareRef = useRef(null);
+ * <Tour isActive={isActive} hasBackdrop isStepCountShown onDismiss={() => setIsActive(false)}>
+ * <TourStep targetRef={saveRef} heading="Save your work">
+ * Changes save automatically to the cloud.
+ * </TourStep>
+ * <TourStep targetRef={shareRef} heading="Share it">
+ * Invite teammates from here.
+ * </TourStep>
+ * </Tour>
+ * ```
+ */
+export function Tour({
+ isActive,
+ children,
+ onDismiss,
+ hasBackdrop = false,
+ isStepCountShown = false,
+}: TourProps) {
+ // Steps register on mount; insertion order (document order) defines the
+ // sequence. A plain array keeps registration order deterministic.
+ const [stepIds, setStepIds] = useState<string[]>([]);
+ const [activeStepIndex, setActiveStepIndex] = useState(0);
+
+ const registerStep = useCallback((id: string) => {
+ setStepIds(prev => (prev.includes(id) ? prev : [...prev, id]));
+ return () => {
+ setStepIds(prev => prev.filter(stepId => stepId !== id));
+ };
+ }, []);
+
+ // Reset to the first step whenever the tour is (re)started, so a dismissed
+ // tour begins from the top next time isActive flips back on.
+ useEffect(() => {
+ if (!isActive) {
+ setActiveStepIndex(0);
+ }
+ }, [isActive]);
+
+ const stepCount = stepIds.length;
+
+ const onNext = useCallback(() => {
+ // Runs from a click/imperative call (never during render), so branch on the
+ // current index directly rather than inside a state updater — calling
+ // onDismiss from within setState triggers a "setState while rendering"
+ // warning.
+ if (activeStepIndex < stepCount - 1) {
+ setActiveStepIndex(activeStepIndex + 1);
+ return;
+ }
+ // Past the last step → complete. onDismiss carries the reason so a
+ // consumer can branch on 'complete' vs an early exit.
+ onDismiss('complete');
+ }, [activeStepIndex, stepCount, onDismiss]);
+
+ const onPrevious = useCallback(() => {
+ setActiveStepIndex(prev => (prev > 0 ? prev - 1 : prev));
+ }, []);
+
+ const activeStepId = isActive ? (stepIds[activeStepIndex] ?? null) : null;
+
+ const contextValue = useMemo<TourContextValue>(
+ () => ({
+ registerStep,
+ activeStepId,
+ activeStepIndex,
+ stepCount,
+ isStepCountShown,
+ hasBackdrop,
+ onNext,
+ onPrevious,
+ onDismiss,
+ }),
+ [
+ registerStep,
+ activeStepId,
+ activeStepIndex,
+ stepCount,
+ isStepCountShown,
+ hasBackdrop,
+ onNext,
+ onPrevious,
+ onDismiss,
+ ],
+ );
+
+ return (
+ <TourContext.Provider value={contextValue}>{children}</TourContext.Provider>
+ );
+}
+
+Tour.displayName = 'Tour';
diff --git a/packages/lab/src/Tour/TourContext.ts b/packages/lab/src/Tour/TourContext.ts
new file mode 100644
index 0000000000..a3d0ffae6d
--- /dev/null
+++ b/packages/lab/src/Tour/TourContext.ts
@@ -0,0 +1,59 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TourContext.ts
+ * @input Uses React createContext
+ * @output Exports TourContext, TourContextValue, TourDismissSource
+ * @position Internal context; provided by Tour, consumed by TourStep + useTour
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Tour/Tour.tsx
+ * - /packages/lab/src/Tour/TourStep.tsx
+ * - /packages/lab/src/Tour/useTour.ts
+ * - /packages/lab/src/Tour/Tour.doc.mjs
+ */
+
+import {createContext} from 'react';
+
+/**
+ * Why a tour was dismissed. Lets a consumer distinguish "finished the whole
+ * tour" from the various early exits, so it can persist "has seen this tour"
+ * appropriately.
+ * - `backdrop`: clicked the dimmed background
+ * - `escape`: pressed Escape at any step
+ * - `close`: pressed the step's close (X) control
+ * - `skip`: chose "skip"/"maybe later" on the first step
+ * - `complete`: advanced past the final step
+ */
+export type TourDismissSource =
+ 'backdrop' | 'escape' | 'close' | 'skip' | 'complete';
+
+/**
+ * Value shared from the Tour controller to its steps. Steps register
+ * themselves on mount (so the controller learns the step order from the
+ * children, in document order) and read whether they are the active step.
+ */
+export interface TourContextValue {
+ /** Register a step by its stable id; returns an unregister cleanup. */
+ registerStep: (id: string) => () => void;
+ /** The id of the step that is currently active, or null when none. */
+ activeStepId: string | null;
+ /** Zero-based index of the active step among registered steps. */
+ activeStepIndex: number;
+ /** Total number of registered steps. */
+ stepCount: number;
+ /** Whether the tour's step count should be shown in each step. */
+ isStepCountShown: boolean;
+ /** Whether a dimmed background is shown behind the active step. */
+ hasBackdrop: boolean;
+ /** Advance to the next step (or complete on the last step). */
+ onNext: () => void;
+ /** Return to the previous step (no-op on the first step). */
+ onPrevious: () => void;
+ /** Dismiss the tour with a reason. */
+ onDismiss: (source: TourDismissSource) => void;
+}
+
+export const TourContext = createContext<TourContextValue | null>(null);
diff --git a/packages/lab/src/Tour/TourStep.tsx b/packages/lab/src/Tour/TourStep.tsx
new file mode 100644
index 0000000000..1b98f09f5a
--- /dev/null
+++ b/packages/lab/src/Tour/TourStep.tsx
@@ -0,0 +1,398 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TourStep.tsx
+ * @input Uses React, Popover/Button/Text/Heading/Stack from @astryxdesign/core, TourContext
+ * @output Exports TourStep component and TourStepProps
+ * @position Lab experiment (facebook/astryx#4239); a single spotlight step in a Tour
+ *
+ * A TourStep highlights a target element and renders a callout anchored to it,
+ * with a heading, body, optional step progress ("2 of 5"), and back / next /
+ * close controls. It registers with the parent `<Tour>` on mount (so step
+ * order follows the children) and only renders its callout while it is the
+ * active step. Anchoring + the callout surface reuse the core `Popover`
+ * (`anchorRef` → the step's target), so positioning, top-layer rendering, and
+ * dismiss semantics come from the existing layer system rather than a bespoke
+ * implementation.
+ *
+ * The highlight is drawn as a separate overlay tracking the target's box — the
+ * consumer's element is never restyled, so there is no cascade fight with the
+ * target's own styles. That overlay is promoted into the browser TOP LAYER
+ * (via the popover API, like the rest of the layer system) so it sits above
+ * page content without any hardcoded z-index; the callout is promoted after
+ * it, so the callout stays above the highlight. Because it is promoted in
+ * place (not portaled out of the tree), it stays inside the consumer's Theme
+ * subtree and inherits theme tokens — including a scoped/nested theme's accent
+ * for the ring. Dimming is an opt-in spotlight cutout (dims around the target,
+ * not over it) rather than a flat scrim.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Tour/Tour.tsx
+ * - /packages/lab/src/Tour/TourContext.ts
+ * - /packages/lab/src/Tour/Tour.doc.mjs (props table, features)
+ * - /packages/lab/src/Tour/Tour.test.tsx (tests for new/changed behavior)
+ * - /packages/lab/src/Tour/index.ts (exports if types change)
+ */
+
+import {
+ useContext,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Popover} from '@astryxdesign/core/Popover';
+import type {LayerAlignment, LayerPlacement} from '@astryxdesign/core/Layer';
+import {Button} from '@astryxdesign/core/Button';
+import {Text} from '@astryxdesign/core/Text';
+import {Heading} from '@astryxdesign/core/Heading';
+import {VStack, HStack} from '@astryxdesign/core/Layout';
+import {
+ colorVars,
+ spacingVars,
+ durationVars,
+ easeVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {TourContext} from './TourContext';
+
+// Client-only layout effect (SSR renders no overlay, so this only runs on the
+// client). Kept local since core does not export its isomorphic variant.
+const useClientLayoutEffect =
+ typeof window !== 'undefined' ? useLayoutEffect : useEffect;
+
+// Gap between the target's edge and the highlight ring, in px.
+const HIGHLIGHT_PADDING = 4;
+
+interface TargetRect {
+ top: number;
+ left: number;
+ width: number;
+ height: number;
+ radius: string;
+}
+
+const styles = stylex.create({
+ content: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-3'],
+ // Keep the callout from growing arbitrarily wide with long body copy.
+ maxWidth: '320px',
+ },
+ footer: {
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ },
+ // Extra clearance between the target and the callout, so the highlight ring
+ // (which extends a few px past the target) is never covered by the callout.
+ // Placement-aware: the margin goes on the side of the callout that faces the
+ // target. Adds to Popover's own small anchor gap.
+ calloutGapBelow: {marginBlockStart: spacingVars['--spacing-2']},
+ calloutGapAbove: {marginBlockEnd: spacingVars['--spacing-2']},
+ calloutGapStart: {marginInlineEnd: spacingVars['--spacing-2']},
+ calloutGapEnd: {marginInlineStart: spacingVars['--spacing-2']},
+ // Full-viewport overlay root, promoted into the browser top layer so it sits
+ // above all page content with NO z-index. UA popover styles are neutralized
+ // so it fills the viewport. Click-through by default (coachmark); interactive
+ // only when it dims (to catch backdrop clicks).
+ overlayRoot: {
+ position: 'fixed',
+ inset: 0,
+ margin: 0,
+ padding: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ overflow: 'visible',
+ pointerEvents: 'none',
+ },
+ overlayInteractive: {
+ pointerEvents: 'auto',
+ },
+ // The highlight box, sized to the target. Non-interactive so clicks reach the
+ // target (coachmark) or the overlay root (dimmed). The accent ring with a
+ // surface-colored gap mirrors the focus-visible outline used across the
+ // system.
+ highlight: {
+ position: 'absolute',
+ pointerEvents: 'none',
+ boxShadow: `0 0 0 2px ${colorVars['--color-background-surface']}, 0 0 0 4px ${colorVars['--color-accent']}`,
+ transitionProperty: 'top, left, width, height',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ // Spotlight cutout: a huge box-shadow spread dims the whole viewport EXCEPT
+ // this box, so the target reads as lit rather than covered. Layered after the
+ // ring so both shadows show. Only applied when the step opts into a backdrop.
+ cutout: {
+ boxShadow: `0 0 0 2px ${colorVars['--color-background-surface']}, 0 0 0 4px ${colorVars['--color-accent']}, 0 0 0 9999px ${colorVars['--color-overlay']}`,
+ },
+ hidden: {
+ opacity: 0,
+ },
+});
+
+const calloutGapStyles = {
+ below: styles.calloutGapBelow,
+ above: styles.calloutGapAbove,
+ start: styles.calloutGapStart,
+ end: styles.calloutGapEnd,
+} as const;
+
+/**
+ * The highlight overlay: a top-layer box sized to the target, plus an optional
+ * spotlight-cutout dim. Rendered inline (not portaled) so it stays inside the
+ * consumer's Theme subtree and inherits theme tokens — the popover API promotes
+ * it into the top layer in place. Rendered before the callout so the callout
+ * promotes on top of it; promoted once (never re-promoted) so that ordering
+ * holds across re-measures.
+ */
+function TourHighlight({
+ rect,
+ hasBackdrop,
+ onBackdropClick,
+}: {
+ rect: TargetRect | null;
+ hasBackdrop: boolean;
+ onBackdropClick: () => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+
+ useClientLayoutEffect(() => {
+ const el = ref.current;
+ if (el == null || typeof el.showPopover !== 'function') {
+ return;
+ }
+ el.showPopover();
+ return () => {
+ if (el.isConnected && typeof el.hidePopover === 'function') {
+ el.hidePopover();
+ }
+ };
+ }, []);
+
+ return (
+ <div
+ ref={ref}
+ popover="manual"
+ data-testid={hasBackdrop ? 'tour-backdrop' : undefined}
+ aria-hidden="true"
+ onClick={hasBackdrop ? onBackdropClick : undefined}
+ {...stylex.props(
+ styles.overlayRoot,
+ hasBackdrop && styles.overlayInteractive,
+ )}>
+ <div
+ data-testid="tour-highlight"
+ {...stylex.props(
+ styles.highlight,
+ hasBackdrop && styles.cutout,
+ rect == null && styles.hidden,
+ )}
+ style={
+ rect != null
+ ? {
+ top: rect.top - HIGHLIGHT_PADDING,
+ left: rect.left - HIGHLIGHT_PADDING,
+ width: rect.width + HIGHLIGHT_PADDING * 2,
+ height: rect.height + HIGHLIGHT_PADDING * 2,
+ borderRadius: rect.radius,
+ }
+ : undefined
+ }
+ />
+ </div>
+ );
+}
+
+export interface TourStepProps {
+ /**
+ * Ref to the element this step points at. The callout anchors to it (like a
+ * Popover trigger); it must be a `<button>` or `[role="button"]` element,
+ * matching Popover's `anchorRef` contract. Accepts a ref to any HTMLElement
+ * subtype (e.g. `useRef<HTMLButtonElement>(null)`).
+ */
+ targetRef: React.RefObject<HTMLElement | null>;
+ /** Step heading. */
+ heading: ReactNode;
+ /** Step body content. */
+ children?: ReactNode;
+ /**
+ * Which side of the target the callout sits on.
+ * @default 'below'
+ */
+ placement?: LayerPlacement;
+ /**
+ * How the callout aligns along the placement side — e.g. with `placement="below"`,
+ * `start` left-aligns it under the target, `center` centers it, `end` right-aligns it.
+ * @default 'start'
+ */
+ alignment?: LayerAlignment;
+ /** Test id applied to the callout content. */
+ 'data-testid'?: string;
+}
+
+/**
+ * A single spotlight step within a `<Tour>`. Renders its callout only while
+ * active.
+ *
+ * @example
+ * ```
+ * <TourStep targetRef={saveRef} heading="Save your work">
+ * Changes save automatically.
+ * </TourStep>
+ * ```
+ */
+export function TourStep({
+ targetRef,
+ heading,
+ children,
+ placement = 'below',
+ alignment = 'start',
+ 'data-testid': testId,
+}: TourStepProps) {
+ const tour = useContext(TourContext);
+ const id = useId();
+ const isActiveStep = tour != null && tour.activeStepId === id;
+
+ // The active target's viewport box, tracked so the highlight overlay can sit
+ // exactly over it. null until measured (or when inactive).
+ const [rect, setRect] = useState<TargetRect | null>(null);
+
+ // Register with the controller on mount so the tour learns this step (and
+ // its position among siblings). Unregister on unmount.
+ useEffect(() => {
+ if (tour == null) {
+ return;
+ }
+ return tour.registerStep(id);
+ }, [tour, id]);
+
+ // Track the target's box while this step is active. Re-measure on
+ // scroll/resize so the highlight stays glued to the target.
+ useEffect(() => {
+ const el = targetRef.current;
+ if (el == null || !isActiveStep) {
+ setRect(null);
+ return;
+ }
+ const measure = () => {
+ const box = el.getBoundingClientRect();
+ setRect({
+ top: box.top,
+ left: box.left,
+ width: box.width,
+ height: box.height,
+ radius: getComputedStyle(el).borderRadius || '0px',
+ });
+ };
+ measure();
+ window.addEventListener('scroll', measure, true);
+ window.addEventListener('resize', measure);
+ return () => {
+ window.removeEventListener('scroll', measure, true);
+ window.removeEventListener('resize', measure);
+ setRect(null);
+ };
+ }, [targetRef, isActiveStep]);
+
+ // Outside a <Tour>, or when this isn't the active step, render nothing.
+ if (tour == null || !isActiveStep) {
+ return null;
+ }
+
+ const {
+ activeStepIndex,
+ stepCount,
+ isStepCountShown,
+ hasBackdrop,
+ onNext,
+ onPrevious,
+ onDismiss,
+ } = tour;
+
+ const isFirstStep = activeStepIndex <= 0;
+ const isLastStep = stepCount > 0 && activeStepIndex === stepCount - 1;
+
+ const content = (
+ <div {...stylex.props(styles.content)} data-testid={testId}>
+ <VStack gap={1}>
+ <Heading level={4}>{heading}</Heading>
+ {children != null && <Text type="body">{children}</Text>}
+ </VStack>
+ <HStack gap={2} xstyle={styles.footer}>
+ {isStepCountShown && stepCount > 0 ? (
+ <Text type="supporting" color="secondary">
+ {`${activeStepIndex + 1} of ${stepCount}`}
+ </Text>
+ ) : (
+ <span />
+ )}
+ <HStack gap={2}>
+ {!isFirstStep && (
+ <Button
+ variant="ghost"
+ size="sm"
+ label="Back"
+ onClick={onPrevious}
+ />
+ )}
+ <Button
+ variant="primary"
+ size="sm"
+ label={isLastStep ? 'Done' : 'Next'}
+ onClick={onNext}
+ />
+ </HStack>
+ </HStack>
+ </div>
+ );
+
+ return (
+ <>
+ {/* Rendered before the callout so the callout promotes above it in the
+ top layer (callout > highlight > page). */}
+ <TourHighlight
+ rect={rect}
+ hasBackdrop={hasBackdrop}
+ onBackdropClick={() => onDismiss('backdrop')}
+ />
+ <Popover
+ // Popover types anchorRef as RefObject<HTMLElement>; TourStep accepts a
+ // nullable ref for ergonomics (useRef<HTMLButtonElement>(null)). Popover
+ // guards a null `.current` internally, so this widening is safe.
+ anchorRef={targetRef as React.RefObject<HTMLElement>}
+ isOpen
+ onOpenChange={open => {
+ // Popover reports close from light-dismiss (backdrop) or Escape.
+ // Route it to the tour as a dismissal so the whole tour ends, not
+ // just this step's popover. Escape and outside-click both surface
+ // here.
+ if (!open) {
+ onDismiss('close');
+ }
+ }}
+ placement={placement}
+ alignment={alignment}
+ // Size the callout to its content instead of matching the target's
+ // width (Popover's default minWidth: anchor-size(width) makes it span a
+ // wide target); the content's own maxWidth caps it.
+ width="fit-content"
+ // Push the callout clear of the highlight ring so the ring is never
+ // covered (placement-aware; adds to Popover's own anchor gap).
+ xstyle={calloutGapStyles[placement]}
+ label={typeof heading === 'string' ? heading : 'Tour step'}
+ hasCloseButton
+ closeButtonLabel="Close tour"
+ content={content}
+ />
+ </>
+ );
+}
+
+TourStep.displayName = 'TourStep';
diff --git a/packages/lab/src/Tour/index.ts b/packages/lab/src/Tour/index.ts
new file mode 100644
index 0000000000..232f6666fd
--- /dev/null
+++ b/packages/lab/src/Tour/index.ts
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input Tour, TourStep, useTour
+ * @output Re-exports the Tour lab experiment's public API
+ * @position Lab entry point for the Tour directory
+ *
+ * SYNC: When modified, update /packages/lab/src/Tour/Tour.doc.mjs
+ */
+
+export {Tour} from './Tour';
+export type {TourProps} from './Tour';
+
+export {TourStep} from './TourStep';
+export type {TourStepProps} from './TourStep';
+
+export {useTour} from './useTour';
+export type {UseTourReturn} from './useTour';
+
+export type {TourDismissSource} from './TourContext';
diff --git a/packages/lab/src/Tour/useTour.ts b/packages/lab/src/Tour/useTour.ts
new file mode 100644
index 0000000000..eff37c8d84
--- /dev/null
+++ b/packages/lab/src/Tour/useTour.ts
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTour.ts
+ * @input Uses React useContext, TourContext
+ * @output Exports useTour hook and UseTourReturn type
+ * @position Public hook; reads the nearest Tour controller's state
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Tour/TourContext.ts
+ * - /packages/lab/src/Tour/Tour.doc.mjs
+ */
+
+import {useContext} from 'react';
+import {TourContext, type TourDismissSource} from './TourContext';
+
+/**
+ * Read-only view of the active Tour's state, for custom step UIs or
+ * instrumentation. Returns `null` when called outside a `<Tour>`.
+ */
+export interface UseTourReturn {
+ /** Zero-based index of the active step. */
+ activeStepIndex: number;
+ /** Total number of registered steps. */
+ stepCount: number;
+ /** Whether the active step is the first one. */
+ isFirstStep: boolean;
+ /** Whether the active step is the last one. */
+ isLastStep: boolean;
+ /** Advance to the next step (or complete on the last step). */
+ next: () => void;
+ /** Return to the previous step. */
+ previous: () => void;
+ /** Dismiss the tour with a reason. */
+ dismiss: (source: TourDismissSource) => void;
+}
+
+/**
+ * Access the current Tour controller state. Must be used inside a `<Tour>`;
+ * returns `null` otherwise so callers can guard.
+ */
+export function useTour(): UseTourReturn | null {
+ const ctx = useContext(TourContext);
+ if (ctx == null) {
+ return null;
+ }
+ return {
+ activeStepIndex: ctx.activeStepIndex,
+ stepCount: ctx.stepCount,
+ isFirstStep: ctx.activeStepIndex <= 0,
+ isLastStep: ctx.stepCount > 0 && ctx.activeStepIndex === ctx.stepCount - 1,
+ next: ctx.onNext,
+ previous: ctx.onPrevious,
+ dismiss: ctx.onDismiss,
+ };
+}
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 171fac6deb..c66b16d7fd 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -37,6 +37,17 @@ export {Drawer, type DrawerProps} from './Drawer';
// BottomSheet — mobile touch sheet on a native modal <dialog>
export {BottomSheet, type BottomSheetProps} from './BottomSheet';
+// Tour — guided product-tour / NUX walkthrough (facebook/astryx#4239)
+export {
+ Tour,
+ type TourProps,
+ TourStep,
+ type TourStepProps,
+ useTour,
+ type UseTourReturn,
+ type TourDismissSource,
+} from './Tour';
+
// Stat — experimental KPI/metric display
export {
Stat,