46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import type { ComponentChildren } from "preact";
|
|
import { useSignal } from "@preact/signals";
|
|
|
|
import { post_json } from "@/src/client.ts";
|
|
|
|
interface FormProps<T> {
|
|
action: string;
|
|
on_success: (data: T) => void;
|
|
on_error?: (message: string) => void;
|
|
class?: string;
|
|
method?: string;
|
|
children: ComponentChildren;
|
|
}
|
|
|
|
// Posts the form's named fields as a JSON object of strings
|
|
export default function Form<T = unknown>(props: FormProps<T>) {
|
|
const submitting = useSignal(false);
|
|
const error = useSignal("");
|
|
|
|
async function submit(event: SubmitEvent) {
|
|
event.preventDefault();
|
|
if (submitting.value) {
|
|
return;
|
|
}
|
|
|
|
const form = event.currentTarget as HTMLFormElement;
|
|
const body = Object.fromEntries(new FormData(form));
|
|
|
|
submitting.value = true;
|
|
error.value = "";
|
|
const result = await post_json<T>(props.action, body, props.method);
|
|
submitting.value = false;
|
|
|
|
if (result.ok) props.on_success(result.data);
|
|
else if (props.on_error) props.on_error(result.error);
|
|
else error.value = result.error;
|
|
}
|
|
|
|
return (
|
|
<form class={props.class} onSubmit={submit}>
|
|
<fieldset disabled={submitting.value}>{props.children}</fieldset>
|
|
{error.value && <p role="alert" class="mt-4 text-error-600 dark:text-error-400">{error.value}</p>}
|
|
</form>
|
|
);
|
|
}
|