import { useCallback, useEffect, useState, type FormEvent } from "react"; import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx"; import type { TopicEdit, TopicVariantEdit } from "../../../contracts/management/contract.ts"; import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts"; import { useRouteInput } from "../../../../../presentation/routes/route-input.tsx"; import { GuardedStudioLink } from "./guarded-studio-link.tsx"; import { slugFromName } from "./slug-from-name.ts"; import { useSaveShortcut } from "./use-save-shortcut.ts"; import { useStudio } from "../use-studio.ts"; /** 경로 파라미터는 `unknown` 으로 들어온다 — 라우터가 코덱을 통과시킨 값이라도 타입은 좁혀 써야 한다. */ function routeId(value: unknown): string { return typeof value === "string" ? value : ""; } type Draft = { name: string; slug: string; description: string; scope: string; thesis: string; variantLabel: string; }; function toDraft(topic: TopicEdit): Draft { return { name: topic.name, slug: topic.slug, description: topic.description ?? "", scope: topic.scope ?? "", thesis: topic.thesis ?? "", variantLabel: topic.variantLabel ?? "", }; } type VariantDraft = { slug: string; title: string; summary: string; conclusion: string; }; const EMPTY_VARIANT: VariantDraft = { slug: "", title: "", summary: "", conclusion: "" }; /** * 주제 한 편을 편집한다. * *

「주제·프로젝트」 화면은 주제를 만들고 지울 수만 있었다. 이름과 slug 말고는 쓸 자리가 없어, * 주제가 답하는 질문(논지)도 축의 이름도 어디에도 적을 수 없었다 — 공개 주제 화면이 그 둘을 읽는데 * 쓸 곳이 없으니 늘 비어 있었다. * *

축(variant)은 주제 안의 접근/구조 하나다. 인증 경계라면 SPA·BFF·Mediator 가 각각 하나고, * 각자 만들어 보고 무엇을 알게 됐는지가 다르다. 비교표가 읽는 것은 요약이 아니라 그 결론이다. * *

새 CSS 를 만들지 않는다 — 프로젝트 편집기와 같은 클래스를 쓰므로 Studio 의 나머지와 같은 * 간격·타이포·색을 따른다. */ export function TopicEditor() { const { params } = useRouteInput<"TECH_LOG_STUDIO_TOPIC_EDIT">(); const topicId = routeId(params.id); const { managementGateway, setRequestAnnouncement } = useStudio(); const [topic, setTopic] = useState(null); const [draft, setDraft] = useState(null); const [variants, setVariants] = useState([]); const [newVariant, setNewVariant] = useState(EMPTY_VARIANT); const [pending, setPending] = useState(false); const [error, setError] = useState(""); const [generation, setGeneration] = useState(0); const reload = useCallback(() => setGeneration((value) => value + 1), []); useEffect(() => { let cancelled = false; // 동기적으로 던지는 호출도 잡는다 — 다른 Studio 편집기와 같은 이유다. void (async () => { try { const [topicList, variantList] = await Promise.all([ managementGateway.listTopics(), managementGateway.listTopicVariants(topicId), ]); if (cancelled) return; const loaded = topicList.find((entry) => entry.id === topicId); if (!loaded) { setError("주제를 찾을 수 없습니다."); return; } setTopic(loaded); setDraft(toDraft(loaded)); setVariants(variantList); setError(""); } catch { if (!cancelled) setError("주제를 불러오지 못했습니다."); } })(); return () => { cancelled = true; }; }, [managementGateway, topicId, generation]); const update = (patch: Partial) => setDraft((current) => (current ? { ...current, ...patch } : current)); const save = async (event: FormEvent) => { event.preventDefault(); if (pending || !topic || !draft || topic.id === undefined || topic.version === undefined) return; setPending(true); setError(""); try { const saved = await managementGateway.updateTopic(topic.id, { expectedVersion: topic.version, name: draft.name.trim(), // slug 는 공개 주소다. 비워 두면 주제 화면에 닿을 수 없으므로 이름에서 만들어 채운다. slug: draft.slug.trim() || slugFromName(draft.name), description: draft.description, scope: draft.scope, thesis: draft.thesis, variantLabel: draft.variantLabel.trim(), }); setRequestAnnouncement(`주제를 버전 ${saved.version}으로 저장했습니다.`); reload(); } catch (failure) { setError(managementFailureMessage(failure, "주제를 저장하지 못했습니다.")); } finally { setPending(false); } }; // 폼 제출과 같은 일을 하므로 submit 이벤트를 만들어 보낸다 — 검증·기본값 처리가 한 곳에 남는다. useSaveShortcut( () => void save({ preventDefault: () => {} } as FormEvent), Boolean(topic && draft) && !pending, ); const addVariant = async (event: FormEvent) => { event.preventDefault(); if (pending || !newVariant.title.trim()) return; setPending(true); setError(""); try { await managementGateway.createTopicVariant(topicId, { slug: newVariant.slug.trim() || slugFromName(newVariant.title), title: newVariant.title.trim(), summary: newVariant.summary, conclusion: newVariant.conclusion, displayOrder: variants.length, }); setNewVariant(EMPTY_VARIANT); setRequestAnnouncement(`${newVariant.title} 을(를) 추가했습니다.`); reload(); } catch (failure) { setError(managementFailureMessage(failure, "축을 추가하지 못했습니다.")); } finally { setPending(false); } }; const saveVariant = async (variant: TopicVariantEdit) => { if (pending || variant.id === undefined || variant.version === undefined) return; setPending(true); setError(""); try { await managementGateway.updateTopicVariant(topicId, variant.id, { expectedVersion: variant.version, slug: variant.slug, title: variant.title, summary: variant.summary, conclusion: variant.conclusion, displayOrder: variant.displayOrder, }); setRequestAnnouncement(`${variant.title} 을(를) 저장했습니다.`); reload(); } catch (failure) { setError(managementFailureMessage(failure, "축을 저장하지 못했습니다.")); } finally { setPending(false); } }; /* 축을 지우면 거기 걸려 있던 기록이 그 주제의 공통 기록으로 돌아간다. 되돌릴 수 없으므로 묻는다. */ const [pendingDelete, setPendingDelete] = useState(null); const removeVariant = async (variant: TopicVariantEdit) => { if (pending || variant.id === undefined || variant.version === undefined) return; setPending(true); setError(""); try { await managementGateway.deleteTopicVariant(topicId, variant.id, variant.version); setRequestAnnouncement(`${variant.title} 을(를) 삭제했습니다.`); setPendingDelete(null); reload(); } catch (failure) { setError(managementFailureMessage(failure, "축을 삭제하지 못했습니다.")); } finally { setPending(false); } }; const patchVariant = (id: string | undefined, patch: Partial) => setVariants((current) => current.map((variant) => (variant.id === id ? { ...variant, ...patch } : variant)), ); const axisLabel = draft?.variantLabel.trim() || "축"; return (

TOPIC · VERSION {topic?.version ?? "—"}

{topic?.name ?? "주제"}

공개 주제 화면이 여기 값을 그대로 읽습니다.

주제·프로젝트로
{error ? (

{error}

) : null} {!topic && !error ? (

주제를 불러오는 중입니다.

) : null} {topic && draft ? ( <>

TOPIC

기본 정보

목록과 주제 화면에 그대로 나가는 값입니다.

{/* 축의 이름은 주제마다 다르다 — 인증 경계에서는 「구조」, 조회 성능에서는 「조회 전략」. 내부 모델 이름(variant)을 화면에 그대로 쓰지 않는다. */} {/* 논지는 이 주제가 답하는 질문이다. 기록을 합쳐 자동으로 나오는 글이 아니라 사람이 쓰는 글이라, 담을 칸이 없던 동안 주제 화면의 첫 문단이 비어 있었다. */}