feat(delete): add undo toasts and harden delete modals

This commit is contained in:
Will Miao
2026-08-11 14:09:10 +08:00
parent eb0f6dd3b6
commit b2c68e6a65
27 changed files with 2555 additions and 51 deletions
@@ -123,6 +123,7 @@ vi.mock('../../../static/js/state/index.js', () => ({
vi.mock('../../../static/js/utils/modalUtils.js', () => ({
showExcludeModal: vi.fn(),
showDeleteModal: vi.fn(),
armDeleteButton: vi.fn(),
}));
vi.mock('../../../static/js/managers/MoveManager.js', () => ({
@@ -1,11 +1,18 @@
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
const showToastMock = vi.fn();
const showActionToastMock = vi.fn();
const handleUndoDeleteMock = vi.fn();
const recreateVirtualScrollMock = vi.fn();
const translateMock = vi.fn((key) => key);
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
showToast: showToastMock,
showActionToast: showActionToastMock,
}));
vi.mock('../../../static/js/utils/undoHelpers.js', () => ({
handleUndoDelete: handleUndoDeleteMock,
}));
vi.mock('../../../static/js/utils/i18nHelpers.js', () => ({
@@ -20,6 +27,17 @@ vi.mock('../../../static/js/components/RecipeCard.js', () => ({
},
}));
vi.mock('../../../static/js/utils/modalUtils.js', () => ({
armDeleteButton: (modalElement) => {
if (!modalElement) return null;
const buttons = modalElement.querySelectorAll('.delete-btn');
buttons.forEach((button) => { button.disabled = true; });
return setTimeout(() => {
buttons.forEach((button) => { button.disabled = false; });
}, 1500);
},
}));
vi.mock('../../../static/js/utils/infiniteScroll.js', () => ({
recreateVirtualScroll: recreateVirtualScrollMock,
}));
@@ -211,3 +229,152 @@ describe('DuplicatesManager prompt matching toggle', () => {
expect(document.getElementById('duplicatesBasis').textContent).toBe('recipes.duplicates.basis.loraCombo');
});
});
describe('DuplicatesManager confirmDeleteDuplicates undo flows', () => {
beforeEach(() => {
vi.clearAllMocks();
setCurrentPageType('recipes');
setupDom();
state.pendingLayoutRecreate = false;
state.virtualScroller = { enable: vi.fn(), disable: vi.fn() };
handleUndoDeleteMock.mockResolvedValue(true);
globalThis.modalManager = { showModal: vi.fn(), closeModal: vi.fn() };
globalThis.recipeManager = { loadRecipes: vi.fn() };
});
afterEach(() => {
state.pendingLayoutRecreate = false;
state.virtualScroller = null;
delete globalThis.modalManager;
delete globalThis.recipeManager;
delete globalThis.fetch;
});
function mockBulkDelete(payload) {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => payload,
});
}
function lastActionToastOptions() {
const call = showActionToastMock.mock.calls[showActionToastMock.mock.calls.length - 1];
return call[3];
}
it('shows the undo action toast with the batch id and reloads recipes on undo', async () => {
mockBulkDelete({ success: true, total_deleted: 2, batch_id: 'recipe-batch-1' });
const manager = new DuplicatesManager({});
manager.inDuplicateMode = true;
manager.selectedForDeletion.add('r1');
manager.selectedForDeletion.add('r2');
await manager.confirmDeleteDuplicates();
expect(showActionToastMock).toHaveBeenCalledTimes(1);
expect(showActionToastMock).toHaveBeenCalledWith(
'toast.undo.deletedBulk',
{ count: 2 },
'success',
expect.objectContaining({
actionText: 'toast.undo.action',
onAction: expect.any(Function),
})
);
// The legacy duplicates success toast is replaced, not duplicated
expect(showToastMock).not.toHaveBeenCalledWith(
'toast.duplicates.deleteSuccess',
expect.anything(),
expect.anything()
);
// exitDuplicateMode still runs for successful deletions
expect(manager.inDuplicateMode).toBe(false);
lastActionToastOptions().onAction();
expect(handleUndoDeleteMock).toHaveBeenCalledTimes(1);
expect(handleUndoDeleteMock).toHaveBeenCalledWith('recipe-batch-1', expect.any(Function));
const refreshFn = handleUndoDeleteMock.mock.calls[0][1];
refreshFn();
expect(globalThis.recipeManager.loadRecipes).toHaveBeenCalledWith(true);
});
it('undoes the batch_ids fallback sequentially with one final refresh and restored toast', async () => {
mockBulkDelete({ success: true, total_deleted: 2, batch_ids: ['rb-1', 'rb-2'] });
const manager = new DuplicatesManager({});
manager.inDuplicateMode = true;
manager.selectedForDeletion.add('r1');
manager.selectedForDeletion.add('r2');
await manager.confirmDeleteDuplicates();
expect(showActionToastMock).toHaveBeenCalledTimes(1);
await lastActionToastOptions().onAction();
expect(handleUndoDeleteMock).toHaveBeenCalledTimes(2);
expect(handleUndoDeleteMock.mock.calls[0]).toEqual(['rb-1', null, { showToast: false, refresh: false }]);
expect(handleUndoDeleteMock.mock.calls[1]).toEqual(['rb-2', null, { showToast: false, refresh: false }]);
expect(globalThis.recipeManager.loadRecipes).toHaveBeenCalledTimes(1);
expect(globalThis.recipeManager.loadRecipes).toHaveBeenCalledWith(true);
expect(showToastMock).toHaveBeenCalledTimes(1);
expect(showToastMock).toHaveBeenCalledWith('toast.undo.restored', {}, 'success');
});
it('keeps the legacy success toast when the response carries no batch field', async () => {
mockBulkDelete({ success: true, total_deleted: 1 });
const manager = new DuplicatesManager({});
manager.inDuplicateMode = true;
manager.selectedForDeletion.add('r1');
await manager.confirmDeleteDuplicates();
expect(showActionToastMock).not.toHaveBeenCalled();
expect(showToastMock).toHaveBeenCalledWith(
'toast.duplicates.deleteSuccess',
{ count: 1, type: 'recipes' },
'success'
);
});
});
describe('DuplicatesManager deleteSelectedDuplicates delay-activate', () => {
beforeEach(() => {
vi.useFakeTimers();
setCurrentPageType('recipes');
setupDom();
document.body.insertAdjacentHTML('beforeend', `
<div id="duplicateDeleteModal" class="modal delete-modal">
<div class="delete-model-info"><p><span id="duplicateDeleteCount">0</span></p></div>
<button class="cancel-btn">Cancel</button>
<button class="delete-btn">Delete</button>
</div>
`);
globalThis.modalManager = { showModal: vi.fn(), closeModal: vi.fn() };
});
afterEach(() => {
vi.useRealTimers();
delete globalThis.modalManager;
});
it('opens with the delete button disabled and enables it after 1500ms', async () => {
const manager = new DuplicatesManager({});
manager.selectedForDeletion.add('r1');
await manager.deleteSelectedDuplicates();
expect(globalThis.modalManager.showModal).toHaveBeenCalledWith('duplicateDeleteModal');
const deleteBtn = document.querySelector('#duplicateDeleteModal .delete-btn');
expect(deleteBtn.disabled).toBe(true);
deleteBtn.click();
expect(deleteBtn.disabled).toBe(true);
vi.advanceTimersByTime(1500);
expect(deleteBtn.disabled).toBe(false);
});
});
@@ -1,16 +1,34 @@
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
const showToastMock = vi.fn();
const showActionToastMock = vi.fn();
const handleUndoDeleteMock = vi.fn();
const resetAndReloadMock = vi.fn();
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
showToast: showToastMock,
showActionToast: showActionToastMock,
}));
vi.mock('../../../static/js/utils/undoHelpers.js', () => ({
handleUndoDelete: handleUndoDeleteMock,
}));
vi.mock('../../../static/js/api/modelApiFactory.js', () => ({
resetAndReload: resetAndReloadMock,
}));
vi.mock('../../../static/js/utils/modalUtils.js', () => ({
armDeleteButton: (modalElement) => {
if (!modalElement) return null;
const buttons = modalElement.querySelectorAll('.delete-btn');
buttons.forEach((button) => { button.disabled = true; });
return setTimeout(() => {
buttons.forEach((button) => { button.disabled = false; });
}, 1500);
},
}));
const { ModelDuplicatesManager } = await import('../../../static/js/components/ModelDuplicatesManager.js');
const { state } = await import('../../../static/js/state/index.js');
@@ -230,3 +248,153 @@ describe('ModelDuplicatesManager verification state', () => {
expect(manager.verifiedGroups.has('visible-hash')).toBe(true);
});
});
describe('ModelDuplicatesManager confirmDeleteDuplicates undo flows', () => {
function mockDeleteAndRecheck(deletePayload) {
global.fetch = vi.fn((url) => {
if (String(url).includes('bulk-delete')) {
return Promise.resolve({
ok: true,
statusText: 'OK',
json: async () => deletePayload,
});
}
return Promise.resolve({
ok: true,
statusText: 'OK',
json: async () => ({ success: true, duplicates: [] }),
});
});
}
function lastActionToastOptions() {
const call = showActionToastMock.mock.calls[showActionToastMock.mock.calls.length - 1];
return call[3];
}
beforeEach(() => {
handleUndoDeleteMock.mockResolvedValue(true);
state.virtualScroller = { enable: vi.fn(), disable: vi.fn() };
globalThis.modalManager = { showModal: vi.fn(), closeModal: vi.fn() };
});
afterEach(() => {
state.virtualScroller = null;
delete globalThis.modalManager;
});
it('shows the undo action toast with the batch id and refreshes models on undo', async () => {
const manager = await createManager();
mockDeleteAndRecheck({ success: true, total_deleted: 1, batch_id: 'model-batch-1' });
manager.inDuplicateMode = true;
manager.selectedForDeletion.add(carPath);
await manager.confirmDeleteDuplicates();
expect(showActionToastMock).toHaveBeenCalledTimes(1);
expect(showActionToastMock).toHaveBeenCalledWith(
'toast.undo.deletedBulk',
{ count: 1 },
'success',
expect.objectContaining({
actionText: 'toast.undo.action',
onAction: expect.any(Function),
})
);
expect(showToastMock).not.toHaveBeenCalledWith(
'toast.duplicates.deleteSuccess',
expect.anything(),
expect.anything()
);
// The existing reset + find-duplicates re-check path still runs
expect(resetAndReloadMock).toHaveBeenCalledWith(true);
// No remaining duplicates -> duplicate mode exited
expect(manager.inDuplicateMode).toBe(false);
lastActionToastOptions().onAction();
expect(handleUndoDeleteMock).toHaveBeenCalledTimes(1);
expect(handleUndoDeleteMock).toHaveBeenCalledWith('model-batch-1', expect.any(Function));
const refreshFn = handleUndoDeleteMock.mock.calls[0][1];
resetAndReloadMock.mockClear();
refreshFn();
expect(resetAndReloadMock).toHaveBeenCalledTimes(1);
expect(resetAndReloadMock).toHaveBeenCalledWith(true);
});
it('undoes the batch_ids fallback sequentially with one final refresh and restored toast', async () => {
const manager = await createManager();
mockDeleteAndRecheck({ success: true, total_deleted: 2, batch_ids: ['mb-1', 'mb-2'] });
manager.inDuplicateMode = true;
manager.selectedForDeletion.add(carPath);
manager.selectedForDeletion.add(copyPath);
await manager.confirmDeleteDuplicates();
expect(showActionToastMock).toHaveBeenCalledTimes(1);
resetAndReloadMock.mockClear();
await lastActionToastOptions().onAction();
expect(handleUndoDeleteMock).toHaveBeenCalledTimes(2);
expect(handleUndoDeleteMock.mock.calls[0]).toEqual(['mb-1', null, { showToast: false, refresh: false }]);
expect(handleUndoDeleteMock.mock.calls[1]).toEqual(['mb-2', null, { showToast: false, refresh: false }]);
expect(resetAndReloadMock).toHaveBeenCalledTimes(1);
expect(resetAndReloadMock).toHaveBeenCalledWith(true);
expect(showToastMock).toHaveBeenCalledTimes(1);
expect(showToastMock).toHaveBeenCalledWith('toast.undo.restored', {}, 'success');
});
it('keeps the legacy success toast when the response carries no batch field', async () => {
const manager = await createManager();
mockDeleteAndRecheck({ success: true, total_deleted: 1 });
manager.inDuplicateMode = true;
manager.selectedForDeletion.add(carPath);
await manager.confirmDeleteDuplicates();
expect(showActionToastMock).not.toHaveBeenCalled();
expect(showToastMock).toHaveBeenCalledWith(
'toast.duplicates.deleteSuccess',
{ count: 1, type: 'loras' },
'success'
);
});
});
describe('ModelDuplicatesManager deleteSelectedDuplicates delay-activate', () => {
beforeEach(() => {
vi.useFakeTimers();
globalThis.modalManager = { showModal: vi.fn(), closeModal: vi.fn() };
});
afterEach(() => {
vi.useRealTimers();
delete globalThis.modalManager;
});
it('opens with the delete button disabled and enables it after 1500ms', async () => {
const manager = await createManager();
document.body.insertAdjacentHTML('beforeend', `
<div id="modelDuplicateDeleteModal" class="modal delete-modal">
<div class="delete-model-info"><p><span id="modelDuplicateDeleteCount">0</span></p></div>
<button class="cancel-btn">Cancel</button>
<button class="delete-btn">Delete</button>
</div>
`);
manager.selectedForDeletion.add(carPath);
await manager.deleteSelectedDuplicates();
expect(globalThis.modalManager.showModal).toHaveBeenCalledWith('modelDuplicateDeleteModal');
const deleteBtn = document.querySelector('#modelDuplicateDeleteModal .delete-btn');
expect(deleteBtn.disabled).toBe(true);
vi.advanceTimersByTime(1500);
expect(deleteBtn.disabled).toBe(false);
});
});
@@ -0,0 +1,191 @@
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
const {
RECIPE_CARD_MODULE,
UI_HELPERS_MODULE,
RECIPE_API_MODULE,
MODEL_CARD_MODULE,
MODAL_MANAGER_MODULE,
STATE_MODULE,
BULK_MANAGER_MODULE,
CONSTANTS_MODULE,
I18N_MODULE,
UNDO_HELPERS_MODULE,
} = vi.hoisted(() => ({
RECIPE_CARD_MODULE: new URL('../../../static/js/components/RecipeCard.js', import.meta.url).pathname,
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
RECIPE_API_MODULE: new URL('../../../static/js/api/recipeApi.js', import.meta.url).pathname,
MODEL_CARD_MODULE: new URL('../../../static/js/components/shared/ModelCard.js', import.meta.url).pathname,
MODAL_MANAGER_MODULE: new URL('../../../static/js/managers/ModalManager.js', import.meta.url).pathname,
STATE_MODULE: new URL('../../../static/js/state/index.js', import.meta.url).pathname,
BULK_MANAGER_MODULE: new URL('../../../static/js/managers/BulkManager.js', import.meta.url).pathname,
CONSTANTS_MODULE: new URL('../../../static/js/utils/constants.js', import.meta.url).pathname,
I18N_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
UNDO_HELPERS_MODULE: new URL('../../../static/js/utils/undoHelpers.js', import.meta.url).pathname,
}));
const showToastMock = vi.fn();
const showActionToastMock = vi.fn();
const handleUndoDeleteMock = vi.fn();
const translateMock = vi.fn((key) => key);
const closeModalMock = vi.fn();
const removeItemByFilePathMock = vi.fn();
vi.mock(UI_HELPERS_MODULE, () => ({
showToast: showToastMock,
showActionToast: showActionToastMock,
copyToClipboard: vi.fn(),
sendLoraToWorkflow: vi.fn(),
}));
vi.mock(RECIPE_API_MODULE, () => ({
updateRecipeMetadata: vi.fn(),
}));
vi.mock(MODEL_CARD_MODULE, () => ({
configureModelCardVideo: vi.fn(),
}));
vi.mock(MODAL_MANAGER_MODULE, () => ({
modalManager: {
showModal: vi.fn(),
closeModal: closeModalMock,
},
}));
vi.mock(STATE_MODULE, () => ({
state: {
virtualScroller: {
removeItemByFilePath: removeItemByFilePathMock,
},
},
getCurrentPageState: vi.fn(() => ({})),
}));
vi.mock(BULK_MANAGER_MODULE, () => ({
bulkManager: {},
}));
vi.mock(CONSTANTS_MODULE, () => ({
NSFW_LEVELS: {},
getBaseModelAbbreviation: vi.fn(),
getMatureBlurThreshold: vi.fn(),
}));
vi.mock(I18N_MODULE, () => ({
translate: translateMock,
}));
vi.mock(UNDO_HELPERS_MODULE, () => ({
handleUndoDelete: handleUndoDeleteMock,
}));
function setupDeleteModal() {
document.body.innerHTML = `
<div id="deleteModal" data-recipe-id="recipe-1" data-file-path="/recipes/r1.json">
<button class="delete-btn">Delete</button>
</div>
`;
const deleteModal = document.getElementById('deleteModal');
// jsdom maps data-file-path to dataset.filePath
deleteModal.dataset.recipeId = 'recipe-1';
deleteModal.dataset.filePath = '/recipes/r1.json';
return deleteModal;
}
async function flushPromises() {
await new Promise((resolve) => setTimeout(resolve, 0));
}
describe('RecipeCard confirmDeleteRecipe undo flow', () => {
beforeEach(() => {
showToastMock.mockReset();
showActionToastMock.mockReset();
handleUndoDeleteMock.mockReset();
translateMock.mockClear();
closeModalMock.mockReset();
removeItemByFilePathMock.mockReset();
setupDeleteModal();
window.recipeManager = { loadRecipes: vi.fn() };
});
afterEach(() => {
delete global.fetch;
delete window.recipeManager;
document.body.innerHTML = '';
});
async function createCard() {
const { RecipeCard } = await import(RECIPE_CARD_MODULE);
const card = Object.create(RecipeCard.prototype);
card.recipe = { id: 'recipe-1', title: 'My Recipe', file_path: '/recipes/r1.json' };
return card;
}
it('shows the undo action toast and wires undo to handleUndoDelete + loadRecipes(true)', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true, message: 'deleted', batch_id: 'recipe-batch-1' }),
});
const card = await createCard();
card.confirmDeleteRecipe();
await flushPromises();
expect(global.fetch).toHaveBeenCalledWith('/api/lm/recipe/recipe-1', expect.objectContaining({
method: 'DELETE',
}));
// No legacy success toast when the delete was staged
expect(showToastMock).not.toHaveBeenCalledWith('toast.recipes.deletedSuccessfully', {}, 'success');
expect(showActionToastMock).toHaveBeenCalledTimes(1);
const [key, params, type, options] = showActionToastMock.mock.calls[0];
expect(key).toBe('toast.undo.deleted');
expect(params).toEqual({ name: 'My Recipe' });
expect(type).toBe('success');
expect(options.actionText).toBe('toast.undo.action');
options.onAction();
expect(handleUndoDeleteMock).toHaveBeenCalledTimes(1);
const [batchId, refreshFn] = handleUndoDeleteMock.mock.calls[0];
expect(batchId).toBe('recipe-batch-1');
refreshFn();
expect(window.recipeManager.loadRecipes).toHaveBeenCalledWith(true);
expect(removeItemByFilePathMock).toHaveBeenCalledWith('/recipes/r1.json');
expect(closeModalMock).toHaveBeenCalledWith('deleteModal');
});
it('keeps the legacy success toast when the delete was not staged', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true, message: 'deleted' }),
});
const card = await createCard();
card.confirmDeleteRecipe();
await flushPromises();
expect(showToastMock).toHaveBeenCalledWith('toast.recipes.deletedSuccessfully', {}, 'success');
expect(showActionToastMock).not.toHaveBeenCalled();
expect(closeModalMock).toHaveBeenCalledWith('deleteModal');
});
it('shows the failure toast when the server rejects the delete', async () => {
global.fetch = vi.fn().mockResolvedValue({ ok: false });
const card = await createCard();
const deleteBtn = document.querySelector('.delete-btn');
card.confirmDeleteRecipe();
await flushPromises();
expect(showToastMock).toHaveBeenCalledWith(
'toast.recipes.deleteFailed',
expect.objectContaining({ message: expect.any(String) }),
'error'
);
expect(deleteBtn.disabled).toBe(false);
expect(deleteBtn.textContent).toBe('Delete');
});
});
@@ -0,0 +1,160 @@
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
const {
RECIPE_CARD_MODULE,
UI_HELPERS_MODULE,
RECIPE_API_MODULE,
MODEL_CARD_MODULE,
MODAL_MANAGER_MODULE,
BULK_MANAGER_MODULE,
I18N_MODULE,
UNDO_HELPERS_MODULE,
API_FACTORY_MODULE,
STATE_MODULE,
} = vi.hoisted(() => ({
RECIPE_CARD_MODULE: new URL('../../../static/js/components/RecipeCard.js', import.meta.url).pathname,
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
RECIPE_API_MODULE: new URL('../../../static/js/api/recipeApi.js', import.meta.url).pathname,
MODEL_CARD_MODULE: new URL('../../../static/js/components/shared/ModelCard.js', import.meta.url).pathname,
MODAL_MANAGER_MODULE: new URL('../../../static/js/managers/ModalManager.js', import.meta.url).pathname,
BULK_MANAGER_MODULE: new URL('../../../static/js/managers/BulkManager.js', import.meta.url).pathname,
I18N_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
UNDO_HELPERS_MODULE: new URL('../../../static/js/utils/undoHelpers.js', import.meta.url).pathname,
API_FACTORY_MODULE: new URL('../../../static/js/api/modelApiFactory.js', import.meta.url).pathname,
STATE_MODULE: new URL('../../../static/js/state/index.js', import.meta.url).pathname,
}));
const showModalMock = vi.fn();
const closeModalMock = vi.fn();
vi.mock(UI_HELPERS_MODULE, () => ({
showToast: vi.fn(),
showActionToast: vi.fn(),
copyToClipboard: vi.fn(),
sendLoraToWorkflow: vi.fn(),
}));
vi.mock(RECIPE_API_MODULE, () => ({
updateRecipeMetadata: vi.fn(),
}));
vi.mock(MODEL_CARD_MODULE, () => ({
configureModelCardVideo: vi.fn(),
}));
vi.mock(MODAL_MANAGER_MODULE, () => ({
modalManager: {
showModal: showModalMock,
closeModal: closeModalMock,
},
}));
vi.mock(BULK_MANAGER_MODULE, () => ({
bulkManager: {},
}));
vi.mock(I18N_MODULE, () => ({
translate: vi.fn((key) => key),
}));
vi.mock(UNDO_HELPERS_MODULE, () => ({
handleUndoDelete: vi.fn(),
}));
// modalUtils.js is intentionally NOT mocked — its real armDeleteButton drives
// the delay-activate behavior under test. Its own imports are mocked below.
vi.mock(API_FACTORY_MODULE, () => ({
getModelApiClient: vi.fn(),
resetAndReload: vi.fn(),
}));
describe('RecipeCard delete confirmation delay-activate', () => {
let capturedOnClose;
beforeEach(async () => {
vi.useFakeTimers();
showModalMock.mockReset();
closeModalMock.mockReset();
capturedOnClose = null;
document.body.innerHTML = '<div id="deleteModal" class="modal delete-modal"></div>';
showModalMock.mockImplementation((id, content, onClose) => {
if (content) {
document.getElementById(id).innerHTML = content;
}
capturedOnClose = onClose;
});
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
});
window.recipeManager = { loadRecipes: vi.fn() };
const { state } = await import(STATE_MODULE);
state.virtualScroller = { removeItemByFilePath: vi.fn() };
});
afterEach(() => {
vi.useRealTimers();
delete global.fetch;
delete window.recipeManager;
document.body.innerHTML = '';
});
async function createCard() {
const { RecipeCard } = await import(RECIPE_CARD_MODULE);
const card = Object.create(RecipeCard.prototype);
card.recipe = { id: 'recipe-1', title: 'My Recipe', file_path: '/recipes/r1.json', file_url: '/preview.png' };
return card;
}
it('opens with a disabled delete button that ignores clicks until 1500ms elapse', async () => {
const card = await createCard();
card.showDeleteConfirmation();
const deleteBtn = document.querySelector('#deleteModal .delete-btn');
expect(deleteBtn.disabled).toBe(true);
deleteBtn.click();
expect(global.fetch).not.toHaveBeenCalled();
vi.advanceTimersByTime(1500);
expect(deleteBtn.disabled).toBe(false);
deleteBtn.click();
expect(global.fetch).toHaveBeenCalledWith(
'/api/lm/recipe/recipe-1',
expect.objectContaining({ method: 'DELETE' })
);
});
it('clears the pending arm timer when the modal closes during the countdown', async () => {
const card = await createCard();
card.showDeleteConfirmation();
const deleteBtn = document.querySelector('#deleteModal .delete-btn');
expect(deleteBtn.disabled).toBe(true);
vi.advanceTimersByTime(700);
capturedOnClose();
expect(deleteBtn.disabled).toBe(false);
expect(vi.getTimerCount()).toBe(0);
});
it('re-arms a full 1500ms countdown when the modal is reopened', async () => {
const card = await createCard();
card.showDeleteConfirmation();
vi.advanceTimersByTime(1400);
capturedOnClose();
card.showDeleteConfirmation();
const deleteBtn = document.querySelector('#deleteModal .delete-btn');
expect(deleteBtn.disabled).toBe(true);
vi.advanceTimersByTime(1499);
expect(deleteBtn.disabled).toBe(true);
vi.advanceTimersByTime(1);
expect(deleteBtn.disabled).toBe(false);
});
});