peppa/apps/web/components/ActionForm.tsx
Асель ccb3b7ec23 PEP-160: точка после текста ошибки, память проекта, AGENTS.md
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 13:03:03 +05:00

59 lines
2.5 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useRef, useState, useTransition, type FormEvent, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { useT } from "@/components/I18n";
import type { FormResult } from "@/lib/created";
import { cn } from "@/lib/utils";
/**
* PEP-160: a create form that keeps what was typed. The server action returns `{ error }` or
* `{ to }` instead of redirecting: while it runs the button shows `pendingText` and a second
* submit is ignored; an error appears next to the button (what happened + `hint`: what to do)
* and the fields stay as they are; on success the form is cleared, its side dialog closes and
* the user goes to the page with the new record.
*/
export function ActionForm({ action, submit, pendingText, hint, className, children }: { action: (f: FormData) => Promise<FormResult>; submit: ReactNode; pendingText: string; /** What to do after an error. */ hint: string; className?: string; children: ReactNode }) {
const t = useT();
const router = useRouter();
const [pending, start] = useTransition();
const [error, setError] = useState<string | null>(null);
// A ref, not state: the second click of a double click arrives before `disabled` is rendered.
const busy = useRef(false);
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault(); // also keeps React from resetting the fields after the action
if (busy.current) return;
busy.current = true;
const form = e.currentTarget;
const data = new FormData(form);
setError(null);
start(async () => {
try {
const r = await action(data);
if ("error" in r) return setError(/[.!?…]$/.test(r.error) ? r.error : r.error + ".");
form.reset();
form.closest("dialog")?.close();
router.push(r.to);
} catch {
setError(t("Не получилось отправить: нет связи с Peppa FACTORY."));
} finally {
busy.current = false;
}
});
};
return (
<form onSubmit={onSubmit} aria-busy={pending} className={cn("flex flex-col", className)}>
{children}
{error && (
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error} {hint}
</p>
)}
<Button variant="default" disabled={pending} aria-busy={pending} className="self-start">
{pending ? pendingText : submit}
</Button>
</form>
);
}