fix(presentation): 처리 중 버튼·화면 문구·context 기능 적재를 고친다 #51

Merged
donghyeon.kang merged 6 commits from donghyeon.kang/fix/r9-screen-copy-pending AGit into main 2026-11-13 17:58:15 +00:00
22 changed files with 409 additions and 56 deletions
+1
View File
@@ -5,3 +5,4 @@
{"schema": 1, "kind": "estimate", "task": "w2-fe-ci-perf", "recorded_at": "2026-11-12T00:10+09:00", "transcript": "00d79702-1dea-4e11-b79a-f021d0d9f4bb", "started_at": "2026-11-11T21:30+09:00", "base": "d1b9c087", "task_kind": "improve+operate", "size": "large", "minutes": {"p30": 540, "p50": 870, "p80": 1380}, "calls": {"p30": 400, "p50": 600, "p80": 900}, "output_tokens": {"p30": 300000, "p50": 450000, "p80": 700000}, "basis": "시간은 착수 노트(공유 노트 w2-fe-ci-perf.md, 2026-11-11 21:45)의 1·2단계 합 9h·14.5h·23h를 옮겼다. 선례 fe-a-layout3-ci의 CI 재편 PR B 예측 3~6시간과 merge 단계 desktop 1회 22~25분. 2단계 불확실성은 FE-GATE-013 실행 환경(호스트·runner 변경 대기)과 runner 1대(1회 25~35분)의 실패-고침 반복 3~5번. 호출·출력 토큰은 착수 때 적지 않아 2단계 시작(1단계 실측 약 2.5시간)에 적었다."}
{"schema": 1, "kind": "actual", "task": "w2-fe-ci-perf", "recorded_at": "2026-11-12T22:25+09:00", "transcript": "00d79702-1dea-4e11-b79a-f021d0d9f4bb", "minutes": 1463, "active_minutes": 308, "calls": 447, "output_tokens": 413297, "cache_read_tokens": 246773496, "max_context": 943246, "within": "p30", "result": "partial", "commits": ["ddfcb6f6", "79a225b6", "0d8e4f5a", "b4210753", "66138440", "1d3eb901", "92abfd20", "1f09c1cc", "27876ffc", "35b60a04", "f90ffb6c", "f6e2560e", "ba72b865"], "why": "작업 중 시간은 p30 안이지만 일이 끝나지 않고 인계됐다(PR #19 Draft). 벽시계의 대부분은 runner 대기열(백엔드 정기 lane 뒤)과 desktop heavy 잠금 대기다. 남은 것: runner 초록 확인, concurrency, firefox 흔들림, coverage 경로, 느린 시험 둘. 세션 기록으로 다시 셌고 인계 절을 쓴 22:10 KST 뒤까지 들어 있다. 기록은 이어받은 세션이 남긴다"}
{"schema": 1, "kind": "estimate", "task": "w2-fe2-takeover", "recorded_at": "2026-11-12T22:25+09:00", "transcript": "fa9a12aa-7abc-46ca-a5fd-ee00cab98618", "started_at": "2026-11-12T21:05+09:00", "base": "ba72b865", "task_kind": "improve+operate", "size": "large", "minutes": {"p30": 180, "p50": 300, "p80": 480}, "calls": {"p30": 250, "p50": 400, "p80": 650}, "output_tokens": {"p30": 150000, "p50": 250000, "p80": 400000}, "basis": "PR #19 이어받기(인계 절 2026-11-12 22:10). concurrency·coverage 경로·느린 시험 둘은 각 30~60분(작음, 선례 W2-BE concurrency). firefox 008 흔들림은 원인 미확정이라 1~4시간. runner 1대를 백엔드와 같이 써 PR run 하나가 대기 포함 1시간 이상(W2-BE 기록: PR run이 2~4시간 뒤로 밀림), 초록 3회와 실패-고침 1~2번을 p80에 넣었다. 첫 5분 뒤에 적었다(인계 대기 중 시작)"}
{"schema": 1, "kind": "estimate", "task": "r9-fe-group-A", "recorded_at": "2026-11-13T18:50+09:00", "transcript": "66f9f89d-a13f-4cee-a2bf-c3c528c6bfb2", "started_at": "2026-11-13T17:57+09:00", "base": "ee95573f", "task_kind": "improve", "size": "large", "minutes": {"p30": 300, "p50": 420, "p80": 600}, "calls": {"p30": 350, "p50": 500, "p80": 750}, "output_tokens": {"p30": 200000, "p50": 300000, "p80": 450000}, "basis": "round9 그룹 A 발견 22건(화면·토큰·story·검사·접근성 기록)을 PR 셋으로. 바꿀 파일 약 60개, CSS 선언 118개 토큰화와 story 37개가 가장 크다. desktop heavy 잠금을 다른 세션 넷과 같이 써 실행마다 대기 10~30분, merge 단계 셋(각 약 21분)과 골든 갱신·변이 실험, runner run 셋(각 약 23분)을 p80에 넣었다. 선례 r9-fe F4a·F5(묶음당 2~4시간). 착수 약 50분 뒤 발견 원문을 다 읽고 PR1 고침을 쓰던 중에 적었다"}
+7 -4
View File
@@ -1182,7 +1182,7 @@ ${write ? `import { ${camel}RouteUrl } from "./${base}-routes.ts";\n` : ""}impor
* the page heading.
*/
export default function ${pascal}ListPage() {
const { message } = useLocale();
const { message, number } = useLocale();
const query = use${pascal}Items();
return (
<CollectionPage
@@ -1203,7 +1203,9 @@ export default function ${pascal}ListPage() {
: ""
}
resultCount={
query.data ? message("${camel}.list.resultCount", { count: query.data.total }) : null
query.data
? message("${camel}.list.resultCount", { count: number(query.data.total) })
: null
}
>
<AsyncSurface state={query.state} onRetry={query.retry}>
@@ -1348,13 +1350,14 @@ describe("${names.id} list page through the router", () => {
HttpResponse.json({
success: true,
data: [{ id: "item-1", name: "First item" }],
meta: { page: { number: 0, size: 20, total: 41, sort: null } },
meta: { page: { number: 0, size: 20, total: 12345, sort: null } },
}),
),
);
await openList();
expect(await screen.findByText("총 41개 항목")).toBeVisible();
// 1112/04-03. The count is a locale-formatted number.
expect(await screen.findByText("총 12,345개 항목")).toBeVisible();
});
// The backend answers an empty list as \`data: []\`, never by dropping \`data\`.
@@ -32,10 +32,15 @@ export function Pagination(props: PaginationProps) {
className="ui-pagination"
role={nested ? "group" : undefined}
>
{/* At the first or last page the edge button is aria-disabled, not
disabled: pressing "previous" on page 2 must not drop keyboard focus
when it becomes the first page. */}
<IconButton
accessibleName={previousLabel}
disabled={page <= 1}
onClick={() => onChange(page - 1)}
aria-disabled={page <= 1 || undefined}
onClick={() => {
if (page > 1) onChange(page - 1);
}}
variant="secondary"
>
<PreviousDirectionalIcon />
@@ -52,8 +57,10 @@ export function Pagination(props: PaginationProps) {
)}
<IconButton
accessibleName={nextLabel}
disabled={page >= pageCount}
onClick={() => onChange(page + 1)}
aria-disabled={page >= pageCount || undefined}
onClick={() => {
if (page < pageCount) onChange(page + 1);
}}
variant="secondary"
>
<NextDirectionalIcon />
@@ -27,7 +27,7 @@ export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
},
ref,
) {
const { message } = useLocale();
const { message, plural } = useLocale();
const [uncontrolledValue, setUncontrolledValue] = useState(
String(defaultValue ?? ""),
);
@@ -55,7 +55,10 @@ export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
? null
: maxLengthMessage
? maxLengthMessage(remaining)
: message("form.remaining", { count: remaining });
: plural(remaining, {
one: message("form.remaining.one", { count: remaining }),
other: message("form.remaining", { count: remaining }),
});
return (
<>
<textarea
+5 -2
View File
@@ -65,7 +65,7 @@ export function ErrorSummary<Values extends FormValues>(props: Readonly<{
<Heading id={headingId}>{message("form.errorSummary")}</Heading>
{entries.length > 0 ? (
<ul>
{entries.map(([name, message]) => (
{entries.map(([name, error]) => (
<li key={name}>
<a
href={`#${fieldId(name)}`}
@@ -75,7 +75,10 @@ export function ErrorSummary<Values extends FormValues>(props: Readonly<{
onFocusField(name);
}}
>
{fieldLabels[name]}: {message}
{message("form.errorSummary.item", {
label: fieldLabels[name],
message: error,
})}
</a>
</li>
))}
+12 -8
View File
@@ -76,17 +76,17 @@ const PLATFORM_KO_MESSAGES = {
"route.invalid.action": "안전한 탐색 링크를 사용해 주세요.",
"route.disabledFeature.title": "현재 사용할 수 없는 기능입니다.",
"route.disabledFeature.description":
"이 기능은 배포 설정에서 중지되어 있습니다. 코드에는 포함되어 있으며 운영자가 다시 켤 수 있습니다.",
"지금은 이 기능을 쓸 수 없습니다. 다른 메뉴를 이용하거나 나중에 다시 확인해 주세요.",
"route.disabledFeature.action": "다른 탐색 링크를 사용해 주세요.",
"route.auth.integration.title": "로그인 연동이 필요합니다.",
"route.auth.integration.description":
"외부 인증 소유자가 연결되면 이 보호 라우트를 사용할 수 있습니다.",
"지금은 로그인할 수 없습니다. 잠시 후 다시 시도해 주세요.",
"route.auth.recovering.title": "세션을 복구하고 있습니다.",
"route.auth.required.title": "세션이 필요합니다.",
"route.auth.recovering.description":
"기존 세션 확인을 계속하려면 복구를 실행하세요.",
"route.auth.required.description":
"이 화면은 인증 연동 지점을 확인하기 위한 보호 라우트입니다.",
"이 화면을 보려면 로그인해 주세요.",
"route.documentTitle": "{title} · {appName}",
"chunk.checking": "새 릴리스 정보를 확인하고 있습니다.",
"chunk.reloadOnce": "새 버전으로 한 번만 전환합니다.",
@@ -124,6 +124,7 @@ const PLATFORM_KO_MESSAGES = {
"template.dangerActions": "위험 작업",
"template.supportReference": "지원 참조: {reference}",
"form.errorSummary": "입력 내용을 확인해 주세요.",
"form.errorSummary.item": "{label}: {message}",
"form.unsaved.title": "저장하지 않은 변경이 있습니다.",
"form.unsaved.description": "이 화면을 떠나면 입력한 내용이 사라집니다.",
"form.validation.required": "필수 입력값입니다.",
@@ -157,6 +158,7 @@ const PLATFORM_KO_MESSAGES = {
"form.reauthLosesInput":
"다시 로그인하면 이 화면에 입력한 내용은 사라집니다. 필요하면 먼저 복사해 두세요.",
"form.remaining": "{count}자 남음",
"form.remaining.one": "{count}자 남음",
"toast.region": "알림",
"error.network_unreachable": "네트워크에 연결할 수 없습니다.",
"error.request_timeout": "요청 시간이 초과되었습니다.",
@@ -253,7 +255,7 @@ const PLATFORM_EN_MESSAGES = {
"route.EXAMPLES_PLATFORM.navigation": "Platform composition",
"route.EXAMPLES_PLATFORM.title": "Platform composition",
"route.NOT_FOUND.navigation": "Not found",
"route.NOT_FOUND.title": "Page not found",
"route.NOT_FOUND.title": "Page not found.",
"async.loading": "Loading",
"async.empty": "There are no items to display.",
"async.refreshing": "Checking for the latest information.",
@@ -282,17 +284,17 @@ const PLATFORM_EN_MESSAGES = {
"route.invalid.action": "Use a safe navigation link.",
"route.disabledFeature.title": "This feature is not available right now.",
"route.disabledFeature.description":
"The deployment configuration has switched it off. It is still part of this build and an operator can switch it back on.",
"You cannot use this feature right now. Use another menu or check again later.",
"route.disabledFeature.action": "Use another navigation link.",
"route.auth.integration.title": "Sign-in integration is required.",
"route.auth.integration.description":
"This protected route is available after an external authentication owner is connected.",
"You cannot sign in right now. Try again in a moment.",
"route.auth.recovering.title": "Recovering the session.",
"route.auth.required.title": "A session is required.",
"route.auth.recovering.description":
"Run recovery to continue checking the existing session.",
"route.auth.required.description":
"This protected route demonstrates the authentication integration seam.",
"Sign in to view this page.",
"route.documentTitle": "{title} · {appName}",
"chunk.checking": "Checking the new release information.",
"chunk.reloadOnce": "Switching to the new version once.",
@@ -329,6 +331,7 @@ const PLATFORM_EN_MESSAGES = {
"template.dangerActions": "Dangerous actions",
"template.supportReference": "Support reference: {reference}",
"form.errorSummary": "Review the entered information.",
"form.errorSummary.item": "{label}: {message}",
"form.unsaved.title": "You have unsaved changes.",
"form.unsaved.description":
"The entered information will be lost if you leave this page.",
@@ -357,12 +360,13 @@ const PLATFORM_EN_MESSAGES = {
"The server reported an unrecognized input field.",
"form.validation.configuration": "Review the input configuration.",
"form.conflict":
"Another update conflicts with this change. Your input has been preserved.",
"Another update conflicts with this change. Your input has been preserved, so check the latest version.",
"form.resendLater":
"The request sent again was not processed. Send the same request again shortly.",
"form.reauthLosesInput":
"Signing in again clears what you entered on this page. Copy it first if you need it.",
"form.remaining": "{count} characters remaining",
"form.remaining.one": "{count} character remaining",
"toast.region": "Notifications",
"error.network_unreachable": "The network is unavailable.",
"error.request_timeout": "The request timed out.",
@@ -41,6 +41,7 @@ export type MessageParameters = Readonly<{
"route.documentTitle": { title: string; appName: string };
"template.supportReference": { reference: string };
"form.remaining": { count: number };
"form.remaining.one": { count: number };
"home.runtime.summary": { buildId: string; releaseId: string };
"boot.supportReference": { reference: string };
}>;
+3 -4
View File
@@ -93,7 +93,6 @@ export function AppShell() {
<SessionStatus />
{integrationAvailable ? (
<Button
disabled={sessionAction.pending}
onClick={() =>
sessionAction.run(
sessionState === "authenticated"
@@ -103,11 +102,11 @@ export function AppShell() {
: "sign-in",
)
}
pending={sessionAction.pending}
pendingLabel={message("common.processing")}
size="compact"
>
{sessionAction.pending
? message("common.processing")
: sessionActionLabel}
{sessionActionLabel}
</Button>
) : null}
</div>
@@ -3,6 +3,7 @@ import {
useContext,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type ReactNode,
@@ -23,6 +24,12 @@ export type SessionContextValue = Readonly<{
}>;
const SessionContext = createContext<SessionContextValue | null>(null);
/**
* 1112/05-03. Set while a session action runs, shared by every session
* button: the shell's and a status page's buttons stay enabled while pending,
* so a press on either is ignored until the action ends.
*/
const SessionActionGateContext = createContext<{ current: boolean } | null>(null);
export function SessionProvider({
children,
@@ -46,6 +53,7 @@ export function SessionProvider({
recoveryDeclined && ownerState === "recovery-pending"
? "unauthenticated"
: ownerState;
const actionGate = useRef(false);
const value = useMemo<SessionContextValue>(
() =>
Object.freeze({
@@ -62,7 +70,11 @@ export function SessionProvider({
);
return (
<SessionContext.Provider value={value}>{children}</SessionContext.Provider>
<SessionContext.Provider value={value}>
<SessionActionGateContext.Provider value={actionGate}>
{children}
</SessionActionGateContext.Provider>
</SessionContext.Provider>
);
}
@@ -77,8 +89,11 @@ export function useSession(): SessionContextValue {
export type SessionAction = "sign-in" | "sign-out" | "recover";
/**
* One session action at a time, with the pending and failed state every
* session button shows. Sign-in returns to the current URL, hash included.
* One session action at a time across every session button, with the
* pending and failed state the pressed button shows. Sign-in returns to the
* current URL, hash included. A press while an action runs, on this button
* or another, is ignored: the buttons stay enabled (`pending`, not
* `disabled`) so keyboard focus survives the action.
*/
export function useSessionAction(): Readonly<{
pending: boolean;
@@ -89,8 +104,12 @@ export function useSessionAction(): Readonly<{
const { beginSignIn, signOut, recover } = useSession();
const [pending, setPending] = useState(false);
const [failed, setFailed] = useState(false);
const ownGate = useRef(false);
const running = useContext(SessionActionGateContext) ?? ownGate;
async function execute(action: SessionAction): Promise<void> {
if (running.current) return;
running.current = true;
setPending(true);
setFailed(false);
try {
@@ -100,6 +119,7 @@ export function useSessionAction(): Readonly<{
} catch {
setFailed(true);
} finally {
running.current = false;
setPending(false);
}
}
+16 -9
View File
@@ -288,12 +288,11 @@ function ProtectedRoute({
}
primaryAction={{
kind: "button",
label: pending
? message("common.processing")
: recovering
? message("action.recoverSession")
: message("action.signIn"),
disabled: pending,
label: recovering
? message("action.recoverSession")
: message("action.signIn"),
pending,
pendingLabel: message("common.processing"),
onAction: () => run(recovering ? "recover" : "sign-in"),
}}
surface="authentication-required"
@@ -519,14 +518,22 @@ function ContextRouteGateway({
.filter((featureId) => platformRuntime.isFeatureActive(featureId))
.map((featureId) => features.load(featureId)),
);
// The feature that owns the entered URL starts loading together with the
// routes, so its runtime half adds no round trip of its own.
// 1112/06-01. The context's features, and the one that owns the entered
// URL, start loading together with the routes: no runtime half waits for
// the routes module first. Owners found on the loaded routes are already
// loading (`features.load` shares one promise per feature); a route owned
// by a feature the context does not declare still loads before render.
const enteredRouteId = registeredRouteIdAt(enteredPathname);
const enteredOwner =
enteredRouteId === undefined ? undefined : ROUTE_FEATURE_OWNER[enteredRouteId];
void Promise.all([
routeModule.loadRoutes(),
loadActive(enteredOwner === undefined ? [] : [enteredOwner]),
loadActive([
...new Set([
...(enteredOwner === undefined ? [] : [enteredOwner]),
...routeModule.featureIds,
]),
]),
])
.then(async ([loaded]) => {
await loadActive(routeOwners(loaded));
+3 -1
View File
@@ -1,4 +1,6 @@
@import "tailwindcss";
/* Tailwind takes class names from src/ only (1112/06-03): words in docs, tests
and scripts must not add rules to the stylesheet every page waits for. */
@import "tailwindcss" source("../../");
@import "../design-system/tokens/primitive.css";
@import "../design-system/tokens/semantic.css";
@import "../design-system/tokens/component.css";
+2 -1
View File
@@ -28,7 +28,8 @@
background: var(--button-primary-hover);
}
.ui-button:disabled {
.ui-button:disabled,
.ui-button[aria-disabled="true"] {
cursor: not-allowed;
opacity: var(--opacity-disabled);
}
@@ -21,6 +21,15 @@ export type PageActionDefinition =
label: string;
onAction(): void;
disabled?: boolean;
/**
* Work started by this action is still running. The button stays
* focusable and is marked `aria-busy`; `disabled` would drop keyboard
* focus (`docs/manual/02-decision-tables.md` 6절). The action ignores
* repeated presses itself.
*/
pending?: boolean;
/** Label while `pending`; the button keeps `label` when omitted. */
pendingLabel?: string;
variant?: "primary" | "secondary" | "danger" | "ghost";
}>
| (Readonly<{
@@ -286,6 +295,8 @@ function PageActionBar(props: Readonly<{
disabled={action.disabled}
key={index}
onClick={action.onAction}
pending={action.pending}
pendingLabel={action.pendingLabel}
variant={action.variant}
>
{action.label}
@@ -0,0 +1,115 @@
// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
/**
* 1112/06-01. A context's features all load before its pages render, so that
* `application.features.get` works in every page of the context. The routes
* module and the features' runtime halves load side by side: a feature that
* does not own the entered URL must not wait for the routes module first.
*/
const gate = vi.hoisted(() => {
let releaseRoutes: () => void = () => {};
const routesLoaded = new Promise<void>((resolve) => {
releaseRoutes = resolve;
});
return {
routesLoaded,
releaseRoutes: () => releaseRoutes(),
peerRuntimeStarted: vi.fn(),
};
});
vi.mock("../../src/.generated/product-feature-index.ts", async () => {
const { FIXTURE_FEATURE_MODULE } = await import("../helpers/fixture-feature.tsx");
const { PEER_FEATURE_MODULE } = await peerModules();
return {
DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature", "peer-feature"],
PRODUCT_FEATURE_MODULES: [FIXTURE_FEATURE_MODULE, PEER_FEATURE_MODULE],
};
});
vi.mock("../../src/.generated/product-context-index.ts", async () => {
const { PEER_CONTEXT_MODULE } = await peerModules();
return { PRODUCT_CONTEXT_MODULES: [PEER_CONTEXT_MODULE] };
});
async function peerModules() {
const { defineFeatureModule } = await import("../../src/features/feature-module.ts");
const { defineBoundedContextModule } = await import(
"../../src/contexts/bounded-context-module.ts"
);
const { FIXTURE_CONTEXT_ROUTES, FIXTURE_FEATURE_MODULE } = await import(
"../helpers/fixture-feature.tsx"
);
const PEER_FEATURE_MODULE = defineFeatureModule({
id: "peer-feature",
contracts: Object.freeze({
featureId: "peer-feature",
routes: Object.freeze({}),
routeRuntimeContracts: Object.freeze({}),
invalidation: Object.freeze({ topics: [], namespaces: [], edges: [] }),
topicVersions: Object.freeze([]),
contractPackages: Object.freeze([]),
}),
routes: Object.freeze({}),
messages: Object.freeze({ "ko-KR": Object.freeze({}), "en-US": Object.freeze({}) }),
loadRuntime: async () =>
Object.freeze({
featureId: "peer-feature",
schemas: Object.freeze({}),
adapters: Object.freeze([]),
contractContributions: Object.freeze([]),
}),
});
const PEER_CONTEXT_MODULE = defineBoundedContextModule({
id: "fixture-context",
features: [FIXTURE_FEATURE_MODULE, PEER_FEATURE_MODULE],
budget: { maxFeatures: 2 },
route: {
path: "fixture/*",
loadRoutes: async () => {
await gate.routesLoaded;
return FIXTURE_CONTEXT_ROUTES;
},
},
});
return { PEER_FEATURE_MODULE, PEER_CONTEXT_MODULE };
}
describe("context feature loading", () => {
it("starts every feature of the context together with its routes module", async () => {
window.history.pushState({}, "", "/fixture/first");
render(
<ApplicationProvider
application={createTestApplication({
// The application loads a feature's runtime half through these.
featureLoaders: {
"peer-feature": async () => {
gate.peerRuntimeStarted();
return {};
},
},
})}
>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
// The routes module is still downloading.
await waitFor(() => expect(gate.peerRuntimeStarted).toHaveBeenCalledOnce());
gate.releaseRoutes();
expect(
await screen.findByRole("heading", { name: "Fixture first page", level: 1 }),
).toBeVisible();
expect(gate.peerRuntimeStarted).toHaveBeenCalledOnce();
});
});
@@ -17,6 +17,7 @@ import {
Tooltip,
useToast,
} from "../../src/presentation/design-system/index.ts";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
/**
* 1112/05-10, 05-11, 05-13, 05-14, 05-17. What the shared primitives promise
@@ -267,4 +268,27 @@ describe("TextArea counter", () => {
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(field).toHaveAccessibleDescription(/27/u);
});
// 1112/04-03. The count picks the locale's singular and plural forms.
it("uses the singular form for one character left in English", () => {
render(
<LocaleProvider initialLocale="en-US">
<TextArea label="Note" maxLength={5} defaultValue="abcd" />
</LocaleProvider>,
);
expect(screen.getByRole("textbox", { name: "Note" })).toHaveAccessibleDescription(
"1 character remaining",
);
});
it("keeps the plural form for other counts", () => {
render(
<LocaleProvider initialLocale="en-US">
<TextArea label="Note" maxLength={5} defaultValue="abc" />
</LocaleProvider>,
);
expect(screen.getByRole("textbox", { name: "Note" })).toHaveAccessibleDescription(
"2 characters remaining",
);
});
});
+56
View File
@@ -1,6 +1,8 @@
// @vitest-environment jsdom
import { fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { Pagination } from "../../src/presentation/design-system/index.ts";
@@ -116,3 +118,57 @@ describe("Pagination modified clicks", () => {
expect(onChange).toHaveBeenCalledWith(2);
});
});
// 1112/05-03. Reaching the first or last page must not take keyboard focus
// away from the edge button the user just pressed.
describe("Pagination edge buttons", () => {
function Controlled(props: Readonly<{ onChange(page: number): void }>) {
const [page, setPage] = useState(2);
return (
<Pagination
label="Pages"
nextLabel="Next"
onChange={(next) => {
props.onChange(next);
setPage(next);
}}
page={page}
pageCount={3}
pageLabel={(candidate) => `Page ${candidate}`}
previousLabel="Previous"
/>
);
}
it("keeps focus on previous when it reaches the first page and ignores further presses", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(<Controlled onChange={onChange} />);
const previous = screen.getByRole("button", { name: "Previous" });
await user.click(previous);
expect(onChange).toHaveBeenCalledWith(1);
expect(previous).not.toBeDisabled();
expect(previous).toHaveAttribute("aria-disabled", "true");
expect(previous).toHaveFocus();
await user.keyboard("{Enter}");
expect(onChange).toHaveBeenCalledOnce();
});
it("marks next at the last page the same way", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(<Controlled onChange={onChange} />);
const next = screen.getByRole("button", { name: "Next" });
await user.click(next);
expect(next).toHaveAttribute("aria-disabled", "true");
expect(next).toHaveFocus();
await user.click(next);
expect(onChange).toHaveBeenCalledOnce();
expect(screen.getByRole("button", { name: "Previous" })).not.toHaveAttribute(
"aria-disabled",
);
});
});
+36 -3
View File
@@ -96,13 +96,41 @@ describe("route-level status surfaces", () => {
expect(beginSignIn).toHaveBeenCalledWith(
"/fixture/items#results",
);
expect(screen.getByRole("button", { name: "처리 중…" })).toBeDisabled();
// 1112/05-03: pending, not disabled, so keyboard focus stays on it.
const busy = screen.getByRole("button", { name: "처리 중…" });
expect(busy).not.toBeDisabled();
expect(busy).toHaveAttribute("aria-busy", "true");
expect(busy).toHaveFocus();
await user.keyboard("{Enter}");
expect(beginSignIn).toHaveBeenCalledOnce();
pending.reject(new Error("identity provider unavailable"));
expect(await screen.findByRole("alert")).toHaveTextContent(
"세션 작업을 완료하지 못했습니다.",
);
expect(screen.getByRole("button", { name: "로그인 시작" })).toBeEnabled();
const retry = screen.getByRole("button", { name: "로그인 시작" });
expect(retry).toBe(busy);
expect(retry).toBeEnabled();
expect(retry).not.toHaveAttribute("aria-busy");
expect(retry).toHaveFocus();
});
// 1112/05-03. The shell's button and the page's button share one action.
it("ignores the other session button while one session action runs", async () => {
const user = userEvent.setup();
const pending = deferred();
const beginSignIn = vi.fn(() => pending.promise);
renderApp("/fixture/items", { session: sessionWithSignIn(beginSignIn) });
const shellButton = await within(screen.getByRole("banner")).findByRole("button", {
name: "로그인",
});
await user.click(await screen.findByRole("button", { name: "로그인 시작" }));
await user.click(shellButton);
expect(beginSignIn).toHaveBeenCalledOnce();
pending.reject(new Error("identity provider unavailable"));
expect(await screen.findByRole("button", { name: "로그인 시작" })).not.toHaveAttribute("aria-busy");
});
it("returns to the current URL with its hash from the shell session action", async () => {
@@ -116,12 +144,17 @@ describe("route-level status surfaces", () => {
await within(banner).findByRole("button", { name: "로그인" }),
);
expect(beginSignIn).toHaveBeenCalledWith("/fixture/first#buttons");
expect(within(banner).getByRole("button", { name: "처리 중…" })).toBeDisabled();
const busy = within(banner).getByRole("button", { name: "처리 중…" });
expect(busy).not.toBeDisabled();
expect(busy).toHaveAttribute("aria-busy", "true");
await user.click(busy);
expect(beginSignIn).toHaveBeenCalledOnce();
pending.reject(new Error("identity provider unavailable"));
expect(await within(banner).findByRole("alert")).toHaveTextContent(
"세션 작업을 완료하지 못했습니다.",
);
expect(within(banner).getByRole("button", { name: "로그인" })).toHaveFocus();
});
it("answers an unknown address with a home link that keeps the basename", async () => {
+1 -1
View File
@@ -121,7 +121,7 @@ describe("generic application router", () => {
await user.selectOptions(localeSelect, "en-US");
await waitFor(() =>
expect(document.title).toBe("Page not found · Frontend Skeleton"),
expect(document.title).toBe("Page not found. · Frontend Skeleton"),
);
expect(
screen.getByRole("heading", { name: "Page not found.", level: 1 }),
+4
View File
@@ -0,0 +1,4 @@
A Tailwind utility written outside src/ (1112/06-03). The production
stylesheet must not contain it: Tailwind scans only src/ for class names.
outline-[3.21px]
+3 -2
View File
@@ -179,7 +179,8 @@ describe("create:feature rendering", () => {
expect(contribution).toContain(`const API_PATH = "${apiPath}";`);
});
// 1103/03-02. A page list's meta.page.total counts every page.
// 1103/03-02. A page list's meta.page.total counts every page; 1112/04-03 shows
// it as a locale-formatted number.
it("shows the total the backend counted, not the length of the first page", () => {
const { files } = plan({ id: "invoice-feature" });
@@ -188,7 +189,7 @@ describe("create:feature rendering", () => {
);
expect(
files.get("src/features/invoice-feature/presentation/invoice-list-page.tsx"),
).toContain('message("invoice.list.resultCount", { count: query.data.total })');
).toContain('message("invoice.list.resultCount", { count: number(query.data.total) })');
});
});
+38 -12
View File
@@ -38,19 +38,30 @@ afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
let built: Promise<string> | undefined;
/** One production build for the file's tests. */
function build(): Promise<string> {
built ??= (async () => {
const outDir = await mkdtemp(path.join(tmpdir(), "design-system-chunk-"));
roots.push(outDir);
const environment = Object.fromEntries(
Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")),
);
const run = spawnSync(
path.resolve("node_modules/.bin/vite"),
["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"],
{ encoding: "utf8", env: environment },
);
expect(run.stderr).toBe("");
expect(run.status).toBe(0);
return outDir;
})();
return built;
}
async function initialJavascript(): Promise<string> {
const outDir = await mkdtemp(path.join(tmpdir(), "design-system-chunk-"));
roots.push(outDir);
const environment = Object.fromEntries(
Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")),
);
const run = spawnSync(
path.resolve("node_modules/.bin/vite"),
["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"],
{ encoding: "utf8", env: environment },
);
expect(run.stderr).toBe("");
expect(run.status).toBe(0);
const outDir = await build();
const manifest = JSON.parse(
await readFile(path.join(outDir, ".vite/manifest.json"), "utf8"),
) as Parameters<typeof classifyViteJavascript>[0];
@@ -73,6 +84,21 @@ describe("design-system code in the initial JavaScript (1101/08-08)", () => {
expect(LAZY_ONLY_CLASSES.filter((name) => renders(code, name))).toEqual([]);
}, childProcessTimeout(4_556));
// 1112/06-03. Tailwind scans the files it is pointed at for class names.
// Words in docs, tests and scripts must not add rules to the stylesheet
// every page blocks on (tests/fixtures/tailwind-source/outside-src.txt).
it("generates utilities from src only, not from docs, tests or scripts", async () => {
const outDir = await build();
const assets = path.join(outDir, "assets");
const stylesheets = (await readdir(assets)).filter((file) => file.endsWith(".css"));
const css = (
await Promise.all(stylesheets.map((file) => readFile(path.join(assets, file), "utf8")))
).join("\n");
expect(css).toContain(".ui-button");
expect(css).not.toContain("3.21px");
}, childProcessTimeout(4_556));
// vite.config.ts declares these modules free of side effects, so the bundler
// drops a module none of whose exports is used. An import kept only for its
// effect (a stylesheet, a polyfill, a registration) would vanish with it.
+32
View File
@@ -130,3 +130,35 @@ describe("internationalization formatter contract", () => {
).toBe(FORMAT_FALLBACK);
});
});
// 1112/04-01, 04-07. Copy an end user reads on the platform status surfaces.
describe("platform status copy", () => {
const ENGLISH_AND_KOREAN = [KO_MESSAGES, EN_MESSAGES] as const;
it("does not explain the template to the end user on status surfaces", () => {
const developerWords =
/라우트|연동 지점|seam|코드에는 포함|운영자|operator|protected route|this build/iu;
for (const catalog of ENGLISH_AND_KOREAN) {
for (const key of [
"route.auth.required.description",
"route.auth.integration.description",
"route.disabledFeature.description",
] as const) {
expect(catalog[key], key).not.toMatch(developerWords);
}
}
});
it("titles the not-found document the same as its heading", () => {
for (const catalog of ENGLISH_AND_KOREAN) {
expect(catalog["route.NOT_FOUND.title"]).toBe(catalog["page.notFound.title"]);
}
});
it("joins an error summary entry through the catalog", () => {
expect(formatMessage("en-US", "form.errorSummary.item", {
label: "Name",
message: "Required.",
})).toBe("Name: Required.");
});
});