1 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
17 * Autocomplete wrapper for select2 library.
19 * @module core/form-autocomplete
22 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 /* globals require: false */
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. */
42 var uniqueId = Date.now();
45 * Make an item in the selection list "active".
47 * @method activateSelection
49 * @param {Number} index The index in the current (visible) list of selection.
50 * @param {Object} state State variables for this autocomplete element.
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;
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();
80 * Update the element that shows the currently selected items.
82 * @method updateSelectionList
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.
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.
95 var newSelection = $(document.getElementById(state.selectionId));
96 var activeId = newSelection.attr('aria-activedescendant');
97 var activeValue = false;
100 activeValue = $(document.getElementById(activeId)).attr('data-value');
102 originalSelect.children('option').each(function(index, ele) {
103 if ($(ele).prop('selected')) {
105 if ($(ele).data('html')) {
106 label = $(ele).data('html');
108 label = $(ele).html();
110 items.push({label: label, value: $(ele).attr('value')});
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);
133 return M.util.js_complete(pendingKey);
135 .catch(notification.exception);
139 * Notify of a change in the selection.
141 * @param {jQuery} originalSelect The jQuery object matching the hidden select list.
143 var notifyChange = function(originalSelect) {
144 if (typeof M.core_formchangechecker !== 'undefined') {
145 M.core_formchangechecker.set_form_changed();
147 originalSelect.change();
151 * Remove the given item from the list of selected things.
153 * @method deselectItem
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.
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')) {
177 // Rerender the selection list.
178 return updateSelectionList(options, state, originalSelect)
180 // Notify that the selection changed.
181 notifyChange(originalSelect);
188 * Make an item in the suggestions "active" (about to be selected).
190 * @method activateItem
192 * @param {Number} index The index in the current (visible) list of suggestions.
193 * @param {Object} state State variables for this instance of autocomplete.
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;
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({
233 * Find the index of the current active suggestion, and activate the next one.
235 * @method activateNextItem
237 * @param {Object} state State variable for this auto complete element.
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]');
246 var current = suggestionsElement.children('[aria-hidden=false]').index(element);
247 // Activate the next one.
248 return activateItem(current + 1, state);
252 * Find the index of the current active selection, and activate the previous one.
254 * @method activatePreviousSelection
256 * @param {Object} state State variables for this instance of autocomplete.
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]');
265 return activateSelection(0, state);
268 var current = selectionsElement.children('[aria-selected=true]').index(element);
269 // Activate the next one.
270 return activateSelection(current - 1, state);
274 * Find the index of the current active selection, and activate the next one.
276 * @method activateNextSelection
278 * @param {Object} state State variables for this instance of autocomplete.
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]');
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;
294 // No selected item found. Move to the first.
298 return activateSelection(current, state);
302 * Find the index of the current active suggestion, and activate the previous one.
304 * @method activatePreviousItem
306 * @param {Object} state State variables for this autocomplete element.
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]');
317 var current = suggestionsElement.children('[aria-hidden=false]').index(element);
319 // Activate the previous one.
320 return activateItem(current - 1, state);
324 * Close the list of suggestions.
326 * @method closeSuggestions
328 * @param {Object} state State variables for this autocomplete element.
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();
346 * Rebuild the list of suggestions based on the current values in the select list, and the query.
348 * @method updateSuggestions
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.
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')};
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',
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) {
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;
397 node.hide().attr('aria-hidden', true);
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.
410 activateItem(0, state);
413 // Nothing matches. Tell them that.
414 str.get_string('nosuggestions', 'form').done(function(nosuggestionsstr) {
415 suggestionsElement.html(nosuggestionsstr);
419 return suggestionsElement;
422 return M.util.js_complete(pendingKey);
424 .catch(notification.exception);
430 * Create a new item for the list (a tag).
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.
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(',');
447 $.each(tags, function(tagindex, tag) {
448 // If we can only select one at a time, deselect any current value.
451 if (!options.multiple) {
452 originalSelect.children('option').prop('selected', false);
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) {
458 $(ele).prop('selected', true);
461 // Only create the item if it's new.
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);
474 return updateSelectionList(options, state, originalSelect)
476 // Notify that the selection changed.
477 notifyChange(originalSelect);
482 // Clear the input field.
483 inputElement.val('');
488 // Close the suggestions list.
489 return closeSuggestions(state);
494 * Select the currently active item from the suggestions list.
496 * @method selectCurrentItem
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.
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);
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);
524 return updateSelectionList(options, state, originalSelect)
526 // Notify that the selection changed.
527 notifyChange(originalSelect);
532 if (options.closeSuggestionsOnSelect) {
533 // Clear the input element.
534 inputElement.val('');
535 // Close the list of suggestions.
536 return closeSuggestions(state);
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);
547 * Fetch a new list of options via ajax.
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.
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) {
576 if (!option.prop('selected')) {
579 existingValues.push(String(option.attr('value')));
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);
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);
600 originalSelect.attr('data-notice', '');
602 // The AJAX handler returned a string instead of the array.
603 originalSelect.attr('data-notice', processedResults);
605 // Update the list of suggestions now from the new values in the select list.
606 pendingPromise.resolve(updateSuggestions(options, state, '', originalSelect));
608 pendingPromise.reject(error);
611 return pendingPromise;
615 * Add all the event listeners required for keyboard nav, blur clicks etc.
617 * @method addNavigation
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.
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);
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();
637 } else if (inputElement.attr('aria-expanded') === "true") {
638 pendingJsPromise.resolve(activateNextItem(state));
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));
646 // Open the suggestions list.
647 pendingJsPromise.resolve(updateSuggestions(options, state, inputElement.val(), originalSelect));
650 // We handled this event, so prevent it.
654 // Choose the previous active item.
655 pendingJsPromise.resolve(activatePreviousItem(state));
657 // We handled this event, so prevent it.
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));
670 pendingJsPromise.resolve();
673 // We handled this event, so prevent it.
677 if (inputElement.attr('aria-expanded') === "true") {
678 // If the suggestion list is open, close it.
679 pendingJsPromise.resolve(closeSuggestions(state));
681 pendingJsPromise.resolve();
683 // We handled this event, so prevent it.
687 pendingJsPromise.resolve();
690 // Support multi lingual COMMA keycode (44).
691 inputElement.on('keypress', function(e) {
693 if (e.keyCode === KEYS.COMMA) {
695 // If we are allowing tags, comma should create a tag (or enter).
696 addPendingJSPromise('keypress-' + e.keyCode)
697 .resolve(createItem(options, state, originalSelect));
699 // We handled this event, so prevent it.
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() {
709 // If tags are enabled, create a tag.
710 addPendingJSPromise('form-autocomplete-submit')
711 .resolve(createItem(options, state, originalSelect));
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);
722 // Only close the menu if the input hasn't regained focus, and if the element still exists.
723 // Due to the half a second delay, it is possible that the input element no longer exist
724 // by the time this code is being executed.
725 if (focusElement.attr('id') != inputElement.attr('id') && $('#' + state.inputId).length) {
727 pendingPromise.then(function() {
728 return createItem(options, state, originalSelect);
732 pendingPromise.then(function() {
733 return closeSuggestions(state);
738 pendingPromise.resolve();
741 if (options.showSuggestions) {
742 var arrowElement = $(document.getElementById(state.downArrowId));
743 arrowElement.on('click', function(e) {
744 var pendingPromise = addPendingJSPromise('form-autocomplete-show-suggestions');
746 // Prevent the close timer, or we will open, then close the suggestions.
747 inputElement.focus();
749 // Handle ajax population of suggestions.
750 if (!inputElement.val() && options.ajax) {
751 require([options.ajax], function(ajaxHandler) {
752 pendingPromise.resolve(updateAjax(e, options, state, originalSelect, ajaxHandler));
755 // Else - open the suggestions list.
756 pendingPromise.resolve(updateSuggestions(options, state, inputElement.val(), originalSelect));
761 var suggestionsElement = $(document.getElementById(state.suggestionsId));
762 // Remove any click handler first.
763 suggestionsElement.parent().prop("onclick", null).off("click");
764 suggestionsElement.parent().on('click', '[role=option]', function(e) {
765 var pendingPromise = addPendingJSPromise('form-autocomplete-parent');
766 // Handle clicks on suggestions.
767 var element = $(e.currentTarget).closest('[role=option]');
768 var suggestionsElement = $(document.getElementById(state.suggestionsId));
769 // Find the index of the clicked on suggestion.
770 var current = suggestionsElement.children('[aria-hidden=false]').index(element);
773 activateItem(current, state)
776 return selectCurrentItem(options, state, originalSelect);
779 return pendingPromise.resolve();
783 var selectionElement = $(document.getElementById(state.selectionId));
784 // Handle clicks on the selected items (will unselect an item).
785 selectionElement.on('click', '[role=listitem]', function(e) {
786 var pendingPromise = addPendingJSPromise('form-autocomplete-clicks');
788 // Remove it from the selection.
789 pendingPromise.resolve(deselectItem(options, state, $(e.currentTarget), originalSelect));
791 // Keyboard navigation for the selection list.
792 selectionElement.on('keydown', function(e) {
793 var pendingPromise = addPendingJSPromise('form-autocomplete-keydown-' + e.keyCode);
796 // We handled this event, so prevent it.
799 // Choose the next selection item.
800 pendingPromise.resolve(activateNextSelection(state));
803 // We handled this event, so prevent it.
806 // Choose the previous selection item.
807 pendingPromise.resolve(activatePreviousSelection(state));
811 // Get the item that is currently selected.
812 var selectedItem = $(document.getElementById(state.selectionId)).children('[data-active-selection=true]');
816 // Unselect this item.
817 pendingPromise.resolve(deselectItem(options, state, selectedItem, originalSelect));
822 // Not handled. Resolve the promise.
823 pendingPromise.resolve();
826 // Whenever the input field changes, update the suggestion list.
827 if (options.showSuggestions) {
828 // If this field uses ajax, set it up.
830 require([options.ajax], function(ajaxHandler) {
831 // Creating throttled handlers free of race conditions, and accurate.
832 // This code keeps track of a throttleTimeout, which is periodically polled.
833 // Once the throttled function is executed, the fact that it is running is noted.
834 // If a subsequent request comes in whilst it is running, this request is re-applied.
835 var throttleTimeout = null;
836 var inProgress = false;
837 var pendingKey = 'autocomplete-throttledhandler';
838 var handler = function(e) {
839 // Empty the current timeout.
840 throttleTimeout = null;
842 // Mark this request as in-progress.
845 // Process the request.
846 updateAjax(e, options, state, originalSelect, ajaxHandler)
848 // Check if the throttleTimeout is still empty.
849 // There's a potential condition whereby the JS request takes long enough to complete that
850 // another task has been queued.
851 // In this case another task will be kicked off and we must wait for that before marking htis as
853 if (null === throttleTimeout) {
854 // Mark this task as complete.
855 M.util.js_complete(pendingKey);
861 .catch(notification.exception);
864 // For input events, we do not want to trigger many, many updates.
865 var throttledHandler = function(e) {
866 window.clearTimeout(throttleTimeout);
868 // A request is currently ongoing.
869 // Delay this request another 100ms.
870 throttleTimeout = window.setTimeout(throttledHandler.bind(this, e), 100);
874 if (throttleTimeout === null) {
875 // There is currently no existing timeout handler, and it has not been recently cleared, so
876 // this is the start of a throttling check.
877 M.util.js_pending(pendingKey);
880 // There is currently no existing timeout handler, and it has not been recently cleared, so this
881 // is the start of a throttling check.
882 // Queue a call to the handler.
883 throttleTimeout = window.setTimeout(handler.bind(this, e), 300);
886 // Trigger an ajax update after the text field value changes.
887 inputElement.on("input", throttledHandler);
890 inputElement.on('input', function(e) {
891 var query = $(e.currentTarget).val();
892 var last = $(e.currentTarget).data('last-value');
893 // IE11 fires many more input events than required - even when the value has not changed.
894 // We need to only do this for real value changed events or the suggestions will be
895 // unclickable on IE11 (because they will be rebuilt before the click event fires).
896 // Note - because of this we cannot close the list when the query is empty or it will break
898 if (last !== query) {
899 updateSuggestions(options, state, query, originalSelect);
901 $(e.currentTarget).data('last-value', query);
908 * Create and return an unresolved Promise for some pending JS.
910 * @param {String} key The unique identifier for this promise
913 var addPendingJSPromise = function(key) {
914 var pendingKey = 'form-autocomplete:' + key;
916 M.util.js_pending(pendingKey);
918 var pendingPromise = $.Deferred();
922 M.util.js_complete(pendingKey);
926 .catch(notification.exception);
928 return pendingPromise;
931 return /** @alias module:core/form-autocomplete */ {
932 // Public variables and functions.
934 * Turn a boring select box into an auto-complete beast.
937 * @param {string} selector The selector that identifies the select box.
938 * @param {boolean} tags Whether to allow support for tags (can define new entries).
939 * @param {string} ajax Name of an AMD module to handle ajax requests. If specified, the AMD
940 * module must expose 2 functions "transport" and "processResults".
941 * These are modeled on Select2 see: https://select2.github.io/options.html#ajax
942 * @param {String} placeholder - The text to display before a selection is made.
943 * @param {Boolean} caseSensitive - If search has to be made case sensitive.
944 * @param {Boolean} showSuggestions - If suggestions should be shown
945 * @param {String} noSelectionString - Text to display when there is no selection
946 * @param {Boolean} closeSuggestionsOnSelect - Whether to close the suggestions immediately after making a selection.
949 enhance: function(selector, tags, ajax, placeholder, caseSensitive, showSuggestions, noSelectionString,
950 closeSuggestionsOnSelect) {
951 // Set some default values.
956 placeholder: placeholder,
957 caseSensitive: false,
958 showSuggestions: true,
959 noSelectionString: noSelectionString
961 var pendingKey = 'autocomplete-setup-' + selector;
962 M.util.js_pending(pendingKey);
963 if (typeof tags !== "undefined") {
966 if (typeof ajax !== "undefined") {
969 if (typeof caseSensitive !== "undefined") {
970 options.caseSensitive = caseSensitive;
972 if (typeof showSuggestions !== "undefined") {
973 options.showSuggestions = showSuggestions;
975 if (typeof noSelectionString === "undefined") {
976 str.get_string('noselection', 'form').done(function(result) {
977 options.noSelectionString = result;
978 }).fail(notification.exception);
981 // Look for the select element.
982 var originalSelect = $(selector);
983 if (!originalSelect) {
984 log.debug('Selector not found: ' + selector);
985 M.util.js_complete(pendingKey);
989 originalSelect.css('visibility', 'hidden').attr('aria-hidden', true);
991 // Hide the original select.
993 // Find or generate some ids.
995 selectId: originalSelect.attr('id'),
996 inputId: 'form_autocomplete_input-' + uniqueId,
997 suggestionsId: 'form_autocomplete_suggestions-' + uniqueId,
998 selectionId: 'form_autocomplete_selection-' + uniqueId,
999 downArrowId: 'form_autocomplete_downarrow-' + uniqueId
1002 // Increment the unique counter so we don't get duplicates ever.
1005 options.multiple = originalSelect.attr('multiple');
1007 if (typeof closeSuggestionsOnSelect !== "undefined") {
1008 options.closeSuggestionsOnSelect = closeSuggestionsOnSelect;
1010 // If not specified, this will close suggestions by default for single-select elements only.
1011 options.closeSuggestionsOnSelect = !options.multiple;
1014 var originalLabel = $('[for=' + state.selectId + ']');
1015 // Create the new markup and insert it after the select.
1016 var suggestions = [];
1017 originalSelect.children('option').each(function(index, option) {
1018 suggestions[index] = {label: option.innerHTML, value: $(option).attr('value')};
1021 // Render all the parts of our UI.
1022 var context = $.extend({}, options, state);
1023 context.options = suggestions;
1026 // Collect rendered inline JS to be executed once the HTML is shown.
1027 var collectedjs = '';
1029 var renderInput = templates.render('core/form_autocomplete_input', context).then(function(html, js) {
1034 var renderDatalist = templates.render('core/form_autocomplete_suggestions', context).then(function(html, js) {
1039 var renderSelection = templates.render('core/form_autocomplete_selection', context).then(function(html, js) {
1044 return $.when(renderInput, renderDatalist, renderSelection)
1045 .then(function(input, suggestions, selection) {
1046 originalSelect.hide();
1047 originalSelect.after(suggestions);
1048 originalSelect.after(input);
1049 originalSelect.after(selection);
1051 templates.runTemplateJS(collectedjs);
1053 // Update the form label to point to the text input.
1054 originalLabel.attr('for', state.inputId);
1055 // Add the event handlers.
1056 addNavigation(options, state, originalSelect);
1058 var suggestionsElement = $(document.getElementById(state.suggestionsId));
1059 // Hide the suggestions by default.
1060 suggestionsElement.hide().attr('aria-hidden', true);
1065 // Show the current values in the selection list.
1066 return updateSelectionList(options, state, originalSelect);
1069 return M.util.js_complete(pendingKey);
1071 .catch(function(error) {
1072 M.util.js_complete(pendingKey);
1073 notification.exception(error);