weekly release 3.6dev
[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 */
27define(['jquery', 'core/log', 'core/str', 'core/templates', 'core/notification'], function($, log, str, templates, notification) {
28
29 // Private functions and variables.
30 /** @var {Object} KEYS - List of keycode constants. */
31 var KEYS = {
32 DOWN: 40,
33 ENTER: 13,
34 SPACE: 32,
35 ESCAPE: 27,
e375029e 36 COMMA: 44,
60a1ea56
DW
37 UP: 38
38 };
39
b7df2485
DW
40 var uniqueId = $.now();
41
60a1ea56
DW
42 /**
43 * Make an item in the selection list "active".
44 *
45 * @method activateSelection
46 * @private
47 * @param {Number} index The index in the current (visible) list of selection.
273b2556 48 * @param {Object} state State variables for this autocomplete element.
60a1ea56 49 */
273b2556 50 var activateSelection = function(index, state) {
60a1ea56 51 // Find the elements in the DOM.
273b2556 52 var selectionElement = $(document.getElementById(state.selectionId));
60a1ea56
DW
53
54 // Count the visible items.
55 var length = selectionElement.children('[aria-selected=true]').length;
56 // Limit the index to the upper/lower bounds of the list (wrap in both directions).
57 index = index % length;
58 while (index < 0) {
59 index += length;
60 }
61 // Find the specified element.
62 var element = $(selectionElement.children('[aria-selected=true]').get(index));
63 // Create an id we can assign to this element.
273b2556 64 var itemId = state.selectionId + '-' + index;
60a1ea56
DW
65
66 // Deselect all the selections.
67 selectionElement.children().attr('data-active-selection', false).attr('id', '');
68 // Select only this suggestion and assign it the id.
69 element.attr('data-active-selection', true).attr('id', itemId);
70 // Tell the input field it has a new active descendant so the item is announced.
71 selectionElement.attr('aria-activedescendant', itemId);
72 };
73
f992dcf6
DP
74 /**
75 * Update the element that shows the currently selected items.
76 *
77 * @method updateSelectionList
78 * @private
79 * @param {Object} options Original options for this autocomplete element.
80 * @param {Object} state State variables for this autocomplete element.
81 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
82 */
83 var updateSelectionList = function(options, state, originalSelect) {
84 // Build up a valid context to re-render the template.
85 var items = [];
86 var newSelection = $(document.getElementById(state.selectionId));
87 var activeId = newSelection.attr('aria-activedescendant');
88 var activeValue = false;
89
90 if (activeId) {
91 activeValue = $(document.getElementById(activeId)).attr('data-value');
92 }
93 originalSelect.children('option').each(function(index, ele) {
94 if ($(ele).prop('selected')) {
a97c9370 95 var label;
96 if ($(ele).data('html')) {
97 label = $(ele).data('html');
98 } else {
99 label = $(ele).html();
100 }
101 items.push({label: label, value: $(ele).attr('value')});
f992dcf6
DP
102 }
103 });
9f5f3dcc 104 var context = $.extend({items: items}, options, state);
f992dcf6
DP
105
106 // Render the template.
107 templates.render('core/form_autocomplete_selection', context).done(function(newHTML) {
108 // Add it to the page.
109 newSelection.empty().append($(newHTML).html());
110
111 if (activeValue !== false) {
112 // Reselect any previously selected item.
113 newSelection.children('[aria-selected=true]').each(function(index, ele) {
114 if ($(ele).attr('data-value') === activeValue) {
115 activateSelection(index, state);
116 }
117 });
118 }
119 }).fail(notification.exception);
1eaba735
FM
120 };
121
122 /**
123 * Notify of a change in the selection.
124 *
125 * @param {jQuery} originalSelect The jQuery object matching the hidden select list.
1eaba735
FM
126 */
127 var notifyChange = function(originalSelect) {
128 if (typeof M.core_formchangechecker !== 'undefined') {
eb97811b
MG
129 M.core_formchangechecker.set_form_changed();
130 }
f992dcf6
DP
131 originalSelect.change();
132 };
133
60a1ea56 134 /**
563fe0a5 135 * Remove the given item from the list of selected things.
60a1ea56 136 *
563fe0a5 137 * @method deselectItem
60a1ea56 138 * @private
273b2556
DW
139 * @param {Object} options Original options for this autocomplete element.
140 * @param {Object} state State variables for this autocomplete element.
c96f55e6 141 * @param {Element} item The item to be deselected.
60a1ea56 142 * @param {Element} originalSelect The original select list.
60a1ea56 143 */
273b2556 144 var deselectItem = function(options, state, item, originalSelect) {
563fe0a5
RW
145 var selectedItemValue = $(item).attr('data-value');
146
147 // We can only deselect items if this is a multi-select field.
273b2556 148 if (options.multiple) {
563fe0a5
RW
149 // Look for a match, and toggle the selected property if there is a match.
150 originalSelect.children('option').each(function(index, ele) {
151 if ($(ele).attr('value') == selectedItemValue) {
152 $(ele).prop('selected', false);
bdd60287
DW
153 // We remove newly created custom tags from the suggestions list when they are deselected.
154 if ($(ele).attr('data-iscustom')) {
155 $(ele).remove();
156 }
60a1ea56 157 }
563fe0a5
RW
158 });
159 }
60a1ea56 160 // Rerender the selection list.
273b2556 161 updateSelectionList(options, state, originalSelect);
1eaba735
FM
162 // Notifiy that the selection changed.
163 notifyChange(originalSelect);
60a1ea56
DW
164 };
165
166 /**
167 * Make an item in the suggestions "active" (about to be selected).
168 *
169 * @method activateItem
170 * @private
171 * @param {Number} index The index in the current (visible) list of suggestions.
273b2556 172 * @param {Object} state State variables for this instance of autocomplete.
60a1ea56 173 */
273b2556 174 var activateItem = function(index, state) {
60a1ea56 175 // Find the elements in the DOM.
273b2556
DW
176 var inputElement = $(document.getElementById(state.inputId));
177 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
178
179 // Count the visible items.
180 var length = suggestionsElement.children('[aria-hidden=false]').length;
181 // Limit the index to the upper/lower bounds of the list (wrap in both directions).
182 index = index % length;
183 while (index < 0) {
184 index += length;
185 }
186 // Find the specified element.
187 var element = $(suggestionsElement.children('[aria-hidden=false]').get(index));
188 // Find the index of this item in the full list of suggestions (including hidden).
189 var globalIndex = $(suggestionsElement.children('[role=option]')).index(element);
190 // Create an id we can assign to this element.
273b2556 191 var itemId = state.suggestionsId + '-' + globalIndex;
60a1ea56
DW
192
193 // Deselect all the suggestions.
194 suggestionsElement.children().attr('aria-selected', false).attr('id', '');
195 // Select only this suggestion and assign it the id.
196 element.attr('aria-selected', true).attr('id', itemId);
197 // Tell the input field it has a new active descendant so the item is announced.
198 inputElement.attr('aria-activedescendant', itemId);
32f3de56
DW
199
200 // Scroll it into view.
201 var scrollPos = element.offset().top
202 - suggestionsElement.offset().top
203 + suggestionsElement.scrollTop()
204 - (suggestionsElement.height() / 2);
205 suggestionsElement.animate({
206 scrollTop: scrollPos
207 }, 100);
60a1ea56
DW
208 };
209
210 /**
211 * Find the index of the current active suggestion, and activate the next one.
212 *
213 * @method activateNextItem
214 * @private
273b2556 215 * @param {Object} state State variable for this auto complete element.
60a1ea56 216 */
273b2556 217 var activateNextItem = function(state) {
60a1ea56 218 // Find the list of suggestions.
273b2556 219 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
220 // Find the active one.
221 var element = suggestionsElement.children('[aria-selected=true]');
222 // Find it's index.
223 var current = suggestionsElement.children('[aria-hidden=false]').index(element);
224 // Activate the next one.
35be5826 225 activateItem(current + 1, state);
60a1ea56
DW
226 };
227
228 /**
229 * Find the index of the current active selection, and activate the previous one.
230 *
231 * @method activatePreviousSelection
232 * @private
273b2556 233 * @param {Object} state State variables for this instance of autocomplete.
60a1ea56 234 */
273b2556 235 var activatePreviousSelection = function(state) {
60a1ea56 236 // Find the list of selections.
273b2556 237 var selectionsElement = $(document.getElementById(state.selectionId));
60a1ea56
DW
238 // Find the active one.
239 var element = selectionsElement.children('[data-active-selection=true]');
240 if (!element) {
273b2556 241 activateSelection(0, state);
60a1ea56
DW
242 return;
243 }
244 // Find it's index.
245 var current = selectionsElement.children('[aria-selected=true]').index(element);
246 // Activate the next one.
35be5826 247 activateSelection(current - 1, state);
60a1ea56
DW
248 };
249 /**
250 * Find the index of the current active selection, and activate the next one.
251 *
252 * @method activateNextSelection
253 * @private
273b2556 254 * @param {Object} state State variables for this instance of autocomplete.
60a1ea56 255 */
273b2556 256 var activateNextSelection = function(state) {
60a1ea56 257 // Find the list of selections.
273b2556 258 var selectionsElement = $(document.getElementById(state.selectionId));
60a1ea56
DW
259 // Find the active one.
260 var element = selectionsElement.children('[data-active-selection=true]');
261 if (!element) {
273b2556 262 activateSelection(0, state);
60a1ea56
DW
263 return;
264 }
265 // Find it's index.
266 var current = selectionsElement.children('[aria-selected=true]').index(element);
267 // Activate the next one.
35be5826 268 activateSelection(current + 1, state);
60a1ea56
DW
269 };
270
271 /**
272 * Find the index of the current active suggestion, and activate the previous one.
273 *
274 * @method activatePreviousItem
275 * @private
273b2556 276 * @param {Object} state State variables for this autocomplete element.
60a1ea56 277 */
273b2556 278 var activatePreviousItem = function(state) {
60a1ea56 279 // Find the list of suggestions.
273b2556 280 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
281 // Find the active one.
282 var element = suggestionsElement.children('[aria-selected=true]');
283 // Find it's index.
284 var current = suggestionsElement.children('[aria-hidden=false]').index(element);
285 // Activate the next one.
35be5826 286 activateItem(current - 1, state);
60a1ea56
DW
287 };
288
289 /**
290 * Close the list of suggestions.
291 *
292 * @method closeSuggestions
293 * @private
273b2556 294 * @param {Object} state State variables for this autocomplete element.
60a1ea56 295 */
273b2556 296 var closeSuggestions = function(state) {
60a1ea56 297 // Find the elements in the DOM.
273b2556
DW
298 var inputElement = $(document.getElementById(state.inputId));
299 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
300
301 // Announce the list of suggestions was closed, and read the current list of selections.
273b2556 302 inputElement.attr('aria-expanded', false).attr('aria-activedescendant', state.selectionId);
60a1ea56
DW
303 // Hide the suggestions list (from screen readers too).
304 suggestionsElement.hide().attr('aria-hidden', true);
305 };
306
307 /**
308 * Rebuild the list of suggestions based on the current values in the select list, and the query.
309 *
310 * @method updateSuggestions
311 * @private
273b2556
DW
312 * @param {Object} options The original options for this autocomplete.
313 * @param {Object} state The state variables for this autocomplete.
314 * @param {String} query The current text for the search string.
60a1ea56 315 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
60a1ea56 316 */
273b2556 317 var updateSuggestions = function(options, state, query, originalSelect) {
60a1ea56 318 // Find the elements in the DOM.
273b2556
DW
319 var inputElement = $(document.getElementById(state.inputId));
320 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
321
322 // Used to track if we found any visible suggestions.
323 var matchingElements = false;
324 // Options is used by the context when rendering the suggestions from a template.
273b2556 325 var suggestions = [];
60a1ea56
DW
326 originalSelect.children('option').each(function(index, option) {
327 if ($(option).prop('selected') !== true) {
9f5f3dcc 328 suggestions[suggestions.length] = {label: option.innerHTML, value: $(option).attr('value')};
60a1ea56
DW
329 }
330 });
331
332 // Re-render the list of suggestions.
273b2556 333 var searchquery = state.caseSensitive ? query : query.toLocaleLowerCase();
9f5f3dcc 334 var context = $.extend({options: suggestions}, options, state);
60a1ea56
DW
335 templates.render(
336 'core/form_autocomplete_suggestions',
273b2556 337 context
60a1ea56
DW
338 ).done(function(newHTML) {
339 // We have the new template, insert it in the page.
340 suggestionsElement.replaceWith(newHTML);
341 // Get the element again.
273b2556 342 suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
343 // Show it if it is hidden.
344 suggestionsElement.show().attr('aria-hidden', false);
345 // For each option in the list, hide it if it doesn't match the query.
346 suggestionsElement.children().each(function(index, node) {
347 node = $(node);
273b2556
DW
348 if ((options.caseSensitive && node.text().indexOf(searchquery) > -1) ||
349 (!options.caseSensitive && node.text().toLocaleLowerCase().indexOf(searchquery) > -1)) {
60a1ea56
DW
350 node.show().attr('aria-hidden', false);
351 matchingElements = true;
352 } else {
353 node.hide().attr('aria-hidden', true);
354 }
355 });
356 // If we found any matches, show the list.
81c471e2 357 inputElement.attr('aria-expanded', true);
60a1ea56 358 if (matchingElements) {
60a1ea56
DW
359 // We only activate the first item in the list if tags is false,
360 // because otherwise "Enter" would select the first item, instead of
361 // creating a new tag.
273b2556
DW
362 if (!options.tags) {
363 activateItem(0, state);
60a1ea56
DW
364 }
365 } else {
81c471e2
DW
366 // Nothing matches. Tell them that.
367 str.get_string('nosuggestions', 'form').done(function(nosuggestionsstr) {
368 suggestionsElement.html(nosuggestionsstr);
369 });
60a1ea56
DW
370 }
371 }).fail(notification.exception);
372
373 };
374
375 /**
376 * Create a new item for the list (a tag).
377 *
378 * @method createItem
379 * @private
273b2556
DW
380 * @param {Object} options The original options for the autocomplete.
381 * @param {Object} state State variables for the autocomplete.
60a1ea56
DW
382 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
383 */
273b2556 384 var createItem = function(options, state, originalSelect) {
60a1ea56 385 // Find the element in the DOM.
273b2556 386 var inputElement = $(document.getElementById(state.inputId));
60a1ea56
DW
387 // Get the current text in the input field.
388 var query = inputElement.val();
389 var tags = query.split(',');
390 var found = false;
391
392 $.each(tags, function(tagindex, tag) {
393 // If we can only select one at a time, deselect any current value.
394 tag = tag.trim();
395 if (tag !== '') {
273b2556 396 if (!options.multiple) {
60a1ea56
DW
397 originalSelect.children('option').prop('selected', false);
398 }
399 // Look for an existing option in the select list that matches this new tag.
400 originalSelect.children('option').each(function(index, ele) {
401 if ($(ele).attr('value') == tag) {
402 found = true;
403 $(ele).prop('selected', true);
404 }
405 });
406 // Only create the item if it's new.
407 if (!found) {
408 var option = $('<option>');
409 option.append(tag);
410 option.attr('value', tag);
411 originalSelect.append(option);
412 option.prop('selected', true);
bdd60287
DW
413 // We mark newly created custom options as we handle them differently if they are "deselected".
414 option.attr('data-iscustom', true);
60a1ea56
DW
415 }
416 }
417 });
bdd60287 418
273b2556 419 updateSelectionList(options, state, originalSelect);
1eaba735
FM
420 // Notifiy that the selection changed.
421 notifyChange(originalSelect);
60a1ea56
DW
422 // Clear the input field.
423 inputElement.val('');
424 // Close the suggestions list.
273b2556 425 closeSuggestions(state);
60a1ea56
DW
426 };
427
60a1ea56
DW
428 /**
429 * Select the currently active item from the suggestions list.
430 *
431 * @method selectCurrentItem
432 * @private
273b2556
DW
433 * @param {Object} options The original options for the autocomplete.
434 * @param {Object} state State variables for the autocomplete.
60a1ea56
DW
435 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
436 */
273b2556 437 var selectCurrentItem = function(options, state, originalSelect) {
60a1ea56 438 // Find the elements in the page.
273b2556
DW
439 var inputElement = $(document.getElementById(state.inputId));
440 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
441 // Here loop through suggestions and set val to join of all selected items.
442
443 var selectedItemValue = suggestionsElement.children('[aria-selected=true]').attr('data-value');
444 // The select will either be a single or multi select, so the following will either
445 // select one or more items correctly.
446 // Take care to use 'prop' and not 'attr' for selected properties.
447 // If only one can be selected at a time, start by deselecting everything.
273b2556 448 if (!options.multiple) {
60a1ea56
DW
449 originalSelect.children('option').prop('selected', false);
450 }
451 // Look for a match, and toggle the selected property if there is a match.
452 originalSelect.children('option').each(function(index, ele) {
453 if ($(ele).attr('value') == selectedItemValue) {
454 $(ele).prop('selected', true);
455 }
456 });
78162bf5 457
60a1ea56 458 // Rerender the selection list.
273b2556 459 updateSelectionList(options, state, originalSelect);
1eaba735
FM
460 // Notifiy that the selection changed.
461 notifyChange(originalSelect);
786e014c 462
198d7291 463 if (options.closeSuggestionsOnSelect) {
786e014c
DW
464 // Clear the input element.
465 inputElement.val('');
466 // Close the list of suggestions.
467 closeSuggestions(state);
468 } else {
469 // Focus on the input element so the suggestions does not auto-close.
470 inputElement.focus();
471 // Remove the last selected item from the suggestions list.
472 updateSuggestions(options, state, inputElement.val(), originalSelect);
473 }
60a1ea56
DW
474 };
475
476 /**
477 * Fetch a new list of options via ajax.
478 *
479 * @method updateAjax
480 * @private
481 * @param {Event} e The event that triggered this update.
273b2556
DW
482 * @param {Object} options The original options for the autocomplete.
483 * @param {Object} state The state variables for the autocomplete.
60a1ea56 484 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
60a1ea56
DW
485 * @param {Object} ajaxHandler This is a module that does the ajax fetch and translates the results.
486 */
273b2556 487 var updateAjax = function(e, options, state, originalSelect, ajaxHandler) {
78162bf5
AN
488 var pendingKey = 'form-autocomplete-updateajax';
489 M.util.js_pending(pendingKey);
60a1ea56
DW
490 // Get the query to pass to the ajax function.
491 var query = $(e.currentTarget).val();
492 // Call the transport function to do the ajax (name taken from Select2).
273b2556 493 ajaxHandler.transport(options.selector, query, function(results) {
60a1ea56 494 // We got a result - pass it through the translator before using it.
273b2556 495 var processedResults = ajaxHandler.processResults(options.selector, results);
60a1ea56
DW
496 var existingValues = [];
497
498 // Now destroy all options that are not currently selected.
499 originalSelect.children('option').each(function(optionIndex, option) {
500 option = $(option);
501 if (!option.prop('selected')) {
502 option.remove();
503 } else {
91ab264c 504 existingValues.push(String(option.attr('value')));
60a1ea56
DW
505 }
506 });
91ab264c
DW
507
508 if (!options.multiple && originalSelect.children('option').length === 0) {
509 // If this is a single select - and there are no current options
510 // the first option added will be selected by the browser. This causes a bug!
511 // We need to insert an empty option so that none of the real options are selected.
512 var option = $('<option>');
513 originalSelect.append(option);
514 }
60a1ea56
DW
515 // And add all the new ones returned from ajax.
516 $.each(processedResults, function(resultIndex, result) {
91ab264c 517 if (existingValues.indexOf(String(result.value)) === -1) {
60a1ea56
DW
518 var option = $('<option>');
519 option.append(result.label);
520 option.attr('value', result.value);
521 originalSelect.append(option);
522 }
523 });
524 // Update the list of suggestions now from the new values in the select list.
273b2556 525 updateSuggestions(options, state, '', originalSelect);
78162bf5
AN
526 M.util.js_complete(pendingKey);
527 }, function(error) {
528 M.util.js_complete(pendingKey);
529 notification.exception(error);
530 });
60a1ea56
DW
531 };
532
533 /**
534 * Add all the event listeners required for keyboard nav, blur clicks etc.
535 *
536 * @method addNavigation
537 * @private
273b2556
DW
538 * @param {Object} options The options used to create this autocomplete element.
539 * @param {Object} state State variables for this autocomplete element.
60a1ea56 540 * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
60a1ea56 541 */
273b2556 542 var addNavigation = function(options, state, originalSelect) {
60a1ea56 543 // Start with the input element.
273b2556 544 var inputElement = $(document.getElementById(state.inputId));
60a1ea56
DW
545 // Add keyboard nav with keydown.
546 inputElement.on('keydown', function(e) {
78162bf5
AN
547 var pendingKey = 'form-autocomplete-addnav-' + state.inputId + '-' + e.keyCode;
548 M.util.js_pending(pendingKey);
549
60a1ea56
DW
550 switch (e.keyCode) {
551 case KEYS.DOWN:
552 // If the suggestion list is open, move to the next item.
273b2556 553 if (!options.showSuggestions) {
97d2ea7f 554 // Do not consume this event.
78162bf5 555 M.util.js_complete(pendingKey);
97d2ea7f
DW
556 return true;
557 } else if (inputElement.attr('aria-expanded') === "true") {
273b2556 558 activateNextItem(state);
60a1ea56 559 } else {
d304952b 560 // Handle ajax population of suggestions.
273b2556
DW
561 if (!inputElement.val() && options.ajax) {
562 require([options.ajax], function(ajaxHandler) {
563 updateAjax(e, options, state, originalSelect, ajaxHandler);
d304952b
AG
564 });
565 } else {
47dd5350 566 // Open the suggestions list.
273b2556 567 updateSuggestions(options, state, inputElement.val(), originalSelect);
d304952b 568 }
60a1ea56
DW
569 }
570 // We handled this event, so prevent it.
571 e.preventDefault();
78162bf5 572 M.util.js_complete(pendingKey);
60a1ea56 573 return false;
60a1ea56
DW
574 case KEYS.UP:
575 // Choose the previous active item.
273b2556 576 activatePreviousItem(state);
60a1ea56
DW
577 // We handled this event, so prevent it.
578 e.preventDefault();
78162bf5 579 M.util.js_complete(pendingKey);
60a1ea56
DW
580 return false;
581 case KEYS.ENTER:
273b2556 582 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
583 if ((inputElement.attr('aria-expanded') === "true") &&
584 (suggestionsElement.children('[aria-selected=true]').length > 0)) {
585 // If the suggestion list has an active item, select it.
273b2556
DW
586 selectCurrentItem(options, state, originalSelect);
587 } else if (options.tags) {
60a1ea56 588 // If tags are enabled, create a tag.
273b2556 589 createItem(options, state, originalSelect);
60a1ea56
DW
590 }
591 // We handled this event, so prevent it.
592 e.preventDefault();
78162bf5 593 M.util.js_complete(pendingKey);
60a1ea56
DW
594 return false;
595 case KEYS.ESCAPE:
596 if (inputElement.attr('aria-expanded') === "true") {
597 // If the suggestion list is open, close it.
273b2556 598 closeSuggestions(state);
60a1ea56
DW
599 }
600 // We handled this event, so prevent it.
601 e.preventDefault();
78162bf5 602 M.util.js_complete(pendingKey);
60a1ea56 603 return false;
e375029e 604 }
78162bf5 605 M.util.js_complete(pendingKey);
e375029e
NK
606 return true;
607 });
608 // Support multi lingual COMMA keycode (44).
609 inputElement.on('keypress', function(e) {
78162bf5
AN
610 var pendingKey = 'form-autocomplete-keypress-' + e.keyCode;
611 M.util.js_pending(pendingKey);
e375029e
NK
612 if (e.keyCode === KEYS.COMMA) {
613 if (options.tags) {
614 // If we are allowing tags, comma should create a tag (or enter).
615 createItem(options, state, originalSelect);
616 }
617 // We handled this event, so prevent it.
618 e.preventDefault();
78162bf5 619 M.util.js_complete(pendingKey);
e375029e 620 return false;
60a1ea56 621 }
78162bf5 622 M.util.js_complete(pendingKey);
60a1ea56
DW
623 return true;
624 });
625 // Handler used to force set the value from behat.
626 inputElement.on('behat:set-value', function() {
6f326bd2 627 var suggestionsElement = $(document.getElementById(state.suggestionsId));
78162bf5
AN
628 var pendingKey = 'form-autocomplete-behat';
629 M.util.js_pending(pendingKey);
6f326bd2
DW
630 if ((inputElement.attr('aria-expanded') === "true") &&
631 (suggestionsElement.children('[aria-selected=true]').length > 0)) {
632 // If the suggestion list has an active item, select it.
633 selectCurrentItem(options, state, originalSelect);
634 } else if (options.tags) {
635 // If tags are enabled, create a tag.
273b2556 636 createItem(options, state, originalSelect);
60a1ea56 637 }
78162bf5 638 M.util.js_complete(pendingKey);
60a1ea56 639 });
e1db2b41 640 inputElement.on('blur', function() {
78162bf5
AN
641 var pendingKey = 'form-autocomplete-blur';
642 M.util.js_pending(pendingKey);
e1db2b41
RW
643 window.setTimeout(function() {
644 // Get the current element with focus.
645 var focusElement = $(document.activeElement);
646 // Only close the menu if the input hasn't regained focus.
647 if (focusElement.attr('id') != inputElement.attr('id')) {
273b2556
DW
648 if (options.tags) {
649 createItem(options, state, originalSelect);
527bde6e 650 }
273b2556 651 closeSuggestions(state);
60a1ea56 652 }
78162bf5 653 M.util.js_complete(pendingKey);
60a1ea56
DW
654 }, 500);
655 });
273b2556
DW
656 if (options.showSuggestions) {
657 var arrowElement = $(document.getElementById(state.downArrowId));
47dd5350 658 arrowElement.on('click', function(e) {
78162bf5
AN
659 var pendingKey = 'form-autocomplete-show-suggestions';
660 M.util.js_pending(pendingKey);
97d2ea7f
DW
661 // Prevent the close timer, or we will open, then close the suggestions.
662 inputElement.focus();
47dd5350
DW
663 // Handle ajax population of suggestions.
664 if (!inputElement.val() && options.ajax) {
665 require([options.ajax], function(ajaxHandler) {
666 updateAjax(e, options, state, originalSelect, ajaxHandler);
667 });
668 } else {
669 // Else - open the suggestions list.
670 updateSuggestions(options, state, inputElement.val(), originalSelect);
671 }
78162bf5 672 M.util.js_complete(pendingKey);
97d2ea7f
DW
673 });
674 }
60a1ea56 675
273b2556 676 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56 677 suggestionsElement.parent().on('click', '[role=option]', function(e) {
78162bf5
AN
678 var pendingKey = 'form-autocomplete-parent';
679 M.util.js_pending(pendingKey);
60a1ea56
DW
680 // Handle clicks on suggestions.
681 var element = $(e.currentTarget).closest('[role=option]');
273b2556 682 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
683 // Find the index of the clicked on suggestion.
684 var current = suggestionsElement.children('[aria-hidden=false]').index(element);
685 // Activate it.
273b2556 686 activateItem(current, state);
60a1ea56 687 // And select it.
273b2556 688 selectCurrentItem(options, state, originalSelect);
78162bf5 689 M.util.js_complete(pendingKey);
60a1ea56 690 });
273b2556 691 var selectionElement = $(document.getElementById(state.selectionId));
60a1ea56 692 // Handle clicks on the selected items (will unselect an item).
adebc069 693 selectionElement.on('click', '[role=listitem]', function(e) {
78162bf5
AN
694 var pendingKey = 'form-autocomplete-clicks';
695 M.util.js_pending(pendingKey);
563fe0a5
RW
696 // Get the item that was clicked.
697 var item = $(e.currentTarget);
698 // Remove it from the selection.
273b2556 699 deselectItem(options, state, item, originalSelect);
78162bf5 700 M.util.js_complete(pendingKey);
60a1ea56
DW
701 });
702 // Keyboard navigation for the selection list.
adebc069 703 selectionElement.on('keydown', function(e) {
78162bf5
AN
704 var pendingKey = 'form-autocomplete-keydown-' + e.keyCode;
705 M.util.js_pending(pendingKey);
60a1ea56
DW
706 switch (e.keyCode) {
707 case KEYS.DOWN:
708 // Choose the next selection item.
273b2556 709 activateNextSelection(state);
60a1ea56
DW
710 // We handled this event, so prevent it.
711 e.preventDefault();
78162bf5 712 M.util.js_complete(pendingKey);
60a1ea56
DW
713 return false;
714 case KEYS.UP:
715 // Choose the previous selection item.
273b2556 716 activatePreviousSelection(state);
60a1ea56
DW
717 // We handled this event, so prevent it.
718 e.preventDefault();
78162bf5 719 M.util.js_complete(pendingKey);
60a1ea56
DW
720 return false;
721 case KEYS.SPACE:
722 case KEYS.ENTER:
563fe0a5 723 // Get the item that is currently selected.
273b2556 724 var selectedItem = $(document.getElementById(state.selectionId)).children('[data-active-selection=true]');
563fe0a5
RW
725 if (selectedItem) {
726 // Unselect this item.
273b2556 727 deselectItem(options, state, selectedItem, originalSelect);
563fe0a5
RW
728 // We handled this event, so prevent it.
729 e.preventDefault();
730 }
78162bf5 731 M.util.js_complete(pendingKey);
60a1ea56
DW
732 return false;
733 }
78162bf5 734 M.util.js_complete(pendingKey);
60a1ea56
DW
735 return true;
736 });
737 // Whenever the input field changes, update the suggestion list.
273b2556 738 if (options.showSuggestions) {
68a0485c
JP
739 // If this field uses ajax, set it up.
740 if (options.ajax) {
741 require([options.ajax], function(ajaxHandler) {
742 var throttleTimeout = null;
78162bf5 743 var pendingKey = 'autocomplete-throttledhandler';
68a0485c
JP
744 var handler = function(e) {
745 updateAjax(e, options, state, originalSelect, ajaxHandler);
78162bf5 746 M.util.js_complete(pendingKey);
68a0485c
JP
747 };
748
749 // For input events, we do not want to trigger many, many updates.
750 var throttledHandler = function(e) {
751 if (throttleTimeout !== null) {
752 window.clearTimeout(throttleTimeout);
753 throttleTimeout = null;
78162bf5
AN
754 } else {
755 // No existing timeout handler, so this is the start of a throttling check.
756 M.util.js_pending(pendingKey);
68a0485c
JP
757 }
758 throttleTimeout = window.setTimeout(handler.bind(this, e), 300);
759 };
760 // Trigger an ajax update after the text field value changes.
761 inputElement.on("input", throttledHandler);
762 });
763 } else {
764 inputElement.on('input', function(e) {
765 var query = $(e.currentTarget).val();
766 var last = $(e.currentTarget).data('last-value');
767 // IE11 fires many more input events than required - even when the value has not changed.
768 // We need to only do this for real value changed events or the suggestions will be
769 // unclickable on IE11 (because they will be rebuilt before the click event fires).
770 // Note - because of this we cannot close the list when the query is empty or it will break
771 // on IE11.
772 if (last !== query) {
773 updateSuggestions(options, state, query, originalSelect);
774 }
775 $(e.currentTarget).data('last-value', query);
776 });
777 }
97d2ea7f 778 }
60a1ea56
DW
779 };
780
781 return /** @alias module:core/form-autocomplete */ {
782 // Public variables and functions.
783 /**
784 * Turn a boring select box into an auto-complete beast.
785 *
786 * @method enhance
c96f55e6 787 * @param {string} selector The selector that identifies the select box.
60a1ea56
DW
788 * @param {boolean} tags Whether to allow support for tags (can define new entries).
789 * @param {string} ajax Name of an AMD module to handle ajax requests. If specified, the AMD
790 * module must expose 2 functions "transport" and "processResults".
791 * These are modeled on Select2 see: https://select2.github.io/options.html#ajax
792 * @param {String} placeholder - The text to display before a selection is made.
ecbc2a2f 793 * @param {Boolean} caseSensitive - If search has to be made case sensitive.
c96f55e6 794 * @param {Boolean} showSuggestions - If suggestions should be shown
427e3cbc 795 * @param {String} noSelectionString - Text to display when there is no selection
198d7291 796 * @param {Boolean} closeSuggestionsOnSelect - Whether to close the suggestions immediately after making a selection.
13426bae 797 * @return {Promise}
60a1ea56 798 */
198d7291
JP
799 enhance: function(selector, tags, ajax, placeholder, caseSensitive, showSuggestions, noSelectionString,
800 closeSuggestionsOnSelect) {
60a1ea56 801 // Set some default values.
273b2556
DW
802 var options = {
803 selector: selector,
804 tags: false,
805 ajax: false,
806 placeholder: placeholder,
807 caseSensitive: false,
427e3cbc
EM
808 showSuggestions: true,
809 noSelectionString: noSelectionString
273b2556 810 };
78162bf5
AN
811 var pendingKey = 'autocomplete-setup-' + selector;
812 M.util.js_pending(pendingKey);
273b2556
DW
813 if (typeof tags !== "undefined") {
814 options.tags = tags;
60a1ea56 815 }
273b2556
DW
816 if (typeof ajax !== "undefined") {
817 options.ajax = ajax;
60a1ea56 818 }
273b2556
DW
819 if (typeof caseSensitive !== "undefined") {
820 options.caseSensitive = caseSensitive;
ecbc2a2f 821 }
273b2556
DW
822 if (typeof showSuggestions !== "undefined") {
823 options.showSuggestions = showSuggestions;
97d2ea7f 824 }
427e3cbc 825 if (typeof noSelectionString === "undefined") {
35be5826 826 str.get_string('noselection', 'form').done(function(result) {
1388b618
JP
827 options.noSelectionString = result;
828 }).fail(notification.exception);
427e3cbc 829 }
60a1ea56
DW
830
831 // Look for the select element.
832 var originalSelect = $(selector);
833 if (!originalSelect) {
834 log.debug('Selector not found: ' + selector);
78162bf5 835 M.util.js_complete(pendingKey);
f3ecea3a 836 return false;
60a1ea56
DW
837 }
838
d8e57f02
DW
839 originalSelect.css('visibility', 'hidden').attr('aria-hidden', true);
840
60a1ea56 841 // Hide the original select.
60a1ea56
DW
842
843 // Find or generate some ids.
273b2556
DW
844 var state = {
845 selectId: originalSelect.attr('id'),
b7df2485
DW
846 inputId: 'form_autocomplete_input-' + uniqueId,
847 suggestionsId: 'form_autocomplete_suggestions-' + uniqueId,
848 selectionId: 'form_autocomplete_selection-' + uniqueId,
849 downArrowId: 'form_autocomplete_downarrow-' + uniqueId
273b2556 850 };
b7df2485
DW
851
852 // Increment the unique counter so we don't get duplicates ever.
853 uniqueId++;
854
273b2556
DW
855 options.multiple = originalSelect.attr('multiple');
856
198d7291
JP
857 if (typeof closeSuggestionsOnSelect !== "undefined") {
858 options.closeSuggestionsOnSelect = closeSuggestionsOnSelect;
859 } else {
860 // If not specified, this will close suggestions by default for single-select elements only.
861 options.closeSuggestionsOnSelect = !options.multiple;
862 }
863
273b2556 864 var originalLabel = $('[for=' + state.selectId + ']');
60a1ea56 865 // Create the new markup and insert it after the select.
273b2556 866 var suggestions = [];
60a1ea56 867 originalSelect.children('option').each(function(index, option) {
9f5f3dcc 868 suggestions[index] = {label: option.innerHTML, value: $(option).attr('value')};
60a1ea56
DW
869 });
870
871 // Render all the parts of our UI.
273b2556
DW
872 var context = $.extend({}, options, state);
873 context.options = suggestions;
874 context.items = [];
875
876 var renderInput = templates.render('core/form_autocomplete_input', context);
877 var renderDatalist = templates.render('core/form_autocomplete_suggestions', context);
878 var renderSelection = templates.render('core/form_autocomplete_selection', context);
60a1ea56 879
f3ecea3a 880 return $.when(renderInput, renderDatalist, renderSelection).then(function(input, suggestions, selection) {
d8e57f02 881 originalSelect.hide();
60a1ea56
DW
882 originalSelect.after(suggestions);
883 originalSelect.after(input);
884 originalSelect.after(selection);
d8e57f02 885
60a1ea56 886 // Update the form label to point to the text input.
273b2556 887 originalLabel.attr('for', state.inputId);
60a1ea56 888 // Add the event handlers.
273b2556
DW
889 addNavigation(options, state, originalSelect);
890
273b2556 891 var suggestionsElement = $(document.getElementById(state.suggestionsId));
60a1ea56
DW
892 // Hide the suggestions by default.
893 suggestionsElement.hide().attr('aria-hidden', true);
894
60a1ea56 895 // Show the current values in the selection list.
273b2556 896 updateSelectionList(options, state, originalSelect);
78162bf5 897 M.util.js_complete(pendingKey);
13426bae 898 return true;
78162bf5
AN
899 }).fail(function(error) {
900 M.util.js_complete(pendingKey);
901 notification.exception(error);
60a1ea56
DW
902 });
903 }
904 };
905});