diff --git a/src/components/ConfigStoreModal.test.tsx b/src/components/ConfigStoreModal.test.tsx index bed095c..a1de64e 100644 --- a/src/components/ConfigStoreModal.test.tsx +++ b/src/components/ConfigStoreModal.test.tsx @@ -1,207 +1,778 @@ // @vitest-environment jsdom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +// +// Pins ConfigStoreModal's async lifecycle (slaclab/react-trace#92). Save and +// every row's Load/Rename/Delete share one busy slot, so only one runs at a +// time. Save, Rename and Delete block all three of Carbon's dismissal paths (X, +// Escape, backdrop) until their server call settles; a Delete also keeps its +// confirmation dialog open until then. A Load doesn't block: dismissing aborts +// it and drops its result, even a response that beat the abort. +// +// Every magpie call returns a promise the test settles by hand, so each case +// controls exactly when a response lands relative to clicks and dismissals. +import { useState } from 'react'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, 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'; - -vi.mock('../api/magpie', () => ({ - saveConfig: vi.fn(), - getConfig: vi.fn(), - listConfigs: vi.fn(), - updateConfig: vi.fn(), - deleteConfig: vi.fn(), +import { CanopyError } from '../api/client'; +import type * as Magpie from '../api/magpie'; +import type { ConfigDTO, PagedResult } from '../api/types'; + +const api = vi.hoisted(() => ({ + saveConfig: vi.fn(), + getConfig: vi.fn(), + listConfigs: vi.fn(), + updateConfig: vi.fn(), + deleteConfig: vi.fn(), })); +vi.mock('../api/magpie', () => api); +// The workspace codec isn't under test: Save sends {}, and Load spreads `data` +// over an empty workspace, so a config's `from` says which one was applied and +// its `warnings` (if any) reach the toast. +vi.mock('../io/serialize', () => ({ + serializeConfigData: () => ({}), + deserializeConfigData: (data: object) => ({ + source: 'native', + plots: [], + warnings: [], + ...data, + }), +})); + +interface Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (reason: unknown) => void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} -import { deleteConfig, getConfig, listConfigs, saveConfig } from '../api/magpie'; - -const plot: Plot = { - id: 'plot-1', - title: 'Plot', - traces: [], - axes: [], - backgroundColor: '#161616', - showLegend: true, - showXGridlines: true, - showYGridlines: true, - showCrosshair: true, - gridStyle: 'solid', - gridOpacity: 1, - tickFontSize: 11, - xAxis: { timeRange: '-1h' }, -}; - -const savedConfig: ConfigDTO = { - id: 'config-1', - app: 'trace', - slug: 'share-slug', - name: null, - description: null, - data: {}, - createdBy: null, - createdDate: '2026-10-01T00:00:00Z', - lastModifiedDate: '2026-10-01T00:00:00Z', -}; - -const listedConfig: ConfigDTO = { - ...savedConfig, - slug: 'test-config', - name: 'Test config', -}; - -const secondListedConfig: ConfigDTO = { - ...listedConfig, - slug: 'second-config', - name: 'Second config', -}; - -function renderModal(onToast = vi.fn(), onLoaded = vi.fn()) { - return render( - +function config(slug: string, name: string, createdDate: string): ConfigDTO { + return { + id: `id-${slug}`, + app: 'trace', + slug, + name, + description: null, + data: { from: slug }, + createdBy: null, + createdDate, + lastModifiedDate: createdDate, + }; +} + +// The list renders newest first, so A is the first row. +const A = config('slug-a', 'Config A', '2026-10-02T00:00:00Z'); +const B = config('slug-b', 'Config B', '2026-10-01T00:00:00Z'); +const PAGE: PagedResult = { results: [B, A], continuationToken: null, totalCount: 2 }; + +// Pending calls, in call order. getConfig doesn't reject on abort by itself: +// a test either settles it by hand (a response that beat the abort) or rejects +// it with an AbortError, as fetch would. +let loads: (Deferred & { slug: string; signal: AbortSignal | undefined })[]; +let saves: Deferred[]; +let renames: Deferred[]; +let deletes: Deferred[]; + +const onLoaded = vi.fn(); +const onToast = vi.fn(); +const parentClose = vi.fn(); + +// Stands in for TraceApp: owns `open`, mounts the modal only while it's open, +// and has a toolbar button that can only set `open` to true. +function Harness() { + const [open, setOpen] = useState(true); + return ( + <> + + {open && ( + { + parentClose(); + setOpen(false); + }} + onLoaded={onLoaded} + onToast={onToast} + /> + )} + ); } -describe('ConfigStoreModal', () => { - beforeEach(() => { - vi.stubGlobal( - 'ResizeObserver', - class { - observe() {} - unobserve() {} - 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, - totalCount: 0, - }); +// Run `fn`, then let every promise continuation and React update it triggers finish. +async function settle(fn: () => void = () => {}) { + await act(async () => { + fn(); + await new Promise((r) => setTimeout(r, 0)); + }); +} + +async function mount() { + const result = render(); + await settle(); + return result; +} + +async function reopen() { + fireEvent.click(screen.getByText('toolbar-open')); + await settle(); +} + +// Each ComposedModal renders a dialog named by its aria-label. Carbon marks a +// closed one aria-hidden, which only a `hidden` query finds. +function dialog(name: string, hidden: boolean): HTMLElement | null { + return screen.queryByRole('dialog', { name, hidden }); +} + +// The config store, or null once TraceApp has unmounted it. +function storeModal(): HTMLElement | null { + return dialog('Config store', true); +} + +// The delete confirmation. It stays mounted, hidden, while the store is. +function confirmModal(): HTMLElement | null { + return dialog('Delete config?', true); +} + +const storeOpen = () => dialog('Config store', false) !== null; +const confirmOpen = () => dialog('Delete config?', false) !== null; + +type RowAction = 'Load' | 'Rename' | 'Delete'; +const ROW_ACTIONS: RowAction[] = ['Load', 'Rename', 'Delete']; + +// `hidden: true` throughout: these also reach the store while the delete +// confirmation is open over it, which a browser hides from assistive tech +// (the confirmation is aria-modal). Testing Library's check ignores aria-modal. +function rowButton(name: string, action: RowAction): HTMLButtonElement { + const row = screen.getByText(name).closest('[role="row"]') as HTMLElement; + return within(row).getByRole('button', { name: action, hidden: true }) as HTMLButtonElement; +} + +function saveButton(): HTMLButtonElement { + return screen.getByRole('button', { + name: /^(Save & copy share link|Saving…)$/, + hidden: true, + }) as HTMLButtonElement; +} + +function allRowButtons(): HTMLButtonElement[] { + return [A, B].flatMap((c) => ROW_ACTIONS.map((action) => rowButton(c.name!, action))); +} + +// The confirmation's own Delete button, which starts the delete. Its +// accessible name starts with the danger description, so match the end. +function confirmDeleteButton(): HTMLButtonElement { + return within(confirmModal()!).getByRole('button', { + name: /(Delete|Deleting…)$/, + hidden: true, + }) as HTMLButtonElement; +} + +// A row's Delete, then the confirmation's. +function startDelete(name: string) { + fireEvent.click(rowButton(name, 'Delete')); + fireEvent.click(confirmDeleteButton()); +} + +// Start `action` on the row named `name`, through the confirmation for a Delete. +function startRowAction(name: string, action: RowAction) { + if (action === 'Delete') startDelete(name); + else fireEvent.click(rowButton(name, action)); +} + +const PATHS = ['X', 'Escape', 'backdrop'] as const; +type DismissPath = (typeof PATHS)[number]; + +// Dismiss the store. Escape goes to the topmost visible modal, as in Carbon. +function dismiss(path: DismissPath) { + const store = storeModal()!; + switch (path) { + case 'X': + fireEvent.click(within(store).getByRole('button', { name: 'Close', hidden: true })); + break; + case 'Escape': + fireEvent.keyDown(document, { key: 'Escape', keyCode: 27 }); + break; + case 'backdrop': { + // The dialog's presentation wrapper is the overlay around it. + const backdrop = store.closest('[role="presentation"]')!; + fireEvent.mouseDown(backdrop); + fireEvent.click(backdrop); + break; + } + } +} + +// The confirmation has a footer, so Carbon doesn't close it on a backdrop click. +const CONFIRM_PATHS = ['X', 'Escape', 'Cancel'] as const; +type ConfirmDismissPath = (typeof CONFIRM_PATHS)[number]; + +function dismissConfirm(path: ConfirmDismissPath) { + const dialog = confirmModal()!; + switch (path) { + case 'X': + fireEvent.click(within(dialog).getByRole('button', { name: 'Close', hidden: true })); + break; + case 'Escape': + fireEvent.keyDown(document, { key: 'Escape', keyCode: 27 }); + break; + case 'Cancel': + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel', hidden: true })); + break; + } +} + +// jsdom has no clipboard API, so a Save's share-link copy normally fails at +// once. Cases that need a pending or rejected copy install one; afterEach +// removes it. +function stubClipboard(writeText: (text: string) => Promise) { + const clipboard = { writeText: vi.fn(writeText) }; + Object.defineProperty(navigator, 'clipboard', { value: clipboard, configurable: true }); + return clipboard; +} + +beforeAll(() => { + // Carbon's icon-button tooltips observe their size; jsdom has no ResizeObserver. + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + 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(), }); +}); + +afterAll(() => { + vi.unstubAllGlobals(); + delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView; +}); - afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - vi.restoreAllMocks(); - delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView; +beforeEach(() => { + loads = []; + saves = []; + renames = []; + deletes = []; + api.listConfigs.mockResolvedValue(PAGE); + api.getConfig.mockImplementation((slug, signal) => { + const d = deferred(); + loads.push({ ...d, slug, signal }); + return d.promise; }); + api.saveConfig.mockImplementation(() => { + const d = deferred(); + saves.push(d); + return d.promise; + }); + api.updateConfig.mockImplementation(() => { + const d = deferred(); + renames.push(d); + return d.promise; + }); + api.deleteConfig.mockImplementation(() => { + const d = deferred(); + deletes.push(d); + return d.promise; + }); + vi.spyOn(window, 'prompt').mockReturnValue('Renamed'); +}); - it('cannot be dismissed while a save is in progress', async () => { - vi.mocked(saveConfig).mockImplementation(() => new Promise(() => {})); - renderModal(); +afterEach(() => { + // No vitest globals, so RTL can't register its own cleanup. + cleanup(); + Reflect.deleteProperty(navigator, 'clipboard'); + vi.restoreAllMocks(); + vi.clearAllMocks(); +}); - fireEvent.click(screen.getByRole('button', { name: /Save & copy share link/ })); - await screen.findByRole('button', { name: 'Saving…' }); - fireEvent.click(screen.getByRole('button', { name: 'Close' })); +describe('ConfigStoreModal: one operation at a time', () => { + it.each([ + ['B, then A', ['slug-b', 'slug-a']], + ['A, then B', ['slug-a', 'slug-b']], + ])('applies only the first of two Load clicks (responses %s)', async (_order, slugs) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + fireEvent.click(rowButton('Config B', 'Load')); + for (const slug of slugs) { + const load = loads.find((l) => l.slug === slug); + if (load) await settle(() => load.resolve(slug === A.slug ? A : B)); + } + expect(api.getConfig.mock.calls.map(([slug]) => slug)).toEqual([A.slug]); + expect(onLoaded).toHaveBeenCalledTimes(1); + expect(onLoaded).toHaveBeenCalledWith(expect.objectContaining(A.data)); + expect(onToast).toHaveBeenCalledTimes(1); + }); - expect(document.querySelector('.cds--modal.is-visible')).not.toBeNull(); + // Inside one act() the second button is still enabled in the DOM, so only + // the slot's ref can turn the click away. + it.each(ROW_ACTIONS)( + 'starts only the Load when a %s click lands before React re-renders', + async (action) => { + await mount(); + act(() => { + rowButton('Config A', 'Load').click(); + rowButton('Config B', action).click(); + }); + expect(api.getConfig.mock.calls.map(([slug]) => slug)).toEqual([A.slug]); + expect(window.prompt).not.toHaveBeenCalled(); + expect(confirmOpen()).toBe(false); + } + ); + + it('disables every row action and Save while a Load is in flight', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + expect(allRowButtons().map((b) => b.disabled)).toEqual(Array(6).fill(true)); + expect(saveButton().disabled).toBe(true); + }); + + it('disables every row action while a Save is in flight', async () => { + await mount(); + fireEvent.click(saveButton()); + expect(allRowButtons().map((b) => b.disabled)).toEqual(Array(6).fill(true)); + }); + + it.each(['Rename', 'Delete'] as const)( + 'does not start a %s while a Load is in flight', + async (action) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + fireEvent.click(rowButton('Config B', action)); + expect(window.prompt).not.toHaveBeenCalled(); + expect(confirmOpen()).toBe(false); + expect(api.updateConfig).not.toHaveBeenCalled(); + expect(api.deleteConfig).not.toHaveBeenCalled(); + } + ); + + it('does not start a Load while a Delete is in flight', async () => { + await mount(); + startDelete('Config B'); + fireEvent.click(rowButton('Config A', 'Load')); + expect(api.getConfig).not.toHaveBeenCalled(); + }); + + // Before the fix the Rename ran, and its `finally` re-enabled A's Load while + // the Load was still in flight. Now the Rename never starts. + it("keeps A's Load disabled after a Rename click during it", async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + fireEvent.click(rowButton('Config B', 'Rename')); + await settle(() => renames.forEach((r) => r.resolve(B))); + expect(rowButton('Config A', 'Load').disabled).toBe(true); }); - it('keeps the fallback share link available until the toast is dismissed', async () => { - vi.mocked(saveConfig).mockResolvedValue(savedConfig); - Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }); - const onToast = vi.fn(); - renderModal(onToast); + it.each([ + ['Load', 'Loading "Config A"…'], + ['Rename', 'Renaming "Config A"…'], + ['Delete', 'Deleting "Config A"…'], + ] as const)('shows a %s in the status line', async (action, status) => { + await mount(); + startRowAction('Config A', action); + expect(screen.queryByText(status)).not.toBeNull(); + }); - fireEvent.click(screen.getByRole('button', { name: /Save & copy share link/ })); + it('shows a Load failure and re-enables the row (control: passes before the fix too)', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + await settle(() => loads[0].reject(new CanopyError('config_not_found', 404, 'not found'))); + expect(within(storeModal()!).queryByText('not found')).not.toBeNull(); + expect(rowButton('Config A', 'Load').disabled).toBe(false); + expect(storeOpen()).toBe(true); + expect(onLoaded).not.toHaveBeenCalled(); + }); +}); - await waitFor(() => { - expect(onToast).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'Workspace saved', - subtitle: expect.stringContaining('share-slug'), - timeout: 0, - }) - ); +describe('ConfigStoreModal: the Load toast', () => { + it('closes after the usual timeout when the config loaded cleanly', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + await settle(() => loads[0].resolve(A)); + expect(onToast).toHaveBeenCalledWith({ + kind: 'success', + title: 'Workspace loaded', + subtitle: 'Loaded "Config A"', + timeout: undefined, }); }); - it('uses a Carbon dialog to confirm deletion and explain the shared-link impact', async () => { - vi.mocked(listConfigs).mockResolvedValue({ - results: [listedConfig], - continuationToken: null, - totalCount: 1, + it('lists the warnings and stays until dismissed when there are any', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + const warnings = ['Skipped trace "X"', 'Unknown axis "Y"']; + await settle(() => loads[0].resolve({ ...A, data: { from: A.slug, warnings } })); + expect(onToast).toHaveBeenCalledWith({ + kind: 'success', + title: 'Workspace loaded', + subtitle: ['Loaded "Config A"', ...warnings].join('\n'), + timeout: 0, }); - const nativeConfirm = vi.spyOn(window, 'confirm'); - renderModal(); + }); +}); - await screen.findByText('test-config'); - fireEvent.click(screen.getAllByRole('button', { name: 'Delete' })[0]); +describe('ConfigStoreModal: dismissing cancels a Load', () => { + it.each(PATHS)( + 'closes on %s during a Load and ignores a response that beat the abort', + async (path) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + dismiss(path); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + + await settle(() => loads[0].resolve(A)); + expect(onLoaded).not.toHaveBeenCalled(); + expect(onToast).not.toHaveBeenCalled(); + expect(parentClose).toHaveBeenCalledTimes(1); + } + ); - expect(document.querySelectorAll('.cds--modal.is-visible')).toHaveLength(2); + it.each(PATHS)('aborts the Load request on %s and reports nothing for it', async (path) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + const { signal } = loads[0]; + dismiss(path); + expect(signal?.aborted).toBe(true); + + await settle(() => + loads[0].reject(new DOMException('The operation was aborted.', 'AbortError')) + ); + expect(onLoaded).not.toHaveBeenCalled(); + expect(onToast).not.toHaveBeenCalled(); + }); + + // The dismissed Load's handler still runs when its response lands. If it + // applied the workspace or called onClose, it would close the reopened modal. + it("drops a dismissed Load's response after a reopen; the new Load still applies", async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + dismiss('Escape'); + await reopen(); + expect(storeOpen()).toBe(true); + + fireEvent.click(rowButton('Config A', 'Load')); + await settle(() => loads[0].resolve(A)); + expect(onLoaded).not.toHaveBeenCalled(); + expect(storeOpen()).toBe(true); + expect(parentClose).toHaveBeenCalledTimes(1); + + await settle(() => loads[1].resolve(A)); + expect(onLoaded).toHaveBeenCalledTimes(1); + expect(storeOpen()).toBe(false); + }); + + it('aborts an in-flight Load on unmount and drops its response', async () => { + const { unmount } = await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + const { signal } = loads[0]; + unmount(); + expect(signal?.aborted).toBe(true); + await settle(() => loads[0].resolve(A)); + expect(onLoaded).not.toHaveBeenCalled(); + expect(onToast).not.toHaveBeenCalled(); + }); +}); + +describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { + it.each(PATHS)( + 'blocks %s during a Save until its server call settles, then closes on it', + async (path) => { + await mount(); + fireEvent.click(saveButton()); + dismiss(path); + expect(storeOpen()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + + // Hold the list refresh that follows: only the server call blocks closing. + const list = deferred>(); + api.listConfigs.mockReturnValueOnce(list.promise); + await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); + expect(api.listConfigs).toHaveBeenCalledTimes(2); + expect(saveButton().disabled).toBe(false); + dismiss(path); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + await settle(() => list.resolve(PAGE)); + } + ); + + it.each(PATHS)( + 'blocks dismissal during a Rename (%s) until its server call settles, not the list refresh after it', + async (path) => { + await mount(); + fireEvent.click(rowButton('Config B', 'Rename')); + dismiss(path); + expect(storeOpen()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + + // Hold the list refresh that follows: only the server call blocks closing. + const list = deferred>(); + api.listConfigs.mockReturnValueOnce(list.promise); + await settle(() => renames[0].resolve(B)); + expect(api.listConfigs).toHaveBeenCalledTimes(2); + expect(screen.queryByText(/^Renaming /)).toBeNull(); + dismiss(path); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + await settle(() => list.resolve(PAGE)); + } + ); + + // Carbon keeps the onClose from the render that opened the confirmation, so + // a guard on render state would let Escape through mid-delete. + it.each(CONFIRM_PATHS)( + 'keeps the delete confirmation open on %s until the Delete settles, then the store closes', + async (path) => { + await mount(); + startDelete('Config B'); + dismissConfirm(path); + expect(confirmOpen()).toBe(true); + expect(storeOpen()).toBe(true); + expect(confirmDeleteButton().disabled).toBe(true); + + // Hold the list refresh that follows: only the server call blocks closing. + const list = deferred>(); + api.listConfigs.mockReturnValueOnce(list.promise); + await settle(() => deletes[0].resolve()); + expect(confirmOpen()).toBe(false); + expect(storeOpen()).toBe(true); + expect(api.listConfigs).toHaveBeenCalledTimes(2); + expect(screen.queryByText(/^Deleting /)).toBeNull(); + dismiss('Escape'); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + await settle(() => list.resolve(PAGE)); + } + ); + + // In a browser the confirmation's overlay covers the store's X and backdrop; + // these events reach them directly to pin the guard behind it. + it.each(['X', 'backdrop'] as const)( + "refuses the store's %s under the delete confirmation, before and during the Delete", + async (path) => { + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + dismiss(path); + expect(storeOpen()).toBe(true); + fireEvent.click(confirmDeleteButton()); + dismiss(path); + expect(storeOpen()).toBe(true); + expect(confirmOpen()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + + // Carbon hides a modal whose onClose doesn't return false, even while + // `open` stays true, and then sends Escape past it. So Escape closing + // the store shows both refusals left it open. + await settle(() => deletes[0].resolve()); + dismiss('Escape'); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + } + ); + + it('shows a Delete failure in the confirmation, which stays open for a retry', async () => { + await mount(); + startDelete('Config B'); + dismissConfirm('Escape'); + await settle(() => deletes[0].reject(new CanopyError('forbidden', 403, 'not allowed'))); + expect(confirmOpen()).toBe(true); + expect(within(confirmModal()!).queryByText('not allowed')).not.toBeNull(); + expect(saveButton().disabled).toBe(false); + + fireEvent.click(confirmDeleteButton()); + expect(api.deleteConfig.mock.calls.map(([slug]) => slug)).toEqual([B.slug, B.slug]); + expect(within(confirmModal()!).queryByText('not allowed')).toBeNull(); + }); + + it.each(CONFIRM_PATHS)( + "drops a failed Delete's error from the store when %s closes the confirmation", + async (path) => { + await mount(); + startDelete('Config B'); + // Refused while the Delete runs. It must leave Carbon's own state open + // too: for Escape, the second press below would otherwise go to the store. + dismissConfirm(path); + await settle(() => deletes[0].reject(new CanopyError('forbidden', 403, 'not allowed'))); + expect(within(confirmModal()!).queryByText('not allowed')).not.toBeNull(); + + dismissConfirm(path); + expect(confirmOpen()).toBe(false); + expect(storeOpen()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + expect(within(storeModal()!).queryByText('not allowed')).toBeNull(); + } + ); + + // Escape closing the store shows the refused X left Carbon's own state open + // (see the case above that refuses X under the delete confirmation). + it('can still be used after X was pressed during a Save', async () => { + await mount(); + fireEvent.click(saveButton()); + dismiss('X'); + await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); + expect(saveButton().disabled).toBe(false); + dismiss('Escape'); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + }); + + it('still toasts a Save that outlives the modal, and touches nothing else', async () => { + const { unmount } = await mount(); + fireEvent.click(saveButton()); + unmount(); + await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); + expect(onToast).toHaveBeenCalledWith(expect.objectContaining({ title: 'Workspace saved' })); + expect(api.listConfigs).toHaveBeenCalledTimes(1); + }); +}); + +describe('ConfigStoreModal: the delete confirmation', () => { + it('asks in a Carbon dialog over the store and explains the shared-link impact', async () => { + const nativeConfirm = vi.spyOn(window, 'confirm'); + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + + expect(screen.getAllByRole('dialog')).toHaveLength(2); expect(screen.getByText('Save current workspace')).toBeTruthy(); expect( - screen.getByText(/This will break any shared links to it\. This action cannot be undone\./) + within(confirmModal()!).getByText( + /This will break any shared links to it\. This action cannot be undone\./ + ) ).toBeTruthy(); expect(nativeConfirm).not.toHaveBeenCalled(); - expect(deleteConfig).not.toHaveBeenCalled(); - - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); - expect(document.querySelectorAll('.cds--modal.is-visible')).toHaveLength(1); - await screen.findByText('test-config'); - }); - - it('deletes the config only after confirming in the Carbon dialog', async () => { - vi.mocked(listConfigs) - .mockResolvedValueOnce({ - results: [listedConfig], - continuationToken: null, - totalCount: 1, - }) - .mockResolvedValue({ - results: [], - continuationToken: null, - totalCount: 0, - }); - vi.mocked(deleteConfig).mockResolvedValue(); - renderModal(); - - await screen.findByText('test-config'); - fireEvent.click(screen.getAllByRole('button', { name: 'Delete' })[0]); - fireEvent.click(document.querySelector('.cds--modal--danger .cds--btn--danger')!); - - 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' }) - ); + expect(api.deleteConfig).not.toHaveBeenCalled(); + + dismissConfirm('Cancel'); + expect(screen.getAllByRole('dialog')).toHaveLength(1); + expect(screen.getByText('Config B')).toBeTruthy(); + expect(api.deleteConfig).not.toHaveBeenCalled(); }); - 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'); + it.each(CONFIRM_PATHS)( + 'closes on %s before the Delete starts, leaving the store open', + async (path) => { + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + dismissConfirm(path); + expect(confirmOpen()).toBe(false); + expect(storeOpen()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + expect(api.deleteConfig).not.toHaveBeenCalled(); + } + ); - 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' })); + it('deletes only after confirming, then refreshes the list', async () => { + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + expect(api.deleteConfig).not.toHaveBeenCalled(); + + fireEvent.click(confirmDeleteButton()); + expect(api.deleteConfig).toHaveBeenCalledWith(B.slug); + api.listConfigs.mockResolvedValue({ results: [A], continuationToken: null, totalCount: 1 }); + await settle(() => deletes[0].resolve()); + expect(screen.queryByText('Config B')).toBeNull(); + expect(screen.getByText('Config A')).toBeTruthy(); + }); +}); - await waitFor(() => - expect(document.querySelectorAll('.cds--modal.is-visible')).toHaveLength(1) - ); - expect(document.activeElement).toBe( - screen.getByRole('region', { name: 'Config store contents' }) - ); +// In a browser the confirmation's overlay covers the store, but the store's +// buttons stay enabled in the DOM, so these click them directly. +describe('ConfigStoreModal: nothing else starts while the delete confirmation is open', () => { + async function confirmDeleteOfB() { + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + expect(confirmOpen()).toBe(true); + } + + // The confirmation is still about B, and its own Delete still deletes B. + async function expectConfirmationStillDeletesB() { + expect(confirmOpen()).toBe(true); + expect(within(confirmModal()!).getByText('Config B')).toBeTruthy(); + expect(confirmDeleteButton().disabled).toBe(false); + fireEvent.click(confirmDeleteButton()); + expect(api.deleteConfig.mock.calls).toEqual([[B.slug]]); + await settle(() => deletes[0].resolve()); + expect(confirmOpen()).toBe(false); + expect(parentClose).not.toHaveBeenCalled(); + } + + it("does not start another row's Load, so the store stays open", async () => { + await confirmDeleteOfB(); + fireEvent.click(rowButton('Config A', 'Load')); + await settle(); + expect(api.getConfig).not.toHaveBeenCalled(); + expect(onLoaded).not.toHaveBeenCalled(); + expect(parentClose).not.toHaveBeenCalled(); + await expectConfirmationStillDeletesB(); + }); + + it("does not prompt for or start another row's Rename", async () => { + await confirmDeleteOfB(); + fireEvent.click(rowButton('Config A', 'Rename')); + await settle(); + expect(window.prompt).not.toHaveBeenCalled(); + expect(api.updateConfig).not.toHaveBeenCalled(); + await expectConfirmationStillDeletesB(); + }); + + it('does not start a Save', async () => { + await confirmDeleteOfB(); + fireEvent.click(saveButton()); + await settle(); + expect(api.saveConfig).not.toHaveBeenCalled(); + await expectConfirmationStillDeletesB(); + }); + + it("does not switch the confirmation to another row's Delete", async () => { + await confirmDeleteOfB(); + fireEvent.click(rowButton('Config A', 'Delete')); + await settle(); + await expectConfirmationStillDeletesB(); + }); +}); + +describe('ConfigStoreModal: focus around the delete confirmation', () => { + // The store's scrolling body, which Carbon makes focusable. Carbon up to 1.108 + // names it by its aria-label ("Config store contents"), later versions by the + // modal heading ("Config store"). + const storeBody = () => screen.getByRole('region', { name: /^Config store/ }); + + it('falls back to the store body when a Delete removes the trigger with its row', async () => { + await mount(); + startDelete('Config B'); + api.listConfigs.mockResolvedValue({ results: [A], continuationToken: null, totalCount: 1 }); + await settle(() => deletes[0].resolve()); + expect(screen.queryByText('Config B')).toBeNull(); + expect(document.activeElement).toBe(storeBody()); + }); + + it('falls back to the store body when the delete trigger is disabled on close', async () => { + await mount(); + const trigger = rowButton('Config B', 'Delete'); + fireEvent.click(trigger); + // Stands in for a trigger that can't take focus when the confirmation closes. + trigger.disabled = true; + dismissConfirm('Cancel'); + await settle(); + expect(confirmOpen()).toBe(false); + expect(document.activeElement).toBe(storeBody()); }); it('moves focus into the delete confirmation and back to its trigger on Escape', async () => { @@ -222,22 +793,14 @@ describe('ConfigStoreModal', () => { } }; try { - vi.mocked(listConfigs).mockResolvedValue({ - results: [listedConfig], - continuationToken: null, - totalCount: 1, - }); - renderModal(); - await screen.findByText('test-config'); - + await mount(); // A keyboard user tabs to the row's Delete button and presses Enter. - const trigger = screen.getAllByRole('button', { name: 'Delete' })[0]; + const trigger = rowButton('Config B', 'Delete'); trigger.focus(); document.addEventListener('focusin', recordFocus); fireEvent.click(trigger); - const confirmation = document.querySelector('.cds--modal--danger')!; - const cancel = within(confirmation).getByRole('button', { name: 'Cancel' }); + const cancel = within(confirmModal()!).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). @@ -246,74 +809,77 @@ describe('ConfigStoreModal', () => { // 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) - ); + await waitFor(() => expect(confirmOpen()).toBe(false)); + expect(storeOpen()).toBe(true); 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 () => { - vi.mocked(listConfigs).mockResolvedValue({ - results: [listedConfig, secondListedConfig], - continuationToken: null, - totalCount: 2, - }); - const requests: { - signal: AbortSignal; - resolve: (value: ConfigDTO) => void; - }[] = []; - vi.mocked(getConfig).mockImplementation( - (_slug, signal) => - new Promise((resolve) => { - requests.push({ signal: signal!, resolve }); - }) - ); - const onLoaded = vi.fn(); - renderModal(undefined, onLoaded); - await screen.findByText('test-config'); - - fireEvent.click(screen.getAllByRole('button', { name: 'Load' })[0]); - fireEvent.click(screen.getAllByRole('button', { name: 'Load' })[1]); - - expect(requests).toHaveLength(2); - expect(requests[0].signal.aborted).toBe(true); - - const data = { schemaVersion: 1, plots: [plot] }; - requests[0].resolve({ ...listedConfig, data }); - requests[1].resolve({ ...secondListedConfig, data }); +describe('ConfigStoreModal: the share-link copy does not hold the Save slot', () => { + const NEW = config('slug-new', 'New', '2026-10-03T00:00:00Z'); + + it.each(PATHS)( + 'frees every action and allows %s once the Save lands, while the copy is pending', + async (path) => { + const copy = deferred(); + const clipboard = stubClipboard(() => copy.promise); + await mount(); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Mine' } }); + fireEvent.click(saveButton()); + await settle(() => saves[0].resolve(NEW)); + expect(clipboard.writeText).toHaveBeenCalledWith(expect.stringMatching(/config=slug-new$/)); + expect(saveButton().disabled).toBe(false); + expect(allRowButtons().map((b) => b.disabled)).toEqual(Array(6).fill(false)); + expect((screen.getByLabelText('Name') as HTMLInputElement).value).toBe(''); + expect(api.listConfigs).toHaveBeenCalledTimes(2); + expect(onToast).not.toHaveBeenCalled(); + + dismiss(path); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + + // The toast still reports the copy after the dialog has gone. + await settle(() => copy.resolve()); + expect(onToast).toHaveBeenCalledWith({ + kind: 'success', + title: 'Workspace saved', + subtitle: 'Share link copied to clipboard (slug-new)', + timeout: undefined, + }); + } + ); - await waitFor(() => expect(onLoaded).toHaveBeenCalledTimes(1)); - expect(onLoaded).toHaveBeenCalledWith( - expect.objectContaining({ plots: [expect.objectContaining({ id: 'plot-1' })] }) - ); + it('lets another operation start while the copy is pending', async () => { + stubClipboard(() => new Promise(() => {})); + await mount(); + fireEvent.click(saveButton()); + await settle(() => saves[0].resolve(NEW)); + fireEvent.click(rowButton('Config A', 'Load')); + expect(api.getConfig.mock.calls.map(([slug]) => slug)).toEqual([A.slug]); }); - it('aborts a pending load when the modal unmounts', async () => { - vi.mocked(listConfigs).mockResolvedValue({ - results: [listedConfig], - continuationToken: null, - totalCount: 1, + // A success toast normally closes after a few seconds, too soon to copy a + // long link by hand. + it.each([ + [ + 'is rejected', + () => stubClipboard(() => Promise.reject(new DOMException('Denied', 'NotAllowedError'))), + ], + ['has no clipboard API', () => {}], + ])('shows the link itself, until dismissed, when the copy %s', async (_case, setUp) => { + setUp(); + await mount(); + fireEvent.click(saveButton()); + await settle(() => saves[0].resolve(NEW)); + expect(onToast).toHaveBeenCalledWith({ + kind: 'success', + title: 'Workspace saved', + subtitle: expect.stringMatching(/^Share link: .*\?config=slug-new$/), + timeout: 0, }); - vi.mocked(getConfig).mockImplementation( - (_slug, signal) => - new Promise(() => { - expect(signal).toBeDefined(); - }) - ); - const onLoaded = vi.fn(); - const view = renderModal(undefined, onLoaded); - await screen.findByText('test-config'); - fireEvent.click(screen.getByRole('button', { name: 'Load' })); - await waitFor(() => expect(getConfig).toHaveBeenCalled()); - - const signal = vi.mocked(getConfig).mock.calls.at(-1)?.[1]; - view.unmount(); - - expect(signal?.aborted).toBe(true); - expect(onLoaded).not.toHaveBeenCalled(); }); }); diff --git a/src/components/ConfigStoreModal.tsx b/src/components/ConfigStoreModal.tsx index eb7bace..589b04a 100644 --- a/src/components/ConfigStoreModal.tsx +++ b/src/components/ConfigStoreModal.tsx @@ -45,6 +45,15 @@ interface ConfigStoreModalProps { }) => void; } +// What the modal is busy with. Save and every row's Load/Rename/Delete share +// this one slot, so only one runs at a time: a successful Load closes the +// modal, which would orphan anything running beside it. +type BusyOp = + | { kind: 'save' } + | { kind: 'load' | 'rename' | 'delete'; slug: string; label: string }; + +const BUSY_VERB = { load: 'Loading', rename: 'Renaming', delete: 'Deleting' } as const; + // One unpaginated page. Truncation is surfaced in the list header rather than // silently hidden; real paging is slaclab/react-trace#80. const PAGE_SIZE = 200; @@ -64,6 +73,11 @@ function shareUrl(slug: string): string { return url.toString(); } +// How a config is named in the status line and the delete confirmation. +function configLabel(config: ConfigDTO): string { + return config.name || config.slug; +} + function errText(err: unknown): string { return errorInfo(err).detail; } @@ -89,19 +103,36 @@ export function ConfigStoreModal({ }: ConfigStoreModalProps) { const [name, setName] = useState(''); const [description, setDescription] = useState(''); - const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [configs, setConfigs] = useState([]); const [totalCount, setTotalCount] = useState(null); const [listing, setListing] = useState(false); - // Slug currently undergoing a row action (delete/load), to disable its buttons. - const [busySlug, setBusySlug] = useState(null); - const [deleteTarget, setDeleteTarget] = useState(null); + + // The one operation in flight (see BusyOp). State drives the render; the ref + // gives handlers and the close guards the current value without waiting for a + // re-render, so a second click in the same tick can't also claim the slot. + const [busy, setBusyState] = useState(null); + const busyRef = useRef(null); + const setBusy = useCallback((op: BusyOp | null) => { + busyRef.current = op; + setBusyState(op); + }, []); + const saving = busy?.kind === 'save'; + const deleting = busy?.kind === 'delete'; + + // The config the delete confirmation is asking about. Its ref serves the + // close guards, like busyRef. + const [deleteTarget, setDeleteTargetState] = useState(null); + const deleteTargetRef = useRef(null); + const setDeleteTarget = useCallback((config: ConfigDTO | null) => { + deleteTargetRef.current = config; + setDeleteTargetState(config); + }, []); // The row button that opened the delete confirmation, to refocus on close. const deleteTriggerRef = useRef(null); const storeBodyRef = useRef(null); - const loadAbortRef = useRef(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 // could land last and overwrite the newer post-mutation list. Only the latest @@ -132,17 +163,82 @@ export function ConfigStoreModal({ } }, []); + // Each open of the modal is a session. Closing or unmounting ends it and + // aborts a pending Load, and an operation applies its result only while its + // session is current, so a dismissed Load can't replace the workspace after + // the dialog is gone. Save, Rename and Delete block dismissal until their + // server call settles, so their session ends before that only if the parent + // closes the modal itself or unmounts it. Their outcome is then dropped, apart + // from Save's toast, which also outlives a close during the share-link copy. + const sessionRef = useRef(0); + const loadAbortRef = useRef(null); + const endSession = useCallback(() => { + sessionRef.current++; + loadAbortRef.current?.abort(); + loadAbortRef.current = null; + }, []); + useEffect(() => endSession, [endSession]); + + // Load the list on open. Nothing resets the form or the slot here: TraceApp + // mounts the modal only while it's open, so each open starts from fresh state. useEffect(() => { - if (open) void Promise.resolve().then(refresh); - }, [open, refresh]); - - useEffect( - () => () => { - loadAbortRef.current?.abort(); - loadAbortRef.current = null; - }, - [] - ); + if (!open) { + endSession(); + return; + } + void Promise.resolve().then(refresh); + }, [open, refresh, endSession]); + + // Carbon's X, Escape and backdrop all call this; returning false keeps the + // dialog open. Save, Rename and Delete block dismissal until their server + // call settles: the change happens either way, so closing would only hide + // its outcome. So does an open delete confirmation. A Load doesn't block; + // closing cancels it. + // This must read refs, not render state. Carbon registers its Escape listener + // once per open and keeps the onClose from that render, when nothing was busy. + const onCloseRef = useRef(onClose); + useEffect(() => { + onCloseRef.current = onClose; + }, [onClose]); + const requestClose = useCallback(() => { + const op = busyRef.current; + if (op && op.kind !== 'load') return false; + if (deleteTargetRef.current) return false; + // The `!open` effect ends the session as well, but only once React has + // committed the close; ending it here leaves no gap for a response. + endSession(); + onCloseRef.current(); + }, [endSession]); + + // The delete confirmation's X, Escape and Cancel. It stays open while the + // Delete's server call runs, so a failure can show in it. Reads the slot's + // ref for the same reason as requestClose. Closing it drops that failure too, + // or the store's banner would show it for a Delete that was cancelled. + const requestCancelDelete = useCallback(() => { + if (busyRef.current?.kind === 'delete') return false; + setError(null); + setDeleteTarget(null); + }, [setDeleteTarget]); + + // Claim the slot for `op`. Returns the session it runs in, or null if `op` + // can't start now. + const begin = (op: BusyOp): number | null => { + if (busyRef.current) return null; + // While the delete confirmation is open, only its own Delete can start. The + // store's buttons behind it stay enabled, and an operation started there + // would show its error under the confirmation's "Could not delete config", + // and a Load would close the store, confirmation and all, on success. + if (deleteTargetRef.current && op.kind !== 'delete') return null; + setBusy(op); + setError(null); + return sessionRef.current; + }; + // Release the slot only if `op` still holds it: Save, Rename and Delete free + // it before their refresh or copy, so by their `finally` another operation + // may have claimed it. + const end = (op: BusyOp) => { + if (busyRef.current === op) setBusy(null); + }; // 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 @@ -163,98 +259,130 @@ export function ConfigStoreModal({ }, [deleteConfirmOpen]); const handleSave = async () => { - setSaving(true); - setError(null); + const op: BusyOp = { kind: 'save' }; + const session = begin(op); + if (session === null) return; try { const data = serializeConfigData({ theme, plots }); const dto = await saveConfig(data, { name: name.trim() || undefined, description: description.trim() || undefined, }); + // The server call has settled. Neither the refresh nor the clipboard write + // is part of the save, so neither holds the slot or blocks closing: a + // pending clipboard permission prompt would otherwise lock the dialog. + end(op); + // The form and the list belong to the session. + if (session === sessionRef.current) { + setName(''); + setDescription(''); + void refresh(); + } // Don't claim a copy that didn't happen: the clipboard API is absent on a // non-secure origin and rejects when permission is denied or the document - // isn't focused. Show the link itself so it can still be copied by hand. + // isn't focused. Show the link itself so it can still be copied by hand, + // in a toast that stays until it's dismissed. const link = shareUrl(dto.slug); const copied = await copyToClipboard(link); + // The toast goes out regardless, even if the dialog has closed since: the + // config exists and its link is useful. onToast({ kind: 'success', title: 'Workspace saved', subtitle: copied ? `Share link copied to clipboard (${dto.slug})` : `Share link: ${link}`, timeout: copied ? undefined : 0, }); - setName(''); - setDescription(''); - await refresh(); } catch (err) { - setError(errText(err)); + if (session === sessionRef.current) setError(errText(err)); } finally { - setSaving(false); + end(op); } }; - const handleLoad = async (slug: string) => { - loadAbortRef.current?.abort(); - const controller = new AbortController(); - loadAbortRef.current = controller; - setBusySlug(slug); - setError(null); + const handleLoad = async (config: ConfigDTO) => { + const op: BusyOp = { kind: 'load', slug: config.slug, label: configLabel(config) }; + const session = begin(op); + if (session === null) return; + const abort = new AbortController(); + loadAbortRef.current = abort; try { - const dto = await getConfig(slug, controller.signal); - if (controller.signal.aborted || loadAbortRef.current !== controller) return; + const dto = await getConfig(config.slug, abort.signal); + // Closing aborts the request, but the response may have arrived first. + if (session !== sessionRef.current) return; const result = deserializeConfigData(dto.data); onLoaded(result); onToast({ kind: 'success', title: 'Workspace loaded', subtitle: [ - dto.name ? `Loaded "${dto.name}"` : `Loaded config ${slug}`, + dto.name ? `Loaded "${dto.name}"` : `Loaded config ${config.slug}`, ...result.warnings, ].join('\n'), timeout: result.warnings.length > 0 ? 0 : undefined, }); - onClose(); + // Close the way X, Escape and the backdrop do. requestClose can't refuse + // here: this Load holds the slot, and begin() turns a Load away while the + // delete confirmation is open. + requestClose(); } catch (err) { - if (!controller.signal.aborted && loadAbortRef.current === controller) { - setError(errText(err)); - } + // A stale session also covers the AbortError from closing. + if (session === sessionRef.current) setError(errText(err)); } finally { - if (loadAbortRef.current === controller) { - loadAbortRef.current = null; - setBusySlug(null); - } + if (loadAbortRef.current === abort) loadAbortRef.current = null; + end(op); } }; const handleRename = async (config: ConfigDTO) => { + // Don't prompt for an action that can't start (see begin). + if (busyRef.current || deleteTargetRef.current) return; const next = window.prompt('Rename config', config.name ?? ''); if (next === null) return; // No-op a blank rename (Save likewise omits empty names) or an unchanged one. const trimmed = next.trim(); if (trimmed === '' || trimmed === (config.name ?? '')) return; - setBusySlug(config.slug); - setError(null); + const op: BusyOp = { kind: 'rename', slug: config.slug, label: configLabel(config) }; + const session = begin(op); + if (session === null) return; try { await updateConfig(config.slug, { name: trimmed }); + if (session !== sessionRef.current) return; + end(op); await refresh(); } catch (err) { - setError(errText(err)); + if (session === sessionRef.current) setError(errText(err)); } finally { - setBusySlug(null); + end(op); } }; - const handleDelete = async () => { - if (!deleteTarget) return; - setBusySlug(deleteTarget.slug); + // A row's Delete opens the confirmation; only its Delete button deletes. + const askDelete = (config: ConfigDTO, trigger: HTMLButtonElement) => { + // Don't ask about an action that can't start, or switch an open + // confirmation to another config. + if (busyRef.current || deleteTargetRef.current) return; + deleteTriggerRef.current = trigger; setError(null); + setDeleteTarget(config); + }; + + const handleDelete = async () => { + const config = deleteTargetRef.current; + if (!config) return; + const op: BusyOp = { kind: 'delete', slug: config.slug, label: configLabel(config) }; + const session = begin(op); + if (session === null) return; try { - await deleteConfig(deleteTarget.slug); + await deleteConfig(config.slug); + if (session !== sessionRef.current) return; setDeleteTarget(null); + end(op); await refresh(); } catch (err) { - setError(errText(err)); + // The confirmation stays open and shows it, so the Delete can be retried. + if (session === sessionRef.current) setError(errText(err)); } finally { - setBusySlug(null); + end(op); } }; @@ -271,11 +399,9 @@ export function ConfigStoreModal({ <> { - if (saving || deleteTarget) return false; - onClose(); - }} + onClose={requestClose} size="lg" + aria-label="Config store" selectorsFloatingMenus={[`.${DELETE_CONFIRM_CLASS}`]} > @@ -313,7 +439,7 @@ export function ConfigStoreModal({ rows={2} />
-
@@ -337,6 +463,10 @@ export function ConfigStoreModal({ onClick={() => void refresh()} disabled={listing} /> + {/* Save shows its progress on its own button. */} + {busy && busy.kind !== 'save' && ( + + )} {listing ? ( @@ -371,8 +501,8 @@ export function ConfigStoreModal({ @@ -380,7 +510,7 @@ export function ConfigStoreModal({ size="sm" kind="ghost" onClick={() => void handleRename(c)} - disabled={busySlug === c.slug} + disabled={busy !== null} > Rename @@ -398,12 +528,10 @@ export function ConfigStoreModal({ hasIconOnly iconDescription="Delete" renderIcon={TrashCan} - onClick={(e: React.MouseEvent) => { - deleteTriggerRef.current = e.currentTarget; - setError(null); - setDeleteTarget(c); - }} - disabled={busySlug === c.slug} + onClick={(e: React.MouseEvent) => + askDelete(c, e.currentTarget) + } + disabled={busy !== null} /> @@ -419,12 +547,10 @@ export function ConfigStoreModal({ { - if (deleteTarget && busySlug === deleteTarget.slug) return false; - setDeleteTarget(null); - }} + onClose={requestCancelDelete} size="sm" danger + aria-label="Delete config?" className={DELETE_CONFIRM_CLASS} > @@ -439,8 +565,8 @@ export function ConfigStoreModal({ )} {deleteTarget && (

- Delete {deleteTarget.name || deleteTarget.slug}? This will break any - shared links to it. This action cannot be undone. + Delete {configLabel(deleteTarget)}? This will break any shared links + to it. This action cannot be undone.

)} @@ -448,11 +574,9 @@ export function ConfigStoreModal({ { - if (busySlug !== deleteTarget.slug) setDeleteTarget(null); - }} + primaryButtonText={deleting ? 'Deleting…' : 'Delete'} + primaryButtonDisabled={deleting} + onRequestClose={requestCancelDelete} onRequestSubmit={() => void handleDelete()} > {null}