Repository Public
1"use client";2import type { UseQueryResult } from "@tanstack/react-query";3import type { ReactNode } from "react";4import type { Schemas } from "@/api/client";5import { ApiError } from "@/api/errors";6import { useI18n } from "@/i18n";7import { cx, type Tone } from "./cx";8import { Button, CopyButton, Skeleton, StateDot } from "./core";9import { Icon, type IconName } from "./Icon";10import { availabilityIcon, freshnessTone } from "./states";1112interface BoxProps {13 tone?: Tone;14 icon?: IconName;15 title: string;16 children?: ReactNode;17 actions?: ReactNode;18 meta?: ReactNode;19 compact?: boolean;20 role?: "status" | "alert";21}22function StateBox({ tone = "neutral", icon = "info", title, children, actions, meta, compact, role }: BoxProps) {23 return (24 <div className={cx("mcc-statebox", `tone-${tone}`, compact && "compact")} role={role}>25 <span className="icon"><Icon name={icon} size={17} /></span>26 <h3>{title}</h3>27 {children ? <p>{children}</p> : null}28 {meta ? <div className="meta">{meta}</div> : null}29 {actions ? <div className="row-wrap">{actions}</div> : null}30 </div>31 );32}3334/** Nothing to show yet: say why and what to do next. */35export function EmptyState({ icon = "info", title, children, actions, compact }: { icon?: IconName; title: string; children?: ReactNode; actions?: ReactNode; compact?: boolean }) {36 return <StateBox icon={icon} title={title} actions={actions} compact={compact ?? false}>{children}</StateBox>;37}3839/** Any failed request, mapped to the right explanation: 501, 503, 403 (naming the permission), network, other. */40export function ErrorState({ error, onRetry, compact }: { error: unknown; onRetry?: (() => void) | undefined; compact?: boolean }) {41 const { t } = useI18n();42 const e = error instanceof ApiError ? error : null;43 const correlation = e?.correlationId ? (44 <>45 <span>{t("errors.correlation")}</span>46 <code data-testid="correlation-id">{e.correlationId}</code>47 <CopyButton text={e.correlationId} label={t("errors.copyCorrelation")} />48 </>49 ) : null;50 const retry = onRetry ? <Button size="sm" icon="refresh" onClick={onRetry}>{t("common.retry")}</Button> : null;51 if (e?.notImplemented) {52 return <StateBox tone="stale" icon="clock" title={t("errors.notAvailable.title")} compact={compact ?? false} role="status" meta={<span data-testid="not-available">{t("errors.notAvailable.meta")}</span>} actions={retry}>{t("errors.notAvailable.body")}</StateBox>;53 }54 if (e?.unavailable) {55 return <StateBox tone="warning" icon="warning" title={e.code === "orchestrator_frozen" ? t("errors.frozen.title") : t("errors.unavailable.title")} compact={compact ?? false} role="alert" meta={correlation} actions={retry}>{e.code === "orchestrator_frozen" ? t("errors.frozen.body") : t("errors.unavailable.body")}</StateBox>;56 }57 if (e?.forbidden) {58 const perm = e.missingPermission;59 return (60 <StateBox tone="offline" icon="denied" title={t("errors.forbidden.title")} compact={compact ?? false} role="alert" meta={correlation}>61 <span data-testid="forbidden">{perm ? t("errors.forbidden.bodyPermission", { permission: perm }) : t("errors.forbidden.body")}</span>62 </StateBox>63 );64 }65 if (e?.network) {66 return <StateBox tone="warning" icon="offline" title={t("errors.network.title")} compact={compact ?? false} role="alert" actions={retry}>{t("errors.network.body")}</StateBox>;67 }68 if (e?.status === 404) {69 return <StateBox tone="neutral" icon="unknown" title={t("errors.notFound.title")} compact={compact ?? false} role="alert" meta={correlation}>{t("errors.notFound.body")}</StateBox>;70 }71 return (72 <StateBox tone="critical" icon="critical" title={t("errors.generic.title")} compact={compact ?? false} role="alert" meta={correlation} actions={retry}>73 {e ? `${e.message} (${e.code})` : t("errors.generic.body")}74 </StateBox>75 );76}7778/** Explains a 403 for a whole route when the permission is known from GET /me. */79export function ForbiddenState({ permission }: { permission: string }) {80 const { t } = useI18n();81 return <StateBox tone="offline" icon="denied" title={t("errors.forbidden.title")} role="alert"><span data-testid="forbidden">{t("errors.forbidden.bodyPermission", { permission })}</span></StateBox>;82}8384/** Short human message for a failed mutation (toasts, inline form errors). */85export function useErrorMessage(): (error: unknown) => { title: string; detail?: string } {86 const { t } = useI18n();87 return (error) => {88 if (!(error instanceof ApiError)) return { title: t("errors.generic.title") };89 const ref = error.correlationId ? t("errors.reference", { id: error.correlationId }) : undefined;90 const detail = [error.message, ref].filter(Boolean).join(" · ");91 if (error.notImplemented) return { title: t("errors.notAvailable.title"), detail: t("errors.notAvailable.body") };92 if (error.network) return { title: t("errors.network.title"), detail: t("errors.network.body") };93 if (error.forbidden) return { title: t("errors.forbidden.title"), detail: error.missingPermission ? t("errors.forbidden.bodyPermission", { permission: error.missingPermission }) : detail };94 if (error.code === "step_up_required") return { title: t("errors.stepUpCancelled") };95 if (error.code === "orchestrator_frozen") return { title: t("errors.frozen.title"), detail: t("errors.frozen.body") };96 if (error.unavailable) return { title: t("errors.unavailable.title"), detail };97 if (error.status === 429) return { title: t("errors.rateLimited"), detail };98 return { title: t("errors.requestFailed"), detail };99 };100}101102export function Banner({ tone, icon, children, actions, role = "status" }: { tone: Tone; icon?: IconName; children: ReactNode; actions?: ReactNode; role?: "status" | "alert" }) {103 return (104 <div className={cx("mcc-banner", `tone-${tone}`)} role={role}>105 <Icon name={icon ?? (tone === "critical" ? "critical" : tone === "warning" ? "warning" : tone === "stale" ? "stale" : tone === "offline" ? "offline" : "info")} size={16} />106 <div className="grow">{children}</div>107 {actions}108 </div>109 );110}111112/** Data on screen is older than it should be (refetch failing, stream down, source stale). */113export function StaleBanner({ since, onRetry, reason }: { since?: number | string | undefined; onRetry?: (() => void) | undefined; reason?: string }) {114 const { t, fmt } = useI18n();115 return (116 <Banner tone="stale" actions={onRetry ? <Button size="sm" icon="refresh" onClick={onRetry}>{t("common.refresh")}</Button> : null}>117 {reason ?? t("ui.stale.body")} {since ? <span className="num">{t("ui.stale.since", { time: fmt.time(since) })}</span> : null}118 </Banner>119 );120}121122export function FreshnessBadge({ freshness, subtle }: { freshness: Schemas["Freshness"]; subtle?: boolean }) {123 const { t } = useI18n();124 return <StateDot tone={freshnessTone(freshness)} label={t(`states.freshness.${freshness}`)} subtle={subtle ?? false} />;125}126127/** Timestamp + freshness of a data view. */128export function DataStamp({ at, freshness, label }: { at?: string | number | undefined; freshness?: Schemas["Freshness"] | undefined; label?: string }) {129 const { t, fmt } = useI18n();130 return (131 <span className="mcc-stamp" data-testid="data-stamp">132 {freshness ? <FreshnessBadge freshness={freshness} subtle /> : null}133 {at ? <time dateTime={new Date(at).toISOString()} title={fmt.dateTime(at, { seconds: true })} className="num">{label ?? t("ui.stamp.updated")} {fmt.time(at)}</time> : <span>{t("ui.stamp.never")}</span>}134 </span>135 );136}137138/** A value that could not be measured: explicit state with its reason, never 0 and never blank. */139export function Unmeasured({ availability, reason }: { availability: Exclude<Schemas["Availability"], "available"> | "not_observed"; reason?: string | undefined }) {140 const { t } = useI18n();141 const label = t(`states.availability.${availability}`);142 return (143 <span className="mcc-unmeasured" title={reason} data-availability={availability}>144 <Icon name={availability === "not_observed" ? "unknown" : availabilityIcon(availability)} size={13} />145 {label}146 {reason ? <span className="sr-only"> — {reason}</span> : null}147 </span>148 );149}150151/** Renders a MetricValue from the API: the formatted value, or its availability state. */152export function MetricValueView({ metric, fallbackUnit }: { metric: Schemas["MetricValue"] | undefined; fallbackUnit?: string }) {153 const { fmt } = useI18n();154 if (!metric) return <Unmeasured availability="not_observed" />;155 if (metric.value === undefined || (metric.availability !== "available" && metric.availability !== "stale")) {156 return <Unmeasured availability={metric.availability === "available" ? "unavailable" : metric.availability} reason={metric.reason} />;157 }158 return <span className="num">{fmt.metric(metric.value, metric.unit ?? fallbackUnit)}</span>;159}160161/** Optional value from the API: formatted when present, "not observed" otherwise. */162export function Observed<T>({ value, children }: { value: T | undefined | null; children: (v: T) => ReactNode }) {163 if (value === undefined || value === null) return <Unmeasured availability="not_observed" />;164 return <>{children(value)}</>;165}166167interface BoundaryProps<T> {168 query: UseQueryResult<T, ApiError>;169 children: (data: T) => ReactNode;170 skeleton?: ReactNode;171 compact?: boolean;172}173/**174 * Standard rendering of a query: skeleton while loading, explicit error state (501 / 503 / 403 / network), data175 * otherwise. When a refetch fails but earlier data exists, the data stays on screen under a stale banner.176 */177export function QueryBoundary<T>({ query, children, skeleton, compact }: BoundaryProps<T>) {178 const { t } = useI18n();179 if (query.data !== undefined) {180 return (181 <>182 {query.isError ? <StaleBanner since={query.dataUpdatedAt} onRetry={() => void query.refetch()} reason={t("ui.stale.refetchFailed")} /> : null}183 {children(query.data)}184 </>185 );186 }187 if (query.isError) return <ErrorState error={query.error} onRetry={() => void query.refetch()} compact={compact ?? false} />;188 return <>{skeleton ?? <div className="stack" role="status" aria-label={t("common.loading")}><Skeleton width="40" /><Skeleton width="80" /><Skeleton width="60" /></div>}</>;189}190191export function LoadMore({ hasMore, loading, onMore }: { hasMore: boolean; loading: boolean; onMore: () => void }) {192 const { t } = useI18n();193 if (!hasMore) return null;194 return <div className="row"><Button onClick={onMore} loading={loading} icon="chevron-down">{t("common.loadMore")}</Button></div>;195}196