feat: 바탕화면 수정본의 Studio 편집기 v2~v4 를 얹는다

`~/Desktop/tech-log-frontend` 가 세 번 더 고쳐져 있었다. 소스 열셋이 바뀌고 둘이
새로 생겼다(`markdown-block-editor`, `catalog-property-picker`). 검사 넷도 함께 바뀌었다.

기능이 바뀐 것부터 적는다.

**편집기에서 즉시 미리보기가 빠졌다.** v2 에서 「편집/나란히/미리보기」 모드가 생겼고,
v4 가 그 모드 자체를 없앴다 — 글 쓰는 화면은 하나이고 공개 렌더는 편집기의 두 번째
상태가 아니라는 판단이다. 직전 리뷰의 완료 조건 하나("preview 는 Desktop/Mobile 을
실제로 전환할 수 있다")가 이로써 다시 미적용이 된다. `InstantPreview` 는 파일로 남아
있으나 편집기 어디서도 부르지 않는다.

**본문이 textarea 에서 블록 편집기로 바뀌었다.** 기존 markdown 을 문단·제목·목록·인용·
코드·구분선·raw 로 읽고 같은 `bodyMarkdown` 계약으로 되돌려 쓴다. 읽었다가 그대로 다시
쓰는 왕복이 글을 바꾸면 작성자가 문서를 열어 저장하기만 해도 내용이 상하므로, 이
저장소가 실제로 쓰는 문법(앵커 단 소제목, 이름표 단 코드 울타리, `:::evidence`, 표,
인용, 목록, 구분선)을 하나씩 넣어 왕복을 검사로 고정했다. 빈 줄이 겹친 자리만 한 줄로
접히고 글자는 그대로다 — 그 예외도 검사에 적었다.

Project·Topic 이 검색 가능한 고르개로, 상태가 인라인 알약으로 바뀌었고, 메타데이터는
접히는 속성 면으로 내려갔다.

`useImperativeHandle` 안에서 부르는 `commit` 이 렌더마다 새로 만들어져 lint 가 막았다.
`useCallback` 으로 고정했다 — 바뀌는 것은 `onChange` 하나다.

Node 24 로 게이트 재실행: check:types · lint · test:unit(1829) · test:component(152) ·
test:tech-log(432) 전부 통과.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015c8cBFUaVr7KLVUx6ujz7D
This commit is contained in:
DongHyeonka
2026-09-16 16:43:37 +09:00
co-authored by Claude Opus 5
parent b9d0585bc6
commit d72eae25ce
20 changed files with 3322 additions and 953 deletions
+33 -55
View File
@@ -104,6 +104,12 @@ function gatewayOf(items: unknown[]): StudioAssetGateway {
};
}
function markdownSource(root: ParentNode = document): HTMLTextAreaElement {
const source = root.querySelector<HTMLTextAreaElement>(".studio-markdown-source");
assert.ok(source, "single-surface Markdown source not found");
return source;
}
test("builds the evidence directive with escaped attribute values", () => {
assert.equal(
buildEvidenceDirective({
@@ -420,7 +426,7 @@ test("focuses the file input on open, traps Tab inside the dialog, and calls onC
// --- CaseFields end-to-end: cursor-preserving insertion + Instant Preview resolves it live ---
test("inserts the directive at the saved cursor position and the live preview renders it without an error panel", async () => {
test("inserts evidence after the active document block without leaving the writing surface", async () => {
const user = userEvent.setup();
const gateway = createMockStudioGateway();
const DIAGRAM_ASSET = {
@@ -441,17 +447,8 @@ test("inserts the directive at the saved cursor position and the live preview re
</MemoryRouter>,
);
const textarea = (await screen.findByLabelText("본문 Markdown")) as HTMLTextAreaElement;
const body = textarea.value;
const cursor = body.indexOf("\n\n");
assert.ok(cursor > 0);
textarea.focus();
textarea.setSelectionRange(cursor, cursor);
/*
자료는 이제 폼에 펼쳐지지 않고 창 안에서 고른다 — 36개가 본문 아래에 전부 늘어서 있으면
글을 쓰는 화면이 자료 관리 화면이 된다. 고르기 전에 창을 연다.
*/
await screen.findByRole("region", { name: "본문" });
screen.getByLabelText("1번째 제목 2").focus();
await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" }));
await user.click(await screen.findByRole("button", { name: /cursor-test-diagram/ }));
@@ -461,19 +458,12 @@ test("inserts the directive at the saved cursor position and the live preview re
caption: "",
zoom: true,
});
assert.equal(
textarea.value,
`${body.slice(0, cursor)}\n\n${expectedDirective}${body.slice(cursor)}`,
);
const panel = screen.getByRole("region", { name: "즉시 미리보기" });
expect(within(panel).queryByRole("alert")).not.toBeInTheDocument();
// `zoom: true` (DIAGRAM kind) renders the figure's image twice -- once as
// the zoom trigger, once inside the (closed) zoom dialog -- both share the
// same alt text, so assert on the first (the visible trigger figure).
const [image] = within(panel).getAllByAltText("커서 삽입 테스트 다이어그램");
assert.equal(image!.getAttribute("src"), "/media/cursor-test-diagram.svg");
const authored = markdownSource().value;
assert.ok(authored.includes(expectedDirective), authored);
assert.ok(authored.indexOf("## 책임 경계") < authored.indexOf(expectedDirective), authored);
assert.ok(authored.indexOf(expectedDirective) < authored.indexOf("정책과 명령을 분리합니다."), authored);
expect(screen.getByLabelText("2번째 자료")).toHaveValue(expectedDirective);
expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
});
// --- Fix round 1 ---
@@ -551,7 +541,7 @@ test("an asset uploaded through the mock composition previews live and passes mo
</MemoryRouter>,
);
await screen.findByLabelText("본문 Markdown");
await screen.findByRole("region", { name: "본문" });
await user.click(screen.getByRole("button", { name: "Asset 업로드" }));
chooseAndUpload(
new File(["<svg/>"], "boundary-check.svg", { type: "image/svg+xml" }),
@@ -565,10 +555,10 @@ test("an asset uploaded through the mock composition previews live and passes mo
// `UnsavedLeaveDialog`, which carries the same native `role="dialog"`, so
// asserting on dialog presence/absence is not a safe signal either way).
await waitFor(() => {
const value = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value;
const value = markdownSource().value;
assert.ok(value.includes('key="boundary-check"'), value);
});
const textarea = screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement;
const textarea = markdownSource();
// Final fix wave, item 2: the upload dialog now collects the alt text, so
// the auto-inserted directive already carries it and no hand-edit of the
@@ -1494,7 +1484,7 @@ test("an asset uploaded with alt text inserts that alt and the document validate
</MemoryRouter>,
);
await screen.findByLabelText("본문 Markdown");
await screen.findByRole("region", { name: "본문" });
await user.click(screen.getByRole("button", { name: "Asset 업로드" }));
await uploadThroughDialog(
user,
@@ -1503,10 +1493,10 @@ test("an asset uploaded with alt text inserts that alt and the document validate
);
await waitFor(() => {
const value = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value;
const value = markdownSource().value;
assert.ok(value.includes('key="alt-text-check"'), value);
});
const body = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value;
const body = markdownSource().value;
assert.ok(body.includes('alt="업로드한 다이어그램 설명"'), body);
assert.ok(!body.includes('alt=""'), body);
@@ -1540,7 +1530,7 @@ test("a decorative upload inserts an empty alt and the document is still publish
</MemoryRouter>,
);
await screen.findByLabelText("본문 Markdown");
await screen.findByRole("region", { name: "본문" });
await user.click(screen.getByRole("button", { name: "Asset 업로드" }));
await uploadThroughDialog(
user,
@@ -1549,10 +1539,10 @@ test("a decorative upload inserts an empty alt and the document is still publish
);
await waitFor(() => {
const value = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value;
const value = markdownSource().value;
assert.ok(value.includes('key="decorative-check"'), value);
});
const body = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value;
const body = markdownSource().value;
assert.ok(body.includes('alt=""'), body);
const { report, preview } = await saveValidateAndPreview(
@@ -1800,7 +1790,7 @@ test("a slow earlier Picker search never overwrites the newer query's results",
// the Picker reports what it *observed*, the screen merges it into a catalog
// that only ever grows.
test("a Picker search never drops an already-inserted asset out of Instant Preview's resolution", async () => {
test("a Picker search never drops an already-inserted asset from the authored document", async () => {
const user = userEvent.setup();
const gateway = createMockStudioGateway();
const { gateway: assetGateway } = searchableGateway([PICKER_A, PICKER_B]);
@@ -1814,37 +1804,25 @@ test("a Picker search never drops an already-inserted asset out of Instant Previ
</MemoryRouter>,
);
await screen.findByLabelText("본문 Markdown");
/*
자료는 이제 폼에 펼쳐지지 않고 창 안에서 고른다 — 36개가 본문 아래에 전부 늘어서 있으면
글을 쓰는 화면이 자료 관리 화면이 된다. 고르기 전에 창을 연다.
*/
await screen.findByRole("region", { name: "본문" });
await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" }));
await user.click(await screen.findByRole("button", { name: /inserted-diagram/ }));
const body = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value;
const body = markdownSource().value;
assert.ok(body.includes('key="inserted-diagram"'), body);
// Now search for something that excludes the asset just inserted. The Picker
// must narrow; the preview must not.
//
// 넣고 나면 창이 닫힌다 — 넣은 뒤 목록 앞에 남아 있을 이유가 없다. 다시 연다.
// Search narrows only the picker. The inserted evidence block remains part
// of the document because the editor owns authored content independently.
await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" }));
await user.type(screen.getByLabelText("Asset 검색"), "other");
await user.click(screen.getByRole("button", { name: "검색" }));
const picker = screen.getByRole("group", { name: "본문에 Asset 삽입" });
const picker = screen.getByRole("dialog", { name: "본문에 넣을 자료 고르기" });
await waitFor(() =>
expect(within(picker).queryByRole("button", { name: /inserted-diagram/ })).not.toBeInTheDocument(),
);
const panel = screen.getByRole("region", { name: "즉시 미리보기" });
assert.equal(
within(panel).queryByRole("alert")?.textContent ?? null,
null,
"the preview refused a directive it resolved before the search",
);
const [image] = within(panel).getAllByAltText("삽입한 다이어그램");
assert.equal(image!.getAttribute("src"), "/media/inserted-diagram.svg");
assert.ok(markdownSource().value.includes('key="inserted-diagram"'));
assert.ok((screen.getByLabelText(/번째 자료/) as HTMLTextAreaElement).value.includes('key="inserted-diagram"'));
expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
});
test("mergeAssetCatalog keeps every previously known asset and lets a fresher copy win", () => {
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import {
blockOf,
chunksOf,
documentOf,
} from "../../../src/features/tech-log/presentation/studio/components/markdown-block-editor.tsx";
/** 편집기가 본문을 읽었다가 그대로 다시 쓰는 길. 작성자가 아무것도 고치지 않은 경우다. */
function roundTrip(markdown: string): string {
return documentOf(chunksOf(markdown).map(blockOf));
}
describe("블록 편집기는 열어 보기만 해도 본문을 바꾸지 않는다", () => {
/*
본문을 블록으로 읽었다가 다시 markdown 으로 쓰는 편집기다. 그 왕복이 글을 바꾸면 작성자가
문서를 열어 저장하기만 해도 내용이 상한다 — 고친 적 없는 문단이 달라지는 것이 가장 나쁜
종류의 손실이다. 이 저장소가 실제로 쓰는 문법을 하나씩 넣어 본다.
*/
it.each([
["소제목과 앵커", "## 문제를 고정하기 {#fix-the-problem}\n\n첫 문단이다."],
[
"이름표를 단 코드 울타리",
'```text label="Hibernate 경고"\nfirstResult/maxResults specified with collection fetch\n```',
],
[
"자료 지시자",
':::evidence key="some-key" alt="설명" caption="" zoom="true"\n:::',
],
["인용", "> 인용한 문장이다.\n> 두 줄짜리다."],
["글머리 목록", "- 첫째\n- 둘째\n- 셋째"],
["번호 목록", "1. 첫째\n2. 둘째"],
["구분선", "---"],
["표", "| 전략 | 쿼리 |\n| --- | --- |\n| fetch join | 1 |"],
[
"여러 덩어리가 이어진 문서",
'## 관찰한 값 {#observed-values}\n\n측정한 내용이다.\n\n```java label="실패한 조회"\nList<FeedItem> findFeed();\n```\n\n- 쿼리 수\n- 로드된 행 수\n\n:::evidence key="chart" alt="" caption=""\n:::',
],
])("%s", (_name, markdown) => {
expect(roundTrip(markdown)).toBe(markdown);
});
/* 빈 줄이 여러 개면 하나로 접힌다 — 글자는 그대로이므로 이것만 예외로 적어 둔다. */
it("빈 줄이 겹친 자리는 한 줄로 접히되 글은 남는다", () => {
expect(roundTrip("첫 문단\n\n\n\n둘째 문단")).toBe("첫 문단\n\n둘째 문단");
});
});
@@ -134,8 +134,7 @@ describe("TechLog Studio project decision authoring", () => {
);
});
it("edits Decision fields and renders the project decision card preview", async () => {
const user = userEvent.setup();
it("edits Decision fields on the single document surface without a preview mode", async () => {
const gateway = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway();
const document = await gateway.createDocument(decisionInput(), {
idempotencyKey: "edit-project-decision",
@@ -149,7 +148,8 @@ describe("TechLog Studio project decision authoring", () => {
</MemoryRouter>,
);
expect(await screen.findByLabelText("결정 상태")).toHaveValue("ADOPTED");
const decisionStatus = await screen.findByRole("group", { name: "결정 상태" });
expect(within(decisionStatus).getByRole("button", { name: "ADOPTED" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByLabelText("결정일")).toHaveValue("2026-08-11");
expect(screen.getByLabelText("결정문")).toHaveValue(
"목록 조회와 컬렉션 로딩을 서로 다른 단계로 수행합니다.",
@@ -163,26 +163,10 @@ describe("TechLog Studio project decision authoring", () => {
expect(screen.getByLabelText("근거 1 대상")).toHaveValue(
FIXTURE_IDS.fetchJoinCase,
);
expect(screen.getByRole("complementary", { name: "작업 상태" }))
.toHaveTextContent("종류설계 결정");
const preview = screen.getByRole("region", { name: "즉시 미리보기" });
expect(
within(preview).getByRole("heading", {
name: "목록 페이징과 컬렉션 로딩을 분리합니다",
}),
).toBeVisible();
expect(within(preview).getByText("판단 이유")).toBeVisible();
expect(within(preview).getByText("영향")).toBeVisible();
expect(within(preview).getByText("근거 기록")).toBeVisible();
/*
같은 기록이 화면에 두 번 나온다 — 위쪽 「이 기록의 맥락」이 이 결정이 어느 조사에 속하는지
보여 주고, 아래 「근거 기록」이 그 결정을 뒷받침한 기록을 다시 세운다. 목차가 본문의 제목을
다시 적는 것과 같은 중복이므로, 확인은 근거 목록 안으로 좁힌다.
*/
const evidence = within(preview).getByText("근거 기록").closest("section")!;
expect(within(evidence as HTMLElement).getByRole("link", {
name: "컬렉션 Fetch Join과 페이징은 왜 충돌하는가",
})).toHaveAttribute("href", "/cases/collection-fetch-join-pagination");
expect(screen.getByLabelText("현재 문서")).toHaveTextContent("PROJECT_DECISION");
expect(screen.getByRole("main", { name: "문서 편집" })).toBeVisible();
expect(screen.queryByRole("button", { name: "나란히" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "미리보기" })).not.toBeInTheDocument();
expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
});
});
@@ -44,8 +44,14 @@ function labelsIn(container: HTMLElement, selector: string): string[] {
);
}
function markdownSource(container: HTMLElement): HTMLTextAreaElement {
const source = container.querySelector<HTMLTextAreaElement>(".studio-markdown-source");
if (!source) throw new Error("single-surface Markdown source not found");
return source;
}
describe("TechLog Studio document editor", () => {
it("loads the Case controls in source order, owns dirty state, and renders an instant local preview", async () => {
it("loads the Case as one document surface and owns dirty state without an editor preview mode", async () => {
const user = userEvent.setup();
const base = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway();
const calls = { save: 0, validate: 0, preview: 0, publish: 0 };
@@ -77,25 +83,23 @@ describe("TechLog Studio document editor", () => {
expect(screen.getByLabelText("요약")).toHaveValue(
"만료 정책과 명령 실행 책임을 분리했습니다.",
);
expect(screen.getByLabelText("Topic")).toHaveValue(FIXTURE_IDS.topicRedis);
expect(screen.getByLabelText("Project")).toHaveValue(FIXTURE_IDS.projectBackend);
expect(screen.getByLabelText("Topic")).toHaveTextContent("Redis");
expect(screen.getByLabelText("Project")).toHaveTextContent("Backend Skeleton");
// The common metadata remains a compact property surface. Record-specific
// content is no longer represented as a stack of `.studio-field` form rows.
expect(labelsIn(view.container, ".studio-field")).toEqual([
"제목",
"slug",
"요약",
"Topic",
"Project",
"문제",
"결론",
"검증 환경",
"재현 조건",
"마지막 검증일",
"본문 Markdown",
"프로젝트",
"주제",
"URL 이름",
]);
expect(screen.getByLabelText("문제")).toHaveValue("저장 기술이 정책을 소유했습니다.");
expect(screen.getByLabelText("본문 Markdown")).toHaveValue(
expect(markdownSource(view.container)).toHaveValue(
"## 책임 경계\n\n정책과 명령을 분리합니다.",
);
expect(screen.getByLabelText("1번째 제목 2")).toHaveValue("책임 경계");
expect(screen.getByLabelText("2번째 텍스트")).toHaveValue("정책과 명령을 분리합니다.");
expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent("저장됨");
await user.clear(screen.getByLabelText("제목"));
@@ -103,35 +107,21 @@ describe("TechLog Studio document editor", () => {
expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent(
"저장되지 않음",
);
/*
종류 이름은 모든 화면이 같은 표를 본다. 예전에는 화면마다 표를 복사해 두어 같은 문서가
편집기에서 "CASE", 목록에서 "Case" 로 갈렸다 — QUESTION 은 네
가지 표기까지 났다.
*/
expect(screen.getByRole("complementary", { name: "작업 상태" })).toHaveTextContent(
"저장 버전4종류검증 기록",
);
// 작성자가 밟는 단계는 저장과 게시 둘뿐이다. 예전에는 검증 → 미리보기 → 게시 세 화면을
// 차례로 거쳐야 했는데, 그 셋은 백엔드가 게시 요청에 요구하는 값을 만들기 위한 것이지
// 작성자에게 물어볼 것이 아니었다 — 지금은 게시 버튼 뒤에서 잇달아 부른다.
// Version/kind belong to the document identity, while the command bar has
// only the two real author actions. There is no edit/split/preview state.
expect(screen.getByLabelText("현재 문서")).toHaveTextContent("CASE·v4");
const rail = screen.getByRole("complementary", { name: "작업 상태" });
expect(within(rail).getAllByRole("button").map((button) => button.textContent)).toEqual([
"저장",
"게시",
]);
expect(within(rail).queryAllByRole("link")).toHaveLength(0);
// 편집과 미리보기는 한 화면에 함께 있다. 탭이었을 때는 고친 결과를 보려면 편집하던 자리를
// 화면에서 치워야 했고, 돌아오면 스크롤 위치도 잃었다 — 그 왕복이 없어야 한다는 것이
// 이 화면의 요구다. 아무것도 누르지 않은 채로 둘 다 보이는지 묻는다.
expect(screen.getByRole("region", { name: "문서 편집" })).toBeVisible();
expect(
within(screen.getByRole("region", { name: "즉시 미리보기" })).getByRole(
"heading",
{ level: 1, name: "편집한 Redis 경계" },
),
).toBeVisible();
expect(screen.queryByRole("tab", { name: "즉시 미리보기" })).toBeNull();
expect(screen.getByRole("main", { name: "문서 편집" })).toBeVisible();
expect(screen.queryByRole("button", { name: "편집" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "나란히" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "미리보기" })).not.toBeInTheDocument();
expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
expect(screen.getByLabelText("제목")).toHaveValue("편집한 Redis 경계");
expect(calls).toEqual({ save: 0, validate: 0, preview: 0, publish: 0 });
});
@@ -227,7 +217,8 @@ describe("TechLog Studio document editor", () => {
const user = userEvent.setup();
renderEditor(FIXTURE_IDS.edgeTokenQuestion);
expect(await screen.findByLabelText("질문 상태")).toHaveValue("OPEN");
const questionStatus = await screen.findByRole("group", { name: "질문 상태" });
expect(within(questionStatus).getByRole("button", { name: "OPEN" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByLabelText("남은 미지수 1")).toHaveValue("신뢰 헤더 위조 가능성");
expect(screen.getByRole("textbox", { name: "다음 검증" })).toHaveValue(
"위협 모델을 비교합니다.",
@@ -240,9 +231,9 @@ describe("TechLog Studio document editor", () => {
expect(screen.getByLabelText("선택지 1 제목")).toHaveValue("");
expect(screen.getByLabelText("선택지 1 설명")).toHaveValue("");
await user.selectOptions(screen.getByLabelText("질문 상태"), "RESOLVED");
await user.click(within(questionStatus).getByRole("button", { name: "RESOLVED" }));
expect(screen.getByLabelText("해결 요약")).toHaveValue("");
expect(screen.getByLabelText("해결 근거")).toHaveValue("");
expect(screen.getByLabelText("해결 근거")).toHaveTextContent("근거 선택");
expect(screen.getByLabelText("근거 링크 문구")).toHaveValue("");
expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent(
"저장되지 않음",
@@ -106,7 +106,7 @@ describe("TechLog Studio validation workflow", () => {
view.unmount();
renderStudio(<DocumentEditorScreen documentId={FIXTURE_IDS.edgeTokenQuestion} />, gateway);
await screen.findByRole("heading", { level: 1, name: "문서 편집" });
await screen.findByRole("heading", { level: 1, name: /oauth2-proxy가 전달한 토큰/ });
expect(document.querySelector("#studio-field-facts")).toBeInTheDocument();
expect(document.querySelector("#studio-field-options")).toBeInTheDocument();
});