From 1811f107484969b27351924d2fd711d8de2ca842 Mon Sep 17 00:00:00 2001 From: itsprade Date: Tue, 10 Nov 2026 17:03:00 +0530 Subject: [PATCH 1/2] feat(stepper): show progress through a fixed sequence of steps Add Stepper for wizard steps, approval stages, quality gates and other fixed sequences. Each step has a status (complete, current, upcoming, skipped), an optional badge and an optional description, and the line between steps fills up to the furthest step reached. The current step gets aria-current="step"; the others announce their status in English or Japanese. It lays out horizontally or vertically. A horizontal Stepper scrolls sideways when its steps don't fit and, below 400px of container width, shows only its markers with "Step 2 of 4" and the current step's label. onStepClick makes completed steps clickable. The Stepper only displays progress; the page decides each step's status. The example app gets a Stepper showcase page. Refs tailor-inc/platform-planning#2178 Co-Authored-By: Claude Opus 5.5 --- .changeset/stepper-component.md | 17 + docs-manifest.json | 28 +- docs-src/components/stepper.docs.examples.tsx | 51 +++ docs-src/components/stepper.docs.outline.md | 89 +++++ .../patterns/form-wizard.docs.examples.tsx | 26 +- docs-src/patterns/form-wizard.docs.outline.md | 4 +- docs-src/skill/SKILL.template.md | 1 + docs/components/stepper.md | 143 +++++++ docs/patterns/form-wizard.md | 26 +- examples/vite-app/src/App.tsx | 1 + .../src/pages/showcase/stepper/page.tsx | 171 +++++++++ examples/vite-app/src/routes.generated.ts | 1 + ...components__stepper__stepper.test.tsx.snap | 5 + packages/core/src/components/stepper/i18n.ts | 22 ++ packages/core/src/components/stepper/index.ts | 2 + .../src/components/stepper/stepper.test.tsx | 254 +++++++++++++ .../core/src/components/stepper/stepper.tsx | 350 ++++++++++++++++++ packages/core/src/components/stepper/types.ts | 50 +++ packages/core/src/index.ts | 1 + 19 files changed, 1205 insertions(+), 37 deletions(-) create mode 100644 .changeset/stepper-component.md create mode 100644 docs-src/components/stepper.docs.examples.tsx create mode 100644 docs-src/components/stepper.docs.outline.md create mode 100644 docs/components/stepper.md create mode 100644 examples/vite-app/src/pages/showcase/stepper/page.tsx create mode 100644 packages/core/__snapshots__/src__components__stepper__stepper.test.tsx.snap create mode 100644 packages/core/src/components/stepper/i18n.ts create mode 100644 packages/core/src/components/stepper/index.ts create mode 100644 packages/core/src/components/stepper/stepper.test.tsx create mode 100644 packages/core/src/components/stepper/stepper.tsx create mode 100644 packages/core/src/components/stepper/types.ts diff --git a/.changeset/stepper-component.md b/.changeset/stepper-component.md new file mode 100644 index 000000000..ad4fa18ae --- /dev/null +++ b/.changeset/stepper-component.md @@ -0,0 +1,17 @@ +--- +"@tailor-platform/app-shell": minor +--- + +Add `Stepper` for showing progress through a fixed sequence of steps: the steps of a wizard form, the stages of an approval flow, the quality gates of a project. Each step has a `status` (`complete`, `current`, `upcoming` or `skipped`), an optional `badge` beside its label and an optional `description` under it, and the line between steps fills up to the furthest step reached. It lays out horizontally or vertically; a horizontal Stepper scrolls sideways when its steps don't fit and, below 400px of container width, shows only its markers with "Step 2 of 4" and the current step's label, and each marker names its step in a tooltip. `onStepClick` makes completed steps clickable, and step ids are typed so `onStepClick` receives your own id union. + +```tsx + +``` diff --git a/docs-manifest.json b/docs-manifest.json index 1d33a8320..2fd5b3b73 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -807,10 +807,10 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "fbc09ef9994494cb", + "outline": "6f44fa0ce14bc031", "snapshot": null, - "outputMd": "851afb4672da6673", - "examples": "157ff03dc999d3d3" + "outputMd": "e86dd12f9aaa196f", + "examples": "f0c771090062761d" } }, "global-header-layout": { @@ -1374,6 +1374,23 @@ "examples": "19131f441efe232f" } }, + "stepper": { + "slug": "stepper", + "kind": "code-backed", + "outline": "docs-src/components/stepper.docs.outline.md", + "output": "docs/components/stepper.md", + "examples": "docs-src/components/stepper.docs.examples.tsx", + "sources": ["packages/core/src/components/stepper/**"], + "claims": [], + "symbols": ["Stepper", "StepperProps", "StepperStep"], + "hashes": { + "typeSurface": "03575b3ae95ff031", + "outline": "620afc4168680aa7", + "snapshot": "62a67309416ceed7", + "outputMd": "dfd07cfec2f84d5b", + "examples": "9a0f9bf7c9b8fb95" + } + }, "styling-theming": { "slug": "styling-theming", "kind": "prose", @@ -1845,6 +1862,7 @@ "packages/core/skills/app-shell-patterns/references/components/sidebar-layout.md": "e50b2d649289d772", "packages/core/skills/app-shell-patterns/references/components/sidebar-section.md": "8ab89452180de4e1", "packages/core/skills/app-shell-patterns/references/components/spinner.md": "e05d94ba9c3d17da", + "packages/core/skills/app-shell-patterns/references/components/stepper.md": "dfd07cfec2f84d5b", "packages/core/skills/app-shell-patterns/references/components/table.md": "f85ec64ceb7f4acf", "packages/core/skills/app-shell-patterns/references/components/tabs.md": "30bb32e57fc78bd9", "packages/core/skills/app-shell-patterns/references/components/text.md": "24262ae6cb49a138", @@ -1884,7 +1902,7 @@ "packages/core/skills/app-shell-patterns/references/patterns/form-modal.md": "be00d1109761b7f1", "packages/core/skills/app-shell-patterns/references/patterns/form-sectioned.md": "d31cd3ae6ad0790c", "packages/core/skills/app-shell-patterns/references/patterns/form-single-page.md": "10a0f4d91a120752", - "packages/core/skills/app-shell-patterns/references/patterns/form-wizard.md": "851afb4672da6673", + "packages/core/skills/app-shell-patterns/references/patterns/form-wizard.md": "e86dd12f9aaa196f", "packages/core/skills/app-shell-patterns/references/patterns/i18n-labels.md": "d9f0851d9c98ecfe", "packages/core/skills/app-shell-patterns/references/patterns/interaction-confirm.md": "2db70f423c6fdf97", "packages/core/skills/app-shell-patterns/references/patterns/interaction-multi-select.md": "253fcea1c4e5a42c", @@ -1892,6 +1910,6 @@ "packages/core/skills/app-shell-patterns/references/patterns/list-dense-scan.md": "59c93617dc135033", "packages/core/skills/app-shell-patterns/references/pages/document-detail.md": "930db027a28bbe24", "packages/core/skills/app-shell-patterns/references/migrations.md": "fe8232d31b24aed0", - "packages/core/skills/app-shell-patterns/SKILL.md": "0e6c9be8c4ece7bc" + "packages/core/skills/app-shell-patterns/SKILL.md": "d1d9cfad4853edcf" } } diff --git a/docs-src/components/stepper.docs.examples.tsx b/docs-src/components/stepper.docs.examples.tsx new file mode 100644 index 000000000..b01f137c8 --- /dev/null +++ b/docs-src/components/stepper.docs.examples.tsx @@ -0,0 +1,51 @@ +import { Badge, Stepper } from "@tailor-platform/app-shell"; + +export function BasicUsage() { + return ( + + ); +} + +export function StageProgress() { + return ( + Next, + description: "Plan 18 Nov", + }, + { id: "qg5", label: "QG5", status: "upcoming", description: "Plan 9 Dec" }, + ]} + /> + ); +} + +export function Vertical() { + return ( + + ); +} diff --git a/docs-src/components/stepper.docs.outline.md b/docs-src/components/stepper.docs.outline.md new file mode 100644 index 000000000..cdc518e73 --- /dev/null +++ b/docs-src/components/stepper.docs.outline.md @@ -0,0 +1,89 @@ +--- +kind: code-backed +group: stepper +title: Stepper +description: Shows progress through a fixed sequence of steps — wizard steps, approval stages, quality gates +sources: + - packages/core/src/components/stepper/** +--- + +# Stepper + +`Stepper` shows how far something has progressed through a fixed sequence of steps: the steps of a [wizard form](../patterns/form-wizard.md), the stages of an approval flow, the quality gates of a project. Each step has a status, and the line between steps is filled up to the furthest step reached. + +It only displays progress. The page decides each step's status and what happens when a step is clicked. + +## Import + +```tsx +import { Stepper } from "@tailor-platform/app-shell"; +``` + +## Basic Usage + + + +## Props + +| Prop | Type | Default | Description | +| ------------- | ---------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| `steps` | `StepperStep[]` | - | The steps, in order | +| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | A row of steps, or a column for beside a form | +| `onStepClick` | `(id: Id) => void` | - | Makes completed steps clickable — for example to go back to an earlier wizard step | +| `aria-label` | `string` | "Progress" | Accessible name for the list of steps (the default is translated) | +| `className` | `string` | - | Additional CSS classes | +| `style` | `CSSProperties` | - | Inline styles | + +### `StepperStep` + +| Field | Type | Description | +| ------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `id` | `Id extends string` | Stable id, passed to `onStepClick` | +| `label` | `ReactNode` | Step name | +| `status` | `"complete" \| "current" \| "upcoming" \| "skipped"` | Where the step stands (below) | +| `badge` | `ReactNode` | Shown beside the label — for example a "Next" or "Overdue" `Badge` | +| `description` | `ReactNode` | Shown under the label — a short hint, or a few lines of values such as plan and actual dates | + +## Status + +| `status` | Marker | Use for | +| ------------ | ------------------------------ | -------------------------------------------- | +| `"complete"` | Filled, with a check | Steps that are done | +| `"current"` | Outlined in the primary colour | The step the user is on, or the next one due | +| `"upcoming"` | Outlined, muted | Steps not started | +| `"skipped"` | Dashed outline, muted | Steps that don't apply to this record | + +Mark at most one step `current`. It gets `aria-current="step"`, and screen readers hear the status of the others ("Completed", "Skipped", "Not started"). + +The line is filled up to the furthest step reached — the last step that is `complete` or `current`. A skipped step before it is filled through; one after it isn't. + +Step ids are typed: give `steps` a union of ids and `onStepClick` receives that union. + +```tsx +type StepId = "supplier" | "lines" | "review"; +const steps: StepperStep[] = [ + /* … */ +]; + + goTo(id)} />; // id: StepId +``` + +## Stage progress + +Badges and descriptions turn the Stepper into a stage tracker on a detail page: + + + +## Vertical + +A vertical Stepper suits a column beside a form, such as a wizard on a page: + + + +## Narrow containers + +A horizontal Stepper adapts to the width of its container, not the viewport: + +- When the steps don't fit side by side, the row scrolls sideways rather than squeezing the labels. +- Below 400px it shows only the markers and lines, with "Step 2 of 4" and the current step's label underneath. This is what a wizard needs in a dialog on a phone. +- Each marker then names its step in a tooltip on hover, and the marker of a completed step becomes the button that goes back to it, so keyboard users still have one visible place to focus. diff --git a/docs-src/patterns/form-wizard.docs.examples.tsx b/docs-src/patterns/form-wizard.docs.examples.tsx index 7235a9096..57e8431eb 100644 --- a/docs-src/patterns/form-wizard.docs.examples.tsx +++ b/docs-src/patterns/form-wizard.docs.examples.tsx @@ -1,6 +1,5 @@ import { useState } from "react"; import { - Badge, Button, Card, Field, @@ -8,6 +7,7 @@ import { Form, Layout, Select, + Stepper, } from "@tailor-platform/app-shell"; const OWNERS = ["Tanaka", "Sato", "Suzuki", "Yamada"]; @@ -60,20 +60,16 @@ export function FormWizard() { - - -
- {STEPS.map((label, i) => ( - - {i + 1}. {label} - - ))} -
-
-
+ {/* Statuses come from the current step; completed steps go back on click */} + ({ + id: String(i), + label, + status: i < step ? "complete" : i === step ? "current" : "upcoming", + }))} + onStepClick={(id) => setStep(Number(id))} + />
diff --git a/docs-src/patterns/form-wizard.docs.outline.md b/docs-src/patterns/form-wizard.docs.outline.md index 35083d61e..3d6f90c84 100644 --- a/docs-src/patterns/form-wizard.docs.outline.md +++ b/docs-src/patterns/form-wizard.docs.outline.md @@ -7,7 +7,7 @@ title: Wizard Form category: pattern subcategory: form description: Multi-stage create flow with 3-7 steps and per-step validation gates -requiredImports: [Layout, Card, Badge, Form, Fieldset, Field, Select, Button] +requiredImports: [Layout, Card, Stepper, Form, Fieldset, Field, Select, Button] tags: [form, wizard, multi-step, stepper, onboarding] do: - Multi-stage Create with 3-7 steps @@ -41,7 +41,7 @@ the upload → map → validate → confirm flow. Don't rebuild it here. - Max 7 steps — more than that causes user abandonment - Back-navigation must preserve prior step's input - Validation must be per-step — don't defer until final submit -- Step indicator collapses to "Step 2 of 4" label below 1024px +- Show the steps with `Stepper`; it collapses to "Step 2 of 4" when its container is narrower than 400px - One `` rendered per step, keyed by step index so it remounts cleanly - Accumulated values live in a `draft` state object above the `Form`; each step's fields read their initial value from it via `defaultValue` diff --git a/docs-src/skill/SKILL.template.md b/docs-src/skill/SKILL.template.md index f0bc48ffd..8b66a26cc 100644 --- a/docs-src/skill/SKILL.template.md +++ b/docs-src/skill/SKILL.template.md @@ -80,5 +80,6 @@ Full rationale in [`styling-theming`](references/concepts/styling-theming.md) - **Metric tiles always go in a `Grid`** (`columns={{ initial: 1, md: 2, xl: 4 }}`) — never one-per-row. - **Forms default to `form/modal`** — only build a routed full-page form when the design explicitly calls for one. - **Forms use AppShell `Form` + `Field`**, submitting via `onFormSubmit` — never a bare `` with `FormData`. `onFormSubmit` reads registered `Field.Root`s, so every control (dropdowns included) just needs a wrapping `Field.Root name="…"` — no `name` on the control, no `useState`. React Hook Form is optional, consumer-installed, and only warranted for cross-field validation, field arrays, or a Zod resolver. Details in [`Form`](references/components/form.md) and the `form/*` patterns. +- **Show progress through a fixed sequence of steps with `Stepper`** — wizard steps, approval stages, quality gates — not Badges or hand-built dots. Give each step a `status` (`complete`, `current`, `upcoming`, `skipped`) derived from your own state; it collapses to "Step 2 of 4" in narrow containers by itself. Details in [`Stepper`](references/components/stepper.md). - **Handle every state:** loading (skeleton), empty (labelled empty state), and error (inline + retry) — never ship only the happy path. - **Keep UI language consistent:** apply the chosen language to navigation, component text, accessibility labels, and feedback. Use the catalog's `useT()` for rendered strings and `labels.t()` for `LocalizedString` metadata; keep server codes and comparison values untranslated. See [`i18n/labels`](references/patterns/i18n-labels.md). diff --git a/docs/components/stepper.md b/docs/components/stepper.md new file mode 100644 index 000000000..c9c69a2bb --- /dev/null +++ b/docs/components/stepper.md @@ -0,0 +1,143 @@ +--- +title: Stepper +description: Shows progress through a fixed sequence of steps — wizard steps, approval stages, quality gates +--- + + + +# Stepper + +`Stepper` shows how far something has progressed through a fixed sequence of steps: the steps of a [wizard form](../patterns/form-wizard.md), the stages of an approval flow, the quality gates of a project. Each step has a status, and the line between steps is filled up to the furthest step reached. + +It only displays progress. The page decides each step's status and what happens when a step is clicked. + +## Import + +```tsx +import { Stepper } from "@tailor-platform/app-shell"; +``` + +## Basic Usage + + + +```tsx +function BasicUsage() { + return ( + + ); +} +``` + +## Props + +| Prop | Type | Default | Description | +| ------------- | ---------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| `steps` | `StepperStep[]` | - | The steps, in order | +| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | A row of steps, or a column for beside a form | +| `onStepClick` | `(id: Id) => void` | - | Makes completed steps clickable — for example to go back to an earlier wizard step | +| `aria-label` | `string` | "Progress" | Accessible name for the list of steps (the default is translated) | +| `className` | `string` | - | Additional CSS classes | +| `style` | `CSSProperties` | - | Inline styles | + +### `StepperStep` + +| Field | Type | Description | +| ------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `id` | `Id extends string` | Stable id, passed to `onStepClick` | +| `label` | `ReactNode` | Step name | +| `status` | `"complete" \| "current" \| "upcoming" \| "skipped"` | Where the step stands (below) | +| `badge` | `ReactNode` | Shown beside the label — for example a "Next" or "Overdue" `Badge` | +| `description` | `ReactNode` | Shown under the label — a short hint, or a few lines of values such as plan and actual dates | + +## Status + +| `status` | Marker | Use for | +| ------------ | ------------------------------ | -------------------------------------------- | +| `"complete"` | Filled, with a check | Steps that are done | +| `"current"` | Outlined in the primary colour | The step the user is on, or the next one due | +| `"upcoming"` | Outlined, muted | Steps not started | +| `"skipped"` | Dashed outline, muted | Steps that don't apply to this record | + +Mark at most one step `current`. It gets `aria-current="step"`, and screen readers hear the status of the others ("Completed", "Skipped", "Not started"). + +The line is filled up to the furthest step reached — the last step that is `complete` or `current`. A skipped step before it is filled through; one after it isn't. + +Step ids are typed: give `steps` a union of ids and `onStepClick` receives that union. + +```tsx +type StepId = "supplier" | "lines" | "review"; +const steps: StepperStep[] = [ + /* … */ +]; + + goTo(id)} />; // id: StepId +``` + +## Stage progress + +Badges and descriptions turn the Stepper into a stage tracker on a detail page: + + + +```tsx +function StageProgress() { + return ( + Next, + description: "Plan 18 Nov", + }, + { id: "qg5", label: "QG5", status: "upcoming", description: "Plan 9 Dec" }, + ]} + /> + ); +} +``` + +## Vertical + +A vertical Stepper suits a column beside a form, such as a wizard on a page: + + + +```tsx +function Vertical() { + return ( + + ); +} +``` + +## Narrow containers + +A horizontal Stepper adapts to the width of its container, not the viewport: + +- When the steps don't fit side by side, the row scrolls sideways rather than squeezing the labels. +- Below 400px it shows only the markers and lines, with "Step 2 of 4" and the current step's label underneath. This is what a wizard needs in a dialog on a phone. +- Each marker then names its step in a tooltip on hover, and the marker of a completed step becomes the button that goes back to it, so keyboard users still have one visible place to focus. diff --git a/docs/patterns/form-wizard.md b/docs/patterns/form-wizard.md index 653e009e8..fe3821c58 100644 --- a/docs/patterns/form-wizard.md +++ b/docs/patterns/form-wizard.md @@ -52,20 +52,16 @@ function FormWizard() { - - -
- {STEPS.map((label, i) => ( - - {i + 1}. {label} - - ))} -
-
-
+ {/* Statuses come from the current step; completed steps go back on click */} + ({ + id: String(i), + label, + status: i < step ? "complete" : i === step ? "current" : "upcoming", + }))} + onStepClick={(id) => setStep(Number(id))} + /> @@ -151,7 +147,7 @@ function FormWizard() { - Max 7 steps — more than that causes user abandonment - Back-navigation must preserve prior step's input - Validation must be per-step — don't defer until final submit -- Step indicator collapses to "Step 2 of 4" label below 1024px +- Show the steps with `Stepper`; it collapses to "Step 2 of 4" when its container is narrower than 400px - One `` rendered per step, keyed by step index so it remounts cleanly - Accumulated values live in a `draft` state object above the `Form`; each step's fields read their initial value from it via `defaultValue` diff --git a/examples/vite-app/src/App.tsx b/examples/vite-app/src/App.tsx index 72d0de124..53cf3aa3a 100644 --- a/examples/vite-app/src/App.tsx +++ b/examples/vite-app/src/App.tsx @@ -77,6 +77,7 @@ const AppInner = () => { + diff --git a/examples/vite-app/src/pages/showcase/stepper/page.tsx b/examples/vite-app/src/pages/showcase/stepper/page.tsx new file mode 100644 index 000000000..625b205e9 --- /dev/null +++ b/examples/vite-app/src/pages/showcase/stepper/page.tsx @@ -0,0 +1,171 @@ +import * as React from "react"; +import { + Badge, + Button, + Card, + Layout, + Stepper, + Text, + type AppShellPageProps, + type StepperStep, +} from "@tailor-platform/app-shell"; + +// Stepper showcase: progress through a fixed sequence of steps — wizard steps, +// approval stages, quality gates. + +// ✅ Reusable Component: Can be moved to components/ui/ (planned / actual / overdue lines) +function GateDates({ + planned, + actual, + overdue, +}: { + planned: string; + actual?: string; + overdue?: number; +}) { + return ( + + Plan {planned} + {actual != null && Done {actual}} + {overdue != null && {overdue} days over} + + ); +} + +// 🧪 Dummy Data: Replace with real data later +const QUALITY_GATES: StepperStep[] = [ + { + id: "qg1", + label: "QG1", + status: "complete", + description: , + }, + { + id: "qg2", + label: "QG2", + status: "complete", + description: , + }, + { id: "qg3", label: "QG3", status: "skipped", description: "Not required" }, + { + id: "qg4", + label: "QG4", + status: "current", + badge: Next, + description: , + }, + { id: "qg5", label: "QG5", status: "upcoming", description: }, + { id: "qg6", label: "QG6", status: "upcoming", description: }, + { id: "qg7", label: "QG7", status: "upcoming", description: }, +]; + +// 🧪 Dummy Data: Replace with real data later +const APPROVAL: StepperStep[] = [ + { id: "draft", label: "Draft", status: "complete", description: "Hanna Suzuki" }, + { id: "manager", label: "Manager", status: "complete", description: "Kenji Mori · 3 Nov" }, + { + id: "finance", + label: "Finance", + status: "current", + badge: Waiting 2 days, + description: "Priya Nair", + }, + { id: "issued", label: "Issued", status: "upcoming" }, +]; + +// 🧪 Dummy Data: Replace with real data later +const WIZARD_STEPS = ["Supplier", "Delivery", "Approval", "Review"]; + +// 🔽 Wizard steps — the page owns the current step; the Stepper only displays it +function WizardStepsDemo() { + const [current, setCurrent] = React.useState(1); + const steps: StepperStep[] = WIZARD_STEPS.map((label, i) => ({ + id: String(i), + label, + status: i < current ? "complete" : i === current ? "current" : "upcoming", + })); + return ( + + + + setCurrent(Number(id))} + /> +
+ + +
+
+
+ ); +} + +const StepperDemoPage = () => ( + + + + + Each step has a status — complete, current, upcoming or skipped — plus an optional badge and + a few lines underneath. A horizontal Stepper scrolls sideways when its steps don't fit; + below 400px of container width it shows only its markers and names the current step. + + + + + {/* 🔽 Stage progress on a detail page */} + + + + + + + +
+ + + + + + + {/* A narrow card: the same Stepper, collapsed to markers plus the current step */} + + + + + + +
+ + + + + + + +
+
+); + +StepperDemoPage.appShellPageProps = { + meta: { + title: "Stepper", + }, +} satisfies AppShellPageProps; + +export default StepperDemoPage; diff --git a/examples/vite-app/src/routes.generated.ts b/examples/vite-app/src/routes.generated.ts index 4b797fdd7..a1fdb697e 100644 --- a/examples/vite-app/src/routes.generated.ts +++ b/examples/vite-app/src/routes.generated.ts @@ -46,6 +46,7 @@ export type GeneratedRouteParams = { "/showcase/metric-card": {}; "/showcase/primitives": {}; "/showcase/spinner": {}; + "/showcase/stepper": {}; "/showcase/timeline": {}; "/showcase/toolbar": {}; "/showcase/tree": {}; diff --git a/packages/core/__snapshots__/src__components__stepper__stepper.test.tsx.snap b/packages/core/__snapshots__/src__components__stepper__stepper.test.tsx.snap new file mode 100644 index 000000000..4266135d0 --- /dev/null +++ b/packages/core/__snapshots__/src__components__stepper__stepper.test.tsx.snap @@ -0,0 +1,5 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`Stepper > snapshots > horizontal 1`] = `"
  1. Supplier, Completed
  2. Lines
    Add at least one line
  3. Approval, Skipped
  4. Review, Not started
"`; + +exports[`Stepper > snapshots > vertical 1`] = `"
  1. Supplier, Completed
  2. Lines
    Add at least one line
  3. Approval, Skipped
  4. Review, Not started
"`; diff --git a/packages/core/src/components/stepper/i18n.ts b/packages/core/src/components/stepper/i18n.ts new file mode 100644 index 000000000..149f68d73 --- /dev/null +++ b/packages/core/src/components/stepper/i18n.ts @@ -0,0 +1,22 @@ +import { defineI18nLabels } from "@/hooks/i18n"; + +export const stepperLabels = defineI18nLabels({ + en: { + label: "Progress", + complete: "Completed", + skipped: "Skipped", + upcoming: "Not started", + stepOf: (props: { current: number; total: number }) => + `Step ${props.current} of ${props.total}`, + }, + ja: { + label: "進捗", + complete: "完了", + skipped: "対象外", + upcoming: "未着手", + stepOf: (props: { current: number; total: number }) => + `ステップ ${props.current} / ${props.total}`, + }, +}); + +export const useStepperT = stepperLabels.useT; diff --git a/packages/core/src/components/stepper/index.ts b/packages/core/src/components/stepper/index.ts new file mode 100644 index 000000000..cb41b27fa --- /dev/null +++ b/packages/core/src/components/stepper/index.ts @@ -0,0 +1,2 @@ +export { Stepper } from "./stepper"; +export type { StepperProps, StepperStep } from "./types"; diff --git a/packages/core/src/components/stepper/stepper.test.tsx b/packages/core/src/components/stepper/stepper.test.tsx new file mode 100644 index 000000000..4941c53c2 --- /dev/null +++ b/packages/core/src/components/stepper/stepper.test.tsx @@ -0,0 +1,254 @@ +import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { createAppShellWrapper } from "../../../tests/test-utils"; +import { Stepper } from "./stepper"; +import type { StepperStep } from "./types"; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +const STEPS: StepperStep[] = [ + { id: "supplier", label: "Supplier", status: "complete" }, + { id: "lines", label: "Lines", status: "current", description: "Add at least one line" }, + { id: "approval", label: "Approval", status: "skipped" }, + { id: "review", label: "Review", status: "upcoming" }, +]; + +const renderStepper = (ui: React.ReactElement, locale = "en") => + render(ui, { wrapper: createAppShellWrapper(locale) }); + +const filledConnectors = () => + Array.from(document.querySelectorAll('[data-slot="stepper-connector"]')).map((c) => + c.className.includes("astw:bg-primary"), + ); + +const stepEls = () => + Array.from(document.querySelectorAll('[data-slot="stepper-step"]')); + +describe("Stepper", () => { + // ========================================================================== + // Snapshots + // ========================================================================== + + describe("snapshots", () => { + it("horizontal", () => { + const { container } = renderStepper(); + expect(container.innerHTML).toMatchSnapshot(); + }); + + it("vertical", () => { + const { container } = renderStepper( + , + ); + expect(container.innerHTML).toMatchSnapshot(); + }); + }); + + // ========================================================================== + // Structure and status + // ========================================================================== + + it("renders an ordered list of steps with their status", () => { + renderStepper(); + const list = screen.getByRole("list", { name: "New order" }); + expect(list.tagName).toBe("OL"); + expect(stepEls().map((el) => el.getAttribute("data-status"))).toEqual([ + "complete", + "current", + "skipped", + "upcoming", + ]); + }); + + it("marks only the current step with aria-current", () => { + renderStepper(); + const current = stepEls().filter((el) => el.getAttribute("aria-current") === "step"); + expect(current).toHaveLength(1); + expect(current[0].textContent).toContain("Lines"); + }); + + it("tells screen readers where the other steps stand", () => { + renderStepper(); + const [supplier, lines, approval, review] = stepEls(); + expect(supplier.textContent).toContain("Completed"); + expect(lines.textContent).not.toContain("Completed"); + expect(approval.textContent).toContain("Skipped"); + expect(review.textContent).toContain("Not started"); + }); + + it("numbers steps and shows a check on completed ones", () => { + renderStepper(); + const markers = Array.from(document.querySelectorAll('[data-slot="stepper-marker"]')); + expect(markers[0].querySelector("svg")).not.toBeNull(); + expect(markers.slice(1).map((m) => m.textContent)).toEqual(["2", "3", "4"]); + }); + + it("fills the line up to the furthest step reached", () => { + renderStepper(); + // Lines is current, so only supplier→lines is filled; the skipped step after it was never reached + expect(filledConnectors()).toEqual([true, false, false]); + }); + + it("fills through a skipped step that lies before the furthest step reached", () => { + renderStepper( + , + ); + expect(filledConnectors()).toEqual([true, true, false]); + }); + + it("names the list with a translated default", () => { + renderStepper(); + expect(screen.getByRole("list", { name: "Progress" })).toBeDefined(); + cleanup(); + renderStepper(, "ja"); + expect(screen.getByRole("list", { name: "進捗" })).toBeDefined(); + }); + + it("types onStepClick with the step ids", () => { + const steps = [ + { id: "supplier", label: "Supplier", status: "complete" }, + { id: "review", label: "Review", status: "current" }, + ] satisfies StepperStep<"supplier" | "review">[]; + renderStepper( + { + expectTypeOf(id).toEqualTypeOf<"supplier" | "review">(); + }} + />, + ); + }); + + it("renders the badge and description slots", () => { + renderStepper( + Next, + description: "Due 12 Nov", + }, + ]} + />, + ); + expect(screen.getByText("Next")).toBeDefined(); + expect(screen.getByText("Due 12 Nov")).toBeDefined(); + }); + + // ========================================================================== + // Narrow containers + // ========================================================================== + + it("adds a 'Step n of total' caption for narrow containers when horizontal", () => { + const { rerender } = renderStepper(); + const caption = document.querySelector('[data-slot="stepper-caption"]'); + expect(caption?.textContent).toBe("Step 2 of 4Lines"); + expect(caption?.getAttribute("aria-hidden")).toBe("true"); + + rerender(); + expect(document.querySelector('[data-slot="stepper-caption"]')).toBeNull(); + }); + + it("translates the caption and status text", () => { + renderStepper(, "ja"); + expect(document.querySelector('[data-slot="stepper-caption"]')?.textContent).toBe( + "ステップ 2 / 4Lines", + ); + expect(stepEls()[0].textContent).toContain("完了"); + }); + + // ========================================================================== + // Clicking + // ========================================================================== + + it("makes only completed steps clickable when onStepClick is set", async () => { + const user = userEvent.setup(); + const onStepClick = vi.fn(); + renderStepper(); + + const buttons = screen.getAllByRole("button"); + expect(buttons).toHaveLength(1); + await user.click(buttons[0]); + expect(onStepClick).toHaveBeenCalledWith("supplier"); + }); + + it("renders no buttons without onStepClick", () => { + renderStepper(); + expect(screen.queryAllByRole("button")).toHaveLength(0); + }); + + // ========================================================================== + // Narrow containers: markers carry a tooltip and the click target + // ========================================================================== + + describe("in a narrow container", () => { + const stubWidth = (width: number) => { + vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(width); + }; + + it("moves the click target from the hidden label to the marker", async () => { + stubWidth(320); + const user = userEvent.setup(); + const onStepClick = vi.fn(); + renderStepper(); + + // One focus stop, and it's the visible marker — not the visually hidden label + const button = await screen.findByRole("button", { name: /^Supplier ?, Completed$/ }); + expect(screen.getAllByRole("button")).toHaveLength(1); + expect(button.querySelector('[data-slot="stepper-marker"]')).not.toBeNull(); + + await user.click(button); + expect(onStepClick).toHaveBeenCalledWith("supplier"); + }); + + it("names each step in a tooltip on its marker", async () => { + stubWidth(320); + const user = userEvent.setup(); + renderStepper(); + + const triggers = await waitFor(() => { + const found = document.querySelectorAll( + '[data-slot="stepper-marker-trigger"]', + ); + expect(found).toHaveLength(4); + return found; + }); + + await user.hover(triggers[3]); + const tooltip = await waitFor(() => { + const content = document.querySelector('[data-slot="tooltip-content"]'); + expect(content).not.toBeNull(); + return content!; + }); + expect(tooltip.textContent).toContain("Review"); + expect(tooltip.textContent).toContain("Not started"); + }); + + it("keeps the label as the click target and adds no tooltips when wide", () => { + stubWidth(800); + renderStepper( {}} />); + expect(document.querySelector('[data-slot="stepper-marker-trigger"]')).toBeNull(); + const button = screen.getByRole("button", { name: /^Supplier ?, Completed$/ }); + expect(button.querySelector('[data-slot="stepper-marker"]')).toBeNull(); + }); + + it("never goes compact when vertical", () => { + stubWidth(320); + renderStepper(); + expect(document.querySelector('[data-slot="stepper-marker-trigger"]')).toBeNull(); + }); + }); +}); diff --git a/packages/core/src/components/stepper/stepper.tsx b/packages/core/src/components/stepper/stepper.tsx new file mode 100644 index 000000000..e9a2277d4 --- /dev/null +++ b/packages/core/src/components/stepper/stepper.tsx @@ -0,0 +1,350 @@ +import * as React from "react"; +import { CheckIcon } from "lucide-react"; + +import { cn } from "@/lib/utils"; +import { Text } from "../text"; +import { Tooltip } from "../tooltip"; +import { useStepperT } from "./i18n"; +import type { StepperProps, StepperStep, StepperStepStatus } from "./types"; + +/** Below this container width a horizontal Stepper shows only its markers. */ +const COMPACT_WIDTH = 400; + +// ============================================================================ +// Marker +// ============================================================================ + +const MARKER_CLASSES: Record = { + complete: "astw:bg-primary astw:text-primary-foreground", + current: "astw:border-2 astw:border-primary astw:bg-background astw:text-primary", + upcoming: "astw:border astw:border-border astw:bg-background astw:text-muted-foreground", + skipped: + "astw:border astw:border-dashed astw:border-muted-foreground astw:bg-background astw:text-muted-foreground", +}; + +function Marker({ status, index }: { status: StepperStepStatus; index: number }) { + return ( + + ); +} + +/** + * The marker of a horizontal Stepper in a narrow container, where the labels + * are hidden: a tooltip names the step, and a completed step's marker is the + * button that goes back to it. + */ +function CompactMarker({ + step, + index, + labelId, + onStepClick, +}: { + step: StepperStep; + index: number; + labelId: string; + onStepClick?: (id: Id) => void; +}) { + const t = useStepperT(); + const clickable = onStepClick != null && step.status === "complete"; + return ( + + onStepClick(step.id)} + className="astw:cursor-pointer astw:rounded-full astw:outline-none astw:focus-visible:ring-[3px] astw:focus-visible:ring-ring/50" + /> + ) : ( + + ) + } + > + + + + {step.label} + {step.status !== "current" && · {t(step.status)}} + + + ); +} + +/** The line from a step to the next one. It is filled up to the furthest step reached. */ +function Connector({ filled, vertical }: { filled: boolean; vertical: boolean }) { + return ( +