import * as React from "react"; import { useSiteAdmin } from "../../context"; import { STATEMENT_PAGE } from "../../statement/layout"; import { Button } from "../../ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "../../ui/card"; import { Notice } from "../../ui/notice"; import { PageHeader } from "../../ui/page-header"; import { Switch } from "../../ui/switch"; import type { WpClient } from "../client"; import type { ConnectionState } from "../setup/types"; import { VerifyDomainButton, useVerifyDomain, type DomainVerification, } from "../verifyDomain"; import { MAX_WAIT_MS, POLL_INTERVAL_MS, panelForRead, panelForStart, type FreeScanPanel, } from "./freeScan"; import type { AccessibilityConfig, AccessibilityStrings, SummaryData, } from "./types"; export interface AccessibilityPageProps { config: AccessibilityConfig; client: WpClient; /** The administrator's locale, for dates (`it-IT`). */ intlLocale: string; } /** * The plugin's Accessibility screen: the widget's switch, the domain's free * homepage scan, the figures of the site's latest full audit, and the way to * the screens where the widget and the statement are changed. * * Its words are the plugin's own (`config.strings`): the PHP view under it * draws the same screen when the app cannot run. */ export function AccessibilityPage({ config, client, intlLocale, }: AccessibilityPageProps) { const { strings: s, links } = config; const [connection, setConnection] = React.useState(config.connection); // Counts the re-reads of the account. The scan and the audit are read // again after each: a domain verified since, or a site registered since, // changes what they answer, and the PHP view reloaded the page for it. const [reads, setReads] = React.useState(0); const reread = (next: ConnectionState) => { setConnection(next); setReads((n) => n + 1); }; const verification = useVerifyDomain({ client, domain: connection.domain, onVerified: reread, }); // A connection just made (`verify=1`, from Setup or the browser flow): the // domain's verification is tried once, unasked, and shown as it would be // from the button: working, then verified or why not. const tried = React.useRef(false); React.useEffect(() => { if (tried.current) return; tried.current = true; const url = new URL(window.location.href); if (url.searchParams.get("verify") !== "1") return; // Once: a reload of this address must not try again. url.searchParams.delete("verify"); window.history.replaceState(window.history.state, "", url); if (connection.canVerifyDomain) void verification.verify(); }); // The scan's card is drawn anew after a re-read, the button that asked for // a verification with it: the focus then goes to the new card's heading. const focusScan = React.useRef(false); React.useEffect(() => { if (!focusScan.current) return; focusScan.current = false; document.getElementById("accessibit-free-heading")?.focus(); }, [reads]); return (
{connection.stale && ( {s.staleText} )} {!connection.siteLinked ? ( ) : ( <> {/* Not on a copy of another site: the scan and the audit figures would be the original's. */} {!connection.stale && ( <> { focusScan.current = true; }} onVerifyDone={(ok) => { if (!ok) focusScan.current = false; }} /> )}

{s.moreTitle}

{s.moreText}
)}
); } /** * "(opens in a new tab)", for a screen reader, after a link's words: in the * plugin's own words, like the rest of the screen. */ const NewTabContext = React.createContext(""); function NewTab() { return {React.useContext(NewTabContext)}; } function ExternalLink({ href, children, }: { href: string; children: React.ReactNode; }) { return ( {children} ); } function NotLinked({ connection, strings: s, links, }: { connection: ConnectionState; strings: AccessibilityStrings; links: AccessibilityConfig["links"]; }) { // A copy of another site says so above, and what to do about it. if (connection.stale) return null; return ( {connection.connected ? ( <> {/* Connected, but this address is not one of the account's sites: not "connect your account", which they have done. */}

{s.notRegistered}{" "} {s.addSite}

{s.afterAdding}

) : (

{s.notConnected}

)}
); } function WidgetCard({ connection, client, strings: s, links, onChange, }: { connection: ConnectionState; client: WpClient; strings: AccessibilityStrings; links: AccessibilityConfig["links"]; onChange: (connection: ConnectionState) => void; }) { const { messages, toast } = useSiteAdmin(); const [saving, setSaving] = React.useState(false); const id = React.useId(); async function set(enabled: boolean) { if (saving) return; setSaving(true); try { onChange(await client.connection.setWidget(enabled)); toast.success(s.saved); } catch (err) { console.error(err); toast.error(messages.common.errors.generic); } finally { setSaving(false); } } return (

{s.widgetTitle}

{!connection.widgetLicensed && ( // The switch does nothing for visitors without a licence, and // nothing else would say why. {s.seePlans} } > {s.widgetUnlicensed} )}
void set(checked)} aria-labelledby={`${id}-label`} aria-describedby={`${id}-note`} className="mt-0.5" />
{/* What turning it on means for visitors, beside the switch. */}

{s.widgetNote}

); } function FreeScanCard({ connection, client, strings: s, links, intlLocale, verification, onVerifyStart, onVerifyDone, }: { connection: ConnectionState; client: WpClient; strings: AccessibilityStrings; links: AccessibilityConfig["links"]; intlLocale: string; verification: DomainVerification; onVerifyStart: () => void; onVerifyDone: (ok: boolean) => void; }) { const t = s.freeScan; const [panel, setPanel] = React.useState({ message: s.freeChecking, issues: [], cta: {}, }); const heading = React.useRef(null); // Bumped by every start: an answer or a timer of an earlier run is dropped. const run = React.useRef(0); const timers = React.useRef([]); const formatDate = React.useCallback( (date: Date) => { // A tag `Intl` cannot parse must not cost the panel: the browser's own. try { return date.toLocaleDateString(intlLocale || undefined); } catch { return date.toLocaleDateString(); } }, [intlLocale], ); const later = (ms: number, fn: () => void) => { timers.current.push(window.setTimeout(fn, ms)); }; const clearTimers = () => { timers.current.forEach((timer) => window.clearTimeout(timer)); timers.current = []; }; const read = React.useCallback( async (attempts: number, mine: number) => { const result = await client.scan.freeScan(); if (run.current !== mine) return; const next = panelForRead(result, attempts, t, formatDate); setPanel(next); if (next.next === "poll") { later(POLL_INTERVAL_MS, () => void read(attempts + 1, mine)); } else if (next.next === "start") { void start(); } }, // eslint-disable-next-line react-hooks/exhaustive-deps -- `start` and `read` call each other [client, t, formatDate], ); const start = React.useCallback(async () => { const mine = ++run.current; clearTimers(); setPanel({ message: t.starting, issues: [], cta: {} }); const next = panelForStart(await client.scan.startFreeScan(), t); if (run.current !== mine) return; setPanel(next); if (next.next === "poll") { later(POLL_INTERVAL_MS, () => void read(0, mine)); } }, [client, t, read]); // Read before starting, so revisiting the screen costs one request and // never starts a scan again. React.useEffect(() => { const mine = ++run.current; void read(0, mine); return () => { run.current += 1; clearTimers(); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- once, when the card opens }, []); // The waiting state ends by itself: the same button becomes usable where // it is, and the status line keeps the failure it explained and adds that // the retry is back. const { retry, waitMs } = panel.cta; React.useEffect(() => { if (retry !== "waiting") return; const wait = Number(waitMs); if (!Number.isFinite(wait) || wait <= 0 || wait > MAX_WAIT_MS) return; const timer = window.setTimeout(() => { setPanel((current) => current.cta.retry === "waiting" ? { ...current, message: current.message ? `${current.message} ${t.retryReady}` : t.retryReady, cta: { ...current.cta, retry: "enabled", waitMs: undefined }, } : current, ); }, wait); return () => window.clearTimeout(timer); }, [retry, waitMs, t.retryReady]); function onRetry() { if (panel.cta.retry !== "enabled") return; // The button is about to go: the focus moves to the panel's heading, // outside the live region, so "where you are" and "what is happening" // are said by two elements instead of competing on one. heading.current?.focus(); void start(); } const unavailable = retry === "spent" || retry === "waiting"; return (

{s.freeTitle}

{s.freeSubdir && {s.freeSubdir}} {!connection.siteVerified && ( {connection.canVerifyDomain && ( )} {s.verifyDomain} } > {s.freeUnverified} )} {verification.failure && ( {verification.failure} )} {/* Rendered with its first message already in it, and the only live region of the panel: the list and the buttons are found by reading on from it. */}

{panel.message}

{panel.issues.length > 0 && (
    {panel.issues.map((issue, index) => (
  • {/* The WCAG reference is always English; the message is in whatever language the service wrote it. Both are marked, so a screen reader reads each with the right voice. */} {issue.criteria || issue.code || ""} {issue.message && ( {" — "} {issue.message} )}
  • ))}
)} {(retry || panel.cta.buy) && (
{retry && ( )} {unavailable && ( {retry === "spent" ? t.retrySpent : t.retryWaiting} )} {panel.cta.buy && ( )}
)}
); } function AuditCard({ client, strings: s, links, intlLocale, }: { client: WpClient; strings: AccessibilityStrings; links: AccessibilityConfig["links"]; intlLocale: string; }) { const t = s.summary; const [summary, setSummary] = React.useState(null); React.useEffect(() => { let cancelled = false; void client.scan.summary().then((result) => { // Supplementary: a failed read draws nothing. if (!cancelled && result.ok) setSummary(result.data); }); return () => { cancelled = true; }; }, [client]); const count = (key: string) => Number(summary?.totals?.[key]) || 0; const score = summary?.complianceScore?.score; let date = ""; if (summary?.lastScanAt) { const when = new Date(summary.lastScanAt); try { date = when.toLocaleDateString(intlLocale || undefined); } catch { date = when.toLocaleDateString(); } } return (

{s.auditTitle}

{/* What these figures are and where they come from: a different scan from the homepage preview above. */} {s.auditText}
{/* The figures arrive after the page: said when they do. Nothing is drawn until there is an audit to describe, or its absence. */}
{summary && (summary.lastScanAt ? ( <>

{t.complianceScore}: {/* The WCAG compliance score, not the legacy `score`. */} {score != null ? `${Math.round(Number(score))}%` : "—"} {` · A ${count("A")} · AA ${count("AA")} · AAA ${count("AAA")} · ${t.errors} ${count("errors")}`}

{t.lastAudit.replace("%s", date)}

) : (

{t.neverScanned}

))}
); } function RecheckCard({ client, strings: s, onChange, }: { client: WpClient; strings: AccessibilityStrings; onChange: (connection: ConnectionState) => void; }) { const { messages, toast } = useSiteAdmin(); const [busy, setBusy] = React.useState(false); const [failure, setFailure] = React.useState(""); async function recheck() { if (busy) return; setBusy(true); setFailure(""); try { onChange(await client.connection.recheck()); // Says the round trip happened; which notices remain says what changed. toast.success(s.rechecked); } catch (err) { console.error(err); setFailure( (err instanceof Error && err.message) || messages.common.errors.generic, ); } finally { setBusy(false); } } return (

{s.recheckTitle}

{s.recheckText}
{failure && ( {failure} )}
); }