Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/button-data-slot.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/date-range-names.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/dependent-select-load.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/form-submitter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

`Form` passes the button that submitted it to `onSubmit`'s values, so `<button type="submit" name="action" value="draft">` gives `{ action: "draft" }`, as a native submit would.
5 changes: 5 additions & 0 deletions .changeset/merged-describedby.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/phone-input-e164.md
Original file line number Diff line number Diff line change
@@ -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`).
5 changes: 5 additions & 0 deletions .changeset/picker-trigger-aria.md
Original file line number Diff line number Diff line change
@@ -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`.
5 changes: 5 additions & 0 deletions .changeset/select-null-value.md
Original file line number Diff line number Diff line change
@@ -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`.
5 changes: 5 additions & 0 deletions .changeset/shared-field-value.md
Original file line number Diff line number Diff line change
@@ -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`.
5 changes: 5 additions & 0 deletions .changeset/tags-input-required.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/choice-inputs/searchable-select.md
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
6 changes: 3 additions & 3 deletions docs/choice-inputs/select.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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`.

:::

Expand Down
2 changes: 1 addition & 1 deletion docs/date-and-time/date-range-picker.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const [range, setRange] = React.useState<DateRangeValue>({ 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
Expand Down
2 changes: 1 addition & 1 deletion docs/text-inputs/phone-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
16 changes: 7 additions & 9 deletions packages/onu/src/components/choice/_combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -547,15 +548,12 @@ export function ComboboxCore({
{list}
</PickerContent>
</Picker>
{name ? (
multiple ? (
selected.map((o) => (
<input key={o.value} type="hidden" name={name.endsWith("[]") ? name : `${name}[]`} value={o.value} />
))
) : (
<input type="hidden" name={name} value={selected[0]?.value ?? ""} />
)
) : null}
<FieldValue
name={name}
value={multiple ? selected.map((o) => o.value) : selected[0]?.value}
control={triggerProps.id as string | undefined}
disabled={disabled}
/>
<span role="status" aria-live="polite" className="sr-only">
{announcement || status}
</span>
Expand Down
32 changes: 20 additions & 12 deletions packages/onu/src/components/choice/_hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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()
Expand Down
57 changes: 56 additions & 1 deletion packages/onu/src/components/choice/api-select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ function Form(
{ value: "S", label: "Seenu" },
]}
value={atoll}
onValueChange={setAtoll}
onValueChange={(v) => setAtoll(v ?? "")}
/>
<button type="button" onClick={() => setAtoll("S")}>
Pick Seenu
Expand Down Expand Up @@ -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 (
<>
<button type="button" onClick={() => setData({ atoll: "K", island: "male" })}>
Load
</button>
<SearchableSelect
aria-label="Island"
parentValue={data.atoll}
options={islandsByAtoll}
value={data.island}
onValueChange={(v) => {
onValueChange(v)
setData((d) => ({ ...d, island: v as string | null }))
}}
/>
</>
)
}
renderWithOnu(<EditPage />)
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(<SearchableSelect {...props} parentValue={null} />)
rerender(<SearchableSelect {...props} parentValue="K" />)
expect(screen.getByRole("combobox", { name: "Island" })).toHaveTextContent("Malé")
expect(onValueChange).not.toHaveBeenCalled()
rerender(<SearchableSelect {...props} parentValue="S" />)
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(<ApiSelect {...props} parentValue={null} value={null} />)
rerender(<ApiSelect {...props} parentValue="S" value="9" />)
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)
Expand Down
6 changes: 3 additions & 3 deletions packages/onu/src/components/choice/api-select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -271,8 +271,8 @@ export function ApiSelect<TItem = unknown>(props: ApiSelectProps<TItem>) {
})

// 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("")
})

Expand Down
5 changes: 2 additions & 3 deletions packages/onu/src/components/choice/dual-listbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -423,9 +424,7 @@ export function DualListbox({
</div>
{pane("chosen")}
</div>
{name
? value.map((v) => <input key={v} type="hidden" name={name.endsWith("[]") ? name : `${name}[]`} value={v} />)
: null}
<FieldValue name={name} value={value} control={id} disabled={disabled} />
{region}
</div>
)
Expand Down
14 changes: 14 additions & 0 deletions packages/onu/src/components/choice/radio-group.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<RadioGroup aria-label="Plan" variant={variant}>
<Radio value="a" label="Basic" description="For one person" aria-describedby="hint" />
</RadioGroup>,
)
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(<RadioGroup aria-label="Delivery" options={methods} onValueChange={onValueChange} />)
Expand Down
8 changes: 5 additions & 3 deletions packages/onu/src/components/choice/radio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export function Radio({
id: idProp,
className,
classNames,
"aria-describedby": describedByProp,
...props
}: RadioProps) {
const group = React.useContext(RadioGroupStyleContext)
Expand All @@ -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") {
Expand All @@ -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)}
Expand Down Expand Up @@ -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)}
Expand Down Expand Up @@ -197,7 +199,7 @@ export function Radio({
const item = (
<RadioGroupItem
id={id}
aria-describedby={joinIds(props["aria-describedby"], descriptionId)}
aria-describedby={describedBy}
aria-invalid={invalid}
{...props}
className={cn(
Expand Down
Loading
Loading