diff --git a/docs/design/echo/grammar-practice-20261005/analysis-reading-review.md b/docs/design/echo/grammar-practice-20261005/analysis-reading-review.md new file mode 100644 index 00000000..1e6003d2 --- /dev/null +++ b/docs/design/echo/grammar-practice-20261005/analysis-reading-review.md @@ -0,0 +1,51 @@ +# 분석 읽기 화면 보완 — #150 / PR #163 + +## 기본 동작 + +AI 분석 결과의 의미 덩어리를 그대로 표시한다. 사용자가 구간을 직접 나누는 것을 등록의 필수 단계로 요구하지 않는다. 구간을 누르면 문장 아래에 직독직해, 해당 문장 성분, 설명, 관련 구문을 표시한다. 문법 성분과 구문은 기존 분석 데이터에서 가져오며 UI가 새로 추론하지 않는다. + +선택한 구간은 붉은 강조 대신 흰 블록, 중립색 테두리, 그림자와 작은 상승 효과로 구분한다. 풀이는 기존 Echo 등장 애니메이션을 사용한다. `prefers-reduced-motion`에서는 이동과 등장 애니메이션을 생략한다. 키보드 포커스는 선택 상태와 별개로 표시한다. + +## 수정 흐름 + +`분석 수정`을 누른 경우에만 구간·계층 편집을 표시한다. `읽기로 돌아가기`와 Escape로 읽기 화면으로 복귀한다. 적용하지 않은 수정이 있으면 공통 ConfirmDialog로 계속 편집/수정 버리기를 선택한다. 원문 보존, 잘못된 계층과 경계의 원자적 거절, 실패 후 입력 보존은 유지한다. + +읽기 표시, 도구 모음, 편집 항목 탐색, 수정 입력, 이탈 확인을 분리했다. 선택/모드 전환/편집 이벤트는 features의 store가 담당하며 각 chunk는 필요한 상태만 구독한다. 스타일은 JSX 내 Tailwind와 CVA를 사용한다. 경계 표기의 인위적인 공백을 제거했고 문장 끝에서 빈 구간을 추가하지 못하게 했다. + +## 검증 + +- 전체 Jest: 124 suites / 451 tests 통과. +- Chromium Storybook: 6개 통과(기본, 선택 풀이, 경계, 계층 오류, 비연속 구문, 읽기로 복귀). +- TypeScript, 변경 범위 ESLint, Next.js production build 통과. +- 실제 브라우저의 데스크톱과 390px 읽기 화면 확인. 모바일 읽기 화면의 contentWidth와 viewportWidth 모두 390px. +- 읽기/수정 전환, Escape 포커스, 미적용 입력 이탈 확인은 자동 테스트로 검증. + +현재 범위는 독립 컴포넌트/Storybook이다. AI 서비스와 저장 및 실제 등록 페이지 연결은 별도 이슈이며 이 PR에서 연결했다고 간주하지 않는다. 미리보기 데이터는 fixture다. + + +## 편집 책임 분리 — 2026-10-06 + +문자열 action type을 해석하던 `editAnalysis` 분기를 제거하고 `EditAnalysisService`의 동작별 메서드로 분리했다. 이벤트는 `edit(service => service.moveBoundary(chunkId, end))`처럼 필요한 동작을 직접 지정한다. + +- `EditAnalysisService`: 변경하지 않는 입력 스냅샷을 바탕으로 경계 이동·나누기·합치기·풀이 수정·문법/구문 저장 및 삭제를 각각 처리한다. +- `validateAnalysisCandidate`: 도메인 검증과 재검토 상태 전환을 공통 적용한다. +- `applyAnalysisEdits`: 이전 편집 결과를 다음 동작에 전달하고 첫 실패에서 중단한다. 중간 결과를 store에 쓰지 않는다. +- store: 전체 성공 시에만 분석·선택·dirty 상태를 반영하고 소비자에게 한 번 알린다. + +새 편집을 추가해도 기존 메서드, 배치 적용 루프, store의 성공 반영 경로에 편집 종류 분기를 추가하지 않는다. 편집 계약과 UI props 계약은 별도 모델 파일로 분리했다. 인라인 타입 import도 상단 `import type`으로 정리했다. + +회귀 검증: 전체 Jest 124 suites / 456 tests, Chromium Storybook 6개, TypeScript와 변경 범위 ESLint 통과. 배치 실패 시 입력·선택 보존 및 후속 동작 중단, 성공 시 앞선 편집 보존과 단일 반영, 각 편집의 검증·원문 보존을 확인했다. 이번 변경에는 화면 배치나 스타일 변경이 없어 이전 시각 검토를 유지하고 Storybook 상호작용을 다시 검증했다. + +## PR 댓글 반영과 유지 근거 — 2026-10-06 + +- **변환 함수**: `models/converters/convertAnalysisToChunkReading.ts`로 옮겼다. 저장된 분석을 읽기용 모델로 변환하므로 범용 utils가 아닌 converter로 명명한다. 문법 추론을 추가하지 않는다. +- **store 생성과 Provider**: 테스트 전용 주입이 아니다. 각 에디터가 받은 초기 분석과 선택·수정 모드·미적용 입력을 해당 인스턴스 수명에 묶는다. 전역 singleton의 초기화/정리 순서에 의존하지 않는다. Context에는 고정된 vanilla store 참조를 전달하고, 상태 변화는 Zustand selector로 구독한다. 이는 [Zustand의 props 초기화 지침](https://zustand.docs.pmnd.rs/learn/guides/initialize-state-with-props)과 같은 패턴이다. 현재 실제 페이지에 여러 에디터가 배치되어 있다는 의미는 아니다. +- **초기값과 콜백**: `initialAnalysis`는 마운트 시 초기값이다. 다른 문서/분석으로 교체하려면 소비자가 key를 바꾼다. 부모의 재렌더링은 편집 상태를 초기화하지 않으며, `onChange`가 바뀌면 최신 콜백으로 알리도록 수정했다. 초기 콜백을 store가 계속 보관하던 문제를 해결한다. +- **입력 책임**: 풀이 필드, 경계 미리보기, 나누기 미리보기를 분리했다. 경계와 나누기는 각각의 컴포넌트에서 필요한 state만 관리한다. 풀이 텍스트는 적용 전까지 DOM 입력값으로 보존하고 적용할 때 FormData로 읽는다. 타이핑마다 텍스트를 React state에도 복제하거나 상위 입력 묶음을 다시 렌더링할 이유가 없기 때문이다. 공통 적용 hook은 현재 풀이와 구조 변경을 기존 원자적 편집 흐름에 전달하고 UI용 오류를 관리한다. +- **클라이언트 경계**: 조합 컴포넌트에서 hooks와 이벤트를 제거하고 읽기/수정 분기 및 키보드 처리를 작은 client component로 옮겼다. 파일을 나눴다고 client parent에서 가져온 하위 컴포넌트가 Server Component가 되는 것은 아니다. 이번 변경의 검증 대상은 상태 구독과 렌더링 책임이며, 번들 크기나 SSR 개선을 주장하지 않는다. +- **키보드 핸들러**: JSX 밖 이름 있는 함수로 분리했다. 이벤트가 발생할 때 `store.getState()`로 읽으므로 키보드 처리만을 위한 상태 구독이 없다. 직접 DOM에 전달하고 memo 자식이나 effect 의존성으로 사용하지 않으므로 `useCallback`을 추가하지 않았다. 함수 생성 자체가 렌더링을 발생시키는 것은 아니다. [React useCallback 문서](https://react.dev/reference/react/useCallback)의 참조 안정성이 필요한 경우와 구분한다. +- **포커스 탐색과 확인창 예외**: 현재 에디터의 DOM 안에서 선택 버튼 또는 읽기 복귀 버튼을 찾아 포커스를 복원한다. 별도 DOM ref 대신 이벤트의 `currentTarget`을 사용한다. 포털 이벤트도 React 트리로 전파되므로 alertdialog 내부 Escape는 Radix에 맡겨 편집기와 확인창이 동시에 닫히지 않도록 한다. + +회귀 검증: 전체 Jest 125 suites / 462 tests 통과. 두 에디터의 선택·수정 격리, 부모 재렌더링 시 입력 보존 및 최신 콜백, 문서 key 변경, 확인창 Escape, 유효성 실패 후 입력 보존, 풀이와 경계의 단일 반영을 확인했다. Profiler로 풀이 입력 시 컨트롤들이 다시 commit되지 않으며 경계 미리보기 변경은 해당 컨트롤에서만 commit됨을 검증했다. 테스트 관찰 래퍼는 실제 컴포넌트를 실행한다. + +Chromium Storybook 10개 통과: 기존 6개와 풀이 입력·경계 미리보기/적용·마지막 구간 비활성·나누기 미리보기/적용 4개. TypeScript, 변경 범위 ESLint, Next.js production build 통과. 화면 배치·테마 변경은 없으며 실제 페이지 연결 범위도 동일하다. diff --git a/src/_storybook/features/grammar-analysis-edit/ChunkBoundaryEditor.stories.tsx b/src/_storybook/features/grammar-analysis-edit/ChunkBoundaryEditor.stories.tsx new file mode 100644 index 00000000..fdf914a2 --- /dev/null +++ b/src/_storybook/features/grammar-analysis-edit/ChunkBoundaryEditor.stories.tsx @@ -0,0 +1,31 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, fn, userEvent, within } from "storybook/test"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; +import { ChunkBoundaryEditor } from "@/features/grammar-analysis-edit/ui/ChunkBoundaryEditor"; + +const analysis = createGrammarAnalysis(); +const meta = { + title: "features/grammar-analysis-edit/ChunkBoundaryEditor", + component: ChunkBoundaryEditor, + args: { chunk: analysis.chunks[0], source: analysis.sourceText, nextEnd: 7, onApply: fn() }, +} satisfies Meta; +export default meta; +type Story = StoryObj; +export const PreviewAndApply: Story = { + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + await userEvent.selectOptions(canvas.getByLabelText("다음 구간과의 경계"), "3"); + await expect(canvas.getByText("She", { selector: "p" })).toBeVisible(); + await expect(args.onApply).not.toHaveBeenCalled(); + await userEvent.click(canvas.getByRole("button", { name: "경계 적용" })); + await expect(args.onApply).toHaveBeenCalledOnce(); + }, +}; +export const LastChunk: Story = { + args: { chunk: analysis.chunks[2], nextEnd: undefined }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByLabelText("다음 구간과의 경계")).toBeDisabled(); + await expect(canvas.getByRole("button", { name: "경계 적용" })).toBeDisabled(); + }, +}; diff --git a/src/_storybook/features/grammar-analysis-edit/ChunkExplanationFields.stories.tsx b/src/_storybook/features/grammar-analysis-edit/ChunkExplanationFields.stories.tsx new file mode 100644 index 00000000..acddb1a4 --- /dev/null +++ b/src/_storybook/features/grammar-analysis-edit/ChunkExplanationFields.stories.tsx @@ -0,0 +1,30 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, userEvent, within } from "storybook/test"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; +import { ChunkExplanationFields } from "@/features/grammar-analysis-edit/ui/ChunkExplanationFields"; + +const meta = { + title: "features/grammar-analysis-edit/ChunkExplanationFields", + component: ChunkExplanationFields, + args: { chunk: createGrammarAnalysis().chunks[0] }, + decorators: [ + (Story) => ( +
+ +
+ ), + ], +} satisfies Meta; +export default meta; +type Story = StoryObj; +export const EditExplanation: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const meaning = canvas.getByLabelText("직독직해"); + await expect(meaning).toHaveValue("그녀는"); + await userEvent.clear(meaning); + await userEvent.type(meaning, "그녀가"); + await expect(meaning).toHaveValue("그녀가"); + await expect(canvas.getByLabelText("구간 설명")).toHaveValue("주어입니다."); + }, +}; diff --git a/src/_storybook/features/grammar-analysis-edit/ChunkSplitEditor.stories.tsx b/src/_storybook/features/grammar-analysis-edit/ChunkSplitEditor.stories.tsx new file mode 100644 index 00000000..4170de15 --- /dev/null +++ b/src/_storybook/features/grammar-analysis-edit/ChunkSplitEditor.stories.tsx @@ -0,0 +1,25 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, fn, userEvent, within } from "storybook/test"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; +import { ChunkSplitEditor } from "@/features/grammar-analysis-edit/ui/ChunkSplitEditor"; + +const analysis = createGrammarAnalysis(); +const meta = { + title: "features/grammar-analysis-edit/ChunkSplitEditor", + component: ChunkSplitEditor, + args: { chunk: analysis.chunks[2], source: analysis.sourceText, onApply: fn() }, +} satisfies Meta; +export default meta; +type Story = StoryObj; +export const PreviewAndSplit: Story = { + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + await userEvent.selectOptions(canvas.getByLabelText("구간 나누기 위치"), "21"); + await expect( + canvas.getByText("not a teacher | but a doctor.", { selector: "p" }), + ).toBeVisible(); + await expect(args.onApply).not.toHaveBeenCalled(); + await userEvent.click(canvas.getByRole("button", { name: "나누기" })); + await expect(args.onApply).toHaveBeenCalledOnce(); + }, +}; 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..633985ad --- /dev/null +++ b/src/_storybook/features/grammar-analysis-edit/GrammarAnalysisEditor.stories.tsx @@ -0,0 +1,73 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, fn, userEvent, waitFor, 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 waitFor(() => expect(canvas.getByRole("heading", { name: "그녀는" })).toBeVisible()); + await expect(canvas.queryByLabelText("직독직해")).not.toBeInTheDocument(); + }, +}; +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: "분석 수정" })); + await userEvent.click(canvas.getByRole("button", { name: "not A but B" })); + await expect(canvas.getByLabelText("시작 1")).toHaveValue("7"); + await expect(canvas.getByLabelText("시작 2")).toHaveValue("21"); + }, +}; + +export const ReturnToReading: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "not a teacher but a doctor." })); + await userEvent.click(canvas.getByRole("button", { name: "분석 수정" })); + await userEvent.click(canvas.getByRole("button", { name: "절" })); + await userEvent.click(canvas.getByRole("button", { name: "읽기로 돌아가기" })); + await expect( + canvas.getByRole("button", { name: "not a teacher but a doctor." }), + ).toHaveAttribute("aria-pressed", "true"); + await expect(canvas.queryByLabelText("상위 항목")).not.toBeInTheDocument(); + }, +}; diff --git a/src/_tests/features/grammar-analysis-edit/ChunkEditorRenderBoundaries.test.tsx b/src/_tests/features/grammar-analysis-edit/ChunkEditorRenderBoundaries.test.tsx new file mode 100644 index 00000000..799d10a5 --- /dev/null +++ b/src/_tests/features/grammar-analysis-edit/ChunkEditorRenderBoundaries.test.tsx @@ -0,0 +1,72 @@ +import { Profiler } from "react"; +import type * as FieldsModule from "@/features/grammar-analysis-edit/ui/ChunkExplanationFields"; +import type * as BoundaryModule from "@/features/grammar-analysis-edit/ui/ChunkBoundaryEditor"; +import type * as SplitModule from "@/features/grammar-analysis-edit/ui/ChunkSplitEditor"; +import { expect, it, jest } from "@jest/globals"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; +import { AnalysisEditorProvider } from "@/features/grammar-analysis-edit/ui/AnalysisEditorProvider"; +import type * as ChunkEditorModule from "@/features/grammar-analysis-edit/ui/ChunkEditor"; + +const commits = { fields: jest.fn(), boundary: jest.fn(), split: jest.fn() }; +// 실제 컴포넌트를 그대로 실행하고 Profiler로 commit 범위만 관찰한다. +jest.mock("@/features/grammar-analysis-edit/ui/ChunkExplanationFields", () => { + const { ChunkExplanationFields: Fields } = jest.requireActual( + "@/features/grammar-analysis-edit/ui/ChunkExplanationFields", + ); + return { + ChunkExplanationFields: (props: React.ComponentProps) => ( + + + + ), + }; +}); +jest.mock("@/features/grammar-analysis-edit/ui/ChunkBoundaryEditor", () => { + const { ChunkBoundaryEditor: Boundary } = jest.requireActual( + "@/features/grammar-analysis-edit/ui/ChunkBoundaryEditor", + ); + return { + ChunkBoundaryEditor: (props: React.ComponentProps) => ( + + + + ), + }; +}); +jest.mock("@/features/grammar-analysis-edit/ui/ChunkSplitEditor", () => { + const { ChunkSplitEditor: Split } = jest.requireActual( + "@/features/grammar-analysis-edit/ui/ChunkSplitEditor", + ); + return { + ChunkSplitEditor: (props: React.ComponentProps) => ( + + + + ), + }; +}); + +it("does not render sibling controls while typing or changing a boundary preview", () => { + // next/jest의 SWC 변환에서는 가져온 jest.mock이 hoist되지 않으므로 관찰 래퍼 등록 후 읽는다. + const { ChunkEditor } = jest.requireActual( + "@/features/grammar-analysis-edit/ui/ChunkEditor", + ); + const analysis = createGrammarAnalysis(); + render( + + + , + ); + Object.values(commits).forEach((spy) => { + expect(spy).toHaveBeenCalled(); + spy.mockClear(); + }); + fireEvent.change(screen.getByLabelText("직독직해"), { target: { value: "새 뜻" } }); + expect(screen.getByLabelText("직독직해")).toHaveValue("새 뜻"); + Object.values(commits).forEach((spy) => expect(spy).not.toHaveBeenCalled()); + fireEvent.change(screen.getByLabelText("다음 구간과의 경계"), { target: { value: "3" } }); + expect(commits.boundary).toHaveBeenCalled(); + expect(commits.fields).not.toHaveBeenCalled(); + expect(commits.split).not.toHaveBeenCalled(); +}); 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..721257e8 --- /dev/null +++ b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx @@ -0,0 +1,202 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import { fireEvent, render, screen, within } 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(); +}); + +it("shows AI chunks for reading and keeps correction controls behind edit mode", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + render(); + expect(screen.queryByRole("button", { name: "절" })).not.toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "She" })); + expect(screen.getByRole("heading", { name: "그녀는" })).toBeInTheDocument(); + expect(screen.getByText("주어")).toBeInTheDocument(); + expect(screen.queryByLabelText("직독직해")).not.toBeInTheDocument(); + await user.keyboard("{Escape}"); + expect(screen.getByRole("button", { name: "She" })).toHaveFocus(); + expect(screen.getByRole("button", { name: "She" })).toHaveAttribute("aria-pressed", "false"); + expect(onChange).not.toHaveBeenCalled(); +}); + +it("guards returning to reading and restores the selected chunk after discarding edits", 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.type(screen.getByLabelText("직독직해"), " 수정"); + await user.keyboard("{Escape}"); + 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.getByRole("heading", { name: "그녀는" })).toBeInTheDocument(); + expect(screen.queryByLabelText("직독직해")).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "절" })).not.toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); +}); + +it("isolates selection and edits between mounted editors", async () => { + const user = userEvent.setup(); + const firstChange = jest.fn(); + const secondChange = jest.fn(); + render( + <> +
+ +
+
+ +
+ , + ); + const first = within(screen.getByRole("region", { name: "첫 번째 노트" })); + const second = within(screen.getByRole("region", { name: "두 번째 노트" })); + await user.click(first.getByRole("button", { name: "She" })); + expect(second.getByRole("button", { name: "She" })).toHaveAttribute("aria-pressed", "false"); + await user.click(first.getByRole("button", { name: "분석 수정" })); + await user.type(first.getByLabelText("직독직해"), " 수정"); + await user.click(first.getByRole("button", { name: "풀이 적용" })); + expect(firstChange).toHaveBeenCalledTimes(1); + expect(secondChange).not.toHaveBeenCalled(); + expect(second.queryByLabelText("직독직해")).not.toBeInTheDocument(); +}); + +it("preserves drafts on parent rerender and notifies the current callback", async () => { + const user = userEvent.setup(); + const original = jest.fn(); + const current = jest.fn(); + const { rerender } = render( + , + ); + await user.click(screen.getByRole("button", { name: "분석 수정" })); + await user.type(screen.getByLabelText("직독직해"), " 수정"); + rerender(); + expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); + await user.click(screen.getByRole("button", { name: "풀이 적용" })); + expect(original).not.toHaveBeenCalled(); + expect(current).toHaveBeenCalledTimes(1); +}); + +it("starts a fresh editor when the document key changes", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + const { rerender } = render( + , + ); + await user.click(screen.getByRole("button", { name: "분석 수정" })); + await user.type(screen.getByLabelText("직독직해"), " 수정"); + const next = createGrammarAnalysis(); + rerender( + ({ ...c, literalMeaning: "새 분석" })), + }} + onChange={onChange} + />, + ); + expect(screen.queryByLabelText("직독직해")).not.toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "She" })); + expect(screen.getByRole("heading", { name: "새 분석" })).toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); +}); + +it("keeps the editor draft when Escape dismisses the confirmation dialog", async () => { + const user = userEvent.setup(); + render(); + 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.keyboard("{Escape}"); + expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument(); + expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); +}); + +it("applies current text with a boundary edit and keeps input after validation failure", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + render(); + await user.click(screen.getByRole("button", { name: "분석 수정" })); + const input = screen.getByLabelText("직독직해"); + // 도메인 길이 제한을 넘는 입력에도 다른 편집 후보를 반영하지 않는다. + fireEvent.change(input, { target: { value: "x".repeat(4001) } }); + await user.selectOptions(screen.getByLabelText("다음 구간과의 경계"), "3"); + await user.click(screen.getByRole("button", { name: "경계 적용" })); + expect(screen.getByRole("alert")).toBeInTheDocument(); + expect(input).toHaveValue("x".repeat(4001)); + expect(onChange).not.toHaveBeenCalled(); + await user.clear(input); + await user.type(input, "고친 뜻"); + await user.click(screen.getByRole("button", { name: "경계 적용" })); + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange).toHaveBeenLastCalledWith( + expect.objectContaining({ + chunks: expect.arrayContaining([ + expect.objectContaining({ + id: "c1", + literalMeaning: "고친 뜻", + range: { start: 0, end: 3 }, + }), + ]), + }), + ); +}); diff --git a/src/_tests/features/grammar-analysis-edit/chunkReading.test.ts b/src/_tests/features/grammar-analysis-edit/chunkReading.test.ts new file mode 100644 index 00000000..3dc9020b --- /dev/null +++ b/src/_tests/features/grammar-analysis-edit/chunkReading.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "@jest/globals"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; +import { convertAnalysisToChunkReading } from "@/features/grammar-analysis-edit/models/converters/convertAnalysisToChunkReading"; + +describe("reading existing analysis", () => { + it("shows the specific role without the enclosing generic clause", () => { + expect(convertAnalysisToChunkReading(createGrammarAnalysis(), "c1")).toMatchObject({ + text: "She", + meaning: "그녀는", + roles: ["주어"], + constructions: [], + }); + }); + it("associates discontinuous constructions with their overlapping chunk", () => { + const analysis = createGrammarAnalysis(); + expect(convertAnalysisToChunkReading(analysis, "c3")?.constructions).toEqual( + analysis.constructions, + ); + expect(convertAnalysisToChunkReading(analysis, "c2")?.constructions).toEqual([]); + }); + it("returns no reading for a deleted or non-chunk selection", () => { + expect(convertAnalysisToChunkReading(createGrammarAnalysis(), "missing")).toBeNull(); + expect(convertAnalysisToChunkReading(createGrammarAnalysis(), "clause")).toBeNull(); + }); +}); 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..658ee212 --- /dev/null +++ b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; +import { EditAnalysisService } from "@/features/grammar-analysis-edit/services/EditAnalysisService"; +import type { AnalysisEdit } from "@/features/grammar-analysis-edit/models/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 = new EditAnalysisService(source).moveBoundary("c1", 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(new EditAnalysisService(source).moveBoundary("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 = new EditAnalysisService(source).splitChunk("c3", 21, "c4"); + if (!split.ok) throw new Error(split.message); + expect(split.analysis.chunks).toHaveLength(4); + const merged = new EditAnalysisService(split.analysis).mergeNext("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(new EditAnalysisService(a).mergeNext("missing").ok).toBe(false); + expect(new EditAnalysisService(a).splitChunk("c3", 21, "s").ok).toBe(false); + }); + it("allows reparenting a child to root and rejects deleting its parent while attached", () => { + const a = createGrammarAnalysis(); + expect(new EditAnalysisService(a).deleteSyntax("clause").ok).toBe(false); + const result = new EditAnalysisService(a).saveSyntax({ ...a.syntax[1], parentId: null }); + expect(result.ok).toBe(true); + }); + it("rejects reparenting into a descendant", () => { + const a = createGrammarAnalysis(); + expect(new EditAnalysisService(a).saveSyntax({ ...a.syntax[0], parentId: "s" }).ok).toBe(false); + }); + it("supports discontinuous construction boundary edits", () => { + const a = createGrammarAnalysis(); + const result = new EditAnalysisService(a).saveConstruction({ + ...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((service) => service.moveBoundary("c1", -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([ + (service) => service.editChunk("c1", { literalMeaning: "수정한 뜻", explanation: "" }), + (service) => service.moveBoundary("c1", -1), + ]); + expect(result.ok).toBe(false); + expect(store.getState().analysis).toBe(before); + expect(onChange).not.toHaveBeenCalled(); +}); + +it("commits a successful batch once, preserving the first edit in the next candidate", () => { + const onChange = jest.fn(); + const store = createAnalysisEditorStore({ initialAnalysis: createGrammarAnalysis(), onChange }); + store.getState().select("c1"); + store.getState().startEditing(); + store.getState().markDirty(); + const result = store + .getState() + .edit([ + (service) => service.editChunk("c1", { literalMeaning: "수정한 뜻", explanation: "설명" }), + (service) => service.moveBoundary("c1", 3), + ]); + expect(result.ok).toBe(true); + expect(store.getState().analysis.chunks[0]).toMatchObject({ + literalMeaning: "수정한 뜻", + explanation: "설명", + range: { start: 0, end: 3 }, + }); + expect(store.getState().dirty).toBe(false); + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange).toHaveBeenCalledWith(store.getState().analysis); +}); + +it("keeps dirty input and selection and skips later operations when a batch fails", () => { + const onChange = jest.fn(); + const store = createAnalysisEditorStore({ initialAnalysis: createGrammarAnalysis(), onChange }); + store.getState().select("c1"); + store.getState().startEditing(); + store.getState().markDirty(); + const before = store.getState().analysis; + const later = jest.fn(); + const result = store + .getState() + .edit([ + (service) => service.editChunk("c1", { literalMeaning: "수정", explanation: "" }), + (service) => service.moveBoundary("c1", -1), + later, + ]); + expect(result.ok).toBe(false); + expect(store.getState()).toMatchObject({ selectedId: "c1", dirty: true, editing: true }); + expect(store.getState().analysis).toBe(before); + expect(later).not.toHaveBeenCalled(); + expect(onChange).not.toHaveBeenCalled(); +}); + +it("adds, updates and deletes annotations without changing the input snapshot", () => { + const source = createGrammarAnalysis(); + const before = JSON.stringify(source); + const service = new EditAnalysisService(source); + const added = service.saveSyntax({ ...source.syntax[1], id: "new-subject" }); + if (!added.ok) throw new Error(added.message); + expect(added.analysis.syntax).toHaveLength(source.syntax.length + 1); + const deleted = new EditAnalysisService(added.analysis).deleteSyntax("new-subject"); + if (!deleted.ok) throw new Error(deleted.message); + expect(deleted.analysis.syntax).toEqual(source.syntax); + const construction = service.saveConstruction({ ...source.constructions[0], id: "new-contrast" }); + if (!construction.ok) throw new Error(construction.message); + const updated = new EditAnalysisService(construction.analysis).saveConstruction({ + ...source.constructions[0], + id: "new-contrast", + meaning: "수정된 뜻", + }); + if (!updated.ok) throw new Error(updated.message); + expect(updated.analysis.constructions).toHaveLength(source.constructions.length + 1); + expect(updated.analysis.constructions.find((item) => item.id === "new-contrast")?.meaning).toBe( + "수정된 뜻", + ); + const removed = new EditAnalysisService(updated.analysis).deleteConstruction("new-contrast"); + if (!removed.ok) throw new Error(removed.message); + expect(removed.analysis.constructions).toEqual(source.constructions); + expect(JSON.stringify(source)).toBe(before); +}); + +it("validates every edit method and rejects unknown targets without changing the source", () => { + const source = createGrammarAnalysis(); + const service = new EditAnalysisService(source); + const before = JSON.stringify(source); + const invalid: AnalysisEdit[] = [ + (s) => s.editChunk("missing", { literalMeaning: "뜻", explanation: "" }), + (s) => s.editChunk("c1", { literalMeaning: "x".repeat(4001), explanation: "" }), + (s) => s.moveBoundary("missing", 3), + (s) => s.moveBoundary("c3", 20), + (s) => s.splitChunk("missing", 3, "new"), + (s) => s.splitChunk("c1", 0, "new"), + (s) => s.mergeNext("c3"), + (s) => s.deleteSyntax("missing"), + (s) => s.deleteConstruction("missing"), + (s) => s.saveConstruction({ ...source.constructions[0], id: source.chunks[0].id }), + ]; + for (const operation of invalid) expect(operation(service).ok).toBe(false); + expect(JSON.stringify(source)).toBe(before); +}); + +it("updates only explanation fields even when the supplied object contains chunk identity", () => { + const source = createGrammarAnalysis(); + const result = new EditAnalysisService(source).editChunk("c1", { + ...source.chunks[1], + literalMeaning: "수정한 뜻", + }); + if (!result.ok) throw new Error(result.message); + expect(result.analysis.chunks[0]).toMatchObject({ + id: "c1", + range: source.chunks[0].range, + literalMeaning: "수정한 뜻", + }); + expect(result.analysis.sourceText).toBe(source.sourceText); +}); 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..68577af7 --- /dev/null +++ b/src/features/grammar-analysis-edit/index.ts @@ -0,0 +1,4 @@ +export { GrammarAnalysisEditor } from "./ui/GrammarAnalysisEditor"; +export { EditAnalysisService } from "./services/EditAnalysisService"; +export type { AnalysisEdit, AnalysisEditResult } from "./models/editAnalysis"; +export type { AnalysisEditorProps } from "./models/interface"; diff --git a/src/features/grammar-analysis-edit/models/converters/convertAnalysisToChunkReading.ts b/src/features/grammar-analysis-edit/models/converters/convertAnalysisToChunkReading.ts new file mode 100644 index 00000000..a2201be1 --- /dev/null +++ b/src/features/grammar-analysis-edit/models/converters/convertAnalysisToChunkReading.ts @@ -0,0 +1,22 @@ +import type { SentenceAnalysis } from "@/entities/grammar-note"; +import type { ChunkReading } from "../interface"; + +/** 저장된 분석을 선택 구간의 읽기 UI 모델로 변환한다. 문법을 새로 추론하지 않는다. */ +export function convertAnalysisToChunkReading( + analysis: SentenceAnalysis, + id: string, +): ChunkReading | null { + const chunk = analysis.chunks.find((item) => item.id === id); + if (!chunk) return null; + const overlaps = (range: { start: number; end: number }) => + range.start < chunk.range.end && chunk.range.start < range.end; + const syntax = analysis.syntax.filter((item) => item.ranges.some(overlaps)); + const specific = syntax.filter((item) => item.role !== "other"); + return { + text: analysis.sourceText.slice(chunk.range.start, chunk.range.end).trim(), + meaning: chunk.literalMeaning, + explanation: chunk.explanation, + roles: [...new Set((specific.length ? specific : syntax).map((item) => item.label))], + constructions: analysis.constructions.filter((item) => item.ranges.some(overlaps)), + }; +} diff --git a/src/features/grammar-analysis-edit/models/editAnalysis.ts b/src/features/grammar-analysis-edit/models/editAnalysis.ts new file mode 100644 index 00000000..e584b8af --- /dev/null +++ b/src/features/grammar-analysis-edit/models/editAnalysis.ts @@ -0,0 +1,26 @@ +import type { + ConstructionAnnotation, + SentenceAnalysis, + SentenceChunk, + SyntaxAnnotation, +} from "@/entities/grammar-note"; + +export type AnalysisEditResult = + | { ok: true; analysis: SentenceAnalysis } + | { ok: false; message: string }; + +export type ChunkExplanation = Pick; + +export interface AnalysisEditing { + editChunk(chunkId: string, explanation: ChunkExplanation): AnalysisEditResult; + moveBoundary(chunkId: string, end: number): AnalysisEditResult; + splitChunk(chunkId: string, offset: number, newId: string): AnalysisEditResult; + mergeNext(chunkId: string): AnalysisEditResult; + saveSyntax(annotation: SyntaxAnnotation): AnalysisEditResult; + deleteSyntax(id: string): AnalysisEditResult; + saveConstruction(annotation: ConstructionAnnotation): AnalysisEditResult; + deleteConstruction(id: string): AnalysisEditResult; +} + +/** 이벤트가 필요한 메서드를 직접 선택한다. 공통 적용 경로는 편집 종류를 해석하지 않는다. */ +export type AnalysisEdit = (service: AnalysisEditing) => AnalysisEditResult; 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..88c301e5 --- /dev/null +++ b/src/features/grammar-analysis-edit/models/interface.ts @@ -0,0 +1,86 @@ +import type { ReactNode } from "react"; +import type { + ConstructionAnnotation, + SentenceAnalysis, + SentenceChunk, + TextRange, + SyntaxAnnotation, +} from "@/entities/grammar-note"; + +import type { AnalysisEdit, AnalysisEditResult } from "./editAnalysis"; + +export interface AnalysisEditorState { + readonly analysis: SentenceAnalysis; + readonly selectedId: string | null; + readonly editing: boolean; + readonly dirty: boolean; + readonly pendingSelection: { id: string | null; editing: boolean } | null; + readonly readingId: string | null; + startEditing: () => void; + finishEditing: () => void; + addSyntax: () => AnalysisEditResult; + 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: SentenceChunk; +} +export interface SyntaxEditorProps { + annotation: SyntaxAnnotation; +} +export interface ConstructionEditorProps { + annotation: ConstructionAnnotation; +} +export interface RangeFieldsProps { + ranges: readonly TextRange[]; + source: string; + onChange: (ranges: TextRange[]) => void; +} + +export interface BoundarySelectProps { + label: string; + source: string; + value: number; + min?: number; + max?: number; + disabled?: boolean; + onChange: (position: number) => void; +} + +export interface ChunkReading { + readonly text: string; + readonly meaning: string; + readonly explanation: string; + readonly roles: readonly string[]; + readonly constructions: readonly ConstructionAnnotation[]; +} + +export interface AnalysisKeyboardBoundaryProps { + children: ReactNode; +} + +export interface ChunkBoundaryEditorProps extends ChunkEditorProps { + source: string; + nextEnd?: number; + onApply: (edit: AnalysisEdit) => void; +} + +export interface ChunkSplitEditorProps extends ChunkEditorProps { + source: string; + onApply: (edit: AnalysisEdit) => 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..61d6126a --- /dev/null +++ b/src/features/grammar-analysis-edit/models/store.ts @@ -0,0 +1,86 @@ +import { createStore } from "zustand/vanilla"; +import { sentenceAnalysisSchema } from "@/entities/grammar-note"; +import type { AnalysisEditorProps, AnalysisEditorState } from "./interface"; +import { applyAnalysisEdits } from "../services/applyAnalysisEdits"; + +/** 에디터 수명에 맞춰 상태를 생성한다. onChange는 성공한 편집을 상위 문서에 전달한다. */ +export function createAnalysisEditorStore({ initialAnalysis, onChange }: AnalysisEditorProps) { + return createStore((set, get) => ({ + analysis: sentenceAnalysisSchema.parse(initialAnalysis), + selectedId: null, + readingId: null, + editing: false, + dirty: false, + pendingSelection: null, + startEditing: () => + set({ editing: true, selectedId: get().selectedId ?? get().analysis.chunks[0].id }), + finishEditing: () => { + const state = get(); + const id = state.analysis.chunks.some((chunk) => chunk.id === state.readingId) + ? state.readingId + : null; + if (state.dirty) set({ pendingSelection: { id, editing: false } }); + else set({ selectedId: id, editing: false }); + }, + addSyntax: () => { + if (get().dirty) return { ok: false, message: "현재 수정을 먼저 적용해 주세요." }; + const id = crypto.randomUUID(); + const result = get().edit((service) => + service.saveSyntax({ + id, + ranges: [{ start: 0, end: get().analysis.sourceText.length }], + parentId: null, + role: "other", + label: "새 문법 항목", + explanation: "", + }), + ); + if (result.ok) set({ selectedId: id, editing: true }); + return result; + }, + markDirty: () => { + if (get().editing) set({ dirty: true }); + }, + resolveSelection: (discard) => { + const pending = get().pendingSelection; + if (discard && pending) + set({ + selectedId: pending.id, + editing: pending.editing, + dirty: false, + readingId: get().analysis.chunks.some((chunk) => chunk.id === pending.id) + ? pending.id + : get().readingId, + }); + set({ pendingSelection: null }); + }, + select: (selectedId) => { + if (get().dirty) set({ pendingSelection: { id: selectedId, editing: get().editing } }); + else + set({ + selectedId, + readingId: get().analysis.chunks.some((chunk) => chunk.id === selectedId) + ? selectedId + : get().readingId, + }); + }, + edit: (command) => { + const result = applyAnalysisEdits(get().analysis, command); + 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/EditAnalysisService.ts b/src/features/grammar-analysis-edit/services/EditAnalysisService.ts new file mode 100644 index 00000000..ffdf42af --- /dev/null +++ b/src/features/grammar-analysis-edit/services/EditAnalysisService.ts @@ -0,0 +1,103 @@ +import type { + ConstructionAnnotation, + SentenceAnalysis, + SyntaxAnnotation, +} from "@/entities/grammar-note"; +import type { AnalysisEditing, AnalysisEditResult, ChunkExplanation } from "../models/editAnalysis"; +import { validateAnalysisCandidate } from "./validateAnalysisCandidate"; + +/** 입력 스냅샷은 변경하지 않고, 각 메서드가 자신의 편집 후보만 만든다. */ +export class EditAnalysisService implements AnalysisEditing { + constructor(private readonly analysis: SentenceAnalysis) {} + + editChunk(chunkId: string, explanation: ChunkExplanation): AnalysisEditResult { + const index = this.analysis.chunks.findIndex((chunk) => chunk.id === chunkId); + if (index < 0) return missing(); + const chunks = [...this.analysis.chunks]; + chunks[index] = { + ...chunks[index], + literalMeaning: explanation.literalMeaning, + explanation: explanation.explanation, + }; + return validateAnalysisCandidate({ ...this.analysis, chunks }); + } + + moveBoundary(chunkId: string, end: number): AnalysisEditResult { + const index = this.analysis.chunks.findIndex((chunk) => chunk.id === chunkId); + if (index < 0) return missing(); + const chunk = this.analysis.chunks[index]; + const next = this.analysis.chunks[index + 1]; + if (!next) return { ok: false, message: "마지막 구간의 끝은 변경할 수 없습니다." }; + const chunks = [...this.analysis.chunks]; + chunks[index] = { ...chunk, range: { ...chunk.range, end } }; + chunks[index + 1] = { ...next, range: { ...next.range, start: end } }; + return validateAnalysisCandidate({ ...this.analysis, chunks }); + } + + splitChunk(chunkId: string, offset: number, newId: string): AnalysisEditResult { + const index = this.analysis.chunks.findIndex((chunk) => chunk.id === chunkId); + if (index < 0) return missing(); + const chunk = this.analysis.chunks[index]; + const chunks = [...this.analysis.chunks]; + chunks.splice( + index, + 1, + { ...chunk, range: { start: chunk.range.start, end: offset } }, + { + id: newId, + range: { start: offset, end: chunk.range.end }, + literalMeaning: "", + explanation: "", + }, + ); + return validateAnalysisCandidate({ ...this.analysis, chunks }); + } + + mergeNext(chunkId: string): AnalysisEditResult { + const index = this.analysis.chunks.findIndex((chunk) => chunk.id === chunkId); + if (index < 0) return missing(); + const chunk = this.analysis.chunks[index]; + const next = this.analysis.chunks[index + 1]; + if (!next) return { ok: false, message: "합칠 다음 구간이 없습니다." }; + const chunks = [...this.analysis.chunks]; + 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"), + }); + return validateAnalysisCandidate({ ...this.analysis, chunks }); + } + + saveSyntax(annotation: SyntaxAnnotation): AnalysisEditResult { + const exists = this.analysis.syntax.some((item) => item.id === annotation.id); + const syntax = exists + ? this.analysis.syntax.map((item) => (item.id === annotation.id ? annotation : item)) + : [...this.analysis.syntax, annotation]; + return validateAnalysisCandidate({ ...this.analysis, syntax }); + } + + deleteSyntax(id: string): AnalysisEditResult { + if (!this.analysis.syntax.some((item) => item.id === id)) return missing(); + const syntax = this.analysis.syntax.filter((item) => item.id !== id); + return validateAnalysisCandidate({ ...this.analysis, syntax }); + } + + saveConstruction(annotation: ConstructionAnnotation): AnalysisEditResult { + const exists = this.analysis.constructions.some((item) => item.id === annotation.id); + const constructions = exists + ? this.analysis.constructions.map((item) => (item.id === annotation.id ? annotation : item)) + : [...this.analysis.constructions, annotation]; + return validateAnalysisCandidate({ ...this.analysis, constructions }); + } + + deleteConstruction(id: string): AnalysisEditResult { + if (!this.analysis.constructions.some((item) => item.id === id)) return missing(); + const constructions = this.analysis.constructions.filter((item) => item.id !== id); + return validateAnalysisCandidate({ ...this.analysis, constructions }); + } +} + +function missing(): AnalysisEditResult { + return { ok: false, message: "편집할 분석 항목을 찾을 수 없습니다." }; +} diff --git a/src/features/grammar-analysis-edit/services/applyAnalysisEdits.ts b/src/features/grammar-analysis-edit/services/applyAnalysisEdits.ts new file mode 100644 index 00000000..eb352c81 --- /dev/null +++ b/src/features/grammar-analysis-edit/services/applyAnalysisEdits.ts @@ -0,0 +1,18 @@ +import type { SentenceAnalysis } from "@/entities/grammar-note"; +import type { AnalysisEdit, AnalysisEditResult } from "../models/editAnalysis"; +import { EditAnalysisService } from "./EditAnalysisService"; + +/** 순서대로 검증하되, 실패하면 중간 후보를 외부에 반영하지 않는다. */ +export function applyAnalysisEdits( + analysis: SentenceAnalysis, + edit: AnalysisEdit | readonly AnalysisEdit[], +): AnalysisEditResult { + const operations = typeof edit === "function" ? [edit] : edit; + let candidate = analysis; + for (const operation of operations) { + const result = operation(new EditAnalysisService(candidate)); + if (!result.ok) return result; + candidate = result.analysis; + } + return { ok: true, analysis: candidate }; +} diff --git a/src/features/grammar-analysis-edit/services/hooks/useChunkEdit.ts b/src/features/grammar-analysis-edit/services/hooks/useChunkEdit.ts new file mode 100644 index 00000000..06870e0c --- /dev/null +++ b/src/features/grammar-analysis-edit/services/hooks/useChunkEdit.ts @@ -0,0 +1,26 @@ +"use client"; + +import { useRef, useState } from "react"; +import type { AnalysisEdit } from "../../models/editAnalysis"; +import { useAnalysisEditor } from "../../ui/AnalysisEditorProvider"; + +export function useChunkEdit(chunkId: string) { + const formRef = useRef(null); + const edit = useAnalysisEditor((state) => state.edit); + const [error, setError] = useState(""); + + function applyEdit(command?: AnalysisEdit) { + if (!formRef.current) return; + // 풀이는 적용 시에만 필요하다. 입력값을 DOM과 React state에 중복 저장하지 않는다. + const data = new FormData(formRef.current); + const literalMeaning = String(data.get("literalMeaning") ?? ""); + const explanation = String(data.get("explanation") ?? ""); + const result = edit([ + (service) => service.editChunk(chunkId, { literalMeaning, explanation }), + ...(command ? [command] : []), + ]); + setError(result.ok ? "" : result.message); + } + + return { formRef, applyEdit, error }; +} 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..a85f3b00 --- /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/services/validateAnalysisCandidate.ts b/src/features/grammar-analysis-edit/services/validateAnalysisCandidate.ts new file mode 100644 index 00000000..d4dbc400 --- /dev/null +++ b/src/features/grammar-analysis-edit/services/validateAnalysisCandidate.ts @@ -0,0 +1,11 @@ +import { sentenceAnalysisSchema } from "@/entities/grammar-note"; +import type { SentenceAnalysis } from "@/entities/grammar-note"; +import type { AnalysisEditResult } from "../models/editAnalysis"; + +/** 모든 편집 후보에 같은 도메인 규칙을 적용하고 재검토 상태로 돌린다. */ +export function validateAnalysisCandidate(candidate: SentenceAnalysis): AnalysisEditResult { + const parsed = sentenceAnalysisSchema.safeParse({ ...candidate, reviewStatus: "needs-review" }); + return parsed.success + ? { ok: true, analysis: parsed.data } + : { ok: false, message: parsed.error.issues[0].message }; +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisBody.tsx b/src/features/grammar-analysis-edit/ui/AnalysisBody.tsx new file mode 100644 index 00000000..68566a0e --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisBody.tsx @@ -0,0 +1,10 @@ +"use client"; + +import { useAnalysisEditor } from "./AnalysisEditorProvider"; +import { AnalysisInspector } from "./AnalysisInspector"; +import { AnalysisReading } from "./AnalysisReading"; + +export function AnalysisBody() { + const editing = useAnalysisEditor((state) => state.editing); + return editing ? : ; +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisEditNavigation.tsx b/src/features/grammar-analysis-edit/ui/AnalysisEditNavigation.tsx new file mode 100644 index 00000000..d2fdca0c --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisEditNavigation.tsx @@ -0,0 +1,63 @@ +"use client"; + +import { useState } from "react"; +import { cva } from "class-variance-authority"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +const itemVariants = cva( + "rounded-md px-3 py-2 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-practice-secondary motion-reduce:transition-none", + { + variants: { + selected: { + true: "bg-practice-ink text-white", + false: "bg-practice-chip text-practice-secondary hover:bg-practice-neutral-surface", + }, + }, + }, +); + +export function AnalysisEditNavigation() { + const analysis = useAnalysisEditor((state) => state.analysis); + const id = useAnalysisEditor((state) => state.selectedId); + const select = useAnalysisEditor((state) => state.select); + const addSyntax = useAnalysisEditor((state) => state.addSyntax); + const dirty = useAnalysisEditor((state) => state.dirty); + const [error, setError] = useState(""); + return ( +
+

문장 성분 · 구문

+
+ {[ + ...analysis.syntax.map((item) => ({ id: item.id, name: item.label })), + ...analysis.constructions.map((item) => ({ id: item.id, name: item.name })), + ].map((item) => ( + + ))} + +
+ {error && ( +

+ {error} +

+ )} +
+ ); +} 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..8b8f4490 --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx @@ -0,0 +1,43 @@ +"use client"; + +import { createContext, useContext, useEffect, useRef, 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); + +/** + * 에디터 인스턴스마다 초기 분석·선택·미적용 입력을 격리한다. + * Context에는 변경되는 상태가 아닌 고정된 store 참조만 전달한다. + * initialAnalysis는 초기값이므로 다른 문서/분석으로 교체할 때는 소비자가 key를 변경한다. + */ +export function AnalysisEditorProvider({ + initialAnalysis, + onChange, + children, +}: AnalysisEditorProviderProps) { + // 부모가 콜백을 변경해도 편집 상태를 초기화하지 않고 최신 수신자에게 알린다. + const onChangeRef = useRef(onChange); + useEffect(() => { + onChangeRef.current = onChange; + }, [onChange]); + const [store] = useState(() => + createAnalysisEditorStore({ + initialAnalysis, + onChange: (analysis) => onChangeRef.current(analysis), + }), + ); + return {children}; +} + +export function useAnalysisEditorStore(): StoreApi { + const store = useContext(Context); + if (!store) throw new Error("AnalysisEditorProvider is required"); + return store; +} + +export function useAnalysisEditor(selector: (state: AnalysisEditorState) => T): T { + return useStore(useAnalysisEditorStore(), selector); +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisExitConfirmation.tsx b/src/features/grammar-analysis-edit/ui/AnalysisExitConfirmation.tsx new file mode 100644 index 00000000..69f17a3b --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisExitConfirmation.tsx @@ -0,0 +1,23 @@ +"use client"; + +import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +export function AnalysisExitConfirmation() { + const pending = useAnalysisEditor((state) => state.pendingSelection); + const resolve = useAnalysisEditor((state) => state.resolveSelection); + return ( + { + if (!open) resolve(false); + }} + title="적용하지 않은 수정을 버릴까요?" + description="계속 편집하면 현재 입력을 유지합니다." + confirmLabel="수정 버리기" + cancelLabel="계속 편집" + onConfirm={() => resolve(true)} + onCancel={() => resolve(false)} + /> + ); +} 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..49441973 --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisInspector.tsx @@ -0,0 +1,32 @@ +"use client"; + +import { useAnalysisEditor } from "./AnalysisEditorProvider"; +import { AnalysisEditNavigation } from "./AnalysisEditNavigation"; +import { ChunkEditor } from "./ChunkEditor"; +import { SyntaxEditor } from "./SyntaxEditor"; +import { ConstructionEditor } from "./ConstructionEditor"; + +/** The correction workspace is mounted only when explicitly requested. */ +export function AnalysisInspector() { + const id = useAnalysisEditor((state) => state.selectedId); + const analysis = useAnalysisEditor((state) => state.analysis); + const markDirty = useAnalysisEditor((state) => state.markDirty); + const chunk = analysis.chunks.find((item) => item.id === id); + const syntax = analysis.syntax.find((item) => item.id === id); + const construction = analysis.constructions.find((item) => item.id === id); + return ( +
+ +
+ {chunk && ( + + )} + {syntax && } + {construction && } +
+
+ ); +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisKeyboardBoundary.tsx b/src/features/grammar-analysis-edit/ui/AnalysisKeyboardBoundary.tsx new file mode 100644 index 00000000..bff39faf --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisKeyboardBoundary.tsx @@ -0,0 +1,38 @@ +"use client"; + +import type { KeyboardEvent } from "react"; +import type { AnalysisKeyboardBoundaryProps } from "../models/interface"; +import { useAnalysisEditorStore } from "./AnalysisEditorProvider"; + +export function AnalysisKeyboardBoundary({ children }: AnalysisKeyboardBoundaryProps) { + const store = useAnalysisEditorStore(); + + // DOM 이벤트이므로 참조 메모화 없이 이름 있는 핸들러로 둔다. + // 키를 누를 때만 최신 상태를 읽어, 키보드 처리용 상태 구독을 만들지 않는다. + function handleKeyDown(event: KeyboardEvent) { + if (event.key !== "Escape" || event.defaultPrevented) return; + // 포털 안의 키 이벤트도 React 트리로 전파된다. 확인창의 Escape와 포커스는 Radix가 처리한다. + if (event.target instanceof Element && event.target.closest('[role="alertdialog"]')) return; + event.preventDefault(); + const { editing, finishEditing, select } = store.getState(); + // DOM 탐색은 현재 에디터 안으로 제한하고, 선택 해제/화면 전환 전에 복귀할 버튼을 찾는다. + if (editing) { + event.currentTarget.querySelector("[data-analysis-action]")?.focus(); + finishEditing(); + } else { + event.currentTarget + .querySelector('[data-chunk-id][aria-pressed="true"]') + ?.focus(); + select(null); + } + } + + return ( +
+ {children} +
+ ); +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisReading.tsx b/src/features/grammar-analysis-edit/ui/AnalysisReading.tsx new file mode 100644 index 00000000..7bad5e36 --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisReading.tsx @@ -0,0 +1,58 @@ +"use client"; + +import { convertAnalysisToChunkReading } from "../models/converters/convertAnalysisToChunkReading"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +export function AnalysisReading() { + const id = useAnalysisEditor((state) => state.selectedId); + const analysis = useAnalysisEditor((state) => state.analysis); + const reading = id ? convertAnalysisToChunkReading(analysis, id) : null; + return ( +
+ {reading ? ( +
+

+ {reading.text} +

+
+

+ {reading.meaning || "아직 풀이가 없습니다."} +

+ {reading.roles.map((role) => ( + + {role} + + ))} +
+ {reading.explanation && ( +

{reading.explanation}

+ )} + {reading.constructions.map((item) => ( +

+ + {item.name} + + {item.meaning} +

+ ))} +
+ ) : ( +
+

+ 궁금한 표현을 눌러보세요. +
+ 뜻과 문장 속 역할을 함께 볼 수 있어요. +

+
+ )} +
+ ); +} 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..972b5aa0 --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisSentence.tsx @@ -0,0 +1,64 @@ +"use client"; + +import { cva } from "class-variance-authority"; +import { useShallow } from "zustand/react/shallow"; +import type { AnalysisItemProps } from "../models/interface"; +import { convertAnalysisToChunkReading } from "../models/converters/convertAnalysisToChunkReading"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +const chunkVariants = cva( + "relative max-w-full cursor-pointer rounded-xl border px-3 py-2.5 text-left text-[23px] leading-relaxed tracking-[-0.02em] break-words outline-none transition-[background-color,box-shadow,transform,border-color] duration-200 ease-out focus-visible:ring-2 focus-visible:ring-practice-secondary focus-visible:ring-offset-4 motion-reduce:transform-none motion-reduce:transition-none sm:px-4 sm:py-3 sm:text-[28px]", + { + variants: { + selected: { + true: "-translate-y-0.5 border-practice-input-line bg-white text-practice-ink shadow-strong", + false: + "border-transparent bg-practice-chip/70 text-practice-body hover:-translate-y-0.5 hover:bg-white hover:shadow-emphasize", + }, + }, + }, +); + +function ChunkButton({ id }: AnalysisItemProps) { + const chunk = useAnalysisEditor((state) => state.analysis.chunks.find((item) => item.id === id)); + const source = useAnalysisEditor((state) => state.analysis.sourceText); + const hint = useAnalysisEditor((state) => { + const reading = convertAnalysisToChunkReading(state.analysis, id); + return reading ? [reading.meaning, ...reading.roles].filter(Boolean).join(" · ") : ""; + }); + const selected = useAnalysisEditor((state) => state.selectedId === id); + const select = useAnalysisEditor((state) => state.select); + if (!chunk) return null; + return ( + + ); +} + +export function AnalysisSentence() { + const ids = useAnalysisEditor( + useShallow((state) => state.analysis.chunks.map((chunk) => chunk.id)), + ); + const translation = useAnalysisEditor((state) => state.analysis.naturalTranslation); + return ( +
+
+ {ids.map((id) => ( + + ))} +
+

+ {translation} +

+
+ ); +} diff --git a/src/features/grammar-analysis-edit/ui/AnalysisToolbar.tsx b/src/features/grammar-analysis-edit/ui/AnalysisToolbar.tsx new file mode 100644 index 00000000..ab4915b0 --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/AnalysisToolbar.tsx @@ -0,0 +1,38 @@ +"use client"; + +import { ArrowLeft, Pencil } from "lucide-react"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +export function AnalysisToolbar() { + const editing = useAnalysisEditor((state) => state.editing); + const startEditing = useAnalysisEditor((state) => state.startEditing); + const finishEditing = useAnalysisEditor((state) => state.finishEditing); + return ( +
+
+

+ {editing ? "EDIT ANALYSIS" : "SENTENCE STUDY"} +

+

+ {editing ? "분석 수정" : "문장 읽기"} +

+ {editing && ( +

분석이 다른 부분만 수정해 주세요.

+ )} +
+ +
+ ); +} 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..a54ce13b --- /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/ChunkBoundaryEditor.tsx b/src/features/grammar-analysis-edit/ui/ChunkBoundaryEditor.tsx new file mode 100644 index 00000000..0ea5d9ff --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/ChunkBoundaryEditor.tsx @@ -0,0 +1,37 @@ +"use client"; + +import { useState } from "react"; +import type { ChunkBoundaryEditorProps } from "../models/interface"; +import { Button } from "@/shared/components/atomics/button/Button"; +import { BoundarySelect } from "./BoundarySelect"; + +export function ChunkBoundaryEditor({ chunk, source, nextEnd, onApply }: ChunkBoundaryEditorProps) { + const [boundary, setBoundary] = useState(chunk.range.end); + function applyBoundary() { + onApply((service) => service.moveBoundary(chunk.id, boundary)); + } + return ( +
+ +

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

+ +
+ ); +} 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..93d9dd3a --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/ChunkEditor.tsx @@ -0,0 +1,48 @@ +"use client"; + +import type { FormEvent } from "react"; +import type { ChunkEditorProps } from "../models/interface"; +import { Button } from "@/shared/components/atomics/button/Button"; +import { useChunkEdit } from "../services/hooks/useChunkEdit"; +import { ChunkExplanationFields } from "./ChunkExplanationFields"; +import { ChunkBoundaryEditor } from "./ChunkBoundaryEditor"; +import { ChunkSplitEditor } from "./ChunkSplitEditor"; +import { useAnalysisEditor } from "./AnalysisEditorProvider"; + +export function ChunkEditor({ chunk }: ChunkEditorProps) { + const { formRef, applyEdit, error } = useChunkEdit(chunk.id); + const source = useAnalysisEditor((state) => state.analysis.sourceText); + const nextEnd = useAnalysisEditor( + (state) => + state.analysis.chunks[state.analysis.chunks.findIndex((item) => item.id === chunk.id) + 1] + ?.range.end, + ); + function submitExplanation(event: FormEvent) { + event.preventDefault(); + applyEdit(); + } + function mergeNext() { + applyEdit((service) => service.mergeNext(chunk.id)); + } + return ( +
+

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

+ + +
+ + +
+ + {error && ( +

+ {error} +

+ )} + + ); +} diff --git a/src/features/grammar-analysis-edit/ui/ChunkExplanationFields.tsx b/src/features/grammar-analysis-edit/ui/ChunkExplanationFields.tsx new file mode 100644 index 00000000..48c18abd --- /dev/null +++ b/src/features/grammar-analysis-edit/ui/ChunkExplanationFields.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { useId } from "react"; +import type { ChunkEditorProps } from "../models/interface"; +import { Input } from "@/shared/components/atomics/input/Input"; +import { Textarea } from "@/shared/components/atomics/textarea/Textarea"; + +export function ChunkExplanationFields({ chunk }: ChunkEditorProps) { + const id = useId(); + return ( + <> + +