chore: sync the frontend template from ebea300 to af3d8e6

Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
This commit is contained in:
DongHyeonka
2026-11-12 08:28:54 +09:00
parent 585c62431a
commit c80320dfc7
738 changed files with 55027 additions and 13567 deletions
@@ -170,14 +170,16 @@ export function useApplicationQuery<Value>(
const retry = useCallback(async () => {
setStaleFailure(false);
await query.refetch();
await query.refetch({ cancelRefetch: false });
}, [query]);
return Object.freeze({
data: query.data,
state: deriveAsyncState({
data: query.data,
isInitialLoading: query.isPending,
// A disabled query is pending but idle; a paused offline first load is
// pending and still waiting, which `isLoading` would miss.
isInitialLoading: query.isPending && query.fetchStatus !== "idle",
failure:
!hasData && query.error instanceof ApplicationQueryError
? query.error.failure
@@ -217,9 +219,19 @@ type ApplicationMutationController<Input, Value> = Readonly<{
state: AsyncState;
submit(input: Input): Promise<ApplicationResult<Value>>;
resolveConflict(): Promise<void>;
/**
* Settles the oldest unknown effect. `NOT_APPLIED` needs evidence (an
* inspect operation or a server read); without it, resend instead.
*/
reconcileUnknownEffect(
resolution: "APPLIED" | "NOT_APPLIED",
): Promise<void>;
/**
* D-1. Sends the oldest unknown-effect request again with its original
* intent, so a keyed command carries the same `Idempotency-Key`. Resolves
* to `null` when nothing is waiting to be resent.
*/
resendUnknownEffect(): Promise<ApplicationResult<Value> | null>;
}>;
type MutationExecution<Input> =
@@ -229,7 +241,10 @@ type MutationExecution<Input> =
type MutationAdmission = {
sequence: number;
state: "ACTIVE" | "UNKNOWN" | "RECONCILING" | "SETTLED";
readonly input: unknown;
intent: MutationIntent | null;
/** Held while UNKNOWN so the same input keeps the same identity token. */
identityLease: Readonly<{ release(): void }> | null;
scope: CacheScopeSnapshot | null;
optimisticLayer: OptimisticLayerLease | null;
optimisticQueryKey: readonly unknown[] | null;
@@ -434,11 +449,30 @@ export function useApplicationMutation<Input, Value>(
});
}
const active = mutationExecutions(queryClient).get(identity) as
| Promise<ApplicationResult<Value>>
| RuntimeMutationExecution<Value>
| undefined;
if (active && duplicatePolicy === "JOIN_IDENTICAL") {
if (
active.joinedWaiters >=
MUTATION_COORDINATOR_BOUNDS.waitersPerJoinedIntent
) {
identityLease?.release();
return Promise.resolve({
ok: false,
error: createFailure(
"DUPLICATE_IN_FLIGHT",
definitionId,
0,
{
code: "JOIN_WAITER_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
),
});
}
active.joinedWaiters += 1;
identityLease?.release();
return active;
return active.promise;
}
if (active && duplicatePolicy === "REJECT_WHILE_ACTIVE") {
identityLease?.release();
@@ -478,10 +512,19 @@ export function useApplicationMutation<Input, Value>(
),
});
}
// D-1. Saving the same canonical input again is the same logical
// request: it reuses the unknown admission's intent (and key).
const replayed = submissionChannel.admissions.find(
(candidate) =>
candidate.state === "UNKNOWN" &&
candidate.intent?.canonicalInputIdentity === identity,
);
const admission: MutationAdmission = {
sequence: submissionChannel.nextSequence++,
state: "ACTIVE",
input,
intent: null,
identityLease: null,
scope: scope ?? null,
optimisticLayer: null,
optimisticQueryKey: optimistic?.queryKey ?? null,
@@ -490,18 +533,27 @@ export function useApplicationMutation<Input, Value>(
};
submissionChannel.admissions.push(admission);
submissionChannel.registry.activeAdmissions += 1;
if (replayed) {
// The new attempt re-applies its own optimistic layer and owns the
// outcome from here.
replayed.optimisticLayer?.reconcile("NOT_APPLIED");
settleMutationAdmission(submissionChannel, replayed);
}
notifyUnknownEffectChannel(submissionChannel);
setConflict(null);
mutation.reset();
let runtimeExecution: RuntimeMutationExecution<Value> | undefined;
const pending = (async (): Promise<ApplicationResult<Value>> => {
let execution: MutationExecution<Input>;
if (scope) {
const intent = mutationIntentFactory.create({
operationId: mutationOperationId,
canonicalInputIdentity: identity,
requiresIdempotencyKey,
});
const intent =
replayed?.intent ??
mutationIntentFactory.create({
operationId: mutationOperationId,
canonicalInputIdentity: identity,
requiresIdempotencyKey,
});
admission.intent = intent;
execution = Object.freeze({ kind: "BOUND", input, intent });
} else {
@@ -563,6 +615,10 @@ export function useApplicationMutation<Input, Value>(
optimisticLayer?.markUncertain();
if (!scope || scope.isCurrent()) {
admission.state = "UNKNOWN";
if (identityLease) {
identityLease.acquire();
admission.identityLease = identityLease;
}
notifyUnknownEffectChannel(submissionChannel);
} else {
settleMutationAdmission(submissionChannel, admission);
@@ -601,12 +657,16 @@ export function useApplicationMutation<Input, Value>(
})
.finally(() => {
identityLease?.release();
if (mutationExecutions(queryClient).get(identity) === pending) {
if (
runtimeExecution &&
mutationExecutions(queryClient).get(identity) === runtimeExecution
) {
mutationExecutions(queryClient).delete(identity);
}
});
if (duplicatePolicy !== "ALLOW_PARALLEL") {
mutationExecutions(queryClient).set(identity, pending);
runtimeExecution = { promise: pending, joinedWaiters: 0 };
mutationExecutions(queryClient).set(identity, runtimeExecution);
}
return pending;
},
@@ -688,6 +748,19 @@ export function useApplicationMutation<Input, Value>(
[mutation, queryClient, unknownEffectChannel],
);
const resendUnknownEffect = useCallback(async () => {
const head = unknownEffectChannel?.admissions[0];
if (
!head ||
head.state !== "UNKNOWN" ||
!head.intent ||
unknownEffectChannel?.reconciliationInFlight
) {
return null;
}
return submit(head.input as Input);
}, [submit, unknownEffectChannel]);
const unknownEffectHead = unknownEffectChannel?.admissions[0];
return Object.freeze({
@@ -703,6 +776,7 @@ export function useApplicationMutation<Input, Value>(
submit,
resolveConflict,
reconcileUnknownEffect,
resendUnknownEffect,
});
}
@@ -811,6 +885,8 @@ function markMutationAdmissionSettled(
): void {
if (admission.state === "SETTLED") return;
admission.state = "SETTLED";
admission.identityLease?.release();
admission.identityLease = null;
channel.registry.activeAdmissions = Math.max(
0,
channel.registry.activeAdmissions - 1,
@@ -828,17 +904,22 @@ function removeAdmissionOptimisticQuery(
});
}
type RuntimeMutationExecution<Value = unknown> = {
promise: Promise<ApplicationResult<Value>>;
joinedWaiters: number;
};
const RUNTIME_MUTATION_EXECUTIONS = new WeakMap<
object,
Map<string, Promise<ApplicationResult<unknown>>>
Map<string, RuntimeMutationExecution>
>();
function mutationExecutions(
owner: object,
): Map<string, Promise<ApplicationResult<unknown>>> {
): Map<string, RuntimeMutationExecution> {
const existing = RUNTIME_MUTATION_EXECUTIONS.get(owner);
if (existing) return existing;
const created = new Map<string, Promise<ApplicationResult<unknown>>>();
const created = new Map<string, RuntimeMutationExecution>();
RUNTIME_MUTATION_EXECUTIONS.set(owner, created);
return created;
}
@@ -1,4 +1,17 @@
import { formatMessage } from "../i18n/index.ts";
import { BOOT_MESSAGES } from "../i18n/boot-messages.ts";
// 09-03. Read from the boot messages alone, not the i18n catalog: the shell
// has to render when the installed feature graph failed to evaluate.
const MESSAGES = BOOT_MESSAGES["ko-KR"];
// 09-10. Failures a fresh load can fix: the config or manifest request did
// not complete. Retrying stays a user action; nothing reloads on its own.
const RETRYABLE_CODES: ReadonlySet<string> = new Set([
"CONFIG_FETCH_FAILED",
"CONFIG_TIMEOUT",
"MANIFEST_FETCH_FAILED",
"MANIFEST_TIMEOUT",
]);
export type BootErrorShellProps = Readonly<{
kind?: string;
@@ -6,48 +19,69 @@ export type BootErrorShellProps = Readonly<{
buildId?: string;
configSchemaVersion?: string;
releaseId?: string;
invalidKeys?: readonly string[];
supportReference: string;
onRetry?: () => void;
}>;
export function BootErrorShell({
kind = "BOOT_CONFIG_FAILURE",
// 09-04. A failure nobody classified is not a configuration failure.
kind = "BOOT_UNEXPECTED_FAILURE",
code = "BOOT_FAILED",
buildId,
configSchemaVersion,
releaseId,
invalidKeys,
supportReference,
onRetry,
}: BootErrorShellProps) {
const retry = onRetry !== undefined && RETRYABLE_CODES.has(code);
return (
<main role="alert">
<h1>{formatMessage("ko-KR", "boot.failure.title")}</h1>
<h1>{MESSAGES["boot.failure.title"]}</h1>
<dl>
<dt>{formatMessage("ko-KR", "boot.field.error")}</dt>
<dt>{MESSAGES["boot.field.error"]}</dt>
<dd>{kind}</dd>
<dt>{formatMessage("ko-KR", "boot.field.code")}</dt>
<dt>{MESSAGES["boot.field.code"]}</dt>
<dd>{code}</dd>
{buildId && (
<>
<dt>{formatMessage("ko-KR", "boot.field.build")}</dt>
<dt>{MESSAGES["boot.field.build"]}</dt>
<dd>{buildId}</dd>
</>
)}
{configSchemaVersion && (
<>
<dt>{formatMessage("ko-KR", "boot.field.configSchema")}</dt>
<dt>{MESSAGES["boot.field.configSchema"]}</dt>
<dd>{configSchemaVersion}</dd>
</>
)}
{releaseId && (
<>
<dt>{formatMessage("ko-KR", "boot.field.release")}</dt>
<dt>{MESSAGES["boot.field.release"]}</dt>
<dd>{releaseId}</dd>
</>
)}
{invalidKeys && invalidKeys.length > 0 && (
<>
<dt>{MESSAGES["boot.field.invalidKeys"]}</dt>
<dd>{invalidKeys.join(", ")}</dd>
</>
)}
</dl>
{retry && (
<>
<p>{MESSAGES["boot.retry.hint"]}</p>
<button type="button" onClick={onRetry}>
{MESSAGES["boot.retry.action"]}
</button>
</>
)}
<p>
{formatMessage("ko-KR", "boot.supportReference", {
reference: supportReference,
})}
{MESSAGES["boot.supportReference"].replace(
"{reference}",
() => supportReference,
)}
</p>
</main>
);
@@ -3,7 +3,9 @@ import {
type ErrorInfo,
type ReactNode,
} from "react";
import { Button, LoadingSurface } from "../design-system/index.ts";
import { useLocale } from "../i18n/index.ts";
import { newIncidentId } from "./render-error-boundary.tsx";
type RecoveryResult =
| Readonly<{ action: "reload-once"; releasePair: string }>
@@ -16,12 +18,17 @@ type Props = Readonly<{
chunkId: string;
failureKind: "CHUNK_LOAD_FAILURE";
}>): Promise<RecoveryResult>;
/** 08-07. Shown with the incident id as the support reference. */
buildId?: string;
/** 08-07. Records the incident id the support surface shows. */
onUnrecovered?: (incidentId: string) => void;
}>;
type State = Readonly<{
error: unknown | null;
recovery: "idle" | "checking" | "reload-requested" | "support";
reason?: string;
incidentId?: string;
}>;
export function isChunkLoadFailure(error: unknown): boolean {
@@ -31,7 +38,11 @@ export function isChunkLoadFailure(error: unknown): boolean {
value.includes("chunkloaderror") ||
value.includes("loading chunk") ||
value.includes("dynamically imported module") ||
value.includes("failed to fetch module script")
value.includes("failed to fetch module script") ||
// WebKit's wording for the same failed dynamic import.
value.includes("importing a module script failed") ||
// Vite rethrows a `vite:preloadError` into the import unless prevented.
value.includes("unable to preload css")
);
}
@@ -50,26 +61,29 @@ export class ChunkRecoveryBoundary extends Component<Props, State> {
failureKind: "CHUNK_LOAD_FAILURE",
})
.then((result) => {
this.setState({
error,
recovery:
result.action === "reload-once"
? "reload-requested"
: "support",
...(result.action === "support" ? { reason: result.reason } : {}),
});
if (result.action === "support") {
this.showSupport(error, result.reason);
} else {
this.setState({ error, recovery: "reload-requested" });
}
})
.catch(() => {
this.setState({
error,
recovery: "support",
reason: "recovery-controller-failed",
});
this.showSupport(error, "recovery-controller-failed");
});
}
private showSupport(error: unknown, reason: string) {
const incidentId = newIncidentId();
this.setState({ error, recovery: "support", reason, incidentId });
try {
this.props.onUnrecovered?.(incidentId);
} catch {
// Diagnostics must never hide the recovery surface.
}
}
render() {
const { error, recovery, reason } = this.state;
const { error, recovery, reason, incidentId } = this.state;
if (error && !isChunkLoadFailure(error)) throw error;
if (error && recovery === "checking") {
return <ChunkRecoverySurface recovery="checking" />;
@@ -78,7 +92,15 @@ export class ChunkRecoveryBoundary extends Component<Props, State> {
return <ChunkRecoverySurface recovery="reload-requested" />;
}
if (error && recovery === "support") {
return <ChunkRecoverySurface recovery="support" reason={reason} />;
return (
<ChunkRecoverySurface
recovery="support"
reason={reason}
supportReference={[this.props.buildId, incidentId]
.filter(Boolean)
.join(":")}
/>
);
}
return this.props.children;
}
@@ -87,16 +109,18 @@ export class ChunkRecoveryBoundary extends Component<Props, State> {
function ChunkRecoverySurface({
recovery,
reason,
supportReference,
}: Readonly<{
recovery: Exclude<State["recovery"], "idle">;
reason?: string;
supportReference?: string;
}>) {
const { message } = useLocale();
if (recovery === "checking") {
return (
<section className="ui-page" aria-live="polite" aria-busy="true">
{message("chunk.checking")}
</section>
<div className="ui-page">
<LoadingSurface description={message("chunk.checking")} />
</div>
);
}
if (recovery === "reload-requested") {
@@ -110,6 +134,17 @@ function ChunkRecoverySurface({
<section className="ui-page" role="alert" data-recovery-reason={reason}>
<h1>{message("chunk.failure.title")}</h1>
<p>{message("chunk.failure.description")}</p>
{/* The automatic reload-once already declined; this one is the user's. */}
<Button onClick={() => window.location.reload()}>
{message("action.reloadOnce")}
</Button>
{supportReference ? (
<p>
{message("template.supportReference", {
reference: supportReference,
})}
</p>
) : null}
</section>
);
}
@@ -1,7 +1,7 @@
import { Component, type ReactNode } from "react";
import type { RenderFailureReport } from "../../application/ports/in/application-api.ts";
import { formatMessage } from "../i18n/index.ts";
import { useLocale } from "../i18n/index.ts";
export type RenderBoundaryProps = Readonly<{
children: ReactNode;
@@ -10,10 +10,24 @@ export type RenderBoundaryProps = Readonly<{
buildId: string;
resetKey?: string;
onRenderFailure?: (report: RenderFailureReport) => void;
fallback?: ReactNode;
/** A function receives the incident id the failure was reported with. */
fallback?: ReactNode | ((incidentId: string) => ReactNode);
}>;
type RenderBoundaryState = Readonly<{ hasError: boolean }>;
type RenderBoundaryState = Readonly<{
hasError: boolean;
incidentId?: string;
}>;
/**
* 08-07. A short id a failure page shows as its support reference and the
* render diagnostic records, so a user's report finds the event.
* `getRandomValues` also works outside secure contexts, unlike `randomUUID`.
*/
export function newIncidentId(): string {
const [value = 0] = crypto.getRandomValues(new Uint32Array(1));
return value.toString(16).padStart(8, "0");
}
export class RenderErrorBoundary extends Component<
RenderBoundaryProps,
@@ -22,7 +36,7 @@ export class RenderErrorBoundary extends Component<
state: RenderBoundaryState = { hasError: false };
static getDerivedStateFromError(): RenderBoundaryState {
return { hasError: true };
return { hasError: true, incidentId: newIncidentId() };
}
componentDidCatch(): void {
@@ -31,6 +45,9 @@ export class RenderErrorBoundary extends Component<
routeId: this.props.routeId,
buildId: this.props.buildId,
boundaryName: this.props.boundaryName,
...(this.state.incidentId === undefined
? {}
: { incidentId: this.state.incidentId }),
});
} catch {
// Diagnostics must never recurse into another render failure.
@@ -49,21 +66,29 @@ export class RenderErrorBoundary extends Component<
render(): ReactNode {
if (this.state.hasError) {
return (
this.props.fallback ?? (
<section role="alert">
<p>{formatMessage("ko-KR", "error.render_failure")}</p>
<button type="button" onClick={this.reset}>
{formatMessage("ko-KR", "action.retry")}
</button>
</section>
)
);
const { fallback } = this.props;
if (typeof fallback === "function") {
return fallback(this.state.incidentId ?? newIncidentId());
}
return fallback ?? <DefaultRenderFailure onRetry={this.reset} />;
}
return this.props.children;
}
}
/** The default fallback, in the current locale. */
function DefaultRenderFailure({ onRetry }: Readonly<{ onRetry(): void }>) {
const { message } = useLocale();
return (
<section role="alert">
<p>{message("error.render_failure")}</p>
<button type="button" onClick={onRetry}>
{message("action.retry")}
</button>
</section>
);
}
export function RouteBoundary(
props: Omit<RenderBoundaryProps, "boundaryName">,
) {
+78 -18
View File
@@ -4,11 +4,20 @@ 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,
NotFoundSurface,
} from "./state-surfaces.tsx";
import { Button } from "./ui/button.ts";
export function LoadingSurface({ label }: Readonly<{ label?: string }>) {
export function LoadingSurface({
label,
description,
}: Readonly<{ label?: string; description?: string }>) {
const { message } = useLocale();
const accessibleLabel = label ?? message("async.loading");
// 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"
@@ -18,7 +27,10 @@ export function LoadingSurface({ label }: Readonly<{ label?: string }>) {
aria-atomic="true"
>
<div className="ui-skeleton" aria-hidden="true" />
<span className="visually-hidden">{accessibleLabel}</span>
{description ? <p>{description}</p> : null}
{accessibleLabel === description ? null : (
<span className="visually-hidden">{accessibleLabel}</span>
)}
</section>
);
}
@@ -48,12 +60,18 @@ 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;
}>;
export function TerminalErrorSurface({
userMessageKey,
action,
onAction,
description,
supportReference,
}: TerminalErrorSurfaceProps) {
const { locale, message } = useLocale();
const messageId = useId();
@@ -74,9 +92,17 @@ export function TerminalErrorSurface({
data-message-key={userMessageKey}
>
<h2 id={messageId}>{errorMessage(userMessageKey, locale)}</h2>
{description ? <p>{description}</p> : null}
{action !== "none" && onAction && (
<Button onClick={onAction}>{actionLabels[action]}</Button>
)}
{supportReference ? (
<p>
{message("template.supportReference", {
reference: supportReference,
})}
</p>
) : null}
</section>
);
}
@@ -84,26 +110,49 @@ export function TerminalErrorSurface({
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;
onReconcileUnknownEffect?: (
resolution: "APPLIED" | "NOT_APPLIED",
) => 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. */
onResendUnknownEffect?: () => void;
}>;
export function AsyncSurface({
state,
children,
idle,
onAction,
onRetry,
onResolveConflict,
onReconcileUnknownEffect,
onResendUnknownEffect,
}: AsyncSurfaceProps) {
const { message } = useLocale();
if (state.base === "idle") return idle ?? null;
if (state.base === "initial-loading") return <LoadingSurface />;
if (state.base === "empty") return <EmptySurface />;
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} />
{state.failure.requestId ? (
<p>
{message("template.supportReference", {
reference: state.failure.requestId,
})}
</p>
) : null}
</div>
);
}
return (
<TerminalErrorSurface
userMessageKey={state.failure.userMessageKey}
@@ -113,6 +162,7 @@ export function AsyncSurface({
? onRetry ?? onAction
: onAction
}
supportReference={state.failure.requestId}
/>
);
}
@@ -144,18 +194,15 @@ export function AsyncSurface({
) : null}
{state.indicator === "mutation-effect-unknown" &&
onReconcileUnknownEffect ? (
<>
<Button
onClick={() => onReconcileUnknownEffect("APPLIED")}
>
{message("action.confirmMutationApplied")}
</Button>
<Button
onClick={() => onReconcileUnknownEffect("NOT_APPLIED")}
>
{message("action.confirmMutationNotApplied")}
</Button>
</>
<Button onClick={() => onReconcileUnknownEffect("APPLIED")}>
{message("action.confirmMutationApplied")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" &&
onResendUnknownEffect ? (
<Button onClick={onResendUnknownEffect}>
{message("action.resendMutation")}
</Button>
) : null}
</div>
) : null}
@@ -163,3 +210,16 @@ export function AsyncSurface({
</section>
);
}
const ACCESS_SURFACES: Readonly<
Partial<
Record<
AppFailure["kind"],
(props: Readonly<{ onAction?: () => void }>) => ReactNode
>
>
> = Object.freeze({
AUTH_REQUIRED: ({ onAction }) => <AuthRequiredSurface onSignIn={onAction} />,
FORBIDDEN: ({ onAction }) => <ForbiddenSurface onNavigate={onAction} />,
NOT_FOUND: ({ onAction }) => <NotFoundSurface onNavigate={onAction} />,
});
+18 -3
View File
@@ -6,6 +6,15 @@ export type PageHeaderProps = Readonly<{
eyebrow?: string;
}>;
function hashTarget(): HTMLElement | null {
try {
const id = decodeURIComponent(window.location.hash.slice(1));
return id ? document.getElementById(id) : null;
} catch {
return null;
}
}
export function PageHeader({
title,
description,
@@ -21,9 +30,15 @@ export function PageHeader({
activeElement === document.body ||
activeElement === document.documentElement ||
activeElement === main;
if (routeOwnsFocus) {
headingRef.current?.focus();
}
if (!routeOwnsFocus) return;
// 08-08. A hash names a target in this page, which exists only once the
// page has rendered. Focus never scrolls: back navigation keeps the
// position the browser restored.
const target = hashTarget();
target?.scrollIntoView?.();
(target && target.tabIndex >= 0 ? target : headingRef.current)?.focus({
preventScroll: true,
});
}, [title]);
return (
@@ -23,7 +23,9 @@ function StateSurface({
<p className="state-surface__eyebrow">{eyebrow}</p>
<h2>{title}</h2>
<p>{description}</p>
{actionLabel ? <Button onClick={onAction}>{actionLabel}</Button> : null}
{actionLabel && onAction ? (
<Button onClick={onAction}>{actionLabel}</Button>
) : null}
</section>
);
}
+2
View File
@@ -23,6 +23,7 @@ export type {
DialogProps,
IconButtonProps,
LinkButtonProps,
LinkTarget,
SpinnerProps,
TextFieldProps,
} from "./primitives/core.tsx";
@@ -138,6 +139,7 @@ export {
ErrorSummary,
Form,
FormActions,
FormFailureStatus,
FormField,
useAppForm,
useDirtyNavigationGuard,
@@ -6,6 +6,7 @@ import {
useRef,
} from "react";
import { createPortal } from "react-dom";
import { Link, type To } from "react-router-dom";
import { CloseIcon } from "../icons/semantic-icons.tsx";
import { useLocale } from "../../i18n/index.ts";
@@ -73,9 +74,21 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
},
);
export type LinkButtonProps = React.AnchorHTMLAttributes<HTMLAnchorElement> &
/**
* Where a link goes. `to` is an in-app destination rendered as a router link,
* so it keeps the router basename and navigates without a document reload.
* `href` stays a plain anchor for external or document-level targets.
*/
export type LinkTarget =
| Readonly<{ href: string; to?: undefined }>
| Readonly<{ to: To; href?: undefined }>;
export type LinkButtonProps = Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
"href"
> &
LinkTarget &
Readonly<{
href: string;
variant?: ButtonVariant;
size?: ButtonSize;
}>;
@@ -84,6 +97,7 @@ export const LinkButton = forwardRef<HTMLAnchorElement, LinkButtonProps>(
function LinkButton(
{
href,
to,
variant = "primary",
size = "default",
className = "",
@@ -91,20 +105,18 @@ export const LinkButton = forwardRef<HTMLAnchorElement, LinkButtonProps>(
},
ref,
) {
return (
<a
{...props}
className={[
"ui-button",
`ui-button--${variant}`,
size === "compact" ? "ui-button--compact" : "",
className,
]
.filter(Boolean)
.join(" ")}
href={href}
ref={ref}
/>
const classes = [
"ui-button",
`ui-button--${variant}`,
size === "compact" ? "ui-button--compact" : "",
className,
]
.filter(Boolean)
.join(" ");
return to === undefined ? (
<a {...props} className={classes} href={href} ref={ref} />
) : (
<Link {...props} className={classes} ref={ref} to={to} />
);
},
);
@@ -390,9 +402,16 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
}
const previousFocus = previousFocusRef.current;
previousFocusRef.current = null;
// Restore only focus the dialog still owns. If something else (a route
// change) already placed focus outside it, do not steal it. The restore
// stays synchronous, as this product's dialogs expect.
const active = document.activeElement;
const focusIsUnclaimed =
active === null || active === document.body || dialog.contains(active);
if (
focusRestoreGenerationRef.current === generation &&
previousFocus?.isConnected
previousFocus?.isConnected &&
focusIsUnclaimed
) {
previousFocus.focus();
}
@@ -2,6 +2,7 @@ import {
forwardRef,
useEffect,
useId,
useImperativeHandle,
useRef,
useState,
} from "react";
@@ -409,6 +410,8 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(
},
ref,
) {
const inputRef = useRef<HTMLInputElement | null>(null);
useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);
return (
<div className={`ui-search-field ${className}`.trim()}>
<SearchIcon />
@@ -426,7 +429,7 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(
aria-invalid={invalid || undefined}
className="ui-field__input"
id={controlId}
ref={ref}
ref={inputRef}
type="search"
value={value}
/>
@@ -435,7 +438,12 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(
{String(value ?? "").length > 0 ? (
<IconButton
accessibleName={clearLabel}
onClick={onClear}
onClick={() => {
onClear();
// The button unmounts once the value is empty; keep focus in
// the field instead of dropping it to the body.
inputRef.current?.focus();
}}
variant="ghost"
>
<CloseIcon />
@@ -1,12 +1,20 @@
import { useId, useRef, useState } from "react";
import { createContext, useContext, useId, useRef, useState } from "react";
import {
Link,
useInRouterContext,
useLocation,
type To,
} from "react-router-dom";
import { useLocale } from "../../i18n/index.ts";
import { NextIcon, PreviousIcon } from "../icons/semantic-icons.tsx";
import { Button, IconButton, LinkButton } from "./core.tsx";
import { Button, IconButton, LinkButton, type LinkTarget } from "./core.tsx";
export type BreadcrumbItem = Readonly<{
label: string;
href?: string;
/** In-app destination, rendered as a router link. Wins over `href`. */
to?: To;
}>;
export function Breadcrumbs({
@@ -20,7 +28,9 @@ export function Breadcrumbs({
const current = index === items.length - 1;
return (
<li key={`${item.label}-${index}`}>
{item.href && !current ? (
{item.to !== undefined && !current ? (
<Link to={item.to}>{item.label}</Link>
) : item.href && !current ? (
<a href={item.href}>{item.label}</a>
) : (
<span aria-current={current ? "page" : undefined}>
@@ -140,73 +150,58 @@ export function Tabs({
);
}
type PaginationEntry = number | "gap";
function paginationEntries(
current: number,
total: number,
around: number,
): readonly PaginationEntry[] {
if (total <= 0) return [];
if (total <= around * 2 + 5) {
return Array.from({ length: total }, (_, index) => index + 1);
}
const shown = new Set<number>([1, total]);
for (
let candidate = current - around;
candidate <= current + around;
candidate += 1
) {
if (candidate >= 1 && candidate <= total) shown.add(candidate);
}
const sorted = [...shown].sort((left, right) => left - right);
const entries: PaginationEntry[] = [];
let previous = 0;
for (const candidate of sorted) {
if (previous && candidate - previous > 1) entries.push("gap");
entries.push(candidate);
previous = candidate;
}
return entries;
}
export function Pagination({
label,
page,
pageCount,
previousLabel,
nextLabel,
pageLabel,
pageAccessibleLabel,
pageControl = "link",
onChange,
className = "",
around = 2,
}: Readonly<{
type PaginationProps = Readonly<{
label: string;
page: number;
pageCount: number;
previousLabel: string;
nextLabel: string;
pageLabel(page: number): string;
/** Accessible name of each page control, when the visible label is terse. */
pageAccessibleLabel?: (page: number) => string;
/**
* `button` renders page controls as buttons, for a list whose page is not
* part of the URL. The default renders links that keep the other search
* parameters.
*/
pageControl?: "link" | "button";
onChange(page: number): void;
className?: string;
/** Pages shown on each side of the current one. */
around?: number;
}>) {
const pages = paginationEntries(page, pageCount, around);
}>;
/**
* Set by a container that already is the pagination navigation landmark
* (CollectionPage), so Pagination renders a labelled group instead of a
* nested `nav`.
*/
export const PaginationLandmarkContext = createContext(false);
export function Pagination(props: PaginationProps) {
const {
label,
page,
pageCount,
previousLabel,
nextLabel,
onChange,
pageControl = "link",
className = "",
} = props;
const inRouter = useInRouterContext();
const nested = useContext(PaginationLandmarkContext);
const Container = nested ? "div" : "nav";
const { direction } = useLocale();
const PreviousDirectionalIcon =
direction === "rtl" ? NextIcon : PreviousIcon;
const NextDirectionalIcon = direction === "rtl" ? PreviousIcon : NextIcon;
return (
<nav
<Container
aria-label={label}
className={"ui-pagination " + className}
className={className ? `ui-pagination ${className}` : "ui-pagination"}
role={nested ? "group" : undefined}
>
<IconButton
accessibleName={previousLabel}
@@ -216,39 +211,18 @@ export function Pagination({
>
<PreviousDirectionalIcon />
</IconButton>
<ol className="ui-pagination__pages">
{pages.map((candidate, index) => (
<li key={candidate === "gap" ? "gap-" + index : candidate}>
{candidate === "gap" ? (
<span aria-hidden="true" className="ui-pagination__gap">
…
</span>
) : pageControl === "button" ? (
<Button
aria-current={candidate === page ? "page" : undefined}
aria-label={pageAccessibleLabel?.(candidate)}
onClick={() => onChange(candidate)}
variant={candidate === page ? "primary" : "ghost"}
>
{pageLabel(candidate)}
</Button>
) : (
<LinkButton
aria-current={candidate === page ? "page" : undefined}
aria-label={pageAccessibleLabel?.(candidate)}
href={"?page=" + candidate}
onClick={(event) => {
event.preventDefault();
onChange(candidate);
}}
variant={candidate === page ? "primary" : "ghost"}
>
{pageLabel(candidate)}
</LinkButton>
)}
</li>
))}
</ol>
{pageControl === "button" ? (
<PageButtons {...props} />
) : inRouter ? (
<RouterPageLinks {...props} />
) : (
<PageLinks
{...props}
target={(candidate) => ({
href: withPage(globalThis.location?.search ?? "", candidate),
})}
/>
)}
<IconButton
accessibleName={nextLabel}
disabled={page >= pageCount}
@@ -257,6 +231,150 @@ export function Pagination({
>
<NextDirectionalIcon />
</IconButton>
</nav>
</Container>
);
}
/**
* The first and last page, the current page and `around` neighbours on each
* side. A gap of one page shows that page instead of an ellipsis.
*/
function visiblePages(
page: number,
pageCount: number,
around = 1,
): Array<number | "gap"> {
const neighbours = Array.from(
{ length: around * 2 + 1 },
(_, index) => page - around + index,
);
const wanted = [...new Set([1, ...neighbours, pageCount])]
.filter((candidate) => candidate >= 1 && candidate <= pageCount)
.sort((left, right) => left - right);
const visible: Array<number | "gap"> = [];
let previous = 0;
for (const candidate of wanted) {
if (candidate - previous === 2) visible.push(candidate - 1);
else if (candidate - previous > 2) visible.push("gap");
visible.push(candidate);
previous = candidate;
}
return visible;
}
/** Keeps every other search parameter and only replaces `page`. */
function withPage(search: string, page: number): string {
const params = new URLSearchParams(search);
params.set("page", String(page));
return `?${params}`;
}
function RouterPageLinks(props: PaginationProps) {
const { search } = useLocation();
return (
<PageLinks
{...props}
target={(candidate) => ({ to: { search: withPage(search, candidate) } })}
/>
);
}
/** The page list: numbered entries, and a hidden-from-AT gap marker. */
function PageList({
page,
pageCount,
around,
render,
}: Readonly<{
page: number;
pageCount: number;
around?: number;
render(candidate: number): React.ReactNode;
}>) {
return (
<ol className="ui-pagination__pages">
{visiblePages(page, pageCount, around).map((candidate, index) => (
<li key={candidate === "gap" ? `gap-${index}` : candidate}>
{candidate === "gap" ? (
<span aria-hidden="true" className="ui-pagination__gap">
…
</span>
) : (
render(candidate)
)}
</li>
))}
</ol>
);
}
function PageButtons({
page,
pageCount,
around,
pageLabel,
pageAccessibleLabel,
onChange,
}: PaginationProps) {
return (
<PageList
page={page}
pageCount={pageCount}
render={(candidate) => (
<Button
aria-current={candidate === page ? "page" : undefined}
aria-label={pageAccessibleLabel?.(candidate)}
onClick={() => onChange(candidate)}
variant={candidate === page ? "primary" : "ghost"}
>
{pageLabel(candidate)}
</Button>
)}
{...(around === undefined ? {} : { around })}
/>
);
}
function PageLinks({
page,
pageCount,
around,
pageLabel,
pageAccessibleLabel,
onChange,
target,
}: PaginationProps & Readonly<{ target(page: number): LinkTarget }>) {
return (
<PageList
page={page}
pageCount={pageCount}
render={(candidate) => (
<LinkButton
{...target(candidate)}
aria-current={candidate === page ? "page" : undefined}
aria-label={pageAccessibleLabel?.(candidate)}
onClick={(event) => {
// The owner decides how a page change is applied; the href is for
// open-in-new-tab and copy-link, so a modified or non-primary
// click stays with the browser (08-12).
if (
event.button !== 0 ||
event.metaKey ||
event.altKey ||
event.ctrlKey ||
event.shiftKey
) {
return;
}
event.preventDefault();
onChange(candidate);
}}
variant={candidate === page ? "primary" : "ghost"}
>
{pageLabel(candidate)}
</LinkButton>
)}
{...(around === undefined ? {} : { around })}
/>
);
}
@@ -1,4 +1,5 @@
import {
cloneElement,
createContext,
useCallback,
useContext,
@@ -104,17 +105,42 @@ export function Popover({ triggerLabel, children }: PopoverProps) {
export type TooltipProps = Readonly<{
content: string;
children: React.ReactElement;
children: React.ReactElement<{ "aria-describedby"?: string | undefined }>;
}>;
/**
* Describes its focusable child (WCAG 1.4.13): the child carries
* `aria-describedby`, and Escape hides the tooltip until the next hover or
* focus.
*/
export function Tooltip({ content, children }: TooltipProps) {
const tooltipId = useId();
const [dismissed, setDismissed] = useState(false);
useEffect(() => {
if (dismissed) return;
// Document level: a hovered trigger does not have keyboard focus.
function dismissOnEscape(event: KeyboardEvent) {
if (event.key === "Escape") setDismissed(true);
}
document.addEventListener("keydown", dismissOnEscape);
return () => document.removeEventListener("keydown", dismissOnEscape);
}, [dismissed]);
const describedBy = [children.props["aria-describedby"], tooltipId]
.filter(Boolean)
.join(" ");
return (
<span className="ui-tooltip">
<span aria-describedby={tooltipId} className="ui-tooltip__trigger">
{children}
</span>
<span className="ui-tooltip__content" id={tooltipId} role="tooltip">
<span
className="ui-tooltip"
onFocus={() => setDismissed(false)}
onMouseEnter={() => setDismissed(false)}
>
{cloneElement(children, { "aria-describedby": describedBy })}
<span
className="ui-tooltip__content"
hidden={dismissed}
id={tooltipId}
role="tooltip"
>
{content}
</span>
</span>
@@ -1,5 +1,7 @@
import { useId, type FormHTMLAttributes, type ReactNode } from "react";
import type { AppFailure } from "../../contracts/errors.ts";
import { TerminalErrorSurface } from "../components/async-surface.tsx";
import { TextField } from "../components/ui/text-field.ts";
import { useLocale } from "../i18n/index.ts";
import type {
@@ -78,6 +80,33 @@ export function ErrorSummary<Values extends FormValues>(props: Readonly<{
);
}
/**
* 08-01. A save that failed for a reason other than the input (sign-in,
* permission, retry later, unavailable) is announced here with its own action, not in
* ErrorSummary. Pass `useAppForm().failure`.
*/
export function FormFailureStatus(props: Readonly<{
failure: AppFailure | null;
onAction?: () => void;
}>) {
const { message } = useLocale();
const { failure, onAction } = props;
if (!failure) return null;
return (
<TerminalErrorSurface
userMessageKey={failure.userMessageKey}
action={failure.action}
onAction={onAction}
// Signing in remounts the scope, so the entered values do not survive.
description={
failure.action === "reauth"
? message("form.reauthLosesInput")
: undefined
}
/>
);
}
export function FormActions(props: Readonly<{
children: ReactNode;
sticky?: boolean;
+4
View File
@@ -19,6 +19,10 @@ export type FormResultState =
| "validation-error"
| "conflict"
| "effect-unknown"
/** 08-01. Not input errors: shown by `FormFailureStatus`, never ErrorSummary. */
| "reauth-required"
| "forbidden"
| "retry-later"
| "unavailable";
export type MappedValidationFailure<Values extends FormValues> = Readonly<{
+164 -60
View File
@@ -7,7 +7,9 @@ import {
type ChangeEvent,
type FormEvent,
} from "react";
import type { ZodType, ZodIssue } from "zod";
import { flushSync } from "react-dom";
import type { ZodIssue, ZodType } from "../../contracts/zod.ts";
import type { AppFailure } from "../../contracts/errors.ts";
import {
useLocale,
type ParameterlessMessageKey,
@@ -41,7 +43,7 @@ export function useAppForm<
Command,
Output,
>(options: AppFormOptions<Values, Command, Output>) {
const { message } = useLocale();
const { resolve } = useLocale();
const {
schema,
defaultValues,
@@ -57,13 +59,32 @@ export function useAppForm<
const [touched, setTouched] = useState<ReadonlySet<FieldName<Values>>>(
() => new Set(),
);
const [fieldErrors, setFieldErrors] = useState<FieldErrors<Values>>(
// 08-10. Errors are held as message keys and translated on render, so a
// locale change re-translates the ones already on screen.
const [fieldErrorKeys, setFieldErrors] = useState<FieldErrors<Values>>(
() => ({} as FieldErrors<Values>),
);
const [formErrors, setFormErrors] = useState<readonly string[]>([]);
const [formErrorKeys, setFormErrors] = useState<readonly string[]>([]);
const fieldErrors = useMemo(
() =>
Object.freeze(
Object.fromEntries(
Object.entries(fieldErrorKeys).map(([name, key]) => [
name,
resolve(String(key)),
]),
),
) as FieldErrors<Values>,
[fieldErrorKeys, resolve],
);
const formErrors = useMemo(
() => formErrorKeys.map((key) => resolve(key)),
[formErrorKeys, resolve],
);
const [pending, setPending] = useState(false);
const [result, setResult] = useState<FormResultState>("idle");
const pendingRef = useRef<Promise<FormResult<Output>> | null>(null);
const [statusFailure, setStatusFailure] = useState<AppFailure | null>(null);
const pendingRef = useRef<Promise<FormResult<Output> | null> | null>(null);
const unknownSubmissionRef = useRef<Values | null>(null);
const dirty = useMemo(
@@ -142,16 +163,20 @@ export function useAppForm<
const settleSuccessfulValues = useCallback(
(settledValues: Values) => {
unknownSubmissionRef.current = null;
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setResult("success");
if (resetOnSuccess) {
setValues(defaultValues);
setInitialValues(defaultValues);
setTouched(new Set());
} else {
setInitialValues(settledValues);
}
// Committed before the caller continues: a `navigate()` right after a
// save must meet a clean form, not the dirty guard of the last render.
flushSync(() => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setResult("success");
if (resetOnSuccess) {
setValues(defaultValues);
setInitialValues(defaultValues);
setTouched(new Set());
} else {
setInitialValues(settledValues);
}
});
},
[defaultValues, resetOnSuccess],
);
@@ -170,11 +195,62 @@ export function useAppForm<
setResult("idle");
}, []);
const submitForm = useCallback(
async (event?: FormEvent<HTMLFormElement>): Promise<FormResult<Output> | null> => {
event?.preventDefault();
if (pendingRef.current) return pendingRef.current;
if (unknownSubmissionRef.current) return null;
const applyOutcome = useCallback(
(outcome: FormResult<Output>, submittedValues: Values) => {
if (outcome.ok) {
settleSuccessfulValues(submittedValues);
return;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
unknownSubmissionRef.current = null;
const mapped = mapValidationFailureToFields<Values>(
outcome.error,
allowedServerFields,
messageKey,
);
setFieldErrors(mapped.fieldErrors);
setFormErrors(mapped.formErrors);
setResult("validation-error");
focusFirstError(mapped.fieldErrors);
} else if (outcome.error.action === "reauth") {
// D-2. Signing in again comes first, whatever the effect.
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
setResult("reauth-required");
} else if (outcome.error.effect === "MAYBE_APPLIED") {
unknownSubmissionRef.current = submittedValues;
setFormErrors([]);
setResult("effect-unknown");
} else if (outcome.error.effect === "APPLIED_CONFIRMED") {
settleSuccessfulValues(submittedValues);
} else if (outcome.error.kind === "CONFLICT") {
unknownSubmissionRef.current = null;
setFormErrors(["form.conflict"]);
setResult("conflict");
} else if (
outcome.error.kind === "FORBIDDEN" ||
outcome.error.action === "retry"
) {
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
setResult(
outcome.error.kind === "FORBIDDEN" ? "forbidden" : "retry-later",
);
} else {
// F-10. Not an input error either: shown by FormFailureStatus.
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
setResult("unavailable");
}
},
[allowedServerFields, focusFirstError, settleSuccessfulValues],
);
const validateAndSubmit = useCallback(
async (): Promise<FormResult<Output> | null> => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
@@ -183,14 +259,14 @@ export function useAppForm<
const errors = issuesToFieldErrors<Values>(
parsed.error.issues,
allowedServerFields,
message,
messageKey,
);
setFieldErrors(errors);
setFormErrors(
parsed.error.issues.some(
(issue) => !allowedServerFields.includes(issue.path[0] as FieldName<Values>),
)
? [message("form.validation.configuration")]
? ["form.validation.configuration"]
: [],
);
setTouched(new Set(allowedServerFields));
@@ -201,60 +277,72 @@ export function useAppForm<
const command = mapToCommand(parsed.data);
setPending(true);
const execution = submit(command);
pendingRef.current = execution;
try {
const outcome = await execution;
if (outcome.ok) {
settleSuccessfulValues(parsed.data);
return outcome;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
unknownSubmissionRef.current = null;
const mapped = mapValidationFailureToFields<Values>(
outcome.error,
allowedServerFields,
message,
);
setFieldErrors(mapped.fieldErrors);
setFormErrors(mapped.formErrors);
setResult("validation-error");
focusFirstError(mapped.fieldErrors);
} else if (outcome.error.effect === "MAYBE_APPLIED") {
unknownSubmissionRef.current = parsed.data;
setFormErrors([]);
setResult("effect-unknown");
} else if (outcome.error.effect === "APPLIED_CONFIRMED") {
settleSuccessfulValues(parsed.data);
} else if (outcome.error.kind === "CONFLICT") {
unknownSubmissionRef.current = null;
setFormErrors([
message("form.conflict"),
]);
setResult("conflict");
} else {
unknownSubmissionRef.current = null;
setFormErrors([message("form.unavailable")]);
setResult("unavailable");
}
const outcome = await submit(command);
applyOutcome(outcome, parsed.data);
return outcome;
} finally {
pendingRef.current = null;
setPending(false);
}
},
[
allowedServerFields,
applyOutcome,
focusFirstError,
mapToCommand,
message,
schema,
settleSuccessfulValues,
submit,
values,
],
);
const submitForm = useCallback(
(event?: FormEvent<HTMLFormElement>): Promise<FormResult<Output> | null> => {
event?.preventDefault();
// One submission from validation to outcome: an async refine must not
// let a second submit through before the command starts.
if (pendingRef.current) return pendingRef.current;
if (unknownSubmissionRef.current) return Promise.resolve(null);
const submission = validateAndSubmit().finally(() => {
pendingRef.current = null;
});
pendingRef.current = submission;
return submission;
},
[validateAndSubmit],
);
/**
* D-1. Runs a resend of the unknown submission (for example
* `mutation.resendUnknownEffect`) through the same outcome handling as a
* submit. The form never builds a new command here: the caller resends the
* original request with its original key.
*/
const resendUnknown = useCallback(
(
send: () => Promise<FormResult<Output> | null>,
): Promise<FormResult<Output> | null> => {
if (pendingRef.current) return pendingRef.current;
// After a remount the form no longer holds the submitted values.
const submittedValues = unknownSubmissionRef.current ?? values;
const resend = (async () => {
setPending(true);
try {
const outcome = await send();
if (outcome) applyOutcome(outcome, submittedValues);
return outcome;
} finally {
setPending(false);
}
})().finally(() => {
pendingRef.current = null;
});
pendingRef.current = resend;
return resend;
},
[applyOutcome, values],
);
return Object.freeze({
formId,
values,
@@ -264,17 +352,33 @@ export function useAppForm<
formErrors,
pending,
result,
/**
* The save failure behind `reauth-required`, `forbidden`, `retry-later`
* or `unavailable`.
*/
failure: STATUS_RESULTS.has(result) ? statusFailure : null,
field,
fieldId,
focusField,
setValue,
submitForm,
resendUnknown,
reset,
settleApplied,
settleNotApplied,
});
}
/** Keeps the key: the form translates at render time. */
const messageKey = (key: ParameterlessMessageKey): string => key;
const STATUS_RESULTS: ReadonlySet<FormResultState> = new Set([
"reauth-required",
"forbidden",
"retry-later",
"unavailable",
]);
function issuesToFieldErrors<Values extends FormValues>(
issues: readonly ZodIssue[],
allowedFields: readonly FieldName<Values>[],
+34
View File
@@ -0,0 +1,34 @@
/**
* 09-03. The boot failure shell's words. They live apart from `catalog.ts`
* because the catalog merges every installed feature's messages: when that
* feature graph throws while it evaluates, the shell reporting it must still
* load. `catalog.ts` spreads these in, so they stay ordinary message keys.
*/
export const BOOT_MESSAGES = Object.freeze({
"ko-KR": Object.freeze({
"boot.failure.title": "애플리케이션을 시작할 수 없습니다.",
"boot.field.error": "오류",
"boot.field.code": "코드",
"boot.field.build": "빌드",
"boot.field.configSchema": "설정 스키마",
"boot.field.release": "릴리스",
"boot.field.invalidKeys": "잘못된 설정 키",
"boot.retry.hint": "네트워크 연결을 확인한 뒤 다시 시도해 주세요.",
"boot.retry.action": "다시 시도",
"boot.supportReference": "지원 참조: {reference}",
} as const),
"en-US": Object.freeze({
"boot.failure.title": "The application could not start.",
"boot.field.error": "Error",
"boot.field.code": "Code",
"boot.field.build": "Build",
"boot.field.configSchema": "Configuration schema",
"boot.field.release": "Release",
"boot.field.invalidKeys": "Invalid configuration keys",
"boot.retry.hint": "Check the network connection and try again.",
"boot.retry.action": "Try again",
"boot.supportReference": "Support reference: {reference}",
} as const),
});
export type BootMessageKey = keyof (typeof BOOT_MESSAGES)["ko-KR"];
+9 -18
View File
@@ -1,4 +1,5 @@
import { INSTALLED_MESSAGE_CATALOGS } from "../../features/installed-feature-messages.ts";
import { BOOT_MESSAGES } from "./boot-messages.ts";
const PLATFORM_KO_MESSAGES = {
"common.unavailable": "요청한 문구를 표시할 수 없습니다.",
@@ -12,7 +13,7 @@ const PLATFORM_KO_MESSAGES = {
"action.contactSupport": "지원 정보 확인",
"action.resolveConflict": "충돌 해결",
"action.confirmMutationApplied": "변경됨으로 확인",
"action.confirmMutationNotApplied": "변경되지 않음으로 확인",
"action.resendMutation": "같은 요청으로 다시 보내기",
"action.continueEditing": "계속 작성",
"action.discardAndLeave": "변경 버리고 이동",
"action.signIn": "로그인 시작",
@@ -132,7 +133,8 @@ const PLATFORM_KO_MESSAGES = {
"form.validation.configuration": "입력 구성을 다시 확인해 주세요.",
"form.conflict":
"다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.",
"form.unavailable": "저장하지 못했습니다. 잠시 후 다시 시도해 주세요.",
"form.reauthLosesInput":
"다시 로그인하면 이 화면에 입력한 내용은 사라집니다. 필요하면 먼저 복사해 두세요.",
"form.remaining": "{count}자 남음",
"toast.region": "알림",
"error.network_unreachable": "네트워크에 연결할 수 없습니다.",
@@ -177,13 +179,7 @@ const PLATFORM_KO_MESSAGES = {
"error.storage_quota_exceeded": "브라우저 저장 공간이 부족합니다.",
"error.telemetry_failure": "사용 기록을 전송하지 못했습니다.",
"error.query_cache_failure": "화면 데이터를 갱신하지 못했습니다.",
"boot.failure.title": "애플리케이션을 시작할 수 없습니다.",
"boot.field.error": "오류",
"boot.field.code": "코드",
"boot.field.build": "빌드",
"boot.field.configSchema": "설정 스키마",
"boot.field.release": "릴리스",
"boot.supportReference": "지원 참조: {reference}",
...BOOT_MESSAGES["ko-KR"],
} as const;
export const KO_MESSAGES = {
@@ -205,7 +201,7 @@ const PLATFORM_EN_MESSAGES = {
"action.contactSupport": "View support information",
"action.resolveConflict": "Resolve conflict",
"action.confirmMutationApplied": "Confirm the change was applied",
"action.confirmMutationNotApplied": "Confirm the change was not applied",
"action.resendMutation": "Send the same request again",
"action.continueEditing": "Continue editing",
"action.discardAndLeave": "Discard and leave",
"action.signIn": "Start sign-in",
@@ -318,7 +314,8 @@ const PLATFORM_EN_MESSAGES = {
"form.validation.configuration": "Review the input configuration.",
"form.conflict":
"Another update conflicts with this change. Your input has been preserved.",
"form.unavailable": "The change could not be saved. Try 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",
"toast.region": "Notifications",
"error.network_unreachable": "The network is unavailable.",
@@ -361,13 +358,7 @@ const PLATFORM_EN_MESSAGES = {
"error.storage_quota_exceeded": "Browser storage is full.",
"error.telemetry_failure": "Usage data could not be sent.",
"error.query_cache_failure": "Screen data could not be refreshed.",
"boot.failure.title": "The application could not start.",
"boot.field.error": "Error",
"boot.field.code": "Code",
"boot.field.build": "Build",
"boot.field.configSchema": "Configuration schema",
"boot.field.release": "Release",
"boot.supportReference": "Support reference: {reference}",
...BOOT_MESSAGES["en-US"],
} as const satisfies Record<keyof typeof PLATFORM_KO_MESSAGES, string>;
export const EN_MESSAGES = {
+8 -2
View File
@@ -74,9 +74,12 @@ const LocaleContext = createContext<LocaleContextValue>(DEFAULT_CONTEXT);
export function LocaleProvider({
children,
initialLocale = "ko-KR",
onLocaleChange,
}: Readonly<{
children: React.ReactNode;
initialLocale?: SupportedLocale;
/** Persists a user's choice; the provider itself stays storage-free. */
onLocaleChange?: (locale: SupportedLocale) => void;
}>) {
const [locale, setLocaleState] = useState<SupportedLocale>(() =>
normalizeLocale(initialLocale),
@@ -92,7 +95,10 @@ export function LocaleProvider({
() => ({
locale,
direction,
setLocale: setLocaleState,
setLocale(next) {
setLocaleState(next);
onLocaleChange?.(next);
},
message: (key, ...args) => formatMessage(locale, key, ...args),
resolve: (key) => resolveMessage(locale, key),
date: (dateValue, options) => formatDate(locale, dateValue, options),
@@ -105,7 +111,7 @@ export function LocaleProvider({
selectPlural(locale, pluralValue, choices),
select: (selectValue, choices) => selectMessage(selectValue, choices),
}),
[direction, locale],
[direction, locale, onLocaleChange],
);
return (
+2 -1
View File
@@ -84,7 +84,8 @@ export function resolveMessage(
const catalog =
MESSAGE_CATALOGS[sourceLocale] ??
MESSAGE_CATALOGS[FALLBACK_LOCALE];
const fallback = KO_MESSAGES["common.unavailable"];
const fallback =
catalog["common.unavailable"] ?? KO_MESSAGES["common.unavailable"];
const canonicalKey =
MESSAGE_KEY_ALIASES[key as keyof typeof MESSAGE_KEY_ALIASES] ?? key;
const template = catalog[canonicalKey as MessageKey] ?? fallback;
+29 -30
View File
@@ -21,7 +21,10 @@ import {
type MessageKey,
} from "../i18n/index.ts";
import { useApplicationRuntime } from "../providers/application-provider.tsx";
import { useSession } from "../providers/session-provider.tsx";
import {
useSession,
useSessionAction,
} from "../providers/session-provider.tsx";
import { useTheme } from "../providers/theme-provider.tsx";
const SESSION_MESSAGE_KEYS = Object.freeze({
@@ -33,38 +36,17 @@ const SESSION_MESSAGE_KEYS = Object.freeze({
export function AppShell() {
const location = useLocation();
const { sessionState, beginSignIn, signOut, recover } = useSession();
const { sessionState } = useSession();
const sessionAction = useSessionAction();
const { preference, setPreference } = useTheme();
const { locale, setLocale, message } = useLocale();
const [navigationOpen, setNavigationOpen] = useState(false);
const navigationTriggerRef = useRef<HTMLButtonElement | null>(null);
const [sessionActionPending, setSessionActionPending] = useState(false);
const [sessionActionFailed, setSessionActionFailed] = useState(false);
useEffect(() => {
setNavigationOpen(false);
}, [location.pathname]);
async function runSessionAction() {
setSessionActionPending(true);
setSessionActionFailed(false);
try {
if (sessionState === "authenticated") {
await signOut();
} else if (sessionState === "recovery-pending") {
await recover();
} else {
await beginSignIn(
`${location.pathname}${location.search}${location.hash}`,
);
}
} catch {
setSessionActionFailed(true);
} finally {
setSessionActionPending(false);
}
}
const sessionActionLabel =
sessionState === "authenticated"
? message("action.signOut")
@@ -128,17 +110,25 @@ export function AppShell() {
</span>
{integrationAvailable ? (
<Button
disabled={sessionActionPending}
onClick={() => void runSessionAction()}
disabled={sessionAction.pending}
onClick={() =>
sessionAction.run(
sessionState === "authenticated"
? "sign-out"
: sessionState === "recovery-pending"
? "recover"
: "sign-in",
)
}
size="compact"
>
{sessionActionPending
{sessionAction.pending
? message("common.processing")
: sessionActionLabel}
</Button>
) : null}
</div>
{sessionActionFailed ? (
{sessionAction.failed ? (
<p className="app-shell__session-error" role="alert">
{message("shell.session.actionFailed")}
</p>
@@ -157,7 +147,12 @@ export function AppShell() {
returnFocusRef={navigationTriggerRef}
title={message("shell.menu")}
>
<PrimaryNavigation id="mobile-primary-navigation" />
{/* Close before the route commits: while the modal is open the page
is inert and the new route cannot take focus. */}
<PrimaryNavigation
id="mobile-primary-navigation"
onNavigate={() => setNavigationOpen(false)}
/>
</Drawer>
<main className="app-shell__content" id="main-content" tabIndex={-1}>
<Outlet />
@@ -166,7 +161,10 @@ export function AppShell() {
);
}
function PrimaryNavigation({ id }: Readonly<{ id: string }>) {
function PrimaryNavigation({
id,
onNavigate,
}: Readonly<{ id: string; onNavigate?: () => void }>) {
const { resolve, message } = useLocale();
const runtime = useApplicationRuntime();
const { pathname } = useLocation();
@@ -203,6 +201,7 @@ function PrimaryNavigation({ id }: Readonly<{ id: string }>) {
}`
}
end
onClick={onNavigate}
to={definition.path}
>
{resolve(`route.${definition.routeId}.navigation`)}
@@ -0,0 +1,23 @@
import type { ReactNode } from "react";
import { LocaleProvider, normalizeLocale } from "../i18n/index.ts";
import { useApplicationPreferences } from "./application-provider.tsx";
import { ThemeProvider } from "./theme-provider.tsx";
/**
* User preferences outlive a session. Mount this above the server-state scope
* fence so a session change (FENCED → READY) does not reset locale or theme.
*/
export function PreferenceProviders({
children,
}: Readonly<{ children: ReactNode }>) {
const preferences = useApplicationPreferences();
return (
<LocaleProvider
initialLocale={normalizeLocale(preferences.getLocale() ?? "ko-KR")}
onLocaleChange={preferences.setLocale}
>
<ThemeProvider>{children}</ThemeProvider>
</LocaleProvider>
);
}
@@ -2,9 +2,11 @@ import {
createContext,
useContext,
useMemo,
useState,
useSyncExternalStore,
type ReactNode,
} from "react";
import { useLocation } from "react-router-dom";
import type {
ApplicationApi,
@@ -53,3 +55,36 @@ export function useSession(): SessionContextValue {
}
return session;
}
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.
*/
export function useSessionAction(): Readonly<{
pending: boolean;
failed: boolean;
run(action: SessionAction): void;
}> {
const { pathname, search, hash } = useLocation();
const { beginSignIn, signOut, recover } = useSession();
const [pending, setPending] = useState(false);
const [failed, setFailed] = useState(false);
async function execute(action: SessionAction): Promise<void> {
setPending(true);
setFailed(false);
try {
if (action === "sign-out") await signOut();
else if (action === "recover") await recover();
else await beginSignIn(`${pathname}${search}${hash}`);
} catch {
setFailed(true);
} finally {
setPending(false);
}
}
return { pending, failed, run: (action) => void execute(action) };
}
+202 -119
View File
@@ -3,7 +3,6 @@ import {
type ReactNode,
Suspense,
useEffect,
useMemo,
useRef,
useState,
} from "react";
@@ -13,33 +12,41 @@ import {
type RouteObject,
useLocation,
useNavigate,
useNavigationType,
useParams,
useSearchParams,
} from "react-router-dom";
import { ROUTE_FEATURE_OWNER } from "../../features/installed-feature-contracts.ts";
import { TECH_LOG_ROUTE_REGISTRY } from "../../features/tech-log/contracts/tech-log-route-contract.ts";
import {
ROUTE_FEATURE_OWNER,
ROUTE_REGISTRY,
} from "../../features/installed-feature-contracts.ts";
import type {
RouteDefinition,
RouteLayoutGroup,
PLATFORM_ROUTE_REGISTRY,
type RouteDefinition,
type RouteLayoutGroup,
} from "../../contracts/routes.ts";
import {
FeatureBoundary,
RouteBoundary,
} from "../boundaries/render-error-boundary.tsx";
import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.tsx";
import { Button, PageHeader } from "../design-system/index.ts";
import { LocaleProvider, useLocale } from "../i18n/index.ts";
import {
Button,
LoadingSurface,
PageHeader,
StatusPage,
} from "../design-system/index.ts";
import { useLocale } from "../i18n/index.ts";
import { TECH_LOG_ROUTE_LAYOUTS } from "../../features/tech-log/presentation/tech-log-route-runtime.tsx";
import {
useApplicationDiagnostics,
useApplicationRecovery,
useApplicationRuntime,
} from "../providers/application-provider.tsx";
import { SessionProvider, useSession } from "../providers/session-provider.tsx";
import { ThemeProvider } from "../providers/theme-provider.tsx";
import {
SessionProvider,
useSession,
useSessionAction,
} from "../providers/session-provider.tsx";
import {
createRedirectLoopGuard,
decideRouteAccessForDefinition,
@@ -60,54 +67,69 @@ import {
RouteInputProvider,
} from "./route-input.tsx";
function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) {
/** Route-level loading: the shared LoadingSurface inside the page frame. */
function RouteLoadingSurface({
definition,
}: Readonly<{ definition?: RouteDefinition }>) {
const { message, resolve } = useLocale();
const title = resolve(`route.${definition.routeId}.title`);
return (
<section
className="ui-page route-loading"
aria-live="polite"
aria-busy="true"
data-surface={definition.loadingSurface}
>
<div className="ui-skeleton" aria-hidden="true" />
<p>{message("route.loading")}</p>
<span className="visually-hidden">
{message("route.loadingNamed", { title })}
</span>
</section>
<div className="ui-page route-loading" data-surface={definition?.loadingSurface}>
<LoadingSurface
description={message("route.loading")}
{...(definition
? {
label: message("route.loadingNamed", {
title: resolve(`route.${definition.routeId}.title`),
}),
}
: {})}
/>
</div>
);
}
function RouteFailureSurface({
definition,
supportReference,
}: {
definition?: RouteDefinition;
/** 08-07. The build and, when reported, the incident id. */
supportReference: string;
}) {
const { message } = useLocale();
return (
<section
className="ui-page"
data-surface={definition?.errorSurface ?? "route-boundary"}
>
<PageHeader
title={message("route.failure.title")}
description={message("route.failure.description")}
/>
</section>
<StatusPage
heading={{
title: message("route.failure.title"),
description: message("route.failure.description"),
}}
// RENDER_FAILURE's registry action: a render defect stays until the
// URL changes, so the page offers the reload itself.
primaryAction={{
kind: "button",
label: message("action.reloadOnce"),
onAction: () => window.location.reload(),
}}
supportReference={supportReference}
surface={definition?.errorSurface ?? "route-boundary"}
variant="unexpected"
/>
);
}
function InvalidRouteSurface({ code }: { code: string }) {
const { message } = useLocale();
return (
<section className="ui-page" data-surface="invalid-route">
<PageHeader
title={message("route.invalid.title")}
description={message("route.invalid.description")}
/>
<StatusPage
heading={{
title: message("route.invalid.title"),
description: message("route.invalid.description"),
}}
surface="invalid-route"
variant="not-found"
>
<p data-route-error={code}>{message("route.invalid.action")}</p>
</section>
</StatusPage>
);
}
@@ -119,15 +141,18 @@ function InvalidRouteSurface({ code }: { code: string }) {
function DisabledFeatureSurface({ featureId }: { featureId: string }) {
const { message } = useLocale();
return (
<section className="ui-page" data-surface="disabled-feature">
<PageHeader
title={message("route.disabledFeature.title")}
description={message("route.disabledFeature.description")}
/>
<StatusPage
heading={{
title: message("route.disabledFeature.title"),
description: message("route.disabledFeature.description"),
}}
surface="disabled-feature"
variant="unavailable"
>
<p data-disabled-feature={featureId}>
{message("route.disabledFeature.action")}
</p>
</section>
</StatusPage>
);
}
@@ -138,16 +163,27 @@ function RouteLifecycle({
definition: RouteDefinition;
buildId: string;
}) {
const location = useLocation();
const { pathname, search } = useLocation();
const navigationType = useNavigationType();
const { message, resolve } = useLocale();
const diagnostics = useApplicationDiagnostics();
// A locale change re-renders the title only; it is not a route change.
useEffect(() => {
document.title = message("route.documentTitle", {
title: resolve(`route.${definition.routeId}.title`),
appName: message("common.appName"),
});
}, [definition, message, resolve]);
// This product's shells own focus on navigation (their skip links target
// `#main-content`), so unlike the template the route does not move it.
useEffect(() => {
try {
if (!navigator.userAgent.toLowerCase().includes("jsdom")) {
// 08-08. Back and forward leave the scroll to the browser, which
// restores the position it saved for that entry.
if (
navigationType !== "POP" &&
!navigator.userAgent.toLowerCase().includes("jsdom")
) {
window.scrollTo({ top: 0, left: 0, behavior: "auto" });
}
} catch {
@@ -157,15 +193,7 @@ function RouteLifecycle({
routeId: definition.routeId,
buildId,
});
}, [
buildId,
definition,
diagnostics,
location.key,
location.pathname,
message,
resolve,
]);
}, [buildId, definition, diagnostics, navigationType, pathname, search]);
return null;
}
@@ -184,7 +212,7 @@ function CanonicalRouteRedirect<RouteIdValue extends string>({
useEffect(() => {
if (definition.path.includes("*")) return;
const source = `${location.pathname}${location.search}`;
const target = buildRouteUrlFromDefinition(
const canonical = buildRouteUrlFromDefinition(
definition,
codecs,
{
@@ -192,6 +220,11 @@ function CanonicalRouteRedirect<RouteIdValue extends string>({
search: input.search,
},
);
// D-16: a route that ignores its query leaves the query in the URL.
const target =
definition.searchSchema === null
? `${canonical}${location.search}`
: canonical;
if (source === target) {
guard.current.reset();
} else if (guard.current.allow(source, target)) {
@@ -209,39 +242,22 @@ function ProtectedRoute({
children: ReactNode;
}) {
const location = useLocation();
const { sessionState, beginSignIn, recover } = useSession();
const { sessionState } = useSession();
const { message } = useLocale();
const [pending, setPending] = useState(false);
const [failed, setFailed] = useState(false);
const { pending, failed, run } = useSessionAction();
const decision = decideRouteAccessForDefinition(definition, sessionState);
async function continueSession() {
setPending(true);
setFailed(false);
try {
if (decision.action === "wait-for-session") {
await recover();
} else {
await beginSignIn(
`${location.pathname}${location.search}${location.hash}`,
);
}
} catch {
setFailed(true);
} finally {
setPending(false);
}
}
if (decision.allowed) return children;
if (sessionState === "integration-failed") {
return (
<section className="ui-page" data-surface="auth-integration-required">
<PageHeader
title={message("route.auth.integration.title")}
description={message("route.auth.integration.description")}
/>
</section>
<StatusPage
heading={{
title: message("route.auth.integration.title"),
description: message("route.auth.integration.description"),
}}
surface="auth-integration-required"
variant="unavailable"
/>
);
}
const recovering = decision.action === "wait-for-session";
@@ -268,7 +284,10 @@ function ProtectedRoute({
}
/>
<div className="auth-gate__actions">
<Button disabled={pending} onClick={() => void continueSession()}>
<Button
disabled={pending}
onClick={() => run(recovering ? "recover" : "sign-in")}
>
{pending
? message("common.processing")
: recovering
@@ -291,21 +310,38 @@ function ProtectedRoute({
);
}
function RegisteredRoute<RouteIdValue extends string>({
routeId,
buildId,
definition,
runtime,
codecs,
registeredNotFound,
}: {
type RegisteredRouteProps<RouteIdValue extends string> = {
routeId: RouteIdValue;
buildId: string;
definition: RouteDefinition;
runtime: GroupedRouteRuntimeDefinition;
codecs: RouteCodecRegistry;
registeredNotFound?: RegisteredNotFoundRegistration;
}) {
};
/**
* Title, focus and route telemetry belong to every answer a route gives,
* including auth-required, invalid-address and disabled-feature surfaces.
*/
function RegisteredRoute<RouteIdValue extends string>(
props: RegisteredRouteProps<RouteIdValue>,
) {
return (
<>
<RouteLifecycle definition={props.definition} buildId={props.buildId} />
<RouteSurface {...props} />
</>
);
}
function RouteSurface<RouteIdValue extends string>({
routeId,
buildId,
definition,
runtime,
codecs,
registeredNotFound,
}: RegisteredRouteProps<RouteIdValue>) {
const params = useParams();
const [search] = useSearchParams();
const location = useLocation();
@@ -332,6 +368,8 @@ function RegisteredRoute<RouteIdValue extends string>({
if (!parsed.success) return <InvalidRouteSurface code={parsed.code} />;
const routeInput = parsed.data;
const RuntimeComponent = runtime.Component;
const boundaryName =
definition.errorSurface === "feature-boundary" ? "feature" : "route";
const notFoundDescriptor: RegisteredNotFoundDescriptor | undefined =
registeredNotFound
? {
@@ -347,8 +385,18 @@ function RegisteredRoute<RouteIdValue extends string>({
}
>
<ChunkRecoveryBoundary
key={registeredNotFound.definition.routeId}
chunkId={registeredNotFound.definition.chunkId}
recover={recovery.recoverChunk}
buildId={buildId}
onUnrecovered={(incidentId) =>
diagnostics.reportRenderFailure({
routeId: registeredNotFound.definition.routeId,
buildId,
boundaryName,
incidentId,
})
}
>
<NotFoundRuntime />
</ChunkRecoveryBoundary>
@@ -366,11 +414,22 @@ function RegisteredRoute<RouteIdValue extends string>({
definition={definition}
codecs={codecs}
/>
<RouteLifecycle definition={definition} buildId={buildId} />
<Suspense fallback={<RouteLoadingSurface definition={definition} />}>
{/* React Router reuses this instance across sibling routes; the key
keeps one route's failed chunk from latching onto the next. */}
<ChunkRecoveryBoundary
key={definition.routeId}
chunkId={definition.chunkId}
recover={recovery.recoverChunk}
buildId={buildId}
onUnrecovered={(incidentId) =>
diagnostics.reportRenderFailure({
routeId,
buildId,
boundaryName,
incidentId,
})
}
>
<RuntimeComponent />
</ChunkRecoveryBoundary>
@@ -389,10 +448,15 @@ function RegisteredRoute<RouteIdValue extends string>({
buildId,
resetKey: `${location.pathname}${location.search}`,
onRenderFailure: diagnostics.reportRenderFailure,
fallback: <RouteFailureSurface definition={definition} />,
fallback: (incidentId: string) => (
<RouteFailureSurface
definition={definition}
supportReference={`${buildId}:${incidentId}`}
/>
),
children: protectedContent,
};
return definition.errorSurface === "feature-boundary" ? (
return boundaryName === "feature" ? (
<FeatureBoundary {...boundaryProps} />
) : (
<RouteBoundary {...boundaryProps} />
@@ -493,36 +557,55 @@ export function createGroupedRouteObjects(
id: `${layoutGroup}_LAYOUT`,
path: "/",
element: layouts[layoutGroup],
errorElement: <RouteFailureSurface />,
errorElement: <RouteFailureSurface supportReference={buildId} />,
children: children[layoutGroup],
}));
}
/**
* Template sync (af3d8e6). The grouped PUBLIC/STUDIO router mounts the routes
* this product composes directly: the platform's and TechLog's. Upstream, a
* generator-installed feature's routes are served by the bounded-context route
* gateway, which this router does not mount; none is installed here, and the
* day one is, `tests/component/product-feature-switch.test.tsx` fails on its
* registered-but-unmounted routes (docs/operations/template-sync-2026-09-29.md).
*/
const MOUNTED_ROUTE_REGISTRY = Object.freeze({
...PLATFORM_ROUTE_REGISTRY,
...TECH_LOG_ROUTE_REGISTRY,
});
/**
* Locale and theme come from `PreferenceProviders` above this component, which
* the server-state scope fence may remount on a session change.
*/
export function AppRouter({
basename = "/",
buildId = "local-build",
}: Readonly<{ basename?: string; buildId?: string }>) {
const router = useMemo(
() =>
createBrowserRouter(
createGroupedRouteObjects(
ROUTE_REGISTRY,
ROUTE_RUNTIME,
TECH_LOG_ROUTE_LAYOUTS,
buildId,
ROUTE_CODECS,
),
{ basename },
const [router, setRouter] = useState<ReturnType<
typeof createBrowserRouter
> | null>(null);
// Created in the effect that disposes it: a disposed router never listens
// to history again, so StrictMode's replayed mount needs a fresh one, and a
// remount must not leave the old router's popstate listener behind.
useEffect(() => {
const created = createBrowserRouter(
createGroupedRouteObjects(
MOUNTED_ROUTE_REGISTRY,
ROUTE_RUNTIME,
TECH_LOG_ROUTE_LAYOUTS,
buildId,
ROUTE_CODECS,
),
[basename, buildId],
);
{ basename },
);
setRouter(created);
return () => created.dispose();
}, [basename, buildId]);
return (
<LocaleProvider>
<ThemeProvider>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</ThemeProvider>
</LocaleProvider>
<SessionProvider>
{router ? <RouterProvider router={router} /> : null}
</SessionProvider>
);
}
@@ -1,6 +1,8 @@
import { z } from "zod";
import { z } from "../../contracts/zod.ts";
export const PLATFORM_ROUTE_CODECS = Object.freeze({
none: z.object({}).strict(),
// D-16: a route without input ignores unknown keys (`?utm_source=`, OAuth
// callback parameters) instead of calling the address invalid.
none: z.object({}),
NotFoundSplat: z.object({ "*": z.string().min(1).optional() }).strict(),
});
File diff suppressed because it is too large Load Diff
+45
View File
@@ -0,0 +1,45 @@
@layer base {
:root {
color: var(--color-content);
background: var(--color-surface);
font-family: var(--font-sans);
}
body {
margin: 0;
min-width: 20rem;
min-height: 100vh;
}
button,
input,
textarea,
select {
font: inherit;
}
a {
color: inherit;
}
h1,
h2,
p {
margin-block-start: 0;
}
h1 {
font-size: clamp(2rem, 5vw, 3.5rem);
line-height: 1.05;
letter-spacing: -0.04em;
}
h2 {
line-height: 1.25;
}
:focus-visible {
outline: 0.1875rem solid var(--color-focus);
outline-offset: 0.1875rem;
}
}
+223
View File
@@ -0,0 +1,223 @@
@layer components {
.readiness-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
}
.readiness-grid p,
.starter-actions p {
margin-block-end: 0;
color: var(--color-content-muted);
line-height: 1.65;
}
.starter-actions,
.auth-example {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 1.5rem;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
}
.route-loading {
padding-block-start: 4rem;
}
.gallery-section {
display: grid;
gap: 1rem;
padding-block: 0.5rem;
}
.gallery-section__header {
max-width: 45rem;
}
.gallery-section__header h2,
.gallery-section__header p {
margin-block-end: 0;
}
.gallery-section__header p {
margin-block-start: 0.4rem;
color: var(--color-content-muted);
line-height: 1.6;
}
.component-grid {
display: grid;
gap: 1rem;
}
.component-grid--two {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.component-grid--three {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.component-stack,
.example-form {
display: grid;
gap: 1rem;
}
.platform-metric-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr));
gap: 1rem;
margin-block: 0;
}
.platform-metric {
display: grid;
gap: 0.25rem;
padding: 0.85rem 1rem;
border: 1px solid var(--color-border);
border-radius: var(--radius-surface);
background: var(--color-panel);
}
.platform-metric dt {
font-size: 0.8125rem;
color: var(--color-content-muted);
}
.platform-metric dd {
display: grid;
gap: 0.15rem;
margin-inline-start: 0;
}
.platform-metric__value {
font-weight: 600;
overflow-wrap: anywhere;
}
.platform-metric__hint,
.platform-operation__path {
display: block;
font-size: 0.8125rem;
color: var(--color-content-muted);
overflow-wrap: anywhere;
}
.badge-row {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.token-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
gap: 0.75rem;
}
.token-swatch {
display: grid;
gap: 0.45rem;
min-width: 0;
border: 1px solid var(--color-border);
border-radius: var(--radius-control);
padding: 0.75rem;
background: var(--color-panel);
}
.token-swatch__color {
height: 4rem;
border: 1px solid color-mix(in oklch, var(--color-content) 15%, transparent);
border-radius: calc(var(--radius-control) / 1.5);
}
.token-swatch code {
overflow: hidden;
color: var(--color-content-muted);
font-size: 0.75rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.gallery-notice {
display: block;
width: fit-content;
max-width: 100%;
box-sizing: border-box;
border: 1px solid var(--color-surface-muted);
border-radius: 999px;
padding: 0.65rem 1rem;
color: var(--color-content);
background: var(--color-panel);
box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 10%, transparent);
font-size: 0.875rem;
font-weight: 650;
}
.state-surface {
display: flex;
min-height: 12rem;
box-sizing: border-box;
flex-direction: column;
align-items: flex-start;
justify-content: center;
border: 1px solid var(--color-surface-muted);
border-radius: var(--radius-surface);
padding: 1.25rem;
background: var(--color-surface);
}
.state-surface h2,
.state-surface p {
margin-block-end: 0.75rem;
}
.state-surface > p:not(.state-surface__eyebrow) {
color: var(--color-content-muted);
line-height: 1.55;
}
.state-surface__eyebrow {
color: var(--color-action-hover);
font-size: 0.75rem;
font-weight: 800;
letter-spacing: 0.04em;
}
.state-surface--warning {
border-color: var(--color-warning-border);
background: var(--color-warning-surface);
}
.state-surface--danger,
.ui-terminal-error {
border-color: var(--color-danger-border);
background: var(--color-danger-surface);
}
.state-surface--loading {
gap: 0.75rem;
}
.state-surface--loading .ui-skeleton {
width: 100%;
}
.state-preview-content {
border-radius: var(--radius-control);
padding: 1rem;
background: var(--color-surface);
}
.app-shell__scrim {
display: none;
}
}
@@ -0,0 +1,719 @@
@layer components {
.ui-page {
@apply mx-auto flex max-w-6xl flex-col gap-6 p-page;
width: 100%;
box-sizing: border-box;
}
.ui-panel {
@apply rounded-surface p-6 shadow-sm;
border: 1px solid var(--color-border);
background: var(--color-panel);
}
.ui-button {
@apply rounded-control bg-action px-4 py-2 font-semibold;
display: inline-flex;
min-height: 2.75rem;
align-items: center;
justify-content: center;
border: 0;
color: var(--color-on-action);
text-decoration: none;
cursor: pointer;
}
.ui-button:hover {
@apply bg-action-hover;
}
.ui-button:disabled {
cursor: not-allowed;
opacity: var(--opacity-disabled);
}
.ui-button--pending {
gap: var(--space-2);
cursor: progress;
}
.ui-button--secondary {
border: 1px solid var(--color-surface-muted);
color: var(--color-content);
background: var(--color-panel);
}
.ui-button--secondary:hover {
color: var(--color-action);
background: var(--color-surface);
}
.ui-button--danger {
color: var(--color-on-action);
background: var(--color-danger);
}
.ui-button--danger:hover {
background: var(--color-danger-hover);
}
.ui-button--ghost {
color: var(--color-content);
background: transparent;
}
.ui-button--ghost:hover {
color: var(--color-action);
background: var(--color-surface-muted);
}
.ui-button--compact {
min-height: var(--size-control-sm);
padding: 0.4rem 0.75rem;
font-size: 0.85rem;
}
.ui-icon-button {
width: var(--size-touch-target);
min-width: var(--size-touch-target);
padding: 0;
}
.app-shell__menu-button.ui-icon-button {
display: none;
}
.ui-icon {
display: inline-block;
flex: 0 0 auto;
stroke-width: var(--icon-stroke-default);
}
.ui-icon--small {
width: var(--size-icon-sm);
height: var(--size-icon-sm);
}
.ui-icon--medium {
width: var(--size-icon-md);
height: var(--size-icon-md);
}
.ui-icon--large {
width: var(--size-icon-lg);
height: var(--size-icon-lg);
}
.ui-spinner {
display: inline-block;
width: var(--size-icon-sm);
height: var(--size-icon-sm);
box-sizing: border-box;
border: 2px solid currentColor;
border-inline-end-color: transparent;
border-radius: var(--radius-full);
animation: ui-spin var(--duration-slow) linear infinite;
}
@keyframes ui-spin {
to {
transform: rotate(360deg);
}
}
.ui-skeleton {
@apply h-24 animate-pulse rounded-surface bg-surface-muted;
}
.ui-empty,
.ui-terminal-error {
@apply rounded-surface border border-surface-muted p-6;
}
.ui-field {
display: grid;
gap: 0.45rem;
}
.ui-field__label {
font-weight: 750;
}
.ui-field__description,
.ui-field__error {
margin: 0;
font-size: 0.875rem;
line-height: 1.5;
}
.ui-field__description {
color: var(--color-content-muted);
}
.ui-field__error {
color: var(--color-danger);
font-weight: 650;
}
.ui-field__input {
width: 100%;
min-height: 2.75rem;
box-sizing: border-box;
border: 1px solid
color-mix(in oklch, var(--color-content-muted) 55%, var(--color-panel));
border-radius: var(--radius-control);
padding: 0.65rem 0.8rem;
color: var(--color-content);
background: var(--color-panel);
}
.ui-field__input[aria-invalid="true"] {
border-color: var(--field-border-invalid);
}
.ui-field__textarea {
min-height: 7rem;
resize: vertical;
}
.ui-field__counter {
justify-self: end;
color: var(--color-content-muted);
font-size: var(--font-size-sm);
}
.ui-choice-field,
.ui-radio-group,
.ui-switch-field {
display: grid;
gap: var(--space-2);
}
.ui-choice-field__control {
display: flex;
min-height: var(--size-touch-target);
align-items: center;
gap: var(--space-2);
cursor: pointer;
}
.ui-choice-field__control input {
width: 1.15rem;
height: 1.15rem;
accent-color: var(--color-action);
}
.ui-choice-field__control small {
display: block;
color: var(--color-content-muted);
}
.ui-radio-group {
min-width: 0;
border: 1px solid var(--color-border);
border-radius: var(--radius-control);
padding: var(--space-3);
}
.ui-radio-group legend {
padding-inline: var(--space-1);
font-weight: var(--font-weight-bold);
}
.ui-switch {
display: inline-flex;
width: fit-content;
min-height: var(--size-touch-target);
align-items: center;
gap: var(--space-2);
border: 0;
color: var(--color-content);
background: transparent;
cursor: pointer;
}
.ui-switch__thumb {
display: inline-block;
width: 2.5rem;
height: 1.5rem;
border: 1px solid var(--color-border-strong);
border-radius: var(--radius-full);
background: var(--color-disabled-surface);
}
.ui-switch__thumb::after {
display: block;
width: 1rem;
height: 1rem;
margin: 0.2rem;
border-radius: var(--radius-full);
background: var(--color-content-muted);
content: "";
transition: transform var(--duration-normal) var(--easing-standard);
}
.ui-switch[aria-checked="true"] .ui-switch__thumb {
border-color: var(--color-action);
background: var(--color-action);
}
.ui-switch[aria-checked="true"] .ui-switch__thumb::after {
background: var(--color-on-action);
transform: translateX(1rem);
}
[dir="rtl"] .ui-switch[aria-checked="true"] .ui-switch__thumb::after {
transform: translateX(-1rem);
}
.ui-search-field {
position: relative;
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: end;
gap: var(--space-2);
}
.ui-card {
display: flex;
min-width: 0;
flex-direction: column;
gap: 1.25rem;
border: 1px solid var(--color-border);
border-radius: var(--radius-surface);
padding: 1.25rem;
background: var(--color-panel);
box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 6%, transparent);
}
.ui-card__header :is(h2, h3, h4),
.ui-card__header p {
margin-block-end: 0;
}
.ui-card__header p {
margin-block-start: 0.4rem;
color: var(--color-content-muted);
line-height: 1.55;
}
.ui-card__content {
flex: 1;
}
.ui-card__footer {
padding-block-start: 1rem;
border-top: 1px solid var(--color-surface-muted);
}
.ui-alert {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
border: 1px solid var(--color-surface-muted);
border-radius: var(--radius-control);
padding: 1rem;
background: var(--color-surface);
}
.ui-alert--info {
border-color: var(--color-info-border);
background: var(--color-info-surface);
}
.ui-alert--success {
border-color: var(--color-success-border);
background: var(--color-success-surface);
}
.ui-alert--warning {
border-color: var(--color-warning-border);
background: var(--color-warning-surface);
}
.ui-alert--danger {
border-color: var(--color-danger-border);
background: var(--color-danger-surface);
}
.ui-alert__content,
.ui-alert__content p {
margin-block: 0.35rem 0;
color: var(--color-content-muted);
}
.ui-alert__dismiss,
.ui-dialog__close {
display: inline-grid;
width: 2rem;
height: 2rem;
flex: 0 0 auto;
place-items: center;
border: 0;
border-radius: var(--radius-control);
color: var(--color-content);
background: transparent;
font-size: 1.35rem;
cursor: pointer;
}
.ui-alert__dismiss.ui-icon-button,
.ui-dialog__close.ui-icon-button {
min-width: 2rem;
min-height: 2rem;
padding: 0;
}
.ui-alert__dismiss:hover,
.ui-dialog__close:hover {
background: color-mix(in oklch, var(--color-content) 8%, transparent);
}
.ui-badge {
display: inline-flex;
border-radius: 999px;
padding: 0.3rem 0.65rem;
color: var(--color-content);
background: var(--color-surface-muted);
font-size: 0.8rem;
font-weight: 750;
}
.ui-badge--info {
color: var(--color-info-content);
background: var(--color-info-surface);
}
.ui-badge--success {
color: var(--color-success-content);
background: var(--color-success-surface);
}
.ui-badge--warning {
color: var(--color-warning-content);
background: var(--color-warning-surface);
}
.ui-badge--danger {
color: var(--color-danger-content);
background: var(--color-danger-surface);
}
.ui-dialog {
width: min(34rem, calc(100vw - 2rem));
max-height: calc(100vh - 2rem);
box-sizing: border-box;
overflow: auto;
border: 0;
border-radius: var(--radius-surface);
padding: 0;
color: var(--color-content);
background: var(--color-panel);
box-shadow: var(--dialog-elevation);
}
.ui-dialog::backdrop {
background: color-mix(in oklch, var(--color-content) 55%, transparent);
backdrop-filter: blur(2px);
}
.ui-drawer {
width: var(--drawer-width);
max-width: none;
height: 100dvh;
max-height: none;
margin-block: 0;
border-radius: 0;
}
.ui-drawer--start {
margin-inline: 0 auto;
}
.ui-drawer--end {
margin-inline: auto 0;
}
.ui-drawer .ui-dialog__surface {
min-height: 100%;
box-sizing: border-box;
}
.ui-popover,
.ui-menu,
.ui-tooltip {
position: relative;
display: inline-block;
}
.ui-popover__content,
.ui-menu__content {
position: absolute;
z-index: var(--layer-popover);
top: calc(100% + var(--space-2));
inset-inline-start: 0;
min-width: 12rem;
border: 1px solid var(--color-border);
border-radius: var(--radius-control);
padding: var(--space-2);
background: var(--color-surface-elevated);
box-shadow: var(--elevation-popover);
}
.ui-menu__content {
display: grid;
gap: var(--space-1);
}
.ui-menu__item {
min-height: var(--size-control-sm);
border: 0;
border-radius: var(--radius-control);
padding: var(--space-2) var(--space-3);
color: var(--color-content);
background: transparent;
text-align: start;
cursor: pointer;
}
.ui-menu__item:hover,
.ui-menu__item:focus-visible {
background: var(--color-surface-muted);
}
.ui-tooltip__content {
position: absolute;
z-index: var(--layer-popover);
inset-block-end: calc(100% + var(--space-2));
inset-inline-start: 50%;
width: max-content;
max-width: 16rem;
padding: var(--space-2);
border-radius: var(--radius-control);
color: var(--color-content-inverse);
background: var(--color-content);
opacity: 0;
pointer-events: none;
transform: translateX(-50%);
transition: opacity var(--duration-fast) var(--easing-standard);
}
.ui-tooltip:focus-within .ui-tooltip__content,
.ui-tooltip:hover .ui-tooltip__content {
opacity: 1;
}
.ui-progress,
.ui-progress__label {
display: grid;
gap: var(--space-2);
}
.ui-progress__label {
grid-template-columns: 1fr auto;
}
.ui-progress__bar {
width: 100%;
accent-color: var(--color-action);
}
.ui-skeleton--text {
height: 1em;
}
.ui-skeleton--control {
height: var(--size-control-md);
}
.ui-skeleton--surface {
height: 6rem;
}
.ui-separator {
width: 100%;
border: 0;
border-block-start: 1px solid var(--color-border);
}
.ui-breadcrumbs ol,
.ui-pagination,
.ui-tabs__list {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.ui-breadcrumbs li:not(:last-child)::after {
margin-inline-start: var(--space-2);
color: var(--color-content-muted);
content: "/";
}
.ui-tabs {
display: grid;
gap: var(--space-3);
}
.ui-tabs__list {
border-block-end: 1px solid var(--color-border);
}
.ui-tabs__tab {
min-height: var(--size-touch-target);
border: 0;
border-block-end: 0.2rem solid transparent;
padding: var(--space-2) var(--space-3);
color: var(--color-content-muted);
background: transparent;
cursor: pointer;
}
.ui-tabs__tab[aria-selected="true"] {
border-block-end-color: var(--color-action);
color: var(--color-content);
font-weight: var(--font-weight-bold);
}
.ui-tabs__panel {
padding: var(--space-3);
}
.ui-toast-region {
position: fixed;
z-index: var(--layer-toast);
inset-block-end: var(--space-4);
inset-inline-end: var(--space-4);
display: grid;
width: var(--toast-width);
gap: var(--space-2);
}
.ui-toast {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-3);
border: 1px solid var(--color-border);
border-inline-start: 0.25rem solid var(--color-info-border);
border-radius: var(--radius-control);
padding: var(--space-3);
background: var(--color-surface-elevated);
box-shadow: var(--elevation-popover);
}
.ui-toast--success {
border-inline-start-color: var(--color-success-border);
}
.ui-toast--warning {
border-inline-start-color: var(--color-warning-border);
}
.ui-toast--danger {
border-inline-start-color: var(--color-danger-border);
}
.ui-toast p {
margin: var(--space-1) 0 0;
color: var(--color-content-muted);
}
.ui-data-table__scroll {
max-width: 100%;
overflow-x: auto;
}
.ui-data-table {
width: 100%;
border-collapse: collapse;
}
.ui-data-table caption {
margin-block-end: var(--space-2);
font-weight: var(--font-weight-bold);
text-align: start;
}
.ui-data-table th,
.ui-data-table td {
border-block-end: 1px solid var(--color-border);
padding: var(--space-3);
text-align: start;
}
.ui-search-filter-toolbar,
.ui-pagination-bar {
display: flex;
flex-wrap: wrap;
align-items: end;
justify-content: space-between;
gap: var(--space-3);
}
.ui-disclosure-group {
display: grid;
gap: var(--space-2);
}
.ui-disclosure-group details {
border: 1px solid var(--color-border);
border-radius: var(--radius-control);
padding: var(--space-3);
}
.ui-disclosure-group summary {
min-height: var(--size-control-sm);
cursor: pointer;
font-weight: var(--font-weight-bold);
}
.ui-focus-ring {
display: inline-flex;
border-radius: var(--radius-control);
}
.ui-focus-ring:focus-within {
outline: 0.1875rem solid var(--color-focus);
outline-offset: 0.1875rem;
}
.ui-dialog__surface {
padding: 1.5rem;
}
.ui-dialog__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.ui-dialog__header h2 {
margin-block-end: 0.35rem;
}
.ui-dialog__header p,
.ui-dialog__content p {
color: var(--color-content-muted);
line-height: 1.6;
}
.ui-dialog__content {
padding-block: 1rem;
}
.ui-dialog__actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 0.75rem;
padding-block-start: 1rem;
border-top: 1px solid var(--color-surface-muted);
}
}
@@ -0,0 +1,93 @@
@media (max-width: 47.999rem) {
.app-shell {
grid-template-columns: minmax(0, 1fr);
grid-template-areas:
"header"
"content";
}
.app-shell__header {
padding-inline: 0.75rem;
}
.app-shell__menu-button.ui-icon-button {
display: inline-flex;
}
.app-shell__sidebar {
position: fixed;
z-index: 50;
top: 4.5rem;
bottom: 0;
left: 0;
display: none;
width: min(18rem, 85vw);
height: auto;
box-sizing: border-box;
box-shadow: 10px 0 30px color-mix(in oklch, var(--color-content) 15%, transparent);
}
.app-shell__sidebar[data-open="true"] {
display: block;
}
.app-shell__scrim {
position: fixed;
z-index: 40;
inset: 4.5rem 0 0;
display: block;
border: 0;
background: color-mix(in oklch, var(--color-content) 35%, transparent);
cursor: pointer;
}
.app-shell__session .session-status {
display: none;
}
.app-shell__session .theme-selector {
display: none;
}
.app-shell__brand {
display: none;
}
.readiness-grid {
grid-template-columns: minmax(0, 1fr);
}
.component-grid--two,
.component-grid--three {
grid-template-columns: minmax(0, 1fr);
}
.page-template__heading,
.page-template__layout[data-has-aside="true"] {
grid-template-columns: minmax(0, 1fr);
}
.page-template__heading .page-header {
grid-row: auto;
}
.page-template__actions,
.page-template__status {
justify-content: flex-start;
}
.form-actions--sticky {
margin-inline: calc(var(--spacing-page) * -1);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
+195
View File
@@ -0,0 +1,195 @@
@layer components {
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.skip-link {
position: fixed;
z-index: 100;
top: 0.75rem;
left: 0.75rem;
padding: 0.75rem 1rem;
border-radius: var(--radius-control);
color: var(--color-panel);
background: var(--color-content);
transform: translateY(-200%);
}
.skip-link:focus {
transform: translateY(0);
}
/* 08-08. Hash targets land below the sticky 4.5rem header. */
html {
scroll-padding-top: 4.5rem;
}
.app-shell {
display: grid;
min-height: 100vh;
grid-template-rows: 4.5rem 1fr;
grid-template-columns: 15rem minmax(0, 1fr);
grid-template-areas:
"header header"
"sidebar content";
}
.app-shell__header {
position: sticky;
z-index: 30;
top: 0;
grid-area: header;
display: flex;
align-items: center;
gap: 1rem;
min-width: 0;
padding: 0.75rem 1.25rem;
border-bottom: 1px solid var(--color-surface-muted);
background: color-mix(in oklch, var(--color-panel) 92%, var(--color-surface));
box-shadow: 0 1px 8px color-mix(in oklch, var(--color-content) 8%, transparent);
}
.app-shell__brand {
overflow: hidden;
font-size: 1.05rem;
font-weight: 800;
text-decoration: none;
text-overflow: ellipsis;
white-space: nowrap;
}
.app-shell__menu-button {
display: none;
align-items: center;
gap: 0.4rem;
border: 1px solid var(--color-surface-muted);
border-radius: var(--radius-control);
padding: 0.55rem 0.75rem;
color: var(--color-content);
background: var(--color-panel);
cursor: pointer;
}
.app-shell__session {
display: flex;
align-items: center;
gap: 0.75rem;
margin-inline-start: auto;
}
.theme-selector,
.locale-selector {
display: block;
}
.theme-selector .ui-field__label,
.locale-selector .ui-field__label {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.theme-selector .ui-field__input,
.locale-selector .ui-field__input {
min-height: var(--size-control-sm);
max-width: 8.5rem;
padding: 0.35rem 2rem 0.35rem 0.65rem;
cursor: pointer;
}
.locale-selector .ui-field__input {
max-width: 7rem;
}
.app-shell__session-error {
position: absolute;
top: calc(100% + 0.25rem);
right: 1rem;
padding: 0.5rem;
color: var(--color-danger);
background: var(--color-panel);
}
.session-status {
display: inline-flex;
width: fit-content;
align-items: center;
border-radius: 999px;
padding: 0.3rem 0.65rem;
color: var(--color-content-muted);
background: var(--color-surface-muted);
font-size: 0.8rem;
font-weight: 700;
}
.session-status[data-state="authenticated"] {
color: var(--color-success-content);
background: var(--color-success-surface);
}
.session-status[data-state="integration-failed"] {
color: var(--color-danger);
}
.app-shell__sidebar {
position: sticky;
top: 4.5rem;
grid-area: sidebar;
height: calc(100vh - 4.5rem);
padding: 1.25rem 0.75rem;
border-right: 1px solid var(--color-border);
background: var(--color-panel);
}
.app-navigation {
display: flex;
flex-direction: column;
gap: 0.25rem;
margin: 0;
padding: 0;
list-style: none;
}
.app-navigation__link {
display: block;
border-radius: var(--radius-control);
padding: 0.75rem 0.9rem;
color: var(--color-content-muted);
font-weight: 650;
text-decoration: none;
}
.app-navigation__link:hover {
color: var(--color-content);
background: var(--color-surface);
}
.app-navigation__link.is-active {
color: var(--color-action-hover);
background: color-mix(
in oklch,
var(--color-action) 14%,
var(--color-panel)
);
font-weight: 800;
}
.app-shell__content {
grid-area: content;
min-width: 0;
}
}
+161
View File
@@ -0,0 +1,161 @@
@layer components {
.page-header {
max-width: 50rem;
padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem;
}
[data-route-heading]:focus {
outline: none;
}
.page-header__eyebrow {
margin-block-end: 0.75rem;
color: var(--color-action);
font-size: 0.8rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.page-header__description {
max-width: 45rem;
color: var(--color-content-muted);
font-size: 1.05rem;
line-height: 1.7;
}
.page-template {
display: grid;
gap: 1.25rem;
min-width: 0;
}
.page-template__breadcrumb {
padding-block-start: 1rem;
color: var(--color-content-muted);
font-size: 0.9rem;
}
.page-template__heading {
display: grid;
min-width: 0;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
gap: 1rem;
}
.page-template__heading .page-header {
grid-row: span 2;
min-width: 0;
}
.page-template__status,
.page-template__actions,
.status-page__actions,
.form-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 0.75rem;
}
.page-template__layout {
display: grid;
min-width: 0;
gap: 1.5rem;
}
.page-template__layout[data-has-aside="true"] {
grid-template-columns: minmax(0, 1fr) minmax(14rem, 20rem);
}
.page-template__content,
.page-template__aside,
.collection-page__results,
.detail-page__sections,
.form-page__fields {
min-width: 0;
}
.page-template__aside,
.detail-page__metadata,
.collection-page__toolbar,
.form-error-summary {
border: 1px solid var(--color-border);
border-radius: var(--radius-surface);
padding: 1rem;
background: var(--color-panel);
}
.collection-page__toolbar,
.collection-page__active-filters,
.collection-page__bulk-actions {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 0.75rem;
}
.collection-page__result-count {
color: var(--color-content-muted);
}
.collection-page__results,
.detail-page__sections,
.form-page__fields,
.form-page__error-summary {
display: grid;
gap: 1rem;
}
.collection-page__pagination {
margin-block-start: 1.25rem;
}
.detail-page__danger {
margin-block-start: 2rem;
border-top: 1px solid var(--color-danger-border);
padding-block-start: 1rem;
}
.form-error-summary {
border-color: var(--color-danger-border);
background: var(--color-danger-surface);
}
.form-error-summary h2 {
font-size: 1.1rem;
}
.form-error-summary p,
.form-error-summary ul {
margin-block-end: 0;
}
.form-actions {
padding-block-start: 1rem;
border-top: 1px solid var(--color-border);
}
.form-actions--sticky {
position: sticky;
z-index: 10;
bottom: 0;
padding: 0.75rem;
background: color-mix(in oklch, var(--color-panel) 94%, transparent);
}
.status-page {
max-width: 48rem;
padding-block: 2rem;
}
.status-page__actions {
justify-content: flex-start;
}
.status-page__support {
color: var(--color-content-muted);
}
}
+28 -13
View File
@@ -2,6 +2,11 @@ import type { ReactNode } from "react";
import { PageHeader } from "../components/page-header.tsx";
import { Button } from "../components/ui/button.ts";
import {
LinkButton,
type LinkTarget,
} from "../design-system/primitives/core.tsx";
import { PaginationLandmarkContext } from "../design-system/primitives/navigation.tsx";
import { useLocale } from "../i18n/index.ts";
export type PageHeading = Readonly<{
@@ -18,12 +23,12 @@ export type PageActionDefinition =
disabled?: boolean;
variant?: "primary" | "secondary" | "danger" | "ghost";
}>
| Readonly<{
| (Readonly<{
kind: "link";
label: string;
href: string;
variant?: "primary" | "secondary" | "danger" | "ghost";
}>;
}> &
LinkTarget);
export type PageTemplateSlots = Readonly<{
heading: PageHeading;
@@ -130,7 +135,9 @@ export function CollectionPage(
className="collection-page__pagination"
aria-label={message("template.pagination")}
>
{props.pagination}
<PaginationLandmarkContext.Provider value>
{props.pagination}
</PaginationLandmarkContext.Provider>
</nav>
) : null}
</StandardPage>
@@ -208,9 +215,12 @@ export function StatusPage(
secondaryAction?: PageActionDefinition;
supportReference?: string;
className?: string;
children?: ReactNode;
headingNode?: ReactNode;
visualPolicy?: "platform" | "inherit";
/** Names the answer for tests and telemetry, e.g. `invalid-route`. */
surface?: string;
/** Extra content under the actions, such as a failure alert. */
children?: ReactNode;
}>,
) {
const { message } = useLocale();
@@ -227,6 +237,7 @@ export function StatusPage(
.filter(Boolean)
.join(" ")}
data-status-variant={props.variant}
data-surface={props.surface}
>
{props.headingNode ?? <PageHeader {...props.heading} />}
{props.primaryAction || props.secondaryAction ? (
@@ -239,6 +250,7 @@ export function StatusPage(
}
/>
) : null}
{props.children}
{props.supportReference ? (
<p className="status-page__support">
{message("template.supportReference", {
@@ -246,7 +258,6 @@ export function StatusPage(
})}
</p>
) : null}
{props.children}
</section>
);
}
@@ -257,19 +268,23 @@ function PageActionBar(props: Readonly<{
}>) {
return (
<div className={props.className ?? "page-template__actions"}>
{props.actions.map((action) =>
{/* Keyed by position: a label that changes while pending must not
remount the button the user just pressed. */}
{props.actions.map((action, index) =>
action.kind === "link" ? (
<a
className={`ui-button ui-button--${action.variant ?? "primary"}`}
href={action.href}
key={`${action.kind}:${action.label}`}
<LinkButton
{...(action.to === undefined
? { href: action.href }
: { to: action.to })}
key={index}
variant={action.variant}
>
{action.label}
</a>
</LinkButton>
) : (
<Button
disabled={action.disabled}
key={`${action.kind}:${action.label}`}
key={index}
onClick={action.onAction}
variant={action.variant}
>