Skip to content
Merged
12 changes: 2 additions & 10 deletions packages/ui/src/stepper/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,14 @@ export const StepperRoot = forwardRef< StepperRef, StepperRootProps >( function
},
} ) );

// Dev warnings: missing accessibility label, duplicate values, missing step
// Dev warnings: missing accessibility label, missing step.
// Duplicate step values are detected at registration time in useStepRegistration.
useEffect( () => {
if ( ! ariaLabel && ! ariaLabelledBy ) {
warning(
"[Stepper] Stepper requires either 'aria-label' or 'aria-labelledby' for accessibility."
);
}
const seenValues = new Set< string >();
for ( const s of steps ) {
if ( seenValues.has( s.value ) ) {
warning(
`[Stepper] Two steps share value '${ s.value }'. Each step must have a unique value.`
);
}
seenValues.add( s.value );
}
if ( value && steps.length > 0 && ! steps.some( ( s ) => s.value === value ) ) {
warning(
`[Stepper] No step found with value '${ value }'. Check that the value matches one of the registered step values.`
Expand Down
95 changes: 89 additions & 6 deletions packages/ui/src/stepper/test/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -592,12 +592,95 @@ describe( 'Stepper dev warnings', () => {
spy.mockRestore();
} );

// NOTE: A test for the duplicate-value warning ("Two steps share value '...'") is
// deliberately omitted. useStepRegistration prevents duplicate entries at registration
// time (it bails out if a step with the same value is already in state), so the
// steps array that the useEffect in root.tsx inspects will never contain duplicates.
// The warning is unreachable in a JSDOM environment via normal JSX rendering, making
// any such test a never-fails assertion that proves nothing about real behaviour.
// NOTE: warning() dedupes messages process-wide, so these tests use step values
// unique to this file to make sure the expected message has not fired elsewhere.
it( 'warns when two steps share the same value', async () => {
const spy = jest.spyOn( console, 'warn' ).mockImplementation( () => {} );
render(
<Stepper.Root orientation="vertical" value="dup-warn" aria-label="Test">
<Stepper.Step value="dup-warn">
<Stepper.Indicator />
</Stepper.Step>
<Stepper.Step value="dup-warn">
<Stepper.Indicator />
</Stepper.Step>
</Stepper.Root>
);
await waitFor( () => {
expect( spy ).toHaveBeenCalledWith(
expect.stringContaining( "Two steps share value 'dup-warn'" )
);
} );
spy.mockRestore();
} );

it( 'keeps the original step registered when a duplicate step unmounts', async () => {
const spy = jest.spyOn( console, 'warn' ).mockImplementation( () => {} );
function Dynamic() {
const [ showDuplicate, setShowDuplicate ] = useState( true );
return (
Comment thread
bogiii marked this conversation as resolved.
Resolved
<>
<button onClick={ () => setShowDuplicate( false ) }>Remove duplicate</button>
<Stepper.Root orientation="vertical" value="dup-unmount" aria-label="Test">
<Stepper.Step value="dup-unmount">
<Stepper.Indicator />
</Stepper.Step>
{ showDuplicate && (
<Stepper.Step value="dup-unmount">
<Stepper.Indicator />
</Stepper.Step>
) }
<Stepper.Step value="last">
<Stepper.Indicator />
</Stepper.Step>
</Stepper.Root>
</>
);
}
const user = userEvent.setup();
render( <Dynamic /> );
// The duplicate is rejected at registration time, so only two steps count.
await waitFor( () => expect( screen.getByText( 'Step 2 of 2' ) ).toBeInTheDocument() );
await user.click( screen.getByRole( 'button', { name: /remove duplicate/i } ) );
// Unmounting the rejected duplicate must not deregister the original step.
await waitFor( () => expect( screen.getByText( 'Step 2 of 2' ) ).toBeInTheDocument() );
expect( screen.getByText( 'Step 1 of 2' ) ).toBeInTheDocument();
spy.mockRestore();
} );

it( 'keeps the step registered when the original unmounts but a duplicate is still mounted', async () => {
const spy = jest.spyOn( console, 'warn' ).mockImplementation( () => {} );
function Dynamic() {
const [ showOriginal, setShowOriginal ] = useState( true );
return (
<>
<button onClick={ () => setShowOriginal( false ) }>Remove original</button>
<Stepper.Root orientation="vertical" value="dup-orig" aria-label="Test">
{ showOriginal && (
<Stepper.Step value="dup-orig">
<Stepper.Indicator />
</Stepper.Step>
) }
<Stepper.Step value="dup-orig">
<Stepper.Indicator />
</Stepper.Step>
<Stepper.Step value="last">
<Stepper.Indicator />
</Stepper.Step>
</Stepper.Root>
</>
);
}
const user = userEvent.setup();
render( <Dynamic /> );
// The duplicate is rejected at registration time, so only two steps count.
await waitFor( () => expect( screen.getByText( 'Step 2 of 2' ) ).toBeInTheDocument() );
await user.click( screen.getByRole( 'button', { name: /remove original/i } ) );
// The duplicate instance is still mounted, so the value must stay registered.
await waitFor( () => expect( screen.getByText( 'Step 2 of 2' ) ).toBeInTheDocument() );
expect( screen.getByText( 'Step 1 of 2' ) ).toBeInTheDocument();
spy.mockRestore();
} );
} );

describe( 'Stepper.Panel dev warnings', () => {
Expand Down
63 changes: 63 additions & 0 deletions packages/ui/src/stepper/test/use-step-registration.tsx
Comment thread
bogiii marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { renderHook, act } from '@testing-library/react';
import { useStepRegistration } from '../use-step-registration';
import type { StepMeta } from '../types';

describe( 'useStepRegistration updateStep', () => {
function setup() {
const hook = renderHook( () => useStepRegistration< StepMeta >() );
act( () => {
hook.result.current.registerStep( { value: 'a', status: 'completed', disabled: false } );
hook.result.current.registerStep( { value: 'b', disabled: false } );
} );
return hook;
}

it( 'keeps the same steps array reference when meta has not changed', () => {
const { result } = setup();
const before = result.current.steps;
act( () => {
result.current.updateStep( { value: 'a', status: 'completed', disabled: false } );
} );
expect( result.current.steps ).toBe( before );
} );

it( 'updates the entry when a field value changes', () => {
const { result } = setup();
act( () => {
result.current.updateStep( { value: 'a', status: 'error', disabled: false } );
} );
expect( result.current.steps[ 0 ] ).toEqual( {
value: 'a',
status: 'error',
disabled: false,
} );
} );

it( 'updates the entry when a field present in the existing meta is absent from the new meta', () => {
const { result } = setup();
// `status` key intentionally omitted — the compare must not treat a
// removed field as "no change".
act( () => {
result.current.updateStep( { value: 'a', disabled: false } );
} );
expect( result.current.steps[ 0 ] ).toEqual( { value: 'a', disabled: false } );
expect( result.current.steps[ 0 ] ).not.toHaveProperty( 'status' );
} );

it( 'is a no-op for a value that was never registered', () => {
const { result } = setup();
const before = result.current.steps;
act( () => {
result.current.updateStep( { value: 'missing', disabled: false } );
} );
expect( result.current.steps ).toBe( before );
} );

it( 'preserves registration order when updating a step', () => {
const { result } = setup();
act( () => {
result.current.updateStep( { value: 'a', status: 'error', disabled: true } );
} );
expect( result.current.steps.map( ( s ) => s.value ) ).toEqual( [ 'a', 'b' ] );
} );
} );
2 changes: 0 additions & 2 deletions packages/ui/src/stepper/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,4 @@ export type StepperPanelProps = ComponentProps< 'div' > & {
value?: string;
/** Keep panel mounted when inactive (works in both orientations) */
keepMounted?: boolean;
children: ReactNode;
className?: string;
};
47 changes: 33 additions & 14 deletions packages/ui/src/stepper/use-step-registration.ts
Comment thread
ciampo marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useState } from '@wordpress/element';
import { useCallback, useRef, useState } from '@wordpress/element';
import { warning } from '../utils/warning';

// ---------------------------------------------------------------------------
// Helpers
Expand All @@ -14,16 +15,33 @@ import { useCallback, useState } from '@wordpress/element';
export function useStepRegistration< T extends { value: string } >() {
const [ steps, setSteps ] = useState< T[] >( [] );

// Per-value mount count. Only the first registration adds a state entry
// (duplicates get a dev warning), and the entry is removed only when the
// last mounted instance deregisters — so transient duplicates (e.g.
// overlapping conditional renders) never drop a still-mounted step. The
// ref also keeps the duplicate check and warning outside the state
// updater, which must stay pure.
const mountCounts = useRef( new Map< string, number >() );

const registerStep = useCallback( ( meta: T ) => {
setSteps( ( prev ) => {
// Avoid duplicate registration (e.g. from concurrent remounts or late renders)
if ( prev.some( ( s ) => s.value === meta.value ) ) {
return prev;
}
return [ ...prev, meta ];
} );
const counts = mountCounts.current;
const count = counts.get( meta.value ) ?? 0;
counts.set( meta.value, count + 1 );
if ( count > 0 ) {
warning(
`[Stepper] Two steps share value '${ meta.value }'. Each step must have a unique value.`
);
} else {
setSteps( ( prev ) => [ ...prev, meta ] );
}

return () => {
const remaining = ( counts.get( meta.value ) ?? 1 ) - 1;
if ( remaining > 0 ) {
counts.set( meta.value, remaining );
return;
}
counts.delete( meta.value );
setSteps( ( prev ) => prev.filter( ( s ) => s.value !== meta.value ) );
};
}, [] );
Expand All @@ -35,12 +53,13 @@ export function useStepRegistration< T extends { value: string } >() {
return prev;
}
const existing = prev[ idx ];
// Union keys from both objects so fields present in existing but
// absent from meta are not silently ignored.
const keys = [
...new Set( [ ...Object.keys( existing ), ...Object.keys( meta ) ] ),
] as ( keyof T )[];
if ( keys.every( ( k ) => existing[ k ] === meta[ k ] ) ) {
// Plain shallow compare. The key-count check catches fields present
// in existing but absent from meta (e.g. a removed `status`).
const metaKeys = Object.keys( meta ) as ( keyof T )[];
const isUnchanged =
Object.keys( existing ).length === metaKeys.length &&
metaKeys.every( ( k ) => existing[ k ] === meta[ k ] );
if ( isUnchanged ) {
return prev;
}
return prev.map( ( s ) => ( s.value === meta.value ? meta : s ) );
Expand Down
Loading