-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathautocomplete.js
More file actions
245 lines (215 loc) · 7.4 KB
/
autocomplete.js
File metadata and controls
245 lines (215 loc) · 7.4 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
const LOCATION_OPTION = Drupal.t('Use current Location', {}, { context: 'Location autocomplete' });
const API_URL = 'https://api.hel.fi/servicemap/v2/address/';
const LOCATION_LOADING = 'location-loading';
const { currentLanguage } = drupalSettings.path;
const locationOptionLabel = `
<div>
<span class="hel-icon hel-icon--locate" role="img" aria-hidden="true"></span>
${LOCATION_OPTION}
</div>
`;
let abortController = new AbortController();
/**
* Get the most appropriate translation for address.
*
* @param {object} fullName - Translations object
* @return {string} - the result
*/
const getTranslation = (fullName) => {
if (fullName[currentLanguage]) {
return fullName[currentLanguage];
}
if (fullName.fi) {
return fullName.fi;
}
return Object.values(fullName)[0];
};
((Drupal, once) => {
/**
* Initialize autocomplete.
*
* @param {HTMLSelectElement} element Select element.
*/
const init = (element) => {
// eslint-disable-next-line no-undef
if (!A11yAutocomplete) {
throw new Error('A11yAutocomplete object not found. Make sure the library is loaded.');
}
// Dont add 'Use current location' option if location not available
let defaultOptions =
'geolocation' in navigator
? [
{
label: locationOptionLabel,
value: LOCATION_OPTION,
index: 0,
// minCharAssistiveHint doesn't seem to work when there is always one item.
item: { label: LOCATION_OPTION, value: LOCATION_OPTION },
},
]
: [];
const parent = element.closest('.hds-text-input');
/**
* Renders automatic location error.
*/
const displayLocationError = () => {
parent.classList.add('hds-text-input--invalid');
const errorSpan = document.createElement('span');
errorSpan.classList.add('hds-text-input__error-text');
errorSpan.id = 'js-locate-error';
errorSpan.textContent = Drupal.t(
"We couldn't retrieve your current location. Try entering an address.",
{},
{ context: 'Location autocomplete' },
);
parent.appendChild(errorSpan);
// Remove automatic location from default options
defaultOptions = [];
};
/**
* Removes automatic location error.
*/
const removeLocationError = () => {
parent.classList.remove('hds-text-input--invalid');
parent.querySelector('.hds-text-input__error-text')?.remove();
};
const minCharAssistiveHint = Drupal.t(
'Type @count or more characters for results',
{},
{ context: 'Location autocomplete' },
);
const inputAssistiveHint = Drupal.t(
'When autocomplete results are available use up and down arrows to review and enter to select. Touch device users, explore by touch or with swipe gestures.',
{},
{ context: 'Location autocomplete' },
);
const noResultsAssistiveHint = Drupal.t(
'No address suggestions were found',
{},
{ context: 'Location autocomplete' },
);
const someResultsAssistiveHint = Drupal.t(
'There are @count results available.',
{},
{ context: 'Location autocomplete' },
);
const oneResultAssistiveHint = Drupal.t('There is one result available.', {}, { context: 'Location autocomplete' });
const highlightedAssistiveHint = Drupal.t(
'@selectedItem @position of @count is highlighted',
{},
{ context: 'Location autocomplete' },
);
// Set by '#autocomplete_route_name'.
const autocompleteRoute = element.dataset.autocompletePath;
// eslint-disable-next-line no-undef
const autocomplete = A11yAutocomplete(element, {
allowRepeatValues: true,
classes: { inputLoading: 'loading', wrapper: 'helfi-location-autocomplete' },
highlightedAssistiveHint,
inputAssistiveHint,
minCharAssistiveHint,
minChars: 0,
noResultsAssistiveHint,
oneResultAssistiveHint,
someResultsAssistiveHint,
source: async (searchTerm, results) => {
try {
abortController.abort();
abortController = new AbortController();
if (searchTerm.length < 3) {
return results(defaultOptions);
}
const reqUrl = new URL(autocompleteRoute, window.location.origin);
reqUrl.searchParams.set('q', searchTerm);
const response = await fetch(reqUrl.toString(), { signal: abortController.signal });
const data = await response.json();
results(defaultOptions.concat(data));
} catch (e) {
if (e.name === 'AbortError') {
return;
}
// eslint-disable-next-line no-console
console.error(e);
results(defaultOptions);
}
},
});
const autocompleteInstance = autocomplete._internal_object;
/**
* Reflect loading and filling location in UI.
*
* @param {boolean} state - true to set loading.
*/
const setLoading = (state) => {
autocompleteInstance.close();
if (state) {
element.classList.toggle(LOCATION_LOADING, true);
return;
}
element.classList.toggle(LOCATION_LOADING, false);
};
// Handle automatic location selection
element.addEventListener('autocomplete-select', (event) => {
if (event.detail.selected.value !== LOCATION_OPTION) {
return;
}
event.preventDefault();
setLoading(element, autocompleteInstance, true);
navigator.geolocation.getCurrentPosition(
async (position) => {
const {
coords: { latitude, longitude },
} = position;
const params = new URLSearchParams({ lat: latitude, lon: longitude });
const reqUrl = new URL(API_URL);
reqUrl.search = params.toString();
try {
const response = await fetch(reqUrl.toString());
const json = await response.json();
event.target.value = getTranslation(json.results[0].full_name);
} catch (_e) {
displayLocationError();
} finally {
setLoading(false);
}
},
() => {
displayLocationError();
setLoading(false);
},
);
});
// Opens the dropdown on focus when input is empty
// Not supported by the a11y-autocomplete library
element.addEventListener('focus', () => {
if (element.classList.contains(LOCATION_LOADING)) {
return;
}
if (autocompleteInstance.input.value === '' && defaultOptions.length) {
autocompleteInstance.displayResults(defaultOptions);
}
});
// Similar to above, allow opening list with arrow keys
element.addEventListener('keydown', (event) => {
if (
autocompleteInstance.input.value === '' &&
defaultOptions.length &&
autocompleteInstance.suggestions.length === 0 &&
event.key === 'ArrowDown'
) {
autocompleteInstance.displayResults(defaultOptions);
}
});
// Hide location error input when changing input
element.addEventListener('change', removeLocationError);
// Focus input if there is a validation error on page load.
if (element.classList.contains('error')) {
element.focus();
}
};
Drupal.behaviors.helfi_location_autocomplete = {
attach(context) {
once('a11y_autocomplete_element', '[data-helfi-location-autocomplete]', context).forEach(init);
},
};
})(Drupal, once);