From 64b33ec3f528ed58e6027273d1da67006170bc16 Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Fri, 16 Oct 2026 16:27:58 +1100 Subject: [PATCH 01/15] feat: StepList round two --- .../react-aria-components/intl/en-US.json | 5 +- .../react-aria-components/src/StepList.tsx | 243 ++++++++++++++++++ .../stories/StepList.css | 59 +++++ .../stories/StepList.stories.tsx | 80 ++++++ 4 files changed, 386 insertions(+), 1 deletion(-) create mode 100644 packages/react-aria-components/src/StepList.tsx create mode 100644 packages/react-aria-components/stories/StepList.css create mode 100644 packages/react-aria-components/stories/StepList.stories.tsx 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..5d625faea2a --- /dev/null +++ b/packages/react-aria-components/src/StepList.tsx @@ -0,0 +1,243 @@ +/* + * 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} from '@react-types/shared'; +import { + ClassNameOrFunction, + ContextValue, + dom, + DOMProps, + RenderProps, + SlotProps, + useContextProps, + useRenderProps +} from './utils'; +import {filterDOMProps} from 'react-aria/filterDOMProps'; +import {getOwnerDocument} from 'react-aria/private/utils/domHelpers'; +import intlMessages from '../intl/*.json'; +import {mergeProps} from 'react-aria/mergeProps'; +import React, { + createContext, + ForwardedRef, + forwardRef, + RefObject, + useContext, + useState +} from 'react'; +import {useId} from 'react-aria/useId'; +import {useLayoutEffect} from 'react-aria/private/utils/useLayoutEffect'; +import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter'; +import {useObjectRef} from 'react-aria/useObjectRef'; + +export interface StepListRenderProps {} + +export interface StepListProps + extends + SlotProps, + 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-StepList' + */ + className?: ClassNameOrFunction; + /** + * The `id` of the currently selected `StepListItem`. Steps rendered before it are marked as + * completed, and steps rendered after it are marked as not completed. + */ + selectedId: string; +} + +export const StepListContext = createContext>(null); + +interface StepListState { + /** The `id` of the currently selected step. */ + selectedId: string; + /** Identifies the steps belonging to this list so an item can locate its sibling steps. */ + groupId: string; +} + +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 {selectedId} = props; + let groupId = useId(); + + let renderProps = useRenderProps({ + ...props, + values: {}, + defaultClassName: 'react-aria-StepList' + }); + + let DOMProps = filterDOMProps(props, {labelable: true}); + + return ( + + + {renderProps.children} + + + ); +}); + +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; +} + +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 `selectedId` of the `StepList`. */ + id: string; +} + +function useStepListItem( + props: StepListItemProps, + state: StepListState | null, + ref: RefObject +) { + let {id} = props; + let groupId = state?.groupId; + let selectedId = state?.selectedId; + let isCurrent = id === selectedId; + // A step is completed if it is rendered before the current step. This can only be determined once + // all of the steps in the group have been rendered, so it is resolved against the DOM. + let [isCompleted, setCompleted] = useState(false); + + useLayoutEffect(() => { + if (!ref.current || groupId == null || isCurrent) { + setCompleted(false); + return; + } + + let currentItem = getOwnerDocument(ref.current).querySelector( + `[data-steplist-group-id="${groupId}"][data-current]` + ); + setCompleted( + currentItem != null && + (currentItem.compareDocumentPosition(ref.current) & Node.DOCUMENT_POSITION_PRECEDING) !== 0 + ); + }, [isCurrent, selectedId, groupId, ref]); + + return { + itemProps: { + 'aria-current': isCurrent ? ('step' as const) : undefined, + 'data-steplist-group-id': groupId, + 'data-current': isCurrent || undefined, + 'data-completed': isCompleted || undefined + }, + isCurrent, + isCompleted + }; +} + +/** + * A StepListItem represents an individual step within a ``. + */ +export const StepListItem = /*#__PURE__*/ (forwardRef as forwardRefType)(function StepListItem( + props: StepListItemProps, + ref: ForwardedRef +) { + let objRef = useObjectRef(ref); + let state = useContext(InternalStepListContext); + let stringFormatter = useLocalizedStringFormatter(intlMessages, 'react-aria-components'); + let {itemProps, isCurrent, isCompleted} = useStepListItem(props, state, objRef); + let hiddenId = useId(); + + let renderProps = useRenderProps({ + ...props, + values: {isCurrent, isCompleted}, + defaultClassName: 'react-aria-StepListItem' + }); + + let DOMProps = filterDOMProps(props, {labelable: true}); + // `id` identifies the step rather than the DOM element, so it is not forwarded to the DOM. + // TODO IS THIS WEIRD OR WRONG?? + delete DOMProps.id; + + let message = stringFormatter.format('stepListItemNotCompleted'); + if (isCurrent) { + message = stringFormatter.format('stepListItemCurrent'); + } else if (isCompleted) { + message = stringFormatter.format('stepListItemCompleted'); + } + + return ( + + + + {renderProps.children} + + + ); +}); + +interface StepListItemContentProps extends DOMProps {} +const StepListItemContext = createContext<{hiddenId: string | undefined} | undefined>(undefined); + +// Need this so I can get an id on the contents so that the announcement makes sense. It lands on this element, not the `li` itself. +export const StepListItemContent = /*#__PURE__*/ (forwardRef as forwardRefType)( + function StepListItemContent(props: StepListItemContentProps, ref: ForwardedRef) { + let context = useContext(StepListItemContext); + let objRef = useObjectRef(ref); + let DOMProps = filterDOMProps(props, {labelable: true}); + let id = useId(); + + return ( + + {props.children} + + ); + } +); diff --git a/packages/react-aria-components/stories/StepList.css b/packages/react-aria-components/stories/StepList.css new file mode 100644 index 00000000000..0f3c2aa9aad --- /dev/null +++ b/packages/react-aria-components/stories/StepList.css @@ -0,0 +1,59 @@ +.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; + } +} 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..fd02813a64f --- /dev/null +++ b/packages/react-aria-components/stories/StepList.stories.tsx @@ -0,0 +1,80 @@ +/* + * 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'}, + {id: 'dns', label: 'Configure DNS'}, + {id: 'advanced', label: 'Advanced settings'} +]; + +export default { + title: 'React Aria Components/StepList', + component: StepList, + args: { + selectedId: 'dns' + }, + argTypes: { + selectedId: { + 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, index) => ( + + {({isCompleted}) => ( + + {isCompleted ? ( + + ) : ( + + )} + + {step.label} + + + )} + + ))} + +
+ ) +}; From 19730beda8e2cf18d0f3549cefc3def052a16c14 Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Mon, 19 Oct 2026 16:06:45 +1100 Subject: [PATCH 02/15] add Wizard --- packages/react-aria-components/src/Wizard.tsx | 334 ++++++++++++++++++ .../react-aria-components/stories/Wizard.css | 115 ++++++ .../stories/Wizard.stories.tsx | 84 +++++ 3 files changed, 533 insertions(+) create mode 100644 packages/react-aria-components/src/Wizard.tsx create mode 100644 packages/react-aria-components/stories/Wizard.css create mode 100644 packages/react-aria-components/stories/Wizard.stories.tsx diff --git a/packages/react-aria-components/src/Wizard.tsx b/packages/react-aria-components/src/Wizard.tsx new file mode 100644 index 00000000000..cbcfc516dbd --- /dev/null +++ b/packages/react-aria-components/src/Wizard.tsx @@ -0,0 +1,334 @@ +/* + * 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 {CollectionBuilder} from 'react-aria/CollectionBuilder'; +import {forwardRefType} from '@react-types/shared'; +import {Collection as ICollection, Key, Node} from '@react-types/shared'; +import intlMessages from '../intl/*.json'; +import React, { + ForwardedRef, + forwardRef, + ReactElement, + ReactNode, + useContext, + useEffect, + useMemo +} from 'react'; +import { + Tab, + TabList, + TabListProps, + TabListStateContext, + TabPanel, + TabPanelProps, + TabPanels, + TabPanelsProps, + TabProps, + Tabs, + TabsProps +} from './Tabs'; +import {useControlledState} from 'react-stately/useControlledState'; +import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter'; +import {VisuallyHidden} from 'react-aria/VisuallyHidden'; + +export interface WizardProps extends Omit { + /** The children of the component (a `WizardStepList` and optional `WizardPanels`). */ + children?: ReactNode; + /** 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; + /** The key of the initially last completed step (uncontrolled). */ + defaultLastCompletedStep?: Key; + /** Handler called when the last completed step changes. */ + 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 displays a sequence of steps. + */ +export const Wizard = /*#__PURE__*/ forwardRef(function Wizard( + props: WizardProps, + ref: ForwardedRef +) { + let {children} = props; + return ( + + {collection => } + + ); +}); + +interface WizardInnerProps { + props: WizardProps; + collection: ICollection>; + tabsRef: ForwardedRef; +} + +export interface WizardStateOptions { + /** Ordered list of step keys, in collection order. */ + keys: Key[]; + /** 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; + /** The key of the initially last completed step (uncontrolled). */ + defaultLastCompletedStep?: Key; + /** Handler called when the last completed step changes. */ + 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 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. The last completed step advances as the selection moves forward + * and is never rolled back unless it's in a controlled state, + * so previously reached steps stay navigable after navigating backwards. + */ +export function useWizardState(options: WizardStateOptions): WizardState { + let { + keys, + allowsRandomAccess = false, + disabledKeys: disabledStepKeys, + onSelectionChange + } = options; + let firstKey = keys.length > 0 ? keys[0] : null; + + let [selectedKeyState, setSelectedKey] = useControlledState( + options.selectedKey, + options.defaultSelectedKey ?? null, + onSelectionChange + ? key => { + if (key != null) { + onSelectionChange(key); + } + } + : undefined + ); + + let selectedKey = selectedKeyState ?? firstKey; + let selectedIndex = selectedKey != null ? keys.indexOf(selectedKey) : -1; + + let [lastCompletedStep, setLastCompletedStep] = useControlledState( + options.lastCompletedStep, + options.defaultLastCompletedStep ?? null, + options.onLastCompletedStepChange + ); + let lastCompletedIndex = lastCompletedStep != null ? keys.indexOf(lastCompletedStep) : -1; + + useEffect(() => { + if (selectedIndex > lastCompletedIndex + 1 && selectedIndex > 0) { + setLastCompletedStep(keys[selectedIndex - 1]); + } + }, [keys, selectedIndex, lastCompletedIndex, setLastCompletedStep]); + + let disabledKeys = useMemo(() => { + // Steps disabled by the consumer are never navigable, however the wizard is configured. + let set = new Set(disabledStepKeys); + keys.forEach((key, i) => { + if (key === selectedKey) { + return; + } + // Completed steps and the current step are navigable; upcoming steps are only if allowsRandomAccess. + if (!allowsRandomAccess && i > lastCompletedIndex + 1) { + set.add(key); + } + }); + return set; + }, [keys, selectedKey, lastCompletedIndex, allowsRandomAccess, disabledStepKeys]); + + return { + selectedKey, + setSelectedKey, + lastCompletedStep, + disabledKeys + }; +} + +function WizardInner({props, collection, tabsRef: ref}: WizardInnerProps) { + let { + children, + selectedKey, + defaultSelectedKey, + onSelectionChange, + lastCompletedStep, + defaultLastCompletedStep, + onLastCompletedStepChange, + allowsRandomAccess, + disabledKeys, + ...tabsProps + } = props; + + // TODO: revist + // Don't have access to the keyboard delegate here, so just rely on the collection order. + let keys = useMemo(() => [...collection].map(item => item.key), [collection]); + + let state = useWizardState({ + keys, + selectedKey, + defaultSelectedKey, + onSelectionChange, + lastCompletedStep, + defaultLastCompletedStep, + onLastCompletedStepChange, + allowsRandomAccess, + disabledKeys + }); + + return ( + + {children} + + ); +} + +export interface WizardStepListProps extends TabListProps {} + +/** The list of steps within a `Wizard` (wraps `TabList`). */ +export const WizardStepList = /*#__PURE__*/ (forwardRef as forwardRefType)(function WizardStepList< + T extends object +>(props: WizardStepListProps, ref: ForwardedRef) { + return ; +}); + +export interface WizardStepProps extends TabProps {} + +export interface WizardStepAria { + /** Whether this step is the current (selected) step. */ + isCurrent: boolean; + /** Whether this step has been completed (precedes the current step). */ + isCompleted: boolean; +} + +/** + * Returns whether the step with the given key is the current step of the enclosing `Wizard`, and + * whether it has already been completed (it is rendered before the current step). + */ +export function useWizardStep(key: Key | undefined): WizardStepAria { + let state = useContext(TabListStateContext); + + if (state == null || key == null || state.selectedKey == null) { + return {isCurrent: false, isCompleted: false}; + } + + let isCurrent = state.selectedKey === key; + + // Walk backwards from the current step. If we reach this step, it precedes the current + // step and is therefore completed. + // Should be ok for performance, wizards are generally short. + let isCompleted = false; + let cursor = state.collection.getKeyBefore(state.selectedKey); + while (cursor != null) { + if (cursor === key) { + isCompleted = true; + break; + } + cursor = state.collection.getKeyBefore(cursor); + } + + return {isCurrent, isCompleted}; +} + +function WizardStepState({stepKey, children}: {stepKey: Key | undefined; children: ReactNode}) { + let {isCurrent, isCompleted} = useWizardStep(stepKey); + let stringFormatter = useLocalizedStringFormatter(intlMessages, 'react-aria-components'); + + let stateText = isCurrent + ? stringFormatter.format('stepListItemCurrent') + : isCompleted + ? stringFormatter.format('stepListItemCompleted') + : stringFormatter.format('stepListItemNotCompleted'); + + return ( + + {!isCurrent && {stateText}} + {children} + + ); +} + +export const WizardStep = /*#__PURE__*/ forwardRef(function WizardStep( + props: WizardStepProps, + ref: ForwardedRef +) { + let {children, ...otherProps} = props; + return ( + + {renderProps => ( + + {typeof children === 'function' ? children(renderProps) : children} + + )} + + ); +}) as (props: WizardStepProps & {ref?: ForwardedRef}) => ReactElement; + +export interface WizardPanelsProps extends TabPanelsProps {} + +export const WizardPanels = /*#__PURE__*/ (forwardRef as forwardRefType)(function WizardPanels< + T extends object +>(props: WizardPanelsProps, ref: ForwardedRef) { + return ; +}); + +export interface WizardPanelProps extends TabPanelProps {} + +export const WizardPanel = /*#__PURE__*/ forwardRef(function WizardPanel( + props: WizardPanelProps, + ref: ForwardedRef +) { + return ; +}); diff --git a/packages/react-aria-components/stories/Wizard.css b/packages/react-aria-components/stories/Wizard.css new file mode 100644 index 00000000000..8bb0df27d3e --- /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-TabList { + display: flex; + overflow-x: auto; + overflow-y: hidden; + border-radius: 16px; + background: var(--spectrum-global-color-gray-300); + } + + .react-aria-Tab { + 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..d155a975f65 --- /dev/null +++ b/packages/react-aria-components/stories/Wizard.stories.tsx @@ -0,0 +1,84 @@ +/* + * 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 {useWizardStep, 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({stepId, index}: {stepId: string; index: number}): ReactNode { + let {isCompleted} = useWizardStep(stepId); + return ( + + ); +} + +export const WizardExample: WizardStory = { + render: (args: any) => ( +
+ + + + {steps.map((step, index) => ( + + + + {step.label} + + Step {index + 1} of {steps.length} + + + + ))} + + +
+ ) +}; From e2fd60bd80872b98283154a4eafc0d803a9d42ec Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Fri, 23 Oct 2026 13:02:22 +1100 Subject: [PATCH 03/15] update readonly to collection and support anchor rendering, add tests --- .../react-aria-components/src/StepList.tsx | 267 ++++++++-------- .../stories/StepList.css | 19 ++ .../stories/StepList.stories.tsx | 73 ++++- .../test/StepList.test.js | 296 ++++++++++++++++++ 4 files changed, 514 insertions(+), 141 deletions(-) create mode 100644 packages/react-aria-components/test/StepList.test.js diff --git a/packages/react-aria-components/src/StepList.tsx b/packages/react-aria-components/src/StepList.tsx index 5d625faea2a..35b4371a790 100644 --- a/packages/react-aria-components/src/StepList.tsx +++ b/packages/react-aria-components/src/StepList.tsx @@ -10,63 +10,69 @@ * governing permissions and limitations under the License. */ -import {AriaLabelingProps, forwardRefType, GlobalDOMAttributes} from '@react-types/shared'; +import { + AriaLabelingProps, + forwardRefType, + GlobalDOMAttributes, + Key, + LinkDOMProps, + Node +} from '@react-types/shared'; import { ClassNameOrFunction, ContextValue, dom, DOMProps, + DOMRenderProps, 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 {getOwnerDocument} from 'react-aria/private/utils/domHelpers'; import intlMessages from '../intl/*.json'; import {mergeProps} from 'react-aria/mergeProps'; -import React, { - createContext, - ForwardedRef, - forwardRef, - RefObject, - useContext, - useState -} from 'react'; +import React, {createContext, ForwardedRef, forwardRef, useContext} from 'react'; import {useId} from 'react-aria/useId'; -import {useLayoutEffect} from 'react-aria/private/utils/useLayoutEffect'; +import {useLink} from 'react-aria/useLink'; import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter'; import {useObjectRef} from 'react-aria/useObjectRef'; -export interface StepListRenderProps {} - -export interface StepListProps +export interface StepListProps extends + Omit, 'disabledKeys'>, + StyleProps, SlotProps, - RenderProps, - GlobalDOMAttributes, - AriaLabelingProps { + AriaLabelingProps, + DOMRenderProps<'ol', undefined>, + GlobalDOMAttributes { /** * 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. + * element. * * @default 'react-aria-StepList' */ - className?: ClassNameOrFunction; + className?: string; /** - * The `id` of the currently selected `StepListItem`. Steps rendered before it are marked as - * completed, and steps rendered after it are marked as not completed. + * 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. */ - selectedId: string; + selectedKey: Key; } -export const StepListContext = createContext>(null); +export const StepListContext = + createContext, HTMLOListElement>>(null); interface StepListState { - /** The `id` of the currently selected step. */ - selectedId: string; - /** Identifies the steps belonging to this list so an item can locate its sibling steps. */ - groupId: string; + /** 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); @@ -74,32 +80,33 @@ 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, +export const StepList = /*#__PURE__*/ (forwardRef as forwardRefType)(function StepList( + props: StepListProps, ref: ForwardedRef ) { [props, ref] = useContextProps(props, ref, StepListContext); - let {selectedId} = props; - let groupId = useId(); - - let renderProps = useRenderProps({ - ...props, - values: {}, - defaultClassName: 'react-aria-StepList' - }); - - let DOMProps = filterDOMProps(props, {labelable: true}); + let {CollectionRoot} = useContext(CollectionRendererContext); + let {selectedKey} = props; + let DOMProps = filterDOMProps(props, {global: true, labelable: true}); return ( - - - {renderProps.children} - - + }> + {collection => ( + + + + + + )} + ); }); @@ -116,6 +123,8 @@ export interface StepListItemRenderProps { * @selector [data-completed] */ isCompleted: boolean; + /** The position of the step within the `StepList`, starting from 1. */ + stepNumber: number; } export interface StepListItemProps @@ -130,114 +139,106 @@ export interface StepListItemProps * @default 'react-aria-StepListItem' */ className?: ClassNameOrFunction; - /** A unique id for the step, which is compared against the `selectedId` of the `StepList`. */ - id: string; + /** A unique id for the step, which is compared against the `selectedKey` of the `StepList`. */ + id?: Key; } -function useStepListItem( - props: StepListItemProps, - state: StepListState | null, - ref: RefObject -) { - let {id} = props; - let groupId = state?.groupId; - let selectedId = state?.selectedId; - let isCurrent = id === selectedId; - // A step is completed if it is rendered before the current step. This can only be determined once - // all of the steps in the group have been rendered, so it is resolved against the DOM. - let [isCompleted, setCompleted] = useState(false); - - useLayoutEffect(() => { - if (!ref.current || groupId == null || isCurrent) { - setCompleted(false); - return; - } - - let currentItem = getOwnerDocument(ref.current).querySelector( - `[data-steplist-group-id="${groupId}"][data-current]` - ); - setCompleted( - currentItem != null && - (currentItem.compareDocumentPosition(ref.current) & Node.DOCUMENT_POSITION_PRECEDING) !== 0 - ); - }, [isCurrent, selectedId, groupId, ref]); - - return { - itemProps: { - 'aria-current': isCurrent ? ('step' as const) : undefined, - 'data-steplist-group-id': groupId, - 'data-current': isCurrent || undefined, - 'data-completed': isCompleted || undefined - }, - isCurrent, - isCompleted - }; +class StepListItemNode extends CollectionNode { + static readonly type = 'item'; } /** * A StepListItem represents an individual step within a ``. */ -export const StepListItem = /*#__PURE__*/ (forwardRef as forwardRefType)(function StepListItem( - props: StepListItemProps, - ref: ForwardedRef -) { - let objRef = useObjectRef(ref); - let state = useContext(InternalStepListContext); - let stringFormatter = useLocalizedStringFormatter(intlMessages, 'react-aria-components'); - let {itemProps, isCurrent, isCompleted} = useStepListItem(props, state, objRef); - let hiddenId = useId(); - - let renderProps = useRenderProps({ - ...props, - values: {isCurrent, isCompleted}, - defaultClassName: 'react-aria-StepListItem' - }); - - let DOMProps = filterDOMProps(props, {labelable: true}); - // `id` identifies the step rather than the DOM element, so it is not forwarded to the DOM. - // TODO IS THIS WEIRD OR WRONG?? - delete DOMProps.id; - - let message = stringFormatter.format('stepListItemNotCompleted'); - if (isCurrent) { - message = stringFormatter.format('stepListItemCurrent'); - } else if (isCompleted) { - message = stringFormatter.format('stepListItemCompleted'); +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} + + + ); } +); - return ( - - - - {renderProps.children} - - - ); -}); +export interface StepListItemContentProps + extends + DOMProps, + LinkDOMProps, + AriaLabelingProps, + Omit, 'onClick'> {} -interface StepListItemContentProps extends DOMProps {} const StepListItemContext = createContext<{hiddenId: string | undefined} | undefined>(undefined); -// Need this so I can get an id on the contents so that the announcement makes sense. It lands on this element, not the `li` itself. +// Need this so I can get an id on the contents so that the announcement makes sense. +// It lands on this element, not the `li` itself. export const StepListItemContent = /*#__PURE__*/ (forwardRef as forwardRefType)( - function StepListItemContent(props: StepListItemContentProps, ref: ForwardedRef) { + function StepListItemContent( + props: StepListItemContentProps, + ref: ForwardedRef + ) { let context = useContext(StepListItemContext); let objRef = useObjectRef(ref); - let DOMProps = filterDOMProps(props, {labelable: true}); 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]; + let DOMProps = filterDOMProps(props, {global: true, labelable: true, isLink}); + delete DOMProps.id; return ( - {props.children} - + ); } ); diff --git a/packages/react-aria-components/stories/StepList.css b/packages/react-aria-components/stories/StepList.css index 0f3c2aa9aad..cbadb9527db 100644 --- a/packages/react-aria-components/stories/StepList.css +++ b/packages/react-aria-components/stories/StepList.css @@ -57,3 +57,22 @@ 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):hover .label { + text-decoration: underline; + } + + &: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 index fd02813a64f..bfb04816d4a 100644 --- a/packages/react-aria-components/stories/StepList.stories.tsx +++ b/packages/react-aria-components/stories/StepList.stories.tsx @@ -16,19 +16,19 @@ import {StepList, StepListItem, StepListItemContent} from '../src/StepList'; import './StepList.css'; const steps = [ - {id: 'domain', label: 'Domain/Sender details'}, - {id: 'dns', label: 'Configure DNS'}, - {id: 'advanced', label: 'Advanced settings'} + {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: { - selectedId: 'dns' + selectedKey: 'dns' }, argTypes: { - selectedId: { + selectedKey: { control: 'radio', options: steps.map(step => step.id) } @@ -56,15 +56,15 @@ export const StepListExample: StepListStory = {
- {steps.map((step, index) => ( + {steps.map(step => ( - {({isCompleted}) => ( + {({isCompleted, stepNumber}) => ( {isCompleted ? ( ) : ( )} @@ -78,3 +78,60 @@ export const StepListExample: StepListStory = {
) }; + +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/test/StepList.test.js b/packages/react-aria-components/test/StepList.test.js new file mode 100644 index 00000000000..af1e0eb3936 --- /dev/null +++ b/packages/react-aria-components/test/StepList.test.js @@ -0,0 +1,296 @@ +/* + * 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 React from 'react'; +import {render} from '@react-spectrum/test-utils-internal'; +import {StepList, StepListContext, StepListItem, StepListItemContent} from '../src/StepList'; + +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', () => { + 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('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'); + } + }); +}); From 83487e79d30080aa806e3a1c99da78c6b7daa7d6 Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Fri, 23 Oct 2026 18:12:25 +1100 Subject: [PATCH 04/15] Fix old storybook --- package.json | 3 ++- packages/react-aria-components/src/StepList.tsx | 15 +++++++++++++-- .../react-aria-components/stories/StepList.css | 4 ++-- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 17699d4f2a2..487a2ecca69 100644 --- a/package.json +++ b/package.json @@ -297,7 +297,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/react-aria-components/src/StepList.tsx b/packages/react-aria-components/src/StepList.tsx index 35b4371a790..311f106cfc7 100644 --- a/packages/react-aria-components/src/StepList.tsx +++ b/packages/react-aria-components/src/StepList.tsx @@ -38,6 +38,8 @@ 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'; @@ -227,16 +229,25 @@ export const StepListItemContent = /*#__PURE__*/ (forwardRef as forwardRefType)( 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; return ( + aria-labelledby={`${context?.hiddenId} ${id}`} + data-hovered={isHovered || undefined} + data-focus-visible={isFocusVisible || undefined}> {props.children} ); diff --git a/packages/react-aria-components/stories/StepList.css b/packages/react-aria-components/stories/StepList.css index cbadb9527db..7a1c8ef632c 100644 --- a/packages/react-aria-components/stories/StepList.css +++ b/packages/react-aria-components/stories/StepList.css @@ -67,11 +67,11 @@ color: inherit; text-decoration: none; - &:is(a):hover .label { + &:is(a)[data-hovered] .label { text-decoration: underline; } - &:focus-visible { + &[data-focus-visible] { outline: 2px solid var(--spectrum-alias-focus-ring-color); outline-offset: 2px; } From 7e41f3b5b5d63abc1795752c6200cb32b9f7607e Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Fri, 6 Nov 2026 14:56:37 -0800 Subject: [PATCH 05/15] update to actual API in tests --- .../test/StepList.test.js | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/packages/react-aria-components/test/StepList.test.js b/packages/react-aria-components/test/StepList.test.js index af1e0eb3936..33b0e4c69f5 100644 --- a/packages/react-aria-components/test/StepList.test.js +++ b/packages/react-aria-components/test/StepList.test.js @@ -13,6 +13,7 @@ import React from 'react'; import {render} from '@react-spectrum/test-utils-internal'; import {StepList, StepListContext, StepListItem, StepListItemContent} from '../src/StepList'; +import {Step} from '/packages/dev/s2-docs/src/Step'; let steps = [ {id: 'domain', label: 'Domain'}, @@ -25,7 +26,7 @@ let renderStepList = (listProps, itemProps) => {steps.map(step => ( - {step.label} + {step.label} ))} @@ -77,7 +78,7 @@ describe('StepList', () => { {steps.map(step => ( - {step.label} + {step.label} ))} @@ -101,7 +102,11 @@ describe('StepList', () => { it('should support dynamic collections', () => { let {getAllByRole} = render( - {step => {step.label}} + {step => ( + + {step.label} + + )} ); @@ -120,9 +125,11 @@ describe('StepList', () => { {step => ( - {({isCurrent, isCompleted}) => - isCurrent ? 'current' : isCompleted ? 'completed' : step.label - } + {({isCurrent, isCompleted}) => ( + + {isCurrent ? 'current' : isCompleted ? 'completed' : step.label} + + )} )} @@ -138,7 +145,11 @@ describe('StepList', () => { it('should provide a 1-based step number to render props', () => { let {getAllByRole} = render( - {() => {({stepNumber}) => `Step ${stepNumber}`}} + {() => ( + + {({stepNumber}) => {`Step ${stepNumber}`}} + + )} ); @@ -156,7 +167,7 @@ describe('StepList', () => { `step-${stepNumber}`} style={({stepNumber}) => ({order: stepNumber})}> - {step.label} + {step.label} )} @@ -209,7 +220,7 @@ describe('StepList', () => { let {getByRole} = render( - A + A ); @@ -222,7 +233,9 @@ describe('StepList', () => { let {getByRole} = render( - A + + A + ); From 2de527a43a06cbc52c6ebb1b1fefa5464ecf1467 Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Fri, 6 Nov 2026 15:31:52 -0800 Subject: [PATCH 06/15] remove comment --- packages/react-aria-components/src/StepList.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/react-aria-components/src/StepList.tsx b/packages/react-aria-components/src/StepList.tsx index 311f106cfc7..092c1923076 100644 --- a/packages/react-aria-components/src/StepList.tsx +++ b/packages/react-aria-components/src/StepList.tsx @@ -213,8 +213,6 @@ export interface StepListItemContentProps const StepListItemContext = createContext<{hiddenId: string | undefined} | undefined>(undefined); -// Need this so I can get an id on the contents so that the announcement makes sense. -// It lands on this element, not the `li` itself. export const StepListItemContent = /*#__PURE__*/ (forwardRef as forwardRefType)( function StepListItemContent( props: StepListItemContentProps, From b6a52df6ed77958532f23f93fdadc2c513922771 Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Fri, 6 Nov 2026 17:04:53 -0800 Subject: [PATCH 07/15] add wizard tests and remove useEffect sync in Wizard --- packages/react-aria-components/src/Wizard.tsx | 66 +- .../react-aria-components/test/Wizard.test.js | 643 ++++++++++++++++++ 2 files changed, 689 insertions(+), 20 deletions(-) create mode 100644 packages/react-aria-components/test/Wizard.test.js diff --git a/packages/react-aria-components/src/Wizard.tsx b/packages/react-aria-components/src/Wizard.tsx index cbcfc516dbd..b2a7ce5838a 100644 --- a/packages/react-aria-components/src/Wizard.tsx +++ b/packages/react-aria-components/src/Wizard.tsx @@ -19,8 +19,8 @@ import React, { ReactElement, ReactNode, useContext, - useEffect, - useMemo + useMemo, + useState } from 'react'; import { Tab, @@ -52,10 +52,13 @@ export interface WizardProps extends Omit * The key of the last completed step (controlled). Every step up to and including the one after * it is navigable by default. */ - lastCompletedStep?: Key; + lastCompletedStep?: Key | null; /** The key of the initially last completed step (uncontrolled). */ defaultLastCompletedStep?: Key; - /** Handler called when the last completed step changes. */ + /** + * 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 @@ -95,10 +98,13 @@ export interface WizardStateOptions { /** Handler called when the selected step changes. */ onSelectionChange?: (key: Key) => void; /** The key of the last completed step (controlled). */ - lastCompletedStep?: Key; + lastCompletedStep?: Key | null; /** The key of the initially last completed step (uncontrolled). */ defaultLastCompletedStep?: Key; - /** Handler called when the last completed step changes. */ + /** + * 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; @@ -125,20 +131,23 @@ export interface WizardState { /** * 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. The last completed step advances as the selection moves forward - * and is never rolled back unless it's in a controlled state, - * so previously reached steps stay navigable after navigating backwards. + * 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(options: WizardStateOptions): WizardState { let { keys, allowsRandomAccess = false, disabledKeys: disabledStepKeys, - onSelectionChange + onSelectionChange, + onLastCompletedStepChange } = options; let firstKey = keys.length > 0 ? keys[0] : null; - let [selectedKeyState, setSelectedKey] = useControlledState( + let [selectedKeyState, setSelectedKeyState] = useControlledState( options.selectedKey, options.defaultSelectedKey ?? null, onSelectionChange @@ -153,18 +162,33 @@ export function useWizardState(options: WizardStateOptions): WizardState { let selectedKey = selectedKeyState ?? firstKey; let selectedIndex = selectedKey != null ? keys.indexOf(selectedKey) : -1; - let [lastCompletedStep, setLastCompletedStep] = useControlledState( - options.lastCompletedStep, - options.defaultLastCompletedStep ?? null, - options.onLastCompletedStepChange + let isLastCompletedStepControlled = options.lastCompletedStep !== undefined; + let [lastCompletedStepState, setLastCompletedStepState] = useState( + options.defaultLastCompletedStep ?? null ); + let lastCompletedStep = isLastCompletedStepControlled + ? (options.lastCompletedStep ?? null) + : lastCompletedStepState; let lastCompletedIndex = lastCompletedStep != null ? keys.indexOf(lastCompletedStep) : -1; - useEffect(() => { - if (selectedIndex > lastCompletedIndex + 1 && selectedIndex > 0) { - setLastCompletedStep(keys[selectedIndex - 1]); + // 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 && selectedIndex - 1 > lastCompletedIndex) { + lastCompletedIndex = selectedIndex - 1; + lastCompletedStep = keys[lastCompletedIndex]; + 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 index = keys.indexOf(key); + if (index - 1 > lastCompletedIndex) { + onLastCompletedStepChange?.(keys[index - 1]); } - }, [keys, selectedIndex, lastCompletedIndex, setLastCompletedStep]); + }; let disabledKeys = useMemo(() => { // Steps disabled by the consumer are never navigable, however the wizard is configured. @@ -219,12 +243,14 @@ function WizardInner({props, collection, tabsRef: ref}: WizardInnerProps) { 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} 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..9d3b64a0785 --- /dev/null +++ b/packages/react-aria-components/test/Wizard.test.js @@ -0,0 +1,643 @@ +/* + * 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, renderHook, 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 { + useWizardState, + useWizardStep, + 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 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 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', async () => { + let tree = render(); + let tabs = tree.getAllByRole('tab'); + + expect(tabs.map(tab => tab.textContent)).toEqual([ + 'CompletedDomain', + 'CompletedDNS', + 'Advanced', + 'Not completedReview' + ]); + let states = tabs.map(tab => tab.firstElementChild); + expect(states[0]).toHaveAttribute('data-completed'); + expect(states[1]).toHaveAttribute('data-completed'); + expect(states[2]).toHaveAttribute('data-current'); + expect(states[2]).not.toHaveAttribute('data-completed'); + expect(states[3]).not.toHaveAttribute('data-completed'); + expect(states[3]).not.toHaveAttribute('data-current'); + + // Completion follows the selection, so steps after the selected step are not completed after + // navigating back, even though they are still navigable. + await user.click(tabs[0]); + expect(tabs.map(tab => tab.textContent)).toEqual([ + 'Domain', + 'Not completedDNS', + 'Not completedAdvanced', + 'Not completedReview' + ]); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + }); + + it('should provide the step state to useWizardStep', async () => { + function StepState({id}) { + let {isCurrent, isCompleted} = useWizardStep(id); + return {isCurrent ? 'current' : isCompleted ? 'completed' : 'upcoming'}; + } + + let tree = render( + + + {steps.map(step => ( + + + + ))} + + + ); + + let getStates = () => + tree.getAllByRole('tab').map(tab => tab.firstElementChild.lastChild.textContent); + expect(getStates()).toEqual(['completed', 'current', 'upcoming', 'upcoming']); + + await user.click(tree.getAllByRole('tab')[0]); + expect(getStates()).toEqual(['current', 'upcoming', 'upcoming', 'upcoming']); + }); + + it('should return a default step state from useWizardStep outside of a Wizard', () => { + let {result} = renderHook(() => useWizardStep('domain')); + expect(result.current).toEqual({isCurrent: false, isCompleted: false}); + }); + + 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('should only allow navigating to the first step when no steps are completed', async () => { + 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']); + + // 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(); + let tree = render( + + ); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); + // 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); + + // Unlike an uncontrolled last completed step, a controlled one can be rolled back. + tree.rerender( + + ); + expect(getNavigableSteps(tree)).toEqual(['domain', 'dns']); + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + 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('should never allow navigating to steps in disabledKeys', async () => { + 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'); + }); + }); +}); + +describe('useWizardState', () => { + it('should select the first step and complete no steps by default', () => { + let {result} = renderHook(() => useWizardState({keys})); + expect(result.current.selectedKey).toBe('domain'); + expect(result.current.lastCompletedStep).toBeNull(); + expect(result.current.disabledKeys).toEqual(new Set(['dns', 'advanced', 'review'])); + }); + + it('should support defaultLastCompletedStep', () => { + let {result} = renderHook(() => useWizardState({keys, defaultLastCompletedStep: 'dns'})); + expect(result.current.selectedKey).toBe('domain'); + expect(result.current.lastCompletedStep).toBe('dns'); + expect(result.current.disabledKeys).toEqual(new Set(['review'])); + }); + + it('should complete the steps before the default selected step', () => { + let onLastCompletedStepChange = jest.fn(); + let renders = []; + let {result} = renderHook(() => { + let state = useWizardState({keys, defaultSelectedKey: 'advanced', onLastCompletedStepChange}); + renders.push(state); + return state; + }); + expect(result.current.selectedKey).toBe('advanced'); + expect(result.current.lastCompletedStep).toBe('dns'); + expect(result.current.disabledKeys).toEqual(new Set(['review'])); + + // The last completed step is derived during render rather than synced in an effect, so it's + // already correct on the first render. Like other default values, it doesn't call the change + // handler. + expect(renders[0].lastCompletedStep).toBe('dns'); + expect(renders[0].disabledKeys).toEqual(new Set(['review'])); + expect(onLastCompletedStepChange).not.toHaveBeenCalled(); + }); + + it('should advance the last completed step with the selection and never roll it back', () => { + let onLastCompletedStepChange = jest.fn(); + let {result} = renderHook(() => useWizardState({keys, onLastCompletedStepChange})); + + act(() => result.current.setSelectedKey('dns')); + expect(result.current.lastCompletedStep).toBe('domain'); + expect(result.current.disabledKeys).toEqual(new Set(['advanced', 'review'])); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(1); + expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('domain'); + + // Skipping ahead completes every step before the selected step. + act(() => result.current.setSelectedKey('review')); + expect(result.current.lastCompletedStep).toBe('advanced'); + expect(result.current.disabledKeys).toEqual(new Set()); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(2); + expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('advanced'); + + act(() => result.current.setSelectedKey('domain')); + expect(result.current.selectedKey).toBe('domain'); + expect(result.current.lastCompletedStep).toBe('advanced'); + expect(result.current.disabledKeys).toEqual(new Set()); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(2); + }); + + it('should support a controlled lastCompletedStep', () => { + let onLastCompletedStepChange = jest.fn(); + let {result, rerender} = renderHook( + ({lastCompletedStep}) => useWizardState({keys, lastCompletedStep, onLastCompletedStepChange}), + {initialProps: {lastCompletedStep: 'advanced'}} + ); + expect(result.current.lastCompletedStep).toBe('advanced'); + expect(result.current.disabledKeys).toEqual(new Set()); + + rerender({lastCompletedStep: 'domain'}); + expect(result.current.lastCompletedStep).toBe('domain'); + expect(result.current.disabledKeys).toEqual(new Set(['advanced', 'review'])); + + act(() => result.current.setSelectedKey('advanced')); + expect(onLastCompletedStepChange).toHaveBeenCalledTimes(1); + expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('dns'); + expect(result.current.lastCompletedStep).toBe('domain'); + expect(result.current.disabledKeys).toEqual(new Set(['review'])); + }); + + it('should always disable steps in disabledKeys', () => { + let {result} = renderHook(() => + useWizardState({keys, allowsRandomAccess: true, disabledKeys: ['dns']}) + ); + expect(result.current.disabledKeys).toEqual(new Set(['dns'])); + }); +}); From 2f763c90f3c74cf14b3ee2e28c08451bcab1b12c Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Wed, 11 Nov 2026 08:31:34 +1100 Subject: [PATCH 08/15] fix lint --- packages/react-aria-components/test/StepList.test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/react-aria-components/test/StepList.test.js b/packages/react-aria-components/test/StepList.test.js index 33b0e4c69f5..70a5f48dca0 100644 --- a/packages/react-aria-components/test/StepList.test.js +++ b/packages/react-aria-components/test/StepList.test.js @@ -13,7 +13,6 @@ import React from 'react'; import {render} from '@react-spectrum/test-utils-internal'; import {StepList, StepListContext, StepListItem, StepListItemContent} from '../src/StepList'; -import {Step} from '/packages/dev/s2-docs/src/Step'; let steps = [ {id: 'domain', label: 'Domain'}, From 061788733b7453d84b3d194c9c1ee806868c44ac Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Wed, 11 Nov 2026 11:13:34 +1100 Subject: [PATCH 09/15] Add docs and exports for readonly steplist --- .../dev/s2-docs/pages/react-aria/StepList.mdx | 167 ++++++++++++++++++ .../react-aria-components/exports/StepList.ts | 24 +++ .../react-aria-components/exports/index.ts | 7 + .../react-aria-components/src/StepList.tsx | 85 +++++---- .../test/StepList.test.js | 98 +++++++++- starters/docs/src/StepList.css | 74 ++++++++ starters/docs/src/StepList.tsx | 52 ++++++ starters/docs/stories/StepList.stories.tsx | 33 ++++ starters/tailwind/src/StepList.tsx | 78 ++++++++ .../tailwind/stories/StepList.stories.tsx | 33 ++++ 10 files changed, 620 insertions(+), 31 deletions(-) create mode 100644 packages/dev/s2-docs/pages/react-aria/StepList.mdx create mode 100644 packages/react-aria-components/exports/StepList.ts create mode 100644 starters/docs/src/StepList.css create mode 100644 starters/docs/src/StepList.tsx create mode 100644 starters/docs/stories/StepList.stories.tsx create mode 100644 starters/tailwind/src/StepList.tsx create mode 100644 starters/tailwind/stories/StepList.stories.tsx 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..dd86be7b22c --- /dev/null +++ b/packages/dev/s2-docs/pages/react-aria/StepList.mdx @@ -0,0 +1,167 @@ +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: 'preferences', label: 'Preferences'}, + {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 -*/ + }> + {/*- 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}} + +
    + + +
    +
    + ); +} +``` + +## API + +```tsx links={{StepList: '#steplist', StepListItem: '#steplistitem', StepListItemContent: '#steplistitemcontent'}} + + + + + +``` + +### StepList + + + +### StepListItem + + + +### StepListItemContent + + 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/index.ts b/packages/react-aria-components/exports/index.ts index 0b2816f589c..ccf44c49e29 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, @@ -472,6 +473,12 @@ export type { SliderFillRenderProps, SliderThumbRenderProps } from '../src/Slider'; +export type { + StepListProps, + StepListItemProps, + StepListItemRenderProps, + StepListItemContentProps +} from '../src/StepList'; export type { SwitchProps, SwitchRenderProps, diff --git a/packages/react-aria-components/src/StepList.tsx b/packages/react-aria-components/src/StepList.tsx index 092c1923076..f0673768eea 100644 --- a/packages/react-aria-components/src/StepList.tsx +++ b/packages/react-aria-components/src/StepList.tsx @@ -24,6 +24,7 @@ import { dom, DOMProps, DOMRenderProps, + PossibleLinkDOMRenderProps, RenderProps, SlotProps, StyleProps, @@ -80,7 +81,7 @@ interface StepListState { const InternalStepListContext = createContext(null); /** - * A StepList displays the steps of a multi step process, and which of them the user has completed. + * 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, @@ -209,45 +210,69 @@ export interface StepListItemContentProps 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 ) { - 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; - + // 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 ( - - {props.children} - + ); } ); + +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; + + return ( + + {props.children} + + ); +} diff --git a/packages/react-aria-components/test/StepList.test.js b/packages/react-aria-components/test/StepList.test.js index 70a5f48dca0..88593612885 100644 --- a/packages/react-aria-components/test/StepList.test.js +++ b/packages/react-aria-components/test/StepList.test.js @@ -10,9 +10,10 @@ * governing permissions and limitations under the License. */ +import {pointerMap, render} from '@react-spectrum/test-utils-internal'; import React from 'react'; -import {render} from '@react-spectrum/test-utils-internal'; import {StepList, StepListContext, StepListItem, StepListItemContent} from '../src/StepList'; +import userEvent from '@testing-library/user-event'; let steps = [ {id: 'domain', label: 'Domain'}, @@ -32,6 +33,11 @@ let renderStepList = (listProps, itemProps) => ); 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'); @@ -259,6 +265,64 @@ describe('StepList', () => { expect(contentId).toBe(step.id); }); + 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( @@ -305,4 +369,36 @@ describe('StepList', () => { 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/starters/docs/src/StepList.css b/starters/docs/src/StepList.css new file mode 100644 index 00000000000..c182b1cd0ec --- /dev/null +++ b/starters/docs/src/StepList.css @@ -0,0 +1,74 @@ +@import './theme.css'; + +.react-aria-StepList { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--spacing-2); + margin: 0; + padding: 0; + list-style: none; + font: var(--font-size) system-ui; + color: var(--text-color); +} + +.react-aria-StepListItem { + display: flex; + align-items: center; + gap: var(--spacing-2); + + .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 line between steps. */ + &:not(:last-child)::after { + content: ''; + width: var(--spacing-6); + border-top: 1px solid var(--border-color); + } + + &[data-completed]::after { + border-color: var(--highlight-background); + } +} + +.react-aria-StepListItemContent { + display: flex; + align-items: center; + gap: var(--spacing-2); + 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/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/tailwind/src/StepList.tsx b/starters/tailwind/src/StepList.tsx new file mode 100644 index 00000000000..68821a623a1 --- /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/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 + + +); From cdb51143fb4bf6e57d56718c48d4bce9ebae365a Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Wed, 11 Nov 2026 11:56:33 +1100 Subject: [PATCH 10/15] Make examples better on small screens --- .../dev/s2-docs/pages/react-aria/StepList.mdx | 4 +- starters/docs/src/StepList.css | 39 +++++++++++++++---- starters/tailwind/src/StepList.tsx | 8 ++-- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/packages/dev/s2-docs/pages/react-aria/StepList.mdx b/packages/dev/s2-docs/pages/react-aria/StepList.mdx index dd86be7b22c..d72b402970c 100644 --- a/packages/dev/s2-docs/pages/react-aria/StepList.mdx +++ b/packages/dev/s2-docs/pages/react-aria/StepList.mdx @@ -51,7 +51,7 @@ import {StepList, StepListItem} from 'vanilla-starter/StepList'; let steps = [ {id: 'account', label: 'Account'}, {id: 'profile', label: 'Profile'}, - {id: 'preferences', label: 'Preferences'}, + {id: 'settings', label: 'Settings'}, {id: 'confirm', label: 'Confirm'} ]; @@ -126,7 +126,7 @@ function Example() { let [index, setIndex] = useState(1); return ( -
    +
    ({ @@ -55,8 +55,8 @@ export function StepListItem({children, href, ...props}: StepListItemProps) { {...props} className={composeTailwindRenderProps( props.className, - // The ::after element draws a connector line between steps. - 'flex items-center gap-2 current:font-semibold after:w-6 after:border-t after:border-neutral-400 data-completed:after:border-blue-600 last:after:hidden' + // The ::before and ::after elements draw the connector lines on either side of the marker. + 'relative box-border flex w-24 flex-1 justify-center px-1 current:font-semibold before:absolute before:start-0 before:end-[calc(50%+--spacing(5))] before:top-3 before:border-t before:border-neutral-400 first:before:hidden current:before:border-blue-600 data-completed:before:border-blue-600 after:absolute after:start-[calc(50%+--spacing(5))] after:end-0 after:top-3 after:border-t after:border-neutral-400 data-completed:after:border-blue-600 last:after:hidden' )}> {({isCurrent, isCompleted, stepNumber}) => { // Only completed steps are links, so users can go back but not skip ahead. @@ -65,7 +65,7 @@ export function StepListItem({children, href, ...props}: StepListItemProps) { + className="flex flex-col items-center gap-2 text-center rounded-xs text-current no-underline outline-0 outline-offset-2 outline-blue-600 dark:outline-blue-500 forced-colors:outline-[Highlight] data-hovered:underline data-focus-visible:outline-2 [-webkit-tap-highlight-color:transparent]"> {isCompleted ? : stepNumber} From 9f2580f7f46029271ab012e237655571097f5815 Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Wed, 11 Nov 2026 13:16:42 +1100 Subject: [PATCH 11/15] add wizard docs --- .../dev/s2-docs/pages/react-aria/StepList.mdx | 5 + .../dev/s2-docs/pages/react-aria/Wizard.mdx | 179 ++++++++++++++++++ .../react-aria-components/exports/Wizard.ts | 28 +++ .../react-aria-components/exports/index.ts | 11 ++ packages/react-aria-components/src/Wizard.tsx | 112 +++++++++-- .../react-aria-components/stories/Wizard.css | 4 +- .../react-aria-components/test/Wizard.test.js | 28 +++ starters/docs/src/Wizard.css | 112 +++++++++++ starters/docs/src/Wizard.tsx | 88 +++++++++ starters/docs/stories/Wizard.stories.tsx | 40 ++++ starters/tailwind/src/Wizard.tsx | 141 ++++++++++++++ starters/tailwind/stories/Wizard.stories.tsx | 36 ++++ 12 files changed, 770 insertions(+), 14 deletions(-) create mode 100644 packages/dev/s2-docs/pages/react-aria/Wizard.mdx create mode 100644 packages/react-aria-components/exports/Wizard.ts create mode 100644 starters/docs/src/Wizard.css create mode 100644 starters/docs/src/Wizard.tsx create mode 100644 starters/docs/stories/Wizard.stories.tsx create mode 100644 starters/tailwind/src/Wizard.tsx create mode 100644 starters/tailwind/stories/Wizard.stories.tsx diff --git a/packages/dev/s2-docs/pages/react-aria/StepList.mdx b/packages/dev/s2-docs/pages/react-aria/StepList.mdx index d72b402970c..768feeb922b 100644 --- a/packages/dev/s2-docs/pages/react-aria/StepList.mdx +++ b/packages/dev/s2-docs/pages/react-aria/StepList.mdx @@ -144,6 +144,11 @@ function Example() { } ``` +## StepList vs. Wizard + +Use a `StepList` to show the user's progress through a process where each step is 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'}} 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..fa1b128ecff --- /dev/null +++ b/packages/dev/s2-docs/pages/react-aria/Wizard.mdx @@ -0,0 +1,179 @@ +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'; +import {FunctionAPI} from '../../src/FunctionAPI'; + +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. + +```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/Wizard.ts b/packages/react-aria-components/exports/Wizard.ts new file mode 100644 index 00000000000..34fc6b7b711 --- /dev/null +++ b/packages/react-aria-components/exports/Wizard.ts @@ -0,0 +1,28 @@ +/* + * 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, + 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 ccf44c49e29..e3105dd0f90 100644 --- a/packages/react-aria-components/exports/index.ts +++ b/packages/react-aria-components/exports/index.ts @@ -264,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, @@ -566,6 +567,16 @@ export type { TreeLoadMoreItemProps, TreeLoadMoreItemRenderProps } from '../src/Tree'; +export type { + WizardProps, + WizardStepListProps, + WizardStepProps, + 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/src/Wizard.tsx b/packages/react-aria-components/src/Wizard.tsx index b2a7ce5838a..5ee7b980067 100644 --- a/packages/react-aria-components/src/Wizard.tsx +++ b/packages/react-aria-components/src/Wizard.tsx @@ -9,6 +9,7 @@ * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ +import {ClassNameOrFunction} from './utils'; import {CollectionBuilder} from 'react-aria/CollectionBuilder'; import {forwardRefType} from '@react-types/shared'; import {Collection as ICollection, Key, Node} from '@react-types/shared'; @@ -26,14 +27,18 @@ import { Tab, TabList, TabListProps, + TabListRenderProps, TabListStateContext, TabPanel, TabPanelProps, + TabPanelRenderProps, TabPanels, TabPanelsProps, TabProps, + TabRenderProps, Tabs, - TabsProps + TabsProps, + TabsRenderProps } from './Tabs'; import {useControlledState} from 'react-stately/useControlledState'; import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter'; @@ -42,6 +47,13 @@ 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). */ @@ -68,7 +80,8 @@ export interface WizardProps extends Omit } /** - * A Wizard displays a sequence of steps. + * 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, @@ -82,6 +95,17 @@ export const Wizard = /*#__PURE__*/ forwardRef(function Wizard( ); }); +// 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>; @@ -216,6 +240,7 @@ export function useWizardState(options: WizardStateOptions): WizardState { function WizardInner({props, collection, tabsRef: ref}: WizardInnerProps) { let { children, + className, selectedKey, defaultSelectedKey, onSelectionChange, @@ -248,6 +273,7 @@ function WizardInner({props, collection, tabsRef: ref}: WizardInnerProps) { return ( extends TabListProps {} +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; +} -/** The list of steps within a `Wizard` (wraps `TabList`). */ +/** + * 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 ; + return ( + + ); }); -export interface WizardStepProps extends TabProps {} +export interface WizardStepProps extends TabProps { + /** + * 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. */ @@ -326,13 +377,20 @@ function WizardStepState({stepKey, children}: {stepKey: Key | undefined; childre ); } +/** + * A WizardStep represents an individual step within a ``. + */ export const WizardStep = /*#__PURE__*/ forwardRef(function WizardStep( props: WizardStepProps, ref: ForwardedRef ) { - let {children, ...otherProps} = props; + let {children, className, ...otherProps} = props; return ( - + {renderProps => ( {typeof children === 'function' ? children(renderProps) : children} @@ -342,19 +400,49 @@ export const WizardStep = /*#__PURE__*/ forwardRef(function WizardStep( ); }) as (props: WizardStepProps & {ref?: ForwardedRef}) => ReactElement; -export interface WizardPanelsProps extends TabPanelsProps {} +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 ; + return ( + + ); }); -export interface WizardPanelProps extends TabPanelProps {} +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 ; + return ( + + ); }); diff --git a/packages/react-aria-components/stories/Wizard.css b/packages/react-aria-components/stories/Wizard.css index 8bb0df27d3e..fd662aa0a5f 100644 --- a/packages/react-aria-components/stories/Wizard.css +++ b/packages/react-aria-components/stories/Wizard.css @@ -5,7 +5,7 @@ --overlap: 12px; --padding: 12px; - .react-aria-TabList { + .react-aria-WizardStepList { display: flex; overflow-x: auto; overflow-y: hidden; @@ -13,7 +13,7 @@ background: var(--spectrum-global-color-gray-300); } - .react-aria-Tab { + .react-aria-WizardStep { display: flex; flex: 1 1 0; align-items: center; diff --git a/packages/react-aria-components/test/Wizard.test.js b/packages/react-aria-components/test/Wizard.test.js index 9d3b64a0785..227d20b2873 100644 --- a/packages/react-aria-components/test/Wizard.test.js +++ b/packages/react-aria-components/test/Wizard.test.js @@ -133,6 +133,34 @@ describe('Wizard', () => { 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( diff --git a/starters/docs/src/Wizard.css b/starters/docs/src/Wizard.css new file mode 100644 index 00000000000..4c688f91f02 --- /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, + .marker[data-completed] { + 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, + &:has(.marker[data-completed])::before, + &:has(.marker[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..d5c3ad7532b --- /dev/null +++ b/starters/docs/src/Wizard.tsx @@ -0,0 +1,88 @@ +'use client'; +import { + type Key, + useWizardStep, + 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 => ( + <> + + {children} + + ))} + + ); +} + +// The step already announces its label and whether it is completed, so the marker is hidden +// from assistive technology. +function StepMarker({id}: {id?: Key}) { + let state = useContext(TabListStateContext); + let {isCompleted} = useWizardStep(id); + let node = id != null ? state?.collection.getItem(id) : null; + return ( + + {isCompleted ? : (node?.index ?? 0) + 1} + + ); +} + +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/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/Wizard.tsx b/starters/tailwind/src/Wizard.tsx new file mode 100644 index 00000000000..93e1ec9fa54 --- /dev/null +++ b/starters/tailwind/src/Wizard.tsx @@ -0,0 +1,141 @@ +'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 { + type Key, + useWizardStep, + 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 ( + + ); +} + +export function WizardStep(props: WizardStepProps) { + return ( + + {composeRenderProps(props.children, (children, {isSelected, isFocusVisible}) => ( + <> + + {children} + + ))} + + ); +} + +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]' + } + } +}); + +interface StepMarkerProps { + id?: Key; + isSelected: boolean; + isFocusVisible: boolean; +} + +// The step already announces its label and whether it is completed, so the marker is hidden +// from assistive technology. +function StepMarker({id, isSelected, isFocusVisible}: StepMarkerProps) { + let state = useContext(TabListStateContext); + let {isCompleted} = useWizardStep(id); + let node = id != null ? state?.collection.getItem(id) : null; + return ( + + {isCompleted ? : (node?.index ?? 0) + 1} + + ); +} + +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/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. + + + +); From 7c66174166563d9ca7da37fa205a97ff9844d6af Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Wed, 11 Nov 2026 14:10:59 +1100 Subject: [PATCH 12/15] refactor and fix typecheck --- .../dev/s2-docs/pages/react-aria/StepList.mdx | 2 +- .../dev/s2-docs/pages/react-aria/Wizard.mdx | 3 +- .../react-aria-components/exports/Wizard.ts | 1 + .../react-aria-components/exports/index.ts | 1 + packages/react-aria-components/src/Wizard.tsx | 218 +++++++++++------- .../stories/Wizard.stories.tsx | 33 ++- .../react-aria-components/test/Wizard.test.js | 179 +++++--------- starters/docs/src/Wizard.css | 6 +- starters/docs/src/Wizard.tsx | 22 +- starters/tailwind/src/Wizard.tsx | 62 ++--- 10 files changed, 243 insertions(+), 284 deletions(-) diff --git a/packages/dev/s2-docs/pages/react-aria/StepList.mdx b/packages/dev/s2-docs/pages/react-aria/StepList.mdx index 768feeb922b..68b444c2bb3 100644 --- a/packages/dev/s2-docs/pages/react-aria/StepList.mdx +++ b/packages/dev/s2-docs/pages/react-aria/StepList.mdx @@ -82,7 +82,7 @@ import {Router, Link as RouterLink} from './Router'; {({selectedRoute}) => ( /*- begin highlight -*/ - }> + 'href' in props ? :
    }> {/*- end highlight -*/} Cart Shipping diff --git a/packages/dev/s2-docs/pages/react-aria/Wizard.mdx b/packages/dev/s2-docs/pages/react-aria/Wizard.mdx index fa1b128ecff..bc8f64e02f0 100644 --- a/packages/dev/s2-docs/pages/react-aria/Wizard.mdx +++ b/packages/dev/s2-docs/pages/react-aria/Wizard.mdx @@ -4,7 +4,6 @@ export default Layout; import docs from 'docs:react-aria-components'; import '../../tailwind/tailwind.css'; import {InlineAlert, Heading, Content} from '@react-spectrum/s2'; -import {FunctionAPI} from '../../src/FunctionAPI'; export const tags = ['stepper', 'steps', 'multi-step', 'form', 'flow']; export const version = 'alpha'; @@ -95,7 +94,7 @@ let steps = [ ## 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 `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"; diff --git a/packages/react-aria-components/exports/Wizard.ts b/packages/react-aria-components/exports/Wizard.ts index 34fc6b7b711..7cca9ffa450 100644 --- a/packages/react-aria-components/exports/Wizard.ts +++ b/packages/react-aria-components/exports/Wizard.ts @@ -19,6 +19,7 @@ export type { WizardProps, WizardStepListProps, WizardStepProps, + WizardStepRenderProps, WizardPanelsProps, WizardPanelProps, WizardStepAria, diff --git a/packages/react-aria-components/exports/index.ts b/packages/react-aria-components/exports/index.ts index e3105dd0f90..7865ade031e 100644 --- a/packages/react-aria-components/exports/index.ts +++ b/packages/react-aria-components/exports/index.ts @@ -571,6 +571,7 @@ export type { WizardProps, WizardStepListProps, WizardStepProps, + WizardStepRenderProps, WizardPanelsProps, WizardPanelProps, WizardStepAria, diff --git a/packages/react-aria-components/src/Wizard.tsx b/packages/react-aria-components/src/Wizard.tsx index 5ee7b980067..04cea4d6eb6 100644 --- a/packages/react-aria-components/src/Wizard.tsx +++ b/packages/react-aria-components/src/Wizard.tsx @@ -9,12 +9,13 @@ * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ -import {ClassNameOrFunction} from './utils'; +import {ClassNameOrFunction, PossibleLinkDOMRenderProps, RenderProps} from './utils'; import {CollectionBuilder} from 'react-aria/CollectionBuilder'; -import {forwardRefType} from '@react-types/shared'; +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, @@ -28,7 +29,6 @@ import { TabList, TabListProps, TabListRenderProps, - TabListStateContext, TabPanel, TabPanelProps, TabPanelRenderProps, @@ -42,6 +42,7 @@ import { } 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 { @@ -112,9 +113,13 @@ interface WizardInnerProps { tabsRef: ForwardedRef; } -export interface WizardStateOptions { - /** Ordered list of step keys, in collection order. */ - keys: Key[]; +// 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). */ @@ -136,7 +141,9 @@ export interface WizardStateOptions { disabledKeys?: Iterable; } -export interface WizardState { +export interface WizardState { + /** The collection of steps. */ + collection: ICollection>; /** The current (selected) step. */ selectedKey: Key | null; /** Sets the current (selected) step. */ @@ -161,19 +168,23 @@ export interface WizardState { * the same event as `onSelectionChange`, so a controlled last completed step can be updated along * with the selection. */ -export function useWizardState(options: WizardStateOptions): WizardState { +export function useWizardState(props: WizardStateOptions): WizardState { let { - keys, + collection, allowsRandomAccess = false, disabledKeys: disabledStepKeys, onSelectionChange, onLastCompletedStepChange - } = options; + } = props; + + // TODO: revist + // Don't have access to the keyboard delegate here, so just rely on the collection order. + let keys = useMemo(() => [...collection].map(item => item.key), [collection]); let firstKey = keys.length > 0 ? keys[0] : null; let [selectedKeyState, setSelectedKeyState] = useControlledState( - options.selectedKey, - options.defaultSelectedKey ?? null, + props.selectedKey, + props.defaultSelectedKey ?? null, onSelectionChange ? key => { if (key != null) { @@ -186,12 +197,12 @@ export function useWizardState(options: WizardStateOptions): WizardState { let selectedKey = selectedKeyState ?? firstKey; let selectedIndex = selectedKey != null ? keys.indexOf(selectedKey) : -1; - let isLastCompletedStepControlled = options.lastCompletedStep !== undefined; + let isLastCompletedStepControlled = props.lastCompletedStep !== undefined; let [lastCompletedStepState, setLastCompletedStepState] = useState( - options.defaultLastCompletedStep ?? null + props.defaultLastCompletedStep ?? null ); let lastCompletedStep = isLastCompletedStepControlled - ? (options.lastCompletedStep ?? null) + ? (props.lastCompletedStep ?? null) : lastCompletedStepState; let lastCompletedIndex = lastCompletedStep != null ? keys.indexOf(lastCompletedStep) : -1; @@ -230,6 +241,7 @@ export function useWizardState(options: WizardStateOptions): WizardState { }, [keys, selectedKey, lastCompletedIndex, allowsRandomAccess, disabledStepKeys]); return { + collection, selectedKey, setSelectedKey, lastCompletedStep, @@ -252,12 +264,8 @@ function WizardInner({props, collection, tabsRef: ref}: WizardInnerProps) { ...tabsProps } = props; - // TODO: revist - // Don't have access to the keyboard delegate here, so just rely on the collection order. - let keys = useMemo(() => [...collection].map(item => item.key), [collection]); - let state = useWizardState({ - keys, + collection, selectedKey, defaultSelectedKey, onSelectionChange, @@ -271,16 +279,18 @@ function WizardInner({props, collection, tabsRef: ref}: WizardInnerProps) { // 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} - + + + {children} + + ); } @@ -310,14 +320,35 @@ export const WizardStepList = /*#__PURE__*/ (forwardRef as forwardRefType)(funct ); }); -export interface WizardStepProps extends TabProps { +export interface WizardStepRenderProps extends TabRenderProps { + /** + * Whether the step is the current step. + * + * @selector [data-current] + */ + isCurrent: boolean; + /** + * Whether the step is rendered before the current 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; + className?: ClassNameOrFunction; } export interface WizardStepAria { @@ -325,56 +356,35 @@ export interface WizardStepAria { isCurrent: boolean; /** Whether this step has been completed (precedes the current step). */ isCompleted: boolean; + /** The position of the step within the wizard, starting from 1. */ + stepNumber: number; } -/** - * Returns whether the step with the given key is the current step of the enclosing `Wizard`, and - * whether it has already been completed (it is rendered before the current step). - */ -export function useWizardStep(key: Key | undefined): WizardStepAria { - let state = useContext(TabListStateContext); - - if (state == null || key == null || state.selectedKey == null) { - return {isCurrent: false, isCompleted: false}; - } - - let isCurrent = state.selectedKey === key; - - // Walk backwards from the current step. If we reach this step, it precedes the current - // step and is therefore completed. - // Should be ok for performance, wizards are generally short. - let isCompleted = false; - let cursor = state.collection.getKeyBefore(state.selectedKey); - while (cursor != null) { - if (cursor === key) { - isCompleted = true; - break; - } - cursor = state.collection.getKeyBefore(cursor); - } - - return {isCurrent, isCompleted}; +interface AriaWizardStepProps { + /** The key of the step. */ + key: Key; } -function WizardStepState({stepKey, children}: {stepKey: Key | undefined; children: ReactNode}) { - let {isCurrent, isCompleted} = useWizardStep(stepKey); - let stringFormatter = useLocalizedStringFormatter(intlMessages, 'react-aria-components'); - - let stateText = isCurrent - ? stringFormatter.format('stepListItemCurrent') - : isCompleted - ? stringFormatter.format('stepListItemCompleted') - : stringFormatter.format('stepListItemNotCompleted'); +/** + * Provides the state of a step within a wizard: whether it is the current step, whether it has + * already been completed (it is rendered before the current 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} = state; + let index = collection.getItem(key)?.index ?? -1; + let selectedIndex = selectedKey != null ? (collection.getItem(selectedKey)?.index ?? -1) : -1; - return ( - - {!isCurrent && {stateText}} - {children} - - ); + return { + isCurrent: index >= 0 && index === selectedIndex, + isCompleted: index >= 0 && index < selectedIndex, + stepNumber: index + 1 + }; } /** @@ -384,21 +394,61 @@ export const WizardStep = /*#__PURE__*/ forwardRef(function WizardStep( props: WizardStepProps, ref: ForwardedRef ) { - let {children, className, ...otherProps} = props; + 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 ( + className={withDefaultClassName( + 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="step" + data-current={isCurrent || undefined} + data-completed={isCompleted || undefined}> {renderProps => ( - - {typeof children === 'function' ? children(renderProps) : children} - + <> + {!isCurrent && {stateText}} + {typeof children === 'function' ? children(getRenderProps(renderProps)) : children} + )} ); -}) as (props: WizardStepProps & {ref?: ForwardedRef}) => ReactElement; +} export interface WizardPanelsProps extends TabPanelsProps { /** diff --git a/packages/react-aria-components/stories/Wizard.stories.tsx b/packages/react-aria-components/stories/Wizard.stories.tsx index d155a975f65..490f771448c 100644 --- a/packages/react-aria-components/stories/Wizard.stories.tsx +++ b/packages/react-aria-components/stories/Wizard.stories.tsx @@ -12,7 +12,7 @@ import {Meta, StoryObj} from '@storybook/react'; import React, {ReactNode} from 'react'; -import {useWizardStep, Wizard, WizardStep, WizardStepList} from '../src/Wizard'; +import {Wizard, WizardStep, WizardStepList} from '../src/Wizard'; import './Wizard.css'; const steps = [ @@ -47,11 +47,16 @@ function CheckIcon(): ReactNode { // The number and check mark repeat the label and the state that `WizardStep` already announces, // so they are decorative. -function StepMarker({stepId, index}: {stepId: string; index: number}): ReactNode { - let {isCompleted} = useWizardStep(stepId); +function StepMarker({ + isCompleted, + stepNumber +}: { + isCompleted: boolean; + stepNumber: number; +}): ReactNode { return ( ); } @@ -66,15 +71,19 @@ export const WizardExample: WizardStory = { defaultSelectedKey="dns" defaultLastCompletedStep="domain"> - {steps.map((step, index) => ( + {steps.map(step => ( - - - {step.label} - - Step {index + 1} of {steps.length} - - + {({isCompleted, stepNumber}) => ( + <> + + + {step.label} + + Step {stepNumber} of {steps.length} + + + + )} ))} diff --git a/packages/react-aria-components/test/Wizard.test.js b/packages/react-aria-components/test/Wizard.test.js index 227d20b2873..01fc94ea8dc 100644 --- a/packages/react-aria-components/test/Wizard.test.js +++ b/packages/react-aria-components/test/Wizard.test.js @@ -10,19 +10,11 @@ * governing permissions and limitations under the License. */ -import {act, pointerMap, render, renderHook, within} from '@react-spectrum/test-utils-internal'; +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 { - useWizardState, - useWizardStep, - Wizard, - WizardPanel, - WizardPanels, - WizardStep, - WizardStepList -} from '../src/Wizard'; +import {Wizard, WizardPanel, WizardPanels, WizardStep, WizardStepList} from '../src/Wizard'; let steps = [ {id: 'domain', label: 'Domain'}, @@ -225,13 +217,12 @@ describe('Wizard', () => { 'Advanced', 'Not completedReview' ]); - let states = tabs.map(tab => tab.firstElementChild); - expect(states[0]).toHaveAttribute('data-completed'); - expect(states[1]).toHaveAttribute('data-completed'); - expect(states[2]).toHaveAttribute('data-current'); - expect(states[2]).not.toHaveAttribute('data-completed'); - expect(states[3]).not.toHaveAttribute('data-completed'); - expect(states[3]).not.toHaveAttribute('data-current'); + 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, so steps after the selected step are not completed after // navigating back, even though they are still navigable. @@ -242,38 +233,45 @@ describe('Wizard', () => { 'Not completedAdvanced', 'Not completedReview' ]); + expect(tabs[0]).toHaveAttribute('data-current'); + expect(tabs[1]).not.toHaveAttribute('data-completed'); expect(getNavigableSteps(tree)).toEqual(['domain', 'dns', 'advanced']); }); - it('should provide the step state to useWizardStep', async () => { - function StepState({id}) { - let {isCurrent, isCompleted} = useWizardStep(id); - return {isCurrent ? 'current' : isCompleted ? 'completed' : 'upcoming'}; - } - + it('should provide the step state as render props', async () => { let tree = render( {steps.map(step => ( - - + + isCurrent ? 'current' : isCompleted ? 'completed' : 'upcoming' + }> + {({stepNumber}) => `${stepNumber}. ${step.label}`} ))} ); - let getStates = () => - tree.getAllByRole('tab').map(tab => tab.firstElementChild.lastChild.textContent); - expect(getStates()).toEqual(['completed', 'current', 'upcoming', 'upcoming']); - - await user.click(tree.getAllByRole('tab')[0]); - expect(getStates()).toEqual(['current', 'upcoming', 'upcoming', 'upcoming']); - }); + let tabs = tree.getAllByRole('tab'); + expect(tabs.map(tab => tab.className)).toEqual([ + 'completed', + 'current', + 'upcoming', + 'upcoming' + ]); + expect(tabs.map(tab => tab.textContent)).toEqual([ + 'Completed1. Domain', + '2. DNS', + 'Not completed3. Advanced', + 'Not completed4. Review' + ]); - it('should return a default step state from useWizardStep outside of a Wizard', () => { - let {result} = renderHook(() => useWizardStep('domain')); - expect(result.current).toEqual({isCurrent: false, isCompleted: false}); + await user.click(tabs[0]); + expect(tabs.map(tab => tab.className)).toEqual(['current', 'upcoming', 'upcoming', 'upcoming']); }); it('should support render props on steps', () => { @@ -378,13 +376,29 @@ describe('Wizard', () => { 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(); }); @@ -582,90 +596,3 @@ describe('Wizard', () => { }); }); }); - -describe('useWizardState', () => { - it('should select the first step and complete no steps by default', () => { - let {result} = renderHook(() => useWizardState({keys})); - expect(result.current.selectedKey).toBe('domain'); - expect(result.current.lastCompletedStep).toBeNull(); - expect(result.current.disabledKeys).toEqual(new Set(['dns', 'advanced', 'review'])); - }); - - it('should support defaultLastCompletedStep', () => { - let {result} = renderHook(() => useWizardState({keys, defaultLastCompletedStep: 'dns'})); - expect(result.current.selectedKey).toBe('domain'); - expect(result.current.lastCompletedStep).toBe('dns'); - expect(result.current.disabledKeys).toEqual(new Set(['review'])); - }); - - it('should complete the steps before the default selected step', () => { - let onLastCompletedStepChange = jest.fn(); - let renders = []; - let {result} = renderHook(() => { - let state = useWizardState({keys, defaultSelectedKey: 'advanced', onLastCompletedStepChange}); - renders.push(state); - return state; - }); - expect(result.current.selectedKey).toBe('advanced'); - expect(result.current.lastCompletedStep).toBe('dns'); - expect(result.current.disabledKeys).toEqual(new Set(['review'])); - - // The last completed step is derived during render rather than synced in an effect, so it's - // already correct on the first render. Like other default values, it doesn't call the change - // handler. - expect(renders[0].lastCompletedStep).toBe('dns'); - expect(renders[0].disabledKeys).toEqual(new Set(['review'])); - expect(onLastCompletedStepChange).not.toHaveBeenCalled(); - }); - - it('should advance the last completed step with the selection and never roll it back', () => { - let onLastCompletedStepChange = jest.fn(); - let {result} = renderHook(() => useWizardState({keys, onLastCompletedStepChange})); - - act(() => result.current.setSelectedKey('dns')); - expect(result.current.lastCompletedStep).toBe('domain'); - expect(result.current.disabledKeys).toEqual(new Set(['advanced', 'review'])); - expect(onLastCompletedStepChange).toHaveBeenCalledTimes(1); - expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('domain'); - - // Skipping ahead completes every step before the selected step. - act(() => result.current.setSelectedKey('review')); - expect(result.current.lastCompletedStep).toBe('advanced'); - expect(result.current.disabledKeys).toEqual(new Set()); - expect(onLastCompletedStepChange).toHaveBeenCalledTimes(2); - expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('advanced'); - - act(() => result.current.setSelectedKey('domain')); - expect(result.current.selectedKey).toBe('domain'); - expect(result.current.lastCompletedStep).toBe('advanced'); - expect(result.current.disabledKeys).toEqual(new Set()); - expect(onLastCompletedStepChange).toHaveBeenCalledTimes(2); - }); - - it('should support a controlled lastCompletedStep', () => { - let onLastCompletedStepChange = jest.fn(); - let {result, rerender} = renderHook( - ({lastCompletedStep}) => useWizardState({keys, lastCompletedStep, onLastCompletedStepChange}), - {initialProps: {lastCompletedStep: 'advanced'}} - ); - expect(result.current.lastCompletedStep).toBe('advanced'); - expect(result.current.disabledKeys).toEqual(new Set()); - - rerender({lastCompletedStep: 'domain'}); - expect(result.current.lastCompletedStep).toBe('domain'); - expect(result.current.disabledKeys).toEqual(new Set(['advanced', 'review'])); - - act(() => result.current.setSelectedKey('advanced')); - expect(onLastCompletedStepChange).toHaveBeenCalledTimes(1); - expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('dns'); - expect(result.current.lastCompletedStep).toBe('domain'); - expect(result.current.disabledKeys).toEqual(new Set(['review'])); - }); - - it('should always disable steps in disabledKeys', () => { - let {result} = renderHook(() => - useWizardState({keys, allowsRandomAccess: true, disabledKeys: ['dns']}) - ); - expect(result.current.disabledKeys).toEqual(new Set(['dns'])); - }); -}); diff --git a/starters/docs/src/Wizard.css b/starters/docs/src/Wizard.css index 4c688f91f02..229b1e33917 100644 --- a/starters/docs/src/Wizard.css +++ b/starters/docs/src/Wizard.css @@ -41,7 +41,7 @@ } &[data-selected] .marker, - .marker[data-completed] { + &[data-completed] .marker { background: var(--highlight-background); border-color: var(--highlight-background); color: var(--highlight-foreground); @@ -90,8 +90,8 @@ } &[data-selected]::before, - &:has(.marker[data-completed])::before, - &:has(.marker[data-completed])::after { + &[data-completed]::before, + &[data-completed]::after { border-color: var(--highlight-background); } } diff --git a/starters/docs/src/Wizard.tsx b/starters/docs/src/Wizard.tsx index d5c3ad7532b..2f37d4e2138 100644 --- a/starters/docs/src/Wizard.tsx +++ b/starters/docs/src/Wizard.tsx @@ -1,7 +1,5 @@ 'use client'; import { - type Key, - useWizardStep, Wizard as RACWizard, WizardPanel as RACWizardPanel, type WizardPanelProps, @@ -31,9 +29,12 @@ export function WizardStepList(props: WizardStepListProps) export function WizardStep(props: WizardStepProps) { return ( - {composeRenderProps(props.children, children => ( + {composeRenderProps(props.children, (children, {isCompleted, stepNumber}) => ( <> - + {/* The step already announces whether it is completed, so the marker is hidden. */} + + {isCompleted ? : stepNumber} + {children} ))} @@ -41,19 +42,6 @@ export function WizardStep(props: WizardStepProps) { ); } -// The step already announces its label and whether it is completed, so the marker is hidden -// from assistive technology. -function StepMarker({id}: {id?: Key}) { - let state = useContext(TabListStateContext); - let {isCompleted} = useWizardStep(id); - let node = id != null ? state?.collection.getItem(id) : null; - return ( - - {isCompleted ? : (node?.index ?? 0) + 1} - - ); -} - export function WizardPanels(props: WizardPanelsProps) { return ; } diff --git a/starters/tailwind/src/Wizard.tsx b/starters/tailwind/src/Wizard.tsx index 93e1ec9fa54..68518ca8d77 100644 --- a/starters/tailwind/src/Wizard.tsx +++ b/starters/tailwind/src/Wizard.tsx @@ -4,8 +4,6 @@ import React, {useContext} from 'react'; import {composeRenderProps} from 'react-aria-components/composeRenderProps'; import {TabListStateContext} from 'react-aria-components/Tabs'; import { - type Key, - useWizardStep, Wizard as AriaWizard, WizardPanel as AriaWizardPanel, type WizardPanelProps, @@ -42,25 +40,6 @@ export function WizardStepList(props: WizardStepListProps) ); } -export function WizardStep(props: WizardStepProps) { - return ( - - {composeRenderProps(props.children, (children, {isSelected, isFocusVisible}) => ( - <> - - {children} - - ))} - - ); -} - const markerStyles = tv({ extend: focusRing, base: 'flex items-center justify-center size-6 shrink-0 rounded-full border text-xs', @@ -73,25 +52,30 @@ const markerStyles = tv({ } }); -interface StepMarkerProps { - id?: Key; - isSelected: boolean; - isFocusVisible: boolean; -} - -// The step already announces its label and whether it is completed, so the marker is hidden -// from assistive technology. -function StepMarker({id, isSelected, isFocusVisible}: StepMarkerProps) { - let state = useContext(TabListStateContext); - let {isCompleted} = useWizardStep(id); - let node = id != null ? state?.collection.getItem(id) : null; +export function WizardStep(props: WizardStepProps) { return ( - - {isCompleted ? : (node?.index ?? 0) + 1} - + + {composeRenderProps( + props.children, + (children, {isSelected, isCompleted, isFocusVisible, stepNumber}) => ( + <> + {/* The step already announces whether it is completed, so the marker is hidden. */} + + {isCompleted ? : stepNumber} + + {children} + + ) + )} + ); } From dc4be23fbd72b2a1b344430492b6f70c0627cf82 Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Mon, 16 Nov 2026 13:52:16 +1100 Subject: [PATCH 13/15] review comments --- .../dev/s2-docs/pages/react-aria/StepList.mdx | 2 +- packages/react-aria-components/src/Tabs.tsx | 5 +- packages/react-aria-components/src/Wizard.tsx | 16 ++-- .../react-aria-components/test/Wizard.test.js | 92 +++++++++++++++++-- 4 files changed, 96 insertions(+), 19 deletions(-) diff --git a/packages/dev/s2-docs/pages/react-aria/StepList.mdx b/packages/dev/s2-docs/pages/react-aria/StepList.mdx index 68b444c2bb3..5f7312d41d3 100644 --- a/packages/dev/s2-docs/pages/react-aria/StepList.mdx +++ b/packages/dev/s2-docs/pages/react-aria/StepList.mdx @@ -146,7 +146,7 @@ function Example() { ## StepList vs. Wizard -Use a `StepList` to show the user's progress through a process where each step is a separate page or route. +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 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 index 04cea4d6eb6..865a1b1a563 100644 --- a/packages/react-aria-components/src/Wizard.tsx +++ b/packages/react-aria-components/src/Wizard.tsx @@ -180,7 +180,7 @@ export function useWizardState(props: WizardStateOptions): WizardState // TODO: revist // Don't have access to the keyboard delegate here, so just rely on the collection order. let keys = useMemo(() => [...collection].map(item => item.key), [collection]); - let firstKey = keys.length > 0 ? keys[0] : null; + let firstKey = collection.getFirstKey() ?? null; let [selectedKeyState, setSelectedKeyState] = useControlledState( props.selectedKey, @@ -328,7 +328,7 @@ export interface WizardStepRenderProps extends TabRenderProps { */ isCurrent: boolean; /** - * Whether the step is rendered before the current step. + * Whether the step is at or before the last completed step. * * @selector [data-completed] */ @@ -354,7 +354,7 @@ export interface WizardStepProps export interface WizardStepAria { /** Whether this step is the current (selected) step. */ isCurrent: boolean; - /** Whether this step has been completed (precedes the current step). */ + /** 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; @@ -367,7 +367,7 @@ interface AriaWizardStepProps { /** * Provides the state of a step within a wizard: whether it is the current step, whether it has - * already been completed (it is rendered before the current step), and its position. + * already been completed (it is at or before the last completed step), and its position. */ export function useWizardStep( props: AriaWizardStepProps, @@ -376,13 +376,15 @@ export function useWizardStep( ref: RefObject ): WizardStepAria { let {key} = props; - let {collection, selectedKey} = state; + let {collection, selectedKey, lastCompletedStep} = state; let index = collection.getItem(key)?.index ?? -1; let selectedIndex = selectedKey != null ? (collection.getItem(selectedKey)?.index ?? -1) : -1; + let lastCompletedIndex = + lastCompletedStep != null ? (collection.getItem(lastCompletedStep)?.index ?? -1) : -1; return { isCurrent: index >= 0 && index === selectedIndex, - isCompleted: index >= 0 && index < selectedIndex, + isCompleted: index >= 0 && index <= lastCompletedIndex, stepNumber: index + 1 }; } @@ -437,7 +439,7 @@ function WizardStepInner({props, state, stepRef}: WizardStepInnerProps) { )} style={typeof style === 'function' ? values => style(getRenderProps(values)) : style} render={render ? (domProps, values) => render(domProps, getRenderProps(values)) : undefined} - aria-current="step" + aria-current={isCurrent ? 'step' : undefined} data-current={isCurrent || undefined} data-completed={isCompleted || undefined}> {renderProps => ( diff --git a/packages/react-aria-components/test/Wizard.test.js b/packages/react-aria-components/test/Wizard.test.js index 01fc94ea8dc..9b8631eda35 100644 --- a/packages/react-aria-components/test/Wizard.test.js +++ b/packages/react-aria-components/test/Wizard.test.js @@ -178,6 +178,21 @@ describe('Wizard', () => { 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( @@ -207,7 +222,7 @@ describe('Wizard', () => { expect(getSelectedStep(tree)).toBe('advanced'); }); - it('should mark the steps before the selected step as completed', async () => { + 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'); @@ -224,23 +239,24 @@ describe('Wizard', () => { expect(tabs[3]).not.toHaveAttribute('data-completed'); expect(tabs[3]).not.toHaveAttribute('data-current'); - // Completion follows the selection, so steps after the selected step are not completed after - // navigating back, even though they are still navigable. + // 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', - 'Not completedDNS', + 'CompletedDNS', 'Not completedAdvanced', 'Not completedReview' ]); expect(tabs[0]).toHaveAttribute('data-current'); - expect(tabs[1]).not.toHaveAttribute('data-completed'); + 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 => ( { let tabs = tree.getAllByRole('tab'); expect(tabs.map(tab => tab.className)).toEqual([ + 'completed', 'completed', 'current', - 'upcoming', 'upcoming' ]); expect(tabs.map(tab => tab.textContent)).toEqual([ 'Completed1. Domain', - '2. DNS', - 'Not completed3. Advanced', + 'Completed2. DNS', + '3. Advanced', 'Not completed4. Review' ]); await user.click(tabs[0]); - expect(tabs.map(tab => tab.className)).toEqual(['current', 'upcoming', 'upcoming', 'upcoming']); + expect(tabs.map(tab => tab.className)).toEqual([ + 'current', + 'completed', + 'upcoming', + 'upcoming' + ]); }); it('should support render props on steps', () => { @@ -353,6 +374,13 @@ describe('Wizard', () => { ); 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]); @@ -474,6 +502,13 @@ describe('Wizard', () => { /> ); 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( @@ -483,9 +518,46 @@ describe('Wizard', () => { /> ); 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( From c239fe0e91ae2ce283a25bc19b0638e613008e6b Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Mon, 16 Nov 2026 15:46:41 +1100 Subject: [PATCH 14/15] add tests, remove collection to array --- packages/react-aria-components/src/Wizard.tsx | 62 +++++++++++-------- .../react-aria-components/test/Wizard.test.js | 27 +++++--- 2 files changed, 53 insertions(+), 36 deletions(-) diff --git a/packages/react-aria-components/src/Wizard.tsx b/packages/react-aria-components/src/Wizard.tsx index 865a1b1a563..4c624b1c9e1 100644 --- a/packages/react-aria-components/src/Wizard.tsx +++ b/packages/react-aria-components/src/Wizard.tsx @@ -177,11 +177,6 @@ export function useWizardState(props: WizardStateOptions): WizardState onLastCompletedStepChange } = props; - // TODO: revist - // Don't have access to the keyboard delegate here, so just rely on the collection order. - let keys = useMemo(() => [...collection].map(item => item.key), [collection]); - let firstKey = collection.getFirstKey() ?? null; - let [selectedKeyState, setSelectedKeyState] = useControlledState( props.selectedKey, props.defaultSelectedKey ?? null, @@ -194,8 +189,7 @@ export function useWizardState(props: WizardStateOptions): WizardState : undefined ); - let selectedKey = selectedKeyState ?? firstKey; - let selectedIndex = selectedKey != null ? keys.indexOf(selectedKey) : -1; + let selectedKey = selectedKeyState ?? collection.getFirstKey(); let isLastCompletedStepControlled = props.lastCompletedStep !== undefined; let [lastCompletedStepState, setLastCompletedStepState] = useState( @@ -204,14 +198,18 @@ export function useWizardState(props: WizardStateOptions): WizardState let lastCompletedStep = isLastCompletedStepControlled ? (props.lastCompletedStep ?? null) : lastCompletedStepState; - let lastCompletedIndex = lastCompletedStep != null ? keys.indexOf(lastCompletedStep) : -1; + 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 && selectedIndex - 1 > lastCompletedIndex) { - lastCompletedIndex = selectedIndex - 1; - lastCompletedStep = keys[lastCompletedIndex]; + if (!isLastCompletedStepControlled && stepBeforeSelectedIndex > lastCompletedIndex) { + lastCompletedIndex = stepBeforeSelectedIndex; + lastCompletedStep = stepBeforeSelected; setLastCompletedStepState(lastCompletedStep); } @@ -219,26 +217,32 @@ export function useWizardState(props: WizardStateOptions): WizardState // updated along with the selection. let setSelectedKey = (key: Key) => { setSelectedKeyState(key); - let index = keys.indexOf(key); - if (index - 1 > lastCompletedIndex) { - onLastCompletedStepChange?.(keys[index - 1]); + 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); - keys.forEach((key, i) => { - if (key === selectedKey) { - return; - } - // Completed steps and the current step are navigable; upcoming steps are only if allowsRandomAccess. - if (!allowsRandomAccess && i > lastCompletedIndex + 1) { - set.add(key); + 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; - }, [keys, selectedKey, lastCompletedIndex, allowsRandomAccess, disabledStepKeys]); + }, [collection, selectedKey, lastCompletedStep, allowsRandomAccess, disabledStepKeys]); return { collection, @@ -249,6 +253,11 @@ export function useWizardState(props: WizardStateOptions): WizardState }; } +// 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, @@ -377,10 +386,9 @@ export function useWizardStep( ): WizardStepAria { let {key} = props; let {collection, selectedKey, lastCompletedStep} = state; - let index = collection.getItem(key)?.index ?? -1; - let selectedIndex = selectedKey != null ? (collection.getItem(selectedKey)?.index ?? -1) : -1; - let lastCompletedIndex = - lastCompletedStep != null ? (collection.getItem(lastCompletedStep)?.index ?? -1) : -1; + let index = getStepIndex(collection, key); + let selectedIndex = getStepIndex(collection, selectedKey); + let lastCompletedIndex = getStepIndex(collection, lastCompletedStep); return { isCurrent: index >= 0 && index === selectedIndex, diff --git a/packages/react-aria-components/test/Wizard.test.js b/packages/react-aria-components/test/Wizard.test.js index 9b8631eda35..abe554c2425 100644 --- a/packages/react-aria-components/test/Wizard.test.js +++ b/packages/react-aria-components/test/Wizard.test.js @@ -29,7 +29,7 @@ function WizardExample({stepProps, children, ...props}) { {steps.map(step => ( - + {step.label} ))} @@ -143,7 +143,7 @@ describe('Wizard', () => { let tree = render( `${defaultClassName} wizard`} - stepProps={{className: ({defaultClassName}) => `${defaultClassName} step`}} + stepProps={() => ({className: ({defaultClassName}) => `${defaultClassName} step`})} /> ); let stepList = tree.getByRole('tablist'); @@ -264,7 +264,9 @@ describe('Wizard', () => { id={step.id} className={({isCurrent, isCompleted}) => isCurrent ? 'current' : isCompleted ? 'completed' : 'upcoming' - }> + } + style={({isCurrent}) => ({fontWeight: isCurrent ? 'bold' : 'normal'})} + render={(domProps, {stepNumber}) =>
    }> {({stepNumber}) => `${stepNumber}. ${step.label}`} ))} @@ -285,6 +287,8 @@ describe('Wizard', () => { '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([ @@ -347,11 +351,15 @@ describe('Wizard', () => { }); describe('lastCompletedStep', () => { - it('should only allow navigating to the first step when no steps are completed', async () => { + 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( @@ -653,14 +661,15 @@ describe('Wizard', () => { expect(onLastCompletedStepChange).toHaveBeenLastCalledWith('advanced'); }); - it('should never allow navigating to steps in disabledKeys', async () => { - let tree = render( - - ); + 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(); + tree = render(); expect(getNavigableSteps(tree)).toEqual(['domain', 'advanced', 'review']); await user.click(tree.getAllByRole('tab')[1]); From 4a5e78a0e3f385a02c25b81ef8c51af6d3786bbb Mon Sep 17 00:00:00 2001 From: Rob Snow Date: Tue, 17 Nov 2026 07:41:56 +1100 Subject: [PATCH 15/15] fix labelling --- .../react-aria-components/src/StepList.tsx | 6 ++++- .../test/StepList.test.js | 25 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/react-aria-components/src/StepList.tsx b/packages/react-aria-components/src/StepList.tsx index f0673768eea..b2c7c51d718 100644 --- a/packages/react-aria-components/src/StepList.tsx +++ b/packages/react-aria-components/src/StepList.tsx @@ -257,6 +257,10 @@ function StepListItemContentInner({props, contentRef: ref}: StepListItemContentI 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/test/StepList.test.js b/packages/react-aria-components/test/StepList.test.js index 88593612885..e610eb6fe60 100644 --- a/packages/react-aria-components/test/StepList.test.js +++ b/packages/react-aria-components/test/StepList.test.js @@ -265,6 +265,31 @@ describe('StepList', () => { 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(