feat: 작업본·게시 기록 목록을 번호로 오간다

「다음」 버튼 하나뿐이라 뒤로 넘어가면 앞쪽으로 돌아올 수 없었다. 커서
페이지네이션이라 앞으로만 갈 수 있었기 때문이다.

서버가 총 쪽수를 주고(StudioPageMetadata) 목록은 `‹ 1 2 3 ›` 을 그린다.
쪽이 많으면 현재 쪽 좌우 2개씩만 그리고 첫·끝은 늘 남긴다 — 어디에
있든 처음과 끝으로 한 번에 갈 수 있다.

게시 기록은 페이지 이동이 아예 없었다(limit 100 으로 한 번에 다 가져왔다).
작업본과 같은 20개 단위로 맞춘다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nAjrqNHGPNngN4aUbcyvJ
This commit is contained in:
DongHyeonka
2026-08-29 22:07:54 +09:00
co-authored by Claude Opus 5
parent 77125d1c7c
commit df371d38bd
14 changed files with 285 additions and 42 deletions
+5 -5
View File
@@ -38,28 +38,28 @@
},
"contractSet": {
"setAlgorithm": "CA_CONTRACT_SET_V1",
"setDigest": "sha256:d087b99f1eed932908890f11636fb2fc2befe34747acf846603ce7ad240d0dbe",
"setDigest": "sha256:e1b17dd429c6eae9c735cfae0383827b57cc557f5300ece8e691c9178d0e4ba1",
"packages": [
{
"packageId": "@tech-log/management-contract",
"version": "1.0.0",
"digest": "sha256:762aa81e6906469939fddd833c204ed3ca53f0fa96371f18a5ea1edaf76a64e8",
"runtimeProtocolVersion": 1,
"sourceRevision": "76a7ccb"
"sourceRevision": "d445555"
},
{
"packageId": "@tech-log/public-contract",
"version": "2.1.0",
"digest": "sha256:afe415880eb5d6289ae10abf493333c97270c323c16a7245a466d4db4466e630",
"runtimeProtocolVersion": 1,
"sourceRevision": "76a7ccb"
"sourceRevision": "d445555"
},
{
"packageId": "@tech-log/studio-contract",
"version": "3.1.0",
"digest": "sha256:96f655d75fc19c535eb87e24f5320fdc382d6d982aaa75b67fe6acbde1ee8ff2",
"digest": "sha256:1732dd7749aea49a41d2ef17dfe9896a73e10b1b97d7d0223b3ac530500816f3",
"runtimeProtocolVersion": 1,
"sourceRevision": "76a7ccb"
"sourceRevision": "d445555"
}
]
}
@@ -115,6 +115,19 @@ function exactSet(left: string[], right: string[]) {
return new Set(left).size === left.length && new Set(right).size === right.length && [...left].sort().join("\0") === [...right].sort().join("\0");
}
/** 모의 게이트웨이의 페이지 메타. 화면 테스트도 번호 페이지네이션을 그대로 지나가야 한다. */
function pageMetadata(number: number, size: number, totalElements: number) {
const totalPages = size <= 0 ? 0 : Math.ceil(totalElements / size);
return {
number,
size,
totalElements,
totalPages,
hasPrevious: number > 1,
hasNext: number < totalPages,
};
}
export function createMockStudioGateway(supplied: Partial<MockStudioDependencies> = {}): StudioGateway {
// The fallback revision has to read whichever map this gateway ends up
// with, so the assets are resolved before the defaults are built -- a
@@ -195,7 +208,10 @@ export function createMockStudioGateway(supplied: Partial<MockStudioDependencies
const items = [...state.documents.values()].map(summary).filter((item) => { const source = state.documents.get(item.id)!; return (!normalized.q || `${item.title} ${source.summary} ${source.slug}`.toLocaleLowerCase("ko-KR").includes(normalized.q)) && (!normalized.kind || item.kind === normalized.kind) && (!normalized.publicationStatus || item.publicationStatus === normalized.publicationStatus) && (!normalized.nextAction || item.nextAction === normalized.nextAction) && (!normalized.projectId || source.projectId === normalized.projectId); });
items.sort((a, b) => { const primary = normalized.sort === "TITLE_ASC" ? a.title.localeCompare(b.title, "ko") : normalized.sort === "UPDATED_ASC" ? a.updatedAt.localeCompare(b.updatedAt) : b.updatedAt.localeCompare(a.updatedAt); return primary || a.id.localeCompare(b.id); });
const page = cursor ? items.filter((item) => { const value = normalized.sort === "TITLE_ASC" ? item.title : item.updatedAt; const order = value.localeCompare(cursor.lastValue, normalized.sort === "TITLE_ASC" ? "ko" : undefined); return normalized.sort === "UPDATED_DESC" ? order < 0 || (order === 0 && item.id > cursor.lastId) : order > 0 || (order === 0 && item.id > cursor.lastId); }) : items; const selected = page.slice(0, limit); const last = selected.at(-1); const lastValue = last ? normalized.sort === "TITLE_ASC" ? last.title : last.updatedAt : "";
return { items: selected, nextCursor: selected.length < page.length && last ? encodeCursor({ binding, lastValue, lastId: last.id }) : null } satisfies DocumentPage;
const pageNumber = Math.max(query.page ?? 1, 1);
const offset = (pageNumber - 1) * limit;
const numbered = pageNumber > 1 ? items.slice(offset, offset + limit) : selected;
return { items: numbered, nextCursor: selected.length < page.length && last ? encodeCursor({ binding, lastValue, lastId: last.id }) : null, page: pageMetadata(pageNumber, limit, items.length) } satisfies DocumentPage;
}); },
createDocument(input, options) { return idempotent("create", "documents", () => input, options, () => { structure(input); const value = materialize(dependencies.idGenerator.next(), 1, input); state.documents.set(value.id, value); return value; }); },
getDocument(documentId, options) { return read(options, () => { uuid(documentId, "/documentId"); return detail(documentId); }); },
@@ -220,7 +236,7 @@ export function createMockStudioGateway(supplied: Partial<MockStudioDependencies
const eventId = dependencies.idGenerator.next(); const publicationId = existing?.publicationId ?? dependencies.idGenerator.next(); const event: PublicationEvent = { publicationEventId: eventId, publicationId, documentId, type: existing ? "REPUBLISHED" : "PUBLISHED", occurredAt: now.toISOString(), publishedVersion: value.version, sourcePublishedEventId: null, snapshotAvailable: true }; const publication: PublicationAggregate = { publicationId, documentId, status: "PUBLISHED", publishedVersion: value.version, publicationRevision: (existing?.publicationRevision ?? 0) + 1, latestEventId: eventId, publicPath: preview.renderModel.publicPath, updatedAt: now.toISOString() }; state.events.set(eventId, event); state.publications.set(documentId, publication); state.snapshots.set(eventId, { event: clone(event), renderModel: clone(preview.renderModel), contentFormatVersion: CONTENT_FORMAT_VERSION, rendererContractVersion: RENDERER_CONTRACT_VERSION }); return { publication, event } satisfies PublishResult;
}); },
unpublishPublication(publicationId, command, options) { return idempotent("unpublish", publicationId, () => command, options, () => { uuid(publicationId, "/publicationId"); const current = [...state.publications.values()].find((item) => item.publicationId === publicationId); if (!current) throw gatewayProblem(404, "PUBLICATION_NOT_FOUND", "Publication not found."); if (current.publicationRevision !== command.expectedPublicationRevision) throw gatewayProblem(409, "PUBLICATION_CONFLICT", "Publication revision changed.", { details: { latestPublication: clone(current) } }); if (current.status === "UNPUBLISHED") return { publication: current, event: state.events.get(current.latestEventId)! }; const event: PublicationEvent = { publicationEventId: dependencies.idGenerator.next(), publicationId, documentId: current.documentId, type: "UNPUBLISHED", occurredAt: dependencies.clock.now().toISOString(), publishedVersion: current.publishedVersion, sourcePublishedEventId: current.latestEventId, snapshotAvailable: false }; const publication: PublicationAggregate = { ...current, status: "UNPUBLISHED", publicationRevision: current.publicationRevision + 1, latestEventId: event.publicationEventId, updatedAt: event.occurredAt }; state.events.set(event.publicationEventId, event); state.publications.set(current.documentId, publication); return { publication, event }; }); },
listPublications(query, options) { return read(options, () => { queryText(query.q); const limit = limitOf(query.limit); const normalized = { q: normalizeQ(query.q), type: query.type ?? null, sort: "OCCURRED_DESC" }; const binding = cursorBinding(normalized); const cursor = query.cursor ? decodeCursor(query.cursor, binding) : null; const all = [...state.events.values()].filter((event) => (!normalized.type || event.type === normalized.type) && (!normalized.q || `${document(event.documentId).title} ${document(event.documentId).summary}`.toLocaleLowerCase("ko-KR").includes(normalized.q))).sort((a, b) => b.occurredAt.localeCompare(a.occurredAt) || a.publicationEventId.localeCompare(b.publicationEventId)); const source = cursor ? all.filter((event) => event.occurredAt < cursor.lastValue || (event.occurredAt === cursor.lastValue && event.publicationEventId > cursor.lastId)) : all; const selected = source.slice(0, limit); const last = selected.at(-1); return { items: selected.map(publicationRow), nextCursor: selected.length < source.length && last ? encodeCursor({ binding, lastValue: last.occurredAt, lastId: last.publicationEventId }) : null } satisfies PublicationPage; }); },
listPublications(query, options) { return read(options, () => { queryText(query.q); const limit = limitOf(query.limit); const normalized = { q: normalizeQ(query.q), type: query.type ?? null, sort: "OCCURRED_DESC" }; const binding = cursorBinding(normalized); const cursor = query.cursor ? decodeCursor(query.cursor, binding) : null; const all = [...state.events.values()].filter((event) => (!normalized.type || event.type === normalized.type) && (!normalized.q || `${document(event.documentId).title} ${document(event.documentId).summary}`.toLocaleLowerCase("ko-KR").includes(normalized.q))).sort((a, b) => b.occurredAt.localeCompare(a.occurredAt) || a.publicationEventId.localeCompare(b.publicationEventId)); const source = cursor ? all.filter((event) => event.occurredAt < cursor.lastValue || (event.occurredAt === cursor.lastValue && event.publicationEventId > cursor.lastId)) : all; const selected = source.slice(0, limit); const last = selected.at(-1); const pageNumber = Math.max(query.page ?? 1, 1); const numbered = pageNumber > 1 ? all.slice((pageNumber - 1) * limit, (pageNumber - 1) * limit + limit) : selected; return { items: numbered.map(publicationRow), nextCursor: selected.length < source.length && last ? encodeCursor({ binding, lastValue: last.occurredAt, lastId: last.publicationEventId }) : null, page: pageMetadata(pageNumber, limit, all.length) } satisfies PublicationPage; }); },
getPublicationSnapshot(publicationEventId, options) { return read(options, () => { uuid(publicationEventId, "/publicationEventId"); if (!state.events.has(publicationEventId)) throw gatewayProblem(404, "PUBLICATION_EVENT_NOT_FOUND", "Publication event not found."); const snapshot = state.snapshots.get(publicationEventId); if (!snapshot) throw gatewayProblem(404, "PUBLICATION_SNAPSHOT_NOT_FOUND", "Publication snapshot not found."); return snapshot; }); },
getCatalog(query, options) { return read(options, () => { if (!query.type) throw requestError([{ path: "/type", message: "type is required." }]); queryText(query.q); const limit = limitOf(query.limit); const normalized = { type: query.type, q: normalizeQ(query.q), sort: "LABEL_ASC" }; const binding = cursorBinding(normalized); const cursor = query.cursor ? decodeCursor(query.cursor, binding) : null; const all = state.catalog.filter((item) => item.type === query.type && (!normalized.q || item.label.toLocaleLowerCase("ko-KR").includes(normalized.q))).sort((a, b) => a.label.localeCompare(b.label, "ko") || a.id.localeCompare(b.id)); const source = cursor ? all.filter((item) => item.label.localeCompare(cursor.lastValue, "ko") > 0 || (item.label === cursor.lastValue && item.id > cursor.lastId)) : all; const selected = source.slice(0, limit); const last = selected.at(-1); return { items: selected, nextCursor: selected.length < source.length && last ? encodeCursor({ binding, lastValue: last.label, lastId: last.id }) : null } satisfies CatalogPage; }); },
};
@@ -12,9 +12,12 @@ export type ListDocumentsQuery = {
publicationStatus?: "NEVER_PUBLISHED" | "PUBLISHED" | "UNPUBLISHED";
nextAction?: "CONTINUE_EDITING" | "VALIDATE" | "FIX_VALIDATION" | "CREATE_PREVIEW" | "PUBLISH" | "NONE";
projectId?: string; sort?: "UPDATED_DESC" | "UPDATED_ASC" | "TITLE_ASC";
cursor?: string; limit?: number;
cursor?: string;
/** 1부터 세는 페이지 번호. 목록 화면이 번호를 그리려면 앞뒤로 오갈 수 있어야 한다. */
page?: number;
limit?: number;
};
export type ListPublicationsQuery = { q?: string; type?: "PUBLISHED" | "REPUBLISHED" | "UNPUBLISHED"; cursor?: string; limit?: number };
export type ListPublicationsQuery = { q?: string; type?: "PUBLISHED" | "REPUBLISHED" | "UNPUBLISHED"; cursor?: string; page?: number; limit?: number };
export type CatalogQuery = { type: "TOPIC" | "PROJECT" | "RELATION" | "EVIDENCE"; q?: string; cursor?: string; limit?: number };
export interface StudioGateway {
@@ -2,7 +2,7 @@
"packageId": "@tech-log/management-contract",
"version": "1.0.0",
"digest": "sha256:762aa81e6906469939fddd833c204ed3ca53f0fa96371f18a5ea1edaf76a64e8",
"sourceRevision": "76a7ccb",
"sourceRevision": "d445555",
"operationIds": [
"createCaseDraft",
"getCaseForEdit",
@@ -2,7 +2,7 @@
"packageId": "@tech-log/public-contract",
"version": "2.1.0",
"digest": "sha256:afe415880eb5d6289ae10abf493333c97270c323c16a7245a466d4db4466e630",
"sourceRevision": "76a7ccb",
"sourceRevision": "d445555",
"operationIds": [
"getPublicSite",
"getPublicHome",
@@ -1,8 +1,8 @@
{
"packageId": "@tech-log/studio-contract",
"version": "3.1.0",
"digest": "sha256:96f655d75fc19c535eb87e24f5320fdc382d6d982aaa75b67fe6acbde1ee8ff2",
"sourceRevision": "76a7ccb",
"digest": "sha256:1732dd7749aea49a41d2ef17dfe9896a73e10b1b97d7d0223b3ac530500816f3",
"sourceRevision": "d445555",
"operationIds": [
"getStudioSession",
"getStudioDashboard",
@@ -1343,13 +1343,26 @@ export interface components {
readyToPublish: number;
publications: number;
};
/** @description 목록 화면이 `‹ 1 2 3 ›` 을 그리려면 총 몇 쪽인지 알아야 한다. 커서만으로는 앞으로만 갈 수
* 있어서 뒤로 넘어간 뒤 돌아올 방법이 없었다. 공개 API 의 `PageMetadata` 와 같은 모양이다.
* */
StudioPageMetadata: {
number: number;
size: number;
totalElements: number;
totalPages: number;
hasPrevious: boolean;
hasNext: boolean;
};
DocumentPage: {
items: components["schemas"]["DocumentSummary"][];
nextCursor: string | null;
page: components["schemas"]["StudioPageMetadata"];
};
PublicationPage: {
items: components["schemas"]["PublicationListItem"][];
nextCursor: string | null;
page: components["schemas"]["StudioPageMetadata"];
};
/** @enum {string} */
CatalogEntryType: "TOPIC" | "PROJECT" | "RELATION" | "EVIDENCE";
@@ -1609,6 +1622,8 @@ export interface components {
/** @description Opaque cursor bound to normalized filters and sort */
Cursor: string;
Limit: number;
/** @description 1부터 세는 페이지 번호. 목록 화면이 번호를 그리려면 앞뒤로 오갈 수 있어야 한다. */
Page: number;
DocumentKind: components["schemas"]["RecordKind"];
PublicationStatus: components["schemas"]["PublicationStatus"];
NextAction: components["schemas"]["NextAction"];
@@ -1686,6 +1701,8 @@ export interface operations {
sort?: components["parameters"]["DocumentSort"];
/** @description Opaque cursor bound to normalized filters and sort */
cursor?: components["parameters"]["Cursor"];
/** @description 1부터 세는 페이지 번호. 목록 화면이 번호를 그리려면 앞뒤로 오갈 수 있어야 한다. */
page?: components["parameters"]["Page"];
limit?: components["parameters"]["Limit"];
};
header?: never;
@@ -1977,6 +1994,8 @@ export interface operations {
type?: components["parameters"]["PublicationEventType"];
/** @description Opaque cursor bound to normalized filters and sort */
cursor?: components["parameters"]["Cursor"];
/** @description 1부터 세는 페이지 번호. 목록 화면이 번호를 그리려면 앞뒤로 오갈 수 있어야 한다. */
page?: components["parameters"]["Page"];
limit?: components["parameters"]["Limit"];
};
header?: never;
@@ -148,6 +148,7 @@ paths:
- { $ref: "#/components/parameters/ProjectId" }
- { $ref: "#/components/parameters/DocumentSort" }
- { $ref: "#/components/parameters/Cursor" }
- { $ref: "#/components/parameters/Page" }
- { $ref: "#/components/parameters/Limit" }
responses:
"200": { description: Working-copy cursor page, content: { application/json: { schema: { $ref: "#/components/schemas/DocumentPageEnvelope" } } } }
@@ -348,6 +349,7 @@ paths:
- { $ref: "#/components/parameters/Query" }
- { $ref: "#/components/parameters/PublicationEventType" }
- { $ref: "#/components/parameters/Cursor" }
- { $ref: "#/components/parameters/Page" }
- { $ref: "#/components/parameters/Limit" }
responses:
"200": { description: Publication cursor page, content: { application/json: { schema: { $ref: "#/components/schemas/PublicationPageEnvelope" } } } }
@@ -579,6 +581,7 @@ components:
Query: { name: q, in: query, description: Free-text query normalized as part of the opaque cursor, schema: { type: string, maxLength: 100 } }
Cursor: { name: cursor, in: query, description: Opaque cursor bound to normalized filters and sort, schema: { type: string, minLength: 1, maxLength: 2000 } }
Limit: { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
Page: { name: page, in: query, description: 1부터 세는 페이지 번호. 목록 화면이 번호를 그리려면 앞뒤로 오갈 수 있어야 한다., schema: { type: integer, minimum: 1, default: 1 } }
DocumentKind: { name: kind, in: query, schema: { $ref: "#/components/schemas/RecordKind" } }
PublicationStatus: { name: publicationStatus, in: query, schema: { $ref: "#/components/schemas/PublicationStatus" } }
NextAction: { name: nextAction, in: query, schema: { $ref: "#/components/schemas/NextAction" } }
@@ -1791,20 +1794,36 @@ components:
needsValidation: { type: integer, minimum: 0 }
readyToPublish: { type: integer, minimum: 0 }
publications: { type: integer, minimum: 0 }
StudioPageMetadata:
description: |
목록 화면이 `‹ 1 2 3 ›` 을 그리려면 총 몇 쪽인지 알아야 한다. 커서만으로는 앞으로만 갈 수
있어서 뒤로 넘어간 뒤 돌아올 방법이 없었다. 공개 API 의 `PageMetadata` 와 같은 모양이다.
type: object
additionalProperties: false
required: [number, size, totalElements, totalPages, hasPrevious, hasNext]
properties:
number: { type: integer, minimum: 1 }
size: { type: integer, minimum: 1, maximum: 100 }
totalElements: { type: integer, minimum: 0 }
totalPages: { type: integer, minimum: 0 }
hasPrevious: { type: boolean }
hasNext: { type: boolean }
DocumentPage:
type: object
additionalProperties: false
required: [items, nextCursor]
required: [items, nextCursor, page]
properties:
items: { type: array, maxItems: 100, items: { $ref: "#/components/schemas/DocumentSummary" } }
nextCursor: { type: [string, "null"], maxLength: 2000 }
page: { $ref: "#/components/schemas/StudioPageMetadata" }
PublicationPage:
type: object
additionalProperties: false
required: [items, nextCursor]
required: [items, nextCursor, page]
properties:
items: { type: array, maxItems: 100, items: { $ref: "#/components/schemas/PublicationListItem" } }
nextCursor: { type: [string, "null"], maxLength: 2000 }
page: { $ref: "#/components/schemas/StudioPageMetadata" }
# ---------------------------------------------------------------- catalog
CatalogEntryType: { type: string, enum: [TOPIC, PROJECT, RELATION, EVIDENCE] }
@@ -5,6 +5,7 @@ import type { DocumentPage } from "../../../contracts/studio/contract.ts";
import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts";
import { useStudio } from "../use-studio.ts";
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
import { StudioPagination } from "./studio-pagination.tsx";
const kindLabel = {
CASE: "Case",
@@ -55,7 +56,7 @@ export function DocumentList() {
const [kind, setKind] = useState<ListDocumentsQuery["kind"]>();
const [status, setStatus] =
useState<ListDocumentsQuery["publicationStatus"]>();
const [cursor, setCursor] = useState<string>();
const [pageNumber, setPageNumber] = useState(1);
const [page, setPage] = useState<DocumentPage | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
@@ -119,7 +120,7 @@ export function DocumentList() {
...(q ? { q } : {}),
...(kind ? { kind } : {}),
...(status ? { publicationStatus: status } : {}),
...(cursor ? { cursor } : {}),
page: pageNumber,
limit: 20,
},
{ signal: controller.signal },
@@ -136,7 +137,7 @@ export function DocumentList() {
},
);
return () => controller.abort();
}, [cursor, gateway, kind, q, retryGeneration, status]);
}, [gateway, kind, pageNumber, q, retryGeneration, status]);
const changeFilter = (next: {
kind?: ListDocumentsQuery["kind"];
@@ -144,12 +145,13 @@ export function DocumentList() {
}) => {
if ("kind" in next) setKind(next.kind);
if ("status" in next) setStatus(next.status);
setCursor(undefined);
// 3쪽에 있던 채로 필터를 좁히면 결과가 그보다 적어 빈 화면이 나온다.
setPageNumber(1);
};
const submitSearch = (event: FormEvent) => {
event.preventDefault();
setQ(searchDraft.trim());
setCursor(undefined);
setPageNumber(1);
};
return (
@@ -240,8 +242,15 @@ export function DocumentList() {
해서, 28건 중 20건이 보이는 동안 무엇을 지워도 "20개" 가 그대로였다.
*/}
<p className="studio-result-count">
<span>{page.items.length}개 표시 중</span>
{page.nextCursor ? <span> · 더 있습니다</span> : null}
<span>
{page.page.totalElements}개 중 {page.items.length}개 표시 중
</span>
{page.page.totalPages > 1 ? (
<span>
{" "}
· {page.page.number} / {page.page.totalPages} 쪽
</span>
) : null}
</p>
{deleteError ? (
<p className="studio-screen-error" role="alert">
@@ -311,15 +320,11 @@ export function DocumentList() {
</GuardedStudioLink>
</section>
)}
{page.nextCursor ? (
<button
className="studio-secondary-button"
type="button"
onClick={() => setCursor(page.nextCursor ?? undefined)}
>
다음 작업본
</button>
) : null}
<StudioPagination
page={page.page}
label="작업본 페이지"
onChange={setPageNumber}
/>
</>
) : null}
</div>
@@ -17,6 +17,7 @@ import {
} from "./publication-flow-classes.ts";
import { UnpublishDialog } from "./unpublish-dialog.tsx";
import { useStudio } from "../use-studio.ts";
import { StudioPagination } from "./studio-pagination.tsx";
const eventLabels = {
PUBLISHED: "게시",
@@ -57,7 +58,7 @@ export function PublicationList({
classes: styles = defaultPublicationFlowClasses,
}: { classes?: PublicationFlowClasses } = {}) {
const studio = useStudio();
const [query, setQuery] = useState<ListPublicationsQuery>({ limit: 100 });
const [query, setQuery] = useState<ListPublicationsQuery>({ page: 1, limit: 20 });
const [queryDraft, setQueryDraft] = useState("");
const [typeDraft, setTypeDraft] =
useState<ListPublicationsQuery["type"]>();
@@ -273,6 +274,13 @@ export function PublicationList({
})}
</ol>
) : null}
{state.status === "READY" ? (
<StudioPagination
page={state.page.page}
label="게시 기록 페이지"
onChange={(next) => setQuery((current) => ({ ...current, page: next }))}
/>
) : null}
<UnpublishDialog
item={selected}
@@ -0,0 +1,88 @@
import type { components } from "../../../contracts/studio/generated.ts";
type PageMetadata = components["schemas"]["StudioPageMetadata"];
/**
* 페이지가 많아지면 번호를 다 그릴 수 없다. 현재 쪽 좌우로 이만큼씩만 그리고 나머지는 생략한다 —
* 첫 쪽과 끝 쪽은 늘 남긴다. 목록 어디에 있든 처음과 끝으로 한 번에 갈 수 있어야 한다.
*/
const AROUND = 2;
function pageNumbers(current: number, total: number): ReadonlyArray<number | "gap"> {
if (total <= 1) return total === 1 ? [1] : [];
const shown = new Set<number>([1, total]);
for (let n = current - AROUND; n <= current + AROUND; n += 1) {
if (n >= 1 && n <= total) shown.add(n);
}
const sorted = [...shown].sort((left, right) => left - right);
const out: (number | "gap")[] = [];
let previous = 0;
for (const n of sorted) {
if (previous && n - previous > 1) out.push("gap");
out.push(n);
previous = n;
}
return out;
}
/**
* Studio 목록의 페이지 이동.
*
* <p>예전에는 「다음」 하나뿐이었다 — 목록이 커서 페이지네이션이라 앞으로만 갈 수 있었고, 뒤로
* 넘어간 뒤 앞쪽으로 돌아올 방법이 없었다. 지금은 서버가 총 쪽수를 주므로 번호를 그린다.
*/
export function StudioPagination({
page,
onChange,
label,
}: {
page: PageMetadata;
onChange: (next: number) => void;
/** 이 목록이 무엇인지 — 화면에 목록이 둘 이상일 때 보조 기술이 구분한다. */
label: string;
}) {
if (page.totalPages <= 1) return null;
const numbers = pageNumbers(page.number, page.totalPages);
return (
<nav className="studio-pagination" aria-label={label}>
<button
type="button"
onClick={() => onChange(page.number - 1)}
disabled={!page.hasPrevious}
aria-label="이전 페이지"
>
‹
</button>
<ol>
{numbers.map((entry, index) =>
entry === "gap" ? (
// 생략된 구간. 읽어 줄 것이 없으므로 보조 기술에서는 숨긴다.
<li key={`gap-${index}`} aria-hidden="true" className="studio-pagination__gap">
…
</li>
) : (
<li key={entry}>
<button
type="button"
onClick={() => onChange(entry)}
aria-label={`${entry} 페이지`}
aria-current={entry === page.number ? "page" : undefined}
>
{entry}
</button>
</li>
),
)}
</ol>
<button
type="button"
onClick={() => onChange(page.number + 1)}
disabled={!page.hasNext}
aria-label="다음 페이지"
>
›
</button>
</nav>
);
}
@@ -189,3 +189,15 @@
.studio-app .studio-document-tools form { grid-column: 1; }
.studio-app .studio-document-row dl { grid-template-columns: minmax(0, 1fr); }
}
/*
목록의 페이지 이동. 예전에는 「다음」 버튼 하나뿐이라 뒤로 넘어간 뒤 앞쪽으로 돌아올 방법이
없었다. 번호는 현재 쪽 좌우로만 그리고 나머지는 생략하되 첫 쪽과 끝 쪽은 늘 남긴다.
*/
.studio-app .studio-pagination { display: flex; align-items: center; gap: 6px; margin-top: 32px; }
.studio-app .studio-pagination ol { display: flex; align-items: center; gap: 4px; margin: 0; padding: 0; list-style: none; }
.studio-app .studio-pagination button { min-width: 40px; min-height: 40px; padding-inline: 10px; border: 1px solid var(--line-strong); border-radius: 5px; background: var(--paper); color: var(--ink); font: inherit; font-size: 14px; font-weight: 550; }
.studio-app .studio-pagination button:disabled { opacity: 0.4; }
/* 지금 보고 있는 쪽. 눌러도 같은 자리라는 것이 보여야 한다. */
.studio-app .studio-pagination button[aria-current="page"] { border-color: var(--signal); background: var(--signal); color: #fff; }
.studio-app .studio-pagination__gap { min-width: 24px; color: var(--faint); text-align: center; }
@@ -0,0 +1,66 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, it, vi } from "vitest";
import { StudioPagination } from "../../../src/features/tech-log/presentation/studio/components/studio-pagination.tsx";
/*
목록은 커서 페이지네이션이라 「다음」 하나뿐이었다 — 뒤로 넘어간 뒤 앞쪽으로 돌아올 방법이
없었다. 번호를 그리는 규칙에는 분기가 있으므로(생략 구간, 첫·끝 쪽 고정) 값으로 고정한다.
*/
const meta = (number: number, totalPages: number) => ({
number,
size: 20,
totalElements: totalPages * 20,
totalPages,
hasPrevious: number > 1,
hasNext: number < totalPages,
});
function numbers() {
return Array.from(
screen.getByRole("navigation").querySelectorAll("ol > li"),
(item) => item.textContent,
);
}
it("한 쪽뿐이면 그리지 않는다", () => {
const { container } = render(
<StudioPagination page={meta(1, 1)} onChange={vi.fn()} label="목록" />,
);
expect(container).toBeEmptyDOMElement();
});
it("쪽이 적으면 번호를 전부 그린다", () => {
render(<StudioPagination page={meta(1, 3)} onChange={vi.fn()} label="목록" />);
expect(numbers()).toEqual(["1", "2", "3"]);
expect(screen.getByRole("button", { name: "1 페이지" })).toHaveAttribute("aria-current", "page");
expect(screen.getByRole("button", { name: "이전 페이지" })).toBeDisabled();
expect(screen.getByRole("button", { name: "다음 페이지" })).toBeEnabled();
});
it("쪽이 많으면 현재 쪽 둘레만 그리고 첫·끝은 남긴다", () => {
render(<StudioPagination page={meta(10, 20)} onChange={vi.fn()} label="목록" />);
// 어디에 있든 처음과 끝으로 한 번에 갈 수 있어야 한다.
expect(numbers()).toEqual(["1", "…", "8", "9", "10", "11", "12", "…", "20"]);
});
it("마지막 쪽에서는 다음으로 갈 수 없다", () => {
render(<StudioPagination page={meta(3, 3)} onChange={vi.fn()} label="목록" />);
expect(screen.getByRole("button", { name: "다음 페이지" })).toBeDisabled();
expect(screen.getByRole("button", { name: "이전 페이지" })).toBeEnabled();
});
it("번호를 누르면 그 쪽을 알린다", async () => {
const onChange = vi.fn();
render(<StudioPagination page={meta(3, 5)} onChange={onChange} label="목록" />);
await userEvent.click(screen.getByRole("button", { name: "5 페이지" }));
expect(onChange).toHaveBeenCalledWith(5);
// 뒤로 돌아오는 길 — 이것이 없어서 고친 것이다.
await userEvent.click(screen.getByRole("button", { name: "이전 페이지" }));
expect(onChange).toHaveBeenCalledWith(2);
});
@@ -87,23 +87,27 @@ describe("TechLog Studio index screens", () => {
const gateway = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway();
renderScreen(<DocumentList />, gateway);
expect(await screen.findByText("7개 표시 중")).toBeVisible();
expect(await screen.findByText("7개 중 7개 표시 중")).toBeVisible();
fireEvent.change(screen.getByLabelText("검색"), { target: { value: "Fetch Join" } });
fireEvent.submit(screen.getByRole("search"));
expect(await screen.findByText("1개 표시 중")).toBeVisible();
expect(await screen.findByText("1개 중 1개 표시 중")).toBeVisible();
expect(screen.getByText("컬렉션 Fetch Join과 페이징은 왜 충돌하는가")).toBeVisible();
fireEvent.change(screen.getByLabelText("종류"), { target: { value: "QUESTION" } });
expect(await screen.findByText("0개 표시 중")).toBeVisible();
expect(await screen.findByText("0개 중 0개 표시 중")).toBeVisible();
expect(screen.getByRole("heading", { level: 2, name: "조건에 맞는 작업본이 없습니다" })).toBeVisible();
});
it("cancels an obsolete list request and advances cursor pagination", async () => {
it("cancels an obsolete list request and moves between numbered pages", async () => {
const base = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioGateway();
const all = await base.listDocuments({ limit: 20 });
let obsoleteSignal: AbortSignal | undefined;
const firstPage: DocumentPage = { items: all.items.slice(0, 1), nextCursor: "next-page" };
const secondPage: DocumentPage = { items: all.items.slice(1, 2), nextCursor: null };
const meta = (number: number) => ({
number, size: 20, totalElements: 2, totalPages: 2,
hasPrevious: number > 1, hasNext: number < 2,
});
const firstPage: DocumentPage = { items: all.items.slice(0, 1), nextCursor: null, page: meta(1) };
const secondPage: DocumentPage = { items: all.items.slice(1, 2), nextCursor: null, page: meta(2) };
const listDocuments = vi.fn<StudioGateway["listDocuments"]>()
.mockImplementationOnce((_query, { signal } = {}) => {
obsoleteSignal = signal;
@@ -116,11 +120,14 @@ describe("TechLog Studio index screens", () => {
fireEvent.change(screen.getByLabelText("종류"), { target: { value: "CASE" } });
await waitFor(() => expect(obsoleteSignal?.aborted).toBe(true));
expect(await screen.findByText("1개 표시 중")).toBeVisible();
await userEvent.click(screen.getByRole("button", { name: "다음 작업본" }));
expect(await screen.findByText("2개 중 1개 표시 중")).toBeVisible();
// 번호로 옮긴다 — 예전에는 「다음」 하나뿐이라 2쪽에서 1쪽으로 돌아올 방법이 없었다.
await userEvent.click(screen.getByRole("button", { name: "2 페이지" }));
await waitFor(() => expect(listDocuments).toHaveBeenCalledTimes(3));
expect(screen.getByText(secondPage.items[0]!.title)).toBeVisible();
expect(screen.queryByRole("button", { name: "다음 작업본" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "1 페이지" })).toBeEnabled();
expect(screen.getByRole("button", { name: "이전 페이지" })).toBeEnabled();
});
it("shows a retry action after a list failure and recovers", async () => {
@@ -138,7 +145,7 @@ describe("TechLog Studio index screens", () => {
expect(await screen.findByRole("alert")).toHaveTextContent("작업본을 불러오지 못했습니다.");
await user.click(screen.getByRole("button", { name: "다시 시도" }));
expect(await screen.findByText("7개 표시 중")).toBeVisible();
expect(await screen.findByText("7개 중 7개 표시 중")).toBeVisible();
expect(gateway.listDocuments).toHaveBeenCalledTimes(2);
});