@@ -26,7 +30,7 @@ export function ExampleActions() {
{error && (
- {error}
+ {exampleErrorMessage(error)}
)}
{pending && (
diff --git a/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx b/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx
index 0e566ac3..ac71486b 100644
--- a/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx
@@ -1,13 +1,16 @@
"use client";
+
import { useId } from "react";
import { Textarea } from "@/shared/components/atomics/textarea/Textarea";
import { Button } from "@/shared/components/atomics/button/Button";
import { useExamples } from "./ExampleProvider";
+
const fields = [
{ field: "sentence", label: "영어 예문" },
{ field: "translation", label: "한국어 뜻" },
{ field: "targetExplanation", label: "목표 어법 설명" },
] as const;
+
export function ExampleCandidateCard({ id, number }: { id: string; number: number }) {
const formId = useId();
const candidate = useExamples((s) => s.candidates.find((candidate) => candidate.id === id));
@@ -16,7 +19,9 @@ export function ExampleCandidateCard({ id, number }: { id: string; number: numbe
const change = useExamples((s) => s.change);
const select = useExamples((s) => s.select);
const generate = useExamples((s) => s.generate);
+
if (!candidate) return null;
+
return (
diff --git a/src/features/grammar-example-generation/ui/ExampleCandidates.tsx b/src/features/grammar-example-generation/ui/ExampleCandidates.tsx
index 392d98be..42e5f2ce 100644
--- a/src/features/grammar-example-generation/ui/ExampleCandidates.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleCandidates.tsx
@@ -1,9 +1,12 @@
"use client";
+
import { useShallow } from "zustand/react/shallow";
import { useExamples } from "./ExampleProvider";
import { ExampleCandidateCard } from "./ExampleCandidateCard";
+
export function ExampleCandidates() {
const ids = useExamples(useShallow((s) => s.candidates.map((candidate) => candidate.id)));
+
return (
{ids.map((id, index) => (
diff --git a/src/features/grammar-example-generation/ui/ExampleProvider.tsx b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
index 54880e88..51e50baf 100644
--- a/src/features/grammar-example-generation/ui/ExampleProvider.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
@@ -1,25 +1,46 @@
"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),
}),
);
+
useEffect(() => () => store.getState().cancel(), [store]);
useEffect(() => {
function beforeUnload(event: BeforeUnloadEvent) {
@@ -28,13 +49,19 @@ export function ExampleProvider({
event.returnValue = "";
}
}
+
window.addEventListener("beforeunload", beforeUnload);
+
return () => window.removeEventListener("beforeunload", beforeUnload);
}, [store]);
+
return {children};
}
+
export function useExamples(selector: (state: ExampleState) => T) {
const store = useContext(Context);
+
if (!store) throw new Error("ExampleProvider가 필요합니다.");
+
return useStore(store, selector);
}
diff --git a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
index 023efd3c..ffbe1e9e 100644
--- a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
+++ b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
@@ -1,4 +1,5 @@
"use client";
+
import { useState } from "react";
import { Button } from "@/shared/components/atomics/button/Button";
import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog";
@@ -6,15 +7,18 @@ import type { GrammarExampleManagerProps } from "../models/interface";
import { ExampleProvider, useExamples } from "./ExampleProvider";
import { ExampleCandidates } from "./ExampleCandidates";
import { ExampleActions } from "./ExampleActions";
+
function ExampleBack({ onBack }: { onBack?: () => void }) {
const [confirm, setConfirm] = useState(false);
const dirty = useExamples((s) => s.dirty);
const saving = useExamples((s) => s.pending === "save");
const discard = useExamples((s) => s.discard);
+
function leave() {
discard();
onBack?.();
}
+
return (
<>
diff --git a/src/features/grammar-history/ui/GrammarHistoryRows.tsx b/src/features/grammar-history/ui/GrammarHistoryRows.tsx
index fde13319..3c7cca9c 100644
--- a/src/features/grammar-history/ui/GrammarHistoryRows.tsx
+++ b/src/features/grammar-history/ui/GrammarHistoryRows.tsx
@@ -1,19 +1,27 @@
import Link from "next/link";
import type { GrammarSessionSummary } from "@/entities/grammar-session";
import { formatGrammarPracticeDate } from "../services/formatPracticeDate";
-export function GrammarHistoryRows({ items }: { items: readonly GrammarSessionSummary[] }) {
+
+export function GrammarHistoryRows({
+ items,
+ resultHref,
+}: {
+ items: readonly GrammarSessionSummary[];
+ resultHref?: (sessionId: string) => string;
+}) {
if (!items.length)
return (
아직 완료한 연습이 없습니다.
);
+
return (
{items.map((item) => (
-
diff --git a/src/features/grammar-note-editor/models/interface.ts b/src/features/grammar-note-editor/models/interface.ts
index 86244e69..c3a844f6 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,
@@ -12,12 +13,17 @@ export type EditorAnalysisResult =
| { status: "analyzed"; data: { metadata: GrammarMetadata; analysis: SentenceAnalysis } }
| { status: "needs-input"; precheck: Exclude
}
| { status: "error"; message: string };
+
export type SaveNoteCommand = {
requestId: string;
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 +36,17 @@ 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..fd9b67d8 100644
--- a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
+++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
@@ -1,35 +1,35 @@
"use server";
+
import { GrammarNotePersistenceError, GrammarNoteRepository } from "@/entities/grammar-note";
import { createSupabaseServerClient } from "@/shared/lib/supabase/server";
import { observeOperation } from "@/shared/lib/logging/observeOperation";
import { recordOperationEvent } from "@/shared/lib/logging/pino";
import { persistReviewedNote } from "../persistReviewedNote";
import type { SaveNoteCommand, SaveNoteResult } from "../../models/interface";
+
export async function saveGrammarNote(command: SaveNoteCommand): Promise {
try {
const note = await observeOperation({
operation: "grammar.note.save",
resourceId: "grammar-note",
recordEvent: recordOperationEvent,
+
execute: async () => {
const client = await createSupabaseServerClient();
const { data, error } = await client.auth.getUser();
+
if (error || !data.user) throw new GrammarNotePersistenceError("UNAUTHORIZED");
+
const repository = new GrammarNoteRepository(client);
+
return persistReviewedNote(command, repository);
},
});
+
return { ok: true, note };
} catch (error) {
const code = error instanceof GrammarNotePersistenceError ? error.code : "PERSISTENCE_FAILED";
- return {
- ok: false,
- message:
- code === "VERSION_CONFLICT"
- ? "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요."
- : code === "UNAUTHORIZED"
- ? "로그인 후 다시 저장해 주세요."
- : "노트를 저장하지 못했습니다. 잠시 후 다시 저장해 주세요.",
- };
+
+ return { ok: false, code };
}
}
diff --git a/src/features/grammar-note-editor/services/createEditorStore.ts b/src/features/grammar-note-editor/services/createEditorStore.ts
index 8c215349..5307a856 100644
--- a/src/features/grammar-note-editor/services/createEditorStore.ts
+++ b/src/features/grammar-note-editor/services/createEditorStore.ts
@@ -9,6 +9,7 @@ export function createEditorStore(
// 입력 변경·화면 이탈 후에도 서버 분석은 끝날 수 있어, 현재 세대의 응답만 적용한다.
let generation = 0;
let saveIdentity: { content: string; id: string } | null = null;
+
return createStore((set, get) => ({
source: initialNote?.source ?? { sentence: "", learningNote: "", revision: 0 },
result: initialNote
@@ -19,15 +20,22 @@ export function createEditorStore(
: null,
stage: initialNote ? "review" : "input",
pending: null,
- error: "",
+ error: null,
fieldErrors: {},
reviewed: false,
analysisDirty: false,
- setAnalysisDirty: (analysisDirty) =>
- 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;
+
generation++;
set((state) => ({
source: { ...state.source, [field]: value, revision: state.source.revision + 1 },
@@ -36,75 +44,96 @@ export function createEditorStore(
pending: null,
reviewed: false,
dirty: true,
- error: "",
+ error: null,
fieldErrors: {},
}));
},
+
changeAnalysis: (analysis) =>
set((state) =>
state.result?.status === "analyzed"
? {
result: { status: "analyzed", data: { ...state.result.data, analysis } },
reviewed: false,
+ analysisDirty: false,
dirty: true,
}
: {},
),
+
setReviewed: (reviewed) => set({ reviewed }),
+
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++;
},
+
analyze: async () => {
if (get().pending) return;
+
const parsed = grammarSourceSchema.safeParse(get().source);
+
if (!parsed.success) {
const errors = parsed.error.flatten().fieldErrors;
+
set({
fieldErrors: { sentence: errors.sentence?.[0], learningNote: errors.learningNote?.[0] },
});
+
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;
+
// 분석 함수는 주입받으므로 서버 구현의 검증을 가정하지 않고 원문·리비전 일치를 다시 확인한다.
if (
result.status === "needs-input" &&
result.precheck.sourceRevision !== parsed.data.revision
)
throw new Error("STALE_PRECHECK");
+
if (result.status === "analyzed") {
const content = grammarNoteContentSchema.safeParse({
source: parsed.data,
...result.data,
examples: [],
});
+
if (!content.success) throw new Error("INVALID_ANALYSIS");
}
+
set({
result,
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" },
});
}
},
+
save: async () => {
const state = get();
+
if (
state.pending ||
state.analysisDirty ||
@@ -112,21 +141,28 @@ export function createEditorStore(
state.result?.status !== "analyzed"
)
return;
+
const content = grammarNoteContentSchema.safeParse({
source: state.source,
...state.result.data,
analysis: { ...state.result.data.analysis, reviewStatus: "reviewed" },
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,
@@ -135,14 +171,17 @@ export function createEditorStore(
? { existing: { id: initialNote.id, expectedVersion: initialNote.version } }
: {}),
});
+
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..3389f0af
--- /dev/null
+++ b/src/features/grammar-note-editor/ui/EditorError.tsx
@@ -0,0 +1,37 @@
+"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..d521d086 100644
--- a/src/features/grammar-note-editor/ui/EditorProvider.tsx
+++ b/src/features/grammar-note-editor/ui/EditorProvider.tsx
@@ -1,41 +1,69 @@
"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";
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),
}),
);
+
useEffect(() => () => store.getState().cancel(), [store]);
useEffect(() => {
function preventUnload(event: BeforeUnloadEvent) {
const state = store.getState();
+
if (!state.dirty && state.pending !== "save") return;
+
event.preventDefault();
event.returnValue = "";
}
+
window.addEventListener("beforeunload", preventUnload);
+
return () => window.removeEventListener("beforeunload", preventUnload);
}, [store]);
+
return {children};
}
+
export function useEditor(selector: (state: EditorState) => T) {
const store = useContext(Context);
+
if (!store) throw new Error("EditorProvider가 필요합니다.");
+
return useStore(store, selector);
}
diff --git a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
index 1efef5e0..2ca2d3e6 100644
--- a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
+++ b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
@@ -1,33 +1,34 @@
"use client";
+
import { useState } from "react";
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({
AnalysisEditor,
onExit,
}: Pick) {
const stage = useEditor((s) => s.stage);
- const error = useEditor((s) => s.error);
+
return (
{stage === "input" ?
:
}
- {error && (
-
- {error}
-
- )}
+
);
}
+
function EditorExit({ onExit }: { onExit: () => void }) {
const [confirm, setConfirm] = useState(false);
const dirty = useEditor((s) => s.dirty);
const saving = useEditor((s) => s.pending === "save");
+
return (
<>
void }) {
disabled={saving}
onClick={() => (dirty ? setConfirm(true) : onExit())}
>
- ← 목록으로
+ ← 뒤로가기
void }) {
>
);
}
+
export function GrammarNoteEditor({ AnalysisEditor, onExit, ...props }: GrammarNoteEditorProps) {
return (
diff --git a/src/features/grammar-practice/index.ts b/src/features/grammar-practice/index.ts
index d1827030..2eba1daf 100644
--- a/src/features/grammar-practice/index.ts
+++ b/src/features/grammar-practice/index.ts
@@ -1,6 +1,9 @@
-export type { GrammarSessionResult } from "./models/interface";
+export type { GrammarSessionResult, GrammarPracticeLauncherProps } from "./models/interface";
+
export {
startGrammarSession,
saveGrammarSessionAnswers,
completeGrammarSession,
} from "./services/actions/grammarSessionActions";
+
+export { GrammarPracticeLauncher } from "./ui/GrammarPracticeLauncher";
diff --git a/src/features/grammar-practice/models/interface.ts b/src/features/grammar-practice/models/interface.ts
index 02d915aa..3ed21133 100644
--- a/src/features/grammar-practice/models/interface.ts
+++ b/src/features/grammar-practice/models/interface.ts
@@ -1,4 +1,22 @@
-import type { GrammarSession } from "@/entities/grammar-session";
+import type {
+ GrammarSession,
+ GrammarSessionMode,
+ GrammarSessionError,
+} from "@/entities/grammar-session";
+
export type GrammarSessionResult =
| { ok: true; data: GrammarSession }
- | { ok: false; message: string };
+ | { ok: false; code: GrammarSessionError["code"] };
+
+export interface GrammarPracticeLauncherProps {
+ noteId: string;
+ activeSessions: Partial>;
+ onStart: (input: {
+ noteId: string;
+ requestId: string;
+ mode: GrammarSessionMode;
+ }) => Promise<
+ GrammarSessionResult | { ok: false; code: "NOT_READY" | "NOT_INVITED" | "RATE_LIMITED" }
+ >;
+ onOpen: (sessionId: string) => void;
+}
diff --git a/src/features/grammar-practice/services/actions/grammarSessionActions.ts b/src/features/grammar-practice/services/actions/grammarSessionActions.ts
index ea9798b0..5b19b3bb 100644
--- a/src/features/grammar-practice/services/actions/grammarSessionActions.ts
+++ b/src/features/grammar-practice/services/actions/grammarSessionActions.ts
@@ -1,4 +1,5 @@
"use server";
+
import { z } from "zod";
import { createSupabaseServerClient } from "@/shared/lib/supabase/server";
import { observeOperation } from "@/shared/lib/logging/observeOperation";
@@ -6,7 +7,6 @@ import { recordOperationEvent } from "@/shared/lib/logging/pino";
import {
GrammarSessionRepository,
GrammarSessionError,
- grammarSessionErrorMessage,
startGrammarSessionSchema,
saveGrammarAnswersSchema,
completeGrammarSessionSchema,
@@ -23,32 +23,41 @@ async function executeSessionAction(
operation,
resourceId: "grammar-session",
recordEvent: recordOperationEvent,
+
execute: async () => {
const supabase = await createSupabaseServerClient();
const { data, error } = await supabase.auth.getUser();
+
if (error || !data.user) throw new GrammarSessionError("UNAUTHORIZED");
+
return { ok: true as const, data: await execute(new GrammarSessionRepository(supabase)) };
},
});
} 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",
};
}
}
+
export async function startGrammarSession(input: unknown): Promise {
return executeSessionAction("grammar.session.start", (repository) =>
repository.start(startGrammarSessionSchema.parse(input)),
);
}
+
export async function saveGrammarSessionAnswers(input: unknown): Promise {
return executeSessionAction("grammar.session.save", (repository) =>
repository.saveAnswers(saveGrammarAnswersSchema.parse(input)),
);
}
+
export async function completeGrammarSession(input: unknown): Promise {
return executeSessionAction("grammar.session.complete", (repository) =>
repository.complete(completeGrammarSessionSchema.parse(input)),
diff --git a/src/features/grammar-practice/ui/GrammarPracticeLauncher.tsx b/src/features/grammar-practice/ui/GrammarPracticeLauncher.tsx
new file mode 100644
index 00000000..ffdd7ea0
--- /dev/null
+++ b/src/features/grammar-practice/ui/GrammarPracticeLauncher.tsx
@@ -0,0 +1,114 @@
+"use client";
+
+import { grammarSessionErrorMessage } from "@/entities/grammar-session";
+import { useRef, useState } from "react";
+import type { GrammarSessionMode } from "@/entities/grammar-session";
+import type { GrammarPracticeLauncherProps } from "../models/interface";
+
+const modes = [
+ {
+ mode: "recall",
+ title: "암기 연습",
+ label: "01 / RECALL",
+ description:
+ "의미 덩어리를 채우고 전체 문장을 떠올려요. 필요하면 힌트와 원문을 확인할 수 있어요.",
+ },
+ {
+ mode: "exam",
+ title: "어법 시험",
+ label: "02 / APPLY",
+ description:
+ "기존 예문을 써보고, 새로운 문맥에 배운 어법을 적용해요. 완료 후 문장별 피드백을 받아요.",
+ },
+] as const;
+
+export function GrammarPracticeLauncher({
+ noteId,
+ activeSessions,
+ onStart,
+ onOpen,
+}: GrammarPracticeLauncherProps) {
+ const [pending, setPending] = useState(null);
+ const [error, setError] = useState(null);
+ const busy = useRef(false);
+ const requests = useRef>>({});
+
+ async function start(mode: GrammarSessionMode) {
+ if (busy.current) return;
+
+ busy.current = true;
+ setPending(mode);
+ setError(null);
+
+ try {
+ const requestId = requests.current[mode] ?? crypto.randomUUID();
+
+ requests.current[mode] = requestId;
+ const result = await onStart({ noteId, requestId, mode });
+
+ if (result.ok) {
+ delete requests.current[mode];
+ onOpen(result.data.id);
+ } else
+ setError(
+ result.code === "NOT_INVITED"
+ ? "AI 기능 이용 권한을 확인해 주세요."
+ : result.code === "RATE_LIMITED"
+ ? "AI 사용 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."
+ : result.code === "NOT_READY"
+ ? "시험 준비 상태를 확인해 주세요."
+ : grammarSessionErrorMessage(result.code),
+ );
+ } catch {
+ setError("연습을 준비하지 못했습니다. 다시 시도해 주세요.");
+ } finally {
+ busy.current = false;
+ setPending(null);
+ }
+ }
+
+ return (
+
+
+ {modes.map(({ mode, title, label, description }) => (
+
+ {label}
+ {title}
+ {description}
+
+ {activeSessions[mode] && (
+ onOpen(activeSessions[mode]!)}
+ className="min-h-11 rounded-md bg-practice-ink px-4 text-sm text-white disabled:opacity-50"
+ >
+ {title} 이어하기
+
+ )}
+ start(mode)}
+ className="min-h-11 rounded-md border border-practice-input-line px-4 text-sm text-practice-ink transition-shadow hover:shadow-emphasize disabled:opacity-50 motion-reduce:transition-none"
+ >
+ {pending === mode ? "준비 중…" : `${title} 새로 시작`}
+
+
+
+ ))}
+
+ {error && (
+
+ {error} 같은 시작 버튼으로 다시 시도할 수 있어요.
+
+ )}
+
+ 새로 시작하면 문장 순서가 바뀝니다. 이어하기는 저장한 순서와 답안을 유지합니다.
+
+
+ );
+}
diff --git a/src/features/grammar-recall/index.ts b/src/features/grammar-recall/index.ts
index 11f7ee6d..82c572ac 100644
--- a/src/features/grammar-recall/index.ts
+++ b/src/features/grammar-recall/index.ts
@@ -1,2 +1,4 @@
export { GrammarRecall } from "./ui/GrammarRecall";
-export type { GrammarRecallProps, RecallActionResult } from "./models/interface";
+export { RecallSession } from "./ui/RecallSession";
+
+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 0cd0573a..abfe39d0 100644
--- a/src/features/grammar-recall/models/interface.ts
+++ b/src/features/grammar-recall/models/interface.ts
@@ -1,14 +1,17 @@
import type { ReactNode } from "react";
import type {
GrammarSession,
+ GrammarSessionError,
GrammarSessionQuestion,
SaveGrammarAnswersInput,
CompleteGrammarSessionInput,
} from "@/entities/grammar-session";
+
export type RecallActionResult =
| { ok: true; data: GrammarSession }
- | { ok: false; message: string };
-export interface GrammarRecallProps {
+ | { ok: false; code: GrammarSessionError["code"] };
+
+export interface RecallSessionProps {
readonly initialSession: GrammarSession;
readonly save: (input: SaveGrammarAnswersInput) => Promise;
readonly complete: (input: CompleteGrammarSessionInput) => Promise;
@@ -16,11 +19,13 @@ export interface GrammarRecallProps {
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;
@@ -28,6 +33,7 @@ export interface RecallQuestionProps {
readonly onMove: (draft: RecallDraft, direction: "next" | "back" | "exit") => void;
readonly audio?: ReactNode;
}
+
export interface RecallSegment {
readonly id: string;
readonly text: string;
diff --git a/src/features/grammar-recall/services/recallDraft.ts b/src/features/grammar-recall/services/recallDraft.ts
index 37720016..a51ee9ae 100644
--- a/src/features/grammar-recall/services/recallDraft.ts
+++ b/src/features/grammar-recall/services/recallDraft.ts
@@ -1,16 +1,22 @@
+import { GRAMMAR_ANSWER_MAX_LENGTH } from "@/entities/grammar-session";
import type { GrammarSession, GrammarSessionQuestion } from "@/entities/grammar-session";
import type { RecallDraft, RecallSegment } from "../models/interface";
+
export function createRecallSegments(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}`,
@@ -18,6 +24,7 @@ export function createRecallSegments(question: GrammarSessionQuestion): RecallSe
hidden: false,
meaning: "",
});
+
segments.push({
id: chunk.id,
text: sentence.slice(chunk.start, chunk.end),
@@ -26,6 +33,7 @@ export function createRecallSegments(question: GrammarSessionQuestion): RecallSe
});
cursor = chunk.end;
}
+
if (cursor < sentence.length)
segments.push({
id: `gap-${cursor}`,
@@ -33,24 +41,30 @@ export function createRecallSegments(question: GrammarSessionQuestion): RecallSe
hidden: false,
meaning: "",
});
+
return segments;
}
+
function isRecallDraft(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.whole.length <= GRAMMAR_ANSWER_MAX_LENGTH &&
!!draft.values &&
Object.values(draft.values).every(
- (value) => typeof value === "string" && value.length <= 1000,
+ (value) => typeof value === "string" && value.length <= GRAMMAR_ANSWER_MAX_LENGTH,
) &&
(draft.assessment === null || draft.assessment === "remembered" || draft.assessment === "again")
);
}
+
export function getRecallDraftKey(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 = {
@@ -58,21 +72,27 @@ export function readRecallDraft(session: GrammarSession): RecallDraft {
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(getRecallDraftKey(session)) ?? "null");
+
if (local?.version === session.version && isRecallDraft(local.draft)) return local.draft;
} catch {
/* 저장소를 사용할 수 없으면 서버에 저장된 답안으로 계속한다. */
}
+
return isRecallDraft(draft) ? draft : { values: {}, whole: "", assessment: null };
}
+
export function persistRecallDraft(session: GrammarSession, draft: RecallDraft) {
try {
sessionStorage.setItem(
@@ -83,8 +103,10 @@ export function persistRecallDraft(session: GrammarSession, draft: RecallDraft)
/* 브라우저 저장 공간이 없더라도 서버 저장과 입력을 막지 않는다. */
}
}
+
export function mergeRecallDraftIntoAnswers(session: GrammarSession, draft: RecallDraft) {
const id = session.questions[session.questionIndex].id;
+
return {
...session.answers,
[`partial:${id}`]: JSON.stringify({ values: draft.values, assessment: draft.assessment }),
diff --git a/src/features/grammar-recall/services/useRecallSession.ts b/src/features/grammar-recall/services/useRecallSession.ts
index c2572202..ccd2eb8b 100644
--- a/src/features/grammar-recall/services/useRecallSession.ts
+++ b/src/features/grammar-recall/services/useRecallSession.ts
@@ -1,26 +1,34 @@
"use client";
+
+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("");
+ 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";
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") {
@@ -28,9 +36,11 @@ export function useRecallSession(props: GrammarRecallProps) {
index = session.questions.length - 1;
} else {
setBusy(false);
+
return;
}
}
+
const saved = await props.save({
id: session.id,
expectedVersion: session.version,
@@ -38,31 +48,41 @@ export function useRecallSession(props: GrammarRecallProps) {
phase,
questionIndex: index,
});
+
if (!saved.ok) {
- setError(saved.message);
+ setError(saved.code);
+
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);
+ setError(completed.code);
+
return;
}
+
props.onComplete(completed.data);
}
} catch {
- setError("진행 상태를 저장하지 못했습니다. 입력은 유지됩니다. 다시 시도해주세요.");
+ setError("FAILED");
} 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
index 59c81db0..ae692bb1 100644
--- a/src/features/grammar-recall/ui/GrammarRecall.tsx
+++ b/src/features/grammar-recall/ui/GrammarRecall.tsx
@@ -1,24 +1,13 @@
-"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];
+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/RecallBlankFields.tsx b/src/features/grammar-recall/ui/RecallBlankFields.tsx
index 23cca7d2..1801d69a 100644
--- a/src/features/grammar-recall/ui/RecallBlankFields.tsx
+++ b/src/features/grammar-recall/ui/RecallBlankFields.tsx
@@ -1,4 +1,6 @@
+import { GRAMMAR_ANSWER_MAX_LENGTH } from "@/entities/grammar-session";
import type { RecallSegment } from "../models/interface";
+
export function RecallBlankFields({
segments,
values,
@@ -19,7 +21,7 @@ export function RecallBlankFields({
onChange(segment.id, event.target.value)}
diff --git a/src/features/grammar-recall/ui/RecallQuestion.tsx b/src/features/grammar-recall/ui/RecallQuestion.tsx
index 255b7aef..211acbde 100644
--- a/src/features/grammar-recall/ui/RecallQuestion.tsx
+++ b/src/features/grammar-recall/ui/RecallQuestion.tsx
@@ -1,8 +1,11 @@
"use client";
+
+import { GRAMMAR_ANSWER_MAX_LENGTH } from "@/entities/grammar-session";
import { useState } from "react";
import type { RecallDraft, RecallQuestionProps } from "../models/interface";
import { persistRecallDraft, readRecallDraft, createRecallSegments } 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));
@@ -10,16 +13,20 @@ export function RecallQuestion({ session, busy, error, onMove, audio }: RecallQu
const [hint, setHint] = useState(false);
const segments = createRecallSegments(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 (
@@ -45,7 +52,7 @@ export function RecallQuestion({ session, busy, error, onMove, audio }: RecallQu