-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
autocomplete-creatable.tsx
47 lines (39 loc) 路 1.32 KB
/
autocomplete-creatable.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { Flex, FlexProps } from "@chakra-ui/react";
import { MaybeRenderProp } from "@chakra-ui/react-utils";
import { isEmpty, runIfFn } from "@chakra-ui/utils";
import React from "react";
import { useAutoCompleteContext } from "./autocomplete-context";
import { baseItemStyles } from "./autocomplete-item";
interface AutoCompleteCreatableProps extends Omit<FlexProps, "children"> {
children?: MaybeRenderProp<{ value: any }>;
alwaysDisplay?: boolean;
}
export function AutoCompleteCreatable(props: AutoCompleteCreatableProps) {
const { alwaysDisplay, children: childrenProp, ...rest } = props;
const {
autoCompleteProps,
getItemProps,
query,
filteredResults,
} = useAutoCompleteContext();
const { children, ...itemProps } = getItemProps(
{
...props,
value: query,
children: runIfFn(childrenProp, {
value: query,
}),
},
true
).item;
const queryExistsInList = filteredResults.some(i => i.value === query);
const showWhenEmpty = isEmpty(query) ? alwaysDisplay : true;
const showCreatable =
autoCompleteProps.creatable && showWhenEmpty && !queryExistsInList;
return showCreatable ? (
<Flex {...baseItemStyles} {...itemProps} {...rest}>
{children || `Add ${query}`}
</Flex>
) : null;
}
AutoCompleteCreatable.displayName = "AutoCompleteCreatable";