Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): let Stepper collapse itself in narrow containers (#5659)

Ernest63a0bcd741bd
diff --git a/.changeset/stepper-collapsed-summary-props.md b/.changeset/stepper-collapsed-summary-props.md
new file mode 100644
index 0000000000..712568b22f
--- /dev/null
+++ b/.changeset/stepper-collapsed-summary-props.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Stepper's `horizontalOptions.collapsedVariant` lets a flow choose `withLabelAndControls`, `withLabel`, or `hiddenLabel` for its compact presentation. Use `withLabel` when the surrounding flow owns Back/Continue, or `hiddenLabel` when surrounding UI owns both the current-step heading and navigation and only a bare progress track is needed. The default preserves both label and controls, its controls require `onStepClick`, and every step keeps its name in the accessible sequence at any width. (#5659)
+@ernestt
diff --git a/.changeset/stepper-configurable-min-step-width.md b/.changeset/stepper-configurable-min-step-width.md
new file mode 100644
index 0000000000..2cf1e8107e
--- /dev/null
+++ b/.changeset/stepper-configurable-min-step-width.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Stepper's `horizontalOptions.minimumStepWidth` configures the per-step width at which a horizontal Stepper collapses. Numbers are interpreted as pixels and strings accept CSS lengths such as `7rem`, `calc(6rem + 8px)`, and custom properties. The browser resolves string units through an invisible measurement element, and changes to the resolved value update the compact layout. Omitting the option preserves the existing 112px threshold. (#5659)
+@imdreamrunner
diff --git a/.changeset/stepper-narrow-collapse.md b/.changeset/stepper-narrow-collapse.md
new file mode 100644
index 0000000000..b3b16880b3
--- /dev/null
+++ b/.changeset/stepper-narrow-collapse.md
@@ -0,0 +1,10 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Stepper collapses itself in narrow containers instead of leaving each consumer to hand-roll a fallback: a horizontal stepper measures its own width and, once a step has under `horizontalOptions.minimumStepWidth` (112px by default), drops the labels to a bare track and uses the configured `collapsedVariant` beneath it. The breakpoint follows the step count rather than the viewport. Both `separated` and `on-track` leave their compact track presentational; navigation moves to named prev/next controls when configured and when `onStepClick` is set. On-track indicators stay on the rail without repeating the active indicator beside the compact label. The full sequence stays intact for screen readers throughout. (#5659)
+@ernestt
+
+[fix] Step labels hold to a single line and ellipsize rather than wrapping and breaking mid-word, so a row of horizontal steps keeps one height and the track under it stays straight. The full label is still carried in the step's accessible name.
+
+[fix] The gap between connector segments is now `--spacing-1`, matching the connector's own thickness, so the track reads as one dashed line at any theme scale.
diff --git a/apps/storybook/stories/Stepper.stories.tsx b/apps/storybook/stories/Stepper.stories.tsx
index 6c28e7e391..524fea4b3a 100644
--- a/apps/storybook/stories/Stepper.stories.tsx
+++ b/apps/storybook/stories/Stepper.stories.tsx
@@ -1113,6 +1113,157 @@ export const StepAdvance: Story = {
},
};
+// ============================================================
+// NARROW CONTAINERS — the stepper collapses itself
+// ============================================================
+
+export const NarrowCollapse: Story = {
+ name: 'Narrow — Collapsed Track',
+ parameters: {
+ 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.",
+ },
+ },
+ },
+ render: () => {
+ const [a, setA] = useState(1);
+ const [b, setB] = useState(1);
+ const [c, setC] = useState(1);
+ const steps = ['Cart', 'Shipping', 'Delivery', 'Payment'];
+ return (
+ <div style={{display: 'grid', gap: 40}}>
+ <div style={{maxWidth: 560}}>
+ <Text type="label">560px — four steps still fit</Text>
+ <Stepper activeStep={a} onStepClick={setA} label="Checkout">
+ {steps.map((s, i) => (
+ <Step key={s} step={i} label={s} />
+ ))}
+ </Stepper>
+ </div>
+ <div style={{maxWidth: 320}}>
+ <Text type="label">320px — separated, navigable</Text>
+ <Stepper activeStep={a} onStepClick={setA} label="Checkout">
+ {steps.map((s, i) => (
+ <Step key={s} step={i} label={s} />
+ ))}
+ </Stepper>
+ </div>
+ <div style={{maxWidth: 320}}>
+ <Text type="label">320px — custom 4rem threshold stays expanded</Text>
+ <Stepper
+ activeStep={a}
+ onStepClick={setA}
+ horizontalOptions={{
+ minimumStepWidth: '4rem',
+ collapsedVariant: 'withLabelAndControls',
+ }}
+ label="Checkout">
+ {steps.map((s, i) => (
+ <Step key={s} step={i} label={s} />
+ ))}
+ </Stepper>
+ </div>
+ <div style={{maxWidth: 320}}>
+ <Text type="label">320px — on-track keeps nodes on the rail</Text>
+ <Stepper
+ activeStep={b}
+ onStepClick={setB}
+ indicatorPosition="on-track"
+ label="Checkout">
+ {steps.map((s, i) => (
+ <Step key={s} step={i} label={s} indicator="number" />
+ ))}
+ </Stepper>
+ </div>
+ <div style={{maxWidth: 320}}>
+ <Text type="label">320px — no onStepClick, so no controls</Text>
+ <Stepper activeStep={c} label="Checkout">
+ {steps.map((s, i) => (
+ <Step key={s} step={i} label={s} />
+ ))}
+ </Stepper>
+ <div style={{marginTop: 12, display: 'flex', gap: 8}}>
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setC(n => Math.max(0, n - 1))}
+ />
+ <Button
+ label="Continue"
+ onClick={() => setC(n => Math.min(3, n + 1))}
+ />
+ </div>
+ </div>
+ <div style={{maxWidth: 320}}>
+ <Text type="label">
+ 320px — a description rides along with the current step
+ </Text>
+ <Stepper activeStep={a} onStepClick={setA} label="Checkout">
+ <Step step={0} label="Cart" description="Review your items" />
+ <Step step={1} label="Shipping" description="Where it goes" />
+ <Step step={2} label="Delivery" description="How fast" />
+ <Step step={3} label="Payment" description="How you pay" />
+ </Stepper>
+ </div>
+ </div>
+ );
+ },
+};
+
+export const NarrowCollapsedVariants: Story = {
+ name: 'Narrow — Collapsed Variants',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'The same 320px horizontal Stepper with each collapsedVariant. hiddenLabel omits the entire compact row—even though onStepClick is present—so it is shorter and leaves only the progress track.',
+ },
+ },
+ },
+ render: () => {
+ const [active, setActive] = useState(1);
+ const steps = ['Cart', 'Shipping', 'Delivery', 'Payment'];
+ const variants = [
+ {
+ value: 'withLabelAndControls',
+ label: 'withLabelAndControls — label and controls',
+ },
+ {value: 'withLabel', label: 'withLabel — label only'},
+ {value: 'hiddenLabel', label: 'hiddenLabel — bare track'},
+ ] as const;
+
+ return (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 320px))',
+ alignItems: 'start',
+ gap: 40,
+ }}>
+ {variants.map(variant => (
+ <div key={variant.value} style={{width: '100%', maxWidth: 320}}>
+ <Text type="label">{variant.label}</Text>
+ <Stepper
+ activeStep={active}
+ onStepClick={setActive}
+ label="Checkout"
+ horizontalOptions={{
+ minimumStepWidth: 112,
+ collapsedVariant: variant.value,
+ }}>
+ {steps.map((step, index) => (
+ <Step key={step} step={index} label={step} />
+ ))}
+ </Stepper>
+ </div>
+ ))}
+ </div>
+ );
+ },
+};
+
// ============================================================
// FRAGMENT-GROUPED STEPS
// ============================================================
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/.gitignore b/internal/vibe-tests/stepper-collapse-naming-test/.gitignore
new file mode 100644
index 0000000000..fbca225379
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/.gitignore
@@ -0,0 +1 @@
+results/
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/PLAN.md b/internal/vibe-tests/stepper-collapse-naming-test/PLAN.md
new file mode 100644
index 0000000000..597e3a5169
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/PLAN.md
@@ -0,0 +1,222 @@
+# Stepper Collapsed-Summary Naming Vibe Test
+
+**Status:** ad-hoc · run 1 complete · decided
+**Related:** [`../README.md`](../README.md) (Checker Protocol), [API Arbitration](https://github.com/facebook/astryx/wiki/API-Arbitration), [Designing Vibe Tests](https://github.com/facebook/astryx/wiki/Designing-Vibe-Tests), [PR #5659](https://github.com/facebook/astryx/pull/5659)
+
+---
+
+## 1. The question
+
+PR #5659 gives `Stepper` a narrow-width collapse: labels drop away, leaving a bare
+segmented track, and a row appears beneath it carrying the current step's name and —
+when `onStepClick` is set — Previous/Next controls.
+
+Feedback on the PR: on mobile both halves of that row are often redundant, because
+consumers already have their own Back/Continue and their own per-step heading. Both
+wizard templates in this repo are that shape — `form-wizard` and `checkout-wizard` each
+pass `onStepClick` so people can jump backward at full width, and each has footer
+buttons and an `<Heading level={2}>` per panel.
+
+So each half needs an off switch. **What should they be called, and should they be two
+props or one?**
+
+## 2. Design
+
+Four-ingredient intake per [Designing Vibe Tests](https://github.com/facebook/astryx/wiki/Designing-Vibe-Tests).
+
+**Goal & measure.** A naive agent is told what the *page* provides and never told a prop
+name. Scored on correctness, hallucination, directness, and confidence calibration.
+Tie-break: hallucination, then fewer concepts.
+
+**Prompt battery.** Four prompts in [`prompts.json`](prompts.json), one per cell of the
+2×2 over what the surrounding page already has. None name a prop, a value, or the word
+"collapse".
+
+| | page already has | correct answer |
+| --- | --- | --- |
+| p1 | footer Back/Continue | controls off, name kept |
+| p2 | a per-step heading | name off, controls kept |
+| p3 | both | both off — bare track |
+| p4 | neither | **set nothing** (negative control) |
+
+**Arms.** Four conditions, plus a recall probe.
+
+| arm | shape |
+| --- | --- |
+| `A` | `hasCollapsedControls` / `hasCollapsedLabel`, both default `true` |
+| `B` | `hasControls` / `hasLabel`, both default `true` |
+| `C` | `hasSummaryControls` / `hasSummaryLabel`, both default `true` |
+| `D` | `collapsedSummary?: 'auto' \| 'label' \| 'controls' \| 'none'` |
+| `recall` | behavior described, props deliberately unnamed — the agent writes what it expects |
+
+**Orchestration.** One isolated sub-agent per (prompt × arm), spawned fresh with the
+wiki's blank-slate preamble, self-reporting but never self-scoring. Five recall samples.
+One judge agent with cross-arm visibility. 22 agents total.
+
+### Fairness (Checker Protocol)
+
+| Invariant | How this honors it |
+| --- | --- |
+| §1 Fair evaluators | One judge, all arms side by side, one rubric. Blinding is impossible here — the arm is legible from the prop names — so the judge was told to score the rubric and not its own taste, and to audit doc parity before reading any result |
+| §2 Only the SUT varies | The four arm docs are **machine-generated from one template** ([`gen-docs.mjs`](gen-docs.mjs)); intro, prop-table rows, `Step` description, example 1 and the anti-pattern are byte-identical. 349/349/349/354 words. The prose naming the props is one sentence with the names swapped, so no arm gets a lexical head start |
+| §3 Never leak the answer | Ground truth lives in `prompts.json` and never reached a generating agent |
+| §4 Representative environment | A skill doc is exactly what a consumer's agent gets |
+| §5 Context-free | Fresh sub-agents, explicitly barred from reading the repo, the component source, or each other's docs |
+
+---
+
+## 3. Findings
+
+### 3.1 Recognition is a four-way tie
+
+**16/16 correct. 16/16 free of hallucination.** Every arm put the right configuration on
+every prompt, including the p4 negative control, which no arm's agent was tempted into
+touching. Directness split on a single result (`c-p2` added an unrequested `<h1>`).
+
+Per the wiki's decision patterns, *all options produce identical code → the difference
+doesn't matter, pick the simpler one*. On this battery the naming does not change whether
+an agent can use the API. Everything below is the tie-break.
+
+### 3.2 The recall probe is where the arms separate
+
+Five agents were given the behavior with the props deliberately unnamed and asked to
+write what they expected.
+
+| sample | controls | name |
+| --- | --- | --- |
+| 1 | `showCollapsedControls` | `showCollapsedStepLabel` |
+| 2 | `showCollapsedControls` | `showCollapsedLabel` |
+| 3 | `showNavigation` | `showStepLabel` |
+| 4 | `showSummaryControls` | `showSummaryLabel` |
+| 5 | `showSummaryControls` | `showSummaryLabel` |
+
+**5/5 produced two independent booleans. Nobody produced an enum.** Every one rejected the
+enum unprompted, and converged on the same reason — that it forces you to restate the half
+you did not want to change. Sample 5 added the sharpest version: the component's existing
+enums (`orientation`, `density`, `indicatorPosition`) are all mutually-exclusive choices,
+and this is not one. **Arm D is out on shape**, despite scoring 5.00 on correctness.
+
+**4/5 rejected a bare `Label` because it collides with the existing `label` prop** — the
+accessible name of the whole sequence. Sample 3: *"a reader would think it toggles that
+string."* Sample 2 flagged the other half too: *"`showControls` alone would sound like it
+suppresses `onStepClick`."* **Arm B is out on ambiguity**, and this is a real collision in
+the shipping API, not an artifact of the test.
+
+That leaves A and C, 2–2. Two things break it:
+
+- **Both `Summary` choosers started at `Collapsed` and switched**, and both said why:
+ the anti-pattern's `data-astryx-stepper-summary` selector looked like the component's
+ internal name. Sample 4: *"`showCollapsedControls` was my first instinct … but the data
+ attribute pointed at 'summary' as the internal name."* That is a reason to guess the
+ implementation, not a reason a consumer would reach for the word.
+- **3/5 explicitly rejected `Summary` as internal vocabulary.** Sample 3: *"'summary' is
+ internal implementation vocabulary that appears nowhere in the prose or the props
+ table."*
+
+### 3.3 The judge picks A, on an effect the scores don't show
+
+> "On p2 and p3, every B and C result stopped to verify the prop wouldn't kill the desktop
+> labels (4/4), and no A or D result did (0/4)."
+
+The word `Collapsed` in the name removes a class of doubt about scope. `Summary` does not,
+because a reader who does not already know the row is called a summary cannot tell what
+the prop reaches.
+
+The judge also caught an inversion hazard specific to the enum: its values name what
+*survives*, while every requirement names what to *remove*. `d-p2` walked into it live —
+*"my first instinct was to set it to `'none'` … `'none'` is the value that most literally
+removes the name"* — and recovered only via an unrelated clause in the prompt.
+
+### 3.4 `show` beats `has` with LLMs, and the convention should still win
+
+**5/5 recall samples produced `show*`**, several rejecting `hide*` explicitly for the
+double negative. Astryx has ~30 `has*` booleans in `packages/core/src` and zero `show*`
+ones, so the house convention says `has*`.
+
+Take the convention. §3.1 is the evidence that it is free: agents used `has*` correctly
+16/16 when the doc said `has*`. The prefix affects what an agent *guesses*, not what it
+*does* with a documented API — and a design system's props are always documented.
+
+### 3.5 The finding that outranks the naming
+
+Every arm hit the same wall, and it is a property of the design rather than of any name.
+**Nobody could tell whether a collapsed track is still tappable.** `d-p1`:
+
+> "there may be no way to tap back to a finished step at all — the labels are gone and I
+> have suppressed the controls … it is the one place where the brief's two phone
+> requirements might be in tension."
+
+That is exactly right, and it applies identically to `a-p1`, `b-p1` and `c-p1`. In the
+`separated` layout the step click targets go with the labels, so turning the controls off
+leaves nothing to press. Addressed in the shipped `hasCollapsedControls` JSDoc, which
+names the consequence and the `on-track` exception rather than leaving it to be
+discovered. Two further cross-arm findings are recorded in §5 as follow-ups.
+
+---
+
+## 4. Decision
+
+**Ship arm A — `hasCollapsedControls` and `hasCollapsedLabel`, both `@default true`.**
+
+- Two booleans, because the recall probe produced two booleans 5/5 and the four states are
+ genuinely independent (§3.2).
+- `has*`, because the convention is unanimous in `packages/core/src` and §3.1 shows the
+ prefix costs nothing in use (§3.4).
+- The `Collapsed` qualifier, because it was the unprompted first instinct in 4/5 recall
+ samples, because it measurably removed scope doubt in the judge's read (§3.3), and
+ because `Summary` only ever won by leaking an internal name (§3.2).
+- Defaults stay `true`: the report is about redundancy, not breakage, and a consumer who
+ passes `onStepClick` with no other navigation must not be stranded on a phone.
+
+Implementation note: `Step` needed **no change**. It already gates its summary portal on
+`summarySlot != null`, so withholding the slot is the entire implementation of
+`hasCollapsedLabel` — and because that row is `aria-hidden` while the `<ol>` keeps every
+step's name, both props are purely visual and cannot shorten what a screen reader hears.
+
+---
+
+## 5. Follow-ups this test surfaced (not naming)
+
+1. **No per-step gating.** All 8 results on p1+p3 independently wrote the same
+ `index < step` guard around `onStepClick`, because nothing lets a step declare itself
+ unreachable. `a-p1` noticed the resulting contradiction: *"my guard makes the future
+ steps look interactive and do nothing, which is the same tab-order complaint the
+ anti-pattern section raises."* Worth a spec.
+2. **The collapse cannot be forced.** All 16 reported being unable to preview or pin the
+ collapsed state. That is a testing and Storybook gap, and it is why the unit tests
+ here have to redefine `clientWidth` by hand.
+
+---
+
+## 6. Caveats
+
+- **p1 was a giveaway in all four arms.** Example 2 in every doc renders p1's answer
+ almost verbatim. Symmetric, so it does not favour an arm, but it means only p2/p3/p4
+ carried signal and the 16/16 in §3.1 is easier than it looks. The judge caught this
+ independently; a re-run should vary which cell the worked example demonstrates.
+- **Both qualifiers were primed, unevenly.** "collapsed" appears 4× in the recall doc (3×
+ in prose), "summary" once, inside a CSS selector. `Collapsed` therefore had the larger
+ prompt-side advantage — which makes the 2–2 split *favourable* to `Summary` on a naive
+ read, and is why §3.2 leans on the switch narratives rather than the raw tally.
+- **n=5 on recall, n=4 per arm.** The unanimous results (enum 0/5, two-booleans 5/5,
+ `show*` 5/5, the `label` collision 4/5) are wide of sampling noise. The 2–2 qualifier
+ split is not, and is decided by §3.3 rather than by count.
+- **One battery, one author.** Written by the same person who drafted the candidates.
+- **Recall batched three scenarios per agent**, deviating from one-agent-per-prompt.
+ Deliberate: naming a coherent *pair* is the realistic act, and splitting it would have
+ measured three unrelated guesses instead of one scheme.
+
+---
+
+## 7. Folder layout
+
+```
+internal/vibe-tests/stepper-collapse-naming-test/
+├── PLAN.md # this file — design + findings + decision
+├── gen-docs.mjs # generates the 5 arm docs from one template (fairness by construction)
+├── docs/ # the generated skill docs, one per arm
+├── prompts.json # the 4-prompt battery + ground truth
+└── results/ # (gitignored) 16 generation + 5 recall + JUDGE.md
+```
+
+Regenerate the docs with `node internal/vibe-tests/stepper-collapse-naming-test/gen-docs.mjs`.
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-a-collapsed.md b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-a-collapsed.md
new file mode 100644
index 0000000000..2973f2169f
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-a-collapsed.md
@@ -0,0 +1,72 @@
+# Stepper
+
+```
+import {Step, Stepper} from '@astryxdesign/core/Stepper';
+```
+
+A horizontal `Stepper` renders a numbered sequence with a label under each
+step. It measures its own width. Once each step has less than about 112px to
+work with, the stepper **collapses**: the labels drop away leaving a bare
+segmented progress track, and a row appears beneath that track carrying the
+current step's name and — when `onStepClick` is set — Previous/Next controls.
+A vertical stepper never collapses.
+
+## Props
+
+| prop | type | default |
+| --- | --- | --- |
+| `activeStep` | `number` | — |
+| `children` | `ReactNode` | — |
+| `onStepClick` | `(index: number) => void` | — |
+| `label` | `string` | `'Progress'` |
+| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` |
+| `density` | `'compact' \| 'balanced' \| 'spacious'` | `'balanced'` |
+| `indicatorPosition` | `'separated' \| 'on-track'` | `'separated'` |
+| `hasCollapsedControls` | `boolean` | `true` |
+| `hasCollapsedLabel` | `boolean` | `true` |
+
+`activeStep` is the zero-based index of the current step. `onStepClick` makes
+steps clickable for non-linear navigation.
+
+`hasCollapsedControls` sets whether the collapsed stepper shows Previous/Next
+controls beneath the track; they only ever appear when `onStepClick` is set.
+`hasCollapsedLabel` sets whether the collapsed stepper names the current step
+beneath the track. The name stays in the accessible sequence either way.
+Neither has any effect while the stepper is wide enough to show its labels.
+
+`Step` takes `step` (zero-based index), `label`, and optionally `description`,
+`status` (`'accent' | 'success' | 'warning' | 'error'`), and `isOptional`.
+
+## Examples
+
+Default, no configuration:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+Turning off one half of the collapsed row:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep} hasCollapsedControls={false}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+## Anti-pattern
+
+Don't hide the collapsed row with CSS:
+
+```css
+/* Don't do this */
+[data-astryx-stepper-summary] { display: none; }
+```
+
+It leaves the controls in the tab order with nothing visible to show for them.
+Use `hasCollapsedControls` / `hasCollapsedLabel` instead.
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-b-bare.md b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-b-bare.md
new file mode 100644
index 0000000000..061d6f4a30
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-b-bare.md
@@ -0,0 +1,72 @@
+# Stepper
+
+```
+import {Step, Stepper} from '@astryxdesign/core/Stepper';
+```
+
+A horizontal `Stepper` renders a numbered sequence with a label under each
+step. It measures its own width. Once each step has less than about 112px to
+work with, the stepper **collapses**: the labels drop away leaving a bare
+segmented progress track, and a row appears beneath that track carrying the
+current step's name and — when `onStepClick` is set — Previous/Next controls.
+A vertical stepper never collapses.
+
+## Props
+
+| prop | type | default |
+| --- | --- | --- |
+| `activeStep` | `number` | — |
+| `children` | `ReactNode` | — |
+| `onStepClick` | `(index: number) => void` | — |
+| `label` | `string` | `'Progress'` |
+| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` |
+| `density` | `'compact' \| 'balanced' \| 'spacious'` | `'balanced'` |
+| `indicatorPosition` | `'separated' \| 'on-track'` | `'separated'` |
+| `hasControls` | `boolean` | `true` |
+| `hasLabel` | `boolean` | `true` |
+
+`activeStep` is the zero-based index of the current step. `onStepClick` makes
+steps clickable for non-linear navigation.
+
+`hasControls` sets whether the collapsed stepper shows Previous/Next
+controls beneath the track; they only ever appear when `onStepClick` is set.
+`hasLabel` sets whether the collapsed stepper names the current step
+beneath the track. The name stays in the accessible sequence either way.
+Neither has any effect while the stepper is wide enough to show its labels.
+
+`Step` takes `step` (zero-based index), `label`, and optionally `description`,
+`status` (`'accent' | 'success' | 'warning' | 'error'`), and `isOptional`.
+
+## Examples
+
+Default, no configuration:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+Turning off one half of the collapsed row:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep} hasControls={false}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+## Anti-pattern
+
+Don't hide the collapsed row with CSS:
+
+```css
+/* Don't do this */
+[data-astryx-stepper-summary] { display: none; }
+```
+
+It leaves the controls in the tab order with nothing visible to show for them.
+Use `hasControls` / `hasLabel` instead.
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-c-summary.md b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-c-summary.md
new file mode 100644
index 0000000000..e3b5e4520f
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-c-summary.md
@@ -0,0 +1,72 @@
+# Stepper
+
+```
+import {Step, Stepper} from '@astryxdesign/core/Stepper';
+```
+
+A horizontal `Stepper` renders a numbered sequence with a label under each
+step. It measures its own width. Once each step has less than about 112px to
+work with, the stepper **collapses**: the labels drop away leaving a bare
+segmented progress track, and a row appears beneath that track carrying the
+current step's name and — when `onStepClick` is set — Previous/Next controls.
+A vertical stepper never collapses.
+
+## Props
+
+| prop | type | default |
+| --- | --- | --- |
+| `activeStep` | `number` | — |
+| `children` | `ReactNode` | — |
+| `onStepClick` | `(index: number) => void` | — |
+| `label` | `string` | `'Progress'` |
+| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` |
+| `density` | `'compact' \| 'balanced' \| 'spacious'` | `'balanced'` |
+| `indicatorPosition` | `'separated' \| 'on-track'` | `'separated'` |
+| `hasSummaryControls` | `boolean` | `true` |
+| `hasSummaryLabel` | `boolean` | `true` |
+
+`activeStep` is the zero-based index of the current step. `onStepClick` makes
+steps clickable for non-linear navigation.
+
+`hasSummaryControls` sets whether the collapsed stepper shows Previous/Next
+controls beneath the track; they only ever appear when `onStepClick` is set.
+`hasSummaryLabel` sets whether the collapsed stepper names the current step
+beneath the track. The name stays in the accessible sequence either way.
+Neither has any effect while the stepper is wide enough to show its labels.
+
+`Step` takes `step` (zero-based index), `label`, and optionally `description`,
+`status` (`'accent' | 'success' | 'warning' | 'error'`), and `isOptional`.
+
+## Examples
+
+Default, no configuration:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+Turning off one half of the collapsed row:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep} hasSummaryControls={false}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+## Anti-pattern
+
+Don't hide the collapsed row with CSS:
+
+```css
+/* Don't do this */
+[data-astryx-stepper-summary] { display: none; }
+```
+
+It leaves the controls in the tab order with nothing visible to show for them.
+Use `hasSummaryControls` / `hasSummaryLabel` instead.
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-d-enum.md b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-d-enum.md
new file mode 100644
index 0000000000..0b4ab18cd4
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-d-enum.md
@@ -0,0 +1,72 @@
+# Stepper
+
+```
+import {Step, Stepper} from '@astryxdesign/core/Stepper';
+```
+
+A horizontal `Stepper` renders a numbered sequence with a label under each
+step. It measures its own width. Once each step has less than about 112px to
+work with, the stepper **collapses**: the labels drop away leaving a bare
+segmented progress track, and a row appears beneath that track carrying the
+current step's name and — when `onStepClick` is set — Previous/Next controls.
+A vertical stepper never collapses.
+
+## Props
+
+| prop | type | default |
+| --- | --- | --- |
+| `activeStep` | `number` | — |
+| `children` | `ReactNode` | — |
+| `onStepClick` | `(index: number) => void` | — |
+| `label` | `string` | `'Progress'` |
+| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` |
+| `density` | `'compact' \| 'balanced' \| 'spacious'` | `'balanced'` |
+| `indicatorPosition` | `'separated' \| 'on-track'` | `'separated'` |
+| `collapsedSummary` | `'auto' \| 'label' \| 'controls' \| 'none'` | `'auto'` |
+
+`activeStep` is the zero-based index of the current step. `onStepClick` makes
+steps clickable for non-linear navigation.
+
+`collapsedSummary` sets what the collapsed stepper shows beneath the track.
+`'auto'` shows the current step's name, plus Previous/Next controls when
+`onStepClick` is set. `'label'` shows the name only. `'controls'` shows the
+controls only. `'none'` shows nothing, leaving the bare track. The name stays
+in the accessible sequence under every value. It has no effect while the
+stepper is wide enough to show its labels.
+
+`Step` takes `step` (zero-based index), `label`, and optionally `description`,
+`status` (`'accent' | 'success' | 'warning' | 'error'`), and `isOptional`.
+
+## Examples
+
+Default, no configuration:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+Turning off one half of the collapsed row:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep} collapsedSummary="label">
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+## Anti-pattern
+
+Don't hide the collapsed row with CSS:
+
+```css
+/* Don't do this */
+[data-astryx-stepper-summary] { display: none; }
+```
+
+It leaves the controls in the tab order with nothing visible to show for them.
+Use `collapsedSummary` instead.
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-recall.md b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-recall.md
new file mode 100644
index 0000000000..1dc6a56da6
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/docs/arm-recall.md
@@ -0,0 +1,61 @@
+# Stepper
+
+```
+import {Step, Stepper} from '@astryxdesign/core/Stepper';
+```
+
+A horizontal `Stepper` renders a numbered sequence with a label under each
+step. It measures its own width. Once each step has less than about 112px to
+work with, the stepper **collapses**: the labels drop away leaving a bare
+segmented progress track, and a row appears beneath that track carrying the
+current step's name and — when `onStepClick` is set — Previous/Next controls.
+A vertical stepper never collapses.
+
+## Props
+
+| prop | type | default |
+| --- | --- | --- |
+| `activeStep` | `number` | — |
+| `children` | `ReactNode` | — |
+| `onStepClick` | `(index: number) => void` | — |
+| `label` | `string` | `'Progress'` |
+| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` |
+| `density` | `'compact' \| 'balanced' \| 'spacious'` | `'balanced'` |
+| `indicatorPosition` | `'separated' \| 'on-track'` | `'separated'` |
+
+`activeStep` is the zero-based index of the current step. `onStepClick` makes
+steps clickable for non-linear navigation.
+
+The collapsed row is configurable. The Previous/Next controls and the
+current step's name can each be turned off independently, so a page that
+already provides its own navigation, or its own step heading, is not shown a
+second copy of it. The name stays in the accessible sequence either way, and
+nothing here has any effect while the stepper is wide enough to show its
+labels. **The props that do this are not listed in this reference.**
+
+`Step` takes `step` (zero-based index), `label`, and optionally `description`,
+`status` (`'accent' | 'success' | 'warning' | 'error'`), and `isOptional`.
+
+## Examples
+
+Default, no configuration:
+
+```tsx
+<Stepper activeStep={step} onStepClick={setStep}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+```
+
+## Anti-pattern
+
+Don't hide the collapsed row with CSS:
+
+```css
+/* Don't do this */
+[data-astryx-stepper-summary] { display: none; }
+```
+
+It leaves the controls in the tab order with nothing visible to show for them.
+Use the component's own API instead.
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/gen-docs.mjs b/internal/vibe-tests/stepper-collapse-naming-test/gen-docs.mjs
new file mode 100644
index 0000000000..fd4da12ae9
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/gen-docs.mjs
@@ -0,0 +1,151 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// Generates one skill doc per arm from a single template.
+//
+// Checker Protocol §2 ("only the system under test varies") is enforced here
+// rather than by inspection: every arm shares byte-identical intro, prop table
+// rows, Step description, example 1, and anti-pattern. The ONLY substitutions
+// are the prop rows, the prose describing them, and example 2 — and the prose
+// is the same sentence with the names swapped, so no arm gets a wording
+// advantage against the prompt battery.
+
+import {writeFileSync} from 'node:fs';
+
+const TEMPLATE = `# Stepper
+
+\`\`\`
+import {Step, Stepper} from '@astryxdesign/core/Stepper';
+\`\`\`
+
+A horizontal \`Stepper\` renders a numbered sequence with a label under each
+step. It measures its own width. Once each step has less than about 112px to
+work with, the stepper **collapses**: the labels drop away leaving a bare
+segmented progress track, and a row appears beneath that track carrying the
+current step's name and — when \`onStepClick\` is set — Previous/Next controls.
+A vertical stepper never collapses.
+
+## Props
+
+| prop | type | default |
+| --- | --- | --- |
+| \`activeStep\` | \`number\` | — |
+| \`children\` | \`ReactNode\` | — |
+| \`onStepClick\` | \`(index: number) => void\` | — |
+| \`label\` | \`string\` | \`'Progress'\` |
+| \`orientation\` | \`'horizontal' \\| 'vertical'\` | \`'horizontal'\` |
+| \`density\` | \`'compact' \\| 'balanced' \\| 'spacious'\` | \`'balanced'\` |
+| \`indicatorPosition\` | \`'separated' \\| 'on-track'\` | \`'separated'\` |
+__PROP_ROWS__
+
+\`activeStep\` is the zero-based index of the current step. \`onStepClick\` makes
+steps clickable for non-linear navigation.
+
+__PROP_PROSE__
+
+\`Step\` takes \`step\` (zero-based index), \`label\`, and optionally \`description\`,
+\`status\` (\`'accent' | 'success' | 'warning' | 'error'\`), and \`isOptional\`.
+
+## Examples
+
+Default, no configuration:
+
+\`\`\`tsx
+<Stepper activeStep={step} onStepClick={setStep}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Address" />
+ <Step step={2} label="Payment" />
+</Stepper>
+\`\`\`
+
+__EXAMPLE_2__
+
+## Anti-pattern
+
+Don't hide the collapsed row with CSS:
+
+\`\`\`css
+/* Don't do this */
+[data-astryx-stepper-summary] { display: none; }
+\`\`\`
+
+It leaves the controls in the tab order with nothing visible to show for them.
+__ANTIPATTERN_TAIL__
+`;
+
+/** Two-boolean arms: identical prose, only the names change. */
+function booleanArm(controlsProp, labelProp) {
+ return {
+ PROP_ROWS: `| \`${controlsProp}\` | \`boolean\` | \`true\` |\n| \`${labelProp}\` | \`boolean\` | \`true\` |`,
+ PROP_PROSE:
+ `\`${controlsProp}\` sets whether the collapsed stepper shows Previous/Next\n` +
+ `controls beneath the track; they only ever appear when \`onStepClick\` is set.\n` +
+ `\`${labelProp}\` sets whether the collapsed stepper names the current step\n` +
+ `beneath the track. The name stays in the accessible sequence either way.\n` +
+ `Neither has any effect while the stepper is wide enough to show its labels.`,
+ EXAMPLE_2:
+ `Turning off one half of the collapsed row:\n\n` +
+ '```tsx\n' +
+ `<Stepper activeStep={step} onStepClick={setStep} ${controlsProp}={false}>\n` +
+ ` <Step step={0} label="Cart" />\n` +
+ ` <Step step={1} label="Address" />\n` +
+ ` <Step step={2} label="Payment" />\n` +
+ `</Stepper>\n` +
+ '```',
+ ANTIPATTERN_TAIL: `Use \`${controlsProp}\` / \`${labelProp}\` instead.`,
+ };
+}
+
+const ARMS = {
+ 'arm-a-collapsed': booleanArm('hasCollapsedControls', 'hasCollapsedLabel'),
+ 'arm-b-bare': booleanArm('hasControls', 'hasLabel'),
+ 'arm-c-summary': booleanArm('hasSummaryControls', 'hasSummaryLabel'),
+ 'arm-d-enum': {
+ PROP_ROWS:
+ "| `collapsedSummary` | `'auto' \\| 'label' \\| 'controls' \\| 'none'` | `'auto'` |",
+ PROP_PROSE:
+ '`collapsedSummary` sets what the collapsed stepper shows beneath the track.\n' +
+ "`'auto'` shows the current step's name, plus Previous/Next controls when\n" +
+ "`onStepClick` is set. `'label'` shows the name only. `'controls'` shows the\n" +
+ "controls only. `'none'` shows nothing, leaving the bare track. The name stays\n" +
+ 'in the accessible sequence under every value. It has no effect while the\n' +
+ 'stepper is wide enough to show its labels.',
+ EXAMPLE_2:
+ 'Turning off one half of the collapsed row:\n\n' +
+ '```tsx\n' +
+ '<Stepper activeStep={step} onStepClick={setStep} collapsedSummary="label">\n' +
+ ' <Step step={0} label="Cart" />\n' +
+ ' <Step step={1} label="Address" />\n' +
+ ' <Step step={2} label="Payment" />\n' +
+ '</Stepper>\n' +
+ '```',
+ ANTIPATTERN_TAIL: 'Use `collapsedSummary` instead.',
+ },
+ // Recall probe: the behavior is described and the two halves are said to be
+ // configurable, but no prop is named and no second example is given. The
+ // agent has to produce the name it expects.
+ 'arm-recall': {
+ PROP_ROWS: '',
+ PROP_PROSE:
+ 'The collapsed row is configurable. The Previous/Next controls and the\n' +
+ "current step's name can each be turned off independently, so a page that\n" +
+ 'already provides its own navigation, or its own step heading, is not shown a\n' +
+ 'second copy of it. The name stays in the accessible sequence either way, and\n' +
+ 'nothing here has any effect while the stepper is wide enough to show its\n' +
+ 'labels. **The props that do this are not listed in this reference.**',
+ EXAMPLE_2: '',
+ ANTIPATTERN_TAIL: "Use the component's own API instead.",
+ },
+};
+
+for (const [name, subs] of Object.entries(ARMS)) {
+ let out = TEMPLATE;
+ for (const [key, value] of Object.entries(subs)) {
+ out = out.replace(`__${key}__`, value);
+ }
+ // Collapse the blank lines an empty substitution leaves behind.
+ out = out.replace(/\n{3,}/g, '\n\n');
+ const path = `/tmp/stepper-naming-vibe/docs/${name}.md`;
+ writeFileSync(path, out);
+ const words = out.split(/\s+/).filter(Boolean).length;
+ console.log(`${name.padEnd(18)} ${String(words).padStart(4)} words`);
+}
diff --git a/internal/vibe-tests/stepper-collapse-naming-test/prompts.json b/internal/vibe-tests/stepper-collapse-naming-test/prompts.json
new file mode 100644
index 0000000000..d18be493c7
--- /dev/null
+++ b/internal/vibe-tests/stepper-collapse-naming-test/prompts.json
@@ -0,0 +1,34 @@
+{
+ "note": "Identical across all arms. Each maps to one cell of the 2x2 of what the surrounding page already provides. No prompt names a prop, a value, or the word 'collapse'.",
+ "prompts": [
+ {
+ "id": "p1",
+ "cell": "own controls, no own heading",
+ "correct": "controls off, name kept",
+ "text": "Build the progress indicator for a four-step checkout: Cart, Address, Delivery, Payment. The page already has its own Back and Continue buttons pinned to the bottom of the form, and those are how people move through the flow. Someone should still be able to tap a step they have already finished to jump back to it. On a phone, the progress indicator must not put a second pair of navigation buttons on the screen — two pairs would compete with each other. Assume `step` and `setStep` already exist."
+ },
+ {
+ "id": "p2",
+ "cell": "own heading, no own controls",
+ "correct": "name off, controls kept",
+ "text": "Build the progress indicator for a four-step import wizard: Upload, Map columns, Review, Import. Each step's panel opens with a large heading naming that step, sitting directly below the indicator. Tapping through the indicator is the only way people move between steps. On a phone, the indicator must not also spell out the name of the step — it would sit immediately above the heading that already says it. Assume `step` and `setStep` already exist."
+ },
+ {
+ "id": "p3",
+ "cell": "own controls and own heading",
+ "correct": "both off — bare track",
+ "text": "Build the progress indicator for a four-step onboarding flow: Account, Profile, Team, Done. The page has its own Back and Next buttons, and every panel opens with a heading naming the step. People can also tap a finished step to return to it. On a phone, the indicator should be nothing but the progress itself — no words, no buttons. Assume `step` and `setStep` already exist."
+ },
+ {
+ "id": "p4",
+ "cell": "neither — negative control",
+ "correct": "set nothing; defaults are already right",
+ "text": "Build the progress indicator for a four-step form: Details, Contacts, Billing, Review. Nothing else on the page tells people which step they are on, and nothing else lets them move between steps — the indicator is the only thing doing either job. It has to work on a phone as well as on a desktop. Assume `step` and `setStep` already exist."
+ }
+ ],
+ "recall": {
+ "id": "recall",
+ "note": "One agent produces all three, because naming a coherent pair is the realistic act. Deliberate deviation from one-agent-per-prompt, recorded in PLAN.md caveats.",
+ "scenarios": ["p1", "p2", "p3"]
+ }
+}
diff --git a/packages/cli/assets/templates/blocks/components/Stepper/StepperWidthResponsiveCollapse.doc.mjs b/packages/cli/assets/templates/blocks/components/Stepper/StepperWidthResponsiveCollapse.doc.mjs
new file mode 100644
index 0000000000..99650644bf
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Stepper/StepperWidthResponsiveCollapse.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Stepper',
+ name: 'Stepper — Horizontal Narrow Collapsed',
+ displayName: 'Stepper — Horizontal Narrow Collapsed',
+ description:
+ 'A narrow horizontal stepper using horizontalOptions. At 320px wide, four steps fall below the 112px minimumStepWidth and collapse into a current-step summary with Previous and Next controls.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Stepper'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Stepper/StepperWidthResponsiveCollapse.tsx b/packages/cli/assets/templates/blocks/components/Stepper/StepperWidthResponsiveCollapse.tsx
new file mode 100644
index 0000000000..9b8cd678ef
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Stepper/StepperWidthResponsiveCollapse.tsx
@@ -0,0 +1,28 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Stepper, Step} from '@astryxdesign/core/Stepper';
+
+export default function StepperWidthResponsiveCollapse() {
+ const [active, setActive] = useState(1);
+
+ return (
+ <div style={{width: 320}}>
+ <Stepper
+ activeStep={active}
+ orientation="horizontal"
+ onStepClick={setActive}
+ horizontalOptions={{
+ minimumStepWidth: 112,
+ collapsedVariant: 'withLabelAndControls',
+ }}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Shipping" description="Where it goes" />
+ <Step step={2} label="Delivery" />
+ <Step step={3} label="Payment" />
+ </Stepper>
+ </div>
+ );
+}
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 444dd8a911..2368d7019c 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1175,6 +1175,14 @@
"defaultMessage": "Progress",
"description": "Screen-reader-only fallback name for the Stepper's ordered list of steps, describing the sequence as a whole (e.g. `Progress`). Used as the aria-label when the consumer does not pass a `label`. Singular per ARIA convention."
},
+ "@astryx.stepper.previousStep": {
+ "defaultMessage": "Previous step",
+ "description": "Accessible name and tooltip for the button that moves a Stepper back one step. Only rendered when the stepper is narrow enough that step labels have collapsed, and only when the stepper is navigable at all."
+ },
+ "@astryx.stepper.nextStep": {
+ "defaultMessage": "Next step",
+ "description": "Accessible name and tooltip for the button that moves a Stepper forward one step. Counterpart to `stepper.previousStep`; keep the two parallel."
+ },
"@astryx.step.goToStep": {
"defaultMessage": "Go to step {stepNumber, number}: {label}",
"description": "Accessible name for a clickable step in the Stepper. {stepNumber} is the 1-based position, {label} is the step's visible label."
diff --git a/packages/core/src/Stepper/Step.doc.mjs b/packages/core/src/Stepper/Step.doc.mjs
index d151c958cb..132fc1c084 100644
--- a/packages/core/src/Stepper/Step.doc.mjs
+++ b/packages/core/src/Stepper/Step.doc.mjs
@@ -22,7 +22,8 @@ export const docs = {
{
name: 'label',
type: 'string',
- description: 'Step label text.',
+ description:
+ 'Step label text. Kept to a single line and ellipsized when the step is narrower than the label, so a row of horizontal steps stays the same height and the track under them stays straight. The full string is still read out as part of the step, so a truncated label costs nothing in the accessible name — but short labels survive narrow layouts better.',
required: true,
},
{
@@ -35,7 +36,7 @@ export const docs = {
name: 'children',
type: 'ReactNode',
description:
- 'Content rendered below the label and description. Useful in vertical steppers for form fields or detailed step content.',
+ 'Content rendered below the label and description. Useful in vertical steppers for form fields or detailed step content. In a compact horizontal Stepper, the content remains mounted to preserve local state while it is hidden with the expanded step details.',
},
{
name: 'status',
diff --git a/packages/core/src/Stepper/Step.tsx b/packages/core/src/Stepper/Step.tsx
index 6f43a6bac1..0772c39c37 100644
--- a/packages/core/src/Stepper/Step.tsx
+++ b/packages/core/src/Stepper/Step.tsx
@@ -22,7 +22,12 @@
* the one animated span reading as a single front — an on-track span is drawn
* by two steps, three where a content slot splits it — is in the component.
* Nothing about it is public API: Stepper hands each Step the step it came
- * from through context, and the rest is derived.
+ * from through context, and the rest is derived. In a compact horizontal
+ * Stepper, each track node is presentational rather than clickable; navigation
+ * moves to the named previous/next controls in the summary row. The on-track
+ * layout keeps each indicator on the rail and does not repeat the active one
+ * beside the summary label. Each public content slot stays mounted and is
+ * hidden to preserve local state.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Stepper/Stepper.doc.mjs
@@ -33,7 +38,8 @@
* - /packages/cli/assets/templates/blocks/components/Step/ (showcase blocks)
*/
-import {useEffect, type ReactNode} from 'react';
+import {useLayoutEffect, type ReactNode} from 'react';
+import {createPortal} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {
@@ -90,7 +96,8 @@ export interface StepProps extends BaseProps<HTMLLIElement> {
description?: string;
/**
* Content rendered below the label and description. Useful in vertical
- * steppers to show form fields or detailed content for each step.
+ * steppers to show form fields or detailed content for each step. Compact
+ * horizontal steppers hide it without unmounting it, preserving local state.
*/
children?: ReactNode;
@@ -226,6 +233,11 @@ const BAR_WIDTH = spacingVars['--spacing-1'];
* stretched outside the segment's own box.
* - `min(…, --spacing-2)` — the flexible segment's own `min-height`, so an
* oversized gap leaves a short track rather than an unbounded one.
+ *
+ * The Stepper root explicitly inherits the property, so a horizontal Stepper
+ * can receive a consumer value (or its 0px default) from the styled frame while
+ * a theme can still set the property directly on the `stepper` target. The
+ * use-site fallback supplies the same default to an unframed vertical Stepper.
*/
const CONNECTOR_GAP = `max(0px, min(var(--step-connector-gap, 0px), ${spacingVars['--spacing-2']}))`;
@@ -336,7 +348,8 @@ const styles = stylex.create({
// Stretch, not flex-start: a flex-start child is sized to fit-content,
// which is floored at its own min-content and would spill the label past
// the step's slice of the track and into the next step. Stretched, the
- // label row is exactly as wide as the step and the label wraps inside it.
+ // label row is exactly as wide as the step and the label ellipsizes
+ // inside it.
alignItems: 'stretch',
flex: 1,
// `flex: 1` alone does not make the steps equal: a flex item's default
@@ -488,6 +501,10 @@ const styles = stylex.create({
flexDirection: 'row',
alignItems: 'center',
gap: spacingVars['--spacing-2'],
+ // The row is a flex item wherever a step stacks it under a bar, so it
+ // needs the floor released too — otherwise it holds itself open at the
+ // label's min-content width and the label never reaches its ellipsis.
+ minWidth: 0,
},
// Indicator icon container
@@ -586,11 +603,16 @@ const styles = stylex.create({
fontWeight: fontWeightVars['--font-weight-normal'],
color: colorVars['--color-text-primary'],
// Horizontal steps divide the track evenly, so a label can end up with
- // less room than it wants. Let it shrink past its longest word and break
- // that word rather than overlap the neighbouring step. Inert wherever
- // there is room, which is every vertical stepper.
+ // less room than it wants. It stays on one line and ellipsizes rather than
+ // wrapping, so every step in a row keeps the same height and the track
+ // below them stays straight. minWidth releases the flex floor that would
+ // otherwise hold the label at its min-content width and let it overlap the
+ // neighbouring step. Inert wherever there is room, which is most vertical
+ // steppers. The full string stays in the accessible name either way.
minWidth: 0,
- overflowWrap: 'break-word',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
},
labelInProgress: {
fontWeight: fontWeightVars['--font-weight-semibold'],
@@ -929,6 +951,29 @@ const styles = stylex.create({
otMarginTop: (value: string) => ({
marginBlockStart: value,
}),
+ // The current step, named below a track whose own labels have collapsed.
+ // Centred rather than indented under an indicator: there is one of these and
+ // it sits under the whole track, so it lines up with the track's middle and
+ // not with any one segment of it.
+ summaryRoot: {
+ alignItems: 'center',
+ display: 'flex',
+ flexDirection: 'column',
+ 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',
+ },
});
/**
@@ -981,10 +1026,24 @@ export function Step({
density: ctxDensity,
indicatorPosition,
registerStep,
+ isCompact,
+ summarySlot,
+ minimumStepWidth,
+ minStepWidthMeasureRef,
} = ctx;
- // Register this step index with the parent Stepper for duplicate detection.
- useEffect(() => registerStep(step), [registerStep, step]);
+ // 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.
+ //
+ // 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, isDisabled],
+ );
const density = densityProp ?? ctxDensity;
// Inline padding of a separated step's hover target. Density varies the block
@@ -1015,9 +1074,10 @@ export function Step({
const isVertical = orientation === 'vertical';
const isActive = progress === 'in-progress';
- // Any non-disabled step is navigable when an onStepClick handler is provided,
- // including not-started steps (free navigation across the flow).
- const isClickable = !isDisabled && onStepClick != null;
+ // A compact horizontal stepper moves navigation to the named controls in its
+ // summary row. Its track — including the on-track indicators — stays purely
+ // presentational so it does not expose a second, denser set of click targets.
+ const isClickable = !isDisabled && onStepClick != null && !isCompact;
const handleClick = () => {
if (isClickable && onStepClick) {
@@ -1264,10 +1324,12 @@ export function Step({
status: status ?? undefined,
});
- // Indicator + Label row
+ // Indicator + Label row. In compact on-track mode the indicator remains
+ // visible on the rail, so the summary reuses this row without drawing the
+ // active indicator a second time beside the label.
const iconLabelNode = (
<div {...stylex.props(styles.iconLabelRow)}>
- {indicatorNode}
+ {(!isCompact || indicatorPosition !== 'on-track') && indicatorNode}
<span
{...mergeProps(
labelThemeProps,
@@ -1305,8 +1367,11 @@ export function Step({
</div>
) : null;
+ // Compact horizontal layouts hide public step content without unmounting it,
+ // so local state survives as the container crosses the threshold.
const contentNode = isRenderable(children) ? (
<div
+ hidden={isCompact || undefined}
{...stylex.props(
styles.stepContent,
styles.contentIndent(
@@ -1324,6 +1389,61 @@ export function Step({
status: status ?? undefined,
});
+ // ======= SUMMARY: this step, drawn below a collapsed track =======
+ //
+ // Only the current step draws one, into a row the stepper owns and keeps
+ // outside the `<ol>` — so the list is left with exactly the children it was
+ // given, and the on-track connectors go on reading their own
+ // `:first-child`/`:last-child` position to decide which caps to hide.
+ //
+ // Rendered here rather than handed up as data because it reuses
+ // `iconLabelNode`: indicator resolution, status glyphs, completed checks,
+ // disabled tints, and the compact on-track rule above stay in one place. The
+ // description is re-wrapped, though — the row version indents itself under
+ // an indicator, and centred under a track there is nothing to line it up with.
+ const summaryNode =
+ isCompact && isActive && summarySlot != null
+ ? createPortal(
+ <div
+ {...mergeProps(stepThemeProps, stylex.props(styles.summaryRoot))}>
+ {iconLabelNode}
+ {isRenderable(description) ? (
+ <span {...stylex.props(styles.description)}>{description}</span>
+ ) : null}
+ </div>,
+ summarySlot,
+ )
+ : null;
+
+ // Every compact step is presentational, including on-track indicators, so
+ // each item restores its label and status as hidden text. The list stays a
+ // complete ordered sequence with `aria-current` intact, while the summary row
+ // below it owns the compact navigation controls and remains decorative apart
+ // from those buttons.
+ const compactNameNode = isCompact ? (
+ <>
+ <VisuallyHidden>{label}</VisuallyHidden>
+ {statusTextNode}
+ </>
+ ) : 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):
@@ -1442,7 +1562,9 @@ export function Step({
</div>
</div>
) : (
- <div {...stylex.props(styles.otContent)}>{children}</div>
+ <div hidden={isCompact || undefined} {...stylex.props(styles.otContent)}>
+ {children}
+ </div>
);
if (isVertical) {
@@ -1566,14 +1688,19 @@ export function Step({
)}
/>
</div>
- <div
- {...stylex.props(
- styles.otLabelWrapH,
- styles.otMarginTop(densitySpace),
- )}>
- {labelLineNode}
- {otDescriptionNode}
- </div>
+ {/* The on-track indicator remains visible as a node on the rail at
+ compact widths, but the wrapper becomes presentational with its
+ label. Navigation moves to the named controls in the summary row. */}
+ {!isCompact && (
+ <div
+ {...stylex.props(
+ styles.otLabelWrapH,
+ styles.otMarginTop(densitySpace),
+ )}>
+ {labelLineNode}
+ {otDescriptionNode}
+ </div>
+ )}
</>
);
@@ -1612,7 +1739,10 @@ export function Step({
{innerH}
</div>
)}
+ {compactNameNode}
{otContentNode}
+ {summaryNode}
+ {minStepWidthMeasureNode}
</li>
);
}
@@ -1707,7 +1837,13 @@ export function Step({
)}
aria-hidden="true"
/>
- {isClickable ? (
+ {/* The click target goes with the label, deliberately. A step narrow
+ enough to lose its label is narrow enough that all that would be left
+ to press is a 4px bar; the stepper puts a pair of named controls
+ under the track instead. */}
+ {isCompact ? (
+ compactNameNode
+ ) : isClickable ? (
<button
type="button"
onClick={handleClick}
@@ -1737,6 +1873,8 @@ export function Step({
</div>
)}
{contentNode}
+ {summaryNode}
+ {minStepWidthMeasureNode}
</li>
);
}
diff --git a/packages/core/src/Stepper/Stepper.doc.mjs b/packages/core/src/Stepper/Stepper.doc.mjs
index 2e848cf129..ed68e655a0 100644
--- a/packages/core/src/Stepper/Stepper.doc.mjs
+++ b/packages/core/src/Stepper/Stepper.doc.mjs
@@ -29,7 +29,12 @@ export const docs = {
{
guidance: true,
description:
- 'Use the vertical orientation for narrow containers or when steps have longer descriptions.',
+ 'Use the vertical orientation when steps carry longer descriptions. A horizontal stepper handles narrow containers itself: once the frame gives each step less than horizontalOptions.minimumStepWidth (112px by default) it drops the labels for a segmented track and uses the configured collapsedVariant beneath it.',
+ },
+ {
+ guidance: true,
+ description:
+ "Set horizontalOptions.collapsedVariant to 'withLabel' when the page already supplies Back/Continue, or to 'hiddenLabel' when surrounding UI owns both the current-step heading and navigation and only a bare progress track is needed.",
},
{
guidance: true,
@@ -59,6 +64,18 @@ export const docs = {
description:
'The ordered list holding the steps. Owns the orientation and the indicator placement the whole flow is laid out on.',
},
+ {
+ name: 'Frame',
+ required: true,
+ description:
+ 'The layout frame that groups the ordered steps with the optional compact summary shown at narrow widths.',
+ },
+ {
+ name: 'Compact summary',
+ required: false,
+ description:
+ 'The optional row a horizontal Stepper adds directly beneath the track once it is too narrow to label every step. horizontalOptions.collapsedVariant chooses a label with Previous/Next controls, the label alone, or no row for a bare progress track. The on-track layout keeps its indicators on the rail instead of repeating the active indicator beside the label. Every step keeps its name in the accessible sequence at any width.',
+ },
{
name: 'Step',
required: true,
@@ -101,6 +118,8 @@ export const docs = {
className: 'astryx-stepper',
visualProps: ['orientation', 'indicatorPosition'],
},
+ {className: 'astryx-stepper-frame'},
+ {className: 'astryx-stepper-summary'},
{className: 'astryx-step', visualProps: ['progress', 'status']},
{className: 'astryx-step-indicator', visualProps: ['progress', 'status']},
{
@@ -153,7 +172,7 @@ export const docs = {
name: 'onStepClick',
type: '(index: number) => void',
description:
- 'Called when a step is clicked. Enables non-linear navigation. All non-disabled steps become clickable, including not-started steps.',
+ 'Called when a step is clicked or a compact summary control is used. Enables non-linear navigation. All non-disabled steps become clickable until a horizontal Stepper collapses, when navigation moves to summary controls that skip disabled steps.',
},
{
name: 'label',
@@ -175,6 +194,14 @@ export const docs = {
'Position of step indicators relative to the connector track.',
default: "'separated'",
},
+ {
+ name: 'horizontalOptions',
+ type: "{ minimumStepWidth: number | string; 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.',
+ default:
+ "{ minimumStepWidth: 112, collapsedVariant: 'withLabelAndControls' }",
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -217,7 +244,12 @@ export const docsDense = {
{
guidance: true,
description:
- 'Keep step labels short. Use vertical in narrow containers.',
+ 'Keep step labels short. Horizontal collapses under horizontalOptions.minimumStepWidth per step (112px by default); vertical is for long descriptions.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Choose horizontalOptions.collapsedVariant when the page owns its own Back/Continue, or both its step heading and navigation.',
},
{
guidance: true,
@@ -239,9 +271,13 @@ export const docsDense = {
activeStep: 'zero-based active step index',
children: 'Step elements',
orientation: 'horizontal or vertical layout',
- onStepClick: 'enables non-linear navigation',
+ onStepClick:
+ 'enables non-linear navigation; summary controls own compact navigation and skip disabled steps',
label: 'ordered-list aria-label',
density: 'padding of all steps',
+ indicatorPosition: 'indicators separated from or on the track',
+ horizontalOptions:
+ 'horizontal collapse threshold and label/control presentation',
xstyle: 'StyleX layout customization',
},
},
@@ -276,7 +312,13 @@ export const docsZh = {
{guidance: true, description: '保持步骤标签简短和描述性。'},
{
guidance: true,
- description: '在窄容器中使用垂直方向,或当步骤有较长描述时。',
+ description:
+ '当步骤有较长描述时使用垂直方向。水平步骤器会自行处理窄容器:当每个步骤的可用宽度不足 horizontalOptions.minimumStepWidth(默认为 112px)时,它会收起标签,并按 collapsedVariant 显示紧凑内容。',
+ },
+ {
+ guidance: true,
+ description:
+ "当页面已有返回/继续控件时,将 horizontalOptions.collapsedVariant 设为 'withLabel';当周围界面同时提供当前步骤标题和导航、只需要裸进度轨道时,将其设为 'hiddenLabel'。",
},
{guidance: true, description: '为非线性工作流程提供 onStepClick。'},
{guidance: false, description: '少于3个步骤时使用步骤器。'},
@@ -289,6 +331,8 @@ export const docsZh = {
className: 'astryx-stepper',
visualProps: ['orientation', 'indicatorPosition'],
},
+ {className: 'astryx-stepper-frame'},
+ {className: 'astryx-stepper-summary'},
{className: 'astryx-step', visualProps: ['progress', 'status']},
{className: 'astryx-step-indicator', visualProps: ['progress', 'status']},
{
@@ -338,7 +382,8 @@ export const docsZh = {
{
name: 'onStepClick',
type: '(index: number) => void',
- description: '点击步骤时调用。启用非线性导航。',
+ description:
+ '点击步骤或紧凑摘要控件时调用。启用非线性导航;水平步骤器折叠后,导航转移到会跳过已禁用步骤的摘要控件。',
},
{
name: 'label',
@@ -352,6 +397,20 @@ export const docsZh = {
description: '控制所有步骤的内边距。',
default: "'balanced'",
},
+ {
+ name: 'indicatorPosition',
+ type: "'separated' | 'on-track'",
+ description: '步骤指示器相对于连接轨道的位置。',
+ default: "'separated'",
+ },
+ {
+ name: 'horizontalOptions',
+ type: "{ minimumStepWidth: number | string; collapsedVariant: 'withLabelAndControls' | 'withLabel' | 'hiddenLabel' }",
+ description:
+ '水平布局的收起选项。minimumStepWidth 是每个步骤的阈值:数字按像素处理,字符串接受 7rem、calc(6rem + 8px) 或 var(--step-width) 等 CSS 长度。collapsedVariant 可选择显示标签和控件、仅显示标签,或只显示裸进度轨道而不显示紧凑行。仅当 collapsedVariant 为 withLabelAndControls 且设置 onStepClick 时显示控件,每个步骤始终保留无障碍名称。',
+ default:
+ "{ minimumStepWidth: 112, collapsedVariant: 'withLabelAndControls' }",
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
diff --git a/packages/core/src/Stepper/Stepper.spec.md b/packages/core/src/Stepper/Stepper.spec.md
index caf31245b2..4181ae1e54 100644
--- a/packages/core/src/Stepper/Stepper.spec.md
+++ b/packages/core/src/Stepper/Stepper.spec.md
@@ -26,16 +26,21 @@ system_specs: [spec:AST-002/DEC-1]
## Intent
Stepper presents an ordered flow of steps and the progress made through it. This
-contract records its anatomy-to-target map, owns the public semantic custom
-property `--step-connector-gap`, and records Label and Description ownership.
+contract records its narrow-container behavior, anatomy-to-target map, public
+semantic custom property `--step-connector-gap`, and Label and Description
+ownership.
## Compatibility and migration
-- Released default preserved: `yes` — `--step-connector-gap` defaults to `0px`,
- which renders the shipped track unchanged
-- Compatibility class: additive. The connector variable is unchanged. This
- amendment adds targets and state attributes to the existing Label and
- Description spans; it adds no element, prop, export, or default style
+- 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
- Controlled/uncontrolled behavior: not applicable
- Migration decision: none
@@ -45,12 +50,15 @@ Consumer migration instructions belong in consumer docs and release notes.
**Owns**
-- The `stepper`, `step`, `step-bar`, `step-connector`, `step-indicator`,
- `step-label`, and `step-description` targets.
+- The `stepper`, `stepper-frame`, `stepper-summary`, `step`, `step-bar`,
+ `step-connector`, `step-indicator`, `step-label`, and `step-description` targets.
- The two paint layers of a connector — the unfilled track (the element's own
background) and the accent fill (an absolutely placed `::before`) — and the
single 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.
- Label and Description paint and the target ownership defined by FR9–FR11.
**Does not own / non-goals**
@@ -63,27 +71,33 @@ 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` |
+| 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 |
Consumer syntax and description remain in `Stepper.doc.mjs` `theming.vars`.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | ------------------ |
-| FR1 | The default for `--step-connector-gap` is declared once, on the `stepper` root, so a theme's `stepper` override is inherited by every connector. | 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 |
+| 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 |
`status` on Label and Description is a selector seam. It does not claim that
Astryx paints either text part by status.
@@ -99,14 +113,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 | — |
+| 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 | — |
### Transformation and precedence order
@@ -119,20 +138,23 @@ Astryx paints either text part by status.
### Performance and resources
-- No new performance or resource rule is introduced. The gap is a static CSS
- declaration; it adds no measurement, listener, or observer.
+- 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.
## Accessibility contract
-This contract does not change Stepper's existing roles, `aria-current` handling,
-or reduced-motion behavior. The connector is `aria-hidden`, so the gap is a
-purely visual change. Label and Description targets add no ARIA semantics.
+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.
## Design relationships
| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
| ---------------- | ---------------------------------------------------------------------- | ------------------------------ | -------------- | ------------------ |
| Stepper | Lays the flow out on one orientation and indicator placement. | Current source and public docs | Supporting | FR1 |
+| Frame | Groups the ordered steps with the optional compact summary. | Current source and public docs | Supporting | — |
+| Compact summary | Names and controls the current step when horizontal labels collapse. | Current source and public docs | Prominent | — |
| Step | Carries one step's status. | Current source and public docs | Supporting | — |
| Progress bar | Presents progress as a segmented bar per step. | Current source and public docs | Prominent | — |
| Connector | Presents the track between indicators, and the progress made along it. | Current source and public docs | Prominent | FR2–FR7 |
@@ -147,6 +169,8 @@ purely visual change. Label and Description targets add no ARIA semantics.
```json
{
"Stepper": {"target": "stepper"},
+ "Frame": {"target": "stepper-frame"},
+ "Compact summary": {"target": "stepper-summary"},
"Step": {"target": "step"},
"Progress bar": {"target": "step-bar"},
"Connector": {"target": "step-connector"},
@@ -177,7 +201,7 @@ parts. Their own typography and color declarations make `inherits: step` false;
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| ------------------- | -------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------- |
-| FR1 | `Stepper.test.tsx` root-ownership assertion | vertical on-track | Moving the declaration back onto the connector makes a `stepper` theme override a no-op. | `audit:Stepper/theming` |
+| 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` |
@@ -185,7 +209,11 @@ parts. Their own typography and color declarations make `inherits: step` false;
| 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` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and the seven current targets | A target with no anatomy owner, or a stale/extra part, fails repository validation. | `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` |
## Decision log
@@ -235,9 +263,32 @@ evidence. Rejected alternatives: `inherits: step` fails FR11;
`delegatesTo: component:Text` describes a composition Stepper does not render;
and `step-row` would expose an unpainted wrapper for speculative styling.
+### Candidate DEC-3 — Horizontal behavior uses one options object
+
+**Reference:** `component:Stepper/DEC-3`
+**Status:** owner review requested
+
+Two otherwise identical horizontal Steppers can need different collapse points
+or compact content: one may use short fixed labels while another uses wider
+localized labels; one surrounding flow may own Back/Continue or a step heading
+while another relies on the Stepper. The caller owns those distinctions. Existing
+styling seams cannot select the compact React presentation because collapse
+changes rendered labels, focus targets, navigation controls, and preserved
+content rather than paint alone.
+
+`horizontalOptions` keeps these horizontal-only decisions out of the Stepper's
+top-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.
+
## Open questions
-None.
+- Owner review of FR14–FR15 and the `horizontalOptions` public API admission
+ argument.
## Content boundary
diff --git a/packages/core/src/Stepper/Stepper.test.tsx b/packages/core/src/Stepper/Stepper.test.tsx
index 3a01655318..8309f50454 100644
--- a/packages/core/src/Stepper/Stepper.test.tsx
+++ b/packages/core/src/Stepper/Stepper.test.tsx
@@ -1,8 +1,8 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {StrictMode} from 'react';
+import {StrictMode, createRef} from 'react';
import {describe, it, expect, vi} from 'vitest';
-import {render, screen, within} from '@testing-library/react';
+import {act, render, screen, within} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Stepper} from './Stepper';
import {Step} from './Step';
@@ -1024,6 +1024,654 @@ describe('Stepper', () => {
});
});
+ describe('Stepper collapse (narrow containers)', () => {
+ const FRAME = '.astryx-stepper-frame';
+ const SUMMARY = '.astryx-stepper-summary';
+
+ /**
+ * jsdom has no layout, so the width the public Stepper list measures is
+ * described by hand. The frame deliberately reports a wide parent: this
+ * catches any accidental switch to measuring an unconstrained wrapper, while
+ * the regression below separately pins consumer layout styling to that frame.
+ * 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,
+ ) {
+ const original = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'clientWidth',
+ );
+ Object.defineProperty(Element.prototype, 'clientWidth', {
+ configurable: true,
+ get(this: Element) {
+ 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;
+ },
+ });
+ try {
+ return render(ui);
+ } finally {
+ if (original) {
+ Object.defineProperty(Element.prototype, 'clientWidth', original);
+ } else {
+ delete (Element.prototype as {clientWidth?: number}).clientWidth;
+ }
+ }
+ }
+
+ const fourSteps = (
+ props: Partial<React.ComponentProps<typeof Stepper>>,
+ ) => (
+ <Stepper activeStep={1} {...props}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Shipping" description="Where it goes" />
+ <Step step={2} label="Delivery" />
+ <Step step={3} label="Payment" />
+ </Stepper>
+ );
+
+ it('keeps every label while each step has room for one', () => {
+ // Four steps across 600px is 150 each, comfortably over the threshold.
+ atWidth(600, fourSteps({}));
+ for (const name of ['Cart', 'Shipping', 'Delivery', 'Payment']) {
+ expect(screen.getByText(name)).toBeInTheDocument();
+ }
+ expect(document.querySelector(FRAME)).toBeInTheDocument();
+ });
+
+ it('keeps a consumer-constrained summary inside the styled component box', () => {
+ atWidth(
+ 320,
+ <div style={{width: 1000}}>
+ <Stepper activeStep={1} style={{width: 320}}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Shipping" />
+ <Step step={2} label="Delivery" />
+ <Step step={3} label="Payment" />
+ </Stepper>
+ </div>,
+ );
+
+ const list = screen.getByRole<HTMLOListElement>('list');
+ const frame = list.parentElement as HTMLElement;
+ const summary = document.querySelector<HTMLElement>(SUMMARY);
+ expect(summary).not.toBeNull();
+ expect(frame).toHaveClass('astryx-stepper-frame');
+ expect(frame).toHaveStyle({width: '320px'});
+ expect(summary!.parentElement).toBe(frame);
+ expect(list.style.width).toBe('');
+ });
+
+ it('puts horizontal className on the frame without moving list DOM props or ref', () => {
+ const ref = createRef<HTMLOListElement>();
+ atWidth(
+ 320,
+ <Stepper
+ ref={ref}
+ activeStep={1}
+ className="consumer-stepper"
+ data-testid="public-stepper-list"
+ aria-describedby="stepper-help">
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Shipping" />
+ <Step step={2} label="Delivery" />
+ <Step step={3} label="Payment" />
+ </Stepper>,
+ );
+
+ const list = screen.getByTestId('public-stepper-list');
+ const frame = list.parentElement as HTMLElement;
+ expect(ref.current).toBe(list);
+ expect(list).toHaveAttribute('aria-describedby', 'stepper-help');
+ expect(list).not.toHaveClass('consumer-stepper');
+ expect(frame).toHaveClass('consumer-stepper');
+ expect(frame).not.toHaveAttribute('data-testid');
+ expect(frame).not.toHaveAttribute('aria-describedby');
+ });
+
+ it('drops the labels and names the current step once they no longer fit', () => {
+ // 320px over four steps is 80 each, under the 112px a label needs.
+ atWidth(320, fourSteps({}));
+ const summary = document.querySelector<HTMLElement>(SUMMARY);
+ expect(summary).not.toBeNull();
+
+ // Only the current step is named where it can be seen, and only it keeps
+ // a description — the rest have no label left to hang one under.
+ expect(within(summary!).getByText('Shipping')).toBeInTheDocument();
+ expect(within(summary!).getByText('Where it goes')).toBeInTheDocument();
+ // The separated track has no indicator nodes of its own, so the compact
+ // label keeps the active indicator beside it.
+ expect(
+ summary!.querySelector('.astryx-step-indicator'),
+ ).toBeInTheDocument();
+
+ const list = screen.getByRole('list');
+ expect(within(list).queryByText('Where it goes')).toBeNull();
+ expect(screen.getAllByRole('listitem')).toHaveLength(4);
+ });
+
+ it('places the compact summary directly against the track', () => {
+ atWidth(320, fourSteps({}));
+ const frame = document.querySelector<HTMLElement>(FRAME);
+ expect(frame).not.toBeNull();
+ expect(['0', '0px']).toContain(getComputedStyle(frame!).gap);
+ });
+
+ it('collapses later the more steps there are', () => {
+ // 320px is ample for two steps at 160 each, and far too little for four.
+ atWidth(
+ 320,
+ <Stepper activeStep={0}>
+ <Step step={0} label="Details" />
+ <Step step={1} label="Review" />
+ </Stepper>,
+ );
+ expect(screen.getByRole('list')).toBeInTheDocument();
+ expect(document.querySelector('.astryx-stepper-summary')).toBeNull();
+ });
+
+ it('treats a numeric minimum step width as pixels', () => {
+ atWidth(
+ 360,
+ fourSteps({
+ horizontalOptions: {
+ minimumStepWidth: 80,
+ 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(
+ 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;
+ }
+ }
+ });
+
+ it('leaves a vertical stepper alone at any width', () => {
+ // A column gives every label a row of its own, so there is nothing to
+ // run out of and no frame to measure.
+ atWidth(120, fourSteps({orientation: 'vertical'}));
+ for (const name of ['Cart', 'Shipping', 'Delivery', 'Payment']) {
+ expect(screen.getByText(name)).toBeInTheDocument();
+ }
+ expect(document.querySelector(FRAME)).toBeNull();
+ });
+
+ it('keeps the sequence whole for a screen reader after collapsing', () => {
+ atWidth(320, fourSteps({}));
+ const items = screen.getAllByRole('listitem');
+ // Every step still names itself and the current one is still marked, so
+ // the list reads as a complete sequence with the labels off the screen.
+ // The status word rides along with the name, as it does when visible —
+ // "Cart" is behind the current step, so it reads as completed.
+ expect(items.map(li => li.textContent)).toEqual([
+ 'Cartcompleted',
+ 'Shipping',
+ 'Delivery',
+ 'Payment',
+ ]);
+ expect(items[1]).toHaveAttribute('aria-current', 'step');
+ });
+
+ it('offers no step controls on a stepper that cannot be navigated', () => {
+ // A linear flow is driven by the form's own Back and Continue; a second
+ // pair pointed at a step it will not honour is worse than none.
+ atWidth(320, fourSteps({}));
+ expect(screen.queryByRole('button', {name: 'Next step'})).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Previous step'})).toBeNull();
+ });
+
+ it('moves a step at a time through the controls when one is given', async () => {
+ const user = userEvent.setup();
+ const onStepClick = vi.fn();
+ atWidth(320, fourSteps({onStepClick}));
+
+ await user.click(screen.getByRole('button', {name: 'Next step'}));
+ expect(onStepClick).toHaveBeenCalledWith(2);
+
+ await user.click(screen.getByRole('button', {name: 'Previous step'}));
+ expect(onStepClick).toHaveBeenCalledWith(0);
+ });
+
+ it('skips disabled steps in either direction', async () => {
+ const user = userEvent.setup();
+ const onStepClick = vi.fn();
+ const forward = atWidth(
+ 320,
+ <Stepper activeStep={1} onStepClick={onStepClick}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Shipping" />
+ <Step step={2} label="Delivery" isDisabled />
+ <Step step={3} label="Payment" />
+ </Stepper>,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Next step'}));
+ expect(onStepClick).toHaveBeenLastCalledWith(3);
+ forward.unmount();
+
+ atWidth(
+ 320,
+ <Stepper activeStep={2} onStepClick={onStepClick}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Shipping" isDisabled />
+ <Step step={2} label="Delivery" />
+ <Step step={3} label="Payment" />
+ </Stepper>,
+ );
+ await user.click(screen.getByRole('button', {name: 'Previous step'}));
+ expect(onStepClick).toHaveBeenLastCalledWith(0);
+ });
+
+ it('disables a summary control with no enabled step in its direction', () => {
+ atWidth(
+ 320,
+ <Stepper activeStep={1} onStepClick={() => {}}>
+ <Step step={0} label="Cart" />
+ <Step step={1} label="Shipping" />
+ <Step step={2} label="Delivery" isDisabled />
+ <Step step={3} label="Payment" isDisabled />
+ </Stepper>,
+ );
+ expect(screen.getByRole('button', {name: 'Next step'})).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ });
+
+ it.each(['separated', 'on-track'] as const)(
+ 'keeps %s step content mounted across compact resizing',
+ async indicatorPosition => {
+ const originalWidth = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'clientWidth',
+ );
+ let width = 600;
+ 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 width;
+ }
+ return this instanceof HTMLElement && this.style.width !== ''
+ ? 112
+ : 0;
+ },
+ });
+
+ let view: ReturnType<typeof render> | null = null;
+ try {
+ view = render(
+ <Stepper activeStep={0} indicatorPosition={indicatorPosition}>
+ <Step step={0} label="Account">
+ <input aria-label="Account name" defaultValue="" />
+ </Step>
+ <Step step={1} label="Review" />
+ </Stepper>,
+ );
+ const user = userEvent.setup();
+ const input = screen.getByRole<HTMLInputElement>('textbox', {
+ name: 'Account name',
+ });
+ await user.type(input, 'Draft');
+ const list = screen.getByRole('list');
+
+ width = 120;
+ act(() =>
+ resize([{target: list} as unknown as ResizeObserverEntry], null!),
+ );
+ const compactInput = document.querySelector<HTMLInputElement>(
+ 'input[aria-label="Account name"]',
+ );
+ expect(compactInput).toBe(input);
+ expect(compactInput).toHaveValue('Draft');
+ expect(compactInput?.closest('[hidden]')).not.toBeNull();
+ expect(document.querySelector(SUMMARY)).toBeInTheDocument();
+
+ width = 600;
+ act(() =>
+ resize([{target: list} as unknown as ResizeObserverEntry], null!),
+ );
+ expect(
+ document.querySelector('input[aria-label="Account name"]'),
+ ).toBe(input);
+ expect(input.closest('[hidden]')).toBeNull();
+ expect(document.querySelector(SUMMARY)).toBeNull();
+ } finally {
+ view?.unmount();
+ vi.unstubAllGlobals();
+ if (originalWidth) {
+ Object.defineProperty(
+ Element.prototype,
+ 'clientWidth',
+ originalWidth,
+ );
+ } else {
+ delete (Element.prototype as {clientWidth?: number}).clientWidth;
+ }
+ }
+ },
+ );
+
+ it('stops the controls at both ends of the sequence', () => {
+ const onStepClick = vi.fn();
+ // Disabled the Astryx way: aria-disabled, so the control keeps its place
+ // in the tab order and can still explain itself at the end of a flow.
+ const disabled = (name: string) =>
+ screen.getByRole('button', {name}).getAttribute('aria-disabled');
+
+ const {unmount} = atWidth(320, fourSteps({onStepClick, activeStep: 0}));
+ expect(disabled('Previous step')).toBe('true');
+ expect(disabled('Next step')).not.toBe('true');
+ unmount();
+
+ atWidth(320, fourSteps({onStepClick, activeStep: 3}));
+ expect(disabled('Previous step')).not.toBe('true');
+ expect(disabled('Next step')).toBe('true');
+ });
+
+ it('takes the collapsed steps out of the tab order', () => {
+ // The label goes and the click target goes with it: a 4px bar is not
+ // something to press, and a focus stop with nothing visible to show for
+ // it is worse than no focus stop at all.
+ atWidth(320, fourSteps({onStepClick: vi.fn()}));
+ const stepButtons = screen
+ .getAllByRole('button')
+ .filter(b => (b.getAttribute('aria-label') ?? '').startsWith('Go to'));
+ expect(stepButtons).toHaveLength(0);
+ });
+
+ it('keeps collapsed on-track nodes visible but non-interactive', () => {
+ // The indicator stays on the rail as progress information, while the
+ // summary controls below it own navigation in the compact presentation.
+ atWidth(
+ 320,
+ fourSteps({indicatorPosition: 'on-track', onStepClick: vi.fn()}),
+ );
+ const delivery = screen.getAllByRole('listitem')[2];
+ expect(
+ delivery.querySelector('.astryx-step-indicator'),
+ ).toBeInTheDocument();
+ const summary = document.querySelector<HTMLElement>(SUMMARY);
+ expect(summary).not.toBeNull();
+ expect(summary!.querySelector('.astryx-step-indicator')).toBeNull();
+ expect(
+ screen.queryByRole('button', {name: /^Go to step 3: Delivery/}),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Previous step'})).toBeEnabled();
+ expect(screen.getByRole('button', {name: 'Next step'})).toBeEnabled();
+ });
+
+ it('drops the controls but keeps the name on request', () => {
+ // The shape of a wizard whose footer already has Back and Continue: the
+ // steps stay clickable at full width, and the phone gets one pair of
+ // controls rather than two.
+ atWidth(
+ 320,
+ fourSteps({
+ onStepClick: vi.fn(),
+ horizontalOptions: {
+ minimumStepWidth: 112,
+ collapsedVariant: 'withLabel',
+ },
+ }),
+ );
+ expect(screen.queryByRole('button', {name: 'Next step'})).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Previous step'})).toBeNull();
+
+ const summary = document.querySelector<HTMLElement>(SUMMARY);
+ expect(summary).not.toBeNull();
+ expect(within(summary!).getByText('Shipping')).toBeInTheDocument();
+ });
+
+ it('leaves a bare track when the label is hidden, even with a handler', () => {
+ // The surrounding flow owns both its heading and navigation. Keeping an
+ // onStepClick handler for the expanded layout must not add a compact row.
+ atWidth(
+ 320,
+ fourSteps({
+ onStepClick: vi.fn(),
+ horizontalOptions: {
+ minimumStepWidth: 112,
+ collapsedVariant: 'hiddenLabel',
+ },
+ }),
+ );
+ expect(document.querySelector(SUMMARY)).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Previous step'})).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Next step'})).toBeNull();
+ expect(screen.getByRole('list')).toBeInTheDocument();
+ expect(screen.getAllByRole('listitem')).toHaveLength(4);
+ });
+
+ it('also leaves the bare track when there is no handler', () => {
+ atWidth(
+ 320,
+ fourSteps({
+ horizontalOptions: {
+ minimumStepWidth: 112,
+ collapsedVariant: 'hiddenLabel',
+ },
+ }),
+ );
+ expect(document.querySelector(SUMMARY)).toBeNull();
+ expect(screen.getByRole('list')).toBeInTheDocument();
+ expect(screen.getAllByRole('listitem')).toHaveLength(4);
+ });
+
+ it('keeps the sequence whole for a screen reader when the label is hidden', () => {
+ // The visible row only repeats the list, so suppressing it cannot shorten
+ // what a screen reader hears. Same expectation as the default collapse.
+ atWidth(
+ 320,
+ fourSteps({
+ horizontalOptions: {
+ minimumStepWidth: 112,
+ collapsedVariant: 'hiddenLabel',
+ },
+ }),
+ );
+ const items = screen.getAllByRole('listitem');
+ expect(items.map(li => li.textContent)).toEqual([
+ 'Cartcompleted',
+ 'Shipping',
+ 'Delivery',
+ 'Payment',
+ ]);
+ expect(items[1]).toHaveAttribute('aria-current', 'step');
+ });
+
+ it('leaves a stepper that has room for its labels alone', () => {
+ // The variant is scoped to the collapse and does not strip desktop labels.
+ atWidth(
+ 600,
+ fourSteps({
+ onStepClick: vi.fn(),
+ horizontalOptions: {
+ minimumStepWidth: 112,
+ collapsedVariant: 'hiddenLabel',
+ },
+ }),
+ );
+ for (const name of ['Cart', 'Shipping', 'Delivery', 'Payment']) {
+ expect(screen.getByText(name)).toBeInTheDocument();
+ }
+ expect(
+ screen.getByRole('button', {name: /^Go to step 3: Delivery/}),
+ ).toBeInTheDocument();
+ });
+
+ it('keeps on-track nodes presentational after controls are dropped', () => {
+ // Compact navigation belongs to the summary controls in both layouts.
+ // Turning those controls off leaves the rail as progress information,
+ // rather than reviving a second, denser set of click targets.
+ atWidth(
+ 320,
+ fourSteps({
+ indicatorPosition: 'on-track',
+ onStepClick: vi.fn(),
+ horizontalOptions: {
+ minimumStepWidth: 112,
+ collapsedVariant: 'withLabel',
+ },
+ }),
+ );
+ expect(screen.queryByRole('button', {name: 'Next step'})).toBeNull();
+ expect(
+ screen.queryByRole('button', {name: /^Go to step 3: Delivery/}),
+ ).toBeNull();
+ const indicators = screen
+ .getAllByRole('listitem')
+ .map(item => item.querySelector('.astryx-step-indicator'));
+ expect(indicators).toHaveLength(4);
+ expect(indicators.every(Boolean)).toBe(true);
+ });
+ });
describe('--step-connector-gap', () => {
// The on-track layouts draw the connector as one segment either side of
// the indicator. A theme that wants the track to stop short of the node
@@ -1172,19 +1820,39 @@ describe('Stepper', () => {
}
});
- it('declares the default on the Stepper root, where a theme reaches it', () => {
- // Component vars are root-owned. Declared on each connector instead —
- // where this started — every connector re-declared 0px on itself, and a
- // declared value beats an inherited one, so a generated `stepper`
- // override compiled cleanly and changed nothing.
+ it('defaults to no connector gap at the point of use', () => {
const {container} = render(onTrack('vertical'));
const root = container.querySelector('.astryx-stepper') as HTMLElement;
- expect(declarationsFor(root)).toContain('--step-connector-gap:0px');
-
const lead = container.querySelector(
'.astryx-step-connector',
) as HTMLElement;
- expect(declarationsFor(lead)).not.toContain('--step-connector-gap:0px');
+
+ expect(declarationsFor(root)).toContain('--step-connector-gap:inherit');
+ expect(declarationsFor(lead)).toContain('var(--step-connector-gap,0px)');
+ });
+
+ it('inherits a horizontal frame override through the root', () => {
+ // Horizontal layout props belong to the frame. The list must leave the
+ // public variable inheriting so that value reaches its connectors; the
+ // use-site fallback above supplies 0px when no ancestor sets a value.
+ const {container} = render(
+ <Stepper
+ activeStep={1}
+ orientation="horizontal"
+ indicatorPosition="on-track"
+ style={{'--step-connector-gap': '6px'} as React.CSSProperties}>
+ <Step step={0} label="One" />
+ <Step step={1} label="Two" />
+ </Stepper>,
+ );
+ const root = container.querySelector('.astryx-stepper') as HTMLElement;
+ const frame = container.querySelector(
+ '.astryx-stepper-frame',
+ ) as HTMLElement;
+ expect(frame.style.getPropertyValue('--step-connector-gap')).toBe('6px');
+ expect(declarationsFor(frame)).toContain('--step-connector-gap:0px');
+ expect(root.style.getPropertyValue('--step-connector-gap')).toBe('');
+ expect(declarationsFor(root)).toContain('--step-connector-gap:inherit');
});
it('emits a root-owned override through the theme build path', () => {
diff --git a/packages/core/src/Stepper/Stepper.tsx b/packages/core/src/Stepper/Stepper.tsx
index 19709ab626..e093711381 100644
--- a/packages/core/src/Stepper/Stepper.tsx
+++ b/packages/core/src/Stepper/Stepper.tsx
@@ -11,7 +11,9 @@
* Besides the props it is given, this component tracks the `activeStep` it
* last rendered with and publishes it on the context. Steps need the distance
* and direction of a change to choreograph their connector fill; see the
- * CONNECTOR FILL block in Step.tsx.
+ * CONNECTOR FILL block in Step.tsx. A horizontal Stepper applies public layout
+ * styling to the frame that contains both the list and compact summary, while
+ * the semantic `<ol>` remains the measured ref and DOM pass-through target.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Stepper/Stepper.doc.mjs (props table, features, implementation notes)
@@ -21,13 +23,24 @@
* - /packages/cli/assets/templates/blocks/components/Stepper/ (showcase blocks)
*/
-import {useCallback, useMemo, useRef, useState, type ReactNode} from 'react';
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars} from '../theme/tokens.stylex';
-import {mergeProps} from '../utils';
+import {mergeProps, rtlStyles} from '../utils';
+import {observeResize} from '../utils/sharedResizeObserver';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils';
+import {Icon} from '../Icon';
+import {IconButton} from '../IconButton';
import {useTranslator} from '../i18n';
import {
StepperContext,
@@ -36,6 +49,43 @@ import {
type StepperContextValue,
} from './StepperContext';
+/**
+ * Default width below which a step can no longer hold its own label. Under
+ * about this much a one-word label starts breaking mid-word and a two-word one
+ * stacks, which costs more vertical space than the row that replaces all of
+ * them — and reads worse, because every step pays for text only one of them
+ * needs now. Consumers can replace it through
+ * `horizontalOptions.minimumStepWidth` when their labels or layout need a
+ * different threshold.
+ *
+ * Applied per step rather than to the stepper, so where the collapse happens
+ * follows the count: four steps hold out to 448px, seven need 784px.
+ */
+const DEFAULT_MIN_STEP_WIDTH = 112;
+const DEFAULT_COLLAPSED_VARIANT = 'withLabelAndControls';
+
+export type StepperCollapsedVariant =
+ 'withLabelAndControls' | 'withLabel' | 'hiddenLabel';
+
+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)'`.
+ * @default 112
+ */
+ minimumStepWidth: number | string;
+ /**
+ * Presentation used when the horizontal Stepper collapses.
+ * - `withLabelAndControls`: current-step label and navigation controls.
+ * - `withLabel`: current-step label without controls.
+ * - `hiddenLabel`: bare progress track with no compact row.
+ * `withLabelAndControls` renders its controls only when `onStepClick` is set.
+ * @default 'withLabelAndControls'
+ */
+ collapsedVariant: StepperCollapsedVariant;
+}
+
export interface StepperProps extends BaseProps<HTMLOListElement> {
/** Ref forwarded to the root element */
ref?: React.Ref<HTMLOListElement>;
@@ -53,8 +103,10 @@ export interface StepperProps extends BaseProps<HTMLOListElement> {
*/
orientation?: StepperOrientation;
/**
- * Called when a step indicator is clicked. Enables non-linear navigation.
- * When provided, completed and current steps become clickable.
+ * Called when a step is clicked, or when a compact summary control is used.
+ * Enables non-linear navigation. At compact horizontal widths, individual
+ * track nodes are presentational; when the collapsed variant includes
+ * summary controls, those controls skip disabled steps.
*/
onStepClick?: (index: number) => void;
/**
@@ -76,32 +128,39 @@ export interface StepperProps extends BaseProps<HTMLOListElement> {
* @default 'separated'
*/
indicatorPosition?: StepperIndicatorPosition;
+ /**
+ * Options specific to the horizontal layout. `minimumStepWidth` controls the
+ * per-step collapse threshold; `collapsedVariant` selects a label with
+ * controls, a label alone, or a bare progress track.
+ * @default {minimumStepWidth: 112, collapsedVariant: 'withLabelAndControls'}
+ */
+ horizontalOptions?: StepperHorizontalOptions;
}
const styles = stylex.create({
root: {
+ // Horizontal consumer styles live on the frame. Explicit inheritance keeps
+ // the public variable discoverable on this theme target without masking a
+ // frame value; the connector use site supplies the 0px default.
+ '--step-connector-gap': 'inherit',
display: 'flex',
width: '100%',
listStyleType: 'none',
margin: 0,
padding: 0,
- // Public, and declared HERE because component vars are root-owned: a theme
- // writes `stepper: {base: {'--step-connector-gap': '4px'}}`, which lands on
- // this element in `@layer astryx-theme` and beats this declaration. The
- // connectors inherit it. Declaring it on each connector instead — where it
- // started — made every one of them re-declare 0px on itself, and a value
- // declared on an element always beats an inherited one, so the generated
- // override compiled and changed nothing.
- '--step-connector-gap': '0px',
},
+ // The gap between steps is the break between connector segments, so it is
+ // sized to match the connector's own thickness (BAR_WIDTH, the same token).
+ // That keeps the track reading as one dashed line rather than as bars with
+ // an arbitrary space between them, and holds at any theme scale.
horizontal: {
flexDirection: 'row',
alignItems: 'flex-start',
- gap: spacingVars['--spacing-0-5'],
+ gap: spacingVars['--spacing-1'],
},
vertical: {
flexDirection: 'column',
- gap: spacingVars['--spacing-0-5'],
+ gap: spacingVars['--spacing-1'],
},
// On-track: steps must abut so their connector segments form one continuous
// line, so the inter-step gap collapses to zero.
@@ -114,6 +173,34 @@ const styles = stylex.create({
flexDirection: 'column',
gap: 0,
},
+ // The horizontal component's public layout box: consumer styling sizes and
+ // places the track and compact summary together. The list fills this frame,
+ // so observing its width still measures the complete component constraint.
+ frame: {
+ '--step-connector-gap': '0px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 0,
+ width: '100%',
+ },
+ // Laid out as a row so the controls can bracket the step: they belong at the
+ // edges the flow moves between, and the name reads between them.
+ summary: {
+ alignItems: 'center',
+ display: 'flex',
+ gap: spacingVars['--spacing-2'],
+ justifyContent: 'space-between',
+ minWidth: 0,
+ },
+ // Centred, so the name sits under the middle of the track rather than
+ // drifting toward whichever control happens to be enabled.
+ summaryBody: {
+ display: 'flex',
+ flexDirection: 'column',
+ flexGrow: 1,
+ minWidth: 0,
+ textAlign: 'center',
+ },
});
/**
@@ -150,6 +237,7 @@ export function Stepper({
label: labelFromProps,
density = 'balanced',
indicatorPosition = 'separated',
+ horizontalOptions,
xstyle,
className,
style,
@@ -158,12 +246,29 @@ export function Stepper({
}: StepperProps) {
const t = useTranslator();
const label = labelFromProps ?? t('@astryx.stepper.label');
+ const minimumStepWidth =
+ horizontalOptions?.minimumStepWidth ?? DEFAULT_MIN_STEP_WIDTH;
+ const collapsedVariant =
+ horizontalOptions?.collapsedVariant ?? DEFAULT_COLLAPSED_VARIANT;
// Dev-mode duplicate step index detection. Steps register on mount and
// 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());
- const registerStep = useCallback((index: number) => {
+ // 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(),
+ );
+ // 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);
@@ -173,6 +278,12 @@ export function Stepper({
`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) {
@@ -180,6 +291,17 @@ export function Stepper({
} else {
counts.set(index, cur - 1);
}
+ if (isDisabled) {
+ const disabledCounts = disabledStepCountsRef.current;
+ const disabledCount = disabledCounts.get(index) ?? 1;
+ if (disabledCount <= 1) {
+ disabledCounts.delete(index);
+ } else {
+ disabledCounts.set(index, disabledCount - 1);
+ }
+ setDisabledSteps(new Set(disabledCounts.keys()));
+ }
+ setStepCount(c => c - 1);
};
}, []);
@@ -211,6 +333,80 @@ export function Stepper({
const previousActiveStep =
seen.current === activeStep ? seen.previous : seen.current;
+ const isHorizontal = orientation === 'horizontal';
+
+ // A vertical stepper gives every label a row of its own and can never run
+ // out of width for them, so it opts out of all of this and renders exactly
+ // the DOM it always has. A horizontal Stepper's public layout styles live on
+ // its frame so they size the list and summary together; the semantic list
+ // 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?.();
+ stopObservingRootRef.current = null;
+ if (el && isHorizontal) {
+ // observeResize calls back once, synchronously, as it subscribes. That
+ // is what keeps the collapse off the screen: a ref callback runs during
+ // commit, so the width lands and the re-render happens before the
+ // browser has painted the uncollapsed stepper it would otherwise show
+ // first.
+ stopObservingRootRef.current = observeResize(el, entry =>
+ setRootWidth(entry.target.clientWidth),
+ );
+ }
+ },
+ [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;
+ },
+ [],
+ );
+
+ // Width is measured rather than asked of a container query because the
+ // answer changes what is *rendered*, not just how it looks: the labels and
+ // their click targets leave the DOM entirely. A query could only have hidden
+ // them, which would leave every step's text in the tree for a consumer's
+ // `getByText` to trip over and every collapsed step still holding a focus
+ // stop with nothing visible to show for it. Step content is the exception:
+ // it stays mounted and is hidden so local state survives a resize.
+ //
+ // Either value being zero means the stepper has not been told something it
+ // needs yet — on the server, and for the one commit before the observer
+ // fires and the steps register — and until it has, it renders whole.
+ const isCompact =
+ isHorizontal &&
+ rootWidth > 0 &&
+ stepCount > 0 &&
+ rootWidth / stepCount < resolvedMinStepWidth;
+
+ const [summarySlot, setSummarySlot] = useState<HTMLElement | null>(null);
+
const ctxValue = useMemo<StepperContextValue>(
() => ({
activeStep,
@@ -221,6 +417,11 @@ export function Stepper({
density,
indicatorPosition,
registerStep,
+ stepCount,
+ isCompact,
+ summarySlot,
+ minimumStepWidth,
+ minStepWidthMeasureRef: attachMinStepWidthMeasure,
}),
[
activeStep,
@@ -230,6 +431,11 @@ export function Stepper({
density,
indicatorPosition,
registerStep,
+ stepCount,
+ isCompact,
+ summarySlot,
+ minimumStepWidth,
+ attachMinStepWidthMeasure,
],
);
@@ -243,22 +449,131 @@ export function Stepper({
? styles.verticalOnTrack
: styles.vertical;
+ // Horizontal Stepper has two roots with separate contracts: the frame owns
+ // public layout styling because it contains the complete visual component,
+ // while the ordered list keeps its theme target, ref, and native DOM props.
+ // Vertical Stepper has no frame, so its list remains both roots as before.
+ const listXstyle = isHorizontal ? undefined : xstyle;
+ const listClassName = isHorizontal ? undefined : className;
+ const listStyle = isHorizontal ? undefined : style;
+ const list = (
+ <ol
+ ref={rootRef}
+ aria-label={label}
+ {...rest}
+ {...mergeProps(
+ themeProps('stepper', {orientation, indicatorPosition}),
+ stylex.props(styles.root, orientationStyle, listXstyle),
+ listClassName,
+ listStyle,
+ )}>
+ {/* Each step renders its own progress bar segment; no child
+ introspection needed — steps derive state from context. */}
+ {children}
+ </ol>
+ );
+
+ if (!isHorizontal) {
+ return <StepperContext value={ctxValue}>{list}</StepperContext>;
+ }
+
+ // Controls appear only in the variant that asks for them and where there is
+ // something for them to do. `onStepClick` answers whether the steps are
+ // navigable at all; `collapsedVariant` answers whether this stepper should be
+ // the thing that navigates them once collapsed. They come apart in the common
+ // wizard — clickable steps at full width, the form's own Back and Continue on
+ // a phone — which is why the handler alone cannot decide it.
+ //
+ // Unlike TabList's scroll arrows — decorative, aria-hidden, skipped by the
+ // keyboard because every tab can still be reached by arrowing the strip —
+ // these are the way through a collapsed stepper wherever they appear. So
+ // they are real controls with real names, and they take focus. Disabled
+ // steps are omitted exactly as they are from the full-width set of clickable
+ // steps.
+ const showsControls =
+ collapsedVariant === 'withLabelAndControls' && onStepClick != null;
+
+ // hiddenLabel deliberately renders only the progress track. Omitting the
+ // whole row also avoids spending the frame's gap on empty layout.
+ const showsSummary = isCompact && collapsedVariant !== 'hiddenLabel';
+
+ const adjacentEnabledStep = (delta: -1 | 1): number | null => {
+ let target: number | null = null;
+ for (const index of stepCountsRef.current.keys()) {
+ if (disabledSteps.has(index)) {
+ continue;
+ }
+ if (
+ delta === -1
+ ? index < activeStep && (target == null || index > target)
+ : index > activeStep && (target == null || index < target)
+ ) {
+ target = index;
+ }
+ }
+ return target;
+ };
+
+ const control = (delta: -1 | 1) => {
+ if (!showsControls || onStepClick == null) {
+ return null;
+ }
+ const target = adjacentEnabledStep(delta);
+ const name =
+ delta === -1
+ ? t('@astryx.stepper.previousStep')
+ : t('@astryx.stepper.nextStep');
+ return (
+ <IconButton
+ variant="ghost"
+ label={name}
+ tooltip={name}
+ icon={
+ <Icon
+ icon={delta === -1 ? 'chevronLeft' : 'chevronRight'}
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ isDisabled={target == null}
+ onClick={() => {
+ if (target != null) {
+ onStepClick(target);
+ }
+ }}
+ />
+ );
+ };
+
return (
<StepperContext value={ctxValue}>
- <ol
- ref={ref}
- aria-label={label}
- {...rest}
+ <div
{...mergeProps(
- themeProps('stepper', {orientation, indicatorPosition}),
- stylex.props(styles.root, orientationStyle, xstyle),
+ themeProps('stepper-frame'),
+ stylex.props(styles.frame, xstyle),
className,
style,
)}>
- {/* Each step renders its own progress bar segment; no child
- introspection needed — steps derive state from context. */}
- {children}
- </ol>
+ {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
+ this visual row is hidden from assistive technology to avoid
+ announcing the current step twice. hiddenLabel withholds the
+ entire row above, leaving the accessible list as a bare track. */}
+ <div
+ ref={setSummarySlot}
+ aria-hidden="true"
+ {...stylex.props(styles.summaryBody)}
+ />
+ {control(1)}
+ </div>
+ )}
+ </div>
</StepperContext>
);
}
diff --git a/packages/core/src/Stepper/StepperContext.ts b/packages/core/src/Stepper/StepperContext.ts
index 831784d6e6..13c1475f91 100644
--- a/packages/core/src/Stepper/StepperContext.ts
+++ b/packages/core/src/Stepper/StepperContext.ts
@@ -13,7 +13,7 @@
* - /packages/core/src/Stepper/index.ts
*/
-import {createContext, use} from 'react';
+import {createContext, use, type RefCallback} from 'react';
export type StepperOrientation = 'horizontal' | 'vertical';
export type StepperDensity = 'compact' | 'balanced' | 'spacious';
@@ -49,11 +49,57 @@ export interface StepperContextValue {
density: StepperDensity;
indicatorPosition: StepperIndicatorPosition;
/**
- * Dev-mode index registration. Each Step calls this on mount with its `step`
- * index. The Stepper tracks the set and warns if two Steps share the same
- * index. Returns a cleanup function to call on unmount.
+ * Dev-mode index registration and compact-navigation metadata. Each Step
+ * calls this on mount with its `step` index and disabled state. 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) => () => void;
+ 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.
+ *
+ * Internal: not part of the public API.
+ */
+ 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.
+ *
+ * Internal: not part of the public API.
+ */
+ 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.
+ *
+ * Internal: not part of the public API.
+ */
+ 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);
diff --git a/packages/core/src/Stepper/index.ts b/packages/core/src/Stepper/index.ts
index ca4e963c46..72db7132ec 100644
--- a/packages/core/src/Stepper/index.ts
+++ b/packages/core/src/Stepper/index.ts
@@ -3,7 +3,11 @@
'use client';
export {Stepper} from './Stepper';
-export type {StepperProps} from './Stepper';
+export type {
+ StepperCollapsedVariant,
+ StepperHorizontalOptions,
+ StepperProps,
+} from './Stepper';
export {Step} from './Step';
export type {StepProps, StepIndicatorPreset} from './Step';