An open source design system that's fully customizable and agent ready
TypeScript
fix(Stepper): simplify collapse and context APIs (#6097)
Xinzi Zhou3750c4606047
diff --git a/.changeset/stepper-pixel-threshold.md b/.changeset/stepper-pixel-threshold.mdnew file mode 100644index 0000000000..9dbea580d3--- /dev/null+++ b/.changeset/stepper-pixel-threshold.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': minor+---++[breaking] Restrict `Stepper`'s `horizontalOptions.minimumStepWidth` to a pixel number and remove compact-layout implementation fields from `useStepperContext`.++Replace CSS-length thresholds such as `'7rem'` with their intended pixel number. Call `registerStep(index, {getIsDisabled})` instead of passing a disabled boolean; the options object is optional. `StepperContextValue` keeps transition history and step registration, while step count, compact state, summary-portal coordination, and threshold measurement remain package-internal.++@imdreamrunnerdiff --git a/apps/storybook/stories/Stepper.stories.tsx b/apps/storybook/stories/Stepper.stories.tsxindex 524fea4b3a..299018f9bb 100644--- a/apps/storybook/stories/Stepper.stories.tsx+++ b/apps/storybook/stories/Stepper.stories.tsx@@ -1123,7 +1123,7 @@ export const NarrowCollapse: Story = {docs: {description: {story:- "A horizontal stepper measures its own width and collapses once a step has less than `horizontalOptions.minimumStepWidth` (112px by default), so the breakpoint follows the step count rather than the viewport. Pass a number for pixels or a CSS length string such as `7rem`. `horizontalOptions.collapsedVariant` selects `'withLabelAndControls'`, `'withLabel'`, or `'hiddenLabel'`; the last renders only the bare progress track with no compact row. The two indicator positions collapse differently on purpose: `separated` drops its indicators with the labels and repeats the active indicator beside the compact label, while `on-track` keeps its indicators as presentational nodes on the rail and does not repeat the active one beside the label. Controls appear only for `withLabelAndControls` when `onStepClick` is set.",+ "A horizontal stepper measures its own width and collapses once a step has less than `horizontalOptions.minimumStepWidth` pixels (112 by default), so the breakpoint follows the step count rather than the viewport. `horizontalOptions.collapsedVariant` selects `'withLabelAndControls'`, `'withLabel'`, or `'hiddenLabel'`; the last renders only the bare progress track with no compact row. The two indicator positions collapse differently on purpose: `separated` drops its indicators with the labels and repeats the active indicator beside the compact label, while `on-track` keeps its indicators as presentational nodes on the rail and does not repeat the active one beside the label. Controls appear only for `withLabelAndControls` when `onStepClick` is set.",},},},@@ -1151,12 +1151,12 @@ export const NarrowCollapse: Story = {</Stepper></div><div style={{maxWidth: 320}}>- <Text type="label">320px — custom 4rem threshold stays expanded</Text>+ <Text type="label">320px — custom 64px threshold stays expanded</Text><StepperactiveStep={a}onStepClick={setA}horizontalOptions={{- minimumStepWidth: '4rem',+ minimumStepWidth: 64,collapsedVariant: 'withLabelAndControls',}}label="Checkout">diff --git a/packages/core/src/Stepper/Step.tsx b/packages/core/src/Stepper/Step.tsxindex 0772c39c37..f9f093462c 100644--- a/packages/core/src/Stepper/Step.tsx+++ b/packages/core/src/Stepper/Step.tsx@@ -63,7 +63,7 @@ import type {BaseProps} from '../BaseProps';import {Icon} from '../Icon';import {VisuallyHidden} from '../VisuallyHidden';import {useTranslator} from '../i18n';-import {useStepperContext} from './StepperContext';+import {useStepperInternalContext} from './StepperContext';import {stepMarker} from './stepper.stylex';import type {StepStatus} from './StepStatus';@@ -962,18 +962,6 @@ const styles = stylex.create({gap: spacingVars['--spacing-0-5'],minWidth: 0,},- // The browser resolves Stepper's public threshold on this box. It lives in- // the active <li> so CSS custom properties applied to the public <ol> inherit- // into it. Fixed and invisible, it cannot affect layout or scrollable size.- minStepWidthMeasure: {- position: 'fixed',- insetBlockStart: 0,- insetInlineStart: 0,- height: 0,- overflow: 'hidden',- pointerEvents: 'none',- visibility: 'hidden',- },});/**@@ -1017,7 +1005,7 @@ export function Step({...rest}: StepProps) {const t = useTranslator();- const ctx = useStepperContext();+ const ctx = useStepperInternalContext();const {activeStep,previousActiveStep,@@ -1028,20 +1016,19 @@ export function Step({registerStep,isCompact,summarySlot,- minimumStepWidth,- minStepWidthMeasureRef,} = ctx;- // Register this step index with the parent Stepper, which uses the tally- // both to warn about duplicate indices and to work out how much width each- // step is getting.+ // Register this step index with the parent Stepper, which uses the tally to+ // warn about duplicate indices and work out how much width each step gets.+ // The optional getter keeps disabled state owned by this Step while compact+ // navigation can read its latest registration.//// A layout effect, not an effect: the width each step has is the stepper's// width divided by this count, so a stepper narrow enough to collapse can// only know it once every step is counted. Running after paint would show// the full stepper for a frame and then snap it shut.useLayoutEffect(- () => registerStep(step, isDisabled),+ () => registerStep(step, {getIsDisabled: () => isDisabled}),[registerStep, step, isDisabled],);@@ -1427,23 +1414,6 @@ export function Step({</>) : null;- // Keep the CSS-length probe on the first logical step rather than the active- // one. `activeStep === stepCount` is the supported all-complete state, where- // no step is active, but the Stepper still needs to resolve a custom compact- // threshold. Step indices are zero-based, so step 0 is a stable single host- // whose position inside the public list also preserves CSS-variable- // inheritance from that root.- const minStepWidthMeasureNode =- !isVertical && step === 0 ? (- <div- ref={minStepWidthMeasureRef}- aria-hidden="true"- {...mergeProps(stylex.props(styles.minStepWidthMeasure), {- style: {width: minimumStepWidth},- })}- />- ) : null;-// ======= ON-TRACK: indicator is a node on the connector =======if (indicatorPosition === 'on-track') {// Connector fill is purely progress-based (matches the separated bar):@@ -1742,7 +1712,6 @@ export function Step({{compactNameNode}{otContentNode}{summaryNode}- {minStepWidthMeasureNode}</li>);}@@ -1874,7 +1843,6 @@ export function Step({)}{contentNode}{summaryNode}- {minStepWidthMeasureNode}</li>);}diff --git a/packages/core/src/Stepper/Stepper.doc.mjs b/packages/core/src/Stepper/Stepper.doc.mjsindex ed68e655a0..d83147dac5 100644--- a/packages/core/src/Stepper/Stepper.doc.mjs+++ b/packages/core/src/Stepper/Stepper.doc.mjs@@ -196,9 +196,9 @@ export const docs = {},{name: 'horizontalOptions',- type: "{ minimumStepWidth: number | string; collapsedVariant: 'withLabelAndControls' | 'withLabel' | 'hiddenLabel' }",+ type: "{ minimumStepWidth: number; collapsedVariant: 'withLabelAndControls' | 'withLabel' | 'hiddenLabel' }",description:- 'Options for horizontal collapse. minimumStepWidth is the per-step threshold: numbers are pixels and strings accept CSS lengths such as 7rem, calc(6rem + 8px), or var(--step-width). collapsedVariant selects a label with controls, the label alone, or a bare progress track with no compact row. Controls appear only for withLabelAndControls when onStepClick is set, and every step keeps its accessible name.',+ 'Options for horizontal collapse. minimumStepWidth is the per-step threshold in pixels. collapsedVariant selects a label with controls, the label alone, or a bare progress track with no compact row. Controls appear only for withLabelAndControls when onStepClick is set, and every step keeps its accessible name.',default:"{ minimumStepWidth: 112, collapsedVariant: 'withLabelAndControls' }",},@@ -405,9 +405,9 @@ export const docsZh = {},{name: 'horizontalOptions',- type: "{ minimumStepWidth: number | string; collapsedVariant: 'withLabelAndControls' | 'withLabel' | 'hiddenLabel' }",+ type: "{ minimumStepWidth: number; collapsedVariant: 'withLabelAndControls' | 'withLabel' | 'hiddenLabel' }",description:- '水平布局的收起选项。minimumStepWidth 是每个步骤的阈值:数字按像素处理,字符串接受 7rem、calc(6rem + 8px) 或 var(--step-width) 等 CSS 长度。collapsedVariant 可选择显示标签和控件、仅显示标签,或只显示裸进度轨道而不显示紧凑行。仅当 collapsedVariant 为 withLabelAndControls 且设置 onStepClick 时显示控件,每个步骤始终保留无障碍名称。',+ '水平布局的收起选项。minimumStepWidth 是每个步骤的像素阈值。collapsedVariant 可选择显示标签和控件、仅显示标签,或只显示裸进度轨道而不显示紧凑行。仅当 collapsedVariant 为 withLabelAndControls 且设置 onStepClick 时显示控件,每个步骤始终保留无障碍名称。',default:"{ minimumStepWidth: 112, collapsedVariant: 'withLabelAndControls' }",},diff --git a/packages/core/src/Stepper/Stepper.public.test.ts b/packages/core/src/Stepper/Stepper.public.test.tsnew file mode 100644index 0000000000..63c2434058--- /dev/null+++ b/packages/core/src/Stepper/Stepper.public.test.ts@@ -0,0 +1,91 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Stepper.public.test.ts+ * @input Imports the Stepper public barrel and internal context module+ * @output Locks the supported horizontal options and context surfaces+ * @position Compatibility test guarding @astryxdesign/core/Stepper+ *+ * The `expectTypeOf` assertions here are enforced by `pnpm -F+ * @astryxdesign/core typecheck`, not by the test run. A failed negative property+ * assertion surfaces as `TS2554: Expected 2 arguments, but got 1`.+ */++import {describe, expectTypeOf, it} from 'vitest';++import type {+ StepperContextValue,+ StepperProps,+ StepperRegistrationOptions,+ useStepperContext,+} from './index';+import type {StepperInternalContextValue} from './StepperContext';++const privateContextFields = [+ 'stepCount',+ 'isCompact',+ 'summarySlot',+ 'minimumStepWidth',+ 'minStepWidthMeasureRef',+] as const;++describe('Stepper public surface', () => {+ it('accepts only pixel numbers for the minimum step width', () => {+ type HorizontalOptions = NonNullable<StepperProps['horizontalOptions']>;++ expectTypeOf<+ HorizontalOptions['minimumStepWidth']+ >().toEqualTypeOf<number>();+ });++ it('keeps private coordination off the public context', () => {+ for (const field of privateContextFields) {+ expectTypeOf<StepperContextValue>().not.toHaveProperty(field);+ expectTypeOf<ReturnType<typeof useStepperContext>>().not.toHaveProperty(+ field,+ );+ }+ });++ it('preserves the supported public context reads', () => {+ expectTypeOf<+ ReturnType<typeof useStepperContext>+ >().toEqualTypeOf<StepperContextValue>();+ expectTypeOf<StepperContextValue>().toHaveProperty('activeStep');+ expectTypeOf<StepperContextValue>().toHaveProperty('previousActiveStep');+ expectTypeOf<StepperContextValue>().toHaveProperty('orientation');+ expectTypeOf<StepperContextValue>().toHaveProperty('isNonLinear');+ expectTypeOf<StepperContextValue>().toHaveProperty('onStepClick');+ expectTypeOf<StepperContextValue>().toHaveProperty('density');+ expectTypeOf<StepperContextValue>().toHaveProperty('indicatorPosition');+ expectTypeOf<StepperContextValue>().toHaveProperty('registerStep');+ });++ it('keeps the registration options on the public context', () => {+ type RegisterStep = StepperContextValue['registerStep'];++ expectTypeOf<Parameters<RegisterStep>[1]>().toEqualTypeOf<+ StepperRegistrationOptions | undefined+ >();+ expectTypeOf<StepperRegistrationOptions['getIsDisabled']>().toEqualTypeOf<+ (() => boolean) | undefined+ >();+ });++ it('keeps layout coordination on the internal context only', () => {+ expectTypeOf<StepperInternalContextValue>().toMatchTypeOf<StepperContextValue>();+ expectTypeOf<StepperInternalContextValue>().toHaveProperty(+ 'previousActiveStep',+ );+ expectTypeOf<StepperInternalContextValue>().toHaveProperty('registerStep');+ expectTypeOf<StepperInternalContextValue>().toHaveProperty('stepCount');+ expectTypeOf<StepperInternalContextValue>().toHaveProperty('isCompact');+ expectTypeOf<StepperInternalContextValue>().toHaveProperty('summarySlot');+ expectTypeOf<StepperInternalContextValue>().not.toHaveProperty(+ 'minimumStepWidth',+ );+ expectTypeOf<StepperInternalContextValue>().not.toHaveProperty(+ 'minStepWidthMeasureRef',+ );+ });+});diff --git a/packages/core/src/Stepper/Stepper.spec.md b/packages/core/src/Stepper/Stepper.spec.mdindex 4181ae1e54..0408f78673 100644--- a/packages/core/src/Stepper/Stepper.spec.md+++ b/packages/core/src/Stepper/Stepper.spec.md@@ -11,7 +11,11 @@ approved_at: 2026-09-02owners: [cixzhang]review_triggers: [public-api, theming, layout]verified_by:- [packages/core/src/Stepper/Stepper.test.tsx, scripts/check-knowledge.mjs]+ [+ packages/core/src/Stepper/Stepper.test.tsx,+ packages/core/src/Stepper/Stepper.public.test.ts,+ scripts/check-knowledge.mjs,+ ]modules: []families: []design_specs: []@@ -33,16 +37,24 @@ ownership.## Compatibility and migration- Released default preserved: `yes` — `horizontalOptions.minimumStepWidth`- defaults to `112`, and `collapsedVariant` defaults to- `withLabelAndControls`, matching the existing behavior-- Compatibility class: additive relative to the released Stepper API. The- horizontal options proposed in the unlanded stack are consolidated before- release rather than shipping three independent top-level props-- Semantic delta: fixed horizontal behavior → one `horizontalOptions` object- configuring its per-step threshold and compact label/control presentation-- Review classification: additive public API; owner review required for FR14+ still defaults to `112`, and `collapsedVariant` defaults to+ `withLabelAndControls`+- Compatibility class: breaking API narrowing relative to `0.5.3`.+ `minimumStepWidth` now accepts pixel numbers only, `registerStep` replaces its+ disabled boolean with an optional options object, and `StepperContextValue`+ no longer names step count, compact state, the summary portal, or threshold+ measurement details+- Semantic delta: CSS-length collapse thresholds → numeric pixel thresholds;+ disabled snapshots passed to registration → an optional `getIsDisabled`+ callback; the context hook's public return → the same state, registration,+ and transition history without compact-layout implementation fields+- Review classification: owner-approved breaking simplification for FR14 and+ the public context boundary- Controlled/uncontrolled behavior: not applicable-- Migration decision: none+- Migration decision: convert CSS lengths to their intended pixel number,+ replace `registerStep(index, isDisabled)` with+ `registerStep(index, {getIsDisabled})` or omit the options, and stop reading+ the five removed context fieldsConsumer migration instructions belong in consumer docs and release notes.@@ -56,9 +68,8 @@ Consumer migration instructions belong in consumer docs and release notes.background) and the accent fill (an absolutely placed `::before`) — and thesingle clip that holds both off the indicator.- Which pieces an on-track connector is drawn from, and how many.-- Resolution of `horizontalOptions.minimumStepWidth` through browser layout and- the compact state derived from that resolved length, the Stepper width, and- registered steps.+- Reading `horizontalOptions.minimumStepWidth` as a pixel number and deriving+ compact state from that threshold, the Stepper width, and registered steps.- Label and Description paint and the target ownership defined by FR9–FR11.**Does not own / non-goals**@@ -71,33 +82,35 @@ Consumer migration instructions belong in consumer docs and release notes.## Public concepts-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |-| ------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------- | --------- | --------------------------------------------------------------------------------------------------------- |-| `--step-connector-gap` | Any CSS `<length-percentage>` | How far the track stops short of the indicator, on the side facing it | `indicatorPosition="on-track"`, both orientations and both directions, only on steps that render an indicator | `0px` | `component:Stepper` | stable | Clamped, never rejected: values below `0` resolve to `0`, values above `--spacing-2` cap at `--spacing-2` |-| `horizontalOptions.minimumStepWidth` | `number \| string` | Required within `horizontalOptions`; per-step width below which a horizontal Stepper uses its compact presentation; numbers are pixels and strings are CSS lengths resolved by the browser | Horizontal orientation | `112` when `horizontalOptions` is omitted | Caller | stable | Invalid CSS follows platform width parsing; use a valid CSS length or a number |-| `horizontalOptions.collapsedVariant` | `withLabelAndControls \| withLabel \| hiddenLabel` | Required within `horizontalOptions`; whether compact mode shows a label with navigation controls, a label alone, or only the bare progress track | Compact horizontal orientation; controls require `withLabelAndControls` and `onStepClick` | `withLabelAndControls` when `horizontalOptions` is omitted | Caller | stable | TypeScript rejects unknown variants |+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ------------------------------------ | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------- | --------- | --------------------------------------------------------------------------------------------------------- |+| `--step-connector-gap` | Any CSS `<length-percentage>` | How far the track stops short of the indicator, on the side facing it | `indicatorPosition="on-track"`, both orientations and both directions, only on steps that render an indicator | `0px` | `component:Stepper` | stable | Clamped, never rejected: values below `0` resolve to `0`, values above `--spacing-2` cap at `--spacing-2` |+| `horizontalOptions.minimumStepWidth` | `number` | Required within `horizontalOptions`; per-step width in pixels below which a horizontal Stepper uses its compact presentation | Horizontal orientation | `112` when `horizontalOptions` is omitted | Caller | stable | TypeScript rejects non-numeric values; numbers are interpreted as pixels |+| `useStepperContext` return | `StepperContextValue` | Stepper state, transition history, and registration for descendant content; excludes step count, compact state, summary portal, and threshold measurement details | Descendants of `Stepper` | Current provider value | Component | stable | Throws outside `Stepper`; TypeScript and runtime omit unsupported layout-coordination fields |+| `horizontalOptions.collapsedVariant` | `withLabelAndControls \| withLabel \| hiddenLabel` | Required within `horizontalOptions`; whether compact mode shows a label with navigation controls, a label alone, or only the bare progress track | Compact horizontal orientation; controls require `withLabelAndControls` and `onStepClick` | `withLabelAndControls` when `horizontalOptions` is omitted | Caller | stable | TypeScript rejects unknown variants |Consumer syntax and description remain in `Stepper.doc.mjs` `theming.vars`.## Behavioral and layout contract-| ID | Candidate invariant | Basis | Draft review state |-| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ------------------------- |-| FR1 | `--step-connector-gap` falls back to `0px` where each connector consumes it and honors values inherited from an ancestor or supplied through the `stepper` theming target. | Reviewed defect (PR #5495) | Settled |-| FR2 | The gap is applied to the ONE edge each segment faces the indicator from, mirrored per axis, so the pair leaves a hole centred on the node. | Current source and browser probe | Settled |-| FR3 | One declaration covers both connector paint layers. A clip on the segment clips its `::before` with it, against one reference box, so the two cannot disagree. | Current source and browser probe | Settled |-| FR4 | The resolved value is clamped to `max(0px, min(value, --spacing-2))` before use. | Reviewed defect (PR #5495) | Settled |-| FR5 | A step rendering no indicator (`indicator="none"`) applies no clip, leaving its track continuous. | Current source and browser probe | Settled |-| FR6 | No accepted value changes the Stepper's outer size, in either orientation. A clip cannot affect layout. | Current source and browser probe | Settled |-| FR7 | The horizontal clip mirrors under `dir="rtl"`, so the hole stays at the indicator rather than moving to the join between steps. | Reviewed defect (PR #5495) | Settled |-| FR8 | The pieces an on-track connector is drawn from are not public: no `data-segment`, and no bare `lead`/`rail`/`content` class is emitted. | `component:Stepper/DEC-1` | Settled |-| FR9 | In both indicator positions, each rendered Label and Description carries its own target and reflects `progress` and `status`. | Current source, docs, and tests | Settled |-| FR10 | Label alone reflects `disabled`, because only Label owns disabled paint. Description and the other targets do not gain the selector for symmetry. | Current source, docs, and tests | Settled |-| FR11 | Label and Description each declare `font-size`, `line-height`, and `color`. Those declarations outrank values inherited from `step`, so only direct targets can expose that paint to themes. | Current source and Chromium probe | Settled |-| FR12 | A compact horizontal summary sits directly beneath its track without an additional frame gap. | Reviewed narrow-layout feedback | Settled |-| FR13 | In compact `on-track`, indicators remain on the rail and the active indicator is not repeated beside the summary label; compact `separated` retains the active indicator beside its label. | Reviewed narrow-layout feedback | Settled |-| FR14 | `horizontalOptions.minimumStepWidth` accepts pixel numbers and CSS lengths. Its invisible browser-resolved probe remains mounted in every progress state, including all-complete, and recomputes compact state whenever its resolved width changes. | Configurable collapse threshold | Proposed for owner review |-| FR15 | `horizontalOptions.collapsedVariant` keeps horizontal-only configuration together: `withLabelAndControls` shows the label and controls, `withLabel` shows only the label, and `hiddenLabel` renders only the bare progress track with no compact row. | Collapsed presentation consolidation | Proposed for owner review |+| ID | Candidate invariant | Basis | Draft review state |+| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ------------------------- |+| FR1 | `--step-connector-gap` falls back to `0px` where each connector consumes it and honors values inherited from an ancestor or supplied through the `stepper` theming target. | Reviewed defect (PR #5495) | Settled |+| FR2 | The gap is applied to the ONE edge each segment faces the indicator from, mirrored per axis, so the pair leaves a hole centred on the node. | Current source and browser probe | Settled |+| FR3 | One declaration covers both connector paint layers. A clip on the segment clips its `::before` with it, against one reference box, so the two cannot disagree. | Current source and browser probe | Settled |+| FR4 | The resolved value is clamped to `max(0px, min(value, --spacing-2))` before use. | Reviewed defect (PR #5495) | Settled |+| FR5 | A step rendering no indicator (`indicator="none"`) applies no clip, leaving its track continuous. | Current source and browser probe | Settled |+| FR6 | No accepted value changes the Stepper's outer size, in either orientation. A clip cannot affect layout. | Current source and browser probe | Settled |+| FR7 | The horizontal clip mirrors under `dir="rtl"`, so the hole stays at the indicator rather than moving to the join between steps. | Reviewed defect (PR #5495) | Settled |+| FR8 | The pieces an on-track connector is drawn from are not public: no `data-segment`, and no bare `lead`/`rail`/`content` class is emitted. | `component:Stepper/DEC-1` | Settled |+| FR9 | In both indicator positions, each rendered Label and Description carries its own target and reflects `progress` and `status`. | Current source, docs, and tests | Settled |+| FR10 | Label alone reflects `disabled`, because only Label owns disabled paint. Description and the other targets do not gain the selector for symmetry. | Current source, docs, and tests | Settled |+| FR11 | Label and Description each declare `font-size`, `line-height`, and `color`. Those declarations outrank values inherited from `step`, so only direct targets can expose that paint to themes. | Current source and Chromium probe | Settled |+| FR12 | A compact horizontal summary sits directly beneath its track without an additional frame gap. | Reviewed narrow-layout feedback | Settled |+| FR13 | In compact `on-track`, indicators remain on the rail and the active indicator is not repeated beside the summary label; compact `separated` retains the active indicator beside its label. | Reviewed narrow-layout feedback | Settled |+| FR14 | `horizontalOptions.minimumStepWidth` accepts a number interpreted as pixels. Compact state compares the registered per-step width directly with that number; no threshold measurement element or observer is rendered. | Configurable collapse threshold | Settled |+| FR15 | `horizontalOptions.collapsedVariant` keeps horizontal-only configuration together: `withLabelAndControls` shows the label and controls, `withLabel` shows only the label, and `hiddenLabel` renders only the bare progress track with no compact row. | Collapsed presentation consolidation | Proposed for owner review |+| FR16 | `useStepperContext` preserves Stepper state, transition history, and `registerStep`, while omitting `stepCount`, `isCompact`, `summarySlot`, `minimumStepWidth`, and `minStepWidthMeasureRef` from both its TypeScript type and runtime object. `registerStep(index, options?)` accepts an optional `getIsDisabled` callback instead of a disabled boolean, and compact navigation reads that callback again when a control activates so a stale render cannot select a newly disabled step. | Public context boundary | Settled |`status` on Label and Description is a selector seam. It does not claim thatAstryx paints either text part by status.@@ -113,19 +126,19 @@ Astryx paints either text part by status.### Representative states-| State | Required invariant | Allowed variation |-| --------------------------------------------------------------- | ------------------ | ----------------- |-| vertical, on-track, indicator | FR2, FR3, FR6 | AV1, AV2 |-| horizontal, on-track, indicator | FR2, FR3, FR6, FR7 | AV1, AV2 |-| `dir="rtl"`, horizontal | FR7 | AV1 |-| `indicator="none"` | FR5 | — |-| value below `0` or above the cap | FR4, FR6 | — |-| both indicator positions; each progress/status; disabled Label | FR9–FR11 | — |-| compact horizontal summary | FR12 | — |-| compact `on-track` and `separated` indicators | FR13 | — |-| numeric, `rem`, `calc()`, or custom-property collapse threshold | FR14 | — |-| all-complete with a custom collapse threshold | FR14 | — |-| each `collapsedVariant`, with and without `onStepClick` | FR15 | — |+| State | Required invariant | Allowed variation |+| -------------------------------------------------------------- | ------------------ | ----------------- |+| vertical, on-track, indicator | FR2, FR3, FR6 | AV1, AV2 |+| horizontal, on-track, indicator | FR2, FR3, FR6, FR7 | AV1, AV2 |+| `dir="rtl"`, horizontal | FR7 | AV1 |+| `indicator="none"` | FR5 | — |+| value below `0` or above the cap | FR4, FR6 | — |+| both indicator positions; each progress/status; disabled Label | FR9–FR11 | — |+| compact horizontal summary | FR12 | — |+| compact `on-track` and `separated` indicators | FR13 | — |+| custom numeric pixel collapse threshold | FR14 | — |+| public context read versus internal layout coordination | FR16 | — |+| each `collapsedVariant`, with and without `onStepClick` | FR15 | — |### Transformation and precedence order@@ -138,15 +151,14 @@ Astryx paints either text part by status.### Performance and resources-- Horizontal Stepper instances register their list and one invisible threshold- probe with the shared ResizeObserver. The probe lets browser layout resolve CSS- lengths and updates compact state when that resolved value changes.+- Horizontal Stepper instances register their list with the shared+ `ResizeObserver`. Numeric pixel thresholds are compared directly, so no second+ observer or measurement element is required.## Accessibility contract-The threshold probe is empty and `aria-hidden`; it adds no accessible content or-focus stop. Compact layout preserves the ordered-list role and `aria-current`-handling while moving optional navigation to the summary controls.+Compact layout preserves the ordered-list role and `aria-current` handling while+moving optional navigation to the summary controls.## Design relationships@@ -199,21 +211,22 @@ parts. Their own typography and color declarations make `inherits: step` false;## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | -------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------- |-| FR1 | `Stepper.test.tsx` fallback and inheritance assertions | vertical and horizontal on-track | Declaring a default on the list blocks values inherited from its horizontal frame. | `audit:Stepper/theming` |-| FR2, FR3 | `Stepper.test.tsx` clip assertions | vertical and horizontal on-track | Clipping the wrong edge, or per-layer copies of the value, fails the suite. | `audit:Stepper/theming` |-| FR4, FR6 | `Stepper.test.tsx` clamp assertion | values below `0` and above the cap | Removing the floor lets a negative inset through; removing the cap unbounds the hole. | `audit:Stepper/theming` |-| FR5 | `Stepper.test.tsx` no-indicator assertion | `indicator="none"` | Applying the clip unconditionally puts holes in a track with no node in them. | `audit:Stepper/theming` |-| FR7 | `Stepper.test.tsx` RTL assertion | `dir="rtl"`, horizontal | Dropping the mirror moves the hole to the join between steps; caught by the assertion. | `audit:Stepper/theming` |-| FR8 | `Stepper.test.tsx` vocabulary guard | vertical on-track | Re-adding `data-segment` or a bare role class fails the guard. | `audit:Stepper/theming` |-| FR9, FR10 | `Stepper.test.tsx` target and generated-theme assertions | Both indicator positions; progress, status, and disabled | Removing a target or state, or moving it off the painted span, fails focused tests. | `audit:Stepper/theming` |-| FR11 | Exact-head Chromium probe | Themed `step`, Label, and Description | If inheritance reaches the text, the Step target's probe color appears there. | `audit:Stepper/theming` |-| FR12 | `Stepper.test.tsx` compact frame gap assertion | Compact horizontal summary | Restoring frame spacing separates the summary from the track and fails the suite. | `audit:Stepper/layout` |-| FR13 | `Stepper.test.tsx` compact indicator assertions | Compact `separated` and `on-track` | Repeating the on-track active indicator, or dropping the separated one, fails the suite. | `audit:Stepper/layout` |-| FR14 | `Stepper.test.tsx` threshold measurement assertions | Default, pixel number, CSS length, resolved-value change | Parsing a CSS string in JavaScript or observing only the list fails the suite. | `audit:Stepper/layout` |-| FR15 | `Stepper.test.tsx` collapsed-variant assertions | Three variants, with and without navigation | A variant shows an unrequested label/control or changes the accessible sequence. | `audit:Stepper/layout` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and the nine current targets | A target with no anatomy owner, or a stale/extra part, fails repository validation. | `audit:Stepper/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------- |+| FR1 | `Stepper.test.tsx` fallback and inheritance assertions | vertical and horizontal on-track | Declaring a default on the list blocks values inherited from its horizontal frame. | `audit:Stepper/theming` |+| FR2, FR3 | `Stepper.test.tsx` clip assertions | vertical and horizontal on-track | Clipping the wrong edge, or per-layer copies of the value, fails the suite. | `audit:Stepper/theming` |+| FR4, FR6 | `Stepper.test.tsx` clamp assertion | values below `0` and above the cap | Removing the floor lets a negative inset through; removing the cap unbounds the hole. | `audit:Stepper/theming` |+| FR5 | `Stepper.test.tsx` no-indicator assertion | `indicator="none"` | Applying the clip unconditionally puts holes in a track with no node in them. | `audit:Stepper/theming` |+| FR7 | `Stepper.test.tsx` RTL assertion | `dir="rtl"`, horizontal | Dropping the mirror moves the hole to the join between steps; caught by the assertion. | `audit:Stepper/theming` |+| FR8 | `Stepper.test.tsx` vocabulary guard | vertical on-track | Re-adding `data-segment` or a bare role class fails the guard. | `audit:Stepper/theming` |+| FR9, FR10 | `Stepper.test.tsx` target and generated-theme assertions | Both indicator positions; progress, status, and disabled | Removing a target or state, or moving it off the painted span, fails focused tests. | `audit:Stepper/theming` |+| FR11 | Exact-head Chromium probe | Themed `step`, Label, and Description | If inheritance reaches the text, the Step target's probe color appears there. | `audit:Stepper/theming` |+| FR12 | `Stepper.test.tsx` compact frame gap assertion | Compact horizontal summary | Restoring frame spacing separates the summary from the track and fails the suite. | `audit:Stepper/layout` |+| FR13 | `Stepper.test.tsx` compact indicator assertions | Compact `separated` and `on-track` | Repeating the on-track active indicator, or dropping the separated one, fails the suite. | `audit:Stepper/layout` |+| FR14 | `Stepper.test.tsx` threshold assertions | Default and custom pixel number | Reintroducing threshold measurement or CSS-length support fails the runtime/type guards. | `audit:Stepper/layout` |+| FR15 | `Stepper.test.tsx` collapsed-variant assertions | Three variants, with and without navigation | A variant shows an unrequested label/control or changes the accessible sequence. | `audit:Stepper/layout` |+| FR16 | `Stepper.public.test.ts` type assertions and `Stepper.test.tsx` runtime key assertion | Public hook/type and separate public/internal provider values | A named layout-coordination field reaches the public type/runtime object, or transition history/registration disappears. | `audit:Stepper/api` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and the nine current targets | A target with no anatomy owner, or a stale/extra part, fails repository validation. | `audit:Stepper/theming` |## Decision log@@ -278,17 +291,35 @@ content rather than paint alone.`horizontalOptions` keeps these horizontal-only decisions out of the Stepper'stop-level API. `minimumStepWidth` names the per-step space the caller is-guaranteeing. A number is pixels, following other Astryx size props; a string is-a CSS length. The browser resolves strings on an invisible descendant of the-public list, so relative units and inherited custom properties keep their CSS-meaning without a partial JavaScript length parser. `collapsedVariant` is one-closed choice because its values describe the complete compact presentation and-avoid conflicting boolean combinations.+guaranteeing. It is a pixel number, following other Astryx size props, so the+Stepper compares it directly without a browser-resolved probe or a second+observer. `collapsedVariant` is one closed choice because its values describe+the complete compact presentation and avoid conflicting boolean combinations.++### DEC-4 — Public context excludes compact-layout implementation fields++**Reference:** `component:Stepper/DEC-4`+**Decider:** `imdreamrunner`, `2026-09-06`++`useStepperContext` preserves the existing Stepper state and transition history.+Its `registerStep` contract replaces the disabled boolean with an optional+options object whose `getIsDisabled` callback lets compact navigation read the+Step's current state. Separate public and package-internal contexts make the+runtime boundary match the type boundary: the public provider contains exactly+the supported keys, while the internal provider adds `stepCount`, `isCompact`,+and `summarySlot` for the built-in `Step`. `minimumStepWidth` and+`minStepWidthMeasureRef` disappear entirely with the pixel-only threshold+implementation.++Rejected: returning the package-internal provider value from+`useStepperContext()` with only a narrower TypeScript return type. JavaScript+could still read the removed fields, making the runtime API contradict the+public contract.## Open questions-- Owner review of FR14–FR15 and the `horizontalOptions` public API admission- argument.+- Owner review of FR15 and the `horizontalOptions.collapsedVariant` public API+ admission argument.## Content boundarydiff --git a/packages/core/src/Stepper/Stepper.test.tsx b/packages/core/src/Stepper/Stepper.test.tsxindex 8309f50454..9b861c17eb 100644--- a/packages/core/src/Stepper/Stepper.test.tsx+++ b/packages/core/src/Stepper/Stepper.test.tsx@@ -1,11 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {StrictMode, createRef} from 'react';+import {StrictMode, createRef, useLayoutEffect} from 'react';import {describe, it, expect, vi} from 'vitest';import {act, render, screen, within} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Stepper} from './Stepper';import {Step} from './Step';+import {useStepperContext} from './StepperContext';import {defineTheme} from '../theme/defineTheme';import {generateThemeCSS} from '../theme/generateThemeRules';@@ -76,6 +77,38 @@ describe('Stepper', () => {).toBeInTheDocument();});+ it.each(['horizontal', 'vertical'] as const)(+ 'exposes only the supported public context keys at runtime when %s',+ orientation => {+ let contextKeys: string[] = [];++ function ContextProbe() {+ contextKeys = Object.keys(useStepperContext()).sort();+ return null;+ }++ render(+ <Stepper activeStep={0} orientation={orientation}>+ <ContextProbe />+ <Step step={0} label="Step 1" />+ </Stepper>,+ );++ expect(contextKeys).toEqual(+ [+ 'activeStep',+ 'previousActiveStep',+ 'orientation',+ 'isNonLinear',+ 'onStepClick',+ 'density',+ 'indicatorPosition',+ 'registerStep',+ ].sort(),+ );+ },+ );+it('supports vertical orientation', () => {render(<Stepper activeStep={0} orientation="vertical">@@ -1036,11 +1069,7 @@ describe('Stepper', () => {* The value has to be in place before the first render because the shared* resize observer takes its opening measurement synchronously during commit.*/- function atWidth(- width: number,- ui: React.ReactElement,- resolvedMinStepWidth = 112,- ) {+ function atWidth(width: number, ui: React.ReactElement) {const original = Object.getOwnPropertyDescriptor(Element.prototype,'clientWidth',@@ -1051,9 +1080,6 @@ describe('Stepper', () => {if (this.classList.contains('astryx-stepper')) {return width;}- if (this instanceof HTMLElement && this.style.width !== '') {- return resolvedMinStepWidth;- }return this.classList.contains('astryx-stepper-frame') ? 1000 : 0;},});@@ -1179,7 +1205,7 @@ describe('Stepper', () => {expect(document.querySelector('.astryx-stepper-summary')).toBeNull();});- it('treats a numeric minimum step width as pixels', () => {+ it('treats the minimum step width as pixels without a measurement probe', () => {atWidth(360,fourSteps({@@ -1188,138 +1214,14 @@ describe('Stepper', () => {collapsedVariant: 'withLabelAndControls',},}),- 80,);expect(document.querySelector(SUMMARY)).toBeNull();- const measure = Array.from(- document.querySelectorAll<HTMLElement>('[aria-hidden="true"]'),- ).find(element => element.style.width !== '');- expect(measure).toHaveStyle({width: '80px'});- });-- it('measures a custom threshold when every step is complete', () => {- // activeStep === stepCount is the supported all-complete state, so no- // step is active. Four steps still get 90px each, which is enough for- // this custom 80px threshold and must not fall back to the 112px default.- atWidth(- 360,- <Stepper- activeStep={4}- horizontalOptions={{- minimumStepWidth: 'var(--completed-step-width)',- collapsedVariant: 'withLabelAndControls',- }}- style={{'--completed-step-width': '5rem'} as React.CSSProperties}>- <Step step={0} label="Cart" />- <Step step={1} label="Shipping" />- <Step step={2} label="Delivery" />- <Step step={3} label="Payment" />- </Stepper>,- 80,- );-- expect(document.querySelector(SUMMARY)).toBeNull();- const measure = Array.from(- document.querySelectorAll<HTMLElement>('[aria-hidden="true"]'),- ).find(element => element.style.width !== '');- expect(measure).toHaveStyle({- width: 'var(--completed-step-width)',- });- expect(measure?.closest('li')).toBe(screen.getAllByRole('listitem')[0]);- });-- it('lets the browser resolve a CSS minimum step width', () => {- // Four steps get 90px each. The browser-resolved 6rem probe is stubbed- // to 96px, so this instance collapses without Stepper parsing the unit.- atWidth(- 360,- fourSteps({- horizontalOptions: {- minimumStepWidth: 'var(--checkout-step-width)',- collapsedVariant: 'withLabelAndControls',- },- style: {'--checkout-step-width': '6rem'} as React.CSSProperties,- }),- 96,- );-- expect(document.querySelector(SUMMARY)).toBeInTheDocument();- const measure = Array.from(- document.querySelectorAll<HTMLElement>('[aria-hidden="true"]'),- ).find(element => element.style.width !== '');- expect(measure).toHaveStyle({width: 'var(--checkout-step-width)'});- const list = screen.getByRole('list');- expect(measure?.closest('ol')).toBe(list);- const frame = list.parentElement;- expect(frame).toHaveClass('astryx-stepper-frame');- expect(frame?.style.getPropertyValue('--checkout-step-width')).toBe(- '6rem',- );- });-- it('responds when a CSS minimum step width resolves to a new size', () => {- const originalWidth = Object.getOwnPropertyDescriptor(- Element.prototype,- 'clientWidth',- );- let resolvedMinStepWidth = 80;- let resize: ResizeObserverCallback = () => {};- class ResizeObserverStub {- constructor(callback: ResizeObserverCallback) {- resize = callback;- }- observe() {}- unobserve() {}- disconnect() {}- }- vi.stubGlobal('ResizeObserver', ResizeObserverStub);- Object.defineProperty(Element.prototype, 'clientWidth', {- configurable: true,- get(this: Element) {- if (this.classList.contains('astryx-stepper')) {- return 360;- }- return this instanceof HTMLElement && this.style.width !== ''- ? resolvedMinStepWidth- : 0;- },- });-- let view: ReturnType<typeof render> | null = null;- try {- view = render(- fourSteps({- horizontalOptions: {- minimumStepWidth: 'var(--step-width, 5rem)',- collapsedVariant: 'withLabelAndControls',- },- }),- );- expect(document.querySelector(SUMMARY)).toBeNull();- const measure = Array.from(+ expect(+ Array.from(document.querySelectorAll<HTMLElement>('[aria-hidden="true"]'),- ).find(element => element.style.width !== '');- expect(measure).toBeDefined();-- resolvedMinStepWidth = 96;- act(() =>- resize([{target: measure!} as unknown as ResizeObserverEntry], null!),- );- expect(document.querySelector(SUMMARY)).toBeInTheDocument();- } finally {- view?.unmount();- vi.unstubAllGlobals();- if (originalWidth) {- Object.defineProperty(- Element.prototype,- 'clientWidth',- originalWidth,- );- } else {- delete (Element.prototype as {clientWidth?: number}).clientWidth;- }- }+ ).find(element => element.style.width !== ''),+ ).toBeUndefined();});it('leaves a vertical stepper alone at any width', () => {@@ -1398,6 +1300,66 @@ describe('Stepper', () => {expect(onStepClick).toHaveBeenLastCalledWith(0);});+ it('reads registration state again when a compact control activates', async () => {+ const user = userEvent.setup();+ const onStepClick = vi.fn();+ const disabled = {+ 0: false,+ 1: false,+ 2: false,+ 3: false,+ };++ function Registration({step}: {step: 0 | 1 | 2 | 3}) {+ const {registerStep} = useStepperContext();+ useLayoutEffect(+ () =>+ registerStep(step, {+ getIsDisabled: () => disabled[step],+ }),+ [registerStep, step],+ );+ return null;+ }++ atWidth(+ 320,+ <Stepper activeStep={1} onStepClick={onStepClick}>+ <Registration step={0} />+ <Registration step={1} />+ <Registration step={2} />+ <Registration step={3} />+ </Stepper>,+ );++ // Step 2 was the target during render. Change only the registered source;+ // no parent render should be needed before activation skips it.+ disabled[2] = true;+ await user.click(screen.getByRole('button', {name: 'Next step'}));+ expect(onStepClick).toHaveBeenCalledWith(3);+ });++ it('reads the current disabled state from each registration', async () => {+ const user = userEvent.setup();+ const onStepClick = vi.fn();+ const steps = (isDeliveryDisabled: boolean) => (+ <Stepper activeStep={1} onStepClick={onStepClick}>+ <Step step={0} label="Cart" />+ <Step step={1} label="Shipping" />+ <Step step={2} label="Delivery" isDisabled={isDeliveryDisabled} />+ <Step step={3} label="Payment" />+ </Stepper>+ );+ const {rerender} = atWidth(320, steps(true));++ await user.click(screen.getByRole('button', {name: 'Next step'}));+ expect(onStepClick).toHaveBeenLastCalledWith(3);++ rerender(steps(false));+ await user.click(screen.getByRole('button', {name: 'Next step'}));+ expect(onStepClick).toHaveBeenLastCalledWith(2);+ });+it('disables a summary control with no enabled step in its direction', () => {atWidth(320,@@ -1435,12 +1397,7 @@ describe('Stepper', () => {Object.defineProperty(Element.prototype, 'clientWidth', {configurable: true,get(this: Element) {- if (this.classList.contains('astryx-stepper')) {- return width;- }- return this instanceof HTMLElement && this.style.width !== ''- ? 112- : 0;+ return this.classList.contains('astryx-stepper') ? width : 0;},});diff --git a/packages/core/src/Stepper/Stepper.tsx b/packages/core/src/Stepper/Stepper.tsxindex e093711381..e11aad483d 100644--- a/packages/core/src/Stepper/Stepper.tsx+++ b/packages/core/src/Stepper/Stepper.tsx@@ -44,9 +44,12 @@ import {IconButton} from '../IconButton';import {useTranslator} from '../i18n';import {StepperContext,+ StepperInternalContext,+ type StepperContextValue,type StepperOrientation,type StepperIndicatorPosition,- type StepperContextValue,+ type StepperInternalContextValue,+ type StepperRegistrationOptions,} from './StepperContext';/**@@ -69,12 +72,11 @@ export type StepperCollapsedVariant =export interface StepperHorizontalOptions {/**- * Minimum width allocated to each step before a horizontal Stepper collapses.- * Numbers are interpreted as pixels. Strings accept CSS length values such- * as `'7rem'`, `'calc(6rem + 8px)'`, or `'var(--step-width)'`.+ * Minimum width in pixels allocated to each step before a horizontal Stepper+ * collapses.* @default 112*/- minimumStepWidth: number | string;+ minimumStepWidth: number;/*** Presentation used when the horizontal Stepper collapses.* - `withLabelAndControls`: current-step label and navigation controls.@@ -255,55 +257,65 @@ export function Stepper({// deregister on unmount; a Map tracks count per index so we can warn when// two Steps share the same `step` value (which breaks aria-current).const stepCountsRef = useRef<Map<number, number>>(new Map());- // Disabled registrations are tracked separately so compact previous/next- // controls can move to the nearest enabled step without inspecting children.- // Counts keep cleanup correct even for the invalid duplicate-index case.- const disabledStepCountsRef = useRef<Map<number, number>>(new Map());- const [disabledSteps, setDisabledSteps] = useState<ReadonlySet<number>>(- () => new Set(),- );+ // Compact navigation reads each Step's disabled state through the getter it+ // registered, so the registry does not copy state that belongs to the Step.+ // A Set keeps cleanup correct even for the invalid duplicate-index case.+ const disabledGettersRef = useRef<+ Map<number, Set<NonNullable<StepperRegistrationOptions['getIsDisabled']>>>+ >(new Map());+ // Registration changes can leave the total step count unchanged (for example+ // when a Step's disabled state changes), so this revision still prompts the+ // parent to refresh compact control availability.+ const [, setRegistrationRevision] = useState(0);// How many steps there are, which the stepper needs for real and not only// for the warning: the width each step is getting is this divided into the// width the stepper got. Counted from what registers rather than from the// children, so grouping steps in a fragment or an array cannot change the// answer.const [stepCount, setStepCount] = useState(0);- const registerStep = useCallback((index: number, isDisabled: boolean) => {- const counts = stepCountsRef.current;- const prev = counts.get(index) ?? 0;- counts.set(index, prev + 1);- if (process.env.NODE_ENV !== 'production' && prev + 1 > 1) {- console.warn(- `[Stepper] Duplicate step index ${index}: two <Step> elements share the same \`step\` value. ` +- `This breaks \`aria-current="step"\` and causes both to show as active simultaneously.`,- );- }- if (isDisabled) {- const disabledCounts = disabledStepCountsRef.current;- disabledCounts.set(index, (disabledCounts.get(index) ?? 0) + 1);- setDisabledSteps(new Set(disabledCounts.keys()));- }- setStepCount(c => c + 1);- return () => {- const cur = counts.get(index) ?? 1;- if (cur <= 1) {- counts.delete(index);- } else {- counts.set(index, cur - 1);+ const registerStep = useCallback(+ (index: number, options?: StepperRegistrationOptions) => {+ const counts = stepCountsRef.current;+ const prev = counts.get(index) ?? 0;+ counts.set(index, prev + 1);+ if (process.env.NODE_ENV !== 'production' && prev + 1 > 1) {+ console.warn(+ `[Stepper] Duplicate step index ${index}: two <Step> elements share the same \`step\` value. ` ++ `This breaks \`aria-current="step"\` and causes both to show as active simultaneously.`,+ );+ }++ const getIsDisabled = options?.getIsDisabled;+ if (getIsDisabled) {+ const getters = disabledGettersRef.current.get(index) ?? new Set();+ getters.add(getIsDisabled);+ disabledGettersRef.current.set(index, getters);}- if (isDisabled) {- const disabledCounts = disabledStepCountsRef.current;- const disabledCount = disabledCounts.get(index) ?? 1;- if (disabledCount <= 1) {- disabledCounts.delete(index);++ setStepCount(c => c + 1);+ setRegistrationRevision(revision => revision + 1);+ return () => {+ const cur = counts.get(index) ?? 1;+ if (cur <= 1) {+ counts.delete(index);} else {- disabledCounts.set(index, disabledCount - 1);+ counts.set(index, cur - 1);}- setDisabledSteps(new Set(disabledCounts.keys()));- }- setStepCount(c => c - 1);- };- }, []);++ if (getIsDisabled) {+ const getters = disabledGettersRef.current.get(index);+ getters?.delete(getIsDisabled);+ if (getters?.size === 0) {+ disabledGettersRef.current.delete(index);+ }+ }++ setStepCount(c => c - 1);+ setRegistrationRevision(revision => revision + 1);+ };+ },+ [],+ );// The step we came *from*. Steps need it to stagger their connector fill:// the distance and direction of the change decide which segment moves first@@ -342,11 +354,7 @@ export function Stepper({// still owns the ref and DOM pass-throughs and fills that frame, so its width// is the effective component width to observe.const [rootWidth, setRootWidth] = useState(0);- const [resolvedMinStepWidth, setResolvedMinStepWidth] = useState(- DEFAULT_MIN_STEP_WIDTH,- );const stopObservingRootRef = useRef<(() => void) | null>(null);- const stopObservingMinStepWidthRef = useRef<(() => void) | null>(null);const attachRoot = useCallback((el: HTMLOListElement | null) => {stopObservingRootRef.current?.();@@ -365,25 +373,10 @@ export function Stepper({[isHorizontal],);const rootRef = useMergedRefs(ref, attachRoot);- const attachMinStepWidthMeasure = useCallback((el: HTMLDivElement | null) => {- stopObservingMinStepWidthRef.current?.();- stopObservingMinStepWidthRef.current = null;- if (el) {- // The browser resolves px, rem, calc(), var(), and the other supported- // CSS length forms before clientWidth is read. Observing the probe as- // well as the Stepper means a root-font-size or custom-property change- // can move the breakpoint without the Stepper itself resizing.- stopObservingMinStepWidthRef.current = observeResize(el, entry =>- setResolvedMinStepWidth(entry.target.clientWidth),- );- }- }, []);useEffect(() => () => {stopObservingRootRef.current?.();stopObservingRootRef.current = null;- stopObservingMinStepWidthRef.current?.();- stopObservingMinStepWidthRef.current = null;},[],);@@ -403,11 +396,11 @@ export function Stepper({isHorizontal &&rootWidth > 0 &&stepCount > 0 &&- rootWidth / stepCount < resolvedMinStepWidth;+ rootWidth / stepCount < minimumStepWidth;const [summarySlot, setSummarySlot] = useState<HTMLElement | null>(null);- const ctxValue = useMemo<StepperContextValue>(+ const publicCtxValue = useMemo<StepperContextValue>(() => ({activeStep,previousActiveStep,@@ -417,11 +410,6 @@ export function Stepper({density,indicatorPosition,registerStep,- stepCount,- isCompact,- summarySlot,- minimumStepWidth,- minStepWidthMeasureRef: attachMinStepWidthMeasure,}),[activeStep,@@ -431,12 +419,16 @@ export function Stepper({density,indicatorPosition,registerStep,+ ],+ );+ const internalCtxValue = useMemo<StepperInternalContextValue>(+ () => ({+ ...publicCtxValue,stepCount,isCompact,summarySlot,- minimumStepWidth,- attachMinStepWidthMeasure,- ],+ }),+ [publicCtxValue, stepCount, isCompact, summarySlot],);const isOnTrack = indicatorPosition === 'on-track';@@ -474,7 +466,13 @@ export function Stepper({);if (!isHorizontal) {- return <StepperContext value={ctxValue}>{list}</StepperContext>;+ return (+ <StepperContext value={publicCtxValue}>+ <StepperInternalContext value={internalCtxValue}>+ {list}+ </StepperInternalContext>+ </StepperContext>+ );}// Controls appear only in the variant that asks for them and where there is@@ -500,7 +498,11 @@ export function Stepper({const adjacentEnabledStep = (delta: -1 | 1): number | null => {let target: number | null = null;for (const index of stepCountsRef.current.keys()) {- if (disabledSteps.has(index)) {+ if (+ [...(disabledGettersRef.current.get(index) ?? [])].some(getIsDisabled =>+ getIsDisabled(),+ )+ ) {continue;}if (@@ -518,7 +520,7 @@ export function Stepper({if (!showsControls || onStepClick == null) {return null;}- const target = adjacentEnabledStep(delta);+ const targetAtRender = adjacentEnabledStep(delta);const name =delta === -1? t('@astryx.stepper.previousStep')@@ -534,10 +536,14 @@ export function Stepper({xstyle={rtlStyles.mirror}/>}- isDisabled={target == null}+ isDisabled={targetAtRender == null}onClick={() => {- if (target != null) {- onStepClick(target);+ // A custom registration may read state that changed without causing+ // Stepper to render. Resolve again at activation so a target that+ // became disabled cannot be selected from the render-time snapshot.+ const currentTarget = adjacentEnabledStep(delta);+ if (currentTarget != null) {+ onStepClick(currentTarget);}}}/>@@ -545,35 +551,37 @@ export function Stepper({};return (- <StepperContext value={ctxValue}>- <div- {...mergeProps(- themeProps('stepper-frame'),- stylex.props(styles.frame, xstyle),- className,- style,- )}>- {list}- {showsSummary && (- <div- {...mergeProps(- themeProps('stepper-summary'),- stylex.props(styles.summary),- )}>- {control(-1)}- {/* The list above still carries every step's name and status, so+ <StepperContext value={publicCtxValue}>+ <StepperInternalContext value={internalCtxValue}>+ <div+ {...mergeProps(+ themeProps('stepper-frame'),+ stylex.props(styles.frame, xstyle),+ className,+ style,+ )}>+ {list}+ {showsSummary && (+ <div+ {...mergeProps(+ themeProps('stepper-summary'),+ stylex.props(styles.summary),+ )}>+ {control(-1)}+ {/* The list above still carries every step's name and status, sothis visual row is hidden from assistive technology to avoidannouncing the current step twice. hiddenLabel withholds theentire row above, leaving the accessible list as a bare track. */}- <div- ref={setSummarySlot}- aria-hidden="true"- {...stylex.props(styles.summaryBody)}- />- {control(1)}- </div>- )}- </div>+ <div+ ref={setSummarySlot}+ aria-hidden="true"+ {...stylex.props(styles.summaryBody)}+ />+ {control(1)}+ </div>+ )}+ </div>+ </StepperInternalContext></StepperContext>);}diff --git a/packages/core/src/Stepper/StepperContext.ts b/packages/core/src/Stepper/StepperContext.tsindex eca384edbc..d585f8c42b 100644--- a/packages/core/src/Stepper/StepperContext.ts+++ b/packages/core/src/Stepper/StepperContext.ts@@ -5,15 +5,27 @@/*** @file StepperContext.ts* @input Uses React createContext/use- * @output Exports StepperContext, useStepperContext, and context types+ * @output Exports the public Stepper context hook and package-internal+ * coordination used by Stepper and Step* @position Context for Stepper <-> Step communication*+ * `StepperContextValue` is the supported public read. It keeps the Stepper+ * state, configuration, transition history, and step registration contract+ * while excluding compact-layout coordination used only by the built-in Step.+ * Its provider carries exactly those keys, so JavaScript and TypeScript observe+ * the same boundary.+ *+ * `StepperInternalContextValue` is carried by a separate package-internal+ * provider. It adds compact-layout coordination for Stepper and Step but is not+ * re-exported from index.ts.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Stepper/Stepper.doc.mjs* - /packages/core/src/Stepper/index.ts+ * - /packages/core/src/Stepper/Stepper.public.test.ts*/-import {createContext, use, type RefCallback} from 'react';+import {createContext, use, type Context} from 'react';export type StepperOrientation = 'horizontal' | 'vertical';export type StepperDensity = 'compact' | 'balanced' | 'spacious';@@ -28,6 +40,13 @@ export type StepperDensity = 'compact' | 'balanced' | 'spacious';*/export type StepperIndicatorPosition = 'separated' | 'on-track';+/** Options reported by a Step when it registers with Stepper. */+export interface StepperRegistrationOptions {+ /** Reads the Step's current disabled state. */+ getIsDisabled?: () => boolean;+}++/** Stepper state and coordination available to descendant content. */export interface StepperContextValue {activeStep: number;/**@@ -37,9 +56,6 @@ export interface StepperContextValue {* crossed (see the CONNECTOR FILL block in Step.tsx). Equal to `activeStep`* on the first render, which is what keeps a stepper that mounts mid-flow* from animating its way to the step it opened on.- *- * Consumers cannot configure this through a Stepper prop; it reflects the- * component-owned transition history exposed by the context hook.*/previousActiveStep: number;orientation: StepperOrientation;@@ -48,63 +64,58 @@ export interface StepperContextValue {density: StepperDensity;indicatorPosition: StepperIndicatorPosition;/**- * Dev-mode index registration and compact-navigation metadata. Each Step- * calls this on mount with its `step` index and disabled state. The Stepper+ * Registers a Step index and an optional disabled-state getter. The Stepper* tracks the set, warns if two Steps share an index, and keeps compact* previous/next controls from selecting disabled steps. Returns a cleanup* function to call on unmount.*/- registerStep: (index: number, isDisabled: boolean) => () => void;- /**- * How many steps have registered. Needed to know how much width each one is- * getting, and to tell the last step from the rest without counting- * children — which would couple the stepper to how they were grouped.- */+ registerStep: (+ index: number,+ options?: StepperRegistrationOptions,+ ) => () => void;+}++/**+ * Package-internal Stepper <-> Step coordination. This type is intentionally+ * absent from the public component barrel.+ */+export interface StepperInternalContextValue extends StepperContextValue {+ /** Number of registered steps used to derive the compact threshold. */stepCount: number;- /**- * True once the stepper is too narrow to give every step a legible label, at- * which point the steps drop theirs and the stepper names the current one- * below the track instead. Always false when vertical, which gives every- * label a row of its own and never runs out of room.- *- * Decided by the parent because it depends on how much width there is and- * how many steps are dividing it, and neither is knowable from inside a- * single step.- */+ /** Whether a horizontal Stepper is currently using its compact layout. */isCompact: boolean;- /**- * Where the current step draws itself once the labels have gone. The- * stepper owns the row — it is outside the `<ol>`, so that the list keeps- * exactly the children it was given and the on-track connectors can go on- * reading their own `:first-child`/`:last-child` position — and the active- * step fills it through a portal.- *- * A portal rather than the step handing its label up through this context:- * an indicator can be any node, so a registered copy would either go stale- * or change identity on every render and re-register forever. Rendered in- * place, it is the same node the step already built, kept live by the same- * render that built it.- *- * Null until the row exists, which is never on a stepper wide enough not to- * need one.- */+ /** Portal target for the active step's compact summary. */summarySlot: HTMLElement | null;- /** CSS length whose resolved value sets the compact per-step threshold. */- minimumStepWidth: number | string;- /** Ref for the first Step's invisible CSS-length measurement element. */- minStepWidthMeasureRef: RefCallback<HTMLDivElement>;}export const StepperContext = createContext<StepperContextValue | null>(null);StepperContext.displayName = 'StepperContext';-export function useStepperContext(): StepperContextValue {- const ctx = use(StepperContext);+export const StepperInternalContext =+ createContext<StepperInternalContextValue | null>(null);+StepperInternalContext.displayName = 'StepperInternalContext';++function useContextValue<T>(context: Context<T | null>, hookName: string): T {+ const ctx = use(context);if (ctx == null) {throw new Error(- 'useStepperContext must be used within Stepper. ' +- 'Wrap your Step in <Stepper>.',+ `${hookName} must be used within Stepper. Wrap your Step in <Stepper>.`,);}return ctx;}++/** Package-internal context read used by the built-in Step. */+export function useStepperInternalContext(): StepperInternalContextValue {+ return useContextValue(StepperInternalContext, 'useStepperInternalContext');+}++/**+ * Reads the enclosing Stepper's public context.+ *+ * Step count, compact state, summary-portal coordination, and threshold+ * measurement details are intentionally not part of this return type.+ */+export function useStepperContext(): StepperContextValue {+ return useContextValue(StepperContext, 'useStepperContext');+}diff --git a/packages/core/src/Stepper/index.ts b/packages/core/src/Stepper/index.tsindex 72db7132ec..6ebc794825 100644--- a/packages/core/src/Stepper/index.ts+++ b/packages/core/src/Stepper/index.ts@@ -17,6 +17,7 @@ export type {StepStatus} from './StepStatus';export {useStepperContext} from './StepperContext';export type {StepperContextValue,+ StepperRegistrationOptions,StepperOrientation,StepperIndicatorPosition,} from './StepperContext';