Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): return focus after the contact dialog closes

Yudhi Armyndharis64ec40d78faf
diff --git a/dashboard/src/components/Modal.tsx b/dashboard/src/components/Modal.tsx
index aa9e2a7aa..08de05980 100644
--- a/dashboard/src/components/Modal.tsx
+++ b/dashboard/src/components/Modal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useId, useRef, type ReactNode } from 'react';
+import { useEffect, useId, useRef, type ReactNode, type RefObject } from 'react';
import { X } from 'lucide-react';
import { bindModalA11y } from '../utils/modalA11y.ts';
@@ -22,6 +22,8 @@ export interface ModalProps {
subheader?: ReactNode;
/** Hide the header close button — for dialogs that must not be dismissed mid-operation. */
hideCloseButton?: boolean;
+ /** The element focus starts on, usually the first field; the first focusable when omitted or empty. */
+ initialFocusRef?: RefObject<HTMLElement | null>;
}
/**
@@ -45,11 +47,13 @@ export function Modal({
headerExtra,
subheader,
hideCloseButton = false,
+ initialFocusRef,
}: ModalProps) {
const titleId = useId();
const cardRef = useRef<HTMLDivElement>(null);
- // Keep the latest onClose in a ref so the open/close effect below can depend on `[open]` only.
+ // Keep the latest onClose in a ref so the open/close effect below can depend on `[open]` (and the stable
+ // initial-focus ref object) only.
// Callers commonly pass an inline arrow (`onClose={() => setShow(false)}`), which is a fresh
// reference on every parent render. If `onClose` were a useEffect dependency, the effect would
// re-run on every keystroke that re-renders the parent — and because that effect performs the
@@ -63,8 +67,13 @@ export function Modal({
useEffect(() => {
if (!open || !cardRef.current) return undefined;
- return bindModalA11y(document, cardRef.current, () => onCloseRef.current());
- }, [open]);
+ return bindModalA11y(
+ document,
+ cardRef.current,
+ () => onCloseRef.current(),
+ () => initialFocusRef?.current ?? null,
+ );
+ }, [open, initialFocusRef]);
if (!open) return null;
diff --git a/dashboard/src/components/chats/ChatDialogs.tsx b/dashboard/src/components/chats/ChatDialogs.tsx
index 1084edab5..0054e9b0c 100644
--- a/dashboard/src/components/chats/ChatDialogs.tsx
+++ b/dashboard/src/components/chats/ChatDialogs.tsx
@@ -1,4 +1,4 @@
-import { useId, useState } from 'react';
+import { useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Loader2 } from 'lucide-react';
import { Modal } from '../Modal';
@@ -89,6 +89,9 @@ export function SaveContactDialog({
const canSave = firstName.trim().length > 0 && !busy;
// The footer's Save button belongs to the form through this id, so Enter in a name field presses it.
const formId = useId();
+ // The dialog opens on the first name, so typing and Enter work at once; the modal focuses it after it has
+ // recorded the opener (autoFocus would have it recorded as the opener instead).
+ const firstRef = useRef<HTMLInputElement | null>(null);
return (
<Modal
open
@@ -96,6 +99,7 @@ export function SaveContactDialog({
title={saved ? t('chats.rowActions.renameContact') : t('chats.rowActions.saveContact')}
className="confirm-modal"
closeLabel={t('common.close')}
+ initialFocusRef={firstRef}
footer={
<>
<button className="btn-secondary" onClick={onClose} disabled={busy}>
@@ -118,11 +122,11 @@ export function SaveContactDialog({
<label>
<span>{t('chats.rowActions.firstName')}</span>
<input
+ ref={firstRef}
type="text"
value={firstName}
maxLength={NAME_MAX_LENGTH}
onChange={e => setFirstName(e.target.value)}
- autoFocus
/>
</label>
<label>
diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.ts
index de1834750..96df9b88a 100644
--- a/dashboard/src/pages/Chats.features.test.ts
+++ b/dashboard/src/pages/Chats.features.test.ts
@@ -1098,6 +1098,50 @@ test("dismissing a dialog a row's menu opened returns focus to the row's menu bu
assert.equal(focusedName(), 'Actions for Alice', 'focus fell to the page');
});
+test("the contact dialog opens on its first name field, and closing it returns focus to the row's menu button", async () => {
+ const { screen, fireEvent, waitFor, within } = rtl;
+ renderPage();
+ await screen.findByText('Alice');
+ const trigger = screen.getByRole('button', { name: 'Actions for Alice' });
+ trigger.focus();
+ fireEvent.click(trigger);
+ const item = await screen.findByRole('button', { name: 'Rename contact' });
+ item.focus();
+ fireEvent.click(item);
+ const dialog = await screen.findByRole('dialog');
+ const first = within(dialog).getByLabelText('First name');
+ assert.equal(document.activeElement === first, true, `focus is on "${focusedName()}", not on the first name field`);
+
+ fireEvent.keyDown(document, { key: 'Escape' });
+ await waitFor(() => assert.ok(!screen.queryByRole('dialog')));
+ assert.equal(focusedName(), 'Actions for Alice', 'focus fell to the page');
+});
+
+test('the contact dialog opened from the room menu returns focus to the room menu button', async () => {
+ const { screen, fireEvent, waitFor, within } = rtl;
+ const { container } = renderPage();
+ fireEvent.click(await screen.findByText('Alice'));
+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the room did not open'));
+ const trigger = container.querySelector('.room-menu-trigger') as HTMLButtonElement;
+ trigger.focus();
+ fireEvent.click(trigger);
+ const item = await within(container.querySelector('.room-menu-popover') as HTMLElement).findByRole('button', {
+ name: 'Rename contact',
+ });
+ item.focus();
+ fireEvent.click(item);
+ const dialog = await screen.findByRole('dialog');
+ assert.equal(
+ document.activeElement === within(dialog).getByLabelText('First name'),
+ true,
+ 'the dialog did not open on its first name field',
+ );
+
+ fireEvent.keyDown(document, { key: 'Escape' });
+ await waitFor(() => assert.ok(!screen.queryByRole('dialog')));
+ assert.equal(focusedName(), 'More actions', 'focus fell to the page after the contact dialog');
+});
+
test("dismissing a dialog the room's menu opened, or the menu itself, returns focus to its button", async () => {
const { screen, fireEvent, waitFor, within } = rtl;
const { container } = renderPage();
diff --git a/dashboard/src/utils/modalA11y.test.ts b/dashboard/src/utils/modalA11y.test.ts
index 90908f7e8..6f6902c89 100644
--- a/dashboard/src/utils/modalA11y.test.ts
+++ b/dashboard/src/utils/modalA11y.test.ts
@@ -100,6 +100,33 @@ test('moves initial focus to the first visible focusable in the dialog', () => {
unbind();
});
+test('moves initial focus to the element the dialog names, and records the opener before that', () => {
+ const { doc, card, focusables, makeElement } = makeWorld(3);
+ const opener = makeElement();
+ opener.focus();
+ const unbind = bindModalA11y(
+ doc as never,
+ card as never,
+ () => {},
+ () => focusables[2] as never,
+ );
+ assert.equal(doc.activeElement, focusables[2] as never);
+ unbind();
+ assert.equal(doc.activeElement, opener as never, 'focus did not return to the opener');
+});
+
+test('falls back to the first focusable when the named initial focus is not there', () => {
+ const { doc, card, focusables } = makeWorld(3);
+ const unbind = bindModalA11y(
+ doc as never,
+ card as never,
+ () => {},
+ () => null,
+ );
+ assert.equal(doc.activeElement, focusables[0] as never);
+ unbind();
+});
+
test('focuses the card itself when the dialog has nothing focusable', () => {
const { doc, card } = makeWorld(0);
const unbind = bindModalA11y(doc as never, card as never, () => {});
diff --git a/dashboard/src/utils/modalA11y.ts b/dashboard/src/utils/modalA11y.ts
index ce5184292..25ecc792e 100644
--- a/dashboard/src/utils/modalA11y.ts
+++ b/dashboard/src/utils/modalA11y.ts
@@ -27,9 +27,15 @@ function visibleFocusables(card: HTMLElement): HTMLElement[] {
/**
* Wires one open dialog: locks background scroll, moves focus into the dialog, traps Tab inside it,
* closes on Escape, and returns a cleanup that restores scroll and focus to the element that was
- * focused when the dialog opened (the trigger).
+ * focused when the dialog opened (the trigger). `initialFocus` names the element focus starts on,
+ * usually the first field; without one, or when it finds none, that is the first focusable.
*/
-export function bindModalA11y(doc: Document, card: HTMLElement, onClose: () => void): () => void {
+export function bindModalA11y(
+ doc: Document,
+ card: HTMLElement,
+ onClose: () => void,
+ initialFocus?: () => HTMLElement | null,
+): () => void {
if (modalStack.length === 0) lockedOverflow = doc.body.style.overflow;
doc.body.style.overflow = 'hidden';
@@ -69,8 +75,10 @@ export function bindModalA11y(doc: Document, card: HTMLElement, onClose: () => v
doc.addEventListener('keydown', onKeyDown, true);
- // Initial focus: the first visible focusable in the dialog, else the dialog card itself.
- (visibleFocusables(card)[0] ?? card).focus();
+ // Initial focus: the element the dialog names, else the first visible focusable in it, else the card itself.
+ // The opener was recorded above, so focus a field here and not with autoFocus: React focuses an autoFocus
+ // input during the commit, before this runs, and it would be recorded as the opener and lost on close.
+ (initialFocus?.() ?? visibleFocusables(card)[0] ?? card).focus();
return () => {
const stackIndex = modalStack.indexOf(stackEntry);