peppa/apps/web/lib/stale-action.ts

155 lines
6.1 KiB
TypeScript

// PEP-324: a page opened before an update presses a button whose server action the new server doesn't
// know (renamed, removed, or the actions key changed) — Next throws `UnrecognizedActionError`. Instead
// of «Application error» and lost text, the page says FORGE was updated, keeps what the person typed
// and reloads itself; after the reload the text goes back into the same fields.
// Pure functions over a minimal DOM/storage shape — the browser glue is components/StaleActionGuard.tsx.
const MESSAGE_RE = /Server Action "[^"]*" was not found on the server/;
/** True for the «action not found on the server» error — as an Error, from another module copy, or as text.
* `nextCheck` — `unstable_isUnrecognizedActionError` from `next/navigation` (passed in by the client
* components: this module stays free of Next imports and testable under plain node). */
export function isStaleAction(err: unknown, nextCheck?: (e: unknown) => boolean): boolean {
if (!err) return false;
if (typeof err === "string") return MESSAGE_RE.test(err);
try {
if (nextCheck?.(err)) return true;
} catch {
/* fall through to the name/message check */
}
const e = err as { name?: unknown; message?: unknown };
return e.name === "UnrecognizedActionError" || (typeof e.message === "string" && MESSAGE_RE.test(e.message));
}
export const DRAFTS_KEY = "peppa.stale-drafts";
export const RELOAD_KEY = "peppa.stale-reload";
/** A second self-reload within this window means reloading did not help: show the button instead. */
export const RELOAD_GUARD_MS = 60_000;
/** Fields of a form submitted this recently still go along: it may be the very submit that failed. */
export const SUBMIT_GRACE_MS = 15_000;
/** Saved text older than this is not restored. */
export const DRAFTS_TTL_MS = 5 * 60_000;
export const FIELD_MAX = 20_000;
export interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
/** The parts of an input/textarea the draft logic reads. */
export interface FieldLike {
tagName: string;
type?: string;
name?: string;
id?: string;
value: string;
form?: unknown;
hasAttribute(name: string): boolean;
}
/** `name`, else `#id`; null for fields whose text is not kept (password, hidden, file, no name…). */
export function fieldKey(el: FieldLike): string | null {
const tag = el.tagName.toUpperCase();
if (tag !== "TEXTAREA" && tag !== "INPUT") return null;
if (tag === "INPUT" && !["text", "search", "email", "url", "tel", ""].includes((el.type ?? "text").toLowerCase())) return null;
if (el.hasAttribute("data-no-draft") || el.hasAttribute("readonly") || el.hasAttribute("disabled")) return null;
if (el.name) return el.name;
if (el.id) return `#${el.id}`;
return null;
}
interface Saved {
path: string;
at: number;
fields: Record<string, string>;
}
/** What the person typed on this page, in memory until an unknown action asks to keep it. */
export class DraftTracker {
private typed = new Map<string, { value: string; form: unknown }>();
private sent = new Map<string, { value: string; at: number }>();
/** An `input` event on a field. */
input(el: FieldLike) {
const key = fieldKey(el);
if (!key) return;
this.sent.delete(key);
if (el.value) this.typed.set(key, { value: el.value.slice(0, FIELD_MAX), form: el.form ?? null });
else this.typed.delete(key);
}
/** A `submit` event: the form's fields move to «sent» — after a successful submit the form is
* cleared and that text must not come back on a later reload. */
submit(form: unknown, now: number) {
for (const [key, v] of this.typed) {
if (v.form !== form) continue;
this.sent.set(key, { value: v.value, at: now });
this.typed.delete(key);
}
}
/** Fields to keep across the reload: everything typed plus what was submitted just now. */
snapshot(now: number): Record<string, string> {
const out: Record<string, string> = {};
for (const [key, v] of this.sent) if (now - v.at <= SUBMIT_GRACE_MS) out[key] = v.value;
for (const [key, v] of this.typed) out[key] = v.value;
return out;
}
}
export function saveDrafts(storage: StorageLike, path: string, fields: Record<string, string>, now: number) {
try {
if (Object.keys(fields).length === 0) storage.removeItem(DRAFTS_KEY);
else storage.setItem(DRAFTS_KEY, JSON.stringify({ path, at: now, fields } satisfies Saved));
} catch {
/* storage full or blocked: the reload still helps */
}
}
/** Saved fields for this page (and forgets them); null when none, stale, or from another page. */
export function takeDrafts(storage: StorageLike, path: string, now: number): Record<string, string> | null {
let raw: string | null = null;
try {
raw = storage.getItem(DRAFTS_KEY);
if (raw !== null) storage.removeItem(DRAFTS_KEY);
} catch {
return null;
}
if (!raw) return null;
try {
const saved = JSON.parse(raw) as Saved;
if (saved.path !== path || !(now - saved.at <= DRAFTS_TTL_MS) || !saved.fields) return null;
return saved.fields;
} catch {
return null;
}
}
/** Put saved text back into empty fields; `find` resolves a field key, `set` writes so React sees it.
* Returns the keys not placed (their field is not on the page yet). */
export function restoreDrafts(fields: Record<string, string>, find: (key: string) => FieldLike | null, set: (el: FieldLike, value: string) => void): string[] {
const left: string[] = [];
for (const [key, value] of Object.entries(fields)) {
const el = find(key);
if (!el || fieldKey(el) !== key) {
left.push(key);
continue;
}
if (!el.value) set(el, value);
}
return left;
}
/** May the page reload itself now? Records the reload; false when it already did within the guard window. */
export function claimReload(storage: StorageLike, now: number): boolean {
try {
const last = Number(storage.getItem(RELOAD_KEY) ?? 0);
if (last && now - last >= 0 && now - last < RELOAD_GUARD_MS) return false;
storage.setItem(RELOAD_KEY, String(now));
return true;
} catch {
// Without storage we cannot tell a loop from a first time: ask the person instead.
return false;
}
}