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