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