From 020803f7dfd094dcf5157943644a28d601629b35 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sun, 7 Dec 2025 17:51:34 +0900 Subject: feat(client): add create deck modal with form validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add CreateDeckModal component that allows users to create new decks with name and optional description fields. Integrates with HomePage via a "Create Deck" button that opens the modal, and refreshes the deck list after successful creation. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- src/client/App.test.tsx | 12 +- src/client/components/CreateDeckModal.test.tsx | 401 +++++++++++++++++++++++++ src/client/components/CreateDeckModal.tsx | 184 ++++++++++++ src/client/pages/HomePage.test.tsx | 155 +++++++++- src/client/pages/HomePage.tsx | 22 +- 5 files changed, 767 insertions(+), 7 deletions(-) create mode 100644 src/client/components/CreateDeckModal.test.tsx create mode 100644 src/client/components/CreateDeckModal.tsx (limited to 'src') diff --git a/src/client/App.test.tsx b/src/client/App.test.tsx index bdc281a..c11eb88 100644 --- a/src/client/App.test.tsx +++ b/src/client/App.test.tsx @@ -37,9 +37,15 @@ vi.mock("./api/client", () => ({ })); // Helper to create mock responses compatible with Hono's ClientResponse -// biome-ignore lint/suspicious/noExplicitAny: Test helper needs flexible typing -function mockResponse(data: { ok: boolean; status?: number; json: () => Promise }) { - return data as unknown as Awaited>; +function mockResponse(data: { + ok: boolean; + status?: number; + // biome-ignore lint/suspicious/noExplicitAny: Test helper needs flexible typing + json: () => Promise; +}) { + return data as unknown as Awaited< + ReturnType + >; } function renderWithRouter(path: string) { diff --git a/src/client/components/CreateDeckModal.test.tsx b/src/client/components/CreateDeckModal.test.tsx new file mode 100644 index 0000000..984f6d0 --- /dev/null +++ b/src/client/components/CreateDeckModal.test.tsx @@ -0,0 +1,401 @@ +/** + * @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(), + rpc: { + api: { + decks: { + $post: 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 { CreateDeckModal } from "./CreateDeckModal"; + +// Helper to create mock responses +function mockResponse(data: { + ok: boolean; + status?: number; + // biome-ignore lint/suspicious/noExplicitAny: Test helper needs flexible typing + json: () => Promise; +}) { + return data as unknown as Awaited< + ReturnType + >; +} + +describe("CreateDeckModal", () => { + const defaultProps = { + isOpen: true, + onClose: vi.fn(), + onDeckCreated: 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(); + + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("renders modal when open", () => { + render(); + + expect(screen.getByRole("dialog")).toBeDefined(); + expect( + screen.getByRole("heading", { name: "Create New Deck" }), + ).toBeDefined(); + expect(screen.getByLabelText("Name")).toBeDefined(); + expect(screen.getByLabelText("Description (optional)")).toBeDefined(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeDefined(); + expect(screen.getByRole("button", { name: "Create" })).toBeDefined(); + }); + + it("disables create button when name is empty", () => { + render(); + + const createButton = screen.getByRole("button", { name: "Create" }); + expect(createButton).toHaveProperty("disabled", true); + }); + + it("enables create button when name has content", async () => { + const user = userEvent.setup(); + render(); + + const nameInput = screen.getByLabelText("Name"); + await user.type(nameInput, "My Deck"); + + const createButton = screen.getByRole("button", { name: "Create" }); + expect(createButton).toHaveProperty("disabled", false); + }); + + it("calls onClose when Cancel is clicked", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + render(); + + 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(); + + // 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(); + + // Click on an element inside the modal + await user.click(screen.getByLabelText("Name")); + + expect(onClose).not.toHaveBeenCalled(); + }); + + it("creates deck with name only", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + const onDeckCreated = vi.fn(); + + vi.mocked(apiClient.rpc.api.decks.$post).mockResolvedValue( + mockResponse({ + ok: true, + json: async () => ({ + deck: { + id: "deck-1", + name: "Test Deck", + description: null, + newCardsPerDay: 20, + }, + }), + }), + ); + + render( + , + ); + + await user.type(screen.getByLabelText("Name"), "Test Deck"); + await user.click(screen.getByRole("button", { name: "Create" })); + + await waitFor(() => { + expect(apiClient.rpc.api.decks.$post).toHaveBeenCalledWith( + { json: { name: "Test Deck", description: null } }, + { headers: { Authorization: "Bearer access-token" } }, + ); + }); + + expect(onDeckCreated).toHaveBeenCalledTimes(1); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it("creates deck with name and description", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + const onDeckCreated = vi.fn(); + + vi.mocked(apiClient.rpc.api.decks.$post).mockResolvedValue( + mockResponse({ + ok: true, + json: async () => ({ + deck: { + id: "deck-1", + name: "Test Deck", + description: "A test description", + newCardsPerDay: 20, + }, + }), + }), + ); + + render( + , + ); + + await user.type(screen.getByLabelText("Name"), "Test Deck"); + await user.type( + screen.getByLabelText("Description (optional)"), + "A test description", + ); + await user.click(screen.getByRole("button", { name: "Create" })); + + await waitFor(() => { + expect(apiClient.rpc.api.decks.$post).toHaveBeenCalledWith( + { json: { name: "Test Deck", description: "A test description" } }, + { headers: { Authorization: "Bearer access-token" } }, + ); + }); + + expect(onDeckCreated).toHaveBeenCalledTimes(1); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it("trims whitespace from name and description", async () => { + const user = userEvent.setup(); + + vi.mocked(apiClient.rpc.api.decks.$post).mockResolvedValue( + mockResponse({ + ok: true, + json: async () => ({ deck: { id: "deck-1" } }), + }), + ); + + render(); + + await user.type(screen.getByLabelText("Name"), " Test Deck "); + await user.type( + screen.getByLabelText("Description (optional)"), + " Description ", + ); + await user.click(screen.getByRole("button", { name: "Create" })); + + await waitFor(() => { + expect(apiClient.rpc.api.decks.$post).toHaveBeenCalledWith( + { json: { name: "Test Deck", description: "Description" } }, + { headers: { Authorization: "Bearer access-token" } }, + ); + }); + }); + + it("shows loading state during submission", async () => { + const user = userEvent.setup(); + + vi.mocked(apiClient.rpc.api.decks.$post).mockImplementation( + () => new Promise(() => {}), // Never resolves + ); + + render(); + + await user.type(screen.getByLabelText("Name"), "Test Deck"); + await user.click(screen.getByRole("button", { name: "Create" })); + + expect(screen.getByRole("button", { name: "Creating..." })).toBeDefined(); + expect(screen.getByRole("button", { name: "Creating..." })).toHaveProperty( + "disabled", + true, + ); + expect(screen.getByRole("button", { name: "Cancel" })).toHaveProperty( + "disabled", + true, + ); + expect(screen.getByLabelText("Name")).toHaveProperty("disabled", true); + expect(screen.getByLabelText("Description (optional)")).toHaveProperty( + "disabled", + true, + ); + }); + + it("displays API error message", async () => { + const user = userEvent.setup(); + + vi.mocked(apiClient.rpc.api.decks.$post).mockResolvedValue( + mockResponse({ + ok: false, + status: 400, + json: async () => ({ error: "Deck name already exists" }), + }), + ); + + render(); + + await user.type(screen.getByLabelText("Name"), "Test Deck"); + await user.click(screen.getByRole("button", { name: "Create" })); + + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain( + "Deck name already exists", + ); + }); + }); + + it("displays generic error on unexpected failure", async () => { + const user = userEvent.setup(); + + vi.mocked(apiClient.rpc.api.decks.$post).mockRejectedValue( + new Error("Network error"), + ); + + render(); + + await user.type(screen.getByLabelText("Name"), "Test Deck"); + await user.click(screen.getByRole("button", { name: "Create" })); + + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain( + "Failed to create deck. Please try again.", + ); + }); + }); + + it("resets form when closed and reopened", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + + const { rerender } = render( + , + ); + + // Type something in the form + await user.type(screen.getByLabelText("Name"), "Test Deck"); + await user.type( + screen.getByLabelText("Description (optional)"), + "Test Description", + ); + + // Click cancel to close + await user.click(screen.getByRole("button", { name: "Cancel" })); + + // Reopen the modal + rerender( + , + ); + + // Form should be reset + expect(screen.getByLabelText("Name")).toHaveProperty("value", ""); + expect(screen.getByLabelText("Description (optional)")).toHaveProperty( + "value", + "", + ); + }); + + it("resets form after successful creation", async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + + vi.mocked(apiClient.rpc.api.decks.$post).mockResolvedValue( + mockResponse({ + ok: true, + json: async () => ({ deck: { id: "deck-1" } }), + }), + ); + + const { rerender } = render( + , + ); + + // Create a deck + await user.type(screen.getByLabelText("Name"), "Test Deck"); + await user.click(screen.getByRole("button", { name: "Create" })); + + await waitFor(() => { + expect(onClose).toHaveBeenCalled(); + }); + + // Reopen the modal + rerender( + , + ); + + // Form should be reset + expect(screen.getByLabelText("Name")).toHaveProperty("value", ""); + expect(screen.getByLabelText("Description (optional)")).toHaveProperty( + "value", + "", + ); + }); +}); diff --git a/src/client/components/CreateDeckModal.tsx b/src/client/components/CreateDeckModal.tsx new file mode 100644 index 0000000..85afb0c --- /dev/null +++ b/src/client/components/CreateDeckModal.tsx @@ -0,0 +1,184 @@ +import { type FormEvent, useState } from "react"; +import { ApiClientError, apiClient } from "../api"; + +interface CreateDeckModalProps { + isOpen: boolean; + onClose: () => void; + onDeckCreated: () => void; +} + +export function CreateDeckModal({ + isOpen, + onClose, + onDeckCreated, +}: CreateDeckModalProps) { + const [name, setName] = useState(""); + const [description, setDescription] = useState(""); + const [error, setError] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); + + const resetForm = () => { + setName(""); + setDescription(""); + setError(null); + }; + + const handleClose = () => { + resetForm(); + onClose(); + }; + + const handleSubmit = async (e: FormEvent) => { + e.preventDefault(); + setError(null); + setIsSubmitting(true); + + try { + const res = await apiClient.rpc.api.decks.$post( + { + json: { + name: name.trim(), + description: description.trim() || null, + }, + }, + { + headers: apiClient.getAuthHeader(), + }, + ); + + 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, + ); + } + + resetForm(); + onDeckCreated(); + onClose(); + } catch (err) { + if (err instanceof ApiClientError) { + setError(err.message); + } else { + setError("Failed to create deck. Please try again."); + } + } finally { + setIsSubmitting(false); + } + }; + + if (!isOpen) { + return null; + } + + return ( +
{ + if (e.target === e.currentTarget) { + handleClose(); + } + }} + onKeyDown={(e) => { + if (e.key === "Escape") { + handleClose(); + } + }} + > +
+

+ Create New Deck +

+ +
+ {error && ( +
+ {error} +
+ )} + +
+ + setName(e.target.value)} + required + maxLength={255} + disabled={isSubmitting} + style={{ width: "100%", boxSizing: "border-box" }} + /> +
+ +
+ +