"use client"; import { useEffect, useState } from "react"; import { RefreshCw } from "lucide-react"; import { unstable_isUnrecognizedActionError } from "next/navigation"; import { useT } from "@/components/I18n"; import { DraftTracker, claimReload, isStaleAction as isStaleText, restoreDrafts, saveDrafts, takeDrafts, type FieldLike } from "@/lib/stale-action"; /** * PEP-324: a button of a page opened before an update calls a server action the new server doesn't * know. The page keeps the typed text, says FORGE was updated and reloads itself (once a minute at * most — then a button). PEP-114 stays: without such a failed press the page never reloads by itself. */ const EVENT = "peppa:stale-action"; const RELOAD_DELAY_MS = 1500; const tracker = new DraftTracker(); /** The «action not found on the server» error, by Next's own check first. */ export const isStaleAction = (err: unknown) => isStaleText(err, unstable_isUnrecognizedActionError); /** Called by the error boundary (app/error.tsx) when the caught error is an unknown action. */ export function reportStaleAction() { if (typeof window !== "undefined") window.dispatchEvent(new Event(EVENT)); } function setFieldValue(el: FieldLike, value: string) { const node = el as unknown as HTMLInputElement | HTMLTextAreaElement; const proto = node instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; // The native setter + an input event: React-controlled fields see the value as typed. Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(node, value); node.dispatchEvent(new Event("input", { bubbles: true })); } function findField(key: string): FieldLike | null { const el = key.startsWith("#") ? document.getElementById(key.slice(1)) : Array.from(document.getElementsByName(key)).find((n) => n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement); return el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement ? el : null; } const path = () => location.pathname + location.search; export function StaleActionGuard() { const t = useT(); const [state, setState] = useState(null); useEffect(() => { // Text saved before the self-reload goes back; parts of the page that mount later get a few tries. let fields = takeDrafts(sessionStorage, path(), Date.now()); const timers: ReturnType[] = []; const place = () => { if (!fields) return; const left = restoreDrafts(fields, findField, setFieldValue); fields = left.length ? Object.fromEntries(left.map((k) => [k, fields![k]])) : null; }; place(); for (const ms of [300, 1000, 3000]) timers.push(setTimeout(place, ms)); const onInput = (e: Event) => { const el = e.target; if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) tracker.input(el); }; const onSubmit = (e: Event) => tracker.submit(e.target, Date.now()); let handled = false; const handle = () => { if (handled) return; handled = true; saveDrafts(sessionStorage, path(), tracker.snapshot(Date.now()), Date.now()); if (claimReload(sessionStorage, Date.now())) { setState("reloading"); timers.push(setTimeout(() => window.location.reload(), RELOAD_DELAY_MS)); } else setState("manual"); }; const onRejection = (e: PromiseRejectionEvent) => { if (!isStaleAction(e.reason)) return; e.preventDefault(); // not an error for the console or «Ошибки из прода» handle(); }; const onError = (e: ErrorEvent) => { if (!isStaleAction(e.error ?? e.message)) return; e.preventDefault(); handle(); }; document.addEventListener("input", onInput, true); document.addEventListener("submit", onSubmit, true); window.addEventListener("unhandledrejection", onRejection); window.addEventListener("error", onError); window.addEventListener(EVENT, handle); return () => { for (const id of timers) clearTimeout(id); document.removeEventListener("input", onInput, true); document.removeEventListener("submit", onSubmit, true); window.removeEventListener("unhandledrejection", onRejection); window.removeEventListener("error", onError); window.removeEventListener(EVENT, handle); }; }, []); if (!state) return null; return (
{state === "reloading" ? ( {t("FORGE обновилась. Обновляем страницу — набранный текст сохранится.")} ) : ( <> {t("FORGE обновилась. Обновите страницу — набранный текст сохранится.")} )}
); }