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..1e5f862b --- /dev/null +++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx @@ -0,0 +1,93 @@ +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 (source) => ({ + status: "analyzed", + data: { + metadata: { ...note.metadata, sourceRevision: source.revision }, + analysis: { ...note.analysis, sourceRevision: source.revision }, + }, + })), + 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, + code: "PERSISTENCE_FAILED", + })), + }, + 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); + }, +}; + +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); + }, +}; +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-analysis-edit/GrammarAnalysisEditor.test.tsx b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx index 721257e8..2b20386e 100644 --- a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx +++ b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx @@ -118,16 +118,31 @@ it("preserves drafts on parent rerender and notifies the current callback", asyn const user = userEvent.setup(); const original = jest.fn(); const current = jest.fn(); + const originalDirty = jest.fn(); + const currentDirty = jest.fn(); const { rerender } = render( - , + , ); await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.type(screen.getByLabelText("직독직해"), " 수정"); - rerender(); + expect(originalDirty.mock.calls).toEqual([[true]]); + rerender( + , + ); expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); await user.click(screen.getByRole("button", { name: "풀이 적용" })); expect(original).not.toHaveBeenCalled(); expect(current).toHaveBeenCalledTimes(1); + expect(originalDirty.mock.calls).toEqual([[true]]); + expect(currentDirty.mock.calls).toEqual([[false]]); }); it("starts a fresh editor when the document key changes", async () => { diff --git a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts index 658ee212..7e68b2cb 100644 --- a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts +++ b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts @@ -190,3 +190,38 @@ it("updates only explanation fields even when the supplied object contains chunk }); expect(result.analysis.sourceText).toBe(source.sourceText); }); + +it("notifies dirty changes within editing events and keeps failed/discard-cancelled drafts dirty", () => { + const onDirtyChange = jest.fn(); + const store = createAnalysisEditorStore({ + initialAnalysis: createGrammarAnalysis(), + onChange: jest.fn(), + onDirtyChange, + }); + store.getState().markDirty(); + expect(onDirtyChange).not.toHaveBeenCalled(); + store.getState().startEditing(); + store.getState().markDirty(); + store.getState().markDirty(); + expect(onDirtyChange.mock.calls).toEqual([[true]]); + const failed = store.getState().edit((service) => + service.saveSyntax({ + id: "s", + ranges: [{ start: 0, end: 1 }], + parentId: "s", + role: "other", + label: "invalid", + explanation: "", + }), + ); + expect(failed.ok).toBe(false); + expect(store.getState().dirty).toBe(true); + store.getState().finishEditing(); + store.getState().resolveSelection(false); + expect(store.getState().dirty).toBe(true); + expect(onDirtyChange.mock.calls).toEqual([[true]]); + store.getState().finishEditing(); + store.getState().resolveSelection(true); + expect(store.getState().dirty).toBe(false); + expect(onDirtyChange.mock.calls).toEqual([[true], [false]]); +}); diff --git a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx new file mode 100644 index 00000000..eba9dd01 --- /dev/null +++ b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx @@ -0,0 +1,113 @@ +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 type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note"; +import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; +import { createEditorNote } from "./fixtures"; +Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); +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); + }); +}); + +it.each<[GrammarNotePersistenceErrorCode, string]>([ + ["UNAUTHORIZED", "로그인 후 다시 저장해 주세요."], + ["VERSION_CONFLICT", "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요."], + ["PERSISTENCE_FAILED", "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요."], +])("%s 저장 오류의 안내는 UI에서 선택하고 재시도할 내용을 유지한다", async (code, message) => { + const { user, save } = setup(); + save.mockResolvedValue({ ok: false, code }); + await user.click(screen.getByRole("button", { name: "분석 수정" })); + await user.type(screen.getByLabelText("직독직해"), " 수정"); + await user.click(screen.getByRole("button", { name: "풀이 적용" })); + await user.click(screen.getByRole("checkbox")); + await user.click(screen.getByRole("button", { name: "검토 완료 · 노트 저장" })); + expect(await screen.findByRole("alert")).toHaveTextContent(message); + expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); + expect(screen.getByRole("button", { name: "검토 완료 · 노트 저장" })).toBeEnabled(); +}); + +it("부모가 다시 렌더링되어도 입력을 유지하고 새 분석 콜백을 호출한다", async () => { + const note = createEditorNote(); + const original = jest.fn(); + const current = jest + .fn() + .mockResolvedValue({ status: "error", message: "분석 서비스 오류" }); + const props = { + save: jest.fn(), + AnalysisEditor: GrammarAnalysisEditor, + onSaved: jest.fn(), + onExit: jest.fn(), + }; + const { rerender } = render(); + const user = userEvent.setup(); + await user.type(screen.getByLabelText(/영어 문장/), note.source.sentence); + await user.type(screen.getByLabelText(/핵심 어법 설명/), note.source.learningNote); + rerender(); + expect(screen.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence); + await user.click(screen.getByRole("button", { name: "문장 분석하기" })); + expect(original).not.toHaveBeenCalled(); + expect(current).toHaveBeenCalledWith( + expect.objectContaining({ + sentence: note.source.sentence, + learningNote: note.source.learningNote, + }), + ); + expect(await screen.findByRole("alert")).toHaveTextContent("분석 서비스 오류"); +}); diff --git a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts new file mode 100644 index 00000000..fc55e7b5 --- /dev/null +++ b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts @@ -0,0 +1,138 @@ +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).toEqual({ code: "PERSISTENCE_FAILED" }); + await store.getState().save(); + expect(deps.save.mock.calls[0][0].requestId).toBe(deps.save.mock.calls[1][0].requestId); + expect(deps.onSaved).toHaveBeenCalledTimes(1); + }); + 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).toEqual({ code: "ANALYSIS_FAILED" }); + }); + it("편집 저장은 읽은 버전을 전달하고 충돌시 초안을 유지한다", async () => { + const deps = dependencies(); + deps.save.mockResolvedValue({ ok: false, code: "VERSION_CONFLICT" }); + 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).toEqual({ code: "VERSION_CONFLICT" }); + }); +}); 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/_tests/features/grammar-note-editor/saveGrammarNote.test.ts b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts new file mode 100644 index 00000000..7b002b4a --- /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, + code: "UNAUTHORIZED", + }); + 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, + code: "VERSION_CONFLICT", + }); + }); + 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/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-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/models/store.ts b/src/features/grammar-analysis-edit/models/store.ts index 61d6126a..ad34a4ea 100644 --- a/src/features/grammar-analysis-edit/models/store.ts +++ b/src/features/grammar-analysis-edit/models/store.ts @@ -4,7 +4,11 @@ import type { AnalysisEditorProps, AnalysisEditorState } from "./interface"; import { applyAnalysisEdits } from "../services/applyAnalysisEdits"; /** 에디터 수명에 맞춰 상태를 생성한다. onChange는 성공한 편집을 상위 문서에 전달한다. */ -export function createAnalysisEditorStore({ initialAnalysis, onChange }: AnalysisEditorProps) { +export function createAnalysisEditorStore({ + initialAnalysis, + onChange, + onDirtyChange, +}: AnalysisEditorProps) { return createStore((set, get) => ({ analysis: sentenceAnalysisSchema.parse(initialAnalysis), selectedId: null, @@ -39,20 +43,24 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi return result; }, markDirty: () => { - if (get().editing) set({ dirty: true }); + if (!get().editing || get().dirty) return; + set({ dirty: true }); + onDirtyChange?.(true); }, resolveSelection: (discard) => { const pending = get().pendingSelection; - if (discard && pending) + if (discard && pending) { set({ selectedId: pending.id, editing: pending.editing, dirty: false, + pendingSelection: null, readingId: get().analysis.chunks.some((chunk) => chunk.id === pending.id) ? pending.id : get().readingId, }); - set({ pendingSelection: null }); + onDirtyChange?.(false); + } else set({ pendingSelection: null }); }, select: (selectedId) => { if (get().dirty) set({ pendingSelection: { id: selectedId, editing: get().editing } }); @@ -72,13 +80,14 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi ...result.analysis.syntax, ...result.analysis.constructions, ].map((item) => item.id); - const selectedId = get().selectedId; + const { selectedId, dirty } = get(); set({ dirty: false, analysis: result.analysis, selectedId: selectedId && ids.includes(selectedId) ? selectedId : null, }); onChange(result.analysis); + if (dirty) onDirtyChange?.(false); } return result; }, diff --git a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx index 8b8f4490..fab08ee1 100644 --- a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx +++ b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx @@ -1,6 +1,6 @@ "use client"; -import { createContext, useContext, useEffect, useRef, useState } from "react"; +import { createContext, useContext, useLayoutEffect, useRef, useState } from "react"; import { useStore } from "zustand"; import type { StoreApi } from "zustand"; import type { AnalysisEditorProviderProps, AnalysisEditorState } from "../models/interface"; @@ -16,17 +16,19 @@ const Context = createContext | null>(null); export function AnalysisEditorProvider({ initialAnalysis, onChange, + onDirtyChange, children, }: AnalysisEditorProviderProps) { // 부모가 콜백을 변경해도 편집 상태를 초기화하지 않고 최신 수신자에게 알린다. - const onChangeRef = useRef(onChange); - useEffect(() => { - onChangeRef.current = onChange; - }, [onChange]); + const callbacks = useRef({ onChange, onDirtyChange }); + useLayoutEffect(() => { + callbacks.current = { onChange, onDirtyChange }; + }, [onChange, onDirtyChange]); const [store] = useState(() => createAnalysisEditorStore({ initialAnalysis, - onChange: (analysis) => onChangeRef.current(analysis), + onChange: (analysis) => callbacks.current.onChange(analysis), + onDirtyChange: (dirty) => callbacks.current.onDirtyChange?.(dirty), }), ); return {children}; 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..8162b773 --- /dev/null +++ b/src/features/grammar-note-editor/models/interface.ts @@ -0,0 +1,58 @@ +import type { ComponentType } from "react"; +import type { + GrammarMetadata, + GrammarNote, + GrammarNoteContent, + GrammarNotePersistenceErrorCode, + 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; code: GrammarNotePersistenceErrorCode }; +export interface GrammarNoteEditorProps { + initialNote?: GrammarNote; + analyze: (source: GrammarSource) => Promise; + save: (command: SaveNoteCommand) => Promise; + AnalysisEditor: ComponentType<{ + initialAnalysis: SentenceAnalysis; + onChange: (analysis: SentenceAnalysis) => void; + onDirtyChange?: (dirty: boolean) => void; + }>; + 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: EditorError | null; + fieldErrors: Partial>; + reviewed: boolean; + analysisDirty: boolean; + setAnalysisDirty: (dirty: boolean) => void; + dirty: boolean; + changeSource: (field: "sentence" | "learningNote", value: string) => void; + changeAnalysis: (analysis: SentenceAnalysis) => 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..bc075299 --- /dev/null +++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts @@ -0,0 +1,27 @@ +"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, code }; + } +} 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..7e6964e9 --- /dev/null +++ b/src/features/grammar-note-editor/services/createEditorStore.ts @@ -0,0 +1,152 @@ +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 initialNote = dependencies.initialNote; + // 입력 변경·화면 이탈 후에도 서버 분석은 끝날 수 있어, 현재 세대의 응답만 적용한다. + let generation = 0; + let saveIdentity: { content: string; id: string } | null = null; + return createStore((set, get) => ({ + source: initialNote?.source ?? { sentence: "", learningNote: "", revision: 0 }, + result: initialNote + ? { + status: "analyzed", + data: { metadata: initialNote.metadata, analysis: initialNote.analysis }, + } + : null, + stage: initialNote ? "review" : "input", + pending: null, + error: null, + 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 }, + result: null, + stage: "input", + pending: null, + reviewed: false, + dirty: true, + 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: 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, + stage: result.status === "analyzed" ? "review" : "input", + reviewed: false, + error: result.status === "error" ? { message: result.message } : null, + }); + } catch { + if (currentGeneration === generation) + set({ + pending: null, + error: { code: "ANALYSIS_FAILED" }, + }); + } + }, + save: async () => { + const state = get(); + if ( + state.pending || + state.analysisDirty || + !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: 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, + content: content.data, + ...(initialNote + ? { 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 { + set({ pending: null, error: { code: "PERSISTENCE_FAILED" } }); + } + }, + })); +} 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..0768513c --- /dev/null +++ b/src/features/grammar-note-editor/services/persistReviewedNote.ts @@ -0,0 +1,36 @@ +import { + GrammarNotePersistenceError, + grammarNoteContentSchema, + type GrammarNoteRepositoryPort, +} from "@/entities/grammar-note"; +import type { SaveNoteCommand } from "../models/interface"; +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/EditorError.tsx b/src/features/grammar-note-editor/ui/EditorError.tsx new file mode 100644 index 00000000..c3530336 --- /dev/null +++ b/src/features/grammar-note-editor/ui/EditorError.tsx @@ -0,0 +1,31 @@ +"use client"; +import { useEditor } from "./EditorProvider"; +export function EditorError() { + const error = useEditor((s) => s.error); + if (!error) return null; + let message: string; + if ("message" in error) message = error.message; + else { + switch (error.code) { + case "VERSION_CONFLICT": + message = "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요."; + break; + case "UNAUTHORIZED": + message = "로그인 후 다시 저장해 주세요."; + break; + case "ANALYSIS_FAILED": + message = "분석을 완료하지 못했습니다. 입력을 유지했으니 다시 시도해 주세요."; + break; + case "INVALID_ANALYSIS": + message = "분석과 입력을 다시 확인해 주세요."; + break; + default: + message = "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요."; + } + } + return ( +

+ {message} +

+ ); +} diff --git a/src/features/grammar-note-editor/ui/EditorProvider.tsx b/src/features/grammar-note-editor/ui/EditorProvider.tsx new file mode 100644 index 00000000..71b58a21 --- /dev/null +++ b/src/features/grammar-note-editor/ui/EditorProvider.tsx @@ -0,0 +1,53 @@ +"use client"; +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, + initialNote, + analyze, + save, + onSaved, +}: Omit & { children: ReactNode }) { + const latest = useRef({ analyze, save, onSaved }); + useLayoutEffect(() => { + latest.current = { analyze, save, onSaved }; + }, [analyze, save, onSaved]); + // initialNote는 초기값이다. 문서 ID·버전이 바뀌면 호출부에서 key로 새 세션을 연다. + 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 new file mode 100644 index 00000000..9a78b3cc --- /dev/null +++ b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx @@ -0,0 +1,54 @@ +"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); + return ( +
+ + {stage === "input" ? : } + +
+ ); +} +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..f405ab92 --- /dev/null +++ b/src/features/grammar-note-editor/ui/ReviewStep.tsx @@ -0,0 +1,74 @@ +"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 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"); + 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(" · ")}

+
+
+
+ +
+ +
+ {analysisDirty && ( +

+ 저장하기 전에 풀이 수정을 적용하거나 취소해 주세요. +

+ )} +
+ + +
+ +
+ ); +} 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 ( +
+ +