"use client"; import * as React from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { CloudUploadIcon, EyeIcon, Loader2Icon, RefreshCwIcon, } from "lucide-react"; import { STATEMENT_LOCALES, isStatementLocale, missingTemporaryColumns, type NewerStatementResult, type StatementAuditSnapshot, type StatementLocale, type TemporaryStatementView, } from "@accessibit/types"; import { SiteAdminApiError, isSessionExpired, type StatementPayload, type StatementPreviewInput, } from "../client"; import { errorText } from "./errorText"; import { useSiteAdmin } from "../context"; import { todayISO } from "../lib/dates"; import { fill as fillTpl, fillFor } from "../lib/fill"; import { STATEMENT_TOUR_ANCHORS } from "../tour"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "../ui/alert-dialog"; import { Button } from "../ui/button"; import { UiLink } from "../ui/link"; import { Notice } from "../ui/notice"; import { PageHeader } from "../ui/page-header"; import type { StatementFormController } from "./formController"; import { STATEMENT_PAGE } from "./layout"; import type { StatementSite } from "./site"; import { LATEST_AUDIT, type StatementAuditOption, } from "./StatementAuditSelect"; import { StatementEmbedPanel, StatementEmbedPlaceholder, type StatementEmbedCode, } from "./StatementEmbedPanel"; import { StatementFacts } from "./StatementFacts"; import { StatementFormCard } from "./StatementFormCard"; import { StatementNewerResultNotice } from "./StatementNewerResultNotice"; import { ANSWER_REASONS, EMPTY_ARTIFACTS, PAST_ONLY_DATE_FIELDS, PRIMARY_LOCALE, REQUIRED_FIELD_IDS, TEMPORARY_FIELD_IDS, blankLocalized, computeArtifacts, formToPayload, formToStatementData, futureDateFields, localeWithLegacyText, missingRequiredFields, normalizeStatus, splitName, statementToForm, type LocalizedDraft, type PastOnlyDateField, type RequiredField, type StatementArtifacts, type StatementForm, type StatementStatus, } from "./statementForm"; import { StatementPhoneBar } from "./StatementPhoneBar"; import { StatementPreviewCard, StatementPreviewDialog, } from "./StatementPreview"; import { STATEMENT_SECTIONS, sectionOfFieldId, sectionStatuses, sectionsToOpen, type StatementSection, } from "./statementSections"; import { statementState } from "./statementState"; import { TemporaryStatementCard, TemporaryStatementPlanNotice, } from "./TemporaryStatementCard"; // The Statement page (ACC-540): the facts on top, the form in six sections // beside the preview of the document, and what to paste on the site under // them. This file holds the page's state and its one action (save, then // generate); what each part looks like is in the files beside it. Everything // it reads and writes goes through the host's client (`SiteAdminClient`). const POLL_INTERVAL_MS = 2500; const MAX_POLL_ATTEMPTS = 120; /** * How long the form has to sit still before the preview re-renders. Short * enough to feel live, long enough that typing a sentence costs one reload * rather than one per character. React only writes `srcdoc` when the rendered * string actually differs, so an edit that leaves the document unchanged * (typing and deleting back) never reloads it at all. */ const PREVIEW_DEBOUNCE_MS = 400; /** The reader asked the system for less motion: no animated scrolling. */ const prefersReducedMotion = (): boolean => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true; /** The browser is showing the focus ring on it: the keyboard is in use. */ const showsFocusRing = (element: Element): boolean => { try { return element.matches(":focus-visible"); } catch { // A browser without the selector: show the focus rather than hide it. return true; } }; /** The focus is on nothing: what had it left the page, or was disabled. */ const focusIsLost = (): boolean => !document.activeElement || document.activeElement === document.body; /** * The page's title as a place the focus can be put: not in the tab order, * and with the ring every focused thing has when the keyboard is in use. */ const TITLE_FOCUS = // `scroll-mt-8`: scrolled to, it keeps the page's own 32px above it, so // the ring is whole and the page is at its top. "focus-visible:outline-ring scroll-mt-8 rounded-sm outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid"; // ─── Main page ──────────────────────────────────────────────────────────────── export interface StatementPageProps { site: StatementSite; companyName: string | null; /** Authenticated user's full name (free-form). Used to pre-fill the * first/last name fields by splitting on the first whitespace. */ userName: string | null; /** Authenticated user's email. Used to pre-fill the feedback email. */ userEmail: string | null; auditSnapshot: StatementAuditSnapshot | null; /** * A result newer than the one the published statement declares (ACC-571), * computed by the host's server (the dashboard's `statementNewerResult.ts`): * the run publishing again would declare, and the one the published * statement declares. Null when there is none, when it is not known — a * statement generated before the source was recorded — and where the host * does not compute it (WordPress): the notice is not shown. */ newerResult?: NewerStatementResult | null; /** * The site's temporary statement (ACC-504), computed by the host's server. * Null or absent on a plan without it (anything but Business and * Enterprise), and where the host has none to offer (WordPress): the card * is not shown at all. */ temporary?: TemporaryStatementView | null; /** * The site's plan as the customer bought it ("Business"), which the notice * under the page names once the year's temporary statement is spent. */ planName?: string | null; /** * False when the server refuses saving, generating and publishing (a * dashboard reader, ACC-540; a WordPress key that may not save): the page * shows the statement with its form switched off and no button that * writes. */ canEdit?: boolean; /** * What stands on top, saying why the page cannot be changed: the host's * words — the dashboard's Viewer notice (`StatementReaderNotice`), a * plan that ended (`StatementEndedNotice`, ACC-540, D4), or WordPress's * key that may not save. */ notice?: React.ReactNode; /** * The plan's end took the statement off the site (ACC-516): the page says * nothing is online and offers no code to paste, which would show nothing. */ withdrawn?: boolean; /** The host's own embed in place of the iframe snippet (WordPress's * shortcode). */ embedCode?: StatementEmbedCode; /** * Told whether the form holds changes the last load or save did not store, * so a host whose links are page loads (WordPress) can ask before leaving. */ onUnsavedChange?: (unsaved: boolean) => void; } /** * The label of each field the statement may require, as the notice above the * form names what is missing. A `Record`, so a field made required without a * name here fails the build. */ const REQUIRED_FIELD_LABELS = { orgName: "orgName", firstName: "firstName", lastName: "lastName", contactEmail: "contactEmail", siteCMS: "siteCmsLabel", sitePublicationDate: "sitePublicationDate", statementDate: "statementDate", employeesWithDisabilities: "employeesWithDisabilities", workstationsForDisabilities: "workstationsForDisabilities", lawNonComplianceReason: "lawNonComplianceReason", disproportionateBurdenReason: "disproportionateBurdenReason", outOfScopeContentReason: "outOfScopeContentReason", } as const satisfies Record; /** What a required field says when it is blank, where the board says more * than "required". */ const REQUIRED_FIELD_ERRORS = { siteCMS: "siteCmsRequired", sitePublicationDate: "sitePublicationDateRequired", statementDate: "statementDateRequired", } as const satisfies Partial>; /** The elements with these ids, first on the page first. */ function inPageOrder(ids: readonly string[]): HTMLElement[] { return ids .map((id) => document.getElementById(id)) .filter((el): el is HTMLElement => el !== null) .sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1, ); } export function StatementPage({ site, companyName, userName, userEmail, auditSnapshot, newerResult = null, temporary = null, planName = null, canEdit = true, notice = null, withdrawn = false, embedCode, onUnsavedChange, }: StatementPageProps) { const { client, messages, locale: lang, toast, format, refresh, links, } = useSiteAdmin(); const statementDict = messages.statement; const formDict = statementDict.form; const temporaryDict = statementDict.temporary; const sessionExpiredText = messages.common.errors.sessionExpired; /** * The site's address exactly as the `Website.url` column records it — which * `sanitizeDomain` has already reduced to a bare hostname. Generation reads * that same column (there is no site-URL column on `Statement` at all), so * anything composed here (`https://${domain.name}` was the previous value) * makes the preview print one string in the scope line and the site-name row * while the published document prints another. The column wins: it is the * record of record, and it is what every already-published artifact carries. */ const siteUrl = site.url; /** * Which audit the statement declares (ACC-388). Seeded from the STORED pin * (`pinnedJobId`), not from the run the snapshot resolved to: those differ * exactly when the pin fell back, and in that case the picker must not show * a dangling id — it drops to "latest" and the amber banner explains why. * When nothing is pinned the sentinel keeps it on "latest", which is what * the server did anyway. */ const [selectedAuditJobId, setSelectedAuditJobId] = useState( auditSnapshot?.pinnedJobId && !auditSnapshot.pinnedFallback ? auditSnapshot.pinnedJobId : LATEST_AUDIT, ); const [auditOptions, setAuditOptions] = useState([]); useEffect(() => { let cancelled = false; client.statements.auditOptions(site.id).then( (options) => { if (!cancelled) setAuditOptions(options); }, () => { // The picker degrades to "latest only" — the same behaviour the page // had before it existed. Never worth breaking the page for. }, ); return () => { cancelled = true; }; }, [client, site.id]); // The language the page is being read in — the working language starts // here purely as a convenience. It has no bearing on what gets published: // every statement is generated in all three languages, and PRIMARY_LOCALE // decides which one an unmatched visitor receives. const initialLocale = isStatementLocale(lang) ? lang : PRIMARY_LOCALE; // `orgName` seeds from the user's company name; any non-empty value already // saved in the statement overrides it via `statementToForm` fallback // semantics. const defaultForm = useMemo(() => { const { first, last } = splitName(userName); return { orgName: companyName ?? "", firstName: first, lastName: last, contactEmail: userEmail ?? "", entityType: "private", websiteUrl: siteUrl, siteCMS: "", sitePublicationDate: "", conformanceLevel: "wcag21aa", statementDate: todayISO(), employeesWithDisabilities: "", workstationsForDisabilities: "", includePdfDisclaimer: false, lawNonCompliance: false, disproportionateBurden: false, outOfScopeContent: false, usabilityTestsPerformed: false, localized: blankLocalized(), }; }, [companyName, userName, userEmail, siteUrl]); const [form, setForm] = useState(defaultForm); // The form as last loaded or saved: what leaving would not lose. Null // until the first load answers. const [storedForm, setStoredForm] = useState(null); // Which language the free-text fields are being edited under, and which // language the preview renders. One control drives both: the document is // published in all three regardless, so this is a view of the work, not a // property of the statement. const [activeLocale, setActiveLocale] = useState(initialLocale); const [statementId, setStatementId] = useState(null); const [statementStatus, setStatementStatus] = useState("draft"); const [artifacts, setArtifacts] = useState(EMPTY_ARTIFACTS); const [isLoading, setIsLoading] = useState(true); /** * The statement could not be read (ACC-540). The page says so and offers * nothing that saves: a blank form saved over a statement the page has not * seen creates a SECOND one, and the code already on the customer's site * keeps pointing at the first. `expired`: only reloading the page helps, * so there is nothing to retry. */ const [loadFailed, setLoadFailed] = useState( false, ); /** Bumped by "Riprova": the statement is read again. */ const [loadAttempt, setLoadAttempt] = useState(0); const retriedLoad = useRef(false); // ACC-571: the save under way started at the newer-result notice, and // then whether its generation was accepted (which arms the focus fix). const newerResultAttempt = useRef(false); const publishedFromNewerResult = useRef(false); /** * The page's title: where the focus goes when the button that had it leaves * the page with its notice, or cannot take it back. */ const titleRef = useRef(null); // Tracked as a phase rather than a boolean so the button can name what it // is doing. With a single `isSaving` flag the label had to be inferred from // whether a statement already existed, which made it read // "Generating → Saving → Generating" across one click of a first create. const [savePhase, setSavePhase] = useState< "idle" | "persisting" | "generating" >("idle"); const isSaving = savePhase !== "idle"; // Flipped to true on the first save attempt that cannot generate: a missing // required field, a date in the future, or the server refusing one. Until // then, empty required fields look "neutral" — marking them before the user // has interacted would feel hostile. A statement saved incomplete in an // earlier visit and never generated opens with it on: that attempt was made. const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false); /** * Which sections of the form are open (ACC-540). The page's state, not the * form card's: a closed section keeps its fields out of the page, so a save * that lands on a gap has to open that gap's section first. */ const [openSections, setOpenSections] = useState([]); /** * The fields a rejected save or publication asks the customer to look at: * the first of them on the page gets the focus once the sections they sit * in are open and drawn. Each request is a new list. */ const [focusRequest, setFocusRequest] = useState(null); /** When the form was last saved; null until a statement exists. */ const [savedAt, setSavedAt] = useState(null); /** The full-size preview (the dialog), and the button that opened it. */ const [previewOpen, setPreviewOpen] = useState(false); const previewOpener = useRef(null); /** "Salva e pubblica" was pressed in the dialog: it runs once that closes. */ const saveOnPreviewClosed = useRef(false); /** * Today, resolved once per mount rather than per render, so the `max` on the * date inputs and the check behind them can never disagree within a render. * A tab left open across midnight keeps yesterday's bound — a day stale on a * cap whose job is to stop 2099, and the server re-checks regardless. */ const today = useMemo(() => todayISO(), []); /** * Past-only dates the SERVER refused at generation, each with the value it * refused (ACC-515). * * The page's own check compares against the browser's today, the server * against its own, so the two can disagree — a device clock running days * fast. Without this nothing would mark the field, and the customer would * be told to correct a date the form shows no problem with. * * The server names fields, not values, so the value recorded is this FORM's. * That is wrong in one case: a colleague's save landing between this page's * save and its generate call, where the date refused was theirs and the one * marked here is fine. It heals on the next click — this page's save * overwrites theirs, and every attempt starts by clearing the mark — which * is why the mark lasts one attempt and no longer. * * Keyed to the value so that an edited date, which has not been judged yet, * does not stay red. */ const [refusedDates, setRefusedDates] = useState< Partial> >({}); /** * The generation has been polled for as long as the page is willing to * wait. The page says so on top and stops asking until the customer asks * again: nothing is lost, the form was saved before the generation started. */ const [generationSlow, setGenerationSlow] = useState(false); /** "Controlla di nuovo lo stato" is waiting for its answer. */ const [checkingStatus, setCheckingStatus] = useState(false); /** * The temporary statement (ACC-504). While one is active the embed serves * it instead of the regular statement, and generating the regular one ends * it — so the page asks before doing that. */ const temporaryActive = temporary?.current?.state === "active"; const [temporaryBusy, setTemporaryBusy] = useState(false); const [confirmSaveOpen, setConfirmSaveOpen] = useState(false); /** The release date of a first publication waiting to be confirmed. */ const [pendingRelease, setPendingRelease] = useState(null); /** What had the focus when one of the page's two questions opened. */ const questionOpener = useRef(null); const pollRef = useRef | null>(null); const pollAttemptsRef = useRef(0); // Tracks the last seen status so we only fire the "ready" toast on // the queued/processing -> ready transition, not on every render // (e.g. when the page reloads with a long-since-ready statement). const prevStatusRef = useRef(statementStatus); /** Languages that actually have a published artifact right now. */ const publishedLocales = useMemo( () => STATEMENT_LOCALES.filter((locale) => artifacts.publicHtmlUrls[locale]), [artifacts.publicHtmlUrls], ); const hasPublished = publishedLocales.length > 0; /** * Whether a statement was ever GENERATED, not whether a row exists: an * incomplete form now persists without generating, so `statementId` can be * set while the user's goal is still to get a statement produced. * * Hoisted here (it used to sit beside the action label) because two things * now turn on it — the Save/Create label, and whether a moved audit picker * is worth warning about. */ const hasGeneratedStatement = !!artifacts.generatedAt; /** * The picker moved but the server snapshot still describes the old run. * * Silent until the statement has been generated at least once. Before that * there is no document whose audit basis could be out of date — the customer * is still filling the form, and "save to refresh the preview" warns about * something that does not exist yet. Same signal the action label uses, so * the note and the Create/Save wording can never disagree about whether a * statement exists. */ const auditSelectionUnsaved = hasGeneratedStatement && auditSnapshot !== null && // Compared against the stored PIN, not the resolved run: after a fallback // the two differ, and comparing against the run would call a picker that // already matches reality "unsaved". (selectedAuditJobId === LATEST_AUDIT ? Boolean(auditSnapshot.pinnedJobId) && !auditSnapshot.pinnedFallback : selectedAuditJobId !== auditSnapshot.pinnedJobId); // The audit picker is saved with the form, so a moved picker counts too. const hasUnsavedChanges = canEdit && storedForm !== null && (JSON.stringify(form) !== JSON.stringify(storedForm) || auditSelectionUnsaved); useEffect(() => { onUnsavedChange?.(hasUnsavedChanges); }, [hasUnsavedChanges, onUnsavedChange]); /** * The one URL the customer ever has to paste: it resolves the VISITOR's * language at request time and redirects to the matching artifact, so * publishing another language later needs no change on their site. */ const publicEntryUrl = statementId ? client.statements.publicUrl(statementId) : null; useEffect(() => { const prev = prevStatusRef.current; prevStatusRef.current = statementStatus; if ( statementStatus === "ready" && (prev === "queued" || prev === "processing") && hasPublished ) { toast.success(formDict.toasts.generateReady); // The server's view of the temporary statement (ACC-504) is out of date // either way: the run ended the one this page knew about, or a colleague // published one while it was under way — which the run left alone, so // the card and the embed panel have to start showing it. refresh(); } }, [ statementStatus, hasPublished, toast, formDict.toasts.generateReady, refresh, ]); function patch( key: K, value: StatementForm[K], ) { setForm((prev) => ({ ...prev, [key]: value })); } /** Writes one free-text field under one language, leaving the others alone. */ function patchLocalized( locale: StatementLocale, field: keyof LocalizedDraft, value: string, ) { setForm((prev) => ({ ...prev, localized: { ...prev.localized, [locale]: { ...prev.localized[locale], [field]: value }, }, })); } /** Integers ≥ 0 only, and "" stays "" — blank means "not declared". */ function patchCount( key: "employeesWithDisabilities" | "workstationsForDisabilities", value: string, ) { patch(key, value.replace(/\D/g, "")); } /** * The sections the form opens on: the ones with something missing, plus * the one that holds the audit picker when the audit that was chosen is * gone. The notice on top says "choose another one", and the picker is * otherwise in a section nothing has opened. * * Whether the audit is gone is read through a ref, as it is when the * statement loads: the server sends it again after every save * (`refresh()`), and a load that depended on it would run again * under the customer, put back the form as saved and close what they had * opened. */ const pinnedFallback = auditSnapshot?.pinnedFallback === true; const pinnedFallbackRef = useRef(pinnedFallback); useEffect(() => { pinnedFallbackRef.current = pinnedFallback; }, [pinnedFallback]); const openingSections = useCallback( (loaded: StatementForm): StatementSection[] => { const open = sectionsToOpen(loaded, today); return pinnedFallbackRef.current && !open.includes("conformance") ? STATEMENT_SECTIONS.filter( (section) => section === "conformance" || open.includes(section), ) : open; }, [today], ); // Load existing statement for the selected domain. useEffect(() => { const controller = new AbortController(); const load = async () => { setIsLoading(true); try { const statement = await client.statements.getForSite(site.id, { signal: controller.signal, }); // Empty-state contract (BUG-27): no statement exists yet for this // site. Treat that as the empty state and DO NOT toast — first-visit // users would otherwise see a misleading "Couldn't load" error. if (statement == null) { setStatementId(null); setStatementStatus("draft"); setArtifacts(EMPTY_ARTIFACTS); setForm(defaultForm); setStoredForm(defaultForm); setActiveLocale(initialLocale); setSavedAt(null); setOpenSections(openingSections(defaultForm)); setLoadFailed(false); return; } setStatementId(statement.id); setStatementStatus(normalizeStatus(statement.status, "draft")); setArtifacts(computeArtifacts(statement)); const loaded = statementToForm(statement, defaultForm); setForm(loaded); setStoredForm(loaded); // A statement written before ACC-260 has one set of free text, filed // under the language the row was saved in and under no other. // Opening on the dashboard's language instead would hide that text // behind the language select, and the likeliest next move is retyping // what is already there. Open where the text is. setActiveLocale(localeWithLegacyText(statement) ?? initialLocale); setSavedAt(statement.updatedAt ?? null); setOpenSections(openingSections(loaded)); // Saved in an earlier visit and never generated: the customer has // already been told what is missing, and finds it marked again. if (!computeArtifacts(statement).generatedAt) { setHasAttemptedSubmit(true); } setLoadFailed(false); } catch (err) { if (controller.signal.aborted) return; console.error(err); const expired = isSessionExpired(err); setLoadFailed(expired ? "expired" : "error"); // The notice says it, and is read out as it appears. A retry that // fails too finds the notice already there, saying nothing new: the // toast is for that. if (retriedLoad.current) { toast.error(expired ? sessionExpiredText : formDict.toasts.loadError); } // An expired session takes "Riprova" away: the effect below hands // its focus on. retriedLoad.current = retriedLoad.current && expired; } finally { if (!controller.signal.aborted) setIsLoading(false); } }; load(); return () => controller.abort(); }, [ client, site.id, defaultForm, initialLocale, openingSections, toast, formDict.toasts.loadError, sessionExpiredText, loadAttempt, ]); // "Riprova" worked, or cannot any more: its button is gone. The title // takes the focus if the button had it; a customer who has moved on // meanwhile is left where they are. useEffect(() => { if (loadFailed === "error" || isLoading || !retriedLoad.current) return; retriedLoad.current = false; if (focusIsLost()) titleRef.current?.focus(); }, [loadFailed, isLoading]); // The chosen audit went missing under a page that stays open (the server // says so with a refresh): the notice says "choose another one or save to // confirm", so the picker's section opens, with whatever else is open, and // the picker lets go of the audit that is gone, as it does when the page // loads: a save that sent it again would be refused. An audit the customer // has chosen meanwhile stays chosen. const pinnedJobId = auditSnapshot?.pinnedJobId ?? null; useEffect(() => { if (!pinnedFallback) return; setOpenSections((open) => open.includes("conformance") ? open : STATEMENT_SECTIONS.filter( (section) => section === "conformance" || open.includes(section), ), ); setSelectedAuditJobId((selected) => selected === pinnedJobId ? LATEST_AUDIT : selected, ); }, [pinnedFallback, pinnedJobId]); /** Reads the statement's status; null when it could not be read. */ const refreshStatus = useCallback( async (id: string): Promise => { try { const statement = await client.statements.get(id); if (!statement) return null; const status = normalizeStatus(statement.status, "draft"); setStatementStatus(status); setArtifacts(computeArtifacts(statement)); return status; } catch (err) { console.error(err); return null; } }, [client], ); // Poll while generation is in progress. useEffect(() => { if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; } if (!statementId) return; if (statementStatus !== "queued" && statementStatus !== "processing") { // Reset poll state when generation completes/fails pollAttemptsRef.current = 0; setGenerationSlow(false); return; } // Given up for now: the customer asks when they want to know ("Controlla // di nuovo lo stato", once per press), and a new save starts it again, // which is why this is a dependency. if (generationSlow) return; pollRef.current = setInterval(() => { pollAttemptsRef.current += 1; // Check timeout if (pollAttemptsRef.current > MAX_POLL_ATTEMPTS) { clearInterval(pollRef.current!); pollRef.current = null; setGenerationSlow(true); // The notice is on top of the page; the customer may be anywhere in // the form. Same words, and a warning: nothing has failed. toast.warning(statementDict.notices.slowTitle); return; } refreshStatus(statementId); }, POLL_INTERVAL_MS); return () => { if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; } }; }, [ statementId, statementStatus, generationSlow, refreshStatus, toast, statementDict.notices.slowTitle, ]); /** * "Controlla di nuovo lo stato": asks once. A generation still under way * leaves the page as it is, with the notice and a save that works: going * back to asking at intervals would lock the save again for as long as the * page had already waited. One that has ended takes the notice away, and * with it the button that was pressed, so the focus goes to the title. */ async function checkGenerationAgain(button: HTMLElement) { if (!statementId || checkingStatus) return; setCheckingStatus(true); const status = await refreshStatus(statementId); setCheckingStatus(false); if (status === null) { toast.error(statementDict.notices.slowCheckError); } else if (status === "queued" || status === "processing") { toast.info(statementDict.notices.slowStill); } else if (document.activeElement === button || focusIsLost()) { // Not if the customer went on with the form while the answer came. titleRef.current?.focus(); } } const persistDraft = useCallback(async (): Promise => { // `form` is a flat record of strings → no deep clone needed; `setForm` // always replaces, so future writes will not mutate this snapshot. const snapshot = form; let statement: StatementPayload; try { statement = await client.statements.save({ statementId, siteId: site.id, // NOT the UI language. This is the field the generator reads to // decide the document's primary language, and it is a column like // any other — leaving it out of a save would move the fallback rather // than leave it where it was. locale: PRIMARY_LOCALE, // A column like any other under the save contract: omitting it clears // the pin, so it is sent on every save rather than only when touched. auditJobId: selectedAuditJobId === LATEST_AUDIT ? null : selectedAuditJobId, ...formToPayload(snapshot), }); } catch (err) { // The save carried a chosen audit, which is refused if that audit has // gone missing since the page was opened. The server's view is what // says so: it brings the notice and frees the picker (the effect on // `pinnedFallback`). Without it every later save is refused too. const answered = err instanceof SiteAdminApiError; if (answered && selectedAuditJobId !== LATEST_AUDIT) refresh(); throw err; } setStatementId(statement.id); setStatementStatus(normalizeStatus(statement.status, "draft")); setArtifacts(computeArtifacts(statement)); setSavedAt(statement.updatedAt ?? null); setStoredForm(snapshot); // The server computed `auditSnapshot` from the pin as it was when the page // rendered. The save may have just moved it, and the preview and the facts // on top of the page both read that prop — so // without this the page would keep declaring the previous audit's bucket // while generation used the new one. That is the preview-versus-artifact // divergence the parity contract exists to prevent, and it would reappear // in the UI layer rather than in the query. refresh(); return statement; // `selectedAuditJobId` belongs here: it is read in the body above, and // omitting it froze this callback on the pin from the render before the // user touched the picker — so the feature's primary flow (open, change // only the audit, save) posted the OLD id and appeared to do nothing. }, [client, statementId, site.id, form, selectedAuditJobId, refresh]); /** * Lands the user on whichever of these fields comes first on the page. A * toast can't name every problem, and the marks it reveals are on the form: * off-screen when the click came from the top of the page, and out of the * page altogether while their section is closed. * * So the sections open first, and the focus moves once they are drawn (the * effect below). Which field is first is asked of the DOM rather than taken * as `ids[0]`: the public-entity fields are APPENDED to the required list, * so list order is not form order — the officer's name sits above the CMS * on screen but after it in the list. */ function focusFirstOf(ids: readonly string[]) { const sections = ids .map(sectionOfFieldId) .filter((section): section is StatementSection => section !== null); setOpenSections((open) => [...new Set([...open, ...sections])]); setFocusRequest([...ids]); } function focusFirstField(keys: readonly RequiredField[]) { focusFirstOf(keys.map((key) => REQUIRED_FIELD_IDS[key])); } useEffect(() => { if (!focusRequest) return; const land = (): boolean => { const first = inPageOrder(focusRequest)[0]; if (!first) return false; // A reason is only ever missing in English, so land on the English // version rather than on a box the user may already have filled in // another language. The textarea keeps its id across languages. if (ANSWER_REASONS.some(({ id }) => id === first.id)) { setActiveLocale(PRIMARY_LOCALE); } first.focus(); first.scrollIntoView({ behavior: prefersReducedMotion() ? "auto" : "smooth", block: "center", }); return true; }; // The sections opened in the same render, so the fields are there; a // frame's grace covers a section that is drawn a moment later. The // request is left as it is: a new one is a new list, and runs this again. if (land()) return; const frame = requestAnimationFrame(land); return () => cancelAnimationFrame(frame); }, [focusRequest]); /** * The page's single action (ACC-245): persist the form, then kick off * generation. The save half is unconditional — a half-filled form is still * work worth keeping, and the user has no other way to keep it now that the * separate draft button is gone. Only generation needs every required * field, so an incomplete form saves and stops there. * * `endTemporary` is the customer's yes to "Chiudere la dichiarazione * temporanea?" (ACC-504): the server refuses to end an active temporary * statement without it. */ async function handleSave(endTemporary = false) { // Whatever ends this attempt short of an accepted generation (a failed // or refused save, a save-only form) arms nothing; only success does. publishedFromNewerResult.current = false; setSavePhase("persisting"); let persisted: StatementPayload; try { persisted = await persistDraft(); } catch (err) { // A failed save must not flip the status to `failed`: nothing was // regenerated, so any previously published artifact is still valid. setSavePhase("idle"); toast.error(errorText(err) || formDict.toasts.saveError); return; } const missing = missingRequiredFields(form); // A future date blocks generation exactly as a gap does, and for the same // reason: the document about to be published would state something untrue. // It does NOT block the draft save above — a typo is not a reason to throw // away every other edit in the same click. const inFuture = futureDateFields(form, today); if (missing.length > 0 || inFuture.length > 0) { setSavePhase("idle"); setHasAttemptedSubmit(true); toast.warning( missing.length > 0 ? formDict.toasts.savedIncomplete : formDict.toasts.savedFutureDate, ); // Land the user on the first gap rather than making them hunt. focusFirstField([...missing, ...inFuture]); return; } setSavePhase("generating"); // A new attempt, a new verdict: whatever the server refused last time is // either refused again below or no longer the reason this one ends as it // does. setRefusedDates({}); try { const result = await client.statements.generate( persisted.id, endTemporary === true ? { endTemporary: true } : undefined, ); // `in`, not `ok`: the package is not strict, and does not narrow a // boolean union. if ("code" in result) { // A temporary statement this page had not seen — a colleague // published it after the page was loaded. Nothing was generated and // nothing ended: ask the question the page would have asked had it // known. The save above has already re-read the server's view, so the // card follows. if (result.code === "temporary_active") { rememberQuestionOpener(); setConfirmSaveOpen(true); return; } // The server's own refusal of a date in the future (ACC-515) is the // same outcome as the page's check above, reached when the two // disagree about today — so it gets the same treatment, not the // failure path. The draft WAS saved and nothing broke: throwing here // toasted the server's message, raw English with column names in it, // and turned the badge to "failed" over a statement a reload shows as // a draft. // // That holds for the CODE, whatever comes with it: the badge never // turns "failed" on a refusal at the door. What the fields decide is // only what the customer is told. const refused = PAST_ONLY_DATE_FIELDS.filter((key) => result.fields.includes(key), ); if (refused.length > 0) { setRefusedDates( Object.fromEntries(refused.map((key) => [key, form[key]])), ); setHasAttemptedSubmit(true); toast.warning(formDict.toasts.savedFutureDate); focusFirstField(refused); return; } // A refusal that names no date this form has: a column the page does // not know yet, which audit-api can start sending before the // dashboard that understands it is deployed. There is nothing to // mark, and "correct the future dates" beside two dates that look // fine is a dead end, so the server's own sentence goes in the toast: // it at least names the column for whoever picks up the ticket. A // body with no list at all lands here too — defensively, since no // audit-api has ever sent the code without one. // // What this cannot cover: an audit-api older than the `code` sends // `message` alone, so its refusal is indistinguishable from any other // failure (the client throws it) and still ends as one, badge // included. toast.error(result.message || formDict.toasts.generateError); return; } // A generation was accepted: a fresh cycle of asking. Not before: a // save that is not stored starts none and leaves the row as it was, // and resetting there sent a page that had stopped waiting back to // waiting for the old generation, with the save locked. (A save that // IS stored makes the row a draft only when no generation holds it; // one saved while a generation runs keeps that run's status, ACC-664, // and only the generate request asks the run for another pass.) pollAttemptsRef.current = 0; setGenerationSlow(false); if (result.statement) { setStatementId(result.statement.id); setStatementStatus(normalizeStatus(result.statement.status, "queued")); setArtifacts(computeArtifacts(result.statement)); } else { setStatementStatus("queued"); } toast.success(formDict.toasts.saved); // Started from the newer-result notice: once the refresh takes it // away, its button goes with it and the focus is put back. publishedFromNewerResult.current = newerResultAttempt.current; newerResultAttempt.current = false; } catch (err) { setStatementStatus("failed"); toast.error(errorText(err) || formDict.toasts.generateError); } finally { setSavePhase("idle"); } } /** * Generating the regular statement ends an active temporary one at once, * and there is no second one this licence year: ask first. An incomplete * form, or one with a date in the future (ACC-381), only saves, which ends * nothing, so it needs no question. */ function requestSave() { beginSave(false); } /** The newer-result notice's button: the same save, remembered as its. */ function publishFromNewerResult() { beginSave(true); } function beginSave(fromNewerResult: boolean) { newerResultAttempt.current = fromNewerResult; publishedFromNewerResult.current = false; if ( temporaryActive && missingRequiredFields(form).length === 0 && futureDateFields(form, today).length === 0 ) { rememberQuestionOpener(); setConfirmSaveOpen(true); } else { void handleSave(); } } /** * The card's action (ACC-504): check the form, then publish. * * A FIRST publication is confirmed before anything is sent: it replaces at * once what the live embed shows, it cannot be withdrawn, and it is the * licence year's only one. A correction of a statement already active * changes none of that, so it is not asked about again. The gap in the form * is reported first — asking "are you sure?" about something that cannot * go through yet would waste the question. * * The server checks every rule again; the check here only saves a round * trip and lands the user on the gap. */ function requestPublishTemporary(releaseDate: string) { const missing = missingTemporaryColumns(formToPayload(form)); if (missing.length > 0) { setHasAttemptedSubmit(true); toast.warning(temporaryDict.toasts.missingFields); focusFirstOf( missing .map((key) => TEMPORARY_FIELD_IDS[key]) .filter((id): id is string => id !== undefined), ); return; } // The temporary document prints the site's publication date, so a day // that has not come stops it as it stops the regular one (ACC-381). The // drafting date in the form is not this document's: the server sets it. if (futureDateFields(form, today).includes("sitePublicationDate")) { setHasAttemptedSubmit(true); toast.warning(temporaryDict.errors.future_publication_date); focusFirstField(["sitePublicationDate"]); return; } if (temporary?.publication === "open") { rememberQuestionOpener(); setPendingRelease(releaseDate); } else void publishTemporary(releaseDate); } /** * The page's two questions ("Pubblicare la dichiarazione temporanea?", * "Chiudere la dichiarazione temporanea?") are opened by its state, not by * a trigger of their own, so nothing gives the focus back when they close * unless the page does: without this it ends on nothing, and the keyboard * starts again from the top of the window. */ function rememberQuestionOpener() { const active = document.activeElement; // `body` is the focus on nothing: what a browser leaves when the button // that was pressed is disabled while the server answers. questionOpener.current = active instanceof HTMLElement && active !== document.body ? active : null; } function restoreFocusAfterQuestion(event: Event) { event.preventDefault(); // Something took the focus on purpose meanwhile, as a save that landed // on a field does: it stays there. if (!focusIsLost()) return; const opener = questionOpener.current; // After a yes the button that asked is busy, and cannot take it: the // title does. if (opener?.isConnected && !opener.matches(":disabled")) opener.focus(); else focusTitleInPlace(); } /** * The focus on the title without the page being thrown to its top: a tap * on the bar a phone has at the bottom, then a yes, leaves the customer * where they were. Someone on the keyboard has to see where the focus is, * and for them (the browser shows the ring) the page does scroll to it. */ function focusTitleInPlace() { const title = titleRef.current; if (!title) return; title.focus({ preventScroll: true }); if (showsFocusRing(title)) title.scrollIntoView({ block: "nearest" }); } /** * The publication itself. It reads the SAVED row, so the form is persisted * first — which stores the columns and generates nothing: the regular * statement is untouched. */ async function publishTemporary(releaseDate: string) { setTemporaryBusy(true); try { const persisted = await persistDraft(); const result = (await client.statements.publishTemporary?.( persisted.id, releaseDate, )) ?? { ok: false, code: "" }; if ("code" in result) { const errors = temporaryDict.errors as Record; toast.error(errors[result.code] ?? temporaryDict.errors.generic); return; } toast.success(temporaryDict.toasts.published); // The card and the embed panel read the server's view of it. refresh(); } catch (err) { toast.error(errorText(err) || temporaryDict.errors.generic); } finally { setTemporaryBusy(false); } } /** * The form as the preview last rendered it. Assigning `srcDoc` re-parses the * whole document and throws the reader's scroll position back to the top, so * rendering on every keystroke made the free-text fields — the ones a * customer types most into — unusable beside their own preview. There is no * in-place update to reach for instead: the iframe is cross-origin by * construction (`sandbox=""`), so its document is unreachable from here. * * Correct on settle, always: the timer restarts on every change and the last * one to fire carries the current form, so the preview cannot end up showing * text the user has since edited away. */ const [previewForm, setPreviewForm] = useState(form); useEffect(() => { const timer = setTimeout(() => setPreviewForm(form), PREVIEW_DEBOUNCE_MS); return () => clearTimeout(timer); }, [form]); /** * The document as the generator writes it, for the OPEN TAB's language rather * than the statement's: typing into the Spanish tab has to show the Spanish * document, or the tabs are writing into something the user cannot see. * * The LANGUAGE is not debounced — switching a tab is a discrete action, not * typing, and it should answer immediately. Only the FORM is (`previewForm`). * * One language, because there is one preview. This used to be a * `previewFor(locale)` callback, for the second preview the embed card * carried; that preview is gone (ACC-381) and with it the reason to render * any language but the one on screen. * * The conformance verdict and non-conformity list are the CLIENT's to * resolve from `audit`, for the language being previewed: the copy they are * written in is legal text, and stays out of this package. The dashboard * renders the document in the browser (`renderPreview`), WordPress asks its * server (`loadPreview`). */ const previewInput = useMemo( () => ({ data: formToStatementData(previewForm, siteUrl), locale: activeLocale, primaryLocale: PRIMARY_LOCALE, audit: auditSnapshot, }), [previewForm, siteUrl, activeLocale, auditSnapshot], ); const { renderPreview, loadPreview } = client.statements; // A local renderer answers in the same render; a remote one keeps showing // the last document until the next arrives, so a slow or failed request // never blanks the preview. const renderedHtml = useMemo( () => renderPreview?.(previewInput) ?? null, [renderPreview, previewInput], ); const [loadedHtml, setLoadedHtml] = useState(""); const [previewLoading, setPreviewLoading] = useState(false); // Until a preview arrives again: the failure stays on screen through the // reloads in between, so it is announced once and its Retry keeps the focus. const [previewFailed, setPreviewFailed] = useState< false | "error" | "expired" >(false); const [previewAttempt, setPreviewAttempt] = useState(0); /** The preview card's heading: where the focus goes when the failure leaves. */ const previewHeadingRef = useRef(null); /** Where the failure's Retry was, while it had the focus: the card or a dialog. */ const previewFocusReturn = useRef<"card" | HTMLElement | null>(null); /** * The request out is the customer's Retry. One that fails again leaves the * alert as it was, saying nothing: `previewRetryFailed` says it again, in a * status of its own. Reloads after an edit stay silent. */ const previewRetried = useRef(false); const [previewRetryFailed, setPreviewRetryFailed] = useState(false); /** Retry is about to go: where its focus lands, if it has it. */ function holdPreviewFocus() { const active = document.activeElement; if (active?.closest("[data-preview-failure]")) { previewFocusReturn.current = active.closest("[role=dialog]") ?? "card"; } } useEffect(() => { if (renderPreview || !loadPreview) return; let cancelled = false; setPreviewLoading(true); loadPreview(previewInput).then( (html) => { if (cancelled) return; setLoadedHtml(html); holdPreviewFocus(); setPreviewFailed(false); setPreviewLoading(false); setPreviewRetryFailed(false); previewRetried.current = false; }, (err) => { console.error(err); if (cancelled) return; const expired = isSessionExpired(err); // Only a reload helps: Retry goes, and its focus with it. if (expired) holdPreviewFocus(); setPreviewFailed(expired ? "expired" : "error"); setPreviewLoading(false); if (previewRetried.current) setPreviewRetryFailed(true); previewRetried.current = false; }, ); return () => { cancelled = true; }; }, [renderPreview, loadPreview, previewInput, previewAttempt]); const previewHtml = renderedHtml ?? loadedHtml; // A retry worked, or the session expired: Retry has gone, with the focus. // It lands on the heading of the preview — where the customer was, with // the document next in reading order — or, in the full-size dialog, on the // dialog. useEffect(() => { const target = previewFocusReturn.current; if (previewFailed === "error" || !target) return; previewFocusReturn.current = null; if (!focusIsLost()) return; if (target === "card") previewHeadingRef.current?.focus(); else if (target.isConnected) target.focus(); }, [previewFailed]); // Nothing to keep or save on a page that only reads. const previewFailedText = canEdit ? formDict.preview.loadFailed : formDict.preview.loadFailedReadOnly; /** What a preview the server renders says while it waits, or has failed. */ const previewState = previewFailed ? ( <>
{previewFailed === "expired" ? sessionExpiredText : previewFailedText} {/* `aria-disabled`, not `disabled`: a button that goes off while it has the focus drops it to the top of the page. */} {previewFailed === "error" && ( )}
{previewRetryFailed ? previewFailedText : ""} ) : previewLoading && !previewHtml ? (

{messages.common.actions.loading}

) : null; /** * The temporary document (ACC-504) for one language and one release date, * through the same functions the publication runs on the saved row (the * host's `renderTemporaryPreview`). Drafted on the day an active statement * was first published, otherwise today: what the server will write. * * The card's preview opens on a click, so it reads the form as it is now. * It is the only preview of this document: the embed panel has none * (ACC-381), for the temporary statement as for the regular one. */ const { renderTemporaryPreview } = client.statements; const temporaryPreviewFor = useCallback( (language: StatementLocale, releaseDate: string) => renderTemporaryPreview?.({ columns: formToPayload(form), siteUrl, locale: language, draftedOn: temporary?.current?.state === "active" ? temporary.current.draftedOn : (temporary?.today ?? todayISO()), releaseDate, }) ?? "", [renderTemporaryPreview, form, siteUrl, temporary], ); const missingRequired = useMemo(() => missingRequiredFields(form), [form]); // Typed as strings so `fieldError` can probe it with any form key, not just // the required subset. const missingSet = useMemo( () => new Set(missingRequired), [missingRequired], ); /** The past-only dates the SERVER refused and the form still carries. */ const refusedNow = useMemo( () => new Set( // The server's verdict stands for the value it was given, and for no // other — see `refusedDates`. PAST_ONLY_DATE_FIELDS.filter( (key) => refusedDates[key] !== undefined && refusedDates[key] === form[key], ), ), [form, refusedDates], ); const futureDates = useMemo( () => new Set([...futureDateFields(form, today), ...refusedNow]), [form, today, refusedNow], ); const canGenerate = missingRequired.length === 0 && futureDates.size === 0; // Never to a reader: a list of what is missing, to someone who cannot fill // it in, is noise on a page they came to read. const showFieldErrors = canEdit && hasAttemptedSubmit && !canGenerate; function fieldError(key: keyof StatementForm) { // A future date is checked before absence: a field cannot be both, and // naming the real problem beats "Required field" on a filled-in input. if (showFieldErrors && futureDates.has(key)) { return { invalid: true, errorMessage: formDict.validation.dateNotFuture }; } const invalid = showFieldErrors && missingSet.has(key); const own = REQUIRED_FIELD_ERRORS[key as keyof typeof REQUIRED_FIELD_ERRORS]; return { invalid, errorMessage: invalid ? own ? formDict.validation[own] : formDict.validation.fieldRequired : undefined, }; } const sections = useMemo( () => sectionStatuses(form, today, refusedNow), [form, today, refusedNow], ); // A generation the page gave up waiting for no longer holds the page: the // customer may save and publish again. The publish asks the running // generation for another pass, or takes the statement over once that run's // claim has gone stale (audit-api, ACC-664); it never starts a second one. const generationBusy = !generationSlow && (statementStatus === "queued" || statementStatus === "processing"); // The action runs the same save-then-generate path either way, but it is // named after what the user is actually doing. The discriminant is whether // a statement was ever GENERATED, not whether a row exists: an incomplete // form now persists without generating, so `statementId` can be set while // the user's goal is still to get a statement produced. While the action // runs, the label follows the phase — the two halves of the click really // are a save and then a generation. const actionLabel = savePhase === "persisting" ? formDict.actions.saving : savePhase === "generating" || generationBusy ? formDict.actions.generating : hasGeneratedStatement ? formDict.actions.saveAndPublish : formDict.actions.createAndPublish; const actionBusy = isSaving || generationBusy; // We intentionally leave the action enabled when required fields are // missing: clicking it saves what is there and reveals what is missing. // Disabling it would leave the user with no feedback about WHICH fields. const actionDisabled = isLoading || isSaving || generationBusy || temporaryBusy; // "C'è un risultato più recente" (ACC-571): to whoever can publish again, // on a statement that was published. Not while the picker names another // audit than the saved one: the next publication declares that, not the // run this would name. Nor beside the fallback warning: that one already // asks for a save, and one cause gets one notice. Nor while a temporary // statement is online: what the link shows is not the regular statement // the notice talks about, and its button would first ask to close the // temporary one — the temporary statement's card has the say until then. const showNewerResult = Boolean(newerResult) && canEdit && hasGeneratedStatement && !auditSelectionUnsaved && !pinnedFallback && !temporaryActive; // The notice's republish worked: the refreshed page finds nothing newer, // and the button that had the focus is gone with the notice. As after // "Riprova", the title takes it, unless the customer has moved on. // Armed only once a generation started from the notice was accepted // (`handleSave`): a failed, cancelled or save-only attempt leaves the // notice where it is, and the next attempt starts unarmed. useEffect(() => { if (showNewerResult || !publishedFromNewerResult.current) return; publishedFromNewerResult.current = false; // In place: seconds after the click, the page is not thrown to its top. if (focusIsLost()) focusTitleInPlace(); }, [showNewerResult]); /** * The page's one action, drawn where each layout wants it: beside the title, * in the bar at the bottom of a phone, and under the full-size preview. One * definition, so the three can never disagree on the label or on whether it * can be pressed. */ const saveButton = (onClick: () => void = requestSave) => ( ); const openPreview = (opener: HTMLElement) => { // Kept to give the focus back: the dialog is opened by this state, not // by a trigger of its own. previewOpener.current = opener; setPreviewOpen(true); }; const controller: StatementFormController = { form, patch, patchLocalized, patchCount, fieldError, showErrors: showFieldErrors, missing: missingSet, readOnly: !canEdit, today, locale: activeLocale, onLocaleChange: setActiveLocale, }; // While the statement is being read, whether a regular one is published // is what the server already said with the temporary statement's view. const knownPublished = isLoading ? (temporary?.regularPublished ?? false) : hasPublished; const state = statementState({ // A generation the page gave up waiting for is not what the statement // "is": until it ends, what is online says it. status: generationSlow ? "draft" : statementStatus, busy: savePhase === "generating", hasPublished: knownPublished, temporary: temporary?.current?.state ?? null, withdrawn, }); /** A calendar day of the temporary statement, as the page writes it. */ const temporaryDay = (day: string) => format.date(new Date(`${day}T00:00:00Z`), { year: "numeric", month: "short", day: "numeric", // A calendar day: formatted in UTC so nobody west of Greenwich is shown // the day before. timeZone: "UTC", }); const temporaryUntil = temporaryActive && temporary?.current ? temporaryDay(temporary.current.releaseDate) : null; /** * What ending the temporary statement costs, for the question that asks. * Until when, where the plan's year has an end to name; "at the renewal" * where it has none; on a plan that dropped it, only that there is no * other. Nothing at all when the statement the page knows to be online is * not this year's (online since before the renewal, or another plan's): * the year's one is still to use. */ const endingCost = temporary?.availableAgainOn ? fillFor(lang, temporaryDict.confirmUntil, { date: temporaryDay(temporary.availableAgainOn), }) : !temporary || !temporaryActive || temporary.publication === "not_in_plan" ? // Also the question asked on the server's word (a `409`), about a // statement published after this page was loaded: this year's by // definition, on a view that does not know it yet. temporaryDict.confirmNoOther : temporary.yearSpent ? temporaryDict.confirmUntilRenewal : null; /** * What the preview is of while a temporary statement is online: the * regular one, which visitors do not see. It "goes back online" on the * temporary one's date only if it was ever published. */ const previewBehindTemporary = temporaryUntil ? knownPublished ? fillFor(lang, formDict.preview.descriptionTemporary, { date: temporaryUntil, }) : formDict.preview.descriptionTemporaryDraft : null; // Where the audits of this site are: the Tracker from Pro up, the Audit // page for Starter and for audits bought with credits. Unlinked where the // host has no such page. const tier = site.trackerLicense?.tier ?? null; const auditsOnTracker = tier !== null && tier !== "start"; const auditsHref = links?.audits?.(site.id, tier); // WordPress does not know the tier (no `trackerLicense` at all): it cannot // tell "run the audit" from "wait for the Tracker", so it says both and // opens the site in the dashboard, which knows (ACC-411). const tierKnown = site.trackerLicense !== undefined; const missingLabels = missingRequired.map( (key) => formDict.fields[REQUIRED_FIELD_LABELS[key]], ); const header = ( {statementDict.title} } description={statementDict.description} > {/* On a phone the action is in the bar at the bottom of the window. */} {canEdit && !loadFailed && (
{saveButton()}
)}
); // Nothing was read: the page has no statement to describe and no form it // can let anyone save. It says so, and reads again when asked. if (loadFailed) { return (
{header} {notice} { if (isLoading) return; retriedLoad.current = true; setLoadAttempt((attempt) => attempt + 1); }} > {isLoading ? (
); } return (
{header} {notice} {!auditSnapshot && ( {auditsOnTracker ? formDict.auditBanner.goToTracker : formDict.auditBanner.goToAudit} ) : ( )) } > {!tierKnown ? formDict.auditBanner.neutralBody : auditsOnTracker ? formDict.auditBanner.waitBody : formDict.auditBanner.startBody} )} {/* A pin that could not be honoured. A warning, because the document the customer is about to sign is derived from something other than what they chose — the one case where staying quiet is not an option. */} {auditSnapshot?.pinnedFallback && ( {formDict.auditPicker.unavailableBody} )} {generationSlow && ( ) => void checkGenerationAgain(event.currentTarget) } > {checkingStatus ? ( )} {/* "C'è un risultato più recente" (ACC-571): to whoever can publish again, on a statement that was published. Not while the picker names another audit than the saved one: the next publication declares that, not the run this would name. Nor beside the fallback warning above: that one already asks for a save, and one cause gets one notice. Nor while a temporary statement is online. */} {showNewerResult && newerResult && ( )} {/* What stops the generation, named: the fields are marked below, in sections that the save has opened. */} {showFieldErrors && missingLabels.length > 0 && ( {fillTpl( missingLabels.length === 1 ? statementDict.notices.missingBodyOne : statementDict.notices.missingBody, { fields: new Intl.ListFormat(format.intlLocale, { style: "long", type: "conjunction", // `String`: the list formatter refuses anything else. }).format(missingLabels.map(String)), }, )} )} {/* The temporary statement (ACC-504), on the plans that include it. Above the form because it publishes from the same fields. */} {temporary && ( )} { if (!open) setPendingRelease(null); }} > {temporaryDict.publishConfirmTitle} {/* Both paragraphs are the description: that it cannot be withdrawn is read out with the question, before the buttons, not left beside it for whoever looks. */}

{fillFor(lang, temporaryDict.publishConfirmLead, { date: pendingRelease ? temporaryDay(pendingRelease) : "", })}

{temporaryDict.publishConfirmRule} {/* The year's statement is the whole plan's (ACC-514): on a plan with subdomains, publishing here spends it for them. */} {temporary?.planShared && ` ${temporaryDict.sharedConfirmNote}`}

{temporaryDict.confirmCancel} { if (pendingRelease) void publishTemporary(pendingRelease); }} > {temporaryDict.publishConfirmAction}
{temporaryDict.confirmTitle}

{temporaryDict.confirmLead}

{endingCost && (

{endingCost} {temporary?.planShared && ` ${temporaryDict.sharedConfirmNote}`}

)}
{ // A cancelled attempt is no attempt: nothing was published. newerResultAttempt.current = false; }} > {temporaryDict.confirmCancel} void handleSave(true)}> {temporaryDict.confirmAction}
{/* The form and its preview, side by side where there is room for both (the form asks for 30rem, the preview for 25rem) and one under the other where there is not. Side by side they are as tall as each other: the preview takes the height of the form and scrolls inside, so a long document never pushes the page down. */}
option.id !== pinnedJobId) : auditOptions, unsaved: auditSelectionUnsaved, }} statuses={sections} open={openSections} onOpenChange={setOpenSections} canGenerate={canGenerate} loading={isLoading} />
{/* On a phone the preview is the dialog, opened from the bar at the bottom: a frame a screen tall in the middle of a form is a trap for the finger that scrolls the page. */}
{/* With an active temporary statement the panel describes THAT: it is what the entry point serves, even when no regular statement was ever published, and it exists in all three languages. Either way the per-language link is the entry point with `?lang=` (ACC-523), never the file on the CDN. Withdrawn with its plan, the entry point serves nothing: no code, and no placeholder promising one after a generation that cannot run. */} {(!withdrawn || temporaryActive) && ((hasPublished || temporaryActive) && publicEntryUrl ? ( ) : ( ))} {temporary && ( )} previewHtml} status={previewState} locale={activeLocale} onLocaleChange={setActiveLocale} returnFocusTo={previewOpener} onClosed={() => { if (!saveOnPreviewClosed.current) return; saveOnPreviewClosed.current = false; requestSave(); }} > {canEdit && saveButton(() => { // The save may land on a field of the form, so it waits for the // dialog to have closed and handed the focus back: run at once, // a quick save would move the focus first and lose it to that. saveOnPreviewClosed.current = true; setPreviewOpen(false); })} {canEdit && saveButton()}
); }