PageSourceSearch

https://www.hopeunions.org/core/misc/ajax.js?v=11.3.17

js hopeunions.org collected 2026-10-02 01:08:34 UTC 66,775 bytes, 1,932 lines download raw bytes

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

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.