Skip to content
Open
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
3 changes: 3 additions & 0 deletions packages/wallet-sdk/src/ui/Dialog/Dialog.scss
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,9 @@
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
border: none;
background-color: transparent;
cursor: pointer;
border-radius: 6px;
transition: background-color 0.2s;
Expand Down
102 changes: 100 additions & 2 deletions packages/wallet-sdk/src/ui/Dialog/Dialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import { sessionFromSolanaAccounts } from ':core/namespaces/solana/session.js';
import { getDisplayableUsername } from ':core/username/getDisplayableUsername.js';
import type { Session } from ':core/session/types.js';

import { DialogContainer, DialogInstance, DialogInstanceProps } from './Dialog.js';
import {
DialogActionItem,
DialogContainer,
DialogInstance,
DialogInstanceProps,
} from './Dialog.js';

const { sessionRef } = vi.hoisted(() => ({
sessionRef: { current: undefined as Session | undefined },
Expand Down Expand Up @@ -61,7 +66,8 @@ describe('DialogContainer', () => {
expect(hiddenClass.length).toEqual(1);

vi.runAllTimers();
expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
// Focusing the dialog also queues jsdom's own selectionchange timer, so match the reveal.
expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 1);
setTimeoutSpy.mockRestore();
});

Expand Down Expand Up @@ -163,3 +169,95 @@ describe('DialogInstance session header', () => {
expect(getDisplayableUsername).not.toHaveBeenCalled();
});
});

describe('DialogInstance accessibility', () => {
const actionItems: DialogActionItem[] = [
{ text: 'Try again', onClick: () => {}, variant: 'primary' },
{ text: 'Cancel', onClick: () => {}, variant: 'secondary' },
];

test('exposes a modal dialog named by its title and described by its message', () => {
renderDialogContainer();

const dialog = screen.getByRole('dialog', { name: 'Test Title' });
expect(dialog).toHaveAttribute('aria-modal', 'true');
expect(dialog).toHaveAccessibleDescription('Test message');
});

test('renders the close control as a labelled button', () => {
const handleClose = vi.fn();
renderDialogContainer({ handleClose });

fireEvent.click(screen.getByRole('button', { name: 'Close' }));

expect(handleClose).toHaveBeenCalledTimes(1);
});

test('closes on Escape', () => {
const handleClose = vi.fn();
renderDialogContainer({ handleClose });

fireEvent.keyDown(document, { key: 'Escape' });

expect(handleClose).toHaveBeenCalledTimes(1);
});

test('ignores an Escape the page has already handled', () => {
const handleClose = vi.fn();
const preventEscape = (event: KeyboardEvent) => event.preventDefault();
document.addEventListener('keydown', preventEscape);
renderDialogContainer({ handleClose });

fireEvent.keyDown(document, { key: 'Escape' });

expect(handleClose).not.toHaveBeenCalled();
document.removeEventListener('keydown', preventEscape);
});

test('focuses the first action when the dialog opens', () => {
renderDialogContainer({ actionItems });

expect(screen.getByRole('button', { name: 'Try again' })).toHaveFocus();
});

test('focuses the close button when the dialog has no actions', () => {
renderDialogContainer();

expect(screen.getByRole('button', { name: 'Close' })).toHaveFocus();
});

test('keeps Tab focus inside the dialog', () => {
renderDialogContainer({ actionItems });
const close = screen.getByRole('button', { name: 'Close' });
const cancel = screen.getByRole('button', { name: 'Cancel' });

cancel.focus();
fireEvent.keyDown(document, { key: 'Tab' });
expect(close).toHaveFocus();

fireEvent.keyDown(document, { key: 'Tab', shiftKey: true });
expect(cancel).toHaveFocus();
});

test('moves Tab focus back into the dialog when it has left', () => {
renderDialogContainer({ actionItems });
(document.activeElement as HTMLElement).blur();

fireEvent.keyDown(document, { key: 'Tab' });

expect(screen.getByRole('button', { name: 'Close' })).toHaveFocus();
});

test('restores focus to the previously focused element when closed', () => {
const trigger = document.createElement('button');
document.body.appendChild(trigger);
trigger.focus();

const { unmount } = renderDialogContainer({ actionItems });
expect(trigger).not.toHaveFocus();

unmount();
expect(trigger).toHaveFocus();
trigger.remove();
});
});
86 changes: 80 additions & 6 deletions packages/wallet-sdk/src/ui/Dialog/Dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { projectEthAccounts } from ':core/namespaces/eip155/session.js';
import { getDisplayableUsername } from ':core/username/getDisplayableUsername.js';
import { store } from ':store/store.js';
import { BaseLogo } from ':ui/assets/BaseLogo.js';
import { useEffect, useMemo, useState } from 'preact/hooks';
import { useEffect, useId, useMemo, useRef, useState } from 'preact/hooks';
import css from './Dialog-css.js';

const closeIcon = `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTQiIGhlaWdodD0iMTQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEzIDFMMSAxM20wLTEyTDEzIDEzIiBzdHJva2U9IiM5Q0EzQUYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PC9zdmc+`;
Expand Down Expand Up @@ -198,6 +198,61 @@ export const DialogInstance: FunctionComponent<DialogInstanceProps> = ({
const [hidden, setHidden] = useState(true);
const [isLoadingUsername, setIsLoadingUsername] = useState(true);
const [username, setUsername] = useState<string | null>(null);
const instanceRef = useRef<HTMLDivElement>(null);
const handleCloseRef = useRef(handleClose);
handleCloseRef.current = handleClose;
// Prefixed so the ids cannot collide with a host page's own Preact `useId` values.
const id = `-coinbase-wallet-sdk-dialog-${useId()}`;
const titleId = `${id}-title`;
const messageId = `${id}-message`;

// Modal focus: move focus into the dialog, keep Tab inside it, close on Escape, and hand
// focus back to whatever the page had focused once the dialog goes away.
useEffect(() => {
const instance = instanceRef.current;
if (!instance) return;

const previouslyFocused =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
const initialFocus =
instance.querySelector<HTMLElement>('.-coinbase-wallet-sdk-dialog-instance-button') ??
instance.querySelector<HTMLElement>('button');
initialFocus?.focus();

const handleKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;

if (event.key === 'Escape') {
event.preventDefault();
handleCloseRef.current();
return;
}
if (event.key !== 'Tab') return;

// The header close button always renders, so there is at least one.
const buttons = instance.querySelectorAll('button');
const first = buttons[0];
const last = buttons[buttons.length - 1];

const active = document.activeElement;
if (!instance.contains(active)) {
event.preventDefault();
first.focus();
} else if (event.shiftKey && active === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && active === last) {
event.preventDefault();
first.focus();
}
};

document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
if (previouslyFocused?.isConnected) previouslyFocused.focus();
};
}, []);

useEffect(() => {
const timer = window.setTimeout(() => {
Expand Down Expand Up @@ -232,6 +287,11 @@ export const DialogInstance: FunctionComponent<DialogInstanceProps> = ({

return (
<div
ref={instanceRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
aria-describedby={messageId}
class={clsx(
'-coinbase-wallet-sdk-dialog-instance',
hidden && '-coinbase-wallet-sdk-dialog-instance-hidden'
Expand All @@ -246,18 +306,32 @@ export const DialogInstance: FunctionComponent<DialogInstanceProps> = ({
</div>
)}
</div>
<div class="-coinbase-wallet-sdk-dialog-instance-header-close" onClick={handleClose}>
<img src={closeIcon} class="-coinbase-wallet-sdk-dialog-instance-header-close-icon" />
</div>
<button
type="button"
aria-label="Close"
class="-coinbase-wallet-sdk-dialog-instance-header-close"
onClick={handleClose}
>
<img
src={closeIcon}
alt=""
class="-coinbase-wallet-sdk-dialog-instance-header-close-icon"
/>
</button>
</div>
<div class="-coinbase-wallet-sdk-dialog-instance-content">
<div class="-coinbase-wallet-sdk-dialog-instance-content-title">{title}</div>
<div class="-coinbase-wallet-sdk-dialog-instance-content-message">{message}</div>
<div id={titleId} class="-coinbase-wallet-sdk-dialog-instance-content-title">
{title}
</div>
<div id={messageId} class="-coinbase-wallet-sdk-dialog-instance-content-message">
{message}
</div>
</div>
{actionItems && actionItems.length > 0 && (
<div class="-coinbase-wallet-sdk-dialog-instance-actions">
{actionItems.map((action, i) => (
<button
type="button"
class={clsx(
'-coinbase-wallet-sdk-dialog-instance-button',
action.variant === 'primary' &&
Expand Down