fix(dialog): recover initial focus from nested modal fallback

This commit is contained in:
cesnimda
2026-11-11 07:44:38 +01:00
parent ec57a24d77
commit df93bfb64e
2 changed files with 22 additions and 1 deletions
+16
View File
@@ -67,3 +67,19 @@ test('finishing the opening transition preserves focus already moved inside the
jest.useRealTimers();
}
});
test('finishing the opening transition recovers Cancel from the nested-modal container fallback', async () => {
jest.useFakeTimers();
try {
render(<ConfirmProvider><Demo /></ConfirmProvider>);
fireEvent.click(screen.getByRole('button', { name: /open confirm/i }));
const container = screen.getByRole('dialog', { name: 'Delete job' }).parentElement!;
expect(container).toHaveAttribute('role', 'presentation');
act(() => container.focus());
expect(container).toHaveFocus();
await act(async () => { jest.advanceTimersByTime(1000); });
expect(screen.getByRole('button', { name: 'Cancel' })).toHaveFocus();
} finally {
jest.useRealTimers();
}
});
+6 -1
View File
@@ -24,6 +24,7 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
const i18n = useOptionalI18n();
const messageId = useId();
const titleId = useId();
const cancelRef = useRef<HTMLButtonElement>(null);
const resolverRef = useRef<((value: boolean) => void) | null>(null);
const [state, setState] = useState<ConfirmState>({
open: false,
@@ -63,6 +64,10 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
<Dialog open={state.open} onClose={() => closeWith(false)} aria-labelledby={titleId} aria-describedby={messageId} fullWidth maxWidth="xs"
slotProps={{
paper: { sx: { borderRadius: 3, border: 1, borderColor: "divider", backgroundImage: "none" } },
transition: { onEntered: (node) => {
// Nested modals can leave initial focus on the container; preserve deliberate focus inside it.
if (node.ownerDocument.activeElement === node) cancelRef.current?.focus();
} },
}}>
<DialogTitle id={titleId} sx={{ pb: 1, fontWeight: 800 }}>{state.title}</DialogTitle>
<DialogContent role="region" aria-labelledby={titleId} tabIndex={0}>
@@ -74,7 +79,7 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
<Typography id={messageId} sx={{ color: "text.secondary" }}>{state.message}</Typography>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5, gap: 1 }}>
<Button autoFocus onClick={() => closeWith(false)}>{state.cancelLabel}</Button>
<Button ref={cancelRef} autoFocus onClick={() => closeWith(false)}>{state.cancelLabel}</Button>
<Button color={state.destructive ? "error" : "primary"} variant="contained" onClick={() => closeWith(true)}>
{state.confirmLabel}
</Button>