1 | import * as React from "react";
|
2 | import { createComponent } from "reakit-system/createComponent";
|
3 | import { createHook } from "reakit-system/createHook";
|
4 | import { useLiveRef } from "reakit-utils/useLiveRef";
|
5 | import { RoleOptions, RoleHTMLProps, useRole } from "../Role/Role";
|
6 | import { unstable_FormStateReturn } from "./FormState";
|
7 | import { FORM_KEYS } from "./__keys";
|
8 |
|
9 | export type unstable_FormOptions = RoleOptions &
|
10 | Pick<unstable_FormStateReturn<any>, "submit">;
|
11 |
|
12 | export type unstable_FormHTMLProps = RoleHTMLProps &
|
13 | React.FormHTMLAttributes<any>;
|
14 |
|
15 | export type unstable_FormProps = unstable_FormOptions & unstable_FormHTMLProps;
|
16 |
|
17 | export const unstable_useForm = createHook<
|
18 | unstable_FormOptions,
|
19 | unstable_FormHTMLProps
|
20 | >({
|
21 | name: "Form",
|
22 | compose: useRole,
|
23 | keys: FORM_KEYS,
|
24 |
|
25 | useProps(options, { onSubmit: htmlOnSubmit, ...htmlProps }) {
|
26 | const onSubmitRef = useLiveRef(htmlOnSubmit);
|
27 |
|
28 | const onSubmit = React.useCallback(
|
29 | (event: React.FormEvent) => {
|
30 | onSubmitRef.current?.(event);
|
31 | if (event.defaultPrevented) return;
|
32 | event.preventDefault();
|
33 | options.submit?.();
|
34 | },
|
35 | [options.submit]
|
36 | );
|
37 |
|
38 | return {
|
39 | role: "form",
|
40 | noValidate: true,
|
41 | onSubmit,
|
42 | ...htmlProps,
|
43 | };
|
44 | },
|
45 | });
|
46 |
|
47 | export const unstable_Form = createComponent({
|
48 | as: "form",
|
49 | useHook: unstable_useForm,
|
50 | });
|