Asset 상세는 이름과 사실 몇 줄뿐이었다. 목록의 썸네일은 "이게 그건가"를 가리는 데 쓰고, 상세에서는 실제로 무엇이 그려져 있는지 읽어야 한다 — 바꾸거나 지우기 전에 확인하는 자리다. 큰 그림을 싣고, 쓰이는 자료라면 지우기 전에 몇 개 기록이 깨지는지를 동작 옆에 못 박는다. 주제와 프로젝트 화면은 목록 둘뿐이라 여느 CMS 의 분류 관리와 같았다. 이 제품에서 값어치 있는 것은 그 둘의 관계다. 「구조」를 먼저 두고 프로젝트 → 주제 나무를 그린다. 답하는 질문이 비어 있는 주제와, 어느 프로젝트에도 걸리지 않은 주제를 함께 드러낸다 — 걸리지 않았다는 사실 자체가 구조의 상태이므로 숨기면 그 주제는 어느 화면에서도 보이지 않는다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015c8cBFUaVr7KLVUx6ujz7D
485 lines
21 KiB
TypeScript
485 lines
21 KiB
TypeScript
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<Asset["managementStatus"], string> = {
|
||
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<readonly Asset[]>([]);
|
||
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<string | null>(null);
|
||
const [morePending, setMorePending] = useState(false);
|
||
const [selected, setSelected] = useState<AssetDetail | null>(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<HTMLButtonElement | null>(null);
|
||
const detailHeadingRef = useRef<HTMLHeadingElement | null>(null);
|
||
const pageHeadingRef = useRef<HTMLHeadingElement | null>(null);
|
||
const rowRefs = useRef(new Map<string, HTMLButtonElement>());
|
||
const openAssetId = useRef<string | null>(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 `<body>`
|
||
// 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 `<body>`. 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 (
|
||
<div className="studio-page studio-assets-page">
|
||
<header className="studio-page-heading">
|
||
<p className="studio-eyebrow">ASSET LIBRARY</p>
|
||
<h1 ref={pageHeadingRef} tabIndex={-1}>Asset</h1>
|
||
<p>
|
||
업로드한 Asset을 검색하고 사용처를 확인하며, 사용하지 않는 Asset을
|
||
정리합니다.
|
||
</p>
|
||
</header>
|
||
|
||
<section className="studio-asset-tools" aria-label="Asset 검색 도구">
|
||
<form role="search" onSubmit={submitSearch}>
|
||
<label htmlFor={searchId}>Asset 검색</label>
|
||
<div>
|
||
<input
|
||
id={searchId}
|
||
type="search"
|
||
value={searchDraft}
|
||
placeholder="Asset 키, 파일 이름"
|
||
onChange={(event) => setSearchDraft(event.target.value)}
|
||
/>
|
||
<button type="submit">검색</button>
|
||
</div>
|
||
</form>
|
||
</section>
|
||
|
||
{/*
|
||
확인 창이 열려 있는 동안에는 같은 문구를 창 안에서만 말한다. 두 벌이 화면에 남으면 읽는
|
||
사람은 무엇이 방금 일어난 일인지 고르게 된다.
|
||
*/}
|
||
<p role="status" aria-live="polite">
|
||
{confirmDelete ? "" : notice}
|
||
</p>
|
||
|
||
{listStatus === "LOADING" ? (
|
||
<p className="studio-loading" role="status">
|
||
Asset 목록을 불러오는 중입니다.
|
||
</p>
|
||
) : null}
|
||
{listStatus === "ERROR" ? (
|
||
<p className="studio-screen-error" role="alert">
|
||
Asset 목록을 불러오지 못했습니다.
|
||
</p>
|
||
) : null}
|
||
{/* The list changing is otherwise silent: a search replaces every row
|
||
and "더 보기" appends without moving anything the reader can see. */}
|
||
<p className="studio-result-count" role="status">
|
||
{listStatus === "READY" ? `${assets.length}개의 Asset` : ""}
|
||
</p>
|
||
{listStatus === "READY" && assets.length === 0 ? (
|
||
<section className="studio-empty-state">
|
||
{q ? (
|
||
<>
|
||
<h2>조건에 맞는 Asset이 없습니다</h2>
|
||
<p>검색어를 바꾸거나 비우면 전체 Asset을 다시 볼 수 있습니다.</p>
|
||
</>
|
||
) : (
|
||
<>
|
||
<h2>등록된 Asset이 없습니다</h2>
|
||
<p>Case 편집 화면에서 Asset을 업로드하면 여기에서 관리할 수 있습니다.</p>
|
||
</>
|
||
)}
|
||
</section>
|
||
) : null}
|
||
|
||
{assets.length > 0 ? (
|
||
<ul className="asset-library-list">
|
||
{assets.map((asset) => (
|
||
<li key={asset.id}>
|
||
{/*
|
||
key 만 있던 동안 이 목록은 "무엇을 고르는지" 를 말해 주지 못했다. Asset 이 스무
|
||
개면 key 스무 줄이고, 그중 어느 것이 찾던 도식인지는 눌러 봐야 알았다.
|
||
썸네일은 그 왕복을 없앤다.
|
||
|
||
주소가 없거나(업로드 처리 중) 그림이 아닌 것(첨부파일)에는 자리를 만들지 않는다 —
|
||
빈 상자가 남으면 목록이 어긋나 보인다.
|
||
*/}
|
||
{asset.publicPath && asset.mediaType.startsWith("image/") ? (
|
||
<img src={asset.publicPath} alt="" loading="lazy" />
|
||
) : (
|
||
<span className="asset-library-list__glyph" aria-hidden="true">
|
||
{asset.kind === "ATTACHMENT" ? "파일" : "—"}
|
||
</span>
|
||
)}
|
||
{/*
|
||
사람이 고르는 이름은 파일 이름이다. 목록이 `assetKey` 를 앞세우던 동안 작성자는
|
||
해시 같은 문자열 스무 줄에서 찾던 도식을 눈으로 골라야 했다 — key 는 본문이
|
||
가리키는 불변 식별자이지 사람이 기억하는 이름이 아니다. 이름을 앞에 두고 key 는
|
||
아래에 작게 남긴다.
|
||
*/}
|
||
<button
|
||
type="button"
|
||
ref={(node) => {
|
||
const rows = rowRefs.current;
|
||
if (node) rows.set(asset.id, node);
|
||
else rows.delete(asset.id);
|
||
}}
|
||
aria-current={selected?.asset.id === asset.id ? "true" : undefined}
|
||
/* 버튼의 이름은 사람이 부르는 이름까지다. 크기·형식까지 이름에 넣으면 목록을
|
||
훑을 때 버튼 하나하나가 문장이 되어 고를 수 없다. */
|
||
aria-label={asset.originalFilename || asset.assetKey}
|
||
onClick={(event) => void openDetail(asset, event.currentTarget)}
|
||
>
|
||
<strong>{asset.originalFilename || asset.assetKey}</strong>
|
||
<small>{assetFacts(asset)}</small>
|
||
<small className="asset-library-list__key">{asset.assetKey}</small>
|
||
</button>
|
||
<span>{ASSET_STATUS_LABELS[asset.managementStatus]}</span>
|
||
{/*
|
||
쓰이지 않는 자료는 지워도 되는 것이고, 쓰이는 자료는 지우면 화면이 깨진다. 그
|
||
차이가 숫자 하나로만 표시되던 동안 「사용 0건」과 「사용 3건」이 같은 회색으로
|
||
나란했다.
|
||
*/}
|
||
<span className={asset.usageCount === 0 ? "asset-usage asset-usage--none" : "asset-usage"}>
|
||
{asset.usageCount === 0 ? "쓰이지 않음" : `${asset.usageCount}곳에서 사용`}
|
||
</span>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
) : null}
|
||
|
||
{nextCursor && listStatus === "READY" ? (
|
||
<button
|
||
className="studio-secondary-button"
|
||
type="button"
|
||
disabled={morePending}
|
||
onClick={() => void loadMore()}
|
||
>
|
||
더 보기
|
||
</button>
|
||
) : null}
|
||
|
||
{selected ? (
|
||
<div
|
||
className="asset-detail"
|
||
aria-label={`${selected.asset.originalFilename || selected.asset.assetKey} 상세`}
|
||
>
|
||
<h2 ref={detailHeadingRef} tabIndex={-1}>
|
||
{selected.asset.originalFilename || selected.asset.assetKey}
|
||
</h2>
|
||
{/*
|
||
큰 그림. 목록의 썸네일은 "이게 그건가"를 가리는 데 쓰고, 여기서는 실제로 무엇이
|
||
그려져 있는지 읽어야 한다 — 바꾸거나 지우기 전에 확인하는 자리다.
|
||
*/}
|
||
{selected.asset.publicPath && selected.asset.mediaType.startsWith("image/") ? (
|
||
<img
|
||
className="asset-detail-preview"
|
||
src={selected.asset.publicPath}
|
||
alt={selected.asset.decorative ? "" : (selected.asset.altText ?? "")}
|
||
/>
|
||
) : null}
|
||
<dl className="asset-detail-facts">
|
||
<div><dt>상태</dt><dd>{ASSET_STATUS_LABELS[selected.asset.managementStatus]}</dd></div>
|
||
<div><dt>파일</dt><dd>{assetFacts(selected.asset)}</dd></div>
|
||
{/* 본문이 가리키는 불변 식별자. 사람이 기억하는 이름이 아니라 복사해 쓰는 값이다. */}
|
||
<div><dt>Key</dt><dd><code>{selected.asset.assetKey}</code></dd></div>
|
||
{selected.asset.altText ? (
|
||
<div><dt>대체 텍스트</dt><dd>{selected.asset.altText}</dd></div>
|
||
) : null}
|
||
</dl>
|
||
{/*
|
||
바꾸거나 지우기 전에 어디에 쓰이는지 전부 보여야 한다. 숫자만으로는 무엇이 깨질지
|
||
알 수 없다.
|
||
*/}
|
||
<h3 className="asset-detail-usage-title">쓰이는 곳</h3>
|
||
{selected.usages.length > 0 ? (
|
||
<ul>
|
||
{selected.usages.map((usage) => (
|
||
<li key={usage.documentId}>
|
||
{/*
|
||
평범한 링크다. 이 화면은 Studio 컨텍스트를 받지 않고 게이트웨이 하나만 받아
|
||
혼자 설 수 있게 되어 있고, 여기서 떠날 때 지킬 편집 상태도 없다.
|
||
*/}
|
||
<a href={`/studio/documents/${usage.documentId}/edit`}>
|
||
{usage.title || "제목 없는 작업본"}
|
||
</a>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
) : (
|
||
<p>아직 어느 기록도 이 자료를 쓰지 않습니다.</p>
|
||
)}
|
||
{/*
|
||
쓰이는 자료를 지우면 그 기록들의 그림 자리가 통째로 빈다. 지우기 전에 무엇이 깨질지
|
||
수가 아니라 이름으로 보여야 한다 — 위의 「쓰이는 곳」이 그 목록이고, 여기서는 그
|
||
사실을 동작 옆에 한 번 더 못 박는다.
|
||
*/}
|
||
{selected.usages.length > 0 ? (
|
||
<p className="asset-detail-warning" role="status">
|
||
{`${selected.usages.length}개 기록이 이 자료를 쓰고 있습니다. 지우면 그 자리가 빕니다.`}
|
||
</p>
|
||
) : null}
|
||
<div className="asset-detail-actions">
|
||
{/*
|
||
삭제는 되돌릴 수 없다. 보관은 목록에서 내리는 것뿐이라 묻지 않는다 — 둘을 같은
|
||
무게로 다루면 확인 창이 곧 습관이 되어 진짜 삭제도 그냥 지나간다.
|
||
*/}
|
||
{canHardDelete(selected) ? (
|
||
<button type="button" disabled={pending} onClick={() => setConfirmDelete(true)}>
|
||
삭제
|
||
</button>
|
||
) : (
|
||
<button type="button" disabled={pending} onClick={() => void archive(selected)}>
|
||
보관
|
||
</button>
|
||
)}
|
||
<button type="button" onClick={closeDetail}>
|
||
닫기
|
||
</button>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
<DestructiveConfirmDialog
|
||
open={confirmDelete && selected !== null}
|
||
pending={pending}
|
||
title="Asset을 삭제합니다"
|
||
targetName={selected?.asset.assetKey ?? ""}
|
||
description="본문이 이 key로 가리키던 그림 자리는 빈 채로 남습니다."
|
||
// 닫혀 있을 때도 children 은 DOM 에 남는다. 화면의 알림과 같은 문구가 두 벌 생기지
|
||
// 않도록 열려 있을 때만 넘긴다.
|
||
error={confirmDelete ? notice : ""}
|
||
onCancel={() => setConfirmDelete(false)}
|
||
onConfirm={() => {
|
||
if (selected) void remove(selected);
|
||
}}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|