diff options
| author | nsfisis <nsfisis@gmail.com> | 2025-12-07 17:51:34 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2025-12-07 17:51:34 +0900 |
| commit | 020803f7dfd094dcf5157943644a28d601629b35 (patch) | |
| tree | 9d89864d0f0a03f5b5f50504a767da4edf3efa2e | |
| parent | ef40cc0f3b1b3013046820b84e8482f1c6a29533 (diff) | |
| download | kioku-020803f7dfd094dcf5157943644a28d601629b35.tar.gz kioku-020803f7dfd094dcf5157943644a28d601629b35.tar.zst kioku-020803f7dfd094dcf5157943644a28d601629b35.zip | |
feat(client): add create deck modal with form validation
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 <noreply@anthropic.com>
| -rw-r--r-- | docs/dev/roadmap.md | 2 | ||||
| -rw-r--r-- | src/client/App.test.tsx | 12 | ||||
| -rw-r--r-- | src/client/components/CreateDeckModal.test.tsx | 401 | ||||
| -rw-r--r-- | src/client/components/CreateDeckModal.tsx | 184 | ||||
| -rw-r--r-- | src/client/pages/HomePage.test.tsx | 155 | ||||
| -rw-r--r-- | src/client/pages/HomePage.tsx | 22 |
6 files changed, 768 insertions, 8 deletions
diff --git a/docs/dev/roadmap.md b/docs/dev/roadmap.md index 54a3376..bcddb38 100644 --- a/docs/dev/roadmap.md +++ b/docs/dev/roadmap.md @@ -85,7 +85,7 @@ Smaller features first to enable early MVP validation. ### Frontend - [x] Deck list page (empty state, list view) -- [ ] Create deck modal/form +- [x] Create deck modal/form - [ ] Edit deck - [ ] Delete deck (with confirmation) - [ ] Add tests 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<any> }) { - return data as unknown as Awaited<ReturnType<typeof apiClient.rpc.api.decks.$get>>; +function mockResponse(data: { + ok: boolean; + status?: number; + // biome-ignore lint/suspicious/noExplicitAny: Test helper needs flexible typing + json: () => Promise<any>; +}) { + return data as unknown as Awaited< + ReturnType<typeof apiClient.rpc.api.decks.$get> + >; } 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<any>; +}) { + return data as unknown as Awaited< + ReturnType<typeof apiClient.rpc.api.decks.$post> + >; +} + +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(<CreateDeckModal {...defaultProps} isOpen={false} />); + + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("renders modal when open", () => { + render(<CreateDeckModal {...defaultProps} />); + + 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(<CreateDeckModal {...defaultProps} />); + + 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(<CreateDeckModal {...defaultProps} />); + + 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(<CreateDeckModal {...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(<CreateDeckModal {...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(<CreateDeckModal {...defaultProps} onClose={onClose} />); + + // 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( + <CreateDeckModal + isOpen={true} + onClose={onClose} + onDeckCreated={onDeckCreated} + />, + ); + + 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( + <CreateDeckModal + isOpen={true} + onClose={onClose} + onDeckCreated={onDeckCreated} + />, + ); + + 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(<CreateDeckModal {...defaultProps} />); + + 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(<CreateDeckModal {...defaultProps} />); + + 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(<CreateDeckModal {...defaultProps} />); + + 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(<CreateDeckModal {...defaultProps} />); + + 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( + <CreateDeckModal + isOpen={true} + onClose={onClose} + onDeckCreated={vi.fn()} + />, + ); + + // 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( + <CreateDeckModal + isOpen={true} + onClose={onClose} + onDeckCreated={vi.fn()} + />, + ); + + // 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( + <CreateDeckModal + isOpen={true} + onClose={onClose} + onDeckCreated={vi.fn()} + />, + ); + + // 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( + <CreateDeckModal + isOpen={true} + onClose={onClose} + onDeckCreated={vi.fn()} + />, + ); + + // 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<string | null>(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 ( + <div + role="dialog" + aria-modal="true" + aria-labelledby="create-deck-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="create-deck-title" style={{ marginTop: 0 }}> + Create New Deck + </h2> + + <form onSubmit={handleSubmit}> + {error && ( + <div role="alert" style={{ color: "red", marginBottom: "1rem" }}> + {error} + </div> + )} + + <div style={{ marginBottom: "1rem" }}> + <label + htmlFor="deck-name" + style={{ display: "block", marginBottom: "0.25rem" }} + > + Name + </label> + <input + id="deck-name" + type="text" + value={name} + onChange={(e) => setName(e.target.value)} + required + maxLength={255} + disabled={isSubmitting} + style={{ width: "100%", boxSizing: "border-box" }} + /> + </div> + + <div style={{ marginBottom: "1rem" }}> + <label + htmlFor="deck-description" + style={{ display: "block", marginBottom: "0.25rem" }} + > + Description (optional) + </label> + <textarea + id="deck-description" + value={description} + onChange={(e) => setDescription(e.target.value)} + maxLength={1000} + disabled={isSubmitting} + rows={3} + style={{ + width: "100%", + boxSizing: "border-box", + resize: "vertical", + }} + /> + </div> + + <div + style={{ + display: "flex", + gap: "0.5rem", + justifyContent: "flex-end", + }} + > + <button type="button" onClick={handleClose} disabled={isSubmitting}> + Cancel + </button> + <button type="submit" disabled={isSubmitting || !name.trim()}> + {isSubmitting ? "Creating..." : "Create"} + </button> + </div> + </form> + </div> + </div> + ); +} diff --git a/src/client/pages/HomePage.test.tsx b/src/client/pages/HomePage.test.tsx index f471924..93351d5 100644 --- a/src/client/pages/HomePage.test.tsx +++ b/src/client/pages/HomePage.test.tsx @@ -21,6 +21,7 @@ vi.mock("../api/client", () => ({ api: { decks: { $get: vi.fn(), + $post: vi.fn(), }, }, }, @@ -38,9 +39,26 @@ 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<any> }) { - return data as unknown as Awaited<ReturnType<typeof apiClient.rpc.api.decks.$get>>; +function mockResponse(data: { + ok: boolean; + status?: number; + // biome-ignore lint/suspicious/noExplicitAny: Test helper needs flexible typing + json: () => Promise<any>; +}) { + return data as unknown as Awaited< + ReturnType<typeof apiClient.rpc.api.decks.$get> + >; +} + +function mockPostResponse(data: { + ok: boolean; + status?: number; + // biome-ignore lint/suspicious/noExplicitAny: Test helper needs flexible typing + json: () => Promise<any>; +}) { + return data as unknown as Awaited< + ReturnType<typeof apiClient.rpc.api.decks.$post> + >; } const mockDecks = [ @@ -288,4 +306,135 @@ describe("HomePage", () => { }); }); }); + + describe("Create Deck", () => { + it("shows Create Deck button", async () => { + vi.mocked(apiClient.rpc.api.decks.$get).mockResolvedValue( + mockResponse({ + ok: true, + json: async () => ({ decks: [] }), + }), + ); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.queryByText("Loading decks...")).toBeNull(); + }); + + expect(screen.getByRole("button", { name: "Create Deck" })).toBeDefined(); + }); + + it("opens modal when Create Deck button is clicked", async () => { + const user = userEvent.setup(); + vi.mocked(apiClient.rpc.api.decks.$get).mockResolvedValue( + mockResponse({ + ok: true, + json: async () => ({ decks: [] }), + }), + ); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.queryByText("Loading decks...")).toBeNull(); + }); + + await user.click(screen.getByRole("button", { name: "Create Deck" })); + + expect(screen.getByRole("dialog")).toBeDefined(); + expect( + screen.getByRole("heading", { name: "Create New Deck" }), + ).toBeDefined(); + }); + + it("closes modal when Cancel is clicked", async () => { + const user = userEvent.setup(); + vi.mocked(apiClient.rpc.api.decks.$get).mockResolvedValue( + mockResponse({ + ok: true, + json: async () => ({ decks: [] }), + }), + ); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.queryByText("Loading decks...")).toBeNull(); + }); + + await user.click(screen.getByRole("button", { name: "Create Deck" })); + expect(screen.getByRole("dialog")).toBeDefined(); + + await user.click(screen.getByRole("button", { name: "Cancel" })); + + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("creates deck and refreshes list", async () => { + const user = userEvent.setup(); + const newDeck = { + id: "deck-new", + name: "New Deck", + description: "A new deck", + newCardsPerDay: 20, + createdAt: "2024-01-03T00:00:00Z", + updatedAt: "2024-01-03T00:00:00Z", + }; + + vi.mocked(apiClient.rpc.api.decks.$get) + .mockResolvedValueOnce( + mockResponse({ + ok: true, + json: async () => ({ decks: [] }), + }), + ) + .mockResolvedValueOnce( + mockResponse({ + ok: true, + json: async () => ({ decks: [newDeck] }), + }), + ); + + vi.mocked(apiClient.rpc.api.decks.$post).mockResolvedValue( + mockPostResponse({ + ok: true, + json: async () => ({ deck: newDeck }), + }), + ); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.queryByText("Loading decks...")).toBeNull(); + }); + + // Open modal + await user.click(screen.getByRole("button", { name: "Create Deck" })); + + // Fill in form + await user.type(screen.getByLabelText("Name"), "New Deck"); + await user.type( + screen.getByLabelText("Description (optional)"), + "A new deck", + ); + + // Submit + await user.click(screen.getByRole("button", { name: "Create" })); + + // Modal should close + await waitFor(() => { + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + // Deck list should be refreshed with new deck + await waitFor(() => { + expect(screen.getByRole("heading", { name: "New Deck" })).toBeDefined(); + }); + expect(screen.getByText("A new deck")).toBeDefined(); + + // API should have been called twice (initial + refresh) + expect(apiClient.rpc.api.decks.$get).toHaveBeenCalledTimes(2); + }); + }); }); diff --git a/src/client/pages/HomePage.tsx b/src/client/pages/HomePage.tsx index c9d0843..d753aa1 100644 --- a/src/client/pages/HomePage.tsx +++ b/src/client/pages/HomePage.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useState } from "react"; import { ApiClientError, apiClient } from "../api"; +import { CreateDeckModal } from "../components/CreateDeckModal"; import { useAuth } from "../stores"; interface Deck { @@ -16,6 +17,7 @@ export function HomePage() { const [decks, setDecks] = useState<Deck[]>([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState<string | null>(null); + const [isCreateModalOpen, setIsCreateModalOpen] = useState(false); const fetchDecks = useCallback(async () => { setIsLoading(true); @@ -69,7 +71,19 @@ export function HomePage() { </header> <main> - <h2>Your Decks</h2> + <div + style={{ + display: "flex", + justifyContent: "space-between", + alignItems: "center", + marginBottom: "1rem", + }} + > + <h2 style={{ margin: 0 }}>Your Decks</h2> + <button type="button" onClick={() => setIsCreateModalOpen(true)}> + Create Deck + </button> + </div> {isLoading && <p>Loading decks...</p>} @@ -116,6 +130,12 @@ export function HomePage() { </ul> )} </main> + + <CreateDeckModal + isOpen={isCreateModalOpen} + onClose={() => setIsCreateModalOpen(false)} + onDeckCreated={fetchDecks} + /> </div> ); } |
