-
-
Notifications
You must be signed in to change notification settings - Fork 284
/
Copy pathAutocomplete.svelte
433 lines (395 loc) · 11.3 KB
/
Autocomplete.svelte
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
432
433
<div
bind:this={element}
use:Anchor
use:useActions={use}
use:forwardEvents
class={classMap({
[className]: true,
'smui-autocomplete': true,
})}
{...exclude($$restProps, ['menu$', 'textfield$', 'list$'])}
>
<div
bind:this={inputContainer}
on:focusin={() => {
focused = true;
}}
on:focusout={handleTextfieldBlur}
on:input={() => {
focusedIndex = -1;
}}
on:keydown|capture={handleTextfieldKeydown}
>
<slot>
<Textfield
{label}
{disabled}
bind:value={text}
{...prefixFilter($$restProps, 'textfield$')}
/>
</slot>
</div>
<Menu
class={classMap({
[menu$class]: true,
'smui-autocomplete__menu': true,
})}
managed
open={menuOpen}
bind:anchorElement={element}
anchor={menu$anchor}
anchorCorner={menu$anchorCorner}
on:SMUIList:mount={handleListAccessor}
{...prefixFilter($$restProps, 'menu$')}
>
<List {...prefixFilter($$restProps, 'list$')}>
{#if loading}
<Item disabled>
<slot name="loading">
<Text>Loading...</Text>
</slot>
</Item>
{:else if error}
<Item disabled>
<slot name="error">
<Text>Error while fetching suggestions.</Text>
</slot>
</Item>
{:else}
{#each matches as match, i}
<Item
disabled={getOptionDisabled(match)}
selected={match === value}
on:mouseenter={() => {
focusedIndex = i;
}}
on:SMUI:action={() =>
toggle ? toggleOption(match) : selectOption(match)}
>
<slot name="match" {match}>
<Text>{getOptionLabel(match)}</Text>
</slot>
</Item>
{:else}
<Item
disabled={noMatchesActionDisabled}
on:SMUI:action={(e) =>
dispatch(element, 'SMUIAutocomplete:noMatchesAction', e)}
>
<slot name="no-matches">
<Text>No matches found.</Text>
</slot>
</Item>
{/each}
{/if}
</List>
</Menu>
</div>
<script lang="ts">
import { get_current_component } from 'svelte/internal';
import type { SmuiAttrs } from '@smui/common';
import type { ActionArray } from '@smui/common/internal';
import {
forwardEventsBuilder,
classMap,
exclude,
prefixFilter,
useActions,
dispatch,
} from '@smui/common/internal';
import Textfield from '@smui/textfield';
import Menu from '@smui/menu';
import type { SMUIListAccessor, SMUIListItemAccessor } from '@smui/list';
import List, { Item, Text } from '@smui/list';
import { Anchor } from '@smui/menu-surface';
type OwnProps = {
use?: ActionArray;
class?: string;
variant?: 'text' | 'raised' | 'unelevated' | 'outlined';
options?: (() => Promise<any[]>) | any[];
value?: any;
getOptionDisabled?: (option: any) => boolean;
getOptionLabel?: (option: any) => string;
text?: string;
label?: string | undefined;
disabled?: boolean;
toggle?: boolean;
combobox?: boolean;
clearOnBlur?: boolean;
selectOnExactMatch?: boolean;
showMenuWithNoInput?: boolean;
noMatchesActionDisabled?: boolean;
search?: (input: string) => Promise<any[] | false>;
menu$class?: string;
menu$anchor?: boolean;
menu$anchorCorner?: Menu['$$prop_def']['anchorCorner'];
};
type $$Props = OwnProps &
SmuiAttrs<'div', OwnProps> & {
[k in keyof Menu['$$prop_def'] as `menu\$${k}`]?: Menu['$$prop_def'][k];
} & {
[k in keyof Textfield['$$prop_def'] as `textfield\$${k}`]?: Textfield['$$prop_def'][k];
} & {
[k in keyof InstanceType<
typeof List
>['$$prop_def'] as `list\$${k}`]?: InstanceType<
typeof List
>['$$prop_def'][k];
} & {
textfield$label?: never;
textfield$value?: never;
};
const forwardEvents = forwardEventsBuilder(get_current_component());
// Remember to update $$Props if you add/remove/rename props.
export let use: ActionArray = [];
let className = '';
export { className as class };
export let options: (() => Promise<any[]>) | any[] = [];
export let value: any = undefined;
export let getOptionDisabled: (option: any) => boolean = () => false;
export let getOptionLabel: (option: any) => string = (option: any) =>
option == null ? '' : `${option}`;
export let text = getOptionLabel(value);
export let label: string | undefined = undefined;
export let disabled = false;
export let toggle = false;
export let combobox = false;
export let clearOnBlur = !combobox;
export let selectOnExactMatch = true;
export let showMenuWithNoInput = true;
export let noMatchesActionDisabled = true;
export let search: (input: string) => Promise<any[] | false> = async (
input: string
) => {
const linput = input.toLowerCase();
const fullOptions =
typeof options == 'function' ? await options() : options || [];
if (linput === '') {
return fullOptions;
}
const result = fullOptions.filter((item) =>
getOptionLabel(item).toLowerCase().includes(linput)
);
result.sort((a, b) => {
const aString = getOptionLabel(a).toLowerCase();
const bString = getOptionLabel(b).toLowerCase();
if (aString.startsWith(linput) && !bString.startsWith(linput)) {
return -1;
} else if (bString.startsWith(linput) && !aString.startsWith(linput)) {
return 1;
}
return 0;
});
return result;
};
export let menu$class = '';
export let menu$anchor = false;
export let menu$anchorCorner: Menu['$$prop_def']['anchorCorner'] =
'BOTTOM_START';
let element: HTMLDivElement;
let inputContainer: HTMLDivElement;
let loading = false;
let error = false;
let focused = false;
let listAccessor: SMUIListAccessor;
let matches: any[] = [];
let focusedIndex = -1;
let focusedItem: SMUIListItemAccessor | undefined = undefined;
$: menuOpen =
focused &&
(text !== '' || showMenuWithNoInput) &&
(loading ||
(!combobox && !(matches.length === 1 && matches[0] === value)) ||
(combobox &&
!!matches.length &&
!(matches.length === 1 && matches[0] === value)));
let previousText: string | undefined = undefined;
$: if (previousText !== text) {
if (!combobox && value != null && getOptionLabel(value) !== text) {
deselectOption(value, false);
}
(async () => {
loading = true;
error = false;
try {
const searchResult = await search(text);
if (searchResult !== false) {
matches = searchResult;
if (selectOnExactMatch) {
const exactMatch = matches.find(
(match) => getOptionLabel(match) === text
);
if (exactMatch && value !== exactMatch) {
selectOption(exactMatch);
}
}
}
} catch (e: any) {
error = true;
}
loading = false;
})();
previousText = text;
}
let previousValue = value;
$: if (!combobox && previousValue !== value) {
// If the value changes from outside, update the text.
text = getOptionLabel(value);
previousValue = value;
} else if (combobox) {
// If the text changes, update value if we're a combobox.
value = text;
}
let previousFocusedIndex: number | undefined = undefined;
$: if (previousFocusedIndex !== focusedIndex) {
const activeItems = getActiveMenuItems();
if (focusedIndex === -1) {
focusedItem = undefined;
} else {
focusedItem = activeItems[focusedIndex];
if (focusedItem) {
focusedItem.activated = true;
if (!isInViewport(focusedItem.element)) {
focusedItem.element.scrollIntoView({
block: 'end',
inline: 'nearest',
});
}
}
}
activeItems.forEach((item, i) => {
if (i !== focusedIndex) {
item.activated = false;
}
});
if (listAccessor) {
listAccessor.getOrderedList().forEach((itemAccessor) => {
itemAccessor.tabindex = -1;
});
}
previousFocusedIndex = focusedIndex;
}
function handleListAccessor(event: CustomEvent<SMUIListAccessor>) {
if (!listAccessor) {
listAccessor = event.detail;
}
}
function selectOption(option: any, setText = true) {
if (setText) {
text = getOptionLabel(option);
}
value = option;
if (!setText) {
previousValue = option;
}
dispatch(element, 'SMUIAutocomplete:selected', option);
}
function deselectOption(option: any, setText = true) {
if (setText) {
text = '';
}
value = undefined;
if (!setText) {
previousValue = undefined;
}
dispatch(element, 'SMUIAutocomplete:deselected', option);
}
function toggleOption(option: any) {
if (option === value) {
deselectOption(option);
} else {
selectOption(option);
}
}
function isInViewport(elem: Element) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <=
(window.innerWidth || document.documentElement.clientWidth)
);
}
function getActiveMenuItems() {
if (!listAccessor) {
return [];
}
return listAccessor
.getOrderedList()
.filter((itemAccessor) => !itemAccessor.disabled);
}
function handleTextfieldKeydown(e: KeyboardEvent) {
if (combobox && !matches.length) {
return;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
if (
focusedIndex === -1 ||
focusedIndex === getActiveMenuItems().length - 1
) {
focusedIndex = 0;
} else {
focusedIndex++;
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (focusedIndex === -1 || focusedIndex === 0) {
focusedIndex = getActiveMenuItems().length - 1;
} else {
focusedIndex--;
}
} else if (e.key === 'Enter') {
e.preventDefault();
const activeItems = getActiveMenuItems();
if (focusedItem) {
if (activeItems[focusedIndex]) {
activeItems[focusedIndex].action(e);
}
focusedIndex = -1;
}
}
}
async function handleTextfieldBlur(event: FocusEvent) {
// Check if the reason we're unfocusing is that the user clicked an item.
if (
event.relatedTarget &&
getActiveMenuItems()
.map((itemAccessor) => itemAccessor.element)
.indexOf(event.relatedTarget as Element) !== -1
) {
return;
}
// Else, clear the currently focused item and mark as not focused.
focusedIndex = -1;
focused = false;
if (clearOnBlur && value == null) {
text = '';
}
}
export function focus() {
if (inputContainer) {
const inputEl = inputContainer.querySelector<HTMLInputElement>(
'input.mdc-text-field__input'
);
if (inputEl) {
inputEl.focus();
}
}
}
export function blur() {
if (inputContainer) {
const inputEl = inputContainer.querySelector<HTMLInputElement>(
'input.mdc-text-field__input'
);
if (inputEl) {
inputEl.blur();
}
}
}
export function getElement() {
return element;
}
</script>