-
Notifications
You must be signed in to change notification settings - Fork 338
Expand file tree
/
Copy pathgetPropGetters.ts
More file actions
379 lines (342 loc) · 11.5 KB
/
Copy pathgetPropGetters.ts
File metadata and controls
379 lines (342 loc) · 11.5 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { noop } from '@algolia/autocomplete-shared';
import { onInput } from './onInput';
import { onKeyDown } from './onKeyDown';
import {
AutocompleteScopeApi,
AutocompleteStore,
BaseItem,
GetEnvironmentProps,
GetFormProps,
GetInputProps,
GetItemProps,
GetLabelProps,
GetListProps,
GetPanelProps,
GetRootProps,
InternalAutocompleteOptions,
} from './types';
import { getActiveItem, isOrContainsNode, isSamsung } from './utils';
interface GetPropGettersOptions<TItem extends BaseItem>
extends AutocompleteScopeApi<TItem> {
store: AutocompleteStore<TItem>;
props: InternalAutocompleteOptions<TItem>;
}
export function getPropGetters<
TItem extends BaseItem,
TEvent,
TMouseEvent,
TKeyboardEvent
>({ props, refresh, store, ...setters }: GetPropGettersOptions<TItem>) {
const getEnvironmentProps: GetEnvironmentProps = (providedProps) => {
const { inputElement, formElement, panelElement, ...rest } = providedProps;
function onMouseDownOrTouchStart(event: MouseEvent | TouchEvent) {
// The `onTouchStart`/`onMouseDown` events shouldn't trigger the `blur`
// handler when it's not an interaction with Autocomplete.
// We detect it with the following heuristics:
// - the panel is closed AND there are no pending requests
// (no interaction with the autocomplete, no future state updates)
// - OR the touched target is the input element (should open the panel)
const isAutocompleteInteraction =
store.getState().isOpen || !store.pendingRequests.isEmpty();
if (!isAutocompleteInteraction || event.target === inputElement) {
return;
}
// @TODO: support cases where there are multiple Autocomplete instances.
// Right now, a second instance makes this computation return false.
const isTargetWithinAutocomplete = [formElement, panelElement].some(
(contextNode) => {
return isOrContainsNode(contextNode, event.target as Node);
}
);
if (isTargetWithinAutocomplete === false) {
store.dispatch('blur', null);
// If requests are still pending when the user closes the panel, they
// could reopen the panel once they resolve.
// We want to prevent any subsequent query from reopening the panel
// because it would result in an unsolicited UI behavior.
if (!props.debug) {
store.pendingRequests.cancelAll();
}
}
}
return {
// We do not rely on the native `blur` event of the input to close the
// panel, but rather on a custom `touchstart`/`mousedown` event outside
// of the autocomplete elements.
// This ensures we don't mistakenly interpret interactions within the
// autocomplete (but outside of the input) as a signal to close the panel.
// For example, clicking reset button causes an input blur, but if
// `openOnFocus=true`, it shouldn't close the panel.
// On touch devices, scrolling results (`touchmove`) causes an input blur
// but shouldn't close the panel.
onTouchStart: onMouseDownOrTouchStart,
onMouseDown: onMouseDownOrTouchStart,
// When scrolling on touch devices (mobiles, tablets, etc.), we want to
// mimic the native platform behavior where the input is blurred to
// hide the virtual keyboard. This gives more vertical space to
// discover all the suggestions showing up in the panel.
onTouchMove(event: TouchEvent) {
if (
store.getState().isOpen === false ||
inputElement !== props.environment.document.activeElement ||
event.target === inputElement
) {
return;
}
inputElement.blur();
},
...rest,
};
};
const getRootProps: GetRootProps = (rest) => {
return {
role: 'combobox',
'aria-expanded': store.getState().isOpen,
'aria-haspopup': 'listbox',
'aria-owns': store.getState().isOpen ? `${props.id}-list` : undefined,
'aria-labelledby': `${props.id}-label`,
...rest,
};
};
const getFormProps: GetFormProps<TEvent> = (providedProps) => {
const { inputElement, ...rest } = providedProps;
return {
action: '',
noValidate: true,
role: 'search',
onSubmit: (event) => {
((event as unknown) as Event).preventDefault();
props.onSubmit({
event,
refresh,
state: store.getState(),
...setters,
});
store.dispatch('submit', null);
providedProps.inputElement?.blur();
},
onReset: (event) => {
((event as unknown) as Event).preventDefault();
props.onReset({
event,
refresh,
state: store.getState(),
...setters,
});
store.dispatch('reset', null);
providedProps.inputElement?.focus();
},
...rest,
};
};
const getInputProps: GetInputProps<TEvent, TMouseEvent, TKeyboardEvent> = (
providedProps
) => {
function onFocus(event: TEvent) {
// We want to trigger a query when `openOnFocus` is true
// because the panel should open with the current query.
if (props.openOnFocus || Boolean(store.getState().query)) {
onInput({
event,
props,
query: store.getState().completion || store.getState().query,
refresh,
store,
...setters,
});
}
store.dispatch('focus', null);
}
const { inputElement, maxLength = 512, ...rest } = providedProps || {};
const activeItem = getActiveItem(store.getState());
const userAgent = props.environment.navigator?.userAgent || '';
const shouldFallbackKeyHint = isSamsung(userAgent);
const enterKeyHint =
activeItem?.itemUrl && !shouldFallbackKeyHint ? 'go' : 'search';
return {
'aria-autocomplete': 'both',
'aria-activedescendant':
store.getState().isOpen && store.getState().activeItemId !== null
? `${props.id}-item-${store.getState().activeItemId}`
: undefined,
'aria-controls': store.getState().isOpen ? `${props.id}-list` : undefined,
'aria-labelledby': `${props.id}-label`,
value: store.getState().completion || store.getState().query,
id: `${props.id}-input`,
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
enterKeyHint,
spellCheck: 'false',
autoFocus: props.autoFocus,
placeholder: props.placeholder,
maxLength,
type: 'search',
onChange: (event) => {
onInput({
event,
props,
query: (((event as unknown) as Event)
.currentTarget as HTMLInputElement).value.slice(0, maxLength),
refresh,
store,
...setters,
});
},
onKeyDown: (event) => {
onKeyDown({
event: (event as unknown) as KeyboardEvent,
props,
refresh,
store,
...setters,
});
},
onFocus,
// We don't rely on the `blur` event.
// See explanation in `onTouchStart`/`onMouseDown`.
// @MAJOR See if we need to keep this handler.
onBlur: noop,
onClick: (event) => {
// When the panel is closed and you click on the input while
// the input is focused, the `onFocus` event is not triggered
// (default browser behavior).
// In an autocomplete context, it makes sense to open the panel in this
// case.
// We mimic this event by catching the `onClick` event which
// triggers the `onFocus` for the panel to open.
if (
providedProps.inputElement ===
props.environment.document.activeElement &&
!store.getState().isOpen
) {
onFocus((event as unknown) as TEvent);
}
},
...rest,
};
};
const getAutocompleteId = (instanceId: string, sourceId: number) => {
return typeof sourceId !== 'undefined'
? `${instanceId}-${sourceId}`
: instanceId;
};
const getLabelProps: GetLabelProps = (providedProps) => {
const { sourceIndex, ...rest } = providedProps || {};
return {
htmlFor: `${getAutocompleteId(props.id, sourceIndex as number)}-input`,
id: `${getAutocompleteId(props.id, sourceIndex as number)}-label`,
...rest,
};
};
const getListProps: GetListProps = (providedProps) => {
const { sourceIndex, ...rest } = providedProps || {};
return {
role: 'listbox',
'aria-labelledby': `${getAutocompleteId(
props.id,
sourceIndex as number
)}-label`,
id: `${getAutocompleteId(props.id, sourceIndex as number)}-list`,
...rest,
};
};
const getPanelProps: GetPanelProps<TMouseEvent> = (rest) => {
return {
onMouseDown(event) {
// Prevents the `activeElement` from being changed to the panel so
// that the blur event is not triggered, otherwise it closes the
// panel.
((event as unknown) as MouseEvent).preventDefault();
},
onMouseLeave() {
store.dispatch('mouseleave', null);
},
...rest,
};
};
const getItemProps: GetItemProps<any, TMouseEvent> = (providedProps) => {
const { item, source, sourceIndex, ...rest } = providedProps;
return {
id: `${getAutocompleteId(props.id, sourceIndex as number)}-item-${
item.__autocomplete_id
}`,
role: 'option',
'aria-selected': store.getState().activeItemId === item.__autocomplete_id,
onMouseMove(event) {
if (item.__autocomplete_id === store.getState().activeItemId) {
return;
}
store.dispatch('mousemove', item.__autocomplete_id);
const activeItem = getActiveItem(store.getState());
if (store.getState().activeItemId !== null && activeItem) {
const { item, itemInputValue, itemUrl, source } = activeItem;
source.onActive({
event,
item,
itemInputValue,
itemUrl,
refresh,
source,
state: store.getState(),
...setters,
});
}
},
onMouseDown(event) {
// Prevents the `activeElement` from being changed to the item so it
// can remain with the current `activeElement`.
((event as unknown) as MouseEvent).preventDefault();
},
onClick(event) {
const itemInputValue = source.getItemInputValue({
item,
state: store.getState(),
});
const itemUrl = source.getItemUrl({
item,
state: store.getState(),
});
// If `getItemUrl` is provided, it means that the suggestion
// is a link, not plain text that aims at updating the query.
// We can therefore skip the state change because it will update
// the `activeItemId`, resulting in a UI flash, especially
// noticeable on mobile.
const runPreCommand = itemUrl
? Promise.resolve()
: onInput({
event,
nextState: { isOpen: false },
props,
query: itemInputValue,
refresh,
store,
...setters,
});
runPreCommand.then(() => {
source.onSelect({
event,
item,
itemInputValue,
itemUrl,
refresh,
source,
state: store.getState(),
...setters,
});
});
},
...rest,
};
};
return {
getEnvironmentProps,
getRootProps,
getFormProps,
getLabelProps,
getInputProps,
getPanelProps,
getListProps,
getItemProps,
};
}