1 | import { createComponent } from "reakit-system/createComponent";
|
2 | import { As, PropsWithAs } from "reakit-utils/types";
|
3 | import { createHook } from "reakit-system/createHook";
|
4 | import { RoleOptions, RoleHTMLProps, useRole } from "../Role/Role";
|
5 | import { unstable_FormStateReturn } from "./FormState";
|
6 | import { unstable_getIn } from "./utils/getIn";
|
7 | import { getMessageId } from "./__utils/getMessageId";
|
8 | import { shouldShowError } from "./__utils/shouldShowError";
|
9 | import { shouldShowMessage } from "./__utils/shouldShowMessage";
|
10 | import { DeepPath } from "./__utils/types";
|
11 | import { FORM_MESSAGE_KEYS } from "./__keys";
|
12 |
|
13 | export type unstable_FormMessageOptions<
|
14 | V,
|
15 | P extends DeepPath<V, P>
|
16 | > = RoleOptions &
|
17 | Pick<
|
18 | unstable_FormStateReturn<V>,
|
19 | "baseId" | "touched" | "errors" | "messages"
|
20 | > & {
|
21 | |
22 |
|
23 |
|
24 | name: P;
|
25 | };
|
26 |
|
27 | export type unstable_FormMessageHTMLProps = RoleHTMLProps;
|
28 |
|
29 | export type unstable_FormMessageProps<
|
30 | V,
|
31 | P extends DeepPath<V, P>
|
32 | > = unstable_FormMessageOptions<V, P> & unstable_FormMessageHTMLProps;
|
33 |
|
34 | export const unstable_useFormMessage = createHook<
|
35 | unstable_FormMessageOptions<any, any>,
|
36 | unstable_FormMessageHTMLProps
|
37 | >({
|
38 | name: "FormMessage",
|
39 | compose: useRole,
|
40 | keys: FORM_MESSAGE_KEYS,
|
41 |
|
42 | useProps(options, htmlProps) {
|
43 | let children = shouldShowError(options, options.name)
|
44 | ? unstable_getIn(options.errors, options.name as any)
|
45 | : undefined;
|
46 |
|
47 | children =
|
48 | children ||
|
49 | (shouldShowMessage(options, options.name)
|
50 | ? unstable_getIn(options.messages, options.name as any)
|
51 | : undefined);
|
52 |
|
53 | return {
|
54 | role: "alert",
|
55 | id: getMessageId(options.name, options.baseId),
|
56 | children,
|
57 | ...htmlProps,
|
58 | };
|
59 | },
|
60 | }) as <V, P extends DeepPath<V, P>>(
|
61 | options: unstable_FormMessageOptions<V, P>,
|
62 | htmlProps?: unstable_FormMessageHTMLProps
|
63 | ) => unstable_FormMessageHTMLProps;
|
64 |
|
65 | export const unstable_FormMessage = (createComponent({
|
66 | as: "div",
|
67 | memo: true,
|
68 | useHook: unstable_useFormMessage,
|
69 | }) as unknown) as <V, P extends DeepPath<V, P>, T extends As = "div">(
|
70 | props: PropsWithAs<unstable_FormMessageOptions<V, P>, T>
|
71 | ) => JSX.Element;
|