59 lines
2.5 KiB
TypeScript
59 lines
2.5 KiB
TypeScript
"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>
|
||
);
|
||
}
|