From b50845ed147ba0f26bc60ef9edef9eaab3c54d13 Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Tue, 6 Oct 2026 02:26:22 +0900 Subject: [PATCH 01/19] feat(grammar): show completion history and note practice summary (#160) --- .../GrammarHistory.stories.tsx | 52 ++++++++ .../grammar-history/GrammarHistory.test.tsx | 40 +++++++ src/features/grammar-history/index.ts | 2 + .../grammar-history/models/interface.ts | 9 ++ .../services/actions/getGrammarHistory.ts | 31 +++++ .../services/formatPracticeDate.ts | 13 ++ .../services/useGrammarHistory.ts | 31 +++++ .../grammar-history/ui/GrammarHistory.tsx | 113 ++++++++++++++++++ .../grammar-history/ui/GrammarHistoryRows.tsx | 34 ++++++ 9 files changed, 325 insertions(+) create mode 100644 src/_storybook/features/grammar-history/GrammarHistory.stories.tsx create mode 100644 src/_tests/features/grammar-history/GrammarHistory.test.tsx create mode 100644 src/features/grammar-history/index.ts create mode 100644 src/features/grammar-history/models/interface.ts create mode 100644 src/features/grammar-history/services/actions/getGrammarHistory.ts create mode 100644 src/features/grammar-history/services/formatPracticeDate.ts create mode 100644 src/features/grammar-history/services/useGrammarHistory.ts create mode 100644 src/features/grammar-history/ui/GrammarHistory.tsx create mode 100644 src/features/grammar-history/ui/GrammarHistoryRows.tsx diff --git a/src/_storybook/features/grammar-history/GrammarHistory.stories.tsx b/src/_storybook/features/grammar-history/GrammarHistory.stories.tsx new file mode 100644 index 00000000..93a5e5a1 --- /dev/null +++ b/src/_storybook/features/grammar-history/GrammarHistory.stories.tsx @@ -0,0 +1,52 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, fn, userEvent, waitFor, within } from "storybook/test"; +import { GrammarHistory } from "@/features/grammar-history"; +const data = { + items: [ + { + id: "session", + noteId: "note", + title: "not A but B", + mode: "recall" as const, + startedAt: "2026-10-01T15:00:00Z", + completedAt: "2026-10-01T16:00:00Z", + questionCount: 4, + }, + ], + total: 1, + page: 1, + pageSize: 10, +}; +const meta = { + title: "Features/Grammar/History", + component: GrammarHistory, + args: { noteId: "note", initialData: data, load: fn(async () => ({ ok: true as const, data })) }, +} satisfies Meta; +export default meta; +type Story = StoryObj; +export const Completed: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const trigger = canvas.getByRole("button", { name: "연습 기록 전체보기" }); + await userEvent.click(trigger); + const page = within(canvasElement.ownerDocument.body); + await expect(await page.findByRole("link", { name: /결과 보기/ })).toHaveAttribute( + "href", + "/grammar-sessions/session/result", + ); + await userEvent.click(page.getByRole("button", { name: "닫기" })); + await waitFor(() => expect(trigger).toHaveFocus()); + }, +}; +export const Empty: Story = { + args: { + initialData: { items: [], total: 0, page: 1, pageSize: 10 }, + load: fn(async () => ({ + ok: true as const, + data: { items: [], total: 0, page: 1, pageSize: 10 }, + })), + }, +}; +export const Failure: Story = { + args: { load: fn(async () => ({ ok: false as const, message: "연습 기록 조회 실패" })) }, +}; diff --git a/src/_tests/features/grammar-history/GrammarHistory.test.tsx b/src/_tests/features/grammar-history/GrammarHistory.test.tsx new file mode 100644 index 00000000..2fa1bdd0 --- /dev/null +++ b/src/_tests/features/grammar-history/GrammarHistory.test.tsx @@ -0,0 +1,40 @@ +import { describe, it, expect, jest } from "@jest/globals"; +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { GrammarHistory } from "@/features/grammar-history"; +import type { GrammarHistoryResult } from "@/features/grammar-history"; +import { formatGrammarPracticeDate } from "@/features/grammar-history/services/formatPracticeDate"; +describe("grammar history", () => { + it("shows Korea date across UTC midnight", () => { + expect(formatGrammarPracticeDate("2026-10-01T16:00:00Z")).toContain("10. 02."); + }); + it("shows completed count, loads empty history and restores focus when closing", async () => { + const user = userEvent.setup(); + const data = { items: [], total: 0, page: 1, pageSize: 10 }; + const load = jest + .fn<() => Promise>() + .mockResolvedValue({ ok: true, data }); + render(); + expect(screen.getByText("완료한 연습 0회")).toBeVisible(); + const trigger = screen.getByRole("button", { name: "연습 기록 전체보기" }); + await user.click(trigger); + expect(await screen.findByText("아직 완료한 연습이 없습니다.")).toBeVisible(); + await user.keyboard("{Escape}"); + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); + expect(trigger).toHaveFocus(); + }); + it("provides retry after failure without fabricating a count", async () => { + const user = userEvent.setup(); + const load = jest + .fn<() => Promise>() + .mockResolvedValueOnce({ ok: false, message: "조회 실패" }) + .mockResolvedValueOnce({ ok: true, data: { items: [], total: 0, page: 1, pageSize: 10 } }); + render(); + expect(screen.queryByText("완료한 연습 0회")).not.toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "연습 기록 전체보기" })); + expect(await screen.findByRole("alert")).toHaveTextContent("조회 실패"); + await user.click(screen.getByRole("button", { name: "다시 불러오기" })); + expect(await screen.findByText("아직 완료한 연습이 없습니다.")).toBeVisible(); + expect(load).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/features/grammar-history/index.ts b/src/features/grammar-history/index.ts new file mode 100644 index 00000000..938f4737 --- /dev/null +++ b/src/features/grammar-history/index.ts @@ -0,0 +1,2 @@ +export { GrammarHistory } from "./ui/GrammarHistory"; +export type { GrammarHistoryProps, GrammarHistoryResult } from "./models/interface"; diff --git a/src/features/grammar-history/models/interface.ts b/src/features/grammar-history/models/interface.ts new file mode 100644 index 00000000..54cfcf5b --- /dev/null +++ b/src/features/grammar-history/models/interface.ts @@ -0,0 +1,9 @@ +import type { GrammarSessionHistory } from "@/entities/grammar-session"; +export type GrammarHistoryResult = + | { ok: true; data: GrammarSessionHistory } + | { ok: false; message: string }; +export interface GrammarHistoryProps { + readonly noteId: string; + readonly initialData?: GrammarSessionHistory; + readonly load: (noteId: string, page: number) => Promise; +} diff --git a/src/features/grammar-history/services/actions/getGrammarHistory.ts b/src/features/grammar-history/services/actions/getGrammarHistory.ts new file mode 100644 index 00000000..3c90c10a --- /dev/null +++ b/src/features/grammar-history/services/actions/getGrammarHistory.ts @@ -0,0 +1,31 @@ +"use server"; +import { z } from "zod"; +import { GrammarSessionRepository, GrammarSessionError } from "@/entities/grammar-session"; +import { createSupabaseServerClient } from "@/shared/lib/supabase/server"; +import { observeOperation } from "@/shared/lib/logging/observeOperation"; +import { recordOperationEvent } from "@/shared/lib/logging/pino"; +import type { GrammarHistoryResult } from "../../models/interface"; +export async function getGrammarHistory(noteId: string, page = 1): Promise { + try { + return await observeOperation({ + operation: "grammar.history", + resourceId: "grammar-note", + recordEvent: recordOperationEvent, + execute: async () => { + const id = z.string().uuid().parse(noteId); + const requestedPage = z.number().int().min(1).max(2147483647).parse(page); + const supabase = await createSupabaseServerClient(); + const { data, error } = await supabase.auth.getUser(); + if (error || !data.user) throw new GrammarSessionError("UNAUTHORIZED"); + const history = await new GrammarSessionRepository(supabase).findHistory({ + noteId: id, + page: requestedPage, + pageSize: 10, + }); + return { ok: true as const, data: history }; + }, + }); + } catch { + return { ok: false, message: "연습 기록을 불러오지 못했습니다. 다시 시도해주세요." }; + } +} diff --git a/src/features/grammar-history/services/formatPracticeDate.ts b/src/features/grammar-history/services/formatPracticeDate.ts new file mode 100644 index 00000000..8f8c7ab1 --- /dev/null +++ b/src/features/grammar-history/services/formatPracticeDate.ts @@ -0,0 +1,13 @@ +export function formatGrammarPracticeDate(value: string) { + const date = new Date(value); + if (Number.isNaN(date.getTime())) return "날짜 확인 필요"; + return new Intl.DateTimeFormat("ko-KR", { + timeZone: "Asia/Seoul", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hour12: false, + }).format(date); +} diff --git a/src/features/grammar-history/services/useGrammarHistory.ts b/src/features/grammar-history/services/useGrammarHistory.ts new file mode 100644 index 00000000..ea52cf40 --- /dev/null +++ b/src/features/grammar-history/services/useGrammarHistory.ts @@ -0,0 +1,31 @@ +"use client"; +import { useEffect, useRef, useState } from "react"; +import type { GrammarHistoryProps } from "../models/interface"; +export function useGrammarHistory({ noteId, initialData, load }: GrammarHistoryProps) { + const [data, setData] = useState(initialData); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const request = useRef(0); + useEffect(() => { + const lifecycle = request; + return () => { + lifecycle.current++; + }; + }, []); + async function refresh(page = 1) { + const token = ++request.current; + setBusy(true); + setError(""); + try { + const result = await load(noteId, page); + if (token !== request.current) return; + if (result.ok) setData(result.data); + else setError(result.message); + } catch { + if (token === request.current) setError("연습 기록을 불러오지 못했습니다."); + } finally { + if (token === request.current) setBusy(false); + } + } + return { data, busy, error, refresh }; +} diff --git a/src/features/grammar-history/ui/GrammarHistory.tsx b/src/features/grammar-history/ui/GrammarHistory.tsx new file mode 100644 index 00000000..406d7729 --- /dev/null +++ b/src/features/grammar-history/ui/GrammarHistory.tsx @@ -0,0 +1,113 @@ +"use client"; +import { useState } from "react"; +import { + Dialog, + DialogContent, + DialogTitle, + DialogDescription, + DialogHeader, + DialogFooter, + DialogClose, + DialogTrigger, +} from "@/shared/components/ui/dialog"; +import type { GrammarHistoryProps } from "../models/interface"; +import { useGrammarHistory } from "../services/useGrammarHistory"; +import { formatGrammarPracticeDate } from "../services/formatPracticeDate"; +import { GrammarHistoryRows } from "./GrammarHistoryRows"; +export function GrammarHistory(props: GrammarHistoryProps) { + const [open, setOpen] = useState(false); + const { data, busy, error, refresh } = useGrammarHistory(props); + const total = data?.total ?? 0; + const last = + props.initialData?.items[0]?.completedAt ?? + (data?.page === 1 ? data.items[0]?.completedAt : undefined); + function changeOpen(next: boolean) { + setOpen(next); + if (next) void refresh(1); + } + return ( +
+

나의 연습

+

+ {data ? `완료한 연습 ${total}회` : "완료한 연습 기록을 확인해보세요."} + {last && ` · 최근 ${formatGrammarPracticeDate(last)}`} +

+ + + + + + + 연습 기록 + +
+ + 완료한 연습만 집계합니다. 날짜는 한국 시간 기준입니다. + + {busy ? ( +
+
+
+
+ ) : error ? ( +
+

+ {error} +

+ +
+ ) : ( + + )} +
+ +
+ + + {data?.page ?? 1} / {Math.max(1, Math.ceil(total / (data?.pageSize ?? 10)))} + + +
+ + + +
+ +
+
+ ); +} diff --git a/src/features/grammar-history/ui/GrammarHistoryRows.tsx b/src/features/grammar-history/ui/GrammarHistoryRows.tsx new file mode 100644 index 00000000..fde13319 --- /dev/null +++ b/src/features/grammar-history/ui/GrammarHistoryRows.tsx @@ -0,0 +1,34 @@ +import Link from "next/link"; +import type { GrammarSessionSummary } from "@/entities/grammar-session"; +import { formatGrammarPracticeDate } from "../services/formatPracticeDate"; +export function GrammarHistoryRows({ items }: { items: readonly GrammarSessionSummary[] }) { + if (!items.length) + return ( +

+ 아직 완료한 연습이 없습니다. +

+ ); + return ( +
    + {items.map((item) => ( +
  • + +
    + +

    + {item.mode === "recall" ? "암기 연습" : "시험 연습"} · {item.questionCount}문장 · + 완료 +

    +
    + 결과 보기 → + +
  • + ))} +
+ ); +} From 6b2139cad0fa06f0ece1997eff9265f57c9006d1 Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Thu, 8 Oct 2026 18:25:45 +0900 Subject: [PATCH 02/19] fix: address grammar editor review feedback (#168) --- .../GrammarNoteEditor.stories.tsx | 2 +- .../GrammarAnalysisEditor.test.tsx | 19 +++++++- .../editAnalysis.test.ts | 35 ++++++++++++++ .../GrammarNoteEditor.test.tsx | 47 +++++++++++++++++++ .../createEditorStore.test.ts | 8 ++-- .../saveGrammarNote.test.ts | 4 +- .../grammar-analysis-edit/models/store.ts | 19 ++++++-- .../ui/AnalysisEditorProvider.tsx | 19 +++----- .../grammar-note-editor/models/interface.ts | 11 ++++- .../services/actions/saveGrammarNote.ts | 10 +--- .../services/createEditorStore.ts | 27 ++++++----- .../grammar-note-editor/ui/EditorError.tsx | 31 ++++++++++++ .../grammar-note-editor/ui/EditorProvider.tsx | 26 +++++++--- .../ui/GrammarNoteEditor.tsx | 8 +--- .../grammar-editor/GrammarEditorClient.tsx | 33 +++++++++++++ .../grammar-editor/GrammarEditorView.tsx | 24 +--------- 16 files changed, 239 insertions(+), 84 deletions(-) create mode 100644 src/features/grammar-note-editor/ui/EditorError.tsx create mode 100644 src/views/grammar-editor/GrammarEditorClient.tsx diff --git a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx index 6122136c..1e5f862b 100644 --- a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx +++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx @@ -54,7 +54,7 @@ export const SaveFailure: Story = { initialNote: note, save: fn(async () => ({ ok: false as const, - message: "노트를 저장하지 못했습니다. 다시 저장해 주세요.", + code: "PERSISTENCE_FAILED", })), }, play: async ({ canvasElement }) => { diff --git a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx index 721257e8..2b20386e 100644 --- a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx +++ b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx @@ -118,16 +118,31 @@ it("preserves drafts on parent rerender and notifies the current callback", asyn const user = userEvent.setup(); const original = jest.fn(); const current = jest.fn(); + const originalDirty = jest.fn(); + const currentDirty = jest.fn(); const { rerender } = render( - , + , ); await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.type(screen.getByLabelText("직독직해"), " 수정"); - rerender(); + expect(originalDirty.mock.calls).toEqual([[true]]); + rerender( + , + ); expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); await user.click(screen.getByRole("button", { name: "풀이 적용" })); expect(original).not.toHaveBeenCalled(); expect(current).toHaveBeenCalledTimes(1); + expect(originalDirty.mock.calls).toEqual([[true]]); + expect(currentDirty.mock.calls).toEqual([[false]]); }); it("starts a fresh editor when the document key changes", async () => { diff --git a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts index 658ee212..7e68b2cb 100644 --- a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts +++ b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts @@ -190,3 +190,38 @@ it("updates only explanation fields even when the supplied object contains chunk }); expect(result.analysis.sourceText).toBe(source.sourceText); }); + +it("notifies dirty changes within editing events and keeps failed/discard-cancelled drafts dirty", () => { + const onDirtyChange = jest.fn(); + const store = createAnalysisEditorStore({ + initialAnalysis: createGrammarAnalysis(), + onChange: jest.fn(), + onDirtyChange, + }); + store.getState().markDirty(); + expect(onDirtyChange).not.toHaveBeenCalled(); + store.getState().startEditing(); + store.getState().markDirty(); + store.getState().markDirty(); + expect(onDirtyChange.mock.calls).toEqual([[true]]); + const failed = store.getState().edit((service) => + service.saveSyntax({ + id: "s", + ranges: [{ start: 0, end: 1 }], + parentId: "s", + role: "other", + label: "invalid", + explanation: "", + }), + ); + expect(failed.ok).toBe(false); + expect(store.getState().dirty).toBe(true); + store.getState().finishEditing(); + store.getState().resolveSelection(false); + expect(store.getState().dirty).toBe(true); + expect(onDirtyChange.mock.calls).toEqual([[true]]); + store.getState().finishEditing(); + store.getState().resolveSelection(true); + expect(store.getState().dirty).toBe(false); + expect(onDirtyChange.mock.calls).toEqual([[true], [false]]); +}); diff --git a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx index 0fc45d68..eba9dd01 100644 --- a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx +++ b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx @@ -3,6 +3,7 @@ import { describe, expect, it, jest } from "@jest/globals"; import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { GrammarNoteEditor, type GrammarNoteEditorProps } from "@/features/grammar-note-editor"; +import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note"; import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; import { createEditorNote } from "./fixtures"; Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); @@ -64,3 +65,49 @@ describe("분석 초안과 노트 저장 연결", () => { expect(screen.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence); }); }); + +it.each<[GrammarNotePersistenceErrorCode, string]>([ + ["UNAUTHORIZED", "로그인 후 다시 저장해 주세요."], + ["VERSION_CONFLICT", "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요."], + ["PERSISTENCE_FAILED", "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요."], +])("%s 저장 오류의 안내는 UI에서 선택하고 재시도할 내용을 유지한다", async (code, message) => { + const { user, save } = setup(); + save.mockResolvedValue({ ok: false, code }); + await user.click(screen.getByRole("button", { name: "분석 수정" })); + await user.type(screen.getByLabelText("직독직해"), " 수정"); + await user.click(screen.getByRole("button", { name: "풀이 적용" })); + await user.click(screen.getByRole("checkbox")); + await user.click(screen.getByRole("button", { name: "검토 완료 · 노트 저장" })); + expect(await screen.findByRole("alert")).toHaveTextContent(message); + expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); + expect(screen.getByRole("button", { name: "검토 완료 · 노트 저장" })).toBeEnabled(); +}); + +it("부모가 다시 렌더링되어도 입력을 유지하고 새 분석 콜백을 호출한다", async () => { + const note = createEditorNote(); + const original = jest.fn(); + const current = jest + .fn() + .mockResolvedValue({ status: "error", message: "분석 서비스 오류" }); + const props = { + save: jest.fn(), + AnalysisEditor: GrammarAnalysisEditor, + onSaved: jest.fn(), + onExit: jest.fn(), + }; + const { rerender } = render(); + const user = userEvent.setup(); + await user.type(screen.getByLabelText(/영어 문장/), note.source.sentence); + await user.type(screen.getByLabelText(/핵심 어법 설명/), note.source.learningNote); + rerender(); + expect(screen.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence); + await user.click(screen.getByRole("button", { name: "문장 분석하기" })); + expect(original).not.toHaveBeenCalled(); + expect(current).toHaveBeenCalledWith( + expect.objectContaining({ + sentence: note.source.sentence, + learningNote: note.source.learningNote, + }), + ); + expect(await screen.findByRole("alert")).toHaveTextContent("분석 서비스 오류"); +}); diff --git a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts index 4a284aa3..fc55e7b5 100644 --- a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts +++ b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts @@ -80,7 +80,7 @@ describe("어법 등록 이벤트", () => { reviewed: true, }); await store.getState().save(); - expect(store.getState().error).toContain("다시 저장"); + expect(store.getState().error).toEqual({ code: "PERSISTENCE_FAILED" }); await store.getState().save(); expect(deps.save.mock.calls[0][0].requestId).toBe(deps.save.mock.calls[1][0].requestId); expect(deps.onSaved).toHaveBeenCalledTimes(1); @@ -120,11 +120,11 @@ describe("어법 등록 이벤트", () => { }); const store = createEditorStore(deps); await store.getState().analyze(); - expect(store.getState().error).toContain("분석"); + expect(store.getState().error).toEqual({ code: "ANALYSIS_FAILED" }); }); it("편집 저장은 읽은 버전을 전달하고 충돌시 초안을 유지한다", async () => { const deps = dependencies(); - deps.save.mockResolvedValue({ ok: false, message: "버전 충돌" }); + deps.save.mockResolvedValue({ ok: false, code: "VERSION_CONFLICT" }); const store = createEditorStore(deps); store.getState().setReviewed(true); await store.getState().save(); @@ -133,6 +133,6 @@ describe("어법 등록 이벤트", () => { expectedVersion: 1, }); expect(store.getState().result).not.toBeNull(); - expect(store.getState().error).toBe("버전 충돌"); + expect(store.getState().error).toEqual({ code: "VERSION_CONFLICT" }); }); }); diff --git a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts index f694d168..7b002b4a 100644 --- a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts +++ b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts @@ -44,7 +44,7 @@ describe("어법 저장 서버 경계", () => { const create = jest.spyOn(GrammarNoteRepository.prototype, "create"); expect(await saveGrammarNote(command())).toEqual({ ok: false, - message: "로그인 후 다시 저장해 주세요.", + code: "UNAUTHORIZED", }); expect(create).not.toHaveBeenCalled(); }); @@ -94,7 +94,7 @@ describe("어법 저장 서버 경계", () => { }); expect(result).toEqual({ ok: false, - message: "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요.", + code: "VERSION_CONFLICT", }); }); it("실패는 내부 이벤트로 기록하고 원문과 내부 오류를 UI에 노출하지 않는다", async () => { diff --git a/src/features/grammar-analysis-edit/models/store.ts b/src/features/grammar-analysis-edit/models/store.ts index 61d6126a..ad34a4ea 100644 --- a/src/features/grammar-analysis-edit/models/store.ts +++ b/src/features/grammar-analysis-edit/models/store.ts @@ -4,7 +4,11 @@ import type { AnalysisEditorProps, AnalysisEditorState } from "./interface"; import { applyAnalysisEdits } from "../services/applyAnalysisEdits"; /** 에디터 수명에 맞춰 상태를 생성한다. onChange는 성공한 편집을 상위 문서에 전달한다. */ -export function createAnalysisEditorStore({ initialAnalysis, onChange }: AnalysisEditorProps) { +export function createAnalysisEditorStore({ + initialAnalysis, + onChange, + onDirtyChange, +}: AnalysisEditorProps) { return createStore((set, get) => ({ analysis: sentenceAnalysisSchema.parse(initialAnalysis), selectedId: null, @@ -39,20 +43,24 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi return result; }, markDirty: () => { - if (get().editing) set({ dirty: true }); + if (!get().editing || get().dirty) return; + set({ dirty: true }); + onDirtyChange?.(true); }, resolveSelection: (discard) => { const pending = get().pendingSelection; - if (discard && pending) + if (discard && pending) { set({ selectedId: pending.id, editing: pending.editing, dirty: false, + pendingSelection: null, readingId: get().analysis.chunks.some((chunk) => chunk.id === pending.id) ? pending.id : get().readingId, }); - set({ pendingSelection: null }); + onDirtyChange?.(false); + } else set({ pendingSelection: null }); }, select: (selectedId) => { if (get().dirty) set({ pendingSelection: { id: selectedId, editing: get().editing } }); @@ -72,13 +80,14 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi ...result.analysis.syntax, ...result.analysis.constructions, ].map((item) => item.id); - const selectedId = get().selectedId; + const { selectedId, dirty } = get(); set({ dirty: false, analysis: result.analysis, selectedId: selectedId && ids.includes(selectedId) ? selectedId : null, }); onChange(result.analysis); + if (dirty) onDirtyChange?.(false); } return result; }, diff --git a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx index 8e2b19ff..fab08ee1 100644 --- a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx +++ b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx @@ -1,6 +1,6 @@ "use client"; -import { createContext, useContext, useEffect, useRef, useState } from "react"; +import { createContext, useContext, useLayoutEffect, useRef, useState } from "react"; import { useStore } from "zustand"; import type { StoreApi } from "zustand"; import type { AnalysisEditorProviderProps, AnalysisEditorState } from "../models/interface"; @@ -20,22 +20,17 @@ export function AnalysisEditorProvider({ children, }: AnalysisEditorProviderProps) { // 부모가 콜백을 변경해도 편집 상태를 초기화하지 않고 최신 수신자에게 알린다. - const onChangeRef = useRef(onChange); - useEffect(() => { - onChangeRef.current = onChange; - }, [onChange]); + const callbacks = useRef({ onChange, onDirtyChange }); + useLayoutEffect(() => { + callbacks.current = { onChange, onDirtyChange }; + }, [onChange, onDirtyChange]); const [store] = useState(() => createAnalysisEditorStore({ initialAnalysis, - onChange: (analysis) => onChangeRef.current(analysis), + onChange: (analysis) => callbacks.current.onChange(analysis), + onDirtyChange: (dirty) => callbacks.current.onDirtyChange?.(dirty), }), ); - useEffect(() => { - onDirtyChange?.(store.getState().dirty); - return store.subscribe((state, previous) => { - if (state.dirty !== previous.dirty) onDirtyChange?.(state.dirty); - }); - }, [store, onDirtyChange]); return {children}; } diff --git a/src/features/grammar-note-editor/models/interface.ts b/src/features/grammar-note-editor/models/interface.ts index 86244e69..8162b773 100644 --- a/src/features/grammar-note-editor/models/interface.ts +++ b/src/features/grammar-note-editor/models/interface.ts @@ -3,6 +3,7 @@ import type { GrammarMetadata, GrammarNote, GrammarNoteContent, + GrammarNotePersistenceErrorCode, GrammarSource, PrecheckResult, SentenceAnalysis, @@ -17,7 +18,9 @@ export type SaveNoteCommand = { content: GrammarNoteContent; existing?: { id: string; expectedVersion: number }; }; -export type SaveNoteResult = { ok: true; note: GrammarNote } | { ok: false; message: string }; +export type SaveNoteResult = + | { ok: true; note: GrammarNote } + | { ok: false; code: GrammarNotePersistenceErrorCode }; export interface GrammarNoteEditorProps { initialNote?: GrammarNote; analyze: (source: GrammarSource) => Promise; @@ -30,12 +33,16 @@ export interface GrammarNoteEditorProps { onSaved: (note: GrammarNote) => void; onExit: () => void; } +export type EditorError = + | { code: GrammarNotePersistenceErrorCode | "ANALYSIS_FAILED" | "INVALID_ANALYSIS" } + | { message: string }; + export interface EditorState { source: GrammarSource; result: EditorAnalysisResult | null; stage: "input" | "review"; pending: "analysis" | "save" | null; - error: string; + error: EditorError | null; fieldErrors: Partial>; reviewed: boolean; analysisDirty: boolean; diff --git a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts index 10cbf14e..bc075299 100644 --- a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts +++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts @@ -22,14 +22,6 @@ export async function saveGrammarNote(command: SaveNoteCommand): Promise - set({ analysisDirty, ...(analysisDirty ? { dirty: true, reviewed: false } : {}) }), + setAnalysisDirty: (analysisDirty) => { + if (get().analysisDirty === analysisDirty) return; + set({ analysisDirty, ...(analysisDirty ? { dirty: true, reviewed: false } : {}) }); + }, dirty: false, changeSource: (field, value) => { if (get().pending === "save") return; @@ -36,7 +38,7 @@ export function createEditorStore( pending: null, reviewed: false, dirty: true, - error: "", + error: null, fieldErrors: {}, })); }, @@ -46,6 +48,7 @@ export function createEditorStore( ? { result: { status: "analyzed", data: { ...state.result.data, analysis } }, reviewed: false, + analysisDirty: false, dirty: true, } : {}, @@ -54,7 +57,7 @@ export function createEditorStore( back: () => { if (get().pending === "save") return; generation++; - set({ stage: "input", pending: null, error: "", analysisDirty: false }); + set({ stage: "input", pending: null, error: null, analysisDirty: false }); }, cancel: () => { generation++; @@ -70,7 +73,7 @@ export function createEditorStore( return; } const currentGeneration = ++generation; - set({ pending: "analysis", error: "", fieldErrors: {} }); + set({ pending: "analysis", error: null, fieldErrors: {} }); try { const result = await dependencies.analyze(parsed.data); if (currentGeneration !== generation) return; @@ -93,13 +96,13 @@ export function createEditorStore( pending: null, stage: result.status === "analyzed" ? "review" : "input", reviewed: false, - error: result.status === "error" ? result.message : "", + error: result.status === "error" ? { message: result.message } : null, }); } catch { if (currentGeneration === generation) set({ pending: null, - error: "분석을 완료하지 못했습니다. 입력을 유지했으니 다시 시도해 주세요.", + error: { code: "ANALYSIS_FAILED" }, }); } }, @@ -119,14 +122,14 @@ export function createEditorStore( examples: initialNote?.examples ?? [], }); if (!content.success) { - set({ error: "분석과 입력을 다시 확인해 주세요." }); + set({ error: { code: "INVALID_ANALYSIS" } }); return; } const signature = JSON.stringify(content.data); // 동일 저장의 네트워크 재시도에는 동일 UUID를 보내 서버 중복 생성을 막는다. if (saveIdentity?.content !== signature) saveIdentity = { content: signature, id: crypto.randomUUID() }; - set({ pending: "save", error: "" }); + set({ pending: "save", error: null }); try { const result = await dependencies.save({ requestId: saveIdentity.id, @@ -136,13 +139,13 @@ export function createEditorStore( : {}), }); if (!result.ok) { - set({ pending: null, error: result.message }); + set({ pending: null, error: { code: result.code } }); return; } set({ pending: null, dirty: false }); dependencies.onSaved(result.note); } catch { - set({ pending: null, error: "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요." }); + set({ pending: null, error: { code: "PERSISTENCE_FAILED" } }); } }, })); diff --git a/src/features/grammar-note-editor/ui/EditorError.tsx b/src/features/grammar-note-editor/ui/EditorError.tsx new file mode 100644 index 00000000..c3530336 --- /dev/null +++ b/src/features/grammar-note-editor/ui/EditorError.tsx @@ -0,0 +1,31 @@ +"use client"; +import { useEditor } from "./EditorProvider"; +export function EditorError() { + const error = useEditor((s) => s.error); + if (!error) return null; + let message: string; + if ("message" in error) message = error.message; + else { + switch (error.code) { + case "VERSION_CONFLICT": + message = "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요."; + break; + case "UNAUTHORIZED": + message = "로그인 후 다시 저장해 주세요."; + break; + case "ANALYSIS_FAILED": + message = "분석을 완료하지 못했습니다. 입력을 유지했으니 다시 시도해 주세요."; + break; + case "INVALID_ANALYSIS": + message = "분석과 입력을 다시 확인해 주세요."; + break; + default: + message = "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요."; + } + } + return ( +

+ {message} +

+ ); +} diff --git a/src/features/grammar-note-editor/ui/EditorProvider.tsx b/src/features/grammar-note-editor/ui/EditorProvider.tsx index 220c2380..71b58a21 100644 --- a/src/features/grammar-note-editor/ui/EditorProvider.tsx +++ b/src/features/grammar-note-editor/ui/EditorProvider.tsx @@ -1,5 +1,13 @@ "use client"; -import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; +import { + createContext, + useContext, + useEffect, + useLayoutEffect, + useRef, + useState, + type ReactNode, +} from "react"; import { useStore } from "zustand"; import type { StoreApi } from "zustand"; import type { EditorState, GrammarNoteEditorProps } from "../models/interface"; @@ -7,15 +15,19 @@ import { createEditorStore } from "../services/createEditorStore"; const Context = createContext | null>(null); export function EditorProvider({ children, - ...dependencies + initialNote, + analyze, + save, + onSaved, }: Omit & { children: ReactNode }) { - const latest = useRef(dependencies); - useEffect(() => { - latest.current = dependencies; - }, [dependencies]); + const latest = useRef({ analyze, save, onSaved }); + useLayoutEffect(() => { + latest.current = { analyze, save, onSaved }; + }, [analyze, save, onSaved]); + // initialNote는 초기값이다. 문서 ID·버전이 바뀌면 호출부에서 key로 새 세션을 연다. const [store] = useState(() => createEditorStore({ - initialNote: dependencies.initialNote, + initialNote, analyze: (source) => latest.current.analyze(source), save: (command) => latest.current.save(command), onSaved: (note) => latest.current.onSaved(note), diff --git a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx index 1efef5e0..9a78b3cc 100644 --- a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx +++ b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx @@ -4,6 +4,7 @@ import { Button } from "@/shared/components/atomics/button/Button"; import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog"; import type { GrammarNoteEditorProps } from "../models/interface"; import { EditorProvider, useEditor } from "./EditorProvider"; +import { EditorError } from "./EditorError"; import { SourceStep } from "./SourceStep"; import { ReviewStep } from "./ReviewStep"; function EditorBody({ @@ -11,16 +12,11 @@ function EditorBody({ onExit, }: Pick) { const stage = useEditor((s) => s.stage); - const error = useEditor((s) => s.error); return (
{stage === "input" ? : } - {error && ( -

- {error} -

- )} +
); } diff --git a/src/views/grammar-editor/GrammarEditorClient.tsx b/src/views/grammar-editor/GrammarEditorClient.tsx new file mode 100644 index 00000000..f31f4730 --- /dev/null +++ b/src/views/grammar-editor/GrammarEditorClient.tsx @@ -0,0 +1,33 @@ +"use client"; +import { useRouter } from "next/navigation"; +import type { GrammarNote } from "@/entities/grammar-note"; +import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; +import { requestGrammarAnalysis } from "@/features/grammar-analysis/services/actions/requestGrammarAnalysis"; +import { GrammarNoteEditor } from "@/features/grammar-note-editor"; +import { saveGrammarNote } from "@/features/grammar-note-editor/services/actions/saveGrammarNote"; + +export function GrammarEditorClient({ + initialNote, + backHref, +}: { + initialNote?: GrammarNote; + backHref: string; +}) { + const router = useRouter(); + const returnTo = + backHref === "/grammar" || backHref.startsWith("/grammar?") ? backHref : "/grammar"; + return ( + { + router.push(`/grammar/${note.id}?returnTo=${encodeURIComponent(returnTo)}`); + router.refresh(); + }} + onExit={() => router.push(returnTo)} + /> + ); +} diff --git a/src/views/grammar-editor/GrammarEditorView.tsx b/src/views/grammar-editor/GrammarEditorView.tsx index d0fd5b91..f638d6e1 100644 --- a/src/views/grammar-editor/GrammarEditorView.tsx +++ b/src/views/grammar-editor/GrammarEditorView.tsx @@ -1,12 +1,6 @@ -"use client"; -import { useRouter } from "next/navigation"; import type { GrammarNote } from "@/entities/grammar-note"; -import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; -import { requestGrammarAnalysis } from "@/features/grammar-analysis/services/actions/requestGrammarAnalysis"; -import { GrammarNoteEditor } from "@/features/grammar-note-editor"; -import { saveGrammarNote } from "@/features/grammar-note-editor/services/actions/saveGrammarNote"; +import { GrammarEditorClient } from "./GrammarEditorClient"; -// 다른 노트나 최신 저장 버전을 열 때 이전 초안이 섞이지 않도록 에디터 key에 ID와 버전을 함께 쓴다. export function GrammarEditorView({ initialNote, backHref = "/grammar", @@ -14,9 +8,6 @@ export function GrammarEditorView({ initialNote?: GrammarNote; backHref?: string; }) { - const router = useRouter(); - const returnTo = - backHref === "/grammar" || backHref.startsWith("/grammar?") ? backHref : "/grammar"; return (
@@ -29,18 +20,7 @@ export function GrammarEditorView({

- { - router.push(`/grammar/${note.id}?returnTo=${encodeURIComponent(returnTo)}`); - router.refresh(); - }} - onExit={() => router.push(returnTo)} - /> +
); From 29e90c52d46e77b851d631ca89646de9ebde36ef Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Thu, 8 Oct 2026 18:49:54 +0900 Subject: [PATCH 03/19] refactor: apply shared review rules to example editing (#169) --- .../GrammarExampleManager.stories.tsx | 2 +- .../GrammarExampleManager.test.tsx | 38 +++++++++++++++++++ .../createExampleStore.test.ts | 4 +- .../exampleActions.test.ts | 10 ++--- .../models/errors.ts | 34 +++++++---------- .../models/interface.ts | 5 ++- .../services/createExampleStore.ts | 18 ++++----- .../services/server/executeExampleAction.ts | 4 +- .../ui/ExampleActions.tsx | 3 +- .../ui/ExampleProvider.tsx | 27 +++++++++---- .../ui/GrammarExampleManager.tsx | 2 +- .../ui/errorMessage.ts | 23 +++++++++++ 12 files changed, 120 insertions(+), 50 deletions(-) create mode 100644 src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx create mode 100644 src/features/grammar-example-generation/ui/errorMessage.ts diff --git a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx index c23634cb..f5d226ec 100644 --- a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx +++ b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx @@ -55,7 +55,7 @@ export const Retry: Story = { play: async ({ canvasElement, args }) => { args.generate.mockResolvedValueOnce({ ok: false, - message: "생성에 실패했습니다. 다시 생성해 주세요.", + code: "FAILED", }); const canvas = within(canvasElement); await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" })); diff --git a/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx new file mode 100644 index 00000000..7f3196d0 --- /dev/null +++ b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx @@ -0,0 +1,38 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import { fireEvent, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { + GrammarExampleManager, + type GrammarExampleManagerProps, +} from "@/features/grammar-example-generation"; +import { createEditorNote } from "../grammar-note-editor/fixtures"; +import { createExampleCandidates } from "./fixtures"; +describe("예문 편집 세션", () => { + it("같은 노트의 버전 갱신에는 초안을 유지하고 최신 콜백을 쓰며 다른 노트에는 초기화한다", async () => { + const note = createEditorNote(); + const generate = jest + .fn() + .mockResolvedValue({ ok: true, data: createExampleCandidates() }); + const save = jest.fn(); + const latestSave = jest + .fn() + .mockResolvedValue({ ok: false, code: "VERSION_CONFLICT" }); + const props = { note, generate, save, onUpdated: jest.fn() }; + const { rerender } = render(); + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: "예문 3개 생성" })); + fireEvent.change((await screen.findAllByLabelText("영어 예문"))[0], { + target: { value: "Edited sentence." }, + }); + await user.click(screen.getAllByRole("checkbox")[0]); + rerender(); + expect(screen.getAllByLabelText("영어 예문")[0]).toHaveValue("Edited sentence."); + await user.click(screen.getByRole("button", { name: "선택한 예문 1개 저장" })); + expect(save).not.toHaveBeenCalled(); + expect(latestSave).toHaveBeenCalledWith(expect.objectContaining({ expectedVersion: 1 })); + expect(await screen.findByRole("alert")).toHaveTextContent("노트가 변경되었습니다"); + expect(screen.getAllByRole("checkbox")[0]).toBeChecked(); + rerender(); + expect(screen.queryByLabelText("영어 예문")).not.toBeInTheDocument(); + }); +}); diff --git a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts index 0be40034..d5db6aad 100644 --- a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts +++ b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts @@ -24,11 +24,11 @@ describe("예문 초안 이벤트", () => { await store.getState().generate(); store.getState().change("candidate-0", "sentence", "Edited sentence"); store.getState().select("candidate-0", true); - generate.mockResolvedValue({ ok: false, message: "실패" }); + generate.mockResolvedValue({ ok: false, code: "FAILED" }); await store.getState().generate("candidate-1"); expect(store.getState().candidates[0].sentence).toBe("Edited sentence"); expect(store.getState().selected).toEqual(["candidate-0"]); - expect(store.getState().error).toBe("실패"); + expect(store.getState().error).toBe("FAILED"); }); it("부분 재생성은 다른 수정본을 건드리지 않는다", async () => { const { store, generate } = setup(); diff --git a/src/_tests/features/grammar-example-generation/exampleActions.test.ts b/src/_tests/features/grammar-example-generation/exampleActions.test.ts index a1ae9573..4225c298 100644 --- a/src/_tests/features/grammar-example-generation/exampleActions.test.ts +++ b/src/_tests/features/grammar-example-generation/exampleActions.test.ts @@ -64,10 +64,10 @@ describe("예문 서버 액션 권한", () => { expect(requestExampleOutput).not.toHaveBeenCalled(); }); it.each([ - ["not_invited", "AI 기능을 사용할 권한이 없습니다."], - ["rate_limited", "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."], - ["unexpected", "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요."], - ])("권한 %s이면 AI를 실행하지 않는다", async (permission, message) => { + ["not_invited", "NOT_INVITED"], + ["rate_limited", "RATE_LIMITED"], + ["unexpected", "FAILED"], + ])("권한 %s이면 AI를 실행하지 않는다", async (permission, code) => { jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(createEditorNote()); rpc.mockResolvedValue({ data: permission, error: null }); const result = await requestGrammarExamples({ @@ -75,7 +75,7 @@ describe("예문 서버 액션 권한", () => { expectedVersion: 1, count: 3, }); - expect(result).toEqual({ ok: false, message }); + expect(result).toEqual({ ok: false, code }); expect(requestExampleOutput).not.toHaveBeenCalled(); }); it("한도 조회 실패를 허용으로 처리하지 않는다", async () => { diff --git a/src/features/grammar-example-generation/models/errors.ts b/src/features/grammar-example-generation/models/errors.ts index f4f92640..203bb768 100644 --- a/src/features/grammar-example-generation/models/errors.ts +++ b/src/features/grammar-example-generation/models/errors.ts @@ -1,22 +1,16 @@ import { GrammarNotePersistenceError } from "@/entities/grammar-note"; - -const messages = new Map([ - ["VERSION_CONFLICT", "노트가 변경되었습니다. 최신 노트를 불러온 뒤 다시 시도해 주세요."], - ["UNAUTHORIZED", "로그인 후 다시 시도해 주세요."], - ["NOT_FOUND", "노트를 찾을 수 없습니다."], - ["rate_limited", "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."], - ["not_invited", "AI 기능을 사용할 권한이 없습니다."], -]); - -export function grammarExampleErrorMessage(error: unknown): string { - const code = - error instanceof GrammarNotePersistenceError - ? error.code - : error instanceof Error - ? error.message - : "UNKNOWN"; - return ( - messages.get(code) ?? - "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요." - ); +import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note"; +export type ExampleErrorCode = + | GrammarNotePersistenceErrorCode + | "NOT_INVITED" + | "RATE_LIMITED" + | "FAILED" + | "GENERATION_FAILED" + | "SAVE_FAILED" + | "INVALID_SELECTION"; +export function grammarExampleErrorCode(error: unknown): ExampleErrorCode { + if (error instanceof GrammarNotePersistenceError) return error.code; + if (error instanceof Error && error.message === "not_invited") return "NOT_INVITED"; + if (error instanceof Error && error.message === "rate_limited") return "RATE_LIMITED"; + return "FAILED"; } diff --git a/src/features/grammar-example-generation/models/interface.ts b/src/features/grammar-example-generation/models/interface.ts index cb4ec544..eb16bcfd 100644 --- a/src/features/grammar-example-generation/models/interface.ts +++ b/src/features/grammar-example-generation/models/interface.ts @@ -1,3 +1,4 @@ +import type { ExampleErrorCode } from "./errors"; import type { GrammarExample, GrammarNote, @@ -13,7 +14,7 @@ export interface SaveExamplesCommand { expectedVersion: number; candidates: readonly GrammarExample[]; } -export type ExampleResult = { ok: true; data: T } | { ok: false; message: string }; +export type ExampleResult = { ok: true; data: T } | { ok: false; code: ExampleErrorCode }; export interface ExampleDependencies { repository: GrammarNoteRepositoryPort; generate: (note: GrammarNote, count: 1 | 3) => Promise; @@ -31,7 +32,7 @@ export interface ExampleState { candidates: readonly GrammarExample[]; selected: readonly string[]; pending: string | null; - error: string; + error: ExampleErrorCode | null; dirty: boolean; change: ( id: string, diff --git a/src/features/grammar-example-generation/services/createExampleStore.ts b/src/features/grammar-example-generation/services/createExampleStore.ts index 20953068..0a464464 100644 --- a/src/features/grammar-example-generation/services/createExampleStore.ts +++ b/src/features/grammar-example-generation/services/createExampleStore.ts @@ -9,14 +9,14 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { candidates: [], selected: [], pending: null, - error: "", + error: null, dirty: false, cancel: () => { generation++; }, discard: () => { generation++; - set({ candidates: [], selected: [], pending: null, error: "", dirty: false }); + set({ candidates: [], selected: [], pending: null, error: null, dirty: false }); }, change: (id, field, value) => { if (get().pending === "save") return; @@ -44,7 +44,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { if (state.pending) return; if (id && !state.candidates.some((candidate) => candidate.id === id)) return; const currentGeneration = ++generation; - set({ pending: id ?? "all", error: "" }); + set({ pending: id ?? "all", error: null }); try { const result = await dependencies.generate({ noteId: state.note.id, @@ -53,7 +53,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { }); if (currentGeneration !== generation) return; if (!result.ok) { - set({ pending: null, error: result.message }); + set({ pending: null, error: result.code }); return; } const candidates = result.data.map((candidate) => grammarExampleSchema.parse(candidate)); @@ -83,7 +83,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { if (currentGeneration === generation) set({ pending: null, - error: "예문 생성에 실패했습니다. 기존 후보를 유지했으니 다시 생성해 주세요.", + error: "GENERATION_FAILED", }); } }, @@ -97,10 +97,10 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { !candidates.length || candidates.some((candidate) => !grammarExampleSchema.safeParse(candidate).success) ) { - set({ error: "저장할 예문을 선택하고 문장·뜻·어법 설명을 모두 입력해 주세요." }); + set({ error: "INVALID_SELECTION" }); return; } - set({ pending: "save", error: "" }); + set({ pending: "save", error: null }); try { const result = await dependencies.save({ noteId: state.note.id, @@ -108,7 +108,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { candidates, }); if (!result.ok) { - set({ pending: null, error: result.message }); + set({ pending: null, error: result.code }); return; } set((current) => ({ @@ -124,7 +124,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { } catch { set({ pending: null, - error: "예문을 저장하지 못했습니다. 선택과 수정 내용을 유지했습니다. 다시 저장해 주세요.", + error: "SAVE_FAILED", }); } }, diff --git a/src/features/grammar-example-generation/services/server/executeExampleAction.ts b/src/features/grammar-example-generation/services/server/executeExampleAction.ts index 62da348c..a5180a83 100644 --- a/src/features/grammar-example-generation/services/server/executeExampleAction.ts +++ b/src/features/grammar-example-generation/services/server/executeExampleAction.ts @@ -4,7 +4,7 @@ import { createSupabaseServerClient } from "@/shared/lib/supabase/server"; import { observeOperation } from "@/shared/lib/logging/observeOperation"; import { recordOperationEvent } from "@/shared/lib/logging/pino"; import type { ExampleDependencies, ExampleResult } from "../../models/interface"; -import { grammarExampleErrorMessage } from "../../models/errors"; +import { grammarExampleErrorCode } from "../../models/errors"; import { requestExampleOutput } from "./requestExampleOutput"; export async function executeExampleAction( operation: string, @@ -38,6 +38,6 @@ export async function executeExampleAction( }); return { ok: true, data }; } catch (error) { - return { ok: false, message: grammarExampleErrorMessage(error) }; + return { ok: false, code: grammarExampleErrorCode(error) }; } } diff --git a/src/features/grammar-example-generation/ui/ExampleActions.tsx b/src/features/grammar-example-generation/ui/ExampleActions.tsx index f6624578..c8068564 100644 --- a/src/features/grammar-example-generation/ui/ExampleActions.tsx +++ b/src/features/grammar-example-generation/ui/ExampleActions.tsx @@ -1,5 +1,6 @@ "use client"; import { Button } from "@/shared/components/atomics/button/Button"; +import { exampleErrorMessage } from "./errorMessage"; import { useExamples } from "./ExampleProvider"; export function ExampleActions() { const pending = useExamples((s) => s.pending); @@ -26,7 +27,7 @@ export function ExampleActions() { {error && (

- {error} + {exampleErrorMessage(error)}

)} {pending && ( diff --git a/src/features/grammar-example-generation/ui/ExampleProvider.tsx b/src/features/grammar-example-generation/ui/ExampleProvider.tsx index 54880e88..52176f5b 100644 --- a/src/features/grammar-example-generation/ui/ExampleProvider.tsx +++ b/src/features/grammar-example-generation/ui/ExampleProvider.tsx @@ -1,20 +1,33 @@ "use client"; -import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; +import { + createContext, + useContext, + useEffect, + useLayoutEffect, + useRef, + useState, + type ReactNode, +} from "react"; import { useStore, type StoreApi } from "zustand"; import type { ExampleState, GrammarExampleManagerProps } from "../models/interface"; import { createExampleStore } from "../services/createExampleStore"; const Context = createContext | null>(null); export function ExampleProvider({ children, - ...props + note, + generate, + save, + onUpdated, + onBack, }: GrammarExampleManagerProps & { children: ReactNode }) { - const latest = useRef(props); - useEffect(() => { - latest.current = props; - }, [props]); + const latest = useRef({ generate, save, onUpdated }); + useLayoutEffect(() => { + latest.current = { generate, save, onUpdated }; + }, [generate, save, onUpdated]); const [store] = useState(() => createExampleStore({ - ...props, + note, + onBack, generate: (command) => latest.current.generate(command), save: (command) => latest.current.save(command), onUpdated: (note) => latest.current.onUpdated(note), diff --git a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx index 023efd3c..04b9ef63 100644 --- a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx +++ b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx @@ -39,7 +39,7 @@ function ExampleBack({ onBack }: { onBack?: () => void }) { /** 노트 ID로 생명주기를 구분한다. 선택 저장 후 남은 후보 보존을 위해 버전 변경으로 재마운트하지 않는다. */ export function GrammarExampleManager({ onBack, ...props }: GrammarExampleManagerProps) { return ( - +
diff --git a/src/features/grammar-example-generation/ui/errorMessage.ts b/src/features/grammar-example-generation/ui/errorMessage.ts new file mode 100644 index 00000000..727452f3 --- /dev/null +++ b/src/features/grammar-example-generation/ui/errorMessage.ts @@ -0,0 +1,23 @@ +import type { ExampleErrorCode } from "../models/errors"; +export function exampleErrorMessage(code: ExampleErrorCode): string { + switch (code) { + case "VERSION_CONFLICT": + return "노트가 변경되었습니다. 최신 노트를 불러온 뒤 다시 시도해 주세요."; + case "UNAUTHORIZED": + return "로그인 후 다시 시도해 주세요."; + case "NOT_FOUND": + return "노트를 찾을 수 없습니다."; + case "RATE_LIMITED": + return "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."; + case "NOT_INVITED": + return "AI 기능을 사용할 권한이 없습니다."; + case "GENERATION_FAILED": + return "예문 생성에 실패했습니다. 기존 후보를 유지했으니 다시 생성해 주세요."; + case "SAVE_FAILED": + return "예문을 저장하지 못했습니다. 선택과 수정 내용을 유지했습니다. 다시 저장해 주세요."; + case "INVALID_SELECTION": + return "저장할 예문을 선택하고 문장·뜻·어법 설명을 모두 입력해 주세요."; + default: + return "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요."; + } +} From 7a160e3a8db7ddf5cd4896cbe3e8cabf3136b9e7 Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Thu, 8 Oct 2026 18:51:09 +0900 Subject: [PATCH 04/19] refactor: keep audio error presentation in UI (#171) --- .../GrammarAudioButton.stories.tsx | 2 +- .../features/grammar-audio/audioCache.test.ts | 5 ++++- .../grammar-audio/requestGrammarAudio.test.ts | 12 +++++++++++- .../grammar-audio/useGrammarAudio.test.tsx | 3 ++- src/features/grammar-audio/models/interface.ts | 9 ++++++++- .../services/actions/requestGrammarAudio.ts | 18 ++++++++++-------- .../grammar-audio/services/useGrammarAudio.ts | 16 +++++++++------- .../grammar-audio/ui/GrammarAudioButton.tsx | 7 ++++--- src/features/grammar-audio/ui/errorMessage.ts | 10 ++++++++++ 9 files changed, 59 insertions(+), 23 deletions(-) create mode 100644 src/features/grammar-audio/ui/errorMessage.ts diff --git a/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx b/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx index 1007f167..e713a54e 100644 --- a/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx +++ b/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx @@ -6,7 +6,7 @@ const meta = { component: GrammarAudioButton, args: { input: { noteId: "note", sentenceId: "source", noteVersion: 1 }, - generate: fn(async () => ({ ok: false as const, message: "음성 생성에 실패했습니다." })), + generate: fn(async () => ({ ok: false as const, code: "GENERATION_FAILED" as const })), }, } satisfies Meta; export default meta; diff --git a/src/_tests/features/grammar-audio/audioCache.test.ts b/src/_tests/features/grammar-audio/audioCache.test.ts index 11fc7bac..6d9b7b91 100644 --- a/src/_tests/features/grammar-audio/audioCache.test.ts +++ b/src/_tests/features/grammar-audio/audioCache.test.ts @@ -12,7 +12,10 @@ describe("grammar audio content cache", () => { }); it("deduplicates concurrent generation and does not cache failure", async () => { const { cachedGrammarAudio } = await import("@/features/grammar-audio/services/audioCache"); - const generate = jest.fn(async () => ({ ok: false as const, message: "failed" })); + const generate = jest.fn(async () => ({ + ok: false as const, + code: "GENERATION_FAILED" as const, + })); await Promise.all([ cachedGrammarAudio("unique", generate), cachedGrammarAudio("unique", generate), diff --git a/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts b/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts index 2704b929..64cba289 100644 --- a/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts +++ b/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts @@ -62,7 +62,7 @@ describe("authenticated saved sentence audio action", () => { deps.getUser.mockResolvedValueOnce({ data: { user: null }, error: null } as unknown as Awaited< ReturnType >); - expect((await deps.requestGrammarAudio(input)).ok).toBe(false); + expect(await deps.requestGrammarAudio(input)).toEqual({ ok: false, code: "UNAUTHORIZED" }); expect(deps.findById).not.toHaveBeenCalled(); expect(deps.rpc).not.toHaveBeenCalled(); expect(deps.OpenAITTSProvider).not.toHaveBeenCalled(); @@ -82,6 +82,16 @@ describe("authenticated saved sentence audio action", () => { expect((await deps.requestGrammarAudio(input)).ok).toBe(false); expect(deps.OpenAITTSProvider).not.toHaveBeenCalled(); }); + it.each([ + ["not_invited", "NOT_INVITED"], + ["rate_limited", "RATE_LIMITED"], + ["unexpected", "GENERATION_FAILED"], + ])("returns %s as a code without spending provider cost", async (permission, code) => { + const deps = await dependencies(); + deps.rpc.mockResolvedValueOnce({ data: permission, error: null }); + expect(await deps.requestGrammarAudio(input)).toEqual({ ok: false, code }); + expect(deps.OpenAITTSProvider).not.toHaveBeenCalled(); + }); it("reuses authenticated content cache and sends only stored text to TTS", async () => { const deps = await dependencies(); const first = await deps.requestGrammarAudio(input); diff --git a/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx b/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx index c05c0752..f7ebbdc9 100644 --- a/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx +++ b/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx @@ -69,11 +69,12 @@ describe("grammar audio lifecycle", () => { it("retries generation failure rather than treating it as playback failure", async () => { const generate = jest .fn<() => Promise>() - .mockResolvedValueOnce({ ok: false, message: "failed" }) + .mockResolvedValueOnce({ ok: false, code: "GENERATION_FAILED" }) .mockResolvedValueOnce(speech); const { result } = renderHook(() => useGrammarAudio({ input, generate })); await act(() => result.current.play()); expect(result.current.status).toBe("generation-error"); + expect(result.current.error).toBe("GENERATION_FAILED"); await act(() => result.current.play()); expect(result.current.status).toBe("playing"); expect(generate).toHaveBeenCalledTimes(2); diff --git a/src/features/grammar-audio/models/interface.ts b/src/features/grammar-audio/models/interface.ts index 2889c26f..a2407406 100644 --- a/src/features/grammar-audio/models/interface.ts +++ b/src/features/grammar-audio/models/interface.ts @@ -3,9 +3,16 @@ export interface GrammarAudioInput { readonly sentenceId: string; readonly noteVersion: number; } +export type GrammarAudioErrorCode = + | "INVALID_INPUT" + | "UNAUTHORIZED" + | "NOT_INVITED" + | "RATE_LIMITED" + | "GENERATION_FAILED" + | "PLAYBACK_FAILED"; export type GrammarAudioResult = | { ok: true; audioBase64: string; mimeType: "audio/mpeg"; cacheKey: string } - | { ok: false; message: string }; + | { ok: false; code: GrammarAudioErrorCode }; export type GrammarAudioStatus = | "idle" | "generating" diff --git a/src/features/grammar-audio/services/actions/requestGrammarAudio.ts b/src/features/grammar-audio/services/actions/requestGrammarAudio.ts index 7ba2aab5..d56ed6c1 100644 --- a/src/features/grammar-audio/services/actions/requestGrammarAudio.ts +++ b/src/features/grammar-audio/services/actions/requestGrammarAudio.ts @@ -24,11 +24,10 @@ export async function requestGrammarAudio(input: unknown): Promise { const parsed = schema.safeParse(input); - if (!parsed.success) return { ok: false as const, message: "음성 요청을 확인해주세요." }; + if (!parsed.success) return { ok: false as const, code: "INVALID_INPUT" as const }; const supabase = await createSupabaseServerClient(); const { data, error } = await supabase.auth.getUser(); - if (error || !data.user) - return { ok: false as const, message: "로그인 후 다시 시도해주세요." }; + if (error || !data.user) return { ok: false as const, code: "UNAUTHORIZED" as const }; const note = await new GrammarNoteRepository(supabase).findById(parsed.data.noteId); const text = resolveGrammarAudioText(note, parsed.data); const model = getOpenAITTSModel(); @@ -40,10 +39,13 @@ export async function requestGrammarAudio(input: unknown): Promise("idle"); - const [message, setMessage] = useState(""); + const [error, setError] = useState(null); const generation = useRef(0); const audio = useRef(null); const speech = useRef | null>(null); @@ -23,6 +24,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { } useEffect(() => { speech.current = null; + setError(null); setStatus("idle"); const lifecycleGeneration = generation; return () => { @@ -41,7 +43,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { release.current?.(); release.current = null; const currentGeneration = ++generation.current; - setMessage(""); + setError(null); release.current = claimGrammarPlayback(stop); let data = speech.current; if (!data) { @@ -50,7 +52,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { const result = await generate(input); if (currentGeneration !== generation.current) return; if (!result.ok) { - setMessage(result.message); + setError(result.code); setStatus("generation-error"); return; } @@ -58,7 +60,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { speech.current = result; } catch { if (currentGeneration !== generation.current) return; - setMessage("음성 생성 요청에 실패했습니다."); + setError("GENERATION_FAILED"); setStatus("generation-error"); return; } @@ -71,7 +73,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { }; player.onerror = () => { if (currentGeneration === generation.current) { - setMessage("음성을 재생하지 못했습니다."); + setError("PLAYBACK_FAILED"); setStatus("playback-error"); } }; @@ -83,9 +85,9 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { setStatus("playing"); } catch { if (currentGeneration !== generation.current) return; - setMessage("음성을 재생하지 못했습니다. 재생 버튼을 다시 눌러주세요."); + setError("PLAYBACK_FAILED"); setStatus("playback-error"); } } - return { status, message, play }; + return { status, error, play }; } diff --git a/src/features/grammar-audio/ui/GrammarAudioButton.tsx b/src/features/grammar-audio/ui/GrammarAudioButton.tsx index 20a0b87a..27ae6518 100644 --- a/src/features/grammar-audio/ui/GrammarAudioButton.tsx +++ b/src/features/grammar-audio/ui/GrammarAudioButton.tsx @@ -1,8 +1,9 @@ "use client"; import type { GrammarAudioButtonProps } from "../models/interface"; +import { grammarAudioErrorMessages } from "./errorMessage"; import { useGrammarAudio } from "../services/useGrammarAudio"; export function GrammarAudioButton(props: GrammarAudioButtonProps) { - const { status, message, play } = useGrammarAudio(props); + const { status, error, play } = useGrammarAudio(props); return (
diff --git a/src/features/grammar-audio/ui/errorMessage.ts b/src/features/grammar-audio/ui/errorMessage.ts new file mode 100644 index 00000000..85016b0a --- /dev/null +++ b/src/features/grammar-audio/ui/errorMessage.ts @@ -0,0 +1,10 @@ +import type { GrammarAudioErrorCode } from "../models/interface"; +export const grammarAudioErrorMessages: Record = { + INVALID_INPUT: "음성 요청을 확인해주세요.", + UNAUTHORIZED: "로그인 후 다시 시도해주세요.", + NOT_INVITED: "AI 음성 이용 권한이 필요합니다.", + RATE_LIMITED: "음성 요청 한도에 도달했습니다. 잠시 후 다시 시도해주세요.", + GENERATION_FAILED: + "음성을 생성하지 못했습니다. 노트가 변경되었다면 새로고침 후 다시 생성해주세요.", + PLAYBACK_FAILED: "음성을 재생하지 못했습니다. 재생 버튼을 다시 눌러주세요.", +}; From bf85fd72a3a2e0e6f7b864433d280618c72f0f23 Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Thu, 8 Oct 2026 18:52:21 +0900 Subject: [PATCH 05/19] refactor: return session error codes at server boundary (#172) --- .../grammarSessionActions.test.ts | 33 +++++++++++++++++++ src/entities/grammar-session/index.ts | 3 +- src/entities/grammar-session/models/errors.ts | 13 -------- .../grammar-session/ui/errorMessage.ts | 12 +++++++ .../grammar-practice/models/interface.ts | 4 +-- .../services/actions/grammarSessionActions.ts | 10 +++--- 6 files changed, 55 insertions(+), 20 deletions(-) create mode 100644 src/_tests/features/grammar-practice/grammarSessionActions.test.ts create mode 100644 src/entities/grammar-session/ui/errorMessage.ts diff --git a/src/_tests/features/grammar-practice/grammarSessionActions.test.ts b/src/_tests/features/grammar-practice/grammarSessionActions.test.ts new file mode 100644 index 00000000..6acac44e --- /dev/null +++ b/src/_tests/features/grammar-practice/grammarSessionActions.test.ts @@ -0,0 +1,33 @@ +/** @jest-environment node */ +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; +import { GrammarSessionRepository } from "@/entities/grammar-session"; +import type { createSupabaseServerClient as CreateClient } from "@/shared/lib/supabase/server"; +import type { startGrammarSession as StartSession } from "@/features/grammar-practice/services/actions/grammarSessionActions"; +jest.mock("server-only", () => ({})); +jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); +jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); +let createSupabaseServerClient: typeof CreateClient; +let startGrammarSession: typeof StartSession; +beforeEach(async () => { + ({ createSupabaseServerClient } = await import("@/shared/lib/supabase/server")); + ({ startGrammarSession } = + await import("@/features/grammar-practice/services/actions/grammarSessionActions")); + jest.clearAllMocks(); +}); +describe("연습 액션 오류 계약", () => { + it("비로그인은 저장소를 호출하지 않고 UI 문구 대신 권한 코드를 반환한다", async () => { + jest.mocked(createSupabaseServerClient).mockResolvedValue({ + auth: { getUser: async () => ({ data: { user: null }, error: null }) }, + } as never); + const start = jest.spyOn(GrammarSessionRepository.prototype, "start"); + expect(await startGrammarSession({})).toEqual({ ok: false, code: "UNAUTHORIZED" }); + expect(start).not.toHaveBeenCalled(); + start.mockRestore(); + }); + it("알 수 없는 내부 오류는 응답에 노출하지 않는다", async () => { + jest + .mocked(createSupabaseServerClient) + .mockRejectedValue(new Error("secret connection details")); + expect(await startGrammarSession({})).toEqual({ ok: false, code: "FAILED" }); + }); +}); diff --git a/src/entities/grammar-session/index.ts b/src/entities/grammar-session/index.ts index 8e8eb9af..1cc20d25 100644 --- a/src/entities/grammar-session/index.ts +++ b/src/entities/grammar-session/index.ts @@ -21,4 +21,5 @@ export type { GrammarSessionSummary, } from "./models/repository"; export { GrammarSessionRepository } from "./infrastructure/GrammarSessionRepository"; -export { GrammarSessionError, grammarSessionErrorMessage } from "./models/errors"; +export { GrammarSessionError } from "./models/errors"; +export { grammarSessionErrorMessage } from "./ui/errorMessage"; diff --git a/src/entities/grammar-session/models/errors.ts b/src/entities/grammar-session/models/errors.ts index 37399e03..b90b2ace 100644 --- a/src/entities/grammar-session/models/errors.ts +++ b/src/entities/grammar-session/models/errors.ts @@ -12,16 +12,3 @@ export class GrammarSessionError extends Error { this.name = "GrammarSessionError"; } } -export function grammarSessionErrorMessage(error: unknown): string { - if (!(error instanceof GrammarSessionError)) - return "연습을 저장하지 못했습니다. 잠시 후 다시 시도해 주세요."; - const messages = { - INVALID_INPUT: "연습 입력을 확인해 주세요.", - NOT_FOUND: "연습을 찾을 수 없습니다.", - CONFLICT: "다른 화면에서 연습이 변경되었습니다. 연습을 다시 열어 주세요.", - INCOMPLETE: "모든 문항에 답한 뒤 완료해 주세요.", - UNAUTHORIZED: "로그인 후 다시 시도해 주세요.", - FAILED: "연습을 저장하지 못했습니다. 잠시 후 다시 시도해 주세요.", - }; - return messages[error.code]; -} diff --git a/src/entities/grammar-session/ui/errorMessage.ts b/src/entities/grammar-session/ui/errorMessage.ts new file mode 100644 index 00000000..2104ad2b --- /dev/null +++ b/src/entities/grammar-session/ui/errorMessage.ts @@ -0,0 +1,12 @@ +import type { GrammarSessionError } from "../models/errors"; +export function grammarSessionErrorMessage(code: GrammarSessionError["code"]): string { + const messages = { + INVALID_INPUT: "연습 입력을 확인해 주세요.", + NOT_FOUND: "연습을 찾을 수 없습니다.", + CONFLICT: "다른 화면에서 연습이 변경되었습니다. 연습을 다시 열어 주세요.", + INCOMPLETE: "모든 문항에 답한 뒤 완료해 주세요.", + UNAUTHORIZED: "로그인 후 다시 시도해 주세요.", + FAILED: "연습을 저장하지 못했습니다. 잠시 후 다시 시도해 주세요.", + }; + return messages[code]; +} diff --git a/src/features/grammar-practice/models/interface.ts b/src/features/grammar-practice/models/interface.ts index 02d915aa..3b5b6022 100644 --- a/src/features/grammar-practice/models/interface.ts +++ b/src/features/grammar-practice/models/interface.ts @@ -1,4 +1,4 @@ -import type { GrammarSession } from "@/entities/grammar-session"; +import type { GrammarSession, GrammarSessionError } from "@/entities/grammar-session"; export type GrammarSessionResult = | { ok: true; data: GrammarSession } - | { ok: false; message: string }; + | { ok: false; code: GrammarSessionError["code"] }; diff --git a/src/features/grammar-practice/services/actions/grammarSessionActions.ts b/src/features/grammar-practice/services/actions/grammarSessionActions.ts index ea9798b0..8e3ef693 100644 --- a/src/features/grammar-practice/services/actions/grammarSessionActions.ts +++ b/src/features/grammar-practice/services/actions/grammarSessionActions.ts @@ -6,7 +6,6 @@ import { recordOperationEvent } from "@/shared/lib/logging/pino"; import { GrammarSessionRepository, GrammarSessionError, - grammarSessionErrorMessage, startGrammarSessionSchema, saveGrammarAnswersSchema, completeGrammarSessionSchema, @@ -33,9 +32,12 @@ async function executeSessionAction( } catch (error) { return { ok: false, - message: grammarSessionErrorMessage( - error instanceof z.ZodError ? new GrammarSessionError("INVALID_INPUT") : error, - ), + code: + error instanceof z.ZodError + ? "INVALID_INPUT" + : error instanceof GrammarSessionError + ? error.code + : "FAILED", }; } } From f12af71e64f18427338c1fd43cd71ba2c9af74e7 Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Thu, 8 Oct 2026 18:52:48 +0900 Subject: [PATCH 06/19] refactor: preserve recall session state and present error codes in UI (#173) --- .../features/grammar-recall/GrammarRecall.stories.tsx | 4 ++-- .../features/grammar-recall/GrammarRecall.test.tsx | 8 +++++--- src/features/grammar-recall/models/interface.ts | 3 ++- .../grammar-recall/services/useRecallSession.ts | 11 ++++++----- src/features/grammar-recall/ui/GrammarRecall.tsx | 7 ++++++- 5 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx b/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx index 18f3e4cc..fb2fad10 100644 --- a/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx +++ b/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx @@ -9,9 +9,9 @@ const meta = { initialSession: recallSession(), save: fn(async () => ({ ok: false as const, - message: "저장하지 못했습니다. 다시 시도해주세요.", + code: "FAILED" as const, })), - complete: fn(async () => ({ ok: false as const, message: "완료 저장 실패" })), + complete: fn(async () => ({ ok: false as const, code: "FAILED" as const })), onComplete: fn(), onExit: fn(), }, diff --git a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx index 9c72dc74..b51a2328 100644 --- a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx +++ b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx @@ -10,7 +10,7 @@ describe("recall workflow", () => { const session = { ...recallSession(), phase: "whole" as const }; const save = jest .fn<() => Promise>() - .mockResolvedValue({ ok: false, message: "저장 실패" }); + .mockResolvedValue({ ok: false, code: "FAILED" as const }); render( { fireEvent.click(screen.getByRole("button", { name: "정답 보기" })); fireEvent.click(screen.getByRole("radio", { name: "다시 볼게요" })); fireEvent.click(screen.getByRole("button", { name: "연습 완료" })); - await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("저장 실패")); + await waitFor(() => + expect(screen.getByRole("alert")).toHaveTextContent("연습을 저장하지 못했습니다"), + ); expect(screen.getByRole("textbox")).toHaveValue("My own answer."); expect(save).toHaveBeenCalledWith( expect.objectContaining({ @@ -37,7 +39,7 @@ describe("recall workflow", () => { const exit = jest.fn(); const save = jest .fn<() => Promise>() - .mockResolvedValue({ ok: false, message: "다시 시도" }); + .mockResolvedValue({ ok: false, code: "FAILED" as const }); render( Promise; diff --git a/src/features/grammar-recall/services/useRecallSession.ts b/src/features/grammar-recall/services/useRecallSession.ts index c2572202..28197b74 100644 --- a/src/features/grammar-recall/services/useRecallSession.ts +++ b/src/features/grammar-recall/services/useRecallSession.ts @@ -1,15 +1,16 @@ "use client"; +import type { GrammarSessionError } from "@/entities/grammar-session"; import { useState } from "react"; import type { GrammarRecallProps, RecallDraft } from "../models/interface"; import { mergeRecallDraftIntoAnswers } from "./recallDraft"; export function useRecallSession(props: GrammarRecallProps) { const [session, setSession] = useState(props.initialSession); const [busy, setBusy] = useState(false); - const [error, setError] = useState(""); + const [error, setError] = useState(null); async function move(draft: RecallDraft, direction: "next" | "back" | "exit") { if (busy) return; setBusy(true); - setError(""); + setError(null); try { const last = session.questionIndex === session.questions.length - 1; const finishing = direction === "next" && last && session.phase === "whole"; @@ -39,7 +40,7 @@ export function useRecallSession(props: GrammarRecallProps) { questionIndex: index, }); if (!saved.ok) { - setError(saved.message); + setError(saved.code); return; } setSession(saved.data); @@ -53,13 +54,13 @@ export function useRecallSession(props: GrammarRecallProps) { expectedVersion: saved.data.version, }); if (!completed.ok) { - setError(completed.message); + setError(completed.code); return; } props.onComplete(completed.data); } } catch { - setError("진행 상태를 저장하지 못했습니다. 입력은 유지됩니다. 다시 시도해주세요."); + setError("FAILED"); } finally { setBusy(false); } diff --git a/src/features/grammar-recall/ui/GrammarRecall.tsx b/src/features/grammar-recall/ui/GrammarRecall.tsx index 59c81db0..3caf9a74 100644 --- a/src/features/grammar-recall/ui/GrammarRecall.tsx +++ b/src/features/grammar-recall/ui/GrammarRecall.tsx @@ -1,8 +1,13 @@ "use client"; +import { grammarSessionErrorMessage } from "@/entities/grammar-session"; import type { GrammarRecallProps } from "../models/interface"; import { useRecallSession } from "../services/useRecallSession"; import { RecallQuestion } from "./RecallQuestion"; export function GrammarRecall(props: GrammarRecallProps) { + return ; +} + +function RecallSession(props: GrammarRecallProps) { const { session, busy, error, move } = useRecallSession(props); const question = session.questions[session.questionIndex]; return ( @@ -15,7 +20,7 @@ export function GrammarRecall(props: GrammarRecallProps) { key={`${session.phase}:${question.id}`} session={session} busy={busy} - error={error} + error={error ? grammarSessionErrorMessage(error) : ""} onMove={move} audio={props.renderAudio?.(question)} /> From 9bfb7af1b7e9b3185110aa1cf149845d7559aed1 Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Thu, 8 Oct 2026 18:53:01 +0900 Subject: [PATCH 07/19] test: verify recall draft lifetime across session changes (#173) --- .../grammar-recall/GrammarRecall.test.tsx | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx index b51a2328..f4b02a0b 100644 --- a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx +++ b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx @@ -113,3 +113,19 @@ describe("recall workflow", () => { ); }); }); + +it("preserves a same-session draft and resets when opening a different session", () => { + const session = { ...recallSession(), phase: "whole" as const }; + const props = { + save: jest.fn<() => Promise>(), + complete: jest.fn<() => Promise>(), + onComplete: jest.fn(), + onExit: jest.fn(), + }; + const { rerender } = render(); + fireEvent.change(screen.getByRole("textbox"), { target: { value: "My draft" } }); + rerender(); + expect(screen.getByRole("textbox")).toHaveValue("My draft"); + rerender(); + expect(screen.getByRole("textbox")).toHaveValue(""); +}); From 46fe5c02ce21c5202115314acc59622e0d8d659e Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Thu, 8 Oct 2026 18:54:12 +0900 Subject: [PATCH 08/19] refactor: separate exam error presentation and session lifetime (#174) --- .../grammar-exam/GrammarExam.stories.tsx | 4 +-- .../grammar-exam/GrammarExamPlayer.test.tsx | 33 ++++++++++++++----- .../grammar-exam/observeExamAction.test.ts | 20 +++++++++++ src/features/grammar-exam/index.ts | 2 ++ src/features/grammar-exam/models/errors.ts | 12 ------- src/features/grammar-exam/models/interface.ts | 7 ++-- .../services/hooks/useGrammarExam.ts | 14 ++++---- .../services/hooks/useInitialExamFeedback.ts | 2 +- .../services/server/observeExamAction.ts | 21 ++++++------ .../ui/GrammarExamFeedbackItem.tsx | 6 ++-- .../grammar-exam/ui/GrammarExamPlayer.tsx | 7 +++- src/features/grammar-exam/ui/errorMessage.ts | 18 ++++++++++ 12 files changed, 101 insertions(+), 45 deletions(-) create mode 100644 src/_tests/features/grammar-exam/observeExamAction.test.ts create mode 100644 src/features/grammar-exam/ui/errorMessage.ts diff --git a/src/_storybook/features/grammar-exam/GrammarExam.stories.tsx b/src/_storybook/features/grammar-exam/GrammarExam.stories.tsx index ce7174a5..d2fa50cc 100644 --- a/src/_storybook/features/grammar-exam/GrammarExam.stories.tsx +++ b/src/_storybook/features/grammar-exam/GrammarExam.stories.tsx @@ -49,7 +49,7 @@ export const SaveFailure: Story = { args: { onSaveAnswers: fn(async () => ({ ok: false as const, - message: "저장하지 못했습니다. 다시 시도해 주세요.", + code: "FAILED" as const, })), }, play: async ({ canvasElement }) => { @@ -71,7 +71,7 @@ export const CompletedFeedback: Story = { }, })} initialFeedback={[createGrammarExamFeedback({ answer: "She is a doctor, not a teacher." })]} - onRequestFeedback={async () => ({ ok: false, message: "잠시 후 다시 시도해 주세요." })} + onRequestFeedback={async () => ({ ok: false, code: "FAILED" as const })} /> ), }; diff --git a/src/_tests/features/grammar-exam/GrammarExamPlayer.test.tsx b/src/_tests/features/grammar-exam/GrammarExamPlayer.test.tsx index b53cc740..4c962d97 100644 --- a/src/_tests/features/grammar-exam/GrammarExamPlayer.test.tsx +++ b/src/_tests/features/grammar-exam/GrammarExamPlayer.test.tsx @@ -30,12 +30,12 @@ describe("Grammar exam UI", () => { expect(screen.queryByRole("button", { name: /듣기|재생/ })).not.toBeInTheDocument(); }); it("failed_save_keeps_user_draft_and_question", async () => { - setup({ onSaveAnswers: async () => ({ ok: false, message: "저장 실패" }) }); + setup({ onSaveAnswers: async () => ({ ok: false, code: "FAILED" as const }) }); fireEvent.change(screen.getByLabelText("영어로 작성해 주세요"), { target: { value: "My draft" }, }); fireEvent.click(screen.getByRole("button", { name: "다음 문항" })); - await screen.findByText("저장 실패"); + await screen.findByText("시험을 처리하지 못했습니다. 입력을 유지한 채 다시 시도해 주세요."); expect(screen.getByLabelText("영어로 작성해 주세요")).toHaveValue("My draft"); expect(screen.getByText("1 / 2")).toBeInTheDocument(); }); @@ -52,7 +52,7 @@ describe("Grammar exam UI", () => { onSaveAnswers: async (input) => ({ ok: true, data: { ...session, ...input, version: 2 } }), onComplete: async () => attempt++ === 0 - ? { ok: false, message: "완료 실패" } + ? { ok: false, code: "FAILED" as const } : { ok: true, data: { ...session, status: "completed" } }, onCompleted, }); @@ -60,7 +60,7 @@ describe("Grammar exam UI", () => { target: { value: "He is an engineer." }, }); fireEvent.click(screen.getByRole("button", { name: "시험 완료" })); - await screen.findByText("완료 실패"); + await screen.findByText("시험을 처리하지 못했습니다. 입력을 유지한 채 다시 시도해 주세요."); expect(onCompleted).not.toHaveBeenCalled(); fireEvent.click(screen.getByRole("button", { name: "시험 완료" })); await waitFor(() => expect(onCompleted).toHaveBeenCalledTimes(1)); @@ -82,7 +82,7 @@ describe("Grammar exam UI", () => { .fn<() => Promise>() .mockImplementation(async () => attempt++ === 0 - ? { ok: false, message: "일시 실패" } + ? { ok: false, code: "FAILED" as const } : { ok: true, data: createGrammarExamFeedback() }, ); render(); @@ -106,7 +106,7 @@ describe("Grammar exam UI", () => { const request = jest .fn[0]["onRequestFeedback"]>>() .mockImplementationOnce(() => first) - .mockResolvedValueOnce({ ok: false, message: "두 번째 실패" }); + .mockResolvedValueOnce({ ok: false, code: "FAILED" as const }); render( @@ -114,7 +114,7 @@ describe("Grammar exam UI", () => { ); await waitFor(() => expect(request).toHaveBeenCalledTimes(1)); resolveFirst({ ok: true, data: createGrammarExamFeedback() }); - await screen.findByText("두 번째 실패"); + await screen.findByText("시험을 처리하지 못했습니다. 입력을 유지한 채 다시 시도해 주세요."); expect(request).toHaveBeenCalledTimes(2); expect(screen.getByText("잘 작성했어요")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "피드백 다시 받기" })).toBeEnabled(); @@ -122,7 +122,7 @@ describe("Grammar exam UI", () => { it("history_mount_does_not_trigger_paid_feedback_and_cached_initial_items_are_skipped", async () => { const request = jest .fn[0]["onRequestFeedback"]>>() - .mockResolvedValue({ ok: false, message: "실패" }); + .mockResolvedValue({ ok: false, code: "FAILED" as const }); const session = createGrammarExam({ status: "completed" }); const view = render(); expect(request).not.toHaveBeenCalled(); @@ -152,3 +152,20 @@ describe("Grammar exam UI", () => { expect(saved.defaultPrevented).toBe(false); }); }); + +it("keeps drafts on same-session rerender and isolates a different exam", () => { + const session = createGrammarExam(); + const props: GrammarExamPlayerProps = { + initialSession: session, + onSaveAnswers: jest.fn(), + onComplete: jest.fn(), + onCompleted: jest.fn(), + onExit: jest.fn(), + }; + const { rerender } = render(); + fireEvent.change(screen.getByLabelText("영어로 작성해 주세요"), { target: { value: "Draft" } }); + rerender(); + expect(screen.getByLabelText("영어로 작성해 주세요")).toHaveValue("Draft"); + rerender(); + expect(screen.getByLabelText("영어로 작성해 주세요")).toHaveValue(""); +}); diff --git a/src/_tests/features/grammar-exam/observeExamAction.test.ts b/src/_tests/features/grammar-exam/observeExamAction.test.ts new file mode 100644 index 00000000..937fd0e7 --- /dev/null +++ b/src/_tests/features/grammar-exam/observeExamAction.test.ts @@ -0,0 +1,20 @@ +/** @jest-environment node */ +import { describe, expect, it, jest } from "@jest/globals"; +import { GrammarSessionError } from "@/entities/grammar-session"; +import { GrammarExamError } from "@/features/grammar-exam/models/errors"; +jest.mock("server-only", () => ({})); +jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); +describe("시험 액션 오류 계약", () => { + it.each([ + [new GrammarSessionError("CONFLICT"), "CONFLICT"], + [new GrammarExamError("NOT_INVITED"), "NOT_INVITED"], + [new Error("secret upstream response"), "FAILED"], + ])("returns a safe code for %s", async (error, code) => { + const { observeExamAction } = + await import("@/features/grammar-exam/services/server/observeExamAction"); + const result = await observeExamAction("test.exam", async () => { + throw error; + }); + expect(result).toEqual({ ok: false, code }); + }); +}); diff --git a/src/features/grammar-exam/index.ts b/src/features/grammar-exam/index.ts index 8ebd83fb..a6de9e23 100644 --- a/src/features/grammar-exam/index.ts +++ b/src/features/grammar-exam/index.ts @@ -13,3 +13,5 @@ export type { } from "./models/interface"; export { GrammarExamPlayer } from "./ui/GrammarExamPlayer"; export { GrammarExamResult } from "./ui/GrammarExamResult"; + +export { grammarExamErrorMessage } from "./ui/errorMessage"; diff --git a/src/features/grammar-exam/models/errors.ts b/src/features/grammar-exam/models/errors.ts index 237968f0..75edd3e1 100644 --- a/src/features/grammar-exam/models/errors.ts +++ b/src/features/grammar-exam/models/errors.ts @@ -6,15 +6,3 @@ export class GrammarExamError extends Error { this.name = "GrammarExamError"; } } -export function grammarExamErrorMessage(error: unknown) { - if (!(error instanceof GrammarExamError)) - return "시험을 처리하지 못했습니다. 잠시 후 다시 시도해 주세요."; - const messages = { - INVALID_INPUT: "시험 입력을 확인해 주세요.", - NOT_READY: "시험을 완료한 뒤 피드백을 받을 수 있습니다.", - RATE_LIMITED: "AI 사용 한도에 도달했습니다. 잠시 후 다시 시도해 주세요.", - NOT_INVITED: "AI 기능 이용 권한을 확인해 주세요.", - FAILED: "AI 응답을 처리하지 못했습니다. 다시 시도해 주세요.", - }; - return messages[error.code]; -} diff --git a/src/features/grammar-exam/models/interface.ts b/src/features/grammar-exam/models/interface.ts index 66c4ddd6..1dc921d0 100644 --- a/src/features/grammar-exam/models/interface.ts +++ b/src/features/grammar-exam/models/interface.ts @@ -1,16 +1,19 @@ +import type { GrammarExamError } from "./errors"; import type { GrammarSession, + GrammarSessionError, GrammarSessionQuestion, SaveGrammarAnswersInput, CompleteGrammarSessionInput, } from "@/entities/grammar-session"; import type { GrammarExamFeedback } from "./schema"; +export type GrammarExamErrorCode = GrammarExamError["code"] | GrammarSessionError["code"]; export type GrammarExamSessionResult = | { ok: true; data: GrammarSession } - | { ok: false; message: string }; + | { ok: false; code: GrammarExamErrorCode }; export type GrammarExamFeedbackResult = | { ok: true; data: GrammarExamFeedback } - | { ok: false; message: string }; + | { ok: false; code: GrammarExamErrorCode }; export interface GrammarExamProvider { createPrompts(input: { targetGrammar: string; diff --git a/src/features/grammar-exam/services/hooks/useGrammarExam.ts b/src/features/grammar-exam/services/hooks/useGrammarExam.ts index 8291ed50..ca7549e5 100644 --- a/src/features/grammar-exam/services/hooks/useGrammarExam.ts +++ b/src/features/grammar-exam/services/hooks/useGrammarExam.ts @@ -1,6 +1,6 @@ "use client"; import { useRef, useState } from "react"; -import type { GrammarExamPlayerProps } from "../../models/interface"; +import type { GrammarExamPlayerProps, GrammarExamErrorCode } from "../../models/interface"; /** 입력 문장은 문항 컴포넌트가 소유하고, 이 훅은 저장·이동·완료만 조율합니다. */ export function useGrammarExam({ initialSession, @@ -10,14 +10,14 @@ export function useGrammarExam({ }: GrammarExamPlayerProps) { const [session, setSession] = useState(initialSession); const [busy, setBusy] = useState(false); - const [message, setMessage] = useState(""); + const [message, setMessage] = useState(null); const pending = useRef(false); const question = session.questions[session.questionIndex]; async function save(answer: string, advance: boolean) { if (pending.current) return; pending.current = true; setBusy(true); - setMessage(""); + setMessage(null); try { const isLast = session.questionIndex === session.questions.length - 1; const index = advance && !isLast ? session.questionIndex + 1 : session.questionIndex; @@ -29,12 +29,12 @@ export function useGrammarExam({ questionIndex: index, }); if (!result.ok) { - setMessage(result.message); + setMessage(result.code); return; } setSession(result.data); if (!advance) { - setMessage("답안을 임시 저장했습니다."); + setMessage("SAVED"); return; } if (!isLast) return; @@ -43,13 +43,13 @@ export function useGrammarExam({ expectedVersion: result.data.version, }); if (!completed.ok) { - setMessage(completed.message); + setMessage(completed.code); return; } setSession(completed.data); onCompleted(completed.data); } catch { - setMessage("답안을 저장하지 못했습니다. 입력을 유지한 채 다시 시도해 주세요."); + setMessage("FAILED"); } finally { pending.current = false; setBusy(false); diff --git a/src/features/grammar-exam/services/hooks/useInitialExamFeedback.ts b/src/features/grammar-exam/services/hooks/useInitialExamFeedback.ts index 58178038..950cb715 100644 --- a/src/features/grammar-exam/services/hooks/useInitialExamFeedback.ts +++ b/src/features/grammar-exam/services/hooks/useInitialExamFeedback.ts @@ -34,7 +34,7 @@ export function useInitialExamFeedback({ try { result = await onRequestFeedback({ sessionId: session.id, questionId: question.id }); } catch { - result = { ok: false, message: "피드백을 불러오지 못했습니다. 다시 시도해 주세요." }; + result = { ok: false, code: "FAILED" }; } if (!isCurrent()) return; setResults((previous) => ({ ...previous, [`${session.id}:${question.id}`]: result })); diff --git a/src/features/grammar-exam/services/server/observeExamAction.ts b/src/features/grammar-exam/services/server/observeExamAction.ts index 459539cd..8688f6b7 100644 --- a/src/features/grammar-exam/services/server/observeExamAction.ts +++ b/src/features/grammar-exam/services/server/observeExamAction.ts @@ -2,12 +2,13 @@ import "server-only"; import { z } from "zod"; import { observeOperation } from "@/shared/lib/logging/observeOperation"; import { recordOperationEvent } from "@/shared/lib/logging/pino"; -import { GrammarSessionError, grammarSessionErrorMessage } from "@/entities/grammar-session"; -import { GrammarExamError, grammarExamErrorMessage } from "../../models/errors"; +import { GrammarSessionError } from "@/entities/grammar-session"; +import { GrammarExamError } from "../../models/errors"; +import type { GrammarExamErrorCode } from "../../models/interface"; export async function observeExamAction( operation: string, execute: () => Promise, -): Promise<{ ok: true; data: T } | { ok: false; message: string }> { +): Promise<{ ok: true; data: T } | { ok: false; code: GrammarExamErrorCode }> { try { return { ok: true, @@ -19,12 +20,12 @@ export async function observeExamAction( }), }; } catch (error) { - const message = - error instanceof GrammarSessionError - ? grammarSessionErrorMessage(error) - : grammarExamErrorMessage( - error instanceof z.ZodError ? new GrammarExamError("INVALID_INPUT") : error, - ); - return { ok: false, message }; + const code = + error instanceof z.ZodError + ? "INVALID_INPUT" + : error instanceof GrammarSessionError || error instanceof GrammarExamError + ? error.code + : "FAILED"; + return { ok: false, code }; } } diff --git a/src/features/grammar-exam/ui/GrammarExamFeedbackItem.tsx b/src/features/grammar-exam/ui/GrammarExamFeedbackItem.tsx index 114805a9..e577afe1 100644 --- a/src/features/grammar-exam/ui/GrammarExamFeedbackItem.tsx +++ b/src/features/grammar-exam/ui/GrammarExamFeedbackItem.tsx @@ -1,4 +1,5 @@ "use client"; +import { grammarExamErrorMessage } from "./errorMessage"; import { useRef, useState } from "react"; import type { GrammarSessionQuestion } from "@/entities/grammar-session"; import type { GrammarExamFeedback } from "../models/schema"; @@ -29,7 +30,8 @@ export function GrammarExamFeedbackItem({ localFeedback ?? initialFeedback ?? (autoResult?.ok ? autoResult.data : undefined); const [busy, setBusy] = useState(false); const [localError, setError] = useState(""); - const error = localError || (autoResult && !autoResult.ok ? autoResult.message : ""); + const error = + localError || (autoResult && !autoResult.ok ? grammarExamErrorMessage(autoResult.code) : ""); const pending = useRef(false); async function request() { if (pending.current) return; @@ -39,7 +41,7 @@ export function GrammarExamFeedbackItem({ try { const result = await onRequest(); if (result.ok) setFeedback(result.data); - else setError(result.message); + else setError(grammarExamErrorMessage(result.code)); } catch { setError("피드백을 불러오지 못했습니다. 다시 시도해 주세요."); } finally { diff --git a/src/features/grammar-exam/ui/GrammarExamPlayer.tsx b/src/features/grammar-exam/ui/GrammarExamPlayer.tsx index 8bc7c38c..fe101eac 100644 --- a/src/features/grammar-exam/ui/GrammarExamPlayer.tsx +++ b/src/features/grammar-exam/ui/GrammarExamPlayer.tsx @@ -1,10 +1,15 @@ "use client"; +import { grammarExamErrorMessage } from "./errorMessage"; import { useState } from "react"; import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog"; import type { GrammarExamPlayerProps } from "../models/interface"; import { useGrammarExam } from "../services/hooks/useGrammarExam"; import { GrammarExamQuestion } from "./GrammarExamQuestion"; export function GrammarExamPlayer(props: GrammarExamPlayerProps) { + return ; +} + +function ExamSession(props: GrammarExamPlayerProps) { const [exitOpen, setExitOpen] = useState(false); const { session, question, busy, message, save } = useGrammarExam(props); if ( @@ -43,7 +48,7 @@ export function GrammarExamPlayer(props: GrammarExamPlayerProps) { /> {message && (

- {message} + {message === "SAVED" ? "답안을 임시 저장했습니다." : grammarExamErrorMessage(message)}

)} Date: Thu, 8 Oct 2026 18:55:06 +0900 Subject: [PATCH 09/19] refactor: isolate history state by note and keep error copy in UI (#175) --- .../GrammarHistory.stories.tsx | 2 +- .../grammar-history/GrammarHistory.test.tsx | 24 ++++++++++++++++--- .../grammar-history/models/interface.ts | 2 +- .../services/actions/getGrammarHistory.ts | 2 +- .../services/useGrammarHistory.ts | 8 +++---- .../grammar-history/ui/GrammarHistory.tsx | 6 ++++- 6 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/_storybook/features/grammar-history/GrammarHistory.stories.tsx b/src/_storybook/features/grammar-history/GrammarHistory.stories.tsx index 93a5e5a1..e4ecb3f9 100644 --- a/src/_storybook/features/grammar-history/GrammarHistory.stories.tsx +++ b/src/_storybook/features/grammar-history/GrammarHistory.stories.tsx @@ -48,5 +48,5 @@ export const Empty: Story = { }, }; export const Failure: Story = { - args: { load: fn(async () => ({ ok: false as const, message: "연습 기록 조회 실패" })) }, + args: { load: fn(async () => ({ ok: false as const, code: "LOAD_FAILED" as const })) }, }; diff --git a/src/_tests/features/grammar-history/GrammarHistory.test.tsx b/src/_tests/features/grammar-history/GrammarHistory.test.tsx index 2fa1bdd0..4e3d82b0 100644 --- a/src/_tests/features/grammar-history/GrammarHistory.test.tsx +++ b/src/_tests/features/grammar-history/GrammarHistory.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, jest } from "@jest/globals"; -import { render, screen, waitFor } from "@testing-library/react"; +import { act, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { GrammarHistory } from "@/features/grammar-history"; import type { GrammarHistoryResult } from "@/features/grammar-history"; @@ -27,14 +27,32 @@ describe("grammar history", () => { const user = userEvent.setup(); const load = jest .fn<() => Promise>() - .mockResolvedValueOnce({ ok: false, message: "조회 실패" }) + .mockResolvedValueOnce({ ok: false, code: "LOAD_FAILED" as const }) .mockResolvedValueOnce({ ok: true, data: { items: [], total: 0, page: 1, pageSize: 10 } }); render(); expect(screen.queryByText("완료한 연습 0회")).not.toBeInTheDocument(); await user.click(screen.getByRole("button", { name: "연습 기록 전체보기" })); - expect(await screen.findByRole("alert")).toHaveTextContent("조회 실패"); + expect(await screen.findByRole("alert")).toHaveTextContent("연습 기록을 불러오지 못했습니다"); await user.click(screen.getByRole("button", { name: "다시 불러오기" })); expect(await screen.findByText("아직 완료한 연습이 없습니다.")).toBeVisible(); expect(load).toHaveBeenCalledTimes(2); }); }); + +it("discards a previous note's in-flight history when the note changes", async () => { + let resolve!: (result: GrammarHistoryResult) => void; + const load = jest.fn<() => Promise>().mockImplementation( + () => + new Promise((done) => { + resolve = done; + }), + ); + const data = { items: [], total: 0, page: 1, pageSize: 10 }; + const { rerender } = render(); + await userEvent.setup().click(screen.getByRole("button", { name: "연습 기록 전체보기" })); + rerender(); + await act(async () => resolve({ ok: true, data: { ...data, total: 99 } })); + expect(screen.getByText("완료한 연습 0회")).toBeVisible(); + expect(screen.queryByText("완료한 연습 99회")).not.toBeInTheDocument(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); +}); diff --git a/src/features/grammar-history/models/interface.ts b/src/features/grammar-history/models/interface.ts index 54cfcf5b..01ee594b 100644 --- a/src/features/grammar-history/models/interface.ts +++ b/src/features/grammar-history/models/interface.ts @@ -1,7 +1,7 @@ import type { GrammarSessionHistory } from "@/entities/grammar-session"; export type GrammarHistoryResult = | { ok: true; data: GrammarSessionHistory } - | { ok: false; message: string }; + | { ok: false; code: "LOAD_FAILED" }; export interface GrammarHistoryProps { readonly noteId: string; readonly initialData?: GrammarSessionHistory; diff --git a/src/features/grammar-history/services/actions/getGrammarHistory.ts b/src/features/grammar-history/services/actions/getGrammarHistory.ts index 3c90c10a..8a7ee4ee 100644 --- a/src/features/grammar-history/services/actions/getGrammarHistory.ts +++ b/src/features/grammar-history/services/actions/getGrammarHistory.ts @@ -26,6 +26,6 @@ export async function getGrammarHistory(noteId: string, page = 1): Promise(null); const generation = useRef(0); useEffect(() => { const lifecycle = generation; @@ -15,14 +15,14 @@ export function useGrammarHistory({ noteId, initialData, load }: GrammarHistoryP async function refresh(page = 1) { const currentGeneration = ++generation.current; setBusy(true); - setError(""); + setError(null); try { const result = await load(noteId, page); if (currentGeneration !== generation.current) return; if (result.ok) setData(result.data); - else setError(result.message); + else setError(result.code); } catch { - if (currentGeneration === generation.current) setError("연습 기록을 불러오지 못했습니다."); + if (currentGeneration === generation.current) setError("LOAD_FAILED"); } finally { if (currentGeneration === generation.current) setBusy(false); } diff --git a/src/features/grammar-history/ui/GrammarHistory.tsx b/src/features/grammar-history/ui/GrammarHistory.tsx index 406d7729..689224fc 100644 --- a/src/features/grammar-history/ui/GrammarHistory.tsx +++ b/src/features/grammar-history/ui/GrammarHistory.tsx @@ -15,6 +15,10 @@ import { useGrammarHistory } from "../services/useGrammarHistory"; import { formatGrammarPracticeDate } from "../services/formatPracticeDate"; import { GrammarHistoryRows } from "./GrammarHistoryRows"; export function GrammarHistory(props: GrammarHistoryProps) { + return ; +} + +function HistoryForNote(props: GrammarHistoryProps) { const [open, setOpen] = useState(false); const { data, busy, error, refresh } = useGrammarHistory(props); const total = data?.total ?? 0; @@ -61,7 +65,7 @@ export function GrammarHistory(props: GrammarHistoryProps) { ) : error ? (

- {error} + 연습 기록을 불러오지 못했습니다. 다시 시도해주세요.

+ + + ), +})); + +const push = jest.fn["push"]>(); +const refresh = jest.fn["refresh"]>(); + +beforeEach(async () => { + const { useRouter } = await import("next/navigation"); + jest.clearAllMocks(); + jest.mocked(useRouter).mockReturnValue({ + push, + refresh, + back: jest.fn(), + forward: jest.fn(), + replace: jest.fn(), + prefetch: jest.fn(), + }); +}); + +describe("editor route navigation", () => { + it("opens the saved note with the list context and refreshes server data", async () => { + const { GrammarEditorClient } = + await import("@/app/(protected)/grammar/_components/GrammarEditorClient"); + render(); + fireEvent.click(screen.getByRole("button", { name: "저장 성공" })); + expect(push).toHaveBeenCalledWith( + `/grammar/${createEditorNote().id}?returnTo=%2Fgrammar%3Fq%3Dcontrast%26page%3D2`, + ); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it("returns from a new note to the filtered list", async () => { + const { GrammarEditorClient } = + await import("@/app/(protected)/grammar/_components/GrammarEditorClient"); + render(); + fireEvent.click(screen.getByRole("button", { name: "나가기" })); + expect(push).toHaveBeenCalledWith("/grammar?q=contrast&page=2"); + expect(refresh).not.toHaveBeenCalled(); + }); + + it.each([undefined, "https://example.com", "/grammar/other"])( + "falls back to the list for an absent or invalid return path: %s", + async (backHref) => { + const { GrammarEditorClient } = + await import("@/app/(protected)/grammar/_components/GrammarEditorClient"); + render(); + fireEvent.click(screen.getByRole("button", { name: "나가기" })); + expect(push).toHaveBeenCalledWith("/grammar"); + }, + ); +}); diff --git a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx index abc1cba0..b96e48d0 100644 --- a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx +++ b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx @@ -1,6 +1,6 @@ import { describe, it, expect, jest, beforeEach } from "@jest/globals"; import { render, screen, fireEvent, waitFor } from "@testing-library/react"; -import { GrammarRecall } from "@/features/grammar-recall"; +import { RecallSession } from "@/features/grammar-recall"; import type { SaveGrammarAnswersInput } from "@/entities/grammar-session"; import type { RecallActionResult } from "@/features/grammar-recall"; import { recallSession } from "./fixture"; @@ -15,7 +15,7 @@ describe("recall workflow", () => { .mockResolvedValue({ ok: false, code: "FAILED" as const }); render( - Promise>()} @@ -46,7 +46,7 @@ describe("recall workflow", () => { .mockResolvedValue({ ok: false, code: "FAILED" as const }); render( - Promise>()} @@ -86,7 +86,7 @@ describe("recall workflow", () => { const onComplete = jest.fn(); render( - ); + const { rerender } = render(); fireEvent.change(screen.getByRole("textbox"), { target: { value: "My draft" } }); - rerender(); + rerender(); expect(screen.getByRole("textbox")).toHaveValue("My draft"); - rerender(); + rerender(); expect(screen.getByRole("textbox")).toHaveValue(""); }); diff --git a/src/views/grammar-editor/GrammarEditorClient.tsx b/src/app/(protected)/grammar/_components/GrammarEditorClient.tsx similarity index 96% rename from src/views/grammar-editor/GrammarEditorClient.tsx rename to src/app/(protected)/grammar/_components/GrammarEditorClient.tsx index 3b853ecf..a037e506 100644 --- a/src/views/grammar-editor/GrammarEditorClient.tsx +++ b/src/app/(protected)/grammar/_components/GrammarEditorClient.tsx @@ -9,10 +9,10 @@ import { saveGrammarNote } from "@/features/grammar-note-editor/services/actions export function GrammarEditorClient({ initialNote, - backHref, + backHref = "/grammar", }: { initialNote?: GrammarNote; - backHref: string; + backHref?: string; }) { const router = useRouter(); const returnTo = diff --git a/src/app/(protected)/grammar/new/page.tsx b/src/app/(protected)/grammar/new/page.tsx index c2550834..960bfa74 100644 --- a/src/app/(protected)/grammar/new/page.tsx +++ b/src/app/(protected)/grammar/new/page.tsx @@ -1,5 +1,7 @@ import { PageContainer } from "@/widgets/app-shell"; import { GrammarEditorView } from "@/views/grammar-editor"; +import { GrammarEditorClient } from "../_components/GrammarEditorClient"; + export default async function NewGrammarNotePage({ searchParams, }: { @@ -8,7 +10,9 @@ export default async function NewGrammarNotePage({ const { returnTo } = await searchParams; return ( - + + + ); } diff --git a/src/features/grammar-recall/index.ts b/src/features/grammar-recall/index.ts index 677a6864..82c572ac 100644 --- a/src/features/grammar-recall/index.ts +++ b/src/features/grammar-recall/index.ts @@ -1,3 +1,4 @@ export { GrammarRecall } from "./ui/GrammarRecall"; +export { RecallSession } from "./ui/RecallSession"; -export type { GrammarRecallProps, RecallActionResult } from "./models/interface"; +export type { RecallSessionProps, RecallActionResult } from "./models/interface"; diff --git a/src/features/grammar-recall/models/interface.ts b/src/features/grammar-recall/models/interface.ts index 7f3afa1c..abfe39d0 100644 --- a/src/features/grammar-recall/models/interface.ts +++ b/src/features/grammar-recall/models/interface.ts @@ -11,7 +11,7 @@ export type RecallActionResult = | { ok: true; data: GrammarSession } | { ok: false; code: GrammarSessionError["code"] }; -export interface GrammarRecallProps { +export interface RecallSessionProps { readonly initialSession: GrammarSession; readonly save: (input: SaveGrammarAnswersInput) => Promise; readonly complete: (input: CompleteGrammarSessionInput) => Promise; diff --git a/src/features/grammar-recall/services/useRecallSession.ts b/src/features/grammar-recall/services/useRecallSession.ts index e161b41f..ccd2eb8b 100644 --- a/src/features/grammar-recall/services/useRecallSession.ts +++ b/src/features/grammar-recall/services/useRecallSession.ts @@ -2,10 +2,10 @@ import type { GrammarSessionError } from "@/entities/grammar-session"; import { useState } from "react"; -import type { GrammarRecallProps, RecallDraft } from "../models/interface"; +import type { RecallSessionProps, RecallDraft } from "../models/interface"; import { mergeRecallDraftIntoAnswers } from "./recallDraft"; -export function useRecallSession(props: GrammarRecallProps) { +export function useRecallSession(props: RecallSessionProps) { const [session, setSession] = useState(props.initialSession); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); diff --git a/src/features/grammar-recall/ui/GrammarRecall.tsx b/src/features/grammar-recall/ui/GrammarRecall.tsx index 7a99c3f0..ae692bb1 100644 --- a/src/features/grammar-recall/ui/GrammarRecall.tsx +++ b/src/features/grammar-recall/ui/GrammarRecall.tsx @@ -1,32 +1,13 @@ -"use client"; - -import { grammarSessionErrorMessage } from "@/entities/grammar-session"; -import type { GrammarRecallProps } from "../models/interface"; -import { useRecallSession } from "../services/useRecallSession"; -import { RecallQuestion } from "./RecallQuestion"; - -export function GrammarRecall(props: GrammarRecallProps) { - return ; -} - -function RecallSession(props: GrammarRecallProps) { - const { session, busy, error, move } = useRecallSession(props); - const question = session.questions[session.questionIndex]; +import type { ReactNode } from "react"; +export function GrammarRecall({ title, children }: { title: string; children: ReactNode }) { return (

RECALL PRACTICE

-

{session.title}

+

{title}

- + {children}
); } diff --git a/src/features/grammar-recall/ui/RecallSession.tsx b/src/features/grammar-recall/ui/RecallSession.tsx new file mode 100644 index 00000000..f153a0c7 --- /dev/null +++ b/src/features/grammar-recall/ui/RecallSession.tsx @@ -0,0 +1,26 @@ +"use client"; + +import { grammarSessionErrorMessage } from "@/entities/grammar-session"; +import type { RecallSessionProps } from "../models/interface"; +import { useRecallSession } from "../services/useRecallSession"; +import { RecallQuestion } from "./RecallQuestion"; + +export function RecallSession(props: RecallSessionProps) { + return ; +} + +function RecallSessionContent(props: RecallSessionProps) { + const { session, busy, error, move } = useRecallSession(props); + const question = session.questions[session.questionIndex]; + + return ( + + ); +} diff --git a/src/views/grammar-editor/GrammarEditorView.tsx b/src/views/grammar-editor/GrammarEditorView.tsx index f638d6e1..f93d42ae 100644 --- a/src/views/grammar-editor/GrammarEditorView.tsx +++ b/src/views/grammar-editor/GrammarEditorView.tsx @@ -1,27 +1,24 @@ -import type { GrammarNote } from "@/entities/grammar-note"; -import { GrammarEditorClient } from "./GrammarEditorClient"; +import type { ReactNode } from "react"; export function GrammarEditorView({ - initialNote, - backHref = "/grammar", + editing = false, + children, }: { - initialNote?: GrammarNote; - backHref?: string; + editing?: boolean; + children: ReactNode; }) { return (

GRAMMAR NOTE

- {initialNote ? "어법 노트 수정" : "배운 어법을 문장으로 남겨요"} + {editing ? "어법 노트 수정" : "배운 어법을 문장으로 남겨요"}

문장과 핵심 어법을 적으면 AI가 분석합니다. 풀이를 확인하고 나만의 노트로 저장하세요.

-
- -
+
{children}
); }