From dc81c4bfd07f86345ecbe39ddbf17ed39c35e4a1 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Tue, 6 Oct 2026 02:18:55 +0900
Subject: [PATCH 1/8] feat(grammar): add searchable paginated note library
(#155)
---
.../GrammarNoteList.stories.tsx | 49 ++++++++++++
.../GrammarLibraryPage.test.tsx | 38 +++++++++
.../grammar-library/libraryQuery.test.ts | 20 +++++
src/app/(protected)/grammar/(list)/error.tsx | 20 +++++
.../(protected)/grammar/(list)/loading.tsx | 1 +
src/app/(protected)/grammar/(list)/page.tsx | 38 +++++++++
src/views/grammar-library/index.ts | 4 +
src/views/grammar-library/models/interface.ts | 9 +++
.../grammar-library/services/libraryQuery.ts | 18 +++++
.../ui/GrammarLibrarySkeleton.tsx | 17 ++++
.../grammar-library/ui/GrammarLibraryView.tsx | 44 +++++++++++
.../grammar-library/ui/GrammarNoteList.tsx | 78 +++++++++++++++++++
12 files changed, 336 insertions(+)
create mode 100644 src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx
create mode 100644 src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx
create mode 100644 src/_tests/views/grammar-library/libraryQuery.test.ts
create mode 100644 src/app/(protected)/grammar/(list)/error.tsx
create mode 100644 src/app/(protected)/grammar/(list)/loading.tsx
create mode 100644 src/app/(protected)/grammar/(list)/page.tsx
create mode 100644 src/views/grammar-library/index.ts
create mode 100644 src/views/grammar-library/models/interface.ts
create mode 100644 src/views/grammar-library/services/libraryQuery.ts
create mode 100644 src/views/grammar-library/ui/GrammarLibrarySkeleton.tsx
create mode 100644 src/views/grammar-library/ui/GrammarLibraryView.tsx
create mode 100644 src/views/grammar-library/ui/GrammarNoteList.tsx
diff --git a/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx b/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx
new file mode 100644
index 00000000..f87f370f
--- /dev/null
+++ b/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx
@@ -0,0 +1,49 @@
+import type { Meta, StoryObj } from "@storybook/nextjs-vite";
+import { expect, within } from "storybook/test";
+import { GrammarNoteList } from "@/views/grammar-library";
+const meta = {
+ title: "Views/Grammar/Note list",
+ component: GrammarNoteList,
+ args: { query: "", data: { items: [], total: 0, page: 1, pageSize: 20 } },
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+export const Empty: Story = {
+ play: async ({ canvasElement }) => {
+ await expect(within(canvasElement).getByText("첫 어법 노트를 만들어보세요")).toBeVisible();
+ },
+};
+export const SearchEmpty: Story = { args: { query: "unknown" } };
+export const Notes: Story = {
+ args: {
+ query: "not",
+ data: {
+ page: 2,
+ pageSize: 20,
+ total: 42,
+ items: [
+ {
+ id: "00000000-0000-4000-8000-000000000001",
+ ownerId: "00000000-0000-4000-8000-000000000002",
+ title: "not A but B",
+ sentence: "She is not a teacher but a doctor.",
+ tags: ["대조", "보어"],
+ version: 1,
+ createdAt: "2026-10-01T00:00:00Z",
+ updatedAt: "2026-10-01T00:00:00Z",
+ },
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getByRole("link", { name: /not A but B/ })).toHaveAttribute(
+ "href",
+ expect.stringContaining("returnTo=%2Fgrammar%3Fq%3Dnot%26page%3D2"),
+ );
+ await expect(canvas.getByRole("link", { name: "2페이지" })).toHaveAttribute(
+ "aria-current",
+ "page",
+ );
+ },
+};
diff --git a/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx b/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx
new file mode 100644
index 00000000..838a685f
--- /dev/null
+++ b/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx
@@ -0,0 +1,38 @@
+/** @jest-environment node */
+import { describe, it, expect, jest, beforeEach } from "@jest/globals";
+
+import type { GrammarNoteRepository } from "@/entities/grammar-note";
+
+jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));
+jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() }));
+jest.mock("next/navigation", () => ({
+ redirect: (url: string) => {
+ throw new Error(`redirect:${url}`);
+ },
+}));
+describe("grammar list route", () => {
+ const findMany = jest.fn["findMany"]>();
+ beforeEach(async () => {
+ const { GrammarNoteRepository } = await import("@/entities/grammar-note");
+ const { createSupabaseServerClient } = await import("@/shared/lib/supabase/server");
+ jest.spyOn(GrammarNoteRepository.prototype, "findMany").mockImplementation(findMany);
+ jest.mocked(createSupabaseServerClient).mockResolvedValue({
+ auth: { getUser: async () => ({ data: { user: { id: "owner" } }, error: null }) },
+ } as unknown as Awaited>);
+ findMany.mockResolvedValue({ items: [], total: 41, page: 999, pageSize: 20 });
+ });
+ it("redirects an out-of-range page to last valid page with search preserved", async () => {
+ const { default: GrammarLibraryPage } = await import("@/app/(protected)/grammar/(list)/page");
+ await expect(
+ GrammarLibraryPage({ searchParams: Promise.resolve({ page: "999", q: "verb" }) }),
+ ).rejects.toThrow("redirect:/grammar?q=verb&page=3");
+ expect(findMany).toHaveBeenCalledWith({ page: 999, pageSize: 20, query: "verb" });
+ });
+ it("normalizes an invalid URL before rendering valid links", async () => {
+ findMany.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 20 });
+ const { default: GrammarLibraryPage } = await import("@/app/(protected)/grammar/(list)/page");
+ await expect(
+ GrammarLibraryPage({ searchParams: Promise.resolve({ page: "bad" }) }),
+ ).rejects.toThrow("redirect:/grammar");
+ });
+});
diff --git a/src/_tests/views/grammar-library/libraryQuery.test.ts b/src/_tests/views/grammar-library/libraryQuery.test.ts
new file mode 100644
index 00000000..b998bac7
--- /dev/null
+++ b/src/_tests/views/grammar-library/libraryQuery.test.ts
@@ -0,0 +1,20 @@
+import { describe, it, expect } from "@jest/globals";
+import {
+ parseGrammarLibraryQuery,
+ grammarLibraryHref,
+} from "@/views/grammar-library/services/libraryQuery";
+describe("grammar library URL", () => {
+ it.each(["0", "-1", "1.5", "Infinity", "2147483648", "bad"])(
+ "normalizes invalid page %s",
+ (page) => expect(parseGrammarLibraryQuery({ page }).page).toBe(1),
+ );
+ it("preserves search and page in a safely encoded return URL", () =>
+ expect(grammarLibraryHref({ page: 3, query: "not A & B" })).toBe(
+ "/grammar?q=not+A+%26+B&page=3",
+ ));
+ it("bounds search and accepts a single value from repeated query", () =>
+ expect(parseGrammarLibraryQuery({ page: ["2", "3"], q: [" verb ", "other"] })).toEqual({
+ page: 2,
+ query: "verb",
+ }));
+});
diff --git a/src/app/(protected)/grammar/(list)/error.tsx b/src/app/(protected)/grammar/(list)/error.tsx
new file mode 100644
index 00000000..0df07d43
--- /dev/null
+++ b/src/app/(protected)/grammar/(list)/error.tsx
@@ -0,0 +1,20 @@
+"use client";
+import { BackNavigation } from "@/shared/components/ui/back-navigation/BackNavigation";
+export default function GrammarLibraryError({ reset }: { reset: () => void }) {
+ return (
+
+
+ 어법 노트를 불러오지 못했습니다.
+
+ 잠시 후 다시 시도해주세요.
+
+
+
+ );
+}
diff --git a/src/app/(protected)/grammar/(list)/loading.tsx b/src/app/(protected)/grammar/(list)/loading.tsx
new file mode 100644
index 00000000..bb04cf63
--- /dev/null
+++ b/src/app/(protected)/grammar/(list)/loading.tsx
@@ -0,0 +1 @@
+export { GrammarLibrarySkeleton as default } from "@/views/grammar-library";
diff --git a/src/app/(protected)/grammar/(list)/page.tsx b/src/app/(protected)/grammar/(list)/page.tsx
new file mode 100644
index 00000000..a2ef25dc
--- /dev/null
+++ b/src/app/(protected)/grammar/(list)/page.tsx
@@ -0,0 +1,38 @@
+import { redirect } from "next/navigation";
+import { 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 {
+ GrammarLibraryView,
+ parseGrammarLibraryQuery,
+ grammarLibraryHref,
+} from "@/views/grammar-library";
+interface Props {
+ searchParams: Promise<{ page?: string | string[]; q?: string | string[] }>;
+}
+export default async function GrammarLibraryPage({ searchParams }: Props) {
+ const raw = await searchParams;
+ const query = parseGrammarLibraryQuery(raw);
+ const supabase = await createSupabaseServerClient();
+ const {
+ data: { user },
+ error,
+ } = await supabase.auth.getUser();
+ if (error || !user) redirect("/login");
+ const data = await observeOperation({
+ operation: "grammar.list",
+ resourceId: "grammar-library",
+ recordEvent: recordOperationEvent,
+ execute: () => new GrammarNoteRepository(supabase).findMany({ ...query, pageSize: 20 }),
+ });
+ const normalizedPage = Math.min(query.page, Math.max(1, Math.ceil(data.total / data.pageSize)));
+ // 범위를 벗어난 URL은 마지막 유효 페이지로 교정한다. 이후 링크와 상세 복귀도 같은 주소를 쓴다.
+ if (
+ normalizedPage !== query.page ||
+ (raw.page !== undefined && raw.page !== String(query.page)) ||
+ (raw.q !== undefined && raw.q !== query.query)
+ )
+ redirect(grammarLibraryHref({ ...query, page: normalizedPage }));
+ return ;
+}
diff --git a/src/views/grammar-library/index.ts b/src/views/grammar-library/index.ts
new file mode 100644
index 00000000..2c0f0b59
--- /dev/null
+++ b/src/views/grammar-library/index.ts
@@ -0,0 +1,4 @@
+export { GrammarLibraryView } from "./ui/GrammarLibraryView";
+export { GrammarNoteList } from "./ui/GrammarNoteList";
+export { GrammarLibrarySkeleton } from "./ui/GrammarLibrarySkeleton";
+export { parseGrammarLibraryQuery, grammarLibraryHref } from "./services/libraryQuery";
diff --git a/src/views/grammar-library/models/interface.ts b/src/views/grammar-library/models/interface.ts
new file mode 100644
index 00000000..e34c31a4
--- /dev/null
+++ b/src/views/grammar-library/models/interface.ts
@@ -0,0 +1,9 @@
+import type { GrammarNotePage } from "@/entities/grammar-note";
+export interface GrammarLibraryQuery {
+ readonly page: number;
+ readonly query: string;
+}
+export interface GrammarNoteListProps {
+ readonly data: GrammarNotePage;
+ readonly query: string;
+}
diff --git a/src/views/grammar-library/services/libraryQuery.ts b/src/views/grammar-library/services/libraryQuery.ts
new file mode 100644
index 00000000..eced3304
--- /dev/null
+++ b/src/views/grammar-library/services/libraryQuery.ts
@@ -0,0 +1,18 @@
+import type { GrammarLibraryQuery } from "../models/interface";
+export function parseGrammarLibraryQuery(params: {
+ page?: string | string[];
+ q?: string | string[];
+}): GrammarLibraryQuery {
+ const raw = Array.isArray(params.page) ? params.page[0] : params.page;
+ const page = Number(raw);
+ return {
+ page: Number.isSafeInteger(page) && page > 0 && page <= 2147483647 ? page : 1,
+ query: (Array.isArray(params.q) ? params.q[0] : (params.q ?? "")).trim().slice(0, 200),
+ };
+}
+export function grammarLibraryHref({ page, query }: GrammarLibraryQuery) {
+ const params = new URLSearchParams();
+ if (query) params.set("q", query);
+ if (page > 1) params.set("page", String(page));
+ return `/grammar${params.toString() ? `?${params}` : ""}`;
+}
diff --git a/src/views/grammar-library/ui/GrammarLibrarySkeleton.tsx b/src/views/grammar-library/ui/GrammarLibrarySkeleton.tsx
new file mode 100644
index 00000000..c034a6e1
--- /dev/null
+++ b/src/views/grammar-library/ui/GrammarLibrarySkeleton.tsx
@@ -0,0 +1,17 @@
+export function GrammarLibrarySkeleton() {
+ return (
+
+
어법 노트를 불러오는 중입니다.
+ {Array.from({ length: 5 }, (_, i) => (
+
+ ))}
+
+ );
+}
diff --git a/src/views/grammar-library/ui/GrammarLibraryView.tsx b/src/views/grammar-library/ui/GrammarLibraryView.tsx
new file mode 100644
index 00000000..786b50b6
--- /dev/null
+++ b/src/views/grammar-library/ui/GrammarLibraryView.tsx
@@ -0,0 +1,44 @@
+import Link from "next/link";
+import Form from "next/form";
+import type { GrammarNoteListProps } from "../models/interface";
+import { GrammarNoteList } from "./GrammarNoteList";
+import { BackNavigation } from "@/shared/components/ui/back-navigation/BackNavigation";
+export function GrammarLibraryView(props: GrammarNoteListProps) {
+ return (
+
+
+
+
+
GRAMMAR PRACTICE
+
어법 노트
+
배운 어법을 문장으로 기억하세요.
+
+
+ 새 노트 작성 →
+
+
+
+
+
+ );
+}
diff --git a/src/views/grammar-library/ui/GrammarNoteList.tsx b/src/views/grammar-library/ui/GrammarNoteList.tsx
new file mode 100644
index 00000000..d5422168
--- /dev/null
+++ b/src/views/grammar-library/ui/GrammarNoteList.tsx
@@ -0,0 +1,78 @@
+import Link from "next/link";
+import type { GrammarNoteListProps } from "../models/interface";
+import { grammarLibraryHref } from "../services/libraryQuery";
+import { getPaginationItems } from "@/shared/utils/pagination";
+export function GrammarNoteList({ data, query }: GrammarNoteListProps) {
+ const returnTo = grammarLibraryHref({ page: data.page, query });
+ const pages = Math.max(1, Math.ceil(data.total / data.pageSize));
+ return (
+
+ {data.total}개의 어법 노트
+ {data.items.length === 0 ? (
+
+
+ {query ? "검색 결과가 없습니다" : "첫 어법 노트를 만들어보세요"}
+
+
+ {query
+ ? "다른 제목이나 문장으로 검색해보세요."
+ : "배운 문장과 핵심 어법을 기록하고 연습하세요."}
+
+
+ ) : (
+
+ )}
+ {pages > 1 && (
+
+ )}
+
+ );
+}
From ebd783e89230c1d560a03ab21326e0e0a673aed7 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Tue, 6 Oct 2026 02:28:26 +0900
Subject: [PATCH 2/8] fix(grammar): show keyed list skeleton during search and
pagination
---
.../GrammarLibraryPage.test.tsx | 9 +++---
src/app/(protected)/grammar/(list)/page.tsx | 32 ++++++-------------
.../ui/GrammarLibraryContent.tsx | 25 +++++++++++++++
3 files changed, 40 insertions(+), 26 deletions(-)
create mode 100644 src/views/grammar-library/ui/GrammarLibraryContent.tsx
diff --git a/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx b/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx
index 838a685f..655537e0 100644
--- a/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx
+++ b/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx
@@ -22,10 +22,11 @@ describe("grammar list route", () => {
findMany.mockResolvedValue({ items: [], total: 41, page: 999, pageSize: 20 });
});
it("redirects an out-of-range page to last valid page with search preserved", async () => {
- const { default: GrammarLibraryPage } = await import("@/app/(protected)/grammar/(list)/page");
- await expect(
- GrammarLibraryPage({ searchParams: Promise.resolve({ page: "999", q: "verb" }) }),
- ).rejects.toThrow("redirect:/grammar?q=verb&page=3");
+ const { GrammarLibraryContent } =
+ await import("@/views/grammar-library/ui/GrammarLibraryContent");
+ await expect(GrammarLibraryContent({ query: { page: 999, query: "verb" } })).rejects.toThrow(
+ "redirect:/grammar?q=verb&page=3",
+ );
expect(findMany).toHaveBeenCalledWith({ page: 999, pageSize: 20, query: "verb" });
});
it("normalizes an invalid URL before rendering valid links", async () => {
diff --git a/src/app/(protected)/grammar/(list)/page.tsx b/src/app/(protected)/grammar/(list)/page.tsx
index a2ef25dc..b81fbb03 100644
--- a/src/app/(protected)/grammar/(list)/page.tsx
+++ b/src/app/(protected)/grammar/(list)/page.tsx
@@ -1,38 +1,26 @@
+import { Suspense } from "react";
import { redirect } from "next/navigation";
-import { 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 {
- GrammarLibraryView,
+ GrammarLibrarySkeleton,
parseGrammarLibraryQuery,
grammarLibraryHref,
} from "@/views/grammar-library";
+import { GrammarLibraryContent } from "@/views/grammar-library/ui/GrammarLibraryContent";
interface Props {
searchParams: Promise<{ page?: string | string[]; q?: string | string[] }>;
}
export default async function GrammarLibraryPage({ searchParams }: Props) {
const raw = await searchParams;
const query = parseGrammarLibraryQuery(raw);
- const supabase = await createSupabaseServerClient();
- const {
- data: { user },
- error,
- } = await supabase.auth.getUser();
- if (error || !user) redirect("/login");
- const data = await observeOperation({
- operation: "grammar.list",
- resourceId: "grammar-library",
- recordEvent: recordOperationEvent,
- execute: () => new GrammarNoteRepository(supabase).findMany({ ...query, pageSize: 20 }),
- });
- const normalizedPage = Math.min(query.page, Math.max(1, Math.ceil(data.total / data.pageSize)));
- // 범위를 벗어난 URL은 마지막 유효 페이지로 교정한다. 이후 링크와 상세 복귀도 같은 주소를 쓴다.
if (
- normalizedPage !== query.page ||
(raw.page !== undefined && raw.page !== String(query.page)) ||
(raw.q !== undefined && raw.q !== query.query)
)
- redirect(grammarLibraryHref({ ...query, page: normalizedPage }));
- return ;
+ redirect(grammarLibraryHref(query));
+ // 검색어/페이지 변경도 새 데이터가 준비될 때까지 해당 목록의 스켈레톤을 보여준다.
+ return (
+ }>
+
+
+ );
}
diff --git a/src/views/grammar-library/ui/GrammarLibraryContent.tsx b/src/views/grammar-library/ui/GrammarLibraryContent.tsx
new file mode 100644
index 00000000..2de11d0c
--- /dev/null
+++ b/src/views/grammar-library/ui/GrammarLibraryContent.tsx
@@ -0,0 +1,25 @@
+import { redirect } from "next/navigation";
+import { 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 { GrammarLibraryQuery } from "../models/interface";
+import { grammarLibraryHref } from "../services/libraryQuery";
+import { GrammarLibraryView } from "./GrammarLibraryView";
+export async function GrammarLibraryContent({ query }: { query: GrammarLibraryQuery }) {
+ const supabase = await createSupabaseServerClient();
+ const {
+ data: { user },
+ error,
+ } = await supabase.auth.getUser();
+ if (error || !user) redirect("/login");
+ const data = await observeOperation({
+ operation: "grammar.list",
+ resourceId: "grammar-library",
+ recordEvent: recordOperationEvent,
+ execute: () => new GrammarNoteRepository(supabase).findMany({ ...query, pageSize: 20 }),
+ });
+ const page = Math.min(query.page, Math.max(1, Math.ceil(data.total / data.pageSize)));
+ if (page !== query.page) redirect(grammarLibraryHref({ ...query, page }));
+ return ;
+}
From 6b2139cad0fa06f0ece1997eff9265f57c9006d1 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:25:45 +0900
Subject: [PATCH 3/8] fix: address grammar editor review feedback (#168)
---
.../GrammarNoteEditor.stories.tsx | 2 +-
.../GrammarAnalysisEditor.test.tsx | 19 +++++++-
.../editAnalysis.test.ts | 35 ++++++++++++++
.../GrammarNoteEditor.test.tsx | 47 +++++++++++++++++++
.../createEditorStore.test.ts | 8 ++--
.../saveGrammarNote.test.ts | 4 +-
.../grammar-analysis-edit/models/store.ts | 19 ++++++--
.../ui/AnalysisEditorProvider.tsx | 19 +++-----
.../grammar-note-editor/models/interface.ts | 11 ++++-
.../services/actions/saveGrammarNote.ts | 10 +---
.../services/createEditorStore.ts | 27 ++++++-----
.../grammar-note-editor/ui/EditorError.tsx | 31 ++++++++++++
.../grammar-note-editor/ui/EditorProvider.tsx | 26 +++++++---
.../ui/GrammarNoteEditor.tsx | 8 +---
.../grammar-editor/GrammarEditorClient.tsx | 33 +++++++++++++
.../grammar-editor/GrammarEditorView.tsx | 24 +---------
16 files changed, 239 insertions(+), 84 deletions(-)
create mode 100644 src/features/grammar-note-editor/ui/EditorError.tsx
create mode 100644 src/views/grammar-editor/GrammarEditorClient.tsx
diff --git a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
index 6122136c..1e5f862b 100644
--- a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
+++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
@@ -54,7 +54,7 @@ export const SaveFailure: Story = {
initialNote: note,
save: fn(async () => ({
ok: false as const,
- message: "노트를 저장하지 못했습니다. 다시 저장해 주세요.",
+ code: "PERSISTENCE_FAILED",
})),
},
play: async ({ canvasElement }) => {
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
index 0fc45d68..eba9dd01 100644
--- a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
+++ b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
@@ -3,6 +3,7 @@ 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 });
@@ -64,3 +65,49 @@ describe("분석 초안과 노트 저장 연결", () => {
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
index 4a284aa3..fc55e7b5 100644
--- a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
+++ b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
@@ -80,7 +80,7 @@ describe("어법 등록 이벤트", () => {
reviewed: true,
});
await store.getState().save();
- expect(store.getState().error).toContain("다시 저장");
+ 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);
@@ -120,11 +120,11 @@ describe("어법 등록 이벤트", () => {
});
const store = createEditorStore(deps);
await store.getState().analyze();
- expect(store.getState().error).toContain("분석");
+ expect(store.getState().error).toEqual({ code: "ANALYSIS_FAILED" });
});
it("편집 저장은 읽은 버전을 전달하고 충돌시 초안을 유지한다", async () => {
const deps = dependencies();
- deps.save.mockResolvedValue({ ok: false, message: "버전 충돌" });
+ deps.save.mockResolvedValue({ ok: false, code: "VERSION_CONFLICT" });
const store = createEditorStore(deps);
store.getState().setReviewed(true);
await store.getState().save();
@@ -133,6 +133,6 @@ describe("어법 등록 이벤트", () => {
expectedVersion: 1,
});
expect(store.getState().result).not.toBeNull();
- expect(store.getState().error).toBe("버전 충돌");
+ expect(store.getState().error).toEqual({ code: "VERSION_CONFLICT" });
});
});
diff --git a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
index f694d168..7b002b4a 100644
--- a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
+++ b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
@@ -44,7 +44,7 @@ describe("어법 저장 서버 경계", () => {
const create = jest.spyOn(GrammarNoteRepository.prototype, "create");
expect(await saveGrammarNote(command())).toEqual({
ok: false,
- message: "로그인 후 다시 저장해 주세요.",
+ code: "UNAUTHORIZED",
});
expect(create).not.toHaveBeenCalled();
});
@@ -94,7 +94,7 @@ describe("어법 저장 서버 경계", () => {
});
expect(result).toEqual({
ok: false,
- message: "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요.",
+ code: "VERSION_CONFLICT",
});
});
it("실패는 내부 이벤트로 기록하고 원문과 내부 오류를 UI에 노출하지 않는다", async () => {
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 8e2b19ff..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";
@@ -20,22 +20,17 @@ export function AnalysisEditorProvider({
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),
}),
);
- 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 86244e69..8162b773 100644
--- a/src/features/grammar-note-editor/models/interface.ts
+++ b/src/features/grammar-note-editor/models/interface.ts
@@ -3,6 +3,7 @@ import type {
GrammarMetadata,
GrammarNote,
GrammarNoteContent,
+ GrammarNotePersistenceErrorCode,
GrammarSource,
PrecheckResult,
SentenceAnalysis,
@@ -17,7 +18,9 @@ export type SaveNoteCommand = {
content: GrammarNoteContent;
existing?: { id: string; expectedVersion: number };
};
-export type SaveNoteResult = { ok: true; note: GrammarNote } | { ok: false; message: string };
+export type SaveNoteResult =
+ | { ok: true; note: GrammarNote }
+ | { ok: false; code: GrammarNotePersistenceErrorCode };
export interface GrammarNoteEditorProps {
initialNote?: GrammarNote;
analyze: (source: GrammarSource) => Promise;
@@ -30,12 +33,16 @@ export interface GrammarNoteEditorProps {
onSaved: (note: GrammarNote) => void;
onExit: () => void;
}
+export type EditorError =
+ | { code: GrammarNotePersistenceErrorCode | "ANALYSIS_FAILED" | "INVALID_ANALYSIS" }
+ | { message: string };
+
export interface EditorState {
source: GrammarSource;
result: EditorAnalysisResult | null;
stage: "input" | "review";
pending: "analysis" | "save" | null;
- error: string;
+ error: EditorError | null;
fieldErrors: Partial>;
reviewed: boolean;
analysisDirty: boolean;
diff --git a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
index 10cbf14e..bc075299 100644
--- a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
+++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
@@ -22,14 +22,6 @@ export async function saveGrammarNote(command: SaveNoteCommand): Promise
- set({ analysisDirty, ...(analysisDirty ? { dirty: true, reviewed: false } : {}) }),
+ setAnalysisDirty: (analysisDirty) => {
+ if (get().analysisDirty === analysisDirty) return;
+ set({ analysisDirty, ...(analysisDirty ? { dirty: true, reviewed: false } : {}) });
+ },
dirty: false,
changeSource: (field, value) => {
if (get().pending === "save") return;
@@ -36,7 +38,7 @@ export function createEditorStore(
pending: null,
reviewed: false,
dirty: true,
- error: "",
+ error: null,
fieldErrors: {},
}));
},
@@ -46,6 +48,7 @@ export function createEditorStore(
? {
result: { status: "analyzed", data: { ...state.result.data, analysis } },
reviewed: false,
+ analysisDirty: false,
dirty: true,
}
: {},
@@ -54,7 +57,7 @@ export function createEditorStore(
back: () => {
if (get().pending === "save") return;
generation++;
- set({ stage: "input", pending: null, error: "", analysisDirty: false });
+ set({ stage: "input", pending: null, error: null, analysisDirty: false });
},
cancel: () => {
generation++;
@@ -70,7 +73,7 @@ export function createEditorStore(
return;
}
const currentGeneration = ++generation;
- set({ pending: "analysis", error: "", fieldErrors: {} });
+ set({ pending: "analysis", error: null, fieldErrors: {} });
try {
const result = await dependencies.analyze(parsed.data);
if (currentGeneration !== generation) return;
@@ -93,13 +96,13 @@ export function createEditorStore(
pending: null,
stage: result.status === "analyzed" ? "review" : "input",
reviewed: false,
- error: result.status === "error" ? result.message : "",
+ error: result.status === "error" ? { message: result.message } : null,
});
} catch {
if (currentGeneration === generation)
set({
pending: null,
- error: "분석을 완료하지 못했습니다. 입력을 유지했으니 다시 시도해 주세요.",
+ error: { code: "ANALYSIS_FAILED" },
});
}
},
@@ -119,14 +122,14 @@ export function createEditorStore(
examples: initialNote?.examples ?? [],
});
if (!content.success) {
- set({ error: "분석과 입력을 다시 확인해 주세요." });
+ set({ error: { code: "INVALID_ANALYSIS" } });
return;
}
const signature = JSON.stringify(content.data);
// 동일 저장의 네트워크 재시도에는 동일 UUID를 보내 서버 중복 생성을 막는다.
if (saveIdentity?.content !== signature)
saveIdentity = { content: signature, id: crypto.randomUUID() };
- set({ pending: "save", error: "" });
+ set({ pending: "save", error: null });
try {
const result = await dependencies.save({
requestId: saveIdentity.id,
@@ -136,13 +139,13 @@ export function createEditorStore(
: {}),
});
if (!result.ok) {
- set({ pending: null, error: result.message });
+ set({ pending: null, error: { code: result.code } });
return;
}
set({ pending: null, dirty: false });
dependencies.onSaved(result.note);
} catch {
- set({ pending: null, error: "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요." });
+ set({ pending: null, error: { code: "PERSISTENCE_FAILED" } });
}
},
}));
diff --git a/src/features/grammar-note-editor/ui/EditorError.tsx b/src/features/grammar-note-editor/ui/EditorError.tsx
new file mode 100644
index 00000000..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
index 220c2380..71b58a21 100644
--- a/src/features/grammar-note-editor/ui/EditorProvider.tsx
+++ b/src/features/grammar-note-editor/ui/EditorProvider.tsx
@@ -1,5 +1,13 @@
"use client";
-import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react";
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import { useStore } from "zustand";
import type { StoreApi } from "zustand";
import type { EditorState, GrammarNoteEditorProps } from "../models/interface";
@@ -7,15 +15,19 @@ import { createEditorStore } from "../services/createEditorStore";
const Context = createContext | null>(null);
export function EditorProvider({
children,
- ...dependencies
+ initialNote,
+ analyze,
+ save,
+ onSaved,
}: Omit & { children: ReactNode }) {
- const latest = useRef(dependencies);
- useEffect(() => {
- latest.current = dependencies;
- }, [dependencies]);
+ const latest = useRef({ analyze, save, onSaved });
+ useLayoutEffect(() => {
+ latest.current = { analyze, save, onSaved };
+ }, [analyze, save, onSaved]);
+ // initialNote는 초기값이다. 문서 ID·버전이 바뀌면 호출부에서 key로 새 세션을 연다.
const [store] = useState(() =>
createEditorStore({
- initialNote: dependencies.initialNote,
+ initialNote,
analyze: (source) => latest.current.analyze(source),
save: (command) => latest.current.save(command),
onSaved: (note) => latest.current.onSaved(note),
diff --git a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
index 1efef5e0..9a78b3cc 100644
--- a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
+++ b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
@@ -4,6 +4,7 @@ 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({
@@ -11,16 +12,11 @@ function EditorBody({
onExit,
}: Pick) {
const stage = useEditor((s) => s.stage);
- const error = useEditor((s) => s.error);
return (
{stage === "input" ?
:
}
- {error && (
-
- {error}
-
- )}
+
);
}
diff --git a/src/views/grammar-editor/GrammarEditorClient.tsx b/src/views/grammar-editor/GrammarEditorClient.tsx
new file mode 100644
index 00000000..f31f4730
--- /dev/null
+++ b/src/views/grammar-editor/GrammarEditorClient.tsx
@@ -0,0 +1,33 @@
+"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";
+
+export function GrammarEditorClient({
+ initialNote,
+ backHref,
+}: {
+ 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/GrammarEditorView.tsx b/src/views/grammar-editor/GrammarEditorView.tsx
index d0fd5b91..f638d6e1 100644
--- a/src/views/grammar-editor/GrammarEditorView.tsx
+++ b/src/views/grammar-editor/GrammarEditorView.tsx
@@ -1,12 +1,6 @@
-"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";
+import { GrammarEditorClient } from "./GrammarEditorClient";
-// 다른 노트나 최신 저장 버전을 열 때 이전 초안이 섞이지 않도록 에디터 key에 ID와 버전을 함께 쓴다.
export function GrammarEditorView({
initialNote,
backHref = "/grammar",
@@ -14,9 +8,6 @@ export function GrammarEditorView({
initialNote?: GrammarNote;
backHref?: string;
}) {
- const router = useRouter();
- const returnTo =
- backHref === "/grammar" || backHref.startsWith("/grammar?") ? backHref : "/grammar";
return (
@@ -29,18 +20,7 @@ export function GrammarEditorView({
- {
- router.push(`/grammar/${note.id}?returnTo=${encodeURIComponent(returnTo)}`);
- router.refresh();
- }}
- onExit={() => router.push(returnTo)}
- />
+
);
From 29e90c52d46e77b851d631ca89646de9ebde36ef Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:49:54 +0900
Subject: [PATCH 4/8] refactor: apply shared review rules to example editing
(#169)
---
.../GrammarExampleManager.stories.tsx | 2 +-
.../GrammarExampleManager.test.tsx | 38 +++++++++++++++++++
.../createExampleStore.test.ts | 4 +-
.../exampleActions.test.ts | 10 ++---
.../models/errors.ts | 34 +++++++----------
.../models/interface.ts | 5 ++-
.../services/createExampleStore.ts | 18 ++++-----
.../services/server/executeExampleAction.ts | 4 +-
.../ui/ExampleActions.tsx | 3 +-
.../ui/ExampleProvider.tsx | 27 +++++++++----
.../ui/GrammarExampleManager.tsx | 2 +-
.../ui/errorMessage.ts | 23 +++++++++++
12 files changed, 120 insertions(+), 50 deletions(-)
create mode 100644 src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
create mode 100644 src/features/grammar-example-generation/ui/errorMessage.ts
diff --git a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
index c23634cb..f5d226ec 100644
--- a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
+++ b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
@@ -55,7 +55,7 @@ export const Retry: Story = {
play: async ({ canvasElement, args }) => {
args.generate.mockResolvedValueOnce({
ok: false,
- message: "생성에 실패했습니다. 다시 생성해 주세요.",
+ code: "FAILED",
});
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" }));
diff --git a/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
new file mode 100644
index 00000000..7f3196d0
--- /dev/null
+++ b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
@@ -0,0 +1,38 @@
+import { describe, expect, it, jest } from "@jest/globals";
+import { fireEvent, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import {
+ GrammarExampleManager,
+ type GrammarExampleManagerProps,
+} from "@/features/grammar-example-generation";
+import { createEditorNote } from "../grammar-note-editor/fixtures";
+import { createExampleCandidates } from "./fixtures";
+describe("예문 편집 세션", () => {
+ it("같은 노트의 버전 갱신에는 초안을 유지하고 최신 콜백을 쓰며 다른 노트에는 초기화한다", async () => {
+ const note = createEditorNote();
+ const generate = jest
+ .fn()
+ .mockResolvedValue({ ok: true, data: createExampleCandidates() });
+ const save = jest.fn();
+ const latestSave = jest
+ .fn()
+ .mockResolvedValue({ ok: false, code: "VERSION_CONFLICT" });
+ const props = { note, generate, save, onUpdated: jest.fn() };
+ const { rerender } = render();
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "예문 3개 생성" }));
+ fireEvent.change((await screen.findAllByLabelText("영어 예문"))[0], {
+ target: { value: "Edited sentence." },
+ });
+ await user.click(screen.getAllByRole("checkbox")[0]);
+ rerender();
+ expect(screen.getAllByLabelText("영어 예문")[0]).toHaveValue("Edited sentence.");
+ await user.click(screen.getByRole("button", { name: "선택한 예문 1개 저장" }));
+ expect(save).not.toHaveBeenCalled();
+ expect(latestSave).toHaveBeenCalledWith(expect.objectContaining({ expectedVersion: 1 }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("노트가 변경되었습니다");
+ expect(screen.getAllByRole("checkbox")[0]).toBeChecked();
+ rerender();
+ expect(screen.queryByLabelText("영어 예문")).not.toBeInTheDocument();
+ });
+});
diff --git a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
index 0be40034..d5db6aad 100644
--- a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
+++ b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
@@ -24,11 +24,11 @@ describe("예문 초안 이벤트", () => {
await store.getState().generate();
store.getState().change("candidate-0", "sentence", "Edited sentence");
store.getState().select("candidate-0", true);
- generate.mockResolvedValue({ ok: false, message: "실패" });
+ generate.mockResolvedValue({ ok: false, code: "FAILED" });
await store.getState().generate("candidate-1");
expect(store.getState().candidates[0].sentence).toBe("Edited sentence");
expect(store.getState().selected).toEqual(["candidate-0"]);
- expect(store.getState().error).toBe("실패");
+ expect(store.getState().error).toBe("FAILED");
});
it("부분 재생성은 다른 수정본을 건드리지 않는다", async () => {
const { store, generate } = setup();
diff --git a/src/_tests/features/grammar-example-generation/exampleActions.test.ts b/src/_tests/features/grammar-example-generation/exampleActions.test.ts
index a1ae9573..4225c298 100644
--- a/src/_tests/features/grammar-example-generation/exampleActions.test.ts
+++ b/src/_tests/features/grammar-example-generation/exampleActions.test.ts
@@ -64,10 +64,10 @@ describe("예문 서버 액션 권한", () => {
expect(requestExampleOutput).not.toHaveBeenCalled();
});
it.each([
- ["not_invited", "AI 기능을 사용할 권한이 없습니다."],
- ["rate_limited", "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."],
- ["unexpected", "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요."],
- ])("권한 %s이면 AI를 실행하지 않는다", async (permission, message) => {
+ ["not_invited", "NOT_INVITED"],
+ ["rate_limited", "RATE_LIMITED"],
+ ["unexpected", "FAILED"],
+ ])("권한 %s이면 AI를 실행하지 않는다", async (permission, code) => {
jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(createEditorNote());
rpc.mockResolvedValue({ data: permission, error: null });
const result = await requestGrammarExamples({
@@ -75,7 +75,7 @@ describe("예문 서버 액션 권한", () => {
expectedVersion: 1,
count: 3,
});
- expect(result).toEqual({ ok: false, message });
+ expect(result).toEqual({ ok: false, code });
expect(requestExampleOutput).not.toHaveBeenCalled();
});
it("한도 조회 실패를 허용으로 처리하지 않는다", async () => {
diff --git a/src/features/grammar-example-generation/models/errors.ts b/src/features/grammar-example-generation/models/errors.ts
index f4f92640..203bb768 100644
--- a/src/features/grammar-example-generation/models/errors.ts
+++ b/src/features/grammar-example-generation/models/errors.ts
@@ -1,22 +1,16 @@
import { GrammarNotePersistenceError } from "@/entities/grammar-note";
-
-const messages = new Map([
- ["VERSION_CONFLICT", "노트가 변경되었습니다. 최신 노트를 불러온 뒤 다시 시도해 주세요."],
- ["UNAUTHORIZED", "로그인 후 다시 시도해 주세요."],
- ["NOT_FOUND", "노트를 찾을 수 없습니다."],
- ["rate_limited", "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."],
- ["not_invited", "AI 기능을 사용할 권한이 없습니다."],
-]);
-
-export function grammarExampleErrorMessage(error: unknown): string {
- const code =
- error instanceof GrammarNotePersistenceError
- ? error.code
- : error instanceof Error
- ? error.message
- : "UNKNOWN";
- return (
- messages.get(code) ??
- "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요."
- );
+import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note";
+export type ExampleErrorCode =
+ | GrammarNotePersistenceErrorCode
+ | "NOT_INVITED"
+ | "RATE_LIMITED"
+ | "FAILED"
+ | "GENERATION_FAILED"
+ | "SAVE_FAILED"
+ | "INVALID_SELECTION";
+export function grammarExampleErrorCode(error: unknown): ExampleErrorCode {
+ if (error instanceof GrammarNotePersistenceError) return error.code;
+ if (error instanceof Error && error.message === "not_invited") return "NOT_INVITED";
+ if (error instanceof Error && error.message === "rate_limited") return "RATE_LIMITED";
+ return "FAILED";
}
diff --git a/src/features/grammar-example-generation/models/interface.ts b/src/features/grammar-example-generation/models/interface.ts
index cb4ec544..eb16bcfd 100644
--- a/src/features/grammar-example-generation/models/interface.ts
+++ b/src/features/grammar-example-generation/models/interface.ts
@@ -1,3 +1,4 @@
+import type { ExampleErrorCode } from "./errors";
import type {
GrammarExample,
GrammarNote,
@@ -13,7 +14,7 @@ export interface SaveExamplesCommand {
expectedVersion: number;
candidates: readonly GrammarExample[];
}
-export type ExampleResult = { ok: true; data: T } | { ok: false; message: string };
+export type ExampleResult = { ok: true; data: T } | { ok: false; code: ExampleErrorCode };
export interface ExampleDependencies {
repository: GrammarNoteRepositoryPort;
generate: (note: GrammarNote, count: 1 | 3) => Promise;
@@ -31,7 +32,7 @@ export interface ExampleState {
candidates: readonly GrammarExample[];
selected: readonly string[];
pending: string | null;
- error: string;
+ error: ExampleErrorCode | null;
dirty: boolean;
change: (
id: string,
diff --git a/src/features/grammar-example-generation/services/createExampleStore.ts b/src/features/grammar-example-generation/services/createExampleStore.ts
index 20953068..0a464464 100644
--- a/src/features/grammar-example-generation/services/createExampleStore.ts
+++ b/src/features/grammar-example-generation/services/createExampleStore.ts
@@ -9,14 +9,14 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
candidates: [],
selected: [],
pending: null,
- error: "",
+ error: null,
dirty: false,
cancel: () => {
generation++;
},
discard: () => {
generation++;
- set({ candidates: [], selected: [], pending: null, error: "", dirty: false });
+ set({ candidates: [], selected: [], pending: null, error: null, dirty: false });
},
change: (id, field, value) => {
if (get().pending === "save") return;
@@ -44,7 +44,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
if (state.pending) return;
if (id && !state.candidates.some((candidate) => candidate.id === id)) return;
const currentGeneration = ++generation;
- set({ pending: id ?? "all", error: "" });
+ set({ pending: id ?? "all", error: null });
try {
const result = await dependencies.generate({
noteId: state.note.id,
@@ -53,7 +53,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
});
if (currentGeneration !== generation) return;
if (!result.ok) {
- set({ pending: null, error: result.message });
+ set({ pending: null, error: result.code });
return;
}
const candidates = result.data.map((candidate) => grammarExampleSchema.parse(candidate));
@@ -83,7 +83,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
if (currentGeneration === generation)
set({
pending: null,
- error: "예문 생성에 실패했습니다. 기존 후보를 유지했으니 다시 생성해 주세요.",
+ error: "GENERATION_FAILED",
});
}
},
@@ -97,10 +97,10 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
!candidates.length ||
candidates.some((candidate) => !grammarExampleSchema.safeParse(candidate).success)
) {
- set({ error: "저장할 예문을 선택하고 문장·뜻·어법 설명을 모두 입력해 주세요." });
+ set({ error: "INVALID_SELECTION" });
return;
}
- set({ pending: "save", error: "" });
+ set({ pending: "save", error: null });
try {
const result = await dependencies.save({
noteId: state.note.id,
@@ -108,7 +108,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
candidates,
});
if (!result.ok) {
- set({ pending: null, error: result.message });
+ set({ pending: null, error: result.code });
return;
}
set((current) => ({
@@ -124,7 +124,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
} catch {
set({
pending: null,
- error: "예문을 저장하지 못했습니다. 선택과 수정 내용을 유지했습니다. 다시 저장해 주세요.",
+ error: "SAVE_FAILED",
});
}
},
diff --git a/src/features/grammar-example-generation/services/server/executeExampleAction.ts b/src/features/grammar-example-generation/services/server/executeExampleAction.ts
index 62da348c..a5180a83 100644
--- a/src/features/grammar-example-generation/services/server/executeExampleAction.ts
+++ b/src/features/grammar-example-generation/services/server/executeExampleAction.ts
@@ -4,7 +4,7 @@ import { createSupabaseServerClient } from "@/shared/lib/supabase/server";
import { observeOperation } from "@/shared/lib/logging/observeOperation";
import { recordOperationEvent } from "@/shared/lib/logging/pino";
import type { ExampleDependencies, ExampleResult } from "../../models/interface";
-import { grammarExampleErrorMessage } from "../../models/errors";
+import { grammarExampleErrorCode } from "../../models/errors";
import { requestExampleOutput } from "./requestExampleOutput";
export async function executeExampleAction(
operation: string,
@@ -38,6 +38,6 @@ export async function executeExampleAction(
});
return { ok: true, data };
} catch (error) {
- return { ok: false, message: grammarExampleErrorMessage(error) };
+ return { ok: false, code: grammarExampleErrorCode(error) };
}
}
diff --git a/src/features/grammar-example-generation/ui/ExampleActions.tsx b/src/features/grammar-example-generation/ui/ExampleActions.tsx
index f6624578..c8068564 100644
--- a/src/features/grammar-example-generation/ui/ExampleActions.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleActions.tsx
@@ -1,5 +1,6 @@
"use client";
import { Button } from "@/shared/components/atomics/button/Button";
+import { exampleErrorMessage } from "./errorMessage";
import { useExamples } from "./ExampleProvider";
export function ExampleActions() {
const pending = useExamples((s) => s.pending);
@@ -26,7 +27,7 @@ export function ExampleActions() {
{error && (
- {error}
+ {exampleErrorMessage(error)}
)}
{pending && (
diff --git a/src/features/grammar-example-generation/ui/ExampleProvider.tsx b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
index 54880e88..52176f5b 100644
--- a/src/features/grammar-example-generation/ui/ExampleProvider.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
@@ -1,20 +1,33 @@
"use client";
-import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react";
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import { useStore, type StoreApi } from "zustand";
import type { ExampleState, GrammarExampleManagerProps } from "../models/interface";
import { createExampleStore } from "../services/createExampleStore";
const Context = createContext | null>(null);
export function ExampleProvider({
children,
- ...props
+ note,
+ generate,
+ save,
+ onUpdated,
+ onBack,
}: GrammarExampleManagerProps & { children: ReactNode }) {
- const latest = useRef(props);
- useEffect(() => {
- latest.current = props;
- }, [props]);
+ const latest = useRef({ generate, save, onUpdated });
+ useLayoutEffect(() => {
+ latest.current = { generate, save, onUpdated };
+ }, [generate, save, onUpdated]);
const [store] = useState(() =>
createExampleStore({
- ...props,
+ note,
+ onBack,
generate: (command) => latest.current.generate(command),
save: (command) => latest.current.save(command),
onUpdated: (note) => latest.current.onUpdated(note),
diff --git a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
index 023efd3c..04b9ef63 100644
--- a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
+++ b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
@@ -39,7 +39,7 @@ function ExampleBack({ onBack }: { onBack?: () => void }) {
/** 노트 ID로 생명주기를 구분한다. 선택 저장 후 남은 후보 보존을 위해 버전 변경으로 재마운트하지 않는다. */
export function GrammarExampleManager({ onBack, ...props }: GrammarExampleManagerProps) {
return (
-
+
diff --git a/src/features/grammar-example-generation/ui/errorMessage.ts b/src/features/grammar-example-generation/ui/errorMessage.ts
new file mode 100644
index 00000000..727452f3
--- /dev/null
+++ b/src/features/grammar-example-generation/ui/errorMessage.ts
@@ -0,0 +1,23 @@
+import type { ExampleErrorCode } from "../models/errors";
+export function exampleErrorMessage(code: ExampleErrorCode): string {
+ switch (code) {
+ case "VERSION_CONFLICT":
+ return "노트가 변경되었습니다. 최신 노트를 불러온 뒤 다시 시도해 주세요.";
+ case "UNAUTHORIZED":
+ return "로그인 후 다시 시도해 주세요.";
+ case "NOT_FOUND":
+ return "노트를 찾을 수 없습니다.";
+ case "RATE_LIMITED":
+ return "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요.";
+ case "NOT_INVITED":
+ return "AI 기능을 사용할 권한이 없습니다.";
+ case "GENERATION_FAILED":
+ return "예문 생성에 실패했습니다. 기존 후보를 유지했으니 다시 생성해 주세요.";
+ case "SAVE_FAILED":
+ return "예문을 저장하지 못했습니다. 선택과 수정 내용을 유지했습니다. 다시 저장해 주세요.";
+ case "INVALID_SELECTION":
+ return "저장할 예문을 선택하고 문장·뜻·어법 설명을 모두 입력해 주세요.";
+ default:
+ return "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요.";
+ }
+}
From 50963961f637c9a86bd489d89b255e34a0a52b4a Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:58:55 +0900
Subject: [PATCH 5/8] style: separate logical blocks for PR #169
---
.../GrammarExampleManager.stories.tsx | 13 ++++++++
.../GrammarExampleManager.test.tsx | 2 ++
.../createExampleStore.test.ts | 20 +++++++++++++
.../exampleActions.test.ts | 21 +++++++++++++
.../exampleServices.test.ts | 24 +++++++++++++++
.../grammar-example-generation/fixtures.ts | 1 +
.../grammar-example-generation/index.ts | 1 +
.../models/errors.ts | 5 ++++
.../models/interface.ts | 6 ++++
.../models/schema.ts | 4 +++
.../services/actions/exampleActions.ts | 3 ++
.../services/createExampleStore.ts | 30 +++++++++++++++++++
.../services/generateExamples.ts | 9 ++++++
.../services/loadTargetNote.ts | 4 +++
.../services/saveExamples.ts | 9 ++++++
.../services/server/executeExampleAction.ts | 8 +++++
.../services/server/requestExampleOutput.ts | 2 ++
.../ui/ExampleActions.tsx | 3 ++
.../ui/ExampleCandidateCard.tsx | 5 ++++
.../ui/ExampleCandidates.tsx | 3 ++
.../ui/ExampleProvider.tsx | 14 +++++++++
.../ui/GrammarExampleManager.tsx | 5 ++++
.../ui/errorMessage.ts | 1 +
23 files changed, 193 insertions(+)
diff --git a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
index f5d226ec..d9524f6d 100644
--- a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
+++ b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
@@ -6,7 +6,9 @@ import {
} from "@/features/grammar-example-generation";
import { createEditorNote } from "@/_tests/features/grammar-note-editor/fixtures";
import { createExampleCandidates } from "@/_tests/features/grammar-example-generation/fixtures";
+
const note = createEditorNote();
+
const meta = {
title: "features/grammar-example-generation/GrammarExampleManager",
component: GrammarExampleManager,
@@ -31,12 +33,17 @@ const meta = {
),
],
} satisfies Meta;
+
export default meta;
+
type Story = StoryObj;
+
export const Empty: Story = {};
+
export const SelectAndSave: Story = {
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
+
await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" }));
await expect(await canvas.findAllByRole("checkbox")).toHaveLength(3);
await userEvent.click(canvas.getAllByRole("checkbox")[0]);
@@ -45,6 +52,7 @@ export const SelectAndSave: Story = {
await expect(canvas.getAllByRole("checkbox")).toHaveLength(2);
},
};
+
export const Retry: Story = {
args: {
generate: fn(async () => ({
@@ -52,23 +60,28 @@ export const Retry: Story = {
data: createExampleCandidates(),
})),
},
+
play: async ({ canvasElement, args }) => {
args.generate.mockResolvedValueOnce({
ok: false,
code: "FAILED",
});
const canvas = within(canvasElement);
+
await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" }));
await expect(await canvas.findByRole("alert")).toBeVisible();
await userEvent.click(canvas.getByRole("button", { name: "예문 다시 생성" }));
await expect(await canvas.findAllByRole("checkbox")).toHaveLength(3);
},
};
+
export const EditCandidate: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
+
await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" }));
const input = (await canvas.findAllByLabelText("한국어 뜻"))[0];
+
await userEvent.clear(input);
await userEvent.type(input, "그는 운전사가 아니라 교사입니다.");
await expect(input).toHaveValue("그는 운전사가 아니라 교사입니다.");
diff --git a/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
index 7f3196d0..af759e9f 100644
--- a/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
+++ b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
@@ -7,6 +7,7 @@ import {
} from "@/features/grammar-example-generation";
import { createEditorNote } from "../grammar-note-editor/fixtures";
import { createExampleCandidates } from "./fixtures";
+
describe("예문 편집 세션", () => {
it("같은 노트의 버전 갱신에는 초안을 유지하고 최신 콜백을 쓰며 다른 노트에는 초기화한다", async () => {
const note = createEditorNote();
@@ -20,6 +21,7 @@ describe("예문 편집 세션", () => {
const props = { note, generate, save, onUpdated: jest.fn() };
const { rerender } = render();
const user = userEvent.setup();
+
await user.click(screen.getByRole("button", { name: "예문 3개 생성" }));
fireEvent.change((await screen.findAllByLabelText("영어 예문"))[0], {
target: { value: "Edited sentence." },
diff --git a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
index d5db6aad..239a2354 100644
--- a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
+++ b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
@@ -3,6 +3,7 @@ import { createExampleStore } from "@/features/grammar-example-generation/servic
import type { GrammarExampleManagerProps } from "@/features/grammar-example-generation";
import { createEditorNote } from "../grammar-note-editor/fixtures";
import { createExampleCandidates } from "./fixtures";
+
function setup() {
const note = createEditorNote();
const dependencies = {
@@ -16,11 +17,14 @@ function setup() {
onUpdated: jest.fn(),
};
const store = createExampleStore(dependencies);
+
return { store, ...dependencies };
}
+
describe("예문 초안 이벤트", () => {
it("재생성 실패시 기존 예문 수정과 선택을 보존한다", async () => {
const { store, generate } = setup();
+
await store.getState().generate();
store.getState().change("candidate-0", "sentence", "Edited sentence");
store.getState().select("candidate-0", true);
@@ -30,10 +34,13 @@ describe("예문 초안 이벤트", () => {
expect(store.getState().selected).toEqual(["candidate-0"]);
expect(store.getState().error).toBe("FAILED");
});
+
it("부분 재생성은 다른 수정본을 건드리지 않는다", async () => {
const { store, generate } = setup();
+
await store.getState().generate();
const preserved = store.getState().candidates[0];
+
generate.mockResolvedValue({
ok: true,
data: [{ ...createExampleCandidates()[1], id: "replacement" }],
@@ -42,10 +49,13 @@ describe("예문 초안 이벤트", () => {
expect(store.getState().candidates[0]).toBe(preserved);
expect(store.getState().candidates[1].id).toBe("replacement");
});
+
it("진행중 후보 수정 이후 늦게 도착한 생성 결과를 무시한다", async () => {
const { store, generate } = setup();
+
await store.getState().generate();
let resolve!: (value: Awaited>) => void;
+
generate.mockImplementation(
() =>
new Promise((r) => {
@@ -53,14 +63,17 @@ describe("예문 초안 이벤트", () => {
}),
);
const pending = store.getState().generate("candidate-0");
+
store.getState().change("candidate-0", "translation", "수정한 뜻");
resolve({ ok: true, data: [{ ...createExampleCandidates()[0], id: "old-response" }] });
await pending;
expect(store.getState().candidates[0].translation).toBe("수정한 뜻");
});
+
it("돌아간 뒤 늦게 도착한 생성 결과를 표시하지 않는다", async () => {
const { store, generate } = setup();
let resolve!: (value: Awaited>) => void;
+
generate.mockImplementation(
() =>
new Promise((r) => {
@@ -68,13 +81,16 @@ describe("예문 초안 이벤트", () => {
}),
);
const pending = store.getState().generate();
+
store.getState().discard();
resolve({ ok: true, data: createExampleCandidates() });
await pending;
expect(store.getState().candidates).toEqual([]);
});
+
it("검토한 선택 예문만 저장하고 선택하지 않은 후보는 유지한다", async () => {
const { store, save } = setup();
+
await store.getState().generate();
store.getState().select("candidate-1", true);
await store.getState().save();
@@ -82,8 +98,10 @@ describe("예문 초안 이벤트", () => {
expect(store.getState().candidates.map((c) => c.id)).toEqual(["candidate-0", "candidate-2"]);
expect(store.getState().note.version).toBe(2);
});
+
it("저장 네트워크 실패시 선택된 수정 후보를 유지한다", async () => {
const { store, save } = setup();
+
await store.getState().generate();
store.getState().select("candidate-0", true);
save.mockRejectedValue(new Error("network"));
@@ -92,8 +110,10 @@ describe("예문 초안 이벤트", () => {
expect(store.getState().candidates).toHaveLength(3);
expect(store.getState().pending).toBeNull();
});
+
it("필수 후보 내용이 공백이면 저장하지 않는다", async () => {
const { store, save } = setup();
+
await store.getState().generate();
store.getState().change("candidate-0", "sentence", " ");
store.getState().select("candidate-0", true);
diff --git a/src/_tests/features/grammar-example-generation/exampleActions.test.ts b/src/_tests/features/grammar-example-generation/exampleActions.test.ts
index 4225c298..be02bf76 100644
--- a/src/_tests/features/grammar-example-generation/exampleActions.test.ts
+++ b/src/_tests/features/grammar-example-generation/exampleActions.test.ts
@@ -7,28 +7,42 @@ import type {
SaveExamplesCommand,
} from "@/features/grammar-example-generation";
import type { requestExampleOutput as RequestOutput } from "@/features/grammar-example-generation/services/server/requestExampleOutput";
+
let createSupabaseServerClient: typeof CreateClient;
+
let requestExampleOutput: typeof RequestOutput;
+
async function requestGrammarExamples(command: GenerateExamplesCommand) {
const action =
await import("@/features/grammar-example-generation/services/actions/exampleActions");
+
return action.requestGrammarExamples(command);
}
+
async function saveGrammarExamples(command: SaveExamplesCommand) {
const action =
await import("@/features/grammar-example-generation/services/actions/exampleActions");
+
return action.saveGrammarExamples(command);
}
+
import { createEditorNote } from "../grammar-note-editor/fixtures";
import { createExampleCandidates } from "./fixtures";
+
jest.mock("server-only", () => ({}));
+
jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));
+
jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() }));
+
jest.mock("@/features/grammar-example-generation/services/server/requestExampleOutput", () => ({
requestExampleOutput: jest.fn(),
}));
+
Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true });
+
const rpc = jest.fn<() => Promise<{ data: string | null; error: Error | null }>>();
+
beforeEach(async () => {
({ createSupabaseServerClient } = await import("@/shared/lib/supabase/server"));
({ requestExampleOutput } =
@@ -41,6 +55,7 @@ beforeEach(async () => {
rpc,
} as never);
});
+
describe("예문 서버 액션 권한", () => {
it("비로그인 생성과 저장은 조회나 유료 호출 전에 차단한다", async () => {
jest.mocked(createSupabaseServerClient).mockResolvedValue({
@@ -58,11 +73,13 @@ describe("예문 서버 액션 권한", () => {
expectedVersion: 1,
candidates: createExampleCandidates(),
});
+
expect(generation.ok).toBe(false);
expect(saving.ok).toBe(false);
expect(find).not.toHaveBeenCalled();
expect(requestExampleOutput).not.toHaveBeenCalled();
});
+
it.each([
["not_invited", "NOT_INVITED"],
["rate_limited", "RATE_LIMITED"],
@@ -75,9 +92,11 @@ describe("예문 서버 액션 권한", () => {
expectedVersion: 1,
count: 3,
});
+
expect(result).toEqual({ ok: false, code });
expect(requestExampleOutput).not.toHaveBeenCalled();
});
+
it("한도 조회 실패를 허용으로 처리하지 않는다", async () => {
jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(createEditorNote());
rpc.mockResolvedValue({ data: null, error: new Error("network") });
@@ -92,8 +111,10 @@ describe("예문 서버 액션 권한", () => {
).toBe(false);
expect(requestExampleOutput).not.toHaveBeenCalled();
});
+
it("선택 저장에는 AI 비용을 소비하지 않는다", async () => {
const note = createEditorNote();
+
jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(note);
jest
.spyOn(GrammarNoteRepository.prototype, "update")
diff --git a/src/_tests/features/grammar-example-generation/exampleServices.test.ts b/src/_tests/features/grammar-example-generation/exampleServices.test.ts
index 4efb3987..09e5e0ee 100644
--- a/src/_tests/features/grammar-example-generation/exampleServices.test.ts
+++ b/src/_tests/features/grammar-example-generation/exampleServices.test.ts
@@ -6,7 +6,9 @@ import { generateExamples } from "@/features/grammar-example-generation/services
import { saveExamples } from "@/features/grammar-example-generation/services/saveExamples";
import { createEditorNote } from "../grammar-note-editor/fixtures";
import { createExampleCandidates } from "./fixtures";
+
Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true });
+
function setup() {
const note = createEditorNote();
const repository = {
@@ -27,6 +29,7 @@ function setup() {
const consumeRequest = jest
.fn()
.mockResolvedValue("allowed");
+
return {
note,
repository,
@@ -35,49 +38,63 @@ function setup() {
command: { noteId: note.id, expectedVersion: 1, count: 3 as const },
};
}
+
describe("저장 노트 기반 예문 생성 및 채택", () => {
it("서버가 읽은 어법을 전달하고 검증된 후보를 미검토 상태로 반환한다", async () => {
const deps = setup();
const result = await generateExamples(deps.command, deps);
+
expect(deps.generate).toHaveBeenCalledWith(deps.note, 3);
expect(result).toHaveLength(3);
expect(result.every((example) => example.reviewStatus === "needs-review")).toBe(true);
expect(new Set(result.map((example) => example.id)).size).toBe(3);
});
+
it("클라이언트가 목표 어법을 끼워 넣으면 외부 호출 전에 거절한다", async () => {
const deps = setup();
+
await expect(generateExamples({ ...deps.command, target: "override" }, deps)).rejects.toThrow();
expect(deps.generate).not.toHaveBeenCalled();
});
+
it("소유하지 않은 노트를 읽을 수 없으면 비용을 소비하지 않는다", async () => {
const deps = setup();
+
deps.repository.findById.mockResolvedValue(null);
await expect(generateExamples(deps.command, deps)).rejects.toMatchObject({ code: "NOT_FOUND" });
expect(deps.consumeRequest).not.toHaveBeenCalled();
});
+
it("버전이 달라지면 이전 어법으로 생성하지 않는다", async () => {
const deps = setup();
+
await expect(
generateExamples({ ...deps.command, expectedVersion: 2 }, deps),
).rejects.toMatchObject({ code: "VERSION_CONFLICT" });
expect(deps.generate).not.toHaveBeenCalled();
});
+
it("한도를 초과하면 외부 요청을 보내지 않는다", async () => {
const deps = setup();
+
deps.consumeRequest.mockResolvedValue("rate_limited");
await expect(generateExamples(deps.command, deps)).rejects.toThrow("rate_limited");
expect(deps.generate).not.toHaveBeenCalled();
});
+
it("예문 개수가 다르거나 공백인 결과를 반환하지 않는다", async () => {
const deps = setup();
+
deps.generate.mockResolvedValue({
examples: [{ sentence: " ", translation: "뜻", targetExplanation: "설명" }],
});
await expect(generateExamples({ ...deps.command, count: 1 }, deps)).rejects.toThrow();
});
+
it("선택한 예문만 검토 완료로 저장하고 기존 노트와 예문을 보존한다", async () => {
const deps = setup();
const candidates = createExampleCandidates();
+
deps.repository.findById.mockResolvedValue({ ...deps.note, examples: [candidates[0]] });
await saveExamples(
{ noteId: deps.note.id, expectedVersion: 1, candidates: [candidates[1]] },
@@ -94,8 +111,10 @@ describe("저장 노트 기반 예문 생성 및 채택", () => {
},
});
});
+
it("저장 충돌은 다른 노트 변경을 덮어쓰지 않는다", async () => {
const deps = setup();
+
await expect(
saveExamples(
{ noteId: deps.note.id, expectedVersion: 2, candidates: createExampleCandidates() },
@@ -104,9 +123,11 @@ describe("저장 노트 기반 예문 생성 및 채택", () => {
).rejects.toMatchObject({ code: "VERSION_CONFLICT" });
expect(deps.repository.update).not.toHaveBeenCalled();
});
+
it("중복 후보 식별자는 저장하지 않는다", async () => {
const deps = setup();
const candidate = createExampleCandidates()[0];
+
await expect(
saveExamples(
{ noteId: deps.note.id, expectedVersion: 1, candidates: [candidate, candidate] },
@@ -115,6 +136,7 @@ describe("저장 노트 기반 예문 생성 및 채택", () => {
).rejects.toThrow();
expect(deps.repository.update).not.toHaveBeenCalled();
});
+
it("saved candidate retry does not increment the version", async () => {
const deps = setup();
const candidates = createExampleCandidates().map((candidate) => ({
@@ -122,11 +144,13 @@ describe("저장 노트 기반 예문 생성 및 채택", () => {
reviewStatus: "reviewed" as const,
}));
const stored = { ...deps.note, version: 2, examples: candidates };
+
deps.repository.findById.mockResolvedValue(stored);
const result = await saveExamples(
{ noteId: deps.note.id, expectedVersion: 1, candidates: createExampleCandidates() },
deps.repository,
);
+
expect(result).toBe(stored);
expect(deps.repository.update).not.toHaveBeenCalled();
});
diff --git a/src/_tests/features/grammar-example-generation/fixtures.ts b/src/_tests/features/grammar-example-generation/fixtures.ts
index 629f2c7b..35ae1837 100644
--- a/src/_tests/features/grammar-example-generation/fixtures.ts
+++ b/src/_tests/features/grammar-example-generation/fixtures.ts
@@ -1,4 +1,5 @@
import type { GrammarExample } from "@/entities/grammar-note";
+
export function createExampleCandidates(): GrammarExample[] {
return [
"He is not a driver but a teacher.",
diff --git a/src/features/grammar-example-generation/index.ts b/src/features/grammar-example-generation/index.ts
index fbe870ee..64362000 100644
--- a/src/features/grammar-example-generation/index.ts
+++ b/src/features/grammar-example-generation/index.ts
@@ -1,4 +1,5 @@
export { GrammarExampleManager } from "./ui/GrammarExampleManager";
+
export type {
GrammarExampleManagerProps,
GenerateExamplesCommand,
diff --git a/src/features/grammar-example-generation/models/errors.ts b/src/features/grammar-example-generation/models/errors.ts
index 203bb768..4ed0ced3 100644
--- a/src/features/grammar-example-generation/models/errors.ts
+++ b/src/features/grammar-example-generation/models/errors.ts
@@ -1,5 +1,6 @@
import { GrammarNotePersistenceError } from "@/entities/grammar-note";
import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note";
+
export type ExampleErrorCode =
| GrammarNotePersistenceErrorCode
| "NOT_INVITED"
@@ -8,9 +9,13 @@ export type ExampleErrorCode =
| "GENERATION_FAILED"
| "SAVE_FAILED"
| "INVALID_SELECTION";
+
export function grammarExampleErrorCode(error: unknown): ExampleErrorCode {
if (error instanceof GrammarNotePersistenceError) return error.code;
+
if (error instanceof Error && error.message === "not_invited") return "NOT_INVITED";
+
if (error instanceof Error && error.message === "rate_limited") return "RATE_LIMITED";
+
return "FAILED";
}
diff --git a/src/features/grammar-example-generation/models/interface.ts b/src/features/grammar-example-generation/models/interface.ts
index eb16bcfd..a2066859 100644
--- a/src/features/grammar-example-generation/models/interface.ts
+++ b/src/features/grammar-example-generation/models/interface.ts
@@ -4,22 +4,27 @@ import type {
GrammarNote,
GrammarNoteRepositoryPort,
} from "@/entities/grammar-note";
+
export interface GenerateExamplesCommand {
noteId: string;
expectedVersion: number;
count: 1 | 3;
}
+
export interface SaveExamplesCommand {
noteId: string;
expectedVersion: number;
candidates: readonly GrammarExample[];
}
+
export type ExampleResult = { ok: true; data: T } | { ok: false; code: ExampleErrorCode };
+
export interface ExampleDependencies {
repository: GrammarNoteRepositoryPort;
generate: (note: GrammarNote, count: 1 | 3) => Promise;
consumeRequest: () => Promise<"allowed" | "not_invited" | "rate_limited">;
}
+
export interface GrammarExampleManagerProps {
note: GrammarNote;
generate: (command: GenerateExamplesCommand) => Promise>;
@@ -27,6 +32,7 @@ export interface GrammarExampleManagerProps {
onUpdated: (note: GrammarNote) => void;
onBack?: () => void;
}
+
export interface ExampleState {
note: GrammarNote;
candidates: readonly GrammarExample[];
diff --git a/src/features/grammar-example-generation/models/schema.ts b/src/features/grammar-example-generation/models/schema.ts
index d45692bb..8d4a9f82 100644
--- a/src/features/grammar-example-generation/models/schema.ts
+++ b/src/features/grammar-example-generation/models/schema.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { grammarExampleSchema } from "@/entities/grammar-note";
+
export const generateExamplesCommandSchema = z
.object({
noteId: z.string().uuid(),
@@ -7,6 +8,7 @@ export const generateExamplesCommandSchema = z
count: z.union([z.literal(1), z.literal(3)]),
})
.strict();
+
export const saveExamplesCommandSchema = z
.object({
noteId: z.string().uuid(),
@@ -14,7 +16,9 @@ export const saveExamplesCommandSchema = z
candidates: z.array(grammarExampleSchema).min(1).max(3),
})
.strict();
+
const text = z.string().min(1).max(4000);
+
export const exampleOutputSchema = z
.object({
examples: z
diff --git a/src/features/grammar-example-generation/services/actions/exampleActions.ts b/src/features/grammar-example-generation/services/actions/exampleActions.ts
index 4630517f..734a3b71 100644
--- a/src/features/grammar-example-generation/services/actions/exampleActions.ts
+++ b/src/features/grammar-example-generation/services/actions/exampleActions.ts
@@ -1,13 +1,16 @@
"use server";
+
import type { GenerateExamplesCommand, SaveExamplesCommand } from "../../models/interface";
import { executeExampleAction } from "../server/executeExampleAction";
import { generateExamples } from "../generateExamples";
import { saveExamples } from "../saveExamples";
+
export async function requestGrammarExamples(command: GenerateExamplesCommand) {
return executeExampleAction("grammar.examples.generate", (dependencies) =>
generateExamples(command, dependencies),
);
}
+
export async function saveGrammarExamples(command: SaveExamplesCommand) {
return executeExampleAction("grammar.examples.save", (dependencies) =>
saveExamples(command, dependencies.repository),
diff --git a/src/features/grammar-example-generation/services/createExampleStore.ts b/src/features/grammar-example-generation/services/createExampleStore.ts
index 0a464464..e05c1ba2 100644
--- a/src/features/grammar-example-generation/services/createExampleStore.ts
+++ b/src/features/grammar-example-generation/services/createExampleStore.ts
@@ -1,9 +1,11 @@
import { createStore } from "zustand/vanilla";
import { grammarExampleSchema } from "@/entities/grammar-note";
import type { ExampleState, GrammarExampleManagerProps } from "../models/interface";
+
export function createExampleStore(dependencies: GrammarExampleManagerProps) {
// 재생성 중 사용자가 후보를 수정할 수 있으므로, 수정 이전에 시작한 응답은 적용하지 않는다.
let generation = 0;
+
return createStore((set, get) => ({
note: dependencies.note,
candidates: [],
@@ -11,15 +13,19 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
pending: null,
error: null,
dirty: false,
+
cancel: () => {
generation++;
},
+
discard: () => {
generation++;
set({ candidates: [], selected: [], pending: null, error: null, dirty: false });
},
+
change: (id, field, value) => {
if (get().pending === "save") return;
+
generation++;
set((state) => ({
candidates: state.candidates.map((candidate) =>
@@ -32,6 +38,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
dirty: true,
}));
},
+
select: (id, selected) =>
set((state) => ({
selected: selected
@@ -39,29 +46,41 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
: state.selected.filter((value) => value !== id),
dirty: true,
})),
+
generate: async (id) => {
const state = get();
+
if (state.pending) return;
+
if (id && !state.candidates.some((candidate) => candidate.id === id)) return;
+
const currentGeneration = ++generation;
+
set({ pending: id ?? "all", error: null });
+
try {
const result = await dependencies.generate({
noteId: state.note.id,
expectedVersion: state.note.version,
count: id ? 1 : 3,
});
+
if (currentGeneration !== generation) return;
+
if (!result.ok) {
set({ pending: null, error: result.code });
+
return;
}
+
const candidates = result.data.map((candidate) => grammarExampleSchema.parse(candidate));
+
if (
candidates.length !== (id ? 1 : 3) ||
new Set(candidates.map((candidate) => candidate.id)).size !== candidates.length
)
throw new Error("INVALID_CANDIDATES");
+
if (
id &&
state.candidates.some(
@@ -69,6 +88,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
)
)
throw new Error("DUPLICATE_CANDIDATE");
+
set((current) => ({
candidates: id
? current.candidates.map((candidate) =>
@@ -87,30 +107,40 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
});
}
},
+
save: async () => {
const state = get();
+
if (state.pending) return;
+
const candidates = state.candidates.filter((candidate) =>
state.selected.includes(candidate.id),
);
+
if (
!candidates.length ||
candidates.some((candidate) => !grammarExampleSchema.safeParse(candidate).success)
) {
set({ error: "INVALID_SELECTION" });
+
return;
}
+
set({ pending: "save", error: null });
+
try {
const result = await dependencies.save({
noteId: state.note.id,
expectedVersion: state.note.version,
candidates,
});
+
if (!result.ok) {
set({ pending: null, error: result.code });
+
return;
}
+
set((current) => ({
note: result.data,
candidates: current.candidates.filter(
diff --git a/src/features/grammar-example-generation/services/generateExamples.ts b/src/features/grammar-example-generation/services/generateExamples.ts
index a9f024d0..97cb0b53 100644
--- a/src/features/grammar-example-generation/services/generateExamples.ts
+++ b/src/features/grammar-example-generation/services/generateExamples.ts
@@ -2,6 +2,7 @@ import { grammarExampleSchema } from "@/entities/grammar-note";
import type { ExampleDependencies } from "../models/interface";
import { exampleOutputSchema, generateExamplesCommandSchema } from "../models/schema";
import { loadTargetNote } from "./loadTargetNote";
+
export async function generateExamples(input: unknown, dependencies: ExampleDependencies) {
// 1. 식별자와 버전을 검사하고 소유권이 적용된 저장소에서 목표 어법을 읽는다.
const command = generateExamplesCommandSchema.parse(input);
@@ -11,10 +12,14 @@ export async function generateExamples(input: unknown, dependencies: ExampleDepe
command.expectedVersion,
);
const permission = await dependencies.consumeRequest();
+
if (permission !== "allowed") throw new Error(permission);
+
// 2. 외부 응답의 구조와 요청 개수를 검사한 뒤 서버가 후보 식별자를 부여한다.
const response = exampleOutputSchema.parse(await dependencies.generate(note, command.count));
+
if (response.examples.length !== command.count) throw new Error("INVALID_EXAMPLE_COUNT");
+
const candidates = response.examples.map((example) =>
grammarExampleSchema.parse({
...example,
@@ -22,19 +27,23 @@ export async function generateExamples(input: unknown, dependencies: ExampleDepe
reviewStatus: "needs-review",
}),
);
+
if (
new Set(candidates.map((candidate) => candidate.sentence.trim().toLowerCase())).size !==
candidates.length
)
throw new Error("DUPLICATE_EXAMPLES");
+
const existingSentences = new Set(
[note.source.sentence, ...note.examples.map((example) => example.sentence)].map((sentence) =>
sentence.trim().toLowerCase(),
),
);
+
if (
candidates.some((candidate) => existingSentences.has(candidate.sentence.trim().toLowerCase()))
)
throw new Error("REPEATED_EXAMPLES");
+
return candidates;
}
diff --git a/src/features/grammar-example-generation/services/loadTargetNote.ts b/src/features/grammar-example-generation/services/loadTargetNote.ts
index 4430f4b5..8945f103 100644
--- a/src/features/grammar-example-generation/services/loadTargetNote.ts
+++ b/src/features/grammar-example-generation/services/loadTargetNote.ts
@@ -2,13 +2,17 @@ import {
GrammarNotePersistenceError,
type GrammarNoteRepositoryPort,
} from "@/entities/grammar-note";
+
export async function loadTargetNote(
repository: GrammarNoteRepositoryPort,
id: string,
expectedVersion: number,
) {
const note = await repository.findById(id);
+
if (!note) throw new GrammarNotePersistenceError("NOT_FOUND");
+
if (note.version !== expectedVersion) throw new GrammarNotePersistenceError("VERSION_CONFLICT");
+
return note;
}
diff --git a/src/features/grammar-example-generation/services/saveExamples.ts b/src/features/grammar-example-generation/services/saveExamples.ts
index 70a1ec2c..d8e2aa6a 100644
--- a/src/features/grammar-example-generation/services/saveExamples.ts
+++ b/src/features/grammar-example-generation/services/saveExamples.ts
@@ -3,14 +3,18 @@ import {
type GrammarNoteRepositoryPort,
} from "@/entities/grammar-note";
import { saveExamplesCommandSchema } from "../models/schema";
+
export async function saveExamples(input: unknown, repository: GrammarNoteRepositoryPort) {
const command = saveExamplesCommandSchema.parse(input);
const note = await repository.findById(command.noteId);
+
if (!note) throw new GrammarNotePersistenceError("NOT_FOUND");
+
if (
new Set(command.candidates.map((candidate) => candidate.id)).size !== command.candidates.length
)
throw new Error("DUPLICATE_CANDIDATE");
+
// 응답을 받지 못한 저장 재시도: 동일 ID와 내용이 이미 채택되었다면 버전을 다시 올리지 않는다.
const alreadySaved = command.candidates.every((candidate) =>
note.examples.some(
@@ -22,12 +26,17 @@ export async function saveExamples(input: unknown, repository: GrammarNoteReposi
saved.reviewStatus === "reviewed",
),
);
+
if (alreadySaved) return note;
+
if (note.version !== command.expectedVersion)
throw new GrammarNotePersistenceError("VERSION_CONFLICT");
+
const existingIds = new Set(note.examples.map((example) => example.id));
+
if (command.candidates.some((candidate) => existingIds.has(candidate.id)))
throw new Error("DUPLICATE_CANDIDATE");
+
return repository.update({
id: note.id,
expectedVersion: command.expectedVersion,
diff --git a/src/features/grammar-example-generation/services/server/executeExampleAction.ts b/src/features/grammar-example-generation/services/server/executeExampleAction.ts
index a5180a83..03723935 100644
--- a/src/features/grammar-example-generation/services/server/executeExampleAction.ts
+++ b/src/features/grammar-example-generation/services/server/executeExampleAction.ts
@@ -6,6 +6,7 @@ import { recordOperationEvent } from "@/shared/lib/logging/pino";
import type { ExampleDependencies, ExampleResult } from "../../models/interface";
import { grammarExampleErrorCode } from "../../models/errors";
import { requestExampleOutput } from "./requestExampleOutput";
+
export async function executeExampleAction(
operation: string,
execute: (dependencies: ExampleDependencies) => Promise,
@@ -15,27 +16,34 @@ export async function executeExampleAction(
operation,
resourceId: "grammar-note",
recordEvent: recordOperationEvent,
+
execute: async () => {
const supabase = await createSupabaseServerClient();
const { data: auth, error } = await supabase.auth.getUser();
+
if (error || !auth.user) throw new GrammarNotePersistenceError("UNAUTHORIZED");
+
return execute({
repository: new GrammarNoteRepository(supabase),
generate: requestExampleOutput,
+
consumeRequest: async () => {
const { data, error: quotaError } = await supabase.rpc("consume_ai_request", {
p_operation: "analysis",
});
+
if (
quotaError ||
(data !== "allowed" && data !== "not_invited" && data !== "rate_limited")
)
throw new Error("QUOTA_FAILED");
+
return data;
},
});
},
});
+
return { ok: true, data };
} catch (error) {
return { ok: false, code: grammarExampleErrorCode(error) };
diff --git a/src/features/grammar-example-generation/services/server/requestExampleOutput.ts b/src/features/grammar-example-generation/services/server/requestExampleOutput.ts
index 8e7ba333..ce5bdc17 100644
--- a/src/features/grammar-example-generation/services/server/requestExampleOutput.ts
+++ b/src/features/grammar-example-generation/services/server/requestExampleOutput.ts
@@ -3,6 +3,7 @@ import { zodTextFormat } from "openai/helpers/zod";
import type { GrammarNote } from "@/entities/grammar-note";
import { getOpenAIEvaluationModel, getOpenAIServerClient } from "@/shared/lib/openai/server";
import { exampleOutputSchema } from "../../models/schema";
+
export async function requestExampleOutput(note: GrammarNote, count: 1 | 3): Promise {
const response = await getOpenAIServerClient().responses.parse(
{
@@ -29,5 +30,6 @@ export async function requestExampleOutput(note: GrammarNote, count: 1 | 3): Pro
},
{ timeout: 60000, maxRetries: 0 },
);
+
return response.output_parsed;
}
diff --git a/src/features/grammar-example-generation/ui/ExampleActions.tsx b/src/features/grammar-example-generation/ui/ExampleActions.tsx
index c8068564..220eb18a 100644
--- a/src/features/grammar-example-generation/ui/ExampleActions.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleActions.tsx
@@ -1,7 +1,9 @@
"use client";
+
import { Button } from "@/shared/components/atomics/button/Button";
import { exampleErrorMessage } from "./errorMessage";
import { useExamples } from "./ExampleProvider";
+
export function ExampleActions() {
const pending = useExamples((s) => s.pending);
const error = useExamples((s) => s.error);
@@ -9,6 +11,7 @@ export function ExampleActions() {
const count = useExamples((s) => s.candidates.length);
const generate = useExamples((s) => s.generate);
const save = useExamples((s) => s.save);
+
return (
diff --git a/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx b/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx
index 0e566ac3..ac71486b 100644
--- a/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx
@@ -1,13 +1,16 @@
"use client";
+
import { useId } from "react";
import { Textarea } from "@/shared/components/atomics/textarea/Textarea";
import { Button } from "@/shared/components/atomics/button/Button";
import { useExamples } from "./ExampleProvider";
+
const fields = [
{ field: "sentence", label: "영어 예문" },
{ field: "translation", label: "한국어 뜻" },
{ field: "targetExplanation", label: "목표 어법 설명" },
] as const;
+
export function ExampleCandidateCard({ id, number }: { id: string; number: number }) {
const formId = useId();
const candidate = useExamples((s) => s.candidates.find((candidate) => candidate.id === id));
@@ -16,7 +19,9 @@ export function ExampleCandidateCard({ id, number }: { id: string; number: numbe
const change = useExamples((s) => s.change);
const select = useExamples((s) => s.select);
const generate = useExamples((s) => s.generate);
+
if (!candidate) return null;
+
return (
diff --git a/src/features/grammar-example-generation/ui/ExampleCandidates.tsx b/src/features/grammar-example-generation/ui/ExampleCandidates.tsx
index 392d98be..42e5f2ce 100644
--- a/src/features/grammar-example-generation/ui/ExampleCandidates.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleCandidates.tsx
@@ -1,9 +1,12 @@
"use client";
+
import { useShallow } from "zustand/react/shallow";
import { useExamples } from "./ExampleProvider";
import { ExampleCandidateCard } from "./ExampleCandidateCard";
+
export function ExampleCandidates() {
const ids = useExamples(useShallow((s) => s.candidates.map((candidate) => candidate.id)));
+
return (
{ids.map((id, index) => (
diff --git a/src/features/grammar-example-generation/ui/ExampleProvider.tsx b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
index 52176f5b..51e50baf 100644
--- a/src/features/grammar-example-generation/ui/ExampleProvider.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
@@ -1,4 +1,5 @@
"use client";
+
import {
createContext,
useContext,
@@ -11,7 +12,9 @@ import {
import { useStore, type StoreApi } from "zustand";
import type { ExampleState, GrammarExampleManagerProps } from "../models/interface";
import { createExampleStore } from "../services/createExampleStore";
+
const Context = createContext
| null>(null);
+
export function ExampleProvider({
children,
note,
@@ -21,6 +24,7 @@ export function ExampleProvider({
onBack,
}: GrammarExampleManagerProps & { children: ReactNode }) {
const latest = useRef({ generate, save, onUpdated });
+
useLayoutEffect(() => {
latest.current = { generate, save, onUpdated };
}, [generate, save, onUpdated]);
@@ -28,11 +32,15 @@ export function ExampleProvider({
createExampleStore({
note,
onBack,
+
generate: (command) => latest.current.generate(command),
+
save: (command) => latest.current.save(command),
+
onUpdated: (note) => latest.current.onUpdated(note),
}),
);
+
useEffect(() => () => store.getState().cancel(), [store]);
useEffect(() => {
function beforeUnload(event: BeforeUnloadEvent) {
@@ -41,13 +49,19 @@ export function ExampleProvider({
event.returnValue = "";
}
}
+
window.addEventListener("beforeunload", beforeUnload);
+
return () => window.removeEventListener("beforeunload", beforeUnload);
}, [store]);
+
return {children};
}
+
export function useExamples(selector: (state: ExampleState) => T) {
const store = useContext(Context);
+
if (!store) throw new Error("ExampleProvider가 필요합니다.");
+
return useStore(store, selector);
}
diff --git a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
index 04b9ef63..ffbe1e9e 100644
--- a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
+++ b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
@@ -1,4 +1,5 @@
"use client";
+
import { useState } from "react";
import { Button } from "@/shared/components/atomics/button/Button";
import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog";
@@ -6,15 +7,18 @@ import type { GrammarExampleManagerProps } from "../models/interface";
import { ExampleProvider, useExamples } from "./ExampleProvider";
import { ExampleCandidates } from "./ExampleCandidates";
import { ExampleActions } from "./ExampleActions";
+
function ExampleBack({ onBack }: { onBack?: () => void }) {
const [confirm, setConfirm] = useState(false);
const dirty = useExamples((s) => s.dirty);
const saving = useExamples((s) => s.pending === "save");
const discard = useExamples((s) => s.discard);
+
function leave() {
discard();
onBack?.();
}
+
return (
<>