1 | import React, { useEffect } from 'react';
|
2 | import usePrevious from '@restart/hooks/usePrevious';
|
3 | import { TypeaheadContext } from './Context';
|
4 | import { defaultSelectHint, getHintText, getInputProps, getInputText, getIsOnlyResult, isFunction, pick, } from '../utils';
|
5 | const inputPropKeys = [
|
6 | 'activeIndex',
|
7 | 'disabled',
|
8 | 'id',
|
9 | 'inputRef',
|
10 | 'isFocused',
|
11 | 'isMenuShown',
|
12 | 'multiple',
|
13 | 'onBlur',
|
14 | 'onChange',
|
15 | 'onClick',
|
16 | 'onFocus',
|
17 | 'onKeyDown',
|
18 | 'placeholder',
|
19 | ];
|
20 | const propKeys = [
|
21 | 'activeIndex',
|
22 | 'hideMenu',
|
23 | 'isMenuShown',
|
24 | 'labelKey',
|
25 | 'onClear',
|
26 | 'onHide',
|
27 | 'onRemove',
|
28 | 'results',
|
29 | 'selected',
|
30 | 'text',
|
31 | 'toggleMenu',
|
32 | ];
|
33 | const contextKeys = [
|
34 | 'activeIndex',
|
35 | 'id',
|
36 | 'initialItem',
|
37 | 'inputNode',
|
38 | 'onActiveItemChange',
|
39 | 'onAdd',
|
40 | 'onInitialItemChange',
|
41 | 'onMenuItemClick',
|
42 | 'setItem',
|
43 | ];
|
44 | const TypeaheadManager = (props) => {
|
45 | const { allowNew, children, initialItem, isMenuShown, onAdd, onInitialItemChange, onKeyDown, onMenuToggle, results, selectHint, } = props;
|
46 | const prevProps = usePrevious(props);
|
47 | const hintText = getHintText(props);
|
48 | useEffect(() => {
|
49 | if (!(allowNew || results.length)) {
|
50 | onInitialItemChange();
|
51 | }
|
52 | });
|
53 | useEffect(() => {
|
54 | if (prevProps && prevProps.isMenuShown !== isMenuShown) {
|
55 | onMenuToggle(isMenuShown);
|
56 | }
|
57 | });
|
58 | const handleKeyDown = (e) => {
|
59 | onKeyDown(e);
|
60 | if (!initialItem) {
|
61 | return;
|
62 | }
|
63 | const addOnlyResult = e.key === 'Enter' && getIsOnlyResult(props);
|
64 | const shouldSelectHint = hintText && defaultSelectHint(e, selectHint);
|
65 | if (addOnlyResult || shouldSelectHint) {
|
66 | onAdd(initialItem);
|
67 | }
|
68 | };
|
69 | const childProps = {
|
70 | ...pick(props, propKeys),
|
71 | getInputProps: getInputProps({
|
72 | ...pick(props, inputPropKeys),
|
73 | onKeyDown: handleKeyDown,
|
74 | value: getInputText(props),
|
75 | }),
|
76 | };
|
77 | const contextValue = {
|
78 | ...pick(props, contextKeys),
|
79 | hintText,
|
80 | isOnlyResult: getIsOnlyResult(props),
|
81 | };
|
82 | return (React.createElement(TypeaheadContext.Provider, { value: contextValue }, isFunction(children) ? children(childProps) : children));
|
83 | };
|
84 | export default TypeaheadManager;
|