import * as React from "react"; import { ExternalLinkIcon, PauseIcon, PlayIcon } from "lucide-react"; import { SCANNER_SOURCE_IP, TRACKER_TIER_NAMES } from "@accessibit/types"; import { RECONNECT, SESSION_EXPIRED, SiteAdminApiError } from "../client"; import { useSiteAdmin } from "../context"; import { fill } from "../lib/fill"; import { STATEMENT_PAGE } from "../statement/layout"; import { Badge, type BadgeProps } from "../ui/badge"; import { Button } from "../ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"; import { renderLink } from "../ui/data-slots"; import { EmptyState } from "../ui/empty-state"; import { Notice } from "../ui/notice"; import { PageHeader } from "../ui/page-header"; import type { TrackerLinks, TrackerRunView, TrackerView } from "./types"; /** * How many checks in a row fail before the Tracker pauses a site: the * dashboard's `MAX_CONSECUTIVE_FAILURES`, which the "failures" pause names. */ const PAUSE_AFTER_FAILURES = 3; /** * Why a pause/resume was refused, as the words to show and whether the * remedy is reconnecting the site (ACC-412). A refusal about who is acting — * the approver gone, their access gone, a key that only reads — is never the * generic error: the admin can fix it, and the screen says how. */ export type SwitchRefusal = { title?: string; text: string; reconnect: boolean; }; type Messages = ReturnType["messages"]; export function switchRefusal( err: unknown, t: Messages["tracker"]["plugin"]["errors"], ): SwitchRefusal { const apiError = err instanceof SiteAdminApiError ? err : null; // The WordPress client folds a refused key into RECONNECT, keeping the // server's code in `details`, and a stale nonce into SESSION_EXPIRED, with // the sentence to show as the message. const code = apiError?.code === RECONNECT && apiError.details?.code === "site_key_required" ? "site_key_required" : apiError?.code; switch (code) { case "connect_owner_left": return { title: t.connectOwnerLeftTitle, text: t.connectOwnerLeft, reconnect: true, }; case "connect_owner_lost_access": return { title: t.connectOwnerLostAccessTitle, text: t.connectOwnerLostAccess, reconnect: true, }; case "site_key_required": return { title: t.siteKeyRequiredTitle, text: t.siteKeyRequired, reconnect: true, }; case RECONNECT: return { text: apiError?.message || t.generic, reconnect: true }; case SESSION_EXPIRED: return { text: apiError?.message || t.generic, reconnect: false }; case "tracker_not_active": return { text: t.notActive, reconnect: false }; case "tracker_no_monitoring": return { text: t.noMonitoring, reconnect: false }; case "site_not_verified": return { text: t.notVerified, reconnect: false }; case "tracker_not_started": return { text: t.notStarted, reconnect: false }; default: return { text: t.generic, reconnect: false }; } } type Tone = NonNullable; /** * A run's result in the dashboard history's words and tones * (`TrackerRunsTable`), or null when there is no outcome to name. */ export function verdictBadge( run: TrackerRunView, isFirstCheck: boolean, t: Messages["tracker"]["history"], count: (n: number) => string, ): { tone: Tone; label: string } | null { if (run.trigger === "audit") { return { tone: "neutral", label: run.status === "failed" ? t.verdict.auditFailed : t.verdict.audit, }; } if (run.status === "failed") return { tone: "error", label: t.failedBadge }; if (run.verdict === "baseline") { return isFirstCheck ? { tone: "info", label: t.verdict.baseline } : { tone: "neutral", label: t.verdict.rebaseline }; } const regressions = run.newIssues?.count ?? 0; if (regressions > 0) { return { tone: "warning", label: fill( regressions === 1 ? t.verdict.regressionOne : t.verdict.regressionOther, { count: count(regressions) }, ), }; } if (run.verdict === "improvement") { return { tone: "success", label: t.verdict.improvement }; } if (run.verdict === "uncomparable") { return { tone: "neutral", label: t.verdict.uncomparable }; } if (run.verdict === null) return null; return { tone: "neutral", label: t.verdict.clean }; } function runHref(links: TrackerLinks, jobId: string): string { return `${links.tracker.replace(/\/$/, "")}/${encodeURIComponent(jobId)}`; } /** The new problems of a run: by severity, then the pages they are on. */ function NewIssues({ run }: { run: TrackerRunView }) { const { messages, format } = useSiteAdmin(); const t = messages.tracker.plugin; const r = messages.tracker.run; const found = run.newIssues; if (!found) return ; if (found.count === 0) return <>{t.noNewIssues}; const parts = [ [found.errors, r.newErrorsOne, r.newErrors], [found.warnings, r.newWarningsOne, r.newWarnings], [found.notices, r.newNoticesOne, r.newNotices], ] .filter(([n]) => (n as number) > 0) .map(([n, one, other]) => n === 1 ? (one as string) : fill(other as string, { n: format.count(n as number) }), ); const more = found.pageCount - found.pages.length; return (
{/* The severities are unknown on a check closed before their ids were kept: the count alone, as the dashboard's box says it. */}

{parts.length > 0 ? parts.join(", ") : format.count(found.count)}

{found.pages.length > 0 && (

{fill(r.newOn, { pages: found.pages.join(", ") })} {more > 0 && ` ${ more === 1 ? t.morePagesOne : fill(t.morePagesOther, { count: format.count(more) }) }`}

)}
); } function Fact({ label, children, }: { label: string; children: React.ReactNode; }) { return (
{label}
{children}
); } /** The site has no Tracker: only the way to activate it (ACC-412). */ function TrackerInactive({ domain, links, }: { domain: string; links: TrackerLinks; }) { const { messages } = useSiteAdmin(); const t = messages.tracker.plugin; return ( ); } export interface TrackerPageProps { domain: string; view: TrackerView; links: TrackerLinks; /** Pause (`false`) or resume (`true`); rejects with the API's error. */ onSetMonitoring: (enabled: boolean) => Promise; } /** * The WordPress plugin's Tracker screen (ACC-412): read-mostly. The status * and why it is paused, the next check, the latest result and the recent * checks with what each found new; pause and resume; and links to the * dashboard for everything else — triage, a run's report, comparisons, * rescans, pages, notifications and subdomains. */ export function TrackerPage({ domain, view, links, onSetMonitoring, }: TrackerPageProps) { const { messages, format, toast } = useSiteAdmin(); const t = messages.tracker.plugin; const status = messages.tracker.status; const history = messages.tracker.history; const [switching, setSwitching] = React.useState(null); const [refusal, setRefusal] = React.useState(null); const refusalRef = React.useRef(null); React.useEffect(() => { if (refusal) refusalRef.current?.focus(); }, [refusal]); const header = ( ); if (!view.active) { return (
{header}
); } const schedule = view.schedule; const latest = view.runs[0] ?? null; const isFirst = (index: number) => index === view.runs.length - 1 && view.totalRuns === view.runs.length; async function toggle(enabled: boolean) { setSwitching(enabled); setRefusal(null); try { await onSetMonitoring(enabled); toast.success(enabled ? t.resumedToast : t.pausedToast); } catch (err) { setRefusal(switchRefusal(err, t.errors)); } finally { setSwitching(null); } } const pause = schedule && !schedule.enabled ? (schedule.pauseReason ?? "other") : null; const pauseCopy = pause ? status.pause[pause] : null; return (
{header} {refusal && (
{refusal.text}
)}

{t.statusTitle}

{!view.monitoring ? ( {t.starterText} ) : ( <>
{!schedule ? status.noSchedule : schedule.enabled ? status.active : status.paused} {schedule?.running && ( {t.running} )}
{pauseCopy && pause && (

{fill(pauseCopy.text, { domain })}

{pause === "target_refused" && (

{status.pause.scannerIp}: {SCANNER_SOURCE_IP}

)}
)} )}
{TRACKER_TIER_NAMES[view.tier] ?? view.tier} {view.monitoring && schedule?.frequency && ( {status.frequency[schedule.frequency]} )} {view.monitoring && ( {!schedule ? status.nextCheckUnknown : !schedule.enabled ? status.nextCheckPaused : schedule.nextRunAt ? format.date(schedule.nextRunAt) : status.nextCheckUnknown} )}
{view.monitoring && schedule && (
{schedule.enabled ? ( ) : ( )}
)}

{t.lastRunTitle}

{!latest ? (

{history.empty}

) : (
{format.date(latest.date)}
)}
{view.runs.length > 0 && (

{t.runsTitle}

{view.runs.map((run, index) => { const date = format.date(run.date); return ( ); })}
{fill(t.runsCaption, { domain })}
{t.dateHeader} {t.resultHeader} {t.scoreHeader} {t.newHeader} {t.openRun}
{date} {run.trigger === "on_demand" && ( {history.onDemand} )} {run.score === null ? t.noScore : `${run.score}%`} {t.openRun}
{renderLink({ label: fill(t.allChecks, { count: format.count(view.totalRuns) }), href: links.tracker, external: true, })}
)}

{t.moreTitle}

{t.moreText}

    {[ { label: t.openTracker, href: links.tracker }, ...(view.monitoring ? [ { label: t.notifications, href: links.notifications }, { label: t.pages, href: links.pages }, ] : []), ...(view.subdomains ? [{ label: t.subdomains, href: links.subdomains }] : []), ].map((link) => (
  • {renderLink({ ...link, external: true })}
  • ))}
); } function RunResult({ run, isFirst, }: { run: TrackerRunView; isFirst: boolean; }) { const { messages, format } = useSiteAdmin(); const badge = verdictBadge( run, isFirst, messages.tracker.history, format.count, ); if (!badge) return ( ); return {badge.label}; }