diff --git a/.changeset/button-data-slot.md b/.changeset/button-data-slot.md
new file mode 100644
index 00000000..20829afa
--- /dev/null
+++ b/.changeset/button-data-slot.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`Button` and `LinkButton` keep `data-slot="button"` when a caller passes its own `data-slot`, so the 44px touch-target rule still applies. Use `data-part` to tag a button.
diff --git a/.changeset/date-range-names.md b/.changeset/date-range-names.md
new file mode 100644
index 00000000..39b985f7
--- /dev/null
+++ b/.changeset/date-range-names.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`DateRangePicker` submits under `names` (for example `{ from: "start", to: "end" }`) without `name` too. It used to submit nothing unless `name` was also set.
diff --git a/.changeset/dependent-select-load.md b/.changeset/dependent-select-load.md
new file mode 100644
index 00000000..aad08198
--- /dev/null
+++ b/.changeset/dependent-select-load.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+Dependent `SearchableSelect` and `ApiSelect` fields (`parentValue`) keep a value that arrives together with the parent, as with react-hook-form's `reset(data)` or an edit page that fetches both, and a value set while the field waits for its parent. They still clear when the parent changes after the value was settled.
diff --git a/.changeset/form-submitter.md b/.changeset/form-submitter.md
new file mode 100644
index 00000000..7ca5b741
--- /dev/null
+++ b/.changeset/form-submitter.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`Form` passes the button that submitted it to `onSubmit`'s values, so `` gives `{ action: "draft" }`, as a native submit would.
diff --git a/.changeset/merged-describedby.md b/.changeset/merged-describedby.md
new file mode 100644
index 00000000..d0348baf
--- /dev/null
+++ b/.changeset/merged-describedby.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`SlugInput` and `Radio` add their own description (the URL preview, the radio's `description`) to a caller's `aria-describedby` instead of letting it replace them.
diff --git a/.changeset/phone-input-e164.md b/.changeset/phone-input-e164.md
new file mode 100644
index 00000000..85de6eb9
--- /dev/null
+++ b/.changeset/phone-input-e164.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`PhoneInput` submits the E.164 value (`+9607771234`) under its `name`, instead of the formatted text in the box (`777-1234`).
diff --git a/.changeset/picker-trigger-aria.md b/.changeset/picker-trigger-aria.md
new file mode 100644
index 00000000..47478349
--- /dev/null
+++ b/.changeset/picker-trigger-aria.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`ColorPicker` and `IconPicker` no longer put `required` and `aria-required` on their trigger button inside a required `FormField`, which axe reported as `aria-allowed-attr`.
diff --git a/.changeset/select-null-value.md b/.changeset/select-null-value.md
new file mode 100644
index 00000000..baced3dc
--- /dev/null
+++ b/.changeset/select-null-value.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`Select` uses the same empty value and callback as `SearchableSelect` and `ApiSelect`: `value` and `defaultValue` are `string | null` (`null` shows the placeholder), and `onValueChange(value, option)` gets the chosen option from `options`, or `(null, null)` when cleared. With `SelectItem` children, `option` is `null`. Code that set `""` or read `""` for an empty select now uses `null`.
diff --git a/.changeset/shared-field-value.md b/.changeset/shared-field-value.md
new file mode 100644
index 00000000..9aab046e
--- /dev/null
+++ b/.changeset/shared-field-value.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+Composite controls (`NumberInput`, `TagsInput`, `SearchableSelect`, `ApiSelect`, the date and time pickers, `ColorPicker`, `IconPicker`, `SegmentedControl`, `DualListbox`, `Rating`) now submit their value through one shared hidden field. It is left out of the submission when the surrounding `FormField` is disabled, not only when the control itself is. `Form` clears a field's server error when such a control's value changes, and `ValidationSummary` links focus the visible control. A multiple `DatePicker` with no days chosen submits nothing (it used to submit an empty `name`), like `TagsInput` and `DualListbox`.
diff --git a/.changeset/tags-input-required.md b/.changeset/tags-input-required.md
new file mode 100644
index 00000000..09287a9b
--- /dev/null
+++ b/.changeset/tags-input-required.md
@@ -0,0 +1,5 @@
+---
+"@javaabu/onu": patch
+---
+
+`TagsInput` with `required` no longer blocks native form submission once it has tags: its text box is required only while there are none.
diff --git a/docs/choice-inputs/searchable-select.md b/docs/choice-inputs/searchable-select.md
index 83e07787..654b1d14 100644
--- a/docs/choice-inputs/searchable-select.md
+++ b/docs/choice-inputs/searchable-select.md
@@ -108,7 +108,7 @@ While `onCreate` runs the row shows "Creating…"; if it throws, the row shows "
## Dependent fields
-A field whose options depend on another (atoll → island): pass `parentValue`. The field is disabled until the parent has a value (the placeholder says which field to fill first) and **clears itself whenever the parent changes**: `onValueChange(null)` (or `[]` for multiple) is called. `options` can then be a map keyed by the parent value or a function of it. For options from an API, [API select](./api-select) takes the same props and sends the parent value with each request.
+A field whose options depend on another (atoll → island): pass `parentValue`. The field is disabled until the parent has a value (the placeholder says which field to fill first) and **clears itself whenever the parent changes**: `onValueChange(null)` (or `[]` for multiple) is called. A value that arrives in the same render as its parent (react-hook-form's `reset(data)`, or an edit page that fetches both) is kept, and so is one set while the field waits for its parent. `options` can then be a map keyed by the parent value or a function of it. For options from an API, [API select](./api-select) takes the same props and sends the parent value with each request.
```tsx
import { ApiSelect, SearchableSelect, Select } from '@javaabu/onu';
diff --git a/docs/choice-inputs/select.md b/docs/choice-inputs/select.md
index 6b103464..ff4e6c89 100644
--- a/docs/choice-inputs/select.md
+++ b/docs/choice-inputs/select.md
@@ -27,8 +27,8 @@ Options with the same `group` are listed under that heading. Options may be plai
| Prop | Type | Default | Description |
| --------------------------------------- | ----------------------------------------- | ------------------ | ------------------------------------------------------------- |
| `options` | `(ChoiceOption \| string)[]` | | Options; or pass `SelectItem` / `SelectGroup` children |
-| `value` / `defaultValue` | `string` | `""` | Selected value; `""` shows the placeholder |
-| `onValueChange` | `(value: string) => void` | | Also called with `""` when cleared |
+| `value` / `defaultValue` | `string \| null` | `null` | Selected value; `null` shows the placeholder |
+| `onValueChange` | `(value: string \| null, option) => void` | | `(null, null)` when cleared; `option` is `null` for children |
| `placeholder` | `string` | "Select an option" | Text when empty |
| `clearable` | `boolean` | `false` | Show a clear button when a value is set; hidden when required |
| `size` | `"sm" \| "default" \| "lg"` | `"default"` | Trigger height |
@@ -42,7 +42,7 @@ Other button props (`aria-label`, `id`, …) and `ref` go to the trigger button.
:::info
-`Select` replaces shadcn's `Select` root in the main export. It stays compatible: if its children contain `SelectTrigger` and `SelectContent`, it behaves exactly like the shadcn root. The primitive is still available from `@javaabu/onu/primitives`. Differences: it always manages the value (so it can be cleared), and an empty value is `""`.
+`Select` replaces shadcn's `Select` root in the main export. It stays compatible: if its children contain `SelectTrigger` and `SelectContent`, it behaves exactly like the shadcn root. The primitive is still available from `@javaabu/onu/primitives`. Differences: it always manages the value (so it can be cleared), an empty value is `null`, and `onValueChange` also gets the option, like `SearchableSelect` and `ApiSelect`.
:::
diff --git a/docs/date-and-time/date-range-picker.md b/docs/date-and-time/date-range-picker.md
index da6aba60..f14d1dee 100644
--- a/docs/date-and-time/date-range-picker.md
+++ b/docs/date-and-time/date-range-picker.md
@@ -17,7 +17,7 @@ const [range, setRange] = React.useState({ from: null, to: null
- Either end may be `null` for an open-ended range ("from 1 March onwards", "up to 31 March").
- Without `withTime`, `to` is the **end of that day** (23:59:59.999). With `withTime`, the To field's time defaults to 23:59.
- If To is before From, the message "End date is before start date" shows under the fields and both triggers are marked invalid.
-- With `name`, hidden inputs post `name[from]` and `name[to]` (`yyyy-MM-dd`, or ISO date-time with `withTime`); override them with `names`.
+- With `name`, hidden inputs post `name[from]` and `name[to]` (`yyyy-MM-dd`, or ISO date-time with `withTime`); override them with `names`, which also works without `name`.
- The fields stack in narrow containers (container query).
## Props
diff --git a/docs/text-inputs/phone-input.md b/docs/text-inputs/phone-input.md
index c3b081d8..3080c70a 100644
--- a/docs/text-inputs/phone-input.md
+++ b/docs/text-inputs/phone-input.md
@@ -3,7 +3,7 @@ title: PhoneInput
sidebar_position: 9
---
-An international phone number input built on [`react-phone-number-input`](https://gitlab.com/catamphetamine/react-phone-number-input) (libphonenumber). It formats the number as you type, defaults to the Maldives (+960), has a searchable country picker built from Onu's `Popover` and `Command`, and returns an [E.164](https://en.wikipedia.org/wiki/E.164) value such as `+9607771234`.
+An international phone number input built on [`react-phone-number-input`](https://gitlab.com/catamphetamine/react-phone-number-input) (libphonenumber). It formats the number as you type, defaults to the Maldives (+960), has a searchable country picker built from Onu's `Popover` and `Command`, and returns an [E.164](https://en.wikipedia.org/wiki/E.164) value such as `+9607771234`. With a `name` (or inside a `FormField`), the form submits that E.164 value, not the formatted text.
```tsx
import { PhoneInput } from "@javaabu/onu"
diff --git a/packages/onu/src/components/choice/_combobox.tsx b/packages/onu/src/components/choice/_combobox.tsx
index b3519808..aba1e042 100644
--- a/packages/onu/src/components/choice/_combobox.tsx
+++ b/packages/onu/src/components/choice/_combobox.tsx
@@ -12,6 +12,7 @@ import { Badge } from "../../ui/badge"
import { Button } from "../../ui/button"
import { Command, CommandGroup, CommandItem, CommandList, CommandSeparator } from "../../ui/command"
import { useMergedRef } from "../../hooks/use-merged-ref"
+import { FieldValue } from "../form/_field-value"
import { Picker, PickerAnchor, PickerContent, PickerTrigger } from "./_picker"
import { groupOptions, type ChoiceOption } from "./options"
import { registerEnglish } from "../../i18n/english"
@@ -547,15 +548,12 @@ export function ComboboxCore({
{list}
- {name ? (
- multiple ? (
- selected.map((o) => (
-
- ))
- ) : (
-
- )
- ) : null}
+ o.value) : selected[0]?.value}
+ control={triggerProps.id as string | undefined}
+ disabled={disabled}
+ />
{announcement || status}
diff --git a/packages/onu/src/components/choice/_hooks.ts b/packages/onu/src/components/choice/_hooks.ts
index 01f19756..0b67a1a6 100644
--- a/packages/onu/src/components/choice/_hooks.ts
+++ b/packages/onu/src/components/choice/_hooks.ts
@@ -9,21 +9,29 @@ import { choice as en_choice } from "../../locales/en/choice"
registerEnglish({ choice: en_choice })
/**
- * Calls `callback` whenever `dep` changes after the first render (compared by
- * JSON so inline objects work). Used to clear a child when its parent changes.
+ * Calls `reset` when `parent` changes after the first render (compared by JSON
+ * so inline objects work), to clear a dependent field (R16.5).
+ *
+ * `stale` says whether the field's value was settled under the old parent and
+ * should be cleared: the field was usable then (not `waiting`), and its value
+ * didn't change in the same render. When parent and value arrive together (a
+ * react-hook-form `reset(data)`, a fetch on an edit page) or the value was set
+ * while the field waited for its parent, the value is kept.
*/
-export function useOnChange(dep: unknown, callback: () => void) {
- const key = JSON.stringify(dep ?? null)
- const previous = React.useRef(key)
- const cb = React.useRef(callback)
+export function useParentChange(parent: unknown, value: unknown, waiting: boolean, reset: (stale: boolean) => void) {
+ const parentKey = JSON.stringify(parent ?? null)
+ const valueKey = JSON.stringify(value ?? null)
+ const previous = React.useRef({ parentKey, valueKey, waiting })
+ const cb = React.useRef(reset)
React.useEffect(() => {
- cb.current = callback
+ cb.current = reset
})
React.useEffect(() => {
- if (previous.current === key) return
- previous.current = key
- cb.current()
- }, [key])
+ const before = previous.current
+ previous.current = { parentKey, valueKey, waiting }
+ if (before.parentKey === parentKey) return
+ cb.current(!before.waiting && before.valueKey === valueKey)
+ }, [parentKey, valueKey, waiting])
}
export interface ParentFieldProps {
@@ -43,7 +51,7 @@ const isEmptyValue = (value: unknown) =>
* The parent of a dependent field (R16.5). A field is dependent when the
* `parentValue` prop is passed at all, even as `undefined`. `parent` is its
* value as a string, or `null` while the parent is empty (`waiting`). Clear
- * the field with `useOnChange(parent, …)`.
+ * the field with `useParentChange(parent, …)`.
*/
export function useParentField(props: ParentFieldProps, placeholder: string | undefined) {
const { t } = useTranslation()
diff --git a/packages/onu/src/components/choice/api-select.test.tsx b/packages/onu/src/components/choice/api-select.test.tsx
index 510ee50d..3208dd39 100644
--- a/packages/onu/src/components/choice/api-select.test.tsx
+++ b/packages/onu/src/components/choice/api-select.test.tsx
@@ -501,7 +501,7 @@ function Form(
{ value: "S", label: "Seenu" },
]}
value={atoll}
- onValueChange={setAtoll}
+ onValueChange={(v) => setAtoll(v ?? "")}
/>
setAtoll("S")}>
Pick Seenu
@@ -657,6 +657,61 @@ describe("parentValue", () => {
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["Malé", "Hulhumalé"])
})
+ it("keeps a value that arrives together with its parent (an edit page loading)", async () => {
+ const onValueChange = vi.fn()
+ function EditPage() {
+ const [data, setData] = React.useState<{ atoll: string | null; island: string | null }>({
+ atoll: null,
+ island: null,
+ })
+ return (
+ <>
+ setData({ atoll: "K", island: "male" })}>
+ Load
+
+ {
+ onValueChange(v)
+ setData((d) => ({ ...d, island: v as string | null }))
+ }}
+ />
+ >
+ )
+ }
+ renderWithOnu( )
+ await userEvent.click(screen.getByRole("button", { name: "Load" }))
+ expect(screen.getByRole("combobox", { name: "Island" })).toHaveTextContent("Malé")
+ expect(onValueChange).not.toHaveBeenCalled()
+ })
+
+ it("keeps a default value while the parent loads, then clears on a real parent change", async () => {
+ const onValueChange = vi.fn()
+ const props = { "aria-label": "Island", options: islandsByAtoll, defaultValue: "male", onValueChange }
+ const { rerender } = renderWithOnu( )
+ rerender( )
+ expect(screen.getByRole("combobox", { name: "Island" })).toHaveTextContent("Malé")
+ expect(onValueChange).not.toHaveBeenCalled()
+ rerender( )
+ expect(onValueChange).toHaveBeenLastCalledWith(null, null)
+ })
+
+ it("keeps an ApiSelect value that arrives together with its parent", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response(JSON.stringify({ data: [] }))),
+ )
+ const onValueChange = vi.fn()
+ const client = newClient()
+ const props = { "aria-label": "Island", url: "/api/islands", debounce: 0, queryClient: client, onValueChange }
+ const { rerender } = renderWithOnu( )
+ rerender( )
+ expect(onValueChange).not.toHaveBeenCalled()
+ })
+
it("sends the parent with ApiSelect requests and clears on change", async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ data: [{ id: 9, name: "Thinadhoo" }] })))
vi.stubGlobal("fetch", fetchMock)
diff --git a/packages/onu/src/components/choice/api-select.tsx b/packages/onu/src/components/choice/api-select.tsx
index f874156a..a7fa2510 100644
--- a/packages/onu/src/components/choice/api-select.tsx
+++ b/packages/onu/src/components/choice/api-select.tsx
@@ -8,7 +8,7 @@ import { useTranslation } from "../../providers/onu-provider"
import { useFormFieldControl } from "../form/form-field"
import { ComboboxCore, type ComboboxPresentationProps } from "./_combobox"
import { useQuickCreate, type QuickCreateProps } from "./_create"
-import { useOnChange, useParentField, type ParentFieldProps } from "./_hooks"
+import { useParentChange, useParentField, type ParentFieldProps } from "./_hooks"
import { useChoiceSelection, useOpenState, type SelectionProps } from "./_selection"
import {
apiOptionsQueryKey,
@@ -271,8 +271,8 @@ export function ApiSelect(props: ApiSelectProps) {
})
// A new parent value: clear the child (R16.5 dependent use).
- useOnChange([dependsOn, parent], () => {
- if (selection.values.length) selection.clear()
+ useParentChange([dependsOn, parent], selection.values, waiting, (stale) => {
+ if (stale && selection.values.length) selection.clear()
setQuery("")
})
diff --git a/packages/onu/src/components/choice/dual-listbox.tsx b/packages/onu/src/components/choice/dual-listbox.tsx
index 8fc5c950..aaee1cf7 100644
--- a/packages/onu/src/components/choice/dual-listbox.tsx
+++ b/packages/onu/src/components/choice/dual-listbox.tsx
@@ -8,6 +8,7 @@ import { cn } from "../../lib/utils"
import { useTranslation } from "../../providers/onu-provider"
import { useThaanaField, type ThaanaProp } from "../../thaana/use-thaana-field"
import { Button } from "../../ui/button"
+import { FieldValue } from "../form/_field-value"
import { useFormField, useFormFieldControl } from "../form/form-field"
import { filterOptions, normalizeOptions, type ChoiceOption, type ChoiceOptionInput } from "./options"
import { registerEnglish } from "../../i18n/english"
@@ -423,9 +424,7 @@ export function DualListbox({
{pane("chosen")}
- {name
- ? value.map((v) => )
- : null}
+
{region}
)
diff --git a/packages/onu/src/components/choice/radio-group.test.tsx b/packages/onu/src/components/choice/radio-group.test.tsx
index 3103bf32..c0858003 100644
--- a/packages/onu/src/components/choice/radio-group.test.tsx
+++ b/packages/onu/src/components/choice/radio-group.test.tsx
@@ -20,6 +20,20 @@ const methods = [
]
describe("RadioGroup", () => {
+ it.each(["default", "card", "image"] as const)(
+ "adds the description to a caller's aria-describedby (%s variant)",
+ (variant) => {
+ renderWithOnu(
+
+
+ ,
+ )
+ const ids = screen.getByRole("radio").getAttribute("aria-describedby")!.split(" ")
+ expect(ids[0]).toBe("hint")
+ expect(document.getElementById(ids[1]!)).toHaveTextContent("For one person")
+ },
+ )
+
it("renders options and selects with the mouse", async () => {
const onValueChange = vi.fn()
renderWithOnu( )
diff --git a/packages/onu/src/components/choice/radio.tsx b/packages/onu/src/components/choice/radio.tsx
index 54a01fe0..534a695d 100644
--- a/packages/onu/src/components/choice/radio.tsx
+++ b/packages/onu/src/components/choice/radio.tsx
@@ -91,6 +91,7 @@ export function Radio({
id: idProp,
className,
classNames,
+ "aria-describedby": describedByProp,
...props
}: RadioProps) {
const group = React.useContext(RadioGroupStyleContext)
@@ -100,6 +101,7 @@ export function Radio({
const id = idProp ?? `radio-${generated}`
const labelId = label ? `${id}-label` : undefined
const descriptionId = description ? `${id}-description` : undefined
+ const describedBy = joinIds(describedByProp, descriptionId)
const invalid = props["aria-invalid"] ?? (group.invalid || undefined)
if (variant === "image") {
@@ -109,7 +111,7 @@ export function Radio({
data-slot="radio-image"
id={id}
aria-labelledby={labelId}
- aria-describedby={joinIds(props["aria-describedby"], descriptionId)}
+ aria-describedby={describedBy}
aria-invalid={invalid}
{...props}
className={cn(radioImageVariants(), group.classNames?.item, classNames?.root, className)}
@@ -163,7 +165,7 @@ export function Radio({
data-size={size}
id={id}
aria-labelledby={labelId}
- aria-describedby={joinIds(props["aria-describedby"], descriptionId)}
+ aria-describedby={describedBy}
aria-invalid={invalid}
{...props}
className={cn(radioCardVariants({ size }), group.classNames?.item, classNames?.root, className)}
@@ -197,7 +199,7 @@ export function Radio({
const item = (
{stars}
- {name ? : null}
+
)
}
@@ -199,7 +200,7 @@ export function Rating({
)}
>
{stars}
- {name ? : null}
+
)
}
diff --git a/packages/onu/src/components/choice/searchable-select.tsx b/packages/onu/src/components/choice/searchable-select.tsx
index bf373457..f5116856 100644
--- a/packages/onu/src/components/choice/searchable-select.tsx
+++ b/packages/onu/src/components/choice/searchable-select.tsx
@@ -6,7 +6,7 @@ import { useTranslation } from "../../providers/onu-provider"
import { useFormFieldControl } from "../form/form-field"
import { ComboboxCore, type ComboboxPresentationProps } from "./_combobox"
import { useQuickCreate, type QuickCreateProps } from "./_create"
-import { useOnChange, useParentField, type ParentFieldProps } from "./_hooks"
+import { useParentChange, useParentField, type ParentFieldProps } from "./_hooks"
import { useChoiceSelection, useOpenState, type SelectionProps } from "./_selection"
import { filterOptions, normalizeOptions, type ChoiceOption, type ChoiceOptionInput } from "./options"
@@ -113,8 +113,8 @@ export function SearchableSelect(props: SearchableSelectProps) {
}, [optionsInput, parent])
const selection = useChoiceSelection({ multiple, value, defaultValue, onValueChange } as SelectionProps, options)
// A new parent value: clear the child (R16.5).
- useOnChange(parent, () => {
- if (selection.values.length) selection.clear()
+ useParentChange(parent, selection.values, waiting, (stale) => {
+ if (stale && selection.values.length) selection.clear()
setQuery("")
})
const create = useQuickCreate({
diff --git a/packages/onu/src/components/choice/segmented-control.tsx b/packages/onu/src/components/choice/segmented-control.tsx
index d1c01562..89060465 100644
--- a/packages/onu/src/components/choice/segmented-control.tsx
+++ b/packages/onu/src/components/choice/segmented-control.tsx
@@ -5,6 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority"
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
import { cn } from "../../lib/utils"
+import { FieldValue } from "../form/_field-value"
import { useFormField, useFormFieldControl } from "../form/form-field"
import { normalizeOptions, type ChoiceOptionInput } from "./options"
import { useControllableState } from "../../hooks/use-controllable-state"
@@ -118,7 +119,7 @@ export function SegmentedControl({
))}
- {name ? : null}
+
>
)
}
diff --git a/packages/onu/src/components/choice/select.test.tsx b/packages/onu/src/components/choice/select.test.tsx
index b6feb840..875fe2b2 100644
--- a/packages/onu/src/components/choice/select.test.tsx
+++ b/packages/onu/src/components/choice/select.test.tsx
@@ -28,7 +28,7 @@ describe("Select", () => {
await userEvent.click(trigger)
expect(screen.getByText("North")).toBeInTheDocument()
await userEvent.click(screen.getByRole("option", { name: "Seenu" }))
- expect(onValueChange).toHaveBeenCalledWith("S")
+ expect(onValueChange).toHaveBeenCalledWith("S", expect.objectContaining({ value: "S", label: "Seenu" }))
expect(trigger).toHaveTextContent("Seenu")
})
@@ -74,22 +74,23 @@ describe("Select", () => {
expect(trigger).toHaveTextContent("B")
await userEvent.click(trigger)
await userEvent.click(screen.getByRole("option", { name: "A" }))
- expect(onValueChange).toHaveBeenCalledWith("a")
+ // SelectItem children have no option object to report.
+ expect(onValueChange).toHaveBeenCalledWith("a", null)
})
it("clears optional fields, controlled", async () => {
function Controlled() {
- const [value, setValue] = React.useState("K")
+ const [value, setValue] = React.useState("K")
return (
<>
- [{value}]
+ [{value === null ? "null" : value}]
>
)
}
renderWithOnu( )
await userEvent.click(screen.getByRole("button", { name: "Clear selection" }))
- expect(screen.getByText("[]")).toBeInTheDocument()
+ expect(screen.getByText("[null]")).toBeInTheDocument()
expect(screen.getByRole("combobox")).toHaveTextContent("Select an option")
expect(screen.getByRole("combobox")).toHaveFocus()
})
diff --git a/packages/onu/src/components/choice/select.tsx b/packages/onu/src/components/choice/select.tsx
index 101ef1be..860540e0 100644
--- a/packages/onu/src/components/choice/select.tsx
+++ b/packages/onu/src/components/choice/select.tsx
@@ -17,7 +17,7 @@ import {
} from "../../ui/select"
import { useFormFieldControl } from "../form/form-field"
import { useMergedRef } from "../../hooks/use-merged-ref"
-import { groupOptions, normalizeOptions, type ChoiceOptionInput } from "./options"
+import { groupOptions, normalizeOptions, type ChoiceOption, type ChoiceOptionInput } from "./options"
import { registerEnglish } from "../../i18n/english"
import { choice as en_choice } from "../../locales/en/choice"
import { useControllableState } from "../../hooks/use-controllable-state"
@@ -27,7 +27,18 @@ registerEnglish({ choice: en_choice })
type RootProps = React.ComponentProps
type TriggerProps = Omit, "value" | "defaultValue" | "dir" | "children" | "ref">
-export interface SelectProps extends Omit, Omit {
+export interface SelectProps
+ extends
+ Omit,
+ Omit {
+ /** Selected value, or `null` for none. */
+ value?: string | null
+ defaultValue?: string | null
+ /**
+ * Called with the new value (`null` when cleared) and its option from
+ * `options` (`null` when cleared, or with `SelectItem` children).
+ */
+ onValueChange?: (value: string | null, option: ChoiceOption | null) => void
/** Options as an array. Alternatively pass `SelectItem` / `SelectGroup` children. */
options?: ReadonlyArray
/** Text shown when nothing is selected. */
@@ -95,7 +106,13 @@ export function Select({
const { t } = useTranslation()
const triggerRef = React.useRef(null)
const mergedRef = useMergedRef(triggerRef, ref)
- const [value, setValue] = useControllableState(valueProp, defaultValue ?? "", onValueChange)
+ const items = normalizeOptions(options)
+ const [value, setValue] = useControllableState(
+ valueProp,
+ defaultValue ?? null,
+ onValueChange,
+ )
+ const select = (next: string | null) => setValue(next, (next !== null && items.find((o) => o.value === next)) || null)
const control = useFormFieldControl({
...triggerRest,
name,
@@ -105,8 +122,9 @@ export function Select({
const { name: fieldName, disabled, required, ...triggerProps } = control
const rootProps = {
- value,
- onValueChange: setValue,
+ // Radix shows the placeholder for "".
+ value: value ?? "",
+ onValueChange: (next: string) => select(next || null),
open,
defaultOpen,
onOpenChange,
@@ -122,8 +140,7 @@ export function Select({
return {children}
}
- const items = normalizeOptions(options)
- const showClear = clearable && !required && !disabled && value !== ""
+ const showClear = clearable && !required && !disabled && value !== null
return (
@@ -149,7 +166,7 @@ export function Select({
data-slot="select-clear"
aria-label={t("choice.clearSelection")}
onClick={() => {
- setValue("")
+ select(null)
triggerRef.current?.focus()
}}
className={cn(
diff --git a/packages/onu/src/components/date/_picker-shell.tsx b/packages/onu/src/components/date/_picker-shell.tsx
index 7d9b6290..ac4db4bd 100644
--- a/packages/onu/src/components/date/_picker-shell.tsx
+++ b/packages/onu/src/components/date/_picker-shell.tsx
@@ -11,6 +11,7 @@ import { useOnu } from "../../providers/onu-provider"
import { Button } from "../../ui/button"
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger } from "../../ui/drawer"
import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover"
+import { FieldValue, type FieldValueValue } from "../form/_field-value"
import { useFormField, useFormFieldControl } from "../form/form-field"
import { registerEnglish } from "../../i18n/english"
import { common as en_common } from "../../locales/en/common"
@@ -85,8 +86,8 @@ interface PickerShellProps extends PickerFieldProps {
icon?: SemanticIconName
/** Name of the panel (dialog). */
panelLabel: string
- /** Hidden form inputs for a field name. */
- hidden?: (name: string) => React.ReactNode
+ /** What the field submits for a field name: `[name, value]` pairs, rendered with `FieldValue`. */
+ submit?: (name: string) => [string, FieldValueValue][]
onClear?: () => void
/** Extra footer content at the start. */
footerStart?: React.ReactNode
@@ -106,7 +107,7 @@ export function PickerShell(props: PickerShellProps) {
announcement,
icon = "calendar",
panelLabel,
- hidden,
+ submit,
onClear,
footerStart,
hideFooter,
@@ -222,7 +223,11 @@ export function PickerShell(props: PickerShellProps) {
{control["aria-label"]}
) : null}
- {control.name && hidden ? hidden(control.name) : null}
+ {control.name && submit
+ ? submit(control.name).map(([name, value]) => (
+
+ ))
+ : null}
{announcement}
@@ -276,8 +281,3 @@ export function PickerShell(props: PickerShellProps) {
>
)
}
-
-/** Hidden ` ` for plain form posts. */
-export function HiddenInput({ name, value }: { name: string; value: string }) {
- return
-}
diff --git a/packages/onu/src/components/date/date-picker.test.tsx b/packages/onu/src/components/date/date-picker.test.tsx
index e04a4978..1c4b4c7a 100644
--- a/packages/onu/src/components/date/date-picker.test.tsx
+++ b/packages/onu/src/components/date/date-picker.test.tsx
@@ -536,7 +536,8 @@ describe('DatePicker — mode="multiple"', () => {
,
)
expect(screen.getByRole("combobox")).toHaveTextContent("Select dates")
- expect(container.querySelector('input[name="days"]')).toHaveValue("")
+ // Nothing is submitted with no days chosen, as a native multi-select would.
+ expect(container.querySelectorAll('input[name^="days"]:not(:disabled)')).toHaveLength(0)
await user.click(screen.getByRole("combobox"))
await user.click(day(/March 20th/))
await user.click(day(/March 5th/))
diff --git a/packages/onu/src/components/date/date-picker.tsx b/packages/onu/src/components/date/date-picker.tsx
index 970fec05..99d38ec6 100644
--- a/packages/onu/src/components/date/date-picker.tsx
+++ b/packages/onu/src/components/date/date-picker.tsx
@@ -15,7 +15,7 @@ import type { Matcher } from "react-day-picker"
import { useOnu } from "../../providers/onu-provider"
import { DateCalendar } from "./date-calendar"
-import { HiddenInput, PickerShell, type PickerFieldProps } from "./_picker-shell"
+import { PickerShell, type PickerFieldProps } from "./_picker-shell"
import { DEFAULT_DATE_FORMAT, formatDate, toISODate } from "./_utils"
import { registerEnglish } from "../../i18n/english"
import { date as en_date } from "../../locales/en/date"
@@ -149,7 +149,7 @@ function SingleDate({
placeholder={placeholder ?? t("date.selectDate")}
panelLabel={t("date.chooseDate")}
announcement={value ? t("date.selected", { value: formatDate(value, "PPPP", locale.dateFns) }) : ""}
- hidden={(name) => }
+ submit={(name) => [[name, value ? toISODate(value) : ""]]}
onClear={() => setValue(null)}
>
{({ close }) => (
@@ -208,13 +208,7 @@ function MultipleDates({
placeholder={placeholder ?? t("date.selectDates")}
panelLabel={t("date.chooseDates")}
announcement={count ? summary : ""}
- hidden={(name) =>
- value.length ? (
- value.map((d) => )
- ) : (
-
- )
- }
+ submit={(name) => [[name, value.map(toISODate)]]}
onClear={() => setValue([])}
>
}
+ submit={(name) => [[name, start ? toISODate(start) : ""]]}
onClear={() => setValue(null)}
>
{({ close }) => (
@@ -336,7 +330,7 @@ function PeriodDates({
placeholder={placeholder ?? t(month ? "date.selectMonth" : "date.selectYear")}
panelLabel={t(month ? "date.chooseMonth" : "date.chooseYear")}
announcement={display ? t("date.selected", { value: display }) : ""}
- hidden={(name) => }
+ submit={(name) => [[name, value ? formatFns(value, month ? "yyyy-MM" : "yyyy") : ""]]}
onClear={() => setValue(null)}
>
{({ close }) => (
diff --git a/packages/onu/src/components/date/date-range-picker.test.tsx b/packages/onu/src/components/date/date-range-picker.test.tsx
index d394a435..7d0f09e1 100644
--- a/packages/onu/src/components/date/date-range-picker.test.tsx
+++ b/packages/onu/src/components/date/date-range-picker.test.tsx
@@ -122,6 +122,25 @@ describe("DateRangePicker (§25.4)", () => {
expect(screen.getByText("Check-in")).toHaveClass("label-x")
})
+ it("submits under custom names without a name", () => {
+ const { container } = renderWithOnu(
+ ,
+ )
+ const data = new FormData(container.querySelector("form")!)
+ expect([...data.entries()]).toEqual([
+ ["start", "2026-03-01"],
+ ["end", "2026-03-03"],
+ ["since", ""],
+ ])
+ })
+
it("is labelled by its FormField and takes its name and state", async () => {
const { container } = renderWithOnu(
diff --git a/packages/onu/src/components/date/date-range-picker.tsx b/packages/onu/src/components/date/date-range-picker.tsx
index 28bbb619..36434c0d 100644
--- a/packages/onu/src/components/date/date-range-picker.tsx
+++ b/packages/onu/src/components/date/date-range-picker.tsx
@@ -10,7 +10,8 @@ import { Label } from "../../ui/label"
import { useFormField, useFormFieldControl } from "../form/form-field"
import { DatePicker } from "./date-picker"
import { DateTimePicker } from "./date-time-picker"
-import { DetachFromFormField, HiddenInput, type PickerFieldProps } from "./_picker-shell"
+import { FieldValue } from "../form/_field-value"
+import { DetachFromFormField, type PickerFieldProps } from "./_picker-shell"
import { toISODate, toISODateTime, type DateRangeValue } from "./_utils"
import { registerEnglish } from "../../i18n/english"
import { date as en_date } from "../../locales/en/date"
@@ -37,7 +38,7 @@ export interface DateRangePickerProps extends Omit<
weekendDays?: number[]
hourCycle?: 12 | 24
minuteStep?: number
- /** Hidden input names. Default: `name[from]` and `name[to]`. */
+ /** Submitted field names, with or without `name`. Default: `name[from]` and `name[to]`. */
names?: { from?: string; to?: string }
/** Override the "From" / "To" labels. */
labels?: { from?: React.ReactNode; to?: React.ReactNode }
@@ -172,12 +173,18 @@ export function DateRangePicker({
{t("date.endBeforeStart")}
) : null}
- {name ? (
- <>
-
-
- >
- ) : null}
+
+
)
}
diff --git a/packages/onu/src/components/date/date-time-picker.tsx b/packages/onu/src/components/date/date-time-picker.tsx
index 54a704c0..bedb1eb7 100644
--- a/packages/onu/src/components/date/date-time-picker.tsx
+++ b/packages/onu/src/components/date/date-time-picker.tsx
@@ -7,7 +7,7 @@ import { Icon } from "../../icons/icon"
import { useOnu } from "../../providers/onu-provider"
import { Button } from "../../ui/button"
import { DateCalendar } from "./date-calendar"
-import { HiddenInput, PickerShell, type PickerFieldProps } from "./_picker-shell"
+import { PickerShell, type PickerFieldProps } from "./_picker-shell"
import {
DEFAULT_DATE_FORMAT,
defaultTimeFormat,
@@ -97,7 +97,7 @@ export function DateTimePicker({
placeholder={placeholder ?? t("date.selectDateTime")}
panelLabel={t("date.chooseDateTime")}
announcement={display ? t("date.selected", { value: display }) : ""}
- hidden={(name) => }
+ submit={(name) => [[name, value ? toISODateTime(value) : ""]]}
onClear={() => {
setValue(null)
setPendingTime(null)
diff --git a/packages/onu/src/components/date/hijri-date-picker.tsx b/packages/onu/src/components/date/hijri-date-picker.tsx
index 0475befd..176e9a8e 100644
--- a/packages/onu/src/components/date/hijri-date-picker.tsx
+++ b/packages/onu/src/components/date/hijri-date-picker.tsx
@@ -9,7 +9,7 @@ import { DEFAULT_WEEKEND_DAYS } from "./date-calendar"
import { CalendarHeader } from "./_calendar-header"
import { addHijriMonths, fromHijri, hijriDaysInMonth, toHijri, type HijriParts } from "./_hijri"
import { PeriodGrid } from "./_period-grid"
-import { HiddenInput, PickerShell, type PickerFieldProps } from "./_picker-shell"
+import { PickerShell, type PickerFieldProps } from "./_picker-shell"
import { DEFAULT_DATE_FORMAT, formatDate, isOutOfRange, toISODate, yearBlockStart } from "./_utils"
import { formatHijriParts, hijriMonthName, type HijriFormat } from "./hijri-date"
import { registerEnglish } from "../../i18n/english"
@@ -374,7 +374,7 @@ export function HijriDatePicker({
placeholder={placeholder ?? t("date.selectHijriDate")}
panelLabel={t("date.chooseDate")}
announcement={value ? t("date.selected", { value: formatHijriParts(toHijri(value), t, "long") }) : ""}
- hidden={(name) => }
+ submit={(name) => [[name, value ? toISODate(value) : ""]]}
onClear={() => setValue(null)}
>
{({ close }) => (
diff --git a/packages/onu/src/components/date/reporting-period-picker.tsx b/packages/onu/src/components/date/reporting-period-picker.tsx
index b3751701..41f36f56 100644
--- a/packages/onu/src/components/date/reporting-period-picker.tsx
+++ b/packages/onu/src/components/date/reporting-period-picker.tsx
@@ -9,7 +9,7 @@ import { ToggleGroup, ToggleGroupItem } from "../../ui/toggle-group"
import { DateCalendar } from "./date-calendar"
import { CalendarHeader } from "./_calendar-header"
import { PeriodGrid } from "./_period-grid"
-import { HiddenInput, PickerShell, type PickerFieldProps } from "./_picker-shell"
+import { PickerShell, type PickerFieldProps } from "./_picker-shell"
import { DEFAULT_DATE_FORMAT, formatDate, toISODate, yearBlockStart, type DateRangeValue } from "./_utils"
import { registerEnglish } from "../../i18n/english"
import { date as en_date } from "../../locales/en/date"
@@ -125,13 +125,11 @@ export function ReportingPeriodPicker({
placeholder={placeholder ?? t("date.selectPeriod")}
panelLabel={t("date.choosePeriod")}
announcement={display ? t("date.selected", { value: display }) : ""}
- hidden={(name) => (
- <>
-
-
-
- >
- )}
+ submit={(name) => [
+ [`${name}[type]`, value?.type ?? ""],
+ [`${name}[from]`, value ? toISODate(value.from) : ""],
+ [`${name}[to]`, value ? toISODate(value.to) : ""],
+ ]}
onClear={() => {
setValue(null)
setPending(null)
diff --git a/packages/onu/src/components/date/time-picker.tsx b/packages/onu/src/components/date/time-picker.tsx
index a681c6aa..944bdab2 100644
--- a/packages/onu/src/components/date/time-picker.tsx
+++ b/packages/onu/src/components/date/time-picker.tsx
@@ -3,7 +3,7 @@
import * as React from "react"
import { useOnu } from "../../providers/onu-provider"
-import { HiddenInput, PickerShell, type PickerFieldProps } from "./_picker-shell"
+import { PickerShell, type PickerFieldProps } from "./_picker-shell"
import { defaultTimeFormat, formatDate, getTimeValue, toISOTime, withTime } from "./_utils"
import { TimePanel } from "./time-panel"
import { registerEnglish } from "../../i18n/english"
@@ -57,7 +57,7 @@ export function TimePicker({
placeholder={placeholder ?? t("date.selectTime")}
panelLabel={t("date.chooseTime")}
announcement={display ? t("date.selected", { value: display }) : ""}
- hidden={(name) => }
+ submit={(name) => [[name, value ? toISOTime(value) : ""]]}
onClear={() => setValue(null)}
>
],
+ ["TagsInput", ],
+ ["SearchableSelect", ],
+ ["DatePicker", ],
+ ["ColorPicker", ],
+ ["IconPicker", ],
+ ["SegmentedControl", ],
+ ["DualListbox", ],
+ ["Rating", ],
+]
+
+describe("composite controls' submitted value", () => {
+ it.each(controls)("%s submits nothing inside a disabled FormField", (_, control) => {
+ const { container } = renderWithOnu(
+ ,
+ )
+ const values = formDataToObject(new FormData(container.querySelector("form")!))
+ expect(Object.keys(values)).toEqual([])
+ })
+
+ it.each(controls)("%s submits its value inside an enabled FormField", (_, control) => {
+ const { container } = renderWithOnu(
+ ,
+ )
+ const data = new FormData(container.querySelector("form")!)
+ expect([...data.keys()].some((key) => key === "field" || key === "field[]")).toBe(true)
+ })
+
+ it("clears a NumberInput's server error when it is edited", async () => {
+ renderWithOnu(
+ ,
+ )
+ await userEvent.click(screen.getByRole("button", { name: "Save" }))
+ await waitFor(() => expect(screen.getByRole("spinbutton", { name: "Amount" })).toHaveFocus())
+ await userEvent.type(screen.getByRole("spinbutton", { name: "Amount" }), "2")
+ expect(screen.queryAllByText("Too small")).toHaveLength(0)
+ })
+
+ it("lets the summary focus a NumberInput, a DatePicker and an empty TagsInput from the field name", async () => {
+ renderWithOnu(
+ ,
+ )
+ const links = screen.getAllByRole("link", { name: "Required" })
+ await userEvent.click(links[0]!)
+ await waitFor(() => expect(screen.getByRole("spinbutton", { name: "Amount" })).toHaveFocus())
+ await userEvent.click(links[1]!)
+ await waitFor(() =>
+ expect(document.activeElement).toBe(document.getElementById(screen.getByText("Date").closest("label")!.htmlFor)),
+ )
+ await userEvent.click(links[2]!)
+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Tags" })).toHaveFocus())
+ })
+})
diff --git a/packages/onu/src/components/form/_field-value.tsx b/packages/onu/src/components/form/_field-value.tsx
new file mode 100644
index 00000000..8b8f88ff
--- /dev/null
+++ b/packages/onu/src/components/form/_field-value.tsx
@@ -0,0 +1,64 @@
+"use client"
+
+import * as React from "react"
+
+import { useClearFieldError } from "./form-context"
+import { useFormField } from "./form-field"
+
+export type FieldValueValue = string | number | null | undefined | readonly string[]
+
+export interface FieldValueProps {
+ /** Field name. Nothing renders without one. Arrays submit as `name[]`. */
+ name?: string
+ /** Value to submit. `null`/`undefined` submit an empty string; an array submits one input per item. */
+ value: FieldValueValue
+ /** `id` of the visible control, so errors for `name` can find and focus it. Defaults to the FormField's `id`. */
+ control?: string
+ /** The control's own disabled state. A disabled `FormField` disables the value too. */
+ disabled?: boolean
+ /** `form` attribute, for controls outside their `