"use client"; import * as React from "react"; import { sanitizeWidgetSettings, type TrackerTier, type WidgetSettings, } from "@accessibit/types"; import { RECONNECT, SESSION_EXPIRED, SiteAdminApiError, type WidgetSaveAnswer, } from "../client"; import { useSiteAdmin } from "../context"; import { derivePosition, fromSettings, toSettings, withPositionDefaults, type OffsetUnit, type UiConfig, type UiPosition, } from "./settings-adapter"; export type WidgetDevice = "desktop" | "mobile"; /** * The site whose widget the page sets, as the host holds it. The dashboard's * `Domain` is one; only `id`, `name` and `settings` are needed for the * appearance and the tools, the rest is read by the status tab. */ export interface WidgetSite { id: string; /** Its address as its name: "esempio.it". */ name: string; /** As stored; sanitized on the way in. */ settings: unknown; /** * The version `settings` were read at (`null`: none were stored), which * the page's saves are checked against, so a save cannot silently * overwrite an edit made elsewhere since. Absent, they are not checked. */ settingsVersion?: number | null; /** The account's slug, which the install code carries. */ companySlug?: string; /** * The widget seen on the site: the status tab then goes last, after the * appearance and the tools (ACC-586). */ isWidgetInstalled?: boolean; /** The Tracker plan the widget may come with. */ trackerLicense?: { isActive: boolean; tier: TrackerTier | null; currentPeriodEnd: string | null; renews?: boolean; renewalCancelled?: boolean; }; /** The plan of the main domain, for a subdomain. */ plan?: { mainUrl: string; paused?: boolean } | null; /** The widget's own licence, when it was bought alone. */ currentPeriodEnd?: string | null; widgetRenews?: boolean; widgetRenewalCancelled?: boolean; /** Whether the site has a bought audit (ACC-542's customers before the * plans); one opened free does not count. */ hasBoughtAudits?: boolean; } /** * Why a save did not go through, as the page words it. The server answers in * English, for whoever reads its logs: the customer is told in their own * language, by what the answer was and not by its text. */ export type WidgetSaveError = /** Signed out (the dashboard's 401): signing in again fixes it. */ | "session" /** A stale page (WordPress's nonce): only a reload fixes it. */ | "reload" /** The site's connection is gone (WordPress): only reconnecting fixes it. */ | "reconnect" | "forbidden" | "notFound" | "publish" | "network" | "generic"; const asVersion = (value: unknown): number | null => typeof value === "number" ? value : null; function saveErrorOf(err: unknown): WidgetSaveError { // No answer at all: the request never reached the server. if (!(err instanceof SiteAdminApiError)) return "network"; if (err.code === SESSION_EXPIRED) return "reload"; if (err.code === RECONNECT) return "reconnect"; if (err.status === 401) return "session"; if (err.status === 403) return "forbidden"; if (err.status === 404) return "notFound"; // The settings are written, and publishing them to the CDN failed: the // dashboard's 502, WordPress's 202 with `published: false`. if (err.code === "publish_failed" || err.status === 502) return "publish"; return "generic"; } type WidgetSettingsValue = { site: WidgetSite; /** False for a reader: the server refuses their save (member and up). */ canEdit: boolean; /** The settings as the fields show them, saved or not. */ config: UiConfig; savedConfig: UiConfig; /** What the widget would receive if the changes were saved now. */ previewSettings: WidgetSettings; isDirty: boolean; /** * Changes that leaving the page would lose. Unlike `isDirty`, not a save * that was stored and only failed to publish: the form stays dirty so Save * can retry the publish, but what it holds is already kept. */ hasUnstoredChanges: boolean; isSaving: boolean; error: WidgetSaveError | null; /** * A save was refused because the settings were changed elsewhere since * they were read (`version_conflict`): what is stored now can * be loaded, or saved over. */ conflict: boolean; patch: (key: K, value: UiConfig[K]) => void; selectPosition: (device: WidgetDevice, position: UiPosition) => void; setOffsetUnit: ( device: WidgetDevice, axis: "H" | "V", unit: OffsetUnit, ) => void; patchTool: (tool: string, checked: boolean) => void; save: () => Promise; discard: () => void; loadLatest: () => void; }; const WidgetSettingsContext = React.createContext( null, ); export function useWidgetSettings(): WidgetSettingsValue { const value = React.useContext(WidgetSettingsContext); if (!value) { throw new Error( "useWidgetSettings must be used within a WidgetSettingsProvider", ); } return value; } /** * The widget's settings while they are being changed (ACC-547): one state for * the three tabs of the Widget page, held in the section's layout so a change * made on one tab is still there on the next, and one save for all of them. * * What is sent is the whole configuration, through `toSettings`: the tabs are * a way to lay the fields out, not three things to save. * * The stored settings are read once, when the provider mounts: the site's * data follows every refresh of the layout (one follows each save), and * reading it again then would throw away what is being typed. Whoever renders * the provider keys it on the site, so another site starts from its own. */ export function WidgetSettingsProvider({ site, canEdit, onSaved, children, }: { site: WidgetSite; canEdit: boolean; /** * Told what was saved, as the server keeps it, and its version: whoever * holds the site for the rest of the host takes them at once, so leaving * the section and coming back before the refresh lands does not start from * the old settings (and save them again over the new). */ onSaved?: (settings: WidgetSettings, version: number | undefined) => void; children: React.ReactNode; }) { const { client, refresh } = useSiteAdmin(); const [savedConfig, setSavedConfig] = React.useState(() => fromSettings(sanitizeWidgetSettings(site.settings)), ); const [config, setConfig] = React.useState(savedConfig); // What the next save is checked against: read with the settings, then // whatever the server last said is stored. const versionRef = React.useRef(site.settingsVersion); const [isSaving, setIsSaving] = React.useState(false); const [error, setError] = React.useState(null); // What is stored now, after a refused save. Kept until it is loaded, or // saved over: editing on does not lose the only way back to it. const [conflict, setConflict] = React.useState<{ settings: unknown } | null>( null, ); const isDirty = React.useMemo( () => JSON.stringify(config) !== JSON.stringify(savedConfig), [config, savedConfig], ); // What the last save stored without publishing, if it did. const [storedConfig, setStoredConfig] = React.useState(null); const hasUnstoredChanges = React.useMemo( () => isDirty && JSON.stringify(config) !== JSON.stringify(storedConfig), [isDirty, config, storedConfig], ); const patch = React.useCallback( (key: K, value: UiConfig[K]) => { setConfig((prev) => Object.is(prev[key], value) ? prev : { ...prev, [key]: value }, ); setError(null); }, [], ); // Picking a position in the grid resets that device's distances to the // position's own (24px on a computer, 12px on a phone), so each position // starts clean instead of inheriting the last one's. Picking the current // position again changes nothing. const selectPosition = React.useCallback( (device: WidgetDevice, position: UiPosition) => { setConfig((prev) => { const current = device === "desktop" ? prev.desktopPosition : prev.mobilePosition; return current === position ? prev : withPositionDefaults(prev, device, position); }); setError(null); }, [], ); // Changing a distance's unit re-anchors that axis: % on the centring key // means anchored to the centre, px to an edge. The grid follows (middle // right with the height in px becomes top right). A change that would give // the impossible "middle centre" is refused. const setOffsetUnit = React.useCallback( (device: WidgetDevice, axis: "H" | "V", unit: OffsetUnit) => { setConfig((prev) => { const hUnit = axis === "H" ? unit : device === "desktop" ? prev.desktopOffsetHUnit : prev.mobileOffsetHUnit; const vUnit = axis === "V" ? unit : device === "desktop" ? prev.desktopOffsetVUnit : prev.mobileOffsetVUnit; const position = device === "desktop" ? prev.desktopPosition : prev.mobilePosition; const nextPosition = derivePosition(position, hUnit, vUnit); if (!nextPosition) return prev; return device === "desktop" ? { ...prev, desktopPosition: nextPosition, desktopOffsetHUnit: hUnit, desktopOffsetVUnit: vUnit, } : { ...prev, mobilePosition: nextPosition, mobileOffsetHUnit: hUnit, mobileOffsetVUnit: vUnit, }; }); setError(null); }, [], ); const patchTool = React.useCallback((tool: string, checked: boolean) => { setConfig((prev) => prev.enabledTools[tool] === checked ? prev : { ...prev, enabledTools: { ...prev.enabledTools, [tool]: checked } }, ); setError(null); }, []); const configRef = React.useRef(config); configRef.current = config; const onSavedRef = React.useRef(onSaved); onSavedRef.current = onSaved; const savingRef = React.useRef(false); const save = React.useCallback(async () => { if (!canEdit || savingRef.current) return false; const snapshot = configRef.current; savingRef.current = true; setIsSaving(true); setError(null); // A conflict is NOT cleared here: a save over it that fails for any other // reason must leave it in place, or Discard would fall back to what this // page first read and show it as clean, while the next save is checked // against the other change's version and overwrites it (PR #1162 review). // It goes once the overwrite is stored, below. try { let answer: WidgetSaveAnswer; try { answer = await client.widget.saveSettings( site.id, toSettings(snapshot), versionRef.current, ); } catch (err) { const current = err instanceof SiteAdminApiError && err.code === "version_conflict" ? (err.details?.current as | { settings?: unknown; version?: unknown } | undefined) : undefined; if (current?.settings !== undefined) { // Loaded or saved over, what is stored now is what the next save // is against: saving over is deliberate, not another conflict. versionRef.current = asVersion(current.version); setConflict({ settings: current.settings }); } else { // Stored, and not published yet: the retry is against it. if ( err instanceof SiteAdminApiError && err.code === "publish_failed" && typeof err.details?.version === "number" ) { versionRef.current = err.details.version; } if ( err instanceof SiteAdminApiError && err.code === "publish_failed" ) { setStoredConfig(snapshot); // Stored over the other change: there is no conflict left. setConflict(null); } setError(saveErrorOf(err)); } return false; } if (answer.version !== undefined) versionRef.current = answer.version; // What the server kept is what is saved; a change made while the save // was on its way stays on the screen, still to be saved. // An answer without them (a 200 with no body to read) is still a save // that went through: what was sent is then what is saved. const stored = answer.settings !== undefined && answer.settings !== null ? fromSettings(sanitizeWidgetSettings(answer.settings)) : snapshot; setSavedConfig(stored); setStoredConfig(null); setConflict(null); setConfig((current) => (current === snapshot ? stored : current)); // The site as the rest of the host holds it takes the new settings // now, and the host's next snapshot says the same a moment later: // coming back to this section starts from them. onSavedRef.current?.(toSettings(stored), answer.version); refresh(); return true; } finally { savingRef.current = false; setIsSaving(false); } }, [canEdit, client, refresh, site.id]); // Replaces what is being changed with what is stored now. Saving instead // keeps the changes and writes them over. const loadLatest = React.useCallback(() => { if (!conflict) return; const latest = fromSettings(sanitizeWidgetSettings(conflict.settings)); setSavedConfig(latest); setConfig(latest); setConflict(null); setError(null); }, [conflict]); // After a conflict "saved" is what is stored now, not what this page read: // anything else would show stale settings as clean, and the next save // would write over the other change without a word. // // After a save that was stored and only failed to publish, the same holds: // the server keeps those settings and its republish sweep publishes them, // so they are what is saved, and Discard drops only what came after them // (PR #1162 review). const discard = React.useCallback(() => { if (conflict) { loadLatest(); return; } if (storedConfig) { setSavedConfig(storedConfig); setConfig(storedConfig); setStoredConfig(null); setError(null); // The host learns it too, so coming back to the section starts there. onSavedRef.current?.( toSettings(storedConfig), versionRef.current ?? undefined, ); return; } setConfig(savedConfig); setError(null); }, [conflict, loadLatest, savedConfig, storedConfig]); const previewSettings = React.useMemo(() => toSettings(config), [config]); const value = React.useMemo( () => ({ site, canEdit, config, savedConfig, previewSettings, isDirty, hasUnstoredChanges, isSaving, error, conflict: conflict !== null, patch, selectPosition, setOffsetUnit, patchTool, save, discard, loadLatest, }), [ site, canEdit, config, savedConfig, previewSettings, isDirty, hasUnstoredChanges, isSaving, error, conflict, patch, selectPosition, setOffsetUnit, patchTool, save, discard, loadLatest, ], ); return ( {children} ); }