Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 * @copyright  2015 Damyon Wiese <damyon@moodle.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 * @since      3.0
23
 */
24
define([
25
    'jquery',
26
    'core/log',
27
    'core/str',
28
    'core/templates',
29
    'core/notification',
30
    'core/loadingicon',
31
    'core/aria',
32
    'core_form/changechecker',
1441 ariadna 33
    'core/popper2',
34
    'theme_boost/bootstrap/dom/event-handler',
1 efrain 35
], function(
36
    $,
37
    log,
38
    str,
39
    templates,
40
    notification,
41
    LoadingIcon,
42
    Aria,
1441 ariadna 43
    FormChangeChecker,
44
    Popper,
45
    EventHandler,
1 efrain 46
) {
47
    // Private functions and variables.
48
    /** @var {Object} KEYS - List of keycode constants. */
49
    var KEYS = {
50
        DOWN: 40,
51
        ENTER: 13,
52
        SPACE: 32,
53
        ESCAPE: 27,
54
        COMMA: 44,
55
        UP: 38,
56
        LEFT: 37,
57
        RIGHT: 39
58
    };
59
 
60
    var uniqueId = Date.now();
61
 
62
    /**
63
     * Make an item in the selection list "active".
64
     *
65
     * @method activateSelection
66
     * @private
67
     * @param {Number} index The index in the current (visible) list of selection.
68
     * @param {Object} state State variables for this autocomplete element.
69
     * @return {Promise}
70
     */
71
    var activateSelection = function(index, state) {
72
        // Find the elements in the DOM.
73
        var selectionElement = $(document.getElementById(state.selectionId));
74
 
75
        index = wrapListIndex(index, selectionElement.children('[aria-selected=true]').length);
76
        // Find the specified element.
77
        var element = $(selectionElement.children('[aria-selected=true]').get(index));
78
        // Create an id we can assign to this element.
79
        var itemId = state.selectionId + '-' + index;
80
 
81
        // Deselect all the selections.
82
        selectionElement.children().attr('data-active-selection', null).attr('id', '');
83
 
84
        // Select only this suggestion and assign it the id.
85
        element.attr('data-active-selection', true).attr('id', itemId);
86
 
87
        // Tell the input field it has a new active descendant so the item is announced.
88
        selectionElement.attr('aria-activedescendant', itemId);
89
        selectionElement.attr('data-active-value', element.attr('data-value'));
90
 
91
        return $.Deferred().resolve();
92
    };
93
 
94
    /**
95
     * Get the actively selected element from the state object.
96
     *
97
     * @param   {Object} state
98
     * @returns {jQuery}
99
     */
100
    var getActiveElementFromState = function(state) {
101
        var selectionRegion = $(document.getElementById(state.selectionId));
102
        var activeId = selectionRegion.attr('aria-activedescendant');
103
 
104
        if (activeId) {
105
            var activeElement = $(document.getElementById(activeId));
106
            if (activeElement.length) {
107
                // The active descendent still exists.
108
                return activeElement;
109
            }
110
        }
111
 
112
        // Ensure we are creating a properly formed selector based on the active value.
113
        var activeValue = selectionRegion.attr('data-active-value')?.replace(/"/g, '\\"');
114
        return selectionRegion.find('[data-value="' + activeValue + '"]');
115
    };
116
 
117
    /**
118
     * Update the active selection from the given state object.
119
     *
120
     * @param   {Object} state
121
     */
122
    var updateActiveSelectionFromState = function(state) {
123
        var activeElement = getActiveElementFromState(state);
124
        var activeValue = activeElement.attr('data-value');
125
 
126
        var selectionRegion = $(document.getElementById(state.selectionId));
127
        if (activeValue) {
128
            // Find the index of the currently selected index.
129
            var activeIndex = selectionRegion.find('[aria-selected=true]').index(activeElement);
130
 
131
            if (activeIndex !== -1) {
132
                activateSelection(activeIndex, state);
133
                return;
134
            }
135
        }
136
 
137
        // Either the active index was not set, or it could not be found.
138
        // Select the first value instead.
139
        activateSelection(0, state);
140
    };
141
 
142
    /**
143
     * Update the element that shows the currently selected items.
144
     *
145
     * @method updateSelectionList
146
     * @private
147
     * @param {Object} options Original options for this autocomplete element.
148
     * @param {Object} state State variables for this autocomplete element.
149
     * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
150
     * @return {Promise}
151
     */
152
    var updateSelectionList = function(options, state, originalSelect) {
153
        var pendingKey = 'form-autocomplete-updateSelectionList-' + state.inputId;
154
        M.util.js_pending(pendingKey);
155
 
156
        // Build up a valid context to re-render the template.
157
        var items = rebuildOptions(originalSelect.children('option:selected'), false);
158
        var newSelection = $(document.getElementById(state.selectionId));
159
 
160
        if (!hasItemListChanged(state, items)) {
161
            M.util.js_complete(pendingKey);
162
            return Promise.resolve();
163
        }
164
 
165
        state.items = items;
166
 
167
        var context = $.extend(options, state);
168
        // Render the template.
169
        return templates.render(options.templates.items, context)
170
        .then(function(html, js) {
171
            // Add it to the page.
172
            templates.replaceNodeContents(newSelection, html, js);
173
 
174
            updateActiveSelectionFromState(state);
175
 
176
            return;
177
        })
178
        .then(function() {
179
            return M.util.js_complete(pendingKey);
180
        })
181
        .catch(notification.exception);
182
    };
183
 
184
    /**
185
     * Check whether the list of items stored in the state has changed.
186
     *
187
     * @param   {Object} state
188
     * @param   {Array} items
189
     * @returns {Boolean}
190
     */
191
    var hasItemListChanged = function(state, items) {
192
        if (state.items.length !== items.length) {
193
            return true;
194
        }
195
 
196
        // Check for any items in the state items which are not present in the new items list.
197
        return state.items.filter(item => items.indexOf(item) === -1).length > 0;
198
    };
199
 
200
    /**
201
     * Notify of a change in the selection.
202
     *
203
     * @param {jQuery} originalSelect The jQuery object matching the hidden select list.
204
     */
205
    var notifyChange = function(originalSelect) {
206
        FormChangeChecker.markFormChangedFromNode(originalSelect[0]);
207
 
208
        // Note, jQuery .change() was not working here. Better to
209
        // use plain JavaScript anyway.
210
        originalSelect[0].dispatchEvent(new Event('change', {bubbles: true}));
211
    };
212
 
213
    /**
214
     * Remove the given item from the list of selected things.
215
     *
216
     * @method deselectItem
217
     * @private
218
     * @param {Object} options Original options for this autocomplete element.
219
     * @param {Object} state State variables for this autocomplete element.
220
     * @param {Element} item The item to be deselected.
221
     * @param {Element} originalSelect The original select list.
222
     * @return {Promise}
223
     */
1441 ariadna 224
    const deselectItem = async(options, state, item, originalSelect) => {
1 efrain 225
        var selectedItemValue = $(item).attr('data-value');
226
 
227
        // Preprend an empty option to the select list to avoid having a default selected option.
228
        if (originalSelect.find('option').first().attr('value') !== undefined) {
229
            originalSelect.prepend($('<option>'));
230
        }
231
 
232
        // Look for a match, and toggle the selected property if there is a match.
233
        originalSelect.children('option').each(function(index, ele) {
234
            if ($(ele).attr('value') == selectedItemValue) {
235
                $(ele).prop('selected', false);
236
                // We remove newly created custom tags from the suggestions list when they are deselected.
237
                if ($(ele).attr('data-iscustom')) {
238
                    $(ele).remove();
239
                }
240
            }
241
        });
1441 ariadna 242
 
243
        const selectedItemText = item[0].childNodes[2].textContent?.trim();
244
        await announceChanges(state.selectionId, selectedItemText, 'removed');
245
 
1 efrain 246
        // Rerender the selection list.
1441 ariadna 247
        await updateSelectionList(options, state, originalSelect);
1 efrain 248
 
1441 ariadna 249
        // Notify that the selection changed.
250
        notifyChange(originalSelect);
1 efrain 251
    };
252
 
253
    /**
254
     * Make an item in the suggestions "active" (about to be selected).
255
     *
256
     * @method activateItem
257
     * @private
258
     * @param {Number} index The index in the current (visible) list of suggestions.
259
     * @param {Object} state State variables for this instance of autocomplete.
260
     * @return {Promise}
261
     */
262
    var activateItem = function(index, state) {
263
        // Find the elements in the DOM.
264
        var inputElement = $(document.getElementById(state.inputId));
265
        var suggestionsElement = $(document.getElementById(state.suggestionsId));
266
 
267
        // Count the visible items.
268
        var length = suggestionsElement.children(':not([aria-hidden])').length;
269
        // Limit the index to the upper/lower bounds of the list (wrap in both directions).
270
        index = index % length;
271
        while (index < 0) {
272
            index += length;
273
        }
274
        // Find the specified element.
275
        var element = $(suggestionsElement.children(':not([aria-hidden])').get(index));
276
        // Find the index of this item in the full list of suggestions (including hidden).
277
        var globalIndex = $(suggestionsElement.children('[role=option]')).index(element);
278
        // Create an id we can assign to this element.
279
        var itemId = state.suggestionsId + '-' + globalIndex;
280
 
281
        // Deselect all the suggestions.
282
        suggestionsElement.children().attr('aria-selected', false).attr('id', '');
283
        // Select only this suggestion and assign it the id.
284
        element.attr('aria-selected', true).attr('id', itemId);
285
        // Tell the input field it has a new active descendant so the item is announced.
286
        inputElement.attr('aria-activedescendant', itemId);
287
 
288
        // Scroll it into view.
289
        var scrollPos = element.offset().top
290
                       - suggestionsElement.offset().top
291
                       + suggestionsElement.scrollTop()
292
                       - (suggestionsElement.height() / 2);
293
        return suggestionsElement.animate({
294
            scrollTop: scrollPos
295
        }, 100).promise();
296
    };
297
 
298
    /**
299
     * Return the index of the currently selected item in the suggestions list.
300
     *
301
     * @param {jQuery} suggestionsElement
302
     * @return {Integer}
303
     */
304
    var getCurrentItem = function(suggestionsElement) {
305
        // Find the active one.
306
        var element = suggestionsElement.children('[aria-selected=true]');
307
        // Find its index.
308
        return suggestionsElement.children(':not([aria-hidden])').index(element);
309
    };
310
 
311
    /**
312
     * Limit the index to the upper/lower bounds of the list (wrap in both directions).
313
     *
314
     * @param {Integer} index The target index.
315
     * @param {Integer} length The length of the list of visible items.
316
     * @return {Integer} The resulting index with necessary wrapping applied.
317
     */
318
    var wrapListIndex = function(index, length) {
319
        index = index % length;
320
        while (index < 0) {
321
            index += length;
322
        }
323
        return index;
324
    };
325
 
326
    /**
327
     * Return the index of the next item in the list without aria-disabled=true.
328
     *
329
     * @param {Integer} current The index of the current item.
330
     * @param {Array} suggestions The list of suggestions.
331
     * @return {Integer}
332
     */
333
    var getNextEnabledItem = function(current, suggestions) {
334
        var nextIndex = wrapListIndex(current + 1, suggestions.length);
335
        if (suggestions[nextIndex].getAttribute('aria-disabled')) {
336
            return getNextEnabledItem(nextIndex, suggestions);
337
        }
338
        return nextIndex;
339
    };
340
 
341
    /**
342
     * Return the index of the previous item in the list without aria-disabled=true.
343
     *
344
     * @param {Integer} current The index of the current item.
345
     * @param {Array} suggestions The list of suggestions.
346
     * @return {Integer}
347
     */
348
    var getPreviousEnabledItem = function(current, suggestions) {
349
        var previousIndex = wrapListIndex(current - 1, suggestions.length);
350
        if (suggestions[previousIndex].getAttribute('aria-disabled')) {
351
            return getPreviousEnabledItem(previousIndex, suggestions);
352
        }
353
        return previousIndex;
354
    };
355
 
356
    /**
357
     * Build a list of renderable options based on a set of option elements from the original select list.
358
     *
359
     * @param {jQuery} originalOptions
360
     * @param {Boolean} includeEmpty
361
     * @return {Array}
362
     */
363
    var rebuildOptions = function(originalOptions, includeEmpty) {
364
        var options = [];
365
        originalOptions.each(function(index, ele) {
366
            var label;
367
            if ($(ele).data('html')) {
368
                label = $(ele).data('html');
369
            } else {
370
                label = $(ele).html();
371
            }
372
            if (includeEmpty || label !== '') {
373
                options.push({
374
                    label: label,
375
                    value: $(ele).attr('value'),
376
                    disabled: ele.disabled,
377
                    classes: ele.classList,
378
                });
379
            }
380
        });
381
        return options;
382
    };
383
 
384
    /**
385
     * Find the index of the current active suggestion, and activate the next one.
386
     *
387
     * @method activateNextItem
388
     * @private
389
     * @param {Object} state State variable for this auto complete element.
390
     * @return {Promise}
391
     */
392
    var activateNextItem = function(state) {
393
        // Find the list of suggestions.
394
        var suggestionsElement = $(document.getElementById(state.suggestionsId));
395
        var suggestions = suggestionsElement.children(':not([aria-hidden])');
396
        var current = getCurrentItem(suggestionsElement);
397
        // Activate the next one.
398
        return activateItem(getNextEnabledItem(current, suggestions), state);
399
    };
400
 
401
    /**
402
     * Find the index of the current active selection, and activate the previous one.
403
     *
404
     * @method activatePreviousSelection
405
     * @private
406
     * @param {Object} state State variables for this instance of autocomplete.
407
     * @return {Promise}
408
     */
409
    var activatePreviousSelection = function(state) {
410
        // Find the list of selections.
411
        var selectionsElement = $(document.getElementById(state.selectionId));
412
        // Find the active one.
413
        var element = selectionsElement.children('[data-active-selection]');
414
        if (!element) {
415
            return activateSelection(0, state);
416
        }
417
        // Find it's index.
418
        var current = selectionsElement.children('[aria-selected=true]').index(element);
419
        // Activate the next one.
420
        return activateSelection(current - 1, state);
421
    };
422
 
423
    /**
424
     * Find the index of the current active selection, and activate the next one.
425
     *
426
     * @method activateNextSelection
427
     * @private
428
     * @param {Object} state State variables for this instance of autocomplete.
429
     * @return {Promise}
430
     */
431
    var activateNextSelection = function(state) {
432
        // Find the list of selections.
433
        var selectionsElement = $(document.getElementById(state.selectionId));
434
 
435
        // Find the active one.
436
        var element = selectionsElement.children('[data-active-selection]');
437
        var current = 0;
438
 
439
        if (element) {
440
            // The element was found. Determine the index and move to the next one.
441
            current = selectionsElement.children('[aria-selected=true]').index(element);
442
            current = current + 1;
443
        } else {
444
            // No selected item found. Move to the first.
445
            current = 0;
446
        }
447
 
448
        return activateSelection(current, state);
449
    };
450
 
451
    /**
452
     * Find the index of the current active suggestion, and activate the previous one.
453
     *
454
     * @method activatePreviousItem
455
     * @private
456
     * @param {Object} state State variables for this autocomplete element.
457
     * @return {Promise}
458
     */
459
    var activatePreviousItem = function(state) {
460
        var suggestionsElement = $(document.getElementById(state.suggestionsId));
461
        var suggestions = suggestionsElement.children(':not([aria-hidden])');
462
        var current = getCurrentItem(suggestionsElement);
463
        // Activate the previous one.
464
        return activateItem(getPreviousEnabledItem(current, suggestions), state);
465
    };
466
 
467
    /**
468
     * Close the list of suggestions.
469
     *
470
     * @method closeSuggestions
471
     * @private
472
     * @param {Object} state State variables for this autocomplete element.
473
     * @return {Promise}
474
     */
475
    var closeSuggestions = function(state) {
476
        // Find the elements in the DOM.
477
        var inputElement = $(document.getElementById(state.inputId));
478
        var suggestionsElement = $(document.getElementById(state.suggestionsId));
479
 
480
        if (inputElement.attr('aria-expanded') === "true") {
481
            // Announce the list of suggestions was closed.
482
            inputElement.attr('aria-expanded', false);
483
        }
484
        // Read the current list of selections.
485
        inputElement.attr('aria-activedescendant', state.selectionId);
486
 
487
        // Hide the suggestions list (from screen readers too).
488
        Aria.hide(suggestionsElement.get());
489
        suggestionsElement.hide();
490
 
491
        return $.Deferred().resolve();
492
    };
493
 
494
    /**
495
     * Rebuild the list of suggestions based on the current values in the select list, and the query.
1441 ariadna 496
     * Any options in the original select with [data-enabled=disabled] will not be included
497
     * as a suggestion option in the enhanced field.
1 efrain 498
     *
499
     * @method updateSuggestions
500
     * @private
501
     * @param {Object} options The original options for this autocomplete.
502
     * @param {Object} state The state variables for this autocomplete.
503
     * @param {String} query The current text for the search string.
504
     * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
505
     * @return {Promise}
506
     */
507
    var updateSuggestions = function(options, state, query, originalSelect) {
508
        var pendingKey = 'form-autocomplete-updateSuggestions-' + state.inputId;
509
        M.util.js_pending(pendingKey);
510
 
511
        // Find the elements in the DOM.
512
        var inputElement = $(document.getElementById(state.inputId));
513
        var suggestionsElement = $(document.getElementById(state.suggestionsId));
514
 
515
        // Used to track if we found any visible suggestions.
516
        var matchingElements = false;
517
        // Options is used by the context when rendering the suggestions from a template.
1441 ariadna 518
        var suggestions = rebuildOptions(originalSelect.children('option:not(:selected, [data-enabled="disabled"])'), true);
1 efrain 519
 
520
        // Re-render the list of suggestions.
521
        var searchquery = state.caseSensitive ? query : query.toLocaleLowerCase();
522
        var context = $.extend({options: suggestions}, options, state);
523
        var returnVal = templates.render(
524
            'core/form_autocomplete_suggestions',
525
            context
526
        )
527
        .then(function(html, js) {
528
            // We have the new template, insert it in the page.
529
            templates.replaceNode(suggestionsElement, html, js);
530
 
531
            // Get the element again.
532
            suggestionsElement = $(document.getElementById(state.suggestionsId));
533
 
534
            // Show it if it is hidden.
535
            Aria.unhide(suggestionsElement.get());
1441 ariadna 536
            Popper.createPopper(inputElement[0], suggestionsElement[0], {
537
                placement: 'bottom-start',
538
                modifiers: [{name: 'flip', enabled: false}],
539
            });
1 efrain 540
 
541
            // For each option in the list, hide it if it doesn't match the query.
542
            suggestionsElement.children().each(function(index, node) {
543
                node = $(node);
544
                if ((options.caseSensitive && node.text().indexOf(searchquery) > -1) ||
545
                        (!options.caseSensitive && node.text().toLocaleLowerCase().indexOf(searchquery) > -1)) {
546
                    Aria.unhide(node.get());
547
                    node.show();
548
                    matchingElements = true;
549
                } else {
550
                    node.hide();
551
                    Aria.hide(node.get());
552
                }
553
            });
554
            // If we found any matches, show the list.
555
            inputElement.attr('aria-expanded', true);
556
            if (originalSelect.attr('data-notice')) {
557
                // Display a notice rather than actual suggestions.
558
                suggestionsElement.html(originalSelect.attr('data-notice'));
559
            } else if (matchingElements) {
560
                // We only activate the first item in the list if tags is false,
561
                // because otherwise "Enter" would select the first item, instead of
562
                // creating a new tag.
563
                if (!options.tags) {
564
                    activateItem(0, state);
565
                }
566
            } else {
567
                // Nothing matches. Tell them that.
568
                str.get_string('nosuggestions', 'form').done(function(nosuggestionsstr) {
569
                    suggestionsElement.html(nosuggestionsstr);
570
                });
571
            }
572
 
573
            return suggestionsElement;
574
        })
575
        .then(function() {
576
            return M.util.js_complete(pendingKey);
577
        })
578
        .catch(notification.exception);
579
 
580
        return returnVal;
581
    };
582
 
583
    /**
584
     * Create a new item for the list (a tag).
585
     *
586
     * @method createItem
587
     * @private
588
     * @param {Object} options The original options for the autocomplete.
589
     * @param {Object} state State variables for the autocomplete.
590
     * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
591
     * @return {Promise}
592
     */
1441 ariadna 593
    const createItem = async(options, state, originalSelect) => {
1 efrain 594
        // Find the element in the DOM.
595
        var inputElement = $(document.getElementById(state.inputId));
596
        // Get the current text in the input field.
597
        var query = inputElement.val();
598
        var tags = query.split(',');
599
        var found = false;
600
 
601
        $.each(tags, function(tagindex, tag) {
602
            // If we can only select one at a time, deselect any current value.
603
            tag = tag.trim();
604
            if (tag !== '') {
605
                if (!options.multiple) {
606
                    originalSelect.children('option').prop('selected', false);
607
                }
608
                // Look for an existing option in the select list that matches this new tag.
609
                originalSelect.children('option').each(function(index, ele) {
610
                    if ($(ele).attr('value') == tag) {
611
                        found = true;
612
                        $(ele).prop('selected', true);
613
                    }
614
                });
615
                // Only create the item if it's new.
616
                if (!found) {
617
                    var option = $('<option>');
618
                    option.append(document.createTextNode(tag));
619
                    option.attr('value', tag);
620
                    originalSelect.append(option);
621
                    option.prop('selected', true);
622
                    // We mark newly created custom options as we handle them differently if they are "deselected".
623
                    option.attr('data-iscustom', true);
624
                }
625
            }
626
        });
627
 
1441 ariadna 628
        // Announce the changes to the assistive technology.
629
        await announceChanges(state.selectionId, query.trim(), 'added');
1 efrain 630
 
1441 ariadna 631
        await updateSelectionList(options, state, originalSelect);
632
        // Notify that the selection changed.
633
        notifyChange(originalSelect);
1 efrain 634
 
1441 ariadna 635
        // Clear the input field.
636
        inputElement.val('');
637
        // Close the suggestions list.
638
        await closeSuggestions(state);
1 efrain 639
    };
640
 
641
    /**
642
     * Select the currently active item from the suggestions list.
643
     *
644
     * @method selectCurrentItem
645
     * @private
646
     * @param {Object} options The original options for the autocomplete.
647
     * @param {Object} state State variables for the autocomplete.
648
     * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
1441 ariadna 649
     * @param {string|null} selectedItem The item to be selected.
1 efrain 650
     * @return {Promise}
651
     */
1441 ariadna 652
    const selectCurrentItem = async(options, state, originalSelect, selectedItem) => {
1 efrain 653
        // Find the elements in the page.
654
        var inputElement = $(document.getElementById(state.inputId));
655
        var suggestionsElement = $(document.getElementById(state.suggestionsId));
656
        // Here loop through suggestions and set val to join of all selected items.
657
 
658
        var selectedItemValue = suggestionsElement.children('[aria-selected=true]').attr('data-value');
659
        // The select will either be a single or multi select, so the following will either
660
        // select one or more items correctly.
661
        // Take care to use 'prop' and not 'attr' for selected properties.
662
        // If only one can be selected at a time, start by deselecting everything.
663
        if (!options.multiple) {
664
            originalSelect.children('option').prop('selected', false);
665
        }
666
        // Look for a match, and toggle the selected property if there is a match.
1441 ariadna 667
        originalSelect.children('option').each(function (index, ele) {
1 efrain 668
            if ($(ele).attr('value') == selectedItemValue) {
669
                $(ele).prop('selected', true);
670
            }
671
        });
672
 
1441 ariadna 673
        await announceChanges(state.selectionId, selectedItem, 'added');
1 efrain 674
 
1441 ariadna 675
        await updateSelectionList(options, state, originalSelect);
676
 
677
        // Notify that the selection changed.
678
        notifyChange(originalSelect);
679
 
680
        if (options.closeSuggestionsOnSelect) {
681
            // Clear the input element.
682
            inputElement.val('');
683
            // Close the list of suggestions.
684
            await closeSuggestions(state);
685
        } else {
686
            // Focus on the input element so the suggestions does not auto-close.
687
            inputElement.focus();
688
            // Remove the last selected item from the suggestions list.
689
            await updateSuggestions(options, state, inputElement.val(), originalSelect);
690
        }
1 efrain 691
    };
692
 
693
    /**
694
     * Fetch a new list of options via ajax.
695
     *
696
     * @method updateAjax
697
     * @private
698
     * @param {Event} e The event that triggered this update.
699
     * @param {Object} options The original options for the autocomplete.
700
     * @param {Object} state The state variables for the autocomplete.
701
     * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
702
     * @param {Object} ajaxHandler This is a module that does the ajax fetch and translates the results.
703
     * @return {Promise}
704
     */
705
    var updateAjax = function(e, options, state, originalSelect, ajaxHandler) {
706
        var pendingPromise = addPendingJSPromise('updateAjax');
707
        // We need to show the indicator outside of the hidden select list.
708
        // So we get the parent id of the hidden select list.
709
        var parentElement = $(document.getElementById(state.selectId)).parent();
710
        LoadingIcon.addIconToContainerRemoveOnCompletion(parentElement, pendingPromise);
711
 
712
        // Get the query to pass to the ajax function.
713
        var query = $(e.currentTarget).val();
714
        // Call the transport function to do the ajax (name taken from Select2).
715
        ajaxHandler.transport(options.selector, query, function(results) {
716
            // We got a result - pass it through the translator before using it.
717
            var processedResults = ajaxHandler.processResults(options.selector, results);
718
            var existingValues = [];
719
 
720
            // Now destroy all options that are not current
721
            originalSelect.children('option').each(function(optionIndex, option) {
722
                option = $(option);
723
                if (!option.prop('selected')) {
724
                    option.remove();
725
                } else {
726
                    existingValues.push(String(option.attr('value')));
727
                }
728
            });
729
 
730
            if (!options.multiple && originalSelect.children('option').length === 0) {
731
                // If this is a single select - and there are no current options
732
                // the first option added will be selected by the browser. This causes a bug!
733
                // We need to insert an empty option so that none of the real options are selected.
734
                var option = $('<option>');
735
                originalSelect.append(option);
736
            }
737
            if ($.isArray(processedResults)) {
738
                // Add all the new ones returned from ajax.
739
                $.each(processedResults, function(resultIndex, result) {
740
                    if (existingValues.indexOf(String(result.value)) === -1) {
741
                        var option = $('<option>');
742
                        option.append(result.label);
743
                        option.attr('value', result.value);
744
                        originalSelect.append(option);
745
                    }
746
                });
747
                originalSelect.attr('data-notice', '');
748
            } else {
749
                // The AJAX handler returned a string instead of the array.
750
                originalSelect.attr('data-notice', processedResults);
751
            }
752
            // Update the list of suggestions now from the new values in the select list.
753
            pendingPromise.resolve(updateSuggestions(options, state, '', originalSelect));
754
        }, function(error) {
755
            pendingPromise.reject(error);
756
        });
757
 
758
        return pendingPromise;
759
    };
760
 
761
    /**
762
     * Add all the event listeners required for keyboard nav, blur clicks etc.
763
     *
764
     * @method addNavigation
765
     * @private
766
     * @param {Object} options The options used to create this autocomplete element.
767
     * @param {Object} state State variables for this autocomplete element.
768
     * @param {JQuery} originalSelect The JQuery object matching the hidden select list.
769
     */
770
    var addNavigation = function(options, state, originalSelect) {
771
        // Start with the input element.
772
        var inputElement = $(document.getElementById(state.inputId));
773
        // Add keyboard nav with keydown.
774
        inputElement.on('keydown', function(e) {
775
            var pendingJsPromise = addPendingJSPromise('addNavigation-' + state.inputId + '-' + e.keyCode);
776
 
777
            switch (e.keyCode) {
778
                case KEYS.DOWN:
779
                    // If the suggestion list is open, move to the next item.
780
                    if (!options.showSuggestions) {
781
                        // Do not consume this event.
782
                        pendingJsPromise.resolve();
783
                        return true;
784
                    } else if (inputElement.attr('aria-expanded') === "true") {
785
                        pendingJsPromise.resolve(activateNextItem(state));
786
                    } else {
787
                        // Handle ajax population of suggestions.
788
                        if (!inputElement.val() && options.ajax) {
789
                            require([options.ajax], function(ajaxHandler) {
790
                                pendingJsPromise.resolve(updateAjax(e, options, state, originalSelect, ajaxHandler));
791
                            });
792
                        } else {
793
                            // Open the suggestions list.
794
                            pendingJsPromise.resolve(updateSuggestions(options, state, inputElement.val(), originalSelect));
795
                        }
796
                    }
797
                    // We handled this event, so prevent it.
798
                    e.preventDefault();
799
                    return false;
800
                case KEYS.UP:
801
                    // Choose the previous active item.
802
                    pendingJsPromise.resolve(activatePreviousItem(state));
803
 
804
                    // We handled this event, so prevent it.
805
                    e.preventDefault();
806
                    return false;
807
                case KEYS.ENTER:
808
                    var suggestionsElement = $(document.getElementById(state.suggestionsId));
809
                    if ((inputElement.attr('aria-expanded') === "true") &&
810
                            (suggestionsElement.children('[aria-selected=true]').length > 0)) {
1441 ariadna 811
                        const selectedItemText = suggestionsElement.children('[aria-selected=true]')[0].textContent.trim();
1 efrain 812
                        // If the suggestion list has an active item, select it.
1441 ariadna 813
                        pendingJsPromise.resolve(selectCurrentItem(options, state, originalSelect, selectedItemText));
1 efrain 814
                    } else if (options.tags) {
815
                        // If tags are enabled, create a tag.
816
                        pendingJsPromise.resolve(createItem(options, state, originalSelect));
817
                    } else {
818
                        pendingJsPromise.resolve();
819
                    }
820
 
821
                    // We handled this event, so prevent it.
822
                    e.preventDefault();
823
                    return false;
824
                case KEYS.ESCAPE:
825
                    if (inputElement.attr('aria-expanded') === "true") {
826
                        // If the suggestion list is open, close it.
827
                        pendingJsPromise.resolve(closeSuggestions(state));
828
                    } else {
829
                        pendingJsPromise.resolve();
830
                    }
831
                    // We handled this event, so prevent it.
832
                    e.preventDefault();
833
                    return false;
834
            }
835
            pendingJsPromise.resolve();
836
            return true;
837
        });
838
        // Support multi lingual COMMA keycode (44).
839
        inputElement.on('keypress', function(e) {
840
 
841
            if (e.keyCode === KEYS.COMMA) {
842
                if (options.tags) {
843
                    // If we are allowing tags, comma should create a tag (or enter).
844
                    addPendingJSPromise('keypress-' + e.keyCode)
845
                    .resolve(createItem(options, state, originalSelect));
846
                }
847
                // We handled this event, so prevent it.
848
                e.preventDefault();
849
                return false;
850
            }
851
            return true;
852
        });
853
        // Support submitting the form without leaving the autocomplete element,
854
        // or submitting too quick before the blur handler action is completed.
855
        inputElement.closest('form').on('submit', function() {
856
            if (options.tags) {
857
                // If tags are enabled, create a tag.
858
                addPendingJSPromise('form-autocomplete-submit')
859
                .resolve(createItem(options, state, originalSelect));
860
            }
861
 
862
            return true;
863
        });
864
        inputElement.on('blur', function() {
865
            var pendingPromise = addPendingJSPromise('form-autocomplete-blur');
866
            window.setTimeout(function() {
867
                // Get the current element with focus.
868
                var focusElement = $(document.activeElement);
869
                var timeoutPromise = $.Deferred();
870
 
871
                // Only close the menu if the input hasn't regained focus and if the element still exists,
872
                // and regain focus if the scrollbar is clicked.
873
                // Due to the half a second delay, it is possible that the input element no longer exist
874
                // by the time this code is being executed.
875
                if (focusElement.is(document.getElementById(state.suggestionsId))) {
876
                    inputElement.focus(); // Probably the scrollbar is clicked. Regain focus.
877
                } else if (!focusElement.is(inputElement) && $(document.getElementById(state.inputId)).length) {
878
                    if (options.tags) {
879
                        timeoutPromise.then(function() {
880
                            return createItem(options, state, originalSelect);
881
                        })
882
                        .catch();
883
                    }
884
                    timeoutPromise.then(function() {
885
                        return closeSuggestions(state);
886
                    })
887
                    .catch();
888
                }
889
 
890
                timeoutPromise.then(function() {
891
                    return pendingPromise.resolve();
892
                })
893
                .catch();
894
                timeoutPromise.resolve();
895
            }, 500);
896
        });
897
        if (options.showSuggestions) {
898
            var arrowElement = $(document.getElementById(state.downArrowId));
899
            arrowElement.on('click', function(e) {
900
                var pendingPromise = addPendingJSPromise('form-autocomplete-show-suggestions');
901
 
902
                // Prevent the close timer, or we will open, then close the suggestions.
903
                inputElement.focus();
904
 
905
                // Handle ajax population of suggestions.
906
                if (!inputElement.val() && options.ajax) {
907
                    require([options.ajax], function(ajaxHandler) {
908
                        pendingPromise.resolve(updateAjax(e, options, state, originalSelect, ajaxHandler));
909
                    });
910
                } else {
911
                    // Else - open the suggestions list.
912
                    pendingPromise.resolve(updateSuggestions(options, state, inputElement.val(), originalSelect));
913
                }
914
            });
915
        }
916
 
917
        var suggestionsElement = $(document.getElementById(state.suggestionsId));
918
        // Remove any click handler first.
919
        suggestionsElement.parent().prop("onclick", null).off("click");
920
        suggestionsElement.parent().on('click', `#${state.suggestionsId} [role=option]`, function(e) {
921
            var pendingPromise = addPendingJSPromise('form-autocomplete-parent');
922
            // Handle clicks on suggestions.
923
            var element = $(e.currentTarget).closest('[role=option]');
924
            var suggestionsElement = $(document.getElementById(state.suggestionsId));
925
            // Find the index of the clicked on suggestion.
926
            var current = suggestionsElement.children(':not([aria-hidden])').index(element);
927
 
928
            // Activate it.
929
            activateItem(current, state)
930
            .then(function() {
931
                // And select it.
1441 ariadna 932
                const selectedItemText = element[0].textContent.trim();
933
                return selectCurrentItem(options, state, originalSelect, selectedItemText);
1 efrain 934
            })
935
            .then(function() {
936
                return pendingPromise.resolve();
937
            })
1441 ariadna 938
            .catch(notification.exception);
1 efrain 939
        });
940
        var selectionElement = $(document.getElementById(state.selectionId));
941
 
942
        // Handle clicks on the selected items (will unselect an item).
943
        selectionElement.on('click', '[role=option]', function(e) {
944
            var pendingPromise = addPendingJSPromise('form-autocomplete-clicks');
945
 
946
            // Remove it from the selection.
947
            pendingPromise.resolve(deselectItem(options, state, $(e.currentTarget), originalSelect));
948
        });
949
 
950
        // When listbox is focused, focus on the first option if there is no focused option.
951
        selectionElement.on('focus', function() {
952
            updateActiveSelectionFromState(state);
953
        });
954
 
955
        // Keyboard navigation for the selection list.
956
        selectionElement.on('keydown', function(e) {
957
            var pendingPromise = addPendingJSPromise('form-autocomplete-keydown-' + e.keyCode);
958
            switch (e.keyCode) {
959
                case KEYS.RIGHT:
960
                case KEYS.DOWN:
961
                    // We handled this event, so prevent it.
962
                    e.preventDefault();
963
 
964
                    // Choose the next selection item.
965
                    pendingPromise.resolve(activateNextSelection(state));
966
                    return;
967
                case KEYS.LEFT:
968
                case KEYS.UP:
969
                    // We handled this event, so prevent it.
970
                    e.preventDefault();
971
 
972
                    // Choose the previous selection item.
973
                    pendingPromise.resolve(activatePreviousSelection(state));
974
                    return;
975
                case KEYS.SPACE:
976
                case KEYS.ENTER:
977
                    // Get the item that is currently selected.
978
                    var selectedItem = $(document.getElementById(state.selectionId)).children('[data-active-selection]');
979
                    if (selectedItem) {
980
                        e.preventDefault();
981
 
982
                        // Unselect this item.
983
                        pendingPromise.resolve(deselectItem(options, state, selectedItem, originalSelect));
984
                    }
985
                    return;
986
            }
987
 
988
            // Not handled. Resolve the promise.
989
            pendingPromise.resolve();
990
        });
991
        // Whenever the input field changes, update the suggestion list.
992
        if (options.showSuggestions) {
993
            // Store the value of the field as its last value, when the field gains focus.
994
            inputElement.on('focus', function(e) {
995
                var query = $(e.currentTarget).val();
996
                $(e.currentTarget).data('last-value', query);
997
            });
998
 
999
            // If this field uses ajax, set it up.
1000
            if (options.ajax) {
1001
                require([options.ajax], function(ajaxHandler) {
1002
                    // Creating throttled handlers free of race conditions, and accurate.
1003
                    // This code keeps track of a throttleTimeout, which is periodically polled.
1004
                    // Once the throttled function is executed, the fact that it is running is noted.
1005
                    // If a subsequent request comes in whilst it is running, this request is re-applied.
1006
                    var throttleTimeout = null;
1007
                    var inProgress = false;
1008
                    var pendingKey = 'autocomplete-throttledhandler';
1009
                    var handler = function(e) {
1010
                        // Empty the current timeout.
1011
                        throttleTimeout = null;
1012
 
1013
                        // Mark this request as in-progress.
1014
                        inProgress = true;
1015
 
1016
                        // Process the request.
1017
                        updateAjax(e, options, state, originalSelect, ajaxHandler)
1018
                        .then(function() {
1019
                            // Check if the throttleTimeout is still empty.
1020
                            // There's a potential condition whereby the JS request takes long enough to complete that
1021
                            // another task has been queued.
1022
                            // In this case another task will be kicked off and we must wait for that before marking htis as
1023
                            // complete.
1024
                            if (null === throttleTimeout) {
1025
                                // Mark this task as complete.
1026
                                M.util.js_complete(pendingKey);
1027
                            }
1028
                            inProgress = false;
1029
 
1030
                            return arguments[0];
1031
                        })
1032
                        .catch(notification.exception);
1033
                    };
1034
 
1035
                    // For input events, we do not want to trigger many, many updates.
1036
                    var throttledHandler = function(e) {
1037
                        window.clearTimeout(throttleTimeout);
1038
                        if (inProgress) {
1039
                            // A request is currently ongoing.
1040
                            // Delay this request another 100ms.
1041
                            throttleTimeout = window.setTimeout(throttledHandler.bind(this, e), 100);
1042
                            return;
1043
                        }
1044
 
1045
                        if (throttleTimeout === null) {
1046
                            // There is currently no existing timeout handler, and it has not been recently cleared, so
1047
                            // this is the start of a throttling check.
1048
                            M.util.js_pending(pendingKey);
1049
                        }
1050
 
1051
                        // There is currently no existing timeout handler, and it has not been recently cleared, so this
1052
                        // is the start of a throttling check.
1053
                        // Queue a call to the handler.
1054
                        throttleTimeout = window.setTimeout(handler.bind(this, e), 300);
1055
                    };
1056
 
1057
                    // Trigger an ajax update after the text field value changes.
1058
                    inputElement.on('input', function(e) {
1059
                        var query = $(e.currentTarget).val();
1060
                        var last = $(e.currentTarget).data('last-value');
1061
                        // IE11 fires many more input events than required - even when the value has not changed.
1062
                        if (last !== query) {
1063
                            throttledHandler(e);
1064
                        }
1065
                        $(e.currentTarget).data('last-value', query);
1066
                    });
1067
                });
1068
            } else {
1069
                inputElement.on('input', function(e) {
1070
                    var query = $(e.currentTarget).val();
1071
                    var last = $(e.currentTarget).data('last-value');
1072
                    // IE11 fires many more input events than required - even when the value has not changed.
1073
                    // We need to only do this for real value changed events or the suggestions will be
1074
                    // unclickable on IE11 (because they will be rebuilt before the click event fires).
1075
                    // Note - because of this we cannot close the list when the query is empty or it will break
1076
                    // on IE11.
1077
                    if (last !== query) {
1078
                        updateSuggestions(options, state, query, originalSelect);
1079
                    }
1080
                    $(e.currentTarget).data('last-value', query);
1081
                });
1082
            }
1083
        }
1441 ariadna 1084
 
1085
        // Add a Bootstrap keydown handler to close the suggestions list preventing the whole Dropdown close.
1086
        EventHandler.on(document, 'keydown.bs.dropdown.data-api', '.dropdown-menu', (event) => {
1087
            const pendingPromise = addPendingJSPromise('addNavigation-' + state.inputId + '-' + event.key);
1088
            if (event.key === "Escape" && inputElement.attr('aria-expanded') === "true") {
1089
                event.stopImmediatePropagation();
1090
                return pendingPromise.resolve(closeSuggestions(state));
1091
            }
1092
            return pendingPromise.resolve();
1093
        });
1 efrain 1094
    };
1095
 
1096
    /**
1097
     * Create and return an unresolved Promise for some pending JS.
1098
     *
1099
     * @param   {String} key The unique identifier for this promise
1100
     * @return  {Promise}
1101
     */
1102
    var addPendingJSPromise = function(key) {
1103
            var pendingKey = 'form-autocomplete:' + key;
1104
 
1105
            M.util.js_pending(pendingKey);
1106
 
1107
            var pendingPromise = $.Deferred();
1108
 
1109
            pendingPromise
1110
            .then(function() {
1111
                M.util.js_complete(pendingKey);
1112
 
1113
                return arguments[0];
1114
            })
1115
            .catch(notification.exception);
1116
 
1117
            return pendingPromise;
1118
    };
1119
 
1120
    /**
1121
     * Turn a boring select box into an auto-complete beast.
1122
     *
1123
     * @method enhanceField
1124
     * @param {string} selector The selector that identifies the select box.
1125
     * @param {boolean} tags Whether to allow support for tags (can define new entries).
1126
     * @param {string} ajax Name of an AMD module to handle ajax requests. If specified, the AMD
1127
     *                      module must expose 2 functions "transport" and "processResults".
1128
     *                      These are modeled on Select2 see: https://select2.github.io/options.html#ajax
1129
     * @param {String|Promise<string>} placeholder - The text to display before a selection is made.
1130
     * @param {Boolean} caseSensitive - If search has to be made case sensitive.
1131
     * @param {Boolean} showSuggestions - If suggestions should be shown
1132
     * @param {String|Promise<string>} noSelectionString - Text to display when there is no selection
1133
     * @param {Boolean} closeSuggestionsOnSelect - Whether to close the suggestions immediately after making a selection.
1134
     * @param {Object} templateOverrides A set of templates to use instead of the standard templates
1135
     * @return {Promise}
1136
     */
1137
     var enhanceField = async function(selector, tags, ajax, placeholder, caseSensitive, showSuggestions, noSelectionString,
1138
                          closeSuggestionsOnSelect, templateOverrides) {
1139
            // Set some default values.
1140
            var options = {
1141
                selector: selector,
1142
                tags: false,
1143
                ajax: false,
1144
                placeholder: await placeholder,
1145
                caseSensitive: false,
1146
                showSuggestions: true,
1147
                noSelectionString: await noSelectionString,
1148
                templates: $.extend({
1149
                        input: 'core/form_autocomplete_input',
1150
                        items: 'core/form_autocomplete_selection_items',
1151
                        layout: 'core/form_autocomplete_layout',
1152
                        selection: 'core/form_autocomplete_selection',
1153
                        suggestions: 'core/form_autocomplete_suggestions',
1154
                    }, templateOverrides),
1155
            };
1156
            var pendingKey = 'autocomplete-setup-' + selector;
1157
            M.util.js_pending(pendingKey);
1158
            if (typeof tags !== "undefined") {
1159
                options.tags = tags;
1160
            }
1161
            if (typeof ajax !== "undefined") {
1162
                options.ajax = ajax;
1163
            }
1164
            if (typeof caseSensitive !== "undefined") {
1165
                options.caseSensitive = caseSensitive;
1166
            }
1167
            if (typeof showSuggestions !== "undefined") {
1168
                options.showSuggestions = showSuggestions;
1169
            }
1170
            if (typeof noSelectionString === "undefined") {
1171
                str.get_string('noselection', 'form').done(function(result) {
1172
                    options.noSelectionString = result;
1173
                }).fail(notification.exception);
1174
            }
1175
 
1176
            // Look for the select element.
1177
            var originalSelect = $(selector);
1178
            if (!originalSelect) {
1179
                log.debug('Selector not found: ' + selector);
1180
                M.util.js_complete(pendingKey);
1181
                return false;
1182
            }
1183
 
1184
            // Ensure we enhance the element only once.
1185
            if (originalSelect.data('enhanced') === 'enhanced') {
1186
                M.util.js_complete(pendingKey);
1187
                return false;
1188
            }
1189
            originalSelect.data('enhanced', 'enhanced');
1190
 
1191
            // Hide the original select.
1192
            Aria.hide(originalSelect.get());
1193
            originalSelect.css('visibility', 'hidden');
1194
 
1195
            // Find or generate some ids.
1196
            var state = {
1197
                selectId: originalSelect.attr('id'),
1198
                inputId: 'form_autocomplete_input-' + uniqueId,
1199
                suggestionsId: 'form_autocomplete_suggestions-' + uniqueId,
1200
                selectionId: 'form_autocomplete_selection-' + uniqueId,
1201
                downArrowId: 'form_autocomplete_downarrow-' + uniqueId,
1202
                items: [],
1203
                required: originalSelect[0]?.ariaRequired === 'true',
1204
            };
1205
 
1206
            // Increment the unique counter so we don't get duplicates ever.
1207
            uniqueId++;
1208
 
1209
            options.multiple = originalSelect.attr('multiple');
1210
            if (!options.multiple) {
1211
                // If this is a single select then there is no way to de-select the current value -
1212
                // unless we add a bogus blank option to be selected when nothing else is.
1213
                // This matches similar code in updateAjax above.
1214
                originalSelect.prepend('<option>');
1215
            }
1216
 
1217
            if (typeof closeSuggestionsOnSelect !== "undefined") {
1218
                options.closeSuggestionsOnSelect = closeSuggestionsOnSelect;
1219
            } else {
1220
                // If not specified, this will close suggestions by default for single-select elements only.
1221
                options.closeSuggestionsOnSelect = !options.multiple;
1222
            }
1223
 
1224
            var originalLabel = $('[for=' + state.selectId + ']');
1225
            // Create the new markup and insert it after the select.
1226
            var suggestions = rebuildOptions(originalSelect.children('option'), true);
1227
 
1228
            // Render all the parts of our UI.
1229
            var context = $.extend({}, options, state);
1230
            context.options = suggestions;
1231
            context.items = [];
1232
 
1233
            // Collect rendered inline JS to be executed once the HTML is shown.
1234
            var collectedjs = '';
1235
 
1236
            var renderLayout = templates.render(options.templates.layout, {})
1237
            .then(function(html) {
1238
                return $(html);
1239
            });
1240
 
1241
            var renderInput = templates.render(options.templates.input, context).then(function(html, js) {
1242
                collectedjs += js;
1243
                return $(html);
1244
            });
1245
 
1246
            var renderDatalist = templates.render(options.templates.suggestions, context).then(function(html, js) {
1247
                collectedjs += js;
1248
                return $(html);
1249
            });
1250
 
1251
            var renderSelection = templates.render(options.templates.selection, context).then(function(html, js) {
1252
                collectedjs += js;
1253
                return $(html);
1254
            });
1255
 
1256
            return Promise.all([renderLayout, renderInput, renderDatalist, renderSelection])
1257
            .then(function([layout, input, suggestions, selection]) {
1258
                originalSelect.hide();
1259
                var container = originalSelect.parent();
1260
 
1261
                // Ensure that the data-fieldtype is set for behat.
1262
                input.find('input').attr('data-fieldtype', 'autocomplete');
1263
 
1264
                container.append(layout);
1265
                container.find('[data-region="form_autocomplete-input"]').replaceWith(input);
1266
                container.find('[data-region="form_autocomplete-suggestions"]').replaceWith(suggestions);
1267
                container.find('[data-region="form_autocomplete-selection"]').replaceWith(selection);
1268
 
1269
                templates.runTemplateJS(collectedjs);
1270
 
1271
                // Update the form label to point to the text input.
1272
                originalLabel.attr('for', state.inputId);
1273
                // Add the event handlers.
1274
                addNavigation(options, state, originalSelect);
1275
 
1276
                var suggestionsElement = $(document.getElementById(state.suggestionsId));
1277
                // Hide the suggestions by default.
1278
                suggestionsElement.hide();
1279
                Aria.hide(suggestionsElement.get());
1280
 
1281
                return;
1282
            })
1283
            .then(function() {
1284
                // Show the current values in the selection list.
1285
                return updateSelectionList(options, state, originalSelect);
1286
            })
1287
            .then(function() {
1288
                return M.util.js_complete(pendingKey);
1289
            })
1290
            .catch(function(error) {
1291
                M.util.js_complete(pendingKey);
1292
                notification.exception(error);
1293
            });
1294
    };
1295
 
1441 ariadna 1296
    /**
1297
     * Announces changes to a tag in the autocomplete form.
1298
     *
1299
     * Updates the text content of a status element to inform users about the addition or removal
1300
     * of a tag. This is useful for accessibility purposes, ensuring screen readers can notify users
1301
     * of changes in the autocomplete component.
1302
     *
1303
     * @param {string} selectionId - The ID of the selection element used to locate the announcer element.
1304
     * @param {string|null|undefined} tagname - The name of the tag that was added or removed.
1305
     * @param {string} action - The action performed on the tag (e.g., "added" or "removed").
1306
     */
1307
    const announceChanges = async(selectionId, tagname, action) => {
1308
        if (!tagname) {
1309
            return;
1310
        }
1311
 
1312
        const status = document.getElementById(`${selectionId}-announcer`);
1313
        if (!status) {
1314
            return;
1315
        }
1316
 
1317
        status.textContent = await str.get_string(action, 'core', tagname);
1318
 
1319
        // Remove the status message after 4 seconds to prevent screen readers from announcing it.
1320
        setTimeout(() => {
1321
            status.textContent = '';
1322
        }, 4000);
1323
 
1324
    };
1325
 
1 efrain 1326
    return {
1327
        // Public variables and functions.
1328
        enhanceField: enhanceField,
1329
 
1330
        /**
1331
         * We need to use jQuery here as some calling code uses .done() and .fail() rather than native .then() and .catch()
1332
         *
1333
         * @method enhance
1334
         * @return {Promise} A jQuery promise
1335
         */
1336
        enhance: function() {
1337
            return $.when(enhanceField(...arguments));
1338
        }
1339
    };
1340
});