import * as React from "react"; import { EyeIcon } from "lucide-react"; import type { StatementAuditSnapshot } from "@accessibit/types"; import { RECONNECT, SiteAdminApiError, isSessionExpired } from "../client"; import { SiteAdminProvider, useSiteAdmin, type SiteAdminLinks, } from "../context"; import { useInputModality } from "../input-modality"; import type { SiteAdminMessages } from "../messages"; import { StatementPage } from "../statement/StatementPage"; import { TrackerPage } from "../tracker/TrackerPage"; import { Button } from "../ui/button"; import { CloseLabelProvider } from "../ui/close-label"; import { ComponentLabelsProvider } from "../ui/component-labels"; import { Notice } from "../ui/notice"; import { widgetSectionOf, type WidgetSection } from "../widget/sections"; import { WidgetAppearanceTab } from "../widget/WidgetAppearanceTab"; import { WidgetFrame } from "../widget/WidgetFrame"; import { WidgetSettingsProvider, useWidgetSettings, } from "../widget/WidgetSettingsProvider"; import { WidgetToolsTab } from "../widget/WidgetToolsTab"; import { AccessibilityPage } from "./accessibility/AccessibilityPage"; import { createWpClient, type WpClient } from "./client"; import { toBcp47, uiLocaleOf, type WpAdminConfig } from "./config"; import { createFormat } from "./format"; import { Notices, useNotices } from "./Notices"; import { SetupPage } from "./setup/SetupPage"; import { Shell } from "./Shell"; import { WpWidgetPreview } from "./WpWidgetPreview"; /** * The widget page's tabs, as `#/appearance` and `#/tools`: a plain link * moves between them without reloading wp-admin, and Back goes to the last. * WordPress has no status tab: the plugin puts the widget on the site itself, * and the plan is the dashboard's to show. */ const WIDGET_SECTIONS: readonly WidgetSection[] = ["appearance", "tools"]; /** * The widget's tabs are `#/tools`. The site's audits are in the dashboard, * whatever its Tracker tier: the plugin does not know it (ACC-411). */ const linksFor = (auditsUrl: string | undefined): SiteAdminLinks => ({ widget: () => "#", ...(auditsUrl ? { audits: () => auditsUrl } : {}), }); /** The plugin's shortcode, which prints the dashboard's embed (ACC-404). */ const STATEMENT_SHORTCODE = "[accessibit_statement]"; /** * Whether a hash is one of ours (`#/tools`, or none). wp-admin's own anchors * are not: its skip link sets `#wpbody-content`, which must not switch tabs. */ const isRouteHash = (hash: string) => hash === "" || hash.startsWith("#/"); /** The last route hash; any other hash leaves it as it was. */ function useLocationHash(): string { const [hash, setHash] = React.useState(() => isRouteHash(window.location.hash) ? window.location.hash : "", ); React.useEffect(() => { const onChange = () => { if (isRouteHash(window.location.hash)) setHash(window.location.hash); }; window.addEventListener("hashchange", onChange); return () => window.removeEventListener("hashchange", onChange); }, []); return hash; } /** * `expired`: the nonce went stale, and only reloading the page helps. * `reconnect`: the site's connection is gone, and only Setup helps (ACC-411). */ type LoadStatus = "loading" | "error" | "expired" | "reconnect" | "ready"; /** * Runs `fetcher` on mount, whenever `key` changes and on `retry`. `result` * keeps the last value through a reload, so a refresh never unmounts a page * that has already rendered. */ function useLoad(fetcher: () => Promise, key: unknown) { const [status, setStatus] = React.useState("loading"); const [result, setResult] = React.useState<{ value: T } | null>(null); const [attempt, setAttempt] = React.useState(0); React.useEffect(() => { let cancelled = false; setStatus("loading"); fetcher().then( (value) => { if (cancelled) return; setResult({ value }); setStatus("ready"); }, (err) => { console.error(err); if (cancelled) return; setStatus( isSessionExpired(err) ? "expired" : err instanceof SiteAdminApiError && err.code === RECONNECT ? "reconnect" : "error", ); }, ); return () => { cancelled = true; }; // `fetcher` is a fresh closure every render; `key` is what identifies it. // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, attempt]); const retry = React.useCallback(() => setAttempt((n) => n + 1), []); return { status, result, retry, retried: attempt > 0 }; } function LoadState({ status, retry, retried, }: { status: LoadStatus; retry: () => void; retried: boolean; }) { const { messages } = useSiteAdmin(); const retryButton = React.useRef(null); const alert = React.useRef(null); // The Retry button that was pressed is swapped out while loading, so a // retry that fails again hands focus to its replacement — or, with no // Retry left to offer, to the alert. React.useEffect(() => { if (!retried) return; if (status === "error") retryButton.current?.focus(); else if (status === "expired" || status === "reconnect") { alert.current?.focus(); } }, [status, retried]); if (status !== "error" && status !== "expired" && status !== "reconnect") { return (

{messages.common.actions.loading}

); } return (

{status === "expired" ? messages.common.errors.sessionExpired : status === "reconnect" ? messages.widget.saveErrors.reconnect : messages.common.errors.generic}

{status === "error" && ( )}
); } /** * Why the form is off. Not a role, so not the dashboard's Viewer notice: the * plugin opens a statement read-only when the site's plan no longer includes * it but one was published (ACC-404), and the dashboard is where that changes. */ function ReadOnlyNotice({ copy }: { copy: { title: string; body: string } }) { return ( {copy.body} ); } function WidgetScreen({ client, config, }: { client: WpClient; config: WpAdminConfig; }) { const { pathname } = useSiteAdmin(); const { result, ...load } = useLoad(() => client.widget.load(), client); if (!result) return ; const { previewUrl } = config; return ( {/* No read-only notice: the plugin opens the widget only for a site that licenses it, so this form is never off (ACC-404). */} ( ) : undefined } previewBeside > {widgetSectionOf(pathname, WIDGET_SECTIONS) === "tools" ? ( ) : ( )} ); } /** * Asks before the page is left with widget changes not saved (ACC-411): every * wp-admin link is a page load, and nothing else keeps them. The dashboard * routes within one page, so this is WordPress's alone. */ function LeaveGuard() { const { hasUnstoredChanges } = useWidgetSettings(); useLeaveGuard(hasUnstoredChanges); return null; } /** Asks before the page is left while `unsaved` (the widget's, the statement's). */ function useLeaveGuard(unsaved: boolean) { React.useEffect(() => { if (!unsaved) return; const ask = (event: BeforeUnloadEvent) => { event.preventDefault(); // Older browsers ask only when this is set. event.returnValue = ""; }; window.addEventListener("beforeunload", ask); return () => window.removeEventListener("beforeunload", ask); }, [unsaved]); } function StatementScreen({ client, config, refreshKey, }: { client: WpClient; config: WpAdminConfig; refreshKey: number; }) { const { notices, form } = useSiteAdmin().messages.statement; const embed = form.embed; // The screen with the most free text: ask before a wp-admin link drops it // (PR #1162 review), as the widget screen does. const [unsaved, setUnsaved] = React.useState(false); useLeaveGuard(unsaved); // Re-read after every save, which may have moved the pinned audit — the // dashboard does the same with `router.refresh()`. const { result, ...load } = useLoad( () => client.statements.auditSnapshot(), refreshKey, ); if (!result) return ; return ( <> {/* A failed refresh keeps the page on the last snapshot; say so. */} {(load.status === "error" || load.status === "expired" || load.status === "reconnect") && } ) } /> ); } /** * The Tracker screen (ACC-412): read on mount, and again after every pause or * resume, so the status shown is the one the server holds. */ function TrackerScreen({ client, config, }: { client: WpClient; config: WpAdminConfig; }) { const [reads, setReads] = React.useState(0); const { result, ...load } = useLoad(() => client.tracker.load(), reads); const links = config.trackerLinks; if (!result || !links) return ; return ( { try { await client.tracker.setMonitoring(enabled); } finally { // After a refusal too: a write that timed out here may still have // landed, and the status shown has to be the server's. setReads((n) => n + 1); } }} /> ); } /** Turns a render error into a message instead of an empty admin page. */ class RenderBoundary extends React.Component< { fallback: React.ReactNode; children: React.ReactNode; /** Told of the error it caught. */ onError?: (error: unknown) => void; }, { failed: boolean } > { state = { failed: false }; static getDerivedStateFromError() { return { failed: true }; } componentDidCatch(error: unknown) { this.props.onError?.(error); } render() { return this.state.failed ? this.props.fallback : this.props.children; } } /** * Says the page is on screen. Rendered inside the boundary, after the page: * a page that fails to render never commits, so this never runs for it. */ function Ready({ onReady }: { onReady?: () => void }) { React.useEffect(() => { onReady?.(); // eslint-disable-next-line react-hooks/exhaustive-deps -- once, after the first commit }, []); return null; } export function App({ config, messages, logo, onReady, onRenderError, frame, portal, }: { config: WpAdminConfig; messages: SiteAdminMessages; /** The AccessiBit logo, for the shell's brand line. */ logo: string; /** Called once the page is on screen, never for one that failed to render. */ onReady?: () => void; /** Called when the page failed to render and its error was caught. */ onRenderError?: (error: unknown) => void; /** Wraps the app and the portal; carries the input-modality mark. */ frame: HTMLElement; portal: HTMLElement; }) { useInputModality(() => frame); const { toast, notices, dismiss } = useNotices(); const sessionExpired = messages.common.errors.sessionExpired; const reconnect = messages.widget.saveErrors.reconnect; const client = React.useMemo( () => createWpClient(config, { sessionExpired, reconnect }), [config, sessionExpired, reconnect], ); const format = React.useMemo( () => createFormat(toBcp47(config.locale)), [config.locale], ); const pathname = useLocationHash(); const links = React.useMemo( () => linksFor(config.auditsUrl), [config.auditsUrl], ); const common = messages.common; // The few words the primitives say on their own, as the dashboard's // `Providers` gives them. const componentLabels = React.useMemo( () => ({ opensInNewTab: common.labels.opensInNewTab, valueOfMax: common.labels.valueOfMax, selectItem: common.labels.selectItem, search: common.actions.search, clear: common.actions.clear, noResults: common.labels.noResults, previousPage: common.labels.paginationPreviousPage, nextPage: common.labels.paginationNextPage, copy: common.actions.copy, copied: common.actions.copied, copyFailed: common.labels.copyFailed, sectionDone: common.labels.sectionDone, sectionTodo: common.labels.sectionTodo, }), [common], ); const [refreshKey, setRefreshKey] = React.useState(0); const refresh = React.useCallback(() => setRefreshKey((n) => n + 1), []); return ( {/* Setup and Accessibility open before there is a connected site, and say which address they are about themselves. */} {messages.common.errors.generic}

} > {config.page === "setup" && config.setup ? ( ) : config.page === "accessibility" && config.accessibility ? ( ) : config.page === "widget" ? ( ) : config.page === "tracker" ? ( ) : ( )}
); }