import { useEffect, useId, useRef, useState, type FormEvent } from "react"; import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx"; import type { Asset, AssetDetail } from "../../../contracts/studio/contract.ts"; import type { StudioAssetGateway } from "../../../application/ports/studio-asset-gateway.ts"; import { isStudioGatewayError } from "../../../application/ports/studio-gateway-error.ts"; import { createLocalId } from "../../../domain/studio/local-id.ts"; /** 관리 상태. 화면에 영문 상수가 그대로 나오던 자리다. */ const ASSET_STATUS_LABELS: Record = { READY: "사용 가능", ARCHIVED: "보관됨", REJECTED: "거부됨", QUARANTINED: "검사 보류", }; /** 사람이 고를 때 실제로 보는 사실들 — 무엇이고, 얼마나 크고, 몇 바이트인가. */ function assetFacts(asset: Asset): string { const parts = [asset.mediaType.replace(/^image\//u, "").toUpperCase()]; // 치수를 모르는 자료가 있다(첨부파일, 처리 중). 모르면 적지 않는다 — 0×0 은 거짓이다. if (asset.width && asset.height) parts.push(`${asset.width}×${asset.height}`); parts.push(byteLabel(asset.byteSize)); return parts.join(" · "); } function byteLabel(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } /** `document-list.tsx`'s page size for the same screen shape. */ const PAGE_SIZE = 20; /** * 공개 이력이 있거나 사용 중인 Asset은 hard delete하지 않는다. 서버도 같은 * 규칙으로 `ASSET_IN_USE`를 던지므로 화면은 시도 자체를 막아 왕복을 줄인다. */ export function canHardDelete(detail: AssetDetail): boolean { return ( !detail.hasPublicationHistory && detail.usages.length === 0 && detail.asset.usageCount === 0 ); } function isAbortError(error: unknown): boolean { return error instanceof DOMException && error.name === "AbortError"; } export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) { const [assets, setAssets] = useState([]); const [listStatus, setListStatus] = useState<"LOADING" | "ERROR" | "READY">( "LOADING", ); // Alignment follow-up, item 1. `q` is the *submitted* query, `searchDraft` // what the user is currently typing. Only `q` is an effect dependency, so // typing costs nothing -- `document-list.tsx` splits the same pair for the // same reason, and it is a stronger guarantee than a debounce: exactly one // request per deliberate search, never a trailing one after the user stops. const [searchDraft, setSearchDraft] = useState(""); const [q, setQ] = useState(""); const [nextCursor, setNextCursor] = useState(null); const [morePending, setMorePending] = useState(false); const [selected, setSelected] = useState(null); const [pending, setPending] = useState(false); const [notice, setNotice] = useState(""); const [confirmDelete, setConfirmDelete] = useState(false); // Wrapped in an object, not a bare `string | null`: the "no appended row to // land on" case still needs a focus move (to the page heading), and a bare // null cannot express "a move is pending, target unknown". const [moreFocus, setMoreFocus] = useState<{ id: string | null } | null>(null); const triggerRef = useRef(null); const detailHeadingRef = useRef(null); const pageHeadingRef = useRef(null); const rowRefs = useRef(new Map()); const openAssetId = useRef(null); const searchId = useId(); useEffect(() => { const controller = new AbortController(); // `active` rather than the abort signal alone: `RequestOptions.signal` is // advisory -- an adapter that ignores it still resolves, and a search the // user has already replaced would then paint stale rows over the newer // ones. This flag flips synchronously the moment `q` changes, so an // abandoned response can never reach `setAssets`. let active = true; setListStatus("LOADING"); props.gateway .listAssets( { ...(q ? { q } : {}), limit: PAGE_SIZE }, { signal: controller.signal }, ) .then((page) => { if (!active) return; setAssets(page.items); setNextCursor(page.nextCursor); setListStatus("READY"); }) .catch((error: unknown) => { if (!active || isAbortError(error)) return; // The `role="alert"` paragraph below is the sole announcement for a // load failure -- also routing it through `notice`'s `role="status"` // paragraph would announce the same sentence twice. setListStatus("ERROR"); }); return () => { active = false; controller.abort(); }; }, [props.gateway, q]); // A freshly opened detail panel should take focus so keyboard and screen // reader users land on it without hunting; re-rendering the same asset // (e.g. after archiving it) must not steal focus back from whatever the // user is doing next. useEffect(() => { if (selected && openAssetId.current !== selected.asset.id) { detailHeadingRef.current?.focus(); } openAssetId.current = selected?.asset.id ?? null; }, [selected]); // Alignment follow-up, item 1. "더 보기" disappears once the server reports // no further cursor, so keeping focus on it would strand focus on `` // exactly when the last page arrives. Moving to the first appended row is // unconditional -- it cannot depend on whether the control survived -- and // it puts the user at the content they asked for. Run as an effect (not // inline after `await`) so the row is committed and its ref attached. useEffect(() => { if (!moreFocus) return; const row = moreFocus.id ? rowRefs.current.get(moreFocus.id) : undefined; // The page heading is the fallback the delete path already relies on: the // one node in this screen that survives every list change. (row ?? pageHeadingRef.current)?.focus(); setMoreFocus(null); }, [moreFocus]); async function openDetail(asset: Asset, trigger: HTMLButtonElement) { triggerRef.current = trigger; try { const detail = await props.gateway.getAsset(asset.id); setSelected(detail); } catch { setNotice("Asset 상세를 불러오지 못했습니다."); } } function submitSearch(event: FormEvent) { event.preventDefault(); // A new query restarts paging: `nextCursor` was issued against the old // query's ordering and means nothing under the new one. setSelected(null); setNextCursor(null); setQ(searchDraft.trim()); } async function loadMore() { if (!nextCursor || morePending) return; const cursor = nextCursor; setMorePending(true); try { const page = await props.gateway.listAssets({ ...(q ? { q } : {}), cursor, limit: PAGE_SIZE, }); // Append, never replace -- and drop anything already on screen so a // server that re-sends a boundary row cannot produce a duplicate React // key (or a duplicate row for the reader). The dedupe lives inside the // updater so it reads the committed list; the focus target is derived // separately from the rendered `assets`, because a state updater is not // invoked synchronously and must stay free of side effects. const known = new Set(assets.map((item) => item.id)); const appended = page.items.filter((item) => !known.has(item.id)); setAssets((current) => { const seen = new Set(current.map((item) => item.id)); return [...current, ...page.items.filter((item) => !seen.has(item.id))]; }); setNextCursor(page.nextCursor); setMoreFocus({ id: appended[0]?.id ?? page.items[0]?.id ?? null }); } catch (error) { setNotice( isStudioGatewayError(error) ? error.problem.detail : "다음 Asset을 불러오지 못했습니다.", ); } finally { setMorePending(false); } } // Dismissing the panel without changing the list (cancel/close): the row // that opened it is still on screen, so restore focus there. function closeDetail() { setSelected(null); queueMicrotask(() => triggerRef.current?.focus()); } // Fix round 1 (I1). A successful delete removes the row from `assets`, so // by the time this runs `triggerRef.current` -- still set, since React // never nulls a plain ref -- points at a button that is no longer attached // to the document. `.focus()` on a detached element is a silent no-op, so // reusing `closeDetail` here left focus stranded on ``. The page // heading is the one thing in this screen guaranteed to survive any list // change (the list itself can disappear into the empty state), so a // deletion moves focus there instead of trying to reuse a node it just // destroyed. function closeDetailAfterRemoval() { setSelected(null); queueMicrotask(() => pageHeadingRef.current?.focus()); } async function archive(detail: AssetDetail) { setPending(true); try { const updated = await props.gateway.updateAssetMetadata( detail.asset.id, { expectedVersion: detail.asset.version, managementStatus: "ARCHIVED" }, { idempotencyKey: createLocalId("studio-asset-archive") }, ); setAssets((current) => current.map((item) => (item.id === updated.id ? updated : item)), ); setSelected({ ...detail, asset: updated }); setNotice("보관했습니다."); } catch (error) { setNotice( isStudioGatewayError(error) ? error.problem.detail : "보관하지 못했습니다.", ); } finally { setPending(false); } } async function remove(detail: AssetDetail) { setPending(true); try { await props.gateway.deleteAsset(detail.asset.id, { idempotencyKey: createLocalId("studio-asset-delete"), }); setAssets((current) => current.filter((item) => item.id !== detail.asset.id)); setNotice("삭제했습니다."); setConfirmDelete(false); closeDetailAfterRemoval(); } catch (error) { setNotice( isStudioGatewayError(error) ? error.problem.detail : "삭제하지 못했습니다.", ); } finally { setPending(false); } } return (

ASSET LIBRARY

Asset

업로드한 Asset을 검색하고 사용처를 확인하며, 사용하지 않는 Asset을 정리합니다.

setSearchDraft(event.target.value)} />
{/* 확인 창이 열려 있는 동안에는 같은 문구를 창 안에서만 말한다. 두 벌이 화면에 남으면 읽는 사람은 무엇이 방금 일어난 일인지 고르게 된다. */}

{confirmDelete ? "" : notice}

{listStatus === "LOADING" ? (

Asset 목록을 불러오는 중입니다.

) : null} {listStatus === "ERROR" ? (

Asset 목록을 불러오지 못했습니다.

) : null} {/* The list changing is otherwise silent: a search replaces every row and "더 보기" appends without moving anything the reader can see. */}

{listStatus === "READY" ? `${assets.length}개의 Asset` : ""}

{listStatus === "READY" && assets.length === 0 ? (
{q ? ( <>

조건에 맞는 Asset이 없습니다

검색어를 바꾸거나 비우면 전체 Asset을 다시 볼 수 있습니다.

) : ( <>

등록된 Asset이 없습니다

Case 편집 화면에서 Asset을 업로드하면 여기에서 관리할 수 있습니다.

)}
) : null} {assets.length > 0 ? (
    {assets.map((asset) => (
  • {/* key 만 있던 동안 이 목록은 "무엇을 고르는지" 를 말해 주지 못했다. Asset 이 스무 개면 key 스무 줄이고, 그중 어느 것이 찾던 도식인지는 눌러 봐야 알았다. 썸네일은 그 왕복을 없앤다. 주소가 없거나(업로드 처리 중) 그림이 아닌 것(첨부파일)에는 자리를 만들지 않는다 — 빈 상자가 남으면 목록이 어긋나 보인다. */} {asset.publicPath && asset.mediaType.startsWith("image/") ? ( ) : ( )} {/* 사람이 고르는 이름은 파일 이름이다. 목록이 `assetKey` 를 앞세우던 동안 작성자는 해시 같은 문자열 스무 줄에서 찾던 도식을 눈으로 골라야 했다 — key 는 본문이 가리키는 불변 식별자이지 사람이 기억하는 이름이 아니다. 이름을 앞에 두고 key 는 아래에 작게 남긴다. */} {ASSET_STATUS_LABELS[asset.managementStatus]} {/* 쓰이지 않는 자료는 지워도 되는 것이고, 쓰이는 자료는 지우면 화면이 깨진다. 그 차이가 숫자 하나로만 표시되던 동안 「사용 0건」과 「사용 3건」이 같은 회색으로 나란했다. */} {asset.usageCount === 0 ? "쓰이지 않음" : `${asset.usageCount}곳에서 사용`}
  • ))}
) : null} {nextCursor && listStatus === "READY" ? ( ) : null} {selected ? (

{selected.asset.originalFilename || selected.asset.assetKey}

{/* 큰 그림. 목록의 썸네일은 "이게 그건가"를 가리는 데 쓰고, 여기서는 실제로 무엇이 그려져 있는지 읽어야 한다 — 바꾸거나 지우기 전에 확인하는 자리다. */} {selected.asset.publicPath && selected.asset.mediaType.startsWith("image/") ? ( {selected.asset.decorative ) : null}
상태
{ASSET_STATUS_LABELS[selected.asset.managementStatus]}
파일
{assetFacts(selected.asset)}
{/* 본문이 가리키는 불변 식별자. 사람이 기억하는 이름이 아니라 복사해 쓰는 값이다. */}
Key
{selected.asset.assetKey}
{selected.asset.altText ? (
대체 텍스트
{selected.asset.altText}
) : null}
{/* 바꾸거나 지우기 전에 어디에 쓰이는지 전부 보여야 한다. 숫자만으로는 무엇이 깨질지 알 수 없다. */}

쓰이는 곳

{selected.usages.length > 0 ? (
    {selected.usages.map((usage) => (
  • {/* 평범한 링크다. 이 화면은 Studio 컨텍스트를 받지 않고 게이트웨이 하나만 받아 혼자 설 수 있게 되어 있고, 여기서 떠날 때 지킬 편집 상태도 없다. */} {usage.title || "제목 없는 작업본"}
  • ))}
) : (

아직 어느 기록도 이 자료를 쓰지 않습니다.

)} {/* 쓰이는 자료를 지우면 그 기록들의 그림 자리가 통째로 빈다. 지우기 전에 무엇이 깨질지 수가 아니라 이름으로 보여야 한다 — 위의 「쓰이는 곳」이 그 목록이고, 여기서는 그 사실을 동작 옆에 한 번 더 못 박는다. */} {selected.usages.length > 0 ? (

{`${selected.usages.length}개 기록이 이 자료를 쓰고 있습니다. 지우면 그 자리가 빕니다.`}

) : null}
{/* 삭제는 되돌릴 수 없다. 보관은 목록에서 내리는 것뿐이라 묻지 않는다 — 둘을 같은 무게로 다루면 확인 창이 곧 습관이 되어 진짜 삭제도 그냥 지나간다. */} {canHardDelete(selected) ? ( ) : ( )}
) : null} setConfirmDelete(false)} onConfirm={() => { if (selected) void remove(selected); }} />
); }