/
AutoComplete.tsx
431 lines (404 loc) · 11.4 KB
/
AutoComplete.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import React, { FC, forwardRef, Fragment } from "react";
import cn from "classnames";
import {
isListboxOptionProps,
ListboxOptionProps,
Option,
TextField,
TextFieldProps,
} from "@react-md/form";
import { List } from "@react-md/list";
import { RenderConditionalPortalProps } from "@react-md/portal";
import { ScaleTransition } from "@react-md/transition";
import { bem, omit, WithForwardedRef } from "@react-md/utils";
import HighlightLabel from "./HighlightLabel";
import useAutoComplete, { PositionOptions } from "./useAutoComplete";
import {
AutoCompleteData,
AutoCompleteFilterFunction,
AutoCompleteHandler,
AutoCompletion,
} from "./types";
import {
getResultId as DEFAULT_GET_RESULT_ID,
getResultLabel as DEFAULT_GET_RESULT_LABEL,
getResultValue as DEFAULT_GET_RESULT_VALUE,
} from "./utils";
export interface AutoCompleteProps
extends Omit<TextFieldProps, "type" | "value" | "defaultValue">,
RenderConditionalPortalProps,
PositionOptions {
/**
* The id to use for the AutoComplete and is required for a11y to fulfill the `combobox` role. This
* id will be passed directly to the `<input>` element and prefixed for all the other id-required
* elements.
*/
id: string;
/**
* @see AutoCompletion
*/
autoComplete?: AutoCompletion;
/**
* Boolean if the text field's value should be cleared when the value is autocompleted. This is useful
* when also adding custom `onAutoComplete` behavior.
*/
clearOnAutoComplete?: boolean;
/**
* The list of data that should be autocompleted based on the provided filter.
*/
data: AutoCompleteData[];
/**
* @see AutoCompleteFilterFunction
*/
filter?: AutoCompleteFilterFunction;
/**
* An optional object of options to provide to the filter function. This will be defaulted to work
* with the fuzzy filter and case-insensitive filter functions to trim whitespace before doing the
* comarisons.
*/
filterOptions?: {};
/**
* An optional className to also apply to the listbox element showing all the matches.
*/
listboxClassName?: string;
/**
* The key to use to extract a label from a result when the provided data list is a list of objects.
*/
labelKey?: string;
/**
* The key to use to extract a searchable value string from a result when the provided data list is a
* list of objects.
*/
valueKey?: string;
/**
* A function to call that will generate an id for each result in the autocomplete's listbox. These ids
* are required for a11y as it'll be used with the `aria-activedescendant` movement within the autocomplete.
*/
getResultId?: typeof DEFAULT_GET_RESULT_ID;
/**
* A function to call that will get a renderable label or children to display for a result in the autocomplete's
* list of results. The default behavior will be to return the result itself if it is a string, otherwise try
* to return the `children` or `labelKey` attribute if it is an object.
*/
getResultLabel?: typeof DEFAULT_GET_RESULT_LABEL;
/**
* A function to call that will extract a searchable value string from each result. This **must** return a string
* and will prevent the autocomplete from filtering data with the built in filter functions.
*/
getResultValue?: typeof DEFAULT_GET_RESULT_VALUE;
/**
* @see AutoCompleteHandler
*/
onAutoComplete?: AutoCompleteHandler;
/**
* Boolean if the result list labels should be updated so that each matching letter is bolded. This
* only works when the data list is a list of strings, or the `label` is a string and when the
* letters appear in order. This will always be false if the `filter` prop is set to `"fuzzy"`.
*/
highlight?: boolean;
}
type WithRef = WithForwardedRef<HTMLInputElement>;
type DefaultProps = Required<
Pick<
AutoCompleteProps,
| "autoComplete"
| "clearOnAutoComplete"
| "portal"
| "highlight"
| "filter"
| "filterOptions"
| "labelKey"
| "valueKey"
| "getResultId"
| "getResultLabel"
| "getResultValue"
| "anchor"
| "xMargin"
| "yMargin"
| "vwMargin"
| "vhMargin"
| "transformOrigin"
| "listboxWidth"
| "preventOverlap"
| "disableSwapping"
| "disableVHBounds"
| "disableHideOnResize"
| "disableHideOnScroll"
>
>;
type WithDefaultProps = AutoCompleteProps & DefaultProps & WithRef;
const block = bem("rmd-autocomplate");
const listbox = bem("rmd-listbox");
/**
* An AutoComplete is an accessible combobox widget that allows for real-time suggestions
* as the user types.
*/
const AutoComplete: FC<AutoCompleteProps & WithRef> = providedProps => {
const {
autoComplete,
data,
filter,
filterOptions,
className,
onBlur,
onFocus,
onClick,
onKeyDown,
onChange,
containerProps,
portal,
portalInto,
portalIntoId,
listboxStyle,
listboxClassName,
forwardedRef,
onAutoComplete,
clearOnAutoComplete,
labelKey,
valueKey,
getResultId,
getResultLabel,
getResultValue,
highlight,
anchor,
listboxWidth,
xMargin,
yMargin,
vwMargin,
vhMargin,
transformOrigin,
preventOverlap,
disableSwapping,
disableVHBounds,
disableHideOnResize,
disableHideOnScroll,
...props
} = providedProps as WithDefaultProps;
const { id } = props;
const comboboxId = `${id}-combobox`;
const suggestionsId = `${id}-listbox`;
const isHighlight =
highlight &&
(filter === "case-insensitive" || typeof filter === "function");
const {
ref,
value,
visible,
activeId,
itemRefs,
filteredData,
fixedStyle,
transitionHooks,
handleBlur,
handleFocus,
handleClick,
handleChange,
handleKeyDown,
handleAutoComplete,
} = useAutoComplete({
autoComplete,
suggestionsId,
data,
filter,
filterOptions,
valueKey,
getResultId,
getResultValue,
onBlur,
onFocus,
onClick,
onChange,
onKeyDown,
forwardedRef,
onAutoComplete,
clearOnAutoComplete,
anchor,
xMargin,
yMargin,
vwMargin,
vhMargin,
transformOrigin,
listboxWidth,
listboxStyle,
preventOverlap,
disableSwapping,
disableVHBounds,
disableHideOnResize,
disableHideOnScroll,
});
return (
<Fragment>
<TextField
{...props}
aria-autocomplete={autoComplete}
aria-controls={comboboxId}
aria-activedescendant={activeId}
autoComplete="off"
value={value}
onBlur={handleBlur}
onFocus={handleFocus}
onClick={handleClick}
onKeyDown={handleKeyDown}
onChange={handleChange}
ref={ref}
className={cn(block(), className)}
containerProps={{
...containerProps,
"aria-haspopup": "listbox",
"aria-owns": suggestionsId,
"aria-expanded": visible,
id: comboboxId,
role: "combobox",
}}
/>
<ScaleTransition
portal={portal}
portalInto={portalInto}
portalIntoId={portalIntoId}
vertical
visible={visible}
{...transitionHooks}
>
<List
id={suggestionsId}
role="listbox"
style={fixedStyle}
className={cn(listbox({ temporary: true }), listboxClassName)}
>
{filteredData.map((datum, i) => {
const resultId = getResultId(suggestionsId, i);
let optionProps: ListboxOptionProps | undefined;
if (isListboxOptionProps(datum)) {
optionProps = omit(datum, [labelKey, valueKey]);
}
return (
<Option
key={resultId}
id={resultId}
{...optionProps}
selected={false}
focused={resultId === activeId}
ref={itemRefs[i]}
onClick={() => handleAutoComplete(i)}
>
<HighlightLabel enabled={isHighlight} value={value}>
{getResultLabel(datum, labelKey, value)}
</HighlightLabel>
</Option>
);
})}
</List>
</ScaleTransition>
</Fragment>
);
};
const defaultProps: DefaultProps = {
portal: false,
filter: "case-insensitive",
filterOptions: {
trim: true,
ignoreWhitespace: true,
},
autoComplete: "list",
clearOnAutoComplete: false,
labelKey: "label",
valueKey: "value",
getResultId: DEFAULT_GET_RESULT_ID,
getResultLabel: DEFAULT_GET_RESULT_LABEL,
getResultValue: DEFAULT_GET_RESULT_VALUE,
highlight: false,
anchor: {
x: "center",
y: "below",
},
xMargin: 0,
yMargin: 0,
vwMargin: 16,
vhMargin: 16,
transformOrigin: true,
listboxWidth: "equal",
preventOverlap: true,
disableSwapping: false,
disableVHBounds: false,
disableHideOnResize: false,
disableHideOnScroll: true,
};
AutoComplete.defaultProps = defaultProps;
if (process.env.NODE_ENV !== "production") {
AutoComplete.displayName = "AutoComplete";
let PropTypes;
try {
PropTypes = require("prop-types");
} catch (e) {}
if (PropTypes) {
AutoComplete.propTypes = {
id: PropTypes.string.isRequired,
data: PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.string, PropTypes.object])
).isRequired,
filter: PropTypes.oneOfType([
PropTypes.oneOf(["none", "fuzzy", "case-insensitive"]),
PropTypes.func,
]),
filterOptions: PropTypes.object,
labelKey: PropTypes.string,
valueKey: PropTypes.string,
getResultId: PropTypes.func,
getResultLabel: PropTypes.func,
getResultValue: PropTypes.func,
highlight: PropTypes.bool,
autoComplete: PropTypes.oneOf(["none", "inline", "list", "both"]),
onAutoComplete: PropTypes.func,
clearOnAutoComplete: PropTypes.bool,
portal: PropTypes.bool,
portalInto: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
PropTypes.object,
]),
portalIntoId: PropTypes.string,
anchor: PropTypes.shape({
x: PropTypes.oneOf([
"inner-left",
"inner-right",
"center",
"left",
"right",
]),
y: PropTypes.oneOf(["above", "below", "center", "top", "bottom"]),
}),
listboxWidth: PropTypes.oneOf(["auto", "equal", "min"]),
vwMargin: PropTypes.number,
vhMargin: PropTypes.number,
xMargin: PropTypes.number,
yMargin: PropTypes.number,
transformOrigin: PropTypes.bool,
preventOverlap: PropTypes.bool,
disableSwapping: PropTypes.bool,
disableVHBounds: PropTypes.bool,
disableHideOnResize: PropTypes.bool,
disableHideOnScroll: PropTypes.bool,
style: PropTypes.object,
className: PropTypes.string,
inputStyle: PropTypes.object,
inputClassName: PropTypes.string,
labelStyle: PropTypes.object,
labelClassName: PropTypes.string,
label: PropTypes.node,
theme: PropTypes.oneOf(["none", "underline", "filled", "outline"]),
dense: PropTypes.bool,
error: PropTypes.bool,
inline: PropTypes.bool,
disabled: PropTypes.bool,
placeholder: PropTypes.string,
underlineDirection: PropTypes.oneOf(["left", "right"]),
leftChildren: PropTypes.node,
rightChildren: PropTypes.node,
isLeftAddon: PropTypes.bool,
isRightAddon: PropTypes.bool,
};
}
}
export default forwardRef<HTMLInputElement, AutoCompleteProps>((props, ref) => (
<AutoComplete {...props} forwardedRef={ref} />
));