((set, get) => ({
source: initialNote?.source ?? { sentence: "", learningNote: "", revision: 0 },
result: initialNote
@@ -23,13 +24,18 @@ export function createEditorStore(
fieldErrors: {},
reviewed: false,
analysisDirty: 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 },
@@ -42,6 +48,7 @@ export function createEditorStore(
fieldErrors: {},
}));
},
+
changeAnalysis: (analysis) =>
set((state) =>
state.result?.status === "analyzed"
@@ -53,44 +60,61 @@ export function createEditorStore(
}
: {},
),
+
setReviewed: (reviewed) => set({ reviewed }),
+
back: () => {
if (get().pending === "save") return;
+
generation++;
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: 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,
@@ -106,8 +130,10 @@ export function createEditorStore(
});
}
},
+
save: async () => {
const state = get();
+
if (
state.pending ||
state.analysisDirty ||
@@ -115,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: { 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: null });
+
try {
const result = await dependencies.save({
requestId: saveIdentity.id,
@@ -138,10 +171,13 @@ export function createEditorStore(
? { existing: { id: initialNote.id, expectedVersion: initialNote.version } }
: {}),
});
+
if (!result.ok) {
set({ pending: null, error: { code: result.code } });
+
return;
}
+
set({ pending: null, dirty: false });
dependencies.onSaved(result.note);
} catch {
diff --git a/src/features/grammar-note-editor/ui/EditorError.tsx b/src/features/grammar-note-editor/ui/EditorError.tsx
index c3530336..3389f0af 100644
--- a/src/features/grammar-note-editor/ui/EditorError.tsx
+++ b/src/features/grammar-note-editor/ui/EditorError.tsx
@@ -1,9 +1,14 @@
"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) {
@@ -23,6 +28,7 @@ export function EditorError() {
message = "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요.";
}
}
+
return (
{message}
diff --git a/src/features/grammar-note-editor/ui/EditorProvider.tsx b/src/features/grammar-note-editor/ui/EditorProvider.tsx
index 71b58a21..d521d086 100644
--- a/src/features/grammar-note-editor/ui/EditorProvider.tsx
+++ b/src/features/grammar-note-editor/ui/EditorProvider.tsx
@@ -1,4 +1,5 @@
"use client";
+
import {
createContext,
useContext,
@@ -12,7 +13,9 @@ 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,
initialNote,
@@ -21,6 +24,7 @@ export function EditorProvider({
onSaved,
}: Omit & { children: ReactNode }) {
const latest = useRef({ analyze, save, onSaved });
+
useLayoutEffect(() => {
latest.current = { analyze, save, onSaved };
}, [analyze, save, onSaved]);
@@ -28,26 +32,38 @@ export function EditorProvider({
const [store] = useState(() =>
createEditorStore({
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 9a78b3cc..2ac375b1 100644
--- a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
+++ b/src/features/grammar-note-editor/ui/GrammarNoteEditor.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";
@@ -7,11 +8,13 @@ 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);
+
return (
@@ -20,10 +23,12 @@ function EditorBody({
);
}
+
function EditorExit({ onExit }: { onExit: () => void }) {
const [confirm, setConfirm] = useState(false);
const dirty = useEditor((s) => s.dirty);
const saving = useEditor((s) => s.pending === "save");
+
return (
<>