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/additional-files-upload-focus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

`AdditionalFilesUpload` now returns focus to the "Add files" picker after removing a new file at `maxFiles`, where it used to be lost because the picker was still disabled.
5 changes: 5 additions & 0 deletions .changeset/bulk-actions-form-focus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

`BulkActionBar` moves focus to the form control when an action's form opens, and back to the action when the form is cancelled, instead of dropping it to the page body.
5 changes: 5 additions & 0 deletions .changeset/editor-toolbar-tab-stop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

The editor toolbar keeps its tab stop when the control holding it is disabled (for example "Text style" with the caret in a code block): Tab and Alt+F10 now reach the first enabled control.
5 changes: 5 additions & 0 deletions .changeset/export-menu-focus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

`ExportMenu` keeps focus on its button while a file is being made: the button is now `aria-disabled` instead of `disabled` while exporting, and its menu won't open until the export finishes.
5 changes: 5 additions & 0 deletions .changeset/record-actions-menu-focus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

`RecordActionsMenu` now returns focus to the "More actions" button when a confirmation opened from its menu closes, instead of leaving it on the page body.
2 changes: 1 addition & 1 deletion docs/files-and-media/additional-files-upload.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Set `name` to also render native fields: `name[removed][]` (hidden ids), `name[a

- Each file's buttons are named with the file ("Remove Lease agreement.pdf", "Restore …").
- Marking a file for removal shows "Will be removed" as text (not only a strike-through), announces it, and moves focus to the Restore button.
- Removing a new file returns focus to the "Add files" picker.
- Removing a new file returns focus to the "Add files" picker, also when the picker was disabled at `maxFiles`.

| Key | Action |
| -------------------------------------------- | ------------------------------------------------------ |
Expand Down
2 changes: 1 addition & 1 deletion docs/listing-pages/bulk-actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ const actions: BulkAction<unknown>[] = [

## Accessibility

The bar is a region named "Bulk actions"; the count is a polite live region, so "3 selected" is announced. Confirmations are alert dialogs that return focus where they were opened. After success, focus moves to the result message so it isn't lost when the bar goes away; errors are `role="alert"`.
The bar is a region named "Bulk actions"; the count is a polite live region, so "3 selected" is announced. Confirmations are alert dialogs that return focus where they were opened. Opening an action's form moves focus to its control, and Cancel returns focus to the action. After success, focus moves to the result message so it isn't lost when the bar goes away; errors are `role="alert"`.
4 changes: 2 additions & 2 deletions docs/listing-pages/export-menu.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: ExportMenu
sidebar_position: 16
---

An **Export** button with a menu of formats (CSV, Excel, PDF). The menu does not build the file: your `onExport(format)` does, either by asking the server with the current filters or in the browser with [`exportRows`](export-rows) from `@javaabu/onu/export`. While the returned promise is pending the button shows a spinner and is disabled.
An **Export** button with a menu of formats (CSV, Excel, PDF). The menu does not build the file: your `onExport(format)` does, either by asking the server with the current filters or in the browser with [`exportRows`](export-rows) from `@javaabu/onu/export`. While the returned promise is pending the button shows a spinner and won't open the menu.

```tsx
import { ExportMenu } from "@javaabu/onu"
Expand Down Expand Up @@ -33,4 +33,4 @@ const exportRows = useExportRows()

## Accessibility

A menu button. "Exporting…" and "Export ready" are announced through a polite live region; the button has `aria-busy` while working.
A menu button. "Exporting…" and "Export ready" are announced through a polite live region; the button has `aria-busy` and `aria-disabled` while working. It uses `aria-disabled` rather than `disabled`, so focus returns to it when the menu closes.
2 changes: 1 addition & 1 deletion docs/rich-content/wysiwyg-editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Other `<div>` props go to the root, and `ref` points at the root. `editorVariant
## Accessibility

- The content area is a `role="textbox"` with `aria-multiline`. Inside a `FormField` it is labelled by the field label and described by help and error text; `aria-invalid`, `aria-required`, `aria-readonly` and `aria-disabled` are set.
- The toolbar follows the WAI-ARIA toolbar pattern: one tab stop, arrow keys move between controls (mirrored in RTL), toggles expose `aria-pressed`.
- The toolbar follows the WAI-ARIA toolbar pattern: one tab stop, arrow keys move between controls (mirrored in RTL), toggles expose `aria-pressed`. When the control holding the tab stop is disabled (for example "Text style" in a code block), the tab stop moves to the first enabled control.
- Link and image dialogs return focus to the button that opened them.
- Toolbar buttons are 44px on touch screens.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ describe("AdditionalFilesUpload", () => {
expect(screen.getByText("b.pdf was not added: only 2 files are allowed.")).toBeInTheDocument()
})

it("moves focus to the picker after removing a file at maxFiles", async () => {
const { container } = renderWithOnu(<AdditionalFilesUpload maxFiles={1} withName={false} withDescription={false} />)
await user().upload(picker(container), [file("a.pdf")])
expect(picker(container)).toBeDisabled()
await user().click(screen.getByRole("button", { name: "Remove a.pdf" }))
expect(picker(container)).toBeEnabled()
expect(picker(container)).toHaveFocus()
})

it("disables every action when disabled", () => {
renderWithOnu(<AdditionalFilesUpload existing={existing} disabled />)
expect(screen.getByRole("button", { name: "Remove Lease agreement.pdf" })).toBeDisabled()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { syncInputFiles } from "./file-utils"
import { registerEnglish } from "../../i18n/english"
import { file as en_file } from "../../locales/en/file"
import { useControllableState } from "../../hooks/use-controllable-state"
import { useFocusAfterRender } from "../../hooks/use-focus-after-render"

registerEnglish({ file: en_file })

Expand Down Expand Up @@ -104,6 +105,8 @@ export function AdditionalFilesUpload({
const { t } = useTranslation()
const [state, setState] = useControllableState<AdditionalFilesValue>(value, defaultValue ?? EMPTY, onValueChange)
const pickerRef = React.useRef<HTMLInputElement>(null)
// The picker may be disabled (at maxFiles) until the removal re-renders it.
const focusPicker = useFocusAfterRender(pickerRef)
const rootRef = React.useRef<HTMLDivElement>(null)
const [announcement, setAnnouncement] = React.useState("")
const kept = existing.filter((a) => !state.removed.includes(a.id)).length
Expand Down Expand Up @@ -143,7 +146,7 @@ export function AdditionalFilesUpload({
const removeAdded = (item: NewAttachment) => {
setState({ ...state, added: state.added.filter((a) => a.key !== item.key) })
setAnnouncement(t("file.removedFile", { name: item.file.name }))
pickerRef.current?.focus()
focusPicker()
}

return (
Expand Down
9 changes: 2 additions & 7 deletions packages/onu/src/components/files/file-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { cn } from "../../lib/utils"
import { useTranslation } from "../../providers/onu-provider"
import { Button, buttonVariants } from "../../ui/button"
import { useFormField, useFormFieldControl } from "../form/form-field"
import { useFocusAfterRender } from "../../hooks/use-focus-after-render"
import { useMergedRef } from "../../hooks/use-merged-ref"
import { FileRow } from "./_file-row"
import type { ExistingAttachment } from "./additional-files-upload"
Expand Down Expand Up @@ -227,7 +228,7 @@ export function FileInput<R = unknown>({
const [announcement, setAnnouncement] = React.useState("")
const [dragActive, setDragActive] = React.useState(false)
// Focus moves back to the input after a removal, once it has re-rendered (it may have been disabled).
const [focusRequest, setFocusRequest] = React.useState(0)
const refocus = useFocusAfterRender(local)
const options: FileValidationOptions = { accept, maxSize, minSize, maxFiles }
const message = useRejectionMessage(options)
const statusId = React.useId()
Expand Down Expand Up @@ -301,10 +302,6 @@ export function FileInput<R = unknown>({
syncInputFiles(local.current, uploads ? NO_FILES : entries.filter(isLocalFile))
}, [entries, uploads])

React.useEffect(() => {
if (focusRequest) local.current?.focus()
}, [focusRequest])

function setEntries(next: FileInputEntry<R>[]) {
entriesRef.current = next
setEntriesState(next)
Expand Down Expand Up @@ -382,8 +379,6 @@ export function FileInput<R = unknown>({
if (!blocked) setDragActive(true)
}

const refocus = () => setFocusRequest((n) => n + 1)

const removeEntry = (entry: FileInputEntry<R>) => {
setEntries(entriesRef.current.filter((e) => e !== entry))
setRejections([])
Expand Down
21 changes: 21 additions & 0 deletions packages/onu/src/components/listing/bulk-actions.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,27 @@ describe("BulkActionBar", () => {
expect(run).not.toHaveBeenCalled()
})

it("moves focus into an input form when it opens and back to its action when cancelled", async () => {
const user = userEvent.setup()
renderWithOnu(
<Bar
actions={[
{ id: "a", label: "Archive", run: vi.fn() },
{ id: "s", label: "Change status", form: ({ id }) => <input id={id} />, run: vi.fn() },
]}
/>,
)
const action = screen.getByRole("button", { name: "Change status" })
action.focus()
await user.keyboard("{Enter}")
expect(screen.getByRole("textbox", { name: "Change status" })).toHaveFocus()
await user.tab()
await user.tab()
expect(screen.getByRole("button", { name: "Cancel" })).toHaveFocus()
await user.keyboard("{Enter}")
expect(screen.getByRole("button", { name: "Change status" })).toHaveFocus()
})

it.each(directions)("works in %s with Dhivehi strings", async (dir) => {
renderWithOnu(<Bar actions={[{ id: "delete", label: "ފޮހެލާ", destructive: true, run: vi.fn() }]} />, {
locale: "dv",
Expand Down
36 changes: 33 additions & 3 deletions packages/onu/src/components/listing/bulk-actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ export function BulkActionBar({
const [confirming, setConfirming] = React.useState<{ action: BulkAction<unknown>; value: unknown } | null>(null)
const [message, setMessage] = React.useState<{ text: string; tone: "success" | "error" } | null>(null)
const messageRef = React.useRef<HTMLDivElement>(null)
const formRef = React.useRef<HTMLFormElement>(null)
const actionRefs = React.useRef(new Map<string, HTMLButtonElement>())
// Opening or cancelling a form swaps the buttons out of the bar: once it has re-rendered, move
// focus into the form or back to the action, so it doesn't drop to the page.
const focusAfterRender = React.useRef<(() => void) | null>(null)
React.useEffect(() => {
const focus = focusAfterRender.current
focusAfterRender.current = null
focus?.()
})
// The bar goes away with the selection: keep keyboard focus on the result instead of losing it.
React.useEffect(() => {
if (message && (selected.length === 0 || message.tone === "error")) messageRef.current?.focus()
Expand Down Expand Up @@ -142,8 +152,23 @@ export function BulkActionBar({
}

const choose = (action: BulkAction<unknown>) => {
if (action.form) setPhase({ kind: "form", action, value: action.defaultValue })
else proceed(action, undefined)
if (!action.form) {
proceed(action, undefined)
return
}
setPhase({ kind: "form", action, value: action.defaultValue })
focusAfterRender.current = () => {
const form = formRef.current
const control =
form?.querySelector<HTMLElement>(`[id="${CSS.escape(formId)}"]`) ??
form?.querySelector<HTMLElement>("input, select, textarea, button")
control?.focus()
}
}

const cancelForm = (action: BulkAction<unknown>) => {
setPhase({ kind: "idle" })
focusAfterRender.current = () => actionRefs.current.get(action.id)?.focus()
}

const confirmOptions = (action: BulkAction<unknown>): ConfirmOptions => {
Expand Down Expand Up @@ -216,6 +241,7 @@ export function BulkActionBar({

{phase.kind === "form" ? (
<form
ref={formRef}
className={cn("gap-2 flex flex-wrap items-center", classNames?.form)}
data-slot="bulk-action-form"
onSubmit={(e) => {
Expand All @@ -239,7 +265,7 @@ export function BulkActionBar({
size="sm"
variant="ghost"
className="touch:min-h-11"
onClick={() => setPhase({ kind: "idle" })}
onClick={() => cancelForm(phase.action)}
>
{t("listing.cancel")}
</Button>
Expand All @@ -249,6 +275,10 @@ export function BulkActionBar({
{visible.map((action) => (
<Button
key={action.id}
ref={(el) => {
if (el) actionRefs.current.set(action.id, el)
else actionRefs.current.delete(action.id)
}}
size="sm"
variant={action.destructive ? "destructive" : "outline"}
disabled={running}
Expand Down
10 changes: 7 additions & 3 deletions packages/onu/src/components/listing/export-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export function ExportMenu({
const { t } = useTranslation()
const [busy, setBusy] = React.useState<ExportFormat | null>(null)
const [status, setStatus] = React.useState("")
const [open, setOpen] = React.useState(false)

const items: ExportOption[] = options.map((o) => (typeof o === "string" ? { format: o } : o))
const labelOf = (o: ExportOption) => o.label ?? (LABEL_KEYS[o.format] ? t(LABEL_KEYS[o.format] as string) : o.format)
Expand All @@ -85,14 +86,17 @@ export function ExportMenu({

return (
<>
<DropdownMenu>
{/* The menu doesn't open while a file is being made. */}
<DropdownMenu open={open} onOpenChange={(next) => setOpen(next && busy === null)}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
data-part="export-menu"
disabled={disabled || busy !== null}
disabled={disabled}
// aria-disabled rather than disabled while exporting, so focus can return to the button as the menu closes.
aria-disabled={busy !== null || undefined}
aria-busy={busy !== null || undefined}
className={cn("touch:min-h-11", classNames?.trigger, className)}
className={cn("touch:min-h-11 aria-disabled:opacity-50", classNames?.trigger, className)}
{...props}
>
{busy ? <Spinner /> : <Icon name="download" />}
Expand Down
14 changes: 13 additions & 1 deletion packages/onu/src/components/listing/record-actions-menu.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { screen, within } from "@testing-library/react"
import { screen, waitFor, within } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { afterEach, describe, expect, it, vi } from "vitest"

Expand Down Expand Up @@ -40,6 +40,18 @@ describe("RecordActionsMenu", () => {
expect(await screen.findByRole("alertdialog", { name: "Delete Jane Doe?" })).toBeInTheDocument()
})

it("returns focus to the More actions button when a confirmation from the menu closes", async () => {
setMobile(false)
renderWithOnu(<RecordActionsMenu name="Jane Doe" actions={actions} />)
const trigger = screen.getByRole("button", { name: "More actions" })
await userEvent.click(trigger)
await userEvent.click(await screen.findByRole("menuitem", { name: "Delete" }))
await screen.findByRole("alertdialog", { name: "Delete Jane Doe?" })
await userEvent.click(screen.getByRole("button", { name: "Cancel" }))
await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument())
expect(trigger).toHaveFocus()
})

it("asks before a risky button action", async () => {
setMobile(false)
renderWithOnu(<RecordActionsMenu name="Jane Doe" maxVisible={3} actions={actions} size="sm" />)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export function RecordActionsMenu({
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
ref={triggerRef}
variant="outline"
size={size === "sm" ? "icon-sm" : "icon"}
aria-label={t("listing.moreActions")}
Expand Down
23 changes: 22 additions & 1 deletion packages/onu/src/components/listing/toolbar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,34 @@ describe("ExportMenu", () => {
await userEvent.click(within(menu).getByRole("menuitem", { name: "Excel" }))
expect(onExport).toHaveBeenCalledWith("excel")
const button = screen.getByRole("button", { name: "Exporting…" })
expect(button).toBeDisabled()
expect(button).toHaveAttribute("aria-disabled", "true")
expect(button).toHaveAttribute("aria-busy", "true")
await act(async () => deferred.resolve())
expect(screen.getByRole("button", { name: "Export" })).toBeEnabled()
expect(screen.getByText("Export ready")).toBeInTheDocument()
})

it("keeps focus on the trigger while exporting, and doesn't reopen until done", async () => {
const deferred = Deferred()
const user = userEvent.setup()
renderWithOnu(<ExportMenu onExport={() => deferred.promise} />)
const trigger = screen.getByRole("button", { name: "Export" })
trigger.focus()
await user.keyboard("{Enter}")
await screen.findByRole("menu")
await user.keyboard("{Enter}")
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument())
expect(trigger).toHaveAccessibleName("Exporting…")
expect(trigger).toHaveFocus()
expect(trigger).toHaveAttribute("aria-disabled", "true")
await user.keyboard("{Enter}")
await user.click(trigger)
expect(screen.queryByRole("menu")).not.toBeInTheDocument()
await act(async () => deferred.resolve())
expect(trigger).not.toHaveAttribute("aria-disabled")
expect(trigger).toHaveFocus()
})

it("accepts custom options and reports failures", async () => {
const onExport = vi.fn(() => Promise.reject(new Error("x")))
renderWithOnu(
Expand Down
Loading
Loading