diff --git a/package.json b/package.json index 712ada4a6d5..9db373ff09b 100644 --- a/package.json +++ b/package.json @@ -296,7 +296,8 @@ ".storybook-s2/**", "packages/dev/s2-docs/**", "starters/**", - "packages/react-aria-components/stories/Sheet.css" + "packages/react-aria-components/stories/Sheet.css", + "packages/react-aria-components/stories/StepList.css" ] }, "drafts": { diff --git a/packages/dev/s2-docs/pages/react-aria/StepList.mdx b/packages/dev/s2-docs/pages/react-aria/StepList.mdx new file mode 100644 index 00000000000..5f7312d41d3 --- /dev/null +++ b/packages/dev/s2-docs/pages/react-aria/StepList.mdx @@ -0,0 +1,172 @@ +import {Layout} from '../../src/Layout'; +export default Layout; + +import docs from 'docs:react-aria-components'; +import '../../tailwind/tailwind.css'; +import {InlineAlert, Heading, Content} from '@react-spectrum/s2'; + +export const tags = ['wizard', 'stepper', 'steps', 'progress', 'steplist']; +export const version = 'alpha'; +export const description = 'Displays the steps of a multi-step process, and which of them the user has completed.'; + +# StepList + +{docs.exports.StepList.description} + + + ```tsx render docs={docs.exports.StepList} links={docs.links} props={[]} type="vanilla" files={["starters/docs/src/StepList.tsx", "starters/docs/src/StepList.css"]} + "use client"; + import {StepList, StepListItem} from 'vanilla-starter/StepList'; + + + Cart + Shipping + Payment + Review + + ``` + + ```tsx render docs={docs.exports.StepList} links={docs.links} props={[]} type="tailwind" files={["starters/tailwind/src/StepList.tsx"]} + "use client"; + import {StepList, StepListItem} from 'tailwind-starter/StepList'; + + + Cart + Shipping + Payment + Review + + ``` + + + +## Content + +`StepList` follows the [Collection Components API](collections?component=StepList), accepting both static and dynamic collections. This example shows a dynamic collection, passing a list of objects to the `items` prop, and a function to render the children. + +```tsx render +"use client"; +import {StepList, StepListItem} from 'vanilla-starter/StepList'; + +let steps = [ + {id: 'account', label: 'Account'}, + {id: 'profile', label: 'Profile'}, + {id: 'settings', label: 'Settings'}, + {id: 'confirm', label: 'Confirm'} +]; + + + {step => {step.label}} + +``` + + + Accessibility + Provide an `aria-label` or `aria-labelledby` that describes the process, such as "Checkout". Each step announces whether it is completed, current, or not completed, and the current step is marked with `aria-current="step"`. + + +### Links + +Use the `href` prop on a `` to create a link to a step. In this example, only completed steps are links, so users can go back to a previous step, but not skip ahead. + +```tsx render files={["packages/dev/s2-docs/pages/react-aria/Router.tsx"]} +"use client"; +import {StepList, StepListItem} from 'vanilla-starter/StepList'; +import {Router, Link as RouterLink} from './Router'; + + + {({selectedRoute}) => ( + /*- begin highlight -*/ + 'href' in props ? :
}> + {/*- end highlight -*/} + Cart + Shipping + Payment + Review + + )} + +``` + +By default, links are rendered as an `` element. Use the `render` prop to integrate your framework's link component. + +```tsx + + 'href' in domProps + ? + :
+ } /> +``` + +## Current step + +Use the `selectedKey` prop to set the current step. The current step is marked with `aria-current="step"`, and the steps before it are marked as completed. Use the `data-current` and `data-completed` attributes to style them. + +```tsx render +"use client"; +import {StepList, StepListItem} from 'vanilla-starter/StepList'; +import {Button} from 'vanilla-starter/Button'; +import {useState} from 'react'; + +let steps = [ + {id: 'cart', label: 'Cart'}, + {id: 'shipping', label: 'Shipping'}, + {id: 'payment', label: 'Payment'}, + {id: 'review', label: 'Review'} +]; + +function Example() { + let [index, setIndex] = useState(1); + + return ( +
+ + {/*- end highlight -*/} + {step => {step.label}} + +
+ + +
+
+ ); +} +``` + +## StepList vs. Wizard + +Use a `StepList` to show a sequence of steps in a user flow, where each step corresponds to a separate page or route. +To allow random access and let users move between the steps they have reached without losing their progress, use a [Wizard](Wizard) instead. + +## API + +```tsx links={{StepList: '#steplist', StepListItem: '#steplistitem', StepListItemContent: '#steplistitemcontent'}} + + + + + +``` + +### StepList + + + +### StepListItem + + + +### StepListItemContent + + diff --git a/packages/dev/s2-docs/pages/react-aria/Wizard.mdx b/packages/dev/s2-docs/pages/react-aria/Wizard.mdx new file mode 100644 index 00000000000..bc8f64e02f0 --- /dev/null +++ b/packages/dev/s2-docs/pages/react-aria/Wizard.mdx @@ -0,0 +1,178 @@ +import {Layout} from '../../src/Layout'; +export default Layout; + +import docs from 'docs:react-aria-components'; +import '../../tailwind/tailwind.css'; +import {InlineAlert, Heading, Content} from '@react-spectrum/s2'; + +export const tags = ['stepper', 'steps', 'multi-step', 'form', 'flow']; +export const version = 'alpha'; +export const description = 'Guides users through a multi-step process one step at a time.'; + +# Wizard + +{docs.exports.Wizard.description} + + + ```tsx render docs={docs.exports.Wizard} links={docs.links} props={['allowsRandomAccess']} type="vanilla" files={["starters/docs/src/Wizard.tsx", "starters/docs/src/Wizard.css"]} + "use client"; + import {Wizard, WizardStepList, WizardStep, WizardPanels, WizardPanel, WizardButtons} from 'vanilla-starter/Wizard'; + + + + Details + Members + Review + + + Name your project and choose who can see it. + Invite people to work on the project with you. + Check the details, then create the project. + + + + ``` + + ```tsx render docs={docs.exports.Wizard} links={docs.links} props={['allowsRandomAccess']} type="tailwind" files={["starters/tailwind/src/Wizard.tsx"]} + "use client"; + import {Wizard, WizardStepList, WizardStep, WizardPanels, WizardPanel, WizardButtons} from 'tailwind-starter/Wizard'; + + + + Details + Members + Review + + + Name your project and choose who can see it. + Invite people to work on the project with you. + Check the details, then create the project. + + + + ``` + + + +## Content + +`WizardStepList` and `WizardPanels` follow the [Collection Components API](collections?component=WizardStepList), accepting both static and dynamic collections. This example shows a dynamic collection, passing a list of objects to the `items` prop, and a function to render the children. + +```tsx render +"use client"; +import {Wizard, WizardStepList, WizardStep, WizardPanels, WizardPanel, WizardButtons} from 'vanilla-starter/Wizard'; + +let steps = [ + {id: 'account', label: 'Account', content: 'Choose a username and password.'}, + {id: 'profile', label: 'Profile', content: 'Add a photo and a short bio.'}, + {id: 'settings', label: 'Settings', content: 'Choose which notifications you receive.'}, + {id: 'confirm', label: 'Confirm', content: 'Check your details, then create your account.'} +]; + + + + {/*- end highlight -*/} + {step => {step.label}} + + + {/*- end highlight -*/} + {step => {step.content}} + + + +``` + + + Accessibility + Provide an `aria-label` or `aria-labelledby` on the `WizardStepList` that describes the process, such as "Sign up". Each step announces whether it is completed, so hide visual indicators such as step numbers and checkmarks with `aria-hidden`. Steps are selected with the Enter or Space key rather than when they receive focus, so keyboard users can review the steps without leaving the current one. + + +## Current step + +Use the `defaultSelectedKey` or `selectedKey` prop to set the current step. The selected key corresponds to the `id` prop of a ``. Steps before the current step are marked as completed, and steps the user hasn't reached yet are disabled. Use the `data-current` and `data-completed` attributes to style them. + +```tsx render +"use client"; +import type {Key} from 'react-aria-components/Wizard'; +import {Wizard, WizardStepList, WizardStep, WizardPanels, WizardPanel, WizardButtons} from 'vanilla-starter/Wizard'; +import {useState} from 'react'; + +function Example() { + let [step, setStep] = useState('members'); + + return ( +
+ + + Details + Members + Review + + + Name your project and choose who can see it. + Invite people to work on the project with you. + Check the details, then create the project. + + + +

Current step: {step}

+
+ ); +} +``` + +Users can go back to any step they have reached, and return to where they left off. Set `allowsRandomAccess` to let users select any step. To restore saved progress, set `defaultLastCompletedStep` to the last step the user completed, or control it with the `lastCompletedStep` and `onLastCompletedStepChange` props. + +## Wizard vs. StepList + +Use a `Wizard` when the content of each step is shown on the same page, and users move between the steps they have reached. When each step is a separate page or route, use a [StepList](StepList) instead to show the user's progress through the process. + +## API + +```tsx links={{Wizard: '#wizard', WizardStepList: '#wizardsteplist', WizardStep: '#wizardstep', WizardPanels: '#wizardpanels', WizardPanel: '#wizardpanel'}} + + + + + + + + +``` + +### Wizard + + + +### WizardStepList + + + +### WizardStep + + + +### WizardPanels + + + +### WizardPanel + + diff --git a/packages/react-aria-components/exports/StepList.ts b/packages/react-aria-components/exports/StepList.ts new file mode 100644 index 00000000000..861cd297e4f --- /dev/null +++ b/packages/react-aria-components/exports/StepList.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ + +// Mark as a client only package. This will cause a build time error if you try +// to import it from a React Server Component in a framework like Next.js. +import 'client-only'; + +export {StepList, StepListContext, StepListItem, StepListItemContent} from '../src/StepList'; +export type { + StepListProps, + StepListItemProps, + StepListItemRenderProps, + StepListItemContentProps +} from '../src/StepList'; +export type {Key} from '@react-types/shared'; diff --git a/packages/react-aria-components/exports/Wizard.ts b/packages/react-aria-components/exports/Wizard.ts new file mode 100644 index 00000000000..7cca9ffa450 --- /dev/null +++ b/packages/react-aria-components/exports/Wizard.ts @@ -0,0 +1,29 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ + +// Mark as a client only package. This will cause a build time error if you try +// to import it from a React Server Component in a framework like Next.js. +import 'client-only'; + +export {Wizard, WizardStepList, WizardStep, WizardPanels, WizardPanel} from '../src/Wizard'; +export type { + WizardProps, + WizardStepListProps, + WizardStepProps, + WizardStepRenderProps, + WizardPanelsProps, + WizardPanelProps, + WizardStepAria, + WizardState, + WizardStateOptions +} from '../src/Wizard'; +export type {Key} from '@react-types/shared'; diff --git a/packages/react-aria-components/exports/index.ts b/packages/react-aria-components/exports/index.ts index 0b2816f589c..7865ade031e 100644 --- a/packages/react-aria-components/exports/index.ts +++ b/packages/react-aria-components/exports/index.ts @@ -196,6 +196,7 @@ export { SliderFillContext, SliderStateContext } from '../src/Slider'; +export {StepList, StepListContext, StepListItem, StepListItemContent} from '../src/StepList'; export {Switch, SwitchField, SwitchButton, SwitchContext, SwitchFieldContext} from '../src/Switch'; export { TableLoadMoreItem, @@ -263,6 +264,7 @@ export { TreeSection, TreeStateContext } from '../src/Tree'; +export {Wizard, WizardStepList, WizardStep, WizardPanels, WizardPanel} from '../src/Wizard'; export {useDrag} from 'react-aria/useDrag'; export { useDrop, @@ -472,6 +474,12 @@ export type { SliderFillRenderProps, SliderThumbRenderProps } from '../src/Slider'; +export type { + StepListProps, + StepListItemProps, + StepListItemRenderProps, + StepListItemContentProps +} from '../src/StepList'; export type { SwitchProps, SwitchRenderProps, @@ -559,6 +567,17 @@ export type { TreeLoadMoreItemProps, TreeLoadMoreItemRenderProps } from '../src/Tree'; +export type { + WizardProps, + WizardStepListProps, + WizardStepProps, + WizardStepRenderProps, + WizardPanelsProps, + WizardPanelProps, + WizardStepAria, + WizardState, + WizardStateOptions +} from '../src/Wizard'; export type {DragOptions, DragResult} from 'react-aria/useDrag'; export type { DragAndDropHooks, diff --git a/packages/react-aria-components/intl/en-US.json b/packages/react-aria-components/intl/en-US.json index 52a68863139..ace67856c2d 100644 --- a/packages/react-aria-components/intl/en-US.json +++ b/packages/react-aria-components/intl/en-US.json @@ -2,5 +2,8 @@ "selectPlaceholder": "Select an item", "tableResizer": "Resizer", "dropzoneLabel": "DropZone", - "colorSwatchPicker": "Color swatches" + "colorSwatchPicker": "Color swatches", + "stepListItemCurrent": "Current", + "stepListItemCompleted": "Completed", + "stepListItemNotCompleted": "Not completed" } diff --git a/packages/react-aria-components/src/StepList.tsx b/packages/react-aria-components/src/StepList.tsx new file mode 100644 index 00000000000..b2c7c51d718 --- /dev/null +++ b/packages/react-aria-components/src/StepList.tsx @@ -0,0 +1,282 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ + +import { + AriaLabelingProps, + forwardRefType, + GlobalDOMAttributes, + Key, + LinkDOMProps, + Node +} from '@react-types/shared'; +import { + ClassNameOrFunction, + ContextValue, + dom, + DOMProps, + DOMRenderProps, + PossibleLinkDOMRenderProps, + RenderProps, + SlotProps, + StyleProps, + useContextProps, + useRenderProps +} from './utils'; +import {Collection} from 'react-aria/Collection'; +import {CollectionBuilder, createLeafComponent} from 'react-aria/CollectionBuilder'; +import {CollectionNode} from 'react-aria/private/collections/BaseCollection'; +import {CollectionProps, CollectionRendererContext} from './Collection'; +import {filterDOMProps} from 'react-aria/filterDOMProps'; +import intlMessages from '../intl/*.json'; +import {mergeProps} from 'react-aria/mergeProps'; +import React, {createContext, ForwardedRef, forwardRef, useContext} from 'react'; +import {useFocusRing} from 'react-aria/useFocusRing'; +import {useHover} from 'react-aria/useHover'; +import {useId} from 'react-aria/useId'; +import {useLink} from 'react-aria/useLink'; +import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter'; +import {useObjectRef} from 'react-aria/useObjectRef'; + +export interface StepListProps + extends + Omit, 'disabledKeys'>, + StyleProps, + SlotProps, + AriaLabelingProps, + DOMRenderProps<'ol', undefined>, + GlobalDOMAttributes { + /** + * The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the + * element. + * + * @default 'react-aria-StepList' + */ + className?: string; + /** + * The `id` of the currently selected `StepListItem`. Steps before it in the collection are marked + * as completed, and steps after it are marked as not completed. + */ + selectedKey: Key; +} + +export const StepListContext = + createContext, HTMLOListElement>>(null); + +interface StepListState { + /** The key of the currently selected step. */ + selectedKey: Key; + /** The index of the currently selected step within the collection, or -1 if it isn't present. */ + selectedIndex: number; +} + +const InternalStepListContext = createContext(null); + +/** + * A StepList displays the steps of a multi-step process, and which of them the user has completed. + */ +export const StepList = /*#__PURE__*/ (forwardRef as forwardRefType)(function StepList( + props: StepListProps, + ref: ForwardedRef +) { + [props, ref] = useContextProps(props, ref, StepListContext); + let {CollectionRoot} = useContext(CollectionRendererContext); + let {selectedKey} = props; + let DOMProps = filterDOMProps(props, {global: true, labelable: true}); + + return ( + }> + {collection => ( + + + + + + )} + + ); +}); + +export interface StepListItemRenderProps { + /** + * Whether the step is the currently selected step. + * + * @selector [data-current] + */ + isCurrent: boolean; + /** + * Whether the step is rendered before the currently selected step. + * + * @selector [data-completed] + */ + isCompleted: boolean; + /** The position of the step within the `StepList`, starting from 1. */ + stepNumber: number; +} + +export interface StepListItemProps + extends + RenderProps, + GlobalDOMAttributes, + AriaLabelingProps { + /** + * The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the + * element. A function may be provided to compute the class based on component state. + * + * @default 'react-aria-StepListItem' + */ + className?: ClassNameOrFunction; + /** A unique id for the step, which is compared against the `selectedKey` of the `StepList`. */ + id?: Key; +} + +class StepListItemNode extends CollectionNode { + static readonly type = 'item'; +} + +/** + * A StepListItem represents an individual step within a ``. + */ +export const StepListItem = /*#__PURE__*/ createLeafComponent( + StepListItemNode, + function StepListItem( + props: StepListItemProps, + ref: ForwardedRef, + node: Node + ) { + let state = useContext(InternalStepListContext); + let stringFormatter = useLocalizedStringFormatter(intlMessages, 'react-aria-components'); + let hiddenId = useId(); + + let isCurrent = state != null && node.key === state.selectedKey; + // A step is completed if it comes before the current step in the collection. + let isCompleted = state != null && state.selectedIndex >= 0 && node.index < state.selectedIndex; + + let renderProps = useRenderProps({ + ...node.props, + children: node.rendered, + values: {isCurrent, isCompleted, stepNumber: node.index + 1}, + defaultClassName: 'react-aria-StepListItem' + }); + + let DOMProps = filterDOMProps(props as any, {global: true, labelable: true}); + // `id` identifies the step rather than the DOM element, so it is not forwarded to the DOM. + delete DOMProps.id; + + let message = stringFormatter.format('stepListItemNotCompleted'); + if (isCurrent) { + message = stringFormatter.format('stepListItemCurrent'); + } else if (isCompleted) { + message = stringFormatter.format('stepListItemCompleted'); + } + + return ( + + + + {renderProps.children} + + + ); + } +); + +export interface StepListItemContentProps + extends + DOMProps, + LinkDOMProps, + AriaLabelingProps, + PossibleLinkDOMRenderProps<'div', undefined>, + Omit, 'onClick'> {} + +const StepListItemContext = createContext<{hiddenId: string | undefined} | undefined>(undefined); + +/** + * A StepListItemContent renders the content of a ``, optionally as a link to the + * step. + */ +export const StepListItemContent = /*#__PURE__*/ (forwardRef as forwardRefType)( + function StepListItemContent( + props: StepListItemContentProps, + ref: ForwardedRef + ) { + // Remount when switching between a link and a plain `div`. A focused link that is removed never + // receives a blur event, so its focus state would otherwise carry over to the new element. + return ( + + ); + } +); + +interface StepListItemContentInnerProps { + props: StepListItemContentProps; + contentRef: ForwardedRef; +} + +function StepListItemContentInner({props, contentRef: ref}: StepListItemContentInnerProps) { + let context = useContext(StepListItemContext); + let objRef = useObjectRef(ref); + let id = useId(); + // A step is only navigable when it is given an `href`. Otherwise `role="img"` is applied to a + // non-focusable element purely so that screen readers treat the contents as a single unit. + let isLink = props.href != null; + let elementType = isLink ? 'a' : 'div'; + let {linkProps} = useLink({...props, elementType}, objRef); + let ElementType = dom[elementType]; + // Only a link is interactive, so a plain `div` never reports hover or focus. + let {hoverProps, isHovered} = useHover({isDisabled: !isLink}); + let {focusProps, isFocusVisible} = useFocusRing(); + let DOMProps = filterDOMProps(props, {global: true, labelable: true, isLink}); + delete DOMProps.id; + + let ariaLabeledBy = props['aria-labelledby'] + ? `${context?.hiddenId} ${props['aria-labelledby']}` + : `${context?.hiddenId} ${id}`; + + return ( + + {props.children} + + ); +} diff --git a/packages/react-aria-components/src/Tabs.tsx b/packages/react-aria-components/src/Tabs.tsx index c4cde0191c9..cd8d4a72291 100644 --- a/packages/react-aria-components/src/Tabs.tsx +++ b/packages/react-aria-components/src/Tabs.tsx @@ -426,7 +426,10 @@ export const Tab = /*#__PURE__*/ createLeafComponent( }); let ElementType = item.props.href ? dom.a : dom.div; - let DOMProps = filterDOMProps(props as any, {global: true}); + let DOMProps = filterDOMProps(props as any, { + global: true, + propNames: new Set(['aria-current']) + }); delete DOMProps.id; delete DOMProps.onClick; diff --git a/packages/react-aria-components/src/Wizard.tsx b/packages/react-aria-components/src/Wizard.tsx new file mode 100644 index 00000000000..4c624b1c9e1 --- /dev/null +++ b/packages/react-aria-components/src/Wizard.tsx @@ -0,0 +1,508 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +import {ClassNameOrFunction, PossibleLinkDOMRenderProps, RenderProps} from './utils'; +import {CollectionBuilder} from 'react-aria/CollectionBuilder'; +import {FocusableElement, forwardRefType, RefObject} from '@react-types/shared'; +import {Collection as ICollection, Key, Node} from '@react-types/shared'; +import intlMessages from '../intl/*.json'; +import React, { + createContext, + ForwardedRef, + forwardRef, + ReactElement, + ReactNode, + useContext, + useMemo, + useState +} from 'react'; +import { + Tab, + TabList, + TabListProps, + TabListRenderProps, + TabPanel, + TabPanelProps, + TabPanelRenderProps, + TabPanels, + TabPanelsProps, + TabProps, + TabRenderProps, + Tabs, + TabsProps, + TabsRenderProps +} from './Tabs'; +import {useControlledState} from 'react-stately/useControlledState'; +import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter'; +import {useObjectRef} from 'react-aria/useObjectRef'; +import {VisuallyHidden} from 'react-aria/VisuallyHidden'; + +export interface WizardProps extends Omit { + /** The children of the component (a `WizardStepList` and optional `WizardPanels`). */ + children?: ReactNode; + /** + * The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the + * element. A function may be provided to compute the class based on component state. + * + * @default 'react-aria-Wizard' + */ + className?: ClassNameOrFunction; + /** The currently selected step (controlled). */ + selectedKey?: Key | null; + /** The initially selected step (uncontrolled). */ + defaultSelectedKey?: Key; + /** Handler called when the selected step changes. */ + onSelectionChange?: (key: Key) => void; + /** + * The key of the last completed step (controlled). Every step up to and including the one after + * it is navigable by default. + */ + lastCompletedStep?: Key | null; + /** The key of the initially last completed step (uncontrolled). */ + defaultLastCompletedStep?: Key; + /** + * Handler called when selecting a step completes the steps before it, in the same event as + * `onSelectionChange`. + */ + onLastCompletedStepChange?: (key: Key | null) => void; + /** + * Whether every step that is not in `disabledKeys` is navigable at any time, rather than only + * completed steps and the one after them. + */ + allowsRandomAccess?: boolean; +} + +/** + * A Wizard guides users through a multi-step process one step at a time, and allows them to + * navigate between the steps they have reached. + */ +export const Wizard = /*#__PURE__*/ forwardRef(function Wizard( + props: WizardProps, + ref: ForwardedRef +) { + let {children} = props; + return ( + + {collection => } + + ); +}); + +// Passes the wizard's default class name to className functions, rather than the one of the +// Tabs component it wraps. +function withDefaultClassName( + className: ClassNameOrFunction | undefined, + defaultClassName: string +): ClassNameOrFunction { + return typeof className === 'function' + ? values => className({...values, defaultClassName}) + : (className ?? defaultClassName); +} + +interface WizardInnerProps { + props: WizardProps; + collection: ICollection>; + tabsRef: ForwardedRef; +} + +// Steps are rendered into the collection outside of the TabListStateContext, so the wizard provides +// its state to them directly. +const WizardStateContext = createContext | null>(null); + +export interface WizardStateOptions { + /** The collection of steps, in order. */ + collection: ICollection>; + /** The currently selected step (controlled). */ + selectedKey?: Key | null; + /** The initially selected step (uncontrolled). */ + defaultSelectedKey?: Key; + /** Handler called when the selected step changes. */ + onSelectionChange?: (key: Key) => void; + /** The key of the last completed step (controlled). */ + lastCompletedStep?: Key | null; + /** The key of the initially last completed step (uncontrolled). */ + defaultLastCompletedStep?: Key; + /** + * Handler called when selecting a step completes the steps before it, in the same event as + * `onSelectionChange`. + */ + onLastCompletedStepChange?: (key: Key | null) => void; + /** Whether every step that is not in `disabledKeys` is navigable at any time. */ + allowsRandomAccess?: boolean; + /** The step keys that are disabled. These steps are never navigable. */ + disabledKeys?: Iterable; +} + +export interface WizardState { + /** The collection of steps. */ + collection: ICollection>; + /** The current (selected) step. */ + selectedKey: Key | null; + /** Sets the current (selected) step. */ + setSelectedKey(key: Key): void; + /** + * The key of the last completed step. Every step up to and including the one after it is + * navigable by default. + */ + lastCompletedStep: Key | null; + /** + * Keys that are not navigable. + */ + disabledKeys: Set; +} + +/** + * This hook controls the selected step and tracks the last completed step so it can derive which + * steps are navigable. Completed steps and the current step are navigable; upcoming steps are not + * unless random access is allowed. Unless it's controlled, the last completed step is derived from + * the selection: it advances as the selection moves forward and is never rolled back, so previously + * reached steps stay navigable after navigating backwards. `onLastCompletedStepChange` is called in + * the same event as `onSelectionChange`, so a controlled last completed step can be updated along + * with the selection. + */ +export function useWizardState(props: WizardStateOptions): WizardState { + let { + collection, + allowsRandomAccess = false, + disabledKeys: disabledStepKeys, + onSelectionChange, + onLastCompletedStepChange + } = props; + + let [selectedKeyState, setSelectedKeyState] = useControlledState( + props.selectedKey, + props.defaultSelectedKey ?? null, + onSelectionChange + ? key => { + if (key != null) { + onSelectionChange(key); + } + } + : undefined + ); + + let selectedKey = selectedKeyState ?? collection.getFirstKey(); + + let isLastCompletedStepControlled = props.lastCompletedStep !== undefined; + let [lastCompletedStepState, setLastCompletedStepState] = useState( + props.defaultLastCompletedStep ?? null + ); + let lastCompletedStep = isLastCompletedStepControlled + ? (props.lastCompletedStep ?? null) + : lastCompletedStepState; + let lastCompletedIndex = getStepIndex(collection, lastCompletedStep); + + // Steps are ordered by getKeyBefore and getKeyAfter, which Tabs also uses to move focus. + let stepBeforeSelected = selectedKey != null ? collection.getKeyBefore(selectedKey) : null; + let stepBeforeSelectedIndex = getStepIndex(collection, stepBeforeSelected); + + // When uncontrolled, every step before the selected step is completed. Store it during render + // rather than syncing it in an effect, so it's correct on the first render and isn't rolled back + // when the selection moves backwards, even if the selection is controlled. + if (!isLastCompletedStepControlled && stepBeforeSelectedIndex > lastCompletedIndex) { + lastCompletedIndex = stepBeforeSelectedIndex; + lastCompletedStep = stepBeforeSelected; + setLastCompletedStepState(lastCompletedStep); + } + + // Notify in the same event as the selection change, so a controlled lastCompletedStep can be + // updated along with the selection. + let setSelectedKey = (key: Key) => { + setSelectedKeyState(key); + let stepBefore = collection.getKeyBefore(key); + if (getStepIndex(collection, stepBefore) > lastCompletedIndex) { + onLastCompletedStepChange?.(stepBefore); + } + }; + + let disabledKeys = useMemo(() => { + // Steps disabled by the consumer are never navigable, however the wizard is configured. + let set = new Set(disabledStepKeys); + if (!allowsRandomAccess) { + // Completed steps, the step after them, and the current step are navigable. The steps after + // those are upcoming, and are only navigable if allowsRandomAccess. + let nextStep = + lastCompletedStep != null && collection.getItem(lastCompletedStep) + ? collection.getKeyAfter(lastCompletedStep) + : collection.getFirstKey(); + let key = nextStep != null ? collection.getKeyAfter(nextStep) : null; + while (key != null) { + if (key !== selectedKey) { + set.add(key); + } + key = collection.getKeyAfter(key); + } + } + return set; + }, [collection, selectedKey, lastCompletedStep, allowsRandomAccess, disabledStepKeys]); + + return { + collection, + selectedKey, + setSelectedKey, + lastCompletedStep, + disabledKeys + }; +} + +// The position of a step within the wizard, or -1 if the key isn't one of its steps. +function getStepIndex(collection: ICollection>, key: Key | null): number { + return key != null ? (collection.getItem(key)?.index ?? -1) : -1; +} + +function WizardInner({props, collection, tabsRef: ref}: WizardInnerProps) { + let { + children, + className, + selectedKey, + defaultSelectedKey, + onSelectionChange, + lastCompletedStep, + defaultLastCompletedStep, + onLastCompletedStepChange, + allowsRandomAccess, + disabledKeys, + ...tabsProps + } = props; + + let state = useWizardState({ + collection, + selectedKey, + defaultSelectedKey, + onSelectionChange, + lastCompletedStep, + defaultLastCompletedStep, + onLastCompletedStepChange, + allowsRandomAccess, + disabledKeys + }); + + // Tabs treats null as a controlled empty selection, so passing it rather than undefined keeps Tabs + // controlled while there is no selected step (e.g. before the collection is populated). + return ( + + + {children} + + + ); +} + +export interface WizardStepListProps extends TabListProps { + /** + * The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the + * element. A function may be provided to compute the class based on component state. + * + * @default 'react-aria-WizardStepList' + */ + className?: ClassNameOrFunction; +} + +/** + * A WizardStepList groups the steps within a ``. The ids of its steps must match up with a + * corresponding `` inside the ``. + */ +export const WizardStepList = /*#__PURE__*/ (forwardRef as forwardRefType)(function WizardStepList< + T extends object +>(props: WizardStepListProps, ref: ForwardedRef) { + return ( + + ); +}); + +export interface WizardStepRenderProps extends TabRenderProps { + /** + * Whether the step is the current step. + * + * @selector [data-current] + */ + isCurrent: boolean; + /** + * Whether the step is at or before the last completed step. + * + * @selector [data-completed] + */ + isCompleted: boolean; + /** The position of the step within the `WizardStepList`, starting from 1. */ + stepNumber: number; +} + +export interface WizardStepProps + extends + Omit, + Omit, 'render'>, + PossibleLinkDOMRenderProps<'div', WizardStepRenderProps> { + /** + * The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the + * element. A function may be provided to compute the class based on component state. + * + * @default 'react-aria-WizardStep' + */ + className?: ClassNameOrFunction; +} + +export interface WizardStepAria { + /** Whether this step is the current (selected) step. */ + isCurrent: boolean; + /** Whether this step is at or before the last completed step. */ + isCompleted: boolean; + /** The position of the step within the wizard, starting from 1. */ + stepNumber: number; +} + +interface AriaWizardStepProps { + /** The key of the step. */ + key: Key; +} + +/** + * Provides the state of a step within a wizard: whether it is the current step, whether it has + * already been completed (it is at or before the last completed step), and its position. + */ +export function useWizardStep( + props: AriaWizardStepProps, + state: WizardState, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + ref: RefObject +): WizardStepAria { + let {key} = props; + let {collection, selectedKey, lastCompletedStep} = state; + let index = getStepIndex(collection, key); + let selectedIndex = getStepIndex(collection, selectedKey); + let lastCompletedIndex = getStepIndex(collection, lastCompletedStep); + + return { + isCurrent: index >= 0 && index === selectedIndex, + isCompleted: index >= 0 && index <= lastCompletedIndex, + stepNumber: index + 1 + }; +} + +/** + * A WizardStep represents an individual step within a ``. + */ +export const WizardStep = /*#__PURE__*/ forwardRef(function WizardStep( + props: WizardStepProps, + ref: ForwardedRef +) { + let state = useContext(WizardStateContext); + // The Wizard renders its steps before its state exists to build the collection the state is + // computed from, which only needs the keys of the steps. + if (!state) { + return ; + } + + return ; +}) as (props: WizardStepProps & {ref?: ForwardedRef}) => ReactElement; + +interface WizardStepInnerProps { + props: WizardStepProps; + state: WizardState; + stepRef: ForwardedRef; +} + +function WizardStepInner({props, state, stepRef}: WizardStepInnerProps) { + let {children, className, style, render, ...otherProps} = props; + let ref = useObjectRef(stepRef); + let {isCurrent, isCompleted, stepNumber} = useWizardStep({key: props.id!}, state, ref); + let stringFormatter = useLocalizedStringFormatter(intlMessages, 'react-aria-components'); + let stateText = isCompleted + ? stringFormatter.format('stepListItemCompleted') + : stringFormatter.format('stepListItemNotCompleted'); + + // Adds the step state to the render props that Tab provides. + let getRenderProps = (renderProps: R): R & WizardStepRenderProps => ({ + ...renderProps, + isCurrent, + isCompleted, + stepNumber + }); + + return ( + ( + typeof className === 'function' ? values => className(getRenderProps(values)) : className, + 'react-aria-WizardStep' + )} + style={typeof style === 'function' ? values => style(getRenderProps(values)) : style} + render={render ? (domProps, values) => render(domProps, getRenderProps(values)) : undefined} + aria-current={isCurrent ? 'step' : undefined} + data-current={isCurrent || undefined} + data-completed={isCompleted || undefined}> + {renderProps => ( + <> + {!isCurrent && {stateText}} + {typeof children === 'function' ? children(getRenderProps(renderProps)) : children} + + )} + + ); +} + +export interface WizardPanelsProps extends TabPanelsProps { + /** + * The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the + * element. + * + * @default 'react-aria-WizardPanels' + */ + className?: string; +} + +/** + * Groups multiple `` elements, and provides CSS variables for animated transitions. + */ +export const WizardPanels = /*#__PURE__*/ (forwardRef as forwardRefType)(function WizardPanels< + T extends object +>(props: WizardPanelsProps, ref: ForwardedRef) { + return ( + + ); +}); + +export interface WizardPanelProps extends TabPanelProps { + /** + * The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the + * element. A function may be provided to compute the class based on component state. + * + * @default 'react-aria-WizardPanel' + */ + className?: ClassNameOrFunction; +} + +/** + * A WizardPanel provides the content for a step. + */ +export const WizardPanel = /*#__PURE__*/ forwardRef(function WizardPanel( + props: WizardPanelProps, + ref: ForwardedRef +) { + return ( + + ); +}); diff --git a/packages/react-aria-components/stories/StepList.css b/packages/react-aria-components/stories/StepList.css new file mode 100644 index 00000000000..7a1c8ef632c --- /dev/null +++ b/packages/react-aria-components/stories/StepList.css @@ -0,0 +1,78 @@ +.react-aria-StepList { + display: flex; + gap: 12px; + margin: 0; + padding: 0 0 24px; + list-style: none; +} + +.react-aria-StepListItem { + --marker-background: var(--spectrum-global-color-gray-200); + --marker-color: var(--spectrum-global-color-gray-700); + --label-color: var(--spectrum-global-color-gray-700); + --line: 2px dashed var(--spectrum-global-color-gray-400); + + display: flex; + align-items: center; + gap: 12px; + + &[data-current], + &[data-completed] { + --marker-background: var(--spectrum-global-color-gray-800); + --marker-color: var(--spectrum-global-color-gray-50); + --label-color: var(--spectrum-global-color-gray-900); + } + + &[data-completed] { + --line: 2px solid var(--spectrum-global-color-gray-800); + } + + /* The connector drawn between this step and the one after it. */ + &:not(:last-child)::after { + content: ''; + width: 96px; + border-top: var(--line); + } + + .marker { + position: relative; + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border-radius: 8px; + background: var(--marker-background); + color: var(--marker-color); + font-size: 14px; + } + + .label { + position: absolute; + top: 28px; + left: 50%; + transform: translateX(-50%); + color: var(--label-color); + font-size: 12px; + white-space: nowrap; + } +} + +.react-aria-StepListItemContent { + /* Stretch over the marker so links have a sensible hit area and focus ring. The label is + absolutely positioned against this element, which occupies the same box as the marker. */ + position: absolute; + inset: 0; + border-radius: inherit; + color: inherit; + text-decoration: none; + + &:is(a)[data-hovered] .label { + text-decoration: underline; + } + + &[data-focus-visible] { + outline: 2px solid var(--spectrum-alias-focus-ring-color); + outline-offset: 2px; + } +} diff --git a/packages/react-aria-components/stories/StepList.stories.tsx b/packages/react-aria-components/stories/StepList.stories.tsx new file mode 100644 index 00000000000..bfb04816d4a --- /dev/null +++ b/packages/react-aria-components/stories/StepList.stories.tsx @@ -0,0 +1,137 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ + +import {Meta, StoryObj} from '@storybook/react'; +import React, {ReactNode} from 'react'; +import {StepList, StepListItem, StepListItemContent} from '../src/StepList'; +import './StepList.css'; + +const steps = [ + {id: 'domain', label: 'Domain/Sender details', href: '#domain'}, + {id: 'dns', label: 'Configure DNS', href: '#dns'}, + {id: 'advanced', label: 'Advanced settings', href: '#advanced'} +]; + +export default { + title: 'React Aria Components/StepList', + component: StepList, + args: { + selectedKey: 'dns' + }, + argTypes: { + selectedKey: { + control: 'radio', + options: steps.map(step => step.id) + } + } +} as Meta; + +export type StepListStory = StoryObj; + +function CheckIcon(): ReactNode { + return ( + + ); +} + +export const StepListExample: StepListStory = { + render: (args: any) => ( +
+ + + {steps.map(step => ( + + {({isCompleted, stepNumber}) => ( + + {isCompleted ? ( + + ) : ( + + )} + + {step.label} + + + )} + + ))} + +
+ ) +}; + +export const StepListDynamic: StepListStory = { + render: (args: any) => ( +
+ + + {(step: (typeof steps)[number]) => ( + + {({isCompleted, stepNumber}) => ( + + {isCompleted ? ( + + ) : ( + + )} + + {step.label} + + + )} + + )} + +
+ ) +}; + +export const StepListLinks: StepListStory = { + render: (args: any) => ( +
+ + + {(step: (typeof steps)[number]) => ( + + {({isCompleted, stepNumber}) => ( + + {isCompleted ? ( + + ) : ( + + )} + {/* Every step has an href, but only completed steps can be navigated back to. */} + + {step.label} + + + )} + + )} + +
+ ) +}; diff --git a/packages/react-aria-components/stories/Wizard.css b/packages/react-aria-components/stories/Wizard.css new file mode 100644 index 00000000000..fd662aa0a5f --- /dev/null +++ b/packages/react-aria-components/stories/Wizard.css @@ -0,0 +1,115 @@ +.wizard { + /* Width of the chevron notch cut into each end of a step. */ + --arrow: 14px; + /* How far a step slides under the previous one so the chevrons interlock. */ + --overlap: 12px; + --padding: 12px; + + .react-aria-WizardStepList { + display: flex; + overflow-x: auto; + overflow-y: hidden; + border-radius: 16px; + background: var(--spectrum-global-color-gray-300); + } + + .react-aria-WizardStep { + display: flex; + flex: 1 1 0; + align-items: center; + gap: 8px; + min-width: 0; + padding: 8px calc(var(--arrow) + var(--padding)); + margin-left: calc(-1 * var(--overlap)); + background: var(--spectrum-global-color-gray-200); + outline: none; + cursor: pointer; + clip-path: polygon( + 0 0, + calc(100% - var(--arrow)) 0, + 100% 50%, + calc(100% - var(--arrow)) 100%, + 0 100%, + var(--arrow) 50% + ); + + &:first-child { + padding-left: var(--padding); + margin-left: 0; + clip-path: polygon( + 0 0, + calc(100% - var(--arrow)) 0, + 100% 50%, + calc(100% - var(--arrow)) 100%, + 0 100% + ); + } + + &:last-child { + padding-right: var(--padding); + clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%, var(--arrow) 50%); + } + + &[data-selected], + &[data-hovered] { + background: var(--spectrum-global-color-gray-100); + } + + /* Steps that are not navigable yet, or every step but the current one when read only. */ + &[data-disabled] { + cursor: default; + } + + &[data-focus-visible] .marker { + outline: 2px solid var(--spectrum-alias-focus-ring-color); + outline-offset: 2px; + } + } + + .marker { + display: flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 9999px; + background: var(--spectrum-global-color-gray-400); + color: var(--spectrum-global-color-gray-800); + font-size: 14px; + } + + [data-completed] .marker { + background: var(--spectrum-global-color-green-600); + color: var(--spectrum-global-color-gray-50); + } + + [data-current] .marker { + background: var(--spectrum-global-color-blue-600); + color: var(--spectrum-global-color-gray-50); + } + + .text { + display: flex; + flex-direction: column; + min-width: 0; + overflow: hidden; + } + + .label, + .position { + overflow: hidden; + font-size: 12px; + line-height: 1.5; + white-space: nowrap; + text-overflow: ellipsis; + } + + .label { + color: var(--spectrum-global-color-gray-800); + } + + .position { + color: var(--spectrum-global-color-gray-700); + } +} diff --git a/packages/react-aria-components/stories/Wizard.stories.tsx b/packages/react-aria-components/stories/Wizard.stories.tsx new file mode 100644 index 00000000000..490f771448c --- /dev/null +++ b/packages/react-aria-components/stories/Wizard.stories.tsx @@ -0,0 +1,93 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ + +import {Meta, StoryObj} from '@storybook/react'; +import React, {ReactNode} from 'react'; +import {Wizard, WizardStep, WizardStepList} from '../src/Wizard'; +import './Wizard.css'; + +const steps = [ + {id: 'domain', label: 'Domain/Sender details'}, + {id: 'dns', label: 'Configure DNS'}, + {id: 'advanced', label: 'Advanced settings'} +]; + +export default { + title: 'React Aria Components/Wizard', + component: Wizard, + args: { + allowsRandomAccess: false + } +} as Meta; + +export type WizardStory = StoryObj; + +function CheckIcon(): ReactNode { + return ( + + ); +} + +// The number and check mark repeat the label and the state that `WizardStep` already announces, +// so they are decorative. +function StepMarker({ + isCompleted, + stepNumber +}: { + isCompleted: boolean; + stepNumber: number; +}): ReactNode { + return ( + + ); +} + +export const WizardExample: WizardStory = { + render: (args: any) => ( +
+ + + + {steps.map(step => ( + + {({isCompleted, stepNumber}) => ( + <> + + + {step.label} + + Step {stepNumber} of {steps.length} + + + + )} + + ))} + + +
+ ) +}; diff --git a/packages/react-aria-components/test/StepList.test.js b/packages/react-aria-components/test/StepList.test.js new file mode 100644 index 00000000000..e610eb6fe60 --- /dev/null +++ b/packages/react-aria-components/test/StepList.test.js @@ -0,0 +1,429 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ + +import {pointerMap, render} from '@react-spectrum/test-utils-internal'; +import React from 'react'; +import {StepList, StepListContext, StepListItem, StepListItemContent} from '../src/StepList'; +import userEvent from '@testing-library/user-event'; + +let steps = [ + {id: 'domain', label: 'Domain'}, + {id: 'dns', label: 'DNS'}, + {id: 'advanced', label: 'Advanced'} +]; + +let renderStepList = (listProps, itemProps) => + render( + + {steps.map(step => ( + + {step.label} + + ))} + + ); + +describe('StepList', () => { + let user; + beforeAll(() => { + user = userEvent.setup({delay: null, pointerMap}); + }); + + it('should render with default classes', () => { + let {getByRole, getAllByRole} = renderStepList(); + expect(getByRole('list')).toHaveClass('react-aria-StepList'); + + for (let item of getAllByRole('listitem')) { + expect(item).toHaveClass('react-aria-StepListItem'); + } + }); + + it('should render with custom classes', () => { + let {getByRole, getAllByRole} = renderStepList({className: 'steps'}, {className: 'step'}); + expect(getByRole('list')).toHaveClass('steps'); + + for (let item of getAllByRole('listitem')) { + expect(item).toHaveClass('step'); + } + }); + + it('should mark steps before the selected step as completed', () => { + let {getAllByRole} = renderStepList(); + let items = getAllByRole('listitem'); + + expect(items[0]).toHaveAttribute('data-completed'); + expect(items[0]).not.toHaveAttribute('data-current'); + expect(items[0]).not.toHaveAttribute('aria-current'); + + expect(items[1]).toHaveAttribute('data-current'); + expect(items[1]).toHaveAttribute('aria-current', 'step'); + expect(items[1]).not.toHaveAttribute('data-completed'); + + expect(items[2]).not.toHaveAttribute('data-completed'); + expect(items[2]).not.toHaveAttribute('data-current'); + }); + + it('should update completed steps when the selected step changes', () => { + let {getAllByRole, rerender} = renderStepList({selectedKey: 'advanced'}); + let items = getAllByRole('listitem'); + expect(items[0]).toHaveAttribute('data-completed'); + expect(items[1]).toHaveAttribute('data-completed'); + expect(items[2]).toHaveAttribute('data-current'); + + rerender( + + {steps.map(step => ( + + {step.label} + + ))} + + ); + + items = getAllByRole('listitem'); + expect(items[0]).toHaveAttribute('data-current'); + expect(items[1]).not.toHaveAttribute('data-completed'); + expect(items[2]).not.toHaveAttribute('data-completed'); + }); + + it('should mark no steps as completed when the selected step is not in the collection', () => { + let {getAllByRole} = renderStepList({selectedKey: 'nope'}); + + for (let item of getAllByRole('listitem')) { + expect(item).not.toHaveAttribute('data-completed'); + expect(item).not.toHaveAttribute('data-current'); + } + }); + + it('should support dynamic collections', () => { + let {getAllByRole} = render( + + {step => ( + + {step.label} + + )} + + ); + + let items = getAllByRole('listitem'); + expect(items.map(item => item.textContent)).toEqual([ + 'CompletedDomain', + 'CurrentDNS', + 'Not completedAdvanced' + ]); + expect(items[0]).toHaveAttribute('data-completed'); + expect(items[1]).toHaveAttribute('data-current'); + }); + + it('should support render props', () => { + let {getAllByRole} = render( + + {step => ( + + {({isCurrent, isCompleted}) => ( + + {isCurrent ? 'current' : isCompleted ? 'completed' : step.label} + + )} + + )} + + ); + + expect(getAllByRole('listitem').map(item => item.lastChild.textContent)).toEqual([ + 'completed', + 'current', + 'Advanced' + ]); + }); + + it('should provide a 1-based step number to render props', () => { + let {getAllByRole} = render( + + {() => ( + + {({stepNumber}) => {`Step ${stepNumber}`}} + + )} + + ); + + expect(getAllByRole('listitem').map(item => item.lastChild.textContent)).toEqual([ + 'Step 1', + 'Step 2', + 'Step 3' + ]); + }); + + it('should provide the step number to className and style functions', () => { + let {getAllByRole} = render( + + {step => ( + `step-${stepNumber}`} + style={({stepNumber}) => ({order: stepNumber})}> + {step.label} + + )} + + ); + + let items = getAllByRole('listitem'); + expect(items.map(item => item.className)).toEqual(['step-1', 'step-2', 'step-3']); + expect(items.map(item => item.style.order)).toEqual(['1', '2', '3']); + }); + + it('should support DOM props', () => { + let {getByRole, getAllByRole} = renderStepList( + {'data-foo': 'bar', 'aria-label': 'test list'}, + {'data-bar': 'foo', 'aria-label': 'test item'} + ); + + let list = getByRole('list'); + expect(list).toHaveAttribute('data-foo', 'bar'); + expect(list).toHaveAttribute('aria-label', 'test list'); + + for (let item of getAllByRole('listitem')) { + expect(item).toHaveAttribute('data-bar', 'foo'); + expect(item).toHaveAttribute('aria-label', 'test item'); + } + }); + + it('should not forward the step id to the DOM', () => { + let {getAllByRole} = renderStepList(); + + for (let item of getAllByRole('listitem')) { + expect(item).not.toHaveAttribute('id'); + } + }); + + it('should support custom render function', () => { + let {getByRole, getAllByRole} = renderStepList( + {render: props =>
    }, + {render: props =>
  1. } + ); + + expect(getByRole('list')).toHaveAttribute('data-custom', 'bar'); + for (let item of getAllByRole('listitem')) { + expect(item).toHaveAttribute('data-custom', 'true'); + } + }); + + it('should support refs', () => { + let listRef = React.createRef(); + let itemRef = React.createRef(); + let {getByRole} = render( + + + A + + + ); + + expect(listRef.current).toBe(getByRole('list')); + expect(itemRef.current).toBe(getByRole('listitem')); + }); + + it('should support slots', () => { + let {getByRole} = render( + + + + A + + + + ); + + let list = getByRole('list'); + expect(list).toHaveAttribute('slot', 'test'); + expect(list).toHaveAttribute('aria-label', 'test'); + }); + + it('should label StepListItemContent with the step state', () => { + let {getByRole} = render( + + + Step A + + + ); + + let step = getByRole('img'); + let [stateId, contentId] = step.getAttribute('aria-labelledby').split(' '); + expect(document.getElementById(stateId)).toHaveTextContent('Current'); + expect(contentId).toBe(step.id); + }); + + it.each([undefined, '#a'])( + 'should label StepListItemContent with the step state and custom aria-labelledby when href is %s', + href => { + let {getByRole} = render( + <> + Custom step + Details + + + + Step A + + + + + ); + + let content = getByRole(href ? 'link' : 'img'); + let status = getByRole('listitem').querySelector('[hidden]'); + expect(status).toHaveTextContent('Current'); + expect(content).toHaveAttribute('aria-labelledby', `${status.id} step-label step-detail`); + expect(content).toHaveAccessibleName('Current Custom step Details'); + } + ); + + it('should support className and style on StepListItemContent', () => { + let {getByRole, rerender} = render( + + + Step A + + + ); + + expect(getByRole('img')).toHaveClass('react-aria-StepListItemContent'); + + rerender( + + + + Step A + + + + ); + + let content = getByRole('img'); + expect(content).toHaveClass('content'); + expect(content).not.toHaveClass('react-aria-StepListItemContent'); + expect(content.style.color).toBe('red'); + }); + + it('should support custom render function on StepListItemContent', () => { + let {getByRole} = render( + + + { + if ('href' in props) { + // eslint-disable-next-line jsx-a11y/anchor-has-content + return ; + } + return
    ; + }}> + Step A + + + +
    }> + Step B + + + + ); + + let link = getByRole('link'); + expect(link).toHaveAttribute('data-custom', 'link'); + expect(link).toHaveAttribute('href', '#a'); + expect(link).toHaveClass('react-aria-StepListItemContent'); + expect(getByRole('img')).toHaveAttribute('data-custom', 'content'); + }); + + it('should render StepListItemContent as a non-focusable div without an href', () => { + let {getByRole} = render( + + + Step A + + + ); + + let content = getByRole('img'); + expect(content.tagName).toBe('DIV'); + expect(content).toHaveAttribute('role', 'img'); + expect(content).not.toHaveAttribute('tabindex'); + expect(content).not.toHaveAttribute('href'); + }); + + it('should render StepListItemContent as an anchor when an href is provided', () => { + let {getAllByRole} = render( + + {step => ( + + {({isCompleted}) => ( + + {step.label} + + )} + + )} + + ); + + let contents = [...getAllByRole('link'), ...getAllByRole('img')]; + expect(contents).toHaveLength(3); + + // Completed step gets the href. + expect(contents[0].tagName).toBe('A'); + expect(contents[0]).toHaveAttribute('href', '#domain'); + expect(contents[0]).not.toHaveAttribute('role'); + + // Current and upcoming steps do not. + for (let content of contents.slice(1)) { + expect(content.tagName).toBe('DIV'); + expect(content).toHaveAttribute('role', 'img'); + expect(content).not.toHaveAttribute('href'); + } + }); + + it('should reset focus state when a focused link is replaced by a non-link', async () => { + let renderSteps = selectedKey => ( + + {step => ( + + {({isCompleted}) => ( + + {step.label} + + )} + + )} + + ); + let {getByRole, getAllByRole, rerender} = render(renderSteps('dns')); + + await user.tab(); + let link = getByRole('link'); + expect(document.activeElement).toBe(link); + expect(link).toHaveAttribute('data-focus-visible', 'true'); + + // Navigating to the focused step makes it current, so it is no longer a link. + rerender(renderSteps('domain')); + for (let content of getAllByRole('img')) { + expect(content).not.toHaveAttribute('data-focus-visible'); + } + + // The step becomes a link again, but is not focused. + rerender(renderSteps('dns')); + expect(getByRole('link')).not.toHaveAttribute('data-focus-visible'); + }); +}); diff --git a/packages/react-aria-components/test/Wizard.test.js b/packages/react-aria-components/test/Wizard.test.js new file mode 100644 index 00000000000..abe554c2425 --- /dev/null +++ b/packages/react-aria-components/test/Wizard.test.js @@ -0,0 +1,679 @@ +/* + * Copyright 2026 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ + +import {act, pointerMap, render, within} from '@react-spectrum/test-utils-internal'; +import React, {useContext, useState} from 'react'; +import {TabListStateContext} from '../src/Tabs'; +import userEvent from '@testing-library/user-event'; +import {Wizard, WizardPanel, WizardPanels, WizardStep, WizardStepList} from '../src/Wizard'; + +let steps = [ + {id: 'domain', label: 'Domain'}, + {id: 'dns', label: 'DNS'}, + {id: 'advanced', label: 'Advanced'}, + {id: 'review', label: 'Review'} +]; +let keys = steps.map(step => step.id); + +function WizardExample({stepProps, children, ...props}) { + return ( + + + {steps.map(step => ( + + {step.label} + + ))} + + + {steps.map(step => ( + + {step.label} panel + + ))} + + {children} + + ); +} + +// Moves the selection from within the wizard, like the Previous and Continue buttons of a wizard. +function StepButtons() { + let state = useContext(TabListStateContext); + if (!state) { + return null; + } + + let index = keys.indexOf(state.selectedKey); + return ( + <> + + + + ); +} + +// The selected step is controlled by the parent, which moves it with Back and Next buttons. +function ControlledWizard({onSelectionChange, ...props}) { + let [selectedKey, setSelectedKey] = useState('domain'); + let index = keys.indexOf(selectedKey); + return ( + <> + { + onSelectionChange?.(key); + setSelectedKey(key); + }} + /> + + + + ); +} + +function getSelectedStep(tree) { + let tabs = tree.getAllByRole('tab'); + return keys[tabs.findIndex(tab => tab.getAttribute('aria-selected') === 'true')]; +} + +function getNavigableSteps(tree) { + return tree + .getAllByRole('tab') + .flatMap((tab, i) => (tab.getAttribute('aria-disabled') === 'true' ? [] : [keys[i]])); +} + +describe('Wizard', () => { + let user; + + beforeAll(() => { + user = userEvent.setup({delay: null, pointerMap}); + jest.useFakeTimers(); + }); + + afterEach(() => { + act(() => jest.runAllTimers()); + }); + + it('should render a step list and the panel of the selected step', () => { + let tree = render(); + let stepList = tree.getByRole('tablist'); + expect(stepList).toHaveAttribute('aria-label', 'Setup'); + + let tabs = within(stepList).getAllByRole('tab'); + expect(tabs).toHaveLength(4); + expect(getSelectedStep(tree)).toBe('domain'); + + let panel = tree.getByRole('tabpanel'); + expect(panel).toHaveTextContent('Domain panel'); + expect(tabs[0]).toHaveAttribute('aria-controls', panel.id); + }); + + it('should render with default classes', () => { + let tree = render(); + let stepList = tree.getByRole('tablist'); + expect(stepList.parentElement).toHaveClass('react-aria-Wizard'); + expect(stepList).toHaveClass('react-aria-WizardStepList'); + for (let step of within(stepList).getAllByRole('tab')) { + expect(step).toHaveClass('react-aria-WizardStep'); + } + + let panel = tree.getByRole('tabpanel'); + expect(panel.parentElement).toHaveClass('react-aria-WizardPanels'); + expect(panel).toHaveClass('react-aria-WizardPanel'); + }); + + it('should pass the default class name to className functions', () => { + let tree = render( + `${defaultClassName} wizard`} + stepProps={() => ({className: ({defaultClassName}) => `${defaultClassName} step`})} + /> + ); + let stepList = tree.getByRole('tablist'); + expect(stepList.parentElement).toHaveClass('react-aria-Wizard', 'wizard'); + for (let step of within(stepList).getAllByRole('tab')) { + expect(step).toHaveClass('react-aria-WizardStep', 'step'); + } + }); + + it('should support uncontrolled selection', async () => { + let onSelectionChange = jest.fn(); + let tree = render( + + ); + expect(getSelectedStep(tree)).toBe('dns'); + expect(tree.getByRole('tabpanel')).toHaveTextContent('DNS panel'); + + await user.click(tree.getAllByRole('tab')[0]); + expect(onSelectionChange).toHaveBeenCalledTimes(1); + expect(onSelectionChange).toHaveBeenLastCalledWith('domain'); + expect(getSelectedStep(tree)).toBe('domain'); + expect(tree.getByRole('tabpanel')).toHaveTextContent('Domain panel'); + }); + + it('should support controlled selection', async () => { + let onSelectionChange = jest.fn(); + let tree = render(); + + await user.click(tree.getAllByRole('tab')[0]); + expect(onSelectionChange).toHaveBeenCalledTimes(1); + expect(onSelectionChange).toHaveBeenLastCalledWith('domain'); + expect(getSelectedStep(tree)).toBe('dns'); + }); + + it('should identify only the selected step as the current step for assistive technology', async () => { + let tree = render(); + let tabs = tree.getAllByRole('tab'); + expect(tabs[0]).toHaveAttribute('aria-current', 'step'); + for (let tab of tabs.slice(1)) { + expect(tab).not.toHaveAttribute('aria-current'); + } + + await user.click(tabs[2]); + expect(tabs[2]).toHaveAttribute('aria-current', 'step'); + for (let tab of [tabs[0], tabs[1], tabs[3]]) { + expect(tab).not.toHaveAttribute('aria-current'); + } + }); + + it('should only select a step on Enter when navigating with the keyboard', async () => { + let onSelectionChange = jest.fn(); + let tree = render( + + ); + let tabs = tree.getAllByRole('tab'); + + await user.tab(); + expect(document.activeElement).toBe(tabs[0]); + + await user.keyboard('{ArrowRight}'); + expect(document.activeElement).toBe(tabs[1]); + await user.keyboard('{ArrowRight}'); + expect(document.activeElement).toBe(tabs[2]); + expect(getSelectedStep(tree)).toBe('domain'); + expect(onSelectionChange).not.toHaveBeenCalled(); + + // The last step isn't navigable yet, so it is skipped. + await user.keyboard('{ArrowRight}'); + expect(document.activeElement).toBe(tabs[0]); + await user.keyboard('{ArrowLeft}'); + expect(document.activeElement).toBe(tabs[2]); + + await user.keyboard('{Enter}'); + expect(onSelectionChange).toHaveBeenCalledTimes(1); + expect(onSelectionChange).toHaveBeenLastCalledWith('advanced'); + expect(getSelectedStep(tree)).toBe('advanced'); + }); + + it('should mark the steps before the selected step as completed and retain memory when going back', async () => { + let tree = render(); + let tabs = tree.getAllByRole('tab'); + + expect(tabs.map(tab => tab.textContent)).toEqual([ + 'CompletedDomain', + 'CompletedDNS', + 'Advanced', + 'Not completedReview' + ]); + expect(tabs[0]).toHaveAttribute('data-completed'); + expect(tabs[1]).toHaveAttribute('data-completed'); + expect(tabs[2]).toHaveAttribute('data-current'); + expect(tabs[2]).not.toHaveAttribute('data-completed'); + expect(tabs[3]).not.toHaveAttribute('data-completed'); + expect(tabs[3]).not.toHaveAttribute('data-current'); + + // Completion follows the selection moving forwards. But it does not change + // going back to earlier steps. + await user.click(tabs[0]); + expect(tabs.map(tab => tab.textContent)).toEqual([ + 'Domain', + 'CompletedDNS', + 'Not completedAdvanced', + 'Not completedReview' + ]); + expect(tabs[0]).toHaveAttribute('data-current'); + expect(tabs[0]).toHaveAttribute('data-completed'); + expect(tabs[1]).toHaveAttribute('data-completed'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + }); + + it('should provide the step state as render props', async () => { + let tree = render( + + + {steps.map(step => ( + + isCurrent ? 'current' : isCompleted ? 'completed' : 'upcoming' + } + style={({isCurrent}) => ({fontWeight: isCurrent ? 'bold' : 'normal'})} + render={(domProps, {stepNumber}) =>
    }> + {({stepNumber}) => `${stepNumber}. ${step.label}`} + + ))} + + + ); + + let tabs = tree.getAllByRole('tab'); + expect(tabs.map(tab => tab.className)).toEqual([ + 'completed', + 'completed', + 'current', + 'upcoming' + ]); + expect(tabs.map(tab => tab.textContent)).toEqual([ + 'Completed1. Domain', + 'Completed2. DNS', + '3. Advanced', + 'Not completed4. Review' + ]); + expect(tabs.map(tab => tab.style.fontWeight)).toEqual(['normal', 'normal', 'bold', 'normal']); + expect(tabs.map(tab => tab.dataset.step)).toEqual(['1', '2', '3', '4']); + + await user.click(tabs[0]); + expect(tabs.map(tab => tab.className)).toEqual([ + 'current', + 'completed', + 'upcoming', + 'upcoming' + ]); + }); + + it('should support render props on steps', () => { + let tree = render( + + + {steps.map(step => ( + + {({isSelected, isDisabled}) => + `${step.label} ${isSelected ? 'selected' : isDisabled ? 'locked' : 'open'}` + } + + ))} + + + ); + + expect(tree.getAllByRole('tab').map(tab => tab.textContent)).toEqual([ + 'CompletedDomain open', + 'DNS selected', + 'Not completedAdvanced locked', + 'Not completedReview locked' + ]); + }); + + it('should support refs', () => { + let wizardRef = React.createRef(); + let stepListRef = React.createRef(); + let stepRef = React.createRef(); + let panelsRef = React.createRef(); + let panelRef = React.createRef(); + let tree = render( + + + + Domain + + + + + Domain panel + + + + ); + + expect(stepListRef.current).toBe(tree.getByRole('tablist')); + expect(wizardRef.current).toBe(tree.getByRole('tablist').parentElement); + expect(stepRef.current).toBe(tree.getByRole('tab')); + expect(panelRef.current).toBe(tree.getByRole('tabpanel')); + expect(panelsRef.current).toBe(tree.getByRole('tabpanel').parentElement); + }); + + describe('lastCompletedStep', () => { + it.each([ + ['no steps are completed', {}], + ['lastCompletedStep is not one of the steps', {lastCompletedStep: 'missing'}] + ])('should only allow navigating to the first step when %s', async (_, props) => { + let onSelectionChange = jest.fn(); + let onLastCompletedStepChange = jest.fn(); + let tree = render( + + ); + expect(getNavigableSteps(tree)).toEqual(['domain']); + + await user.click(tree.getAllByRole('tab')[1]); + expect(getSelectedStep(tree)).toBe('domain'); + expect(onSelectionChange).not.toHaveBeenCalled(); + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + it('should allow navigating to completed steps and the step after the last completed step', async () => { + let onLastCompletedStepChange = jest.fn(); + let tree = render( + + ); + expect(getSelectedStep(tree)).toBe('domain'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + let tabs = tree.getAllByRole('tab'); + expect(tabs[0]).toHaveAttribute('data-current'); + expect(tabs[0]).toHaveAttribute('data-completed'); + expect(tabs[1]).toHaveAccessibleName('Completed DNS'); + expect(tabs[1]).toHaveAttribute('data-completed'); + expect(tabs[2]).not.toHaveAttribute('data-completed'); + expect(tabs[3]).not.toHaveAttribute('data-completed'); + + // Selecting the step after the last completed step doesn't complete any more steps. + await user.click(tree.getAllByRole('tab')[2]); + expect(getSelectedStep(tree)).toBe('advanced'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + it('should not complete any steps when the default selected step follows the last completed step', () => { + let onLastCompletedStepChange = jest.fn(); + let tree = render( + + ); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns']); + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + it('should complete the steps before the default selected step', () => { + let onLastCompletedStepChange = jest.fn(); + // Records every step that is rendered as disabled. + let disabledSteps = new Set(); + let tree = render( + + + {steps.map(step => ( + + {({isDisabled}) => { + if (isDisabled) { + disabledSteps.add(step.id); + } + return step.label; + }} + + ))} + + + ); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + + // The last completed step is derived during render rather than synced in an effect, so the + // completed steps are never rendered as disabled. + expect(disabledSteps).toEqual(new Set(['review'])); + // Like other default values, the derived last completed step doesn't call the change handler. + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + it('should complete steps as the selection advances and keep them navigable after going back', async () => { + let onLastCompletedStepChange = jest.fn(); + let tree = render( + + + + ); + let previous = tree.getByRole('button', {name: 'Previous'}); + let next = tree.getByRole('button', {name: 'Continue'}); + + await user.click(next); + expect(getSelectedStep(tree)).toBe('dns'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns']); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(1); + expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('domain'); + + await user.click(next); + expect(getSelectedStep(tree)).toBe('advanced'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(2); + expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('dns'); + + // Going back never rolls back an uncontrolled last completed step. + await user.click(previous); + expect(getSelectedStep(tree)).toBe('dns'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + + await user.click(tree.getAllByRole('tab')[0]); + expect(getSelectedStep(tree)).toBe('domain'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + + // The furthest step reached can be selected again directly. + await user.click(tree.getAllByRole('tab')[2]); + expect(getSelectedStep(tree)).toBe('advanced'); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(2); + }); + + it('should derive the last completed step when the parent changes the selection', async () => { + let onLastCompletedStepChange = jest.fn(); + let tree = render(); + let back = tree.getByRole('button', {name: 'Back'}); + let next = tree.getByRole('button', {name: 'Next'}); + + await user.click(next); + expect(getSelectedStep(tree)).toBe('dns'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns']); + + await user.click(next); + expect(getSelectedStep(tree)).toBe('advanced'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + + // Going back never rolls back an uncontrolled last completed step, even when the selection is + // controlled. + await user.click(back); + expect(getSelectedStep(tree)).toBe('dns'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + + // The parent changed the selection itself rather than through the wizard, so it isn't notified + // about the steps that the selection completed. + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + it('should support a controlled lastCompletedStep', () => { + let onLastCompletedStepChange = jest.fn(); + let tree = render( + + ); + expect(getNavigableSteps(tree)).toEqual(keys); + let tabs = tree.getAllByRole('tab'); + expect(tabs.map(tab => tab.hasAttribute('data-completed'))).toEqual([ + true, + true, + true, + false + ]); + + // Unlike an uncontrolled last completed step, a controlled one can be rolled back. + tree.rerender( + + ); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns']); + expect(tabs.map(tab => tab.hasAttribute('data-completed'))).toEqual([ + true, + false, + false, + false + ]); + expect(tabs[1]).toHaveAccessibleName('Not completed DNS'); + + tree.rerender( + + ); + expect(getNavigableSteps(tree)).toEqual(['domain']); + for (let tab of tabs) { + expect(tab).not.toHaveAttribute('data-completed'); + } + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + it.each(['lastCompletedStep', 'defaultLastCompletedStep'])( + 'should mark a step with key zero as completed with %s', + prop => { + let tree = render( + + + First + Second + + + ); + let tabs = tree.getAllByRole('tab'); + expect(tabs[0]).toHaveAttribute('data-current'); + expect(tabs[0]).toHaveAttribute('data-completed'); + expect(tabs[1]).not.toHaveAttribute('data-completed'); + expect(tabs[1]).not.toHaveAttribute('aria-disabled'); + } + ); + + it('should request completing steps without updating a controlled lastCompletedStep', async () => { + let onLastCompletedStepChange = jest.fn(); + let tree = render( + + + + ); + let next = tree.getByRole('button', {name: 'Continue'}); + + // Selecting the step after the last completed step doesn't complete any more steps. + await user.click(next); + expect(getSelectedStep(tree)).toBe('dns'); + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + + await user.click(next); + expect(getSelectedStep(tree)).toBe('advanced'); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(1); + expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('dns'); + + // The last completed step is still "domain", so the step after "dns" isn't navigable once + // the selection moves away from it. + await user.click(tree.getByRole('button', {name: 'Previous'})); + expect(getSelectedStep(tree)).toBe('dns'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns']); + }); + + it('should call onLastCompletedStepChange in the same event as onSelectionChange', async () => { + // Records each pair of values that the parent renders with. Strict mode renders twice, so + // only changes are recorded. + let renders = []; + function FullyControlledWizard() { + let [selectedKey, setSelectedKey] = useState('domain'); + let [lastCompletedStep, setLastCompletedStep] = useState(null); + if (renders.at(-1)?.join() !== [selectedKey, lastCompletedStep].join()) { + renders.push([selectedKey, lastCompletedStep]); + } + + return ( + + + + ); + } + + let tree = render(); + let previous = tree.getByRole('button', {name: 'Previous'}); + let next = tree.getByRole('button', {name: 'Continue'}); + + await user.click(next); + expect(getSelectedStep(tree)).toBe('dns'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns']); + + await user.click(next); + expect(getSelectedStep(tree)).toBe('advanced'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + + await user.click(previous); + expect(getSelectedStep(tree)).toBe('dns'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + + // Both values are updated together, so the parent never renders a selected step that is + // ahead of the step after the last completed step. + expect(renders).toEqual([ + ['domain', null], + ['dns', 'domain'], + ['advanced', 'dns'], + ['dns', 'dns'] + ]); + }); + + it('should keep the selected step navigable when it is beyond the step after the last completed step', () => { + let tree = render(); + expect(getSelectedStep(tree)).toBe('review'); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'review']); + }); + + it('should allow navigating to any step with allowsRandomAccess', async () => { + let onLastCompletedStepChange = jest.fn(); + let tree = render( + + ); + expect(getNavigableSteps(tree)).toEqual(keys); + + await user.click(tree.getAllByRole('tab')[3]); + expect(getSelectedStep(tree)).toBe('review'); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(1); + expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('advanced'); + }); + + it.each([ + ['disabledKeys', {disabledKeys: ['dns']}], + ['isDisabled', {stepProps: step => ({isDisabled: step.id === 'dns'})}] + ])('should never allow navigating to steps disabled with %s', async (_, disabledProps) => { + let tree = render(); + expect(getNavigableSteps(tree)).toEqual(['domain', 'advanced', 'review']); + tree.unmount(); + + tree = render(); + expect(getNavigableSteps(tree)).toEqual(['domain', 'advanced', 'review']); + + await user.click(tree.getAllByRole('tab')[1]); + expect(getSelectedStep(tree)).toBe('domain'); + }); + }); +}); diff --git a/starters/docs/src/StepList.css b/starters/docs/src/StepList.css new file mode 100644 index 00000000000..c5a4cfa4f27 --- /dev/null +++ b/starters/docs/src/StepList.css @@ -0,0 +1,97 @@ +@import './theme.css'; + +.react-aria-StepList { + display: flex; + max-width: 100%; + margin: 0; + padding: 0; + list-style: none; + font: var(--font-size) system-ui; + color: var(--text-color); +} + +.react-aria-StepListItem { + position: relative; + /* Steps share the available width equally, with a preferred width of 96px. */ + flex: 1; + width: calc(var(--spacing) * 24); + box-sizing: border-box; + padding-inline: var(--spacing-1); + display: flex; + justify-content: center; + + .marker { + display: flex; + align-items: center; + justify-content: center; + width: var(--spacing-6); + height: var(--spacing-6); + box-sizing: border-box; + border: 1px solid var(--border-color); + border-radius: 50%; + font-size: var(--font-size-sm); + } + + &[data-current] .marker, + &[data-completed] .marker { + background: var(--highlight-background); + border-color: var(--highlight-background); + color: var(--highlight-foreground); + forced-color-adjust: none; + } + + &[data-current] { + font-weight: 600; + } + + /* Connector lines. Each step draws the lines on either side of its marker, + so they stay centered when steps have different widths. */ + &::before, + &::after { + content: ''; + position: absolute; + top: var(--spacing-3); + border-top: 1px solid var(--border-color); + } + + &::before { + inset-inline: 0 calc(50% + var(--spacing-5)); + } + + &::after { + inset-inline: calc(50% + var(--spacing-5)) 0; + } + + &:first-child::before, + &:last-child::after { + display: none; + } + + &[data-current]::before, + &[data-completed]::before, + &[data-completed]::after { + border-color: var(--highlight-background); + } +} + +.react-aria-StepListItemContent { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--spacing-2); + text-align: center; + color: inherit; + text-decoration: none; + border-radius: var(--radius-sm); + outline: none; + -webkit-tap-highlight-color: transparent; + + &[data-hovered] { + text-decoration: underline; + } + + &[data-focus-visible] { + outline: 2px solid var(--focus-ring-color); + outline-offset: 2px; + } +} diff --git a/starters/docs/src/StepList.tsx b/starters/docs/src/StepList.tsx new file mode 100644 index 00000000000..4ed094b256e --- /dev/null +++ b/starters/docs/src/StepList.tsx @@ -0,0 +1,52 @@ +'use client'; +import { + StepList as RACStepList, + type StepListProps, + StepListItem as RACStepListItem, + type StepListItemProps as RACStepListItemProps, + StepListItemContent, + type StepListItemContentProps +} from 'react-aria-components/StepList'; +import {Check} from 'lucide-react'; +import {createContext, type ReactNode, useContext} from 'react'; +import './StepList.css'; + +const RenderLinkContext = createContext(undefined); + +export function StepList({ + renderLink, + ...props +}: StepListProps & {renderLink?: StepListItemContentProps['render']}) { + return ( + + + + ); +} + +export interface StepListItemProps extends Omit { + children?: ReactNode; + href?: string; +} + +export function StepListItem({children, href, ...props}: StepListItemProps) { + let renderLink = useContext(RenderLinkContext); + return ( + + {({isCompleted, stepNumber}) => { + // Only completed steps are links, so users can go back but not skip ahead. + let isLink = isCompleted && href != null; + return ( + + + {isCompleted ? : stepNumber} + + {children} + + ); + }} + + ); +} diff --git a/starters/docs/src/Wizard.css b/starters/docs/src/Wizard.css new file mode 100644 index 00000000000..229b1e33917 --- /dev/null +++ b/starters/docs/src/Wizard.css @@ -0,0 +1,112 @@ +@import './theme.css'; + +.react-aria-Wizard { + display: flex; + flex-direction: column; + gap: var(--spacing-4); + width: calc(var(--spacing) * 100); + max-width: 100%; + font: var(--font-size) system-ui; + color: var(--text-color); +} + +.react-aria-WizardStepList { + display: flex; +} + +.react-aria-WizardStep { + position: relative; + flex: 1; + box-sizing: border-box; + padding-inline: var(--spacing-1); + display: flex; + flex-direction: column; + align-items: center; + gap: var(--spacing-2); + text-align: center; + outline: none; + cursor: default; + -webkit-tap-highlight-color: transparent; + + .marker { + display: flex; + align-items: center; + justify-content: center; + width: var(--spacing-6); + height: var(--spacing-6); + box-sizing: border-box; + border: 1px solid var(--border-color); + border-radius: 50%; + font-size: var(--font-size-sm); + } + + &[data-selected] .marker, + &[data-completed] .marker { + background: var(--highlight-background); + border-color: var(--highlight-background); + color: var(--highlight-foreground); + forced-color-adjust: none; + } + + &[data-selected] { + font-weight: 600; + } + + &[data-hovered] { + color: var(--text-color-hover); + } + + /* Steps the user hasn't reached yet. */ + &[data-disabled] { + color: var(--text-color-disabled); + } + + &[data-focus-visible] .marker { + outline: 2px solid var(--focus-ring-color); + outline-offset: 2px; + } + + /* Connector lines. Each step draws the lines on either side of its marker, + so they stay centered when steps have different widths. */ + &::before, + &::after { + content: ''; + position: absolute; + top: var(--spacing-3); + border-top: 1px solid var(--border-color); + } + + &::before { + inset-inline: 0 calc(50% + var(--spacing-5)); + } + + &::after { + inset-inline: calc(50% + var(--spacing-5)) 0; + } + + &:first-child::before, + &:last-child::after { + display: none; + } + + &[data-selected]::before, + &[data-completed]::before, + &[data-completed]::after { + border-color: var(--highlight-background); + } +} + +.react-aria-WizardPanel { + padding: var(--spacing-3); + border-radius: var(--radius); + outline: none; + + &[data-focus-visible] { + outline: 2px solid var(--focus-ring-color); + } +} + +.wizard-buttons { + display: flex; + justify-content: space-between; +} diff --git a/starters/docs/src/Wizard.tsx b/starters/docs/src/Wizard.tsx new file mode 100644 index 00000000000..2f37d4e2138 --- /dev/null +++ b/starters/docs/src/Wizard.tsx @@ -0,0 +1,76 @@ +'use client'; +import { + Wizard as RACWizard, + WizardPanel as RACWizardPanel, + type WizardPanelProps, + WizardPanels as RACWizardPanels, + type WizardPanelsProps, + type WizardProps, + WizardStep as RACWizardStep, + WizardStepList as RACWizardStepList, + type WizardStepListProps, + type WizardStepProps +} from 'react-aria-components/Wizard'; +import {TabListStateContext} from 'react-aria-components/Tabs'; +import {composeRenderProps} from 'react-aria-components/composeRenderProps'; +import {Check} from 'lucide-react'; +import {useContext} from 'react'; +import {Button} from './Button'; +import './Wizard.css'; + +export function Wizard(props: WizardProps) { + return ; +} + +export function WizardStepList(props: WizardStepListProps) { + return ; +} + +export function WizardStep(props: WizardStepProps) { + return ( + + {composeRenderProps(props.children, (children, {isCompleted, stepNumber}) => ( + <> + {/* The step already announces whether it is completed, so the marker is hidden. */} + + {isCompleted ? : stepNumber} + + {children} + + ))} + + ); +} + +export function WizardPanels(props: WizardPanelsProps) { + return ; +} + +export function WizardPanel(props: WizardPanelProps) { + return ; +} + +// Back and Next buttons that move between steps. Render inside the , outside . +export function WizardButtons() { + let state = useContext(TabListStateContext); + if (!state || state.selectedKey == null) { + return null; + } + + let {collection, selectedKey, setSelectedKey} = state; + let previousKey = collection.getKeyBefore(selectedKey); + let nextKey = collection.getKeyAfter(selectedKey); + return ( +
    + + +
    + ); +} diff --git a/starters/docs/stories/StepList.stories.tsx b/starters/docs/stories/StepList.stories.tsx new file mode 100644 index 00000000000..eaeb4364229 --- /dev/null +++ b/starters/docs/stories/StepList.stories.tsx @@ -0,0 +1,33 @@ +import {StepList, StepListItem} from '../src/StepList'; +import type {Meta, StoryFn} from '@storybook/react'; + +const meta: Meta = { + component: StepList, + parameters: { + layout: 'centered' + }, + tags: ['autodocs'], + args: { + selectedKey: 'payment' + } +}; + +export default meta; +type Story = StoryFn; + +export const Example: Story = args => ( + + + Cart + + + Shipping + + + Payment + + + Review + + +); diff --git a/starters/docs/stories/Wizard.stories.tsx b/starters/docs/stories/Wizard.stories.tsx new file mode 100644 index 00000000000..e55449576c5 --- /dev/null +++ b/starters/docs/stories/Wizard.stories.tsx @@ -0,0 +1,40 @@ +import { + Wizard, + WizardButtons, + WizardPanel, + WizardPanels, + WizardStep, + WizardStepList +} from '../src/Wizard'; +import {fn} from 'storybook/test'; +import type {Meta, StoryFn} from '@storybook/react'; + +const meta: Meta = { + component: Wizard, + parameters: { + layout: 'centered' + }, + args: { + onSelectionChange: fn() + }, + tags: ['autodocs'] +}; + +export default meta; +type Story = StoryFn; + +export const Example: Story = args => ( + + + Details + Members + Review + + + Name your project and choose who can see it. + Invite people to work on the project with you. + Check the details, then create the project. + + + +); diff --git a/starters/tailwind/src/StepList.tsx b/starters/tailwind/src/StepList.tsx new file mode 100644 index 00000000000..95d9f4c85c9 --- /dev/null +++ b/starters/tailwind/src/StepList.tsx @@ -0,0 +1,78 @@ +'use client'; +import {Check} from 'lucide-react'; +import React, {createContext, useContext} from 'react'; +import { + StepList as AriaStepList, + StepListItem as AriaStepListItem, + StepListItemContent as AriaStepListItemContent, + type StepListItemContentProps, + type StepListItemProps as AriaStepListItemProps, + type StepListProps +} from 'react-aria-components/StepList'; +import {twMerge} from 'tailwind-merge'; +import {tv} from 'tailwind-variants'; +import {composeTailwindRenderProps} from './utils'; + +const RenderLinkContext = createContext(undefined); + +export function StepList({ + renderLink, + ...props +}: StepListProps & {renderLink?: StepListItemContentProps['render']}) { + return ( + + + + ); +} + +export interface StepListItemProps extends Omit { + children?: React.ReactNode; + href?: string; +} + +const markerStyles = tv({ + base: 'flex items-center justify-center size-6 shrink-0 rounded-full border text-xs', + variants: { + isUpcoming: { + true: 'border-neutral-400', + false: + 'border-transparent bg-blue-600 text-white forced-color-adjust-none forced-colors:bg-[Highlight] forced-colors:text-[HighlightText]' + } + } +}); + +export function StepListItem({children, href, ...props}: StepListItemProps) { + let renderLink = useContext(RenderLinkContext); + return ( + + {({isCurrent, isCompleted, stepNumber}) => { + // Only completed steps are links, so users can go back but not skip ahead. + let isLink = isCompleted && href != null; + return ( + + + {isCompleted ? : stepNumber} + + {children} + + ); + }} + + ); +} diff --git a/starters/tailwind/src/Wizard.tsx b/starters/tailwind/src/Wizard.tsx new file mode 100644 index 00000000000..68518ca8d77 --- /dev/null +++ b/starters/tailwind/src/Wizard.tsx @@ -0,0 +1,125 @@ +'use client'; +import {Check} from 'lucide-react'; +import React, {useContext} from 'react'; +import {composeRenderProps} from 'react-aria-components/composeRenderProps'; +import {TabListStateContext} from 'react-aria-components/Tabs'; +import { + Wizard as AriaWizard, + WizardPanel as AriaWizardPanel, + type WizardPanelProps, + WizardPanels as AriaWizardPanels, + type WizardPanelsProps, + type WizardProps, + WizardStep as AriaWizardStep, + WizardStepList as AriaWizardStepList, + type WizardStepListProps, + type WizardStepProps +} from 'react-aria-components/Wizard'; +import {tv} from 'tailwind-variants'; +import {Button} from './Button'; +import {composeTailwindRenderProps, focusRing} from './utils'; + +export function Wizard(props: WizardProps) { + return ( + + ); +} + +export function WizardStepList(props: WizardStepListProps) { + return ( + + ); +} + +const markerStyles = tv({ + extend: focusRing, + base: 'flex items-center justify-center size-6 shrink-0 rounded-full border text-xs', + variants: { + isUpcoming: { + true: 'border-neutral-400', + false: + 'border-transparent bg-blue-600 text-white forced-color-adjust-none forced-colors:bg-[Highlight] forced-colors:text-[HighlightText]' + } + } +}); + +export function WizardStep(props: WizardStepProps) { + return ( + + {composeRenderProps( + props.children, + (children, {isSelected, isCompleted, isFocusVisible, stepNumber}) => ( + <> + {/* The step already announces whether it is completed, so the marker is hidden. */} + + {isCompleted ? : stepNumber} + + {children} + + ) + )} + + ); +} + +export function WizardPanels(props: WizardPanelsProps) { + return ; +} + +const panelStyles = tv({ + extend: focusRing, + base: 'box-border p-4 text-sm text-neutral-900 dark:text-neutral-100' +}); + +export function WizardPanel(props: WizardPanelProps) { + return ( + + panelStyles({...renderProps, className}) + )} + /> + ); +} + +// Back and Next buttons that move between steps. Render inside the , outside . +export function WizardButtons() { + let state = useContext(TabListStateContext); + if (!state || state.selectedKey == null) { + return null; + } + + let {collection, selectedKey, setSelectedKey} = state; + let previousKey = collection.getKeyBefore(selectedKey); + let nextKey = collection.getKeyAfter(selectedKey); + return ( +
    + + +
    + ); +} diff --git a/starters/tailwind/stories/StepList.stories.tsx b/starters/tailwind/stories/StepList.stories.tsx new file mode 100644 index 00000000000..60d848111f5 --- /dev/null +++ b/starters/tailwind/stories/StepList.stories.tsx @@ -0,0 +1,33 @@ +import React from 'react'; +import {StepList, StepListItem} from '../src/StepList'; +import {type Meta} from '@storybook/react'; + +const meta: Meta = { + component: StepList, + parameters: { + layout: 'centered' + }, + tags: ['autodocs'], + args: { + selectedKey: 'payment' + } +}; + +export default meta; + +export const Example = (args: any) => ( + + + Cart + + + Shipping + + + Payment + + + Review + + +); diff --git a/starters/tailwind/stories/Wizard.stories.tsx b/starters/tailwind/stories/Wizard.stories.tsx new file mode 100644 index 00000000000..2fd42f8f8e5 --- /dev/null +++ b/starters/tailwind/stories/Wizard.stories.tsx @@ -0,0 +1,36 @@ +import React from 'react'; +import { + Wizard, + WizardButtons, + WizardPanel, + WizardPanels, + WizardStep, + WizardStepList +} from '../src/Wizard'; +import {type Meta} from '@storybook/react'; + +const meta: Meta = { + component: Wizard, + parameters: { + layout: 'centered' + }, + tags: ['autodocs'] +}; + +export default meta; + +export const Example = (args: any) => ( + + + Details + Members + Review + + + Name your project and choose who can see it. + Invite people to work on the project with you. + Check the details, then create the project. + + + +);