import * as React from "react"; import { SiteAdminApiError, isSessionExpired } from "../client"; import { useSiteAdmin } from "../context"; import { fill } from "../lib/fill"; import { Button } from "../ui/button"; import type { WpClient } from "./client"; import type { ConnectionState } from "./setup/types"; /** * Verifying the site's domain from WordPress itself: the plugin answers a * challenge AccessiBit then reads from the site's public address. One call * here; it comes back with the connection as it now stands. * * Shared by Setup and Accessibility, which both say when a domain is not * verified. The words are the dashboard dictionary's (`setup.verify`). */ export function useVerifyDomain({ client, domain, onVerified, }: { client: WpClient; domain: string; onVerified: (connection: ConnectionState) => void; }) { const { messages, toast } = useSiteAdmin(); const t = messages.setup; const [busy, setBusy] = React.useState(false); const [failure, setFailure] = React.useState(""); const running = React.useRef(false); /** The words for a verification that did not go through. */ const failureText = (err: unknown): string => { if (isSessionExpired(err)) return messages.common.errors.sessionExpired; const code = err instanceof SiteAdminApiError ? err.code : undefined; const status = err instanceof SiteAdminApiError ? err.status : undefined; switch (code) { case "verification_unreachable": case "verification_mismatch": case "domain_changed": return fill(t.verify.unreachable, { domain }); case "already_verified": return fill(t.errors.domain_claimed, { domain }); case "not_domain_root": return fill(t.verify.notRoot, { domain }); case "rate_limited": return t.errors.too_many_requests; case "network_error": return t.errors.network_error; default: // No answer at all: the request never left the browser. return code || status ? t.verify.failed : t.errors.network_error; } }; /** Resolves to whether the domain is now verified. */ async function verify(): Promise { if (running.current) return false; running.current = true; setBusy(true); setFailure(""); try { const next = await client.connection.verifyDomain(); onVerified(next); if (next.siteVerified) toast.success(t.verify.done); return next.siteVerified; } catch (err) { setFailure(failureText(err)); return false; } finally { running.current = false; setBusy(false); } } return { busy, failure, verify }; } export type DomainVerification = ReturnType; /** The button that starts it. Stays focusable while it works. */ export function VerifyDomainButton({ verification, onStart, onDone, }: { verification: DomainVerification; /** A press is starting a verification. */ onStart?: () => void; /** The verification this button started ended; `ok` when it went through. */ onDone?: (ok: boolean) => void; }) { const { messages } = useSiteAdmin(); const t = messages.setup.verify; return ( ); }