` props.
+| Prop | Type | Default | Description |
+| ------ | ------------------------------ | ------- | ----------------------------------------------------------------------------------------------- |
+| `size` | `"sm" \| "md" \| "lg" \| "xl"` | `"md"` | Max width of the panel: 24rem, 32rem, 45rem or 60rem — the same steps as `Sheet.Content` `size` |
+
+Also accepts `className` and all standard HTML `
` props. The panel never grows taller than the viewport; put long content in `Dialog.Body` so it scrolls while the header and footer stay in view.
## Tall Content
-`Dialog.Content` is never taller than the viewport minus 2rem (16px above and below, the same margin as on the sides). When the content is taller, the whole dialog scrolls, including the title and the close button. `Escape` and a click on the backdrop still close it.
+`Dialog.Content` is never taller than the viewport minus 2rem (16px above and below, the same margin as on the sides). Without a `Dialog.Body`, content that is taller makes the whole dialog scroll, including the title and the close button. `Escape` and a click on the backdrop still close it.
On open, focus moves to the first control in the dialog. In a dialog that scrolls, this happens only when that control is in view at the top. When it is below the fold (for example, a footer button after a long body), the dialog itself takes focus instead, so it opens at the top rather than scrolled to that control. `Tab` then moves to the control. Pass `initialFocus` to choose the element yourself.
-To keep a header or footer in view while only the body scrolls, make `Dialog.Content` a flex column and give the body `min-h-0 flex-1 overflow-y-auto`. A `className` with its own `max-h-*` or `overflow-*` replaces the defaults.
+To keep the header and footer in view while only the middle scrolls, wrap the middle in `Dialog.Body`. `Dialog.Content` is already a flex column, and `Dialog.Body` is the only child that shrinks; the header, footer and anything else placed directly in `Dialog.Content` keep their height. A `className` with its own `max-h-*` or `overflow-*` replaces the defaults.
### Dialog.Trigger / Dialog.Close Props
@@ -170,7 +175,9 @@ function DeleteConfirmation() {
### Form Dialog
-Edit the item name and save to update the value outside the dialog. Empty or whitespace-only names are rejected through `Form` and `Field`. Cancel or close leaves the saved name unchanged; reopening restores it. Cancel is explicitly `type="button"` so it does not submit the form.
+Put the `Form` inside `Dialog.Body` and submit it from the footer with `form=""`, so the Save button stays visible however long the form gets. [`FormLayout`](./form-layout.md) lays the fields out in columns that fit the dialog's width.
+
+In this example, empty or whitespace-only names are rejected through `Form` and `Field`. Cancel or close leaves the saved name unchanged; reopening restores it. Cancel is explicitly `type="button"` so it does not submit the form.
@@ -184,38 +191,46 @@ function FormDialog() {
Saved item name: {name}
}>Edit item
-
+
Edit item
Save a new name, or cancel to keep the saved name.
-
+
+
+ typeof value === "string" && value.trim() ? undefined : "Name is required."
+ }
+ >
+ Item name
+
+ Name is required.
+
+
+ SKU
+
+
+
+
+
+
+ }>Cancel
+
+ Save item
+
+
diff --git a/docs/components/form-layout.md b/docs/components/form-layout.md
new file mode 100644
index 000000000..3e5599af2
--- /dev/null
+++ b/docs/components/form-layout.md
@@ -0,0 +1,212 @@
+---
+title: FormLayout
+description: Responsive multi-column grid, sections and action bar for laying out form fields in a dialog, sheet or page
+---
+
+
+
+# FormLayout
+
+`FormLayout` lays out form fields in a responsive grid. Put it inside `
` and place `Field.Root`s in it; it handles columns, field widths, sections and the action bar so you don't hand-write `grid md:grid-cols-2` or `md:col-span-2` on every form.
+
+Columns follow the width of the **container**, not the viewport. The same fields show two columns in a large dialog, one in a narrow sheet and three in a page section, with no changes to the markup.
+
+This is why `FormLayout` is not built on [`Grid`](./grid.md): `Grid` picks its columns from the viewport width, so a form inside a 480px dialog on a wide screen would still get the wide-screen columns. `FormLayout` measures its own container instead.
+
+## Import
+
+```tsx
+import { FormLayout } from "@tailor-platform/app-shell";
+```
+
+## Basic Usage
+
+
+
+```tsx
+function BasicUsage() {
+ return (
+ console.log(values)}>
+
+
+ Supplier name
+
+
+
+ Code
+
+
+
+ Email
+
+
+
+ Notes
+
+
+
+
+ );
+}
+```
+
+Fields go straight into the grid. Widen a field with `span` on `Field.Root` — `"full"` takes the whole row.
+
+## Sub-components
+
+| Sub-component | Description |
+| -------------------- | ----------------------------------------------------------------------------------- |
+| `FormLayout` | The grid. `columns` is the most columns to show |
+| `FormLayout.Section` | A titled group of fields (`
`) with its own grid, drawn as a card or plain |
+| `FormLayout.Item` | Places non-field content (an Alert, a table) in the grid with a `span` |
+| `FormLayout.Actions` | Right-aligned action bar, optionally sticky |
+
+## Props
+
+### FormLayout Props
+
+| Prop | Type | Default | Description |
+| ----------- | ------------------ | ------- | ----------------------------------------------------------------------- |
+| `columns` | `1 \| 2 \| 3 \| 4` | `2` | The most columns to show. Sections inherit it unless they set their own |
+| `className` | `string` | - | Additional CSS classes |
+| `style` | `CSSProperties` | - | Inline styles |
+| `children` | `React.ReactNode` | - | Fields, sections, items and actions |
+
+### FormLayout.Section Props
+
+| Prop | Type | Default | Description |
+| ------------- | ------------------- | -------- | -------------------------------------------------------------------------------- |
+| `title` | `React.ReactNode` | - | Section heading (an `h3` inside the legend); also the fieldset's accessible name |
+| `description` | `React.ReactNode` | - | Supporting text under the title; also the fieldset's accessible description |
+| `action` | `React.ReactNode` | - | Header action slot, right of the title |
+| `columns` | `1 \| 2 \| 3 \| 4` | inherits | Overrides the columns inherited from `FormLayout` |
+| `variant` | `"card" \| "plain"` | `"card"` | `"card"` on pages; `"plain"` (heading + divider) inside a Dialog or Sheet |
+| `disabled` | `boolean` | - | Disables every field in the section |
+| `id` | `string` | - | Element id, e.g. for anchor navigation |
+| `className` | `string` | - | Additional CSS classes |
+
+### FormLayout.Item Props
+
+| Prop | Type | Default | Description |
+| ----------- | ------------------ | ------- | -------------------------------- |
+| `span` | `2 \| 3 \| "full"` | - | How many columns the item covers |
+| `className` | `string` | - | Additional CSS classes |
+
+### FormLayout.Actions Props
+
+| Prop | Type | Default | Description |
+| ---------- | ----------------- | ------- | --------------------------------------------------------------------------------------------- |
+| `sticky` | `boolean` | `false` | Floats the bar as a card 16px above the bottom of the scrolling area on long forms |
+| `start` | `React.ReactNode` | - | Content on the left (e.g. "Draft · not saved yet"); moves to its own line when space runs out |
+| `children` | `React.ReactNode` | - | Buttons, right-aligned. Put Cancel first and the primary action last |
+
+## Columns
+
+`columns` is a maximum. The grid steps down as its container narrows:
+
+| Container width | Columns shown |
+| --------------- | ----------------------- |
+| < 400px | 1 |
+| ≥ 400px | 2 |
+| ≥ 640px | 3 (when `columns` ≥ 3) |
+| ≥ 880px | 4 (when `columns` is 4) |
+
+Buttons in `FormLayout.Actions`, `Dialog.Footer` and `Sheet.Footer` keep their natural width and sit on the right; when they don't fit side by side they wrap, still right-aligned, rather than stretching full width.
+
+Pick the maximum by where the form lives: `2` for dialogs, sheets and most pages, `3` for wide page sections, `4` for the header fields of a document form (PO, invoice). Keep related fields next to each other in source order; the grid fills left to right.
+
+## Field widths
+
+Every field takes one column unless it sets `span` on `Field.Root` or `Fieldset.Root` (`2`, `3` or `"full"`), or on `FormLayout.Item` for other content. Size each field with these rules:
+
+1. **Size by the value, not the label.** Ask how long the value the user types or picks usually is.
+2. **One short value takes one column** — the default. Codes, numbers, amounts, dates, statuses, single picks from a list, emails, phone numbers.
+3. **A value that often runs long, or that is two values, takes two columns** (`span={2}`): full names and titles, a street line, a date range.
+4. **Free text, sentences and anything that isn't a single value take the full row** (`span="full"`): notes and descriptions, a checkbox or switch with a sentence label, a group of checkboxes, a file upload, an alert, a table, totals. A field holding a `Textarea` does this on its own; give it a `span` to keep it narrower.
+5. **Keep related fields together.** Fields that belong together sit side by side in source order (currency and amount, city and postal code); a group that must stay together, such as an address, goes in a `Fieldset.Root span={2}` with its own `FormLayout`.
+6. **Don't widen a field to fill a row.** An empty cell at the end of a row is fine; a stretched short field reads as a longer value than it is.
+7. **Don't size for small screens.** Spans are capped at the columns shown — `span={3}` in a two-column grid covers both — and every field takes the full width in a narrow container, so no field needs a mobile variant.
+
+How the rules apply to common fields:
+
+| Field | Width | Rule |
+| --------------------------------------------------------------------- | --------------------------------------------------- | ---- |
+| Text, select, combobox, date, number, money, code, email, phone | One column (default) | 2 |
+| Names and titles (legal name, a long supplier name), date ranges | `span={2}` | 3 |
+| `Textarea` (notes, descriptions) | Full row (automatic) | 4 |
+| Checkbox or switch with a sentence label, checkbox group, file upload | `span="full"` | 4 |
+| Alerts, tables, line items, totals | `FormLayout.Item span="full"` | 4 |
+| Address block | `Fieldset.Root span={2}` with a nested `FormLayout` | 5 |
+
+`span` only works on a **direct child** of the `FormLayout` or `FormLayout.Section` grid. The grid applies the span to its own children, because only the grid knows how many columns it is showing. A `Field.Root` wrapped in another element — a `div`, or a component of yours that renders a wrapper around it — is no longer a direct child, so its span is dropped and it takes one column. Put the `span` on the outermost element instead: use `FormLayout.Item span={2}` around the wrapper, or have your component pass `span` to the `Field.Root` it renders without wrapping it.
+
+## Sections
+
+
+
+```tsx
+function Sections() {
+ return (
+ console.log(values)}>
+
+
+
+ Supplier
+
+
+
+ Supplier reference
+
+
+
+
+
+ Ship to
+
+
+
+ Delivery instructions
+
+
+
+
+
+ Cancel
+
+ Create
+
+
+
+ );
+}
+```
+
+Use sections once a form has more than about eight fields or two natural groups. On a page each section is a card; inside a Dialog or Sheet use `variant="plain"`, which draws a heading instead of a card inside the panel, and a divider between one plain section and the next. Give sections an `id` to link to them from a section nav.
+
+## Required fields
+
+Mark required fields with `Field.Label required` and put `required` on the control. The label shows a `*`; the control's `required` is what validation checks and screen readers announce.
+
+## Choosing a container
+
+`FormLayout` handles the fields; the container depends on the form:
+
+| If the form… | Use |
+| ------------------------------------------------ | --------------------------------------------------------------------------------------------- |
+| Has header fields plus line items | `Layout maxWidth="xl"`, `FormLayout columns={4}` for the header, sections in the view's order |
+| Has ordered steps that depend on earlier answers | A [wizard](../patterns/form-wizard.md): one `Form` per step |
+| Needs its own URL, or is long enough to scroll | `Layout maxWidth="lg"` with card sections; add a section nav column if it helps (see below) |
+| Edits part of a record shown beside it | `Sheet` (`size="lg"`) with `FormLayout columns={2}` |
+| Anything else | `Dialog` sized to the form (`sm`–`xl`); plain sections once it has groups |
+
+A section nav is optional. It usually earns its column from about three sections; when you add one, widen the page to `Layout maxWidth="xl"` so the form keeps its width.
+
+In a Dialog, put the `Form` inside `Dialog.Body` and submit from `Dialog.Footer` with `form=""`, so the footer stays visible however long the form gets. On a page, Save lives in `Layout.Header`; add a sticky `FormLayout.Actions` as well when the form scrolls.
+
+## Related
+
+- [Form, Field, and Fieldset](./form.md) — The form controls `FormLayout` arranges.
+- [Layout](./layout.md) — Page scaffolding; `maxWidth` centres form pages.
+- [Dialog](./dialog.md) — `size` and `Dialog.Body` for modal forms.
+- [Sheet](./sheet.md) — Side panel for editing beside a list.
+- [Grid](./grid.md) — General-purpose content grid for non-form content.
diff --git a/docs/components/form.md b/docs/components/form.md
index 016fd6dd3..7196f0750 100644
--- a/docs/components/form.md
+++ b/docs/components/form.md
@@ -160,6 +160,7 @@ A compound component that groups all parts of a form field and manages its valid
| `Field.Root` | Context boundary for a single field. Manages validation state. |
| `Field.Label` | Accessible label; `htmlFor` is resolved automatically via context. |
| `Field.Control` | Styled text ` `. `Select`, `Combobox`, and the other self-wired controls go directly under `Field.Root` instead. |
+| `Field.Value` | A read-only value in the control's place, at an input's height, so it lines up with editable fields beside it. |
| `Field.Description` | Supplementary help text; automatically linked via `aria-describedby`. |
| `Field.Error` | Validation error message. Use `match` to target specific validity states. |
| `Field.Validity` | Render-prop access to the field's `ValidityState` for fully custom validation UI. |
@@ -178,8 +179,30 @@ A compound component that groups all parts of a form field and manages its valid
| `validate` | `(value: string) => string \| undefined` | - | Custom validation function; return an error message string to mark the field invalid. |
| `validationMode` | `"onSubmit" \| "onBlur" \| "onChange"` | - | Overrides the parent Form's `validationMode` for this field. |
| `validationDebounceTime` | `number` | - | Debounce delay (ms) for `"onChange"` validation mode. |
+| `span` | `2 \| 3 \| "full"` | - | Columns the field covers inside a [`FormLayout`](./form-layout.md) grid. Ignored outside it. |
| `className` | `string` | - | Additional CSS classes for the field wrapper. |
+### Field.Label Props
+
+Accepts all standard `` props, plus:
+
+| Prop | Type | Default | Description |
+| ---------- | --------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
+| `required` | `boolean` | `false` | Shows the required marker (`*`) after the label. Visual only — also set `required` on the control, which is what's checked and announced. |
+
+### Read-only values
+
+Use `Field.Value` for a value the form shows but doesn't change: a supplier fixed after the order is confirmed, a status badge, a calculated total. It takes the control's place and height, so it lines up with the inputs in the same row.
+
+```tsx
+
+ Supplier
+ Kansai Textile Co.
+
+```
+
+There is no control for the label to point at, so `Field.Value` is a group named by the `Field.Label` in the same `Field.Root`: screen readers read "Supplier, Kansai Textile Co." together. Without a `Field.Label`, give `Field.Value` an `aria-label`.
+
### Field.Error Props
| Prop | Type | Default | Description |
@@ -433,11 +456,12 @@ A compound component (`Fieldset.Root`, `Fieldset.Legend`) for grouping related f
### Fieldset.Root Props
-| Prop | Type | Default | Description |
-| ----------- | ----------------- | ------- | ------------------------------------------ |
-| `children` | `React.ReactNode` | - | Field components to group. |
-| `disabled` | `boolean` | - | Disables all controls within the fieldset. |
-| `className` | `string` | - | Additional CSS classes. |
+| Prop | Type | Default | Description |
+| ----------- | ------------------ | ------- | ------------------------------------------- |
+| `children` | `React.ReactNode` | - | Field components to group. |
+| `disabled` | `boolean` | - | Disables all controls within the fieldset. |
+| `span` | `2 \| 3 \| "full"` | - | Columns covered inside a `FormLayout` grid. |
+| `className` | `string` | - | Additional CSS classes. |
### Example
@@ -510,6 +534,7 @@ The `Field` context handles only accessibility wiring (`htmlFor`, `aria-describe
## Related
+- [FormLayout](./form-layout.md) — Multi-column grid, sections and action bar for laying out fields.
- [Testing](../concepts/testing.md#find-form-controls-by-role-and-accessible-name) — Role-based field interactions, form submission, and validation tests.
- [Input](./input.md) — Standalone styled input, useful outside of forms.
- [Textarea](./textarea.md) — Multi-line text control that integrates automatically with `Field`.
diff --git a/docs/components/layout.md b/docs/components/layout.md
index 69621883e..a28e5bb9d 100644
--- a/docs/components/layout.md
+++ b/docs/components/layout.md
@@ -44,16 +44,17 @@ function BasicUsage() {
### Layout Props
-| Prop | Type | Default | Description |
-| ----------- | ------------------- | ------------ | --------------------------------------------------------------------------------------- |
-| `className` | `string` | - | Additional CSS classes for container |
-| `style` | `CSSProperties` | - | Inline styles for the layout container |
-| `children` | `Layout.Column[]` | **Required** | `Layout.Header` and/or `Layout.Column` components |
-| `fill` | `boolean` | `false` | Fill the available height instead of growing with content (see [Fill Mode](#fill-mode)) |
-| `columns` | `1 \| 2 \| 3` | - | **(Deprecated)** Auto-detected from `Layout.Column` children count when omitted |
-| `title` | `string` | - | **(Deprecated)** Use `` instead |
-| `actions` | `React.ReactNode[]` | - | **(Deprecated)** Use `` instead |
-| `gap` | `number` | `4` | **(Deprecated)** Use `className` (e.g. `className="gap-6"`) instead |
+| Prop | Type | Default | Description |
+| ----------- | ---------------------- | ------------ | --------------------------------------------------------------------------------------- |
+| `className` | `string` | - | Additional CSS classes for container |
+| `style` | `CSSProperties` | - | Inline styles for the layout container |
+| `children` | `Layout.Column[]` | **Required** | `Layout.Header` and/or `Layout.Column` components |
+| `fill` | `boolean` | `false` | Fill the available height instead of growing with content (see [Fill Mode](#fill-mode)) |
+| `maxWidth` | `"md" \| "lg" \| "xl"` | - | Centre the page and cap its width (see [Max Width](#max-width)) |
+| `columns` | `1 \| 2 \| 3` | - | **(Deprecated)** Auto-detected from `Layout.Column` children count when omitted |
+| `title` | `string` | - | **(Deprecated)** Use `` instead |
+| `actions` | `React.ReactNode[]` | - | **(Deprecated)** Use `` instead |
+| `gap` | `number` | `4` | **(Deprecated)** Use `className` (e.g. `className="gap-6"`) instead |
### Layout.Header Props
@@ -310,6 +311,36 @@ Use `fill` for pages whose main content manages its own scrolling (typically a `
> Because the shell is viewport-bounded, page content scrolls inside the content area rather than on the document. If you have code that read `window`/document scroll, reach for the content scroll container instead — see [Accessing the content scroll container](./sidebar-layout.md#accessing-the-content-scroll-container).
+## Max Width
+
+By default a layout spans the whole content area. On wide screens a form stretched that far leaves long empty rows and puts Save far from the fields. Set `maxWidth` to centre the page and cap its width — the header and the columns together, so the title and actions line up with the content:
+
+| Value | Width | Use for |
+| ------ | -------------- | --------------------------------------------------------------------------------------------- |
+| `"md"` | 48rem (768px) | Single-column forms, settings pages |
+| `"lg"` | 64rem (1024px) | Two-column forms |
+| `"xl"` | 80rem (1280px) | Document forms with line items (PO, invoice), and forms with a section nav column beside them |
+
+```tsx
+
+
+ Create
+ ,
+ ]}
+ />
+
+
+ {/* … */}
+
+
+
+```
+
+Leave it off for lists and dashboards, which use the full width. Document forms with line items use `"xl"`: wide enough for the line-item table, without stretching the header fields across a wide screen.
+
## Gap Spacing
Use the `gap` prop to control the space between columns. Supported steps are `4`, `6` and `8`:
@@ -422,8 +453,6 @@ function Dashboard() {
```tsx
function ProductEditor() {
- const [product, setProduct] = useState(initialProduct);
-
return (
Cancel
,
- Save Changes ,
+
+ Save Changes
+ ,
]}
/>
-
- Product Details
- setProduct({ ...product, name: e.target.value })}
- />
- setProduct({ ...product, price: e.target.value })}
- />
- setProduct({ ...product, description: e.target.value })}
- />
-
+
+
+
+
+ Name
+
+
+
+ Price
+
+
+
+ Description
+
+
+
+
+
-
- Preview
-
-
+
+
+
+
+
+
);
diff --git a/docs/migrations.md b/docs/migrations.md
index ba49b357a..269ec8f66 100644
--- a/docs/migrations.md
+++ b/docs/migrations.md
@@ -15,6 +15,7 @@ Each entry states which versions are affected, what breaks, how to detect it, an
| Version | Change |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------- |
+| 1.21.0 | [Scroll a dialog's content in `Dialog.Body`](#1210-scroll-a-dialogs-content-in-dialogbody) |
| 1.21.0 | [Testing helpers deprecated in favour of TestingProvider](#1210-testing-helpers-deprecated-in-favour-of-testingprovider) |
| 1.20.0 | [z-index tokens renamed; old names are aliases](#1200-z-index-tokens-renamed-old-names-are-aliases) |
| 1.18.0 | [Destructive colours now resolve to the danger roles](#1180-destructive-colours-now-resolve-to-the-danger-roles) |
@@ -30,6 +31,32 @@ Each entry states which versions are affected, what breaks, how to detect it, an
| 1.0.2 | [`Toaster` no longer accepts `richColors`](#102-toaster-no-longer-accepts-richcolors) |
| before 1.0 | [Pre-1.0 breaking changes](#before-10) |
+## 1.21.0: scroll a dialog's content in `Dialog.Body`
+
+**Applies to:** dialogs that made `Dialog.Content` a flex column themselves (for example `className="flex flex-col max-h-[85vh]"`) and gave a direct child its own scroll area (`min-h-0 flex-1 overflow-y-auto`) to keep the header and footer in view.
+
+`Dialog.Content` is now a flex column by default, and only `Dialog.Body` shrinks in it: every other direct child keeps its full height. A hand-made scroll area therefore grows to fit its content, and the whole dialog scrolls instead, header and footer included. Nothing errors.
+
+To find these, search for `Dialog.Content` with `flex-col` in its `className`, or for `overflow-y-auto` on a direct child of `Dialog.Content`.
+
+Before:
+
+```tsx
+
+ …
+ {list}
+
+```
+
+After:
+
+```tsx
+
+ …
+ {list}
+
+```
+
## 1.21.0: testing helpers deprecated in favour of TestingProvider
**Applies to:** tests importing `AppShell` or `TestAppShellProps` from `@tailor-platform/app-shell/testing`.
diff --git a/docs/patterns/form-modal.md b/docs/patterns/form-modal.md
index e12bb4eaf..b4c6426c0 100644
--- a/docs/patterns/form-modal.md
+++ b/docs/patterns/form-modal.md
@@ -23,41 +23,48 @@ function ModalForm() {
return (
}>Add address
-
+
Add address
Add a shipping address to this order.
{/*
+ * The form sits in `Dialog.Body`, which scrolls when the form is long;
+ * the footer stays put and submits through `form="address-form"`.
* `onFormSubmit` fires only after validation passes and receives the
* registered field values — no `` + `new FormData(...)`.
*/}
-
- noValidate
- onFormSubmit={(values) => window.alert(`Saving ${values.label}`)}
- >
-
-
- Label
-
- Label is required.
-
-
- Street
-
- Street is required.
-
-
- City
-
- City is required.
-
-
-
- }>Cancel
- Save
-
-
+
+
+ id="address-form"
+ noValidate
+ onFormSubmit={(values) => window.alert(`Saving ${values.label}`)}
+ >
+
+
+ Label
+
+ Label is required.
+
+
+ Street
+
+ Street is required.
+
+
+ City
+
+ City is required.
+
+
+
+
+
+ }>Cancel
+
+ Save
+
+
);
@@ -193,7 +200,8 @@ function ModalFormConfirm() {
## Constraints
-- Dialog renders full-screen sheet below 1024px; centered max-w-md at 1024–1280px
+- `Dialog.Content size` sets the width: `"md"` (32rem, default) for up to ~6 fields, `"lg"` (45rem) for 6–12 fields grouped with `FormLayout.Section variant="plain"`. Lay fields out with [`FormLayout`](../components/form-layout.md) (`columns={2}`)
+- Put the `Form` inside `Dialog.Body` so long forms scroll while the header and footer stay put; submit from `Dialog.Footer` with `form=""`
- Route-driven variant requires both parent path and create/edit path to render the same component
- `onOpenChange` must navigate back — just calling `setOpen(false)` leaves the URL broken
- Use ``, never a bare ` ` — see **Form state** below
@@ -202,7 +210,7 @@ function ModalFormConfirm() {
## Form state
-Applies to every `form/*` pattern. Full detail in **`components.md`** → Forms.
+Applies to every `form/*` pattern. Full detail in [Form, Field, and Fieldset](../components/form.md) and [FormLayout](../components/form-layout.md).
`form/composer` follows all of this too, with one documented exception noted below: its body is
controlled, because a composer reads the value during render to gate its submit and swap its
diff --git a/docs/patterns/form-sectioned.md b/docs/patterns/form-sectioned.md
index 0ac669d79..267ce4ab9 100644
--- a/docs/patterns/form-sectioned.md
+++ b/docs/patterns/form-sectioned.md
@@ -23,7 +23,7 @@ function FormSectioned() {
const onCancel = () => {};
return (
-
+
onSave(values)}
>
- {/* Anchor nav — each entry targets its section's Card by id. */}
-
+ {/* Anchor nav — each entry targets its FormLayout.Section by id. */}
+
{SECTIONS.map((section) => (
{section.title}
))}
-
-
-
-
-
- Name
-
- Name is required.
-
-
- SKU
-
- SKU is required.
-
-
- Description
-
-
-
-
-
-
-
-
-
-
-
- Price
-
- Price is required.
-
-
- Currency
-
-
-
-
-
-
-
-
-
-
-
-
- Initial quantity
-
- Initial quantity is required.
-
-
- Reorder point
-
-
- Leave blank to disable replenishment alerts.
-
-
- {/*
- * Object items would otherwise reach `onFormSubmit` as JSON.
- * `itemToStringValue` picks the field to submit; `mapItem`
- * stays responsible for what the user sees.
- */}
-
- Default warehouse
- ({ label: w.name, key: String(w.id) })}
- itemToStringValue={(w) => String(w.id)}
- placeholder="Select warehouse"
- />
-
-
-
-
+ {/* Each section is a card with its own two-column grid; one Form wraps them all. */}
+
+
+
+ Name
+
+ Name is required.
+
+
+ SKU
+
+ SKU is required.
+
+
+ Description
+
+
+
+
+
+
+ Price
+
+ Price is required.
+
+
+ Currency
+
+
+
+
+
+
+
+ Initial quantity
+
+ Initial quantity is required.
+
+
+ Reorder point
+
+ Leave blank to disable replenishment alerts.
+
+ {/*
+ * Object items would otherwise reach `onFormSubmit` as JSON.
+ * `itemToStringValue` picks the field to submit; `mapItem`
+ * stays responsible for what the user sees.
+ */}
+
+ Default warehouse
+ ({ label: w.name, key: String(w.id) })}
+ itemToStringValue={(w) => String(w.id)}
+ placeholder="Select warehouse"
+ />
+
+
+
@@ -141,17 +139,19 @@ function FormSectioned() {
- Max ~6 sections — more than that is too hard to scan; promote to `form/wizard`
- Required-marker convention must be consistent across all sections
-- One `Card.Root` per section, titled via `Card.Header title` + `description`; `Fieldset.Root`
- inside supplies the field grouping and the responsive grid
+- One `FormLayout.Section` per section (`title` + `description`); it renders the card, the
+ `` grouping and the responsive grid
+- The section nav column is optional. It usually earns its space from about three sections; with
+ it, use `Layout maxWidth="xl"` so the form keeps its width, without it `Layout maxWidth="lg"`
- Save/Cancel belong in `Layout.Header`, wired with `` matching the
`Form`'s `id` (requires 1.13.0+)
-- Section headings must match anchor-nav labels — derive both from one `SECTIONS` array so they
+- When there is a section nav, its labels must match the section headings — derive both from one `SECTIONS` array so they
cannot drift
- A single `` wraps every section — do not nest a `Form` per section
## Form state
-Rules that apply to every `form/*` pattern are in **`components.md`** → Forms, with a worked example
+Rules that apply to every `form/*` pattern are in [Form, Field, and Fieldset](../components/form.md) and [FormLayout](../components/form-layout.md), with a worked example
in **`form/modal`** → Form state: `Form` + `Field` is the default stack, submit via `onFormSubmit`,
dropdowns need only a wrapping `Field.Root` (no `name`, no state), server errors route through
`errors`, and React Hook Form is an optional escape hatch.
diff --git a/docs/patterns/form-single-page.md b/docs/patterns/form-single-page.md
index 6cb29963f..a6e86cc28 100644
--- a/docs/patterns/form-single-page.md
+++ b/docs/patterns/form-single-page.md
@@ -22,7 +22,7 @@ function FormSinglePage() {
const onCancel = () => {};
return (
-
+
{/*
* Save/Cancel live in the page header and reach the form through the
* native `form` attribute, matching `Form`'s `id`. No state plumbing.
@@ -39,44 +39,47 @@ function FormSinglePage() {
]}
/>
-
- id="product-form"
- noValidate
- className="max-w-2xl space-y-4"
- onFormSubmit={(values) => onSave(values)}
- >
-
- Name
-
- Name is required.
-
-
- SKU
-
- Format: ABC-1234
- Use the format ABC-1234.
- SKU is required.
-
+ id="product-form" noValidate onFormSubmit={(values) => onSave(values)}>
{/*
- * Dropdowns need no `name` and no React state: `Field.Root` registers
- * the control, so its value arrives in `onFormSubmit` under the
- * field's name like any other input.
+ * FormLayout puts the fields in two columns (one on narrow screens);
+ * `span="full"` gives the description the whole row.
*/}
-
- Category
-
-
-
-
- Price
-
- Price cannot be negative.
- Price is required.
-
-
- Description
-
-
+
+
+
+ Name
+
+ Name is required.
+
+
+ SKU
+
+ Format: ABC-1234
+ Use the format ABC-1234.
+ SKU is required.
+
+ {/*
+ * Dropdowns need no `name` and no React state: `Field.Root` registers
+ * the control, so its value arrives in `onFormSubmit` under the
+ * field's name like any other input.
+ */}
+
+ Category
+
+
+
+
+ Price
+
+ Price cannot be negative.
+ Price is required.
+
+
+ Description
+
+
+
+
@@ -88,7 +91,7 @@ function FormSinglePage() {
## Constraints
-- Single column full width below 1024px; single column max-w constrained at 1024–1280px
+- `Layout maxWidth="lg"` centres the page at 64rem; fields sit in one `FormLayout.Section` card with `FormLayout columns={2}`, collapsing to one column on narrow screens
- Without an explicit routed-page requirement, the answer is `form/modal`
- A `/create` or `/edit` route in the screen spec does NOT require a full-page replacement
- Save/Cancel belong in `Layout.Header`, wired with `` matching the
@@ -98,7 +101,7 @@ function FormSinglePage() {
## Form state
-Rules that apply to every `form/*` pattern are in **`components.md`** → Forms, with a worked example
+Rules that apply to every `form/*` pattern are in [Form, Field, and Fieldset](../components/form.md) and [FormLayout](../components/form-layout.md), with a worked example
in **`form/modal`** → Form state: `Form` + `Field` is the default stack, submit via `onFormSubmit`,
dropdowns need only a wrapping `Field.Root` (no `name`, no state), server errors route through
`errors`, and React Hook Form is an optional escape hatch.
diff --git a/docs/patterns/form-wizard.md b/docs/patterns/form-wizard.md
index 653e009e8..368ba8505 100644
--- a/docs/patterns/form-wizard.md
+++ b/docs/patterns/form-wizard.md
@@ -72,17 +72,17 @@ function FormWizard() {
{step === 0 && (
-
+
Title
Title is required.
-
+
Description
-
+
)}
{step === 1 && (
@@ -99,7 +99,7 @@ function FormWizard() {
)}
{step === 2 && (
-
+
Start date
@@ -109,7 +109,7 @@ function FormWizard() {
Estimate (hours)
-
+
)}
{step === 3 && (
diff --git a/examples/vite-app/src/App.tsx b/examples/vite-app/src/App.tsx
index 035b50f91..a9d327144 100644
--- a/examples/vite-app/src/App.tsx
+++ b/examples/vite-app/src/App.tsx
@@ -70,6 +70,7 @@ const AppInner = () => {
+
diff --git a/examples/vite-app/src/pages/showcase/form-templates/complex-examples.tsx b/examples/vite-app/src/pages/showcase/form-templates/complex-examples.tsx
new file mode 100644
index 000000000..73517e12f
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/complex-examples.tsx
@@ -0,0 +1,612 @@
+import * as React from "react";
+import {
+ Badge,
+ Button,
+ Card,
+ Checkbox,
+ Combobox,
+ DataTable,
+ DatePicker,
+ Field,
+ Fieldset,
+ Form,
+ FormLayout,
+ Grid,
+ Select,
+ Tabs,
+ Text,
+ Textarea,
+ aggregations,
+ createColumnHelper,
+ CellEditError,
+ useDataTable,
+ useResolvedLocale,
+} from "@tailor-platform/app-shell";
+import {
+ AddressFields,
+ BUYERS,
+ CARRIERS,
+ CURRENCIES,
+ DeliveryFields,
+ PAYMENT_TERMS,
+ SUPPLIERS,
+ SupplierFields,
+ WAREHOUSES,
+} from "./fields";
+
+// Complex examples: how far FormLayout stretches before you need anything
+// custom. Each one is self-contained so it can be lifted into a real page.
+
+// ✅ Reusable Component: Can be moved to components/ui/
+function ExampleHeader({
+ id,
+ title,
+ children,
+}: {
+ id: string;
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+
+
+ {id}
+ {title}
+
+
+ {children}
+
+
+ );
+}
+
+// ============================================================================
+// E1 — Width playground
+// ============================================================================
+
+const WIDTHS = [
+ { value: "360", label: "360px", note: "Phone or narrow sheet → 1 column" },
+ { value: "560", label: "560px", note: "Dialog md → 2 columns" },
+ { value: "760", label: "760px", note: "Dialog lg / sheet lg → 3 columns" },
+ { value: "1040", label: "1040px", note: "Page → 4 columns" },
+];
+
+function WidthPlayground() {
+ const [width, setWidth] = React.useState("760");
+ return (
+
+
+ One field set with columns={4} and mixed spans. Pick a container
+ width and watch it reflow — the grid reads its container, not the window.
+
+
setWidth(String(value))}>
+
+ {WIDTHS.map((option) => (
+
+ {option.label}
+
+ ))}
+
+
+
+ {WIDTHS.find((option) => option.value === width)?.note}
+
+
+
+
+
+ Product name · span 2
+
+
+
+ SKU
+
+
+
+ Status
+
+
+
+ Supplier · span 3
+
+
+
+ Currency
+
+
+
+ Unit cost
+
+
+
+ Retail price
+
+
+
+ MOQ
+
+
+
+ Lead time (days)
+
+
+
+ Notes · span full
+
+
+
+
+
+
+ );
+}
+
+// ============================================================================
+// E2 — Dense master record: per-section columns + nested groups
+// ============================================================================
+
+function DenseItemMaster() {
+ return (
+
+
+ Each section picks its own column count. Billing and shipping are two{" "}
+ Fieldset.Root span={2} groups side by side, each holding a nested
+ FormLayout that reflows inside its half.
+
+
+
+
+
+ Legal name
+
+
+
+ Trading name
+
+
+
+ Supplier code
+
+
+
+ Tax ID
+
+
+
+ Category
+
+
+
+ Account owner
+
+
+
+ Supplier since
+
+
+
+
+ {/* 🔽 Narrow numeric fields: four across, even on a medium page */}
+
+
+ Currency
+
+
+
+ Payment terms
+
+
+
+ Credit limit
+
+
+
+ Early-pay discount %
+
+
+
+ Default lead time
+
+
+
+ Minimum order
+
+
+
+ Preferred carrier
+
+
+
+ Receiving warehouse
+
+
+
+
+ {/* 🔽 Two address groups side by side, each a nested two-column layout */}
+
+
+ Billing address
+
+
+
+ Shipping address
+
+
+
+
+ {/* 🔽 Long text gets fewer, wider columns */}
+
+
+ Quality notes
+
+
+
+ Internal notes
+
+
+
+
+
+
+ );
+}
+
+// ============================================================================
+// E3 — Conditional fields, header actions, locked section
+// ============================================================================
+
+function ConditionalFields() {
+ const [dropShip, setDropShip] = React.useState(false);
+ const [rush, setRush] = React.useState(false);
+ return (
+
+
+ Fields appear and disappear without the layout jumping: a checkbox reveals a nested address
+ group, a section has a header action, and a confirmed section is disabled as a whole.
+
+
+
+
+ Copy from supplier
+
+ }
+ >
+
+ Ship to
+
+
+
+ Carrier
+
+
+
+ Expected delivery
+
+
+
+ setDropShip(checked === true)}
+ />
+
+ {dropShip && (
+
+
+
+ )}
+
+ setRush(checked === true)}
+ />
+
+ {rush && (
+ <>
+
+ Reason for rush
+
+
+
+ Rush fee
+
+
+ >
+ )}
+
+
+ Confirmed}
+ disabled
+ >
+
+ Approved by
+
+
+
+ Approved on
+
+
+
+ Budget line
+
+
+
+
+
+
+ );
+}
+
+// ============================================================================
+// E4 — Form beside a sticky summary
+// ============================================================================
+
+function FormWithSummary() {
+ return (
+
+
+ A Grid puts the form next to a 320px summary on wide screens and stacks them on
+ narrow ones. The form's own columns adapt to whatever width is left.
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* 🔽 Summary panel */}
+
+
+
+ {/* 🧪 Dummy Data: Replace with real data later */}
+
+ Lines
+ 3
+ Units
+ 276
+ Subtotal
+ $11,556.00
+ Freight (est.)
+ $420.00
+ Total
+ $11,976.00
+
+
+
+
+
+ );
+}
+
+// ============================================================================
+// E5 — Document with editable line items (DataTable inline editing)
+// ============================================================================
+
+type Line = {
+ id: string;
+ item: string | null;
+ quantity: number | null;
+ unitPrice: number | null;
+ discount: number | null;
+};
+
+// 🧪 Dummy Data: Replace with real data later
+const ITEM_OPTIONS = [
+ { value: "DT-HD-BLK-M", label: "Cotton Wreath Hoodie — Black / M" },
+ { value: "DT-HD-BLK-L", label: "Cotton Wreath Hoodie — Black / L" },
+ { value: "DT-JN-IND-32", label: "Selvedge Jean — Indigo / 32" },
+ { value: "DT-TS-WHT-M", label: "Heavyweight Tee — White / M" },
+];
+// 🧪 Dummy Data: Replace with real data later
+const INITIAL_LINES: Line[] = [
+ { id: "1", item: "DT-HD-BLK-M", quantity: 120, unitPrice: 38.5, discount: 0 },
+ { id: "2", item: "DT-HD-BLK-L", quantity: 96, unitPrice: 38.5, discount: 5 },
+ { id: "3", item: "DT-JN-IND-32", quantity: 60, unitPrice: 54, discount: 0 },
+];
+
+const lineAmount = (line: Line) =>
+ (line.quantity ?? 0) * (line.unitPrice ?? 0) * (1 - (line.discount ?? 0) / 100);
+
+const { column } = createColumnHelper();
+
+function DocumentWithLineItems() {
+ // Same locale as the table's money cells, so totals and cells read alike.
+ const { locale } = useResolvedLocale();
+ const money = (n: number) =>
+ new Intl.NumberFormat(locale, { style: "currency", currency: "USD" }).format(n);
+ const [lines, setLines] = React.useState(INITIAL_LINES);
+ const nextId = React.useRef(INITIAL_LINES.length + 1);
+ const patch = (id: string, change: Partial) =>
+ setLines((current) => current.map((line) => (line.id === id ? { ...line, ...change } : line)));
+
+ const table = useDataTable({
+ data: { rows: lines },
+ columns: [
+ column({
+ id: "item",
+ label: "Item",
+ type: "text",
+ footer: "Total",
+ edit: {
+ options: ITEM_OPTIONS,
+ onValueCommitted: (row, value) => {
+ if (value === null) throw new CellEditError("Choose an item");
+ patch(row.id, { item: value });
+ },
+ },
+ }),
+ column({
+ id: "quantity",
+ label: "Quantity",
+ type: "number",
+ width: 120,
+ typeOptions: { maxDecimals: 0 },
+ footer: aggregations.sum((row) => row.quantity),
+ edit: {
+ onValueCommitted: (row, value) => {
+ if (value === null || !Number.isInteger(value) || value <= 0) {
+ throw new CellEditError("Enter a whole number above 0");
+ }
+ patch(row.id, { quantity: value });
+ },
+ },
+ }),
+ column({
+ id: "unitPrice",
+ label: "Unit price",
+ type: "money",
+ width: 130,
+ typeOptions: { currency: "USD" },
+ edit: {
+ onValueCommitted: (row, value) => {
+ if (value === null || value < 0) throw new CellEditError("Enter a price of 0 or more");
+ patch(row.id, { unitPrice: value });
+ },
+ },
+ }),
+ column({
+ id: "discount",
+ label: "Discount %",
+ type: "number",
+ width: 120,
+ edit: {
+ onValueCommitted: (row, value) => {
+ if (value !== null && (value < 0 || value > 100)) {
+ throw new CellEditError("Enter 0–100");
+ }
+ patch(row.id, { discount: value });
+ },
+ },
+ }),
+ column({
+ id: "amount",
+ label: "Amount",
+ type: "money",
+ width: 140,
+ accessor: lineAmount,
+ typeOptions: { currency: "USD" },
+ footer: aggregations.sum(lineAmount, (total) => money(total ?? 0)),
+ }),
+ ],
+ });
+
+ const subtotal = lines.reduce((sum, line) => sum + lineAmount(line), 0);
+ const tax = subtotal * 0.1;
+
+ return (
+
+
+ Header fields four across, then a DataTable with inline-editable cells, footer
+ totals and an add-line action in the section header. Click a quantity, price or item to edit
+ it; totals update as you confirm.
+
+
+
+
+
+
+
+
+
+ setLines((current) => [
+ ...current,
+ {
+ id: String(nextId.current++),
+ item: null,
+ quantity: 1,
+ unitPrice: 0,
+ discount: 0,
+ },
+ ])
+ }
+ >
+ Add line
+
+ }
+ >
+
+
+
+
+
+
+ {/* 🔽 Totals block, right-aligned under the table */}
+
+
+ Subtotal
+
+ {money(subtotal)}
+
+ Tax (10%)
+
+ {money(tax)}
+
+ Total
+
+ {money(subtotal + tax)}
+
+
+
+
+
+
+ Draft · {lines.length} lines
+
+ }
+ >
+
+ Save draft
+
+ Submit for approval
+
+
+
+
+ );
+}
+
+// ============================================================================
+
+export function ComplexExamples() {
+ return (
+
+
+
+
+
+
+
+ );
+}
diff --git a/examples/vite-app/src/pages/showcase/form-templates/document/page.tsx b/examples/vite-app/src/pages/showcase/form-templates/document/page.tsx
new file mode 100644
index 000000000..3bb6b6315
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/document/page.tsx
@@ -0,0 +1,12 @@
+import { type AppShellPageProps } from "@tailor-platform/app-shell";
+import { DocumentForm } from "../page-templates";
+
+const Page = () => ;
+
+Page.appShellPageProps = {
+ meta: {
+ title: "Document Form",
+ },
+} satisfies AppShellPageProps;
+
+export default Page;
diff --git a/examples/vite-app/src/pages/showcase/form-templates/field-types.tsx b/examples/vite-app/src/pages/showcase/form-templates/field-types.tsx
new file mode 100644
index 000000000..b55b28fdb
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/field-types.tsx
@@ -0,0 +1,214 @@
+import * as React from "react";
+import {
+ Attachment,
+ Autocomplete,
+ Button,
+ Checkbox,
+ Combobox,
+ DateField,
+ DatePicker,
+ DateRangePicker,
+ Field,
+ Fieldset,
+ Form,
+ FormLayout,
+ Select,
+ Text,
+ Textarea,
+ useAttachment,
+ useToast,
+ type AttachmentItem,
+} from "@tailor-platform/app-shell";
+import { BUYERS, CARRIERS, DEPARTMENTS, PAYMENT_TERMS, SUPPLIERS } from "./fields";
+
+// 🔽 Field types — every control AppShell has, inside one FormLayout, so you
+// can see how each one sits in the grid and how far it spans by default.
+
+// 🧪 Dummy Data: Replace with real data later
+const TAGS = ["Seasonal", "Reorder", "Sample", "Wholesale", "Drop ship"];
+
+// 🧪 Dummy Data: Replace with real data later
+const INITIAL_FILES: AttachmentItem[] = [
+ { id: "quote", fileName: "Kansai-quote-Q4.pdf", mimeType: "application/pdf" },
+ { id: "spec", fileName: "Hoodie-spec-sheet.xlsx", mimeType: "application/vnd.ms-excel" },
+];
+
+export function FieldTypes() {
+ const toast = useToast();
+ // A server-side error (e.g. a duplicate) shown until the user edits the value.
+ const [taxIdTaken, setTaxIdTaken] = React.useState(true);
+ const files = useAttachment({
+ initialItems: INITIAL_FILES,
+ accept: ".pdf,.xlsx,.csv,image/*",
+ });
+
+ return (
+
+
+ Field types
+
+ Every control in one form. Short controls take one column; text areas, checkbox groups,
+ date ranges and file uploads span the row. Submit with empty required fields to see the
+ errors.
+
+
+
+
toast.success("Saved")}>
+
+ {/* 🔽 Text and numbers */}
+
+
+ Item name
+
+ Enter a name.
+
+
+ Supplier email
+
+ Enter a valid email address.
+
+
+ Phone
+
+
+
+ Quantity
+
+ Units, minimum 1.
+ Order at least 1 unit.
+
+
+ Unit price (USD)
+
+
+ {/* 🧪 Dummy Data: Replace with real data later */}
+
+ Tax ID
+ setTaxIdTaken(false)} />
+
+ This tax ID is already on another supplier. Edit it to save.
+
+
+
+ Notes
+
+ Shown on the receiving note.
+
+
+
+ {/* 🔽 Choices */}
+
+
+ Payment terms
+
+ Choose payment terms.
+
+
+ Departments
+
+ Select, several at once.
+
+
+ Supplier
+
+ Combobox: search a fixed list.
+ Choose a supplier.
+
+
+ Tags
+
+ Combobox, several at once.
+
+
+ Carrier
+
+ Autocomplete: suggestions, any text allowed.
+
+
+ Buyer
+
+ Disabled: set from your account.
+
+
+ Notify on receipt
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* 🔽 Dates */}
+
+
+ Order date
+
+ Enter the order date.
+
+
+ Expected delivery
+
+
+
+ Delivery window
+
+ The dock accepts the goods on these dates.
+
+
+
+ {/* 🔽 Files */}
+
+
+
+
+
+
+ {/* 🔽 Read-only values */}
+
+ {/* 🧪 Dummy Data: Replace with real data later */}
+
+ PO number
+ PO-10000041
+
+
+ Created by
+ Kenji Mori
+
+
+ Created on
+ 28 Oct 2026
+
+
+
+
+
+ Reset
+
+ Save
+
+
+
+
+ );
+}
diff --git a/examples/vite-app/src/pages/showcase/form-templates/fields.tsx b/examples/vite-app/src/pages/showcase/form-templates/fields.tsx
new file mode 100644
index 000000000..d7f97daa2
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/fields.tsx
@@ -0,0 +1,176 @@
+import {
+ Checkbox,
+ Combobox,
+ DatePicker,
+ Field,
+ FormLayout,
+ Select,
+ Textarea,
+} from "@tailor-platform/app-shell";
+
+// One set of purchase-order fields, reused by every template so the only
+// thing that changes between them is the container and the column count.
+
+// 🧪 Dummy Data: Replace with real data later
+export const SUPPLIERS = [
+ "Acme Industrial Supplies",
+ "Kansai Textile Co.",
+ "Northwind Fabrics",
+ "Osaka Trim & Notions",
+ "Pacific Packaging Ltd.",
+];
+// 🧪 Dummy Data: Replace with real data later
+export const WAREHOUSES = ["Tokyo DC", "Osaka DC", "Nagoya DC", "Austin Main Warehouse"];
+// 🧪 Dummy Data: Replace with real data later
+export const CURRENCIES = ["USD", "EUR", "GBP", "JPY"];
+// 🧪 Dummy Data: Replace with real data later
+export const PAYMENT_TERMS = ["Net 15", "Net 30", "Net 60", "Due on receipt"];
+// 🧪 Dummy Data: Replace with real data later
+export const INCOTERMS = ["EXW", "FOB", "CIF", "DAP", "DDP"];
+// 🧪 Dummy Data: Replace with real data later
+export const CARRIERS = ["Yamato Transport", "Sagawa Express", "DHL", "FedEx Freight"];
+// 🧪 Dummy Data: Replace with real data later
+export const BUYERS = ["Hanna Suzuki", "Kenji Mori", "Priya Nair", "Sam Taylor"];
+// 🧪 Dummy Data: Replace with real data later
+export const DEPARTMENTS = ["Merchandising", "Operations", "Wholesale", "Retail"];
+// 🧪 Dummy Data: Replace with real data later
+export const COUNTRIES = ["Japan", "United States", "United Kingdom", "Vietnam", "Portugal"];
+
+// 🔽 Supplier fields
+export function SupplierFields() {
+ return (
+ <>
+
+ Supplier
+
+ Choose a supplier.
+
+
+ Supplier reference
+
+
+
+ Currency
+
+
+
+ Payment terms
+
+
+ >
+ );
+}
+
+// 🔽 Delivery fields
+export function DeliveryFields({ withInstructions = true }: { withInstructions?: boolean }) {
+ return (
+ <>
+
+ Ship to
+
+ Choose a warehouse.
+
+
+ Expected delivery
+
+
+
+ Incoterms
+
+
+
+ Carrier
+
+
+ {withInstructions && (
+
+ Delivery instructions
+
+
+ )}
+ >
+ );
+}
+
+// 🔽 Billing & notes fields
+export function BillingFields() {
+ return (
+ <>
+
+ Buyer
+
+
+
+ Department
+
+
+
+ Cost center
+
+
+
+ Internal notes
+
+ Not printed on the purchase order.
+
+
+
+
+ >
+ );
+}
+
+// 🔽 Supplier master fields (quick create)
+export function NewSupplierFields() {
+ return (
+ <>
+
+ Supplier name
+
+ Enter a supplier name.
+
+
+ Code
+
+ Enter a code.
+
+
+ Country
+
+
+
+ Email
+
+ Enter a valid email.
+
+
+ Phone
+
+
+ >
+ );
+}
+
+// 🔽 Reusable address block — a nested FormLayout reflows inside whatever span it gets
+export function AddressFields({ prefix }: { prefix: string }) {
+ return (
+
+
+ Street
+
+
+
+ City
+
+
+
+ Postcode
+
+
+
+ Country
+
+
+
+ );
+}
diff --git a/examples/vite-app/src/pages/showcase/form-templates/overlay-templates.tsx b/examples/vite-app/src/pages/showcase/form-templates/overlay-templates.tsx
new file mode 100644
index 000000000..1851d43d6
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/overlay-templates.tsx
@@ -0,0 +1,89 @@
+import * as React from "react";
+import { Button, Dialog, Form, Sheet } from "@tailor-platform/app-shell";
+
+// Overlay templates: the form opens on top of the current page. Each one puts
+// `Form id` inside the scrolling body and submits from the footer with
+// `form=""`, so the footer stays visible however long the form gets.
+
+// 🔽 T1 — Modal form. One template at every size: `size` follows the form's
+// length (sm/md for a handful of fields, lg/xl once it needs plain sections).
+export function ModalForm({
+ trigger,
+ size = "md",
+ title,
+ description,
+ submitLabel,
+ children,
+}: {
+ trigger: React.ReactElement;
+ size?: React.ComponentProps["size"];
+ title: string;
+ description?: string;
+ submitLabel: string;
+ children: React.ReactNode;
+}) {
+ const [open, setOpen] = React.useState(false);
+ const formId = React.useId();
+ return (
+
+
+
+
+ {title}
+ {description != null && {description} }
+
+
+ setOpen(false)}>
+ {children}
+
+
+
+ }>Cancel
+
+ {submitLabel}
+
+
+
+
+ );
+}
+
+// 🔽 T2 — Side sheet (edit while keeping the list or detail in view)
+export function SheetForm({
+ trigger,
+ title,
+ description,
+ submitLabel,
+ children,
+}: {
+ trigger: React.ReactElement;
+ title: string;
+ description?: string;
+ submitLabel: string;
+ children: React.ReactNode;
+}) {
+ const [open, setOpen] = React.useState(false);
+ const formId = React.useId();
+ return (
+
+
+
+
+ {title}
+ {description != null && {description} }
+
+
+
setOpen(false)}>
+ {children}
+
+
+
+ }>Cancel
+
+ {submitLabel}
+
+
+
+
+ );
+}
diff --git a/examples/vite-app/src/pages/showcase/form-templates/overview.tsx b/examples/vite-app/src/pages/showcase/form-templates/overview.tsx
new file mode 100644
index 000000000..bb212988d
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/overview.tsx
@@ -0,0 +1,219 @@
+import * as React from "react";
+import {
+ Badge,
+ Button,
+ Card,
+ FormLayout,
+ Grid,
+ Layout,
+ Table,
+ Text,
+ useNavigate,
+} from "@tailor-platform/app-shell";
+import { ComplexExamples } from "./complex-examples";
+import { DeliveryFields, NewSupplierFields, SupplierFields } from "./fields";
+import { FieldTypes } from "./field-types";
+import { ModalForm, SheetForm } from "./overlay-templates";
+
+type Template = {
+ id: string;
+ name: string;
+ when: string;
+ container: string;
+ columns: string;
+ action: React.ReactNode;
+};
+
+// 🧪 Dummy Data: Replace with real data later
+const ROUTES = {
+ page: "/showcase/form-templates/page",
+ document: "/showcase/form-templates/document",
+};
+
+// ✅ Reusable Component: Can be moved to components/ui/
+function TemplateCard({ template }: { template: Template }) {
+ return (
+
+
+ {template.id}
+ {template.name}
+
+ }
+ description={template.when}
+ />
+
+
+ Container
+ {template.container}
+ Columns
+ {template.columns}
+
+ {template.action}
+
+
+ );
+}
+
+export function FormTemplatesOverview() {
+ const navigate = useNavigate();
+
+ const templates: Template[] = [
+ {
+ id: "T1",
+ name: "Modal form",
+ when: "Create or edit without leaving the page. Pick the size by the form's length; add plain sections once it has groups.",
+ container: 'Dialog size="sm" – "xl"',
+ columns: "Up to 2",
+ action: (
+ <>
+ Open md · 6 fields }
+ >
+
+
+
+
+ Open lg · 12 fields }
+ >
+
+
+
+
+
+
+
+
+
+ >
+ ),
+ },
+ {
+ id: "T2",
+ name: "Side sheet",
+ when: "Edit part of a record while the list or detail stays in view.",
+ container: 'Sheet size="lg"',
+ columns: "Up to 2",
+ action: (
+ Open sheet}
+ >
+
+
+
+
+ ),
+ },
+ {
+ id: "T3",
+ name: "Page form",
+ when: "The form needs its own URL. Card sections, a sticky action bar, and an optional section nav — on by default from three sections.",
+ container: 'Layout maxWidth="lg" (or "xl" with the nav)',
+ columns: "Up to 2 per section",
+ action: (
+ <>
+ navigate(`${ROUTES.page}?nav=1`)}>
+ With section nav
+
+ navigate(`${ROUTES.page}?nav=0`)}>
+ Without
+
+ >
+ ),
+ },
+ {
+ id: "T4",
+ name: "Document form",
+ when: "Header fields plus line items: PO, GR, invoice. Sections follow the document's view page.",
+ container: 'Layout maxWidth="xl"',
+ columns: "Up to 4 for the header",
+ action: (
+ navigate(ROUTES.document)}>
+ Open document
+
+ ),
+ },
+ ];
+
+ return (
+
+
+
+
+ Every template uses the same purchase-order fields. Only the container and the maximum
+ column count change: FormLayout reflows by the width of its container, so one field
+ definition fits a dialog, a sheet and a page.
+
+
+ {/* 🔽 Template catalogue */}
+
+ {templates.map((template) => (
+
+ ))}
+
+
+ {/* 🔽 Choosing a template */}
+
+
+
+
+
+
+ If the form…
+ Use
+
+
+
+ {/* 🧪 Dummy Data: Replace with real data later */}
+ {[
+ ["Has line items (a document with header and lines)", "T4 Document form"],
+ [
+ "Has ordered steps that depend on earlier answers",
+ "A wizard (form/wizard pattern)",
+ ],
+ ["Needs its own URL, or is long enough to scroll a page", "T3 Page form"],
+ ["Edits part of a record shown beside it", "T2 Side sheet"],
+ ["Everything else", "T1 Modal form, sized to fit"],
+ ].map(([condition, use]) => (
+
+ {condition}
+ {use}
+
+ ))}
+
+
+
+
+
+ {/* 🔽 Field types */}
+
+
+ {/* 🔽 Complex examples */}
+
+ Complex examples
+
+ How far FormLayout stretches: container-driven reflow, dense records, nested groups,
+ conditional fields, a summary panel and editable line items.
+
+
+
+
+
+ );
+}
diff --git a/examples/vite-app/src/pages/showcase/form-templates/page-templates.tsx b/examples/vite-app/src/pages/showcase/form-templates/page-templates.tsx
new file mode 100644
index 000000000..70cea7f44
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/page-templates.tsx
@@ -0,0 +1,336 @@
+import type { MouseEvent } from "react";
+import {
+ Button,
+ Checkbox,
+ Combobox,
+ DatePicker,
+ Field,
+ Fieldset,
+ Form,
+ FormLayout,
+ Input,
+ ItemList,
+ Layout,
+ Select,
+ Table,
+ Text,
+ Textarea,
+ useAppShellScrollContainer,
+ useNavigate,
+} from "@tailor-platform/app-shell";
+import { AddressFields, BillingFields, BUYERS, DeliveryFields, SupplierFields } from "./fields";
+
+// Page templates: the form owns the route. Save sits in `Layout.Header` and
+// reaches the form through `form=""`; long forms add a sticky action bar.
+
+const BACK = "/showcase/form-templates";
+
+// 🔽 T3 — Page form. Sections are cards; the section nav is opt-in.
+// Most sections are long enough to scroll past; Approval stays short.
+// 🧪 Dummy Data: Replace with real data later
+const SECTIONS = [
+ { id: "supplier", title: "Supplier", description: "Who you are buying from and on what terms." },
+ { id: "delivery", title: "Delivery", description: "Where and when the goods arrive." },
+ { id: "billing", title: "Billing", description: "Which entity is invoiced, and how." },
+ { id: "approval", title: "Approval", description: "Who signs off before the PO is sent." },
+ { id: "ownership", title: "Ownership & notes", description: "Internal ownership and notes." },
+];
+const anchorIdFor = (id: string) => `page-form-section-${id}`;
+const sectionProps = (index: number) => ({
+ id: anchorIdFor(SECTIONS[index].id),
+ title: SECTIONS[index].title,
+ description: SECTIONS[index].description,
+});
+
+// 🧪 Dummy Data: Replace with real data later
+const ENTITIES = ["Denim Tears Inc. (US)", "Denim Tears KK (Japan)", "Denim Tears Ltd. (UK)"];
+// 🧪 Dummy Data: Replace with real data later
+const TAX_CODES = ["Standard 10%", "Reduced 8%", "Exempt", "Reverse charge"];
+// 🧪 Dummy Data: Replace with real data later
+const MATCHING = ["2-way (PO + invoice)", "3-way (PO + receipt + invoice)"];
+
+export function PageForm({
+ // Not a rule: a default you can override. A nav earns its space once there
+ // are enough sections to jump between.
+ sectionNav = SECTIONS.length >= 3,
+}: {
+ sectionNav?: boolean;
+}) {
+ const navigate = useNavigate();
+ const scrollRef = useAppShellScrollContainer();
+
+ // Scroll the content area, not the browser's default anchor jump: that also
+ // scrolls the shell's outer frame, shifting the header and sidebar out of place.
+ const jumpTo = (event: MouseEvent, anchorId: string) => {
+ const container = scrollRef.current;
+ const target = document.getElementById(anchorId);
+ if (!container || !target) return;
+ event.preventDefault();
+ const top =
+ target.getBoundingClientRect().top -
+ container.getBoundingClientRect().top +
+ container.scrollTop -
+ 16;
+ container.scrollTo({ top, behavior: "smooth" });
+ window.history.replaceState(window.history.state, "", `#${anchorId}`);
+ };
+
+ const form = (
+ navigate(BACK)}>
+
+ {/* 🔽 Supplier — long */}
+
+
+
+ Supplier contact
+
+
+
+ Contact email
+
+ Enter a valid email address.
+
+
+ Quote number
+
+
+
+ Quote valid until
+
+
+
+ Note to supplier
+
+
+
+
+ {/* 🔽 Delivery — long, with an address group */}
+
+
+
+ Delivery address
+
+
+
+ Delivery instructions
+
+
+
+
+
+
+
+ {/* 🔽 Billing — long, with an address group */}
+
+
+ Bill to
+
+
+
+ Invoices from supplier to
+
+ Enter a valid email address.
+
+
+ Tax code
+
+
+
+ Invoice matching
+
+ 3-way holds payment until the goods are received.
+
+
+ Billing address
+
+
+
+
+ {/* 🔽 Approval — deliberately short */}
+
+
+ Approver
+
+ Choose an approver.
+
+
+ Approve by
+
+
+
+
+ {/* 🔽 Ownership & notes */}
+
+
+
+
+ Draft · not saved yet
+
+ }
+ >
+ navigate(BACK)}>
+ Cancel
+
+ Create
+
+
+
+ );
+
+ return (
+ // The nav takes a column of its own, so the page widens to keep the form's width
+
+ navigate(BACK)}>
+ Cancel
+ ,
+
+ Create
+ ,
+ ]}
+ />
+ {/* Layout counts its direct Layout.Column children to build the grid,
+ so the columns can't sit inside a fragment. */}
+ {sectionNav && (
+ // 🔽 Section nav — sticky beside the form on wide screens
+
+
+ {SECTIONS.map((section) => (
+ jumpTo(event, anchorIdFor(section.id))}
+ />
+ }
+ >
+ {section.title}
+
+ ))}
+
+
+ )}
+ {form}
+
+ );
+}
+
+// 🔽 T4 — Document form (header fields + line items)
+// 🧪 Dummy Data: Replace with real data later
+const LINES = [
+ { sku: "DT-HD-BLK-M", name: "Cotton Wreath Hoodie — Black / M", qty: 120, price: 38.5 },
+ { sku: "DT-HD-BLK-L", name: "Cotton Wreath Hoodie — Black / L", qty: 96, price: 38.5 },
+ { sku: "DT-JN-IND-32", name: "Selvedge Jean — Indigo / 32", qty: 60, price: 54.0 },
+];
+const money = (n: number) =>
+ n.toLocaleString("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 });
+// Example-app utilities lose to the table's own alignment classes, so set it inline.
+const RIGHT = { textAlign: "right" } as const;
+const total = LINES.reduce((sum, line) => sum + line.qty * line.price, 0);
+
+export function DocumentForm() {
+ const navigate = useNavigate();
+ return (
+
+ navigate(BACK)}>
+ Cancel
+ ,
+
+ Create
+ ,
+ ]}
+ />
+
+ navigate(BACK)}>
+
+ {/* 🔽 Header fields — four across on wide screens */}
+
+
+
+
+
+ {/* 🔽 Line items — LineItems (as#676) replaces this Table once it ships */}
+
+ {/* Out to the card's edges: the table pads its own first and last cells */}
+
+
+
+
+ Item
+
+ Quantity
+
+
+ Unit price
+
+
+ Amount
+
+
+
+
+ {LINES.map((line) => (
+
+
+
+ {line.name}
+ {line.sku}
+
+
+
+
+
+
+ {money(line.price)}
+
+
+ {money(line.qty * line.price)}
+
+
+ ))}
+
+
+
+
+ Total
+
+
+ {money(total)}
+
+
+
+
+
+
+
+
+
+ Note to supplier
+
+
+
+ Internal note
+
+
+
+
+
+
+
+ );
+}
diff --git a/examples/vite-app/src/pages/showcase/form-templates/page.tsx b/examples/vite-app/src/pages/showcase/form-templates/page.tsx
new file mode 100644
index 000000000..e3fa122fa
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/page.tsx
@@ -0,0 +1,12 @@
+import { type AppShellPageProps } from "@tailor-platform/app-shell";
+import { FormTemplatesOverview } from "./overview";
+
+const Page = () => ;
+
+Page.appShellPageProps = {
+ meta: {
+ title: "Form Templates",
+ },
+} satisfies AppShellPageProps;
+
+export default Page;
diff --git a/examples/vite-app/src/pages/showcase/form-templates/page/page.tsx b/examples/vite-app/src/pages/showcase/form-templates/page/page.tsx
new file mode 100644
index 000000000..cfcff64a6
--- /dev/null
+++ b/examples/vite-app/src/pages/showcase/form-templates/page/page.tsx
@@ -0,0 +1,18 @@
+import { type AppShellPageProps, useSearchParams } from "@tailor-platform/app-shell";
+import { PageForm } from "../page-templates";
+
+// `?nav=1` / `?nav=0` turns the section nav on or off; without it the
+// template's default applies.
+const Page = () => {
+ const [searchParams] = useSearchParams();
+ const nav = searchParams.get("nav");
+ return ;
+};
+
+Page.appShellPageProps = {
+ meta: {
+ title: "Page Form",
+ },
+} satisfies AppShellPageProps;
+
+export default Page;
diff --git a/examples/vite-app/src/routes.generated.ts b/examples/vite-app/src/routes.generated.ts
index dfc93c810..59e302070 100644
--- a/examples/vite-app/src/routes.generated.ts
+++ b/examples/vite-app/src/routes.generated.ts
@@ -39,6 +39,9 @@ export type GeneratedRouteParams = {
"/showcase/document-progress": {};
"/showcase/dropdown": {};
"/showcase/filter-rail": {};
+ "/showcase/form-templates": {};
+ "/showcase/form-templates/document": {};
+ "/showcase/form-templates/page": {};
"/showcase/forms": {};
"/showcase/forms/zod-rhf": {};
"/showcase/grid": {};
diff --git a/packages/core/__snapshots__/src__components__dialog__dialog.test.tsx.snap b/packages/core/__snapshots__/src__components__dialog__dialog.test.tsx.snap
index 6d28e1242..4b4ec1f29 100644
--- a/packages/core/__snapshots__/src__components__dialog__dialog.test.tsx.snap
+++ b/packages/core/__snapshots__/src__components__dialog__dialog.test.tsx.snap
@@ -2,6 +2,6 @@
exports[`Dialog > snapshots > closed dialog (trigger only) 1`] = `"Open "`;
-exports[`Dialog > snapshots > open dialog with header 1`] = `"Open
Dialog Title Dialog description text
Close "`;
+exports[`Dialog > snapshots > open dialog with header 1`] = `"Open
Dialog Title Dialog description text
Close "`;
-exports[`Dialog > snapshots > open dialog with header and footer 1`] = `"Open
Confirm Action Are you sure?
Cancel Confirm
Close "`;
+exports[`Dialog > snapshots > open dialog with header and footer 1`] = `"Open
Confirm Action Are you sure?
Cancel Confirm
Close "`;
diff --git a/packages/core/__snapshots__/src__components__form-layout__form-layout.test.tsx.snap b/packages/core/__snapshots__/src__components__form-layout__form-layout.test.tsx.snap
new file mode 100644
index 000000000..3401d3264
--- /dev/null
+++ b/packages/core/__snapshots__/src__components__form-layout__form-layout.test.tsx.snap
@@ -0,0 +1,7 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`FormLayout > snapshots > card section with header and actions 1`] = `"
Delivery Where goods arrive
Copy
"`;
+
+exports[`FormLayout > snapshots > fields in a two-column grid 1`] = `""`;
+
+exports[`FormLayout > snapshots > plain section 1`] = `""`;
diff --git a/packages/core/__snapshots__/src__components__sheet__sheet.test.tsx.snap b/packages/core/__snapshots__/src__components__sheet__sheet.test.tsx.snap
index d81091df3..9fc44f599 100644
--- a/packages/core/__snapshots__/src__components__sheet__sheet.test.tsx.snap
+++ b/packages/core/__snapshots__/src__components__sheet__sheet.test.tsx.snap
@@ -8,4 +8,4 @@ exports[`Sheet > snapshots > open sheet (left side) 1`] = `"Open
"`;
-exports[`Sheet > snapshots > open sheet with header and footer 1`] = `"Open
"`;
+exports[`Sheet > snapshots > open sheet with header and footer 1`] = `"Open
"`;
diff --git a/packages/core/__snapshots__/src__components__tree-picker__tree-picker.test.tsx.snap b/packages/core/__snapshots__/src__components__tree-picker__tree-picker.test.tsx.snap
index c61a78395..adc541112 100644
--- a/packages/core/__snapshots__/src__components__tree-picker__tree-picker.test.tsx.snap
+++ b/packages/core/__snapshots__/src__components__tree-picker__tree-picker.test.tsx.snap
@@ -2,10 +2,10 @@
exports[`TreePicker > snapshots > closed 1`] = `"Reopen "`;
-exports[`TreePicker > snapshots > empty state 1`] = `"Reopen
Bulk picker Cancel Add items
Close "`;
+exports[`TreePicker > snapshots > empty state 1`] = `"Reopen
Bulk picker Cancel Add items
Close "`;
-exports[`TreePicker > snapshots > expanded parent with a partial selection 1`] = `"Reopen
Bulk picker Cancel Add 1 item
Close "`;
+exports[`TreePicker > snapshots > expanded parent with a partial selection 1`] = `"Reopen
Bulk picker Cancel Add 1 item
Close "`;
-exports[`TreePicker > snapshots > open with a filter slot 1`] = `"Reopen
Bulk picker Cancel Add items
Close "`;
+exports[`TreePicker > snapshots > open with a filter slot 1`] = `"Reopen
Bulk picker Cancel Add items
Close "`;
-exports[`TreePicker > snapshots > open with collapsed tree 1`] = `"Reopen
Bulk picker Cancel Add items
Close "`;
+exports[`TreePicker > snapshots > open with collapsed tree 1`] = `"Reopen
Bulk picker Cancel Add items
Close "`;
diff --git a/packages/core/src/components/activity-card/activity-card.test.tsx b/packages/core/src/components/activity-card/activity-card.test.tsx
index 59821a673..a2008adaf 100644
--- a/packages/core/src/components/activity-card/activity-card.test.tsx
+++ b/packages/core/src/components/activity-card/activity-card.test.tsx
@@ -54,6 +54,24 @@ describe("ActivityCard (standalone)", () => {
expect(screen.getByText("All activities")).toBeDefined();
});
+ it("scrolls the full list in the dialog's body, keeping the title in view", async () => {
+ const user = userEvent.setup();
+ const many = Array.from({ length: 8 }, (_, i) => ({
+ ...mockActivities[0],
+ id: `id-${i}`,
+ }));
+ render( );
+ await user.click(screen.getByText("2 more activities"));
+
+ // Only Dialog.Body shrinks in a dialog: a plain scrolling child would grow
+ // to its full height and scroll the whole panel, title included.
+ const dialog = await screen.findByRole("dialog");
+ const body = dialog.querySelector('[data-slot="dialog-body"]');
+ expect(body).not.toBeNull();
+ expect(body?.contains(screen.getByText("All activities"))).toBe(false);
+ expect(body?.querySelectorAll('[data-slot="activity-card-item"]')).toHaveLength(8);
+ });
+
it("uses count overflow label when overflowLabel is count", () => {
const many = Array.from({ length: 8 }, (_, i) => ({
...mockActivities[0],
diff --git a/packages/core/src/components/activity-card/activity-card.tsx b/packages/core/src/components/activity-card/activity-card.tsx
index 546ce5bad..9c8a620a4 100644
--- a/packages/core/src/components/activity-card/activity-card.tsx
+++ b/packages/core/src/components/activity-card/activity-card.tsx
@@ -239,10 +239,12 @@ function Items({ children }: ActivityCardItemsPr
All activities
- ({ children }: ActivityCardItemsPr
)}
>
{renderList(items, children, groupBy)}
-
+
>
diff --git a/packages/core/src/components/dialog/dialog.test.tsx b/packages/core/src/components/dialog/dialog.test.tsx
index 0378539a1..843b9e930 100644
--- a/packages/core/src/components/dialog/dialog.test.tsx
+++ b/packages/core/src/components/dialog/dialog.test.tsx
@@ -9,6 +9,7 @@ afterEach(() => {
});
const isPopup = (el: HTMLElement) => el.getAttribute("data-slot") === "dialog-content";
+const getDialogPanel = () => document.querySelector('[data-slot="dialog-content"]') as HTMLElement;
describe("Dialog", () => {
// ==========================================================================
@@ -200,6 +201,22 @@ describe("Dialog", () => {
});
});
+ it("right-aligns footer buttons at their own width at every size", () => {
+ render(
+
+
+ Footer
+
+ Save
+
+
+ ,
+ );
+ const footer = screen.getByText("Save").parentElement!;
+ expect(footer.className).toContain("astw:justify-end");
+ expect(footer.className).not.toContain("flex-col");
+ });
+
it("renders DialogFooter", async () => {
const user = userEvent.setup();
@@ -224,6 +241,80 @@ describe("Dialog", () => {
});
});
+ it("sizes the panel with the size prop, defaulting to md", () => {
+ const { rerender } = render(
+
+
+ Sized
+
+ ,
+ );
+ expect(getDialogPanel().className).toContain("astw:sm:max-w-[min(32rem,calc(100%-2rem))]");
+
+ rerender(
+
+
+ Sized
+
+ ,
+ );
+ expect(getDialogPanel().className).toContain("astw:sm:max-w-[min(60rem,calc(100%-2rem))]");
+ expect(getDialogPanel().className).not.toContain("32rem");
+ });
+
+ // lg and xl are wider than the sm breakpoint; a bare `sm:max-w-[45rem]`
+ // would replace the base margin and touch the screen edges up to 45rem.
+ it.each(["sm", "md", "lg", "xl"] as const)(
+ "keeps the 1rem side margin at every width for size %s",
+ (size) => {
+ render(
+
+
+ Sized
+
+ ,
+ );
+ const smMaxWidth = getDialogPanel()
+ .className.split(/\s+/)
+ .filter((c) => c.startsWith("astw:sm:max-w-"));
+ expect(smMaxWidth).toHaveLength(1);
+ expect(smMaxWidth[0]).toMatch(/^astw:sm:max-w-\[min\(\d+rem,calc\(100%-2rem\)\)\]$/);
+ },
+ );
+
+ it("only lets Dialog.Body shrink, so other children keep their height", () => {
+ render(
+
+
+ Long
+ Body content
+
+ ,
+ );
+ expect(getDialogPanel().className).toContain(
+ "astw:[&>*:not([data-slot=dialog-body])]:shrink-0",
+ );
+ const body = screen.getByText("Body content");
+ expect(body.className).toContain("astw:flex-1");
+ expect(body.className).toContain("astw:min-h-0");
+ });
+
+ it("caps the panel at the viewport height and scrolls Dialog.Body", () => {
+ render(
+
+
+ Long
+ Body content
+
+ ,
+ );
+ const panel = document.querySelector('[data-slot="dialog-content"]') as HTMLElement;
+ expect(panel.className).toContain("astw:max-h-[calc(100dvh-2rem)]");
+ const body = screen.getByText("Body content");
+ expect(body!.getAttribute("data-slot")).toBe("dialog-body");
+ expect(body.className).toContain("astw:overflow-y-auto");
+ });
+
it("closes dialog when pressing Escape", async () => {
const user = userEvent.setup();
@@ -283,18 +374,27 @@ describe("Dialog", () => {
expect(content.className).not.toContain("astw:overflow-y-auto");
});
- it("lets className switch to a flex column for a pinned header and footer", async () => {
+ it("scrolls Dialog.Body while the header and footer stay pinned", async () => {
render(
-
- Pinned
+
+
+ Pinned
+
+ Long content
+ Actions
,
);
const content = await screen.findByRole("dialog");
- expect(content.className).toContain("astw:flex");
- expect(content.className).not.toMatch(/(^|\s)astw:grid(\s|$)/);
+ expect(content.className).toContain("astw:flex-col");
+ // Every child but the body keeps its height; the body shrinks and scrolls.
+ expect(content.className).toContain("astw:[&>*:not([data-slot=dialog-body])]:shrink-0");
+ const body = screen.getByText("Long content");
+ expect(body.dataset.slot).toBe("dialog-body");
+ expect(body.className).toContain("astw:min-h-0");
+ expect(body.className).toContain("astw:overflow-y-auto");
});
});
// jsdom has no layout, so overflow is simulated by stubbing the popup's
diff --git a/packages/core/src/components/dialog/dialog.tsx b/packages/core/src/components/dialog/dialog.tsx
index 3ea07c60d..8867631f4 100644
--- a/packages/core/src/components/dialog/dialog.tsx
+++ b/packages/core/src/components/dialog/dialog.tsx
@@ -74,7 +74,24 @@ function Overlay({ className, ...props }: React.ComponentProps;
+type Size = "sm" | "md" | "lg" | "xl";
+
+// Same steps as `Sheet.Content`'s `size`, so a form keeps its width when it
+// moves between a dialog and a sheet. Each size keeps the base 1rem margin on
+// both sides (`min(…, 100% - 2rem)`): `lg` and `xl` are wider than the `sm`
+// breakpoint, so a plain `max-w-[45rem]` would touch the screen edges
+// between 640px and the size.
+const sizeClasses: Record = {
+ sm: "astw:sm:max-w-[min(24rem,calc(100%-2rem))]",
+ md: "astw:sm:max-w-[min(32rem,calc(100%-2rem))]",
+ lg: "astw:sm:max-w-[min(45rem,calc(100%-2rem))]",
+ xl: "astw:sm:max-w-[min(60rem,calc(100%-2rem))]",
+};
+
+type DialogContentProps = React.ComponentProps & {
+ /** Controls the max-width of the dialog panel (`sm` 24rem | `md` 32rem | `lg` 45rem | `xl` 60rem), always leaving a 1rem margin on each side. @default "md" */
+ size?: Size;
+};
const TABBABLE_SELECTOR =
'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"]), [contenteditable=""], [contenteditable="true"]';
@@ -90,8 +107,21 @@ function firstTabbable(root: HTMLElement): HTMLElement | null {
);
}
-/** The main dialog panel that contains the dialog content. Automatically includes a close button and overlay. */
-function Content({ className, children, ref, initialFocus, ...props }: DialogContentProps) {
+/**
+ * The main dialog panel that contains the dialog content. Automatically includes a close button and overlay.
+ *
+ * The panel never grows past the viewport height. Wrap long content (e.g. a
+ * form) in `Dialog.Body` so it scrolls while the header and footer stay put;
+ * without a `Body`, the whole panel scrolls.
+ */
+function Content({
+ className,
+ children,
+ ref,
+ initialFocus,
+ size = "md",
+ ...props
+}: DialogContentProps) {
const popupRef = React.useRef(null);
// Base UI focuses the first tabbable element on open (the popup itself on
@@ -125,8 +155,16 @@ function Content({ className, children, ref, initialFocus, ...props }: DialogCon
// inside the dialog instead of running off both edges, where the page
// behind it cannot scroll. 2rem matches the horizontal margin, and dvh
// follows the mobile browser bar as it shows and hides.
+ //
+ // In a flex column, children would shrink to fit the max height, and
+ // a child that is itself a scroll container (a table wrapper, any
+ // `overflow-*` block) would get its own scrollbar inside the dialog's.
+ // So only `Dialog.Body` shrinks; everything else keeps its height and
+ // the dialog scrolls instead.
className={cn(
- "astw:bg-card astw:data-open:animate-in astw:data-ending-style:animate-out astw:data-ending-style:fade-out-0 astw:data-open:fade-in-0 astw:data-ending-style:zoom-out-95 astw:data-open:zoom-in-95 astw:fill-mode-forwards astw:fixed astw:top-[50%] astw:left-[50%] astw:z-(--z-portal) astw:grid astw:w-full astw:max-w-[calc(100%-2rem)] astw:max-h-[calc(100dvh-2rem)] astw:overflow-y-auto astw:translate-x-[-50%] astw:translate-y-[-50%] astw:gap-4 astw:rounded-lg astw:border astw:border-border astw:p-6 astw:shadow-lg astw:duration-200 astw:sm:max-w-lg",
+ "astw:bg-card astw:data-open:animate-in astw:data-ending-style:animate-out astw:data-ending-style:fade-out-0 astw:data-open:fade-in-0 astw:data-ending-style:zoom-out-95 astw:data-open:zoom-in-95 astw:fill-mode-forwards astw:fixed astw:top-[50%] astw:left-[50%] astw:z-(--z-portal) astw:flex astw:flex-col astw:w-full astw:max-w-[calc(100%-2rem)] astw:max-h-[calc(100dvh-2rem)] astw:overflow-y-auto astw:translate-x-[-50%] astw:translate-y-[-50%] astw:gap-4 astw:rounded-lg astw:border astw:border-border astw:p-6 astw:shadow-lg astw:duration-200",
+ "astw:[&>*:not([data-slot=dialog-body])]:shrink-0",
+ sizeClasses[size],
className,
)}
{...props}
@@ -157,13 +195,35 @@ function Header({ className, ...props }: React.ComponentProps<"div">) {
}
Header.displayName = "Dialog.Header";
+/**
+ * The scrollable middle of the dialog, between `Dialog.Header` and
+ * `Dialog.Footer`. Long content scrolls here instead of pushing the footer
+ * off-screen. It is the only child of `Dialog.Content` that shrinks.
+ */
+function Body({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+Body.displayName = "Dialog.Body";
+
/** A layout wrapper for dialog action buttons, typically placed at the bottom. */
function Footer({ className, ...props }: React.ComponentProps<"div">) {
return (
{
expect(screen.getByText("Test Label")).toBeDefined();
});
+ it("shows a visual-only required marker on the label", () => {
+ render(
+
+ Name
+
+ ,
+ );
+ const marker = document.querySelector('[data-slot="field-required-marker"]');
+ expect(marker!.getAttribute("aria-hidden")).toBe("true");
+ expect(marker?.textContent).toBe("*");
+ // The accessible name stays the label text; `required` on the control is what's announced.
+ expect((screen.getByRole("textbox", { name: "Name" }) as HTMLInputElement).required).toBe(true);
+ });
+
+ it("renders no required marker by default", () => {
+ render(
+
+ Name
+
+ ,
+ );
+ expect(document.querySelector('[data-slot="field-required-marker"]')).toBeNull();
+ });
+
+ it("sets data-span from span for FormLayout", () => {
+ const { container } = render(
+
+
+ ,
+ );
+ expect(container.querySelector('[data-slot="field"]')!.getAttribute("data-span")).toBe("full");
+ });
+
it("renders description text", () => {
render(
@@ -266,4 +299,50 @@ describe("Field", () => {
warn.mockRestore();
});
});
+
+ describe("Field.Value", () => {
+ it("shows a read-only value at a control's height", () => {
+ render(
+
+ Supplier
+ Kansai Textile Co.
+ ,
+ );
+ const value = screen.getByText("Kansai Textile Co.");
+ expect(value.getAttribute("data-slot")).toBe("field-value");
+ expect(value.className).toContain("astw:min-h-9");
+ expect(document.querySelector("input")).toBeNull();
+ });
+
+ it("is named by the field's label", async () => {
+ render(
+
+ Supplier
+ Kansai Textile Co.
+ ,
+ );
+ const value = await screen.findByRole("group", { name: "Supplier" });
+ expect(value.textContent).toBe("Kansai Textile Co.");
+ const label = screen.getByText("Supplier");
+ expect(value.getAttribute("aria-labelledby")).toBe(label.id);
+ });
+
+ it("stays a plain element without a label", () => {
+ render(
+
+ Kansai Textile Co.
+ ,
+ );
+ const value = screen.getByText("Kansai Textile Co.");
+ expect(value.hasAttribute("role")).toBe(false);
+ expect(value.hasAttribute("aria-labelledby")).toBe(false);
+ });
+
+ it("takes an aria-label when there is no Field.Label", () => {
+ render(Kansai Textile Co. );
+ expect(screen.getByRole("group", { name: "Supplier" }).textContent).toBe(
+ "Kansai Textile Co.",
+ );
+ });
+ });
});
diff --git a/packages/core/src/components/field/field.tsx b/packages/core/src/components/field/field.tsx
index 74abb6974..937eae163 100644
--- a/packages/core/src/components/field/field.tsx
+++ b/packages/core/src/components/field/field.tsx
@@ -1,5 +1,6 @@
import * as React from "react";
import { Field as BaseField } from "@base-ui/react/field";
+import { useLabelableContext } from "@base-ui/react/internals/labelable-provider";
import { useOnceWarnings } from "@/hooks/use-once-warnings";
import { cn } from "@/lib/utils";
@@ -12,6 +13,7 @@ import { DateField, DatePicker, DateRangePicker } from "../date-field";
import { Select } from "../select";
import { Textarea } from "../textarea";
import { Tree } from "../tree";
+import type { FormSpan } from "@/lib/form-span";
// Only the props relevant to the Field abstraction are picked from BaseField.Root.
// Base UI-internal props (e.g. actionsRef) are intentionally excluded
@@ -41,6 +43,11 @@ type FieldRootProps = Pick<
* When provided, the field is marked invalid (`invalid={!!error}`).
*/
error?: { message?: string };
+ /**
+ * How many columns the field covers inside a `FormLayout` grid (`2`, `3`
+ * or `"full"`). Ignored outside `FormLayout`.
+ */
+ span?: FormSpan;
};
/**
@@ -97,6 +104,7 @@ function Root({
isDirty,
invalid,
error,
+ span,
// Absorb RHF's isValidating so it doesn't leak to the DOM.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
isValidating: _isValidating,
@@ -105,6 +113,7 @@ function Root({
return (
) {
+function Label({
+ className,
+ required,
+ children,
+ ...props
+}: React.ComponentProps & {
+ /** Shows the required marker (`*`) after the label text. */
+ required?: boolean;
+}) {
return (
}
- />
+ >
+ {children}
+ {required && (
+
+ *
+
+ )}
+
);
}
Label.displayName = "Field.Label";
@@ -318,10 +350,52 @@ function Validity({ ...props }: React.ComponentProps)
}
Validity.displayName = "Field.Validity";
+/**
+ * A read-only value in the control's place.
+ *
+ * It reserves an input's height, so a value the form shows but doesn't
+ * change — a supplier fixed after confirmation, a status badge, a calculated
+ * total — lines up with the editable fields beside it. Takes any content.
+ *
+ * There is no control for `Field.Label` to point at, so the value is a
+ * `group` named by the label (`aria-labelledby`): screen readers read
+ * "Supplier, Kansai Textile Co." together. Outside a `Field.Root` with a
+ * `Field.Label`, give it an `aria-label` yourself.
+ *
+ * @example
+ * ```tsx
+ *
+ * Supplier
+ * Kansai Textile Co.
+ *
+ * ```
+ */
+function Value({ className, ...props }: React.ComponentProps<"div">) {
+ // `Field.Label` registers its id with the field's labelable context.
+ const { labelId } = useLabelableContext();
+ // A generic `div` can't take a name, so the value becomes a `group` once
+ // it has one, from the label or from the consumer.
+ const named = Boolean(labelId || props["aria-label"] || props["aria-labelledby"]);
+ return (
+
+ );
+}
+Value.displayName = "Field.Value";
+
export const Field = {
Root,
Label,
Control,
+ Value,
Description,
Error,
Validity,
diff --git a/packages/core/src/components/fieldset/fieldset.tsx b/packages/core/src/components/fieldset/fieldset.tsx
index 77c75c700..5c47130ba 100644
--- a/packages/core/src/components/fieldset/fieldset.tsx
+++ b/packages/core/src/components/fieldset/fieldset.tsx
@@ -3,6 +3,7 @@ import { Fieldset as BaseFieldset } from "@base-ui/react/fieldset";
import { cn } from "@/lib/utils";
import { Text } from "../text";
+import type { FormSpan } from "@/lib/form-span";
/**
* Groups related fields with a shared legend for accessible form sectioning.
@@ -25,10 +26,19 @@ import { Text } from "../text";
type FieldsetRootProps = Pick<
React.ComponentProps,
"disabled" | "className" | "style"
-> & { children: React.ReactNode };
+> & {
+ children: React.ReactNode;
+ /**
+ * How many columns the fieldset covers inside a `FormLayout` grid (`2`,
+ * `3` or `"full"`). Ignored outside `FormLayout`.
+ */
+ span?: FormSpan;
+};
-function Root({ className, ...props }: FieldsetRootProps) {
- return ;
+function Root({ className, span, ...props }: FieldsetRootProps) {
+ return (
+
+ );
}
Root.displayName = "Fieldset.Root";
diff --git a/packages/core/src/components/form-layout/form-layout.test.tsx b/packages/core/src/components/form-layout/form-layout.test.tsx
new file mode 100644
index 000000000..edb6fbe63
--- /dev/null
+++ b/packages/core/src/components/form-layout/form-layout.test.tsx
@@ -0,0 +1,292 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+import { FormLayout } from "./form-layout";
+import { Field } from "../field";
+import { Fieldset } from "../fieldset";
+
+afterEach(() => {
+ cleanup();
+});
+
+const getGrid = (container: HTMLElement) =>
+ container.querySelector(
+ '[data-slot="form-layout"] > [data-slot="form-layout-grid"]',
+ ) as HTMLElement;
+
+describe("FormLayout", () => {
+ // ==========================================================================
+ // Snapshots — DOM structure for representative configurations
+ // ==========================================================================
+
+ describe("snapshots", () => {
+ it("fields in a two-column grid", () => {
+ const { container } = render(
+
+
+ Name
+
+
+
+ Notes
+
+
+ ,
+ );
+ expect(container.innerHTML).toMatchSnapshot();
+ });
+
+ it("card section with header and actions", () => {
+ const { container } = render(
+
+
+
+ Warehouse
+
+
+
+
+ Cancel
+ Save
+
+ ,
+ );
+ expect(container.innerHTML).toMatchSnapshot();
+ });
+
+ it("plain section", () => {
+ const { container } = render(
+
+
+
+ Supplier
+
+
+
+ ,
+ );
+ expect(container.innerHTML).toMatchSnapshot();
+ });
+ });
+
+ // ==========================================================================
+ // Columns and spans
+ // ==========================================================================
+
+ it("defaults to two columns that step down by container width", () => {
+ const { container } = render(
+
+
+ ,
+ );
+ const grid = getGrid(container);
+ expect(grid.className).toContain("astw:grid-cols-1");
+ expect(grid.className).toContain("astw:@[400px]:grid-cols-2");
+ expect(grid.className).not.toContain("grid-cols-3");
+ });
+
+ it("adds a step per column up to the requested maximum", () => {
+ const { container } = render(
+
+
+ ,
+ );
+ const grid = getGrid(container);
+ expect(grid.className).toContain("astw:@[640px]:grid-cols-3");
+ expect(grid.className).toContain("astw:@[880px]:grid-cols-4");
+ });
+
+ it("only widens span 3 where three columns exist", () => {
+ const { container: two } = render(
+
+
+ ,
+ );
+ expect(getGrid(two).className).not.toContain("col-span-3");
+ cleanup();
+
+ const { container: three } = render(
+
+
+ ,
+ );
+ expect(getGrid(three).className).toContain("astw:@[640px]:[&>[data-span='3']]:col-span-3");
+ });
+
+ it("makes a field holding a Textarea full width unless it sets its own span", () => {
+ const { container } = render(
+
+
+ Notes
+
+
+
+ Summary
+
+
+ ,
+ );
+ const grid = getGrid(container);
+ // The rule lives on the grid and only matches fields without a `data-span`
+ expect(grid.className).toContain(
+ "astw:[&>[data-slot=field]:has(textarea):not([data-span])]:col-span-full",
+ );
+ const [notes, summary] = Array.from(grid.querySelectorAll('[data-slot="field"]'));
+ expect(notes.hasAttribute("data-span")).toBe(false);
+ expect(summary.getAttribute("data-span")).toBe("2");
+ });
+
+ it("forwards span to Field.Root, Fieldset.Root and FormLayout.Item", () => {
+ const { container } = render(
+
+
+
+
+
+ Group
+
+ Custom
+ ,
+ );
+ expect(container.querySelector('[data-slot="field"]')!.getAttribute("data-span")).toBe("2");
+ expect(container.querySelector('[data-slot="fieldset"]')!.getAttribute("data-span")).toBe(
+ "full",
+ );
+ expect(
+ container.querySelector('[data-slot="form-layout-item"]')!.getAttribute("data-span"),
+ ).toBe("3");
+ });
+
+ // ==========================================================================
+ // Sections
+ // ==========================================================================
+
+ it("names the section's fieldset with its title", () => {
+ render(
+
+
+
+
+
+
+ ,
+ );
+ expect(screen.getByRole("group", { name: "Delivery" })).toBeDefined();
+ });
+
+ it("renders the section title as a heading inside the legend", () => {
+ render(
+
+
+ ,
+ );
+ const heading = screen.getByRole("heading", { name: "Delivery" });
+ expect(heading.tagName).toBe("H3");
+ expect(heading.parentElement!.getAttribute("data-slot")).toBe("form-layout-section-title");
+ });
+
+ it("describes the section's fieldset with its description", () => {
+ render(
+
+
+
+ ,
+ );
+ const delivery = screen.getByRole("group", { name: "Delivery" });
+ const describedBy = delivery.getAttribute("aria-describedby");
+ expect(describedBy).toBeTruthy();
+ expect(document.getElementById(describedBy!)!.textContent).toBe("Where goods arrive");
+ expect(screen.getByRole("group", { name: "Notes" }).hasAttribute("aria-describedby")).toBe(
+ false,
+ );
+ });
+
+ it("draws a plain section's divider only after another plain section", () => {
+ const { container } = render(
+
+ Notice
+
+
+ ,
+ );
+ const [a] = Array.from(container.querySelectorAll('[data-slot="form-layout-section"]'));
+ // The border comes from a sibling selector, so neither section sets an
+ // unconditional `border-t`.
+ expect(a.className).not.toMatch(/(^|\s)astw:border-t(\s|$)/);
+ expect(a.className).toContain(
+ "astw:[[data-slot=form-layout-section][data-variant=plain]+&]:border-t",
+ );
+ });
+
+ it("sections inherit the layout's columns unless they set their own", () => {
+ const { container } = render(
+
+
+
+
+
+
+
+ ,
+ );
+ const [a, b] = Array.from(
+ container.querySelectorAll(
+ '[data-slot="form-layout-section"] [data-slot="form-layout-grid"]',
+ ),
+ );
+ expect(a.className).toContain("astw:@[880px]:grid-cols-4");
+ expect(b.className).not.toContain("grid-cols-3");
+ });
+
+ it("disables every field in a disabled section", () => {
+ render(
+
+
+
+ A
+
+
+
+ ,
+ );
+ expect((screen.getByLabelText("A") as HTMLInputElement).disabled).toBe(true);
+ });
+
+ it("puts the section id on the outer element for anchor links", () => {
+ const { container } = render(
+
+
+ ,
+ );
+ expect(container.querySelector("#section-delivery")!.getAttribute("data-slot")).toBe(
+ "form-layout-section",
+ );
+ });
+
+ // ==========================================================================
+ // Actions
+ // ==========================================================================
+
+ it("renders start content before the buttons and only sticks when asked", () => {
+ const { container, rerender } = render(
+
+
+ Save
+
+ ,
+ );
+ const actions = container.querySelector('[data-slot="form-layout-actions"]')!;
+ expect(actions!.hasAttribute("data-sticky")).toBe(false);
+ expect(actions.textContent).toBe("DraftSave");
+
+ rerender(
+
+
+ Save
+
+ ,
+ );
+ expect(
+ container.querySelector('[data-slot="form-layout-actions"]')!.hasAttribute("data-sticky"),
+ ).toBe(true);
+ });
+});
diff --git a/packages/core/src/components/form-layout/form-layout.tsx b/packages/core/src/components/form-layout/form-layout.tsx
new file mode 100644
index 000000000..81650910f
--- /dev/null
+++ b/packages/core/src/components/form-layout/form-layout.tsx
@@ -0,0 +1,333 @@
+import * as React from "react";
+import { Fieldset as BaseFieldset } from "@base-ui/react/fieldset";
+
+import { cn } from "@/lib/utils";
+import { Card } from "../card";
+import { Text } from "../text";
+import type {
+ FormColumns,
+ FormLayoutActionsProps,
+ FormLayoutItemProps,
+ FormLayoutProps,
+ FormLayoutSectionProps,
+} from "./types";
+
+// ============================================================================
+// Grid classes
+//
+// Columns follow the width of the nearest `@container` (the FormLayout root,
+// a section card, a Dialog body…), not the viewport, so the same field
+// markup reflows inside a dialog, a sheet and a page. Thresholds match
+// DescriptionCard (400px for two columns) and leave about 190px per field.
+// A card section measures its outer edge, while its grid sits inside the
+// card's 24px padding, so there two columns start at a 352px grid (about
+// 165px per field) — still enough for a short value.
+//
+// Spans are applied from the grid side (`[&>[data-span=…]]`) because only the
+// grid knows its column count: a `span={3}` field in a two-column grid must
+// stop at two, or the browser adds an implicit third column.
+//
+// Class strings MUST stay literal so Tailwind's compiler emits them.
+// ============================================================================
+
+const COLUMN_CLASSES: Record = {
+ 1: "astw:grid-cols-1",
+ 2: "astw:grid-cols-1 astw:@[400px]:grid-cols-2",
+ 3: "astw:grid-cols-1 astw:@[400px]:grid-cols-2 astw:@[640px]:grid-cols-3",
+ 4: "astw:grid-cols-1 astw:@[400px]:grid-cols-2 astw:@[640px]:grid-cols-3 astw:@[880px]:grid-cols-4",
+};
+
+const SPAN_TWO =
+ "astw:@[400px]:[&>[data-span='2']]:col-span-2 astw:@[400px]:[&>[data-span='3']]:col-span-2";
+const SPAN_THREE = "astw:@[640px]:[&>[data-span='3']]:col-span-3";
+
+const SPAN_CLASSES: Record = {
+ 1: "",
+ 2: SPAN_TWO,
+ 3: cn(SPAN_TWO, SPAN_THREE),
+ 4: cn(SPAN_TWO, SPAN_THREE),
+};
+
+function gridClasses(columns: FormColumns) {
+ return cn(
+ "astw:grid astw:gap-x-6 astw:gap-y-4 astw:[&>*]:min-w-0",
+ // Field.Root aligns its children to the start; in a grid cell every
+ // control should fill the column instead.
+ "astw:[&>[data-slot=field]]:items-stretch",
+ "astw:[&>[data-span=full]]:col-span-full",
+ // Free text needs the whole row. A field holding a Textarea takes it
+ // unless it sets its own `span`.
+ "astw:[&>[data-slot=field]:has(textarea):not([data-span])]:col-span-full",
+ COLUMN_CLASSES[columns],
+ SPAN_CLASSES[columns],
+ );
+}
+
+const FormLayoutContext = React.createContext<{ columns: FormColumns }>({ columns: 2 });
+
+// ============================================================================
+// FormLayout.Section
+// ============================================================================
+
+/**
+ * FormLayout.Section — A titled group of fields with its own grid.
+ *
+ * Renders a `` whose legend holds the `title` as an `h3`, so
+ * screen readers announce the group and list the section among the page's
+ * headings. The `description` is the fieldset's accessible description.
+ * Use `variant="card"` on pages and `variant="plain"` inside a Dialog or
+ * Sheet, where a card inside the panel looks heavy.
+ *
+ * @example
+ * ```tsx
+ *
+ * …
+ * …
+ * …
+ *
+ * ```
+ */
+function Section({
+ title,
+ description,
+ action,
+ columns,
+ variant = "card",
+ disabled,
+ id,
+ className,
+ style,
+ children,
+}: FormLayoutSectionProps) {
+ const inherited = React.useContext(FormLayoutContext);
+ const effectiveColumns = columns ?? inherited.columns;
+ const hasHeader = title != null || description != null || action != null;
+ const descriptionId = React.useId();
+
+ const body = (
+
+ {hasHeader && (
+
+
+ {/*
+ * The legend names the fieldset; the heading inside it puts the
+ * section in the page outline, so screen reader users can jump
+ * between sections by heading.
+ */}
+ {title != null && (
+
+
+ {title}
+
+
+ )}
+ {description != null && (
+
+ {description}
+
+ )}
+
+ {action != null && (
+
{action}
+ )}
+
+ )}
+
+
+ {children}
+
+
+
+ );
+
+ if (variant === "plain") {
+ return (
+
+ {body}
+
+ );
+ }
+
+ return (
+
+ {body}
+
+ );
+}
+Section.displayName = "FormLayout.Section";
+
+// ============================================================================
+// FormLayout.Item
+// ============================================================================
+
+/**
+ * FormLayout.Item — Places non-field content (an Alert, a table, a custom
+ * block) in the form grid. `Field.Root` and `Fieldset.Root` take `span`
+ * themselves and need no wrapper.
+ */
+function Item({ span, className, style, children }: FormLayoutItemProps) {
+ return (
+
+ {children}
+
+ );
+}
+Item.displayName = "FormLayout.Item";
+
+// ============================================================================
+// FormLayout.Actions
+// ============================================================================
+
+/**
+ * FormLayout.Actions — The form's action bar, right-aligned and full width.
+ *
+ * On a page, Save usually lives in `Layout.Header` (via `form=""`); add
+ * a `sticky` action bar as well when the form is long enough to scroll.
+ * Inside a Dialog or Sheet use `Dialog.Footer` / `Sheet.Footer` instead.
+ */
+function Actions({ sticky = false, start, className, style, children }: FormLayoutActionsProps) {
+ return (
+
+ {/*
+ * Buttons keep their natural width. When space runs out the start
+ * content moves to its own line first; the buttons wrap (still
+ * right-aligned) only if they don't fit side by side.
+ */}
+ {start != null && (
+
+ {start}
+
+ )}
+
+ {children}
+
+
+ );
+}
+Actions.displayName = "FormLayout.Actions";
+
+// ============================================================================
+// FormLayout
+// ============================================================================
+
+/** Implementation for {@link FormLayout}; exported below with its sub-components attached. */
+function FormLayoutRoot({ columns = 2, className, style, children }: FormLayoutProps) {
+ return (
+
+
+
[data-slot=form-layout-section]]:gap-y-6",
+ )}
+ >
+ {children}
+
+
+
+ );
+}
+
+/**
+ * Typed explicitly rather than assigning onto a `function FormLayout`, for the
+ * same declaration-rollup reason as `Layout` (see `check-dts`).
+ */
+type FormLayoutComponent = typeof FormLayoutRoot & {
+ Section: typeof Section;
+ Item: typeof Item;
+ Actions: typeof Actions;
+};
+
+/**
+ * FormLayout — Lays out form fields in a responsive grid.
+ *
+ * Put it inside `` and place `Field.Root`s, `FormLayout.Section`s,
+ * `FormLayout.Item`s and `FormLayout.Actions` in it. `columns` is the most
+ * columns to show; the grid steps down to one column as its container
+ * narrows, so one form definition fits a Dialog, a Sheet or a page.
+ *
+ * Widen a field with `span` on `Field.Root` / `Fieldset.Root` (`2`, `3` or
+ * `"full"`). Spans never exceed the columns currently shown.
+ *
+ * @example
+ * ```tsx
+ * // Modal: fields straight in the grid
+ *
+ *
+ * …
+ * …
+ * …
+ *
+ *
+ *
+ * // Page: one card per section
+ *
+ *
+ * …
+ * …
+ *
+ *
+ * ```
+ */
+export const FormLayout: FormLayoutComponent = Object.assign(FormLayoutRoot, {
+ Section,
+ Item,
+ Actions,
+});
diff --git a/packages/core/src/components/form-layout/index.ts b/packages/core/src/components/form-layout/index.ts
new file mode 100644
index 000000000..6d3af475a
--- /dev/null
+++ b/packages/core/src/components/form-layout/index.ts
@@ -0,0 +1,8 @@
+// Main component (with Section / Item / Actions attached) and public prop types
+export { FormLayout } from "./form-layout";
+export type {
+ FormLayoutProps,
+ FormLayoutSectionProps,
+ FormLayoutItemProps,
+ FormLayoutActionsProps,
+} from "./types";
diff --git a/packages/core/src/components/form-layout/types.ts b/packages/core/src/components/form-layout/types.ts
new file mode 100644
index 000000000..ceccb17b2
--- /dev/null
+++ b/packages/core/src/components/form-layout/types.ts
@@ -0,0 +1,100 @@
+import type { CSSProperties, ReactNode } from "react";
+import type { FormSpan } from "@/lib/form-span";
+
+// ============================================================================
+// FORM LAYOUT TYPES
+// ============================================================================
+
+/**
+ * The most columns a form grid may show. The grid drops to fewer columns
+ * when its container is narrower, so the same form fits a dialog, a sheet
+ * or a full page.
+ */
+export type FormColumns = 1 | 2 | 3 | 4;
+
+/** Visual treatment of a `FormLayout.Section`. */
+export type FormSectionVariant = "card" | "plain";
+
+/**
+ * Props for the FormLayout component
+ */
+export interface FormLayoutProps {
+ /**
+ * The most columns to show. The grid reflows from this number down to one
+ * column as its container narrows (≥880px → 4, ≥640px → 3, ≥400px → 2).
+ * Sections inherit this value unless they set their own.
+ * @default 2
+ */
+ columns?: FormColumns;
+ /** Additional CSS classes */
+ className?: string;
+ /** Inline styles */
+ style?: CSSProperties;
+ /** Fields, `FormLayout.Section`s, `FormLayout.Item`s and `FormLayout.Actions` */
+ children: ReactNode;
+}
+
+/**
+ * Props for FormLayout.Section
+ */
+export interface FormLayoutSectionProps {
+ /** Section heading, rendered as an `h3` inside the fieldset's legend, so it also names the fieldset */
+ title?: ReactNode;
+ /** Supporting text under the title, also the fieldset's accessible description */
+ description?: ReactNode;
+ /** Header action slot (e.g. a "Copy from supplier" button) */
+ action?: ReactNode;
+ /** Overrides the columns inherited from `FormLayout` */
+ columns?: FormColumns;
+ /**
+ * `"card"` draws the section as a card (use on pages).
+ * `"plain"` draws a heading, with a divider when it follows another plain
+ * section (use inside a Dialog or Sheet).
+ * @default "card"
+ */
+ variant?: FormSectionVariant;
+ /** Disables every field in the section */
+ disabled?: boolean;
+ /** Element id, e.g. for anchor navigation */
+ id?: string;
+ /** Additional CSS classes */
+ className?: string;
+ /** Inline styles */
+ style?: CSSProperties;
+ /** Child content */
+ children?: ReactNode;
+}
+
+/**
+ * Props for FormLayout.Item
+ */
+export interface FormLayoutItemProps {
+ /** How many grid columns the item covers */
+ span?: FormSpan;
+ /** Additional CSS classes */
+ className?: string;
+ /** Inline styles */
+ style?: CSSProperties;
+ /** Child content */
+ children?: ReactNode;
+}
+
+/**
+ * Props for FormLayout.Actions
+ */
+export interface FormLayoutActionsProps {
+ /**
+ * Pins the action bar to the bottom of the scrolling area, so Save stays
+ * in reach on long forms.
+ * @default false
+ */
+ sticky?: boolean;
+ /** Content shown on the left of the bar (e.g. a "Last saved" note) */
+ start?: ReactNode;
+ /** Additional CSS classes */
+ className?: string;
+ /** Inline styles */
+ style?: CSSProperties;
+ /** Buttons, right-aligned. Put Cancel first and the primary action last. */
+ children?: ReactNode;
+}
diff --git a/packages/core/src/components/layout/layout.test.tsx b/packages/core/src/components/layout/layout.test.tsx
index 1eccdb506..deade39b2 100644
--- a/packages/core/src/components/layout/layout.test.tsx
+++ b/packages/core/src/components/layout/layout.test.tsx
@@ -253,6 +253,29 @@ describe("Layout", () => {
expect(grid.hasAttribute("data-layout-fill")).toBe(false);
});
+ it("centres and caps the page width with maxWidth", () => {
+ const { container } = render(
+
+
+ Form
+ ,
+ );
+ const grid = container.firstElementChild as HTMLElement;
+ expect(grid.className).toContain("astw:mx-auto");
+ expect(grid.className).toContain("astw:max-w-5xl");
+ });
+
+ it("is full width without maxWidth", () => {
+ const { container } = render(
+
+ Content
+ ,
+ );
+ const grid = container.firstElementChild as HTMLElement;
+ expect(grid.className).not.toContain("astw:mx-auto");
+ expect(grid.className).not.toContain("astw:max-w-");
+ });
+
it("warns when deprecated columns prop doesn't match child count", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
render(
diff --git a/packages/core/src/components/layout/layout.tsx b/packages/core/src/components/layout/layout.tsx
index 2232bf447..a551b9a58 100644
--- a/packages/core/src/components/layout/layout.tsx
+++ b/packages/core/src/components/layout/layout.tsx
@@ -1,6 +1,12 @@
import * as React from "react";
import { cn } from "../../lib/utils";
-import type { LayoutProps, ColumnProps, LayoutHeaderProps, ColumnArea } from "./types";
+import type {
+ LayoutProps,
+ ColumnProps,
+ LayoutHeaderProps,
+ ColumnArea,
+ LayoutMaxWidth,
+} from "./types";
import { Text } from "../text";
/**
@@ -139,6 +145,12 @@ const AREA_WIDTHS: Record = {
right: "280px",
};
+const MAX_WIDTH_CLASSES: Record = {
+ md: "astw:mx-auto astw:max-w-3xl",
+ lg: "astw:mx-auto astw:max-w-5xl",
+ xl: "astw:mx-auto astw:max-w-7xl",
+};
+
const POSITION_TEMPLATES: Record = {
2: "1fr 280px",
3: "320px 1fr 280px",
@@ -153,6 +165,7 @@ function LayoutRoot({
title,
actions,
fill,
+ maxWidth,
children,
}: LayoutProps) {
const areas: (ColumnArea | undefined)[] = [];
@@ -217,6 +230,7 @@ function LayoutRoot({
{...(fill ? { "data-layout-fill": fillFrom } : {})}
className={cn(
"astw:grid astw:grid-cols-1 astw:w-full",
+ maxWidth && MAX_WIDTH_CLASSES[maxWidth],
hasAnyHeader ? "astw:pb-4" : "astw:py-4",
gapClass,
"astw:[&>[data-layout-header]]:col-span-full",
diff --git a/packages/core/src/components/layout/types.ts b/packages/core/src/components/layout/types.ts
index 8e0969d7f..552164de6 100644
--- a/packages/core/src/components/layout/types.ts
+++ b/packages/core/src/components/layout/types.ts
@@ -14,6 +14,11 @@ export type ColumnCount = 1 | 2 | 3;
*/
export type ColumnArea = "left" | "main" | "right";
+/**
+ * Supported max-width presets for Layout
+ */
+export type LayoutMaxWidth = "md" | "lg" | "xl";
+
/**
* Props for the Layout component
*/
@@ -59,6 +64,17 @@ export interface LayoutProps {
* disable its own scrolling (the fill layout bounds everything internally).
*/
fill?: boolean;
+ /**
+ * Centres the page and caps its width — header and columns together — so
+ * forms and other reading-width pages don't stretch across wide screens.
+ * - `"md"`: 48rem (768px) — single-column forms
+ * - `"lg"`: 64rem (1024px) — two-column forms
+ * - `"xl"`: 80rem (1280px) — document forms with line items, and forms
+ * with a section nav column
+ *
+ * Omit for full-width pages (lists, dashboards).
+ */
+ maxWidth?: LayoutMaxWidth;
/** Child elements - Layout.Header and/or Layout.Column components */
children: ReactNode;
}
diff --git a/packages/core/src/components/sheet/sheet.test.tsx b/packages/core/src/components/sheet/sheet.test.tsx
index d71fb5613..685fd463d 100644
--- a/packages/core/src/components/sheet/sheet.test.tsx
+++ b/packages/core/src/components/sheet/sheet.test.tsx
@@ -312,6 +312,21 @@ describe("Sheet", () => {
});
});
+ it("right-aligns footer buttons at their own width instead of stacking them full width", () => {
+ render(
+
+
+
+ Save
+
+
+ ,
+ );
+ const footer = screen.getByText("Save").parentElement!;
+ expect(footer.className).toContain("astw:justify-end");
+ expect(footer.className).not.toContain("astw:flex-col");
+ });
+
it("closes sheet when pressing Escape", async () => {
const user = userEvent.setup();
diff --git a/packages/core/src/components/sheet/sheet.tsx b/packages/core/src/components/sheet/sheet.tsx
index e3e2fcf96..c5003d3ec 100644
--- a/packages/core/src/components/sheet/sheet.tsx
+++ b/packages/core/src/components/sheet/sheet.tsx
@@ -243,7 +243,8 @@ function Footer({ className, ...props }: React.ComponentProps<"div">) {