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
@@ -6,12 +6,11 @@ import { useStudioAssetGateway } from "../use-studio.ts";
import { buildEvidenceDirective } from "./asset-picker.tsx"; import { buildEvidenceDirective } from "./asset-picker.tsx";
import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx"; import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx";
import { AssetUploadDialog } from "./asset-upload-dialog.tsx"; import { AssetUploadDialog } from "./asset-upload-dialog.tsx";
import { MarkdownToolbar } from "./markdown-toolbar.tsx";
import { FieldNotice, type FieldIssue } from "./field-issues.tsx"; import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
import { MarkdownBlockEditor, type MarkdownBlockEditorHandle } from "./markdown-block-editor.tsx";
type CaseInput = components["schemas"]["CaseInput"]; type CaseInput = components["schemas"]["CaseInput"];
/** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. */
export const CASE_FIELD_PATHS = [ export const CASE_FIELD_PATHS = [
"/problem", "/problem",
"/conclusion", "/conclusion",
@@ -27,26 +26,6 @@ const ASSET_KIND_OPTIONS: ReadonlyArray<{ value: AssetKind; label: string }> = [
{ value: "ATTACHMENT", label: "첨부파일" }, { value: "ATTACHMENT", label: "첨부파일" },
]; ];
/**
* `:::evidence ...` is a block directive, so the parser requires a blank line
* before and after it. Inserting straight into `selectionStart`/`selectionEnd`
* without normalizing the surrounding whitespace would produce a directive
* glued to adjacent text -- a well-formed-looking block that the parser still
* rejects.
*/
function insertAtCursor(
textarea: HTMLTextAreaElement,
directive: string,
commit: (next: string) => void,
) {
const { selectionStart, selectionEnd, value } = textarea;
const prefix = value.slice(0, selectionStart);
const suffix = value.slice(selectionEnd);
const before = prefix.length === 0 || prefix.endsWith("\n\n") ? prefix : `${prefix}\n\n`;
const after = suffix.startsWith("\n") ? suffix : `\n${suffix}`;
commit(`${before}${directive}${after}`);
}
export function CaseFields({ export function CaseFields({
draft, draft,
issues, issues,
@@ -55,37 +34,21 @@ export function CaseFields({
onAssetUploaded, onAssetUploaded,
}: { }: {
draft: CaseInput; draft: CaseInput;
/** 마지막 게시 시도가 남긴 지적. 각 칸 아래에는 그 칸의 것만 붙는다. */
issues: readonly FieldIssue[]; issues: readonly FieldIssue[];
onChange(draft: CaseInput): void; onChange(draft: CaseInput): void;
/**
* The editor screen owns the resolution catalog Instant Preview reads, and
* merges what the Picker observes into it -- it never adopts the Picker's
* (searchable, and so narrowable) displayed list wholesale.
*/
onAssetsObserved?: (assets: readonly Asset[]) => void; onAssetsObserved?: (assets: readonly Asset[]) => void;
onAssetUploaded?: (asset: Asset) => void; onAssetUploaded?: (asset: Asset) => void;
}) { }) {
// Asset UI must use the throwing accessor, not the nullable `assetGateway`
// field directly -- see `use-studio.ts`'s `useStudioAssetGateway` doc.
const assetGateway = useStudioAssetGateway(); const assetGateway = useStudioAssetGateway();
const bodyRef = useRef<HTMLTextAreaElement>(null); const bodyEditorRef = useRef<MarkdownBlockEditorHandle>(null);
const uploadTriggerRef = useRef<HTMLButtonElement>(null); const uploadTriggerRef = useRef<HTMLButtonElement>(null);
const [uploadKind, setUploadKind] = useState<AssetKind>("IMAGE"); const [uploadKind, setUploadKind] = useState<AssetKind>("IMAGE");
const [uploadOpen, setUploadOpen] = useState(false); const [uploadOpen, setUploadOpen] = useState(false);
const update = (patch: Partial<CaseInput>) => onChange({ ...draft, ...patch }); const update = (patch: Partial<CaseInput>) => onChange({ ...draft, ...patch });
const insertDirective = (directive: string) => { const insertDirective = (directive: string) => {
const textarea = bodyRef.current; if (bodyEditorRef.current) bodyEditorRef.current.insertMarkdown(directive);
if (!textarea) { else update({ bodyMarkdown: draft.bodyMarkdown ? `${draft.bodyMarkdown}\n\n${directive}` : directive });
update({
bodyMarkdown: draft.bodyMarkdown
? `${draft.bodyMarkdown}\n\n${directive}\n`
: `${directive}\n`,
});
return;
}
insertAtCursor(textarea, directive, (next) => update({ bodyMarkdown: next }));
}; };
const closeUpload = () => { const closeUpload = () => {
@@ -94,37 +57,81 @@ export function CaseFields({
}; };
return ( return (
<section className="studio-editor-section" aria-labelledby="studio-case-fields-title"> <section className="studio-editor-section studio-record-authoring" aria-labelledby="studio-case-fields-title">
<div className="studio-editor-section-heading"><p className="studio-eyebrow">CASE</p><h2 id="studio-case-fields-title">문제와 검증</h2></div> <div className="studio-editor-section-heading">
<div className="studio-field-grid"> <p className="studio-eyebrow">CASE</p>
<label className="studio-field studio-field--wide"><span>문제</span><textarea value={draft.problem} onChange={(event) => update({ problem: event.currentTarget.value })} /><FieldNotice issues={issues} path="/problem" /></label> <h2 id="studio-case-fields-title">문제와 검증</h2>
<label className="studio-field studio-field--wide"><span>결론</span><textarea value={draft.conclusion} onChange={(event) => update({ conclusion: event.currentTarget.value })} /><FieldNotice issues={issues} path="/conclusion" /></label> <p>문제와 결론을 먼저 고정하고, 그 사이의 검증 과정을 본문 블록으로 이어서 작성합니다.</p>
<label className="studio-field"><span>검증 환경</span><textarea value={draft.environment} onChange={(event) => update({ environment: event.currentTarget.value })} /><FieldNotice issues={issues} path="/environment" /></label>
<label className="studio-field"><span>재현 조건</span><textarea value={draft.reproduction} onChange={(event) => update({ reproduction: event.currentTarget.value })} /><FieldNotice issues={issues} path="/reproduction" /></label>
<label className="studio-field"><span>마지막 검증일</span><input type="date" value={draft.lastVerifiedOn ?? ""} onChange={(event) => update({ lastVerifiedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/lastVerifiedOn" /></label>
<div className="studio-field studio-field--wide"><label htmlFor="studio-field-body">본문 Markdown</label><MarkdownToolbar target={bodyRef} onInsert={(next) => update({ bodyMarkdown: next })} /><textarea id="studio-field-body" ref={bodyRef} className="studio-markdown-field" value={draft.bodyMarkdown} onChange={(event) => update({ bodyMarkdown: event.currentTarget.value })} /><FieldNotice issues={issues} path="/bodyMarkdown" /></div>
</div> </div>
<div className="studio-asset-panel" role="group" aria-labelledby="studio-asset-panel-title">
<p className="studio-eyebrow">EVIDENCE</p> <div className="studio-semantic-blocks">
<h3 id="studio-asset-panel-title">본문에 Asset 삽입</h3> <label className="studio-document-block" data-tone="problem">
<p>목록에서 선택하면 본문 커서 위치에 evidence 구문을 삽입합니다. READY 상태의 Asset만 선택할 수 있습니다.</p> <span className="studio-document-block__label">문제</span>
<div className="studio-asset-panel-actions"> <textarea
<label className="studio-asset-kind-field"> aria-label="문제"
<span>업로드 종류</span> value={draft.problem}
placeholder="어떤 현상이 문제였는지 한 문단으로 적어 주세요."
onChange={(event) => update({ problem: event.currentTarget.value })}
/>
<FieldNotice issues={issues} path="/problem" />
</label>
<label className="studio-document-block" data-tone="conclusion">
<span className="studio-document-block__label">결론</span>
<textarea
aria-label="결론"
value={draft.conclusion}
placeholder="검증을 통해 무엇을 확인했는지 적어 주세요."
onChange={(event) => update({ conclusion: event.currentTarget.value })}
/>
<FieldNotice issues={issues} path="/conclusion" />
</label>
</div>
<details className="studio-detail-properties">
<summary>
<span>검증 세부정보</span>
<span>{[draft.environment, draft.reproduction, draft.lastVerifiedOn].filter(Boolean).length}개 입력됨</span>
</summary>
<div className="studio-detail-properties__body">
<label className="studio-property-row studio-property-row--writing">
<span className="studio-property-name">검증 환경</span>
<textarea aria-label="검증 환경" value={draft.environment} placeholder="OS, 버전, 구성처럼 결과의 범위를 결정하는 조건" onChange={(event) => update({ environment: event.currentTarget.value })} />
<FieldNotice issues={issues} path="/environment" />
</label>
<label className="studio-property-row studio-property-row--writing">
<span className="studio-property-name">재현 조건</span>
<textarea aria-label="재현 조건" value={draft.reproduction} placeholder="같은 현상을 다시 만들기 위해 필요한 조건" onChange={(event) => update({ reproduction: event.currentTarget.value })} />
<FieldNotice issues={issues} path="/reproduction" />
</label>
<label className="studio-property-row">
<span className="studio-property-name">마지막 검증일</span>
<input aria-label="마지막 검증일" type="date" value={draft.lastVerifiedOn ?? ""} onChange={(event) => update({ lastVerifiedOn: event.currentTarget.value || null })} />
<FieldNotice issues={issues} path="/lastVerifiedOn" />
</label>
</div>
</details>
<div className="studio-body-authoring">
<div className="studio-body-authoring__heading">
<div>
<span>본문</span>
<p>작성 화면이 곧 문서입니다. 빈 블록에서 / 를 입력해 제목·목록·코드 블록을 추가할 수 있습니다.</p>
</div>
<div className="studio-inline-asset-actions">
<AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onAssetsObserved={onAssetsObserved} onInsert={insertDirective} />
<label className="studio-asset-kind-field studio-asset-kind-field--compact">
<span className="studio-visually-hidden">업로드 종류</span>
<select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}> <select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>
{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)} {ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
</select> </select>
</label> </label>
<button <button ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>업로드</button>
ref={uploadTriggerRef}
type="button"
onClick={() => setUploadOpen(true)}
>
Asset 업로드
</button>
</div> </div>
<AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onAssetsObserved={onAssetsObserved} onInsert={insertDirective} />
</div> </div>
<MarkdownBlockEditor ref={bodyEditorRef} label="본문" value={draft.bodyMarkdown} onChange={(bodyMarkdown) => update({ bodyMarkdown })} />
<FieldNotice issues={issues} path="/bodyMarkdown" />
</div>
{uploadOpen ? ( {uploadOpen ? (
<AssetUploadDialog <AssetUploadDialog
gateway={assetGateway} gateway={assetGateway}
@@ -0,0 +1,88 @@
import { useMemo, useRef, useState } from "react";
import type { components } from "../../../contracts/studio/generated.ts";
type CatalogEntry = components["schemas"]["CatalogEntry"];
/**
* Project/Topic property picker used by the document writing surface.
*
* Native <select> was technically correct but became painful once catalogs grew: authors had to
* scroll a flat list and the control looked like a settings form. This picker keeps the document
* property row compact, then opens a searchable choice surface only when the property is edited.
*/
export function CatalogPropertyPicker({
label,
value,
entries,
emptyLabel,
missingLabel = "목록에 없는 대상",
onChange,
}: {
label: string;
value: string | null | undefined;
entries: readonly CatalogEntry[];
emptyLabel: string;
missingLabel?: string;
onChange(value: string | null): void;
}) {
const detailsRef = useRef<HTMLDetailsElement>(null);
const [query, setQuery] = useState("");
const selected = value ? entries.find((entry) => entry.id === value) : undefined;
const shown = selected?.label ?? (value ? missingLabel : emptyLabel);
const filtered = useMemo(() => {
const needle = query.trim().toLocaleLowerCase();
if (!needle) return entries;
return entries.filter((entry) => entry.label.toLocaleLowerCase().includes(needle));
}, [entries, query]);
const choose = (next: string | null) => {
onChange(next);
setQuery("");
if (detailsRef.current) detailsRef.current.open = false;
};
return (
<details ref={detailsRef} className="studio-catalog-property-picker">
<summary aria-label={label}>
<span data-empty={!value ? "" : undefined} data-missing={value && !selected ? "" : undefined}>{shown}</span>
<span className="studio-catalog-property-picker__chevron" aria-hidden="true">⌄</span>
</summary>
<div className="studio-catalog-property-picker__popover">
<label className="studio-catalog-property-picker__search">
<span className="studio-visually-hidden">{label} 검색</span>
<input
type="search"
value={query}
placeholder={`${label} 검색`}
onChange={(event) => setQuery(event.currentTarget.value)}
/>
</label>
<div className="studio-catalog-property-picker__options" role="listbox" aria-label={`${label} 선택`}>
<button
type="button"
role="option"
aria-selected={!value}
onClick={() => choose(null)}
>
<span>{emptyLabel}</span>
{!value ? <strong aria-hidden="true">✓</strong> : null}
</button>
{filtered.map((entry) => (
<button
key={entry.id}
type="button"
role="option"
aria-selected={entry.id === value}
onClick={() => choose(entry.id)}
>
<span>{entry.label}</span>
{entry.id === value ? <strong aria-hidden="true">✓</strong> : null}
</button>
))}
{filtered.length === 0 ? <p>검색 결과가 없습니다.</p> : null}
</div>
</div>
</details>
);
}
@@ -4,20 +4,12 @@ import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
import { missingTopicIssue } from "../../../domain/content-format/project-public-render-model.ts"; import { missingTopicIssue } from "../../../domain/content-format/project-public-render-model.ts";
import type { TopicVariantEdit } from "../../../contracts/management/contract.ts"; import type { TopicVariantEdit } from "../../../contracts/management/contract.ts";
import { RelationEditor } from "./relation-editor.tsx"; import { RelationEditor } from "./relation-editor.tsx";
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
import { CatalogPropertyPicker } from "./catalog-property-picker.tsx";
type CatalogEntry = components["schemas"]["CatalogEntry"]; type CatalogEntry = components["schemas"]["CatalogEntry"];
/**
* 요약이 들어갈 수 있는 최대 길이. 계약 `WorkingCopyInputBase.summary` 와 같은 값이어야 한다 —
* 여기가 더 크면 다 쓰고 나서 저장할 때 거절당하고, 더 작으면 쓸 수 있는 자리를 못 쓴다.
*/
const SUMMARY_MAX = 2000; const SUMMARY_MAX = 2000;
/**
* 목록·검색 카드는 요약을 세 줄에서 자른다. 작성자에게는 그 경계가 보이지 않아서, 500자를 써도
* 독자가 받는 것은 앞 세 줄뿐이라는 사실을 알 방법이 없었다. 정확한 글자 수는 글자 폭에 따라
* 달라지므로 어림수로 알린다 — 여기서 필요한 것은 정밀도가 아니라 경계가 있다는 사실이다.
*/
const SUMMARY_CARD_PREVIEW = 90; const SUMMARY_CARD_PREVIEW = 90;
/** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. 나머지는 게시 버튼 옆에 남는다. */ /** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. 나머지는 게시 버튼 옆에 남는다. */
@@ -31,6 +23,13 @@ export const COMMON_FIELD_PATHS = [
"/variantIds", "/variantIds",
] as const; ] as const;
/**
* 문서의 공통 정보는 "관리 폼"이 아니라 문서 자체의 첫 부분처럼 편집한다.
*
* 제목과 요약은 종이 위에서 직접 고치듯 크게 노출하고, 분류/URL/연결 같은 부가 정보만
* Notion의 properties처럼 한 덩어리로 접을 수 있게 둔다. 작성자가 글을 쓰기 전에 2열 form을
* 해석하는 비용을 없애는 것이 목적이다.
*/
export function CommonDocumentFields({ export function CommonDocumentFields({
draft, draft,
topics, topics,
@@ -44,64 +43,127 @@ export function CommonDocumentFields({
topics: CatalogEntry[]; topics: CatalogEntry[];
projects: CatalogEntry[]; projects: CatalogEntry[];
relations: CatalogEntry[]; relations: CatalogEntry[];
/** 고른 주제의 축. 주제를 고르지 않았거나 축을 쓰지 않는 주제면 빈 목록이다. */
variants: readonly TopicVariantEdit[]; variants: readonly TopicVariantEdit[];
/** 마지막 게시 시도가 남긴 지적. 각 칸 아래에는 그 칸의 것만 붙는다. */
issues: readonly FieldIssue[]; issues: readonly FieldIssue[];
onUpdate(patch: Partial<WorkingCopyInput>): void; onUpdate(patch: Partial<WorkingCopyInput>): void;
}) { }) {
const missingTopic = missingTopicIssue(draft.topicId ?? null, topics); const missingTopic = missingTopicIssue(draft.topicId ?? null, topics);
const selectedProject = projects.find((entry) => entry.id === draft.projectId)?.label;
const selectedTopic = topics.find((entry) => entry.id === draft.topicId)?.label;
const relationCount = draft.relations.filter((relation) => relation.targetId).length;
return ( return (
<section className="studio-editor-section" aria-labelledby="studio-common-fields-title"> <section className="studio-document-lead" aria-label="문서 기본 정보">
<div className="studio-editor-section-heading"><p className="studio-eyebrow">DOCUMENT</p><h2 id="studio-common-fields-title">기본 정보</h2></div> <div className="studio-document-kicker" aria-hidden="true">
<div className="studio-field-grid"> <span>{DOCUMENT_KIND_LABELS[draft.kind]}</span>
<label className="studio-field studio-field--wide"><span>제목</span><input value={draft.title} maxLength={120} onChange={(event) => onUpdate({ title: event.currentTarget.value })} /><FieldNotice issues={issues} path="/title" /></label> {selectedProject ? <><i>·</i><span>{selectedProject}</span></> : null}
<label className="studio-field"><span>slug</span><input value={draft.slug} maxLength={100} placeholder="비우면 제목에서 만듭니다 (영문 소문자·숫자·하이픈)" onChange={(event) => onUpdate({ slug: event.currentTarget.value as WorkingCopyInput["slug"] })} /><FieldNotice issues={issues} path="/slug" /></label> {selectedTopic ? <><i>·</i><span>{selectedTopic}</span></> : null}
{/* </div>
요약만 label 로 감싸지 않고 htmlFor 로 잇는다. 감싸면 label 안의 글자가 모두 칸의
이름이 되어 "요약 412 / 600" 처럼 타자마다 이름이 바뀐다 — 이름은 「요약」로 두고
남은 자리는 그 옆에 따로 보여 준다.
*/}
<div className="studio-field studio-field--wide"><label htmlFor="studio-field-summary">요약</label><textarea id="studio-field-summary" value={draft.summary} maxLength={SUMMARY_MAX} onChange={(event) => onUpdate({ summary: event.currentTarget.value })} /><span className="studio-char-count" aria-hidden="true" data-full={draft.summary.length >= SUMMARY_MAX ? "" : undefined}>목록 카드에는 약 {SUMMARY_CARD_PREVIEW}자까지 보입니다 · {draft.summary.length} / {SUMMARY_MAX}</span><FieldNotice issues={issues} path="/summary" /></div>
{/*
고른 주제가 목록에 없을 수 있다 — 보관으로 내렸거나 지워진 주제다. 예전에는 그 상태가
미리보기를 통째로 죽여 UUID 만 보여 줬다. 지금은 미리보기가 살아 있으므로, 무엇이
잘못됐는지는 이 칸이 말해야 한다.
없는 값을 셀렉트에 임시 항목으로 남겨 둔다. 남기지 않으면 셀렉트가 「선택하지 않음」으로 <h1 className="studio-document-title-heading" aria-label={draft.title || "제목 없는 작업본"}>
보여서, 작성자는 고른 적 없는 주제 때문에 경고가 뜬다고 읽는다. <label className="studio-field studio-document-title-field">
*/} <span className="studio-visually-hidden">제목</span>
<label className="studio-field"><span>Topic</span><select value={draft.topicId ?? ""} onChange={(event) => onUpdate({ topicId: event.currentTarget.value || null })}><option value="">선택하지 않음</option>{missingTopic && draft.topicId ? <option value={draft.topicId}>목록에 없는 주제</option> : null}{topics.map((entry) => <option key={entry.id} value={entry.id}>{entry.label}</option>)}</select>{missingTopic ? <p className="studio-field-error" role="alert">{missingTopic}</p> : null}<FieldNotice issues={issues} path="/topicId" /></label> <input
<label className="studio-field"><span>Project</span><select value={draft.projectId ?? ""} onChange={(event) => onUpdate({ projectId: event.currentTarget.value || null })}><option value="">미지정</option>{projects.map((entry) => <option key={entry.id} value={entry.id}>{entry.label}</option>)}</select><FieldNotice issues={issues} path="/projectId" /></label> aria-label="제목"
value={draft.title}
maxLength={120}
placeholder="제목을 입력하세요"
onChange={(event) => onUpdate({ title: event.currentTarget.value })}
/>
<FieldNotice issues={issues} path="/title" />
</label>
</h1>
<div className="studio-field studio-document-summary-field">
<label className="studio-visually-hidden" htmlFor="studio-field-summary">요약</label>
<textarea
id="studio-field-summary"
aria-label="요약"
value={draft.summary}
maxLength={SUMMARY_MAX}
placeholder="이 기록에서 다루는 핵심을 한두 문장으로 적어 주세요."
onChange={(event) => onUpdate({ summary: event.currentTarget.value })}
/>
<div className="studio-document-summary-meta">
<span>목록 카드에는 약 {SUMMARY_CARD_PREVIEW}자까지 보입니다.</span>
<span className="studio-char-count" aria-hidden="true" data-full={draft.summary.length >= SUMMARY_MAX ? "" : undefined}>{draft.summary.length} / {SUMMARY_MAX}</span>
</div>
<FieldNotice issues={issues} path="/summary" />
</div>
<details className="studio-document-properties" open>
<summary>
<span className="studio-document-properties__title">속성</span>
<span className="studio-document-properties__summary">
{selectedProject ?? "프로젝트 없음"} · {selectedTopic ?? "주제 없음"}
</span>
<span className="studio-document-properties__toggle" aria-hidden="true">접기</span>
</summary>
<div className="studio-property-list">
<div className="studio-field studio-property-row">
<span className="studio-property-name">프로젝트</span>
<span className="studio-property-control">
<CatalogPropertyPicker
label="Project"
value={draft.projectId}
entries={projects}
emptyLabel="프로젝트 없음"
onChange={(projectId) => onUpdate({ projectId })}
/>
</span>
<FieldNotice issues={issues} path="/projectId" />
</div>
<div className="studio-field studio-property-row">
<span className="studio-property-name">주제</span>
<span className="studio-property-control">
<CatalogPropertyPicker
label="Topic"
value={draft.topicId}
entries={topics}
emptyLabel="주제 없음"
missingLabel="목록에 없는 주제"
onChange={(topicId) => onUpdate({ topicId })}
/>
</span>
{missingTopic ? <p className="studio-field-error" role="alert">{missingTopic}</p> : null}
<FieldNotice issues={issues} path="/topicId" />
</div>
<label className="studio-field studio-property-row studio-property-row--slug">
<span className="studio-property-name">URL 이름</span>
<span className="studio-property-control studio-property-control--slug">
<span aria-hidden="true">/</span>
<input
aria-label="slug"
value={draft.slug}
maxLength={100}
placeholder="비우면 제목에서 자동 생성"
onChange={(event) => onUpdate({ slug: event.currentTarget.value as WorkingCopyInput["slug"] })}
/>
</span>
<small>직접 정하지 않아도 저장할 때 제목을 기준으로 만들어집니다.</small>
<FieldNotice issues={issues} path="/slug" />
</label>
</div> </div>
{/*
보조 기술에는 글자마다 세어 읽어 줄 수 없다 — 받아쓰기가 된다. 한계에 닿는 순간만 알린다.
label 밖에 두는 이유는 안에 두면 요약 칸의 이름이 이 문장까지 포함하게 되기 때문이다.
*/}
<p role="status" className="studio-visually-hidden">
{draft.summary.length >= SUMMARY_MAX ? `요약을 ${SUMMARY_MAX}자까지 모두 썼습니다. 더 입력되지 않습니다.` : ""}
</p>
{/*
축은 주제 안에서만 뜻이 있다. 주제를 고르지 않았거나 축을 쓰지 않는 주제면 이 자리를
그리지 않는다 — 고를 것이 없는 목록은 무엇을 놓쳤나 싶게 만든다.
아무 축에도 걸지 않아도 된다. 그 경우 이 기록은 주제의 공통 기록으로 읽힌다.
*/}
{variants.length > 0 ? ( {variants.length > 0 ? (
<fieldset className="studio-checkbox-set"> <fieldset className="studio-property-variants">
<legend>축 — 고르지 않으면 이 주제의 공통 기록이 됩니다</legend> <legend>축</legend>
{variants.map((variant) => ( <div className="studio-property-chips">
<label className="studio-field--checkbox" key={variant.id ?? variant.slug}> {variants.map((variant) => {
const id = variant.id ?? "";
const checked = (draft.variantIds ?? []).includes(id);
return (
<label key={variant.id ?? variant.slug} data-selected={checked ? "" : undefined}>
<input <input
type="checkbox" type="checkbox"
checked={(draft.variantIds ?? []).includes(variant.id ?? "")} checked={checked}
onChange={(event) => { onChange={(event) => {
const checked = event.currentTarget.checked;
const id = variant.id ?? "";
const current = draft.variantIds ?? []; const current = draft.variantIds ?? [];
onUpdate({ onUpdate({
variantIds: checked variantIds: event.currentTarget.checked
? [...current, id] ? [...current, id]
: current.filter((chosen) => chosen !== id), : current.filter((chosen) => chosen !== id),
}); });
@@ -109,12 +171,35 @@ export function CommonDocumentFields({
/> />
<span>{variant.title}</span> <span>{variant.title}</span>
</label> </label>
))} );
})}
</div>
<small>고르지 않으면 이 주제의 공통 기록으로 취급합니다.</small>
<FieldNotice issues={issues} path="/variantIds" /> <FieldNotice issues={issues} path="/variantIds" />
</fieldset> </fieldset>
) : null} ) : null}
<RelationEditor evidence={draft.kind === "PROJECT_DECISION"} relations={draft.relations} catalog={relations} onChange={(next) => onUpdate({ relations: next })} /> </details>
<details className="studio-document-relations">
<summary>
<span>연결된 기록</span>
<span>{relationCount > 0 ? `${relationCount}개 연결됨` : "필요할 때 추가"}</span>
</summary>
<div className="studio-document-relations__body">
<p>이 기록을 읽기 전·후에 이어지는 기록이나 판단 근거를 연결합니다.</p>
<RelationEditor
evidence={draft.kind === "PROJECT_DECISION"}
relations={draft.relations}
catalog={relations}
onChange={(next) => onUpdate({ relations: next })}
/>
<FieldNotice issues={issues} path="/relations" /> <FieldNotice issues={issues} path="/relations" />
</div>
</details>
<p role="status" className="studio-visually-hidden">
{draft.summary.length >= SUMMARY_MAX ? `요약을 ${SUMMARY_MAX}자까지 모두 썼습니다. 더 입력되지 않습니다.` : ""}
</p>
</section> </section>
); );
} }
@@ -6,12 +6,10 @@ import { useStudioAssetGateway } from "../use-studio.ts";
import { buildEvidenceDirective } from "./asset-picker.tsx"; import { buildEvidenceDirective } from "./asset-picker.tsx";
import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx"; import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx";
import { AssetUploadDialog } from "./asset-upload-dialog.tsx"; import { AssetUploadDialog } from "./asset-upload-dialog.tsx";
import { MarkdownToolbar } from "./markdown-toolbar.tsx";
import { FieldNotice, type FieldIssue } from "./field-issues.tsx"; import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
import { MarkdownBlockEditor, type MarkdownBlockEditorHandle } from "./markdown-block-editor.tsx";
type ConceptInput = components["schemas"]["ConceptInput"]; type ConceptInput = components["schemas"]["ConceptInput"];
/** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. */
export const CONCEPT_FIELD_PATHS = ["/basisVersion", "/bodyMarkdown"] as const; export const CONCEPT_FIELD_PATHS = ["/basisVersion", "/bodyMarkdown"] as const;
const ASSET_KIND_OPTIONS: ReadonlyArray<{ value: AssetKind; label: string }> = [ const ASSET_KIND_OPTIONS: ReadonlyArray<{ value: AssetKind; label: string }> = [
@@ -20,117 +18,53 @@ const ASSET_KIND_OPTIONS: ReadonlyArray<{ value: AssetKind; label: string }> = [
{ value: "ATTACHMENT", label: "첨부파일" }, { value: "ATTACHMENT", label: "첨부파일" },
]; ];
/** export function ConceptFields({ draft, issues, onChange, onAssetsObserved, onAssetUploaded }: {
* `:::evidence ...` is a block directive, so the parser requires a blank line
* before and after it. Inserting straight into `selectionStart`/`selectionEnd`
* without normalizing the surrounding whitespace would produce a directive
* glued to adjacent text -- a well-formed-looking block that the parser still
* rejects.
*/
function insertAtCursor(
textarea: HTMLTextAreaElement,
directive: string,
commit: (next: string) => void,
) {
const { selectionStart, selectionEnd, value } = textarea;
const prefix = value.slice(0, selectionStart);
const suffix = value.slice(selectionEnd);
const before = prefix.length === 0 || prefix.endsWith("\n\n") ? prefix : `${prefix}\n\n`;
const after = suffix.startsWith("\n") ? suffix : `\n${suffix}`;
commit(`${before}${directive}${after}`);
}
export function ConceptFields({
draft,
issues,
onChange,
onAssetsObserved,
onAssetUploaded,
}: {
draft: ConceptInput; draft: ConceptInput;
/** 마지막 게시 시도가 남긴 지적. 각 칸 아래에는 그 칸의 것만 붙는다. */
issues: readonly FieldIssue[]; issues: readonly FieldIssue[];
onChange(draft: ConceptInput): void; onChange(draft: ConceptInput): void;
/**
* The editor screen owns the resolution catalog Instant Preview reads, and
* merges what the Picker observes into it -- it never adopts the Picker's
* (searchable, and so narrowable) displayed list wholesale.
*/
onAssetsObserved?: (assets: readonly Asset[]) => void; onAssetsObserved?: (assets: readonly Asset[]) => void;
onAssetUploaded?: (asset: Asset) => void; onAssetUploaded?: (asset: Asset) => void;
}) { }) {
// Asset UI must use the throwing accessor, not the nullable `assetGateway`
// field directly -- see `use-studio.ts`'s `useStudioAssetGateway` doc.
const assetGateway = useStudioAssetGateway(); const assetGateway = useStudioAssetGateway();
const bodyRef = useRef<HTMLTextAreaElement>(null); const bodyEditorRef = useRef<MarkdownBlockEditorHandle>(null);
const uploadTriggerRef = useRef<HTMLButtonElement>(null); const uploadTriggerRef = useRef<HTMLButtonElement>(null);
const [uploadKind, setUploadKind] = useState<AssetKind>("IMAGE"); const [uploadKind, setUploadKind] = useState<AssetKind>("IMAGE");
const [uploadOpen, setUploadOpen] = useState(false); const [uploadOpen, setUploadOpen] = useState(false);
const update = (patch: Partial<ConceptInput>) => onChange({ ...draft, ...patch }); const update = (patch: Partial<ConceptInput>) => onChange({ ...draft, ...patch });
const insertDirective = (directive: string) => bodyEditorRef.current?.insertMarkdown(directive);
const insertDirective = (directive: string) => {
const textarea = bodyRef.current;
if (!textarea) {
update({
bodyMarkdown: draft.bodyMarkdown
? `${draft.bodyMarkdown}\n\n${directive}\n`
: `${directive}\n`,
});
return;
}
insertAtCursor(textarea, directive, (next) => update({ bodyMarkdown: next }));
};
const closeUpload = () => {
setUploadOpen(false);
queueMicrotask(() => uploadTriggerRef.current?.focus());
};
return ( return (
<section className="studio-editor-section" aria-labelledby="studio-concept-fields-title"> <section className="studio-editor-section studio-record-authoring" aria-labelledby="studio-concept-fields-title">
<div className="studio-editor-section-heading"><p className="studio-eyebrow">CONCEPT</p><h2 id="studio-concept-fields-title">개념</h2></div> <div className="studio-editor-section-heading">
<div className="studio-field-grid"> <p className="studio-eyebrow">CONCEPT</p>
<label className="studio-field"><span>기준 버전</span><input value={draft.basisVersion} onChange={(event) => update({ basisVersion: event.currentTarget.value })} /><small>&ldquo;Kubernetes 1.31&rdquo; 처럼 무엇을 보고 썼는지. 비워도 됩니다.</small><FieldNotice issues={issues} path="/basisVersion" /></label> <h2 id="studio-concept-fields-title">개념</h2>
<div className="studio-field studio-field--wide"><label htmlFor="studio-field-body">본문 Markdown</label><MarkdownToolbar target={bodyRef} onInsert={(next) => update({ bodyMarkdown: next })} /><textarea id="studio-field-body" ref={bodyRef} className="studio-markdown-field" value={draft.bodyMarkdown} onChange={(event) => update({ bodyMarkdown: event.currentTarget.value })} /><small>&ldquo;##&rdquo; 소제목이 목차가 됩니다. 아키텍처 도식은 아래에서 삽입하세요.</small><FieldNotice issues={issues} path="/bodyMarkdown" /></div> <p>전체 작동 원리를 한 문서 흐름으로 설명합니다.</p>
</div> </div>
<div className="studio-asset-panel" role="group" aria-labelledby="studio-asset-panel-title">
<p className="studio-eyebrow">EVIDENCE</p> <label className="studio-inline-property studio-inline-property--version">
<h3 id="studio-asset-panel-title">본문에 Asset 삽입</h3> <span>기준 버전</span>
<p>목록에서 선택하면 본문 커서 위치에 evidence 구문을 삽입합니다. READY 상태의 Asset만 선택할 수 있습니다.</p> <input aria-label="기준 버전" value={draft.basisVersion} placeholder="예: Kubernetes 1.31" onChange={(event) => update({ basisVersion: event.currentTarget.value })} />
<div className="studio-asset-panel-actions"> <FieldNotice issues={issues} path="/basisVersion" />
<label className="studio-asset-kind-field">
<span>업로드 종류</span>
<select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>
{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
</select>
</label> </label>
<button
ref={uploadTriggerRef} <div className="studio-body-authoring">
type="button" <div className="studio-body-authoring__heading">
onClick={() => setUploadOpen(true)} <div><span>본문</span><p>빈 블록에서 / 를 입력해 구조를 추가하세요.</p></div>
> <div className="studio-inline-asset-actions">
Asset 업로드
</button>
</div>
<AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onAssetsObserved={onAssetsObserved} onInsert={insertDirective} /> <AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onAssetsObserved={onAssetsObserved} onInsert={insertDirective} />
<label className="studio-asset-kind-field studio-asset-kind-field--compact"><span className="studio-visually-hidden">업로드 종류</span><select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>
<button ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>업로드</button>
</div> </div>
{uploadOpen ? ( </div>
<AssetUploadDialog <MarkdownBlockEditor ref={bodyEditorRef} label="본문" value={draft.bodyMarkdown} onChange={(bodyMarkdown) => update({ bodyMarkdown })} />
gateway={assetGateway} <FieldNotice issues={issues} path="/bodyMarkdown" />
kind={uploadKind} </div>
onUploaded={(asset) => {
{uploadOpen ? <AssetUploadDialog gateway={assetGateway} kind={uploadKind} onUploaded={(asset) => {
onAssetUploaded?.(asset); onAssetUploaded?.(asset);
insertDirective(buildEvidenceDirective({ insertDirective(buildEvidenceDirective({ assetKey: asset.assetKey, alt: asset.decorative ? "" : (asset.altText ?? ""), caption: "", zoom: asset.kind === "DIAGRAM" }));
assetKey: asset.assetKey, setUploadOpen(false);
alt: asset.decorative ? "" : (asset.altText ?? ""), }} onClose={() => setUploadOpen(false)} /> : null}
caption: "",
zoom: asset.kind === "DIAGRAM",
}));
closeUpload();
}}
onClose={closeUpload}
/>
) : null}
</section> </section>
); );
} }
@@ -1,9 +1,4 @@
import { useState } from "react";
import type { components } from "../../../contracts/studio/generated.ts"; import type { components } from "../../../contracts/studio/generated.ts";
import { usePreviewScrollSync } from "./use-preview-scroll-sync.ts";
import { EditorContextPanel } from "./editor-context-panel.tsx";
import { EditorSectionToc } from "./editor-section-toc.tsx";
import type { Asset } from "../../../contracts/studio/contract.ts"; import type { Asset } from "../../../contracts/studio/contract.ts";
import type { TopicVariantEdit } from "../../../contracts/management/contract.ts"; import type { TopicVariantEdit } from "../../../contracts/management/contract.ts";
import type { DocumentEditorController } from "./document-editor-controller.ts"; import type { DocumentEditorController } from "./document-editor-controller.ts";
@@ -11,7 +6,6 @@ import { CASE_FIELD_PATHS, CaseFields } from "./case-fields.tsx";
import { CONCEPT_FIELD_PATHS, ConceptFields } from "./concept-fields.tsx"; import { CONCEPT_FIELD_PATHS, ConceptFields } from "./concept-fields.tsx";
import { COMMON_FIELD_PATHS, CommonDocumentFields } from "./common-document-fields.tsx"; import { COMMON_FIELD_PATHS, CommonDocumentFields } from "./common-document-fields.tsx";
import { DocumentStatusBar } from "./document-status-bar.tsx"; import { DocumentStatusBar } from "./document-status-bar.tsx";
import { InstantPreview } from "./instant-preview.tsx";
import { DECISION_FIELD_PATHS, ProjectDecisionFields } from "./project-decision-fields.tsx"; import { DECISION_FIELD_PATHS, ProjectDecisionFields } from "./project-decision-fields.tsx";
import { issuesOutside } from "./field-issues.tsx"; import { issuesOutside } from "./field-issues.tsx";
import { QUESTION_FIELD_PATHS, QuestionFields } from "./question-fields.tsx"; import { QUESTION_FIELD_PATHS, QuestionFields } from "./question-fields.tsx";
@@ -21,19 +15,28 @@ import { SETUP_FIELD_PATHS, SetupFields } from "./setup-fields.tsx";
type CatalogEntry = components["schemas"]["CatalogEntry"]; type CatalogEntry = components["schemas"]["CatalogEntry"];
type RecordKind = components["schemas"]["RecordKind"]; type RecordKind = components["schemas"]["RecordKind"];
/**
* Studio's document screen is a single authoring surface.
*
* There is deliberately no edit/split/preview mode here. The old UI was a
* Markdown CMS with a Notion-looking skin: authors edited form controls on the
* left and had to decide when to look at another rendering on the right. The
* writing surface now owns the screen. Title, properties and record-specific
* content are edited in the same vertical document flow; the public page can
* still be opened as a separate route after publishing, but it is no longer a
* second state of this editor.
*/
export function DocumentEditor({ export function DocumentEditor({
controller, controller,
catalog, catalog,
variants, variants,
assets, assets: _assets,
onAssetsObserved, onAssetsObserved,
onAssetUploaded, onAssetUploaded,
}: { }: {
controller: DocumentEditorController; controller: DocumentEditorController;
catalog: CatalogEntry[]; catalog: CatalogEntry[];
/** 고른 주제의 축. 주제를 고르지 않았거나 축을 쓰지 않는 주제면 빈 목록이다. */
variants: readonly TopicVariantEdit[]; variants: readonly TopicVariantEdit[];
/** Owned by `DocumentEditorScreen` so the CASE editor's Picker/Upload and Instant Preview share one list. */
assets: readonly Asset[]; assets: readonly Asset[];
onAssetsObserved: (assets: readonly Asset[]) => void; onAssetsObserved: (assets: readonly Asset[]) => void;
onAssetUploaded: (asset: Asset) => void; onAssetUploaded: (asset: Asset) => void;
@@ -43,19 +46,6 @@ export function DocumentEditor({
const relations = catalog.filter(({ type }) => type === "RELATION"); const relations = catalog.filter(({ type }) => type === "RELATION");
const evidence = catalog.filter(({ type }) => type === "EVIDENCE"); const evidence = catalog.filter(({ type }) => type === "EVIDENCE");
/*
게시를 막는 것이 무엇인지 그 칸 아래에 적는다. 예전에는 이 목록이 화면 맨 위에 한 덩어리로
있었고, 작성자는 `/topicId` 같은 경로를 읽고 어느 칸인지 스스로 찾아야 했다.
어느 칸에도 붙지 못한 것은 게시 버튼 옆에 남긴다 — 사라지면 이유를 말해 주지 않는 실패만
남는다.
*/
const issues = controller.publishIssues;
/*
삼항 사슬의 마지막 else 가 「나머지 전부」였다. 종류를 더하면 그 종류의 지적이 결정의
칸 경로로 걸러져, 자기 칸 아래에 붙지도 게시 버튼 옆에 남지도 않고 사라진다. 표로 두면
컴파일러가 빈 자리를 잡는다.
*/
const KIND_PATHS: Record<RecordKind, readonly string[]> = { const KIND_PATHS: Record<RecordKind, readonly string[]> = {
CASE: CASE_FIELD_PATHS, CASE: CASE_FIELD_PATHS,
CONCEPT: CONCEPT_FIELD_PATHS, CONCEPT: CONCEPT_FIELD_PATHS,
@@ -65,133 +55,42 @@ export function DocumentEditor({
PROJECT_DECISION: DECISION_FIELD_PATHS, PROJECT_DECISION: DECISION_FIELD_PATHS,
}; };
const kindPaths = KIND_PATHS[controller.draft.kind]; const kindPaths = KIND_PATHS[controller.draft.kind];
/* const unplaced = issuesOutside(controller.publishIssues, [...COMMON_FIELD_PATHS, ...kindPaths]);
미리보기가 편집 중인 절을 따라온다. 본문을 쓰는 종류에서만 뜻이 있다 — 구조화된 칸만 있는
종류는 미리보기에 맞출 소제목이 없다.
*/
usePreviewScrollSync(
"studio-editor-workspace",
"studio-editor-preview-body",
controller.draft.kind === "CASE"
|| controller.draft.kind === "CONCEPT"
|| controller.draft.kind === "SETUP",
);
const unplaced = issuesOutside(issues, [...COMMON_FIELD_PATHS, ...kindPaths]);
/*
미리보기를 어떻게 볼지. 「넓게」는 편집 칸을 잠시 접어 공개 화면과 같은 폭으로 보여 준다 —
좁은 칸에 갇힌 미리보기는 공개 화면이 아니라 좁은 화면용 배치를 보여 주고 있었다.
*/
const [previewMode, setPreviewMode] = useState<"split" | "full" | "hidden">("split");
const [previewWidth, setPreviewWidth] = useState<"desktop" | "mobile">("desktop");
/*
편집과 미리보기를 한 화면에 나란히 둔다. 예전에는 탭이었고, 고친 것이 어떻게 보이는지
확인하려면 탭을 옮겨야 했다 — 옮기는 동안 편집 중이던 칸은 화면에서 사라졌고, 돌아오면
스크롤 위치도 잃었다. 두 패널을 동시에 두면 그 왕복이 통째로 없어진다.
탭을 없앴으므로 각 패널은 스스로 이름을 가져야 한다. `aria-labelledby` 로 제목을 가리켜
landmark 로 만든다 — 탭 목록이 하던 "여기는 편집, 저기는 미리보기" 안내를 대신한다.
*/
return ( return (
<div className="studio-editor-page"> <div className="studio-editor-page studio-editor-page--single-surface">
<div className="studio-editor-split" data-preview={previewMode}> <header className="studio-editor-commandbar">
<section <div className="studio-editor-commandbar__identity" aria-label="현재 문서">
id="studio-editor-workspace" <span>{controller.draft.kind}</span>
className="studio-editor-workspace" <i aria-hidden="true">·</i>
aria-labelledby="studio-edit-title" <span>v{controller.saved.version}</span>
hidden={previewMode === "full"}
>
<header className="studio-editor-heading">
<p className="studio-eyebrow">{controller.draft.kind} · VERSION {controller.saved.version}</p>
<h1 id="studio-edit-title">문서 편집</h1>
<p>{controller.draft.title || "제목 없는 작업본"}</p>
</header>
{/*
7,540px 짜리 폼에 섹션으로 이동할 수단이 하나도 없었다. 공개 상세 화면이 이미
sticky 목차를 갖고 있고, 같은 일을 여기서 한다.
*/}
{/*
읽는 쪽은 맥락을 잃지 않게 해 놓고 쓰는 쪽은 잃게 두고 있었다. 지금 쓰는 글이 어느
프로젝트의 어느 주제에 속하고 무엇과 이어져 있는지를 폼 위쪽에 세운다.
*/}
<EditorContextPanel draft={controller.draft} catalog={catalog} />
<EditorSectionToc containerId="studio-editor-workspace" />
<CommonDocumentFields draft={controller.draft} topics={topics} projects={projects} relations={relations} variants={variants} issues={issues} onUpdate={controller.update} />
{controller.draft.kind === "CASE"
? <CaseFields draft={controller.draft} issues={issues} onChange={controller.replace} onAssetsObserved={onAssetsObserved} onAssetUploaded={onAssetUploaded} />
: controller.draft.kind === "CONCEPT"
? <ConceptFields draft={controller.draft} issues={issues} onChange={controller.replace} onAssetsObserved={onAssetsObserved} onAssetUploaded={onAssetUploaded} />
: controller.draft.kind === "SETUP"
? <SetupFields draft={controller.draft} issues={issues} onChange={controller.replace} onAssetsObserved={onAssetsObserved} onAssetUploaded={onAssetUploaded} />
: controller.draft.kind === "REFERENCE"
? <ReferenceFields draft={controller.draft} issues={issues} onChange={controller.replace} />
: controller.draft.kind === "QUESTION"
? <QuestionFields draft={controller.draft} evidence={evidence} issues={issues} onChange={controller.replace} />
: <ProjectDecisionFields draft={controller.draft} issues={issues} onChange={controller.replace} />}
</section>
{/*
미리보기는 편집 칸보다 훨씬 짧을 수도, 길 수도 있다. 그대로 두면 본문을 스크롤하는
동안 화면 밖으로 나가 버리므로 붙잡아 두고 자기 높이 안에서 따로 스크롤한다.
*/}
<section
className="studio-editor-preview"
aria-labelledby="studio-preview-title"
hidden={previewMode === "hidden"}
>
<header className="studio-editor-preview__heading">
<p className="studio-eyebrow">LIVE</p>
<h2 id="studio-preview-title">즉시 미리보기</h2>
{/*
미리보기가 늘 좁은 칸에 갇혀 있었다. 공개 화면은 1,180px 셸인데 이 칸은 그 절반도
안 되므로, 작성자가 보는 것은 <em>공개 화면</em>이 아니라 좁은 화면용 배치였다 —
데스크톱에서 어떻게 보이는지는 게시한 뒤에야 알 수 있었다.
*/}
<div className="studio-preview-modes" role="group" aria-label="미리보기 보기 방식">
{(
[
["split", "나란히"],
["full", "넓게"],
["hidden", "숨김"],
] as const
).map(([mode, label]) => (
<button
key={mode}
type="button"
aria-pressed={previewMode === mode}
onClick={() => setPreviewMode(mode)}
>
{label}
</button>
))}
</div>
<div className="studio-preview-modes" role="group" aria-label="미리보기 폭">
{(
[
["desktop", "데스크톱"],
["mobile", "모바일"],
] as const
).map(([width, label]) => (
<button
key={width}
type="button"
aria-pressed={previewWidth === width}
onClick={() => setPreviewWidth(width)}
>
{label}
</button>
))}
</div>
</header>
<div
id="studio-editor-preview-body"
className="studio-editor-preview__body"
data-width={previewWidth}
>
<InstantPreview draft={controller.draft} catalog={catalog} assets={assets} />
</div>
</section>
</div> </div>
<DocumentStatusBar controller={controller} unplacedIssues={unplaced} /> <DocumentStatusBar controller={controller} unplacedIssues={unplaced} />
</header>
<main id="studio-editor-workspace" className="studio-editor-workspace studio-document-canvas" aria-label="문서 편집">
<CommonDocumentFields
draft={controller.draft}
topics={topics}
projects={projects}
relations={relations}
variants={variants}
issues={controller.publishIssues}
onUpdate={controller.update}
/>
{controller.draft.kind === "CASE"
? <CaseFields draft={controller.draft} issues={controller.publishIssues} onChange={controller.replace} onAssetsObserved={onAssetsObserved} onAssetUploaded={onAssetUploaded} />
: controller.draft.kind === "CONCEPT"
? <ConceptFields draft={controller.draft} issues={controller.publishIssues} onChange={controller.replace} onAssetsObserved={onAssetsObserved} onAssetUploaded={onAssetUploaded} />
: controller.draft.kind === "SETUP"
? <SetupFields draft={controller.draft} issues={controller.publishIssues} onChange={controller.replace} onAssetsObserved={onAssetsObserved} onAssetUploaded={onAssetUploaded} />
: controller.draft.kind === "REFERENCE"
? <ReferenceFields draft={controller.draft} issues={controller.publishIssues} onChange={controller.replace} />
: controller.draft.kind === "QUESTION"
? <QuestionFields draft={controller.draft} evidence={evidence} issues={controller.publishIssues} onChange={controller.replace} />
: <ProjectDecisionFields draft={controller.draft} issues={controller.publishIssues} onChange={controller.replace} />}
</main>
</div> </div>
); );
} }
@@ -1,6 +1,5 @@
import type { DocumentEditorController } from "./document-editor-controller.ts"; import type { DocumentEditorController } from "./document-editor-controller.ts";
import type { FieldIssue } from "./field-issues.tsx"; import type { FieldIssue } from "./field-issues.tsx";
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
const labels = { const labels = {
CLEAN: "저장됨", CLEAN: "저장됨",
@@ -10,58 +9,43 @@ const labels = {
} as const; } as const;
/** /**
* 작업 상태와 저장·게시를 화면 아래에 고정한다. * Notion-like editor chrome: status and the two real actions live in the top
* * command bar. Version/kind already belong to the document identity on the
* 예전에는 오른쪽 세로 rail 이었다. 그 자리는 편집기와 미리보기가 함께 쓸 가로 폭을 가져갔고, * left, so repeating them in a bottom dashboard only makes the editor feel
* 편집 칸이 길어질수록 rail 은 위에 붙은 채 본문만 멀어졌다. 아래에 고정하면 폭을 돌려주면서 * like an admin form.
* 스크롤 위치와 무관하게 저장·게시에 손이 닿는다 — 릴리즈 편집에서 버튼이 아래로 밀려나던
* 것과 같은 문제를 여기서는 만들지 않는다.
*
* `aside` 와 「작업 상태」라는 이름은 그대로 둔다. 자리가 바뀐 것이지 이 묶음이 무엇인지가
* 바뀐 것은 아니고, 보조 기술이 이 영역을 부르던 이름도 그대로여야 한다.
*/ */
export function DocumentStatusBar({ export function DocumentStatusBar({
controller, controller,
unplacedIssues, unplacedIssues,
}: { }: {
controller: DocumentEditorController; controller: DocumentEditorController;
/**
* 어느 칸에도 붙지 못한 지적. 화면에 없는 칸을 가리키는 것들이며, 여기 남기지 않으면 이유를
* 말해 주지 않는 실패만 남는다.
*/
unplacedIssues: readonly FieldIssue[]; unplacedIssues: readonly FieldIssue[];
}) { }) {
const busy = controller.status === "SAVING" || controller.publishing; const busy = controller.status === "SAVING" || controller.publishing;
const problem = controller.status === "CONFLICT"
? "서버 최신본과 충돌했습니다. 이 세션에서는 다시 열어 비교해 주세요."
: controller.saveError || controller.publishError;
return ( return (
<aside className="studio-document-status-bar" aria-labelledby="studio-document-status-title"> <aside className="studio-document-status-bar" aria-labelledby="studio-document-status-title">
<h2 id="studio-document-status-title" className="studio-visually-hidden">작업 상태</h2> <h2 id="studio-document-status-title" className="studio-visually-hidden">작업 상태</h2>
<p className={`studio-editor-status studio-editor-status--${controller.status.toLowerCase()}`} role="status" aria-label="편집 상태">{labels[controller.status]}</p> <p
<dl><div><dt>저장 버전</dt><dd>{controller.saved.version}</dd></div><div><dt>종류</dt><dd>{DOCUMENT_KIND_LABELS[controller.draft.kind]}</dd></div></dl> className={`studio-editor-status studio-editor-status--${controller.status.toLowerCase()}`}
{/* role="status"
경고는 하나만 띄운다. 충돌은 그 자체로 무엇을 해야 하는지 말해 주므로 서버가 준 문구보다 aria-label="편집 상태"
앞서고, 그 밖의 실패는 서버가 준 이유를 그대로 보여 준다. 둘을 함께 띄우면 같은 실패를 >
두 번 말하게 된다. <span className="studio-editor-status__dot" aria-hidden="true" />
*/} {labels[controller.status]}
{controller.status === "CONFLICT" ? ( </p>
<p className="studio-editor-conflict" role="alert">서버 최신본과 충돌했습니다. 이 세션에서는 다시 열어 비교해 주세요.</p>
) : controller.saveError ? (
<p className="studio-editor-conflict" role="alert">{controller.saveError}</p>
) : controller.publishError ? (
<p className="studio-editor-conflict" role="alert">{controller.publishError}</p>
) : (
<p className="studio-document-status-bar__note">불완전한 초안도 저장할 수 있습니다. Ctrl+S 로도 저장합니다. 게시를 누르면 채워야 할 칸을 그 자리에 표시합니다.</p>
)}
<div className="studio-document-status-bar__actions"> <div className="studio-document-status-bar__actions">
<button type="button" title="Ctrl+S" onClick={() => { void controller.save(); }} disabled={busy || controller.status === "CLEAN" || controller.status === "CONFLICT"}>{controller.status === "SAVING" ? "저장 중…" : "저장"}</button> <button
{/* type="button"
버튼은 저장과 게시 둘뿐이다. 예전에는 게시까지 검증 → 미리보기 → 게시 세 화면을 차례로 title="Ctrl+S"
밟아야 했다 — 백엔드가 게시 요청에 신선한 검증 id 와 미리보기 id, 그리고 현재 경고를 모두 onClick={() => { void controller.save(); }}
확인했다는 목록을 요구하기 때문이다(`PublishStudioDocumentUseCase`). disabled={busy || controller.status === "CLEAN" || controller.status === "CONFLICT"}
>
그 셋은 작성자에게 물어볼 것이 없다. 검증은 서버가 판정하고, 미리보기는 그 판정으로부터 {controller.status === "SAVING" ? "저장 중…" : "저장"}
만들어지며, 경고는 게시를 막지 않는다. 그래서 세 요청을 이 버튼 뒤로 옮겼다. 계약도 </button>
백엔드도 그대로다 — 사라진 것은 작성자가 밟던 화면이지 서버가 지키던 불변식이 아니다.
*/}
<button <button
className="studio-primary-button" className="studio-primary-button"
type="button" type="button"
@@ -71,14 +55,18 @@ export function DocumentStatusBar({
{controller.publishing ? "게시 중…" : "게시"} {controller.publishing ? "게시 중…" : "게시"}
</button> </button>
</div> </div>
{problem ? <p className="studio-editor-command-error" role="alert">{problem}</p> : null}
{unplacedIssues.length ? ( {unplacedIssues.length ? (
<ul className="studio-editor-unplaced-issues" aria-label="칸에 붙지 못한 지적"> <details className="studio-editor-command-issues">
<summary>{unplacedIssues.length}개 항목 확인 필요</summary>
<ul aria-label="칸에 붙지 못한 지적">
{unplacedIssues.map((issue) => ( {unplacedIssues.map((issue) => (
<li key={`${issue.code}:${issue.path}`} data-severity={issue.severity}> <li key={`${issue.code}:${issue.path}`} data-severity={issue.severity}>
{issue.message} <code>{issue.path}</code> {issue.message} <code>{issue.path}</code>
</li> </li>
))} ))}
</ul> </ul>
</details>
) : null} ) : null}
</aside> </aside>
); );
@@ -55,25 +55,28 @@ export function EditorContextPanel({
return ( return (
<aside className="studio-editor-context" aria-label="이 기록의 맥락"> <aside className="studio-editor-context" aria-label="이 기록의 맥락">
<p className="studio-eyebrow">맥락</p> <div className="studio-editor-context__location">
<span className="studio-editor-context__label">맥락</span>
<dl> <dl>
<div> <div>
<dt>프로젝트</dt> <dt>프로젝트</dt>
<dd>{label(draft.projectId, project, "고르지 않음")}</dd> <dd>{label(draft.projectId, project, "고르지 않음")}</dd>
</div> </div>
<span aria-hidden="true" className="studio-editor-context__separator">/</span>
<div> <div>
<dt>주제</dt> <dt>주제</dt>
<dd>{label(draft.topicId, topic, "고르지 않음")}</dd> <dd>{label(draft.topicId, topic, "고르지 않음")}</dd>
</div> </div>
<span aria-hidden="true" className="studio-editor-context__separator">/</span>
<div> <div>
<dt>종류</dt> <dt>종류</dt>
<dd>{DOCUMENT_KIND_LABELS[draft.kind]}</dd> <dd>{DOCUMENT_KIND_LABELS[draft.kind]}</dd>
</div> </div>
</dl> </dl>
<p className="studio-context-relations-title"> </div>
{related.length > 0 ? `이어지는 기록 ${related.length}` : "이어지는 기록 없음"}
</p>
{related.length > 0 ? ( {related.length > 0 ? (
<details className="studio-editor-context__relations">
<summary>연결된 기록 {related.length}</summary>
<ul> <ul>
{related.map(({ relation, target }) => ( {related.map(({ relation, target }) => (
<li key={relation.id ?? relation.targetId ?? ""}> <li key={relation.id ?? relation.targetId ?? ""}>
@@ -88,7 +91,10 @@ export function EditorContextPanel({
</li> </li>
))} ))}
</ul> </ul>
) : null} </details>
) : (
<span className="studio-editor-context__empty">연결된 기록 없음</span>
)}
</aside> </aside>
); )
} }
@@ -0,0 +1,343 @@
import { forwardRef, type KeyboardEvent, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
type BlockKind =
| "paragraph"
| "heading"
| "bullet"
| "numbered"
| "quote"
| "code"
| "divider"
| "raw";
type MarkdownBlock = Readonly<{
kind: BlockKind;
content: string;
level?: 2 | 3;
language?: string;
}>;
export type MarkdownBlockEditorHandle = Readonly<{
insertMarkdown(markdown: string): void;
}>;
const COMMANDS: ReadonlyArray<Readonly<{ kind: BlockKind; label: string; hint: string }>> = [
{ kind: "paragraph", label: "텍스트", hint: "일반 문단" },
{ kind: "heading", label: "제목", hint: "문서 안의 큰 구분" },
{ kind: "bullet", label: "글머리 목록", hint: "순서 없는 목록" },
{ kind: "numbered", label: "번호 목록", hint: "순서가 있는 목록" },
{ kind: "quote", label: "인용", hint: "주의·인용 문장" },
{ kind: "code", label: "코드", hint: "명령·코드 블록" },
{ kind: "divider", label: "구분선", hint: "내용을 나눕니다" },
];
/**
* 원문을 블록 단위로 나눈다.
*
* <p>검사에서 부른다 — 기존 본문을 블록으로 읽었다가 다시 markdown 으로 쓸 때 글이 바뀌면
* 작성자가 열어 보기만 해도 문서가 상한다. 그 왕복을 실제 본문으로 확인할 길이 필요하다.
*/
export function chunksOf(markdown: string): string[] {
const lines = markdown.replaceAll("\r\n", "\n").split("\n");
const chunks: string[] = [];
let index = 0;
const push = (from: number, to: number) => {
const chunk = lines.slice(from, to).join("\n").trimEnd();
if (chunk.trim()) chunks.push(chunk);
};
while (index < lines.length) {
while (index < lines.length && !lines[index]?.trim()) index += 1;
if (index >= lines.length) break;
const start = index;
const line = lines[index] ?? "";
const fence = line.match(/^\s*(```+|~~~+)/u)?.[1];
if (fence) {
index += 1;
while (index < lines.length) {
const current = lines[index] ?? "";
index += 1;
if (current.trimStart().startsWith(fence)) break;
}
push(start, index);
continue;
}
if (/^\s*:::[\w-]+/u.test(line)) {
index += 1;
while (index < lines.length) {
const current = lines[index] ?? "";
index += 1;
if (/^\s*:::\s*$/u.test(current)) break;
}
push(start, index);
continue;
}
if (/^\s*#{1,6}\s+/u.test(line) || /^\s*(?:---+|___+|\*\*\*+)\s*$/u.test(line)) {
index += 1;
push(start, index);
continue;
}
const listLike = /^\s*(?:[-*+]\s+|\d+[.)]\s+|>\s?)/u.test(line);
if (listLike) {
const matcher = /^\s*(?:[-*+]\s+|\d+[.)]\s+|>\s?)/u;
index += 1;
while (index < lines.length && matcher.test(lines[index] ?? "")) index += 1;
push(start, index);
continue;
}
index += 1;
while (
index < lines.length
&& Boolean(lines[index]?.trim())
&& !/^\s*#{1,6}\s+/u.test(lines[index] ?? "")
&& !/^\s*(```+|~~~+)/u.test(lines[index] ?? "")
&& !/^\s*:::[\w-]+/u.test(lines[index] ?? "")
) index += 1;
push(start, index);
}
return chunks;
}
export function blockOf(raw: string): MarkdownBlock {
const heading = raw.match(/^(#{2,3})\s+([\s\S]*)$/u);
if (heading) return { kind: "heading", level: heading[1]?.length === 3 ? 3 : 2, content: heading[2] ?? "" };
const code = raw.match(/^(```+|~~~+)([^\n]*)\n?([\s\S]*?)\n?\1\s*$/u);
if (code) return { kind: "code", language: (code[2] ?? "").trim(), content: code[3] ?? "" };
if (/^\s*(?:---+|___+|\*\*\*+)\s*$/u.test(raw)) return { kind: "divider", content: "" };
if (/^\s*:::[\w-]+/u.test(raw) || /^\s*\|/u.test(raw)) return { kind: "raw", content: raw };
if (/^\s*>\s?/u.test(raw)) return { kind: "quote", content: raw.split("\n").map((line) => line.replace(/^\s*>\s?/u, "")).join("\n") };
if (/^\s*[-*+]\s+/u.test(raw)) return { kind: "bullet", content: raw.split("\n").map((line) => line.replace(/^\s*[-*+]\s+/u, "")).join("\n") };
if (/^\s*\d+[.)]\s+/u.test(raw)) return { kind: "numbered", content: raw.split("\n").map((line) => line.replace(/^\s*\d+[.)]\s+/u, "")).join("\n") };
return { kind: "paragraph", content: raw };
}
function markdownOf(block: MarkdownBlock): string {
switch (block.kind) {
case "heading": return `${"#".repeat(block.level ?? 2)} ${block.content.trimEnd()}`;
case "bullet": return block.content.split("\n").map((line) => `- ${line}`).join("\n");
case "numbered": return block.content.split("\n").map((line, index) => `${index + 1}. ${line}`).join("\n");
case "quote": return block.content.split("\n").map((line) => `> ${line}`).join("\n");
case "code": return `\`\`\`${block.language ?? ""}\n${block.content}\n\`\`\``;
case "divider": return "---";
case "raw":
case "paragraph":
default: return block.content;
}
}
export function documentOf(blocks: readonly MarkdownBlock[]): string {
return blocks.map(markdownOf).filter((block) => block.trim()).join("\n\n");
}
function blankBlock(kind: BlockKind): MarkdownBlock {
if (kind === "heading") return { kind, level: 2, content: "" };
if (kind === "code") return { kind, language: "", content: "" };
if (kind === "divider") return { kind, content: "" };
return { kind, content: "" };
}
function kindLabel(block: MarkdownBlock): string {
if (block.kind === "raw" && block.content.startsWith(":::evidence")) return "자료";
return {
paragraph: "텍스트",
heading: `제목 ${block.level ?? 2}`,
bullet: "목록",
numbered: "번호",
quote: "인용",
code: "코드",
divider: "구분선",
raw: "고급 블록",
}[block.kind];
}
export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonly<{
value: string;
label: string;
onChange(value: string): void;
}>>(function MarkdownBlockEditor({ value, label, onChange }, ref) {
const parsed = useMemo(() => chunksOf(value).map(blockOf), [value]);
const [blocks, setBlocks] = useState<MarkdownBlock[]>(() => parsed.length ? parsed : [blankBlock("paragraph")]);
const [activeIndex, setActiveIndex] = useState(0);
const [insertMenu, setInsertMenu] = useState<number | null>(null);
const lastEmitted = useRef(value);
// Blank blocks are real authoring state even though Markdown has no token for
// them. Keep them locally; only replace the local document when a genuinely
// external value arrives (load/reset), not after our own onChange round-trip.
useEffect(() => {
if (value === lastEmitted.current) return;
const incoming = chunksOf(value).map(blockOf);
setBlocks(incoming.length ? incoming : [blankBlock("paragraph")]);
lastEmitted.current = value;
}, [value]);
/*
`useImperativeHandle` 안에서 부르므로 정체성이 렌더마다 바뀌면 안 된다. 바뀌는 것은
`onChange` 하나이고 나머지(setState·ref)는 React 가 고정해 준다.
*/
const commit = useCallback(
(next: readonly MarkdownBlock[]) => {
const materialized = [...next];
setBlocks(materialized);
const markdown = documentOf(materialized);
lastEmitted.current = markdown;
onChange(markdown);
},
[onChange],
);
const replace = (index: number, next: MarkdownBlock) => commit(blocks.map((block, at) => at === index ? next : block));
const insert = (at: number, block: MarkdownBlock) => {
const next = [...blocks];
next.splice(at, 0, block);
commit(next);
setActiveIndex(at);
setInsertMenu(null);
};
useImperativeHandle(ref, () => ({
insertMarkdown(markdown: string) {
const incoming = chunksOf(markdown).map(blockOf);
const next = [...blocks];
const at = Math.min(activeIndex + 1, next.length);
next.splice(at, 0, ...(incoming.length ? incoming : ([{ kind: "raw", content: markdown }] satisfies MarkdownBlock[])));
commit(next);
setActiveIndex(at);
},
}), [activeIndex, blocks, commit]);
const move = (index: number, delta: -1 | 1) => {
const target = index + delta;
if (target < 0 || target >= blocks.length) return;
const next = [...blocks];
[next[index], next[target]] = [next[target]!, next[index]!];
commit(next);
setActiveIndex(target);
};
const remove = (index: number) => {
if (blocks.length === 1) {
commit([blankBlock("paragraph")]);
return;
}
commit(blocks.filter((_, at) => at !== index));
setActiveIndex(Math.max(0, index - 1));
};
const chooseCommand = (index: number, kind: BlockKind) => {
replace(index, blankBlock(kind));
setInsertMenu(null);
};
const keyDown = (event: KeyboardEvent<HTMLTextAreaElement>, index: number, block: MarkdownBlock) => {
if (event.key === "/" && block.content === "") {
queueMicrotask(() => setInsertMenu(index));
return;
}
if (event.key === "Escape") setInsertMenu(null);
if (event.key === "Enter" && !event.shiftKey && block.kind === "heading") {
event.preventDefault();
insert(index + 1, blankBlock("paragraph"));
}
};
return (
<section className="studio-block-editor" aria-label={label}>
<textarea className="studio-markdown-source" aria-hidden="true" tabIndex={-1} readOnly value={documentOf(blocks)} />
<div className="studio-block-editor__blocks">
{blocks.map((block, index) => (
<div
className="studio-authoring-block"
data-kind={block.kind}
data-active={activeIndex === index ? "" : undefined}
key={index}
onFocusCapture={() => setActiveIndex(index)}
>
<div className="studio-authoring-block__gutter" aria-label={`${kindLabel(block)} 블록 작업`}>
<button type="button" className="studio-block-grip" title="블록 메뉴" onClick={() => setInsertMenu(insertMenu === index ? null : index)} aria-label={`${index + 1}번째 블록 메뉴`}>⋮⋮</button>
</div>
<div className="studio-authoring-block__content">
{block.kind === "divider" ? (
<div className="studio-block-divider" role="separator" />
) : block.kind === "code" ? (
<div className="studio-code-authoring-block">
<input
className="studio-code-language"
aria-label={`${index + 1}번째 코드 언어`}
value={block.language ?? ""}
placeholder="language"
onChange={(event) => replace(index, { ...block, language: event.currentTarget.value })}
/>
<textarea
aria-label={`${index + 1}번째 코드`}
value={block.content}
spellCheck={false}
placeholder="코드나 명령을 입력하세요"
onKeyDown={(event) => keyDown(event, index, block)}
onChange={(event) => replace(index, { ...block, content: event.currentTarget.value })}
/>
</div>
) : block.kind === "raw" ? (
<div className="studio-raw-authoring-block">
<span>{kindLabel(block)}</span>
<textarea
aria-label={`${index + 1}번째 ${kindLabel(block)}`}
value={block.content}
spellCheck={false}
onChange={(event) => replace(index, { ...block, content: event.currentTarget.value })}
/>
</div>
) : (
<textarea
className={`studio-block-input studio-block-input--${block.kind}`}
aria-label={`${index + 1}번째 ${kindLabel(block)}`}
rows={1}
value={block.content}
placeholder={block.kind === "paragraph" ? "내용을 입력하거나 / 를 눌러 블록을 추가하세요" : kindLabel(block)}
onKeyDown={(event) => keyDown(event, index, block)}
onChange={(event) => {
const content = event.currentTarget.value;
replace(index, { ...block, content });
if (content === "/") setInsertMenu(index);
else if (insertMenu === index) setInsertMenu(null);
}}
/>
)}
</div>
<div className="studio-authoring-block__actions" aria-label={`${index + 1}번째 블록 순서와 삭제`}>
<button type="button" onClick={() => move(index, -1)} disabled={index === 0} aria-label="위로 이동">↑</button>
<button type="button" onClick={() => move(index, 1)} disabled={index === blocks.length - 1} aria-label="아래로 이동">↓</button>
<button type="button" onClick={() => remove(index)} aria-label="블록 삭제">삭제</button>
</div>
{insertMenu === index ? (
<div className="studio-slash-menu" role="menu" aria-label="블록 추가">
<p>블록</p>
{COMMANDS.map((command) => (
<button
key={command.kind}
type="button"
role="menuitem"
onClick={() => block.content === "/" ? chooseCommand(index, command.kind) : insert(index + 1, blankBlock(command.kind))}
>
<strong>{command.label}</strong>
<span>{command.hint}</span>
</button>
))}
</div>
) : null}
</div>
))}
</div>
<button className="studio-block-add" type="button" onClick={() => insert(blocks.length, blankBlock("paragraph"))}>+ 블록 추가</button>
<p className="studio-block-editor__hint">빈 블록에서 <kbd>/</kbd> 를 입력하면 제목·목록·코드 같은 블록으로 바꿀 수 있습니다.</p>
</section>
);
});
@@ -9,19 +9,20 @@ function ordered(items: OrderedText[]): OrderedText[] {
return items.map((item, order) => ({ ...item, order })); return items.map((item, order) => ({ ...item, order }));
} }
/** /** Reorderable semantic block collection used by QUESTION/REFERENCE/DECISION. */
* 순서 있는 항목 목록. export function OrderedTextList({
* label,
* <p>Question 문서 하나가 7,540px 이고 textarea 가 21개였다. 반복 그룹이 여섯이고 각 항목마다 fieldId,
* 「위로 · 아래로 · 삭제」 셋이 붙어 버튼이 51개였다 — 폼의 대부분이 순서를 바꾸는 버튼이었고, items,
* 정작 21개 입력칸은 크기·테두리·배경이 전부 같아 「확인한 사실 2」와 「선택지 4」가 눈으로 tone,
* 구분되지 않았다. onChange,
* }: {
* <p>두 가지를 바꾼다. 그룹을 접을 수 있게 해서 지금 쓰지 않는 것은 한 줄로 줄이고, 순서 바꾸기는 label: string;
* 끌어서 한다. 「위로/아래로」는 남긴다 — 끌기는 키보드로 할 수 없고, 그것만 두면 키보드로 쓰는 fieldId?: string;
* 사람에게서 순서 바꾸기를 통째로 빼앗는다. 대신 작게 적는다. items: OrderedText[];
*/ tone?: "fact" | "assumption" | "unknown" | "constraint" | "example" | "impact";
export function OrderedTextList({ label, fieldId, items, onChange }: { label: string; fieldId?: string; items: OrderedText[]; onChange(items: OrderedText[]): void }) { onChange(items: OrderedText[]): void;
}) {
const [collapsed, setCollapsed] = useState(false); const [collapsed, setCollapsed] = useState(false);
const [draggingIndex, setDraggingIndex] = useState<number | null>(null); const [draggingIndex, setDraggingIndex] = useState<number | null>(null);
@@ -33,7 +34,6 @@ export function OrderedTextList({ label, fieldId, items, onChange }: { label: st
onChange(ordered(next)); onChange(ordered(next));
}; };
/** 끌어 놓은 자리로 옮긴다. 두 항목을 맞바꾸지 않고 빼서 끼운다 — 세 칸을 건너뛸 때 그 사이가 뒤집히지 않는다. */
const dropAt = (target: number) => { const dropAt = (target: number) => {
if (draggingIndex === null || draggingIndex === target) return; if (draggingIndex === null || draggingIndex === target) return;
const next = [...items]; const next = [...items];
@@ -44,48 +44,44 @@ export function OrderedTextList({ label, fieldId, items, onChange }: { label: st
}; };
return ( return (
<fieldset id={fieldId} className="studio-ordered-list" tabIndex={fieldId ? -1 : undefined}> <fieldset id={fieldId} className="studio-ordered-list studio-block-collection" data-tone={tone} tabIndex={fieldId ? -1 : undefined}>
<legend> <legend>
{label} <span>{label}</span>
{/* 지금 쓰지 않는 그룹은 한 줄로 줄인다. 개수를 함께 적어 접은 채로도 무엇이 들었는지 안다. */} <span className="studio-block-collection__count">{items.length}</span>
<button <button className="studio-ordered-list__toggle" type="button" aria-expanded={!collapsed} onClick={() => setCollapsed((current) => !current)}>
className="studio-ordered-list__toggle" {collapsed ? "펼치기" : "접기"}
type="button"
aria-expanded={!collapsed}
onClick={() => setCollapsed((current) => !current)}
>
{collapsed ? `펼치기 (${items.length})` : "접기"}
</button> </button>
</legend> </legend>
{collapsed ? null : ( {collapsed ? null : (
<> <>
{items.length === 0 ? <p>아직 입력한 항목이 없습니다.</p> : null} {items.length === 0 ? <p className="studio-block-collection__empty">아직 입력한 항목이 없습니다.</p> : null}
{items.map((item, index) => ( {items.map((item, index) => (
<div <div
className={`studio-ordered-item${draggingIndex === index ? " is-dragging" : ""}`} className={`studio-ordered-item studio-list-block${draggingIndex === index ? " is-dragging" : ""}`}
key={item.id} key={item.id}
onDragOver={(event) => { onDragOver={(event) => { if (draggingIndex !== null) event.preventDefault(); }}
if (draggingIndex !== null) event.preventDefault(); onDrop={(event) => { event.preventDefault(); dropAt(index); }}
}}
onDrop={(event) => {
event.preventDefault();
dropAt(index);
}}
> >
<span <span className="studio-ordered-item__handle" draggable aria-hidden="true" onDragStart={() => setDraggingIndex(index)} onDragEnd={() => setDraggingIndex(null)}>⋮⋮</span>
className="studio-ordered-item__handle" <span className="studio-list-block__index" aria-hidden="true">{String(index + 1).padStart(2, "0")}</span>
draggable <label>
aria-hidden="true" <span className="studio-visually-hidden">{label} {index + 1}</span>
onDragStart={() => setDraggingIndex(index)} <textarea
onDragEnd={() => setDraggingIndex(null)} id={fieldId ? `${fieldId}-${index}-text` : undefined}
> aria-label={`${label} ${index + 1}`}
⠿ value={item.text}
</span> placeholder={`${label}을 입력하세요`}
<label><span>{label} {index + 1}</span><textarea id={fieldId ? `${fieldId}-${index}-text` : undefined} value={item.text} onChange={(event) => onChange(ordered(items.map((candidate, candidateIndex) => candidateIndex === index ? { ...candidate, text: event.currentTarget.value } : candidate)))} /></label> onChange={(event) => onChange(ordered(items.map((candidate, candidateIndex) => candidateIndex === index ? { ...candidate, text: event.currentTarget.value } : candidate)))}
<div className="studio-item-actions"><button type="button" onClick={() => move(index, -1)} disabled={index === 0}>위로</button><button type="button" onClick={() => move(index, 1)} disabled={index === items.length - 1}>아래로</button><button type="button" onClick={() => onChange(ordered(items.filter((_, candidateIndex) => candidateIndex !== index)))}>삭제</button></div> />
</label>
<div className="studio-item-actions">
<button type="button" onClick={() => move(index, -1)} disabled={index === 0} aria-label="위로">↑</button>
<button type="button" onClick={() => move(index, 1)} disabled={index === items.length - 1} aria-label="아래로">↓</button>
<button type="button" onClick={() => onChange(ordered(items.filter((_, candidateIndex) => candidateIndex !== index)))}>삭제</button>
</div>
</div> </div>
))} ))}
<button className="studio-add-item" type="button" disabled={items.length >= 50} onClick={() => { if (items.length < 50) onChange(ordered([...items, { id: createNewItemId(), text: "", order: items.length }])); }}>{label} 추가</button> <button className="studio-add-item" aria-label={`${label} 추가`} type="button" disabled={items.length >= 50} onClick={() => { if (items.length < 50) onChange(ordered([...items, { id: createNewItemId(), text: "", order: items.length }])); }}>+ {label}</button>
</> </>
)} )}
</fieldset> </fieldset>
@@ -3,93 +3,22 @@ import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
import { OrderedTextList } from "./ordered-text-list.tsx"; import { OrderedTextList } from "./ordered-text-list.tsx";
type ProjectDecisionInput = components["schemas"]["ProjectDecisionInput"]; type ProjectDecisionInput = components["schemas"]["ProjectDecisionInput"];
export const DECISION_FIELD_PATHS = ["/decisionStatus", "/decidedOn", "/statement", "/rationale", "/consequences"] as const;
/** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. */ export function ProjectDecisionFields({ draft, issues, onChange }: { draft: ProjectDecisionInput; issues: readonly FieldIssue[]; onChange(draft: ProjectDecisionInput): void }) {
export const DECISION_FIELD_PATHS = [ const update = (patch: Partial<ProjectDecisionInput>) => onChange({ ...draft, ...patch });
"/decisionStatus",
"/decidedOn",
"/statement",
"/rationale",
"/consequences",
] as const;
export function ProjectDecisionFields({
draft,
issues,
onChange,
}: {
draft: ProjectDecisionInput;
/** 마지막 게시 시도가 남긴 지적. 각 칸 아래에는 그 칸의 것만 붙는다. */
issues: readonly FieldIssue[];
onChange(draft: ProjectDecisionInput): void;
}) {
const update = (patch: Partial<ProjectDecisionInput>) => {
onChange({ ...draft, ...patch });
};
return ( return (
<section <section className="studio-editor-section studio-record-authoring" aria-labelledby="studio-project-decision-fields-title">
className="studio-editor-section" <div className="studio-editor-section-heading"><p className="studio-eyebrow">PROJECT DECISION</p><h2 id="studio-project-decision-fields-title">프로젝트 결정</h2><p>선택 자체보다 왜 그렇게 결정했는지와 남는 영향을 함께 기록합니다.</p></div>
aria-labelledby="studio-project-decision-fields-title"
> <div className="studio-decision-properties">
<div className="studio-editor-section-heading"> <fieldset className="studio-inline-choice" aria-label="결정 상태"><legend>상태</legend>{([ [null,"미정"], ["PROPOSED","PROPOSED"], ["ADOPTED","ADOPTED"] ] as const).map(([value,label]) => <button key={label} type="button" aria-pressed={draft.decisionStatus===value || (!draft.decisionStatus&&value===null)} onClick={() => update({ decisionStatus: value })}>{label}</button>)}<FieldNotice issues={issues} path="/decisionStatus" /></fieldset>
<p className="studio-eyebrow">PROJECT DECISION</p> <label className="studio-inline-property studio-inline-property--date"><span>결정일</span><input aria-label="결정일" type="date" value={draft.decidedOn ?? ""} onChange={(event) => update({ decidedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/decidedOn" /></label>
<h2 id="studio-project-decision-fields-title">프로젝트 결정</h2>
</div> </div>
<div className="studio-field-grid">
<label className="studio-field"> <label className="studio-document-block" data-tone="decision"><span className="studio-document-block__label">결정문</span><textarea aria-label="결정문" value={draft.statement} placeholder="무엇을 선택했는지 단정적으로 적어 주세요." onChange={(event) => update({ statement: event.currentTarget.value })} /><FieldNotice issues={issues} path="/statement" /></label>
<span>결정 상태</span> <label className="studio-document-block" data-tone="rationale"><span className="studio-document-block__label">판단 이유</span><textarea aria-label="판단 이유" value={draft.rationale} placeholder="어떤 근거와 제약 때문에 이 선택을 했는지 적어 주세요." onChange={(event) => update({ rationale: event.currentTarget.value })} /><FieldNotice issues={issues} path="/rationale" /></label>
<select <OrderedTextList label="영향" tone="impact" fieldId="studio-field-consequences" items={draft.consequences} onChange={(consequences) => update({ consequences })} />
value={draft.decisionStatus ?? ""}
onChange={(event) => {
const value = event.currentTarget.value;
update({
decisionStatus: value === "PROPOSED" || value === "ADOPTED"
? value
: null,
});
}}
>
<option value="">아직 정하지 않음</option>
<option value="PROPOSED">PROPOSED</option>
<option value="ADOPTED">ADOPTED</option>
</select>
<FieldNotice issues={issues} path="/decisionStatus" />
</label>
<label className="studio-field">
<span>결정일</span>
<input
type="date"
value={draft.decidedOn ?? ""}
onChange={(event) => {
update({ decidedOn: event.currentTarget.value || null });
}}
/>
<FieldNotice issues={issues} path="/decidedOn" />
</label>
<label className="studio-field studio-field--wide">
<span>결정문</span>
<textarea
value={draft.statement}
onChange={(event) => update({ statement: event.currentTarget.value })}
/>
<FieldNotice issues={issues} path="/statement" />
</label>
<label className="studio-field studio-field--wide">
<span>판단 이유</span>
<textarea
value={draft.rationale}
onChange={(event) => update({ rationale: event.currentTarget.value })}
/>
<FieldNotice issues={issues} path="/rationale" />
</label>
</div>
<OrderedTextList
label="영향"
fieldId="studio-field-consequences"
items={draft.consequences}
onChange={(consequences) => update({ consequences })}
/>
<FieldNotice issues={issues} path="/consequences" /> <FieldNotice issues={issues} path="/consequences" />
</section> </section>
); );
@@ -1,70 +1,78 @@
import type { components } from "../../../contracts/studio/generated.ts"; import type { components } from "../../../contracts/studio/generated.ts";
import { createNewItemId } from "../../../domain/studio/local-id.ts"; import { createNewItemId } from "../../../domain/studio/local-id.ts";
import { CatalogPropertyPicker } from "./catalog-property-picker.tsx";
import { FieldNotice, type FieldIssue } from "./field-issues.tsx"; import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
import { OrderedTextList } from "./ordered-text-list.tsx"; import { OrderedTextList } from "./ordered-text-list.tsx";
/** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. */ export const QUESTION_FIELD_PATHS = ["/questionStatus", "/facts", "/assumptions", "/unknowns", "/constraints", "/options", "/nextValidation", "/resolution"] as const;
export const QUESTION_FIELD_PATHS = [
"/questionStatus",
"/facts",
"/assumptions",
"/unknowns",
"/constraints",
"/options",
"/nextValidation",
"/resolution",
] as const;
type CatalogEntry = components["schemas"]["CatalogEntry"]; type CatalogEntry = components["schemas"]["CatalogEntry"];
type QuestionInput = components["schemas"]["QuestionInput"]; type QuestionInput = components["schemas"]["QuestionInput"];
type QuestionOption = components["schemas"]["QuestionOption"]; type QuestionOption = components["schemas"]["QuestionOption"];
const orderedOptions = (options: QuestionOption[]) => options.map((option, order) => ({ ...option, order }));
function orderedOptions(options: QuestionOption[]): QuestionOption[] {
return options.map((option, order) => ({ ...option, order }));
}
export function QuestionFields({ draft, evidence, issues, onChange }: { draft: QuestionInput; evidence: CatalogEntry[]; issues: readonly FieldIssue[]; onChange(draft: QuestionInput): void }) { export function QuestionFields({ draft, evidence, issues, onChange }: { draft: QuestionInput; evidence: CatalogEntry[]; issues: readonly FieldIssue[]; onChange(draft: QuestionInput): void }) {
const update = (patch: Partial<QuestionInput>) => onChange({ ...draft, ...patch }); const update = (patch: Partial<QuestionInput>) => onChange({ ...draft, ...patch });
const moveOption = (index: number, delta: -1 | 1) => { const setStatus = (status: "OPEN" | "RESOLVED" | null) => {
const target = index + delta; if (status === "RESOLVED") update({ questionStatus: "RESOLVED", resolution: draft.resolution ?? { summary: "", evidenceTargetId: null, linkLabel: "" } });
if (target < 0 || target >= draft.options.length) return; else update({ questionStatus: status, resolution: null });
const next = [...draft.options];
[next[index], next[target]] = [next[target]!, next[index]!];
update({ options: orderedOptions(next) });
}; };
return ( return (
<section className="studio-editor-section" aria-labelledby="studio-question-fields-title"> <section className="studio-editor-section studio-record-authoring" aria-labelledby="studio-question-fields-title">
<div className="studio-editor-section-heading"><p className="studio-eyebrow">QUESTION</p><h2 id="studio-question-fields-title">판단과 다음 검증</h2></div> <div className="studio-editor-section-heading"><p className="studio-eyebrow">QUESTION</p><h2 id="studio-question-fields-title">판단과 다음 검증</h2><p>확인한 것과 아직 모르는 것을 섞지 않고 별도 블록으로 유지합니다.</p></div>
<label className="studio-field"><span>질문 상태</span><select value={draft.questionStatus ?? ""} onChange={(event) => {
const value = event.currentTarget.value; <fieldset className="studio-inline-choice" aria-label="질문 상태">
if (value === "RESOLVED") update({ questionStatus: "RESOLVED", resolution: draft.resolution ?? { summary: "", evidenceTargetId: null, linkLabel: "" } }); <legend>상태</legend>
else update({ questionStatus: value === "OPEN" ? "OPEN" : null, resolution: null }); {([ [null, "미정"], ["OPEN", "OPEN"], ["RESOLVED", "RESOLVED"] ] as const).map(([value, label]) => (
}}><option value="">아직 정하지 않음</option><option value="OPEN">OPEN</option><option value="RESOLVED">RESOLVED</option></select><FieldNotice issues={issues} path="/questionStatus" /></label> <button key={label} type="button" aria-pressed={draft.questionStatus === value || (!draft.questionStatus && value === null)} onClick={() => setStatus(value)}>{label}</button>
<OrderedTextList label="확인한 사실" fieldId="studio-field-facts" items={draft.facts} onChange={(facts) => update({ facts })} /> ))}
<FieldNotice issues={issues} path="/facts" /> <FieldNotice issues={issues} path="/questionStatus" />
<OrderedTextList label="가정" fieldId="studio-field-assumptions" items={draft.assumptions} onChange={(assumptions) => update({ assumptions })} />
<FieldNotice issues={issues} path="/assumptions" />
<OrderedTextList label="남은 미지수" fieldId="studio-field-unknowns" items={draft.unknowns} onChange={(unknowns) => update({ unknowns })} />
<FieldNotice issues={issues} path="/unknowns" />
<OrderedTextList label="제약" fieldId="studio-field-constraints" items={draft.constraints} onChange={(constraints) => update({ constraints })} />
<FieldNotice issues={issues} path="/constraints" />
<fieldset id="studio-field-options" className="studio-ordered-list" tabIndex={-1}><legend>검토한 선택지</legend>
<FieldNotice issues={issues} path="/options" />
{draft.options.length === 0 ? <p>아직 입력한 선택지가 없습니다.</p> : null}
{draft.options.map((option, index) => <div className="studio-ordered-item" key={option.id}>
<label><span>선택지 {index + 1} 제목</span><input value={option.title} onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, candidateIndex) => candidateIndex === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} /></label>
<label><span>선택지 {index + 1} 설명</span><textarea value={option.description} onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, candidateIndex) => candidateIndex === index ? { ...candidate, description: event.currentTarget.value } : candidate)) })} /></label>
<div className="studio-item-actions"><button type="button" onClick={() => moveOption(index, -1)} disabled={index === 0}>위로</button><button type="button" onClick={() => moveOption(index, 1)} disabled={index === draft.options.length - 1}>아래로</button><button type="button" onClick={() => update({ options: orderedOptions(draft.options.filter((_, candidateIndex) => candidateIndex !== index)) })}>삭제</button></div>
</div>)}
<button className="studio-add-item" type="button" disabled={draft.options.length >= 50} onClick={() => { if (draft.options.length < 50) update({ options: orderedOptions([...draft.options, { id: createNewItemId(), title: "", description: "", order: draft.options.length }]) }); }}>선택지 추가</button>
</fieldset> </fieldset>
<label className="studio-field studio-field--wide"><span>다음 검증</span><textarea value={draft.nextValidation} onChange={(event) => update({ nextValidation: event.currentTarget.value })} /><FieldNotice issues={issues} path="/nextValidation" /></label>
{draft.questionStatus === "RESOLVED" && draft.resolution ? <fieldset className="studio-resolution-fields"><legend>해결 내용</legend> <OrderedTextList label="확인한 사실" tone="fact" fieldId="studio-field-facts" items={draft.facts} onChange={(facts) => update({ facts })} />
<FieldNotice issues={issues} path="/facts" />
<OrderedTextList label="가정" tone="assumption" fieldId="studio-field-assumptions" items={draft.assumptions} onChange={(assumptions) => update({ assumptions })} />
<FieldNotice issues={issues} path="/assumptions" />
<OrderedTextList label="남은 미지수" tone="unknown" fieldId="studio-field-unknowns" items={draft.unknowns} onChange={(unknowns) => update({ unknowns })} />
<FieldNotice issues={issues} path="/unknowns" />
<OrderedTextList label="제약" tone="constraint" fieldId="studio-field-constraints" items={draft.constraints} onChange={(constraints) => update({ constraints })} />
<FieldNotice issues={issues} path="/constraints" />
<fieldset id="studio-field-options" className="studio-option-blocks" tabIndex={-1}>
<legend><span>검토한 선택지</span><span>{draft.options.length}</span></legend>
<FieldNotice issues={issues} path="/options" />
{draft.options.map((option, index) => (
<div className="studio-option-block studio-ordered-item" key={option.id}>
<span className="studio-option-block__number">{String(index + 1).padStart(2, "0")}</span>
<div className="studio-option-block__writing">
<input aria-label={`선택지 ${index + 1} 제목`} value={option.title} placeholder="선택지" onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, at) => at === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} />
<textarea aria-label={`선택지 ${index + 1} 설명`} value={option.description} placeholder="장단점과 배제 이유를 적어 주세요." onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, at) => at === index ? { ...candidate, description: event.currentTarget.value } : candidate)) })} />
</div>
<div className="studio-item-actions"><button type="button" aria-label="위로" onClick={() => { const target=index-1; if(target<0)return; const next=[...draft.options]; [next[index],next[target]]=[next[target]!,next[index]!]; update({options:orderedOptions(next)}); }} disabled={index===0}>↑</button><button type="button" aria-label="아래로" onClick={() => { const target=index+1; if(target>=draft.options.length)return; const next=[...draft.options]; [next[index],next[target]]=[next[target]!,next[index]!]; update({options:orderedOptions(next)}); }} disabled={index===draft.options.length-1}>↓</button><button type="button" onClick={() => update({ options: orderedOptions(draft.options.filter((_, at) => at !== index)) })}>삭제</button></div>
</div>
))}
<button className="studio-add-item" aria-label="선택지 추가" type="button" disabled={draft.options.length >= 50} onClick={() => { if (draft.options.length < 50) update({ options: orderedOptions([...draft.options, { id: createNewItemId(), title: "", description: "", order: draft.options.length }]) }); }}>+ 선택지</button>
</fieldset>
<label className="studio-document-block" data-tone="next">
<span className="studio-document-block__label">다음 검증</span>
<textarea aria-label="다음 검증" value={draft.nextValidation} placeholder="무엇을 확인해야 다음 판단으로 넘어갈 수 있는지 적어 주세요." onChange={(event) => update({ nextValidation: event.currentTarget.value })} />
<FieldNotice issues={issues} path="/nextValidation" />
</label>
{draft.questionStatus === "RESOLVED" && draft.resolution ? (
<section className="studio-resolution-block" aria-label="해결 내용">
<div className="studio-resolution-block__heading"><span>해결 내용</span><small>이 질문을 닫은 근거와 결론</small></div>
<textarea aria-label="해결 요약" value={draft.resolution.summary} placeholder="어떤 근거로 질문을 해결했는지 적어 주세요." onChange={(event) => update({ resolution: { ...draft.resolution!, summary: event.currentTarget.value } })} />
<div className="studio-resolution-block__properties">
<span>근거 기록</span>
<CatalogPropertyPicker label="해결 근거" value={draft.resolution.evidenceTargetId} entries={evidence} emptyLabel="근거 선택" onChange={(evidenceTargetId) => update({ resolution: { ...draft.resolution!, evidenceTargetId } })} />
<input aria-label="근거 링크 문구" value={draft.resolution.linkLabel} placeholder="링크에 표시할 문구" onChange={(event) => update({ resolution: { ...draft.resolution!, linkLabel: event.currentTarget.value } })} />
</div>
<FieldNotice issues={issues} path="/resolution" /> <FieldNotice issues={issues} path="/resolution" />
<label className="studio-field studio-field--wide"><span>해결 요약</span><textarea value={draft.resolution.summary} onChange={(event) => update({ resolution: { ...draft.resolution!, summary: event.currentTarget.value } })} /></label> </section>
<label className="studio-field"><span>해결 근거</span><select value={draft.resolution.evidenceTargetId ?? ""} onChange={(event) => update({ resolution: { ...draft.resolution!, evidenceTargetId: event.currentTarget.value || null } })}><option value="">근거 선택</option>{evidence.map((entry) => <option key={entry.id} value={entry.id}>{entry.label}</option>)}</select></label> ) : null}
<label className="studio-field"><span>근거 링크 문구</span><input value={draft.resolution.linkLabel} onChange={(event) => update({ resolution: { ...draft.resolution!, linkLabel: event.currentTarget.value } })} /></label>
</fieldset> : null}
</section> </section>
); );
} }
@@ -6,19 +6,8 @@ import { OrderedTextList } from "./ordered-text-list.tsx";
type ReferenceInput = components["schemas"]["ReferenceInput"]; type ReferenceInput = components["schemas"]["ReferenceInput"];
type ReferenceRule = components["schemas"]["ReferenceRule"]; type ReferenceRule = components["schemas"]["ReferenceRule"];
/** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. */ export const REFERENCE_FIELD_PATHS = ["/purpose", "/rules", "/applyWhen", "/exceptions", "/examples", "/verifiedOn"] as const;
export const REFERENCE_FIELD_PATHS = [ const orderedRules = (rules: ReferenceRule[]) => rules.map((rule, order) => ({ ...rule, order }));
"/purpose",
"/rules",
"/applyWhen",
"/exceptions",
"/examples",
"/verifiedOn",
] as const;
function orderedRules(rules: ReferenceRule[]): ReferenceRule[] {
return rules.map((rule, order) => ({ ...rule, order }));
}
export function ReferenceFields({ draft, issues, onChange }: { draft: ReferenceInput; issues: readonly FieldIssue[]; onChange(draft: ReferenceInput): void }) { export function ReferenceFields({ draft, issues, onChange }: { draft: ReferenceInput; issues: readonly FieldIssue[]; onChange(draft: ReferenceInput): void }) {
const update = (patch: Partial<ReferenceInput>) => onChange({ ...draft, ...patch }); const update = (patch: Partial<ReferenceInput>) => onChange({ ...draft, ...patch });
@@ -29,27 +18,41 @@ export function ReferenceFields({ draft, issues, onChange }: { draft: ReferenceI
[next[index], next[target]] = [next[target]!, next[index]!]; [next[index], next[target]] = [next[target]!, next[index]!];
update({ rules: orderedRules(next) }); update({ rules: orderedRules(next) });
}; };
return ( return (
<section className="studio-editor-section" aria-labelledby="studio-reference-fields-title"> <section className="studio-editor-section studio-record-authoring" aria-labelledby="studio-reference-fields-title">
<div className="studio-editor-section-heading"><p className="studio-eyebrow">REFERENCE</p><h2 id="studio-reference-fields-title">재사용할 기준</h2></div> <div className="studio-editor-section-heading"><p className="studio-eyebrow">REFERENCE</p><h2 id="studio-reference-fields-title">재사용할 기준</h2><p>나중에 다시 찾아도 바로 판단할 수 있도록 규칙을 짧고 독립적인 블록으로 적습니다.</p></div>
<label className="studio-field studio-field--wide"><span>이 기준을 쓰는 이유</span><textarea value={draft.purpose} onChange={(event) => update({ purpose: event.currentTarget.value })} /><FieldNotice issues={issues} path="/purpose" /></label>
<fieldset className="studio-ordered-list"><legend>판단 기준</legend> <label className="studio-document-block" data-tone="purpose">
<span className="studio-document-block__label">이 기준을 쓰는 이유</span>
<textarea aria-label="이 기준을 쓰는 이유" value={draft.purpose} placeholder="이 기준이 어떤 판단을 빠르게 만드는지 적어 주세요." onChange={(event) => update({ purpose: event.currentTarget.value })} />
<FieldNotice issues={issues} path="/purpose" />
</label>
<fieldset className="studio-rule-blocks">
<legend><span>판단 기준</span><span>{draft.rules.length}</span></legend>
<FieldNotice issues={issues} path="/rules" /> <FieldNotice issues={issues} path="/rules" />
{draft.rules.length === 0 ? <p>아직 입력한 판단 기준이 없습니다.</p> : null} {draft.rules.map((rule, index) => (
{draft.rules.map((rule, index) => <div className="studio-ordered-item" key={rule.id}> <div className="studio-rule-block studio-ordered-item" key={rule.id}>
<label><span>판단 기준 {index + 1} 제목</span><input value={rule.title} onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, candidateIndex) => candidateIndex === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} /></label> <span className="studio-rule-block__number" aria-hidden="true">{String(index + 1).padStart(2, "0")}</span>
<label><span>판단 기준 {index + 1} 본문</span><textarea value={rule.body} onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, candidateIndex) => candidateIndex === index ? { ...candidate, body: event.currentTarget.value } : candidate)) })} /></label> <div className="studio-rule-block__writing">
<div className="studio-item-actions"><button type="button" onClick={() => moveRule(index, -1)} disabled={index === 0}>위로</button><button type="button" onClick={() => moveRule(index, 1)} disabled={index === draft.rules.length - 1}>아래로</button><button type="button" onClick={() => update({ rules: orderedRules(draft.rules.filter((_, candidateIndex) => candidateIndex !== index)) })}>삭제</button></div> <input aria-label={`판단 기준 ${index + 1} 제목`} value={rule.title} placeholder="한 줄 판단 기준" onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, at) => at === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} />
</div>)} <textarea aria-label={`판단 기준 ${index + 1} 본문`} value={rule.body} placeholder="왜 이 기준을 쓰는지, 적용 범위가 무엇인지 설명하세요." onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, at) => at === index ? { ...candidate, body: event.currentTarget.value } : candidate)) })} />
<button className="studio-add-item" type="button" disabled={draft.rules.length >= 50} onClick={() => { if (draft.rules.length < 50) update({ rules: orderedRules([...draft.rules, { id: createNewItemId(), title: "", body: "", order: draft.rules.length }]) }); }}>판단 기준 추가</button> </div>
<div className="studio-item-actions"><button type="button" aria-label="위로" onClick={() => moveRule(index, -1)} disabled={index === 0}>↑</button><button type="button" aria-label="아래로" onClick={() => moveRule(index, 1)} disabled={index === draft.rules.length - 1}>↓</button><button type="button" onClick={() => update({ rules: orderedRules(draft.rules.filter((_, at) => at !== index)) })}>삭제</button></div>
</div>
))}
<button className="studio-add-item" aria-label="판단 기준 추가" type="button" disabled={draft.rules.length >= 50} onClick={() => { if (draft.rules.length < 50) update({ rules: orderedRules([...draft.rules, { id: createNewItemId(), title: "", body: "", order: draft.rules.length }]) }); }}>+ 판단 기준</button>
</fieldset> </fieldset>
<OrderedTextList label="적용할 때" items={draft.applyWhen} onChange={(applyWhen) => update({ applyWhen })} />
<OrderedTextList label="적용할 때" tone="fact" items={draft.applyWhen} onChange={(applyWhen) => update({ applyWhen })} />
<FieldNotice issues={issues} path="/applyWhen" /> <FieldNotice issues={issues} path="/applyWhen" />
<OrderedTextList label="예외와 주의" items={draft.exceptions} onChange={(exceptions) => update({ exceptions })} /> <OrderedTextList label="예외와 주의" tone="constraint" items={draft.exceptions} onChange={(exceptions) => update({ exceptions })} />
<FieldNotice issues={issues} path="/exceptions" /> <FieldNotice issues={issues} path="/exceptions" />
<OrderedTextList label="예시" items={draft.examples} onChange={(examples) => update({ examples })} /> <OrderedTextList label="예시" tone="example" items={draft.examples} onChange={(examples) => update({ examples })} />
<FieldNotice issues={issues} path="/examples" /> <FieldNotice issues={issues} path="/examples" />
<label className="studio-field"><span>마지막 검증일</span><input type="date" value={draft.verifiedOn ?? ""} onChange={(event) => update({ verifiedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/verifiedOn" /></label>
<label className="studio-inline-property studio-inline-property--date"><span>마지막 검증일</span><input aria-label="마지막 검증일" type="date" value={draft.verifiedOn ?? ""} onChange={(event) => update({ verifiedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/verifiedOn" /></label>
</section> </section>
); );
} }
@@ -6,13 +6,11 @@ import { useStudioAssetGateway } from "../use-studio.ts";
import { buildEvidenceDirective } from "./asset-picker.tsx"; import { buildEvidenceDirective } from "./asset-picker.tsx";
import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx"; import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx";
import { AssetUploadDialog } from "./asset-upload-dialog.tsx"; import { AssetUploadDialog } from "./asset-upload-dialog.tsx";
import { MarkdownToolbar } from "./markdown-toolbar.tsx";
import { FieldNotice, type FieldIssue } from "./field-issues.tsx"; import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
import { MarkdownBlockEditor, type MarkdownBlockEditorHandle } from "./markdown-block-editor.tsx";
type SetupInput = components["schemas"]["SetupInput"]; type SetupInput = components["schemas"]["SetupInput"];
type PinnedVersion = components["schemas"]["PinnedVersion"]; type PinnedVersion = components["schemas"]["PinnedVersion"];
/** 이 화면이 자기 칸 아래에 보여 줄 수 있는 경로. */
export const SETUP_FIELD_PATHS = ["/pinnedVersions", "/bodyMarkdown"] as const; export const SETUP_FIELD_PATHS = ["/pinnedVersions", "/bodyMarkdown"] as const;
const ASSET_KIND_OPTIONS: ReadonlyArray<{ value: AssetKind; label: string }> = [ const ASSET_KIND_OPTIONS: ReadonlyArray<{ value: AssetKind; label: string }> = [
@@ -21,183 +19,63 @@ const ASSET_KIND_OPTIONS: ReadonlyArray<{ value: AssetKind; label: string }> = [
{ value: "ATTACHMENT", label: "첨부파일" }, { value: "ATTACHMENT", label: "첨부파일" },
]; ];
/** export function SetupFields({ draft, issues, onChange, onAssetsObserved, onAssetUploaded }: {
* `:::evidence ...` is a block directive, so the parser requires a blank line
* before and after it. Inserting straight into `selectionStart`/`selectionEnd`
* without normalizing the surrounding whitespace would produce a directive
* glued to adjacent text -- a well-formed-looking block that the parser still
* rejects.
*/
function insertAtCursor(
textarea: HTMLTextAreaElement,
directive: string,
commit: (next: string) => void,
) {
const { selectionStart, selectionEnd, value } = textarea;
const prefix = value.slice(0, selectionStart);
const suffix = value.slice(selectionEnd);
const before = prefix.length === 0 || prefix.endsWith("\n\n") ? prefix : `${prefix}\n\n`;
const after = suffix.startsWith("\n") ? suffix : `\n${suffix}`;
commit(`${before}${directive}${after}`);
}
/**
* 환경 구성 편집 화면.
*
* <p>다른 다섯 종류는 끝난 일을 적는다. 이 종류만 읽는 사람이 그대로 따라 하는 절차를 적으므로,
* 본문에 명령과 표가 들어간다 — Case 의 「검증 환경」 같은 평문 한 칸으로는 담기지 않는다.
*
* <p>버전만 본문 밖에 둔다. 이 절차가 어느 버전 위에서 성립했는지는 그 기록의 유효 범위이고,
* 목록과 머리말이 본문을 열지 않고 보여 줘야 하는 값이기 때문이다. 개념의 「기준 버전」이 같은
* 이유로 따로 있고, 다른 점은 셋업의 버전이 하나가 아니라 여럿이라는 것뿐이다.
*/
export function SetupFields({
draft,
issues,
onChange,
onAssetsObserved,
onAssetUploaded,
}: {
draft: SetupInput; draft: SetupInput;
/** 마지막 게시 시도가 남긴 지적. 각 칸 아래에는 그 칸의 것만 붙는다. */
issues: readonly FieldIssue[]; issues: readonly FieldIssue[];
onChange(draft: SetupInput): void; onChange(draft: SetupInput): void;
onAssetsObserved?: (assets: readonly Asset[]) => void; onAssetsObserved?: (assets: readonly Asset[]) => void;
onAssetUploaded?: (asset: Asset) => void; onAssetUploaded?: (asset: Asset) => void;
}) { }) {
const assetGateway = useStudioAssetGateway(); const assetGateway = useStudioAssetGateway();
const bodyRef = useRef<HTMLTextAreaElement>(null); const bodyEditorRef = useRef<MarkdownBlockEditorHandle>(null);
const uploadTriggerRef = useRef<HTMLButtonElement>(null); const uploadTriggerRef = useRef<HTMLButtonElement>(null);
const [uploadKind, setUploadKind] = useState<AssetKind>("DIAGRAM"); const [uploadKind, setUploadKind] = useState<AssetKind>("DIAGRAM");
const [uploadOpen, setUploadOpen] = useState(false); const [uploadOpen, setUploadOpen] = useState(false);
const update = (patch: Partial<SetupInput>) => onChange({ ...draft, ...patch }); const update = (patch: Partial<SetupInput>) => onChange({ ...draft, ...patch });
const replaceVersion = (index: number, patch: Partial<PinnedVersion>) => update({ pinnedVersions: draft.pinnedVersions.map((pinned, at) => at === index ? { ...pinned, ...patch } : pinned) });
const replaceVersion = (index: number, patch: Partial<PinnedVersion>) => { const insertDirective = (directive: string) => bodyEditorRef.current?.insertMarkdown(directive);
update({
pinnedVersions: draft.pinnedVersions.map((pinned, at) =>
at === index ? { ...pinned, ...patch } : pinned,
),
});
};
const insertDirective = (directive: string) => {
const textarea = bodyRef.current;
if (!textarea) {
update({
bodyMarkdown: draft.bodyMarkdown
? `${draft.bodyMarkdown}\n\n${directive}\n`
: `${directive}\n`,
});
return;
}
insertAtCursor(textarea, directive, (next) => update({ bodyMarkdown: next }));
};
const closeUpload = () => {
setUploadOpen(false);
queueMicrotask(() => uploadTriggerRef.current?.focus());
};
return ( return (
<section className="studio-editor-section" aria-labelledby="studio-setup-fields-title"> <section className="studio-editor-section studio-record-authoring" aria-labelledby="studio-setup-fields-title">
<div className="studio-editor-section-heading"> <div className="studio-editor-section-heading">
<p className="studio-eyebrow">SETUP</p> <p className="studio-eyebrow">SETUP</p>
<h2 id="studio-setup-fields-title">환경 구성</h2> <h2 id="studio-setup-fields-title">환경 구성</h2>
<p>다시 따라 할 수 있는 절차를 블록 단위로 작성합니다.</p>
</div> </div>
<div className="studio-field-grid">
<div className="studio-field studio-field--wide" role="group" aria-labelledby="studio-pinned-versions-title"> <details className="studio-detail-properties" open={draft.pinnedVersions.length > 0}>
<span id="studio-pinned-versions-title">고정한 버전</span> <summary><span>고정한 버전</span><span>{draft.pinnedVersions.length ? `${draft.pinnedVersions.length}개` : "선택 사항"}</span></summary>
<ul className="studio-pinned-versions"> <div className="studio-version-properties">
{draft.pinnedVersions.map((pinned, index) => ( {draft.pinnedVersions.map((pinned, index) => (
// 행에는 안정된 식별자가 없다. 값으로 키를 만들면 이름을 지우는 순간 키가 <div className="studio-version-property" key={index}>
// 겹쳐 입력 중이던 칸이 다른 행으로 옮겨 간다. <input aria-label={`고정 버전 ${index + 1} 이름`} value={pinned.name} placeholder="Keycloak" onChange={(event) => replaceVersion(index, { name: event.currentTarget.value })} />
<li key={index}> <input aria-label={`고정 버전 ${index + 1} 버전`} value={pinned.version} placeholder="26.7.0" onChange={(event) => replaceVersion(index, { version: event.currentTarget.value })} />
<label> <button type="button" onClick={() => update({ pinnedVersions: draft.pinnedVersions.filter((_, at) => at !== index) })}>삭제</button>
<span>이름</span> </div>
<input
value={pinned.name}
onChange={(event) => replaceVersion(index, { name: event.currentTarget.value })}
/>
</label>
<label>
<span>버전</span>
<input
value={pinned.version}
onChange={(event) => replaceVersion(index, { version: event.currentTarget.value })}
/>
</label>
<button
type="button"
onClick={() =>
update({
pinnedVersions: draft.pinnedVersions.filter((_, at) => at !== index),
})
}
>
{`${pinned.name || `${index + 1}번째`} 삭제`}
</button>
</li>
))} ))}
</ul> <button className="studio-inline-add" type="button" onClick={() => update({ pinnedVersions: [...draft.pinnedVersions, { name: "", version: "" }] })}>+ 버전 추가</button>
<button
type="button"
onClick={() =>
update({ pinnedVersions: [...draft.pinnedVersions, { name: "", version: "" }] })
}
>
버전 추가
</button>
<small>&ldquo;Keycloak&rdquo; / &ldquo;26.7.0&rdquo; 처럼 적습니다. 비우면 화면에 표를 그리지 않습니다.</small>
<FieldNotice issues={issues} path="/pinnedVersions" /> <FieldNotice issues={issues} path="/pinnedVersions" />
</div> </div>
<div className="studio-field studio-field--wide"> </details>
<label htmlFor="studio-field-body">절차 Markdown</label>
<MarkdownToolbar target={bodyRef} onInsert={(next) => update({ bodyMarkdown: next })} /> <div className="studio-body-authoring">
<textarea <div className="studio-body-authoring__heading">
id="studio-field-body" <div><span>절차</span><p>명령은 코드 블록으로, 단계는 제목과 목록으로 나누면 공개 화면에도 그대로 반영됩니다.</p></div>
ref={bodyRef} <div className="studio-inline-asset-actions">
className="studio-markdown-field" <AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onAssetsObserved={onAssetsObserved} onInsert={insertDirective} />
value={draft.bodyMarkdown} <label className="studio-asset-kind-field studio-asset-kind-field--compact"><span className="studio-visually-hidden">업로드 종류</span><select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>
onChange={(event) => update({ bodyMarkdown: event.currentTarget.value })} <button ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>업로드</button>
/> </div>
<small>&ldquo;##&rdquo; 소제목이 목차가 됩니다. 명령은 코드블록으로 적어야 그대로 복사됩니다.</small> </div>
<MarkdownBlockEditor ref={bodyEditorRef} label="절차 본문" value={draft.bodyMarkdown} onChange={(bodyMarkdown) => update({ bodyMarkdown })} />
<FieldNotice issues={issues} path="/bodyMarkdown" /> <FieldNotice issues={issues} path="/bodyMarkdown" />
</div> </div>
</div>
<div className="studio-asset-panel" role="group" aria-labelledby="studio-asset-panel-title"> {uploadOpen ? <AssetUploadDialog gateway={assetGateway} kind={uploadKind} onUploaded={(asset) => {
<p className="studio-eyebrow">EVIDENCE</p>
<h3 id="studio-asset-panel-title">본문에 Asset 삽입</h3>
<p>목록에서 선택하면 본문 커서 위치에 evidence 구문을 삽입합니다. READY 상태의 Asset만 선택할 수 있습니다.</p>
<div className="studio-asset-panel-actions">
<label className="studio-asset-kind-field">
<span>업로드 종류</span>
<select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>
{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
</select>
</label>
<button ref={uploadTriggerRef} type="button" onClick={() => setUploadOpen(true)}>
Asset 업로드
</button>
</div>
<AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onAssetsObserved={onAssetsObserved} onInsert={insertDirective} />
</div>
{uploadOpen ? (
<AssetUploadDialog
gateway={assetGateway}
kind={uploadKind}
onUploaded={(asset) => {
onAssetUploaded?.(asset); onAssetUploaded?.(asset);
insertDirective(buildEvidenceDirective({ insertDirective(buildEvidenceDirective({ assetKey: asset.assetKey, alt: asset.decorative ? "" : (asset.altText ?? ""), caption: "", zoom: asset.kind === "DIAGRAM" }));
assetKey: asset.assetKey, setUploadOpen(false);
alt: asset.decorative ? "" : (asset.altText ?? ""), }} onClose={() => setUploadOpen(false)} /> : null}
caption: "",
zoom: asset.kind === "DIAGRAM",
}));
closeUpload();
}}
onClose={closeUpload}
/>
) : null}
</section> </section>
); );
} }
@@ -2542,7 +2542,7 @@ dialog::backdrop {
.public-document-body ul { padding-left: 22px; list-style: disc; } .public-document-body ul { padding-left: 22px; list-style: disc; }
.public-document-body ul > li::marker { color: var(--faint); } .public-document-body ul > li::marker { color: var(--faint); }
.public-document-body ul > li + li { margin-top: 14px; } .public-document-body ul > li + li { margin-top: 14px; }
.reference-purpose { padding: 27px 0 31px; border-top: 1px solid var(--line-strong); border-bottom: 1px solid var(--line); } .reference-purpose { padding: 27px 0 31px; border-top: 1px solid var(--line-strong); border-bottom: 0; }
.reference-purpose h2 { margin: 12px 0 10px; } .reference-purpose h2 { margin: 12px 0 10px; }
.reference-purpose > p:last-child { margin: 0; } .reference-purpose > p:last-child { margin: 0; }
.reference-rules, .reference-rules,
@@ -4879,3 +4879,12 @@ summary {
border-bottom: 1px solid var(--line); border-bottom: 1px solid var(--line);
} }
} }
/* Reference sections share one divider. Purpose used to end with a border and
applicability immediately started with another one, producing two horizontal
rules around a strip of whitespace. Keep the transition owned by the next
section only. */
.reference-purpose + .reference-applicability {
border-top: 1px solid var(--line-strong);
}
File diff suppressed because it is too large Load Diff
+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", () => { test("builds the evidence directive with escaped attribute values", () => {
assert.equal( assert.equal(
buildEvidenceDirective({ 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 --- // --- 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 user = userEvent.setup();
const gateway = createMockStudioGateway(); const gateway = createMockStudioGateway();
const DIAGRAM_ASSET = { const DIAGRAM_ASSET = {
@@ -441,17 +447,8 @@ test("inserts the directive at the saved cursor position and the live preview re
</MemoryRouter>, </MemoryRouter>,
); );
const textarea = (await screen.findByLabelText("본문 Markdown")) as HTMLTextAreaElement; await screen.findByRole("region", { name: "본문" });
const body = textarea.value; screen.getByLabelText("1번째 제목 2").focus();
const cursor = body.indexOf("\n\n");
assert.ok(cursor > 0);
textarea.focus();
textarea.setSelectionRange(cursor, cursor);
/*
자료는 이제 폼에 펼쳐지지 않고 창 안에서 고른다 — 36개가 본문 아래에 전부 늘어서 있으면
글을 쓰는 화면이 자료 관리 화면이 된다. 고르기 전에 창을 연다.
*/
await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" })); await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" }));
await user.click(await screen.findByRole("button", { name: /cursor-test-diagram/ })); 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: "", caption: "",
zoom: true, zoom: true,
}); });
assert.equal( const authored = markdownSource().value;
textarea.value, assert.ok(authored.includes(expectedDirective), authored);
`${body.slice(0, cursor)}\n\n${expectedDirective}${body.slice(cursor)}`, assert.ok(authored.indexOf("## 책임 경계") < authored.indexOf(expectedDirective), authored);
); assert.ok(authored.indexOf(expectedDirective) < authored.indexOf("정책과 명령을 분리합니다."), authored);
expect(screen.getByLabelText("2번째 자료")).toHaveValue(expectedDirective);
const panel = screen.getByRole("region", { name: "즉시 미리보기" }); expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
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");
}); });
// --- Fix round 1 --- // --- Fix round 1 ---
@@ -551,7 +541,7 @@ test("an asset uploaded through the mock composition previews live and passes mo
</MemoryRouter>, </MemoryRouter>,
); );
await screen.findByLabelText("본문 Markdown"); await screen.findByRole("region", { name: "본문" });
await user.click(screen.getByRole("button", { name: "Asset 업로드" })); await user.click(screen.getByRole("button", { name: "Asset 업로드" }));
chooseAndUpload( chooseAndUpload(
new File(["<svg/>"], "boundary-check.svg", { type: "image/svg+xml" }), 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 // `UnsavedLeaveDialog`, which carries the same native `role="dialog"`, so
// asserting on dialog presence/absence is not a safe signal either way). // asserting on dialog presence/absence is not a safe signal either way).
await waitFor(() => { await waitFor(() => {
const value = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value; const value = markdownSource().value;
assert.ok(value.includes('key="boundary-check"'), 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 // 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 // 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>, </MemoryRouter>,
); );
await screen.findByLabelText("본문 Markdown"); await screen.findByRole("region", { name: "본문" });
await user.click(screen.getByRole("button", { name: "Asset 업로드" })); await user.click(screen.getByRole("button", { name: "Asset 업로드" }));
await uploadThroughDialog( await uploadThroughDialog(
user, user,
@@ -1503,10 +1493,10 @@ test("an asset uploaded with alt text inserts that alt and the document validate
); );
await waitFor(() => { await waitFor(() => {
const value = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value; const value = markdownSource().value;
assert.ok(value.includes('key="alt-text-check"'), 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);
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>, </MemoryRouter>,
); );
await screen.findByLabelText("본문 Markdown"); await screen.findByRole("region", { name: "본문" });
await user.click(screen.getByRole("button", { name: "Asset 업로드" })); await user.click(screen.getByRole("button", { name: "Asset 업로드" }));
await uploadThroughDialog( await uploadThroughDialog(
user, user,
@@ -1549,10 +1539,10 @@ test("a decorative upload inserts an empty alt and the document is still publish
); );
await waitFor(() => { await waitFor(() => {
const value = (screen.getByLabelText("본문 Markdown") as HTMLTextAreaElement).value; const value = markdownSource().value;
assert.ok(value.includes('key="decorative-check"'), 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); assert.ok(body.includes('alt=""'), body);
const { report, preview } = await saveValidateAndPreview( 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 // the Picker reports what it *observed*, the screen merges it into a catalog
// that only ever grows. // 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 user = userEvent.setup();
const gateway = createMockStudioGateway(); const gateway = createMockStudioGateway();
const { gateway: assetGateway } = searchableGateway([PICKER_A, PICKER_B]); 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>, </MemoryRouter>,
); );
await screen.findByLabelText("본문 Markdown"); await screen.findByRole("region", { name: "본문" });
/*
자료는 이제 폼에 펼쳐지지 않고 창 안에서 고른다 — 36개가 본문 아래에 전부 늘어서 있으면
글을 쓰는 화면이 자료 관리 화면이 된다. 고르기 전에 창을 연다.
*/
await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" })); await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" }));
await user.click(await screen.findByRole("button", { name: /inserted-diagram/ })); 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); assert.ok(body.includes('key="inserted-diagram"'), body);
// Now search for something that excludes the asset just inserted. The Picker // Search narrows only the picker. The inserted evidence block remains part
// must narrow; the preview must not. // of the document because the editor owns authored content independently.
//
// 넣고 나면 창이 닫힌다 — 넣은 뒤 목록 앞에 남아 있을 이유가 없다. 다시 연다.
await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" })); await user.click(await screen.findByRole("button", { name: "본문에 자료 넣기" }));
await user.type(screen.getByLabelText("Asset 검색"), "other"); await user.type(screen.getByLabelText("Asset 검색"), "other");
await user.click(screen.getByRole("button", { name: "검색" })); await user.click(screen.getByRole("button", { name: "검색" }));
const picker = screen.getByRole("group", { name: "본문에 Asset 삽입" }); const picker = screen.getByRole("dialog", { name: "본문에 넣을 자료 고르기" });
await waitFor(() => await waitFor(() =>
expect(within(picker).queryByRole("button", { name: /inserted-diagram/ })).not.toBeInTheDocument(), expect(within(picker).queryByRole("button", { name: /inserted-diagram/ })).not.toBeInTheDocument(),
); );
const panel = screen.getByRole("region", { name: "즉시 미리보기" }); assert.ok(markdownSource().value.includes('key="inserted-diagram"'));
assert.ok((screen.getByLabelText(/번째 자료/) as HTMLTextAreaElement).value.includes('key="inserted-diagram"'));
assert.equal( expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
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");
}); });
test("mergeAssetCatalog keeps every previously known asset and lets a fresher copy win", () => { 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 () => { it("edits Decision fields on the single document surface without a preview mode", async () => {
const user = userEvent.setup();
const gateway = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway(); const gateway = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway();
const document = await gateway.createDocument(decisionInput(), { const document = await gateway.createDocument(decisionInput(), {
idempotencyKey: "edit-project-decision", idempotencyKey: "edit-project-decision",
@@ -149,7 +148,8 @@ describe("TechLog Studio project decision authoring", () => {
</MemoryRouter>, </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("2026-08-11");
expect(screen.getByLabelText("결정문")).toHaveValue( expect(screen.getByLabelText("결정문")).toHaveValue(
"목록 조회와 컬렉션 로딩을 서로 다른 단계로 수행합니다.", "목록 조회와 컬렉션 로딩을 서로 다른 단계로 수행합니다.",
@@ -163,26 +163,10 @@ describe("TechLog Studio project decision authoring", () => {
expect(screen.getByLabelText("근거 1 대상")).toHaveValue( expect(screen.getByLabelText("근거 1 대상")).toHaveValue(
FIXTURE_IDS.fetchJoinCase, FIXTURE_IDS.fetchJoinCase,
); );
expect(screen.getByRole("complementary", { name: "작업 상태" })) expect(screen.getByLabelText("현재 문서")).toHaveTextContent("PROJECT_DECISION");
.toHaveTextContent("종류설계 결정"); expect(screen.getByRole("main", { name: "문서 편집" })).toBeVisible();
expect(screen.queryByRole("button", { name: "나란히" })).not.toBeInTheDocument();
const preview = screen.getByRole("region", { name: "즉시 미리보기" }); expect(screen.queryByRole("button", { name: "미리보기" })).not.toBeInTheDocument();
expect( expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
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");
}); });
}); });
@@ -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", () => { 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 user = userEvent.setup();
const base = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway(); const base = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway();
const calls = { save: 0, validate: 0, preview: 0, publish: 0 }; 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("요약")).toHaveValue(
"만료 정책과 명령 실행 책임을 분리했습니다.", "만료 정책과 명령 실행 책임을 분리했습니다.",
); );
expect(screen.getByLabelText("Topic")).toHaveValue(FIXTURE_IDS.topicRedis); expect(screen.getByLabelText("Topic")).toHaveTextContent("Redis");
expect(screen.getByLabelText("Project")).toHaveValue(FIXTURE_IDS.projectBackend); 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([ expect(labelsIn(view.container, ".studio-field")).toEqual([
"제목", "제목",
"slug",
"요약", "요약",
"Topic", "프로젝트",
"Project", "주제",
"문제", "URL 이름",
"결론",
"검증 환경",
"재현 조건",
"마지막 검증일",
"본문 Markdown",
]); ]);
expect(screen.getByLabelText("문제")).toHaveValue("저장 기술이 정책을 소유했습니다."); expect(screen.getByLabelText("문제")).toHaveValue("저장 기술이 정책을 소유했습니다.");
expect(screen.getByLabelText("본문 Markdown")).toHaveValue( expect(markdownSource(view.container)).toHaveValue(
"## 책임 경계\n\n정책과 명령을 분리합니다.", "## 책임 경계\n\n정책과 명령을 분리합니다.",
); );
expect(screen.getByLabelText("1번째 제목 2")).toHaveValue("책임 경계");
expect(screen.getByLabelText("2번째 텍스트")).toHaveValue("정책과 명령을 분리합니다.");
expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent("저장됨"); expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent("저장됨");
await user.clear(screen.getByLabelText("제목")); await user.clear(screen.getByLabelText("제목"));
@@ -103,35 +107,21 @@ describe("TechLog Studio document editor", () => {
expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent( expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent(
"저장되지 않음", "저장되지 않음",
); );
/*
종류 이름은 모든 화면이 같은 표를 본다. 예전에는 화면마다 표를 복사해 두어 같은 문서가 // Version/kind belong to the document identity, while the command bar has
편집기에서 "CASE", 목록에서 "Case" 로 갈렸다 — QUESTION 은 네 // only the two real author actions. There is no edit/split/preview state.
가지 표기까지 났다. expect(screen.getByLabelText("현재 문서")).toHaveTextContent("CASE·v4");
*/
expect(screen.getByRole("complementary", { name: "작업 상태" })).toHaveTextContent(
"저장 버전4종류검증 기록",
);
// 작성자가 밟는 단계는 저장과 게시 둘뿐이다. 예전에는 검증 → 미리보기 → 게시 세 화면을
// 차례로 거쳐야 했는데, 그 셋은 백엔드가 게시 요청에 요구하는 값을 만들기 위한 것이지
// 작성자에게 물어볼 것이 아니었다 — 지금은 게시 버튼 뒤에서 잇달아 부른다.
const rail = screen.getByRole("complementary", { name: "작업 상태" }); const rail = screen.getByRole("complementary", { name: "작업 상태" });
expect(within(rail).getAllByRole("button").map((button) => button.textContent)).toEqual([ expect(within(rail).getAllByRole("button").map((button) => button.textContent)).toEqual([
"저장", "저장",
"게시", "게시",
]); ]);
expect(within(rail).queryAllByRole("link")).toHaveLength(0); expect(within(rail).queryAllByRole("link")).toHaveLength(0);
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.getByRole("region", { name: "문서 편집" })).toBeVisible(); expect(screen.queryByRole("region", { name: "즉시 미리보기" })).not.toBeInTheDocument();
expect(
within(screen.getByRole("region", { name: "즉시 미리보기" })).getByRole(
"heading",
{ level: 1, name: "편집한 Redis 경계" },
),
).toBeVisible();
expect(screen.queryByRole("tab", { name: "즉시 미리보기" })).toBeNull();
expect(screen.getByLabelText("제목")).toHaveValue("편집한 Redis 경계"); expect(screen.getByLabelText("제목")).toHaveValue("편집한 Redis 경계");
expect(calls).toEqual({ save: 0, validate: 0, preview: 0, publish: 0 }); expect(calls).toEqual({ save: 0, validate: 0, preview: 0, publish: 0 });
}); });
@@ -227,7 +217,8 @@ describe("TechLog Studio document editor", () => {
const user = userEvent.setup(); const user = userEvent.setup();
renderEditor(FIXTURE_IDS.edgeTokenQuestion); 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.getByLabelText("남은 미지수 1")).toHaveValue("신뢰 헤더 위조 가능성");
expect(screen.getByRole("textbox", { name: "다음 검증" })).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("");
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("해결 근거")).toHaveValue(""); expect(screen.getByLabelText("해결 근거")).toHaveTextContent("근거 선택");
expect(screen.getByLabelText("근거 링크 문구")).toHaveValue(""); expect(screen.getByLabelText("근거 링크 문구")).toHaveValue("");
expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent( expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent(
"저장되지 않음", "저장되지 않음",
@@ -106,7 +106,7 @@ describe("TechLog Studio validation workflow", () => {
view.unmount(); view.unmount();
renderStudio(<DocumentEditorScreen documentId={FIXTURE_IDS.edgeTokenQuestion} />, gateway); 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-facts")).toBeInTheDocument();
expect(document.querySelector("#studio-field-options")).toBeInTheDocument(); expect(document.querySelector("#studio-field-options")).toBeInTheDocument();
}); });