-
Notifications
You must be signed in to change notification settings - Fork 554
Expand file tree
/
Copy pathcreateAutocompletePropGetters.ts
More file actions
364 lines (331 loc) · 9.85 KB
/
createAutocompletePropGetters.ts
File metadata and controls
364 lines (331 loc) · 9.85 KB
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
import { find } from '../../lib';
import type { ComponentProps, MutableRef } from '../../types';
type BaseHit = Record<string, unknown>;
export type AutocompleteIndexConfig<TItem extends BaseHit> = {
indexName: string;
getQuery?: (item: TItem) => string;
getURL?: (item: TItem) => string;
onSelect?: (params: {
item: TItem;
query: string;
setQuery: (query: string) => void;
url?: string;
}) => void;
};
type GetInputProps = () => ComponentProps<'input'>;
type ValidAriaRole = 'combobox' | 'row' | 'grid';
type GetItemProps = (
item: { __indexName: string } & Record<string, unknown>,
index: number
) => {
id?: string;
role?: ValidAriaRole;
'aria-selected'?: boolean;
} & {
onSelect: () => void;
onApply: () => void;
};
type GetPanelProps = () => {
id?: string;
hidden?: boolean;
role?: ValidAriaRole;
'aria-labelledby'?: string;
};
type GetRootProps = () => { ref?: MutableRef<HTMLDivElement | null> };
type CreateAutocompletePropGettersParams = {
useEffect: (effect: () => void, inputs?: readonly unknown[]) => void;
useId: () => string;
useMemo: <TType>(factory: () => TType, inputs: readonly unknown[]) => TType;
useRef: <TType>(initialValue: TType | null) => { current: TType | null };
useState: <TType>(
initialState: TType
) => [TType, (newState: TType) => unknown];
};
export type UsePropGetters<TItem extends BaseHit> = (params: {
indices: Array<{
indexName: string;
indexId: string;
hits: Array<{ [key: string]: unknown }>;
}>;
indicesConfig: Array<AutocompleteIndexConfig<TItem>>;
onRefine: (query: string) => void;
onSelect: NonNullable<AutocompleteIndexConfig<TItem>['onSelect']>;
onApply: (query: string) => void;
/**
* Called when the form is submitted (Enter pressed).
* Useful for detached mode to close the modal.
*/
onSubmit?: () => void;
placeholder?: string;
/**
* Whether the autocomplete is in detached mode (mobile).
* In detached mode:
* - Panel stays open (doesn't close on body click)
* - Tab key doesn't close panel
*/
isDetached?: boolean;
/**
* Whether the panel should be hidden even when open
* (e.g., when all sources are empty and there's no custom content to show).
*/
shouldHidePanel?: boolean;
/**
* Whether the input should be focused and the panel open initially.
*/
autoFocus?: boolean;
}) => {
getInputProps: GetInputProps;
getItemProps: GetItemProps;
getPanelProps: GetPanelProps;
getRootProps: GetRootProps;
/**
* Whether the panel is open.
*/
isOpen: boolean;
/**
* Function to set the panel open state. Useful for detached mode.
*/
setIsOpen: (isOpen: boolean) => void;
/**
* Function to focus the input. Useful for detached mode to show the keyboard.
*/
focusInput: () => void;
};
export function createAutocompletePropGetters({
useEffect,
useId,
useMemo,
useRef,
useState,
}: CreateAutocompletePropGettersParams) {
return function usePropGetters<TItem extends BaseHit>({
indices,
indicesConfig,
onRefine,
onSelect: globalOnSelect,
onApply,
onSubmit,
placeholder,
isDetached = false,
shouldHidePanel = false,
autoFocus = false,
}: Parameters<UsePropGetters<TItem>>[0]): ReturnType<UsePropGetters<TItem>> {
const getElementId = createGetElementId(useId());
const inputRef = useRef<HTMLInputElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
const [isOpen, setIsOpen] = useState(autoFocus);
const [activeDescendant, setActiveDescendant] = useState<
string | undefined
>(undefined);
const { items, itemsIds } = useMemo(
() => buildItems({ indices, indicesConfig, getElementId }),
[indices, indicesConfig, getElementId]
);
useEffect(() => {
// In detached mode, we don't close the panel on body click
// because the overlay handles closing
if (isDetached) {
return () => {};
}
const onBodyClick = (event: MouseEvent) => {
if (unwrapRef(rootRef)?.contains(event.target as HTMLElement)) {
return;
}
setIsOpen(false);
};
document.body.addEventListener('click', onBodyClick);
return () => {
document.body.removeEventListener('click', onBodyClick);
};
}, [rootRef, isDetached]);
const getNextActiveDescendant = (key: string): string | undefined => {
switch (key) {
case 'ArrowUp': {
const prevIndex = itemsIds.indexOf(activeDescendant || '') - 1;
return itemsIds[prevIndex] || itemsIds[itemsIds.length - 1];
}
case 'ArrowDown': {
const nextIndex = itemsIds.indexOf(activeDescendant || '') + 1;
return itemsIds[nextIndex] || itemsIds[0];
}
default:
return undefined;
}
};
const submit = (
override: {
query?: string;
activeDescendant?: string;
} = {}
) => {
if (isOpen) {
setIsOpen(false);
} else {
inputRef.current?.blur();
}
const actualDescendant = override.activeDescendant ?? activeDescendant;
if (!actualDescendant && override.query) {
onRefine(override.query);
}
if (actualDescendant && items.has(actualDescendant)) {
const {
item,
config: { onSelect: indexOnSelect, getQuery, getURL },
} = items.get(actualDescendant)!;
const actualOnSelect = indexOnSelect ?? globalOnSelect;
actualOnSelect({
item,
query: getQuery?.(item) ?? '',
url: getURL?.(item),
setQuery: (query) => onRefine(query),
});
setActiveDescendant(undefined);
}
onSubmit?.();
};
return {
getInputProps: () => ({
id: getElementId('input'),
ref: inputRef,
role: 'combobox',
autoFocus,
'aria-autocomplete': 'list',
'aria-expanded': isOpen,
'aria-haspopup': 'grid',
'aria-controls': getElementId('panel'),
'aria-activedescendant': activeDescendant,
placeholder,
onFocus: () => setIsOpen(true),
onKeyDown: (event) => {
switch (event.key) {
case 'Escape': {
if (isOpen) {
setIsOpen(false);
event.preventDefault();
} else {
setActiveDescendant(undefined);
}
break;
}
case 'ArrowUp':
case 'ArrowDown': {
setIsOpen(true);
const nextActiveDescendant = getNextActiveDescendant(event.key)!;
setActiveDescendant(nextActiveDescendant);
document
.getElementById(nextActiveDescendant)
?.scrollIntoView(false);
event.preventDefault();
break;
}
case 'Enter': {
submit({ query: (event.target as HTMLInputElement).value });
break;
}
case 'Tab':
// In detached mode, Tab doesn't close the panel
if (!isDetached) {
setIsOpen(false);
}
break;
default:
setIsOpen(true);
return;
}
},
onKeyUp: (event) => {
switch (event.key) {
case 'ArrowLeft':
case 'ArrowUp':
case 'ArrowRight':
case 'ArrowDown':
case 'Escape':
case 'Return':
event.preventDefault();
return;
default:
setActiveDescendant(undefined);
break;
}
},
}),
getItemProps: (item, index) => {
const id = getElementId('item', item.__indexName, index);
return {
id,
role: 'row',
'aria-selected': id === activeDescendant,
onSelect: () => submit({ activeDescendant: id }),
onApply: () => {
const {
item: currentItem,
config: { getQuery },
} = items.get(id)!;
onApply(getQuery?.(currentItem) ?? '');
},
};
},
getPanelProps: () => ({
hidden: !isOpen || shouldHidePanel,
id: getElementId('panel'),
role: 'grid',
'aria-labelledby': getElementId('input'),
}),
getRootProps: () => ({
ref: rootRef,
}),
isOpen,
setIsOpen,
focusInput: () => {
inputRef.current?.focus();
},
};
};
}
function buildItems<TItem extends BaseHit>({
indices,
indicesConfig,
getElementId,
}: Pick<Parameters<UsePropGetters<TItem>>[0], 'indices' | 'indicesConfig'> & {
getElementId: ReturnType<typeof createGetElementId>;
}) {
const itemsIds = [];
const items = new Map<
string,
{ item: TItem; config: AutocompleteIndexConfig<TItem> }
>();
for (let i = 0; i < indices.length; i++) {
const currentIndexConfig = find(
indicesConfig,
(config) => config.indexName === indices[i].indexName
);
const hits = indices[i]?.hits || [];
for (let position = 0; position < hits.length; position++) {
const itemId = getElementId(
'item',
currentIndexConfig?.indexName || indices[i].indexName,
position
);
items.set(itemId, {
item: hits[position] as TItem,
config: currentIndexConfig!,
});
itemsIds.push(itemId);
}
}
return { items, itemsIds };
}
function createGetElementId(autocompleteId: string) {
return function getElementId(...suffixes: Array<string | number>) {
const prefix = 'autocomplete';
return `${prefix}${autocompleteId}${suffixes.join(':')}`;
};
}
/**
* Returns the framework-agnostic value of a ref.
*/
function unwrapRef<TType>(ref: { current: TType | null }): TType | null {
return ref.current && typeof ref.current === 'object' && 'base' in ref.current
? (ref.current.base as TType) // Preact
: ref.current; // React
}