peppa/apps/web/components/StaleActionGuard.tsx
peppa-bot 64ce2a1cc0
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 37с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1854с
peppa-ci / ci (pull_request) Successful in 33m9s
PEP-324: ревью в браузере — текст возвращается в своё поле, секреты не запоминаются, ошибки страниц доходят до «Ошибок из прода»
Проверка рабочей сборки настоящим браузером (подмена действия на неизвестное серверу и ответ 500) нашла три изъяна:
- ответ, набранный в карточке одного вопроса, после самообновления возвращался в поле другого: адресом поля было имя, а на Главной у каждой карточки поле «answer». Адрес теперь — собственный id поля, имя — только когда текстовое поле с таким именем на странице одно;
- секрет проекта и ключ сервера вводятся в textarea и попали бы в sessionStorage: поля секретов и кодов по имени не запоминаются;
- ошибка, пойманная новой границей app/error.tsx, не уходила в «Ошибки из прода» (на main уходила): Next печатает её console.error, взятым до обёртки ErrorReporter. Граница сама поднимает её через reportError.

Тесты на каждый изъян падали до правки; спека, design архива, AGENTS.md и память дополнены.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 00:37:49 +05:00

126 lines
5.8 KiB
TypeScript

"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, isTextField, 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 }));
}
/** Text fields of this name on the page. Text is kept and put back by name only when there is exactly
* one: a card per question means a field per card under the same name, and an answer must not come
* back in another question's field. */
const named = (name: string) =>
Array.from(document.getElementsByName(name)).filter((n): n is HTMLInputElement | HTMLTextAreaElement => (n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement) && isTextField(n));
const alone = (name: string) => named(name).length === 1;
function findField(key: string): FieldLike | null {
if (!key.startsWith("#")) {
const fields = named(key);
return fields.length === 1 ? fields[0]! : null;
}
const el = document.getElementById(key.slice(1));
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 | "reloading" | "manual">(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<typeof setTimeout>[] = [];
const place = () => {
if (!fields) return;
const left = restoreDrafts(fields, findField, setFieldValue, alone);
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, alone);
};
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 (
<div role="alert" className="fixed inset-x-0 top-0 z-50 flex flex-wrap items-center justify-center gap-3 border-b border-primary/50 bg-background/95 px-4 py-2 text-sm shadow">
{state === "reloading" ? (
<span className="inline-flex items-center gap-2">
<RefreshCw className="size-3.5 animate-spin" /> {t("FORGE обновилась. Обновляем страницу — набранный текст сохранится.")}
</span>
) : (
<>
<span>{t("FORGE обновилась. Обновите страницу — набранный текст сохранится.")}</span>
<button type="button" onClick={() => window.location.reload()} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1 font-medium text-primary-foreground">
<RefreshCw className="size-3.5" /> {t("Обновить страницу")}
</button>
</>
)}
</div>
);
}