import { useCallback, useEffect, useState, type FormEvent } from "react"; import { PROJECT_PHASE_LABELS } from "../../../domain/public/project-phase-labels.ts"; import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx"; import type { ProjectIndexItem, TopicEdit } from "../../../contracts/management/contract.ts"; import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts"; import { GuardedStudioLink } from "./guarded-studio-link.tsx"; import { slugFromName } from "./slug-from-name.ts"; import { useStudio } from "../use-studio.ts"; /** * 주제와 프로젝트 관리. * *

이 화면이 존재하는 이유는 문서 발행이 주제를 요구하는데 주제를 만들 곳이 없었기 때문이다. * 그래서 범위를 목록·생성·삭제로 끊었다 — 편집(이름 변경, 단계 전환, 공개 범위)은 계약에 있고 * 백엔드도 구현돼 있으나, 그 화면은 별도 설계가 필요하다. * *

새 CSS 를 만들지 않는다. 작업본 목록이 쓰는 클래스만 재사용하므로 이 화면은 Studio 의 * 나머지와 같은 간격·타이포·색을 그대로 따른다. */ const visibilityLabel: Record = { PRIVATE: "비공개", UNLISTED: "주소로만", PUBLIC: "공개", }; export function TaxonomyManager() { const { managementGateway, setRequestAnnouncement } = useStudio(); const [topics, setTopics] = useState(null); const [projects, setProjects] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [pending, setPending] = useState(false); /* 주제와 프로젝트는 다른 기록이 매달려 있는 자리다. 지우기 직전에 무엇이 지워지는지 이름으로 보여 주고 한 번 묻는다 — 목록에서 두 줄 아래를 눌렀다는 것을 여기서 잡는다. */ /* 한 화면이 성격이 다른 두 엔티티를 같은 문법으로 다루고 있었다. 만들기 폼 둘이 한 줄에 붙어 「추가」 버튼 두 개가 같은 이름·같은 모양으로 나란히 섰고, 주제 행은 프로젝트에 맞춘 그리드라 절반이 빈칸이었다. 탭으로 나눠 한 번에 한 종류만 다룬다. */ const [tab, setTab] = useState<"STRUCTURE" | "TOPIC" | "PROJECT">("STRUCTURE"); /* 프로젝트마다 어느 주제를 묶었는지. 목록에는 없고 상세에만 있어 따로 읽는다. */ const [links, setLinks] = useState>(new Map()); const [pendingDelete, setPendingDelete] = useState< { kind: "TOPIC"; topic: TopicEdit } | { kind: "PROJECT"; project: ProjectIndexItem } | null >(null); const [generation, setGeneration] = useState(0); const [topicName, setTopicName] = useState(""); const [topicSlug, setTopicSlug] = useState(""); const [projectTitle, setProjectTitle] = useState(""); const reload = useCallback(() => setGeneration((value) => value + 1), []); useEffect(() => { let cancelled = false; setLoading(true); setError(""); void Promise.all([managementGateway.listTopics(), managementGateway.listProjects(0, 50)]).then( ([topicList, projectPage]) => { if (cancelled) return; setTopics(topicList); const items = projectPage.items ?? []; setProjects(items); setLoading(false); /* 어느 프로젝트가 어느 주제를 묶었는지는 목록에 없고 상세에만 있다. 구조를 그리려면 그 연결이 필요하므로 따로 읽는다 — 실패해도 목록 두 개는 이미 그려져 있으므로 구조 탭만 비고 화면 전체가 죽지는 않는다. */ void Promise.all( items.map(async (project) => project.id ? ([project.id, (await managementGateway.getProject(project.id)).topicIds ?? []] as const) : null, ), ).then( (pairs) => { if (cancelled) return; setLinks(new Map(pairs.filter((pair) => pair !== null))); }, () => undefined, ); }, () => { if (cancelled) return; setError("주제와 프로젝트를 불러오지 못했습니다."); setLoading(false); }, ); return () => { cancelled = true; }; }, [managementGateway, generation]); /** * slug 를 비워 두면 이름에서 만든다. 한글 이름이 흔한데 이전 규칙은 한글을 전부 버려서, 이름에 * 섞인 영문·숫자만 남았다 — `인증` 은 빈 slug 가 되고 `Redis 캐시` 와 `Redis 클러스터` 는 둘 다 * `redis` 가 됐다. 지금은 로마자로 옮긴다 ({@link slugFromName}). */ const slugify = slugFromName; const submitTopic = async (event: FormEvent) => { event.preventDefault(); if (pending) return; const name = topicName.trim(); const slug = slugify(topicSlug || topicName); if (!name || !slug) { setError("주제 이름과 slug 를 입력해 주세요. slug 는 영문·숫자·하이픈만 가능합니다."); return; } setPending(true); setError(""); try { await managementGateway.createTopic({ name, slug } as TopicEdit); setTopicName(""); setTopicSlug(""); setRequestAnnouncement(`주제 ${name} 을(를) 만들었습니다.`); reload(); } catch (error) { setError(managementFailureMessage(error, "주제를 만들지 못했습니다.")); } finally { setPending(false); } }; const submitProject = async (event: FormEvent) => { event.preventDefault(); if (pending) return; const title = projectTitle.trim(); if (!title) { setError("프로젝트 이름을 입력해 주세요."); return; } setPending(true); setError(""); try { const created = await managementGateway.createProject(title); /* 생성 계약은 이름만 받는데(`CreateDraftRequest`), slug 가 없는 프로젝트는 공개 화면에 나타날 수 없다 — 공개 계약의 `ProjectSummary` 는 `slug` 와 `path` 를 요구하므로 서버는 slug 가 빈 프로젝트를 통째로 생략한다. 기록에 프로젝트를 붙여 게시해도 공개 문서의 프로젝트 칸이 비어 있던 이유가 이것이다. 그래서 만든 직후에 이름에서 만든 slug 를 채운다. 주제가 `{name, slug}` 를 함께 보내는 것과 같은 규칙이고(`slugFromName`), 한글 이름도 로마자로 옮겨 유효한 slug 가 된다. */ const project = await managementGateway.getProject(created.id); await managementGateway.updateProject(created.id, { expectedVersion: project.version, name: project.name, slug: slugFromName(project.name), oneLinePurpose: project.oneLinePurpose ?? "", purposeMarkdown: project.purposeMarkdown ?? "", boundaryMarkdown: project.boundaryMarkdown ?? "", phase: project.phase, technologyLabels: project.technologyLabels ?? [], targetVisibility: project.targetVisibility === "PUBLIC" || project.targetVisibility === "UNLISTED" ? project.targetVisibility : "PRIVATE", }); setProjectTitle(""); setRequestAnnouncement(`프로젝트 ${title} 을(를) 만들었습니다.`); reload(); } catch (error) { setError(managementFailureMessage(error, "프로젝트를 만들지 못했습니다.")); } finally { setPending(false); } }; const removeTopic = async (topic: TopicEdit) => { if (pending || topic.id === undefined || topic.version === undefined) return; setPending(true); setError(""); try { await managementGateway.deleteTopic(topic.id, topic.version); setRequestAnnouncement(`주제 ${topic.name} 을(를) 삭제했습니다.`); setPendingDelete(null); reload(); } catch (error) { setError(managementFailureMessage(error, "주제를 삭제하지 못했습니다.")); } finally { setPending(false); } }; const removeProject = async (project: ProjectIndexItem) => { if (pending) return; setPending(true); setError(""); try { await managementGateway.deleteProject(project.id, project.version); setRequestAnnouncement(`프로젝트 ${project.name} 을(를) 삭제했습니다.`); setPendingDelete(null); reload(); } catch (error) { setError(managementFailureMessage(error, "프로젝트를 삭제하지 못했습니다.")); } finally { setPending(false); } }; /* 프로젝트 게시는 문서 게시와 별개다. 문서를 게시해도 그 문서가 속한 프로젝트는 비공개로 남고, 공개 화면들(프로젝트 목록·프로필의 "현재 프로젝트"·홈의 focus)은 전부 게시된 프로젝트만 읽는다. 그래서 그 화면들이 조용히 비어 있었다 — 게시할 방법 자체가 없었기 때문이다. */ const togglePublish = async (project: ProjectIndexItem) => { if (pending) return; setPending(true); setError(""); const published = project.targetVisibility !== "PRIVATE"; try { if (published) { await managementGateway.unpublishProject(project.id, project.version); setRequestAnnouncement(`프로젝트 ${project.name} 을(를) 비공개로 되돌렸습니다.`); } else { await managementGateway.publishProject(project.id, project.version, "PUBLIC"); setRequestAnnouncement(`프로젝트 ${project.name} 을(를) 공개했습니다.`); } reload(); } catch (error) { setError( managementFailureMessage( error, published ? "프로젝트를 비공개로 되돌리지 못했습니다." : "프로젝트를 게시하지 못했습니다.", ), ); } finally { setPending(false); } }; return (

TAXONOMY

주제와 프로젝트

문서를 게시하려면 주제가 필요합니다. 여기서 만들고 정리합니다.

{/* 구조가 먼저다. 주제와 프로젝트를 따로 세는 목록 둘만 있으면 이 화면은 여느 CMS 의 분류 관리와 같아진다 — 이 제품에서 값어치 있는 것은 그 둘의 관계다. */}
{tab === "TOPIC" ? (
setTopicName(event.target.value)} /> setTopicSlug(event.target.value)} />
) : (
setProjectTitle(event.target.value)} />
)}
{loading ? (

주제와 프로젝트를 불러오는 중입니다.

) : null} {error ? (

{error}

) : null} {!loading && topics && projects && tab === "STRUCTURE" ? (
    {projects.map((project) => { const linked = links.get(project.id ?? "") ?? []; const inProject = topics.filter((topic) => topic.id && linked.includes(topic.id)); return (
  1. {project.id ? ( {project.name} ) : ( {project.name} )} {PROJECT_PHASE_LABELS[project.phase] ?? project.phase} {/* 공개 프로젝트 화면의 첫 문단과 상태 줄이 이 값들로 그려진다. 비어 있으면 그 화면이 헐거워지는데, 무엇이 비었는지는 편집기를 열어야 알 수 있었다. */} {project.currentObjective?.trim() ? null : 현재 목표 없음}
    {inProject.length > 0 ? (
      {inProject.map((topic) => (
    • {topic.id ? ( {topic.name} ) : ( topic.name )} {/* 질문이 비어 있으면 공개 주제 화면의 첫 문장이 비어 나온다. */} {topic.thesis?.trim() ? null : 답하는 질문 없음}
    • ))}
    ) : (

    묶은 주제가 없습니다.

    )}
  2. ); })}
{/* 어느 프로젝트에도 걸리지 않은 주제. 걸리지 않았다는 사실 자체가 구조의 상태이므로 숨기지 않는다 — 숨기면 그 주제는 어느 화면에서도 보이지 않는다. */} {(() => { const linkedIds = new Set([...links.values()].flat()); const orphans = topics.filter((topic) => topic.id && !linkedIds.has(topic.id)); if (orphans.length === 0) return null; return (

어느 프로젝트에도 걸리지 않은 주제

    {orphans.map((topic) => (
  • {topic.id ? ( {topic.name} ) : ( topic.name )}
  • ))}
); })()}
) : null} {!loading && topics && tab === "TOPIC" ? ( <>

{topics.length}개의 주제

{topics.length ? (
{topics.map((topic) => (

TOPIC

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

{topic.id ? ( {topic.name} ) : ( topic.name )}

{topic.slug}

상태
{/* `ACTIVE` 를 "사용 중" 이라 적었더니, 방금 만들어 아무도 쓰지 않는 주제까지 "사용 중" 으로 보였다. 그 상태에서 삭제가 거절되면 작성자는 둘을 같은 말로 읽는다 — 실제로는 서로 다른 이야기다. */}
{topic.status === "ARCHIVED" ? "보관" : "활성"}
{/* 편집 진입점이 제목 링크뿐이었다. 라벨이 없어 누를 수 있는지 알 수 없었고, 그 화면에 축·논지·범위가 있다는 사실도 목록에서는 드러나지 않았다 — 프로젝트 행과 같은 격으로 버튼을 둔다. */} {topic.id ? ( 편집 ) : null}
))}
) : (

아직 주제가 없습니다. 위에서 하나 만들어 주세요.

)} ) : null} {!loading && projects && tab === "PROJECT" ? ( <>

{projects.length}개의 프로젝트

{projects.length ? (
{projects.map((project) => (

PROJECT

{project.name}

{project.currentObjective ?? "목표 미지정"}

단계
{PROJECT_PHASE_LABELS[project.phase] ?? project.phase}
공개
{/* "게시됨" 이 아니라 어디까지 보이는지를 적는다 — UNLISTED 는 주소를 아는 사람만 닿고 목록에는 없다. 둘을 같은 말로 적으면 왜 목록에 안 나오는지 설명할 방법이 없다. */}
{visibilityLabel[project.targetVisibility] ?? project.targetVisibility}
{/* 편집 진입점은 이 버튼 하나다. 예전에는 「다음: 내용 편집」 이라는 dl 칸과 이 버튼이 같은 주소를 가리키며 한 행에 150px 간격으로 두 번 나왔다 — 읽는 사람은 둘이 다른 일을 한다고 읽는다. */} 내용 편집
))}
) : (

아직 프로젝트가 없습니다.

)} ) : null} setPendingDelete(null)} onConfirm={() => { if (!pendingDelete) return; if (pendingDelete.kind === "PROJECT") void removeProject(pendingDelete.project); else void removeTopic(pendingDelete.topic); }} />
); }