diff options
| author | nsfisis <nsfisis@gmail.com> | 2025-12-07 18:21:20 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2025-12-07 18:21:20 +0900 |
| commit | af9a4912f914bb198fe13bd3421ea33ff3bf9d45 (patch) | |
| tree | 707f81a146739ec4c2abb67033f8612cb5079d41 | |
| parent | 0b0e7e802fcb50652c3e9912363d996a039d56d8 (diff) | |
| download | kioku-af9a4912f914bb198fe13bd3421ea33ff3bf9d45.tar.gz kioku-af9a4912f914bb198fe13bd3421ea33ff3bf9d45.tar.zst kioku-af9a4912f914bb198fe13bd3421ea33ff3bf9d45.zip | |
feat(client): add card list view in deck detail page
Add DeckDetailPage component that displays all cards in a deck with their
front/back content, state, review count, and lapses. Deck names on HomePage
are now clickable links to navigate to the deck detail view.
๐ค 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.tsx | 7 | ||||
| -rw-r--r-- | src/client/pages/DeckDetailPage.test.tsx | 375 | ||||
| -rw-r--r-- | src/client/pages/DeckDetailPage.tsx | 246 | ||||
| -rw-r--r-- | src/client/pages/HomePage.tsx | 10 | ||||
| -rw-r--r-- | src/client/pages/index.ts | 1 |
6 files changed, 638 insertions, 3 deletions
diff --git a/docs/dev/roadmap.md b/docs/dev/roadmap.md index 4c2ccba..86e0a5e 100644 --- a/docs/dev/roadmap.md +++ b/docs/dev/roadmap.md @@ -103,7 +103,7 @@ Smaller features first to enable early MVP validation. - [x] Add tests ### Frontend -- [ ] Card list view (in deck detail page) +- [x] Card list view (in deck detail page) - [ ] Create card form (front/back) - [ ] Edit card - [ ] Delete card diff --git a/src/client/App.tsx b/src/client/App.tsx index 5e749d2..4c5b08a 100644 --- a/src/client/App.tsx +++ b/src/client/App.tsx @@ -1,6 +1,6 @@ import { Route, Switch } from "wouter"; import { ProtectedRoute } from "./components"; -import { HomePage, LoginPage, NotFoundPage } from "./pages"; +import { DeckDetailPage, HomePage, LoginPage, NotFoundPage } from "./pages"; export function App() { return ( @@ -10,6 +10,11 @@ export function App() { <HomePage /> </ProtectedRoute> </Route> + <Route path="/decks/:deckId"> + <ProtectedRoute> + <DeckDetailPage /> + </ProtectedRoute> + </Route> <Route path="/login" component={LoginPage} /> <Route component={NotFoundPage} /> </Switch> diff --git a/src/client/pages/DeckDetailPage.test.tsx b/src/client/pages/DeckDetailPage.test.tsx new file mode 100644 index 0000000..de22b08 --- /dev/null +++ b/src/client/pages/DeckDetailPage.test.tsx @@ -0,0 +1,375 @@ +/** + * @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 { Route, Router } from "wouter"; +import { memoryLocation } from "wouter/memory-location"; +import { apiClient } from "../api/client"; +import { AuthProvider } from "../stores"; +import { DeckDetailPage } from "./DeckDetailPage"; + +vi.mock("../api/client", () => ({ + apiClient: { + login: vi.fn(), + logout: vi.fn(), + isAuthenticated: vi.fn(), + getTokens: vi.fn(), + getAuthHeader: vi.fn(), + rpc: { + api: { + decks: { + $get: vi.fn(), + $post: vi.fn(), + }, + }, + }, + }, + ApiClientError: class ApiClientError extends Error { + constructor( + message: string, + public status: number, + public code?: string, + ) { + super(message); + this.name = "ApiClientError"; + } + }, +})); + +// Mock fetch globally +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +const mockDeck = { + id: "deck-1", + name: "Japanese Vocabulary", + description: "Common Japanese words", + newCardsPerDay: 20, + createdAt: "2024-01-01T00:00:00Z", + updatedAt: "2024-01-01T00:00:00Z", +}; + +const mockCards = [ + { + id: "card-1", + deckId: "deck-1", + front: "Hello", + back: "ใใใซใกใฏ", + state: 0, + due: "2024-01-01T00:00:00Z", + stability: 0, + difficulty: 0, + elapsedDays: 0, + scheduledDays: 0, + reps: 0, + lapses: 0, + lastReview: null, + createdAt: "2024-01-01T00:00:00Z", + updatedAt: "2024-01-01T00:00:00Z", + deletedAt: null, + syncVersion: 0, + }, + { + id: "card-2", + deckId: "deck-1", + front: "Goodbye", + back: "ใใใใชใ", + state: 2, + due: "2024-01-02T00:00:00Z", + stability: 5.5, + difficulty: 5.0, + elapsedDays: 1, + scheduledDays: 7, + reps: 5, + lapses: 1, + lastReview: "2024-01-01T00:00:00Z", + createdAt: "2024-01-01T00:00:00Z", + updatedAt: "2024-01-01T00:00:00Z", + deletedAt: null, + syncVersion: 0, + }, +]; + +function renderWithProviders(path = "/decks/deck-1") { + const { hook } = memoryLocation({ path, static: true }); + return render( + <Router hook={hook}> + <AuthProvider> + <Route path="/decks/:deckId"> + <DeckDetailPage /> + </Route> + </AuthProvider> + </Router>, + ); +} + +describe("DeckDetailPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(apiClient.getTokens).mockReturnValue({ + accessToken: "access-token", + refreshToken: "refresh-token", + }); + vi.mocked(apiClient.isAuthenticated).mockReturnValue(true); + vi.mocked(apiClient.getAuthHeader).mockReturnValue({ + Authorization: "Bearer access-token", + }); + }); + + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + it("renders back link and deck name", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect( + screen.getByRole("heading", { name: "Japanese Vocabulary" }), + ).toBeDefined(); + }); + + expect(screen.getByText(/Back to Decks/)).toBeDefined(); + expect(screen.getByText("Common Japanese words")).toBeDefined(); + }); + + it("shows loading state while fetching data", async () => { + mockFetch.mockImplementation(() => new Promise(() => {})); // Never resolves + + renderWithProviders(); + + expect(screen.getByText("Loading...")).toBeDefined(); + }); + + it("displays empty state when no cards exist", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: [] }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("This deck has no cards yet.")).toBeDefined(); + }); + expect(screen.getByText("Add cards to start studying!")).toBeDefined(); + }); + + it("displays list of cards", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Hello")).toBeDefined(); + }); + expect(screen.getByText("ใใใซใกใฏ")).toBeDefined(); + expect(screen.getByText("Goodbye")).toBeDefined(); + expect(screen.getByText("ใใใใชใ")).toBeDefined(); + }); + + it("displays card count", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByRole("heading", { name: "Cards (2)" })).toBeDefined(); + }); + }); + + it("displays card state labels", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("State: New")).toBeDefined(); + }); + expect(screen.getByText("State: Review")).toBeDefined(); + }); + + it("displays card stats (reps and lapses)", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Reviews: 0")).toBeDefined(); + }); + expect(screen.getByText("Reviews: 5")).toBeDefined(); + expect(screen.getByText("Lapses: 0")).toBeDefined(); + expect(screen.getByText("Lapses: 1")).toBeDefined(); + }); + + it("displays error on API failure for deck", async () => { + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + json: async () => ({ error: "Deck not found" }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain("Deck not found"); + }); + }); + + it("displays error on API failure for cards", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: false, + status: 500, + json: async () => ({ error: "Failed to load cards" }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByRole("alert").textContent).toContain( + "Failed to load cards", + ); + }); + }); + + it("allows retry after error", async () => { + const user = userEvent.setup(); + // First call fails for both deck and cards (they run in parallel) + mockFetch + .mockResolvedValueOnce({ + ok: false, + status: 500, + json: async () => ({ error: "Server error" }), + }) + .mockResolvedValueOnce({ + ok: false, + status: 500, + json: async () => ({ error: "Server error" }), + }) + // Second call (retry) succeeds + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: mockCards }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByRole("alert")).toBeDefined(); + }); + + await user.click(screen.getByRole("button", { name: "Retry" })); + + await waitFor(() => { + expect( + screen.getByRole("heading", { name: "Japanese Vocabulary" }), + ).toBeDefined(); + }); + }); + + it("passes auth header when fetching data", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: mockDeck }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: [] }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect(mockFetch).toHaveBeenCalledWith("/api/decks/deck-1", { + headers: { Authorization: "Bearer access-token" }, + }); + }); + expect(mockFetch).toHaveBeenCalledWith("/api/decks/deck-1/cards", { + headers: { Authorization: "Bearer access-token" }, + }); + }); + + it("does not show description if deck has none", async () => { + const deckWithoutDescription = { ...mockDeck, description: null }; + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ deck: deckWithoutDescription }), + }) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ cards: [] }), + }); + + renderWithProviders(); + + await waitFor(() => { + expect( + screen.getByRole("heading", { name: "Japanese Vocabulary" }), + ).toBeDefined(); + }); + + // No description should be shown + expect(screen.queryByText("Common Japanese words")).toBeNull(); + }); +}); diff --git a/src/client/pages/DeckDetailPage.tsx b/src/client/pages/DeckDetailPage.tsx new file mode 100644 index 0000000..c713ab0 --- /dev/null +++ b/src/client/pages/DeckDetailPage.tsx @@ -0,0 +1,246 @@ +import { useCallback, useEffect, useState } from "react"; +import { Link, useParams } from "wouter"; +import { ApiClientError, apiClient } from "../api"; + +interface Card { + id: string; + deckId: string; + front: string; + back: string; + state: number; + due: string; + reps: number; + lapses: number; + createdAt: string; + updatedAt: string; +} + +interface Deck { + id: string; + name: string; + description: string | null; +} + +const CardStateLabels: Record<number, string> = { + 0: "New", + 1: "Learning", + 2: "Review", + 3: "Relearning", +}; + +export function DeckDetailPage() { + const { deckId } = useParams<{ deckId: string }>(); + const [deck, setDeck] = useState<Deck | null>(null); + const [cards, setCards] = useState<Card[]>([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState<string | null>(null); + + const fetchDeck = useCallback(async () => { + if (!deckId) return; + + const authHeader = apiClient.getAuthHeader(); + if (!authHeader) { + throw new ApiClientError("Not authenticated", 401); + } + + const res = await fetch(`/api/decks/${deckId}`, { + 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, + ); + } + + const data = await res.json(); + setDeck(data.deck); + }, [deckId]); + + const fetchCards = useCallback(async () => { + if (!deckId) return; + + const authHeader = apiClient.getAuthHeader(); + if (!authHeader) { + throw new ApiClientError("Not authenticated", 401); + } + + const res = await fetch(`/api/decks/${deckId}/cards`, { + 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, + ); + } + + const data = await res.json(); + setCards(data.cards); + }, [deckId]); + + const fetchData = useCallback(async () => { + setIsLoading(true); + setError(null); + + try { + await Promise.all([fetchDeck(), fetchCards()]); + } catch (err) { + if (err instanceof ApiClientError) { + setError(err.message); + } else { + setError("Failed to load data. Please try again."); + } + } finally { + setIsLoading(false); + } + }, [fetchDeck, fetchCards]); + + useEffect(() => { + fetchData(); + }, [fetchData]); + + if (!deckId) { + return ( + <div> + <p>Invalid deck ID</p> + <Link href="/">Back to decks</Link> + </div> + ); + } + + return ( + <div> + <header style={{ marginBottom: "1rem" }}> + <Link href="/" style={{ textDecoration: "none" }}> + ← Back to Decks + </Link> + </header> + + {isLoading && <p>Loading...</p>} + + {error && ( + <div role="alert" style={{ color: "red" }}> + {error} + <button + type="button" + onClick={fetchData} + style={{ marginLeft: "0.5rem" }} + > + Retry + </button> + </div> + )} + + {!isLoading && !error && deck && ( + <main> + <div style={{ marginBottom: "1.5rem" }}> + <h1 style={{ margin: 0 }}>{deck.name}</h1> + {deck.description && ( + <p style={{ margin: "0.5rem 0 0 0", color: "#666" }}> + {deck.description} + </p> + )} + </div> + + <div + style={{ + display: "flex", + justifyContent: "space-between", + alignItems: "center", + marginBottom: "1rem", + }} + > + <h2 style={{ margin: 0 }}>Cards ({cards.length})</h2> + </div> + + {cards.length === 0 && ( + <div> + <p>This deck has no cards yet.</p> + <p>Add cards to start studying!</p> + </div> + )} + + {cards.length > 0 && ( + <ul style={{ listStyle: "none", padding: 0 }}> + {cards.map((card) => ( + <li + key={card.id} + style={{ + border: "1px solid #ccc", + padding: "1rem", + marginBottom: "0.5rem", + borderRadius: "4px", + }} + > + <div + style={{ + display: "flex", + justifyContent: "space-between", + alignItems: "flex-start", + }} + > + <div style={{ flex: 1, minWidth: 0 }}> + <div + style={{ + display: "flex", + gap: "1rem", + marginBottom: "0.5rem", + }} + > + <div style={{ flex: 1, minWidth: 0 }}> + <strong>Front:</strong> + <p + style={{ + margin: "0.25rem 0 0 0", + whiteSpace: "pre-wrap", + wordBreak: "break-word", + }} + > + {card.front} + </p> + </div> + <div style={{ flex: 1, minWidth: 0 }}> + <strong>Back:</strong> + <p + style={{ + margin: "0.25rem 0 0 0", + whiteSpace: "pre-wrap", + wordBreak: "break-word", + }} + > + {card.back} + </p> + </div> + </div> + <div + style={{ + display: "flex", + gap: "1rem", + fontSize: "0.875rem", + color: "#666", + }} + > + <span> + State: {CardStateLabels[card.state] || "Unknown"} + </span> + <span>Reviews: {card.reps}</span> + <span>Lapses: {card.lapses}</span> + </div> + </div> + </div> + </li> + ))} + </ul> + )} + </main> + )} + </div> + ); +} diff --git a/src/client/pages/HomePage.tsx b/src/client/pages/HomePage.tsx index a51dfc1..fb13422 100644 --- a/src/client/pages/HomePage.tsx +++ b/src/client/pages/HomePage.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useState } from "react"; +import { Link } from "wouter"; import { ApiClientError, apiClient } from "../api"; import { CreateDeckModal } from "../components/CreateDeckModal"; import { DeleteDeckModal } from "../components/DeleteDeckModal"; @@ -131,7 +132,14 @@ export function HomePage() { }} > <div> - <h3 style={{ margin: 0 }}>{deck.name}</h3> + <h3 style={{ margin: 0 }}> + <Link + href={`/decks/${deck.id}`} + style={{ textDecoration: "none", color: "inherit" }} + > + {deck.name} + </Link> + </h3> {deck.description && ( <p style={{ margin: "0.5rem 0 0 0", color: "#666" }}> {deck.description} diff --git a/src/client/pages/index.ts b/src/client/pages/index.ts index 0844b31..c71e661 100644 --- a/src/client/pages/index.ts +++ b/src/client/pages/index.ts @@ -1,3 +1,4 @@ +export { DeckDetailPage } from "./DeckDetailPage"; export { HomePage } from "./HomePage"; export { LoginPage } from "./LoginPage"; export { NotFoundPage } from "./NotFoundPage"; |
