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
89 changes: 88 additions & 1 deletion src/components/ConfigStoreModal.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { ConfigStoreModal } from './ConfigStoreModal';
import type { ConfigDTO } from '../api/types';
import type { Plot } from '../types';
Expand Down Expand Up @@ -78,6 +78,13 @@ describe('ConfigStoreModal', () => {
disconnect() {}
}
);
// jsdom has no scrollIntoView. Carbon's modal calls it when focus moves to
// an element inside a scrolling ModalBody.
Object.defineProperty(Element.prototype, 'scrollIntoView', {
configurable: true,
writable: true,
value: vi.fn(),
});
vi.mocked(listConfigs).mockResolvedValue({
results: [],
continuationToken: null,
Expand All @@ -89,6 +96,7 @@ describe('ConfigStoreModal', () => {
cleanup();
vi.unstubAllGlobals();
vi.restoreAllMocks();
delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView;
});

it('cannot be dismissed while a save is in progress', async () => {
Expand Down Expand Up @@ -167,6 +175,85 @@ describe('ConfigStoreModal', () => {

await waitFor(() => expect(deleteConfig).toHaveBeenCalledWith('test-config'));
await screen.findByText('No saved configs yet.');
// The row's button went with the row, so focus falls back to the store body.
expect(document.activeElement).toBe(
screen.getByRole('region', { name: 'Config store contents' })
);
});

it('falls back to the store body when the delete trigger is disabled on close', async () => {
vi.mocked(listConfigs).mockResolvedValue({
results: [listedConfig],
continuationToken: null,
totalCount: 1,
});
renderModal();
await screen.findByText('test-config');

const trigger = screen.getAllByRole('button', { name: 'Delete' })[0];
fireEvent.click(trigger);
// Stands in for a row still mid-delete (busySlug) when the dialog closes.
(trigger as HTMLButtonElement).disabled = true;
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));

await waitFor(() =>
expect(document.querySelectorAll('.cds--modal.is-visible')).toHaveLength(1)
);
expect(document.activeElement).toBe(
screen.getByRole('region', { name: 'Config store contents' })
);
});

it('moves focus into the delete confirmation and back to its trigger on Escape', async () => {
// Carbon's focus wrap only targets elements with an offsetParent, which
// jsdom never sets (no layout). Without one the store's wrap can't move
// focus at all and this test couldn't see it pull focus back.
const offsetParent = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetParent')!;
Object.defineProperty(HTMLElement.prototype, 'offsetParent', {
configurable: true,
get(this: HTMLElement) {
return this.parentElement;
},
});
const focusedOutside: Element[] = [];
const recordFocus = (e: FocusEvent) => {
if (!(e.target as Element).closest('.cds--modal--danger')) {
focusedOutside.push(e.target as Element);
}
};
try {
vi.mocked(listConfigs).mockResolvedValue({
results: [listedConfig],
continuationToken: null,
totalCount: 1,
});
renderModal();
await screen.findByText('test-config');

// A keyboard user tabs to the row's Delete button and presses Enter.
const trigger = screen.getAllByRole('button', { name: 'Delete' })[0];
trigger.focus();
document.addEventListener('focusin', recordFocus);
fireEvent.click(trigger);

const confirmation = document.querySelector<HTMLElement>('.cds--modal--danger')!;
const cancel = within(confirmation).getByRole('button', { name: 'Cancel' });
await waitFor(() => expect(document.activeElement).toBe(cancel));
// jsdom lets the outer focus() win, so also check the store never took
// focus on the way (in a browser its pull-back wins and focus stays there).
expect(focusedOutside).toEqual([]);
document.removeEventListener('focusin', recordFocus);

// One Escape closes the confirmation and focus goes back to the trigger.
fireEvent.keyDown(cancel, { key: 'Escape' });
await waitFor(() =>
expect(document.querySelectorAll('.cds--modal.is-visible')).toHaveLength(1)
);
expect(document.activeElement).toBe(trigger);
} finally {
document.removeEventListener('focusin', recordFocus);
Object.defineProperty(HTMLElement.prototype, 'offsetParent', offsetParent);
}
});

it('aborts superseded loads and only applies the latest response', async () => {
Expand Down
35 changes: 33 additions & 2 deletions src/components/ConfigStoreModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ interface ConfigStoreModalProps {
// silently hidden; real paging is slaclab/react-trace#80.
const PAGE_SIZE = 200;

// Marks the delete confirmation, which opens as a second modal over the store.
// The store's Carbon focus wrap treats focus leaving for an element outside it
// as Tab-past-the-end and pulls it back to its own first button. Listing this
// class in the store's `selectorsFloatingMenus` lets focus move into the
// confirmation; the confirmation's own wrap then keeps it there.
const DELETE_CONFIRM_CLASS = 'config-store-delete-confirm';

function shareUrl(slug: string): string {
const url = new URL(window.location.href);
url.search = '';
Expand Down Expand Up @@ -92,6 +99,9 @@ export function ConfigStoreModal({
// Slug currently undergoing a row action (delete/load), to disable its buttons.
const [busySlug, setBusySlug] = useState<string | null>(null);
const [deleteTarget, setDeleteTarget] = useState<ConfigDTO | null>(null);
// The row button that opened the delete confirmation, to refocus on close.
const deleteTriggerRef = useRef<HTMLButtonElement | null>(null);
const storeBodyRef = useRef<HTMLDivElement>(null);
const loadAbortRef = useRef<AbortController | null>(null);
// Monotonic refresh id. A Save/Delete fires its own refresh while the open
// refresh may still be in flight; without this, the slower (older) response
Expand Down Expand Up @@ -135,6 +145,24 @@ export function ConfigStoreModal({
[]
);

// Return focus to the store when the delete confirmation closes. Otherwise it
// stays on the hidden confirmation, and the next Tab leaves the store for the
// page behind it. After a delete the row's button is gone (the list reloads),
// or still disabled if that reload lands in a later render, so fall back to
// the store's scrollable body, which Carbon makes focusable.
// Runs as the cleanup, i.e. after the commit that closes the confirmation, so
// its focus wrap is already off and doesn't pull focus back.
const deleteConfirmOpen = deleteTarget !== null;
useEffect(() => {
if (!deleteConfirmOpen) return;
const trigger = deleteTriggerRef.current;
const storeBody = storeBodyRef.current;
return () => {
const triggerUsable = trigger?.isConnected && !trigger.disabled;
(triggerUsable ? trigger : storeBody)?.focus();
};
}, [deleteConfirmOpen]);

const handleSave = async () => {
setSaving(true);
setError(null);
Expand Down Expand Up @@ -249,9 +277,10 @@ export function ConfigStoreModal({
onClose();
}}
size="lg"
selectorsFloatingMenus={[`.${DELETE_CONFIRM_CLASS}`]}
>
<ModalHeader title="Config store" />
<ModalBody hasScrollingContent>
<ModalBody hasScrollingContent aria-label="Config store contents" ref={storeBodyRef}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 4 }}>
{error && !deleteTarget && (
<InlineNotification
Expand Down Expand Up @@ -370,7 +399,8 @@ export function ConfigStoreModal({
hasIconOnly
iconDescription="Delete"
renderIcon={TrashCan}
onClick={() => {
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
deleteTriggerRef.current = e.currentTarget;
setError(null);
setDeleteTarget(c);
}}
Expand All @@ -396,6 +426,7 @@ export function ConfigStoreModal({
}}
size="sm"
danger
className={DELETE_CONFIRM_CLASS}
>
<ModalHeader title="Delete config?" />
<ModalBody>
Expand Down
Loading