diff --git a/.changeset/confirm-question-locale.md b/.changeset/confirm-question-locale.md new file mode 100644 index 000000000..c95de468a --- /dev/null +++ b/.changeset/confirm-question-locale.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +The confirm question for a named action (`confirm: true` on "Approve", "Suspend" and the like) is now worded by the locale, so Dhivehi reads "{name} {action}؟" instead of an English-ordered title with a Latin "?". Only delete actions add "This can't be undone." below. diff --git a/.changeset/dv-date-fns-locale.md b/.changeset/dv-date-fns-locale.md new file mode 100644 index 000000000..898cf121b --- /dev/null +++ b/.changeset/dv-date-fns-locale.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +The Dhivehi date-fns locale now labels "afternoon" and "evening" as PM and "midnight" and "night" as AM, and parses short and narrow weekday names (`parse("އާދި", "EEE", …)`). diff --git a/.changeset/format-currency-english.md b/.changeset/format-currency-english.md new file mode 100644 index 000000000..355004cad --- /dev/null +++ b/.changeset/format-currency-english.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`useFormatCurrency` now brings its own English text, so it no longer renders the literal `common.currency` in a build where no other module loaded the `common` strings. diff --git a/.changeset/locale-load-retry.md b/.changeset/locale-load-retry.md new file mode 100644 index 000000000..3ddf15827 --- /dev/null +++ b/.changeset/locale-load-retry.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`OnuProvider locale="dv"` now retries a failed Dhivehi chunk load (after 1, 3 and 10 seconds, then when the browser comes back online) instead of staying in English for the rest of the session. diff --git a/.changeset/onu-locale-formatting.md b/.changeset/onu-locale-formatting.md new file mode 100644 index 000000000..d9e7c15b5 --- /dev/null +++ b/.changeset/onu-locale-formatting.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`DataTable` date cells and chart tooltip numbers are now formatted with Onu's locale instead of the browser's, so Dhivehi pages show Dhivehi month names and server and client render the same text. diff --git a/.changeset/thaana-controlled-toggle.md b/.changeset/thaana-controlled-toggle.md new file mode 100644 index 000000000..b955f3c71 --- /dev/null +++ b/.changeset/thaana-controlled-toggle.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +A controlled `useThaanaInput({ enabled })` no longer drifts out of step when the Thaana shortcut is pressed and the parent keeps the value: the field keeps typing Thaana while it shows `dir="rtl"`. `attachThaanaKeyboard`'s `onToggle` now receives the requested state and leaves the change to you (call `setEnabled`); without `onToggle` the shortcut still flips the mode itself. diff --git a/.changeset/thaana-follows-element.md b/.changeset/thaana-follows-element.md new file mode 100644 index 000000000..f5ead5077 --- /dev/null +++ b/.changeset/thaana-follows-element.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +The Thaana keyboard now attaches to fields that mount later or get replaced, so `CommandPalette thaana` types Thaana and a `TextInput` keeps typing Thaana after an `endAddon` appears. `useThaanaInput(options)` and `useThaanaField(thaana)` now return a callback `ref` to put on the element instead of taking a ref object. diff --git a/.changeset/thaana-multiline-paste.md b/.changeset/thaana-multiline-paste.md new file mode 100644 index 000000000..15c50b5e7 --- /dev/null +++ b/.changeset/thaana-multiline-paste.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`paste: "transliterate"` now converts pastes that contain line breaks or tabs, so multi-line Latin text pasted into a Thaana `Textarea` becomes Thaana. diff --git a/.changeset/thaana-select-typeahead.md b/.changeset/thaana-select-typeahead.md new file mode 100644 index 000000000..8d1d39f76 --- /dev/null +++ b/.changeset/thaana-select-typeahead.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +Typing on a closed select with `thaana` now starts the search with the Thaana letter (`ކ`, not `k`). diff --git a/docs/charts/category-chart.md b/docs/charts/category-chart.md index 5cce7e6d8..3275baa63 100644 --- a/docs/charts/category-chart.md +++ b/docs/charts/category-chart.md @@ -217,7 +217,7 @@ Reduced motion still wins inside ``. `useChartAn ## Primitives -The shadcn primitives are exported from the same entry for custom charts: `ChartContainer`, `ChartTooltip`, `ChartTooltipContent` (with an Onu `valueFormatter` prop), `ChartLegend`, `ChartLegendContent`, `ChartStyle` and the `ChartConfig` type. They are not exported from the package root, so `recharts` stays optional. +The shadcn primitives are exported from the same entry for custom charts: `ChartContainer`, `ChartTooltip`, `ChartTooltipContent` (with an Onu `valueFormatter` prop; without it, numbers use Onu's number locale), `ChartLegend`, `ChartLegendContent`, `ChartStyle` and the `ChartConfig` type. They are not exported from the package root, so `recharts` stays optional. ## RTL diff --git a/docs/guides/dhivehi-and-locales.md b/docs/guides/dhivehi-and-locales.md index 696e5743a..19a8d5fe7 100644 --- a/docs/guides/dhivehi-and-locales.md +++ b/docs/guides/dhivehi-and-locales.md @@ -16,7 +16,7 @@ import { dv } from '@javaabu/onu/locales/dv'; Only apps that use Dhivehi download its text (about 15 kB brotli): - `locale={dv}`, with `dv` imported from `@javaabu/onu/locales/dv`, bundles Dhivehi with your app. The first render is already in Dhivehi. Use this when Dhivehi is the main or a common language. -- `locale="dv"` loads Dhivehi on demand, as a separate chunk, when the provider first needs it. Direction and `lang` switch at once, and strings show in English until the chunk arrives (usually within the first frames). This suits a language switcher in a mostly English app. +- `locale="dv"` loads Dhivehi on demand, as a separate chunk, when the provider first needs it. Direction and `lang` switch at once, and strings show in English until the chunk arrives (usually within the first frames). A failed load is retried after 1, 3 and 10 seconds, then again when the browser comes back online. This suits a language switcher in a mostly English app. - English needs nothing: leave out `locale` (or pass `"en"`). Each component brings the English text it uses, so a page with a text field does not carry the strings of the data table, the map or the editor. `import { dv } from '@javaabu/onu'` still works too; it bundles Dhivehi like the `locales/dv` import. diff --git a/docs/guides/thaana-input.md b/docs/guides/thaana-input.md index 8504c9923..281260485 100644 --- a/docs/guides/thaana-input.md +++ b/docs/guides/thaana-input.md @@ -44,8 +44,8 @@ Pass your own map with `createKeymap(latinKeys, thaanaCharacters)`. import { useThaanaInput, attachThaanaKeyboard, transliterate } from '@javaabu/onu/thaana'; function MyField() { - const ref = useRef(null); - const { enabled, toggle } = useThaanaInput(ref, { keymap: 'phonetic' }); + // `ref` is a callback ref: the keyboard follows the element, even one that mounts later. + const { ref, enabled, toggle } = useThaanaInput({ keymap: 'phonetic' }); return ; } @@ -54,6 +54,9 @@ const keyboard = attachThaanaKeyboard(document.querySelector('#name')); keyboard.setEnabled(false); keyboard.detach(); +// Own the state: with onToggle, Alt+Shift+T asks instead of flipping the mode itself. +const owned = attachThaanaKeyboard(input, { onToggle: (next) => owned.setEnabled(next) }); + transliterate('dhivehi'); // "ދހިވެހި" ``` diff --git a/docs/listing-pages/data-table.md b/docs/listing-pages/data-table.md index 8c96a8b0f..0e3c66d85 100644 --- a/docs/listing-pages/data-table.md +++ b/docs/listing-pages/data-table.md @@ -69,7 +69,7 @@ The table always shows the rows it is given (it never sorts or pages by itself): Other `
` props and `ref` go to the root. -`DataTableColumn`: `id`, `header` (text), `headerContent?`, `accessor?` (key or function), `cell?`, `sortable?`, `hideable?`, `primary?`, `align?`, `numeric?` (tabular figures, end-aligned), `hideOnCards?`, `className?`, `headerClassName?`. +`DataTableColumn`: `id`, `header` (text), `headerContent?`, `accessor?` (key or function), `cell?`, `sortable?`, `hideable?`, `primary?`, `align?`, `numeric?` (tabular figures, end-aligned), `hideOnCards?`, `className?`, `headerClassName?`. Without `cell`, a `Date` value is shown with Onu's locale (`useFormatDate`, "Jan 2, 2026" / "2 ޖެނުއަރީ 2026"), not the browser's. ## Accessibility diff --git a/docs/overlays/action-menu.md b/docs/overlays/action-menu.md index f30c3c87b..b3d9010d7 100644 --- a/docs/overlays/action-menu.md +++ b/docs/overlays/action-menu.md @@ -89,7 +89,7 @@ const { t } = useTranslation() ``` -A destructive action (or `confirm: true`) asks "Delete Jane Doe?" for `id: "delete"`, "Permanently delete Jane Doe?" for `id: "force-delete"`, and "{label} Jane Doe?" otherwise, with "This can't be undone." below; `confirm` options replace any part of that. The dialog is styled even without a `ConfirmProvider`. +A destructive action (or `confirm: true`) asks "Delete Jane Doe?" for `id: "delete"`, "Permanently delete Jane Doe?" for `id: "force-delete"`, and "{label} Jane Doe?" otherwise (worded by the locale, so Dhivehi puts the name first and ends with "؟"). Only `id: "delete"` and `id: "force-delete"` add a "can't be undone" warning; `confirm` options replace any part of that. The dialog is styled even without a `ConfirmProvider`. ### `RecordAction` diff --git a/docs/text-inputs/thaana-toggle.md b/docs/text-inputs/thaana-toggle.md index 9182d78eb..02b026aca 100644 --- a/docs/text-inputs/thaana-toggle.md +++ b/docs/text-inputs/thaana-toggle.md @@ -10,8 +10,7 @@ import { ThaanaToggle } from "@javaabu/onu" import { useThaanaInput } from "@javaabu/onu/thaana" function MyField() { - const ref = useRef(null) - const { enabled, toggle } = useThaanaInput(ref) + const { ref, enabled, toggle } = useThaanaInput() return (
diff --git a/packages/onu/src/components/choice/_combobox.tsx b/packages/onu/src/components/choice/_combobox.tsx index aba1e042c..548147379 100644 --- a/packages/onu/src/components/choice/_combobox.tsx +++ b/packages/onu/src/components/choice/_combobox.tsx @@ -7,6 +7,7 @@ import { Command as CommandPrimitive } from "cmdk" import { Icon } from "../../icons/icon" import { cn } from "../../lib/utils" import { useTranslation } from "../../providers/onu-provider" +import { transliterate } from "../../thaana/convert" import { useThaanaField, type ThaanaProp } from "../../thaana/use-thaana-field" import { Badge } from "../../ui/badge" import { Button } from "../../ui/button" @@ -138,8 +139,7 @@ function SearchField({ className?: string onKeyDown?: React.KeyboardEventHandler }) { - const ref = React.useRef(null) - const { fieldProps } = useThaanaField(ref, thaana) + const { ref, fieldProps } = useThaanaField(thaana) return (
@@ -275,9 +275,10 @@ export function ComboboxCore({ e.preventDefault() setOpen(true) } else if (e.key.length === 1 && e.key !== " " && !e.ctrlKey && !e.metaKey && !e.altKey) { - // Typing on the closed field starts a search. + // Typing on the closed field starts a search, in Thaana when the search field types Thaana. e.preventDefault() - onQueryChange(e.key) + const thaanaOn = !!thaana && (typeof thaana !== "object" || thaana.defaultEnabled !== false) + onQueryChange(thaanaOn ? transliterate(e.key, typeof thaana === "object" ? thaana.keymap : undefined) : e.key) setOpen(true) } else if ((e.key === "Backspace" || e.key === "Delete") && clearable && !required && selected.length) { e.preventDefault() diff --git a/packages/onu/src/components/choice/account-switcher.tsx b/packages/onu/src/components/choice/account-switcher.tsx index 492da295b..3bf7ffca8 100644 --- a/packages/onu/src/components/choice/account-switcher.tsx +++ b/packages/onu/src/components/choice/account-switcher.tsx @@ -110,8 +110,7 @@ function SearchInput({ placeholder: string thaana?: ThaanaProp }) { - const ref = React.useRef(null) - const { fieldProps } = useThaanaField(ref, thaana) + const { ref, fieldProps } = useThaanaField(thaana) return (
diff --git a/packages/onu/src/components/choice/dual-listbox.tsx b/packages/onu/src/components/choice/dual-listbox.tsx index aaee1cf72..df1cf55f8 100644 --- a/packages/onu/src/components/choice/dual-listbox.tsx +++ b/packages/onu/src/components/choice/dual-listbox.tsx @@ -55,8 +55,7 @@ function FilterInput({ disabled?: boolean className?: string }) { - const ref = React.useRef(null) - const { fieldProps } = useThaanaField(ref, thaana) + const { ref, fieldProps } = useThaanaField(thaana) return (
{ expect(await screen.findByRole("combobox", { name: "Search…" })).toHaveValue("a") }) + it("seeds the search with the Thaana letter when typing on a closed thaana field", async () => { + const user = userEvent.setup() + renderWithOnu(, { locale: "dv" }) + screen.getByRole("combobox", { name: "ރަށް" }).focus() + await user.keyboard("k") + expect(await screen.findByRole("combobox", { name: "ހޯއްދަވާ…" })).toHaveValue("ކ") + }) + + it("seeds the search with the Latin key when thaana starts off", async () => { + const user = userEvent.setup() + renderWithOnu(, { + locale: "dv", + }) + screen.getByRole("combobox", { name: "ރަށް" }).focus() + await user.keyboard("k") + expect(await screen.findByRole("combobox", { name: "ހޯއްދަވާ…" })).toHaveValue("k") + }) + it("is controlled and clearable on optional fields", async () => { function Controlled() { const [value, setValue] = React.useState("male") diff --git a/packages/onu/src/components/inputs/tags-input.tsx b/packages/onu/src/components/inputs/tags-input.tsx index 78d7e02ea..5d8357f73 100644 --- a/packages/onu/src/components/inputs/tags-input.tsx +++ b/packages/onu/src/components/inputs/tags-input.tsx @@ -83,11 +83,17 @@ export function TagsInput({ const { t } = useTranslation() const local = React.useRef(null) const anchorRef = React.useRef(null) - const merged = useMergedRef(local, ref) const [tags, setTags] = useControllableState(valueProp, defaultValue, onValueChange) const [text, setText] = React.useState("") const [announce, setAnnounce] = React.useState(null) - const { fieldProps, active: thaanaActive, enabled: thaanaOn, toggle } = useThaanaField(local, thaana) + const { + ref: thaanaRef, + fieldProps, + active: thaanaActive, + enabled: thaanaOn, + toggle, + } = useThaanaField(thaana) + const merged = useMergedRef(local, thaanaRef, ref) const { name, ...control } = useFormFieldControl({ ...props, disabled: disabledProp }) const disabled = !!control.disabled const full = max !== undefined && tags.length >= max diff --git a/packages/onu/src/components/inputs/text-input.test.tsx b/packages/onu/src/components/inputs/text-input.test.tsx index 517c22572..a3ced178e 100644 --- a/packages/onu/src/components/inputs/text-input.test.tsx +++ b/packages/onu/src/components/inputs/text-input.test.tsx @@ -70,6 +70,14 @@ describe("TextInput", () => { expect(input).toHaveValue("ަހމަދު") }) + it("keeps typing Thaana when an end addon replaces the input node", () => { + const { rerender } = renderWithOnu() + rerender() + const input = screen.getByRole("textbox") + typeThaana(input, "ahmadu") + expect(input).toHaveValue("ަހމަދު") + }) + it("toggles Thaana with the toggle button and announces it", async () => { renderWithOnu() const toggle = screen.getByRole("button", { name: /Thaana and Latin/ }) diff --git a/packages/onu/src/components/inputs/text-input.tsx b/packages/onu/src/components/inputs/text-input.tsx index 9b7749877..bbce0739c 100644 --- a/packages/onu/src/components/inputs/text-input.tsx +++ b/packages/onu/src/components/inputs/text-input.tsx @@ -94,10 +94,15 @@ export function TextInput({ ref, ...props }: TextInputProps) { - const local = React.useRef(null) - const merged = useMergedRef(local, ref) const latin = props.type === "email" || props.type === "url" - const { fieldProps, active, enabled, toggle } = useThaanaField(local, latin ? undefined : thaana) + const { + ref: thaanaRef, + fieldProps, + active, + enabled, + toggle, + } = useThaanaField(latin ? undefined : thaana) + const merged = useMergedRef(thaanaRef, ref) const controlProps = useFormFieldControl(latin ? latinProps(props, urlProtocol) : props) const showToggle = active && thaanaToggle const end = diff --git a/packages/onu/src/components/inputs/textarea.tsx b/packages/onu/src/components/inputs/textarea.tsx index 685b386d4..0151d5b23 100644 --- a/packages/onu/src/components/inputs/textarea.tsx +++ b/packages/onu/src/components/inputs/textarea.tsx @@ -31,9 +31,8 @@ export function Textarea({ onChange, ...props }: TextareaProps) { - const local = React.useRef(null) - const merged = useMergedRef(local, ref) - const { fieldProps, active, enabled, toggle } = useThaanaField(local, thaana) + const { ref: thaanaRef, fieldProps, active, enabled, toggle } = useThaanaField(thaana) + const merged = useMergedRef(thaanaRef, ref) const controlProps = useFormFieldControl(props) const [typed, setTyped] = React.useState(() => String(props.defaultValue ?? "").length) const count = props.value !== undefined ? String(props.value).length : typed diff --git a/packages/onu/src/components/listing/data-table.test.tsx b/packages/onu/src/components/listing/data-table.test.tsx index b4f34c4f6..ce357ae24 100644 --- a/packages/onu/src/components/listing/data-table.test.tsx +++ b/packages/onu/src/components/listing/data-table.test.tsx @@ -421,6 +421,20 @@ describe("DataTable", () => { expect(screen.getByRole("columnheader", { name: /Name/ })).toHaveAttribute("aria-sort", "ascending") }) + it("formats dates with Onu's locale, not the browser's", () => { + renderWithOnu( + , + { locale: "dv" }, + ) + expect(screen.getAllByText("2 ޖެނުއަރީ 2026").length).toBeGreaterThan(0) + }) + it("supports a custom empty state and pagination without a total", () => { renderWithOnu(Nothing

} pagination />) expect(screen.getByText("Nothing")).toBeInTheDocument() diff --git a/packages/onu/src/components/listing/data-table.tsx b/packages/onu/src/components/listing/data-table.tsx index 1b211108c..3a860bc97 100644 --- a/packages/onu/src/components/listing/data-table.tsx +++ b/packages/onu/src/components/listing/data-table.tsx @@ -18,6 +18,7 @@ import { cva, type VariantProps } from "class-variance-authority" import { useAnnouncer } from "../../a11y/use-announcer" import { useIsMobile } from "../../hooks/use-mobile" +import { useFormatDate } from "../../i18n/format" import { Icon } from "../../icons/icon" import { cn } from "../../lib/utils" import { useLinkComponent, useTranslation } from "../../providers/onu-provider" @@ -143,9 +144,9 @@ function valueOf(column: DataTableColumn, row: T): unknown return row[key] } -function display(value: unknown): React.ReactNode { +function display(value: unknown, formatDate: (date: Date) => string): React.ReactNode { if (value === null || value === undefined || value === "") return null - if (value instanceof Date) return value.toLocaleDateString() + if (value instanceof Date) return formatDate(value) if (typeof value === "string" || typeof value === "number") return value return String(value) } @@ -190,6 +191,7 @@ export function DataTable({ ...props }: DataTableProps) { const { t } = useTranslation() + const formatDate = useFormatDate() const Link = useLinkComponent() const internal = useListingState({ url: false }) const state = stateProp ?? internal @@ -291,7 +293,7 @@ export function DataTable({ const clickable = !!onRowClick || !!getRowHref const renderValue = (column: DataTableColumn, row: T) => { - const content = column.cell ? column.cell(row) : display(valueOf(column, row)) + const content = column.cell ? column.cell(row) : display(valueOf(column, row), formatDate) const shown = content ?? {t("common.emptyValue")} if (column !== primary) return shown const href = getRowHref?.(row) diff --git a/packages/onu/src/components/listing/search-box.tsx b/packages/onu/src/components/listing/search-box.tsx index 8d546e89c..92c06ba21 100644 --- a/packages/onu/src/components/listing/search-box.tsx +++ b/packages/onu/src/components/listing/search-box.tsx @@ -63,8 +63,8 @@ export function SearchBox({ }: SearchBoxProps) { const { t } = useTranslation() const local = React.useRef(null) - const merged = useMergedRef(local, ref) - const { fieldProps } = useThaanaField(local, thaana) + const { ref: thaanaRef, fieldProps } = useThaanaField(thaana) + const merged = useMergedRef(local, thaanaRef, ref) const controlProps = useFormFieldControl(props) const [applied, setApplied] = React.useState(value ?? defaultValue) diff --git a/packages/onu/src/components/overlays/_menu-items.tsx b/packages/onu/src/components/overlays/_menu-items.tsx index 9e9952245..16b72b919 100644 --- a/packages/onu/src/components/overlays/_menu-items.tsx +++ b/packages/onu/src/components/overlays/_menu-items.tsx @@ -147,7 +147,8 @@ export function needsConfirm(item: MenuActionItem) { * The question to ask before running an item. With a record `name`, `true` * (or a `destructive` item) asks "Delete Jane Doe?" (`id: "delete"`), * "Permanently delete Jane Doe?" (`id: "force-delete"`) or "Approve Jane Doe?" - * (the item's label), and given options are laid over that question. + * (the item's label, worded by the locale's `listing.actionRecordTitle`), and + * given options are laid over that question. Only deletes add "This can't be undone." */ export function useConfirmQuestion(name?: string) { const { t } = useTranslation() @@ -167,9 +168,15 @@ export function useConfirmQuestion(name?: string) { variant: "destructive", ...custom, } + const action = textOf(item.label) + const isDelete = item.id === "delete" return { - title: item.id === "delete" ? t("listing.deleteRecordTitle", { name }) : `${textOf(item.label)} ${name}?`, - description: t("listing.deleteRecordDescription"), + title: isDelete + ? t("listing.deleteRecordTitle", { name }) + : action + ? t("listing.actionRecordTitle", { action, name }) + : undefined, + description: isDelete ? t("listing.deleteRecordDescription") : undefined, confirmLabel: item.label, variant: destructive ? "destructive" : "default", ...custom, diff --git a/packages/onu/src/components/overlays/action-menu.test.tsx b/packages/onu/src/components/overlays/action-menu.test.tsx index dc40b21c6..a3c5277a3 100644 --- a/packages/onu/src/components/overlays/action-menu.test.tsx +++ b/packages/onu/src/components/overlays/action-menu.test.tsx @@ -421,7 +421,18 @@ describe("ActionMenu with a record name", () => { await userEvent.click(screen.getByRole("button", { name: "Actions for Form 12" })) await userEvent.click(await screen.findByRole("menuitem", { name: "Suspend" })) - expect(await screen.findByRole("alertdialog", { name: "Suspend Form 12?" })).toBeInTheDocument() + const suspend = await screen.findByRole("alertdialog", { name: "Suspend Form 12?" }) + expect(within(suspend).queryByText("This can't be undone.")).not.toBeInTheDocument() + await userEvent.keyboard("{Escape}") + }) + + it("words the confirm question in the locale's order", async () => { + renderWithOnu(, { + locale: "dv", + }) + await userEvent.click(screen.getAllByRole("button")[0]!) + await userEvent.click(await screen.findByRole("menuitem", { name: "ހުއްޓާލާ" })) + expect(await screen.findByRole("alertdialog", { name: "ފޯމް 12 ހުއްޓާލާ؟" })).toBeInTheDocument() await userEvent.keyboard("{Escape}") }) diff --git a/packages/onu/src/components/overlays/command-palette.test.tsx b/packages/onu/src/components/overlays/command-palette.test.tsx index e4070a25c..2cabf397f 100644 --- a/packages/onu/src/components/overlays/command-palette.test.tsx +++ b/packages/onu/src/components/overlays/command-palette.test.tsx @@ -274,6 +274,26 @@ describe("CommandPalette", () => { expect(input).toHaveAttribute("lang", "dv") expect(input).toHaveAttribute("dir", "rtl") expect(screen.getByRole("button", { name: /Thaana and Latin/ })).toBeInTheDocument() + fireEvent( + input, + new InputEvent("beforeinput", { inputType: "insertText", data: "k", cancelable: true, bubbles: true }), + ) + expect(input).toHaveValue("ކ") + }) + + it("types Thaana each time the palette opens", async () => { + renderWithOnu() + for (let i = 0; i < 2; i++) { + fireEvent.keyDown(document, { key: "k", ctrlKey: true }) + const input = await screen.findByRole("combobox") + fireEvent( + input, + new InputEvent("beforeinput", { inputType: "insertText", data: "k", cancelable: true, bubbles: true }), + ) + expect(input).toHaveValue("ކ") + fireEvent.keyDown(input, { key: "Escape" }) + await waitFor(() => expect(screen.queryByRole("combobox")).not.toBeInTheDocument()) + } }) it("closes from the phone close button", async () => { diff --git a/packages/onu/src/components/overlays/command-palette.tsx b/packages/onu/src/components/overlays/command-palette.tsx index d1f6e1b14..6b330d238 100644 --- a/packages/onu/src/components/overlays/command-palette.tsx +++ b/packages/onu/src/components/overlays/command-palette.tsx @@ -175,8 +175,13 @@ export function CommandPalette({ const [open, setOpenState] = useControllableState(openProp, defaultOpen, onOpenChange) const [query, setQuery] = React.useState("") const [known, setKnown] = React.useState>({}) - const inputRef = React.useRef(null) - const { fieldProps, active: thaanaActive, enabled: thaanaEnabled, toggle } = useThaanaField(inputRef, thaana) + const { + ref: inputRef, + fieldProps, + active: thaanaActive, + enabled: thaanaEnabled, + toggle, + } = useThaanaField(thaana) const recentKey = (typeof recent === "object" && recent.storageKey) || DEFAULT_RECENT_KEY const maxRecent = (typeof recent === "object" && recent.max) || 5 diff --git a/packages/onu/src/hooks/use-merged-ref.ts b/packages/onu/src/hooks/use-merged-ref.ts index 99aad8815..39ce5c95d 100644 --- a/packages/onu/src/hooks/use-merged-ref.ts +++ b/packages/onu/src/hooks/use-merged-ref.ts @@ -15,20 +15,16 @@ function setRef(ref: React.Ref | undefined, node: T | null): () => void { } /** - * Merges a forwarded ref with a local one. Returns a React 19 ref callback with a + * Merges a forwarded ref with local ones. 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) { +export function useMergedRef(a: React.Ref | undefined, b?: React.Ref, c?: React.Ref) { return React.useCallback( // `node` is null only when an older ref composer detaches by calling with null. (node: T | null) => { - const undoA = setRef(a, node) - const undoB = setRef(b, node) - return () => { - undoA() - undoB() - } + const undo = [setRef(a, node), setRef(b, node), setRef(c, node)] + return () => undo.forEach((fn) => fn()) }, - [a, b], + [a, b, c], ) } diff --git a/packages/onu/src/i18n/english-registry.test.ts b/packages/onu/src/i18n/english-registry.test.ts index bedfbedb2..eabf4aa59 100644 --- a/packages/onu/src/i18n/english-registry.test.ts +++ b/packages/onu/src/i18n/english-registry.test.ts @@ -45,7 +45,7 @@ function registeredNamespaces(code: string) { const modules = sourceFiles(SRC) .map((file) => path.relative(SRC, file).split(path.sep).join("/")) - .filter((rel) => !rel.startsWith("locales/") && !rel.startsWith("i18n/")) + .filter((rel) => !rel.startsWith("locales/")) const withStrings = modules.filter((rel) => usedNamespaces(readFileSync(path.join(SRC, rel), "utf8")).size) diff --git a/packages/onu/src/i18n/format.ts b/packages/onu/src/i18n/format.ts index 5e4248fe6..ebe92237e 100644 --- a/packages/onu/src/i18n/format.ts +++ b/packages/onu/src/i18n/format.ts @@ -3,7 +3,11 @@ import * as React from "react" import { format as formatDateFns, isValid, parseISO } from "date-fns" +import { common as en_common } from "../locales/en/common" import { useOnu } from "../providers/onu-provider" +import { registerEnglish } from "./english" + +registerEnglish({ common: en_common }) /** A date as a `Date`, a timestamp, or an ISO string (`"2026-03-12"`, `"2026-03-12T09:30:00Z"`). */ export type DateInput = Date | number | string diff --git a/packages/onu/src/locales/date-fns-dv.test.ts b/packages/onu/src/locales/date-fns-dv.test.ts new file mode 100644 index 000000000..ca3c9dd33 --- /dev/null +++ b/packages/onu/src/locales/date-fns-dv.test.ts @@ -0,0 +1,35 @@ +import { format, parse } from "date-fns" +import { describe, expect, it } from "vitest" + +import { dv } from "./date-fns-dv" + +describe("Dhivehi date-fns locale", () => { + it("labels flexible day periods by the half of the day they fall in", () => { + const at = (hour: number) => new Date(2026, 2, 12, hour, 0) + expect(format(at(0), "b", { locale: dv })).toBe("މކ") // midnight + expect(format(at(2), "B", { locale: dv })).toBe("މކ") // night + expect(format(at(9), "B", { locale: dv })).toBe("މކ") // morning + expect(format(at(12), "b", { locale: dv })).toBe("މފ") // noon + expect(format(at(14), "B", { locale: dv })).toBe("މފ") // afternoon + expect(format(at(19), "BBBB", { locale: dv })).toBe("މެންދުރުފަހު") // evening + expect(format(at(9), "a", { locale: dv })).toBe("މކ") + expect(format(at(21), "a", { locale: dv })).toBe("މފ") + }) + + it("parses full, short and narrow weekday names", () => { + const ref = new Date(2026, 2, 12) + const day = (text: string, pattern: string) => parse(text, pattern, ref, { locale: dv }).getDay() + expect(day("އާދިއްތަ", "EEEE")).toBe(0) + expect(day("އާދި", "EEE")).toBe(0) + expect(day("އަން", "EEE")).toBe(2) + expect(day("ބުރާ", "EEE")).toBe(4) + expect(day("ބު", "EEEEE")).toBe(3) + expect(day("ބުރ", "EEEEE")).toBe(4) + for (const pattern of ["EEEE", "EEE", "EEEEE"]) { + for (let d = 0; d < 7; d++) { + const date = new Date(2026, 2, 8 + d) + expect(day(format(date, pattern, { locale: dv }), pattern)).toBe(d) + } + } + }) +}) diff --git a/packages/onu/src/locales/date-fns-dv.ts b/packages/onu/src/locales/date-fns-dv.ts index 257f8f4c0..15940b980 100644 --- a/packages/onu/src/locales/date-fns-dv.ts +++ b/packages/onu/src/locales/date-fns-dv.ts @@ -109,6 +109,20 @@ function matcher(values: readonly string[]): MatchFn { } } +// date-fns day periods before noon ("night" is 00:00–03:59 for the `B` token). +const AM_PERIODS = new Set(["am", "midnight", "night", "morning"]) + +// Weekday names of every width, longest first so "ބުރާސްފަތި" is not read as "ބު". +const dayNames = [days, shortDays, narrowDays] + .flatMap((names) => names.map((name, value) => ({ name, value }))) + .sort((a, b) => b.name.length - a.name.length) + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const dayMatcher: MatchFn = (str: string) => { + const hit = dayNames.find((d) => str.startsWith(d.name)) + return hit ? { value: hit.value, rest: str.slice(hit.name.length) } : null +} + export const dv: Locale = { code: "dv", formatDistance: (token, count, options) => { @@ -139,7 +153,7 @@ export const dv: Locale = { dayPeriod: (period, options) => { const am = options?.width === "wide" ? "މެންދުރުކުރިން" : "މކ" const pm = options?.width === "wide" ? "މެންދުރުފަހު" : "މފ" - return String(period).startsWith("a") || period === "morning" ? am : pm + return AM_PERIODS.has(String(period)) ? am : pm }, }, match: { @@ -153,7 +167,7 @@ export const dv: Locale = { return m ? { value: Number(m[1]) as 1 | 2 | 3 | 4, rest: str.slice(m[0].length) } : null }, month: matcher(months), - day: matcher(days), + day: dayMatcher, dayPeriod: (str) => { if (str.startsWith("މކ") || str.startsWith("މެންދުރުކުރިން")) return { value: "am", rest: str.slice(str.startsWith("މކ") ? 2 : 14) } diff --git a/packages/onu/src/locales/dv/listing.ts b/packages/onu/src/locales/dv/listing.ts index 82e1c8db7..00862fb6c 100644 --- a/packages/onu/src/locales/dv/listing.ts +++ b/packages/onu/src/locales/dv/listing.ts @@ -36,6 +36,7 @@ export const listing = { actionsFor: "{name} އާ ގުޅޭ ކަންކަން", deleteRecordTitle: "{name} ފޮހެލަންތަ؟", deleteRecordDescription: "މިކަން އަނބުރާ ބަދަލެއް ނުކުރެވޭނެ.", + actionRecordTitle: "{name} {action}؟", restore: "އަނބުރާ ގެންނާ", deletePermanently: "ދާއިމީގޮތުން ނައްތާލުން", deletePermanentlyTitle: "{name} ދާއިމީގޮތުން ފޮހެލަންތަ؟", diff --git a/packages/onu/src/locales/en/listing.ts b/packages/onu/src/locales/en/listing.ts index 21aaf922d..c0394ba65 100644 --- a/packages/onu/src/locales/en/listing.ts +++ b/packages/onu/src/locales/en/listing.ts @@ -41,6 +41,7 @@ export const listing = { actionsFor: "Actions for {name}", deleteRecordTitle: "Delete {name}?", deleteRecordDescription: "This can't be undone.", + actionRecordTitle: "{action} {name}?", restore: "Restore", deletePermanently: "Delete permanently", deletePermanentlyTitle: "Permanently delete {name}?", diff --git a/packages/onu/src/maps/_place-search.tsx b/packages/onu/src/maps/_place-search.tsx index 48247366e..faa01a799 100644 --- a/packages/onu/src/maps/_place-search.tsx +++ b/packages/onu/src/maps/_place-search.tsx @@ -87,8 +87,7 @@ export function PlaceSearchBox({ "aria-label": ariaLabel, }: PlaceSearchBoxProps) { const { t } = useTranslation() - const inputRef = React.useRef(null) - const { fieldProps } = useThaanaField(inputRef, thaana) + const { ref: inputRef, fieldProps } = useThaanaField(thaana) const { query, setQuery, results, status, reset, retry } = usePlaceSearchBox({ search, minChars, debounce }) const [open, setOpen] = React.useState(false) const [active, setActive] = React.useState(-1) diff --git a/packages/onu/src/providers/onu-provider.loading.test.tsx b/packages/onu/src/providers/onu-provider.loading.test.tsx index 45de36ddc..2ca0198aa 100644 --- a/packages/onu/src/providers/onu-provider.loading.test.tsx +++ b/packages/onu/src/providers/onu-provider.loading.test.tsx @@ -1,6 +1,6 @@ import { render, screen, waitFor } from "@testing-library/react" import { SearchIcon } from "lucide-react" -import { beforeEach, describe, expect, it, vi } from "vitest" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import type * as ProviderModule from "./onu-provider" import type * as IconModule from "../icons/icon" @@ -53,6 +53,63 @@ describe("OnuProvider locales", () => { expect(document.body.textContent).toMatch(/[ހ-޿]/) }) + describe("when the Dhivehi chunk fails to load", () => { + const network = { offline: true, attempts: 0 } + + beforeEach(() => { + network.offline = true + network.attempts = 0 + vi.useFakeTimers({ shouldAdvanceTime: true }) + vi.doMock("../locales/dv/dv", async (importOriginal) => { + const actual = await importOriginal() + return { + get dv() { + network.attempts++ + if (network.offline) throw new Error("Failed to fetch dynamically imported module") + return actual.dv + }, + } + }) + }) + + afterEach(() => { + vi.doUnmock("../locales/dv/dv") + vi.useRealTimers() + }) + + async function renderDv() { + const mod = await load() + const Text = textOf(mod) + await import("../components/form/label") + render( + + + , + ) + await waitFor(() => expect(network.attempts).toBeGreaterThan(0)) + } + + it("retries after a delay", async () => { + await renderDv() + network.offline = false + await vi.advanceTimersByTimeAsync(1000) + await waitFor(() => expect(screen.queryByText("(optional)")).not.toBeInTheDocument()) + expect(document.body.textContent).toMatch(/[ހ-޿]/) + }) + + it("gives up after a few retries, then tries again when the browser comes back online", async () => { + await renderDv() + for (let i = 0; i < 4; i++) await vi.advanceTimersByTimeAsync(15_000) + const attempts = network.attempts + network.offline = false + await vi.advanceTimersByTimeAsync(60_000) + expect(network.attempts).toBe(attempts) + expect(screen.getByText("(optional)")).toBeInTheDocument() + window.dispatchEvent(new Event("online")) + await waitFor(() => expect(screen.queryByText("(optional)")).not.toBeInTheDocument()) + }) + }) + it("uses a locale object right away", async () => { const mod = await load() const Text = textOf(mod) diff --git a/packages/onu/src/providers/onu-provider.tsx b/packages/onu/src/providers/onu-provider.tsx index 3dd521e56..0266ea07c 100644 --- a/packages/onu/src/providers/onu-provider.tsx +++ b/packages/onu/src/providers/onu-provider.tsx @@ -89,6 +89,9 @@ const localeLoaders: Record, () => Promise import("../locales/dv/dv").then((m) => m.dv), } +/** Delays before retrying a failed locale load, in ms. */ +const LOCALE_RETRY_DELAYS = [1000, 3000, 10000] + /** * Resolves `OnuProvider locale`. Built-in codes other than English load their text * on demand; until it arrives, the code and direction are already right and strings @@ -103,12 +106,29 @@ function useResolvedLocale(prop: OnuLocale | BuiltInLocaleCode): OnuLocale { const load = code && code !== "en" ? localeLoaders[code] : undefined if (!code || !load || loadedLocales.has(code)) return let live = true - void load().then((locale) => { - loadedLocales.set(code, locale) - if (live) rerender() - }) + let timer: ReturnType | undefined + // A failed chunk load (flaky network, a deploy that replaced the chunk) is retried + // with a growing delay, then again whenever the browser comes back online. + const attempt = (retry: number) => { + load().then( + (locale) => { + loadedLocales.set(code, locale) + if (live) rerender() + }, + () => { + if (!live) return + if (retry < LOCALE_RETRY_DELAYS.length) + timer = setTimeout(() => attempt(retry + 1), LOCALE_RETRY_DELAYS[retry]) + else window.addEventListener("online", onOnline, { once: true }) + }, + ) + } + const onOnline = () => attempt(0) + attempt(0) return () => { live = false + clearTimeout(timer) + window.removeEventListener("online", onOnline) } }, [code]) diff --git a/packages/onu/src/thaana/attach.ts b/packages/onu/src/thaana/attach.ts index 9e57e2fdd..400b716dd 100644 --- a/packages/onu/src/thaana/attach.ts +++ b/packages/onu/src/thaana/attach.ts @@ -23,7 +23,12 @@ export interface ThaanaKeyboardOptions { * Default: Alt+Shift+T. Matched on `event.code`, so it works on any layout. */ toggleShortcut?: false | ThaanaShortcut - /** Called when the shortcut toggles the mode. */ + /** + * Called with the requested state when the shortcut is pressed. When given, + * the keyboard does not flip itself: call `setEnabled` to apply the change, + * so a controlled owner stays the source of truth. Without it, the shortcut + * flips the mode directly. + */ onToggle?: (enabled: boolean) => void } @@ -159,8 +164,8 @@ export function attachThaanaKeyboard(el: ThaanaTarget, options: ThaanaKeyboardOp return } event.preventDefault() - enabled = !enabled - options.onToggle?.(enabled) + if (options.onToggle) options.onToggle(!enabled) + else enabled = !enabled } el.addEventListener("beforeinput", onBeforeInput as EventListener) diff --git a/packages/onu/src/thaana/convert.ts b/packages/onu/src/thaana/convert.ts index 8f3d5d527..428c2d425 100644 --- a/packages/onu/src/thaana/convert.ts +++ b/packages/onu/src/thaana/convert.ts @@ -25,7 +25,7 @@ export function containsThaana(text: string): boolean { return THAANA.test(text) } -/** True when every character could have come from a Latin keyboard (printable ASCII). */ +/** True when every character could have come from a Latin keyboard (printable ASCII, tabs and line breaks). */ export function isLatinKeyboardText(text: string): boolean { - return /^[\x20-\x7E]*$/.test(text) + return /^[\t\n\r\x20-\x7E]*$/.test(text) } diff --git a/packages/onu/src/thaana/thaana.test.tsx b/packages/onu/src/thaana/thaana.test.tsx index 94668cf67..370b2c1d2 100644 --- a/packages/onu/src/thaana/thaana.test.tsx +++ b/packages/onu/src/thaana/thaana.test.tsx @@ -68,6 +68,7 @@ describe("keymaps", () => { expect(containsThaana("ދިވެހި")).toBe(true) expect(isLatinKeyboardText("Hello, world!")).toBe(true) expect(isLatinKeyboardText("ދ")).toBe(false) + expect(isLatinKeyboardText("line one\n\tline two\r\n")).toBe(true) }) }) @@ -129,6 +130,14 @@ describe("attachThaanaKeyboard", () => { expect(type(convert, "", { inputType: "insertFromPaste" }).defaultPrevented).toBe(false) }) + it("transliterates multi-line pastes into a textarea", () => { + const el = document.createElement("textarea") + document.body.appendChild(el) + attachThaanaKeyboard(el, { paste: "transliterate" }) + type(el, "salAm\n\tdhivehi", { inputType: "insertFromPaste" }) + expect(el.value).toBe("ސަލާމ\n\tދހިވެހި") + }) + it("converts words composed by predictive (Android) keyboards", () => { const el = input("x ") attachThaanaKeyboard(el) @@ -157,13 +166,23 @@ describe("attachThaanaKeyboard", () => { expect(el.value).toBe("ދިވެހި") }) - it("toggles with Alt+Shift+T, a custom shortcut, or not at all", () => { + it("leaves the change to onToggle when it is given", () => { const el = input() const onToggle = vi.fn() const kb = attachThaanaKeyboard(el, { onToggle }) fireEvent.keyDown(el, { code: "KeyT", altKey: true, shiftKey: true }) - expect(kb.isEnabled()).toBe(false) expect(onToggle).toHaveBeenLastCalledWith(false) + expect(kb.isEnabled()).toBe(true) + kb.setEnabled(false) + fireEvent.keyDown(el, { code: "KeyT", altKey: true, shiftKey: true }) + expect(onToggle).toHaveBeenLastCalledWith(true) + }) + + it("toggles with Alt+Shift+T, a custom shortcut, or not at all", () => { + const el = input() + const kb = attachThaanaKeyboard(el) + fireEvent.keyDown(el, { code: "KeyT", altKey: true, shiftKey: true }) + expect(kb.isEnabled()).toBe(false) fireEvent.keyDown(el, { code: "KeyT", altKey: true }) fireEvent.keyDown(el, { code: "KeyX", altKey: true, shiftKey: true }) expect(kb.isEnabled()).toBe(false) @@ -258,8 +277,7 @@ describe("insertText", () => { describe("useThaanaInput", () => { function Field(props: { enabled?: boolean; onEnabledChange?: (v: boolean) => void; defaultEnabled?: boolean }) { - const ref = React.useRef(null) - const { enabled, toggle } = useThaanaInput(ref, { + const { ref, enabled, toggle } = useThaanaInput({ ...props, toggleShortcut: { code: "KeyT", altKey: true, shiftKey: true }, }) @@ -296,12 +314,41 @@ describe("useThaanaInput", () => { rerender() expect(getByRole("button")).toHaveTextContent("on") }) + + it("keeps typing in step with a controlled value the parent does not change", () => { + const onEnabledChange = vi.fn() + const { getByLabelText, getByRole } = render() + const el = getByLabelText("field") as HTMLInputElement + fireEvent.keyDown(el, { code: "KeyT", altKey: true, shiftKey: true }) + expect(onEnabledChange).toHaveBeenCalledWith(false) + expect(getByRole("button")).toHaveTextContent("on") + type(el, "m") + expect(el.value).toBe("މ") + }) + + it("follows the element when it mounts later or is replaced", () => { + function Late({ show, swap }: { show: boolean; swap?: boolean }) { + const { ref } = useThaanaInput() + if (!show) return null + return swap ?