From e86440b6381f6f36aeee34a1d0cd64a024d50daa Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:15:53 +0000 Subject: [PATCH 01/72] Call useListingState's onValueChange only on real state changes (#66, 4.1) Co-Authored-By: Claude Opus 5.5 --- .../listing-state-stable-on-value-change.md | 5 +++++ .../listing/use-listing-state.test.tsx | 20 +++++++++++++++++ .../components/listing/use-listing-state.ts | 22 +++++++++++++------ 3 files changed, 40 insertions(+), 7 deletions(-) create mode 100644 .changeset/listing-state-stable-on-value-change.md diff --git a/.changeset/listing-state-stable-on-value-change.md b/.changeset/listing-state-stable-on-value-change.md new file mode 100644 index 00000000..074fb133 --- /dev/null +++ b/.changeset/listing-state-stable-on-value-change.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`useListingState` no longer calls `onValueChange` on every render when `paramNames` is passed inline, or on mount under StrictMode; it fires only when the listing state changes. diff --git a/packages/onu/src/components/listing/use-listing-state.test.tsx b/packages/onu/src/components/listing/use-listing-state.test.tsx index ded8f779..09743b4f 100644 --- a/packages/onu/src/components/listing/use-listing-state.test.tsx +++ b/packages/onu/src/components/listing/use-listing-state.test.tsx @@ -1,3 +1,4 @@ +import * as React from "react" import { act, renderHook } from "@testing-library/react" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" @@ -147,6 +148,25 @@ describe("useListingState", () => { expect(onValueChange).toHaveBeenCalledWith(expect.objectContaining({ page: 2 })) }) + it("does not call onValueChange on re-renders with an inline paramNames object (#66, 4.1)", () => { + const onValueChange = vi.fn() + const { result, rerender } = renderHook(() => useListingState({ paramNames: { search: "q" }, onValueChange })) + rerender() + rerender() + expect(onValueChange).not.toHaveBeenCalled() + act(() => result.current.setSearch("ali")) + expect(onValueChange).toHaveBeenCalledTimes(1) + rerender() + expect(onValueChange).toHaveBeenCalledTimes(1) + expect(window.location.search).toBe("?q=ali") + }) + + it("does not call onValueChange on mount under StrictMode (#66, 4.1)", () => { + const onValueChange = vi.fn() + renderHook(() => useListingState({ url: false, onValueChange }), { wrapper: React.StrictMode }) + expect(onValueChange).not.toHaveBeenCalled() + }) + it("keeps search, filters, sort and page in the URL with replaceState (§25.6 browser behaviour)", () => { setUrl("/users?tab=1#/components/x") const push = vi.spyOn(window.history, "pushState") diff --git a/packages/onu/src/components/listing/use-listing-state.ts b/packages/onu/src/components/listing/use-listing-state.ts index 33aad16b..bc161679 100644 --- a/packages/onu/src/components/listing/use-listing-state.ts +++ b/packages/onu/src/components/listing/use-listing-state.ts @@ -236,7 +236,12 @@ function sameFilters(a: FilterValues, b: FilterValues) { */ export function useListingState(options: UseListingStateOptions = {}): ListingController { const { url = true, paramPrefix, paramNames, onValueChange, defaultSelection, defaultColumnVisibility } = options - const urlOptions = React.useMemo(() => ({ paramPrefix, paramNames }), [paramPrefix, paramNames]) + // Compared by value: callers naturally pass `paramNames` inline. + const paramNamesKey = JSON.stringify(paramNames ?? {}) + const urlOptions = React.useMemo( + () => ({ paramPrefix, paramNames: JSON.parse(paramNamesKey) as Partial }), + [paramPrefix, paramNamesKey], + ) const defaults = React.useMemo( () => ({ ...BASE_STATE, ...options.defaultState, filters: cleanFilters(options.defaultState?.filters ?? {}) }), @@ -260,7 +265,6 @@ export function useListingState(options: UseListingStateOptions = {}): ListingCo React.useEffect(() => { onChangeRef.current = onValueChange }) - const first = React.useRef(true) const { search, sort, page, perPage, filters, view } = full const stateForEffects = React.useMemo( () => ({ search, sort, page, perPage, filters, view }), @@ -269,13 +273,17 @@ export function useListingState(options: UseListingStateOptions = {}): ListingCo React.useEffect(() => { if (url) writeUrl(stateForEffects, defaults, urlOptions) - if (first.current) { - first.current = false - return - } - onChangeRef.current?.(stateForEffects) }, [stateForEffects, url, defaults, urlOptions]) + // Only a real state change notifies: not mount, not StrictMode's effect replay, + // not a re-render with new option identities. + const notified = React.useRef(stateForEffects) + React.useEffect(() => { + if (notified.current === stateForEffects) return + notified.current = stateForEffects + onChangeRef.current?.(stateForEffects) + }, [stateForEffects]) + /** * Applies a change. Returning the previous object means "nothing changed". * A real change clears the selection; `resetPage` also goes back to page 1. From 00d6584bdd2815eecd2717862c03dd9c93f25c54 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:15:58 +0000 Subject: [PATCH 02/72] Ignore row clicks that come from the row's portalled menu or dialog (#66, 5.1) Co-Authored-By: Claude Opus 5.5 --- .changeset/row-click-portals.md | 5 +++++ .../onu/src/components/listing/_collection.tsx | 4 ++-- .../onu/src/components/listing/_shared.tsx | 14 ++++++++++---- .../src/components/listing/data-table.test.tsx | 16 ++++++++++++++++ .../onu/src/components/listing/data-table.tsx | 4 ++-- .../onu/src/components/listing/views.test.tsx | 18 ++++++++++++++++++ 6 files changed, 53 insertions(+), 8 deletions(-) create mode 100644 .changeset/row-click-portals.md diff --git a/.changeset/row-click-portals.md b/.changeset/row-click-portals.md new file mode 100644 index 00000000..283c9e3d --- /dev/null +++ b/.changeset/row-click-portals.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +Clicking inside a row's actions menu or confirm dialog no longer opens the row in `DataTable`, `ListView` and the other collection views. diff --git a/packages/onu/src/components/listing/_collection.tsx b/packages/onu/src/components/listing/_collection.tsx index 9b894777..2ba0465b 100644 --- a/packages/onu/src/components/listing/_collection.tsx +++ b/packages/onu/src/components/listing/_collection.tsx @@ -3,7 +3,7 @@ import * as React from "react" import { useLinkComponent, useTranslation } from "../../providers/onu-provider" -import { isInteractiveTarget } from "./_shared" +import { ignoresRowClick } from "./_shared" import { SelectionCheckbox } from "./_selection-checkbox" // The dropdown on its own: row menus never open as context menus, so tables don't bundle one. import { DropdownActionMenu as ActionMenu } from "../overlays/_action-menu" @@ -90,7 +90,7 @@ export function useCollectionItem(props: CollectionProps) { const clickable = !!props.onItemClick || !!href const onClick = clickable ? (event: React.MouseEvent) => { - if (isInteractiveTarget(event.target, event.currentTarget)) return + if (ignoresRowClick(event)) return if (props.onItemClick) props.onItemClick(item) else event.currentTarget.querySelector("a[data-row-link]")?.click() } diff --git a/packages/onu/src/components/listing/_shared.tsx b/packages/onu/src/components/listing/_shared.tsx index 5e2fe269..379ea67e 100644 --- a/packages/onu/src/components/listing/_shared.tsx +++ b/packages/onu/src/components/listing/_shared.tsx @@ -24,10 +24,16 @@ export function useNoun(noun: ListingNoun | undefined) { ) } -/** Whether a click landed on (or inside) an interactive element, so row clicks can ignore it. */ -export function isInteractiveTarget(target: EventTarget | null, stopAt?: Element | null) { - let el = target instanceof Element ? target : null - while (el && el !== stopAt) { +/** + * Whether a row's click handler should ignore this click: it landed on (or inside) an interactive + * element, or outside the row's DOM altogether. React bubbles events from portals (the row's ⋯ menu, + * its confirm dialog) through the component tree, so those clicks reach the row too. + */ +export function ignoresRowClick(event: React.MouseEvent) { + const row = event.currentTarget + let el = event.target instanceof Element ? event.target : null + if (!el || !row.contains(el)) return true + while (el && el !== row) { if ( el.matches( "a,button,input,select,textarea,label,summary,[role=button],[role=checkbox],[role=menuitem],[role=switch],[contenteditable=true]", diff --git a/packages/onu/src/components/listing/data-table.test.tsx b/packages/onu/src/components/listing/data-table.test.tsx index b4f34c4f..51ecc367 100644 --- a/packages/onu/src/components/listing/data-table.test.tsx +++ b/packages/onu/src/components/listing/data-table.test.tsx @@ -276,6 +276,22 @@ describe("DataTable", () => { expect(onDelete).toHaveBeenCalledWith("1") }) + it("ignores clicks inside the row's portalled menu and confirm dialog", async () => { + const onRowClick = vi.fn() + renderWithOnu( + [{ id: "delete", label: "Delete", destructive: true, onSelect: vi.fn() }]} + />, + ) + await userEvent.click(screen.getByRole("button", { name: "Actions for Jane Doe" })) + await userEvent.click(await screen.findByRole("menuitem", { name: "Delete" })) + const dialog = await screen.findByRole("alertdialog", { name: "Delete Jane Doe?" }) + await userEvent.click(within(dialog).getByRole("heading", { name: "Delete Jane Doe?" })) + expect(onRowClick).not.toHaveBeenCalled() + }) + it("opens the record when the row or its name is clicked (§25.6)", async () => { const onRowClick = vi.fn() const { unmount } = renderWithOnu( diff --git a/packages/onu/src/components/listing/data-table.tsx b/packages/onu/src/components/listing/data-table.tsx index 1b211108..77226e8d 100644 --- a/packages/onu/src/components/listing/data-table.tsx +++ b/packages/onu/src/components/listing/data-table.tsx @@ -23,7 +23,7 @@ import { cn } from "../../lib/utils" import { useLinkComponent, useTranslation } from "../../providers/onu-provider" import { Skeleton } from "../../ui/skeleton" import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "../../ui/table" -import { isInteractiveTarget } from "./_shared" +import { ignoresRowClick } from "./_shared" import { SelectionCheckbox } from "./_selection-checkbox" import { SortMenu } from "./_sort-menu" import { formatFilterLabel, useActiveFilterChips } from "./active-filter-chips" @@ -283,7 +283,7 @@ export function DataTable({ const headerChecked: boolean | "indeterminate" = allSelected ? true : someSelected ? "indeterminate" : false const openRow = (row: T, event: React.MouseEvent) => { - if (isInteractiveTarget(event.target, event.currentTarget)) return + if (ignoresRowClick(event)) return if (window.getSelection?.()?.toString()) return if (onRowClick) onRowClick(row) else if (getRowHref?.(row)) event.currentTarget.querySelector("a[data-row-link]")?.click() diff --git a/packages/onu/src/components/listing/views.test.tsx b/packages/onu/src/components/listing/views.test.tsx index 55672cf9..79907beb 100644 --- a/packages/onu/src/components/listing/views.test.tsx +++ b/packages/onu/src/components/listing/views.test.tsx @@ -61,6 +61,24 @@ describe.each(["list", "grid"] as const)("ListView layout=%s", (layout) => { expect(onItemClick).toHaveBeenCalledWith(users[2]) }) + it("ignores clicks inside the item's portalled confirm dialog", async () => { + const onItemClick = vi.fn() + renderWithOnu( + u.name} + onItemClick={onItemClick} + itemActions={() => [{ id: "delete", label: "Delete", destructive: true, onSelect: vi.fn() }]} + />, + ) + await userEvent.click(screen.getByRole("button", { name: "Actions for Jane Doe" })) + await userEvent.click(await screen.findByRole("menuitem", { name: "Delete" })) + const dialog = await screen.findByRole("alertdialog", { name: "Delete Jane Doe?" }) + await userEvent.click(within(dialog).getByRole("heading", { name: "Delete Jane Doe?" })) + expect(onItemClick).not.toHaveBeenCalled() + }) + it("follows the link when the item is clicked", async () => { const clicked = vi.fn((e: Event) => e.preventDefault()) renderWithOnu( From 527349431703721af49b17543f44729e9659d5a7 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:16:06 +0000 Subject: [PATCH 03/72] Keep SignaturePad's drawing when the translator changes identity (#66, 4.2) Co-Authored-By: Claude Opus 5.5 --- .changeset/signature-pad-keeps-drawing.md | 5 +++++ packages/onu/src/media/signature-pad.test.tsx | 18 +++++++++++++++++- packages/onu/src/media/signature-pad.tsx | 7 +++++-- 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 .changeset/signature-pad-keeps-drawing.md diff --git a/.changeset/signature-pad-keeps-drawing.md b/.changeset/signature-pad-keeps-drawing.md new file mode 100644 index 00000000..d2d57b62 --- /dev/null +++ b/.changeset/signature-pad-keeps-drawing.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`SignaturePad` keeps the drawing when the language changes or `OnuProvider` re-renders with new props, so the pad and the submitted value no longer disagree. diff --git a/packages/onu/src/media/signature-pad.test.tsx b/packages/onu/src/media/signature-pad.test.tsx index 83f993db..b4116bfe 100644 --- a/packages/onu/src/media/signature-pad.test.tsx +++ b/packages/onu/src/media/signature-pad.test.tsx @@ -1,8 +1,9 @@ -import { act, screen } from "@testing-library/react" +import { act, render, screen } from "@testing-library/react" import userEvent from "@testing-library/user-event" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { directions, expectNoA11yViolations, renderWithOnu } from "../../test/utils" +import { OnuProvider } from "../providers/onu-provider" import { renderTypedSignature, SignaturePad } from "./signature-pad" // userEvent-driven tests can be slow when the whole suite runs in parallel with coverage. @@ -166,6 +167,21 @@ describe("SignaturePad", () => { expect(screen.getByRole("button", { name: "Draw" })).toBeDisabled() }) + it("keeps the drawing when the translator changes identity (#66, 4.2)", () => { + const ui = (maps: object) => ( + + + + ) + const { rerender } = render(ui({})) + act(() => lastPad().stroke()) + // An inline `maps={{…}}` gives the provider a new `t` on every render. + rerender(ui({})) + expect(pads).toHaveLength(1) + expect(lastPad().toData()).toHaveLength(1) + expect(document.querySelector("input[name=signature]")!.value).toBe("data:image/png;base64,1") + }) + it("offers typing the name as an accessible alternative", async () => { vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null) const onValueChange = vi.fn() diff --git a/packages/onu/src/media/signature-pad.tsx b/packages/onu/src/media/signature-pad.tsx index a427708a..cba7bd36 100644 --- a/packages/onu/src/media/signature-pad.tsx +++ b/packages/onu/src/media/signature-pad.tsx @@ -102,8 +102,11 @@ export function SignaturePad({ const canvasRef = React.useRef(null) const padRef = React.useRef(null) const onValueChangeRef = React.useRef(onValueChange) + // `t` changes identity with provider props; the pad must not be recreated (and wiped) for that. + const tRef = React.useRef(t) React.useEffect(() => { onValueChangeRef.current = onValueChange + tRef.current = t }) const [innerMode, setInnerMode] = React.useState(defaultMode) const mode = modeProp ?? innerMode @@ -132,7 +135,7 @@ export function SignaturePad({ const onEnd = () => { setStrokes(pad.toData().length) emit(pad.toDataURL("image/png")) - setAnnounce(t("input.signatureCaptured")) + setAnnounce(tRef.current("input.signatureCaptured")) } pad.addEventListener("endStroke", onEnd) @@ -166,7 +169,7 @@ export function SignaturePad({ padRef.current = null } // eslint-disable-next-line react-hooks/exhaustive-deps -- Pen settings are applied below without recreating the pad. - }, [mode, emit, t]) + }, [mode, emit]) React.useEffect(() => { const pad = padRef.current From 8c13685109edc695b228da8c73874b6dc5fcde1a Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:16:14 +0000 Subject: [PATCH 04/72] Let a NumberInput stepper be cleared and step one way from keys and buttons (#66, 2.1) Co-Authored-By: Claude Opus 5.5 --- .changeset/number-input-stepper-typing.md | 5 ++++ docs/text-inputs/number-input.md | 4 +-- .../components/inputs/number-input.test.tsx | 27 +++++++++++++++++++ .../src/components/inputs/number-input.tsx | 17 +++++++----- 4 files changed, 44 insertions(+), 9 deletions(-) create mode 100644 .changeset/number-input-stepper-typing.md 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/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/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) => { From 2ce3c12993682d186a7c25b69013ea09c0d1af38 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:16:55 +0000 Subject: [PATCH 05/72] Turn typed spaces into separators in a manual SlugInput (#66, 2.2) Co-Authored-By: Claude Opus 5.5 --- .changeset/slug-input-typed-spaces.md | 5 ++++ docs/text-inputs/slug-input.md | 2 ++ .../src/components/inputs/slug-input.test.tsx | 24 ++++++++++++++++++- .../onu/src/components/inputs/slug-input.tsx | 14 +++++++++-- 4 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 .changeset/slug-input-typed-spaces.md 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/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/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< From a2116bb22c140f4b1dc6c1ac513f4216db81e89e Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:17:20 +0000 Subject: [PATCH 06/72] Build Pagination links from the paginator's own URLs (#66, 5.2) Co-Authored-By: Claude Opus 5.5 --- .changeset/pagination-server-links.md | 5 ++ docs/listing-pages/pagination.md | 1 + .../components/listing/pagination.test.tsx | 33 ++++++++ .../onu/src/components/listing/pagination.tsx | 76 +++++++++++++++---- 4 files changed, 99 insertions(+), 16 deletions(-) create mode 100644 .changeset/pagination-server-links.md diff --git a/.changeset/pagination-server-links.md b/.changeset/pagination-server-links.md new file mode 100644 index 00000000..71ae2313 --- /dev/null +++ b/.changeset/pagination-server-links.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`Pagination` builds page links from the URLs a Laravel paginator sends, so the query string (search, filters) and a custom `pageName` are kept instead of being replaced by `path?page=N`. diff --git a/docs/listing-pages/pagination.md b/docs/listing-pages/pagination.md index 303b47a0..078310f6 100644 --- a/docs/listing-pages/pagination.md +++ b/docs/listing-pages/pagination.md @@ -25,6 +25,7 @@ import { Pagination } from "@javaabu/onu" - Previous is disabled on the first page and Next on the last (or when a simple paginator has no `next_page_url`). - With numbered pages the previous and next buttons are icon-only (their accessible names stay "Go to previous page" / "Go to next page"). Without a total (simple paginators) or with `numbered={false}` they show their labels. - With `getPageHref`, or a paginator with a `path` / `links`, pages are links rendered with `OnuProvider linkComponent` (Inertia, Next). Plain clicks still call `onPageChange` when given. +- Page links from a paginator come from the URLs the server sent (`links`, `first_page_url`, `prev_page_url`, …), so the query string from `->withQueryString()` and a custom `pageName` are kept. Pages the server didn't list swap the page number in one of those URLs; `path` is used only when the server sent no URLs. ## Props diff --git a/packages/onu/src/components/listing/pagination.test.tsx b/packages/onu/src/components/listing/pagination.test.tsx index 1dcd0396..b5d790bf 100644 --- a/packages/onu/src/components/listing/pagination.test.tsx +++ b/packages/onu/src/components/listing/pagination.test.tsx @@ -123,6 +123,39 @@ describe("Pagination", () => { expect(screen.getByRole("button", { name: "Go to next page" })).toBeDisabled() }) + it("keeps the server's query string and page name in page links", () => { + const url = (n: number) => `/users?search=ali&users_page=${n}` + renderWithOnu( + , + ) + expect(screen.getByRole("link", { name: "Go to next page" })).toHaveAttribute("href", url(3)) + expect(screen.getByRole("link", { name: "Go to previous page" })).toHaveAttribute("href", url(1)) + expect(screen.getByRole("link", { name: "Go to page 10" })).toHaveAttribute("href", url(10)) + // Page 4 isn't in `links[]`; it is built from the server's URLs, not from `path`. + expect(screen.getByRole("link", { name: "Go to page 4" })).toHaveAttribute("href", url(4)) + }) + it("uses hasNextPage when the total is unknown", () => { renderWithOnu() expect(screen.getByRole("button", { name: "Go to next page" })).toBeEnabled() diff --git a/packages/onu/src/components/listing/pagination.tsx b/packages/onu/src/components/listing/pagination.tsx index b22db94a..8f007b4d 100644 --- a/packages/onu/src/components/listing/pagination.tsx +++ b/packages/onu/src/components/listing/pagination.tsx @@ -25,6 +25,8 @@ export interface LaravelPaginationMeta { from?: number | null to?: number | null path?: string + first_page_url?: string | null + last_page_url?: string | null next_page_url?: string | null prev_page_url?: string | null links?: LaravelPaginatorLink[] | LaravelResourceLinks @@ -63,14 +65,53 @@ export interface PaginationInfo { to?: number prevUrl?: string | null nextUrl?: string | null - /** Builds the URL of any page, when the server gave a `path`. */ - pageUrl?: (page: number) => string + /** + * The URL of a page, built from the URLs the server sent (keeping its query string and page + * name), or from `path` when it sent none. Undefined when neither tells how to reach that page. + */ + pageUrl?: (page: number) => string | undefined } function isResource(input: LaravelResourceCollection | LaravelPaginationMeta): input is LaravelResourceCollection { return "meta" in input && typeof input.meta === "object" && input.meta !== null } +/** Page number of a `links[]` entry: Laravel 11+ sends `page`, older versions only the label. */ +function linkPage(link: LaravelPaginatorLink) { + if (typeof link.page === "number") return link.page + return /^\d+$/.test(link.label.trim()) ? Number(link.label.trim()) : undefined +} + +/** + * Builds page URLs from the URLs a Laravel paginator sent. Those carry the query string + * (`->withQueryString()`) and a custom `pageName`, which `path` alone loses: a page the server + * listed uses its URL as is, any other swaps the page number in one of them. + */ +function serverPageUrl(known: Map, path: string | undefined) { + const absolute = (url: string) => /^[a-z][a-z\d+.-]*:/i.test(url) + const build = (template: string, param: string, n: number) => { + const url = new URL(template, "http://localhost") + url.searchParams.set(param, String(n)) + return absolute(template) ? url.toString() : `${url.pathname}${url.search}${url.hash}` + } + // The page parameter is the one whose value tracks the page number in every known URL. + let template: { url: string; param: string } | undefined + const entries = [...known] + const [first] = entries + if (first) { + const params = [...new URL(first[1], "http://localhost").searchParams.keys()] + const param = params + .filter((key) => + entries.every(([n, url]) => new URL(url, "http://localhost").searchParams.get(key) === String(n)), + ) + .sort((a, b) => Number(b === "page") - Number(a === "page"))[0] + if (param) template = { url: first[1], param } + } + if (!template && path) template = { url: path, param: "page" } + if (!known.size && !template) return undefined + return (n: number) => known.get(n) ?? (template ? build(template.url, template.param, n) : undefined) +} + /** * Reads a Laravel paginator (`->paginate()` / `->simplePaginate()` as JSON) or an * API resource collection (`{ data, meta, links }`) into one shape (R16.4). @@ -82,7 +123,19 @@ export function normalizePagination(input: LaravelResourceCollection | LaravelPa const page = Number(meta.current_page) const lastPage = meta.last_page ?? (meta.total !== undefined ? Math.max(1, Math.ceil(meta.total / perPage)) : undefined) - const path = meta.path + const prevUrl = resourceLinks?.prev ?? meta.prev_page_url ?? null + const nextUrl = resourceLinks?.next ?? meta.next_page_url ?? null + + const known = new Map() + const add = (n: number | undefined, url: string | null | undefined) => { + if (n !== undefined && url && !known.has(n)) known.set(n, url) + } + if (Array.isArray(meta.links)) for (const link of meta.links) add(linkPage(link), link.url) + add(1, resourceLinks?.first ?? meta.first_page_url) + add(lastPage, resourceLinks?.last ?? meta.last_page_url) + add(page - 1, prevUrl) + add(page + 1, nextUrl) + return { page, perPage, @@ -90,15 +143,9 @@ export function normalizePagination(input: LaravelResourceCollection | LaravelPa lastPage, from: meta.from ?? undefined, to: meta.to ?? undefined, - prevUrl: resourceLinks?.prev ?? meta.prev_page_url ?? null, - nextUrl: resourceLinks?.next ?? meta.next_page_url ?? null, - pageUrl: path - ? (n: number) => { - const url = new URL(path, "http://localhost") - url.searchParams.set("page", String(n)) - return path.startsWith("http") ? url.toString() : `${url.pathname}${url.search}` - } - : undefined, + prevUrl, + nextUrl, + pageUrl: serverPageUrl(known, meta.path), } } @@ -209,10 +256,7 @@ export function Pagination({ const hrefFor = (target: number) => { if (target === page) return undefined - if (getPageHref) return getPageHref(target) - if (target === page - 1 && info?.prevUrl) return info.prevUrl - if (target === page + 1 && info?.nextUrl) return info.nextUrl - return undefined + return getPageHref?.(target) } const go = (target: number) => (event: React.MouseEvent) => { From f446b095c9ec7e83513f498bd641a4839b862595 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:17:49 +0000 Subject: [PATCH 07/72] Keep editor content across rebuilds and follow the locale in the placeholder (#66, 4.3) Co-Authored-By: Claude Opus 5.5 --- .changeset/editor-keeps-content-on-rebuild.md | 5 +++ packages/onu/src/editor/_use-editor.ts | 30 +++++++++++--- .../onu/src/editor/wysiwyg-editor.test.tsx | 41 ++++++++++++++++++- 3 files changed, 69 insertions(+), 7 deletions(-) create mode 100644 .changeset/editor-keeps-content-on-rebuild.md diff --git a/.changeset/editor-keeps-content-on-rebuild.md b/.changeset/editor-keeps-content-on-rebuild.md new file mode 100644 index 00000000..25ba69f7 --- /dev/null +++ b/.changeset/editor-keeps-content-on-rebuild.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`WysiwygEditor` and `BlockEditor` keep what was typed when `thaana` is toggled, instead of going back to `defaultValue`, and the placeholder switches language with the locale. diff --git a/packages/onu/src/editor/_use-editor.ts b/packages/onu/src/editor/_use-editor.ts index 35aa387d..b132775b 100644 --- a/packages/onu/src/editor/_use-editor.ts +++ b/packages/onu/src/editor/_use-editor.ts @@ -68,10 +68,13 @@ export function useOnuEditor({ const thaanaOptions = typeof thaana === "object" ? thaana : {} const [serialized, setSerialized] = React.useState(() => stringifyValue(initial)) - const latest = React.useRef({ onValueChange, format, shortcuts, onReady }) + const latest = React.useRef({ onValueChange, format, shortcuts, onReady, placeholder }) React.useEffect(() => { - latest.current = { onValueChange, format, shortcuts, onReady } + latest.current = { onValueChange, format, shortcuts, onReady, placeholder } }) + // What the editor holds now, so a recreated editor (thaana or schema change) + // starts from the typed content instead of `defaultValue`. + const content = React.useRef(initial) // ARIA attributes for the contenteditable; ProseMirror reads them on every update. const attributes = React.useRef>({}) @@ -82,15 +85,16 @@ export function useOnuEditor({ shouldRerenderOnTransaction: false, editable, autofocus: autofocus ?? false, - content: initial, + content: content.current, extensions: [ ...createSchemaExtensions({ headingLevels, blocks }), Placeholder.configure({ placeholder: ({ node }) => { - if (typeof placeholder === "function") { - return placeholder({ type: node.type.name, level: node.attrs.level as number | undefined }) + const current = latest.current.placeholder + if (typeof current === "function") { + return current({ type: node.type.name, level: node.attrs.level as number | undefined }) } - return placeholder ?? "" + return current ?? "" }, emptyEditorClass: "is-empty", emptyNodeClass: placeholderOnEveryBlock ? "is-empty" : "onu-empty-node", @@ -129,6 +133,7 @@ export function useOnuEditor({ onCreate: ({ editor: e }) => latest.current.onReady?.(e), onUpdate: ({ editor: e }) => { const next = readValue(e, latest.current.format) + content.current = next setSerialized(e.isEmpty ? "" : stringifyValue(next)) latest.current.onValueChange?.(next, e) }, @@ -176,8 +181,21 @@ export function useOnuEditor({ if (!editor || editor.isDestroyed || value === undefined) return if (sameValue(readValue(editor, format), value)) return editor.commands.setContent(value, { emitUpdate: false }) + content.current = value }, [editor, value, format]) + // The placeholder follows the locale: redraw it when its text changes. A function + // placeholder is compared by what it returns, since callers pass it inline. + const placeholderKey = + typeof placeholder === "function" + ? JSON.stringify( + [{ type: "paragraph" }, ...[1, 2, 3, 4, 5, 6].map((level) => ({ type: "heading", level }))].map(placeholder), + ) + : (placeholder ?? "") + React.useEffect(() => { + if (editor && !editor.isDestroyed) editor.view.setProps({}) + }, [editor, placeholderKey]) + return { editor, editable, diff --git a/packages/onu/src/editor/wysiwyg-editor.test.tsx b/packages/onu/src/editor/wysiwyg-editor.test.tsx index 73e6b804..8e160b26 100644 --- a/packages/onu/src/editor/wysiwyg-editor.test.tsx +++ b/packages/onu/src/editor/wysiwyg-editor.test.tsx @@ -1,6 +1,6 @@ import * as React from "react" import type { Editor } from "@tiptap/core" -import { act, fireEvent, screen, waitFor, within } from "@testing-library/react" +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react" import userEvent from "@testing-library/user-event" import { describe, expect, it, vi } from "vitest" @@ -9,6 +9,8 @@ import "../../test/prosemirror" import { directions, expectNoA11yViolations, renderWithOnu } from "../../test/utils" import { FormErrorsProvider } from "../components/form/form-context" import { FormField } from "../components/form/form-field" +import { dv } from "../locales/dv" +import { OnuProvider, type OnuProviderProps } from "../providers/onu-provider" import { formatShortcut } from "./_toolbar" import { WysiwygEditor, type WysiwygEditorProps } from "./wysiwyg-editor" @@ -466,6 +468,43 @@ describe("WysiwygEditor", () => { expect(editor.storage.thaanaKeyboard.enabled).toBe(false) }) + it("keeps typed content when thaana is toggled (#66, 4.3)", async () => { + const editors: Editor[] = [] + const ui = (thaana: boolean) => ( + editors.push(e)} + /> + ) + const { rerender, container } = renderWithOnu(ui(false)) + await waitFor(() => expect(editors).toHaveLength(1)) + act(() => { + editors[0]!.commands.setContent("

Typed text

", { emitUpdate: true }) + }) + const hidden = container.querySelector("input[name=body]")! + expect(hidden.value).toContain("Typed text") + rerender(ui(true)) + await waitFor(() => expect(editors).toHaveLength(2)) + expect(editors[1]!.getText()).toBe("Typed text") + expect(hidden.value).toContain("Typed text") + }) + + it("updates the placeholder when the locale changes (#66, 4.3)", async () => { + const ui = (locale: OnuProviderProps["locale"]) => ( + + + + ) + const { rerender, container } = render(ui("en")) + await screen.findByRole("textbox", { name: "Story" }) + await waitFor(() => expect(container.querySelector("[data-placeholder='Start writing…']")).toBeInTheDocument()) + rerender(ui(dv)) + await waitFor(() => expect(container.querySelector("[data-placeholder='ލިޔަން ފައްޓަވާ…']")).toBeInTheDocument()) + }) + it("shows Dhivehi strings", async () => { renderWithOnu(, { locale: "dv" }) expect(await screen.findByRole("textbox", { name: "ލިޔުން އެޑިޓަރު" })).toBeInTheDocument() From 243964db7bee01505730435644ccd1ef34c7920b Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:17:56 +0000 Subject: [PATCH 08/72] Only cancel page drops that carry files while a dropzone is mounted (#66, 5.3) Co-Authored-By: Claude Opus 5.5 --- .changeset/file-input-text-drop.md | 5 +++++ packages/onu/src/components/files/file-input.test.tsx | 2 ++ packages/onu/src/components/files/file-input.tsx | 1 + 3 files changed, 8 insertions(+) create mode 100644 .changeset/file-input-text-drop.md diff --git a/.changeset/file-input-text-drop.md b/.changeset/file-input-text-drop.md new file mode 100644 index 00000000..f2a2f396 --- /dev/null +++ b/.changeset/file-input-text-drop.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +A mounted `FileInput` dropzone no longer cancels text dropped elsewhere on the page, such as into a textarea or the editor. diff --git a/packages/onu/src/components/files/file-input.test.tsx b/packages/onu/src/components/files/file-input.test.tsx index dbff3320..89093920 100644 --- a/packages/onu/src/components/files/file-input.test.tsx +++ b/packages/onu/src/components/files/file-input.test.tsx @@ -292,6 +292,8 @@ describe("FileInput appearance=dropzone", () => { expect(screen.getByLabelText("Browse file")).toBe(input(container)) // A file dropped next to the zone does not replace the page. expect(fireEvent.drop(document.body, { dataTransfer: filesData([dropped]) })).toBe(false) + // Text dropped elsewhere on the page (a textarea, the editor) is left alone. + expect(fireEvent.drop(document.body, { dataTransfer: { types: ["text/plain"], files: [] } })).toBe(true) }) it("accepts pasted files on the field and, optionally, the document", async () => { diff --git a/packages/onu/src/components/files/file-input.tsx b/packages/onu/src/components/files/file-input.tsx index c1d72ecd..331cbcd0 100644 --- a/packages/onu/src/components/files/file-input.tsx +++ b/packages/onu/src/components/files/file-input.tsx @@ -364,6 +364,7 @@ export function FileInput({ if (hasFiles(e.dataTransfer)) e.preventDefault() } const drop = (e: DragEvent) => { + if (!hasFiles(e.dataTransfer)) return const target = e.target as HTMLInputElement | null if (!(target?.tagName === "INPUT" && target.type === "file")) e.preventDefault() } From c9c4bfa3d621d6755e237577b9c7fb6b267c8d98 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:17:59 +0000 Subject: [PATCH 09/72] Skip disabled suggestions in TagsInput and never add one (#66, 2.3) Co-Authored-By: Claude Opus 5.5 --- .changeset/tags-input-disabled-suggestions.md | 5 +++ docs/text-inputs/tags-input.md | 2 +- .../src/components/inputs/_suggestions.tsx | 21 ++++++++--- .../src/components/inputs/tags-input.test.tsx | 36 +++++++++++++++++++ .../onu/src/components/inputs/tags-input.tsx | 4 +-- 5 files changed, 60 insertions(+), 8 deletions(-) create mode 100644 .changeset/tags-input-disabled-suggestions.md 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/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/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/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 78d7e02e..50166de3 100644 --- a/packages/onu/src/components/inputs/tags-input.tsx +++ b/packages/onu/src/components/inputs/tags-input.tsx @@ -128,10 +128,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) From f698e86aac65cb2f30e783fdf439256d7e3be78a Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:18:39 +0000 Subject: [PATCH 10/72] Filter Autocomplete suggestions by a controlled value set from outside (#66, 2.4) Co-Authored-By: Claude Opus 5.5 --- .changeset/autocomplete-controlled-filter.md | 5 ++++ .../components/inputs/autocomplete.test.tsx | 27 +++++++++++++++++++ .../src/components/inputs/autocomplete.tsx | 6 +++++ 3 files changed, 38 insertions(+) create mode 100644 .changeset/autocomplete-controlled-filter.md 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/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" From a352a06500bc297fafb8f71f9ea92d906ed5bf3f Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:19:02 +0000 Subject: [PATCH 11/72] Call React 19 ref cleanups in useMergedRef (#66, 4.5) Co-Authored-By: Claude Opus 5.5 --- .changeset/merged-ref-cleanup.md | 5 ++++ .../onu/src/hooks/use-merged-ref.test.tsx | 22 +++++++++++++++ packages/onu/src/hooks/use-merged-ref.ts | 27 ++++++++++++++----- 3 files changed, 48 insertions(+), 6 deletions(-) create mode 100644 .changeset/merged-ref-cleanup.md diff --git a/.changeset/merged-ref-cleanup.md b/.changeset/merged-ref-cleanup.md new file mode 100644 index 00000000..5c7dbd53 --- /dev/null +++ b/.changeset/merged-ref-cleanup.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +Inputs that forward a ref now honour React 19 ref cleanup functions: a ref callback that returns a cleanup has it called on unmount instead of being called again with `null`. diff --git a/packages/onu/src/hooks/use-merged-ref.test.tsx b/packages/onu/src/hooks/use-merged-ref.test.tsx index f2d99f04..db82081f 100644 --- a/packages/onu/src/hooks/use-merged-ref.test.tsx +++ b/packages/onu/src/hooks/use-merged-ref.test.tsx @@ -19,4 +19,26 @@ describe("useMergedRef", () => { expect(object.current).toBeNull() expect(callback).toHaveBeenLastCalledWith(null) }) + + it("calls a React 19 callback ref's cleanup instead of calling it with null (#66, 4.5)", () => { + const cleanup = vi.fn() + const callback = vi.fn(() => cleanup) + const object = React.createRef() + const { container, unmount } = render() + expect(callback).toHaveBeenCalledTimes(1) + expect(callback).toHaveBeenCalledWith(container.firstChild) + unmount() + expect(cleanup).toHaveBeenCalledTimes(1) + expect(callback).toHaveBeenCalledTimes(1) + expect(object.current).toBeNull() + }) + + it("still calls a callback ref without a cleanup with null, next to one with a cleanup", () => { + const plain = vi.fn() + const cleanup = vi.fn() + const { unmount } = render( cleanup} />) + unmount() + expect(plain).toHaveBeenLastCalledWith(null) + expect(cleanup).toHaveBeenCalledTimes(1) + }) }) diff --git a/packages/onu/src/hooks/use-merged-ref.ts b/packages/onu/src/hooks/use-merged-ref.ts index e0025bb4..99aad881 100644 --- a/packages/onu/src/hooks/use-merged-ref.ts +++ b/packages/onu/src/hooks/use-merged-ref.ts @@ -2,17 +2,32 @@ import * as React from "react" -function setRef(ref: React.Ref | undefined, node: T | null) { - if (typeof ref === "function") ref(node) - else if (ref) (ref as React.RefObject).current = node +/** Sets one ref and returns how to undo it: the ref's own React 19 cleanup, or a call with `null`. */ +function setRef(ref: React.Ref | undefined, node: T | null): () => void { + if (typeof ref === "function") { + const cleanup = ref(node) + return typeof cleanup === "function" ? cleanup : () => ref(null) + } + if (ref) (ref as React.RefObject).current = node + return () => { + if (ref) (ref as React.RefObject).current = null + } } -/** Merges a forwarded ref with a local one. */ +/** + * Merges a forwarded ref with a local one. Returns a React 19 ref callback with a + * cleanup, so a ref that returns its own cleanup gets it called on detach. + */ export function useMergedRef(a: React.Ref | undefined, b?: React.Ref) { return React.useCallback( + // `node` is null only when an older ref composer detaches by calling with null. (node: T | null) => { - setRef(a, node) - setRef(b, node) + const undoA = setRef(a, node) + const undoB = setRef(b, node) + return () => { + undoA() + undoB() + } }, [a, b], ) From a6fd17b1144bf87dccc7b1f0f7a9fb3a9c041546 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:19:13 +0000 Subject: [PATCH 12/72] Drop results of aborted uploads even when the uploader ignores the signal (#66, 5.4) Co-Authored-By: Claude Opus 5.5 --- .changeset/upload-ignore-aborted.md | 5 ++++ .../src/components/files/file-input.test.tsx | 29 +++++++++++++++++++ .../onu/src/components/files/use-files.ts | 21 ++++++++++++-- 3 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 .changeset/upload-ignore-aborted.md diff --git a/.changeset/upload-ignore-aborted.md b/.changeset/upload-ignore-aborted.md new file mode 100644 index 00000000..81a529f7 --- /dev/null +++ b/.changeset/upload-ignore-aborted.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +A cancelled, removed or replaced upload no longer lands in the `FileInput` value when a custom `upload` ignores its abort signal, and Cancel marks the upload cancelled straight away. diff --git a/packages/onu/src/components/files/file-input.test.tsx b/packages/onu/src/components/files/file-input.test.tsx index 89093920..0de2be70 100644 --- a/packages/onu/src/components/files/file-input.test.tsx +++ b/packages/onu/src/components/files/file-input.test.tsx @@ -694,6 +694,35 @@ describe("FileInput uploads", () => { expect(screen.getByText("a.pdf removed")).toBeInTheDocument() }) + it("keeps cancelled and replaced uploads out of the value when the uploader ignores the signal", async () => { + const calls: { resolve: (v: unknown) => void }[] = [] + const upload = vi.fn(() => new Promise((resolve) => calls.push({ resolve }))) + const onUploaded = vi.fn() + const { container, unmount } = renderWithOnu( + , + ) + await user().upload(input(container), [file("a.pdf"), file("b.pdf")]) + await userEvent.click(screen.getByRole("button", { name: "Cancel upload of a.pdf" })) + expect(await screen.findByText("Upload of a.pdf cancelled")).toBeInTheDocument() + await userEvent.click(screen.getByRole("button", { name: "Cancel upload of b.pdf" })) + await userEvent.click(await screen.findByRole("button", { name: "Remove b.pdf" })) + await act(async () => calls[0]!.resolve({ id: 1 })) + await act(async () => calls[1]!.resolve({ id: 2 })) + expect(hiddenValues(container, "docs")).toEqual([]) + expect(onUploaded).not.toHaveBeenCalled() + expect(screen.getByText("Cancelled")).toBeInTheDocument() + unmount() + + // Single mode: the file picked last wins, whichever request finishes last. + calls.length = 0 + const single = renderWithOnu() + await user().upload(input(single.container), file("old.pdf")) + await user().upload(input(single.container), file("new.pdf")) + await act(async () => calls[1]!.resolve({ id: 20 })) + await act(async () => calls[0]!.resolve({ id: 10 })) + expect(hiddenValues(single.container, "slip")).toEqual(["20"]) + }) + it("shows Laravel errors and calls onError", async () => { const { upload, calls } = controllableUploader() const onError = vi.fn() diff --git a/packages/onu/src/components/files/use-files.ts b/packages/onu/src/components/files/use-files.ts index 79169170..4bfc5dbc 100644 --- a/packages/onu/src/components/files/use-files.ts +++ b/packages/onu/src/components/files/use-files.ts @@ -189,6 +189,8 @@ export function useUploadQueue(options: UseUploadQueueOptions) { onProgress: (progress) => update(id, { progress: Math.max(0, Math.min(100, progress)) }), }).then( (response) => { + // A custom uploader may ignore the signal: a cancelled, removed or replaced upload still resolves. + if (controller.signal.aborted) return controllers.current.delete(id) const patch = { status: "success", progress: 100, response } as const update(id, patch) @@ -196,8 +198,10 @@ export function useUploadQueue(options: UseUploadQueueOptions) { callbacks.current.onUploaded?.({ id, file, ...patch }) }, (error: unknown) => { + // Cancelling already marked it; a removed or replaced upload has left the list. + if (controller.signal.aborted) return controllers.current.delete(id) - if (isAbortError(error) || controller.signal.aborted) { + if (isAbortError(error)) { update(id, { status: "cancelled" }) setAnnouncement(t("file.cancelledFile", { name: file.name })) return @@ -229,7 +233,18 @@ export function useUploadQueue(options: UseUploadQueueOptions) { [start], ) - const cancel = React.useCallback((id: string) => controllers.current.get(id)?.abort(), []) + const cancel = React.useCallback( + (id: string) => { + const controller = controllers.current.get(id) + if (!controller) return + controllers.current.delete(id) + controller.abort() + update(id, { status: "cancelled" }) + const item = items.find((i) => i.id === id) + if (item) setAnnouncement(t("file.cancelledFile", { name: item.file.name })) + }, + [items, update, t], + ) const retry = React.useCallback( (id: string) => { @@ -241,11 +256,13 @@ export function useUploadQueue(options: UseUploadQueueOptions) { const remove = React.useCallback((id: string) => { controllers.current.get(id)?.abort() + controllers.current.delete(id) setItems((list) => list.filter((item) => item.id !== id)) }, []) const clear = React.useCallback(() => { for (const controller of controllers.current.values()) controller.abort() + controllers.current.clear() setItems([]) }, []) From 3eaa03a1a7f416a7d6c78fc18462b8d8da1c26a1 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:19:28 +0000 Subject: [PATCH 13/72] Leave focus where the user moved it when InlineEdit saves on blur (#66, 2.5) Co-Authored-By: Claude Opus 5.5 --- .changeset/inline-edit-blur-focus.md | 5 ++ docs/form-scaffolding/inline-edit.md | 2 +- .../src/components/form/inline-edit.test.tsx | 46 +++++++++++++++++++ .../onu/src/components/form/inline-edit.tsx | 22 +++++---- 4 files changed, 64 insertions(+), 11 deletions(-) create mode 100644 .changeset/inline-edit-blur-focus.md 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/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/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()} /> From d1c0b284120468066589b77a3629a1157f0fa429 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:20:04 +0000 Subject: [PATCH 14/72] Merge Form's forwarded ref with useMergedRef (#66, 4.5) Co-Authored-By: Claude Opus 5.5 --- .changeset/form-ref-cleanup.md | 5 +++++ packages/onu/src/components/form/form.test.tsx | 12 ++++++++++++ packages/onu/src/components/form/form.tsx | 8 +++----- 3 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 .changeset/form-ref-cleanup.md diff --git a/.changeset/form-ref-cleanup.md b/.changeset/form-ref-cleanup.md new file mode 100644 index 00000000..d5548349 --- /dev/null +++ b/.changeset/form-ref-cleanup.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`Form` attaches a forwarded ref once instead of on every render, and calls a React 19 ref cleanup on unmount. diff --git a/packages/onu/src/components/form/form.test.tsx b/packages/onu/src/components/form/form.test.tsx index a5702c09..c8fd41b9 100644 --- a/packages/onu/src/components/form/form.test.tsx +++ b/packages/onu/src/components/form/form.test.tsx @@ -251,6 +251,18 @@ describe("Form", () => { expect(screen.getByRole("alert")).toHaveTextContent("މި ފޯމުގައި 2 މައްސަލަ ވޭ") await expectNoA11yViolations() }) + + it("attaches a forwarded ref once and calls its React 19 cleanup (#66, 4.5)", () => { + const cleanup = vi.fn() + const ref = vi.fn(() => cleanup) + const { rerender, unmount, container } = renderWithOnu(
) + rerender() + expect(ref).toHaveBeenCalledTimes(1) + expect(ref).toHaveBeenCalledWith(container.querySelector("form")) + unmount() + expect(cleanup).toHaveBeenCalledTimes(1) + expect(ref).toHaveBeenCalledTimes(1) + }) }) describe("Form with react-hook-form", () => { diff --git a/packages/onu/src/components/form/form.tsx b/packages/onu/src/components/form/form.tsx index a6c01c25..f8897cc3 100644 --- a/packages/onu/src/components/form/form.tsx +++ b/packages/onu/src/components/form/form.tsx @@ -3,6 +3,7 @@ import * as React from "react" import { FormProvider, type FieldValues, type UseFormReturn } from "react-hook-form" +import { useMergedRef } from "../../hooks/use-merged-ref" import { cn } from "../../lib/utils" import type { LabelLayout } from "../../providers/onu-provider" import { useTranslation } from "../../providers/onu-provider" @@ -127,6 +128,7 @@ export function Form({ }: FormProps) { const { t } = useTranslation() const formRef = React.useRef(null) + const mergedRef = useMergedRef(formRef, ref) const busy = React.useRef(false) const pendingFocus = React.useRef(false) const [submitting, setSubmitting] = React.useState(false) @@ -250,11 +252,7 @@ export function Form({ { - formRef.current = node - if (typeof ref === "function") ref(node) - else if (ref) ref.current = node - }} + ref={mergedRef} data-slot="form" data-status={status} aria-busy={processing || undefined} From c0f608edbf35bce7e7851ef048f6577796146c05 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:20:08 +0000 Subject: [PATCH 15/72] Drop an abandoned custom range when ReportingPeriodPicker commits (#66, 2.6) Co-Authored-By: Claude Opus 5.5 --- .changeset/reporting-period-abandoned-custom.md | 5 +++++ .../components/date/reporting-period-picker.test.tsx | 12 ++++++++++++ .../src/components/date/reporting-period-picker.tsx | 3 ++- 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 .changeset/reporting-period-abandoned-custom.md 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/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) } }} From 9194803fa66358527141df66314cf00c9bac0b6b Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:20:16 +0000 Subject: [PATCH 16/72] Scope FilterPanel's count and Clear all to its own filters (#66, 5.5) Co-Authored-By: Claude Opus 5.5 --- .changeset/filter-panel-scope.md | 5 ++++ docs/listing-pages/filter-panel.md | 4 ++-- .../components/listing/filter-panel.test.tsx | 12 ++++++++++ .../src/components/listing/filter-panel.tsx | 23 ++++++++++++++----- 4 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 .changeset/filter-panel-scope.md diff --git a/.changeset/filter-panel-scope.md b/.changeset/filter-panel-scope.md new file mode 100644 index 00000000..a7e3946c --- /dev/null +++ b/.changeset/filter-panel-scope.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`FilterPanel`'s count badge and Clear all now cover only the filters in the panel, so tabs and `ListingPage` query filters are no longer counted or cleared by it. diff --git a/docs/listing-pages/filter-panel.md b/docs/listing-pages/filter-panel.md index 7ab1dd1e..7131c799 100644 --- a/docs/listing-pages/filter-panel.md +++ b/docs/listing-pages/filter-panel.md @@ -79,7 +79,7 @@ For a classic filter bar that you render yourself (a `GET` form above a server-r - Changes in the panel are a draft: the list doesn't change until **Apply**. - **Cancel**, Escape or clicking outside close the panel and throw the draft away. -- **Clear all** removes every filter straight away and closes the panel. +- **Clear all** removes every filter in the panel straight away and closes the panel. The button's count and Clear all cover only the panel's `filters`: tabs and `queryFilters` in the same `value` are left alone. - Each filter has its own **Clear** link. - Reopening the panel always shows the filters currently applied. @@ -102,7 +102,7 @@ Every definition also accepts `render` (replace the built-in control) and `forma | ----------------------- | ---------------------------------------------------------- | --------------- | -------------------------------------- | | `filters` | `FilterDefinition[]` | | Filters on offer | | `value` | `FilterValues` | | Applied filters | -| `onApply` | `(filters) => void` | | Apply (and `{}` on Clear all) | +| `onApply` | `(filters) => void` | | Apply, and Clear all (the panel's filters removed) | | `open` / `onOpenChange` | `boolean` / `(open) => void` | | Controlled open state | | `defaultOpen` | `boolean` | `false` | Initial open state when uncontrolled | | `sheet` | `boolean` | below 768px | Force the bottom sheet or the dropdown | diff --git a/packages/onu/src/components/listing/filter-panel.test.tsx b/packages/onu/src/components/listing/filter-panel.test.tsx index 5aee753e..0b23e3e3 100644 --- a/packages/onu/src/components/listing/filter-panel.test.tsx +++ b/packages/onu/src/components/listing/filter-panel.test.tsx @@ -159,6 +159,18 @@ describe("FilterPanel", () => { await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()) }) + it("counts and clears only its own filters, keeping tabs and query filters it doesn't show", async () => { + renderWithOnu() + const button = screen.getByRole("button", { name: "Filters, 1 applied" }) + expect(within(button).getByText("1")).toBeInTheDocument() + const panel = await openPanel() + await userEvent.click(within(panel).getByRole("button", { name: "Clear all" })) + expect(applied()).toEqual({ tab: "archived", owner: "me" }) + expect(screen.getByRole("button", { name: "Filters" })).toBeInTheDocument() + await openPanel() + expect(screen.getByRole("button", { name: "Clear all" })).toBeDisabled() + }) + it("each filter has its own Clear link (§25.7)", async () => { renderWithOnu() const panel = await openPanel() diff --git a/packages/onu/src/components/listing/filter-panel.tsx b/packages/onu/src/components/listing/filter-panel.tsx index 47e9b3c2..da9924eb 100644 --- a/packages/onu/src/components/listing/filter-panel.tsx +++ b/packages/onu/src/components/listing/filter-panel.tsx @@ -27,7 +27,10 @@ export interface FilterPanelProps { filters: FilterDefinition[] /** The applied filters. */ value: FilterValues - /** Called with the new filters on Apply, and with `{}` on Clear all. */ + /** + * Called with the new filters on Apply, and on Clear all with this panel's filters removed. + * Values for keys the panel doesn't show (tabs, `queryFilters`) are passed through untouched. + */ onApply: (filters: FilterValues) => void /** Controlled open state. */ open?: boolean @@ -74,6 +77,13 @@ export interface FilterPanelProps { * the page, changes are a draft until Filter (or Enter), Reset clears the * form's filters, and Expand shows the fields past `collapsedCount`. */ +/** The values with this panel's filters removed, keeping filters it doesn't own (tabs, query filters). */ +function withoutFilters(value: FilterValues, filters: FilterDefinition[]) { + const next = { ...value } + for (const definition of filters) delete next[definition.key] + return cleanFilters(next) +} + export function FilterPanel(props: FilterPanelProps) { const { t } = useTranslation() const { announce, region } = useAnnouncer({ role: "status" }) @@ -180,10 +190,9 @@ function FilterQueryForm({ className="touch:min-h-11" onClick={() => { // Reset clears this form's fields and keeps any other filters. - const next = { ...draft } - for (const definition of filters) delete next[definition.key] + const next = withoutFilters(draft, filters) setDraft(next) - onApply(cleanFilters(next)) + onApply(next) }} > {t("listing.filterReset")} @@ -241,7 +250,9 @@ function FilterPopoverPanel({ if (open) setDraft(value) } - const count = Object.values(cleanFilters(value)).length + // Only this panel's filters: tabs and query filters on the page are not its to count or clear. + const applied = cleanFilters(value) + const count = filters.filter((definition) => definition.key in applied).length const format = new Intl.NumberFormat(locale.numberLocale) const apply = () => { @@ -249,7 +260,7 @@ function FilterPopoverPanel({ setOpen(false) } const clearAll = () => { - onApply({}) + onApply(withoutFilters(value, filters)) setOpen(false) } From 2b14969aff897205f2280513a5746b478013b0f2 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:20:21 +0000 Subject: [PATCH 17/72] Merge ValidationSummary's forwarded ref with useMergedRef (#66, 4.5) Co-Authored-By: Claude Opus 5.5 --- .changeset/validation-summary-ref-cleanup.md | 5 +++++ .../components/form/validation-summary.test.tsx | 16 +++++++++++++++- .../src/components/form/validation-summary.tsx | 8 +++----- 3 files changed, 23 insertions(+), 6 deletions(-) create mode 100644 .changeset/validation-summary-ref-cleanup.md diff --git a/.changeset/validation-summary-ref-cleanup.md b/.changeset/validation-summary-ref-cleanup.md new file mode 100644 index 00000000..a1db931f --- /dev/null +++ b/.changeset/validation-summary-ref-cleanup.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`ValidationSummary` attaches a forwarded ref once instead of on every render, and calls a React 19 ref cleanup on unmount. diff --git a/packages/onu/src/components/form/validation-summary.test.tsx b/packages/onu/src/components/form/validation-summary.test.tsx index b9f84c50..a54326d2 100644 --- a/packages/onu/src/components/form/validation-summary.test.tsx +++ b/packages/onu/src/components/form/validation-summary.test.tsx @@ -1,6 +1,6 @@ import { screen, waitFor } from "@testing-library/react" import userEvent from "@testing-library/user-event" -import { describe, expect, it } from "vitest" +import { describe, expect, it, vi } from "vitest" import { directions, expectNoA11yViolations, renderWithOnu } from "../../../test/utils" import { form as dv_form } from "../../locales/dv/form" @@ -87,6 +87,20 @@ describe("ValidationSummary", () => { }) }) +describe("ValidationSummary ref", () => { + it("attaches a forwarded ref once and calls its React 19 cleanup (#66, 4.5)", () => { + const cleanup = vi.fn() + const ref = vi.fn(() => cleanup) + const { rerender, unmount } = renderWithOnu() + rerender() + expect(ref).toHaveBeenCalledTimes(1) + expect(ref).toHaveBeenCalledWith(screen.getByRole("alert")) + unmount() + expect(cleanup).toHaveBeenCalledTimes(1) + expect(ref).toHaveBeenCalledTimes(1) + }) +}) + describe("ValidationSummary with a ValidationError that has no message", () => { it("shows the translated title", () => { const errors = getValidationErrors(new ValidationError({ name: "ނަން ލިޔުއްވާ" })) diff --git a/packages/onu/src/components/form/validation-summary.tsx b/packages/onu/src/components/form/validation-summary.tsx index 4ead7e35..a5323a18 100644 --- a/packages/onu/src/components/form/validation-summary.tsx +++ b/packages/onu/src/components/form/validation-summary.tsx @@ -2,6 +2,7 @@ import * as React from "react" +import { useMergedRef } from "../../hooks/use-merged-ref" import { Icon } from "../../icons/icon" import { cn } from "../../lib/utils" import { useTranslation } from "../../providers/onu-provider" @@ -47,6 +48,7 @@ export function ValidationSummary({ }: ValidationSummaryProps) { const { t } = useTranslation() const local = React.useRef(null) + const mergedRef = useMergedRef(local, ref) const titleId = React.useId() const payload = isValidationPayload(errors) ? errors : null const entries = errorEntries(payload ? payload.errors : (errors as FormErrors | null | undefined)) @@ -73,11 +75,7 @@ export function ValidationSummary({ return (
{ - local.current = node - if (typeof ref === "function") ref(node) - else if (ref) ref.current = node - }} + ref={mergedRef} data-slot="validation-summary" role="alert" tabIndex={-1} From a94b5679a9e759f956d285545bed74c675177d42 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:21:14 +0000 Subject: [PATCH 18/72] Label custom filter controls with a real label and pass labelId (#66, 5.6) Co-Authored-By: Claude Opus 5.5 --- .changeset/filter-render-label.md | 5 ++++ docs/listing-pages/filter-panel.md | 4 +-- .../components/listing/_filter-controls.tsx | 29 +++++++++++++++++++ .../components/listing/filter-panel.test.tsx | 26 +++++++++++++++++ .../src/components/listing/filter-panel.tsx | 21 ++++++++------ .../src/components/listing/listing-types.ts | 4 ++- 6 files changed, 77 insertions(+), 12 deletions(-) create mode 100644 .changeset/filter-render-label.md diff --git a/.changeset/filter-render-label.md b/.changeset/filter-render-label.md new file mode 100644 index 00000000..c8ee4000 --- /dev/null +++ b/.changeset/filter-render-label.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +A custom filter `render` control is now named by the filter's label: the label is a real `