From 3f10e68b07a9d9f7632bdebf230ab2deccaff47c Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Tue, 6 Oct 2026 02:25:49 +0900 Subject: [PATCH 01/16] feat(grammar): add semantic blank and whole sentence recall (#158) --- .../grammar-recall/GrammarRecall.stories.tsx | 41 +++++ .../grammar-recall/GrammarRecall.test.tsx | 55 +++++++ src/_tests/features/grammar-recall/fixture.ts | 33 ++++ .../grammar-recall/recallDraft.test.ts | 45 ++++++ src/features/grammar-recall/index.ts | 2 + .../grammar-recall/models/interface.ts | 36 +++++ .../grammar-recall/services/recallDraft.ts | 93 ++++++++++++ .../services/useRecallSession.ts | 68 +++++++++ .../grammar-recall/ui/GrammarRecall.tsx | 24 +++ .../grammar-recall/ui/RecallBlankFields.tsx | 35 +++++ .../grammar-recall/ui/RecallQuestion.tsx | 142 ++++++++++++++++++ 11 files changed, 574 insertions(+) create mode 100644 src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx create mode 100644 src/_tests/features/grammar-recall/GrammarRecall.test.tsx create mode 100644 src/_tests/features/grammar-recall/fixture.ts create mode 100644 src/_tests/features/grammar-recall/recallDraft.test.ts create mode 100644 src/features/grammar-recall/index.ts create mode 100644 src/features/grammar-recall/models/interface.ts create mode 100644 src/features/grammar-recall/services/recallDraft.ts create mode 100644 src/features/grammar-recall/services/useRecallSession.ts create mode 100644 src/features/grammar-recall/ui/GrammarRecall.tsx create mode 100644 src/features/grammar-recall/ui/RecallBlankFields.tsx create mode 100644 src/features/grammar-recall/ui/RecallQuestion.tsx diff --git a/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx b/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx new file mode 100644 index 00000000..18f3e4cc --- /dev/null +++ b/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx @@ -0,0 +1,41 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, fn, userEvent, waitFor, within } from "storybook/test"; +import { GrammarRecall } from "@/features/grammar-recall"; +import { recallSession } from "@/_tests/features/grammar-recall/fixture"; +const meta = { + title: "Features/Grammar/Recall", + component: GrammarRecall, + args: { + initialSession: recallSession(), + save: fn(async () => ({ + ok: false as const, + message: "저장하지 못했습니다. 다시 시도해주세요.", + })), + complete: fn(async () => ({ ok: false as const, message: "완료 저장 실패" })), + onComplete: fn(), + onExit: fn(), + }, + beforeEach: () => { + sessionStorage.clear(); + }, +} satisfies Meta; +export default meta; +type Story = StoryObj; +export const Partial: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.type(canvas.getByLabelText("이다"), "is"); + await userEvent.tab(); + await expect(canvas.getByLabelText("교사가 아니라 의사")).toHaveFocus(); + await userEvent.type( + canvas.getByLabelText("교사가 아니라 의사"), + "not a teacher but a doctor.", + ); + await expect(canvas.queryByText("She is not a teacher but a doctor.")).not.toBeInTheDocument(); + await userEvent.click(canvas.getByRole("button", { name: "정답 보기" })); + await waitFor(() => + expect(canvas.getByText("She is not a teacher but a doctor.")).toBeVisible(), + ); + }, +}; +export const Whole: Story = { args: { initialSession: { ...recallSession(), phase: "whole" } } }; diff --git a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx new file mode 100644 index 00000000..6664e91e --- /dev/null +++ b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx @@ -0,0 +1,55 @@ +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 type { RecallActionResult } from "@/features/grammar-recall"; +import { recallSession } from "./fixture"; +describe("recall workflow", () => { + beforeEach(() => sessionStorage.clear()); + it("does not expose the whole answer before reveal and keeps typed input after save failure", async () => { + const session = { ...recallSession(), phase: "whole" as const }; + const save = jest + .fn<() => Promise>() + .mockResolvedValue({ ok: false, message: "저장 실패" }); + render( + Promise>()} + onComplete={jest.fn()} + onExit={jest.fn()} + />, + ); + expect(screen.queryByText(session.questions[0].sentence!)).not.toBeInTheDocument(); + fireEvent.change(screen.getByRole("textbox"), { target: { value: "My own answer." } }); + 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("저장 실패")); + expect(screen.getByRole("textbox")).toHaveValue("My own answer."); + expect(save).toHaveBeenCalledWith( + expect.objectContaining({ + answers: expect.objectContaining({ "whole:source": "My own answer." }), + }), + ); + }); + it("saves before exiting and remains on page when saving fails", async () => { + const exit = jest.fn(); + const save = jest + .fn<() => Promise>() + .mockResolvedValue({ ok: false, message: "다시 시도" }); + render( + Promise>()} + onComplete={jest.fn()} + onExit={exit} + />, + ); + fireEvent.change(screen.getByLabelText("이다"), { target: { value: "is" } }); + fireEvent.click(screen.getByRole("button", { name: "저장하고 노트로" })); + await waitFor(() => expect(screen.getByRole("alert")).toBeVisible()); + expect(exit).not.toHaveBeenCalled(); + expect(screen.getByLabelText("이다")).toHaveValue("is"); + }); +}); diff --git a/src/_tests/features/grammar-recall/fixture.ts b/src/_tests/features/grammar-recall/fixture.ts new file mode 100644 index 00000000..98f35d26 --- /dev/null +++ b/src/_tests/features/grammar-recall/fixture.ts @@ -0,0 +1,33 @@ +import type { GrammarSession } from "@/entities/grammar-session"; +export function recallSession(): GrammarSession { + return { + id: "00000000-0000-4000-8000-000000000001", + noteId: "00000000-0000-4000-8000-000000000002", + noteVersion: 1, + title: "not A but B", + learningNote: "A가 아니라 B", + mode: "recall", + status: "active", + questions: [ + { + id: "source", + kind: "existing", + sentence: "She is not a teacher but a doctor.", + translation: "그녀는 교사가 아니라 의사입니다.", + context: "", + requiredWords: [], + chunks: [ + { id: "subject", start: 0, end: 4, meaning: "그녀는" }, + { id: "verb", start: 4, end: 7, meaning: "이다" }, + { id: "contrast", start: 7, end: 34, meaning: "교사가 아니라 의사" }, + ], + }, + ], + answers: {}, + phase: "partial", + questionIndex: 0, + version: 1, + startedAt: "2026-10-01T00:00:00Z", + completedAt: null, + }; +} diff --git a/src/_tests/features/grammar-recall/recallDraft.test.ts b/src/_tests/features/grammar-recall/recallDraft.test.ts new file mode 100644 index 00000000..0a5056eb --- /dev/null +++ b/src/_tests/features/grammar-recall/recallDraft.test.ts @@ -0,0 +1,45 @@ +import { describe, it, expect, beforeEach } from "@jest/globals"; +import { recallSession } from "./fixture"; +import { + recallSegments, + readRecallDraft, + persistRecallDraft, + answersWithRecallDraft, +} from "@/features/grammar-recall/services/recallDraft"; +describe("recall drafts and semantic blanks", () => { + beforeEach(() => sessionStorage.clear()); + it("uses stable semantic chunks without losing whitespace or punctuation", () => { + const question = recallSession().questions[0]; + const segments = recallSegments(question); + expect(segments.map((s) => s.text).join("")).toBe(question.sentence); + expect(segments.filter((s) => s.hidden).map((s) => s.id)).toEqual(["verb", "contrast"]); + }); + it("uses whole sentence recall when an example has no verified chunks", () => { + const question = { ...recallSession().questions[0], chunks: [] }; + expect(recallSegments(question)).toEqual([ + { id: "source-whole", text: question.sentence, meaning: question.translation, hidden: true }, + ]); + }); + it("restores unsent input on refresh but discards draft from a different saved revision", () => { + const session = recallSession(); + const draft = { values: { contrast: "my answer" }, whole: "", assessment: null }; + persistRecallDraft(session, draft); + expect(readRecallDraft(session)).toEqual(draft); + expect(readRecallDraft({ ...session, version: 2 }).values).toEqual({}); + }); + it("preserves both phases and self assessment in checkpoint payload", () => { + const session = { + ...recallSession(), + phase: "whole" as const, + answers: { "partial:other": "old" }, + }; + const answers = answersWithRecallDraft(session, { + values: { verb: "is" }, + whole: "She is a doctor.", + assessment: "again", + }); + expect(answers["whole:source"]).toBe("She is a doctor."); + expect(answers["partial:other"]).toBe("old"); + expect(JSON.parse(answers["partial:source"]).assessment).toBe("again"); + }); +}); diff --git a/src/features/grammar-recall/index.ts b/src/features/grammar-recall/index.ts new file mode 100644 index 00000000..11f7ee6d --- /dev/null +++ b/src/features/grammar-recall/index.ts @@ -0,0 +1,2 @@ +export { GrammarRecall } from "./ui/GrammarRecall"; +export type { GrammarRecallProps, RecallActionResult } from "./models/interface"; diff --git a/src/features/grammar-recall/models/interface.ts b/src/features/grammar-recall/models/interface.ts new file mode 100644 index 00000000..0cd0573a --- /dev/null +++ b/src/features/grammar-recall/models/interface.ts @@ -0,0 +1,36 @@ +import type { ReactNode } from "react"; +import type { + GrammarSession, + GrammarSessionQuestion, + SaveGrammarAnswersInput, + CompleteGrammarSessionInput, +} from "@/entities/grammar-session"; +export type RecallActionResult = + | { ok: true; data: GrammarSession } + | { ok: false; message: string }; +export interface GrammarRecallProps { + readonly initialSession: GrammarSession; + readonly save: (input: SaveGrammarAnswersInput) => Promise; + readonly complete: (input: CompleteGrammarSessionInput) => Promise; + readonly onComplete: (session: GrammarSession) => void; + readonly onExit: () => void; + readonly renderAudio?: (question: GrammarSessionQuestion) => ReactNode; +} +export interface RecallDraft { + values: Record; + whole: string; + assessment: "remembered" | "again" | null; +} +export interface RecallQuestionProps { + readonly session: GrammarSession; + readonly busy: boolean; + readonly error: string; + readonly onMove: (draft: RecallDraft, direction: "next" | "back" | "exit") => void; + readonly audio?: ReactNode; +} +export interface RecallSegment { + readonly id: string; + readonly text: string; + readonly hidden: boolean; + readonly meaning: string; +} diff --git a/src/features/grammar-recall/services/recallDraft.ts b/src/features/grammar-recall/services/recallDraft.ts new file mode 100644 index 00000000..40f0e11b --- /dev/null +++ b/src/features/grammar-recall/services/recallDraft.ts @@ -0,0 +1,93 @@ +import type { GrammarSession, GrammarSessionQuestion } from "@/entities/grammar-session"; +import type { RecallDraft, RecallSegment } from "../models/interface"; +export function recallSegments(question: GrammarSessionQuestion): RecallSegment[] { + const sentence = question.sentence ?? ""; + const chunks = question.chunks; + if (chunks.length < 2) + return [ + { id: `${question.id}-whole`, text: sentence, hidden: true, meaning: question.translation }, + ]; + const segments: RecallSegment[] = []; + let cursor = 0; + for (const [index, chunk] of chunks.entries()) { + if (chunk.start < cursor || chunk.end > sentence.length || chunk.end <= chunk.start) continue; + if (chunk.start > cursor) + segments.push({ + id: `gap-${cursor}`, + text: sentence.slice(cursor, chunk.start), + hidden: false, + meaning: "", + }); + segments.push({ + id: chunk.id, + text: sentence.slice(chunk.start, chunk.end), + hidden: index > 0, + meaning: chunk.meaning, + }); + cursor = chunk.end; + } + if (cursor < sentence.length) + segments.push({ + id: `gap-${cursor}`, + text: sentence.slice(cursor), + hidden: false, + meaning: "", + }); + return segments; +} +function validDraft(value: unknown): value is RecallDraft { + if (!value || typeof value !== "object") return false; + const draft = value as Partial; + return ( + typeof draft.whole === "string" && + draft.whole.length <= 3000 && + !!draft.values && + Object.values(draft.values).every( + (value) => typeof value === "string" && value.length <= 1000, + ) && + (draft.assessment === null || draft.assessment === "remembered" || draft.assessment === "again") + ); +} +export function recallDraftKey(session: GrammarSession) { + return `echo:grammar-recall:${session.id}:${session.phase}:${session.questionIndex}`; +} +export function readRecallDraft(session: GrammarSession): RecallDraft { + const question = session.questions[session.questionIndex]; + let draft: RecallDraft = { + values: {}, + whole: session.answers[`whole:${question.id}`] ?? "", + assessment: null, + }; + try { + const partial = JSON.parse(session.answers[`partial:${question.id}`] ?? "null"); + if (partial && typeof partial === "object" && partial.values) + draft = { ...draft, values: partial.values, assessment: partial.assessment ?? null }; + } catch { + /* 이전 버전의 단순 문자열 답안은 빈칸 초안으로 해석하지 않는다. */ + } + try { + const local = JSON.parse(sessionStorage.getItem(recallDraftKey(session)) ?? "null"); + if (local?.version === session.version && validDraft(local.draft)) return local.draft; + } catch { + /* 저장소를 사용할 수 없으면 서버에 저장된 답안으로 계속한다. */ + } + return validDraft(draft) ? draft : { values: {}, whole: "", assessment: null }; +} +export function persistRecallDraft(session: GrammarSession, draft: RecallDraft) { + try { + sessionStorage.setItem( + recallDraftKey(session), + JSON.stringify({ version: session.version, draft }), + ); + } catch { + /* 브라우저 저장 공간이 없더라도 서버 저장과 입력을 막지 않는다. */ + } +} +export function answersWithRecallDraft(session: GrammarSession, draft: RecallDraft) { + const id = session.questions[session.questionIndex].id; + return { + ...session.answers, + [`partial:${id}`]: JSON.stringify({ values: draft.values, assessment: draft.assessment }), + ...(session.phase === "whole" ? { [`whole:${id}`]: draft.whole } : {}), + }; +} diff --git a/src/features/grammar-recall/services/useRecallSession.ts b/src/features/grammar-recall/services/useRecallSession.ts new file mode 100644 index 00000000..27cebab9 --- /dev/null +++ b/src/features/grammar-recall/services/useRecallSession.ts @@ -0,0 +1,68 @@ +"use client"; +import { useState } from "react"; +import type { GrammarRecallProps, RecallDraft } from "../models/interface"; +import { answersWithRecallDraft } from "./recallDraft"; +export function useRecallSession(props: GrammarRecallProps) { + const [session, setSession] = useState(props.initialSession); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + async function move(draft: RecallDraft, direction: "next" | "back" | "exit") { + if (busy) return; + setBusy(true); + setError(""); + try { + const last = session.questionIndex === session.questions.length - 1; + const finishing = direction === "next" && last && session.phase === "whole"; + let phase = session.phase; + let index = session.questionIndex; + if (direction === "next" && !finishing) { + if (last) { + phase = "whole"; + index = 0; + } else index++; + } + if (direction === "back") { + if (index > 0) index--; + else if (phase === "whole") { + phase = "partial"; + index = session.questions.length - 1; + } else { + setBusy(false); + return; + } + } + const saved = await props.save({ + id: session.id, + expectedVersion: session.version, + answers: answersWithRecallDraft(session, draft), + phase, + questionIndex: index, + }); + if (!saved.ok) { + setError(saved.message); + return; + } + setSession(saved.data); + if (direction === "exit") { + props.onExit(); + return; + } + if (finishing) { + const completed = await props.complete({ + id: saved.data.id, + expectedVersion: saved.data.version, + }); + if (!completed.ok) { + setError(completed.message); + return; + } + props.onComplete(completed.data); + } + } catch { + setError("진행 상태를 저장하지 못했습니다. 입력은 유지됩니다. 다시 시도해주세요."); + } finally { + setBusy(false); + } + } + return { session, busy, error, move }; +} diff --git a/src/features/grammar-recall/ui/GrammarRecall.tsx b/src/features/grammar-recall/ui/GrammarRecall.tsx new file mode 100644 index 00000000..59c81db0 --- /dev/null +++ b/src/features/grammar-recall/ui/GrammarRecall.tsx @@ -0,0 +1,24 @@ +"use client"; +import type { GrammarRecallProps } from "../models/interface"; +import { useRecallSession } from "../services/useRecallSession"; +import { RecallQuestion } from "./RecallQuestion"; +export function GrammarRecall(props: GrammarRecallProps) { + const { session, busy, error, move } = useRecallSession(props); + const question = session.questions[session.questionIndex]; + return ( +
+
+

RECALL PRACTICE

+

{session.title}

+
+ +
+ ); +} diff --git a/src/features/grammar-recall/ui/RecallBlankFields.tsx b/src/features/grammar-recall/ui/RecallBlankFields.tsx new file mode 100644 index 00000000..23cca7d2 --- /dev/null +++ b/src/features/grammar-recall/ui/RecallBlankFields.tsx @@ -0,0 +1,35 @@ +import type { RecallSegment } from "../models/interface"; +export function RecallBlankFields({ + segments, + values, + onChange, + disabled, +}: { + segments: readonly RecallSegment[]; + values: Record; + onChange: (id: string, value: string) => void; + disabled: boolean; +}) { + return ( +
+ {segments.map((segment) => + segment.hidden ? ( + + ) : ( + {segment.text} + ), + )} +
+ ); +} diff --git a/src/features/grammar-recall/ui/RecallQuestion.tsx b/src/features/grammar-recall/ui/RecallQuestion.tsx new file mode 100644 index 00000000..2764e4d3 --- /dev/null +++ b/src/features/grammar-recall/ui/RecallQuestion.tsx @@ -0,0 +1,142 @@ +"use client"; +import { useState } from "react"; +import type { RecallDraft, RecallQuestionProps } from "../models/interface"; +import { persistRecallDraft, readRecallDraft, recallSegments } from "../services/recallDraft"; +import { RecallBlankFields } from "./RecallBlankFields"; +export function RecallQuestion({ session, busy, error, onMove, audio }: RecallQuestionProps) { + const question = session.questions[session.questionIndex]; + const [draft, setDraft] = useState(() => readRecallDraft(session)); + const [revealed, setRevealed] = useState(false); + const [hint, setHint] = useState(false); + const segments = recallSegments(question); + const partial = session.phase === "partial"; + function update(next: RecallDraft) { + setDraft(next); + persistRecallDraft(session, next); + } + function changeBlank(id: string, value: string) { + update({ ...draft, values: { ...draft.values, [id]: value } }); + } + const filled = partial + ? segments.filter((s) => s.hidden).every((s) => draft.values[s.id]?.trim()) + : !!draft.whole.trim(); + return ( +
+
+ + {partial ? "01 · 의미 덩어리 채우기" : "02 · 문장 전체 떠올리기"} + + + {session.questionIndex + 1} / {session.questions.length} + +
+

{question.translation}

+

핵심 어법: {session.learningNote}

+ {partial ? ( + + ) : ( +