-
Notifications
You must be signed in to change notification settings - Fork 331
/
Copy pathauto-complete.tsx
251 lines (231 loc) · 7.5 KB
/
auto-complete.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import React, {
CSSProperties,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react'
import Input from '../input'
import AutoCompleteItem, { AutoCompleteItemProps } from './auto-complete-item'
import AutoCompleteDropdown from './auto-complete-dropdown'
import AutoCompleteSearching from './auto-complete-searching'
import AutoCompleteEmpty from './auto-complete-empty'
import { AutoCompleteContext, AutoCompleteConfig } from './auto-complete-context'
import { NormalTypes } from '../utils/prop-types'
import Loading from '../loading'
import { pickChild } from '../utils/collections'
import useCurrentState from '../utils/use-current-state'
import useScale, { withScale } from '../use-scale'
export type AutoCompleteTypes = NormalTypes
export type AutoCompleteOption = {
label: string
value: string
}
export type AutoCompleteOptions = Array<
typeof AutoCompleteItem | AutoCompleteOption | React.ReactElement<AutoCompleteItemProps>
>
interface Props {
options?: AutoCompleteOptions
type?: AutoCompleteTypes
initialValue?: string
value?: string
onChange?: (value: string) => void
onSearch?: (value: string) => void
onSelect?: (value: string) => void
searching?: boolean | undefined
clearable?: boolean
dropdownClassName?: string
dropdownStyle?: CSSProperties
disableMatchWidth?: boolean
disableFreeSolo?: boolean
className?: string
getPopupContainer?: () => HTMLElement | null
}
const defaultProps = {
options: [] as AutoCompleteOptions,
initialValue: '',
disabled: false,
clearable: false,
type: 'default' as AutoCompleteTypes,
disableMatchWidth: false,
disableFreeSolo: false,
className: '',
}
type NativeAttrs = Omit<React.InputHTMLAttributes<any>, keyof Props>
export type AutoCompleteProps = Props & NativeAttrs
const childrenToOptionsNode = (options: Array<AutoCompleteOption>) =>
options.map((item, index) => {
const key = `auto-complete-item-${index}`
if (React.isValidElement(item)) return React.cloneElement(item, { key })
const validItem = item as AutoCompleteOption
return (
<AutoCompleteItem key={key} value={validItem.value} isLabelOnly>
{validItem.label}
</AutoCompleteItem>
)
})
// When the search is not set, the "clearable" icon can be displayed in the original location.
// When the search is seted, at least one element should exist to avoid re-render.
const getSearchIcon = (searching?: boolean, scale: string | number = 1) => {
if (searching === undefined) return null
return searching ? <Loading scale={+scale / 2} /> : <span />
}
const AutoCompleteComponent = React.forwardRef<
HTMLInputElement,
React.PropsWithChildren<AutoCompleteProps>
>(
(
{
options,
initialValue: customInitialValue,
onSelect,
onSearch,
onChange,
searching,
children,
type,
value,
clearable,
disabled,
dropdownClassName,
dropdownStyle,
disableMatchWidth,
disableFreeSolo,
getPopupContainer,
...props
}: React.PropsWithChildren<AutoCompleteProps> & typeof defaultProps,
userRef: React.Ref<HTMLInputElement | null>,
) => {
const resetTimer = useRef<number>()
const { SCALES, getScaleProps } = useScale()
const ref = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const [state, setState, stateRef] = useCurrentState<string>(customInitialValue)
const [selectVal, setSelectVal] = useState<string>(customInitialValue)
const [visible, setVisible] = useState<boolean>(false)
useImperativeHandle(userRef, () => inputRef.current)
const [, searchChild] = pickChild(children, AutoCompleteSearching)
const [, emptyChild] = pickChild(children, AutoCompleteEmpty)
const autoCompleteItems = useMemo(() => {
const hasSearchChild = searchChild && React.Children.count(searchChild) > 0
const hasEmptyChild = emptyChild && React.Children.count(emptyChild) > 0
if (searching) {
return hasSearchChild ? (
searchChild
) : (
<AutoCompleteSearching>Searching...</AutoCompleteSearching>
)
}
if (options.length === 0) {
if (state === '') return null
return hasEmptyChild ? (
emptyChild
) : (
<AutoCompleteEmpty>No Options</AutoCompleteEmpty>
)
}
return childrenToOptionsNode(options as Array<AutoCompleteOption>)
}, [searching, options])
const showClearIcon = useMemo(
() => clearable && searching === undefined,
[clearable, searching],
)
const updateValue = (val: string) => {
if (disabled) return
setSelectVal(val)
onSelect && onSelect(val)
setState(val)
inputRef.current && inputRef.current.focus()
}
const updateVisible = (next: boolean) => setVisible(next)
const onInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setVisible(true)
onSearch && onSearch(event.target.value)
setState(event.target.value)
}
const resetInputValue = () => {
if (!disableFreeSolo) return
if (!state || state === '') return
if (state !== selectVal) {
setState(selectVal)
}
}
useEffect(() => {
onChange && onChange(state)
}, [state])
useEffect(() => {
if (value === undefined) return
setState(value)
}, [value])
const initialValue = useMemo<AutoCompleteConfig>(
() => ({
ref,
value: state,
updateValue,
visible,
updateVisible,
}),
[state, visible],
)
const toggleFocusHandler = (next: boolean) => {
clearTimeout(resetTimer.current)
setVisible(next)
if (next) {
onSearch && onSearch(stateRef.current)
} else {
resetTimer.current = window.setTimeout(() => {
resetInputValue()
clearTimeout(resetTimer.current)
}, 100)
}
}
const inputProps = {
...props,
disabled,
value: state,
}
return (
<AutoCompleteContext.Provider value={initialValue}>
<div ref={ref} className="auto-complete">
<Input
ref={inputRef}
type={type}
onChange={onInputChange}
onFocus={() => toggleFocusHandler(true)}
onBlur={() => toggleFocusHandler(false)}
clearable={showClearIcon}
width={SCALES.width(1, 'initial')}
height={SCALES.height(2.25)}
iconRight={getSearchIcon(searching, getScaleProps('scale'))}
{...inputProps}
/>
<AutoCompleteDropdown
visible={visible}
disableMatchWidth={disableMatchWidth}
className={dropdownClassName}
dropdownStyle={dropdownStyle}
getPopupContainer={getPopupContainer}
>
{autoCompleteItems}
</AutoCompleteDropdown>
<style jsx>{`
.auto-complete {
width: ${SCALES.width(1, 'max-content')};
height: ${SCALES.height(1, 'auto')};
padding: ${SCALES.pt(0)} ${SCALES.pr(0)} ${SCALES.pb(0)} ${SCALES.pl(0)};
margin: ${SCALES.mt(0)} ${SCALES.mr(0)} ${SCALES.mb(0)} ${SCALES.ml(0)};
}
.auto-complete :global(.loading) {
width: max-content;
}
`}</style>
</div>
</AutoCompleteContext.Provider>
)
},
)
AutoCompleteComponent.defaultProps = defaultProps
AutoCompleteComponent.displayName = 'GeistAutoComplete'
const AutoComplete = withScale(AutoCompleteComponent)
export default AutoComplete