From 48491ff66d60f43c96cd3d600cc407b8f798379f Mon Sep 17 00:00:00 2001 From: Wonik Choi Date: Mon, 5 Oct 2026 11:41:57 +0900 Subject: [PATCH 1/4] feat: edit sentence analysis boundaries and hierarchy --- .../GrammarAnalysisEditor.stories.tsx | 59 ++++++++ .../GrammarAnalysisEditor.test.tsx | 55 ++++++++ .../editAnalysis.test.ts | 96 +++++++++++++ src/_tests/fixtures/grammarAnalysis.ts | 71 ++++++++++ src/features/grammar-analysis-edit/index.ts | 3 + .../grammar-analysis-edit/models/interface.ts | 70 ++++++++++ .../grammar-analysis-edit/models/store.ts | 52 +++++++ .../services/editAnalysis.ts | 82 +++++++++++ .../services/textBoundaries.ts | 14 ++ .../ui/AnalysisEditorProvider.tsx | 25 ++++ .../ui/AnalysisInspector.tsx | 124 ++++++++++++++++ .../ui/AnalysisSentence.tsx | 58 ++++++++ .../ui/BoundarySelect.tsx | 42 ++++++ .../grammar-analysis-edit/ui/ChunkEditor.tsx | 132 ++++++++++++++++++ .../ui/ConstructionEditor.tsx | 61 ++++++++ .../ui/GrammarAnalysisEditor.tsx | 17 +++ .../grammar-analysis-edit/ui/RangeFields.tsx | 54 +++++++ .../grammar-analysis-edit/ui/SyntaxEditor.tsx | 116 +++++++++++++++ 18 files changed, 1131 insertions(+) create mode 100644 src/_storybook/features/grammar-analysis-edit/GrammarAnalysisEditor.stories.tsx create mode 100644 src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx create mode 100644 src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts create mode 100644 src/_tests/fixtures/grammarAnalysis.ts create mode 100644 src/features/grammar-analysis-edit/index.ts create mode 100644 src/features/grammar-analysis-edit/models/interface.ts create mode 100644 src/features/grammar-analysis-edit/models/store.ts create mode 100644 src/features/grammar-analysis-edit/services/editAnalysis.ts create mode 100644 src/features/grammar-analysis-edit/services/textBoundaries.ts create mode 100644 src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx create mode 100644 src/features/grammar-analysis-edit/ui/AnalysisInspector.tsx create mode 100644 src/features/grammar-analysis-edit/ui/AnalysisSentence.tsx create mode 100644 src/features/grammar-analysis-edit/ui/BoundarySelect.tsx create mode 100644 src/features/grammar-analysis-edit/ui/ChunkEditor.tsx create mode 100644 src/features/grammar-analysis-edit/ui/ConstructionEditor.tsx create mode 100644 src/features/grammar-analysis-edit/ui/GrammarAnalysisEditor.tsx create mode 100644 src/features/grammar-analysis-edit/ui/RangeFields.tsx create mode 100644 src/features/grammar-analysis-edit/ui/SyntaxEditor.tsx diff --git a/src/_storybook/features/grammar-analysis-edit/GrammarAnalysisEditor.stories.tsx b/src/_storybook/features/grammar-analysis-edit/GrammarAnalysisEditor.stories.tsx new file mode 100644 index 00000000..d6189e01 --- /dev/null +++ b/src/_storybook/features/grammar-analysis-edit/GrammarAnalysisEditor.stories.tsx @@ -0,0 +1,59 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, fn, userEvent, within } from "storybook/test"; +import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; + +const meta = { + title: "features/grammar-analysis-edit/GrammarAnalysisEditor", + component: GrammarAnalysisEditor, + args: { initialAnalysis: createGrammarAnalysis(), onChange: fn() }, + decorators: [ + (Story) => ( +
+ +
+ ), + ], +} satisfies Meta; +export default meta; +type Story = StoryObj; +export const Default: Story = {}; +export const SelectedChunk: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "She" })); + await userEvent.click(canvas.getByRole("button", { name: "풀이·구간 편집" })); + await expect(canvas.getByLabelText("직독직해")).toHaveValue("그녀는"); + }, +}; +export const BoundaryEditing: Story = { + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "She" })); + await userEvent.click(canvas.getByRole("button", { name: "풀이·구간 편집" })); + const boundary = canvas.getByLabelText("다음 구간과의 경계"); + await userEvent.selectOptions(boundary, "3"); + await userEvent.click(canvas.getByRole("button", { name: "경계 적용" })); + await expect(args.onChange).toHaveBeenCalled(); + await expect(canvas.queryByRole("alert")).not.toBeInTheDocument(); + }, +}; +export const HierarchyError: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "절" })); + await userEvent.click(canvas.getByRole("button", { name: "풀이·구간 편집" })); + await userEvent.selectOptions(canvas.getByLabelText("상위 항목"), "s"); + await userEvent.click(canvas.getByRole("button", { name: "문법 수정 적용" })); + await expect(canvas.getByRole("alert")).toBeVisible(); + }, +}; +export const DiscontinuousConstruction: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "not A but B" })); + await userEvent.click(canvas.getByRole("button", { name: "풀이·구간 편집" })); + await expect(canvas.getByLabelText("시작 1")).toHaveValue("7"); + await expect(canvas.getByLabelText("시작 2")).toHaveValue("21"); + }, +}; diff --git a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx new file mode 100644 index 00000000..3c965adc --- /dev/null +++ b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx @@ -0,0 +1,55 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; + +describe("grammar analysis review below the sentence", () => { + it("selects a chunk and edits its explanation without losing the source", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + render(); + await user.click(screen.getByRole("button", { name: "She" })); + await user.click(screen.getByRole("button", { name: "풀이·구간 편집" })); + await user.clear(screen.getByLabelText("직독직해")); + await user.type(screen.getByLabelText("직독직해"), "그녀는 주어"); + expect(onChange).not.toHaveBeenCalled(); + await user.click(screen.getByRole("button", { name: "풀이 적용" })); + expect(onChange).toHaveBeenCalledWith( + expect.objectContaining({ + sourceText: createGrammarAnalysis().sourceText, + reviewStatus: "needs-review", + }), + ); + }); + it("keeps an invalid hierarchy draft visible with a recoverable error", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + render(); + await user.click(screen.getByRole("button", { name: "절" })); + await user.click(screen.getByRole("button", { name: "풀이·구간 편집" })); + await user.selectOptions(screen.getByLabelText("상위 항목"), "s"); + await user.click(screen.getByRole("button", { name: "문법 수정 적용" })); + expect(screen.getByRole("alert")).toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); + await user.selectOptions(screen.getByLabelText("상위 항목"), ""); + await user.click(screen.getByRole("button", { name: "문법 수정 적용" })); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect(onChange).toHaveBeenCalledTimes(1); + }); +}); + +it("asks before leaving an unapplied edit and preserves input when continuing", async () => { + const user = userEvent.setup(); + render(); + await user.click(screen.getByRole("button", { name: "She" })); + await user.click(screen.getByRole("button", { name: "풀이·구간 편집" })); + await user.type(screen.getByLabelText("직독직해"), " 수정"); + await user.click(screen.getByRole("button", { name: "동사" })); + expect(screen.getByRole("alertdialog")).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "계속 편집" })); + expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); + await user.click(screen.getByRole("button", { name: "동사" })); + await user.click(screen.getByRole("button", { name: "수정 버리기" })); + expect(screen.queryByLabelText("직독직해")).not.toBeInTheDocument(); +}); diff --git a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts new file mode 100644 index 00000000..190169c4 --- /dev/null +++ b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; +import { editAnalysis } from "@/features/grammar-analysis-edit/services/editAnalysis"; +import { createAnalysisEditorStore } from "@/features/grammar-analysis-edit/models/store"; + +describe("analysis edits", () => { + it("moves adjacent boundaries together without changing source and requires review", () => { + const source = createGrammarAnalysis(); + const result = editAnalysis(source, { type: "move-boundary", chunkId: "c1", end: 3 }); + expect(result.ok).toBe(true); + if (!result.ok) throw new Error(result.message); + expect(result.analysis.chunks[0].range.end).toBe(3); + expect(result.analysis.chunks[1].range.start).toBe(3); + expect(result.analysis.sourceText).toBe(source.sourceText); + expect(result.analysis.reviewStatus).toBe("needs-review"); + expect(source.chunks[0].range.end).toBe(4); + }); + it.each([-1, 0, 7, 100, NaN])("rejects an invalid boundary %s atomically", (end) => { + const source = createGrammarAnalysis(); + const before = JSON.stringify(source); + expect(editAnalysis(source, { type: "move-boundary", chunkId: "c1", end }).ok).toBe(false); + expect(JSON.stringify(source)).toBe(before); + }); + it("splits and merges meaning chunks while preserving exact text coverage", () => { + const source = createGrammarAnalysis(); + const split = editAnalysis(source, { + type: "split-chunk", + chunkId: "c3", + offset: 21, + newId: "c4", + }); + if (!split.ok) throw new Error(split.message); + expect(split.analysis.chunks).toHaveLength(4); + const merged = editAnalysis(split.analysis, { type: "merge-next", chunkId: "c3" }); + if (!merged.ok) throw new Error(merged.message); + expect(merged.analysis.chunks.map((c) => c.range)).toEqual(source.chunks.map((c) => c.range)); + }); + it("rejects unknown targets and duplicate IDs", () => { + const a = createGrammarAnalysis(); + expect(editAnalysis(a, { type: "merge-next", chunkId: "missing" }).ok).toBe(false); + expect(editAnalysis(a, { type: "split-chunk", chunkId: "c3", offset: 21, newId: "s" }).ok).toBe( + false, + ); + }); + it("allows reparenting a child to root and rejects deleting its parent while attached", () => { + const a = createGrammarAnalysis(); + expect(editAnalysis(a, { type: "delete-syntax", id: "clause" }).ok).toBe(false); + const result = editAnalysis(a, { + type: "save-syntax", + annotation: { ...a.syntax[1], parentId: null }, + }); + expect(result.ok).toBe(true); + }); + it("rejects reparenting into a descendant", () => { + const a = createGrammarAnalysis(); + expect( + editAnalysis(a, { type: "save-syntax", annotation: { ...a.syntax[0], parentId: "s" } }).ok, + ).toBe(false); + }); + it("supports discontinuous construction boundary edits", () => { + const a = createGrammarAnalysis(); + const result = editAnalysis(a, { + type: "save-construction", + annotation: { + ...a.constructions[0], + ranges: [ + { start: 7, end: 20 }, + { start: 21, end: 33 }, + ], + }, + }); + expect(result.ok).toBe(true); + }); + it("does not notify document consumers when only selection changes or an edit fails", () => { + const onChange = jest.fn(); + const store = createAnalysisEditorStore({ initialAnalysis: createGrammarAnalysis(), onChange }); + const original = store.getState().analysis; + store.getState().select("c1"); + store.getState().edit({ type: "move-boundary", chunkId: "c1", end: -1 }); + expect(store.getState().analysis).toBe(original); + expect(onChange).not.toHaveBeenCalled(); + }); +}); + +it("applies text and structural edits together or preserves both on failure", () => { + const onChange = jest.fn(); + const store = createAnalysisEditorStore({ initialAnalysis: createGrammarAnalysis(), onChange }); + const before = store.getState().analysis; + const result = store.getState().edit([ + { type: "edit-chunk", chunkId: "c1", literalMeaning: "수정한 뜻", explanation: "" }, + { type: "move-boundary", chunkId: "c1", end: -1 }, + ]); + expect(result.ok).toBe(false); + expect(store.getState().analysis).toBe(before); + expect(onChange).not.toHaveBeenCalled(); +}); diff --git a/src/_tests/fixtures/grammarAnalysis.ts b/src/_tests/fixtures/grammarAnalysis.ts new file mode 100644 index 00000000..a47b6068 --- /dev/null +++ b/src/_tests/fixtures/grammarAnalysis.ts @@ -0,0 +1,71 @@ +import type { SentenceAnalysis } from "@/entities/grammar-note"; + +export function createGrammarAnalysis(): SentenceAnalysis { + return { + sourceText: "She is not a teacher but a doctor.", + sourceRevision: 0, + chunks: [ + { + id: "c1", + range: { start: 0, end: 4 }, + literalMeaning: "그녀는", + explanation: "주어입니다.", + }, + { id: "c2", range: { start: 4, end: 7 }, literalMeaning: "이다", explanation: "동사입니다." }, + { + id: "c3", + range: { start: 7, end: 34 }, + literalMeaning: "교사가 아니라 의사", + explanation: "대조되는 보어입니다.", + }, + ], + syntax: [ + { + id: "clause", + ranges: [{ start: 0, end: 34 }], + parentId: null, + role: "other", + label: "절", + explanation: "완전한 절입니다.", + }, + { + id: "s", + ranges: [{ start: 0, end: 3 }], + parentId: "clause", + role: "subject", + label: "주어", + explanation: "주체를 나타냅니다.", + }, + { + id: "v", + ranges: [{ start: 4, end: 6 }], + parentId: "clause", + role: "verb", + label: "동사", + explanation: "주어와 보어를 연결합니다.", + }, + { + id: "complement", + ranges: [{ start: 7, end: 33 }], + parentId: "clause", + role: "complement", + label: "보어", + explanation: "주어를 설명합니다.", + }, + ], + constructions: [ + { + id: "contrast", + name: "not A but B", + ranges: [ + { start: 7, end: 10 }, + { start: 21, end: 24 }, + ], + meaning: "A가 아니라 B", + explanation: "대조할 내용을 연결합니다.", + }, + ], + naturalTranslation: "그녀는 교사가 아니라 의사입니다.", + reviewStatus: "reviewed", + }; +} diff --git a/src/features/grammar-analysis-edit/index.ts b/src/features/grammar-analysis-edit/index.ts new file mode 100644 index 00000000..ace7a38c --- /dev/null +++ b/src/features/grammar-analysis-edit/index.ts @@ -0,0 +1,3 @@ +export { GrammarAnalysisEditor } from "./ui/GrammarAnalysisEditor"; +export { editAnalysis } from "./services/editAnalysis"; +export type { AnalysisEdit, AnalysisEditResult, AnalysisEditorProps } from "./models/interface"; diff --git a/src/features/grammar-analysis-edit/models/interface.ts b/src/features/grammar-analysis-edit/models/interface.ts new file mode 100644 index 00000000..6f462259 --- /dev/null +++ b/src/features/grammar-analysis-edit/models/interface.ts @@ -0,0 +1,70 @@ +import type { ReactNode } from "react"; +import type { + ConstructionAnnotation, + SentenceAnalysis, + SyntaxAnnotation, +} from "@/entities/grammar-note"; + +export type AnalysisEdit = + | { type: "move-boundary"; chunkId: string; end: number } + | { type: "split-chunk"; chunkId: string; offset: number; newId: string } + | { type: "merge-next"; chunkId: string } + | { type: "edit-chunk"; chunkId: string; literalMeaning: string; explanation: string } + | { type: "save-syntax"; annotation: SyntaxAnnotation } + | { type: "delete-syntax"; id: string } + | { type: "save-construction"; annotation: ConstructionAnnotation } + | { type: "delete-construction"; id: string }; + +export type AnalysisEditResult = + | { ok: true; analysis: SentenceAnalysis } + | { ok: false; message: string }; + +export interface AnalysisEditorState { + readonly analysis: SentenceAnalysis; + readonly selectedId: string | null; + readonly editing: boolean; + readonly dirty: boolean; + readonly pendingSelection: { id: string | null } | null; + startEditing: () => void; + markDirty: () => void; + resolveSelection: (discard: boolean) => void; + select: (id: string | null) => void; + edit: (edit: AnalysisEdit | readonly AnalysisEdit[]) => AnalysisEditResult; +} + +export interface AnalysisEditorProps { + initialAnalysis: SentenceAnalysis; + onChange: (analysis: SentenceAnalysis) => void; +} + +export interface AnalysisEditorProviderProps extends AnalysisEditorProps { + children: ReactNode; +} + +export interface AnalysisItemProps { + id: string; +} +export interface ChunkEditorProps { + chunk: import("@/entities/grammar-note").SentenceChunk; +} +export interface SyntaxEditorProps { + annotation: SyntaxAnnotation; +} +export interface ConstructionEditorProps { + annotation: ConstructionAnnotation; +} +export interface RangeFieldsProps { + ranges: readonly import("@/entities/grammar-note").TextRange[]; + source: string; + onChange: (ranges: import("@/entities/grammar-note").TextRange[]) => void; +} + +export interface BoundarySelectProps { + label: string; + source: string; + value: number; + min?: number; + max?: number; + disabled?: boolean; + onChange: (position: number) => void; +} diff --git a/src/features/grammar-analysis-edit/models/store.ts b/src/features/grammar-analysis-edit/models/store.ts new file mode 100644 index 00000000..e06f31cc --- /dev/null +++ b/src/features/grammar-analysis-edit/models/store.ts @@ -0,0 +1,52 @@ +import { createStore } from "zustand/vanilla"; +import { sentenceAnalysisSchema } from "@/entities/grammar-note"; +import type { AnalysisEditorProps, AnalysisEditorState } from "./interface"; +import { editAnalysis } from "../services/editAnalysis"; + +export function createAnalysisEditorStore({ initialAnalysis, onChange }: AnalysisEditorProps) { + return createStore((set, get) => ({ + analysis: sentenceAnalysisSchema.parse(initialAnalysis), + selectedId: null, + editing: false, + dirty: false, + pendingSelection: null, + startEditing: () => set({ editing: true }), + markDirty: () => { + if (get().editing) set({ dirty: true }); + }, + resolveSelection: (discard) => { + const pending = get().pendingSelection; + if (discard && pending) set({ selectedId: pending.id, editing: false, dirty: false }); + set({ pendingSelection: null }); + }, + select: (selectedId) => { + if (get().dirty) set({ pendingSelection: { id: selectedId } }); + else set({ selectedId, editing: false }); + }, + edit: (command) => { + const commands = "type" in command ? [command] : command; + let analysis = get().analysis; + for (const item of commands) { + const result = editAnalysis(analysis, item); + if (!result.ok) return result; + analysis = result.analysis; + } + const result = { ok: true as const, analysis }; + if (result.ok) { + const ids = [ + ...result.analysis.chunks, + ...result.analysis.syntax, + ...result.analysis.constructions, + ].map((item) => item.id); + const selectedId = get().selectedId; + set({ + dirty: false, + analysis: result.analysis, + selectedId: selectedId && ids.includes(selectedId) ? selectedId : null, + }); + onChange(result.analysis); + } + return result; + }, + })); +} diff --git a/src/features/grammar-analysis-edit/services/editAnalysis.ts b/src/features/grammar-analysis-edit/services/editAnalysis.ts new file mode 100644 index 00000000..baf90ff6 --- /dev/null +++ b/src/features/grammar-analysis-edit/services/editAnalysis.ts @@ -0,0 +1,82 @@ +import { sentenceAnalysisSchema } from "@/entities/grammar-note"; +import type { SentenceAnalysis } from "@/entities/grammar-note"; +import type { AnalysisEdit, AnalysisEditResult } from "../models/interface"; + +/** Apply edits atomically: invalid proposals never mutate the reviewed analysis. */ +export function editAnalysis(analysis: SentenceAnalysis, edit: AnalysisEdit): AnalysisEditResult { + let candidate: SentenceAnalysis = { ...analysis, reviewStatus: "needs-review" }; + if (edit.type === "save-syntax") { + const exists = analysis.syntax.some((item) => item.id === edit.annotation.id); + candidate = { + ...candidate, + syntax: exists + ? analysis.syntax.map((item) => (item.id === edit.annotation.id ? edit.annotation : item)) + : [...analysis.syntax, edit.annotation], + }; + } else if (edit.type === "delete-syntax") { + if (!analysis.syntax.some((item) => item.id === edit.id)) return missing(); + candidate = { ...candidate, syntax: analysis.syntax.filter((item) => item.id !== edit.id) }; + } else if (edit.type === "save-construction") { + const exists = analysis.constructions.some((item) => item.id === edit.annotation.id); + candidate = { + ...candidate, + constructions: exists + ? analysis.constructions.map((item) => + item.id === edit.annotation.id ? edit.annotation : item, + ) + : [...analysis.constructions, edit.annotation], + }; + } else if (edit.type === "delete-construction") { + if (!analysis.constructions.some((item) => item.id === edit.id)) return missing(); + candidate = { + ...candidate, + constructions: analysis.constructions.filter((item) => item.id !== edit.id), + }; + } else { + const index = analysis.chunks.findIndex((chunk) => chunk.id === edit.chunkId); + if (index < 0) return missing(); + const chunk = analysis.chunks[index]; + const next = analysis.chunks[index + 1]; + const chunks = [...analysis.chunks]; + if (edit.type === "edit-chunk") { + chunks[index] = { + ...chunk, + literalMeaning: edit.literalMeaning, + explanation: edit.explanation, + }; + } else if (edit.type === "move-boundary") { + if (!next) return { ok: false, message: "마지막 구간의 끝은 변경할 수 없습니다." }; + chunks[index] = { ...chunk, range: { ...chunk.range, end: edit.end } }; + chunks[index + 1] = { ...next, range: { ...next.range, start: edit.end } }; + } else if (edit.type === "split-chunk") { + chunks.splice( + index, + 1, + { ...chunk, range: { start: chunk.range.start, end: edit.offset } }, + { + id: edit.newId, + range: { start: edit.offset, end: chunk.range.end }, + literalMeaning: "", + explanation: "", + }, + ); + } else { + if (!next) return { ok: false, message: "합칠 다음 구간이 없습니다." }; + chunks.splice(index, 2, { + ...chunk, + range: { start: chunk.range.start, end: next.range.end }, + literalMeaning: [chunk.literalMeaning, next.literalMeaning].filter(Boolean).join(" "), + explanation: [chunk.explanation, next.explanation].filter(Boolean).join("\n"), + }); + } + candidate = { ...candidate, chunks }; + } + const parsed = sentenceAnalysisSchema.safeParse(candidate); + return parsed.success + ? { ok: true, analysis: parsed.data } + : { ok: false, message: parsed.error.issues[0].message }; +} + +function missing(): AnalysisEditResult { + return { ok: false, message: "편집할 분석 항목을 찾을 수 없습니다." }; +} diff --git a/src/features/grammar-analysis-edit/services/textBoundaries.ts b/src/features/grammar-analysis-edit/services/textBoundaries.ts new file mode 100644 index 00000000..529747fe --- /dev/null +++ b/src/features/grammar-analysis-edit/services/textBoundaries.ts @@ -0,0 +1,14 @@ +/** Human-readable word boundaries; raw UTF-16 offsets remain a domain detail. */ +export function getTextBoundaries(text: string) { + const positions = new Set([0, text.length]); + for (const match of text.matchAll(/\S+/gu)) { + positions.add(match.index); + positions.add(match.index + match[0].length); + } + return [...positions] + .sort((a, b) => a - b) + .map((position) => ({ + position, + label: `${text.slice(Math.max(0, position - 24), position)} │ ${text.slice(position, position + 24)}`, + })); +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx new file mode 100644 index 00000000..2d4f5fca --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx @@ -0,0 +1,25 @@ +"use client"; + +import { createContext, useContext, useState } from "react"; +import { useStore } from "zustand"; +import type { StoreApi } from "zustand"; +import type { AnalysisEditorProviderProps, AnalysisEditorState } from "../models/interface"; +import { createAnalysisEditorStore } from "../models/store"; + +const Context = createContext | null>(null); + +/** Remount with a source revision key after a new analysis replaces the source. */ +export function AnalysisEditorProvider({ + initialAnalysis, + onChange, + children, +}: AnalysisEditorProviderProps) { + const [store] = useState(() => createAnalysisEditorStore({ initialAnalysis, onChange })); + return {children}; +} + +export function useAnalysisEditor(selector: (state: AnalysisEditorState) => T): T { + const store = useContext(Context); + if (!store) throw new Error("AnalysisEditorProvider is required"); + return useStore(store, selector); +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisInspector.tsx b/src/features/grammar-analysis-edit/ui/AnalysisInspector.tsx new file mode 100644 index 00000000..d8e42e9e --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisInspector.tsx @@ -0,0 +1,124 @@ +"use client"; + +import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog"; +import { Button } from "@/shared/components/atomics/button/Button"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; +import { ChunkEditor } from "./ChunkEditor"; +import { SyntaxEditor } from "./SyntaxEditor"; +import { ConstructionEditor } from "./ConstructionEditor"; + +export function AnalysisInspector() { + const editing = useAnalysisEditor((state) => state.editing); + const startEditing = useAnalysisEditor((state) => state.startEditing); + const markDirty = useAnalysisEditor((state) => state.markDirty); + const pending = useAnalysisEditor((state) => state.pendingSelection); + const resolveSelection = useAnalysisEditor((state) => state.resolveSelection); + const selectedId = useAnalysisEditor((state) => state.selectedId); + const select = useAnalysisEditor((state) => state.select); + const analysis = useAnalysisEditor((state) => state.analysis); + const edit = useAnalysisEditor((state) => state.edit); + const chunk = analysis.chunks.find((item) => item.id === selectedId); + const syntax = analysis.syntax.find((item) => item.id === selectedId); + const construction = analysis.constructions.find((item) => item.id === selectedId); + const addSyntax = () => { + const id = crypto.randomUUID(); + const result = edit({ + type: "save-syntax", + annotation: { + id, + ranges: [{ start: 0, end: analysis.sourceText.length }], + parentId: null, + role: "other", + label: "새 문법 항목", + explanation: "", + }, + }); + if (result.ok) select(id); + }; + return ( +
+
+

문법과 구문

+ {analysis.syntax.map((item) => ( + + ))} + {analysis.constructions.map((item) => ( + + ))} + +
+ {!editing && selectedId && ( +
+

+ {chunk + ? analysis.sourceText.slice(chunk.range.start, chunk.range.end) + : (syntax?.label ?? construction?.name)} +

+

{chunk?.literalMeaning ?? construction?.meaning}

+

+ {chunk?.explanation ?? syntax?.explanation ?? construction?.explanation} +

+ {syntax && ( +

+ 상위 항목:{" "} + {analysis.syntax.find((item) => item.id === syntax.parentId)?.label ?? "최상위"} +

+ )} + +
+ )} + {editing && ( +
+ + {chunk && ( + + )} + {syntax && } + {construction && } +
+ )} + { + if (!open) resolveSelection(false); + }} + title="적용하지 않은 수정을 버릴까요?" + description="계속 편집하면 현재 입력을 유지합니다." + confirmLabel="수정 버리기" + cancelLabel="계속 편집" + onConfirm={() => resolveSelection(true)} + onCancel={() => resolveSelection(false)} + /> + {!selectedId && ( +

문장 구간 또는 문법 항목을 선택해 주세요.

+ )} +
+ ); +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisSentence.tsx b/src/features/grammar-analysis-edit/ui/AnalysisSentence.tsx new file mode 100644 index 00000000..85705ca6 --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisSentence.tsx @@ -0,0 +1,58 @@ +"use client"; + +import type { AnalysisItemProps } from "../models/interface"; +import { cva } from "class-variance-authority"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +const chunkVariants = cva( + "whitespace-pre-wrap border-b-2 px-1 py-2 text-left text-2xl leading-relaxed outline-none transition-colors focus-visible:ring-2 focus-visible:ring-practice-focus", + { + variants: { + selected: { + true: "border-practice-accent bg-practice-accent/5 text-practice-ink", + false: "border-transparent text-practice-body hover:border-practice-input-line", + }, + }, + }, +); + +function ChunkButton({ id }: AnalysisItemProps) { + const chunk = useAnalysisEditor((state) => state.analysis.chunks.find((item) => item.id === id)); + const source = useAnalysisEditor((state) => state.analysis.sourceText); + const selected = useAnalysisEditor((state) => state.selectedId === id); + const select = useAnalysisEditor((state) => state.select); + if (!chunk) return null; + return ( + + ); +} + +export function AnalysisSentence() { + const chunks = useAnalysisEditor((state) => state.analysis.chunks); + const translation = useAnalysisEditor((state) => state.analysis.naturalTranslation); + return ( +
+
+ {chunks.map((chunk) => ( + + ))} +
+

{translation}

+

+ 구간을 선택하면 아래에서 풀이와 경계를 편집할 수 있습니다. +

+
+ ); +} diff --git a/src/features/grammar-analysis-edit/ui/BoundarySelect.tsx b/src/features/grammar-analysis-edit/ui/BoundarySelect.tsx new file mode 100644 index 00000000..9eb3c544 --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/BoundarySelect.tsx @@ -0,0 +1,42 @@ +"use client"; + +import { useId } from "react"; +import { getTextBoundaries } from "../services/textBoundaries"; +import type { BoundarySelectProps } from "../models/interface"; + +export function BoundarySelect({ + label, + source, + value, + min = 0, + max = source.length, + onChange, + disabled, +}: BoundarySelectProps) { + const id = useId(); + const options = getTextBoundaries(source).filter( + (item) => item.position >= min && item.position <= max, + ); + if (!options.some((item) => item.position === value)) + options.push({ position: value, label: `${source.slice(0, value)} │ ${source.slice(value)}` }); + return ( + + ); +} diff --git a/src/features/grammar-analysis-edit/ui/ChunkEditor.tsx b/src/features/grammar-analysis-edit/ui/ChunkEditor.tsx new file mode 100644 index 00000000..dcf7d10f --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/ChunkEditor.tsx @@ -0,0 +1,132 @@ +"use client"; + +import type { ChunkEditorProps } from "../models/interface"; + +import { useId, useState } from "react"; +import { Input } from "@/shared/components/atomics/input/Input"; +import { Textarea } from "@/shared/components/atomics/textarea/Textarea"; +import { Button } from "@/shared/components/atomics/button/Button"; +import type { AnalysisEdit } from "../models/interface"; +import { getTextBoundaries } from "../services/textBoundaries"; +import { BoundarySelect } from "./BoundarySelect"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +export function ChunkEditor({ chunk }: ChunkEditorProps) { + const id = useId(); + const [meaning, setMeaning] = useState(chunk.literalMeaning); + const [explanation, setExplanation] = useState(chunk.explanation); + const [boundary, setBoundary] = useState(chunk.range.end); + + const [error, setError] = useState(""); + const edit = useAnalysisEditor((state) => state.edit); + const source = useAnalysisEditor((state) => state.analysis.sourceText); + const next = useAnalysisEditor( + (state) => + state.analysis.chunks[state.analysis.chunks.findIndex((item) => item.id === chunk.id) + 1], + ); + const [split, setSplit] = useState( + () => + getTextBoundaries(source).find( + (item) => item.position > chunk.range.start && item.position < chunk.range.end, + )?.position ?? chunk.range.start, + ); + const run = (command: AnalysisEdit) => { + const result = edit([ + { type: "edit-chunk", chunkId: chunk.id, literalMeaning: meaning, explanation }, + command, + ]); + setError(result.ok ? "" : result.message); + }; + return ( +
+

+ {source.slice(chunk.range.start, chunk.range.end)} +

+ +