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