feat: UX 리뷰의 남은 네 항목을 반영한다

H2. 편집기.
7,540px 폼에 섹션으로 갈 수단이 목차도 접기도 앵커도 없었다. 화면에 실제로 있는
`section[aria-labelledby]` 를 읽어 목차를 만든다 — 목록을 손으로 적지 않으므로
섹션이 바뀌어도 이 파일은 그대로다.

미리보기가 sticky 로 문서 맨 위에 고정돼, 폼 중반에서 지금 쓰는 문단이 미리보기
어디인지 볼 방법이 없었다. 커서가 지난 마지막 `##` 을 찾아 미리보기의 같은 제목으로
옮긴다. 스크롤 비율을 맞추는 방식은 두 쪽 길이가 다르면 늘 어긋난다. 손으로 넘기는
중에는 따라가지 않는다.

반복 그룹은 접을 수 있고 순서는 끌어서 바꾼다. 「위로/아래로」는 남긴다 — 끌기는
키보드로 할 수 없고, 그것만 두면 키보드로 쓰는 사람에게서 순서 바꾸기를 빼앗는다.
대신 작게 적는다.

H3. 주제와 프로젝트를 탭으로 나눈다.
한 화면이 성격이 다른 두 엔티티를 같은 문법으로 다뤘다. 「추가」 버튼 둘이 같은
이름·같은 모양으로 한 줄에 있었고, 주제 행은 프로젝트에 맞춘 그리드라 절반이
빈칸이었다. 버튼 이름을 「주제 추가」·「프로젝트 추가」로 가르고, 프로젝트 행에서
같은 주소를 두 번 가리키던 「내용 편집」 하나를 없애고, 주제 행에 편집 버튼을 둔다.

M10. 프로필에 연락·구독 수단. 계약은 처음부터 `contacts` 를 주고 있었고 화면이
읽지 않았다 — 읽고 나서 할 수 있는 일이 하나도 없었다. 프로필이 게시 전이면 빈
목록이고 그때는 구역을 그리지 않는다.

M11. 공개 화면 HTML 에 Studio 청크 셋이 modulepreload 로 붙어 있었다. 읽기만 하는
사람이 편집기 번들을 내려받았다. 빌드에서 그 셋만 뺀다 — 공개 라우트의 미리 받기는
그대로 둔다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PTnWufiY9ATv57egkKKVAV
This commit is contained in:
DongHyeonka
2026-09-09 19:27:25 +09:00
co-authored by Claude Opus 5
parent 41b6457166
commit 02fff0cd03
12 changed files with 438 additions and 28 deletions
@@ -6,6 +6,7 @@ import type {
Project,
PublicContentQueries,
PublicRecord,
PublicContact,
PublicTopic,
PublicTopicDetail,
QuestionRecord,
@@ -442,6 +443,26 @@ export function createHttpPublicContentGateway(
* one object with a named slot per kind rather than a list, because each slot
* has its own shape; the order below is the order the screen renders them in.
*/
/** 프로필이 게시되지 않았으면 404 다 — 그것은 오류가 아니라 "아직 없다" 이므로 빈 목록으로 돌린다. */
async function listContacts(): Promise<PublicContact[]> {
const profile = await read<Readonly<{ contacts?: readonly Readonly<Record<string, unknown>>[] }>>(
"getPublicProfile",
{},
);
if (profile === NOT_FOUND) return [];
return Object.freeze(
(profile.contacts ?? [])
.map((contact) =>
Object.freeze({
type: String(contact.type ?? ""),
label: String(contact.label ?? ""),
url: String(contact.url ?? ""),
}),
)
.filter((contact) => contact.label.length > 0 && contact.url.length > 0),
) as PublicContact[];
}
async function listTopics(): Promise<PublicTopic[]> {
const page = await read<Page>("listPublicTopics", {});
if (page === NOT_FOUND) return [];
@@ -676,6 +697,7 @@ export function createHttpPublicContentGateway(
getRecord,
getProject,
getRelease,
listContacts,
listTopics,
getTopicDetail,
getProjectRecords,
@@ -381,6 +381,10 @@ export const publicContentQueries = Object.freeze({
async getProjectActivity(projectSlug: string) {
return getProjectActivity(projectSlug);
},
/* 정적 카탈로그에는 프로필이 없다. 빈 목록이면 화면이 그 구역을 그리지 않는다. */
async listContacts() {
return [];
},
async listTopics() {
return listTopics();
},
@@ -220,6 +220,9 @@ export type Release = {
};
/** 계약 `TopicListItem`. 목록 화면이 쓰는 만큼만 옮긴다. */
/** 계약 `ContactLink`. */
export type PublicContact = { type: string; label: string; url: string };
export type PublicTopic = {
name: string;
slug: string;
@@ -352,6 +355,13 @@ export type PublicContentQueries = Readonly<{
* 있었고, Studio 에서 주제를 만들어도 바뀌지 않았다.
*/
listTopics(): Promise<PublicTopic[]>;
/**
* 프로필의 연락·구독 수단. 프로필이 아직 게시 전이면 빈 목록이다.
*
* <p>읽고 나서 할 수 있는 것이 하나도 없었다 — 이메일도 GitHub 도 피드도 없었다. 계약은
* 처음부터 `contacts` 를 주고 있었고 화면이 그것을 읽지 않았을 뿐이다.
*/
listContacts(): Promise<PublicContact[]>;
/** 주제 한 편. 주제가 없으면 `undefined`. */
getTopicDetail(slug: string): Promise<PublicTopicDetail | undefined>;
getLatestEntries(): Promise<LatestRecordEntry[]>;
@@ -33,13 +33,15 @@ export function ProfilePage() {
const entries = (await queries.searchPublicContent("")).filter(
(item) => item.contentType === "PROJECT",
);
const [resolved, topics] = await Promise.all([
const [resolved, topics, contacts] = await Promise.all([
Promise.all(entries.map((item) => queries.getProject(item.path.replace("/projects/", "")))),
queries.listTopics(),
queries.listContacts(),
]);
return {
currentProjects: resolved.filter((project) => project !== undefined),
topics,
contacts,
};
});
@@ -118,6 +120,30 @@ export function ProfilePage() {
</ul>
)}
</section>
{/*
읽고 나서 할 수 있는 것.
이메일도 GitHub 도 피드도 없어서, 이 기록들을 읽은 사람이 그다음에 할 수 있는 일이
하나도 없었다. 계약은 처음부터 `contacts` 를 주고 있었고 화면이 그것을 읽지 않았다.
프로필이 아직 게시되지 않았으면 빈 목록이고, 그때는 구역을 그리지 않는다 — 제목만
있는 빈 목록은 아무것도 말하지 않는다.
*/}
{view.ready && view.data.contacts.length > 0 ? (
<section className="profile-contacts" aria-labelledby="profile-contacts-title">
<p className="section-kicker">Contact</p>
<h2 id="profile-contacts-title">연락과 구독</h2>
<ul>
{view.data.contacts.map((contact) => (
<li key={contact.url}>
<a href={contact.url} rel="me noreferrer" target="_blank">
{contact.label}
</a>
</li>
))}
</ul>
</section>
) : null}
</main>
);
}
@@ -1,4 +1,6 @@
import type { components } from "../../../contracts/studio/generated.ts";
import { usePreviewScrollSync } from "./use-preview-scroll-sync.ts";
import { EditorSectionToc } from "./editor-section-toc.tsx";
import type { Asset } from "../../../contracts/studio/contract.ts";
import type { TopicVariantEdit } from "../../../contracts/management/contract.ts";
import type { DocumentEditorController } from "./document-editor-controller.ts";
@@ -60,6 +62,17 @@ export function DocumentEditor({
PROJECT_DECISION: DECISION_FIELD_PATHS,
};
const kindPaths = KIND_PATHS[controller.draft.kind];
/*
미리보기가 편집 중인 절을 따라온다. 본문을 쓰는 종류에서만 뜻이 있다 — 구조화된 칸만 있는
종류는 미리보기에 맞출 소제목이 없다.
*/
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]);
/*
@@ -73,12 +86,21 @@ export function DocumentEditor({
return (
<div className="studio-editor-page">
<div className="studio-editor-split">
<section className="studio-editor-workspace" aria-labelledby="studio-edit-title">
<section
id="studio-editor-workspace"
className="studio-editor-workspace"
aria-labelledby="studio-edit-title"
>
<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 목차를 갖고 있고, 같은 일을 여기서 한다.
*/}
<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} />
@@ -101,7 +123,7 @@ export function DocumentEditor({
<p className="studio-eyebrow">LIVE</p>
<h2 id="studio-preview-title">즉시 미리보기</h2>
</header>
<div className="studio-editor-preview__body">
<div id="studio-editor-preview-body" className="studio-editor-preview__body">
<InstantPreview draft={controller.draft} catalog={catalog} assets={assets} />
</div>
</section>
@@ -0,0 +1,95 @@
import { useEffect, useState } from "react";
/**
* 편집 폼의 섹션 목차.
*
* <p>Question 문서 하나를 재어 보면 폼이 7,540px 이고 textarea 가 21개다. 그중 「확인한 사실 2」와
* 「선택지 4」는 크기·테두리·배경이 전부 같아 눈으로 구분되지 않고, 섹션으로 이동할 수단이 목차도
* 접기도 앵커도 없이 하나도 없었다 — 아래쪽을 고치려면 매번 스크롤로 찾아 내려가야 했다.
*
* <p>공개 상세 화면이 이미 sticky 목차를 갖고 있다. 같은 일을 편집 폼에 한다. 다만 섹션은 폼이
* 그리는 것이라 여기서 목록을 손으로 적지 않고, 화면에 실제로 있는 `section[aria-labelledby]` 를
* 읽는다 — 종류가 늘거나 섹션이 바뀌어도 이 파일은 그대로다.
*/
export function EditorSectionToc({ containerId }: { containerId: string }) {
const [sections, setSections] = useState<ReadonlyArray<{ id: string; label: string }>>([]);
const [activeId, setActiveId] = useState<string | null>(null);
useEffect(() => {
const container = document.getElementById(containerId);
if (!container) return;
const read = () => {
const found: Array<{ id: string; label: string }> = [];
for (const section of container.querySelectorAll("section[aria-labelledby]")) {
const labelId = section.getAttribute("aria-labelledby");
const heading = labelId ? document.getElementById(labelId) : null;
const label = heading?.textContent?.trim();
if (labelId && label) found.push({ id: labelId, label });
}
setSections((current) =>
current.length === found.length && current.every((item, at) => item.id === found[at]?.id)
? current
: found,
);
};
read();
/*
섹션은 종류를 바꾸거나 자료를 넣으면 바뀐다. 폼이 다시 그려질 때마다 목차를 다시 읽되,
읽은 결과가 같으면 상태를 바꾸지 않는다 — 그러지 않으면 관찰이 렌더를 부르고 렌더가 다시
관찰을 부른다.
*/
const observer = new MutationObserver(read);
observer.observe(container, { childList: true, subtree: true });
return () => observer.disconnect();
}, [containerId]);
useEffect(() => {
if (sections.length === 0) return;
/*
IntersectionObserver 가 없는 환경이 있다(jsdom 이 그렇다). 없으면 목차는 그대로 두고 지금
어디인지만 표시하지 않는다 — 이동은 여전히 된다.
*/
if (typeof IntersectionObserver !== "function") return;
const observer = new IntersectionObserver(
(entries) => {
const visible = entries
.filter((entry) => entry.isIntersecting)
.sort((left, right) => left.boundingClientRect.top - right.boundingClientRect.top)[0];
if (visible) setActiveId(visible.target.id);
},
{ rootMargin: "-20% 0px -70% 0px" },
);
for (const section of sections) {
const heading = document.getElementById(section.id);
if (heading) observer.observe(heading);
}
return () => observer.disconnect();
}, [sections]);
if (sections.length < 2) return null;
return (
<nav className="studio-editor-toc" aria-label="편집 구역">
<ul>
{sections.map((section) => (
<li key={section.id}>
<a
href={`#${section.id}`}
aria-current={section.id === activeId ? "true" : undefined}
onClick={(event) => {
event.preventDefault();
const heading = document.getElementById(section.id);
heading?.scrollIntoView({ behavior: "smooth", block: "start" });
setActiveId(section.id);
}}
>
{section.label}
</a>
</li>
))}
</ul>
</nav>
);
}
@@ -1,3 +1,5 @@
import { useState } from "react";
import type { components } from "../../../contracts/studio/generated.ts";
import { createNewItemId } from "../../../domain/studio/local-id.ts";
@@ -7,7 +9,22 @@ function ordered(items: OrderedText[]): OrderedText[] {
return items.map((item, order) => ({ ...item, order }));
}
/**
* 순서 있는 항목 목록.
*
* <p>Question 문서 하나가 7,540px 이고 textarea 가 21개였다. 반복 그룹이 여섯이고 각 항목마다
* 「위로 · 아래로 · 삭제」 셋이 붙어 버튼이 51개였다 — 폼의 대부분이 순서를 바꾸는 버튼이었고,
* 정작 21개 입력칸은 크기·테두리·배경이 전부 같아 「확인한 사실 2」와 「선택지 4」가 눈으로
* 구분되지 않았다.
*
* <p>두 가지를 바꾼다. 그룹을 접을 수 있게 해서 지금 쓰지 않는 것은 한 줄로 줄이고, 순서 바꾸기는
* 끌어서 한다. 「위로/아래로」는 남긴다 — 끌기는 키보드로 할 수 없고, 그것만 두면 키보드로 쓰는
* 사람에게서 순서 바꾸기를 통째로 빼앗는다. 대신 작게 적는다.
*/
export function OrderedTextList({ label, fieldId, items, onChange }: { label: string; fieldId?: string; items: OrderedText[]; onChange(items: OrderedText[]): void }) {
const [collapsed, setCollapsed] = useState(false);
const [draggingIndex, setDraggingIndex] = useState<number | null>(null);
const move = (index: number, delta: -1 | 1) => {
const target = index + delta;
if (target < 0 || target >= items.length) return;
@@ -15,17 +32,62 @@ export function OrderedTextList({ label, fieldId, items, onChange }: { label: st
[next[index], next[target]] = [next[target]!, next[index]!];
onChange(ordered(next));
};
/** 끌어 놓은 자리로 옮긴다. 두 항목을 맞바꾸지 않고 빼서 끼운다 — 세 칸을 건너뛸 때 그 사이가 뒤집히지 않는다. */
const dropAt = (target: number) => {
if (draggingIndex === null || draggingIndex === target) return;
const next = [...items];
const [moved] = next.splice(draggingIndex, 1);
if (moved) next.splice(target, 0, moved);
onChange(ordered(next));
setDraggingIndex(null);
};
return (
<fieldset id={fieldId} className="studio-ordered-list" tabIndex={fieldId ? -1 : undefined}>
<legend>{label}</legend>
{items.length === 0 ? <p>아직 입력한 항목이 없습니다.</p> : null}
{items.map((item, index) => (
<div className="studio-ordered-item" key={item.id}>
<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>
<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>
</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>
<legend>
{label}
{/* 지금 쓰지 않는 그룹은 한 줄로 줄인다. 개수를 함께 적어 접은 채로도 무엇이 들었는지 안다. */}
<button
className="studio-ordered-list__toggle"
type="button"
aria-expanded={!collapsed}
onClick={() => setCollapsed((current) => !current)}
>
{collapsed ? `펼치기 (${items.length})` : "접기"}
</button>
</legend>
{collapsed ? null : (
<>
{items.length === 0 ? <p>아직 입력한 항목이 없습니다.</p> : null}
{items.map((item, index) => (
<div
className={`studio-ordered-item${draggingIndex === index ? " is-dragging" : ""}`}
key={item.id}
onDragOver={(event) => {
if (draggingIndex !== null) event.preventDefault();
}}
onDrop={(event) => {
event.preventDefault();
dropAt(index);
}}
>
<span
className="studio-ordered-item__handle"
draggable
aria-hidden="true"
onDragStart={() => setDraggingIndex(index)}
onDragEnd={() => setDraggingIndex(null)}
>
⠿
</span>
<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>
<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>
</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>
</>
)}
</fieldset>
);
}
@@ -36,6 +36,12 @@ export function TaxonomyManager() {
주제와 프로젝트는 다른 기록이 매달려 있는 자리다. 지우기 직전에 무엇이 지워지는지 이름으로
보여 주고 한 번 묻는다 — 목록에서 두 줄 아래를 눌렀다는 것을 여기서 잡는다.
*/
/*
한 화면이 성격이 다른 두 엔티티를 같은 문법으로 다루고 있었다. 만들기 폼 둘이 한 줄에 붙어
「추가」 버튼 두 개가 같은 이름·같은 모양으로 나란히 섰고, 주제 행은 프로젝트에 맞춘 그리드라
절반이 빈칸이었다. 탭으로 나눠 한 번에 한 종류만 다룬다.
*/
const [tab, setTab] = useState<"TOPIC" | "PROJECT">("TOPIC");
const [pendingDelete, setPendingDelete] = useState<
{ kind: "TOPIC"; topic: TopicEdit } | { kind: "PROJECT"; project: ProjectIndexItem } | null
>(null);
@@ -219,7 +225,39 @@ export function TaxonomyManager() {
</div>
</header>
<section className="studio-document-tools" aria-label="주제 만들기">
<div className="studio-taxonomy-tabs" role="tablist" aria-label="주제와 프로젝트">
<button
type="button"
role="tab"
id="taxonomy-tab-topic"
aria-selected={tab === "TOPIC"}
aria-controls={tab === "TOPIC" ? "taxonomy-panel" : undefined}
tabIndex={tab === "TOPIC" ? 0 : -1}
onClick={() => setTab("TOPIC")}
>
{`주제 ${topics?.length ?? 0}`}
</button>
<button
type="button"
role="tab"
id="taxonomy-tab-project"
aria-selected={tab === "PROJECT"}
aria-controls={tab === "PROJECT" ? "taxonomy-panel" : undefined}
tabIndex={tab === "PROJECT" ? 0 : -1}
onClick={() => setTab("PROJECT")}
>
{`프로젝트 ${projects?.length ?? 0}`}
</button>
</div>
<section
id="taxonomy-panel"
role="tabpanel"
aria-labelledby={tab === "TOPIC" ? "taxonomy-tab-topic" : "taxonomy-tab-project"}
className="studio-document-tools"
aria-label={tab === "TOPIC" ? "주제 만들기" : "프로젝트 만들기"}
>
{tab === "TOPIC" ? (
<form onSubmit={submitTopic}>
<label htmlFor="taxonomy-topic-name">새 주제</label>
<div>
@@ -238,10 +276,11 @@ export function TaxonomyManager() {
onChange={(event) => setTopicSlug(event.target.value)}
/>
<button type="submit" disabled={pending}>
추가
주제 추가
</button>
</div>
</form>
) : (
<form onSubmit={submitProject}>
<label htmlFor="taxonomy-project-title">새 프로젝트</label>
<div>
@@ -253,10 +292,11 @@ export function TaxonomyManager() {
onChange={(event) => setProjectTitle(event.target.value)}
/>
<button type="submit" disabled={pending}>
추가
프로젝트 추가
</button>
</div>
</form>
)}
</section>
{loading ? (
@@ -270,7 +310,7 @@ export function TaxonomyManager() {
</p>
) : null}
{!loading && topics ? (
{!loading && topics && tab === "TOPIC" ? (
<>
<p className="studio-result-count">{topics.length}개의 주제</p>
{topics.length ? (
@@ -307,6 +347,19 @@ export function TaxonomyManager() {
</div>
</dl>
<div className="studio-row-actions">
{/*
편집 진입점이 제목 링크뿐이었다. 라벨이 없어 누를 수 있는지 알 수 없었고,
그 화면에 축·논지·범위가 있다는 사실도 목록에서는 드러나지 않았다 —
프로젝트 행과 같은 격으로 버튼을 둔다.
*/}
{topic.id ? (
<GuardedStudioLink
className="studio-secondary-button"
href={`/studio/topics/${topic.id}`}
>
편집
</GuardedStudioLink>
) : null}
<button
className="studio-secondary-button studio-danger-button"
type="button"
@@ -328,7 +381,7 @@ export function TaxonomyManager() {
</>
) : null}
{!loading && projects ? (
{!loading && projects && tab === "PROJECT" ? (
<>
<p className="studio-result-count">{projects.length}개의 프로젝트</p>
{projects.length ? (
@@ -358,20 +411,12 @@ export function TaxonomyManager() {
*/}
<dd>{visibilityLabel[project.targetVisibility] ?? project.targetVisibility}</dd>
</div>
<div>
<dt>다음</dt>
<dd>
<GuardedStudioLink href={`/studio/projects/${project.id}`}>
내용 편집
</GuardedStudioLink>
</dd>
</div>
</dl>
<div className="studio-row-actions">
{/*
「다음: 내용 편집」 을 안내하면서 정작 그 줄의 버튼은 게시 취소와 삭제뿐이라,
편집 진입점이 작은 텍스트 링크로만 있었다. 공개 프로젝트 화면이 비어 있던
이유가 여기다 — 쓰라고 안내하고 쓸 자리를 눈에 띄게 주지 않았다.
편집 진입점은 이 버튼 하나다. 예전에는 「다음: 내용 편집」 이라는 dl 칸과
이 버튼이 같은 주소를 가리키며 한 행에 150px 간격으로 두 번 나왔다 —
읽는 사람은 둘이 다른 일을 한다고 읽는다.
*/}
<GuardedStudioLink
className="studio-secondary-button"
@@ -0,0 +1,74 @@
import { useEffect } from "react";
/**
* 편집 중인 절을 미리보기에서도 보이게 한다.
*
* <p>미리보기는 `position: sticky` 로 문서 맨 위에 고정돼 있다. 폼 중반(예: scrollY 2700, 「가정」
* 편집 중)에서 오른쪽을 보면 여전히 문서 첫 문단이다 — 지금 쓰는 문단이 미리보기 어디에 있는지
* 볼 방법이 없었다.
*
* <p>맞추는 기준은 본문 소제목이다. 편집 폼에서 마지막으로 지나간 `##` 소제목을 찾고, 미리보기에서
* 같은 글을 가진 제목으로 옮긴다 — 두 쪽의 스크롤 비율을 맞추는 방식은 길이가 다르면 늘 어긋난다.
*
* <p>사용자가 미리보기를 직접 스크롤하는 동안에는 손대지 않는다. 따라다니는 것이 방해가 되는
* 순간이 그때다.
*/
export function usePreviewScrollSync(
formId: string,
previewId: string,
enabled: boolean,
): void {
useEffect(() => {
if (!enabled) return;
const form = document.getElementById(formId);
const preview = document.getElementById(previewId);
if (!form || !preview) return;
let userScrolling = 0;
const noteUserScroll = () => {
userScrolling = Date.now();
};
preview.addEventListener("wheel", noteUserScroll, { passive: true });
preview.addEventListener("touchmove", noteUserScroll, { passive: true });
let frame = 0;
const sync = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
// 방금 손으로 넘긴 참이면 따라가지 않는다.
if (Date.now() - userScrolling < 1200) return;
/*
본문 textarea 안에서 커서가 지난 마지막 `##` 을 찾는다. 커서가 없으면(다른 칸을 보는
중이면) 아무것도 하지 않는다 — 화면이 제멋대로 움직이는 것보다 가만히 있는 편이 낫다.
*/
const body = form.querySelector<HTMLTextAreaElement>("textarea.studio-markdown-field");
if (!body || document.activeElement !== body) return;
const before = body.value.slice(0, body.selectionStart);
const headings = [...before.matchAll(/^##\s+(.+)$/gmu)];
const current = headings.at(-1)?.[1]?.trim();
if (!current) return;
const target = [...preview.querySelectorAll("h2, h3")].find(
(heading) => heading.textContent?.replace(/#$/u, "").trim() === current,
);
if (!target) return;
const top =
target.getBoundingClientRect().top -
preview.getBoundingClientRect().top +
preview.scrollTop;
preview.scrollTo({ top: Math.max(0, top - 12), behavior: "smooth" });
});
};
form.addEventListener("keyup", sync);
form.addEventListener("click", sync);
return () => {
cancelAnimationFrame(frame);
form.removeEventListener("keyup", sync);
form.removeEventListener("click", sync);
preview.removeEventListener("wheel", noteUserScroll);
preview.removeEventListener("touchmove", noteUserScroll);
};
}, [enabled, formId, previewId]);
}
@@ -248,3 +248,36 @@
.studio-app .studio-markdown-toolbar { display: flex; flex-wrap: wrap; gap: 6px; margin: -2px 0 6px; }
.studio-app .studio-markdown-toolbar button { min-height: 32px; padding: 0 12px; border: 1px solid var(--line-strong); border-radius: 4px; background: #fff; color: var(--ink-soft); font-size: 12px; font-weight: 600; cursor: pointer; }
.studio-app .studio-markdown-toolbar button:hover { border-color: var(--signal); color: var(--signal); }
/*
편집 폼의 구역 목차.
7,540px 폼에 섹션 이동 수단이 없었다 — 목차도 접기도 앵커도 없어서 아래쪽을 고치려면 매번
스크롤로 찾아 내려가야 했다. 폼 위에 붙여 두고 따라다니게 한다.
*/
.studio-app .studio-editor-toc { position: sticky; top: 0; z-index: 1; margin: 0 0 8px; padding: 10px 0; background: var(--paper, #fff); border-bottom: 1px solid var(--line); }
.studio-app .studio-editor-toc ul { display: flex; flex-wrap: wrap; gap: 4px 14px; margin: 0; padding: 0; list-style: none; }
.studio-app .studio-editor-toc a { color: var(--muted); font-size: 13px; font-weight: 560; }
.studio-app .studio-editor-toc a:hover { color: var(--ink); text-decoration: underline; text-underline-offset: 4px; }
/* 지금 보고 있는 구역. 배경 대신 글자만 진하게 — Studio 의 다른 곳과 같은 언어다. */
.studio-app .studio-editor-toc a[aria-current="true"] { color: var(--ink); font-weight: 700; }
/* 미리보기 본문이 스스로 스크롤한다. 편집 중인 절로 옮기려면 이 요소가 스크롤 컨테이너여야 한다. */
.studio-app .studio-editor-preview__body { flex: 1; min-height: 0; overflow-y: auto; scroll-behavior: smooth; }
/*
반복 그룹.
Question 문서 하나에 textarea 21개와 버튼 51개가 있었고, 그중 34개가 「위로/아래로」였다.
폼의 대부분이 순서를 바꾸는 버튼이었다. 끌기 손잡이를 두고 그 셋은 작게 적는다.
*/
.studio-app .studio-ordered-list legend { display: flex; align-items: baseline; gap: 10px; }
.studio-app .studio-ordered-list__toggle { min-height: 32px; padding: 0 2px; border: 0; background: none; color: var(--muted); font: inherit; font-size: 12px; font-weight: 560; }
.studio-app .studio-ordered-list__toggle:hover { color: var(--ink); text-decoration: underline; text-underline-offset: 4px; }
.studio-app .studio-ordered-item { display: grid; grid-template-columns: 20px minmax(0, 1fr); align-items: start; column-gap: 8px; }
.studio-app .studio-ordered-item__handle { cursor: grab; color: var(--line-strong); font-size: 15px; line-height: 2; user-select: none; }
.studio-app .studio-ordered-item__handle:active { cursor: grabbing; }
.studio-app .studio-ordered-item.is-dragging { opacity: 0.45; }
.studio-app .studio-ordered-item .studio-item-actions { grid-column: 2; }
/* 순서 바꾸기는 이 행의 목적이 아니다 — 글자 크기로 그렇게 말한다. */
.studio-app .studio-ordered-item .studio-item-actions button { font-size: 12px; font-weight: 500; }
@@ -429,3 +429,9 @@
.studio-app .studio-document-row dl > div:nth-child(2) dd a:hover { text-decoration: underline; text-underline-offset: 4px; }
/* 삭제는 여전히 빨강이되 이 행에서 가장 강한 것은 아니게 둔다. */
.studio-app .studio-document-row .studio-danger-button { font-size: 14px; font-weight: 500; }
/* 주제와 프로젝트를 가르는 탭. 홈의 주제 칩과 같은 언어를 쓴다. */
.studio-app .studio-taxonomy-tabs { display: flex; gap: 6px; margin: 24px 0 0; }
.studio-app .studio-taxonomy-tabs button { min-height: 40px; padding: 0 14px; border: 0; border-radius: 17px; background: #f0f0ed; color: var(--muted); font: inherit; font-size: 14px; font-weight: 560; }
.studio-app .studio-taxonomy-tabs button[aria-selected="true"] { background: var(--ink); color: #fff; font-weight: 650; }
.studio-app .studio-taxonomy-tabs button:hover:not([aria-selected="true"]) { color: var(--ink); }