"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; 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(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) => { 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 (
{children} {error && (

{error} {hint}

)}
); }