diff --git a/.changeset/autocomplete-controlled-filter.md b/.changeset/autocomplete-controlled-filter.md new file mode 100644 index 00000000..1f8cb036 --- /dev/null +++ b/.changeset/autocomplete-controlled-filter.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`Autocomplete`: the suggestion list now filters by a controlled `value` set from outside, so resetting the field from the parent shows the full list again. diff --git a/.changeset/date-calendar-page-limits.md b/.changeset/date-calendar-page-limits.md new file mode 100644 index 00000000..1bac5f3d --- /dev/null +++ b/.changeset/date-calendar-page-limits.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`DateCalendar`: in the months, years and year-range views, Page Up/Down and arrow keys past the edge no longer page beyond `min` or `max` while the Previous / Next buttons are disabled. diff --git a/.changeset/hijri-picker-focus-time.md b/.changeset/hijri-picker-focus-time.md new file mode 100644 index 00000000..3a5cf5d8 --- /dev/null +++ b/.changeset/hijri-picker-focus-time.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`HijriDatePicker`: a value or `today` that carries a time on the last day of a Hijri month now opens with that day focused instead of the 1st. diff --git a/.changeset/inline-edit-blur-focus.md b/.changeset/inline-edit-blur-focus.md new file mode 100644 index 00000000..e66495e0 --- /dev/null +++ b/.changeset/inline-edit-blur-focus.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`InlineEdit`: saving or cancelling on blur no longer pulls focus back to the value, so clicking another field after editing lands there. A failing `validate` on blur keeps the error showing without trapping focus in the editor. diff --git a/.changeset/number-input-stepper-typing.md b/.changeset/number-input-stepper-typing.md new file mode 100644 index 00000000..1bae3371 --- /dev/null +++ b/.changeset/number-input-stepper-typing.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`NumberInput`: a stepper field can now be cleared and retyped (it falls back to `min` only on blur), and the arrow keys step exactly like the − / + buttons instead of rounding to the step's decimals. diff --git a/.changeset/reporting-period-abandoned-custom.md b/.changeset/reporting-period-abandoned-custom.md new file mode 100644 index 00000000..bd7aee9a --- /dev/null +++ b/.changeset/reporting-period-abandoned-custom.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`ReportingPeriodPicker`: a half-picked custom range is dropped when you then pick a month, quarter or year, instead of replacing your choice when the popover closes. diff --git a/.changeset/search-box-clear-once.md b/.changeset/search-box-clear-once.md new file mode 100644 index 00000000..d1bba8a7 --- /dev/null +++ b/.changeset/search-box-clear-once.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`SearchBox`: clicking ✕ with unsubmitted text now runs one search for `""`, instead of first searching the draft on blur. diff --git a/.changeset/slug-input-typed-spaces.md b/.changeset/slug-input-typed-spaces.md new file mode 100644 index 00000000..3057e0c7 --- /dev/null +++ b/.changeset/slug-input-typed-spaces.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`SlugInput`: typing a space by hand now inserts the separator (`my custom slug` gives `my-custom-slug`), including with a custom `separator` such as `_`. `toSlug(text, { preserveTrailing: true })` keeps a trailing word break for any separator. diff --git a/.changeset/tags-input-disabled-suggestions.md b/.changeset/tags-input-disabled-suggestions.md new file mode 100644 index 00000000..4bd8bb30 --- /dev/null +++ b/.changeset/tags-input-disabled-suggestions.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`TagsInput`: Enter no longer adds a disabled suggestion, and the arrow keys skip disabled suggestions. diff --git a/.changeset/wizard-finish-once.md b/.changeset/wizard-finish-once.md new file mode 100644 index 00000000..c56617c2 --- /dev/null +++ b/.changeset/wizard-finish-once.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`Wizard`: Finish stays busy until `onComplete` settles, so a second click can no longer run `onComplete` twice. diff --git a/docs/date-and-time/date-calendar.md b/docs/date-and-time/date-calendar.md index 89d2ef01..8536164b 100644 --- a/docs/date-and-time/date-calendar.md +++ b/docs/date-and-time/date-calendar.md @@ -66,7 +66,7 @@ Without `today`, "today" is the browser's date. When server-rendered, no day is ## Accessibility -See the [DatePicker keyboard table](./date-picker#accessibility). The caption is a button ("March 2026: choose a month"); page changes are announced through a polite live region; the current month/year/range has `aria-current="date"`. +See the [DatePicker keyboard table](./date-picker#accessibility); in every view, Page Up/Down and arrows past the edge stop at `min` and `max` like the Previous and Next buttons. The caption is a button ("March 2026: choose a month"); page changes are announced through a polite live region; the current month/year/range has `aria-current="date"`. - With `events`, each day's accessible name includes its event count, so the dots (hidden from screen readers) aren't the only signal. - With `readOnly`, the clicked day's event list is a polite live region, so it is read out when it changes. Enter or Space on a day lists its events. diff --git a/docs/form-scaffolding/inline-edit.md b/docs/form-scaffolding/inline-edit.md index 91466bbc..cfe434b6 100644 --- a/docs/form-scaffolding/inline-edit.md +++ b/docs/form-scaffolding/inline-edit.md @@ -50,7 +50,7 @@ If the thrown error has a `message`, it is shown; otherwise "Couldn’t save. Pl - The value is a button named "Edit Name: Aishath Shifa". - In edit mode the input is labelled by `label` and described by the key hint; errors are announced (`role="alert"`) and linked with `aria-describedby`. -- After saving or cancelling, focus returns to the value; "Name saved" is announced. +- After saving or cancelling with the keyboard or the buttons, focus returns to the value; "Name saved" is announced. When focus leaves the editor (`blurBehavior`), it stays where the user moved it, and a failing `validate` keeps the editor open with its error without pulling focus back. - While saving, the input is read-only and `aria-busy`. | Key | Action | diff --git a/docs/layout-and-navigation/wizard.md b/docs/layout-and-navigation/wizard.md index 405169fc..e5796516 100644 --- a/docs/layout-and-navigation/wizard.md +++ b/docs/layout-and-navigation/wizard.md @@ -25,7 +25,7 @@ import { Wizard } from "@javaabu/onu" /> ``` -`validate` can be async (e.g. react-hook-form's `trigger`). While it runs, Next shows a spinner and ignores further clicks. If it returns `false`, the step is marked "Has errors" and the wizard stays. +`validate` can be async (e.g. react-hook-form's `trigger`). While it runs, and on the last step until `onComplete` settles, Next (or Finish) shows a spinner and ignores further clicks, so `onComplete` runs once. If it returns `false`, the step is marked "Has errors" and the wizard stays. ## Navigation diff --git a/docs/text-inputs/number-input.md b/docs/text-inputs/number-input.md index 74303ac4..0e14be90 100644 --- a/docs/text-inputs/number-input.md +++ b/docs/text-inputs/number-input.md @@ -43,7 +43,7 @@ The selected unit is controlled with `unitValue` / `onUnitChange` (uncontrolled: ## Stepper -`stepper` adds large − and + buttons at the sides, for cart quantities, tickets and guest counts. Holding a button repeats the step (`repeatDelay`, then every `repeatInterval` ms); arrow keys work in the field as usual. +`stepper` adds large − and + buttons at the sides, for cart quantities, tickets and guest counts. Holding a button repeats the step (`repeatDelay`, then every `repeatInterval` ms); arrow keys in the field step exactly like the buttons. ```tsx const [tickets, setTickets] = useState(1) @@ -53,7 +53,7 @@ const [tickets, setTickets] = useState(1) ``` -A stepper always holds a number: `min` defaults to `0`, `defaultValue` to `min`, and clearing the field falls back to `min`, so `value` and `onValueChange` use `number` rather than `number | null`. `size="sm" | "default" | "lg"` sets its height and width (variants exported as `numberInputVariants`); on touch screens the buttons are at least 44px in every size, and `lg` suits kiosks. A `unit` can sit next to the number between the buttons. +A stepper always holds a number: `min` defaults to `0`, `defaultValue` to `min`, and a field left empty falls back to `min` on blur (you can clear it and type a new number), so `value` and `onValueChange` use `number` rather than `number | null`. `size="sm" | "default" | "lg"` sets its height and width (variants exported as `numberInputVariants`); on touch screens the buttons are at least 44px in every size, and `lg` suits kiosks. A `unit` can sit next to the number between the buttons. ## Form submission diff --git a/docs/text-inputs/slug-input.md b/docs/text-inputs/slug-input.md index c7d820e7..3900e59c 100644 --- a/docs/text-inputs/slug-input.md +++ b/docs/text-inputs/slug-input.md @@ -18,6 +18,8 @@ const [title, setTitle] = useState("") ``` +When the user types the slug by hand it is normalised as they type: a space (or any other word break) becomes the `separator`, and a trailing one is dropped on blur. + On an edit page, pass the saved slug as `defaultValue` (or `value`). It then starts unlocked, so editing the title does not change a published URL until the user locks it again. ## Thaana titles diff --git a/docs/text-inputs/tags-input.md b/docs/text-inputs/tags-input.md index f0c4d474..f5a7bbfc 100644 --- a/docs/text-inputs/tags-input.md +++ b/docs/text-inputs/tags-input.md @@ -54,5 +54,5 @@ With `thaana`, the field types Thaana (`dir="rtl"`, `lang="dv"`), and the Thaana | ---------------------------------- | ------------------------------------------------------------ | | Enter / , | Add the typed tag (Enter on an empty field submits the form) | | Backspace (empty field) | Remove the last tag | -| ↓ / ↑ | Move through suggestions | +| ↓ / ↑ | Move through suggestions, skipping disabled ones | | Esc | Close suggestions | diff --git a/packages/onu/src/components/date/_period-grid.tsx b/packages/onu/src/components/date/_period-grid.tsx index 5ff3398f..2f60f3c2 100644 --- a/packages/onu/src/components/date/_period-grid.tsx +++ b/packages/onu/src/components/date/_period-grid.tsx @@ -16,6 +16,8 @@ export interface GridKeyboardOptions { onPage?: (delta: number) => void /** Moving past the first or last cell: page in that direction and land on `index` of the new page. */ onOverflow?: (delta: number, index: number) => void + /** Whether paging in a direction (-1 back, +1 forward) is allowed. When not, PageUp/PageDown do nothing and arrows stop at the edge. */ + canPage?: (delta: number) => boolean /** Wrap around at the ends (clock faces). */ wrapAround?: boolean /** Every arrow moves by one (a clock face has no rows). */ @@ -53,7 +55,7 @@ export function handleGridKey(e: React.KeyboardEvent, o: GridKeyboardOptions): b case "PageDown": if (!o.onPage) return false e.preventDefault() - o.onPage(e.key === "PageUp" ? -1 : 1) + if (o.canPage?.(e.key === "PageUp" ? -1 : 1) ?? true) o.onPage(e.key === "PageUp" ? -1 : 1) return true default: return false @@ -61,7 +63,7 @@ export function handleGridKey(e: React.KeyboardEvent, o: GridKeyboardOptions): b e.preventDefault() if (target < 0 || target >= o.count) { if (o.wrapAround) target = wrap(target, o.count) - else if (o.onOverflow) { + else if (o.onOverflow && (o.canPage?.(target < 0 ? -1 : 1) ?? true)) { o.onOverflow(target < 0 ? -1 : 1, wrap(target, o.count)) return true } else target = Math.max(0, Math.min(o.count - 1, target)) @@ -91,6 +93,9 @@ export interface PeriodGridProps { label: string onSelect: (index: number) => void onPage?: (delta: number) => void + /** Whether there is a previous / next page; when not, the keyboard stops at this one. Default `true`. */ + canPrev?: boolean + canNext?: boolean /** Cell that is focusable first. Defaults to the selected cell, then the current one, then the first. */ activeIndex?: number /** Focus the active cell when mounted. */ @@ -117,6 +122,8 @@ export function PeriodGrid({ label, onSelect, onPage, + canPrev = true, + canNext = true, activeIndex, initialFocus, layout = "grid", @@ -162,6 +169,7 @@ export function PeriodGrid({ onPage(delta) } : undefined, + canPage: (delta) => (delta < 0 ? canPrev : canNext), wrapAround: clock, linear: clock, }) diff --git a/packages/onu/src/components/date/date-calendar.test.tsx b/packages/onu/src/components/date/date-calendar.test.tsx index afbac9db..a501bd89 100644 --- a/packages/onu/src/components/date/date-calendar.test.tsx +++ b/packages/onu/src/components/date/date-calendar.test.tsx @@ -231,6 +231,27 @@ describe("DateCalendar — zooming out (§25.1)", () => { expect(caption()).toHaveTextContent("2004–2015") }) + it("does not page past min or max from the keyboard in the zoomed views", async () => { + const user = userEvent.setup() + renderWithOnu( + , + ) + expect(screen.getByRole("button", { name: "Previous year" })).toBeDisabled() + const months = screen.getByRole("grid", { name: "Months" }) + act(() => within(months).getByRole("button", { name: "January 2026" }).focus()) + await user.keyboard("{PageUp}") + expect(caption()).toHaveTextContent("2026") + await user.keyboard("{ArrowUp}") + expect(caption()).toHaveTextContent("2026") + expect(document.activeElement).toHaveAccessibleName("January 2026") + act(() => within(months).getByRole("button", { name: "December 2026" }).focus()) + await user.keyboard("{PageDown}") + expect(caption()).toHaveTextContent("2026") + await user.keyboard("{ArrowRight}") + expect(caption()).toHaveTextContent("2026") + expect(document.activeElement).toHaveAccessibleName("December 2026") + }) + it("turns into a month picker with minView", async () => { const user = userEvent.setup() const onPeriodSelect = vi.fn() diff --git a/packages/onu/src/components/date/date-calendar.tsx b/packages/onu/src/components/date/date-calendar.tsx index a7c667ea..44fe093b 100644 --- a/packages/onu/src/components/date/date-calendar.tsx +++ b/packages/onu/src/components/date/date-calendar.tsx @@ -357,6 +357,8 @@ export function DateCalendar(props: DateCalendarProps) { label={t(view === "month" ? "date.months" : view === "year" ? "date.years" : "date.decades")} initialFocus={focusGrid} onPage={(delta) => (delta < 0 ? nav.prev() : nav.next())} + canPrev={nav.canPrev} + canNext={nav.canNext} onSelect={(index) => { const target = items[index]!.date if (atBottom) { diff --git a/packages/onu/src/components/date/hijri-date-picker.tsx b/packages/onu/src/components/date/hijri-date-picker.tsx index 03d07510..52427bc7 100644 --- a/packages/onu/src/components/date/hijri-date-picker.tsx +++ b/packages/onu/src/components/date/hijri-date-picker.tsx @@ -70,8 +70,9 @@ export function HijriCalendar({ const lead = (first.getDay() - weekStartsOn + 7) % 7 const weeks = Math.ceil((lead + daysInMonth) / 7) const cells = Array.from({ length: weeks * 7 }, (_, i) => addDays(first, i - lead)) - const lastDay = addDays(first, daysInMonth - 1) - const inMonth = (d: Date) => d >= first && d <= lastDay + // Up to the next month's midnight, so a date with a time on the last day still counts. + const nextMonth = addDays(first, daysInMonth) + const inMonth = (d: Date) => d >= first && d < nextMonth const focusTarget = [focused, selected, today].find((d): d is Date => !!d && inMonth(d)) ?? first React.useEffect(() => { diff --git a/packages/onu/src/components/date/hijri-date.test.tsx b/packages/onu/src/components/date/hijri-date.test.tsx index d61975e5..0909ba3a 100644 --- a/packages/onu/src/components/date/hijri-date.test.tsx +++ b/packages/onu/src/components/date/hijri-date.test.tsx @@ -145,6 +145,19 @@ describe("HijriDatePicker", () => { } }) + it("opens focused on today or the value when it carries a time", async () => { + const days = hijriDaysInMonth(1447, 9) + const lastDay = fromHijri({ year: 1447, month: 9, day: days }) + const afternoon = new Date(lastDay.getFullYear(), lastDay.getMonth(), lastDay.getDate(), 15, 30) + const { user, unmount } = setup() + await user.click(screen.getByRole("combobox")) + expect(focused()).toHaveAccessibleName(new RegExp(`^(Today, )?${days} Ramadan 1447`)) + unmount() + setup() + await userEvent.click(screen.getByRole("combobox")) + expect(focused()).toHaveAccessibleName(new RegExp(`^(Today, )?${days} Ramadan 1447`)) + }) + it("does not pick days outside min/max", async () => { const onChange = vi.fn() const { user } = setup( diff --git a/packages/onu/src/components/date/reporting-period-picker.test.tsx b/packages/onu/src/components/date/reporting-period-picker.test.tsx index 1c7c2d76..61224637 100644 --- a/packages/onu/src/components/date/reporting-period-picker.test.tsx +++ b/packages/onu/src/components/date/reporting-period-picker.test.tsx @@ -135,6 +135,18 @@ describe("ReportingPeriodPicker", () => { expect(screen.getByRole("combobox")).toHaveTextContent("03/03/2026 – 17/03/2026") }) + it("drops an abandoned custom click when another period is picked", async () => { + const onChange = vi.fn() + const { user } = setup() + await user.click(screen.getByRole("combobox")) + await user.click(radio("Custom range")) + await user.click(button(/March 12th, 2026/)) + await user.click(radio("Monthly")) + await user.click(button("May 2026")) + expect(onChange).toHaveBeenLastCalledWith({ type: "monthly", from: new Date(2026, 4, 1), to: end(2026, 4, 31) }) + expect(screen.getByRole("combobox")).toHaveTextContent("May 2026") + }) + it("keeps half a custom range as a one-day range on Done", async () => { const onChange = vi.fn() const { user } = setup( diff --git a/packages/onu/src/components/date/reporting-period-picker.tsx b/packages/onu/src/components/date/reporting-period-picker.tsx index 41f36f56..f5bdace8 100644 --- a/packages/onu/src/components/date/reporting-period-picker.tsx +++ b/packages/onu/src/components/date/reporting-period-picker.tsx @@ -111,6 +111,8 @@ export function ReportingPeriodPicker({ const display = value ? describe(value) : null const commit = (next: ReportingPeriod, close: () => void) => { + // A custom range left half-picked is abandoned; closing must not turn it into the value. + setPending(null) setValue({ ...next, from: startOfDay(next.from), to: endOfDay(next.to) }) close() } @@ -242,7 +244,6 @@ export function ReportingPeriodPicker({ onSelect={(range) => { setPending(range) if (range.from && range.to && range.from.getTime() !== range.to.getTime()) { - setPending(null) commit({ type: "custom", from: range.from, to: range.to }, close) } }} diff --git a/packages/onu/src/components/form/inline-edit.test.tsx b/packages/onu/src/components/form/inline-edit.test.tsx index 14ff6b5d..304cf46e 100644 --- a/packages/onu/src/components/form/inline-edit.test.tsx +++ b/packages/onu/src/components/form/inline-edit.test.tsx @@ -121,6 +121,52 @@ describe("InlineEdit", () => { expect(onSave).toHaveBeenCalledTimes(1) }) + it("leaves focus where the user moved it when blur saves or cancels", async () => { + const onSave = vi.fn() + const { rerender } = renderWithOnu( + <> + + + , + ) + await userEvent.click(screen.getByRole("button", { name: /Edit A/ })) + await userEvent.type(screen.getByRole("textbox", { name: "A" }), "2") + await userEvent.click(screen.getByRole("textbox", { name: "other" })) + expect(onSave).toHaveBeenCalledWith("12") + expect(screen.getByRole("textbox", { name: "other" })).toHaveFocus() + // Unchanged: closes on blur without saving, focus still stays put. + await userEvent.click(screen.getByRole("button", { name: /Edit A/ })) + await userEvent.click(screen.getByRole("textbox", { name: "other" })) + expect(screen.getByRole("textbox", { name: "other" })).toHaveFocus() + rerender( + <> + + + , + ) + await userEvent.click(screen.getByRole("button", { name: /Edit A/ })) + await userEvent.click(screen.getByRole("textbox", { name: "other" })) + expect(screen.getByRole("textbox", { name: "other" })).toHaveFocus() + }) + + it("lets the user leave a field that fails validation", async () => { + renderWithOnu( + <> + (v ? null : "Required")} /> + + , + ) + await userEvent.click(screen.getByRole("button", { name: /Edit Name/ })) + await userEvent.clear(screen.getByRole("textbox", { name: "Name" })) + await userEvent.click(screen.getByRole("textbox", { name: "other" })) + expect(screen.getByRole("alert")).toHaveTextContent("Required") + expect(screen.getByRole("textbox", { name: "other" })).toHaveFocus() + // The editor stays open with the error, and Enter still refocuses it. + await userEvent.click(screen.getByRole("textbox", { name: "Name" })) + await userEvent.keyboard("{Enter}") + expect(screen.getByRole("textbox", { name: "Name" })).toHaveFocus() + }) + it("is controlled, multiline (Ctrl+Enter saves) and reports changes", async () => { function Controlled() { const [value, setValue] = React.useState("Line 1") diff --git a/packages/onu/src/components/form/inline-edit.tsx b/packages/onu/src/components/form/inline-edit.tsx index 435981bb..4591d656 100644 --- a/packages/onu/src/components/form/inline-edit.tsx +++ b/packages/onu/src/components/form/inline-edit.tsx @@ -102,25 +102,27 @@ export function InlineEdit({ setEditing(true) } - function cancel() { - returnFocus.current = true + // Focus goes back to the value after Enter, Escape or the buttons. When focus left the editor + // (blur), it stays where the user moved it, even if the editor stays open with an error. + function cancel({ fromBlur = false } = {}) { + returnFocus.current = !fromBlur setDraft(value) setError(null) setEditing(false) onCancel?.() } - async function save() { + async function save({ fromBlur = false } = {}) { if (saving) return if (draft === value) { - returnFocus.current = true + returnFocus.current = !fromBlur setEditing(false) return } const invalid = validate?.(draft) if (invalid) { setError(invalid) - fieldRef.current?.focus() + if (!fromBlur) fieldRef.current?.focus() return } setSaving(true) @@ -128,12 +130,12 @@ export function InlineEdit({ try { await onSave?.(draft) if (valueProp === undefined) setUncontrolled(draft) - returnFocus.current = true + returnFocus.current = !fromBlur setEditing(false) setAnnouncement(t("form.inlineEditSaved", { label })) } catch (e) { setError(e instanceof Error && e.message ? e.message : t("form.inlineEditFailed")) - requestAnimationFrame(() => fieldRef.current?.focus()) + if (!fromBlur) requestAnimationFrame(() => fieldRef.current?.focus()) } finally { setSaving(false) } @@ -154,8 +156,8 @@ export function InlineEdit({ function onBlur(event: React.FocusEvent) { if (blurBehavior === "none" || saving) return if (rootRef.current?.contains(event.relatedTarget as Node | null)) return - if (blurBehavior === "cancel") cancel() - else void save() + if (blurBehavior === "cancel") cancel({ fromBlur: true }) + else void save({ fromBlur: true }) } const shown = renderValue ? renderValue(value) : value @@ -225,7 +227,7 @@ export function InlineEdit({ title={t("form.cancelEdit")} disabled={saving} startIcon="close" - onClick={cancel} + onClick={() => cancel()} /> diff --git a/packages/onu/src/components/inputs/_suggestions.tsx b/packages/onu/src/components/inputs/_suggestions.tsx index 85abd4e0..8cbdf8ce 100644 --- a/packages/onu/src/components/inputs/_suggestions.tsx +++ b/packages/onu/src/components/inputs/_suggestions.tsx @@ -108,6 +108,8 @@ interface UseComboboxStateOptions { open?: boolean defaultOpen?: boolean onOpenChange?: (open: boolean) => void + /** Rows the arrow keys skip and Enter never picks. */ + isDisabled?: (index: number) => boolean } /** @@ -123,6 +125,15 @@ export function useComboboxState(itemCount: number, options: UseComboboxStateOpt const listId = React.useId() const optionId = (i: number) => `${listId}-option-${i}` const current = active >= itemCount ? -1 : active + const isDisabled = options.isDisabled ?? (() => false) + // The next enabled row from `from` in direction `step`, wrapping around; -1 when there is none. + const nextEnabled = (from: number, step: 1 | -1) => { + for (let n = 1; n <= itemCount; n++) { + const i = (((from + step * n) % itemCount) + itemCount) % itemCount + if (!isDisabled(i)) return i + } + return -1 + } const onKeyDown = (e: React.KeyboardEvent, onPick: (index: number) => void): boolean => { if (e.nativeEvent.isComposing) return false @@ -131,18 +142,18 @@ export function useComboboxState(itemCount: number, options: UseComboboxStateOpt e.preventDefault() if (!open) { setOpen(true) - setActive(e.altKey ? -1 : 0) - } else setActive(itemCount ? (current + 1) % itemCount : -1) + setActive(e.altKey ? -1 : nextEnabled(-1, 1)) + } else setActive(nextEnabled(current, 1)) return true case "ArrowUp": e.preventDefault() if (!open) { setOpen(true) - setActive(itemCount - 1) - } else setActive(itemCount ? (current <= 0 ? itemCount - 1 : current - 1) : -1) + setActive(nextEnabled(0, -1)) + } else setActive(nextEnabled(current < 0 ? 0 : current, -1)) return true case "Enter": - if (open && current >= 0) { + if (open && current >= 0 && !isDisabled(current)) { e.preventDefault() onPick(current) return true diff --git a/packages/onu/src/components/inputs/autocomplete.test.tsx b/packages/onu/src/components/inputs/autocomplete.test.tsx index 3139babc..fa1f76b1 100644 --- a/packages/onu/src/components/inputs/autocomplete.test.tsx +++ b/packages/onu/src/components/inputs/autocomplete.test.tsx @@ -393,6 +393,33 @@ describe("Autocomplete as an editable select", () => { expect(screen.getByText("Hello!")).toBeInTheDocument() }) + it("filters by a value the parent resets", async () => { + function Resettable() { + const [value, setValue] = React.useState("") + return ( + <> + + + + ) + } + renderWithOnu() + const input = screen.getByRole("combobox") + await userEvent.type(input, "ap") + await userEvent.click(screen.getByRole("button", { name: "Reset" })) + expect(input).toHaveValue("") + await userEvent.click(input) + await userEvent.keyboard("{ArrowDown}") + expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["apple", "banana", "cherry"]) + }) + it("types Thaana and shows a toggle", async () => { renderWithOnu(, { locale: "dv", diff --git a/packages/onu/src/components/inputs/autocomplete.tsx b/packages/onu/src/components/inputs/autocomplete.tsx index 94d92fb4..09a3b826 100644 --- a/packages/onu/src/components/inputs/autocomplete.tsx +++ b/packages/onu/src/components/inputs/autocomplete.tsx @@ -110,6 +110,12 @@ export function Autocomplete({ onValueChange, ) const [query, setQuery] = React.useState(value) + // The list filters by what is in the field, so it follows a value set from outside (a controlled reset). + const [prevValue, setPrevValue] = React.useState(value) + if (value !== prevValue) { + setPrevValue(value) + setQuery(value) + } const [listOpen, setListOpen] = React.useState(openProp ?? defaultOpen ?? false) const isAsync = typeof suggestions === "function" diff --git a/packages/onu/src/components/inputs/number-input.test.tsx b/packages/onu/src/components/inputs/number-input.test.tsx index 3fbfd4b3..9051fd95 100644 --- a/packages/onu/src/components/inputs/number-input.test.tsx +++ b/packages/onu/src/components/inputs/number-input.test.tsx @@ -274,6 +274,33 @@ describe("NumberInput stepper", () => { expect(input).toHaveValue("1") }) + it("can be cleared and retyped, clamping only on blur", async () => { + const onValueChange = vi.fn() + renderWithOnu() + const input = screen.getByRole("spinbutton") + await userEvent.click(input) + await userEvent.keyboard("{End}{Backspace}") + expect(input).toHaveValue("") + await userEvent.keyboard("5") + expect(input).toHaveValue("5") + await userEvent.tab() + expect(input).toHaveValue("5") + expect(onValueChange).toHaveBeenLastCalledWith(5) + }) + + it("steps the same way from the arrow keys and the buttons", async () => { + renderWithOnu() + const input = screen.getByRole("spinbutton") + fireEvent.pointerDown(screen.getByRole("button", { name: "Increase" }), { button: 0 }) + fireEvent.pointerUp(window) + expect(input).toHaveValue("11.5") + input.focus() + await userEvent.keyboard("{ArrowUp}") + expect(input).toHaveValue("12.5") + await userEvent.tab() + expect(input).toHaveValue("12.5") + }) + it.each(directions)("uses Dhivehi labels in %s", async (dir) => { renderWithOnu(, { dir, locale: "dv" }) expect(screen.getByRole("button", { name: "އިތުރުކުރޭ" })).toBeInTheDocument() diff --git a/packages/onu/src/components/inputs/number-input.tsx b/packages/onu/src/components/inputs/number-input.tsx index c84e8c57..4eff3069 100644 --- a/packages/onu/src/components/inputs/number-input.tsx +++ b/packages/onu/src/components/inputs/number-input.tsx @@ -281,10 +281,12 @@ export function NumberInput(allProps: NumberInputProps) { if (next !== value) setValue(next) } + // The one stepping rule, shared by the arrow keys and the − / + buttons. + const stepFrom = (current: number | null | undefined, delta: number) => + typeof current === "number" ? clamp(Number((current + delta).toFixed(10)), min, max) : clamp(0, min, max) + const stepBy = (delta: number) => { - const current = draft !== null ? fromText(draft) : value - const next = - typeof current === "number" ? clamp(Number((current + delta).toFixed(precision)), min, max) : clamp(0, min, max) + const next = stepFrom(draft !== null ? fromText(draft) : value, delta) commit(next) if (draft !== null) setDraft(toDraft(next), next) } @@ -299,8 +301,7 @@ export function NumberInput(allProps: NumberInputProps) { latest.current = value }, [value]) const change = (delta: number) => { - const current = latest.current ?? min ?? 0 - const next = clamp(Number((current + delta).toFixed(10)), min, max) + const next = stepFrom(latest.current ?? min ?? 0, delta) if (next === latest.current) return false latest.current = next setValue(next) @@ -424,8 +425,10 @@ export function NumberInput(allProps: NumberInputProps) { const text = e.target.value if (!/^[\d\s\u00a0\u202f.,'\u2019\u066b\u066c+\-\u2212]*$/.test(text)) return const parsed = fromText(text) - setDraft(text, parsed === undefined ? value : parsed) - if (parsed !== undefined) commit(parsed) + // An emptied stepper keeps its value until blur, so the field can be cleared and retyped. + const settled = parsed !== undefined && !(stepper && parsed === null) + setDraft(text, settled ? parsed : value) + if (settled) commit(parsed) onChange?.(e) }} onKeyDown={(e) => { diff --git a/packages/onu/src/components/inputs/slug-input.test.tsx b/packages/onu/src/components/inputs/slug-input.test.tsx index 0e484563..334a4434 100644 --- a/packages/onu/src/components/inputs/slug-input.test.tsx +++ b/packages/onu/src/components/inputs/slug-input.test.tsx @@ -28,7 +28,9 @@ describe("toSlug and thaanaToLatin", () => { it("slugifies Latin text", () => { expect(toSlug("Hulhumalé Ferry Schedule 2026!")).toBe("hulhumale-ferry-schedule-2026") expect(toSlug("A & B", { separator: "_" })).toBe("a-and-b".replace(/-/g, "_")) - expect(toSlug("trailing ", { preserveTrailing: true })).toBe("trailing") + expect(toSlug("trailing ", { preserveTrailing: true })).toBe("trailing-") + expect(toSlug("trailing ", { separator: "_", preserveTrailing: true })).toBe("trailing_") + expect(toSlug("trailing ")).toBe("trailing") expect(toSlug("trailing-", { preserveTrailing: true })).toBe("trailing-") }) @@ -137,6 +139,26 @@ describe("SlugInput", () => { expect(input).toHaveValue("HELLO_WORLD") }) + it("turns typed spaces into word breaks in manual mode", async () => { + renderWithOnu() + const input = screen.getByRole("textbox") + await userEvent.clear(input) + await userEvent.type(input, "my custom slug") + expect(input).toHaveValue("my-custom-slug") + }) + + it("lets a word break be typed with a custom separator", async () => { + renderWithOnu() + const input = screen.getByRole("textbox") + await userEvent.clear(input) + await userEvent.type(input, "my custom_slug") + expect(input).toHaveValue("my_custom_slug") + await userEvent.type(input, " ") + expect(input).toHaveValue("my_custom_slug_") + await userEvent.tab() + expect(input).toHaveValue("my_custom_slug") + }) + it("trims a trailing separator on blur", async () => { renderWithOnu() const input = screen.getByRole("textbox") diff --git a/packages/onu/src/components/inputs/slug-input.tsx b/packages/onu/src/components/inputs/slug-input.tsx index c3ff1d7a..38633ffd 100644 --- a/packages/onu/src/components/inputs/slug-input.tsx +++ b/packages/onu/src/components/inputs/slug-input.tsx @@ -21,7 +21,11 @@ export { thaanaToLatin } export interface ToSlugOptions { separator?: string - /** Keep a trailing separator, for normalising while the user types. */ + /** + * Keep a word break at the end (a trailing space, the separator or any other + * character that would become one) as a trailing separator, for normalising + * while the user types. + */ preserveTrailing?: boolean } @@ -31,7 +35,13 @@ export interface ToSlugOptions { * symbols and spacing. */ export function toSlug(text: string, { separator = "-", preserveTrailing = false }: ToSlugOptions = {}): string { - return slugify(thaanaToLatin(text), { separator, preserveTrailingDash: preserveTrailing && separator === "-" }) + const latin = thaanaToLatin(text) + const slug = slugify(latin, { separator }) + // The text ends in a word break if one more letter would land after a separator. + if (preserveTrailing && slug && slugify(`${latin}a`, { separator }) === `${slug}${separator}a`) { + return slug + separator + } + return slug } export interface SlugInputProps extends Omit< diff --git a/packages/onu/src/components/inputs/tags-input.test.tsx b/packages/onu/src/components/inputs/tags-input.test.tsx index 158435dd..06c53bf1 100644 --- a/packages/onu/src/components/inputs/tags-input.test.tsx +++ b/packages/onu/src/components/inputs/tags-input.test.tsx @@ -136,6 +136,42 @@ describe("TagsInput", () => { expect(input).toHaveAttribute("aria-expanded", "false") }) + it("never adds a disabled suggestion, and arrow keys skip it", async () => { + const { container } = renderWithOnu( + , + ) + const input = screen.getByRole("combobox") + await userEvent.type(input, "ma") + await userEvent.keyboard("{ArrowDown}{ArrowDown}") + expect(input).toHaveAttribute("aria-activedescendant", screen.getByRole("option", { name: "Mahibadhoo" }).id) + await userEvent.keyboard("{ArrowDown}") + expect(input).toHaveAttribute("aria-activedescendant", screen.getByRole("option", { name: "Maafushi" }).id) + await userEvent.keyboard("{ArrowUp}") + expect(input).toHaveAttribute("aria-activedescendant", screen.getByRole("option", { name: "Mahibadhoo" }).id) + await userEvent.keyboard("{Enter}") + expect(tagTexts(container)).toEqual(["Mahibadhoo"]) + }) + + it("does not add a disabled suggestion with Enter", async () => { + const { container } = renderWithOnu( + , + ) + const input = screen.getByRole("combobox") + await userEvent.type(input, "ma{ArrowDown}") + expect(input).not.toHaveAttribute("aria-activedescendant") + // Enter adds what was typed, not the disabled suggestion. + await userEvent.keyboard("{Enter}") + expect(tagTexts(container)).toEqual(["ma"]) + }) + it("loads async suggestions", async () => { const fetcher = vi.fn(async (q: string) => [`${q}-1`, `${q}-2`]) renderWithOnu() diff --git a/packages/onu/src/components/inputs/tags-input.tsx b/packages/onu/src/components/inputs/tags-input.tsx index 5d8357f7..17ed0cd5 100644 --- a/packages/onu/src/components/inputs/tags-input.tsx +++ b/packages/onu/src/components/inputs/tags-input.tsx @@ -134,10 +134,10 @@ export function TagsInput({ local.current?.focus() } - const combobox = useComboboxState(items.length) + const combobox = useComboboxState(items.length, { isDisabled: (i) => !!items[i]?.disabled }) const pick = (index: number) => { const option = items[index] - if (!option) return + if (!option || option.disabled) return add([option.value]) setText("") combobox.setActive(-1) diff --git a/packages/onu/src/components/layout/wizard.test.tsx b/packages/onu/src/components/layout/wizard.test.tsx index 10041a88..416748ca 100644 --- a/packages/onu/src/components/layout/wizard.test.tsx +++ b/packages/onu/src/components/layout/wizard.test.tsx @@ -133,6 +133,21 @@ describe("Wizard", () => { expect(validate).toHaveBeenCalledTimes(1) }) + it("stays busy until onComplete settles, so Finish runs it once", async () => { + let resolve: () => void = () => {} + const onComplete = vi.fn(() => new Promise((r) => (resolve = r))) + renderWithOnu() + await userEvent.click(screen.getByRole("button", { name: "Submit" })) + const finish = screen.getByRole("button", { name: "Submit" }) + expect(finish).toBeDisabled() + expect(finish).toHaveAttribute("aria-busy", "true") + await userEvent.click(finish) + expect(onComplete).toHaveBeenCalledTimes(1) + resolve() + await waitFor(() => expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled()) + expect(onComplete).toHaveBeenCalledTimes(1) + }) + it.each(directions)("translates in %s", async (dir) => { renderWithOnu( { - if (validating) return false + if (busy.current) return false + busy.current = true setValidating(true) - let ok = true try { + let ok = true if (current.validate) ok = await current.validate() if (ok && onValidateStep) ok = await onValidateStep(index, current) + setFailed((prev) => { + const nextSet = new Set(prev) + if (ok) nextSet.delete(index) + else nextSet.add(index) + return nextSet + }) + if (!ok) return false + setCompleted((prev) => new Set(prev).add(index)) + if (index === total - 1) await onComplete?.() + else change(index + 1) + return true } finally { + busy.current = false setValidating(false) } - setFailed((prev) => { - const nextSet = new Set(prev) - if (ok) nextSet.delete(index) - else nextSet.add(index) - return nextSet - }) - if (!ok) return false - setCompleted((prev) => new Set(prev).add(index)) - if (index === total - 1) { - await onComplete?.() - } else { - change(index + 1) - } - return true } const back = () => { diff --git a/packages/onu/src/components/listing/search-box.test.tsx b/packages/onu/src/components/listing/search-box.test.tsx index acb5d13f..e1e7946d 100644 --- a/packages/onu/src/components/listing/search-box.test.tsx +++ b/packages/onu/src/components/listing/search-box.test.tsx @@ -65,6 +65,17 @@ describe("SearchBox", () => { expect(screen.queryByRole("button", { name: "Clear search box" })).not.toBeInTheDocument() }) + it("searches once when ✕ is clicked with unsubmitted text", async () => { + const onSearch = vi.fn() + renderWithOnu() + const box = screen.getByRole("searchbox") + await userEvent.type(box, "zz") + await userEvent.click(screen.getByRole("button", { name: "Clear search box" })) + expect(box).toHaveValue("") + expect(box).toHaveFocus() + expect(onSearch.mock.calls).toEqual([[""]]) + }) + it("follows a controlled value", () => { const { rerender } = renderWithOnu() rerender() diff --git a/packages/onu/src/components/listing/search-box.tsx b/packages/onu/src/components/listing/search-box.tsx index 92c06ba2..0eedf1f1 100644 --- a/packages/onu/src/components/listing/search-box.tsx +++ b/packages/onu/src/components/listing/search-box.tsx @@ -129,6 +129,8 @@ export function SearchBox({ size="icon-xs" aria-label={t("listing.clearSearchInput")} className="touch:size-11" + // Keep focus in the box: a blur here would submit the draft just before the click submits "". + onMouseDown={(e) => e.preventDefault()} onClick={() => { change("") if (applied !== "") submit("")