From b5b90d956d6e868e218f456ded4bcd305f3f9a37 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Tue, 6 Oct 2026 02:18:01 +0900
Subject: [PATCH 1/4] feat(grammar): connect reviewed note registration and
revision-safe saves (#153)
---
.../GrammarNoteEditor.stories.tsx | 65 ++++++++
.../createEditorStore.test.ts | 140 ++++++++++++++++++
.../features/grammar-note-editor/fixtures.ts | 25 ++++
src/app/(protected)/grammar/new/page.tsx | 14 ++
src/features/grammar-note-editor/index.ts | 2 +
.../grammar-note-editor/models/interface.ts | 49 ++++++
.../services/actions/saveGrammarNote.ts | 40 +++++
.../services/createEditorStore.ts | 135 +++++++++++++++++
.../grammar-note-editor/ui/EditorProvider.tsx | 41 +++++
.../ui/GrammarNoteEditor.tsx | 58 ++++++++
.../grammar-note-editor/ui/ReviewStep.tsx | 50 +++++++
.../grammar-note-editor/ui/SourceField.tsx | 43 ++++++
.../grammar-note-editor/ui/SourceStep.tsx | 56 +++++++
.../grammar-editor/GrammarEditorView.tsx | 47 ++++++
src/views/grammar-editor/index.ts | 1 +
15 files changed, 766 insertions(+)
create mode 100644 src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
create mode 100644 src/_tests/features/grammar-note-editor/createEditorStore.test.ts
create mode 100644 src/_tests/features/grammar-note-editor/fixtures.ts
create mode 100644 src/app/(protected)/grammar/new/page.tsx
create mode 100644 src/features/grammar-note-editor/index.ts
create mode 100644 src/features/grammar-note-editor/models/interface.ts
create mode 100644 src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
create mode 100644 src/features/grammar-note-editor/services/createEditorStore.ts
create mode 100644 src/features/grammar-note-editor/ui/EditorProvider.tsx
create mode 100644 src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
create mode 100644 src/features/grammar-note-editor/ui/ReviewStep.tsx
create mode 100644 src/features/grammar-note-editor/ui/SourceField.tsx
create mode 100644 src/features/grammar-note-editor/ui/SourceStep.tsx
create mode 100644 src/views/grammar-editor/GrammarEditorView.tsx
create mode 100644 src/views/grammar-editor/index.ts
diff --git a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
new file mode 100644
index 00000000..e6ba4a55
--- /dev/null
+++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
@@ -0,0 +1,65 @@
+import type { Meta, StoryObj } from "@storybook/nextjs-vite";
+import { expect, fn, userEvent, within } from "storybook/test";
+import type { GrammarNoteEditorProps } from "@/features/grammar-note-editor";
+import { GrammarNoteEditor } from "@/features/grammar-note-editor";
+import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit";
+import { createEditorNote } from "@/_tests/features/grammar-note-editor/fixtures";
+const note = createEditorNote();
+const meta = {
+ title: "features/grammar-note-editor/GrammarNoteEditor",
+ component: GrammarNoteEditor,
+ args: {
+ analyze: fn(async () => ({
+ status: "analyzed",
+ data: { metadata: note.metadata, analysis: note.analysis },
+ })),
+ save: fn(async () => ({ ok: true, note })),
+ AnalysisEditor: GrammarAnalysisEditor,
+ onSaved: fn(),
+ onExit: fn(),
+ },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+export const EmptyInput: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole("button", { name: "문장 분석하기" }));
+ await expect(canvas.getAllByRole("alert")).toHaveLength(2);
+ await expect(canvas.queryByLabelText("제목")).not.toBeInTheDocument();
+ },
+};
+export const ReviewAndSave: Story = {
+ args: { initialNote: note },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getByRole("button", { name: "검토 완료 · 노트 저장" })).toBeDisabled();
+ await userEvent.click(canvas.getByRole("checkbox"));
+ await userEvent.click(canvas.getByRole("button", { name: "검토 완료 · 노트 저장" }));
+ await expect(args.onSaved).toHaveBeenCalled();
+ },
+};
+export const SaveFailure: Story = {
+ args: {
+ initialNote: note,
+ save: fn(async () => ({
+ ok: false as const,
+ message: "노트를 저장하지 못했습니다. 다시 저장해 주세요.",
+ })),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole("checkbox"));
+ await userEvent.click(canvas.getByRole("button", { name: "검토 완료 · 노트 저장" }));
+ await expect(await canvas.findByRole("alert")).toBeVisible();
+ await userEvent.click(canvas.getByRole("button", { name: "이전 · 입력 수정" }));
+ await expect(canvas.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence);
+ },
+};
diff --git a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
new file mode 100644
index 00000000..09c5b27d
--- /dev/null
+++ b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
@@ -0,0 +1,140 @@
+import { randomUUID } from "node:crypto";
+Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true });
+import { describe, expect, it, jest } from "@jest/globals";
+import { createEditorStore } from "@/features/grammar-note-editor/services/createEditorStore";
+import type {
+ EditorAnalysisResult,
+ GrammarNoteEditorProps,
+} from "@/features/grammar-note-editor/models/interface";
+import { createEditorNote } from "./fixtures";
+function dependencies() {
+ const note = createEditorNote();
+ return {
+ initialNote: note,
+ analyze: jest
+ .fn()
+ .mockResolvedValue({
+ status: "analyzed",
+ data: { metadata: note.metadata, analysis: note.analysis },
+ }),
+ save: jest.fn().mockResolvedValue({ ok: true, note }),
+ onSaved: jest.fn(),
+ };
+}
+describe("어법 등록 이벤트", () => {
+ it("두 필수 입력이 없으면 분석 요청을 보내지 않는다", async () => {
+ const deps = dependencies();
+ const store = createEditorStore({ ...deps, initialNote: undefined });
+ await store.getState().analyze();
+ expect(deps.analyze).not.toHaveBeenCalled();
+ expect(store.getState().fieldErrors).toHaveProperty("sentence");
+ expect(store.getState().fieldErrors).toHaveProperty("learningNote");
+ });
+ it("입력을 수정하면 진행 중인 이전 분석을 무시한다", async () => {
+ let resolve!: (result: EditorAnalysisResult) => void;
+ const deps = dependencies();
+ deps.analyze.mockImplementation(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const store = createEditorStore(deps);
+ const pending = store.getState().analyze();
+ store.getState().changeSource("learningNote", "새로운 설명");
+ resolve({
+ status: "analyzed",
+ data: { metadata: deps.initialNote.metadata, analysis: deps.initialNote.analysis },
+ });
+ await pending;
+ expect(store.getState().result).toBeNull();
+ expect(store.getState().source.learningNote).toBe("새로운 설명");
+ });
+ it("분석 취소 후 늦게 도착한 결과로 검토 화면으로 이동하지 않는다", async () => {
+ let resolve!: (result: EditorAnalysisResult) => void;
+ const deps = dependencies();
+ deps.analyze.mockImplementation(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const store = createEditorStore(deps);
+ const pending = store.getState().analyze();
+ store.getState().back();
+ resolve({
+ status: "analyzed",
+ data: { metadata: deps.initialNote.metadata, analysis: deps.initialNote.analysis },
+ });
+ await pending;
+ expect(store.getState().stage).toBe("input");
+ });
+ it("네트워크 저장 실패 후 재시도에 동일 요청 식별자를 사용한다", async () => {
+ const deps = dependencies();
+ deps.save.mockRejectedValueOnce(new Error("network"));
+ const store = createEditorStore({ ...deps, initialNote: undefined });
+ store.setState({
+ source: deps.initialNote.source,
+ result: {
+ status: "analyzed",
+ data: { metadata: deps.initialNote.metadata, analysis: deps.initialNote.analysis },
+ },
+ reviewed: true,
+ });
+ await store.getState().save();
+ expect(store.getState().error).toContain("다시 저장");
+ 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);
+ });
+ it("검토를 확인하기 전에는 저장하지 않고 분석 수정 후 확인을 해제한다", async () => {
+ const deps = dependencies();
+ const store = createEditorStore(deps);
+ await store.getState().save();
+ expect(deps.save).not.toHaveBeenCalled();
+ store.getState().setReviewed(true);
+ store.getState().changeAnalysis(deps.initialNote.analysis);
+ expect(store.getState().reviewed).toBe(false);
+ });
+ it("사전 체크 수정 필요는 입력을 유지하고 분석 검토로 넘어가지 않는다", async () => {
+ const deps = dependencies();
+ deps.analyze.mockResolvedValue({
+ status: "needs-input",
+ precheck: {
+ status: "uncertain",
+ sourceRevision: 0,
+ issues: [{ field: "learningNote", message: "더 설명해주세요", suggestion: null }],
+ },
+ });
+ const store = createEditorStore(deps);
+ await store.getState().analyze();
+ expect(store.getState().stage).toBe("input");
+ expect(store.getState().source).toEqual(deps.initialNote.source);
+ });
+ it("원문과 불일치하는 분석은 저장 가능한 결과로 적용하지 않는다", async () => {
+ const deps = dependencies();
+ deps.analyze.mockResolvedValue({
+ status: "analyzed",
+ data: {
+ ...deps.initialNote,
+ analysis: { ...deps.initialNote.analysis, sourceRevision: 999 },
+ },
+ });
+ const store = createEditorStore(deps);
+ await store.getState().analyze();
+ expect(store.getState().error).toContain("분석");
+ });
+ it("편집 저장은 읽은 버전을 전달하고 충돌시 초안을 유지한다", async () => {
+ const deps = dependencies();
+ deps.save.mockResolvedValue({ ok: false, message: "버전 충돌" });
+ const store = createEditorStore(deps);
+ store.getState().setReviewed(true);
+ await store.getState().save();
+ expect(deps.save.mock.calls[0][0].existing).toEqual({
+ id: deps.initialNote.id,
+ expectedVersion: 1,
+ });
+ expect(store.getState().result).not.toBeNull();
+ expect(store.getState().error).toBe("버전 충돌");
+ });
+});
diff --git a/src/_tests/features/grammar-note-editor/fixtures.ts b/src/_tests/features/grammar-note-editor/fixtures.ts
new file mode 100644
index 00000000..d830ce32
--- /dev/null
+++ b/src/_tests/features/grammar-note-editor/fixtures.ts
@@ -0,0 +1,25 @@
+import type { GrammarNote } from "@/entities/grammar-note";
+import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis";
+export function createEditorNote(): GrammarNote {
+ return {
+ id: "00000000-0000-4000-8000-000000000001",
+ ownerId: "owner",
+ version: 1,
+ createdAt: "2026-10-06T00:00:00Z",
+ updatedAt: "2026-10-06T00:00:00Z",
+ source: {
+ sentence: createGrammarAnalysis().sourceText,
+ learningNote: "not A but B",
+ revision: 0,
+ },
+ metadata: {
+ source: "ai",
+ sourceRevision: 0,
+ title: "A가 아니라 B",
+ tags: ["대조"],
+ grammarKey: null,
+ },
+ analysis: createGrammarAnalysis(),
+ examples: [],
+ };
+}
diff --git a/src/app/(protected)/grammar/new/page.tsx b/src/app/(protected)/grammar/new/page.tsx
new file mode 100644
index 00000000..c2550834
--- /dev/null
+++ b/src/app/(protected)/grammar/new/page.tsx
@@ -0,0 +1,14 @@
+import { PageContainer } from "@/widgets/app-shell";
+import { GrammarEditorView } from "@/views/grammar-editor";
+export default async function NewGrammarNotePage({
+ searchParams,
+}: {
+ searchParams: Promise<{ returnTo?: string }>;
+}) {
+ const { returnTo } = await searchParams;
+ return (
+
+
+
+ );
+}
diff --git a/src/features/grammar-note-editor/index.ts b/src/features/grammar-note-editor/index.ts
new file mode 100644
index 00000000..7283fa43
--- /dev/null
+++ b/src/features/grammar-note-editor/index.ts
@@ -0,0 +1,2 @@
+export { GrammarNoteEditor } from "./ui/GrammarNoteEditor";
+export type { GrammarNoteEditorProps, SaveNoteCommand, SaveNoteResult } from "./models/interface";
diff --git a/src/features/grammar-note-editor/models/interface.ts b/src/features/grammar-note-editor/models/interface.ts
new file mode 100644
index 00000000..fd9c6d1c
--- /dev/null
+++ b/src/features/grammar-note-editor/models/interface.ts
@@ -0,0 +1,49 @@
+import type { ComponentType } from "react";
+import type {
+ GrammarMetadata,
+ GrammarNote,
+ GrammarNoteContent,
+ GrammarSource,
+ PrecheckResult,
+ SentenceAnalysis,
+} from "@/entities/grammar-note";
+
+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 interface GrammarNoteEditorProps {
+ initialNote?: GrammarNote;
+ analyze: (source: GrammarSource) => Promise;
+ save: (command: SaveNoteCommand) => Promise;
+ AnalysisEditor: ComponentType<{
+ initialAnalysis: SentenceAnalysis;
+ onChange: (analysis: SentenceAnalysis) => void;
+ }>;
+ onSaved: (note: GrammarNote) => void;
+ onExit: () => void;
+}
+export interface EditorState {
+ source: GrammarSource;
+ result: EditorAnalysisResult | null;
+ stage: "input" | "review";
+ pending: "analysis" | "save" | null;
+ error: string;
+ fieldErrors: Partial>;
+ reviewed: boolean;
+ dirty: boolean;
+ changeSource: (field: "sentence" | "learningNote", value: string) => void;
+ changeAnalysis: (analysis: SentenceAnalysis) => void;
+ markDirty: () => void;
+ setReviewed: (reviewed: boolean) => void;
+ back: () => void;
+ analyze: () => Promise;
+ save: () => Promise;
+ cancel: () => void;
+}
diff --git a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
new file mode 100644
index 00000000..98544947
--- /dev/null
+++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
@@ -0,0 +1,40 @@
+"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 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 command.existing
+ ? repository.update({
+ id: command.existing.id,
+ expectedVersion: command.existing.expectedVersion,
+ content: command.content,
+ })
+ : repository.create({ requestId: command.requestId, content: command.content });
+ },
+ });
+ return { ok: true, note };
+ } catch (error) {
+ const code = error instanceof GrammarNotePersistenceError ? error.code : "PERSISTENCE_FAILED";
+ return {
+ ok: false,
+ message:
+ code === "VERSION_CONFLICT"
+ ? "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요."
+ : code === "UNAUTHORIZED"
+ ? "로그인 후 다시 저장해 주세요."
+ : "노트를 저장하지 못했습니다. 잠시 후 다시 저장해 주세요.",
+ };
+ }
+}
diff --git a/src/features/grammar-note-editor/services/createEditorStore.ts b/src/features/grammar-note-editor/services/createEditorStore.ts
new file mode 100644
index 00000000..de8aa466
--- /dev/null
+++ b/src/features/grammar-note-editor/services/createEditorStore.ts
@@ -0,0 +1,135 @@
+import { createStore } from "zustand/vanilla";
+import { grammarNoteContentSchema, grammarSourceSchema } from "@/entities/grammar-note";
+import type { EditorState, GrammarNoteEditorProps } from "../models/interface";
+
+export function createEditorStore(
+ dependencies: Omit,
+) {
+ const initial = dependencies.initialNote;
+ let request = 0;
+ let saveIdentity: { content: string; id: string } | null = null;
+ return createStore((set, get) => ({
+ source: initial?.source ?? { sentence: "", learningNote: "", revision: 0 },
+ result: initial
+ ? { status: "analyzed", data: { metadata: initial.metadata, analysis: initial.analysis } }
+ : null,
+ stage: initial ? "review" : "input",
+ pending: null,
+ error: "",
+ fieldErrors: {},
+ reviewed: false,
+ dirty: false,
+ changeSource: (field, value) => {
+ if (get().pending === "save") return;
+ request++;
+ set((state) => ({
+ source: { ...state.source, [field]: value, revision: state.source.revision + 1 },
+ result: null,
+ stage: "input",
+ pending: null,
+ reviewed: false,
+ dirty: true,
+ error: "",
+ fieldErrors: {},
+ }));
+ },
+ changeAnalysis: (analysis) =>
+ set((state) =>
+ state.result?.status === "analyzed"
+ ? {
+ result: { status: "analyzed", data: { ...state.result.data, analysis } },
+ reviewed: false,
+ dirty: true,
+ }
+ : {},
+ ),
+ markDirty: () => set({ dirty: true, reviewed: false }),
+ setReviewed: (reviewed) => set({ reviewed }),
+ back: () => {
+ if (get().pending === "save") return;
+ request++;
+ set({ stage: "input", pending: null, error: "" });
+ },
+ cancel: () => {
+ request++;
+ },
+ 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 token = ++request;
+ set({ pending: "analysis", error: "", fieldErrors: {} });
+ try {
+ const result = await dependencies.analyze(parsed.data);
+ if (token !== request) 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 : "",
+ });
+ } catch {
+ if (token === request)
+ set({
+ pending: null,
+ error: "분석을 완료하지 못했습니다. 입력을 유지했으니 다시 시도해 주세요.",
+ });
+ }
+ },
+ save: async () => {
+ const state = get();
+ if (state.pending || !state.reviewed || state.result?.status !== "analyzed") return;
+ const content = grammarNoteContentSchema.safeParse({
+ source: state.source,
+ ...state.result.data,
+ analysis: { ...state.result.data.analysis, reviewStatus: "reviewed" },
+ examples: initial?.examples ?? [],
+ });
+ if (!content.success) {
+ set({ error: "분석과 입력을 다시 확인해 주세요." });
+ return;
+ }
+ const signature = JSON.stringify(content.data);
+ // 동일 저장의 네트워크 재시도에는 동일 UUID를 보내 서버 중복 생성을 막는다.
+ if (saveIdentity?.content !== signature)
+ saveIdentity = { content: signature, id: crypto.randomUUID() };
+ set({ pending: "save", error: "" });
+ try {
+ const result = await dependencies.save({
+ requestId: saveIdentity.id,
+ content: content.data,
+ ...(initial ? { existing: { id: initial.id, expectedVersion: initial.version } } : {}),
+ });
+ if (!result.ok) {
+ set({ pending: null, error: result.message });
+ return;
+ }
+ set({ pending: null, dirty: false });
+ dependencies.onSaved(result.note);
+ } catch {
+ set({ pending: null, error: "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요." });
+ }
+ },
+ }));
+}
diff --git a/src/features/grammar-note-editor/ui/EditorProvider.tsx b/src/features/grammar-note-editor/ui/EditorProvider.tsx
new file mode 100644
index 00000000..220c2380
--- /dev/null
+++ b/src/features/grammar-note-editor/ui/EditorProvider.tsx
@@ -0,0 +1,41 @@
+"use client";
+import { createContext, useContext, useEffect, 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
+}: Omit & { children: ReactNode }) {
+ const latest = useRef(dependencies);
+ useEffect(() => {
+ latest.current = dependencies;
+ }, [dependencies]);
+ const [store] = useState(() =>
+ createEditorStore({
+ initialNote: dependencies.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
new file mode 100644
index 00000000..1efef5e0
--- /dev/null
+++ b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
@@ -0,0 +1,58 @@
+"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 { 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 (
+ <>
+
+
+ >
+ );
+}
+export function GrammarNoteEditor({ AnalysisEditor, onExit, ...props }: GrammarNoteEditorProps) {
+ return (
+
+
+
+ );
+}
diff --git a/src/features/grammar-note-editor/ui/ReviewStep.tsx b/src/features/grammar-note-editor/ui/ReviewStep.tsx
new file mode 100644
index 00000000..2275f079
--- /dev/null
+++ b/src/features/grammar-note-editor/ui/ReviewStep.tsx
@@ -0,0 +1,50 @@
+"use client";
+import { Button } from "@/shared/components/atomics/button/Button";
+import type { GrammarNoteEditorProps } from "../models/interface";
+import { useEditor } from "./EditorProvider";
+export function ReviewStep({ AnalysisEditor }: Pick) {
+ const result = useEditor((s) => s.result);
+ const change = useEditor((s) => s.changeAnalysis);
+ const markDirty = useEditor((s) => s.markDirty);
+ const reviewed = useEditor((s) => s.reviewed);
+ const review = useEditor((s) => s.setReviewed);
+ const saving = useEditor((s) => s.pending === "save");
+ const save = useEditor((s) => s.save);
+ const back = useEditor((s) => s.back);
+ if (result?.status !== "analyzed") return null;
+ return (
+
+
+
AI 분석 · 검토 후 저장
+
{result.data.metadata.title}
+
{result.data.metadata.tags.join(" · ")}
+
+
+
+
+
+
+
+ );
+}
diff --git a/src/features/grammar-note-editor/ui/SourceField.tsx b/src/features/grammar-note-editor/ui/SourceField.tsx
new file mode 100644
index 00000000..8fb98842
--- /dev/null
+++ b/src/features/grammar-note-editor/ui/SourceField.tsx
@@ -0,0 +1,43 @@
+"use client";
+import { useId } from "react";
+import { Textarea } from "@/shared/components/atomics/textarea/Textarea";
+import { useEditor } from "./EditorProvider";
+export function SourceField({
+ field,
+ label,
+ placeholder,
+}: {
+ field: "sentence" | "learningNote";
+ label: string;
+ placeholder: string;
+}) {
+ const id = useId();
+ const value = useEditor((s) => s.source[field]);
+ const error = useEditor((s) => s.fieldErrors[field]);
+ const change = useEditor((s) => s.changeSource);
+ const saving = useEditor((s) => s.pending === "save");
+ return (
+
+ );
+}
diff --git a/src/features/grammar-note-editor/ui/SourceStep.tsx b/src/features/grammar-note-editor/ui/SourceStep.tsx
new file mode 100644
index 00000000..f0b9b36a
--- /dev/null
+++ b/src/features/grammar-note-editor/ui/SourceStep.tsx
@@ -0,0 +1,56 @@
+"use client";
+import { Button } from "@/shared/components/atomics/button/Button";
+import { useEditor } from "./EditorProvider";
+import { SourceField } from "./SourceField";
+export function SourceStep() {
+ const pending = useEditor((s) => s.pending);
+ const analyze = useEditor((s) => s.analyze);
+ const back = useEditor((s) => s.back);
+ const result = useEditor((s) => s.result);
+ return (
+
+ );
+}
diff --git a/src/views/grammar-editor/GrammarEditorView.tsx b/src/views/grammar-editor/GrammarEditorView.tsx
new file mode 100644
index 00000000..f5555d47
--- /dev/null
+++ b/src/views/grammar-editor/GrammarEditorView.tsx
@@ -0,0 +1,47 @@
+"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";
+
+/** initialNote가 바뀌면 key로 편집 생명주기를 새로 시작한다. 목록 검색 복귀 경로는 내부 경로만 허용한다. */
+export function GrammarEditorView({
+ initialNote,
+ backHref = "/grammar",
+}: {
+ 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/index.ts b/src/views/grammar-editor/index.ts
new file mode 100644
index 00000000..493d014e
--- /dev/null
+++ b/src/views/grammar-editor/index.ts
@@ -0,0 +1 @@
+export { GrammarEditorView } from "./GrammarEditorView";
From d283e46b220a5d438fefa8ecb581e88b5565118f Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Tue, 6 Oct 2026 02:24:49 +0900
Subject: [PATCH 2/4] test(grammar): exercise source analysis and preserved
back navigation (#153)
---
.../GrammarNoteEditor.stories.tsx | 19 +++++++++++++++++--
1 file changed, 17 insertions(+), 2 deletions(-)
diff --git a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
index e6ba4a55..5093a60a 100644
--- a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
+++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
@@ -9,9 +9,12 @@ const meta = {
title: "features/grammar-note-editor/GrammarNoteEditor",
component: GrammarNoteEditor,
args: {
- analyze: fn(async () => ({
+ analyze: fn(async (source) => ({
status: "analyzed",
- data: { metadata: note.metadata, analysis: note.analysis },
+ data: {
+ metadata: { ...note.metadata, sourceRevision: source.revision },
+ analysis: { ...note.analysis, sourceRevision: source.revision },
+ },
})),
save: fn(async () => ({ ok: true, note })),
AnalysisEditor: GrammarAnalysisEditor,
@@ -63,3 +66,15 @@ export const SaveFailure: Story = {
await expect(canvas.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence);
},
};
+
+export const AnalyzeThenReview: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.type(canvas.getByLabelText(/영어 문장/), note.source.sentence);
+ await userEvent.type(canvas.getByLabelText(/핵심 어법 설명/), note.source.learningNote);
+ await userEvent.click(canvas.getByRole("button", { name: "문장 분석하기" }));
+ await expect(await canvas.findByRole("heading", { name: note.metadata.title })).toBeVisible();
+ await userEvent.click(canvas.getByRole("button", { name: "이전 · 입력 수정" }));
+ await expect(canvas.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence);
+ },
+};
From 775367cb5e6319ee792115dd7c87a222027718b5 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Tue, 6 Oct 2026 02:31:12 +0900
Subject: [PATCH 3/4] fix(grammar): protect unapplied analysis and retry
confirmed note saves (#153)
---
.../GrammarNoteEditor.stories.tsx | 13 ++
.../GrammarNoteEditor.test.tsx | 66 +++++++++++
.../createEditorStore.test.ts | 10 +-
.../saveGrammarNote.test.ts | 111 ++++++++++++++++++
.../grammar-analysis-edit/models/interface.ts | 1 +
.../ui/AnalysisEditorProvider.tsx | 7 ++
.../grammar-note-editor/models/interface.ts | 4 +-
.../services/actions/saveGrammarNote.ts | 9 +-
.../services/createEditorStore.ts | 14 ++-
.../services/persistReviewedNote.ts | 35 ++++++
.../grammar-note-editor/ui/ReviewStep.tsx | 32 ++++-
11 files changed, 281 insertions(+), 21 deletions(-)
create mode 100644 src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
create mode 100644 src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
create mode 100644 src/features/grammar-note-editor/services/persistReviewedNote.ts
diff --git a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
index 5093a60a..6122136c 100644
--- a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
+++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
@@ -78,3 +78,16 @@ export const AnalyzeThenReview: Story = {
await expect(canvas.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence);
},
};
+export const UnappliedAnalysisBlocksSave: Story = {
+ args: { initialNote: note },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole("button", { name: "She" }));
+ await userEvent.click(canvas.getByRole("button", { name: "분석 수정" }));
+ await userEvent.type(canvas.getByLabelText("직독직해"), " 수정");
+ await expect(canvas.getByRole("checkbox")).toBeDisabled();
+ await expect(canvas.getByRole("button", { name: "검토 완료 · 노트 저장" })).toBeDisabled();
+ await userEvent.click(canvas.getByRole("button", { name: "풀이 적용" }));
+ await expect(canvas.getByRole("checkbox")).toBeEnabled();
+ },
+};
diff --git a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
new file mode 100644
index 00000000..0fc45d68
--- /dev/null
+++ b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
@@ -0,0 +1,66 @@
+import { randomUUID } from "node:crypto";
+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 { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit";
+import { createEditorNote } from "./fixtures";
+Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true });
+function setup() {
+ const note = createEditorNote();
+ const save = jest.fn().mockResolvedValue({ ok: true, note });
+ render(
+ ({
+ status: "analyzed",
+ data: { metadata: note.metadata, analysis: note.analysis },
+ })}
+ save={save}
+ AnalysisEditor={GrammarAnalysisEditor}
+ onSaved={() => {}}
+ onExit={() => {}}
+ />,
+ );
+ return { user: userEvent.setup(), save, note };
+}
+describe("분석 초안과 노트 저장 연결", () => {
+ it("미적용 풀이가 있으면 저장을 막고 적용 이후 검토를 다시 받는다", async () => {
+ const { user, save } = setup();
+ await user.click(screen.getByRole("button", { name: "She" }));
+ await user.click(screen.getByRole("button", { name: "분석 수정" }));
+ await user.clear(screen.getByLabelText("직독직해"));
+ await user.type(screen.getByLabelText("직독직해"), "그녀는 새 풀이");
+ expect(screen.getByRole("checkbox")).toBeDisabled();
+ expect(screen.getByRole("button", { name: "검토 완료 · 노트 저장" })).toBeDisabled();
+ await user.click(screen.getByRole("button", { name: "풀이 적용" }));
+ expect(screen.getByRole("checkbox")).toBeEnabled();
+ expect(screen.getByRole("checkbox")).not.toBeChecked();
+ await user.click(screen.getByRole("checkbox"));
+ await user.click(screen.getByRole("button", { name: "검토 완료 · 노트 저장" }));
+ expect(save).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: expect.objectContaining({
+ analysis: expect.objectContaining({
+ chunks: expect.arrayContaining([
+ expect.objectContaining({ id: "c1", literalMeaning: "그녀는 새 풀이" }),
+ ]),
+ }),
+ }),
+ }),
+ );
+ });
+ it("미적용 풀이에서 입력으로 돌아가기 전 확인하고 원문은 보존한다", async () => {
+ const { user, note } = setup();
+ await user.click(screen.getByRole("button", { name: "She" }));
+ await user.click(screen.getByRole("button", { name: "분석 수정" }));
+ await user.type(screen.getByLabelText("직독직해"), " 수정");
+ await user.click(screen.getByRole("button", { name: "이전 · 입력 수정" }));
+ expect(screen.getByRole("alertdialog")).toBeVisible();
+ await user.click(screen.getByRole("button", { name: "계속 수정" }));
+ expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정");
+ await user.click(screen.getByRole("button", { name: "이전 · 입력 수정" }));
+ await user.click(screen.getByRole("button", { name: "입력으로 돌아가기" }));
+ expect(screen.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence);
+ });
+});
diff --git a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
index 09c5b27d..4a284aa3 100644
--- a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
+++ b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
@@ -11,12 +11,10 @@ function dependencies() {
const note = createEditorNote();
return {
initialNote: note,
- analyze: jest
- .fn()
- .mockResolvedValue({
- status: "analyzed",
- data: { metadata: note.metadata, analysis: note.analysis },
- }),
+ analyze: jest.fn().mockResolvedValue({
+ status: "analyzed",
+ data: { metadata: note.metadata, analysis: note.analysis },
+ }),
save: jest.fn().mockResolvedValue({ ok: true, note }),
onSaved: jest.fn(),
};
diff --git a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
new file mode 100644
index 00000000..f694d168
--- /dev/null
+++ b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
@@ -0,0 +1,111 @@
+import { randomUUID } from "node:crypto";
+import { beforeEach, describe, expect, it, jest } from "@jest/globals";
+import { GrammarNotePersistenceError, GrammarNoteRepository } from "@/entities/grammar-note";
+import type { createSupabaseServerClient as CreateClient } from "@/shared/lib/supabase/server";
+import type { recordOperationEvent as RecordEvent } from "@/shared/lib/logging/pino";
+import type { SaveNoteCommand } from "@/features/grammar-note-editor";
+async function saveGrammarNote(command: SaveNoteCommand) {
+ const action = await import("@/features/grammar-note-editor/services/actions/saveGrammarNote");
+ return action.saveGrammarNote(command);
+}
+let createSupabaseServerClient: typeof CreateClient;
+let recordOperationEvent: typeof RecordEvent;
+import { createEditorNote } from "./fixtures";
+jest.mock("server-only", () => ({}));
+jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));
+jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() }));
+Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true });
+function command() {
+ const note = createEditorNote();
+ return {
+ requestId: randomUUID(),
+ content: {
+ source: note.source,
+ metadata: note.metadata,
+ analysis: note.analysis,
+ examples: [],
+ },
+ };
+}
+beforeEach(async () => {
+ ({ createSupabaseServerClient } = await import("@/shared/lib/supabase/server"));
+ ({ recordOperationEvent } = await import("@/shared/lib/logging/pino"));
+ jest.restoreAllMocks();
+ jest.clearAllMocks();
+ jest.mocked(createSupabaseServerClient).mockResolvedValue({
+ auth: { getUser: async () => ({ data: { user: { id: "owner" } }, error: null }) },
+ } as never);
+});
+describe("어법 저장 서버 경계", () => {
+ it("인증 실패시 저장소 쓰기를 호출하지 않는다", async () => {
+ jest.mocked(createSupabaseServerClient).mockResolvedValue({
+ auth: { getUser: async () => ({ data: { user: null }, error: null }) },
+ } as never);
+ const create = jest.spyOn(GrammarNoteRepository.prototype, "create");
+ expect(await saveGrammarNote(command())).toEqual({
+ ok: false,
+ message: "로그인 후 다시 저장해 주세요.",
+ });
+ expect(create).not.toHaveBeenCalled();
+ });
+ it("클라이언트가 미검토 분석을 보내면 저장하지 않는다", async () => {
+ const create = jest.spyOn(GrammarNoteRepository.prototype, "create");
+ const input = command();
+ input.content.analysis = { ...input.content.analysis, reviewStatus: "needs-review" };
+ expect((await saveGrammarNote(input)).ok).toBe(false);
+ expect(create).not.toHaveBeenCalled();
+ });
+ it("정상 저장은 동일 요청 ID와 검토 내용을 저장소에 전달한다", async () => {
+ const input = command();
+ const create = jest
+ .spyOn(GrammarNoteRepository.prototype, "create")
+ .mockResolvedValue(createEditorNote());
+ expect((await saveGrammarNote(input)).ok).toBe(true);
+ expect(create).toHaveBeenCalledWith(input);
+ });
+ it("수정 저장 응답을 잃은 재시도는 이미 저장한 동일 버전을 성공으로 돌려준다", async () => {
+ const note = createEditorNote();
+ const update = jest
+ .spyOn(GrammarNoteRepository.prototype, "update")
+ .mockRejectedValue(new GrammarNotePersistenceError("VERSION_CONFLICT"));
+ jest
+ .spyOn(GrammarNoteRepository.prototype, "findById")
+ .mockResolvedValue({ ...note, version: 2 });
+ const result = await saveGrammarNote({
+ ...command(),
+ existing: { id: note.id, expectedVersion: 1 },
+ });
+ expect(result.ok).toBe(true);
+ expect(update).toHaveBeenCalledTimes(1);
+ });
+ it("내용이 다른 버전 충돌을 성공으로 오인하지 않고 초안 재검토를 요청한다", async () => {
+ const note = createEditorNote();
+ jest
+ .spyOn(GrammarNoteRepository.prototype, "update")
+ .mockRejectedValue(new GrammarNotePersistenceError("VERSION_CONFLICT"));
+ jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue({
+ ...note,
+ version: 2,
+ metadata: { ...note.metadata, title: "다른 제목" },
+ });
+ const result = await saveGrammarNote({
+ ...command(),
+ existing: { id: note.id, expectedVersion: 1 },
+ });
+ expect(result).toEqual({
+ ok: false,
+ message: "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요.",
+ });
+ });
+ it("실패는 내부 이벤트로 기록하고 원문과 내부 오류를 UI에 노출하지 않는다", async () => {
+ jest
+ .spyOn(GrammarNoteRepository.prototype, "create")
+ .mockRejectedValue(new Error("secret database url"));
+ const result = await saveGrammarNote(command());
+ expect(JSON.stringify(result)).not.toContain("secret");
+ expect(recordOperationEvent).toHaveBeenCalledWith(expect.objectContaining({ phase: "failed" }));
+ expect(JSON.stringify(jest.mocked(recordOperationEvent).mock.calls)).not.toContain(
+ createEditorNote().source.sentence,
+ );
+ });
+});
diff --git a/src/features/grammar-analysis-edit/models/interface.ts b/src/features/grammar-analysis-edit/models/interface.ts
index 88c301e5..c982bf68 100644
--- a/src/features/grammar-analysis-edit/models/interface.ts
+++ b/src/features/grammar-analysis-edit/models/interface.ts
@@ -28,6 +28,7 @@ export interface AnalysisEditorState {
export interface AnalysisEditorProps {
initialAnalysis: SentenceAnalysis;
onChange: (analysis: SentenceAnalysis) => void;
+ onDirtyChange?: (dirty: boolean) => void;
}
export interface AnalysisEditorProviderProps extends AnalysisEditorProps {
diff --git a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx
index 8b8f4490..8e2b19ff 100644
--- a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx
+++ b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx
@@ -16,6 +16,7 @@ const Context = createContext | null>(null);
export function AnalysisEditorProvider({
initialAnalysis,
onChange,
+ onDirtyChange,
children,
}: AnalysisEditorProviderProps) {
// 부모가 콜백을 변경해도 편집 상태를 초기화하지 않고 최신 수신자에게 알린다.
@@ -29,6 +30,12 @@ export function AnalysisEditorProvider({
onChange: (analysis) => onChangeRef.current(analysis),
}),
);
+ 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 fd9c6d1c..86244e69 100644
--- a/src/features/grammar-note-editor/models/interface.ts
+++ b/src/features/grammar-note-editor/models/interface.ts
@@ -25,6 +25,7 @@ export interface GrammarNoteEditorProps {
AnalysisEditor: ComponentType<{
initialAnalysis: SentenceAnalysis;
onChange: (analysis: SentenceAnalysis) => void;
+ onDirtyChange?: (dirty: boolean) => void;
}>;
onSaved: (note: GrammarNote) => void;
onExit: () => void;
@@ -37,10 +38,11 @@ export interface EditorState {
error: string;
fieldErrors: Partial>;
reviewed: boolean;
+ analysisDirty: boolean;
+ setAnalysisDirty: (dirty: boolean) => void;
dirty: boolean;
changeSource: (field: "sentence" | "learningNote", value: string) => void;
changeAnalysis: (analysis: SentenceAnalysis) => void;
- markDirty: () => void;
setReviewed: (reviewed: boolean) => void;
back: () => void;
analyze: () => Promise;
diff --git a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
index 98544947..10cbf14e 100644
--- a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
+++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
@@ -3,6 +3,7 @@ import { GrammarNotePersistenceError, GrammarNoteRepository } from "@/entities/g
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 {
@@ -15,13 +16,7 @@ export async function saveGrammarNote(command: SaveNoteCommand): Promise
+ set({ analysisDirty, ...(analysisDirty ? { dirty: true, reviewed: false } : {}) }),
dirty: false,
changeSource: (field, value) => {
if (get().pending === "save") return;
@@ -43,12 +46,11 @@ export function createEditorStore(
}
: {},
),
- markDirty: () => set({ dirty: true, reviewed: false }),
setReviewed: (reviewed) => set({ reviewed }),
back: () => {
if (get().pending === "save") return;
request++;
- set({ stage: "input", pending: null, error: "" });
+ set({ stage: "input", pending: null, error: "", analysisDirty: false });
},
cancel: () => {
request++;
@@ -99,7 +101,13 @@ export function createEditorStore(
},
save: async () => {
const state = get();
- if (state.pending || !state.reviewed || state.result?.status !== "analyzed") return;
+ if (
+ state.pending ||
+ state.analysisDirty ||
+ !state.reviewed ||
+ state.result?.status !== "analyzed"
+ )
+ return;
const content = grammarNoteContentSchema.safeParse({
source: state.source,
...state.result.data,
diff --git a/src/features/grammar-note-editor/services/persistReviewedNote.ts b/src/features/grammar-note-editor/services/persistReviewedNote.ts
new file mode 100644
index 00000000..ef7ac019
--- /dev/null
+++ b/src/features/grammar-note-editor/services/persistReviewedNote.ts
@@ -0,0 +1,35 @@
+import {
+ GrammarNotePersistenceError,
+ grammarNoteContentSchema,
+ type GrammarNoteRepositoryPort,
+} from "@/entities/grammar-note";
+import type { SaveNoteCommand } from "../models/interface";
+/** 생성의 중복 방지는 저장소의 요청 UUID, 수정의 재시도는 확정된 버전과 동일 내용으로 판정한다. */
+export async function persistReviewedNote(
+ command: SaveNoteCommand,
+ repository: GrammarNoteRepositoryPort,
+) {
+ const parsed = grammarNoteContentSchema.safeParse(command.content);
+ if (!parsed.success || parsed.data.analysis.reviewStatus !== "reviewed")
+ throw new GrammarNotePersistenceError("INVALID_INPUT");
+ if (!command.existing)
+ return repository.create({ requestId: command.requestId, content: parsed.data });
+ const { id, expectedVersion } = command.existing;
+ try {
+ return await repository.update({ id, expectedVersion, content: parsed.data });
+ } catch (error) {
+ if (!(error instanceof GrammarNotePersistenceError) || error.code !== "VERSION_CONFLICT")
+ throw error;
+ const current = await repository.findById(id);
+ if (current?.version === expectedVersion + 1) {
+ const currentContent = grammarNoteContentSchema.parse({
+ source: current.source,
+ metadata: current.metadata,
+ analysis: current.analysis,
+ examples: current.examples,
+ });
+ if (JSON.stringify(currentContent) === JSON.stringify(parsed.data)) return current;
+ }
+ throw error;
+ }
+}
diff --git a/src/features/grammar-note-editor/ui/ReviewStep.tsx b/src/features/grammar-note-editor/ui/ReviewStep.tsx
index 2275f079..f405ab92 100644
--- a/src/features/grammar-note-editor/ui/ReviewStep.tsx
+++ b/src/features/grammar-note-editor/ui/ReviewStep.tsx
@@ -1,11 +1,15 @@
"use client";
+import { useState } from "react";
+import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog";
import { Button } from "@/shared/components/atomics/button/Button";
import type { GrammarNoteEditorProps } from "../models/interface";
import { useEditor } from "./EditorProvider";
export function ReviewStep({ AnalysisEditor }: Pick) {
const result = useEditor((s) => s.result);
const change = useEditor((s) => s.changeAnalysis);
- const markDirty = useEditor((s) => s.markDirty);
+ const analysisDirty = useEditor((s) => s.analysisDirty);
+ const setAnalysisDirty = useEditor((s) => s.setAnalysisDirty);
+ const [confirmBack, setConfirmBack] = useState(false);
const reviewed = useEditor((s) => s.reviewed);
const review = useEditor((s) => s.setReviewed);
const saving = useEditor((s) => s.pending === "save");
@@ -20,31 +24,51 @@ export function ReviewStep({ AnalysisEditor }: Pick{result.data.metadata.tags.join(" · ")}