diff options
| author | nsfisis <nsfisis@gmail.com> | 2025-12-07 18:33:16 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2025-12-07 18:33:16 +0900 |
| commit | c2609af9d8bac65d3e70b3860160ac8bfe097241 (patch) | |
| tree | b6c2968188fd7e4a54451c2c5ba330a04dc3e8c0 | |
| parent | 858178d6878229c0ac413d3ea5a4f799d6114ecb (diff) | |
| download | kioku-c2609af9d8bac65d3e70b3860160ac8bfe097241.tar.gz kioku-c2609af9d8bac65d3e70b3860160ac8bfe097241.tar.zst kioku-c2609af9d8bac65d3e70b3860160ac8bfe097241.zip | |
feat(client): add delete card modal with confirmation
Completes Phase 5 card management by adding the ability to delete cards
with a confirmation dialog. Includes unit tests for the modal component
and integration tests for the delete flow in DeckDetailPage.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
| -rw-r--r-- | docs/dev/roadmap.md | 4 | ||||
| -rw-r--r-- | src/client/components/DeleteCardModal.test.tsx | 286 | ||||
| -rw-r--r-- | src/client/components/DeleteCardModal.tsx | 161 | ||||
| -rw-r--r-- | src/client/pages/DeckDetailPage.test.tsx | 203 | ||||
| -rw-r--r-- | src/client/pages/DeckDetailPage.tsx | 45 |
5 files changed, 691 insertions, 8 deletions
diff --git a/docs/dev/roadmap.md b/docs/dev/roadmap.md index 7552761..76e016a 100644 --- a/docs/dev/roadmap.md +++ b/docs/dev/roadmap.md @@ -106,8 +106,8 @@ Smaller features first to enable early MVP validation. - [x] Card list view (in deck detail page) - [x] Create card form (front/back) - [x] Edit card -- [ ] Delete card -- [ ] Add tests +- [x] Delete card +- [x] Add tests **✅ Milestone**: Users can create and manage cards diff --git a/src/client/components/DeleteCardModal.test.tsx b/src/client/components/DeleteCardModal.test.tsx new file mode 100644 index 0000000..4178ee8 --- /dev/null +++ b/src/client/components/DeleteCardModal.test.tsx @@ -0,0 +1,286 @@ +/** + * @vitest-environment jsdom + */ +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { apiClient } from "../api/client"; + +vi.mock("../api/client", () => ({ + apiClient: { + getAuthHeader: vi.fn(), + }, + ApiClientError: class ApiClientError extends Error { + constructor( + message: string, + public status: number, + public code?: string, + ) { + super(message); + this.name = "ApiClientError"; + } + }, +})); + +// Import after mock is set up +import { DeleteCardModal } from "./DeleteCardModal"; + +// Mock fetch globally +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +describe("DeleteCardModal", () => { + const mockCard = { + id: "card-123", + front: "Test Question", + }; + + const defaultProps = { + isOpen: true, + deckId: "deck-456", + card: mockCard, + onClose: vi.fn(), + onCardDeleted: vi.fn(), + }; + + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(apiClient.getAuthHeader).mockReturnValue({ + Authorization: "Bearer access-token", + }); + }); + + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + it("does not render when closed", () => { + render(<DeleteCardModal {...defaultProps} isOpen={false} />); + + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("does not render when card is null", () => { + render(<DeleteCardModal {...defaultProps} card={null} />); + + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("renders modal when open with card", () => { + render(<DeleteCardModal {...defaultProps} />); + + expect(screen.getByRole("dialog")).toBeDefined(); + expect(screen.getByRole("heading", { name: "Delete Card" })).toBeDefined(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeDefined(); + expect(screen.getByRole("button", { name: "Delete" })).toBeDefined(); + }); + + it("displays confirmation message with card front text", () => { + render(<DeleteCardModal {...defaultProps} />); + + expect(screen.getByText(/Are you sure you want to delete/)).toBeDefined(); + expect(screen.getByText(/"Test Question"/)).toBeDefined(); + }); + + it("truncates long front text in confirmation message", () => { + const longFrontCard = { + id: "card-123", + front: + "This is a very long question that should be truncated when displayed in the confirmation modal", + }; + render(<DeleteCardModal {...defaultProps} card={longFrontCard} />); + + expect( + screen.getByText( + /"This is a very long question that should be trunca.../, + ), + ).toBeDefined(); + }); + + it("displays warning about permanent deletion", () => { + render(<DeleteCardModal {...defaultProps} />); + + expect(screen.getByText(/This action cannot be undone/)).toBeDefined(); + }); + + it("calls onClose when Cancel is clicked", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + render(<DeleteCardModal {...defaultProps} onClose={onClose} />); + + await user.click(screen.getByRole("button", { name: "Cancel" })); + + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it("calls onClose when clicking outside the modal", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + render(<DeleteCardModal {...defaultProps} onClose={onClose} />); + + // Click on the backdrop (the dialog element itself) + const dialog = screen.getByRole("dialog"); + await user.click(dialog); + + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it("does not call onClose when clicking inside the modal content", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + render(<DeleteCardModal {...defaultProps} onClose={onClose} />); + + // Click on the heading inside the modal + await user.click(screen.getByRole("heading", { name: "Delete Card" })); + + expect(onClose).not.toHaveBeenCalled(); + }); + + it("deletes card when Delete is clicked", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + const onCardDeleted = vi.fn(); + + mockFetch.mockResolvedValue({ + ok: true, + json: async () => ({}), + }); + + render( + <DeleteCardModal + isOpen={true} + deckId="deck-456" + card={mockCard} + onClose={onClose} + onCardDeleted={onCardDeleted} + />, + ); + + await user.click(screen.getByRole("button", { name: "Delete" })); + + await waitFor(() => { + expect(mockFetch).toHaveBeenCalledWith( + "/api/decks/deck-456/cards/card-123", + { + method: "DELETE", + headers: { + Authorization: "Bearer access-token", + }, + }, + ); + }); + + expect(onCardDeleted).toHaveBeenCalledTimes(1); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it("shows loading state during deletion", async () => { + const user = userEvent.setup(); + + mockFetch.mockImplementation(() => new Promise(() => {})); // Never resolves + + render(<DeleteCardModal {...defaultProps} />); + + await user.click(screen.getByRole("button", { name: "Delete" })); + + expect(screen.getByRole("button", { name: "Deleting..." })).toBeDefined(); + expect(screen.getByRole("button", { name: "Deleting..." })).toHaveProperty( + "disabled", + true, + ); + expect(screen.getByRole("button", { name: "Cancel" })).toHaveProperty( + "disabled", + true, + ); + }); + + it("displays API error message", async () => { + const user = userEvent.setup(); + + mockFetch.mockResolvedValue({ + ok: false, + status: 404, + json: async () => ({ error: "Card not found" }), + }); + + render(<DeleteCardModal {...defaultProps} />); + + await user.click(screen.getByRole("button", { name: "Delete" })); + + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain("Card not found"); + }); + }); + + it("displays generic error on unexpected failure", async () => { + const user = userEvent.setup(); + + mockFetch.mockRejectedValue(new Error("Network error")); + + render(<DeleteCardModal {...defaultProps} />); + + await user.click(screen.getByRole("button", { name: "Delete" })); + + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain( + "Failed to delete card. Please try again.", + ); + }); + }); + + it("displays error when not authenticated", async () => { + const user = userEvent.setup(); + + vi.mocked(apiClient.getAuthHeader).mockReturnValue(undefined); + + render(<DeleteCardModal {...defaultProps} />); + + await user.click(screen.getByRole("button", { name: "Delete" })); + + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain( + "Not authenticated", + ); + }); + }); + + it("clears error when modal is closed", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + + mockFetch.mockResolvedValue({ + ok: false, + status: 404, + json: async () => ({ error: "Some error" }), + }); + + const { rerender } = render( + <DeleteCardModal {...defaultProps} onClose={onClose} />, + ); + + // Trigger error + await user.click(screen.getByRole("button", { name: "Delete" })); + await waitFor(() => { + expect(screen.getByRole("alert")).toBeDefined(); + }); + + // Close and reopen the modal + await user.click(screen.getByRole("button", { name: "Cancel" })); + rerender(<DeleteCardModal {...defaultProps} onClose={onClose} />); + + // Error should be cleared + expect(screen.queryByRole("alert")).toBeNull(); + }); + + it("displays card front correctly when card changes", () => { + const { rerender } = render(<DeleteCardModal {...defaultProps} />); + + expect(screen.getByText(/"Test Question"/)).toBeDefined(); + + const newCard = { id: "card-789", front: "Another Question" }; + rerender(<DeleteCardModal {...defaultProps} card={newCard} />); + + expect(screen.getByText(/"Another Question"/)).toBeDefined(); + }); +}); diff --git a/src/client/components/DeleteCardModal.tsx b/src/client/components/DeleteCardModal.tsx new file mode 100644 index 0000000..99abbd0 --- /dev/null +++ b/src/client/components/DeleteCardModal.tsx @@ -0,0 +1,161 @@ +import { useState } from "react"; +import { ApiClientError, apiClient } from "../api"; + +interface Card { + id: string; + front: string; +} + +interface DeleteCardModalProps { + isOpen: boolean; + deckId: string; + card: Card | null; + onClose: () => void; + onCardDeleted: () => void; +} + +export function DeleteCardModal({ + isOpen, + deckId, + card, + onClose, + onCardDeleted, +}: DeleteCardModalProps) { + const [error, setError] = useState<string | null>(null); + const [isDeleting, setIsDeleting] = useState(false); + + const handleClose = () => { + setError(null); + onClose(); + }; + + const handleDelete = async () => { + if (!card) return; + + setError(null); + setIsDeleting(true); + + try { + const authHeader = apiClient.getAuthHeader(); + if (!authHeader) { + throw new ApiClientError("Not authenticated", 401); + } + + const res = await fetch(`/api/decks/${deckId}/cards/${card.id}`, { + method: "DELETE", + headers: authHeader, + }); + + if (!res.ok) { + const errorBody = await res.json().catch(() => ({})); + throw new ApiClientError( + (errorBody as { error?: string }).error || + `Request failed with status ${res.status}`, + res.status, + ); + } + + onCardDeleted(); + onClose(); + } catch (err) { + if (err instanceof ApiClientError) { + setError(err.message); + } else { + setError("Failed to delete card. Please try again."); + } + } finally { + setIsDeleting(false); + } + }; + + if (!isOpen || !card) { + return null; + } + + // Truncate front text for display if too long + const displayFront = + card.front.length > 50 ? `${card.front.slice(0, 50)}...` : card.front; + + return ( + <div + role="dialog" + aria-modal="true" + aria-labelledby="delete-card-title" + style={{ + position: "fixed", + top: 0, + left: 0, + right: 0, + bottom: 0, + backgroundColor: "rgba(0, 0, 0, 0.5)", + display: "flex", + alignItems: "center", + justifyContent: "center", + zIndex: 1000, + }} + onClick={(e) => { + if (e.target === e.currentTarget) { + handleClose(); + } + }} + onKeyDown={(e) => { + if (e.key === "Escape") { + handleClose(); + } + }} + > + <div + style={{ + backgroundColor: "white", + padding: "1.5rem", + borderRadius: "8px", + width: "100%", + maxWidth: "400px", + margin: "1rem", + }} + > + <h2 id="delete-card-title" style={{ marginTop: 0 }}> + Delete Card + </h2> + + {error && ( + <div role="alert" style={{ color: "red", marginBottom: "1rem" }}> + {error} + </div> + )} + + <p>Are you sure you want to delete this card?</p> + <p style={{ color: "#666", fontStyle: "italic" }}>"{displayFront}"</p> + <p style={{ color: "#666" }}>This action cannot be undone.</p> + + <div + style={{ + display: "flex", + gap: "0.5rem", + justifyContent: "flex-end", + marginTop: "1.5rem", + }} + > + <button type="button" onClick={handleClose} disabled={isDeleting}> + Cancel + </button> + <button + type="button" + onClick={handleDelete} + disabled={isDeleting} + style={{ + backgroundColor: "#dc3545", + color: "white", + border: "none", + padding: "0.5rem 1rem", + borderRadius: "4px", + cursor: isDeleting ? "not-allowed" : "pointer", + }} + > + {isDeleting ? "Deleting..." : "Delete"} + </button> + </div> + </div> + </div> + ); +} diff --git a/src/client/pages/DeckDetailPage.test.tsx b/src/client/pages/DeckDetailPage.test.tsx index de22b08..0589073 100644 --- a/src/client/pages/DeckDetailPage.test.tsx +++ b/src/client/pages/DeckDetailPage.test.tsx @@ -372,4 +372,207 @@ describe("DeckDetailPage", () => { // No description should be shown expect(screen.queryByText("Common Japanese words")).toBeNull(); }); + + describe("Delete Card", () => { + it("shows Delete button for each card", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Hello")).toBeDefined(); + }); + + const deleteButtons = screen.getAllByRole("button", { name: "Delete" }); + expect(deleteButtons.length).toBe(2); + }); + + it("opens delete confirmation modal when Delete button is clicked", async () => { + const user = userEvent.setup(); + + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Hello")).toBeDefined(); + }); + + const deleteButtons = screen.getAllByRole("button", { name: "Delete" }); + const firstDeleteButton = deleteButtons[0]; + if (firstDeleteButton) { + await user.click(firstDeleteButton); + } + + expect(screen.getByRole("dialog")).toBeDefined(); + expect( + screen.getByRole("heading", { name: "Delete Card" }), + ).toBeDefined(); + }); + + it("closes delete modal when Cancel is clicked", async () => { + const user = userEvent.setup(); + + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Hello")).toBeDefined(); + }); + + const deleteButtons = screen.getAllByRole("button", { name: "Delete" }); + const firstDeleteButton = deleteButtons[0]; + if (firstDeleteButton) { + await user.click(firstDeleteButton); + } + + expect(screen.getByRole("dialog")).toBeDefined(); + + await user.click(screen.getByRole("button", { name: "Cancel" })); + + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("deletes card and refreshes list on confirmation", async () => { + const user = userEvent.setup(); + + mockFetch + // Initial load + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }) + // Delete request + .mockResolvedValueOnce({ + ok: true, + json: async () => ({}), + }) + // Refresh cards after deletion + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: [mockCards[1]] }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Hello")).toBeDefined(); + }); + + const deleteButtons = screen.getAllByRole("button", { name: "Delete" }); + const firstDeleteButton = deleteButtons[0]; + if (firstDeleteButton) { + await user.click(firstDeleteButton); + } + + // Find the Delete button in the modal (not the card list) + const modalDeleteButtons = screen.getAllByRole("button", { + name: "Delete", + }); + const confirmDeleteButton = modalDeleteButtons.find((btn) => + btn.closest('[role="dialog"]'), + ); + if (confirmDeleteButton) { + await user.click(confirmDeleteButton); + } + + // Wait for modal to close and list to refresh + await waitFor(() => { + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + // Verify DELETE request was made + expect(mockFetch).toHaveBeenCalledWith("/api/decks/deck-1/cards/card-1", { + method: "DELETE", + headers: { Authorization: "Bearer access-token" }, + }); + + // Verify card count updated + await waitFor(() => { + expect( + screen.getByRole("heading", { name: "Cards (1)" }), + ).toBeDefined(); + }); + }); + + it("displays error when delete fails", async () => { + const user = userEvent.setup(); + + mockFetch + // Initial load + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }) + // Delete request fails + .mockResolvedValueOnce({ + ok: false, + status: 500, + json: async () => ({ error: "Failed to delete card" }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Hello")).toBeDefined(); + }); + + const deleteButtons = screen.getAllByRole("button", { name: "Delete" }); + const firstDeleteButton = deleteButtons[0]; + if (firstDeleteButton) { + await user.click(firstDeleteButton); + } + + // Find the Delete button in the modal + const modalDeleteButtons = screen.getAllByRole("button", { + name: "Delete", + }); + const confirmDeleteButton = modalDeleteButtons.find((btn) => + btn.closest('[role="dialog"]'), + ); + if (confirmDeleteButton) { + await user.click(confirmDeleteButton); + } + + // Error should be displayed in the modal + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain( + "Failed to delete card", + ); + }); + }); + }); }); diff --git a/src/client/pages/DeckDetailPage.tsx b/src/client/pages/DeckDetailPage.tsx index 57e4af9..cdc216a 100644 --- a/src/client/pages/DeckDetailPage.tsx +++ b/src/client/pages/DeckDetailPage.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react"; import { Link, useParams } from "wouter"; import { ApiClientError, apiClient } from "../api"; import { CreateCardModal } from "../components/CreateCardModal"; +import { DeleteCardModal } from "../components/DeleteCardModal"; import { EditCardModal } from "../components/EditCardModal"; interface Card { @@ -38,6 +39,7 @@ export function DeckDetailPage() { const [error, setError] = useState<string | null>(null); const [isCreateModalOpen, setIsCreateModalOpen] = useState(false); const [editingCard, setEditingCard] = useState<Card | null>(null); + const [deletingCard, setDeletingCard] = useState<Card | null>(null); const fetchDeck = useCallback(async () => { if (!deckId) return; @@ -241,13 +243,34 @@ export function DeckDetailPage() { <span>Lapses: {card.lapses}</span> </div> </div> - <button - type="button" - onClick={() => setEditingCard(card)} - style={{ marginLeft: "1rem" }} + <div + style={{ + display: "flex", + gap: "0.5rem", + marginLeft: "1rem", + }} > - Edit - </button> + <button + type="button" + onClick={() => setEditingCard(card)} + > + Edit + </button> + <button + type="button" + onClick={() => setDeletingCard(card)} + style={{ + backgroundColor: "#dc3545", + color: "white", + border: "none", + padding: "0.5rem 1rem", + borderRadius: "4px", + cursor: "pointer", + }} + > + Delete + </button> + </div> </div> </li> ))} @@ -274,6 +297,16 @@ export function DeckDetailPage() { onCardUpdated={fetchCards} /> )} + + {deckId && ( + <DeleteCardModal + isOpen={deletingCard !== null} + deckId={deckId} + card={deletingCard} + onClose={() => setDeletingCard(null)} + onCardDeleted={fetchCards} + /> + )} </div> ); } |
