UNPKG

2.19 kBPlain TextView Raw
1import { createComponent } from "reakit-system/createComponent";
2import { As, PropsWithAs } from "reakit-utils/types";
3import { createHook } from "reakit-system/createHook";
4import { RoleOptions, RoleHTMLProps, useRole } from "../Role/Role";
5import { unstable_FormStateReturn } from "./FormState";
6import { unstable_getIn } from "./utils/getIn";
7import { getMessageId } from "./__utils/getMessageId";
8import { shouldShowError } from "./__utils/shouldShowError";
9import { shouldShowMessage } from "./__utils/shouldShowMessage";
10import { DeepPath } from "./__utils/types";
11import { FORM_MESSAGE_KEYS } from "./__keys";
12
13export 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 * FormInput's name as in form values.
23 */
24 name: P;
25 };
26
27export type unstable_FormMessageHTMLProps = RoleHTMLProps;
28
29export type unstable_FormMessageProps<
30 V,
31 P extends DeepPath<V, P>
32> = unstable_FormMessageOptions<V, P> & unstable_FormMessageHTMLProps;
33
34export 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
65export 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;