Added the Search API Synonym module to deal specifically with licence and license...
[yaffs-website] / web / core / misc / ajax.es6.js
1 /**
2  * @file
3  * Provides Ajax page updating via jQuery $.ajax.
4  *
5  * Ajax is a method of making a request via JavaScript while viewing an HTML
6  * page. The request returns an array of commands encoded in JSON, which is
7  * then executed to make any changes that are necessary to the page.
8  *
9  * Drupal uses this file to enhance form elements with `#ajax['url']` and
10  * `#ajax['wrapper']` properties. If set, this file will automatically be
11  * included to provide Ajax capabilities.
12  */
13
14 (function($, window, Drupal, drupalSettings) {
15   /**
16    * Attaches the Ajax behavior to each Ajax form element.
17    *
18    * @type {Drupal~behavior}
19    *
20    * @prop {Drupal~behaviorAttach} attach
21    *   Initialize all {@link Drupal.Ajax} objects declared in
22    *   `drupalSettings.ajax` or initialize {@link Drupal.Ajax} objects from
23    *   DOM elements having the `use-ajax-submit` or `use-ajax` css class.
24    * @prop {Drupal~behaviorDetach} detach
25    *   During `unload` remove all {@link Drupal.Ajax} objects related to
26    *   the removed content.
27    */
28   Drupal.behaviors.AJAX = {
29     attach(context, settings) {
30       function loadAjaxBehavior(base) {
31         const elementSettings = settings.ajax[base];
32         if (typeof elementSettings.selector === 'undefined') {
33           elementSettings.selector = `#${base}`;
34         }
35         $(elementSettings.selector)
36           .once('drupal-ajax')
37           .each(function() {
38             elementSettings.element = this;
39             elementSettings.base = base;
40             Drupal.ajax(elementSettings);
41           });
42       }
43
44       // Load all Ajax behaviors specified in the settings.
45       Object.keys(settings.ajax || {}).forEach(base => loadAjaxBehavior(base));
46
47       Drupal.ajax.bindAjaxLinks(document.body);
48
49       // This class means to submit the form to the action using Ajax.
50       $('.use-ajax-submit')
51         .once('ajax')
52         .each(function() {
53           const elementSettings = {};
54
55           // Ajax submits specified in this manner automatically submit to the
56           // normal form action.
57           elementSettings.url = $(this.form).attr('action');
58           // Form submit button clicks need to tell the form what was clicked so
59           // it gets passed in the POST request.
60           elementSettings.setClick = true;
61           // Form buttons use the 'click' event rather than mousedown.
62           elementSettings.event = 'click';
63           // Clicked form buttons look better with the throbber than the progress
64           // bar.
65           elementSettings.progress = { type: 'throbber' };
66           elementSettings.base = $(this).attr('id');
67           elementSettings.element = this;
68
69           Drupal.ajax(elementSettings);
70         });
71     },
72
73     detach(context, settings, trigger) {
74       if (trigger === 'unload') {
75         Drupal.ajax.expired().forEach(instance => {
76           // Set this to null and allow garbage collection to reclaim
77           // the memory.
78           Drupal.ajax.instances[instance.instanceIndex] = null;
79         });
80       }
81     },
82   };
83
84   /**
85    * Extends Error to provide handling for Errors in Ajax.
86    *
87    * @constructor
88    *
89    * @augments Error
90    *
91    * @param {XMLHttpRequest} xmlhttp
92    *   XMLHttpRequest object used for the failed request.
93    * @param {string} uri
94    *   The URI where the error occurred.
95    * @param {string} customMessage
96    *   The custom message.
97    */
98   Drupal.AjaxError = function(xmlhttp, uri, customMessage) {
99     let statusCode;
100     let statusText;
101     let responseText;
102     if (xmlhttp.status) {
103       statusCode = `\n${Drupal.t('An AJAX HTTP error occurred.')}\n${Drupal.t(
104         'HTTP Result Code: !status',
105         { '!status': xmlhttp.status },
106       )}`;
107     } else {
108       statusCode = `\n${Drupal.t(
109         'An AJAX HTTP request terminated abnormally.',
110       )}`;
111     }
112     statusCode += `\n${Drupal.t('Debugging information follows.')}`;
113     const pathText = `\n${Drupal.t('Path: !uri', { '!uri': uri })}`;
114     statusText = '';
115     // In some cases, when statusCode === 0, xmlhttp.statusText may not be
116     // defined. Unfortunately, testing for it with typeof, etc, doesn't seem to
117     // catch that and the test causes an exception. So we need to catch the
118     // exception here.
119     try {
120       statusText = `\n${Drupal.t('StatusText: !statusText', {
121         '!statusText': $.trim(xmlhttp.statusText),
122       })}`;
123     } catch (e) {
124       // Empty.
125     }
126
127     responseText = '';
128     // Again, we don't have a way to know for sure whether accessing
129     // xmlhttp.responseText is going to throw an exception. So we'll catch it.
130     try {
131       responseText = `\n${Drupal.t('ResponseText: !responseText', {
132         '!responseText': $.trim(xmlhttp.responseText),
133       })}`;
134     } catch (e) {
135       // Empty.
136     }
137
138     // Make the responseText more readable by stripping HTML tags and newlines.
139     responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
140     responseText = responseText.replace(/[\n]+\s+/g, '\n');
141
142     // We don't need readyState except for status == 0.
143     const readyStateText =
144       xmlhttp.status === 0
145         ? `\n${Drupal.t('ReadyState: !readyState', {
146             '!readyState': xmlhttp.readyState,
147           })}`
148         : '';
149
150     customMessage = customMessage
151       ? `\n${Drupal.t('CustomMessage: !customMessage', {
152           '!customMessage': customMessage,
153         })}`
154       : '';
155
156     /**
157      * Formatted and translated error message.
158      *
159      * @type {string}
160      */
161     this.message =
162       statusCode +
163       pathText +
164       statusText +
165       customMessage +
166       responseText +
167       readyStateText;
168
169     /**
170      * Used by some browsers to display a more accurate stack trace.
171      *
172      * @type {string}
173      */
174     this.name = 'AjaxError';
175   };
176
177   Drupal.AjaxError.prototype = new Error();
178   Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
179
180   /**
181    * Provides Ajax page updating via jQuery $.ajax.
182    *
183    * This function is designed to improve developer experience by wrapping the
184    * initialization of {@link Drupal.Ajax} objects and storing all created
185    * objects in the {@link Drupal.ajax.instances} array.
186    *
187    * @example
188    * Drupal.behaviors.myCustomAJAXStuff = {
189    *   attach: function (context, settings) {
190    *
191    *     var ajaxSettings = {
192    *       url: 'my/url/path',
193    *       // If the old version of Drupal.ajax() needs to be used those
194    *       // properties can be added
195    *       base: 'myBase',
196    *       element: $(context).find('.someElement')
197    *     };
198    *
199    *     var myAjaxObject = Drupal.ajax(ajaxSettings);
200    *
201    *     // Declare a new Ajax command specifically for this Ajax object.
202    *     myAjaxObject.commands.insert = function (ajax, response, status) {
203    *       $('#my-wrapper').append(response.data);
204    *       alert('New content was appended to #my-wrapper');
205    *     };
206    *
207    *     // This command will remove this Ajax object from the page.
208    *     myAjaxObject.commands.destroyObject = function (ajax, response, status) {
209    *       Drupal.ajax.instances[this.instanceIndex] = null;
210    *     };
211    *
212    *     // Programmatically trigger the Ajax request.
213    *     myAjaxObject.execute();
214    *   }
215    * };
216    *
217    * @param {object} settings
218    *   The settings object passed to {@link Drupal.Ajax} constructor.
219    * @param {string} [settings.base]
220    *   Base is passed to {@link Drupal.Ajax} constructor as the 'base'
221    *   parameter.
222    * @param {HTMLElement} [settings.element]
223    *   Element parameter of {@link Drupal.Ajax} constructor, element on which
224    *   event listeners will be bound.
225    *
226    * @return {Drupal.Ajax}
227    *   The created Ajax object.
228    *
229    * @see Drupal.AjaxCommands
230    */
231   Drupal.ajax = function(settings) {
232     if (arguments.length !== 1) {
233       throw new Error(
234         'Drupal.ajax() function must be called with one configuration object only',
235       );
236     }
237     // Map those config keys to variables for the old Drupal.ajax function.
238     const base = settings.base || false;
239     const element = settings.element || false;
240     delete settings.base;
241     delete settings.element;
242
243     // By default do not display progress for ajax calls without an element.
244     if (!settings.progress && !element) {
245       settings.progress = false;
246     }
247
248     const ajax = new Drupal.Ajax(base, element, settings);
249     ajax.instanceIndex = Drupal.ajax.instances.length;
250     Drupal.ajax.instances.push(ajax);
251
252     return ajax;
253   };
254
255   /**
256    * Contains all created Ajax objects.
257    *
258    * @type {Array.<Drupal.Ajax|null>}
259    */
260   Drupal.ajax.instances = [];
261
262   /**
263    * List all objects where the associated element is not in the DOM
264    *
265    * This method ignores {@link Drupal.Ajax} objects not bound to DOM elements
266    * when created with {@link Drupal.ajax}.
267    *
268    * @return {Array.<Drupal.Ajax>}
269    *   The list of expired {@link Drupal.Ajax} objects.
270    */
271   Drupal.ajax.expired = function() {
272     return Drupal.ajax.instances.filter(
273       instance =>
274         instance &&
275         instance.element !== false &&
276         !document.body.contains(instance.element),
277     );
278   };
279
280   /**
281    * Bind Ajax functionality to links that use the 'use-ajax' class.
282    *
283    * @param {HTMLElement} element
284    *   Element to enable Ajax functionality for.
285    */
286   Drupal.ajax.bindAjaxLinks = element => {
287     // Bind Ajax behaviors to all items showing the class.
288     $(element)
289       .find('.use-ajax')
290       .once('ajax')
291       .each((i, ajaxLink) => {
292         const $linkElement = $(ajaxLink);
293
294         const elementSettings = {
295           // Clicked links look better with the throbber than the progress bar.
296           progress: { type: 'throbber' },
297           dialogType: $linkElement.data('dialog-type'),
298           dialog: $linkElement.data('dialog-options'),
299           dialogRenderer: $linkElement.data('dialog-renderer'),
300           base: $linkElement.attr('id'),
301           element: ajaxLink,
302         };
303         const href = $linkElement.attr('href');
304         /**
305          * For anchor tags, these will go to the target of the anchor rather
306          * than the usual location.
307          */
308         if (href) {
309           elementSettings.url = href;
310           elementSettings.event = 'click';
311         }
312         Drupal.ajax(elementSettings);
313       });
314   };
315
316   /**
317    * Settings for an Ajax object.
318    *
319    * @typedef {object} Drupal.Ajax~elementSettings
320    *
321    * @prop {string} url
322    *   Target of the Ajax request.
323    * @prop {?string} [event]
324    *   Event bound to settings.element which will trigger the Ajax request.
325    * @prop {bool} [keypress=true]
326    *   Triggers a request on keypress events.
327    * @prop {?string} selector
328    *   jQuery selector targeting the element to bind events to or used with
329    *   {@link Drupal.AjaxCommands}.
330    * @prop {string} [effect='none']
331    *   Name of the jQuery method to use for displaying new Ajax content.
332    * @prop {string|number} [speed='none']
333    *   Speed with which to apply the effect.
334    * @prop {string} [method]
335    *   Name of the jQuery method used to insert new content in the targeted
336    *   element.
337    * @prop {object} [progress]
338    *   Settings for the display of a user-friendly loader.
339    * @prop {string} [progress.type='throbber']
340    *   Type of progress element, core provides `'bar'`, `'throbber'` and
341    *   `'fullscreen'`.
342    * @prop {string} [progress.message=Drupal.t('Please wait...')]
343    *   Custom message to be used with the bar indicator.
344    * @prop {object} [submit]
345    *   Extra data to be sent with the Ajax request.
346    * @prop {bool} [submit.js=true]
347    *   Allows the PHP side to know this comes from an Ajax request.
348    * @prop {object} [dialog]
349    *   Options for {@link Drupal.dialog}.
350    * @prop {string} [dialogType]
351    *   One of `'modal'` or `'dialog'`.
352    * @prop {string} [prevent]
353    *   List of events on which to stop default action and stop propagation.
354    */
355
356   /**
357    * Ajax constructor.
358    *
359    * The Ajax request returns an array of commands encoded in JSON, which is
360    * then executed to make any changes that are necessary to the page.
361    *
362    * Drupal uses this file to enhance form elements with `#ajax['url']` and
363    * `#ajax['wrapper']` properties. If set, this file will automatically be
364    * included to provide Ajax capabilities.
365    *
366    * @constructor
367    *
368    * @param {string} [base]
369    *   Base parameter of {@link Drupal.Ajax} constructor
370    * @param {HTMLElement} [element]
371    *   Element parameter of {@link Drupal.Ajax} constructor, element on which
372    *   event listeners will be bound.
373    * @param {Drupal.Ajax~elementSettings} elementSettings
374    *   Settings for this Ajax object.
375    */
376   Drupal.Ajax = function(base, element, elementSettings) {
377     const defaults = {
378       event: element ? 'mousedown' : null,
379       keypress: true,
380       selector: base ? `#${base}` : null,
381       effect: 'none',
382       speed: 'none',
383       method: 'replaceWith',
384       progress: {
385         type: 'throbber',
386         message: Drupal.t('Please wait...'),
387       },
388       submit: {
389         js: true,
390       },
391     };
392
393     $.extend(this, defaults, elementSettings);
394
395     /**
396      * @type {Drupal.AjaxCommands}
397      */
398     this.commands = new Drupal.AjaxCommands();
399
400     /**
401      * @type {bool|number}
402      */
403     this.instanceIndex = false;
404
405     // @todo Remove this after refactoring the PHP code to:
406     //   - Call this 'selector'.
407     //   - Include the '#' for ID-based selectors.
408     //   - Support non-ID-based selectors.
409     if (this.wrapper) {
410       /**
411        * @type {string}
412        */
413       this.wrapper = `#${this.wrapper}`;
414     }
415
416     /**
417      * @type {HTMLElement}
418      */
419     this.element = element;
420
421     /**
422      * @deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0.
423      * Use elementSettings.
424      *
425      * @type {Drupal.Ajax~elementSettings}
426      */
427     this.element_settings = elementSettings;
428
429     /**
430      * @type {Drupal.Ajax~elementSettings}
431      */
432     this.elementSettings = elementSettings;
433
434     // If there isn't a form, jQuery.ajax() will be used instead, allowing us to
435     // bind Ajax to links as well.
436     if (this.element && this.element.form) {
437       /**
438        * @type {jQuery}
439        */
440       this.$form = $(this.element.form);
441     }
442
443     // If no Ajax callback URL was given, use the link href or form action.
444     if (!this.url) {
445       const $element = $(this.element);
446       if ($element.is('a')) {
447         this.url = $element.attr('href');
448       } else if (this.element && element.form) {
449         this.url = this.$form.attr('action');
450       }
451     }
452
453     // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
454     // the server detect when it needs to degrade gracefully.
455     // There are four scenarios to check for:
456     // 1. /nojs/
457     // 2. /nojs$ - The end of a URL string.
458     // 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar).
459     // 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment).
460     const originalUrl = this.url;
461
462     /**
463      * Processed Ajax URL.
464      *
465      * @type {string}
466      */
467     this.url = this.url.replace(/\/nojs(\/|$|\?|#)/, '/ajax$1');
468     // If the 'nojs' version of the URL is trusted, also trust the 'ajax'
469     // version.
470     if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
471       drupalSettings.ajaxTrustedUrl[this.url] = true;
472     }
473
474     // Set the options for the ajaxSubmit function.
475     // The 'this' variable will not persist inside of the options object.
476     const ajax = this;
477
478     /**
479      * Options for the jQuery.ajax function.
480      *
481      * @name Drupal.Ajax#options
482      *
483      * @type {object}
484      *
485      * @prop {string} url
486      *   Ajax URL to be called.
487      * @prop {object} data
488      *   Ajax payload.
489      * @prop {function} beforeSerialize
490      *   Implement jQuery beforeSerialize function to call
491      *   {@link Drupal.Ajax#beforeSerialize}.
492      * @prop {function} beforeSubmit
493      *   Implement jQuery beforeSubmit function to call
494      *   {@link Drupal.Ajax#beforeSubmit}.
495      * @prop {function} beforeSend
496      *   Implement jQuery beforeSend function to call
497      *   {@link Drupal.Ajax#beforeSend}.
498      * @prop {function} success
499      *   Implement jQuery success function to call
500      *   {@link Drupal.Ajax#success}.
501      * @prop {function} complete
502      *   Implement jQuery success function to clean up ajax state and trigger an
503      *   error if needed.
504      * @prop {string} dataType='json'
505      *   Type of the response expected.
506      * @prop {string} type='POST'
507      *   HTTP method to use for the Ajax request.
508      */
509     ajax.options = {
510       url: ajax.url,
511       data: ajax.submit,
512       beforeSerialize(elementSettings, options) {
513         return ajax.beforeSerialize(elementSettings, options);
514       },
515       beforeSubmit(formValues, elementSettings, options) {
516         ajax.ajaxing = true;
517         return ajax.beforeSubmit(formValues, elementSettings, options);
518       },
519       beforeSend(xmlhttprequest, options) {
520         ajax.ajaxing = true;
521         return ajax.beforeSend(xmlhttprequest, options);
522       },
523       success(response, status, xmlhttprequest) {
524         // Sanity check for browser support (object expected).
525         // When using iFrame uploads, responses must be returned as a string.
526         if (typeof response === 'string') {
527           response = $.parseJSON(response);
528         }
529
530         // Prior to invoking the response's commands, verify that they can be
531         // trusted by checking for a response header. See
532         // \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details.
533         // - Empty responses are harmless so can bypass verification. This
534         //   avoids an alert message for server-generated no-op responses that
535         //   skip Ajax rendering.
536         // - Ajax objects with trusted URLs (e.g., ones defined server-side via
537         //   #ajax) can bypass header verification. This is especially useful
538         //   for Ajax with multipart forms. Because IFRAME transport is used,
539         //   the response headers cannot be accessed for verification.
540         if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
541           if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
542             const customMessage = Drupal.t(
543               'The response failed verification so will not be processed.',
544             );
545             return ajax.error(xmlhttprequest, ajax.url, customMessage);
546           }
547         }
548
549         return ajax.success(response, status);
550       },
551       complete(xmlhttprequest, status) {
552         ajax.ajaxing = false;
553         if (status === 'error' || status === 'parsererror') {
554           return ajax.error(xmlhttprequest, ajax.url);
555         }
556       },
557       dataType: 'json',
558       type: 'POST',
559     };
560
561     if (elementSettings.dialog) {
562       ajax.options.data.dialogOptions = elementSettings.dialog;
563     }
564
565     // Ensure that we have a valid URL by adding ? when no query parameter is
566     // yet available, otherwise append using &.
567     if (ajax.options.url.indexOf('?') === -1) {
568       ajax.options.url += '?';
569     } else {
570       ajax.options.url += '&';
571     }
572     // If this element has a dialog type use if for the wrapper if not use 'ajax'.
573     let wrapper = `drupal_${elementSettings.dialogType || 'ajax'}`;
574     if (elementSettings.dialogRenderer) {
575       wrapper += `.${elementSettings.dialogRenderer}`;
576     }
577     ajax.options.url += `${Drupal.ajax.WRAPPER_FORMAT}=${wrapper}`;
578
579     // Bind the ajaxSubmit function to the element event.
580     $(ajax.element).on(elementSettings.event, function(event) {
581       if (
582         !drupalSettings.ajaxTrustedUrl[ajax.url] &&
583         !Drupal.url.isLocal(ajax.url)
584       ) {
585         throw new Error(
586           Drupal.t('The callback URL is not local and not trusted: !url', {
587             '!url': ajax.url,
588           }),
589         );
590       }
591       return ajax.eventResponse(this, event);
592     });
593
594     // If necessary, enable keyboard submission so that Ajax behaviors
595     // can be triggered through keyboard input as well as e.g. a mousedown
596     // action.
597     if (elementSettings.keypress) {
598       $(ajax.element).on('keypress', function(event) {
599         return ajax.keypressResponse(this, event);
600       });
601     }
602
603     // If necessary, prevent the browser default action of an additional event.
604     // For example, prevent the browser default action of a click, even if the
605     // Ajax behavior binds to mousedown.
606     if (elementSettings.prevent) {
607       $(ajax.element).on(elementSettings.prevent, false);
608     }
609   };
610
611   /**
612    * URL query attribute to indicate the wrapper used to render a request.
613    *
614    * The wrapper format determines how the HTML is wrapped, for example in a
615    * modal dialog.
616    *
617    * @const {string}
618    *
619    * @default
620    */
621   Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
622
623   /**
624    * Request parameter to indicate that a request is a Drupal Ajax request.
625    *
626    * @const {string}
627    *
628    * @default
629    */
630   Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
631
632   /**
633    * Execute the ajax request.
634    *
635    * Allows developers to execute an Ajax request manually without specifying
636    * an event to respond to.
637    *
638    * @return {object}
639    *   Returns the jQuery.Deferred object underlying the Ajax request. If
640    *   pre-serialization fails, the Deferred will be returned in the rejected
641    *   state.
642    */
643   Drupal.Ajax.prototype.execute = function() {
644     // Do not perform another ajax command if one is already in progress.
645     if (this.ajaxing) {
646       return;
647     }
648
649     try {
650       this.beforeSerialize(this.element, this.options);
651       // Return the jqXHR so that external code can hook into the Deferred API.
652       return $.ajax(this.options);
653     } catch (e) {
654       // Unset the ajax.ajaxing flag here because it won't be unset during
655       // the complete response.
656       this.ajaxing = false;
657       window.alert(
658         `An error occurred while attempting to process ${this.options.url}: ${
659           e.message
660         }`,
661       );
662       // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
663       // so that calling code can take appropriate action.
664       return $.Deferred().reject();
665     }
666   };
667
668   /**
669    * Handle a key press.
670    *
671    * The Ajax object will, if instructed, bind to a key press response. This
672    * will test to see if the key press is valid to trigger this event and
673    * if it is, trigger it for us and prevent other keypresses from triggering.
674    * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
675    * and 32. RETURN is often used to submit a form when in a textfield, and
676    * SPACE is often used to activate an element without submitting.
677    *
678    * @param {HTMLElement} element
679    *   Element the event was triggered on.
680    * @param {jQuery.Event} event
681    *   Triggered event.
682    */
683   Drupal.Ajax.prototype.keypressResponse = function(element, event) {
684     // Create a synonym for this to reduce code confusion.
685     const ajax = this;
686
687     // Detect enter key and space bar and allow the standard response for them,
688     // except for form elements of type 'text', 'tel', 'number' and 'textarea',
689     // where the spacebar activation causes inappropriate activation if
690     // #ajax['keypress'] is TRUE. On a text-type widget a space should always
691     // be a space.
692     if (
693       event.which === 13 ||
694       (event.which === 32 &&
695         element.type !== 'text' &&
696         element.type !== 'textarea' &&
697         element.type !== 'tel' &&
698         element.type !== 'number')
699     ) {
700       event.preventDefault();
701       event.stopPropagation();
702       $(element).trigger(ajax.elementSettings.event);
703     }
704   };
705
706   /**
707    * Handle an event that triggers an Ajax response.
708    *
709    * When an event that triggers an Ajax response happens, this method will
710    * perform the actual Ajax call. It is bound to the event using
711    * bind() in the constructor, and it uses the options specified on the
712    * Ajax object.
713    *
714    * @param {HTMLElement} element
715    *   Element the event was triggered on.
716    * @param {jQuery.Event} event
717    *   Triggered event.
718    */
719   Drupal.Ajax.prototype.eventResponse = function(element, event) {
720     event.preventDefault();
721     event.stopPropagation();
722
723     // Create a synonym for this to reduce code confusion.
724     const ajax = this;
725
726     // Do not perform another Ajax command if one is already in progress.
727     if (ajax.ajaxing) {
728       return;
729     }
730
731     try {
732       if (ajax.$form) {
733         // If setClick is set, we must set this to ensure that the button's
734         // value is passed.
735         if (ajax.setClick) {
736           // Mark the clicked button. 'form.clk' is a special variable for
737           // ajaxSubmit that tells the system which element got clicked to
738           // trigger the submit. Without it there would be no 'op' or
739           // equivalent.
740           element.form.clk = element;
741         }
742
743         ajax.$form.ajaxSubmit(ajax.options);
744       } else {
745         ajax.beforeSerialize(ajax.element, ajax.options);
746         $.ajax(ajax.options);
747       }
748     } catch (e) {
749       // Unset the ajax.ajaxing flag here because it won't be unset during
750       // the complete response.
751       ajax.ajaxing = false;
752       window.alert(
753         `An error occurred while attempting to process ${ajax.options.url}: ${
754           e.message
755         }`,
756       );
757     }
758   };
759
760   /**
761    * Handler for the form serialization.
762    *
763    * Runs before the beforeSend() handler (see below), and unlike that one, runs
764    * before field data is collected.
765    *
766    * @param {object} [element]
767    *   Ajax object's `elementSettings`.
768    * @param {object} options
769    *   jQuery.ajax options.
770    */
771   Drupal.Ajax.prototype.beforeSerialize = function(element, options) {
772     // Allow detaching behaviors to update field values before collecting them.
773     // This is only needed when field values are added to the POST data, so only
774     // when there is a form such that this.$form.ajaxSubmit() is used instead of
775     // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
776     // isn't called, but don't rely on that: explicitly check this.$form.
777     if (this.$form) {
778       const settings = this.settings || drupalSettings;
779       Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
780     }
781
782     // Inform Drupal that this is an AJAX request.
783     options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
784
785     // Allow Drupal to return new JavaScript and CSS files to load without
786     // returning the ones already loaded.
787     // @see \Drupal\Core\Theme\AjaxBasePageNegotiator
788     // @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
789     // @see system_js_settings_alter()
790     const pageState = drupalSettings.ajaxPageState;
791     options.data['ajax_page_state[theme]'] = pageState.theme;
792     options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
793     options.data['ajax_page_state[libraries]'] = pageState.libraries;
794   };
795
796   /**
797    * Modify form values prior to form submission.
798    *
799    * @param {Array.<object>} formValues
800    *   Processed form values.
801    * @param {jQuery} element
802    *   The form node as a jQuery object.
803    * @param {object} options
804    *   jQuery.ajax options.
805    */
806   Drupal.Ajax.prototype.beforeSubmit = function(formValues, element, options) {
807     // This function is left empty to make it simple to override for modules
808     // that wish to add functionality here.
809   };
810
811   /**
812    * Prepare the Ajax request before it is sent.
813    *
814    * @param {XMLHttpRequest} xmlhttprequest
815    *   Native Ajax object.
816    * @param {object} options
817    *   jQuery.ajax options.
818    */
819   Drupal.Ajax.prototype.beforeSend = function(xmlhttprequest, options) {
820     // For forms without file inputs, the jQuery Form plugin serializes the
821     // form values, and then calls jQuery's $.ajax() function, which invokes
822     // this handler. In this circumstance, options.extraData is never used. For
823     // forms with file inputs, the jQuery Form plugin uses the browser's normal
824     // form submission mechanism, but captures the response in a hidden IFRAME.
825     // In this circumstance, it calls this handler first, and then appends
826     // hidden fields to the form to submit the values in options.extraData.
827     // There is no simple way to know which submission mechanism will be used,
828     // so we add to extraData regardless, and allow it to be ignored in the
829     // former case.
830     if (this.$form) {
831       options.extraData = options.extraData || {};
832
833       // Let the server know when the IFRAME submission mechanism is used. The
834       // server can use this information to wrap the JSON response in a
835       // TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
836       options.extraData.ajax_iframe_upload = '1';
837
838       // The triggering element is about to be disabled (see below), but if it
839       // contains a value (e.g., a checkbox, textfield, select, etc.), ensure
840       // that value is included in the submission. As per above, submissions
841       // that use $.ajax() are already serialized prior to the element being
842       // disabled, so this is only needed for IFRAME submissions.
843       const v = $.fieldValue(this.element);
844       if (v !== null) {
845         options.extraData[this.element.name] = v;
846       }
847     }
848
849     // Disable the element that received the change to prevent user interface
850     // interaction while the Ajax request is in progress. ajax.ajaxing prevents
851     // the element from triggering a new request, but does not prevent the user
852     // from changing its value.
853     $(this.element).prop('disabled', true);
854
855     if (!this.progress || !this.progress.type) {
856       return;
857     }
858
859     // Insert progress indicator.
860     const progressIndicatorMethod = `setProgressIndicator${this.progress.type
861       .slice(0, 1)
862       .toUpperCase()}${this.progress.type.slice(1).toLowerCase()}`;
863     if (
864       progressIndicatorMethod in this &&
865       typeof this[progressIndicatorMethod] === 'function'
866     ) {
867       this[progressIndicatorMethod].call(this);
868     }
869   };
870
871   /**
872    * An animated progress throbber and container element for AJAX operations.
873    *
874    * @param {string} [message]
875    *   (optional) The message shown on the UI.
876    * @return {string}
877    *   The HTML markup for the throbber.
878    */
879   Drupal.theme.ajaxProgressThrobber = message => {
880     // Build markup without adding extra white space since it affects rendering.
881     const messageMarkup =
882       typeof message === 'string'
883         ? Drupal.theme('ajaxProgressMessage', message)
884         : '';
885     const throbber = '<div class="throbber">&nbsp;</div>';
886
887     return `<div class="ajax-progress ajax-progress-throbber">${throbber}${messageMarkup}</div>`;
888   };
889
890   /**
891    * An animated progress throbber and container element for AJAX operations.
892    *
893    * @return {string}
894    *   The HTML markup for the throbber.
895    */
896   Drupal.theme.ajaxProgressIndicatorFullscreen = () =>
897     '<div class="ajax-progress ajax-progress-fullscreen">&nbsp;</div>';
898
899   /**
900    * Formats text accompanying the AJAX progress throbber.
901    *
902    * @param {string} message
903    *   The message shown on the UI.
904    * @return {string}
905    *   The HTML markup for the throbber.
906    */
907   Drupal.theme.ajaxProgressMessage = message =>
908     `<div class="message">${message}</div>`;
909
910   /**
911    * Sets the progress bar progress indicator.
912    */
913   Drupal.Ajax.prototype.setProgressIndicatorBar = function() {
914     const progressBar = new Drupal.ProgressBar(
915       `ajax-progress-${this.element.id}`,
916       $.noop,
917       this.progress.method,
918       $.noop,
919     );
920     if (this.progress.message) {
921       progressBar.setProgress(-1, this.progress.message);
922     }
923     if (this.progress.url) {
924       progressBar.startMonitoring(
925         this.progress.url,
926         this.progress.interval || 1500,
927       );
928     }
929     this.progress.element = $(progressBar.element).addClass(
930       'ajax-progress ajax-progress-bar',
931     );
932     this.progress.object = progressBar;
933     $(this.element).after(this.progress.element);
934   };
935
936   /**
937    * Sets the throbber progress indicator.
938    */
939   Drupal.Ajax.prototype.setProgressIndicatorThrobber = function() {
940     this.progress.element = $(
941       Drupal.theme('ajaxProgressThrobber', this.progress.message),
942     );
943     $(this.element).after(this.progress.element);
944   };
945
946   /**
947    * Sets the fullscreen progress indicator.
948    */
949   Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function() {
950     this.progress.element = $(Drupal.theme('ajaxProgressIndicatorFullscreen'));
951     $('body').after(this.progress.element);
952   };
953
954   /**
955    * Handler for the form redirection completion.
956    *
957    * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
958    *   Drupal Ajax response.
959    * @param {number} status
960    *   XMLHttpRequest status.
961    */
962   Drupal.Ajax.prototype.success = function(response, status) {
963     // Remove the progress element.
964     if (this.progress.element) {
965       $(this.progress.element).remove();
966     }
967     if (this.progress.object) {
968       this.progress.object.stopMonitoring();
969     }
970     $(this.element).prop('disabled', false);
971
972     // Save element's ancestors tree so if the element is removed from the dom
973     // we can try to refocus one of its parents. Using addBack reverse the
974     // result array, meaning that index 0 is the highest parent in the hierarchy
975     // in this situation it is usually a <form> element.
976     const elementParents = $(this.element)
977       .parents('[data-drupal-selector]')
978       .addBack()
979       .toArray();
980
981     // Track if any command is altering the focus so we can avoid changing the
982     // focus set by the Ajax command.
983     let focusChanged = false;
984     Object.keys(response || {}).forEach(i => {
985       if (response[i].command && this.commands[response[i].command]) {
986         this.commands[response[i].command](this, response[i], status);
987         if (
988           response[i].command === 'invoke' &&
989           response[i].method === 'focus'
990         ) {
991           focusChanged = true;
992         }
993       }
994     });
995
996     // If the focus hasn't be changed by the ajax commands, try to refocus the
997     // triggering element or one of its parents if that element does not exist
998     // anymore.
999     if (
1000       !focusChanged &&
1001       this.element &&
1002       !$(this.element).data('disable-refocus')
1003     ) {
1004       let target = false;
1005
1006       for (let n = elementParents.length - 1; !target && n >= 0; n--) {
1007         target = document.querySelector(
1008           `[data-drupal-selector="${elementParents[n].getAttribute(
1009             'data-drupal-selector',
1010           )}"]`,
1011         );
1012       }
1013
1014       if (target) {
1015         $(target).trigger('focus');
1016       }
1017     }
1018
1019     // Reattach behaviors, if they were detached in beforeSerialize(). The
1020     // attachBehaviors() called on the new content from processing the response
1021     // commands is not sufficient, because behaviors from the entire form need
1022     // to be reattached.
1023     if (this.$form) {
1024       const settings = this.settings || drupalSettings;
1025       Drupal.attachBehaviors(this.$form.get(0), settings);
1026     }
1027
1028     // Remove any response-specific settings so they don't get used on the next
1029     // call by mistake.
1030     this.settings = null;
1031   };
1032
1033   /**
1034    * Build an effect object to apply an effect when adding new HTML.
1035    *
1036    * @param {object} response
1037    *   Drupal Ajax response.
1038    * @param {string} [response.effect]
1039    *   Override the default value of {@link Drupal.Ajax#elementSettings}.
1040    * @param {string|number} [response.speed]
1041    *   Override the default value of {@link Drupal.Ajax#elementSettings}.
1042    *
1043    * @return {object}
1044    *   Returns an object with `showEffect`, `hideEffect` and `showSpeed`
1045    *   properties.
1046    */
1047   Drupal.Ajax.prototype.getEffect = function(response) {
1048     const type = response.effect || this.effect;
1049     const speed = response.speed || this.speed;
1050
1051     const effect = {};
1052     if (type === 'none') {
1053       effect.showEffect = 'show';
1054       effect.hideEffect = 'hide';
1055       effect.showSpeed = '';
1056     } else if (type === 'fade') {
1057       effect.showEffect = 'fadeIn';
1058       effect.hideEffect = 'fadeOut';
1059       effect.showSpeed = speed;
1060     } else {
1061       effect.showEffect = `${type}Toggle`;
1062       effect.hideEffect = `${type}Toggle`;
1063       effect.showSpeed = speed;
1064     }
1065
1066     return effect;
1067   };
1068
1069   /**
1070    * Handler for the form redirection error.
1071    *
1072    * @param {object} xmlhttprequest
1073    *   Native XMLHttpRequest object.
1074    * @param {string} uri
1075    *   Ajax Request URI.
1076    * @param {string} [customMessage]
1077    *   Extra message to print with the Ajax error.
1078    */
1079   Drupal.Ajax.prototype.error = function(xmlhttprequest, uri, customMessage) {
1080     // Remove the progress element.
1081     if (this.progress.element) {
1082       $(this.progress.element).remove();
1083     }
1084     if (this.progress.object) {
1085       this.progress.object.stopMonitoring();
1086     }
1087     // Undo hide.
1088     $(this.wrapper).show();
1089     // Re-enable the element.
1090     $(this.element).prop('disabled', false);
1091     // Reattach behaviors, if they were detached in beforeSerialize().
1092     if (this.$form) {
1093       const settings = this.settings || drupalSettings;
1094       Drupal.attachBehaviors(this.$form.get(0), settings);
1095     }
1096     throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
1097   };
1098
1099   /**
1100    * Provide a wrapper for new content via Ajax.
1101    *
1102    * Wrap the inserted markup when inserting multiple root elements with an
1103    * ajax effect.
1104    *
1105    * @param {jQuery} $newContent
1106    *   Response elements after parsing.
1107    * @param {Drupal.Ajax} ajax
1108    *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1109    * @param {object} response
1110    *   The response from the Ajax request.
1111    *
1112    * @deprecated in Drupal 8.6.x and will be removed before Drupal 9.0.0.
1113    *   Use data with desired wrapper. See https://www.drupal.org/node/2974880.
1114    *
1115    * @todo Add deprecation warning after it is possible. For more information
1116    *   see: https://www.drupal.org/project/drupal/issues/2973400
1117    *
1118    * @see https://www.drupal.org/node/2940704
1119    */
1120   Drupal.theme.ajaxWrapperNewContent = ($newContent, ajax, response) =>
1121     (response.effect || ajax.effect) !== 'none' &&
1122     $newContent.filter(
1123       i =>
1124         !// We can not consider HTML comments or whitespace text as separate
1125         // roots, since they do not cause visual regression with effect.
1126         (
1127           $newContent[i].nodeName === '#comment' ||
1128           ($newContent[i].nodeName === '#text' &&
1129             /^(\s|\n|\r)*$/.test($newContent[i].textContent))
1130         ),
1131     ).length > 1
1132       ? Drupal.theme('ajaxWrapperMultipleRootElements', $newContent)
1133       : $newContent;
1134
1135   /**
1136    * Provide a wrapper for multiple root elements via Ajax.
1137    *
1138    * @param {jQuery} $elements
1139    *   Response elements after parsing.
1140    *
1141    * @deprecated in Drupal 8.6.x and will be removed before Drupal 9.0.0.
1142    *   Use data with desired wrapper. See https://www.drupal.org/node/2974880.
1143    *
1144    * @todo Add deprecation warning after it is possible. For more information
1145    *   see: https://www.drupal.org/project/drupal/issues/2973400
1146    *
1147    * @see https://www.drupal.org/node/2940704
1148    */
1149   Drupal.theme.ajaxWrapperMultipleRootElements = $elements =>
1150     $('<div></div>').append($elements);
1151
1152   /**
1153    * @typedef {object} Drupal.AjaxCommands~commandDefinition
1154    *
1155    * @prop {string} command
1156    * @prop {string} [method]
1157    * @prop {string} [selector]
1158    * @prop {string} [data]
1159    * @prop {object} [settings]
1160    * @prop {bool} [asterisk]
1161    * @prop {string} [text]
1162    * @prop {string} [title]
1163    * @prop {string} [url]
1164    * @prop {object} [argument]
1165    * @prop {string} [name]
1166    * @prop {string} [value]
1167    * @prop {string} [old]
1168    * @prop {string} [new]
1169    * @prop {bool} [merge]
1170    * @prop {Array} [args]
1171    *
1172    * @see Drupal.AjaxCommands
1173    */
1174
1175   /**
1176    * Provide a series of commands that the client will perform.
1177    *
1178    * @constructor
1179    */
1180   Drupal.AjaxCommands = function() {};
1181   Drupal.AjaxCommands.prototype = {
1182     /**
1183      * Command to insert new content into the DOM.
1184      *
1185      * @param {Drupal.Ajax} ajax
1186      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1187      * @param {object} response
1188      *   The response from the Ajax request.
1189      * @param {string} response.data
1190      *   The data to use with the jQuery method.
1191      * @param {string} [response.method]
1192      *   The jQuery DOM manipulation method to be used.
1193      * @param {string} [response.selector]
1194      *   A optional jQuery selector string.
1195      * @param {object} [response.settings]
1196      *   An optional array of settings that will be used.
1197      */
1198     insert(ajax, response) {
1199       // Get information from the response. If it is not there, default to
1200       // our presets.
1201       const $wrapper = response.selector
1202         ? $(response.selector)
1203         : $(ajax.wrapper);
1204       const method = response.method || ajax.method;
1205       const effect = ajax.getEffect(response);
1206
1207       // Apply any settings from the returned JSON if available.
1208       const settings = response.settings || ajax.settings || drupalSettings;
1209
1210       // Parse response.data into an element collection.
1211       let $newContent = $($.parseHTML(response.data, document, true));
1212       // For backward compatibility, in some cases a wrapper will be added. This
1213       // behavior will be removed before Drupal 9.0.0. If different behavior is
1214       // needed, the theme functions can be overriden.
1215       // @see https://www.drupal.org/node/2940704
1216       $newContent = Drupal.theme(
1217         'ajaxWrapperNewContent',
1218         $newContent,
1219         ajax,
1220         response,
1221       );
1222
1223       // If removing content from the wrapper, detach behaviors first.
1224       switch (method) {
1225         case 'html':
1226         case 'replaceWith':
1227         case 'replaceAll':
1228         case 'empty':
1229         case 'remove':
1230           Drupal.detachBehaviors($wrapper.get(0), settings);
1231           break;
1232         default:
1233           break;
1234       }
1235
1236       // Add the new content to the page.
1237       $wrapper[method]($newContent);
1238
1239       // Immediately hide the new content if we're using any effects.
1240       if (effect.showEffect !== 'show') {
1241         $newContent.hide();
1242       }
1243
1244       // Determine which effect to use and what content will receive the
1245       // effect, then show the new content.
1246       const $ajaxNewContent = $newContent.find('.ajax-new-content');
1247       if ($ajaxNewContent.length) {
1248         $ajaxNewContent.hide();
1249         $newContent.show();
1250         $ajaxNewContent[effect.showEffect](effect.showSpeed);
1251       } else if (effect.showEffect !== 'show') {
1252         $newContent[effect.showEffect](effect.showSpeed);
1253       }
1254
1255       // Attach all JavaScript behaviors to the new content, if it was
1256       // successfully added to the page, this if statement allows
1257       // `#ajax['wrapper']` to be optional.
1258       if ($newContent.parents('html').length) {
1259         // Attach behaviors to all element nodes.
1260         $newContent.each((index, element) => {
1261           if (element.nodeType === Node.ELEMENT_NODE) {
1262             Drupal.attachBehaviors(element, settings);
1263           }
1264         });
1265       }
1266     },
1267
1268     /**
1269      * Command to remove a chunk from the page.
1270      *
1271      * @param {Drupal.Ajax} [ajax]
1272      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1273      * @param {object} response
1274      *   The response from the Ajax request.
1275      * @param {string} response.selector
1276      *   A jQuery selector string.
1277      * @param {object} [response.settings]
1278      *   An optional array of settings that will be used.
1279      * @param {number} [status]
1280      *   The XMLHttpRequest status.
1281      */
1282     remove(ajax, response, status) {
1283       const settings = response.settings || ajax.settings || drupalSettings;
1284       $(response.selector)
1285         .each(function() {
1286           Drupal.detachBehaviors(this, settings);
1287         })
1288         .remove();
1289     },
1290
1291     /**
1292      * Command to mark a chunk changed.
1293      *
1294      * @param {Drupal.Ajax} [ajax]
1295      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1296      * @param {object} response
1297      *   The JSON response object from the Ajax request.
1298      * @param {string} response.selector
1299      *   A jQuery selector string.
1300      * @param {bool} [response.asterisk]
1301      *   An optional CSS selector. If specified, an asterisk will be
1302      *   appended to the HTML inside the provided selector.
1303      * @param {number} [status]
1304      *   The request status.
1305      */
1306     changed(ajax, response, status) {
1307       const $element = $(response.selector);
1308       if (!$element.hasClass('ajax-changed')) {
1309         $element.addClass('ajax-changed');
1310         if (response.asterisk) {
1311           $element
1312             .find(response.asterisk)
1313             .append(
1314               ` <abbr class="ajax-changed" title="${Drupal.t(
1315                 'Changed',
1316               )}">*</abbr> `,
1317             );
1318         }
1319       }
1320     },
1321
1322     /**
1323      * Command to provide an alert.
1324      *
1325      * @param {Drupal.Ajax} [ajax]
1326      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1327      * @param {object} response
1328      *   The JSON response from the Ajax request.
1329      * @param {string} response.text
1330      *   The text that will be displayed in an alert dialog.
1331      * @param {number} [status]
1332      *   The XMLHttpRequest status.
1333      */
1334     alert(ajax, response, status) {
1335       window.alert(response.text, response.title);
1336     },
1337
1338     /**
1339      * Command to set the window.location, redirecting the browser.
1340      *
1341      * @param {Drupal.Ajax} [ajax]
1342      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1343      * @param {object} response
1344      *   The response from the Ajax request.
1345      * @param {string} response.url
1346      *   The URL to redirect to.
1347      * @param {number} [status]
1348      *   The XMLHttpRequest status.
1349      */
1350     redirect(ajax, response, status) {
1351       window.location = response.url;
1352     },
1353
1354     /**
1355      * Command to provide the jQuery css() function.
1356      *
1357      * @param {Drupal.Ajax} [ajax]
1358      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1359      * @param {object} response
1360      *   The response from the Ajax request.
1361      * @param {string} response.selector
1362      *   A jQuery selector string.
1363      * @param {object} response.argument
1364      *   An array of key/value pairs to set in the CSS for the selector.
1365      * @param {number} [status]
1366      *   The XMLHttpRequest status.
1367      */
1368     css(ajax, response, status) {
1369       $(response.selector).css(response.argument);
1370     },
1371
1372     /**
1373      * Command to set the settings used for other commands in this response.
1374      *
1375      * This method will also remove expired `drupalSettings.ajax` settings.
1376      *
1377      * @param {Drupal.Ajax} [ajax]
1378      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1379      * @param {object} response
1380      *   The response from the Ajax request.
1381      * @param {bool} response.merge
1382      *   Determines whether the additional settings should be merged to the
1383      *   global settings.
1384      * @param {object} response.settings
1385      *   Contains additional settings to add to the global settings.
1386      * @param {number} [status]
1387      *   The XMLHttpRequest status.
1388      */
1389     settings(ajax, response, status) {
1390       const ajaxSettings = drupalSettings.ajax;
1391
1392       // Clean up drupalSettings.ajax.
1393       if (ajaxSettings) {
1394         Drupal.ajax.expired().forEach(instance => {
1395           // If the Ajax object has been created through drupalSettings.ajax
1396           // it will have a selector. When there is no selector the object
1397           // has been initialized with a special class name picked up by the
1398           // Ajax behavior.
1399
1400           if (instance.selector) {
1401             const selector = instance.selector.replace('#', '');
1402             if (selector in ajaxSettings) {
1403               delete ajaxSettings[selector];
1404             }
1405           }
1406         });
1407       }
1408
1409       if (response.merge) {
1410         $.extend(true, drupalSettings, response.settings);
1411       } else {
1412         ajax.settings = response.settings;
1413       }
1414     },
1415
1416     /**
1417      * Command to attach data using jQuery's data API.
1418      *
1419      * @param {Drupal.Ajax} [ajax]
1420      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1421      * @param {object} response
1422      *   The response from the Ajax request.
1423      * @param {string} response.name
1424      *   The name or key (in the key value pair) of the data attached to this
1425      *   selector.
1426      * @param {string} response.selector
1427      *   A jQuery selector string.
1428      * @param {string|object} response.value
1429      *   The value of to be attached.
1430      * @param {number} [status]
1431      *   The XMLHttpRequest status.
1432      */
1433     data(ajax, response, status) {
1434       $(response.selector).data(response.name, response.value);
1435     },
1436
1437     /**
1438      * Command to apply a jQuery method.
1439      *
1440      * @param {Drupal.Ajax} [ajax]
1441      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1442      * @param {object} response
1443      *   The response from the Ajax request.
1444      * @param {Array} response.args
1445      *   An array of arguments to the jQuery method, if any.
1446      * @param {string} response.method
1447      *   The jQuery method to invoke.
1448      * @param {string} response.selector
1449      *   A jQuery selector string.
1450      * @param {number} [status]
1451      *   The XMLHttpRequest status.
1452      */
1453     invoke(ajax, response, status) {
1454       const $element = $(response.selector);
1455       $element[response.method](...response.args);
1456     },
1457
1458     /**
1459      * Command to restripe a table.
1460      *
1461      * @param {Drupal.Ajax} [ajax]
1462      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1463      * @param {object} response
1464      *   The response from the Ajax request.
1465      * @param {string} response.selector
1466      *   A jQuery selector string.
1467      * @param {number} [status]
1468      *   The XMLHttpRequest status.
1469      */
1470     restripe(ajax, response, status) {
1471       // :even and :odd are reversed because jQuery counts from 0 and
1472       // we count from 1, so we're out of sync.
1473       // Match immediate children of the parent element to allow nesting.
1474       $(response.selector)
1475         .find('> tbody > tr:visible, > tr:visible')
1476         .removeClass('odd even')
1477         .filter(':even')
1478         .addClass('odd')
1479         .end()
1480         .filter(':odd')
1481         .addClass('even');
1482     },
1483
1484     /**
1485      * Command to update a form's build ID.
1486      *
1487      * @param {Drupal.Ajax} [ajax]
1488      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1489      * @param {object} response
1490      *   The response from the Ajax request.
1491      * @param {string} response.old
1492      *   The old form build ID.
1493      * @param {string} response.new
1494      *   The new form build ID.
1495      * @param {number} [status]
1496      *   The XMLHttpRequest status.
1497      */
1498     update_build_id(ajax, response, status) {
1499       $(`input[name="form_build_id"][value="${response.old}"]`).val(
1500         response.new,
1501       );
1502     },
1503
1504     /**
1505      * Command to add css.
1506      *
1507      * Uses the proprietary addImport method if available as browsers which
1508      * support that method ignore @import statements in dynamically added
1509      * stylesheets.
1510      *
1511      * @param {Drupal.Ajax} [ajax]
1512      *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1513      * @param {object} response
1514      *   The response from the Ajax request.
1515      * @param {string} response.data
1516      *   A string that contains the styles to be added.
1517      * @param {number} [status]
1518      *   The XMLHttpRequest status.
1519      */
1520     add_css(ajax, response, status) {
1521       // Add the styles in the normal way.
1522       $('head').prepend(response.data);
1523       // Add imports in the styles using the addImport method if available.
1524       let match;
1525       const importMatch = /^@import url\("(.*)"\);$/gim;
1526       if (
1527         document.styleSheets[0].addImport &&
1528         importMatch.test(response.data)
1529       ) {
1530         importMatch.lastIndex = 0;
1531         do {
1532           match = importMatch.exec(response.data);
1533           document.styleSheets[0].addImport(match[1]);
1534         } while (match);
1535       }
1536     },
1537   };
1538 })(jQuery, window, Drupal, drupalSettings);