UNPKG

2.81 kBJavaScriptView Raw
1import cn from 'classnames';
2import React, { useImperativeHandle, useRef, useState } from 'react';
3const DropdownListInput = /*#__PURE__*/React.forwardRef(function ({
4 name,
5 autoComplete,
6 value,
7 allowSearch,
8 placeholder,
9 textAccessor,
10 dataKeyAccessor,
11 searchTerm,
12 onSearch,
13 onAutofill,
14 onAutofillChange,
15 renderValue,
16 disabled,
17 readOnly
18}, ref) {
19 const [autofilling, setAutofilling] = useState(false);
20 const searchRef = useRef(null);
21
22 const handleAutofillDetect = ({
23 animationName
24 }) => {
25 let autofilling;
26 if (animationName === 'react-widgets-autofill-start') autofilling = true;else if (animationName === 'react-widgets-autofill-cancel') autofilling = false;else return;
27 setAutofilling(autofilling);
28 onAutofill(autofilling);
29 };
30
31 const handleAutofill = e => {
32 setAutofilling(false);
33 onAutofillChange(e);
34 };
35
36 let dataKey = dataKeyAccessor(value);
37 let text = value == null ? '' : textAccessor(value);
38 let strValue = String(dataKey != null ? dataKey : '');
39 if (strValue === String({})) strValue = '';
40 const inputValue = !value && placeholder ? /*#__PURE__*/React.createElement("span", {
41 className: "rw-placeholder"
42 }, placeholder) : renderValue ? renderValue({
43 item: value,
44 dataKey,
45 text
46 }) : text;
47 useImperativeHandle(ref, () => ({
48 focus() {
49 if (searchRef.current) searchRef.current.focus();
50 }
51
52 })); // There is some interaction between unmounting the search and value inputs
53 // that cancels autofilling in Chrome, it may be due to an input the browser
54 // was considering suddenly disappeared. hiding it seems to avoid the issue
55
56 const style = autofilling ? {
57 display: 'none'
58 } : undefined;
59 return /*#__PURE__*/React.createElement("div", {
60 className: "rw-dropdown-list-input"
61 }, autoComplete !== 'off' && /*#__PURE__*/React.createElement("input", {
62 name: name,
63 tabIndex: -1,
64 disabled: disabled,
65 readOnly: readOnly,
66 value: strValue == null ? '' : strValue,
67 autoComplete: autoComplete,
68 onChange: handleAutofill,
69 onAnimationStart: handleAutofillDetect,
70 "aria-hidden": !autofilling,
71 className: cn('rw-detect-autofill', !autofilling && 'rw-sr')
72 }), /*#__PURE__*/React.createElement(React.Fragment, null, allowSearch && /*#__PURE__*/React.createElement("input", {
73 ref: searchRef,
74 disabled: disabled,
75 readOnly: readOnly,
76 style: style,
77 className: "rw-dropdownlist-search",
78 autoComplete: "off",
79 value: searchTerm || '',
80 size: (searchTerm || '').length + 2,
81 onChange: onSearch
82 }), !searchTerm && /*#__PURE__*/React.createElement("span", {
83 className: "rw-dropdown-list-value",
84 style: style
85 }, inputValue)));
86});
87DropdownListInput.displayName = 'DropdownListInput';
88export default DropdownListInput;
\No newline at end of file