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/.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/.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/.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/.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/.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/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} 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} 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. 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() 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], ) 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