MDL-69107 form_autocomplete: Rewrite item selection
[moodle.git] / lib / amd / src / form-autocomplete.js
CommitLineData
60a1ea56
DW
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Autocomplete wrapper for select2 library.
18 *
19 * @module core/form-autocomplete
20 * @class autocomplete
21 * @package core
22 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @since 3.0
25 */
26/* globals require: false */
df5feea4 27define(
7cc18dc2
AN
28 ['jquery', 'core/log', 'core/str', 'core/templates', 'core/notification', 'core/loadingicon', 'core/aria'],
29function($, log, str, templates, notification, LoadingIcon, Aria) {
60a1ea56
DW
30
31 // Private functions and variables.
32 /** @var {Object} KEYS - List of keycode constants. */
33 var KEYS = {
34 DOWN: 40,
35 ENTER: 13,
36 SPACE: 32,
37 ESCAPE: 27,
e375029e 38 COMMA: 44,
f5cb4b9b
TB
39 UP: 38,
40 LEFT: 37,
41 RIGHT: 39
60a1ea56
DW
42 };
43
a6c73503 44 var uniqueId = Date.now();
b7df2485 45
60a1ea56
DW
46 /**
47 * Make an item in the selection list "active".
48 *
49 * @method activateSelection
50 * @private
51 * @param {Number} index The index in the current (visible) list of selection.
273b2556 52 * @param {Object} state State variables for this autocomplete element.
e994dea0 53 * @return {Promise}
60a1ea56 54 */
273b2556 55 var activateSelection = function(index, state) {
60a1ea56 56 // Find the elements in the DOM.
273b2556 57 var selectionElement = $(document.getElementById(state.selectionId));
60a1ea56
DW
58
59 // Count the visible items.
60 var length = selectionElement.children('[aria-selected=true]').length;
61 // Limit the index to the upper/lower bounds of the list (wrap in both directions).
62 index = index % length;
63 while (index < 0) {
64 index += length;
65 }
66 // Find the specified element.
67 var element = $(selectionElement.children('[aria-selected=true]').get(index));
68 // Create an id we can assign to this element.
273b2556 69 var itemId = state.selectionId + '-' + index;
60a1ea56
DW
70
71 // Deselect all the selections.
5d16bfcf
AN
72 selectionElement.children().attr('data-active-selection', null).attr('id', '');
73
60a1ea56
DW
74 // Select only this suggestion and assign it the id.
75 element.attr('data-active-selection', true).attr('id', itemId);
5d16bfcf 76
60a1ea56
DW
77 // Tell the input field it has a new active descendant so the item is announced.
78 selectionElement.attr('aria-activedescendant', itemId);
7d786c79 79 selectionElement.attr('data-active-value', element.attr('data-value'));
e994dea0
AN
80
81 return $.Deferred().resolve();
60a1ea56
DW
82 };
83
7d786c79
AN
84 /**
85 * Get the actively selected element from the state object.
86 *
87 * @param {Object} state
88 * @returns {jQuery}
89 */
90 var getActiveElementFromState = function(state) {
91 var selectionRegion = $(document.getElementById(state.selectionId));
92 var activeId = selectionRegion.attr('aria-activedescendant');
93
94 if (activeId) {
95 var activeElement = $(document.getElementById(activeId));
96 if (activeElement.length) {
97 // The active descendent still exists.
98 return activeElement;
99 }
100 }
101
102 var activeValue = selectionRegion.attr('data-active-value');
103 return selectionRegion.find('[data-value="' + activeValue + '"]');
104 };
105
106 /**
107 * Update the active selection from the given state object.
108 *
109 * @param {Object} state
110 */
111 var updateActiveSelectionFromState = function(state) {
112 var activeElement = getActiveElementFromState(state);
113 var activeValue = activeElement.attr('data-value');
114
115 var selectionRegion = $(document.getElementById(state.selectionId));
116 if (activeValue) {
117 // Find the index of the currently selected index.
118 var activeIndex = selectionRegion.find('[aria-selected=true]').index(activeElement);
119
120 if (activeIndex !== -1) {
121 activateSelection(activeIndex, state);
122 return;
123 }
124 }
125
126 // Either the active index was not set, or it could not be found.
127 // Select the first value instead.
128 activateSelection(0, state);
129 };
130
f992dcf6
DP
131 /**
132 * Update the element that shows the currently selected items.
133 *
134 * @method updateSelectionList
135 * @private
136 * @param {Object} options Original options for this autocomplete element.
137 * @param {Object} state State variables for this autocomplete element.
138 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
e994dea0 139 * @return {Promise}
f992dcf6
DP
140 */
141 var updateSelectionList = function(options, state, originalSelect) {
e994dea0
AN
142 var pendingKey = 'form-autocomplete-updateSelectionList-' + state.inputId;
143 M.util.js_pending(pendingKey);
144
f992dcf6
DP
145 // Build up a valid context to re-render the template.
146 var items = [];
147 var newSelection = $(document.getElementById(state.selectionId));
f992dcf6
DP
148 originalSelect.children('option').each(function(index, ele) {
149 if ($(ele).prop('selected')) {
a97c9370 150 var label;
151 if ($(ele).data('html')) {
152 label = $(ele).data('html');
153 } else {
154 label = $(ele).html();
155 }
9cbeaec2
PH
156 if (label !== '') {
157 items.push({label: label, value: $(ele).attr('value')});
158 }
f992dcf6
DP
159 }
160 });
7d786c79
AN
161
162 if (!hasItemListChanged(state, items)) {
163 M.util.js_complete(pendingKey);
164 return Promise.resolve();
165 }
166
167 state.items = items;
168
169 var context = $.extend(options, state);
f992dcf6 170 // Render the template.
1be0f90c 171 return templates.render(options.templates.items, context)
e994dea0 172 .then(function(html, js) {
f992dcf6 173 // Add it to the page.
e994dea0 174 templates.replaceNodeContents(newSelection, html, js);
f992dcf6 175
7d786c79 176 updateActiveSelectionFromState(state);
e994dea0 177
7d786c79 178 return;
e994dea0
AN
179 })
180 .then(function() {
181 return M.util.js_complete(pendingKey);
182 })
183 .catch(notification.exception);
1eaba735
FM
184 };
185
7d786c79
AN
186 /**
187 * Check whether the list of items stored in the state has changed.
188 *
189 * @param {Object} state
190 * @param {Array} items
191 */
192 var hasItemListChanged = function(state, items) {
193 if (state.items.length !== items.length) {
194 return true;
195 }
196
197 // Check for any items in the state items which are not present in the new items list.
198 return state.items.filter(item => items.indexOf(item) === -1).length > 0;
199 };
200
1eaba735
FM
201 /**
202 * Notify of a change in the selection.
203 *
204 * @param {jQuery} originalSelect The jQuery object matching the hidden select list.
1eaba735
FM
205 */
206 var notifyChange = function(originalSelect) {
207 if (typeof M.core_formchangechecker !== 'undefined') {
eb97811b
MG
208 M.core_formchangechecker.set_form_changed();
209 }
be612e5f
TH
210
211 // Note, jQuery .change() was not working here. Better to
212 // use plain JavaScript anyway.
213 originalSelect[0].dispatchEvent(new Event('change'));
f992dcf6
DP
214 };
215
60a1ea56 216 /**
563fe0a5 217 * Remove the given item from the list of selected things.
60a1ea56 218 *
563fe0a5 219 * @method deselectItem
60a1ea56 220 * @private
273b2556
DW
221 * @param {Object} options Original options for this autocomplete element.
222 * @param {Object} state State variables for this autocomplete element.
c96f55e6 223 * @param {Element} item The item to be deselected.
60a1ea56 224 * @param {Element} originalSelect The original select list.
e994dea0 225 * @return {Promise}
60a1ea56 226 */
273b2556 227 var deselectItem = function(options, state, item, originalSelect) {
563fe0a5
RW
228 var selectedItemValue = $(item).attr('data-value');
229
9cbeaec2
PH
230 // Look for a match, and toggle the selected property if there is a match.
231 originalSelect.children('option').each(function(index, ele) {
232 if ($(ele).attr('value') == selectedItemValue) {
233 $(ele).prop('selected', false);
234 // We remove newly created custom tags from the suggestions list when they are deselected.
235 if ($(ele).attr('data-iscustom')) {
236 $(ele).remove();
60a1ea56 237 }
9cbeaec2
PH
238 }
239 });
60a1ea56 240 // Rerender the selection list.
e994dea0
AN
241 return updateSelectionList(options, state, originalSelect)
242 .then(function() {
243 // Notify that the selection changed.
244 notifyChange(originalSelect);
245
246 return;
247 });
60a1ea56
DW
248 };
249
250 /**
251 * Make an item in the suggestions "active" (about to be selected).
252 *
253 * @method activateItem
254 * @private
255 * @param {Number} index The index in the current (visible) list of suggestions.
273b2556 256 * @param {Object} state State variables for this instance of autocomplete.
e994dea0 257 * @return {Promise}
60a1ea56 258 */
273b2556 259 var activateItem = function(index, state) {
60a1ea56 260 // Find the elements in the DOM.
273b2556
DW
261 var inputElement = $(document.getElementById(state.inputId));
262 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
263
264 // Count the visible items.
7cc18dc2 265 var length = suggestionsElement.children(':not([aria-hidden])').length;
60a1ea56
DW
266 // Limit the index to the upper/lower bounds of the list (wrap in both directions).
267 index = index % length;
268 while (index < 0) {
269 index += length;
270 }
271 // Find the specified element.
7cc18dc2 272 var element = $(suggestionsElement.children(':not([aria-hidden])').get(index));
60a1ea56
DW
273 // Find the index of this item in the full list of suggestions (including hidden).
274 var globalIndex = $(suggestionsElement.children('[role=option]')).index(element);
275 // Create an id we can assign to this element.
273b2556 276 var itemId = state.suggestionsId + '-' + globalIndex;
60a1ea56
DW
277
278 // Deselect all the suggestions.
279 suggestionsElement.children().attr('aria-selected', false).attr('id', '');
280 // Select only this suggestion and assign it the id.
281 element.attr('aria-selected', true).attr('id', itemId);
282 // Tell the input field it has a new active descendant so the item is announced.
283 inputElement.attr('aria-activedescendant', itemId);
32f3de56
DW
284
285 // Scroll it into view.
286 var scrollPos = element.offset().top
287 - suggestionsElement.offset().top
288 + suggestionsElement.scrollTop()
289 - (suggestionsElement.height() / 2);
e994dea0 290 return suggestionsElement.animate({
32f3de56 291 scrollTop: scrollPos
e994dea0 292 }, 100).promise();
60a1ea56
DW
293 };
294
295 /**
296 * Find the index of the current active suggestion, and activate the next one.
297 *
298 * @method activateNextItem
299 * @private
273b2556 300 * @param {Object} state State variable for this auto complete element.
e994dea0 301 * @return {Promise}
60a1ea56 302 */
273b2556 303 var activateNextItem = function(state) {
60a1ea56 304 // Find the list of suggestions.
273b2556 305 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
306 // Find the active one.
307 var element = suggestionsElement.children('[aria-selected=true]');
308 // Find it's index.
7cc18dc2 309 var current = suggestionsElement.children(':not([aria-hidden])').index(element);
60a1ea56 310 // Activate the next one.
e994dea0 311 return activateItem(current + 1, state);
60a1ea56
DW
312 };
313
314 /**
315 * Find the index of the current active selection, and activate the previous one.
316 *
317 * @method activatePreviousSelection
318 * @private
273b2556 319 * @param {Object} state State variables for this instance of autocomplete.
e994dea0 320 * @return {Promise}
60a1ea56 321 */
273b2556 322 var activatePreviousSelection = function(state) {
60a1ea56 323 // Find the list of selections.
273b2556 324 var selectionsElement = $(document.getElementById(state.selectionId));
60a1ea56 325 // Find the active one.
5d16bfcf 326 var element = selectionsElement.children('[data-active-selection]');
60a1ea56 327 if (!element) {
e994dea0 328 return activateSelection(0, state);
60a1ea56
DW
329 }
330 // Find it's index.
331 var current = selectionsElement.children('[aria-selected=true]').index(element);
332 // Activate the next one.
e994dea0 333 return activateSelection(current - 1, state);
60a1ea56 334 };
e994dea0 335
60a1ea56
DW
336 /**
337 * Find the index of the current active selection, and activate the next one.
338 *
339 * @method activateNextSelection
340 * @private
273b2556 341 * @param {Object} state State variables for this instance of autocomplete.
e994dea0 342 * @return {Promise}
60a1ea56 343 */
273b2556 344 var activateNextSelection = function(state) {
60a1ea56 345 // Find the list of selections.
273b2556 346 var selectionsElement = $(document.getElementById(state.selectionId));
e994dea0 347
60a1ea56 348 // Find the active one.
5d16bfcf 349 var element = selectionsElement.children('[data-active-selection]');
e994dea0
AN
350 var current = 0;
351
352 if (element) {
353 // The element was found. Determine the index and move to the next one.
354 current = selectionsElement.children('[aria-selected=true]').index(element);
355 current = current + 1;
356 } else {
357 // No selected item found. Move to the first.
358 current = 0;
60a1ea56 359 }
e994dea0
AN
360
361 return activateSelection(current, state);
60a1ea56
DW
362 };
363
364 /**
365 * Find the index of the current active suggestion, and activate the previous one.
366 *
367 * @method activatePreviousItem
368 * @private
273b2556 369 * @param {Object} state State variables for this autocomplete element.
e994dea0 370 * @return {Promise}
60a1ea56 371 */
273b2556 372 var activatePreviousItem = function(state) {
60a1ea56 373 // Find the list of suggestions.
273b2556 374 var suggestionsElement = $(document.getElementById(state.suggestionsId));
e994dea0 375
60a1ea56
DW
376 // Find the active one.
377 var element = suggestionsElement.children('[aria-selected=true]');
e994dea0 378
60a1ea56 379 // Find it's index.
7cc18dc2 380 var current = suggestionsElement.children(':not([aria-hidden])').index(element);
e994dea0
AN
381
382 // Activate the previous one.
383 return activateItem(current - 1, state);
60a1ea56
DW
384 };
385
386 /**
387 * Close the list of suggestions.
388 *
389 * @method closeSuggestions
390 * @private
273b2556 391 * @param {Object} state State variables for this autocomplete element.
e994dea0 392 * @return {Promise}
60a1ea56 393 */
273b2556 394 var closeSuggestions = function(state) {
60a1ea56 395 // Find the elements in the DOM.
273b2556
DW
396 var inputElement = $(document.getElementById(state.inputId));
397 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56 398
e2ee6025
SR
399 if (inputElement.attr('aria-expanded') === "true") {
400 // Announce the list of suggestions was closed.
401 inputElement.attr('aria-expanded', false);
402 }
403 // Read the current list of selections.
404 inputElement.attr('aria-activedescendant', state.selectionId);
e994dea0 405
60a1ea56 406 // Hide the suggestions list (from screen readers too).
7cc18dc2
AN
407 Aria.hide(suggestionsElement.get());
408 suggestionsElement.hide();
e994dea0
AN
409
410 return $.Deferred().resolve();
60a1ea56
DW
411 };
412
413 /**
414 * Rebuild the list of suggestions based on the current values in the select list, and the query.
415 *
416 * @method updateSuggestions
417 * @private
273b2556
DW
418 * @param {Object} options The original options for this autocomplete.
419 * @param {Object} state The state variables for this autocomplete.
420 * @param {String} query The current text for the search string.
60a1ea56 421 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
e994dea0 422 * @return {Promise}
60a1ea56 423 */
273b2556 424 var updateSuggestions = function(options, state, query, originalSelect) {
e994dea0
AN
425 var pendingKey = 'form-autocomplete-updateSuggestions-' + state.inputId;
426 M.util.js_pending(pendingKey);
427
60a1ea56 428 // Find the elements in the DOM.
273b2556
DW
429 var inputElement = $(document.getElementById(state.inputId));
430 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
431
432 // Used to track if we found any visible suggestions.
433 var matchingElements = false;
434 // Options is used by the context when rendering the suggestions from a template.
273b2556 435 var suggestions = [];
60a1ea56
DW
436 originalSelect.children('option').each(function(index, option) {
437 if ($(option).prop('selected') !== true) {
9f5f3dcc 438 suggestions[suggestions.length] = {label: option.innerHTML, value: $(option).attr('value')};
60a1ea56
DW
439 }
440 });
441
442 // Re-render the list of suggestions.
273b2556 443 var searchquery = state.caseSensitive ? query : query.toLocaleLowerCase();
9f5f3dcc 444 var context = $.extend({options: suggestions}, options, state);
e994dea0 445 var returnVal = templates.render(
60a1ea56 446 'core/form_autocomplete_suggestions',
273b2556 447 context
e994dea0
AN
448 )
449 .then(function(html, js) {
60a1ea56 450 // We have the new template, insert it in the page.
e994dea0
AN
451 templates.replaceNode(suggestionsElement, html, js);
452
60a1ea56 453 // Get the element again.
273b2556 454 suggestionsElement = $(document.getElementById(state.suggestionsId));
7cc18dc2 455
60a1ea56 456 // Show it if it is hidden.
7cc18dc2
AN
457 Aria.unhide(suggestionsElement.get());
458 suggestionsElement.show();
459
60a1ea56
DW
460 // For each option in the list, hide it if it doesn't match the query.
461 suggestionsElement.children().each(function(index, node) {
462 node = $(node);
273b2556
DW
463 if ((options.caseSensitive && node.text().indexOf(searchquery) > -1) ||
464 (!options.caseSensitive && node.text().toLocaleLowerCase().indexOf(searchquery) > -1)) {
7cc18dc2
AN
465 Aria.unhide(node.get());
466 node.show();
60a1ea56
DW
467 matchingElements = true;
468 } else {
7cc18dc2
AN
469 node.hide();
470 Aria.hide(node.get());
60a1ea56
DW
471 }
472 });
473 // If we found any matches, show the list.
81c471e2 474 inputElement.attr('aria-expanded', true);
9411beb3
DM
475 if (originalSelect.attr('data-notice')) {
476 // Display a notice rather than actual suggestions.
477 suggestionsElement.html(originalSelect.attr('data-notice'));
478 } else if (matchingElements) {
60a1ea56
DW
479 // We only activate the first item in the list if tags is false,
480 // because otherwise "Enter" would select the first item, instead of
481 // creating a new tag.
273b2556
DW
482 if (!options.tags) {
483 activateItem(0, state);
60a1ea56
DW
484 }
485 } else {
81c471e2
DW
486 // Nothing matches. Tell them that.
487 str.get_string('nosuggestions', 'form').done(function(nosuggestionsstr) {
488 suggestionsElement.html(nosuggestionsstr);
489 });
60a1ea56 490 }
60a1ea56 491
e994dea0
AN
492 return suggestionsElement;
493 })
494 .then(function() {
495 return M.util.js_complete(pendingKey);
496 })
497 .catch(notification.exception);
498
499 return returnVal;
60a1ea56
DW
500 };
501
502 /**
503 * Create a new item for the list (a tag).
504 *
505 * @method createItem
506 * @private
273b2556
DW
507 * @param {Object} options The original options for the autocomplete.
508 * @param {Object} state State variables for the autocomplete.
60a1ea56 509 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
e994dea0 510 * @return {Promise}
60a1ea56 511 */
273b2556 512 var createItem = function(options, state, originalSelect) {
60a1ea56 513 // Find the element in the DOM.
273b2556 514 var inputElement = $(document.getElementById(state.inputId));
60a1ea56
DW
515 // Get the current text in the input field.
516 var query = inputElement.val();
517 var tags = query.split(',');
518 var found = false;
519
520 $.each(tags, function(tagindex, tag) {
521 // If we can only select one at a time, deselect any current value.
522 tag = tag.trim();
523 if (tag !== '') {
273b2556 524 if (!options.multiple) {
60a1ea56
DW
525 originalSelect.children('option').prop('selected', false);
526 }
527 // Look for an existing option in the select list that matches this new tag.
528 originalSelect.children('option').each(function(index, ele) {
529 if ($(ele).attr('value') == tag) {
530 found = true;
531 $(ele).prop('selected', true);
532 }
533 });
534 // Only create the item if it's new.
535 if (!found) {
536 var option = $('<option>');
18e2f403 537 option.append(document.createTextNode(tag));
60a1ea56
DW
538 option.attr('value', tag);
539 originalSelect.append(option);
540 option.prop('selected', true);
bdd60287
DW
541 // We mark newly created custom options as we handle them differently if they are "deselected".
542 option.attr('data-iscustom', true);
60a1ea56
DW
543 }
544 }
545 });
bdd60287 546
e994dea0
AN
547 return updateSelectionList(options, state, originalSelect)
548 .then(function() {
549 // Notify that the selection changed.
550 notifyChange(originalSelect);
551
552 return;
553 })
554 .then(function() {
555 // Clear the input field.
556 inputElement.val('');
557
558 return;
559 })
560 .then(function() {
561 // Close the suggestions list.
562 return closeSuggestions(state);
563 });
60a1ea56
DW
564 };
565
60a1ea56
DW
566 /**
567 * Select the currently active item from the suggestions list.
568 *
569 * @method selectCurrentItem
570 * @private
273b2556
DW
571 * @param {Object} options The original options for the autocomplete.
572 * @param {Object} state State variables for the autocomplete.
60a1ea56 573 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
e994dea0 574 * @return {Promise}
60a1ea56 575 */
273b2556 576 var selectCurrentItem = function(options, state, originalSelect) {
60a1ea56 577 // Find the elements in the page.
273b2556
DW
578 var inputElement = $(document.getElementById(state.inputId));
579 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
580 // Here loop through suggestions and set val to join of all selected items.
581
582 var selectedItemValue = suggestionsElement.children('[aria-selected=true]').attr('data-value');
583 // The select will either be a single or multi select, so the following will either
584 // select one or more items correctly.
585 // Take care to use 'prop' and not 'attr' for selected properties.
586 // If only one can be selected at a time, start by deselecting everything.
273b2556 587 if (!options.multiple) {
60a1ea56
DW
588 originalSelect.children('option').prop('selected', false);
589 }
590 // Look for a match, and toggle the selected property if there is a match.
591 originalSelect.children('option').each(function(index, ele) {
592 if ($(ele).attr('value') == selectedItemValue) {
593 $(ele).prop('selected', true);
594 }
595 });
78162bf5 596
e994dea0
AN
597 return updateSelectionList(options, state, originalSelect)
598 .then(function() {
599 // Notify that the selection changed.
600 notifyChange(originalSelect);
786e014c 601
e994dea0
AN
602 return;
603 })
604 .then(function() {
605 if (options.closeSuggestionsOnSelect) {
606 // Clear the input element.
607 inputElement.val('');
608 // Close the list of suggestions.
609 return closeSuggestions(state);
610 } else {
611 // Focus on the input element so the suggestions does not auto-close.
612 inputElement.focus();
613 // Remove the last selected item from the suggestions list.
614 return updateSuggestions(options, state, inputElement.val(), originalSelect);
615 }
616 });
60a1ea56
DW
617 };
618
619 /**
620 * Fetch a new list of options via ajax.
621 *
622 * @method updateAjax
623 * @private
624 * @param {Event} e The event that triggered this update.
273b2556
DW
625 * @param {Object} options The original options for the autocomplete.
626 * @param {Object} state The state variables for the autocomplete.
60a1ea56 627 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
60a1ea56 628 * @param {Object} ajaxHandler This is a module that does the ajax fetch and translates the results.
e994dea0 629 * @return {Promise}
60a1ea56 630 */
273b2556 631 var updateAjax = function(e, options, state, originalSelect, ajaxHandler) {
e994dea0 632 var pendingPromise = addPendingJSPromise('updateAjax');
efef2efd
HN
633 // We need to show the indicator outside of the hidden select list.
634 // So we get the parent id of the hidden select list.
635 var parentElement = $(document.getElementById(state.selectId)).parent();
636 LoadingIcon.addIconToContainerRemoveOnCompletion(parentElement, pendingPromise);
e994dea0 637
60a1ea56
DW
638 // Get the query to pass to the ajax function.
639 var query = $(e.currentTarget).val();
640 // Call the transport function to do the ajax (name taken from Select2).
273b2556 641 ajaxHandler.transport(options.selector, query, function(results) {
60a1ea56 642 // We got a result - pass it through the translator before using it.
273b2556 643 var processedResults = ajaxHandler.processResults(options.selector, results);
60a1ea56
DW
644 var existingValues = [];
645
646 // Now destroy all options that are not currently selected.
9cbeaec2
PH
647 if (!options.multiple) {
648 originalSelect.children('option').remove();
649 }
60a1ea56
DW
650 originalSelect.children('option').each(function(optionIndex, option) {
651 option = $(option);
652 if (!option.prop('selected')) {
653 option.remove();
654 } else {
91ab264c 655 existingValues.push(String(option.attr('value')));
60a1ea56
DW
656 }
657 });
91ab264c
DW
658
659 if (!options.multiple && originalSelect.children('option').length === 0) {
660 // If this is a single select - and there are no current options
661 // the first option added will be selected by the browser. This causes a bug!
662 // We need to insert an empty option so that none of the real options are selected.
663 var option = $('<option>');
664 originalSelect.append(option);
665 }
9411beb3
DM
666 if ($.isArray(processedResults)) {
667 // Add all the new ones returned from ajax.
668 $.each(processedResults, function(resultIndex, result) {
669 if (existingValues.indexOf(String(result.value)) === -1) {
670 var option = $('<option>');
671 option.append(result.label);
672 option.attr('value', result.value);
673 originalSelect.append(option);
674 }
675 });
676 originalSelect.attr('data-notice', '');
677 } else {
678 // The AJAX handler returned a string instead of the array.
679 originalSelect.attr('data-notice', processedResults);
680 }
60a1ea56 681 // Update the list of suggestions now from the new values in the select list.
e994dea0 682 pendingPromise.resolve(updateSuggestions(options, state, '', originalSelect));
78162bf5 683 }, function(error) {
e994dea0 684 pendingPromise.reject(error);
78162bf5 685 });
e994dea0
AN
686
687 return pendingPromise;
60a1ea56
DW
688 };
689
690 /**
691 * Add all the event listeners required for keyboard nav, blur clicks etc.
692 *
693 * @method addNavigation
694 * @private
273b2556
DW
695 * @param {Object} options The options used to create this autocomplete element.
696 * @param {Object} state State variables for this autocomplete element.
60a1ea56 697 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
60a1ea56 698 */
273b2556 699 var addNavigation = function(options, state, originalSelect) {
60a1ea56 700 // Start with the input element.
273b2556 701 var inputElement = $(document.getElementById(state.inputId));
60a1ea56
DW
702 // Add keyboard nav with keydown.
703 inputElement.on('keydown', function(e) {
e994dea0 704 var pendingJsPromise = addPendingJSPromise('addNavigation-' + state.inputId + '-' + e.keyCode);
78162bf5 705
60a1ea56
DW
706 switch (e.keyCode) {
707 case KEYS.DOWN:
708 // If the suggestion list is open, move to the next item.
273b2556 709 if (!options.showSuggestions) {
97d2ea7f 710 // Do not consume this event.
e994dea0 711 pendingJsPromise.resolve();
97d2ea7f
DW
712 return true;
713 } else if (inputElement.attr('aria-expanded') === "true") {
e994dea0 714 pendingJsPromise.resolve(activateNextItem(state));
60a1ea56 715 } else {
d304952b 716 // Handle ajax population of suggestions.
273b2556
DW
717 if (!inputElement.val() && options.ajax) {
718 require([options.ajax], function(ajaxHandler) {
e994dea0 719 pendingJsPromise.resolve(updateAjax(e, options, state, originalSelect, ajaxHandler));
d304952b
AG
720 });
721 } else {
47dd5350 722 // Open the suggestions list.
e994dea0 723 pendingJsPromise.resolve(updateSuggestions(options, state, inputElement.val(), originalSelect));
d304952b 724 }
60a1ea56
DW
725 }
726 // We handled this event, so prevent it.
727 e.preventDefault();
728 return false;
60a1ea56
DW
729 case KEYS.UP:
730 // Choose the previous active item.
e994dea0
AN
731 pendingJsPromise.resolve(activatePreviousItem(state));
732
60a1ea56
DW
733 // We handled this event, so prevent it.
734 e.preventDefault();
735 return false;
736 case KEYS.ENTER:
273b2556 737 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
738 if ((inputElement.attr('aria-expanded') === "true") &&
739 (suggestionsElement.children('[aria-selected=true]').length > 0)) {
740 // If the suggestion list has an active item, select it.
e994dea0 741 pendingJsPromise.resolve(selectCurrentItem(options, state, originalSelect));
273b2556 742 } else if (options.tags) {
60a1ea56 743 // If tags are enabled, create a tag.
e994dea0
AN
744 pendingJsPromise.resolve(createItem(options, state, originalSelect));
745 } else {
746 pendingJsPromise.resolve();
60a1ea56 747 }
e994dea0 748
60a1ea56
DW
749 // We handled this event, so prevent it.
750 e.preventDefault();
751 return false;
752 case KEYS.ESCAPE:
753 if (inputElement.attr('aria-expanded') === "true") {
754 // If the suggestion list is open, close it.
e994dea0
AN
755 pendingJsPromise.resolve(closeSuggestions(state));
756 } else {
757 pendingJsPromise.resolve();
60a1ea56
DW
758 }
759 // We handled this event, so prevent it.
760 e.preventDefault();
761 return false;
e375029e 762 }
e994dea0 763 pendingJsPromise.resolve();
e375029e
NK
764 return true;
765 });
766 // Support multi lingual COMMA keycode (44).
767 inputElement.on('keypress', function(e) {
e994dea0 768
e375029e
NK
769 if (e.keyCode === KEYS.COMMA) {
770 if (options.tags) {
771 // If we are allowing tags, comma should create a tag (or enter).
e994dea0
AN
772 addPendingJSPromise('keypress-' + e.keyCode)
773 .resolve(createItem(options, state, originalSelect));
e375029e
NK
774 }
775 // We handled this event, so prevent it.
776 e.preventDefault();
777 return false;
60a1ea56
DW
778 }
779 return true;
780 });
072a033a
SR
781 // Support submitting the form without leaving the autocomplete element,
782 // or submitting too quick before the blur handler action is completed.
783 inputElement.closest('form').on('submit', function() {
784 if (options.tags) {
785 // If tags are enabled, create a tag.
786 addPendingJSPromise('form-autocomplete-submit')
787 .resolve(createItem(options, state, originalSelect));
788 }
789
790 return true;
791 });
e1db2b41 792 inputElement.on('blur', function() {
e994dea0 793 var pendingPromise = addPendingJSPromise('form-autocomplete-blur');
e1db2b41
RW
794 window.setTimeout(function() {
795 // Get the current element with focus.
796 var focusElement = $(document.activeElement);
6654ac11 797 var timeoutPromise = $.Deferred();
e994dea0 798
e75bf415
SR
799 // Only close the menu if the input hasn't regained focus and if the element still exists,
800 // and regain focus if the scrollbar is clicked.
072a033a
SR
801 // Due to the half a second delay, it is possible that the input element no longer exist
802 // by the time this code is being executed.
e75bf415
SR
803 if (focusElement.is(document.getElementById(state.suggestionsId))) {
804 inputElement.focus(); // Probably the scrollbar is clicked. Regain focus.
805 } else if (!focusElement.is(inputElement) && $(document.getElementById(state.inputId)).length) {
273b2556 806 if (options.tags) {
6654ac11 807 timeoutPromise.then(function() {
e994dea0
AN
808 return createItem(options, state, originalSelect);
809 })
810 .catch();
527bde6e 811 }
6654ac11 812 timeoutPromise.then(function() {
e994dea0
AN
813 return closeSuggestions(state);
814 })
815 .catch();
60a1ea56 816 }
e994dea0 817
6654ac11
AN
818 timeoutPromise.then(function() {
819 return pendingPromise.resolve();
820 })
821 .catch();
822 timeoutPromise.resolve();
60a1ea56
DW
823 }, 500);
824 });
273b2556
DW
825 if (options.showSuggestions) {
826 var arrowElement = $(document.getElementById(state.downArrowId));
47dd5350 827 arrowElement.on('click', function(e) {
e994dea0
AN
828 var pendingPromise = addPendingJSPromise('form-autocomplete-show-suggestions');
829
97d2ea7f
DW
830 // Prevent the close timer, or we will open, then close the suggestions.
831 inputElement.focus();
e994dea0 832
47dd5350
DW
833 // Handle ajax population of suggestions.
834 if (!inputElement.val() && options.ajax) {
835 require([options.ajax], function(ajaxHandler) {
e994dea0 836 pendingPromise.resolve(updateAjax(e, options, state, originalSelect, ajaxHandler));
47dd5350
DW
837 });
838 } else {
839 // Else - open the suggestions list.
e994dea0 840 pendingPromise.resolve(updateSuggestions(options, state, inputElement.val(), originalSelect));
47dd5350 841 }
97d2ea7f
DW
842 });
843 }
60a1ea56 844
273b2556 845 var suggestionsElement = $(document.getElementById(state.suggestionsId));
5cfd7a72
MO
846 // Remove any click handler first.
847 suggestionsElement.parent().prop("onclick", null).off("click");
b643c886 848 suggestionsElement.parent().on('click', `#${state.suggestionsId} [role=option]`, function(e) {
e994dea0 849 var pendingPromise = addPendingJSPromise('form-autocomplete-parent');
60a1ea56
DW
850 // Handle clicks on suggestions.
851 var element = $(e.currentTarget).closest('[role=option]');
273b2556 852 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56 853 // Find the index of the clicked on suggestion.
7cc18dc2 854 var current = suggestionsElement.children(':not([aria-hidden])').index(element);
e994dea0 855
60a1ea56 856 // Activate it.
e994dea0
AN
857 activateItem(current, state)
858 .then(function() {
859 // And select it.
860 return selectCurrentItem(options, state, originalSelect);
861 })
862 .then(function() {
863 return pendingPromise.resolve();
864 })
865 .catch();
60a1ea56 866 });
273b2556 867 var selectionElement = $(document.getElementById(state.selectionId));
7d786c79 868
60a1ea56 869 // Handle clicks on the selected items (will unselect an item).
b643c886 870 selectionElement.on('click', '[role=option]', function(e) {
e994dea0
AN
871 var pendingPromise = addPendingJSPromise('form-autocomplete-clicks');
872
563fe0a5 873 // Remove it from the selection.
e994dea0 874 pendingPromise.resolve(deselectItem(options, state, $(e.currentTarget), originalSelect));
60a1ea56 875 });
7d786c79 876
0438cd60
SR
877 // When listbox is focused, focus on the first option if there is no focused option.
878 selectionElement.on('focus', function() {
7d786c79 879 updateActiveSelectionFromState(state);
f5cb4b9b 880 });
7d786c79 881
60a1ea56 882 // Keyboard navigation for the selection list.
adebc069 883 selectionElement.on('keydown', function(e) {
e994dea0 884 var pendingPromise = addPendingJSPromise('form-autocomplete-keydown-' + e.keyCode);
60a1ea56 885 switch (e.keyCode) {
f5cb4b9b 886 case KEYS.RIGHT:
60a1ea56 887 case KEYS.DOWN:
60a1ea56
DW
888 // We handled this event, so prevent it.
889 e.preventDefault();
e994dea0
AN
890
891 // Choose the next selection item.
892 pendingPromise.resolve(activateNextSelection(state));
a88838c2 893 return;
f5cb4b9b 894 case KEYS.LEFT:
60a1ea56 895 case KEYS.UP:
60a1ea56
DW
896 // We handled this event, so prevent it.
897 e.preventDefault();
e994dea0
AN
898
899 // Choose the previous selection item.
900 pendingPromise.resolve(activatePreviousSelection(state));
a88838c2 901 return;
60a1ea56
DW
902 case KEYS.SPACE:
903 case KEYS.ENTER:
563fe0a5 904 // Get the item that is currently selected.
5d16bfcf 905 var selectedItem = $(document.getElementById(state.selectionId)).children('[data-active-selection]');
563fe0a5 906 if (selectedItem) {
563fe0a5 907 e.preventDefault();
e994dea0
AN
908
909 // Unselect this item.
910 pendingPromise.resolve(deselectItem(options, state, selectedItem, originalSelect));
563fe0a5 911 }
a88838c2 912 return;
60a1ea56 913 }
e994dea0
AN
914
915 // Not handled. Resolve the promise.
916 pendingPromise.resolve();
60a1ea56
DW
917 });
918 // Whenever the input field changes, update the suggestion list.
273b2556 919 if (options.showSuggestions) {
517e568e
SR
920 // Store the value of the field as its last value, when the field gains focus.
921 inputElement.on('focus', function(e) {
922 var query = $(e.currentTarget).val();
923 $(e.currentTarget).data('last-value', query);
924 });
925
68a0485c
JP
926 // If this field uses ajax, set it up.
927 if (options.ajax) {
928 require([options.ajax], function(ajaxHandler) {
e994dea0
AN
929 // Creating throttled handlers free of race conditions, and accurate.
930 // This code keeps track of a throttleTimeout, which is periodically polled.
931 // Once the throttled function is executed, the fact that it is running is noted.
932 // If a subsequent request comes in whilst it is running, this request is re-applied.
68a0485c 933 var throttleTimeout = null;
e994dea0 934 var inProgress = false;
78162bf5 935 var pendingKey = 'autocomplete-throttledhandler';
68a0485c 936 var handler = function(e) {
e994dea0
AN
937 // Empty the current timeout.
938 throttleTimeout = null;
939
940 // Mark this request as in-progress.
941 inProgress = true;
942
943 // Process the request.
944 updateAjax(e, options, state, originalSelect, ajaxHandler)
945 .then(function() {
946 // Check if the throttleTimeout is still empty.
947 // There's a potential condition whereby the JS request takes long enough to complete that
948 // another task has been queued.
949 // In this case another task will be kicked off and we must wait for that before marking htis as
950 // complete.
951 if (null === throttleTimeout) {
952 // Mark this task as complete.
953 M.util.js_complete(pendingKey);
954 }
955 inProgress = false;
956
957 return arguments[0];
958 })
959 .catch(notification.exception);
68a0485c
JP
960 };
961
962 // For input events, we do not want to trigger many, many updates.
963 var throttledHandler = function(e) {
e994dea0
AN
964 window.clearTimeout(throttleTimeout);
965 if (inProgress) {
966 // A request is currently ongoing.
967 // Delay this request another 100ms.
968 throttleTimeout = window.setTimeout(throttledHandler.bind(this, e), 100);
969 return;
970 }
971
972 if (throttleTimeout === null) {
973 // There is currently no existing timeout handler, and it has not been recently cleared, so
974 // this is the start of a throttling check.
78162bf5 975 M.util.js_pending(pendingKey);
68a0485c 976 }
e994dea0
AN
977
978 // There is currently no existing timeout handler, and it has not been recently cleared, so this
979 // is the start of a throttling check.
980 // Queue a call to the handler.
68a0485c
JP
981 throttleTimeout = window.setTimeout(handler.bind(this, e), 300);
982 };
e994dea0 983
68a0485c 984 // Trigger an ajax update after the text field value changes.
517e568e
SR
985 inputElement.on('input', function(e) {
986 var query = $(e.currentTarget).val();
987 var last = $(e.currentTarget).data('last-value');
988 // IE11 fires many more input events than required - even when the value has not changed.
989 if (last !== query) {
990 throttledHandler(e);
991 }
992 $(e.currentTarget).data('last-value', query);
993 });
68a0485c
JP
994 });
995 } else {
996 inputElement.on('input', function(e) {
997 var query = $(e.currentTarget).val();
998 var last = $(e.currentTarget).data('last-value');
999 // IE11 fires many more input events than required - even when the value has not changed.
1000 // We need to only do this for real value changed events or the suggestions will be
1001 // unclickable on IE11 (because they will be rebuilt before the click event fires).
1002 // Note - because of this we cannot close the list when the query is empty or it will break
1003 // on IE11.
1004 if (last !== query) {
1005 updateSuggestions(options, state, query, originalSelect);
1006 }
1007 $(e.currentTarget).data('last-value', query);
1008 });
1009 }
97d2ea7f 1010 }
60a1ea56
DW
1011 };
1012
e994dea0
AN
1013 /**
1014 * Create and return an unresolved Promise for some pending JS.
1015 *
1016 * @param {String} key The unique identifier for this promise
1017 * @return {Promise}
1018 */
1019 var addPendingJSPromise = function(key) {
1020 var pendingKey = 'form-autocomplete:' + key;
1021
1022 M.util.js_pending(pendingKey);
1023
1024 var pendingPromise = $.Deferred();
1025
1026 pendingPromise
1027 .then(function() {
1028 M.util.js_complete(pendingKey);
1029
1030 return arguments[0];
1031 })
1032 .catch(notification.exception);
1033
1034 return pendingPromise;
1035 };
1036
60a1ea56
DW
1037 return /** @alias module:core/form-autocomplete */ {
1038 // Public variables and functions.
1039 /**
1040 * Turn a boring select box into an auto-complete beast.
1041 *
1042 * @method enhance
c96f55e6 1043 * @param {string} selector The selector that identifies the select box.
60a1ea56
DW
1044 * @param {boolean} tags Whether to allow support for tags (can define new entries).
1045 * @param {string} ajax Name of an AMD module to handle ajax requests. If specified, the AMD
1046 * module must expose 2 functions "transport" and "processResults".
1047 * These are modeled on Select2 see: https://select2.github.io/options.html#ajax
1048 * @param {String} placeholder - The text to display before a selection is made.
ecbc2a2f 1049 * @param {Boolean} caseSensitive - If search has to be made case sensitive.
c96f55e6 1050 * @param {Boolean} showSuggestions - If suggestions should be shown
427e3cbc 1051 * @param {String} noSelectionString - Text to display when there is no selection
198d7291 1052 * @param {Boolean} closeSuggestionsOnSelect - Whether to close the suggestions immediately after making a selection.
1be0f90c 1053 * @param {Object} templateOverrides A set of templates to use instead of the standard templates
13426bae 1054 * @return {Promise}
60a1ea56 1055 */
198d7291 1056 enhance: function(selector, tags, ajax, placeholder, caseSensitive, showSuggestions, noSelectionString,
1be0f90c 1057 closeSuggestionsOnSelect, templateOverrides) {
60a1ea56 1058 // Set some default values.
273b2556
DW
1059 var options = {
1060 selector: selector,
1061 tags: false,
1062 ajax: false,
1063 placeholder: placeholder,
1064 caseSensitive: false,
427e3cbc 1065 showSuggestions: true,
1be0f90c
AN
1066 noSelectionString: noSelectionString,
1067 templates: $.extend({
1068 input: 'core/form_autocomplete_input',
1069 items: 'core/form_autocomplete_selection_items',
1070 layout: 'core/form_autocomplete_layout',
1071 selection: 'core/form_autocomplete_selection',
1072 suggestions: 'core/form_autocomplete_suggestions',
1073 }, templateOverrides),
273b2556 1074 };
78162bf5
AN
1075 var pendingKey = 'autocomplete-setup-' + selector;
1076 M.util.js_pending(pendingKey);
273b2556
DW
1077 if (typeof tags !== "undefined") {
1078 options.tags = tags;
60a1ea56 1079 }
273b2556
DW
1080 if (typeof ajax !== "undefined") {
1081 options.ajax = ajax;
60a1ea56 1082 }
273b2556
DW
1083 if (typeof caseSensitive !== "undefined") {
1084 options.caseSensitive = caseSensitive;
ecbc2a2f 1085 }
273b2556
DW
1086 if (typeof showSuggestions !== "undefined") {
1087 options.showSuggestions = showSuggestions;
97d2ea7f 1088 }
427e3cbc 1089 if (typeof noSelectionString === "undefined") {
35be5826 1090 str.get_string('noselection', 'form').done(function(result) {
1388b618
JP
1091 options.noSelectionString = result;
1092 }).fail(notification.exception);
427e3cbc 1093 }
60a1ea56
DW
1094
1095 // Look for the select element.
1096 var originalSelect = $(selector);
1097 if (!originalSelect) {
1098 log.debug('Selector not found: ' + selector);
78162bf5 1099 M.util.js_complete(pendingKey);
f3ecea3a 1100 return false;
60a1ea56
DW
1101 }
1102
7cc18dc2
AN
1103 Aria.hide(originalSelect.get());
1104 originalSelect.css('visibility', 'hidden');
d8e57f02 1105
60a1ea56 1106 // Hide the original select.
60a1ea56
DW
1107
1108 // Find or generate some ids.
273b2556
DW
1109 var state = {
1110 selectId: originalSelect.attr('id'),
b7df2485
DW
1111 inputId: 'form_autocomplete_input-' + uniqueId,
1112 suggestionsId: 'form_autocomplete_suggestions-' + uniqueId,
1113 selectionId: 'form_autocomplete_selection-' + uniqueId,
7d786c79
AN
1114 downArrowId: 'form_autocomplete_downarrow-' + uniqueId,
1115 items: [],
273b2556 1116 };
b7df2485
DW
1117
1118 // Increment the unique counter so we don't get duplicates ever.
1119 uniqueId++;
1120
273b2556 1121 options.multiple = originalSelect.attr('multiple');
588b86fd
TH
1122 if (!options.multiple) {
1123 // If this is a single select then there is no way to de-select the current value -
1124 // unless we add a bogus blank option to be selected when nothing else is.
1125 // This matches similar code in updateAjax above.
1126 originalSelect.prepend('<option>');
1127 }
273b2556 1128
198d7291
JP
1129 if (typeof closeSuggestionsOnSelect !== "undefined") {
1130 options.closeSuggestionsOnSelect = closeSuggestionsOnSelect;
1131 } else {
1132 // If not specified, this will close suggestions by default for single-select elements only.
1133 options.closeSuggestionsOnSelect = !options.multiple;
1134 }
1135
273b2556 1136 var originalLabel = $('[for=' + state.selectId + ']');
60a1ea56 1137 // Create the new markup and insert it after the select.
273b2556 1138 var suggestions = [];
60a1ea56 1139 originalSelect.children('option').each(function(index, option) {
9f5f3dcc 1140 suggestions[index] = {label: option.innerHTML, value: $(option).attr('value')};
60a1ea56
DW
1141 });
1142
1143 // Render all the parts of our UI.
273b2556
DW
1144 var context = $.extend({}, options, state);
1145 context.options = suggestions;
1146 context.items = [];
1147
5cdf8d49
DM
1148 // Collect rendered inline JS to be executed once the HTML is shown.
1149 var collectedjs = '';
1150
1be0f90c
AN
1151 var renderLayout = templates.render(options.templates.layout, {})
1152 .then(function(html) {
1153 return $(html);
1154 });
1155
1156 var renderInput = templates.render(options.templates.input, context).then(function(html, js) {
5cdf8d49 1157 collectedjs += js;
1be0f90c 1158 return $(html);
5cdf8d49
DM
1159 });
1160
1be0f90c 1161 var renderDatalist = templates.render(options.templates.suggestions, context).then(function(html, js) {
5cdf8d49 1162 collectedjs += js;
1be0f90c 1163 return $(html);
5cdf8d49
DM
1164 });
1165
1be0f90c 1166 var renderSelection = templates.render(options.templates.selection, context).then(function(html, js) {
5cdf8d49 1167 collectedjs += js;
1be0f90c 1168 return $(html);
5cdf8d49 1169 });
60a1ea56 1170
1be0f90c
AN
1171 return $.when(renderLayout, renderInput, renderDatalist, renderSelection)
1172 .then(function(layout, input, suggestions, selection) {
d8e57f02 1173 originalSelect.hide();
1be0f90c
AN
1174 var container = originalSelect.parent();
1175
f07d3b71
AN
1176 // Ensure that the data-fieldtype is set for behat.
1177 input.find('input').attr('data-fieldtype', 'autocomplete');
1178
1be0f90c
AN
1179 container.append(layout);
1180 container.find('[data-region="form_autocomplete-input"]').replaceWith(input);
1181 container.find('[data-region="form_autocomplete-suggestions"]').replaceWith(suggestions);
1182 container.find('[data-region="form_autocomplete-selection"]').replaceWith(selection);
d8e57f02 1183
5cdf8d49
DM
1184 templates.runTemplateJS(collectedjs);
1185
60a1ea56 1186 // Update the form label to point to the text input.
273b2556 1187 originalLabel.attr('for', state.inputId);
60a1ea56 1188 // Add the event handlers.
273b2556
DW
1189 addNavigation(options, state, originalSelect);
1190
273b2556 1191 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56 1192 // Hide the suggestions by default.
7cc18dc2
AN
1193 suggestionsElement.hide();
1194 Aria.hide(suggestionsElement.get());
60a1ea56 1195
e994dea0
AN
1196 return;
1197 })
1198 .then(function() {
60a1ea56 1199 // Show the current values in the selection list.
e994dea0
AN
1200 return updateSelectionList(options, state, originalSelect);
1201 })
1202 .then(function() {
1203 return M.util.js_complete(pendingKey);
1204 })
1205 .catch(function(error) {
78162bf5
AN
1206 M.util.js_complete(pendingKey);
1207 notification.exception(error);
60a1ea56
DW
1208 });
1209 }
1210 };
1211});