import * as React from "react"; import { RECONNECT, SiteAdminApiError, isSessionExpired } from "../../client"; import { useSiteAdmin } from "../../context"; import { fill } from "../../lib/fill"; import { STATEMENT_PAGE } from "../../statement/layout"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "../../ui/alert-dialog"; import { Badge } from "../../ui/badge"; import { Button, buttonVariants } from "../../ui/button"; import { Checkbox } from "../../ui/checkbox"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "../../ui/card"; import { Notice } from "../../ui/notice"; import { OtpInput } from "../../ui/otp-input"; import { PageHeader } from "../../ui/page-header"; import { TextField } from "../../ui/text-field"; import type { WpClient } from "../client"; import { VerifyDomainButton, useVerifyDomain } from "../verifyDomain"; import { PLAN_PRODUCTS, type AccountDetails, type ConnectionRefusal, type ConnectionState, type SetupConfig, } from "./types"; const CODE_LENGTH = 6; /** The service's wait between two codes to one address. */ const RESEND_SECONDS = 60; /** Enough to refuse what cannot be an address; the code sent is the check. */ const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; type SetupMessages = ReturnType["messages"]["setup"]; /** A failed call, as the code the screen words it by. */ function refusalOf(err: unknown): ConnectionRefusal { if (!(err instanceof SiteAdminApiError)) return { code: "generic" }; const wait = err.details?.retryAfterSeconds; const kind = err.details?.kind; return { // No answer at all (the request never left the browser) reads as the // plugin's own `network_error`. code: err.code ?? (err.status ? "generic" : "network_error"), ...(typeof wait === "number" && wait > 0 ? { retryAfterSeconds: wait } : {}), ...(kind === "cooldown" || kind === "cap" ? { kind } : {}), ...(typeof err.details?.field === "string" ? { field: err.details.field } : {}), }; } /** * Whether a `rate_limited` wait is the minute after a code was sent, which * the resend button counts down, rather than the hourly cap on codes, which * no "we have just sent you a code" or seconds countdown describes. By the * service's `kind`; from the wait alone where an older service sent none. */ function isCooldown(refusal: ConnectionRefusal): boolean { if (!refusal.retryAfterSeconds) return false; return refusal.kind ? refusal.kind === "cooldown" : refusal.retryAfterSeconds <= RESEND_SECONDS; } /** The sentence for a refusal: by its code, never the server's English. */ function refusalText( refusal: ConnectionRefusal, errors: SetupMessages["errors"], vars: { email: string; domain: string }, ): string { if (refusal.code === "rate_limited") { return isCooldown(refusal) ? fill(errors.rate_limited, { seconds: refusal.retryAfterSeconds }) : errors.rate_limited_later; } // Own keys only: a code such as `constructor` is not one of ours. const known = Object.prototype.hasOwnProperty.call(errors, refusal.code) ? (errors as Record)[refusal.code] : undefined; return fill(known ?? errors.generic, vars); } /** Seconds left of a wait that ends at `until` (a `Date.now()` value). */ function useCountdown(until: number): number { const left = () => Math.max(0, Math.ceil((until - Date.now()) / 1000)); const [seconds, setSeconds] = React.useState(left); React.useEffect(() => { setSeconds(left()); if (until <= Date.now()) return; const timer = window.setInterval(() => { const now = left(); setSeconds(now); if (now === 0) window.clearInterval(timer); }, 1000); return () => window.clearInterval(timer); // eslint-disable-next-line react-hooks/exhaustive-deps -- `left` reads `until` alone }, [until]); return seconds; } export interface SetupPageProps { config: SetupConfig; client: WpClient; /** Leaves the page; the tests' seam. */ navigate?: (url: string) => void; } /** * The plugin's Setup screen: connect this WordPress site with the email of an * AccessiBit account and the code sent to it, without leaving wp-admin; and, * once connected, what the connection is, what the site's plan includes, and * the ways to re-read or end it. * * An address with no AccessiBit account gets one on the way: the right code * is followed by who to create it for. * * The browser flow stays, as a second way in for those who would rather sign * in on AccessiBit itself; a real form post, since it leaves for the * dashboard. */ export function SetupPage({ config, client, navigate = (url) => window.location.assign(url), }: SetupPageProps) { const { messages } = useSiteAdmin(); const t = messages.setup; const [connection, setConnection] = React.useState(config.connection); // Asked for from the connected state: the email step, to bind anew. const [reconnecting, setReconnecting] = React.useState( config.connection.connected && config.connection.pendingEmail !== "", ); const { links, flash } = config; const showConnect = !connection.connected || reconnecting; // Reconnect opens the email step and Cancel closes it: the focus follows, // to the field that appeared and back to the button that opened it. const reconnectButton = React.useRef(null); const [asked, setAsked] = React.useState(false); const closeReconnect = () => { setReconnecting(false); setAsked(false); // After the render that puts the button back. window.setTimeout(() => reconnectButton.current?.focus()); }; return (
{flash && ( {flash.link.label} ) : undefined } > {flash.text} )} {connection.connected && ( { setAsked(true); setReconnecting(true); }} onChange={setConnection} navigate={navigate} /> )} {showConnect && ( navigate( `${links.accessibility}${links.accessibility.includes("?") ? "&" : "?"}verify=1`, ) } /> )}
); } function ConnectCard({ connection, client, config, focusOnOpen = false, onCancel, onConnected, }: { connection: ConnectionState; client: WpClient; config: SetupConfig; /** Opened by a button press: its first field takes the focus. */ focusOnOpen?: boolean; /** Set while reconnecting: back to the connection as it is. */ onCancel?: () => void; onConnected: () => void; }) { const { messages, toast } = useSiteAdmin(); const t = messages.setup; const { domain } = connection; const { links, browserConnect } = config; const [email, setEmail] = React.useState(connection.pendingEmail); // The address a code is waiting for: the code step while there is one. const [sentTo, setSentTo] = React.useState(connection.pendingEmail); const [emailError, setEmailError] = React.useState(""); const [code, setCode] = React.useState(""); const [codeError, setCodeError] = React.useState(""); // Counts the codes refused: each one gets fresh, empty boxes. Emptying // `code` alone is not enough when the refusal lands in the same render as // the last digit, since the boxes would never see the value change. const [attempt, setAttempt] = React.useState(0); // The address has no AccessiBit account: the right code was refused with // `account_details_required`, and is sent again with who to create one for. const [needsAccount, setNeedsAccount] = React.useState(false); const [name, setName] = React.useState(""); const [company, setCompany] = React.useState(""); const [terms, setTerms] = React.useState(false); const [accountErrors, setAccountErrors] = React.useState<{ name?: string; company?: string; terms?: string; }>({}); const [refusal, setRefusal] = React.useState(null); const [busy, setBusy] = React.useState(null); // The wait before another code, and the address it holds for: the service // counts per address, so another one is not held back. const [resendAt, setResendAt] = React.useState(0); const [heldFor, setHeldFor] = React.useState(""); const wait = useCountdown(resendAt); const card = React.useRef(null); const focusFirst = (selector: string) => card.current?.querySelector(selector)?.focus(); // A field's error is tied to the field, which says it when the focus // arrives. Only where the focus is already on it (Enter pressed in it) would // nothing be heard: then, and only then, the live region below says it. const [sayError, setSayError] = React.useState(false); const focusField = (selector: string) => { const field = card.current?.querySelector(selector); setSayError(!field || document.activeElement === field); field?.focus(); }; // Counts the refusals of a code that are not about the code itself: the // boxes, disabled while it was checked, lost the focus to the page. const [refused, setRefused] = React.useState(0); React.useEffect(() => { if (focusOnOpen) focusFirst("input"); // eslint-disable-next-line react-hooks/exhaustive-deps -- once, when the card opens }, []); // A refused code hands the focus back to the first box, once the boxes // can take it again: they are disabled while the code is being checked. React.useEffect(() => { if (codeError && busy === null) { focusField('[data-slot="otp-input"] input'); } }, [codeError, busy]); // Any other refusal of a code (a role, a site, the network) is the notice's // to say; the focus, dropped when the boxes were disabled, goes back to the // first box, where the code typed is still there to send again. // The refusal and the boxes' return land in the same render. React.useEffect(() => { if (refused) focusFirst('[data-slot="otp-input"] input'); }, [refused]); const step = needsAccount ? "account" : sentTo ? "code" : "email"; // Moving between the steps hands the focus to the step's first field. const lastStep = React.useRef(step); React.useEffect(() => { if (lastStep.current === step) return; lastStep.current = step; focusFirst(step === "code" ? '[data-slot="otp-input"] input' : "input"); }, [step]); async function send(address: string, again: boolean) { setRefusal(null); setCodeError(""); setBusy("send"); try { const normalised = await client.connection.requestCode(address); setEmail(normalised); setSentTo(normalised); setCode(""); setResendAt(Date.now() + RESEND_SECONDS * 1000); setHeldFor(normalised); if (again) toast.success(t.code.resent); } catch (err) { const failed = refusalOf(err); if (failed.code === "invalid_email") { setEmailError(t.connect.emailInvalid); focusField("input"); } else { // The minute after a send is counted down on the resend button; the // hourly cap is not: an hour of seconds says nothing useful. if (isCooldown(failed)) { setResendAt(Date.now() + failed.retryAfterSeconds * 1000); setHeldFor(address.toLowerCase()); } setRefusal(failed); } } finally { setBusy(null); } } function submitEmail(event: React.FormEvent) { event.preventDefault(); if (busy) return; const address = email.trim(); if (!EMAIL_SHAPE.test(address)) { setEmailError(t.connect.emailInvalid); focusField("input"); return; } setEmailError(""); // Still inside the wait for this address: say so without asking again. // From the clock, not the countdown shown: that one is a render behind. const left = Math.ceil((resendAt - Date.now()) / 1000); if (left > 0 && address.toLowerCase() === heldFor) { setRefusal({ code: "rate_limited", retryAfterSeconds: left, kind: "cooldown", }); return; } void send(address, false); } async function verify(digits: string, account?: AccountDetails) { if (busy) return; if (digits.length < CODE_LENGTH) { setCodeError(t.code.incomplete); return; } setRefusal(null); setCodeError(""); setBusy("verify"); try { await client.connection.verifyCode(digits, account); onConnected(); } catch (err) { setBusy(null); const failed = refusalOf(err); if (failed.code === "account_details_required") { // Not a refusal to show: the next step. The code stays as typed, to // go again with the account's details. setNeedsAccount(true); } else if ( failed.code === "invalid_account" && (failed.field === "name" || failed.field === "company_name" || failed.field === "accepted_terms") ) { // One of the details, as AccessiBit holds them to its own limits: // said on its field, which takes the focus. const [errors, target] = failed.field === "name" ? [{ name: t.account.nameError }, "#accessibit-setup-name"] : failed.field === "company_name" ? [ { company: t.account.companyError }, "#accessibit-setup-company", ] : [{ terms: t.account.termsError }, "#accessibit-setup-terms"]; setAccountErrors(errors); focusField(target); } else if ( failed.code === "invalid_code" || failed.code === "no_pending_code" ) { // About the code itself (expired while the details were typed, say): // said on the field, which is emptied for the next try. setNeedsAccount(false); setCode(""); setAttempt((n) => n + 1); setCodeError(refusalText(failed, t.errors, { email: sentTo, domain })); } else { setRefusal(failed); setRefused((n) => n + 1); } } } function submitAccount(event: React.FormEvent) { event.preventDefault(); if (busy) return; const within = (value: string) => { const length = value.trim().length; return length >= 2 && length <= 100; }; const errors = { ...(within(name) ? {} : { name: t.account.nameError }), ...(within(company) ? {} : { company: t.account.companyError }), // The administrator's own tick: nothing is created without it. ...(terms ? {} : { terms: t.account.termsError }), }; setAccountErrors(errors); if (errors.name || errors.company) { focusField( errors.name ? "#accessibit-setup-name" : "#accessibit-setup-company", ); return; } if (errors.terms) { focusField("#accessibit-setup-terms"); return; } void verify(code, { name: name.trim(), companyName: company.trim(), acceptedTerms: true, }); } // Read out as it appears (`role="alert"`); the focus stays where it was. const refusalNotice = refusal && ( {isSessionRefusal(refusal) ? messages.common.errors.sessionExpired : refusalText(refusal, t.errors, { email: sentTo || email, domain })} ); return (

{fill( step === "account" ? t.account.title : connection.connected ? t.connect.reconnectTitle : step === "code" ? t.code.title : t.connect.title, { domain }, )}

{step === "account" ? fill(t.account.intro, { email: sentTo, domain }) : step === "code" ? fill(t.code.sentTo, { email: sentTo }) : t.connect.intro}
{refusalNotice} {/* Said here only where the focus did not move to the field: one that arrives there hears the error from the field itself. */}

{!sayError ? null : step === "account" ? (accountErrors.name ?? accountErrors.company ?? accountErrors.terms) : step === "email" ? emailError : codeError}

{step === "account" ? (
{ setName(event.target.value); if (accountErrors.name) { setAccountErrors((current) => ({ ...current, name: undefined, })); } }} /> { setCompany(event.target.value); if (accountErrors.company) { setAccountErrors((current) => ({ ...current, company: undefined, })); } }} />
{ setTerms(checked === true); if (accountErrors.terms) { setAccountErrors((current) => ({ ...current, terms: undefined, })); } }} className="mt-1" />

{t.connect.terms} {" · "} {t.connect.privacy}

{accountErrors.terms && (

{accountErrors.terms}

)}
) : step === "email" ? (
{ setEmail(event.target.value); if (emailError) setEmailError(""); }} /> {/* Said before the button: the click is the consent to contact AccessiBit about this site, and nothing leaves it before. */}
{onCancel && ( )}
) : (
{ event.preventDefault(); void verify(code); }} noValidate className="flex flex-col gap-4" > fill(t.code.digitLabel, { n, total })} disabled={busy === "verify"} className="max-w-sm" onChange={(next) => { setCode(next); if (codeError) setCodeError(""); // The last digit sends the code: nothing else is left to do. if (next.length === CODE_LENGTH && next !== code) { void verify(next); } }} />
)} {!connection.connected && step === "email" && ( {t.connect.freeScanText} )} {browserConnect && (

{t.connect.browserTitle}

{t.connect.browserText}

)}
); } const isSessionRefusal = (refusal: ConnectionRefusal) => refusal.code === "session_expired"; function ExternalLink({ href, children, }: { href: string; children: React.ReactNode; }) { const { messages } = useSiteAdmin(); return ( {children} {messages.common.labels.opensInNewTab} ); } function ConnectedCard({ connection, client, links, reconnecting, reconnectButton, onReconnect, onChange, navigate, }: { connection: ConnectionState; client: WpClient; links: SetupConfig["links"]; reconnecting: boolean; reconnectButton: React.Ref; onReconnect: () => void; onChange: (connection: ConnectionState) => void; navigate: (url: string) => void; }) { const { messages, toast, format } = useSiteAdmin(); const t = messages.setup; const c = t.connected; const { domain } = connection; const [busy, setBusy] = React.useState(null); const [confirming, setConfirming] = React.useState(false); // The question is opened by state, not by a trigger of the dialog's, so // the focus is handed back to the button that asked it by hand. const disconnectButton = React.useRef(null); const recheckButton = React.useRef(null); const [failure, setFailure] = React.useState(""); const verification = useVerifyDomain({ client, domain, onVerified: onChange, }); /** The words for a failed re-read or disconnect. */ const failureText = (err: unknown): string => { if (isSessionExpired(err)) return messages.common.errors.sessionExpired; if (err instanceof SiteAdminApiError && err.code === RECONNECT) { return err.message; } const failed = refusalOf(err); // Not the code step's "too many codes": nothing here asks for one. return failed.code === "rate_limited" ? t.errors.too_many_requests : refusalText(failed, t.errors, { email: "", domain }); }; async function recheck() { if (busy) return; setFailure(""); setBusy("recheck"); try { onChange(await client.connection.recheck()); toast.success(c.rechecked); } catch (err) { setFailure(failureText(err)); } finally { setBusy(null); } } async function disconnect() { if (busy) return; setFailure(""); setBusy("disconnect"); try { const outcome = await client.connection.disconnect(); // Reloaded, so PHP says what became of the key in its own words, and // every other screen of the plugin starts from the new state. navigate( `${links.setup}${links.setup.includes("?") ? "&" : "?"}disconnected=${encodeURIComponent(outcome)}`, ); } catch (err) { setBusy(null); setFailure(failureText(err)); } } const plan = connection.plan; return (

{c.title}

{failure && ( {failure} )} {connection.stale && ( {fill(c.staleText, { bound: connection.boundDomain, domain })} )} {!connection.stale && !connection.siteLinked && ( {c.addSite} } > {c.notLinkedText} )}
{c.account}
{/* The name; the slug where an older connection kept none. */} {connection.companyName || connection.companySlug} {c.connected}
{c.site}
{connection.stale ? connection.boundDomain : domain} {connection.siteLinked && !connection.stale && ( {connection.siteVerified ? c.verified : c.notVerified} )}
{connection.siteLinked && !connection.stale && !connection.siteVerified && (

{c.notVerifiedText} {connection.canVerifyDomain && ` ${t.verify.hint}`}

{verification.failure && ( {verification.failure} )} {connection.canVerifyDomain && (
{ if (ok) recheckButton.current?.focus(); }} />
)}
)} {plan && connection.siteLinked && !connection.stale && (

{t.plan.title}

    {PLAN_PRODUCTS.map((product) => { const entry = plan[product]; if (!entry) return null; const end = entry.status !== "none" && entry.periodEnd ? fill(t.plan.until, { date: format.date(entry.periodEnd, { dateStyle: "medium", }), }) : null; return (
  • {t.plan[product]} {entry.status !== "none" && entry.name && ( {" · "} {entry.name} )} {end && ( {end} )} {t.plan[entry.status]}
  • ); })}

{t.plan.seePlans}

)}
{!connection.stale && (

{c.recheckText}

)}
{/* Not on a copy of another site: re-reading would bind the copy to the original. Only a new connection may re-bind. */} {!connection.stale && ( )} {!reconnecting && ( )} {/* The question's own button is the red one: this only asks it. */}
{ event.preventDefault(); disconnectButton.current?.focus(); }} > {c.disconnectTitle} {c.disconnectText} {c.cancel} void disconnect()} > {c.disconnectConfirm}
); }