Files
clean-architecture-frontend…/src/presentation/components/async-surface.tsx
T
DongHyeonka 683ccfb56b fix(query): 키 없는 결과 불명 요청의 같은 입력 재제출을 훅이 막는다
문제
0929/03-03은 화면 버튼 쪽만 고쳐졌다. 남은 길이 둘이다.
- useApplicationMutation의 submit은 같은 canonical input의 결과 불명
  admission을 찾아 그 intent를 그대로 다시 보낸다. 키 없는 intent(NEVER)면
  서버가 가려낼 수 없는 두 번째 요청이다. 막는 곳은 폼(unknownSubmissionRef)과
  두 페이지의 버튼·onSubmit 검사뿐이라, 폼 밖에서 submit을 부르는 화면은 같은
  항목을 둘 만들 수 있다(리뷰 실험 X1: 재전송은 null인데 같은 입력 submit이
  두 번째 POST를 보냈고 keys=[null,null]).
- AsyncSurface는 state.unknownEffectResendable !== false일 때 재전송 버튼을
  그린다. 코디네이터 없이 손으로 만든 AsyncState(플래그 없음)는 지금도 버튼을
  그린다(실험 X3).

고른 방법
- submit이 같은 입력의 결과 불명 admission을 찾았는데 그 intent에 키가 없으면
  보내지 않고 NOT_STARTED DUPLICATE_IN_FLIGHT(code UNKNOWN_EFFECT_PENDING)를
  돌려준다. admission을 만들기 전이라 결과 불명 상태와 identity lease는 그대로다.
  KEYED의 같은 키 재전송, 입력이 바뀐 새 요청은 바뀌지 않는다. LEGACY(테스트
  하네스) 경로는 intent가 없어 replay 자체가 없으므로 영향이 없다.
- AsyncSurface는 unknownEffectResendable === true일 때만 재전송 버튼을 그린다.
  코디네이터의 state는 늘 이 값을 싣는다(canResendUnknownEffect).
- 기존 async-surface 테스트 "renders unknown mutation effects with
  confirm-applied and resend only"는 플래그 없는 상태로 버튼을 기대했다. 이
  수정의 의도대로 isUnknownEffectResendable: true를 입력에 적었다. 단언은 그대로다.
- 런북 6.3-4와 매뉴얼 01에 키 없는 재제출과 손으로 만든 상태를 적었다.

버린 대안
FailureKind에 새 kind를 더한다: 닫힌 레지스트리를 넓히는 계약 변경이다.
"같은 논리 요청이 아직 끝나지 않았다"는 DUPLICATE_IN_FLIGHT(action none)로
충분하다.

위험·한계
- 다운스트림이 AsyncSurface에 손으로 만든 결과 불명 상태와 onResendUnknownEffect를
  넘기던 화면은 재전송 버튼이 사라진다. 코디네이터의 state를 넘기면 그대로다.
- 결과 불명 admission은 메모리에만 있다. 새로고침 뒤 같은 입력은 막지 못한다
  (런북 6.3-7의 한계 그대로).

검증
desktop batch에서 확인:
node scripts/run-vitest.ts run tests/component/application-mutation-admission.test.tsx
tests/component/async-surface.test.tsx tests/component/application-query.test.tsx

Refs: 0929/03-03
2026-11-06 02:33:16 +09:00

271 lines
8.7 KiB
TypeScript

import { useId, type ReactNode } from "react";
import type { AsyncState } from "../../application/view-models/async-state.ts";
import type { AppFailure } from "../../contracts/errors.ts";
import { useLocale } from "../i18n/index.ts";
import { errorMessage } from "./error-copy.ts";
import {
AuthRequiredSurface,
ForbiddenSurface,
type HeadingLevel,
NotFoundSurface,
} from "./state-surfaces.tsx";
import { Button } from "./ui/button.ts";
export function LoadingSurface({
label,
description,
}: Readonly<{ label?: string; description?: string }>) {
const { message } = useLocale();
// Visible copy doubles as the name unless a separate label is given.
const accessibleLabel = label ?? description ?? message("async.loading");
return (
<section
className="state-surface state-surface--loading"
aria-busy="true"
aria-label={accessibleLabel}
aria-live="polite"
aria-atomic="true"
>
<div className="ui-skeleton" aria-hidden="true" />
{description ? <p>{description}</p> : null}
{accessibleLabel === description ? null : (
<span className="visually-hidden">{accessibleLabel}</span>
)}
</section>
);
}
export type EmptySurfaceProps = Readonly<{
title?: string;
description?: string;
action?: ReactNode;
/** 08-05. Below the heading of the card or section that holds it. */
headingLevel?: HeadingLevel | undefined;
}>;
export function EmptySurface({
title,
description,
action,
headingLevel = 2,
}: EmptySurfaceProps) {
const { message } = useLocale();
const Heading = `h${headingLevel}` as const;
return (
<section className="ui-empty state-surface" aria-live="polite">
<Heading>{title ?? message("async.empty")}</Heading>
{description ? <p>{description}</p> : null}
{action}
</section>
);
}
export type TerminalErrorSurfaceProps = Readonly<{
userMessageKey: string;
action: AppFailure["action"];
onAction?: () => void;
/** Read before the action, inside the same alert. */
description?: string;
/** 08-07. The id a user quotes to support, e.g. `AppFailure.requestId`. */
supportReference?: string;
/** 08-05. Below the heading of the card or section that holds it. */
headingLevel?: HeadingLevel | undefined;
}>;
export function TerminalErrorSurface({
userMessageKey,
action,
onAction,
description,
supportReference,
headingLevel = 2,
}: TerminalErrorSurfaceProps) {
const { locale, message } = useLocale();
const messageId = useId();
const Heading = `h${headingLevel}` as const;
const actionLabels: Readonly<
Record<Exclude<AppFailure["action"], "none">, string>
> = Object.freeze({
retry: message("action.retry"),
reauth: message("action.reauth"),
navigate: message("action.navigateSafe"),
"reload-once": message("action.reloadOnce"),
"contact-support": message("action.contactSupport"),
});
return (
<section
className="ui-terminal-error state-surface state-surface--danger"
role="alert"
aria-labelledby={messageId}
data-message-key={userMessageKey}
>
<Heading id={messageId}>{errorMessage(userMessageKey, locale)}</Heading>
{description ? <p>{description}</p> : null}
{action !== "none" && onAction && (
<Button onClick={onAction}>{actionLabels[action]}</Button>
)}
{supportReference ? (
<p>
{message("template.supportReference", {
reference: supportReference,
})}
</p>
) : null}
</section>
);
}
export type AsyncSurfaceProps = Readonly<{
state: AsyncState;
children?: ReactNode;
/** Shown while the query has not started (e.g. disabled); nothing if omitted. */
idle?: ReactNode;
onAction?: () => void;
onRetry?: () => void;
onResolveConflict?: () => void;
/** Only `APPLIED` is offered: "not applied" needs evidence the UI lacks. */
onReconcileUnknownEffect?: (resolution: "APPLIED") => void;
/**
* D-1. Resends the unknown request with its original intent and key.
* 0929/03-03. Drawn only when `state.unknownEffectResendable` is `true`
* (the coordinator's `canResendUnknownEffect`): a request without a key
* would go out as a second, unprotected one, and a state built by hand
* without that answer draws no resend either.
*/
onResendUnknownEffect?: () => void;
/** 08-05. Title level of the empty and failure surfaces it renders. */
headingLevel?: HeadingLevel | undefined;
/**
* 0929/08-04. Shown with an unknown mutation result: the request id of the
* save whose effect is unknown (`useAppForm().supportReference`). A
* terminal error shows its own `failure.requestId`.
*/
supportReference?: string | undefined;
}>;
export function AsyncSurface({
state,
children,
idle,
onAction,
onRetry,
onResolveConflict,
onReconcileUnknownEffect,
onResendUnknownEffect,
headingLevel,
supportReference,
}: AsyncSurfaceProps) {
const { message } = useLocale();
if (state.base === "idle") return idle ?? null;
if (state.base === "initial-loading") return <LoadingSurface />;
if (state.base === "empty") return <EmptySurface headingLevel={headingLevel} />;
if (state.base === "terminal-error" && state.failure) {
const AccessState = ACCESS_SURFACES[state.failure.kind];
if (AccessState) {
// 08-11. Access failures use the same surfaces as the design system's
// AccessSurface, so a query and the gallery show one copy.
return (
<div role="alert" data-message-key={state.failure.userMessageKey}>
<AccessState onAction={onAction} headingLevel={headingLevel} />
{state.failure.requestId ? (
<p>
{message("template.supportReference", {
reference: state.failure.requestId,
})}
</p>
) : null}
</div>
);
}
return (
<TerminalErrorSurface
userMessageKey={state.failure.userMessageKey}
action={state.failure.action}
onAction={
state.failure.action === "retry"
? onRetry ?? onAction
: onAction
}
supportReference={state.failure.requestId}
headingLevel={headingLevel}
/>
);
}
return (
<section aria-busy={state.overlay.refreshing || state.overlay.mutationPending}>
{state.indicator ? (
<div role="status" aria-live="polite">
<span>
{message(
state.indicator === "stale-degraded"
? "async.staleDegraded"
: state.indicator === "mutation-effect-unknown"
? "async.mutationEffectUnknown"
: state.indicator === "mutation-conflict"
? "async.mutationConflict"
: state.indicator === "mutation-pending"
? "async.mutationPending"
: "async.refreshing",
)}
</span>
{state.indicator === "stale-degraded" && onRetry ? (
<Button onClick={onRetry}>{message("action.retry")}</Button>
) : null}
{state.indicator === "mutation-conflict" && onResolveConflict ? (
<Button onClick={onResolveConflict}>
{message("action.resolveConflict")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" &&
onReconcileUnknownEffect ? (
<Button onClick={() => onReconcileUnknownEffect("APPLIED")}>
{message("action.confirmMutationApplied")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" &&
onResendUnknownEffect &&
state.unknownEffectResendable === true ? (
<Button onClick={onResendUnknownEffect}>
{message("action.resendMutation")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" && supportReference ? (
<p>
{message("template.supportReference", {
reference: supportReference,
})}
</p>
) : null}
</div>
) : null}
{children}
</section>
);
}
const ACCESS_SURFACES: Readonly<
Partial<
Record<
AppFailure["kind"],
(
props: Readonly<{
onAction?: () => void;
headingLevel?: HeadingLevel | undefined;
}>,
) => ReactNode
>
>
> = Object.freeze({
AUTH_REQUIRED: ({ onAction, headingLevel }) => (
<AuthRequiredSurface onSignIn={onAction} headingLevel={headingLevel} />
),
FORBIDDEN: ({ onAction, headingLevel }) => (
<ForbiddenSurface onNavigate={onAction} headingLevel={headingLevel} />
),
NOT_FOUND: ({ onAction, headingLevel }) => (
<NotFoundSurface onNavigate={onAction} headingLevel={headingLevel} />
),
});