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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/editor-keeps-content-on-rebuild.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/form-ref-cleanup.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/listing-state-stable-on-value-change.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/merged-ref-cleanup.md
Original file line number Diff line number Diff line change
@@ -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`.
5 changes: 5 additions & 0 deletions .changeset/signature-pad-keeps-drawing.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/validation-summary-ref-cleanup.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions packages/onu/src/components/form/form.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<Form ref={ref} />)
rerender(<Form ref={ref} className="x" />)
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", () => {
Expand Down
8 changes: 3 additions & 5 deletions packages/onu/src/components/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -127,6 +128,7 @@ export function Form<T extends FieldValues = FormValues>({
}: FormProps<T>) {
const { t } = useTranslation()
const formRef = React.useRef<HTMLFormElement>(null)
const mergedRef = useMergedRef(formRef, ref)
const busy = React.useRef(false)
const pendingFocus = React.useRef(false)
const [submitting, setSubmitting] = React.useState(false)
Expand Down Expand Up @@ -250,11 +252,7 @@ export function Form<T extends FieldValues = FormValues>({
<FormErrorsProvider errors={errors}>
<ClearFieldErrorProvider value={clearFieldError}>
<form
ref={(node) => {
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}
Expand Down
16 changes: 15 additions & 1 deletion packages/onu/src/components/form/validation-summary.test.tsx
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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(<ValidationSummary errors={payload} ref={ref} />)
rerender(<ValidationSummary errors={payload} ref={ref} className="x" />)
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: "ނަން ލިޔުއްވާ" }))
Expand Down
8 changes: 3 additions & 5 deletions packages/onu/src/components/form/validation-summary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -47,6 +48,7 @@ export function ValidationSummary({
}: ValidationSummaryProps) {
const { t } = useTranslation()
const local = React.useRef<HTMLDivElement>(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))
Expand All @@ -73,11 +75,7 @@ export function ValidationSummary({

return (
<div
ref={(node) => {
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}
Expand Down
20 changes: 20 additions & 0 deletions packages/onu/src/components/listing/use-listing-state.test.tsx
Original file line number Diff line number Diff line change
@@ -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"

Expand Down Expand Up @@ -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")
Expand Down
22 changes: 15 additions & 7 deletions packages/onu/src/components/listing/use-listing-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ListingParamNames> }),
[paramPrefix, paramNamesKey],
)

const defaults = React.useMemo<ListingState>(
() => ({ ...BASE_STATE, ...options.defaultState, filters: cleanFilters(options.defaultState?.filters ?? {}) }),
Expand All @@ -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<ListingState>(
() => ({ search, sort, page, perPage, filters, view }),
Expand All @@ -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.
Expand Down
30 changes: 24 additions & 6 deletions packages/onu/src/editor/_use-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<EditorValue>(initial)
// ARIA attributes for the contenteditable; ProseMirror reads them on every update.
const attributes = React.useRef<Record<string, string>>({})

Expand All @@ -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",
Expand Down Expand Up @@ -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)
},
Expand Down Expand Up @@ -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,
Expand Down
41 changes: 40 additions & 1 deletion packages/onu/src/editor/wysiwyg-editor.test.tsx
Original file line number Diff line number Diff line change
@@ -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"

Expand All @@ -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"

Expand Down Expand Up @@ -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) => (
<WysiwygEditor
aria-label="Story"
name="body"
defaultValue="<p>Hello</p>"
thaana={thaana}
onReady={(e) => editors.push(e)}
/>
)
const { rerender, container } = renderWithOnu(ui(false))
await waitFor(() => expect(editors).toHaveLength(1))
act(() => {
editors[0]!.commands.setContent("<p>Typed text</p>", { emitUpdate: true })
})
const hidden = container.querySelector<HTMLInputElement>("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"]) => (
<OnuProvider locale={locale}>
<WysiwygEditor aria-label="Story" />
</OnuProvider>
)
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(<WysiwygEditor thaana />, { locale: "dv" })
expect(await screen.findByRole("textbox", { name: "ލިޔުން އެޑިޓަރު" })).toBeInTheDocument()
Expand Down
22 changes: 22 additions & 0 deletions packages/onu/src/hooks/use-merged-ref.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLDivElement>()
const { container, unmount } = render(<Probe a={callback} b={object} />)
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(<Probe a={plain} b={() => cleanup} />)
unmount()
expect(plain).toHaveBeenLastCalledWith(null)
expect(cleanup).toHaveBeenCalledTimes(1)
})
})
Loading
Loading