---
title: "Tour · Base UI — StyleX Blocks"
description: "A guided walkthrough that spotlights elements one step at a time with an anchored card."
url: "https://stylexblocks.com/components/base-ui/tour/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Tour

A guided walkthrough that spotlights elements one step at a time with an anchored card.

- Behavior engine: Base UI
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/tour.md), [UI SDK](https://stylexblocks.com/components/ui-sdk/tour.md)
- Category: Feedback
- Sizes: sm, md, lg
- HTML page: https://stylexblocks.com/components/base-ui/tour/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style base-ui
```

Then add the item as source you own:

```sh
npx stylexblocks add tour
```

Equivalent: `npx shadcn add @stylexblocks/tour`. Registry item JSON: https://stylexblocks.com/r/base-ui/tour.json

## Usage

```tsx
import { Tour, useTour, type TourStep } from "#components/ui/base-ui/tour.tsx";
import { Button } from "#components/ui/base-ui/button.tsx";

const steps: TourStep[] = [
  {
    id: "search",
    target: () => document.querySelector<HTMLElement>("#search"),
    title: "Find anything",
    description: "Search projects, people, and settings from one place.",
    placement: "bottom-start",
    arrow: true,
    actions: [{ label: "Next", action: "next" }],
  },
  {
    id: "settings",
    target: () => document.querySelector<HTMLElement>("#settings"),
    title: "Make it yours",
    description: "Theme, notifications, and members live here.",
    actions: [
      { label: "Back", action: "prev" },
      { label: "Finish", action: "dismiss" },
    ],
  },
];

export function Example() {
  // Hand-built on Base UI's Popover: the card anchors to each target, the
  // backdrop cuts a spotlight hole around it, Escape ends the tour.
  const tour = useTour({ steps });
  return (
    <>
      <Button onClick={() => tour.start()}>Start tour</Button>
      <Tour.Root tour={tour} size="md">
        <Tour.Portal>
          <Tour.Backdrop />
          <Tour.Spotlight />
          <Tour.Positioner>
            <Tour.Content>
              <Tour.Arrow />
              <Tour.Header>
                <Tour.Title />
                <Tour.Description />
              </Tour.Header>
              <Tour.Footer>
                <Tour.ProgressText />
                <Tour.Control>
                  <Tour.Actions>
                    {(actions) =>
                      actions.map((action) => (
                        <Tour.ActionTrigger
                          key={action.label}
                          action={action}
                          render={<Button size="xs" />}
                        >
                          {action.label}
                        </Tour.ActionTrigger>
                      ))
                    }
                  </Tour.Actions>
                </Tour.Control>
              </Tour.Footer>
              <Tour.CloseTrigger>×</Tour.CloseTrigger>
            </Tour.Content>
          </Tour.Positioner>
        </Tour.Portal>
      </Tour.Root>
    </>
  );
}
```

## Source

`components/ui/base-ui/tour.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { Popover as BasePopover } from "@base-ui/react/popover";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { createSlotRecipeContext } from "#lib/base-ui/create-slot-recipe-context.tsx";
import { defineSlotRecipe } from "#lib/recipe-props.ts";
import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { semanticShadows } from '@stylexblocks/ui/semantic-tokens/shadows.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
import { zIndices } from '@stylexblocks/ui/tokens/z-indices.stylex.ts'

// Every layer stacks on one base: backdrop (+0), spotlight (+1), card (+2).
// The engines set `--tour-layer` per part.
const tourZIndex = `calc(var(--tour-z-index) + var(--tour-layer, 0))`

const tourBackdrop = stylex.create({
  base: {
    '--tour-z-index': zIndices.modal,
    '--tour-layer': 0,
    zIndex: tourZIndex,
    backgroundColor: semanticColors.bgBackdrop,
    // the spotlight hole glides between steps, but tracks scroll and resize
    // instantly (engines flag those updates with data-instant)
    transitionProperty: 'clip-path',
    transitionDuration: {
      default: durations.moderate,
      ':is([data-instant])': '0ms',
    },
    transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
    animationName: {
      default: null,
      ':is([data-open], [data-state="open"])': 'fade-in',
      ':is([data-closed], [data-state="closed"])': 'fade-out',
    },
    animationDuration: {
      default: null,
      ':is([data-open], [data-state="open"])': durations.moderate,
      ':is([data-closed], [data-state="closed"])': durations.faster,
    },
  },
})

const tourSpotlight = stylex.create({
  base: {
    '--tour-z-index': zIndices.modal,
    '--tour-layer': 1,
    zIndex: tourZIndex,
    boxShadow: `0 0 0 2px ${colorPalette.focusRing}`,
    transitionProperty: 'left, top, width, height',
    transitionDuration: {
      default: durations.moderate,
      ':is([data-instant])': '0ms',
    },
    transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
  },
})

const tourPositioner = stylex.create({
  base: {
    '--tour-z-index': zIndices.modal,
    '--tour-layer': 2,
    zIndex: tourZIndex,
    // a step without a target is a centered dialog
    position: {
      default: null,
      ':is([data-type="dialog"])': 'fixed',
    },
    inset: {
      default: null,
      ':is([data-type="dialog"])': 0,
    },
    display: {
      default: null,
      ':is([data-type="dialog"])': 'flex',
    },
    alignItems: {
      default: null,
      ':is([data-type="dialog"])': 'center',
    },
    justifyContent: {
      default: null,
      ':is([data-type="dialog"])': 'center',
    },
  },
})

const tourContent = stylex.create({
  base: {
    position: 'relative',
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._3,
    width: 'var(--tour-size)',
    maxWidth: 'calc(100vw - 2rem)',
    padding: 'var(--tour-padding)',
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    '--tour-size': sizes.xs,
    '--tour-radius': semanticRadii.panel,
    '--tour-bg': semanticColors.bgPanel,
    backgroundColor: 'var(--tour-bg)',
    borderRadius: 'var(--tour-radius)',
    boxShadow: semanticShadows.overlay,
    outline: 'none',
    transformOrigin: 'var(--transform-origin)',
    animationName: {
      default: null,
      ':is([data-open], [data-state="open"])': 'scale-in, fade-in',
      ':is([data-closed], [data-state="closed"])': 'scale-out, fade-out',
    },
    animationDuration: {
      default: null,
      ':is([data-open], [data-state="open"])': durations.fast,
      ':is([data-closed], [data-state="closed"])': durations.faster,
    },
  },
})

const tourContentSizes = stylex.create({
  sm: {
    '--tour-padding': spacing._3,
    '--tour-size': sizes.xs,
  },
  md: {
    '--tour-padding': spacing._4,
    '--tour-size': sizes.xs,
  },
  lg: {
    '--tour-padding': spacing._5,
    '--tour-size': sizes.sm,
  },
})

const tourHeader = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._1,
    paddingInlineEnd: spacing._6,
  },
})

const tourTitle = stylex.create({
  base: {
    margin: 0,
    fontSize: fontSizes.md,
    lineHeight: lineHeights.md,
    fontWeight: fontWeights.semibold,
    color: semanticColors.fg,
  },
})

const tourDescription = stylex.create({
  base: {
    margin: 0,
    color: semanticColors.fgMuted,
  },
})

const tourProgressText = stylex.create({
  base: {
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    fontVariantNumeric: 'tabular-nums',
    color: semanticColors.fgMuted,
  },
})

const tourFooter = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: spacing._3,
    paddingTop: spacing._1,
  },
})

const tourControl = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    gap: spacing._2,
    marginInlineStart: 'auto',
  },
})

const tourCloseTrigger = stylex.create({
  base: {
    position: 'absolute',
    top: spacing._2_5,
    insetInlineEnd: spacing._2_5,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: sizes._6,
    height: sizes._6,
    padding: 0,
    borderWidth: 0,
    borderRadius: semanticRadii.control,
    color: semanticColors.fgMuted,
    backgroundColor: {
      default: 'transparent',
      ':hover': semanticColors.bgMuted,
    },
    cursor: 'pointer',
    outlineWidth: {
      default: null,
      ':focus-visible': '2px',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '1px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
  },
})

const tourArrow = stylex.create({
  base: {
    '--arrow-size': sizes._3,
    '--arrow-background': 'var(--tour-bg)',
  },
})

const tourArrowTip = stylex.create({
  base: {
    backgroundColor: 'var(--arrow-background)',
  },
})

export type TourSize = keyof typeof tourContentSizes

// defineSlotRecipe validates the shape at compile time: default values must
// exist in the axis maps, and slot keys must be `styles` or a declared axis
const tourRecipe = defineSlotRecipe({
  slots: {
    backdrop: { styles: tourBackdrop },
    spotlight: { styles: tourSpotlight },
    positioner: { styles: tourPositioner },
    content: { styles: tourContent, sizes: tourContentSizes },
    header: { styles: tourHeader },
    title: { styles: tourTitle },
    description: { styles: tourDescription },
    progressText: { styles: tourProgressText },
    footer: { styles: tourFooter },
    control: { styles: tourControl },
    closeTrigger: { styles: tourCloseTrigger },
    arrow: { styles: tourArrow },
    arrowTip: { styles: tourArrowTip },
  },
  defaultVariants: { size: "md" },
});

// What the recipe leaves to the composition layer here: Base UI has no tour
// layers, so the backdrop and spotlight are fixed to the viewport, and the
// arrow is a single rotated square placed against the popup edge.
const chrome = stylex.create({
  backdrop: { position: "fixed", inset: 0 },
  spotlight: { position: "fixed", pointerEvents: "none" },
  arrow: {
    width: "var(--arrow-size)",
    height: "var(--arrow-size)",
    backgroundColor: "var(--arrow-background)",
    transform: "rotate(45deg)",
    top: {
      default: null,
      ':is([data-side="bottom"])': "calc(var(--arrow-size) / -2)",
    },
    bottom: {
      default: null,
      ':is([data-side="top"])': "calc(var(--arrow-size) / -2)",
    },
    left: {
      default: null,
      ':is([data-side="right"])': "calc(var(--arrow-size) / -2)",
    },
    right: {
      default: null,
      ':is([data-side="left"])': "calc(var(--arrow-size) / -2)",
    },
  },
});

const { withRootProvider, withContext } = createSlotRecipeContext(tourRecipe);

// ---------------------------------------------------------------------------
// Tour state machine (hand-built: Base UI has no tour primitive)
// ---------------------------------------------------------------------------

type Side = "top" | "bottom" | "left" | "right";
type Align = "start" | "center" | "end";
export type TourPlacement = Side | `${Side}-start` | `${Side}-end`;
export type TourStepActionType = "next" | "prev" | "dismiss" | "skip";
export type TourStatus = "idle" | "started" | "completed" | "dismissed" | "skipped";

export interface TourStepAction {
  label: string;
  /** Built-in action, or a function receiving the tour API. */
  action?: TourStepActionType | ((tour: TourApi) => void);
  /** Extra attributes for the action trigger. */
  attrs?: Record<string, unknown>;
}

export interface TourStep {
  id: string;
  /** The element to highlight. Omit it for a centered dialog step. */
  target?: () => HTMLElement | null;
  title: React.ReactNode;
  description: React.ReactNode;
  /** Card placement relative to the target. @default "bottom" */
  placement?: TourPlacement;
  /** Show an arrow pointing at the target. */
  arrow?: boolean;
  actions?: TourStepAction[];
}

export interface UseTourProps {
  steps: TourStep[];
  onStepChange?: (details: { stepId: string | null; stepIndex: number }) => void;
  onStatusChange?: (details: { status: TourStatus; stepId: string | null }) => void;
  /** @default true */
  closeOnInteractOutside?: boolean;
  /** @default true */
  closeOnEscape?: boolean;
  /** ←/→ move between steps while the card has focus. @default true */
  keyboardNavigation?: boolean;
  /** Padding between the target and the spotlight edge. @default { x: 10, y: 10 } */
  spotlightOffset?: { x: number; y: number };
  /** @default 4 */
  spotlightRadius?: number;
}

export interface TourApi {
  open: boolean;
  steps: TourStep[];
  step: TourStep | null;
  stepIndex: number;
  totalSteps: number;
  hasNextStep: boolean;
  hasPrevStep: boolean;
  firstStep: boolean;
  lastStep: boolean;
  /** Start at a step id, or the first step. */
  start: (id?: string) => void;
  setStep: (id: string) => void;
  next: () => void;
  prev: () => void;
  dismiss: () => void;
  skip: () => void;
  getProgressText: () => string;
  getProgressPercent: () => number;
  /** Resolved options, read by the parts. */
  options: Required<Omit<UseTourProps, "steps" | "onStepChange" | "onStatusChange">>;
  /** Focus returns here when the tour ends. */
  restoreFocusRef: React.RefObject<HTMLElement | null>;
}

/** Creates the tour state; pass the result to `<Tour.Root tour>`. */
export function useTour(props: UseTourProps): TourApi {
  const {
    steps,
    onStepChange,
    onStatusChange,
    closeOnInteractOutside = true,
    closeOnEscape = true,
    keyboardNavigation = true,
    spotlightOffset = { x: 10, y: 10 },
    spotlightRadius = 4,
  } = props;
  const [stepIndex, setStepIndex] = useState(-1);
  const restoreFocusRef = useRef<HTMLElement | null>(null);
  const callbacks = useRef({ onStepChange, onStatusChange });
  callbacks.current = { onStepChange, onStatusChange };

  const goTo = useCallback(
    (index: number) => {
      setStepIndex(index);
      callbacks.current.onStepChange?.({
        stepId: steps[index]?.id ?? null,
        stepIndex: index,
      });
    },
    [steps],
  );

  const end = useCallback(
    (status: TourStatus) => {
      const stepId = steps[stepIndex]?.id ?? null;
      setStepIndex(-1);
      callbacks.current.onStatusChange?.({ status, stepId });
    },
    [steps, stepIndex],
  );

  const open = stepIndex >= 0 && stepIndex < steps.length;
  const step = open ? steps[stepIndex]! : null;
  const total = steps.length;

  return useMemo<TourApi>(() => {
    const api: TourApi = {
      open,
      steps,
      step,
      stepIndex,
      totalSteps: total,
      hasNextStep: open && stepIndex < total - 1,
      hasPrevStep: open && stepIndex > 0,
      firstStep: stepIndex === 0,
      lastStep: stepIndex === total - 1,
      start: (id) => {
        const active = document.activeElement;
        restoreFocusRef.current = active instanceof HTMLElement ? active : null;
        const index = id ? Math.max(0, steps.findIndex((s) => s.id === id)) : 0;
        goTo(index);
        callbacks.current.onStatusChange?.({
          status: "started",
          stepId: steps[index]?.id ?? null,
        });
      },
      setStep: (id) => {
        const index = steps.findIndex((s) => s.id === id);
        if (index >= 0) goTo(index);
      },
      next: () => (stepIndex < total - 1 ? goTo(stepIndex + 1) : end("completed")),
      prev: () => {
        if (stepIndex > 0) goTo(stepIndex - 1);
      },
      dismiss: () => end("dismissed"),
      skip: () => end("skipped"),
      getProgressText: () => `${stepIndex + 1} of ${total}`,
      getProgressPercent: () => ((stepIndex + 1) / total) * 100,
      options: {
        closeOnInteractOutside,
        closeOnEscape,
        keyboardNavigation,
        spotlightOffset,
        spotlightRadius,
      },
      restoreFocusRef,
    };
    return api;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    open,
    step,
    stepIndex,
    total,
    steps,
    goTo,
    end,
    closeOnInteractOutside,
    closeOnEscape,
    keyboardNavigation,
    spotlightOffset.x,
    spotlightOffset.y,
    spotlightRadius,
  ]);
}

// ---------------------------------------------------------------------------
// Geometry: the spotlight rect follows the target every frame while open
// ---------------------------------------------------------------------------

interface Rect {
  x: number;
  y: number;
  width: number;
  height: number;
}

interface Geometry {
  target: HTMLElement | null;
  /** Spotlight rect in viewport coordinates (target + offset). */
  rect: Rect | null;
  viewport: { width: number; height: number };
  stepId: string | null;
  /** True for scroll/resize updates (no transition), false on step change. */
  instant: boolean;
}

const sameRect = (a: Rect | null, b: Rect | null) =>
  a === b ||
  (!!a &&
    !!b &&
    a.x === b.x &&
    a.y === b.y &&
    a.width === b.width &&
    a.height === b.height);

function useTargetGeometry(tour: TourApi): Geometry | null {
  const [geometry, setGeometry] = useState<Geometry | null>(null);
  const { step, open } = tour;
  const { x: ox, y: oy } = tour.options.spotlightOffset;

  useEffect(() => {
    if (!open || !step) {
      setGeometry(null);
      return;
    }
    const first = step.target?.();
    first?.scrollIntoView({ block: "nearest", inline: "nearest" });
    let frame = 0;
    const tick = () => {
      const target = step.target?.() ?? null;
      const r = target?.getBoundingClientRect();
      const rect = r
        ? { x: r.x - ox, y: r.y - oy, width: r.width + ox * 2, height: r.height + oy * 2 }
        : null;
      const viewport = { width: window.innerWidth, height: window.innerHeight };
      setGeometry((prev) =>
        prev &&
        prev.target === target &&
        prev.stepId === step.id &&
        sameRect(prev.rect, rect) &&
        prev.viewport.width === viewport.width &&
        prev.viewport.height === viewport.height
          ? prev
          : {
              target,
              rect,
              viewport,
              stepId: step.id,
              instant: prev?.stepId === step.id,
            },
      );
      frame = requestAnimationFrame(tick);
    };
    tick();
    return () => cancelAnimationFrame(frame);
  }, [open, step, ox, oy]);

  return geometry;
}

/** Full-viewport rectangle with a rounded hole, for `clip-path: path(evenodd)`. */
function spotlightPath(viewport: Geometry["viewport"], rect: Rect | null, radius: number) {
  const outer = `M0 0H${viewport.width}V${viewport.height}H0Z`;
  if (!rect) return outer;
  const { x, y, width: w, height: h } = rect;
  const r = Math.max(0, Math.min(radius, w / 2, h / 2));
  return (
    `${outer}M${x + r} ${y}H${x + w - r}A${r} ${r} 0 0 1 ${x + w} ${y + r}` +
    `V${y + h - r}A${r} ${r} 0 0 1 ${x + w - r} ${y + h}H${x + r}` +
    `A${r} ${r} 0 0 1 ${x} ${y + h - r}V${y + r}A${r} ${r} 0 0 1 ${x + r} ${y}Z`
  );
}

interface TourContextValue {
  tour: TourApi;
  geometry: Geometry | null;
}

const TourContext = createContext<TourContextValue | null>(null);

function useTourPart() {
  const ctx = useContext(TourContext);
  if (!ctx) throw new Error("Tour parts must be rendered inside <Tour.Root>");
  return ctx;
}

/** The current tour API, for custom parts. */
export function useTourContext() {
  return useTourPart().tour;
}

// ---------------------------------------------------------------------------
// Parts
// ---------------------------------------------------------------------------

export interface TourRootProps {
  tour: TourApi;
  children?: React.ReactNode;
}

/**
 * Drives Base UI's Popover from the tour state: open while a step is
 * active; Escape, the close button, and outside presses end the tour
 * (presses inside the spotlighted target don't).
 */
function RootNode({ tour, children }: TourRootProps) {
  const geometry = useTargetGeometry(tour);
  const value = useMemo(() => ({ tour, geometry }), [tour, geometry]);
  return (
    <TourContext.Provider value={value}>
      <BasePopover.Root
        open={tour.open}
        onOpenChange={(open, details) => {
          if (open) return;
          const { reason, event } = details;
          if (reason === "escape-key" && !tour.options.closeOnEscape) return;
          if (reason === "outside-press") {
            if (!tour.options.closeOnInteractOutside) return;
            const target = event?.target;
            if (target instanceof Node && geometry?.target?.contains(target)) return;
          }
          if (
            reason === "escape-key" ||
            reason === "outside-press" ||
            reason === "close-press"
          ) {
            tour.dismiss();
          }
        }}
      >
        {children}
      </BasePopover.Root>
    </TourContext.Provider>
  );
}

function BackdropNode(allProps: useRender.ComponentProps<"div">) {
  const { render, ...rest } = allProps;
  const { tour, geometry } = useTourPart();
  const viewport = geometry?.viewport ?? { width: 0, height: 0 };
  const hasTarget = !!geometry?.rect;
  return useRender({
    defaultTagName: "div",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        "aria-hidden": true,
        "data-state": tour.open ? "open" : "closed",
        "data-type": hasTarget ? "tooltip" : "dialog",
        "data-instant": geometry?.instant ? "" : undefined,
        style: {
          clipPath: hasTarget
            ? `path(evenodd, "${spotlightPath(viewport, geometry!.rect, tour.options.spotlightRadius)}")`
            : undefined,
        },
      } as React.ComponentProps<"div">,
      rest,
    ),
  });
}

function SpotlightNode(allProps: useRender.ComponentProps<"div">) {
  const { render, ...rest } = allProps;
  const { tour, geometry } = useTourPart();
  const rect = geometry?.rect;
  const element = useRender({
    defaultTagName: "div",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        "aria-hidden": true,
        "data-instant": geometry?.instant ? "" : undefined,
        style: rect
          ? {
              left: rect.x,
              top: rect.y,
              width: rect.width,
              height: rect.height,
              borderRadius: tour.options.spotlightRadius,
            }
          : undefined,
      } as React.ComponentProps<"div">,
      rest,
    ),
  });
  return rect ? element : null;
}

/** Viewport-centered virtual anchor for steps without a target. */
const centerAnchor = {
  getBoundingClientRect: () =>
    DOMRect.fromRect({
      x: window.innerWidth / 2,
      y: window.innerHeight / 2,
      width: 0,
      height: 0,
    }),
};

function PositionerNode(
  allProps: React.ComponentProps<typeof BasePopover.Positioner>,
) {
  const { tour, geometry } = useTourPart();
  const placement = tour.step?.placement ?? "bottom";
  const [side, align = "center"] = placement.split("-") as [Side, Align?];
  const target = geometry?.target ?? null;
  const gap = side === "left" || side === "right"
    ? tour.options.spotlightOffset.x
    : tour.options.spotlightOffset.y;
  return (
    <BasePopover.Positioner
      data-step-type={target ? "tooltip" : "dialog"}
      anchor={target ?? centerAnchor}
      positionMethod={target ? "absolute" : "fixed"}
      side={target ? side : "bottom"}
      align={target ? align : "center"}
      sideOffset={
        target ? gap + 10 : ({ positioner }) => -positioner.height / 2
      }
      collisionPadding={12}
      {...allProps}
    />
  );
}

function ContentNode(allProps: React.ComponentProps<typeof BasePopover.Popup>) {
  const { tour } = useTourPart();
  const ref = useRef<HTMLDivElement>(null);
  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    if (!tour.options.keyboardNavigation || event.defaultPrevented) return;
    if ((event.target as HTMLElement).closest("input, textarea, select, [contenteditable]")) {
      return;
    }
    const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
    const forward = event.key === (rtl ? "ArrowLeft" : "ArrowRight");
    const back = event.key === (rtl ? "ArrowRight" : "ArrowLeft");
    if (forward && tour.hasNextStep) tour.next();
    if (back && tour.hasPrevStep) tour.prev();
  };
  return (
    <BasePopover.Popup
      ref={ref}
      tabIndex={-1}
      initialFocus={ref}
      finalFocus={tour.restoreFocusRef}
      data-step={tour.step?.id}
      onKeyDown={onKeyDown}
      {...allProps}
    />
  );
}

function ProgressTextNode(allProps: useRender.ComponentProps<"div">) {
  const { render, ...rest } = allProps;
  const { tour } = useTourPart();
  return useRender({
    defaultTagName: "div",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps({ children: tour.getProgressText() }, rest),
  });
}

function TitleNode({
  children,
  ...rest
}: React.ComponentProps<typeof BasePopover.Title>) {
  const { tour } = useTourPart();
  return <BasePopover.Title {...rest}>{children ?? tour.step?.title}</BasePopover.Title>;
}

function DescriptionNode({
  children,
  ...rest
}: React.ComponentProps<typeof BasePopover.Description>) {
  const { tour } = useTourPart();
  return (
    <BasePopover.Description {...rest}>
      {children ?? tour.step?.description}
    </BasePopover.Description>
  );
}

/** Rendered only for steps with `arrow: true` and a target. */
function ArrowNode(allProps: React.ComponentProps<typeof BasePopover.Arrow>) {
  const { tour, geometry } = useTourPart();
  if (!tour.step?.arrow || !geometry?.target) return null;
  return <BasePopover.Arrow {...allProps} />;
}

function CloseTriggerNode(allProps: React.ComponentProps<typeof BasePopover.Close>) {
  return <BasePopover.Close aria-label="Close tour" {...allProps} />;
}

/** Renders the current step's actions through a render function. */
function Actions({ children }: { children: (actions: TourStepAction[]) => React.ReactNode }) {
  const { tour } = useTourPart();
  return <>{children(tour.step?.actions ?? [])}</>;
}

export type TourActionTriggerProps = useRender.ComponentProps<"button"> & {
  action: TourStepAction;
};

function ActionTrigger({ render, action, ...rest }: TourActionTriggerProps) {
  const { tour } = useTourPart();
  const kind = action.action;
  const run = () => {
    if (typeof kind === "function") return kind(tour);
    if (kind === "next") return tour.next();
    if (kind === "prev") return tour.prev();
    if (kind === "dismiss") return tour.dismiss();
    if (kind === "skip") return tour.skip();
  };
  const disabled =
    (kind === "next" && !tour.hasNextStep) || (kind === "prev" && !tour.hasPrevStep);
  return useRender({
    defaultTagName: "button",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        type: "button",
        ...action.attrs,
        "data-type": typeof kind === "string" ? kind : "custom",
        disabled,
        "data-disabled": disabled ? "" : undefined,
        onClick: run,
      } as React.ComponentProps<"button">,
      rest,
    ),
  });
}

/**
 * Tour — a hand-built product tour on Base UI's Popover, wearing the tour
 * slot recipe. Create the state with `useTour({ steps })` and pass it to
 * `<Tour.Root tour size>`. Each step scrolls its target into view; the
 * backdrop cuts a spotlight hole around it (tracked every frame, so scroll
 * and resize stay aligned) and the card anchors to it through Popover's
 * positioner (targetless steps center in the viewport). Focus moves into
 * the card and returns when the tour ends; Escape, the close button, and
 * outside presses dismiss; ←/→ step through. Steps declare their own
 * `actions` (`next`, `prev`, `dismiss`, `skip`); render them with
 * `Tour.Actions` + `Tour.ActionTrigger` (compose a Button via `render`).
 */
export const Tour = {
  Root: withRootProvider(RootNode, "TourRoot"),
  Portal: BasePopover.Portal,
  Backdrop: withContext(
    BackdropNode,
    () => [tourBackdrop.base, chrome.backdrop],
    "TourBackdrop",
  ),
  Spotlight: withContext(
    SpotlightNode,
    () => [tourSpotlight.base, chrome.spotlight],
    "TourSpotlight",
  ),
  Positioner: withContext(PositionerNode, "positioner", "TourPositioner"),
  Content: withContext(ContentNode, "content", "TourContent"),
  Arrow: withContext(
    ArrowNode,
    () => [tourArrow.base, chrome.arrow],
    "TourArrow",
  ),
  Header: withContext("div", "header", "TourHeader"),
  Title: withContext(TitleNode, "title", "TourTitle"),
  Description: withContext(DescriptionNode, "description", "TourDescription"),
  ProgressText: withContext(ProgressTextNode, "progressText", "TourProgressText"),
  Footer: withContext("div", "footer", "TourFooter"),
  Control: withContext("div", "control", "TourControl"),
  CloseTrigger: withContext(CloseTriggerNode, "closeTrigger", "TourCloseTrigger"),
  Actions,
  ActionTrigger,
};
```
