Ordo UI
组件Navigation

Stepper

@mox-hub/ui 组件 · Navigation · canonical

stepper@mox-hub/uiNavigationcanonicalsrc/components/stepper.tsx

变体轴

orientation
horizontalvertical
变体演示stepper

Props API

Prop类型默认值说明
defaultValue*number1—
value*number——
onValueChange*(value: number) => void——
orientation*StepperOrientation'horizontal'—
className*string——
children*ReactNode——
indicators*StepIndicators{}—

源码

packages/ui/src/components/stepper.tsx
/* eslint-disable react-hooks/exhaustive-deps */

import type { HTMLAttributes, ReactElement } from 'react';
import {
  Children,
  createContext,
  isValidElement,
  useCallback,
  useContext,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
} from 'react';
import { useDirection } from '@base-ui/react/direction-provider';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { cn } from '../lib/utils';

/**
 * 复合式步骤条(reui base-nova 配方移植,2026-09-14)。
 * Stepper 为受控/非受控根,StepperNav > StepperItem(step) > Trigger/Indicator/Separator 组合;
 * 纯展示流程(状态机推进、不可点击导航)可不放 StepperTrigger,直接用 Indicator + Title。
 * 与 reui 原配方差异:inactive 指示器用 muted、标题/描述按 data-state 变色、指示器与分隔线带 motion-shift 过渡。
 */

// Types
type StepperOrientation = 'horizontal' | 'vertical';
type StepState = 'active' | 'completed' | 'inactive' | 'loading';
type StepIndicators = {
  active?: React.ReactNode;
  completed?: React.ReactNode;
  inactive?: React.ReactNode;
  loading?: React.ReactNode;
};

interface StepperContextValue {
  /** useId 前缀:同页多个 Stepper 的 tab/panel id 不再互相冲突 */
  baseId: string;
  activeStep: number;
  setActiveStep: (step: number) => void;
  /** 已挂载的 panel 步骤号:trigger 只给真实存在的 panel 挂 aria-controls */
  panelValues: number[];
  registerPanel: (step: number) => void;
  unregisterPanel: (step: number) => void;
  stepsCount: number;
  orientation: StepperOrientation;
  registerTrigger: (node: HTMLButtonElement | null) => void;
  unregisterTrigger: (node: HTMLButtonElement) => void;
  triggerNodes: HTMLButtonElement[];
  focusNext: (currentIdx: number) => void;
  focusPrev: (currentIdx: number) => void;
  focusFirst: () => void;
  focusLast: () => void;
  indicators: StepIndicators;
}

interface StepItemContextValue {
  step: number;
  state: StepState;
  isDisabled: boolean;
  isLoading: boolean;
}

const StepperContext = createContext<StepperContextValue | undefined>(undefined);
const StepItemContext = createContext<StepItemContextValue | undefined>(undefined);

export function useStepper() {
  const ctx = useContext(StepperContext);
  if (!ctx) throw new Error('useStepper must be used within a Stepper');
  return ctx;
}

export function useStepItem() {
  const ctx = useContext(StepItemContext);
  if (!ctx) throw new Error('useStepItem must be used within a StepperItem');
  return ctx;
}

interface StepperProps extends HTMLAttributes<HTMLDivElement> {
  defaultValue?: number;
  value?: number;
  onValueChange?: (value: number) => void;
  orientation?: StepperOrientation;
  indicators?: StepIndicators;
}

function Stepper({
  defaultValue = 1,
  value,
  onValueChange,
  orientation = 'horizontal',
  className,
  children,
  indicators = {},
  ...props
}: StepperProps) {
  const [activeStep, setActiveStep] = useState(defaultValue);
  const [triggerNodes, setTriggerNodes] = useState<HTMLButtonElement[]>([]);
  const [panelValues, setPanelValues] = useState<number[]>([]);
  const baseId = useId();

  const registerPanel = useCallback((step: number) => {
    setPanelValues((prev) => (prev.includes(step) ? prev : [...prev, step]));
  }, []);
  const unregisterPanel = useCallback((step: number) => {
    setPanelValues((prev) => prev.filter((value) => value !== step));
  }, []);

  // Register/unregister triggers
  const registerTrigger = useCallback((node: HTMLButtonElement | null) => {
    if (!node) return;
    setTriggerNodes((prev) => (prev.includes(node) ? prev : [...prev, node]));
  }, []);
  const unregisterTrigger = useCallback((node: HTMLButtonElement) => {
    setTriggerNodes((prev) => prev.filter((n) => n !== node));
  }, []);

  const handleSetActiveStep = useCallback(
    (step: number) => {
      if (value === undefined) {
        setActiveStep(step);
      }
      onValueChange?.(step);
    },
    [value, onValueChange]
  );

  const currentStep = value ?? activeStep;

  // Keyboard navigation logic
  const focusTrigger = (idx: number) => {
    if (triggerNodes[idx]) triggerNodes[idx].focus();
  };
  const focusNext = (currentIdx: number) =>
    focusTrigger((currentIdx + 1) % triggerNodes.length);
  const focusPrev = (currentIdx: number) =>
    focusTrigger((currentIdx - 1 + triggerNodes.length) % triggerNodes.length);
  const focusFirst = () => focusTrigger(0);
  const focusLast = () => focusTrigger(triggerNodes.length - 1);

  // Context value
  const contextValue = useMemo<StepperContextValue>(
    () => ({
      baseId,
      activeStep: currentStep,
      setActiveStep: handleSetActiveStep,
      panelValues,
      registerPanel,
      unregisterPanel,
      stepsCount: Children.toArray(children).filter(
        (child): child is ReactElement =>
          isValidElement(child) &&
          (child.type as { displayName?: string }).displayName === StepperItem.displayName
      ).length,
      orientation,
      registerTrigger,
      unregisterTrigger,
      focusNext,
      focusPrev,
      focusFirst,
      focusLast,
      triggerNodes,
      indicators,
    }),
    [
      baseId,
      currentStep,
      handleSetActiveStep,
      panelValues,
      registerPanel,
      unregisterPanel,
      children,
      orientation,
      registerTrigger,
      unregisterTrigger,
      triggerNodes,
    ]
  );

  return (
    <StepperContext.Provider value={contextValue}>
      <div
        data-slot="stepper"
        className={cn('w-full', className)}
        data-orientation={orientation}
        {...props}
      >
        {children}
      </div>
    </StepperContext.Provider>
  );
}

interface StepperItemProps extends React.HTMLAttributes<HTMLDivElement> {
  step: number;
  completed?: boolean;
  disabled?: boolean;
  loading?: boolean;
}

function StepperItem({
  step,
  completed = false,
  disabled = false,
  loading = false,
  className,
  children,
  ...props
}: StepperItemProps) {
  const { activeStep } = useStepper();

  const state: StepState =
    completed || step < activeStep
      ? 'completed'
      : activeStep === step
        ? 'active'
        : 'inactive';

  const isLoading = loading && step === activeStep;

  return (
    <StepItemContext.Provider
      value={{ step, state, isDisabled: disabled, isLoading }}
    >
      <div
        data-slot="stepper-item"
        className={cn(
          'group/step flex items-center justify-center not-last:flex-1 group-data-[orientation=horizontal]/stepper-nav:flex-row group-data-[orientation=vertical]/stepper-nav:flex-col',
          className
        )}
        data-state={state}
        {...(isLoading ? { 'data-loading': true } : {})}
        {...props}
      >
        {children}
      </div>
    </StepItemContext.Provider>
  );
}
StepperItem.displayName = 'StepperItem';

type StepperTriggerProps = useRender.ComponentProps<'button'>;

function StepperTrigger({
  className,
  children,
  tabIndex,
  render,
  ...props
}: StepperTriggerProps) {
  const { state, isLoading, step, isDisabled } = useStepItem();
  const {
    baseId,
    panelValues,
    setActiveStep,
    activeStep,
    registerTrigger,
    unregisterTrigger,
    triggerNodes,
    focusNext,
    focusPrev,
    focusFirst,
    focusLast,
  } = useStepper();
  const direction = useDirection();
  const isSelected = activeStep === step;
  const id = `${baseId}-tab-${step}`;
  const panelId = `${baseId}-panel-${step}`;

  // Register this trigger for keyboard navigation(禁用步不进入方向键序列)
  const btnRef = useRef<HTMLButtonElement>(null);
  useEffect(() => {
    const node = btnRef.current;
    if (!node || isDisabled) return;
    registerTrigger(node);
    return () => unregisterTrigger(node);
  }, [isDisabled, registerTrigger, unregisterTrigger]);

  // Find our index among triggers for navigation
  const myIdx = useMemo(
    () =>
      triggerNodes.findIndex((n: HTMLButtonElement) => n === btnRef.current),
    [triggerNodes, btnRef.current]
  );

  const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
    if (isDisabled) return;
    switch (e.key) {
      // 左右箭头随书写方向翻转;上下箭头语义不变。
      case 'ArrowRight':
        e.preventDefault();
        if (myIdx !== -1) {
          if (direction === 'rtl') focusPrev(myIdx);
          else focusNext(myIdx);
        }
        break;
      case 'ArrowLeft':
        e.preventDefault();
        if (myIdx !== -1) {
          if (direction === 'rtl') focusNext(myIdx);
          else focusPrev(myIdx);
        }
        break;
      case 'ArrowDown':
        e.preventDefault();
        if (myIdx !== -1 && focusNext) focusNext(myIdx);
        break;
      case 'ArrowUp':
        e.preventDefault();
        if (myIdx !== -1 && focusPrev) focusPrev(myIdx);
        break;
      case 'Home':
        e.preventDefault();
        if (focusFirst) focusFirst();
        break;
      case 'End':
        e.preventDefault();
        if (focusLast) focusLast();
        break;
      case 'Enter':
      case ' ':
        e.preventDefault();
        setActiveStep(step);
        break;
    }
  };

  const defaultProps = {
    role: 'tab',
    id,
    'aria-selected': isSelected,
    'aria-controls': panelValues.includes(step) ? panelId : undefined,
    tabIndex: typeof tabIndex === 'number' ? tabIndex : isSelected ? 0 : -1,
    'data-slot': 'stepper-trigger',
    'data-state': state,
    'data-loading': isLoading,
    className: cn(
      'focus-visible:border-ring focus-visible:ring-ring/50 inline-flex cursor-pointer items-center rounded-full outline-none focus-visible:z-sticky focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 pointer-coarse:min-h-11',
      'gap-2.5',
      className
    ),
    onClick: () => {
      if (!isDisabled) setActiveStep(step);
    },
    onKeyDown: handleKeyDown,
    disabled: isDisabled,
    children,
  };

  return useRender({
    defaultTagName: 'button',
    render,
    ref: btnRef,
    props: mergeProps<'button'>(defaultProps, props),
  });
}

function StepperIndicator({
  children,
  className,
}: React.ComponentProps<'div'>) {
  const { state, isLoading } = useStepItem();
  const { indicators } = useStepper();

  return (
    <div
      data-slot="stepper-indicator"
      data-state={state}
      className={cn(
        'border-background bg-muted text-muted-foreground data-[state=completed]:bg-primary data-[state=completed]:text-primary-foreground data-[state=active]:bg-primary data-[state=active]:text-primary-foreground relative flex size-6 shrink-0 items-center justify-center overflow-hidden motion-shift',
        'rounded-full text-xs',
        className
      )}
    >
      <div className="absolute">
        {indicators &&
        ((isLoading && indicators.loading) ||
          (state === 'completed' && indicators.completed) ||
          (state === 'active' && indicators.active) ||
          (state === 'inactive' && indicators.inactive))
          ? (isLoading && indicators.loading) ||
            (state === 'completed' && indicators.completed) ||
            (state === 'active' && indicators.active) ||
            (state === 'inactive' && indicators.inactive)
          : children}
      </div>
    </div>
  );
}

function StepperSeparator({ className }: React.ComponentProps<'div'>) {
  const { state } = useStepItem();

  return (
    <div
      data-slot="stepper-separator"
      data-state={state}
      className={cn(
        'bg-border m-0.5 motion-shift group-data-[orientation=horizontal]/stepper-nav:h-0.5 group-data-[orientation=horizontal]/stepper-nav:flex-1 group-data-[orientation=horizontal]/stepper-nav:rounded-full group-data-[orientation=vertical]/stepper-nav:h-12 group-data-[orientation=vertical]/stepper-nav:w-0.5',
        'data-[state=completed]:bg-primary',
        className
      )}
    />
  );
}

function StepperTitle({ children, className }: React.ComponentProps<'h3'>) {
  const { state } = useStepItem();

  return (
    <h3
      data-slot="stepper-title"
      data-state={state}
      className={cn(
        'text-sm leading-none font-medium text-muted-foreground data-[state=active]:text-foreground data-[state=completed]:text-foreground',
        className
      )}
    >
      {children}
    </h3>
  );
}

function StepperDescription({
  children,
  className,
}: React.ComponentProps<'div'>) {
  const { state } = useStepItem();

  return (
    <div
      data-slot="stepper-description"
      data-state={state}
      className={cn('text-muted-foreground text-sm', className)}
    >
      {children}
    </div>
  );
}

function StepperNav({ children, className, ...props }: React.ComponentProps<'nav'>) {
  const { activeStep, orientation } = useStepper();

  return (
    <nav
      role="tablist"
      aria-orientation={orientation}
      data-slot="stepper-nav"
      data-state={activeStep}
      data-orientation={orientation}
      className={cn(
        'group/stepper-nav inline-flex data-[orientation=horizontal]:w-full data-[orientation=horizontal]:flex-row data-[orientation=vertical]:flex-col',
        className
      )}
      {...props}
    >
      {children}
    </nav>
  );
}

function StepperPanel({
  children,
  className,
  value,
  ...props
}: React.ComponentProps<'div'> & {
  /** 关联的步骤号;提供时补 role=tabpanel 与 aria-labelledby */
  value?: number;
}) {
  const {
    activeStep,
    baseId,
    registerPanel,
    unregisterPanel,
    triggerNodes,
  } = useStepper();
  const tabId = value === undefined ? undefined : `${baseId}-tab-${value}`;
  // #37:纯展示形态没有 Trigger 时,tab id 不存在,不能输出悬空 aria-labelledby。
  const hasTrigger =
    tabId !== undefined && triggerNodes.some((node) => node.id === tabId);

  useEffect(() => {
    if (value === undefined) return;
    registerPanel(value);
    return () => unregisterPanel(value);
  }, [value, registerPanel, unregisterPanel]);

  return (
    <div
      data-slot="stepper-panel"
      data-state={
        value === undefined
          ? undefined
          : value === activeStep
            ? 'active'
            : 'inactive'
      }
      id={value === undefined ? undefined : `${baseId}-panel-${value}`}
      role={value === undefined ? undefined : 'tabpanel'}
      aria-labelledby={hasTrigger ? tabId : undefined}
      tabIndex={value === undefined ? undefined : 0}
      className={cn('w-full', className)}
      {...props}
    >
      {children}
    </div>
  );
}

interface StepperContentProps extends React.ComponentProps<'div'> {
  value: number;
  forceMount?: boolean;
}

function StepperContent({
  value,
  forceMount,
  children,
  className,
}: StepperContentProps) {
  const {
    activeStep,
    baseId,
    registerPanel,
    unregisterPanel,
    triggerNodes,
  } = useStepper();
  const isActive = value === activeStep;
  const hasTrigger = triggerNodes.some(
    (node) => node.id === `${baseId}-tab-${value}`
  );

  useEffect(() => {
    registerPanel(value);
    return () => unregisterPanel(value);
  }, [value, registerPanel, unregisterPanel]);

  if (!forceMount && !isActive) {
    return null;
  }

  return (
    <div
      data-slot="stepper-content"
      data-state={isActive ? 'active' : 'inactive'}
      id={`${baseId}-panel-${value}`}
      role="tabpanel"
      aria-labelledby={hasTrigger ? `${baseId}-tab-${value}` : undefined}
      tabIndex={0}
      className={cn('w-full', className, !isActive && forceMount && 'hidden')}
      hidden={!isActive && forceMount}
    >
      {children}
    </div>
  );
}

export {
  Stepper,
  StepperItem,
  StepperTrigger,
  StepperIndicator,
  StepperSeparator,
  StepperTitle,
  StepperDescription,
  StepperPanel,
  StepperContent,
  StepperNav,
  type StepperProps,
  type StepperItemProps,
  type StepperTriggerProps,
  type StepperContentProps,
  type StepIndicators,
  type StepState,
};

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

复合步骤条,由 Stepper/StepperNav/StepperItem/StepperTrigger/StepperIndicator 组合;受控用 value 与 onValueChange,纯展示可省略 Trigger。