PageSourceSearch

https://www.livekuban.ru/core/misc/ajax.js?v=11.3.8

js livekuban.ru collected 2026-09-24 08:29:50 UTC 66,137 bytes, 1,914 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    ajax.options.url += `${Drupal.ajax.WRAPPER_FORMAT}=${wrapper}`;
635
636    // Bind the ajaxSubmit function to the element event.
637    $(ajax.element).on(elementSettings.event, function (event) {
638      if (
639        !drupalSettings.ajaxTrustedUrl[ajax.url] &&
640        !Drupal.url.isLocal(ajax.url)
641      ) {
642        throw new Error(
643          Drupal.t('The callback URL is not local and not trusted: !url', {
644            '!url': ajax.url,
645          }),
646        );
647      }
648      return ajax.eventResponse(this, event);
649    });
650
651    // If necessary, enable keyboard submission so that Ajax behaviors
652    // can be triggered through keyboard input as well as e.g. a mousedown
653    // action.
654    if (elementSettings.keypress) {
655      $(ajax.element).on('keypress', function (event) {
656        return ajax.keypressResponse(this, event);
657      });
658    }
659
660    // If necessary, prevent the browser default action of an additional event.
661    // For example, prevent the browser default action of a click, even if the
662    // Ajax behavior binds to mousedown.
663    if (elementSettings.prevent) {
664      $(ajax.element).on(elementSettings.prevent, false);
665    }
666  };
667
668  /**
669   * URL query attribute to indicate the wrapper used to render a request.
670   *
671   * The wrapper format determines how the HTML is wrapped, for example in a
672   * modal dialog.
673   *
674   * @const {string}
675   *
676   * @default
677   */
678  Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
679
680  /**
681   * Request parameter to indicate that a request is a Drupal Ajax request.
682   *
683   * @const {string}
684   *
685   * @default
686   */
687  Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
688
689  /**
690   * Execute the ajax request.
691   *
692   * Allows developers to execute an Ajax request manually without specifying
693   * an event to respond to.
694   *
695   * @return {object}
696   *   Returns the jQuery.Deferred object underlying the Ajax request. If
697   *   pre-serialization fails, the Deferred will be returned in the rejected
698   *   state.
699   */
700  Drupal.Ajax.prototype.execute = function () {
701    // Do not perform another ajax command if one is already in progress.
702    if (this.ajaxing) {
703      return;
704    }
705
706    try {
707      this.beforeSerialize(this.element, this.options);
708      // Return the jqXHR so that external code can hook into the Deferred API.
709      return $.ajax(this.options);
710    } catch (e) {
711      // Unset the ajax.ajaxing flag here because it won't be unset during
712      // the complete response.
713      this.ajaxing = false;
714      window.alert(
715        `An error occurred while attempting to process ${this.options.url}: ${e.message}`,
716      );
717      // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
718      // so that calling code can take appropriate action.
719      return $.Deferred().reject();
720    }
721  };
722
723  /**
724   * Handle a key press.
725   *
726   * The Ajax object will, if instructed, bind to a key press response. This
727   * will test to see if the key press is valid to trigger this event and
728   * if it is, trigger it for us and prevent other keypresses from triggering.
729   * In this case we're handling RETURN and SPACE BAR keypresses (event codes 13
730   * and 32. RETURN is often used to submit a form when in a textfield, and
731   * SPACE is often used to activate an element without submitting.
732   *
733   * @param {HTMLElement} element
734   *   Element the event was triggered on.
735   * @param {jQuery.Event} event
736   *   Triggered event.
737   */
738  Drupal.Ajax.prototype.keypressResponse = function (element, event) {
739    // Create a synonym for this to reduce code confusion.
740    const ajax = this;
741
742    // Detect enter key and space bar and allow the standard response for them,
743    // except for form elements of type 'text', 'tel', 'number' and 'textarea',
744    // where the space bar activation causes inappropriate activation if
745    // #ajax['keypress'] is TRUE. On a text-type widget a space should always
746    // be a space.
747    if (
748      event.which === 13 ||
749      (event.which === 32 &&
750        element.type !== 'text' &&
751        element.type !== 'textarea' &&
752        element.type !== 'tel' &&
753        element.type !== 'number')
754    ) {
755      event.preventDefault();
756      event.stopPropagation();
757      $(element).trigger(ajax.elementSettings.event);
758    }
759  };
760
761  /**
762   * Handle an event that triggers an Ajax response.
763   *
764   * When an event that triggers an Ajax response happens, this method will
765   * perform the actual Ajax call. It is bound to the event using
766   * bind() in the constructor, and it uses the options specified on the
767   * Ajax object.
768   *
769   * @param {HTMLElement} element
770   *   Element the event was triggered on.
771   * @param {jQuery.Event} event
772   *   Triggered event.
773   */
774  Drupal.Ajax.prototype.eventResponse = function (element, event) {
775    event.preventDefault();
776    event.stopPropagation();
777
778    // Create a synonym for this to reduce code confusion.
779    const ajax = this;
780
781    // Do not perform another Ajax command if one is already in progress.
782    if (ajax.ajaxing) {
783      return;
784    }
785
786    try {
787      if (ajax.$form) {
788        // If setClick is set, we must set this to ensure that the button's
789        // value is passed.
790        if (ajax.setClick) {
791          // Mark the clicked button. 'form.clk' is a special variable for
792          // ajaxSubmit that tells the system which element got clicked to
793          // trigger the submit. Without it there would be no 'op' or
794          // equivalent.
795          element.form.clk = element;
796        }
797
798        ajax.$form.ajaxSubmit(ajax.options);
799      } else {
800        ajax.beforeSerialize(ajax.element, ajax.options);
801        $.ajax(ajax.options);
802      }
803    } catch (e) {
804      // Unset the ajax.ajaxing flag here because it won't be unset during
805      // the complete response.
806      ajax.ajaxing = false;
807      window.alert(
808        `An error occurred while attempting to process ${ajax.options.url}: ${e.message}`,
809      );
810    }
811  };
812
813  /**
814   * Handler for the form serialization.
815   *
816   * Runs before the beforeSend() handler (see below), and unlike that one, runs
817   * before field data is collected.
818   *
819   * @param {object} [element]
820   *   Ajax object's `elementSettings`.
821   * @param {object} options
822   *   jQuery.ajax options.
823   */
824  Drupal.Ajax.prototype.beforeSerialize = function (element, options) {
825    // Allow detaching behaviors to update field values before collecting them.
826    // This is only needed when field values are added to the POST data, so only
827    // when there is a form such that this.$form.ajaxSubmit() is used instead of
828    // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
829    // isn't called, but don't rely on that: explicitly check this.$form.
830    if (this.$form && document.body.contains(this.$form.get(0))) {
831      const settings = this.settings || drupalSettings;
832      Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
833    }
834
835    // Inform Drupal that this is an AJAX request.
836    options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
837
838    // Allow Drupal to return new JavaScript and CSS files to load without
839    // returning the ones already loaded.
840    // @see \Drupal\Core\StackMiddleWare\AjaxPageState
841    // @see \Drupal\Core\Theme\AjaxBasePageNegotiator
842    // @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
843    // @see system_js_settings_alter()
844    const pageState = drupalSettings.ajaxPageState;
845    options.data['ajax_page_state[theme]'] = pageState.theme;
846    options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
847    options.data['ajax_page_state[libraries]'] = pageState.libraries;
848  };
849
850  /**
851   * Modify form values prior to form submission.
852   *
853   * @param {Array.<object>} formValues
854   *   Processed form values.
855   * @param {jQuery} element
856   *   The form node as a jQuery object.
857   * @param {object} options
858   *   jQuery.ajax options.
859   */
860  Drupal.Ajax.prototype.beforeSubmit = function (formValues, element, options) {
861    // This function is left empty to make it simple to override for modules
862    // that wish to add functionality here.
863  };
864
865  /**
866   * Prepare the Ajax request before it is sent.
867   *
868   * @param {XMLHttpRequest} xmlhttprequest
869   *   Native Ajax object.
870   * @param {object} options
871   *   jQuery.ajax options.
872   */
873  Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) {
874    // For forms without file inputs, the jQuery Form plugin serializes the
875    // form values, and then calls jQuery's $.ajax() function, which invokes
876    // this handler. In this circumstance, options.extraData is never used. For
877    // forms with file inputs, the jQuery Form plugin uses the browser's normal
878    // form submission mechanism, but captures the response in a hidden IFRAME.
879    // In this circumstance, it calls this handler first, and then appends
880    // hidden fields to the form to submit the values in options.extraData.
881    // There is no simple way to know which submission mechanism will be used,
882    // so we add to extraData regardless, and allow it to be ignored in the
883    // former case.
884    if (this.$form) {
885      options.extraData = options.extraData || {};
886
887      // Let the server know when the IFRAME submission mechanism is used. The
888      // server can use this information to wrap the JSON response in a
889      // TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
890      options.extraData.ajax_iframe_upload = '1';
891
892      // The triggering element is about to be disabled (see below), but if it
893      // contains a value (e.g., a checkbox, textfield, select, etc.), ensure
894      // that value is included in the submission. As per above, submissions
895      // that use $.ajax() are already serialized prior to the element being
896      // disabled, so this is only needed for IFRAME submissions.
897      const v = $.fieldValue(this.element);
898      if (v !== null) {
899        options.extraData[this.element.name] = v;
900      }
901    }
902
903    // Disable the element that received the change to prevent user interface
904    // interaction while the Ajax request is in progress. ajax.ajaxing prevents
905    // the element from triggering a new request, but does not prevent the user
906    // from changing its value.
907    $(this.element).prop('disabled', true);
908
909    if (!this.progress || !this.progress.type) {
910      return;
911    }
912
913    // Insert progress indicator.
914    const progressIndicatorMethod = `setProgressIndicator${this.progress.type
915      .slice(0, 1)
916      .toUpperCase()}${this.progress.type.slice(1).toLowerCase()}`;
917    if (
918      progressIndicatorMethod in this &&
919      typeof this[progressIndicatorMethod] === 'function'
920    ) {
921      this[progressIndicatorMethod].call(this);
922    }
923  };
924
925  /**
926   * An animated progress throbber and container element for AJAX operations.
927   *
928   * @param {string} [message]
929   *   (optional) The message shown on the UI.
930   * @return {string}
931   *   The HTML markup for the throbber.
932   */
933  Drupal.theme.ajaxProgressThrobber = (message) => {
934    // Build markup without adding extra white space since it affects rendering.
935    const messageMarkup =
936      typeof message === 'string'
937        ? Drupal.theme('ajaxProgressMessage', message)
938        : '';
939    const throbber = '<div class="throbber">&nbsp;</div>';
940
941    return `<div class="ajax-progress ajax-progress-throbber">${throbber}${messageMarkup}</div>`;
942  };
943
944  /**
945   * An animated progress throbber and container element for AJAX operations.
946   *
947   * @return {string}
948   *   The HTML markup for the throbber.
949   */
950  Drupal.theme.ajaxProgressIndicatorFullscreen = () =>
951    '<div class="ajax-progress ajax-progress-fullscreen">&nbsp;</div>';
952
953  /**
954   * Formats text accompanying the AJAX progress throbber.
955   *
956   * @param {string} message
957   *   The message shown on the UI.
958   * @return {string}
959   *   The HTML markup for the throbber.
960   */
961  Drupal.theme.ajaxProgressMessage = (message) =>
962    `<div class="message">${message}</div>`;
963
964  /**
965   * Provide a wrapper for the AJAX progress bar element.
966   *
967   * @param {jQuery} $element
968   *   Progress bar element.
969   * @return {string}
970   *   The HTML markup for the progress bar.
971   */
972  Drupal.theme.ajaxProgressBar = ($element) =>
973    $('<div class="ajax-progress ajax-progress-bar"></div>').append($element);
974
975  /**
976   * Sets the progress bar progress indicator.
977   */
978  Drupal.Ajax.prototype.setProgressIndicatorBar = function () {
979    const progressBar = new Drupal.ProgressBar(
980      `ajax-progress-${this.element.id}`,
981      $.noop,
982      this.progress.method,
983      $.noop,
984    );
985    if (this.progress.message) {
986      progressBar.setProgress(-1, this.progress.message);
987    }
988    if (this.progress.url) {
989      progressBar.startMonitoring(
990        this.progress.url,
991        this.progress.interval || 1500,
992      );
993    }
994    this.progress.element = $(
995      Drupal.theme('ajaxProgressBar', progressBar.element),
996    );
997    this.progress.object = progressBar;
998    $(this.element).after(this.progress.element);
999  };
1000
1001  /**
1002   * Sets the throbber progress indicator.
1003   */
1004  Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
1005    this.progress.element = $(
1006      Drupal.theme('ajaxProgressThrobber', this.progress.message),
1007    );
1008    if ($(this.element).closest('[data-drupal-ajax-container]').length) {
1009      $(this.element)
1010        .closest('[data-drupal-ajax-container]')
1011        .after(this.progress.element);
1012    } else {
1013      $(this.element).after(this.progress.element);
1014    }
1015  };
1016
1017  /**
1018   * Sets the fullscreen progress indicator.
1019   */
1020  Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
1021    this.progress.element = $(Drupal.theme('ajaxProgressIndicatorFullscreen'));
1022    $('body').append(this.progress.element);
1023  };
1024
1025  /**
1026   * Helper method to make sure commands are executed in sequence.
1027   *
1028   * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
1029   *   Drupal Ajax response.
1030   * @param {number} status
1031   *   XMLHttpRequest status.
1032   *
1033   * @return {Promise}
1034   *  The promise that will resolve once all commands have finished executing.
1035   */
1036  Drupal.Ajax.prototype.commandExecutionQueue = function (response, status) {
1037    const ajaxCommands = this.commands;
1038    return Object.keys(response || {}).reduce(
1039      // Add all commands to a single execution queue.
1040      (executionQueue, key) =>
1041        executionQueue.then(() => {
1042          const { command } = response[key];
1043          if (command && ajaxCommands[command]) {
1044            // When a command returns a promise, the remaining commands will not
1045            // execute until that promise has been fulfilled. This is typically
1046            // used to ensure JavaScript files added via the 'add_js' command
1047            // have loaded before subsequent commands execute.
1048            return ajaxCommands[command](this, response[key], status);
1049          }
1050        }),
1051      Promise.resolve(),
1052    );
1053  };
1054
1055  /**
1056   * Handler for the form redirection completion.
1057   *
1058   * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
1059   *   Drupal Ajax response.
1060   * @param {number} status
1061   *   XMLHttpRequest status.
1062   *
1063   * @return {Promise}
1064   * The promise that will resolve once all commands have finished executing.
1065   */
1066  Drupal.Ajax.prototype.success = function (response, status) {
1067    // Remove the progress element.
1068    if (this.progress.element) {
1069      $(this.progress.element).remove();
1070    }
1071    if (this.progress.object) {
1072      this.progress.object.stopMonitoring();
1073    }
1074    $(this.element).prop('disabled', false);
1075
1076    // Save element's ancestors tree so if the element is removed from the dom
1077    // we can try to refocus one of its parents. Using addBack reverse the
1078    // result array, meaning that index 0 is the highest parent in the hierarchy
1079    // in this situation it is usually a <form> element.
1080    const elementParents = $(this.element)
1081      .parents('[data-drupal-selector]')
1082      .addBack()
1083      .toArray();
1084
1085    // Track if any command is altering the focus so we can avoid changing the
1086    // focus set by the Ajax command.
1087    const focusChanged = Object.keys(response || {}).some((key) => {
1088      const { command, method } = response[key];
1089      return (
1090        command === 'focusFirst' ||
1091        command === 'openDialog' ||
1092        (command === 'invoke' && method === 'focus')
1093      );
1094    });
1095
1096    return (
1097      this.commandExecutionQueue(response, status)
1098        // If the focus hasn't been changed by the AJAX commands, try to refocus
1099        // the triggering element or one of its parents if that element does not
1100        // exist anymore.
1101        .then(() => {
1102          if (!focusChanged) {
1103            let target = false;
1104            if (this.element) {
1105              if (
1106                $(this.element).data('refocus-blur') &&
1107                this.preCommandsFocusedElementSelector
1108              ) {
1109                target = document.querySelector(
1110                  `[data-drupal-selector="${this.preCommandsFocusedElementSelector}"]`,
1111                );
1112              }
1113              if (!target && !$(this.element).data('disable-refocus')) {
1114                for (
1115                  let n = elementParents.length - 1;
1116                  !target && n >= 0;
1117                  n--
1118                ) {
1119                  target = document.querySelector(
1120                    `[data-drupal-selector="${elementParents[n].getAttribute(
1121                      'data-drupal-selector',
1122                    )}"]`,
1123                  );
1124                }
1125              }
1126            }
1127            if (target) {
1128              $(target).trigger('focus');
1129            }
1130          }
1131          // Reattach behaviors, if they were detached in beforeSerialize(). The
1132          // attachBehaviors() called on the new content from processing the
1133          // response commands is not sufficient, because behaviors from the
1134          // entire form need to be reattached.
1135          if (this.$form && document.body.contains(this.$form.get(0))) {
1136            const settings = this.settings || drupalSettings;
1137            Drupal.attachBehaviors(this.$form.get(0), settings);
1138          }
1139          // Remove any response-specific settings so they don't get used on the
1140          // next call by mistake.
1141          this.settings = null;
1142        })
1143        .catch((error) =>
1144          // eslint-disable-next-line no-console
1145          console.error(
1146            Drupal.t(
1147              'An error occurred during the execution of the Ajax response: !error',
1148              {
1149                '!error': error,
1150              },
1151            ),
1152          ),
1153        )
1154    );
1155  };
1156
1157  /**
1158   * Build an effect object to apply an effect when adding new HTML.
1159   *
1160   * @param {object} response
1161   *   Drupal Ajax response.
1162   * @param {string} [response.effect]
1163   *   Override the default value of {@link Drupal.Ajax#elementSettings}.
1164   * @param {string|number} [response.speed]
1165   *   Override the default value of {@link Drupal.Ajax#elementSettings}.
1166   *
1167   * @return {object}
1168   *   Returns an object with `showEffect`, `hideEffect` and `showSpeed`
1169   *   properties.
1170   */
1171  Drupal.Ajax.prototype.getEffect = function (response) {
1172    const type = response.effect || this.effect;
1173    const speed = response.speed || this.speed;
1174
1175    const effect = {};
1176    if (type === 'none') {
1177      effect.showEffect = 'show';
1178      effect.hideEffect = 'hide';
1179      effect.showSpeed = '';
1180    } else if (type === 'fade') {
1181      effect.showEffect = 'fadeIn';
1182      effect.hideEffect = 'fadeOut';
1183      effect.showSpeed = speed;
1184    } else {
1185      effect.showEffect = `${type}Toggle`;
1186      effect.hideEffect = `${type}Toggle`;
1187      effect.showSpeed = speed;
1188    }
1189
1190    return effect;
1191  };
1192
1193  /**
1194   * Handler for the form redirection error.
1195   *
1196   * @param {object} xmlhttprequest
1197   *   Native XMLHttpRequest object.
1198   * @param {string} uri
1199   *   Ajax Request URI.
1200   * @param {string} [customMessage]
1201   *   Extra message to print with the Ajax error.
1202   */
1203  Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
1204    // Remove the progress element.
1205    if (this.progress.element) {
1206      $(this.progress.element).remove();
1207    }
1208    if (this.progress.object) {
1209      this.progress.object.stopMonitoring();
1210    }
1211    // Undo hide.
1212    $(this.wrapper).show();
1213    // Re-enable the element.
1214    $(this.element).prop('disabled', false);
1215    // Reattach behaviors, if they were detached in beforeSerialize(), and the
1216    // form is still part of the document.
1217    if (this.$form && document.body.contains(this.$form.get(0))) {
1218      const settings = this.settings || drupalSettings;
1219      Drupal.attachBehaviors(this.$form.get(0), settings);
1220    }
1221    throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
1222  };
1223
1224  /**
1225   * Provide a wrapper for new content via Ajax.
1226   *
1227   * Wrap the inserted markup when inserting multiple root elements with an
1228   * ajax effect.
1229   *
1230   * @param {jQuery} $newContent
1231   *   Response elements after parsing.
1232   * @param {Drupal.Ajax} ajax
1233   *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1234   * @param {object} response
1235   *   The response from the Ajax request.
1236   *
1237   * @deprecated in drupal:8.6.0 and is removed from drupal:12.0.0.
1238   *   Use data with desired wrapper.
1239   *
1240   * @see https://www.drupal.org/node/2940704
1241   *
1242   * @todo Add deprecation warning after it is possible. For more information
1243   *   see: https://www.drupal.org/project/drupal/issues/2973400
1244   */
1245  Drupal.theme.ajaxWrapperNewContent = ($newContent, ajax, response) =>
1246    (response.effect || ajax.effect) !== 'none' &&
1247    $newContent.filter(
1248      (i) =>
1249        !(
1250          // We can not consider HTML comments or whitespace text as separate
1251          // roots, since they do not cause visual regression with effect.
1252          (
1253            $newContent[i].nodeName === '#comment' ||
1254            ($newContent[i].nodeName === '#text' &&
1255              /^(\s|\n|\r)*$/.test($newContent[i].textContent))
1256          )
1257        ),
1258    ).length > 1
1259      ? Drupal.theme('ajaxWrapperMultipleRootElements', $newContent)
1260      : $newContent;
1261
1262  /**
1263   * Provide a wrapper for multiple root elements via Ajax.
1264   *
1265   * @param {jQuery} $elements
1266   *   Response elements after parsing.
1267   *
1268   * @deprecated in drupal:8.6.0 and is removed from drupal:12.0.0.
1269   *   Use data with desired wrapper.
1270   *
1271   * @see https://www.drupal.org/node/2940704
1272   *
1273   * @todo Add deprecation warning after it is possible. For more information
1274   *   see: https://www.drupal.org/project/drupal/issues/2973400
1275   */
1276  Drupal.theme.ajaxWrapperMultipleRootElements = ($elements) =>
1277    $('<div></div>').append($elements);
1278
1279  /**
1280   * @typedef {object} Drupal.AjaxCommands~commandDefinition
1281   *
1282   * @prop {string} command
1283   * @prop {string} [method]
1284   * @prop {string} [selector]
1285   * @prop {string} [data]
1286   * @prop {object} [settings]
1287   * @prop {boolean} [asterisk]
1288   * @prop {string} [text]
1289   * @prop {string} [title]
1290   * @prop {string} [url]
1291   * @prop {object} [argument]
1292   * @prop {string} [name]
1293   * @prop {string} [value]
1294   * @prop {string} [old]
1295   * @prop {string} [new]
1296   * @prop {boolean} [merge]
1297   * @prop {Array} [args]
1298   *
1299   * @see Drupal.AjaxCommands
1300   */
1301
1302  /**
1303   * Provide a series of commands that the client will perform.
1304   *
1305   * @constructor
1306   */
1307  Drupal.AjaxCommands = function () {};
1308  Drupal.AjaxCommands.prototype = {
1309    /**
1310     * Command to insert new content into the DOM.
1311     *
1312     * @param {Drupal.Ajax} ajax
1313     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1314     * @param {object} response
1315     *   The response from the Ajax request.
1316     * @param {string} response.data
1317     *   The data to use with the jQuery method.
1318     * @param {string} [response.method]
1319     *   The jQuery DOM manipulation method to be used.
1320     * @param {string} [response.selector]
1321     *   An optional jQuery selector string.
1322     * @param {object} [response.settings]
1323     *   An optional array of settings that will be used.
1324     */
1325    insert(ajax, response) {
1326      // Get information from the response. If it is not there, default to
1327      // our presets.
1328      const $wrapper = response.selector
1329        ? $(response.selector)
1330        : $(ajax.wrapper);
1331      const method = response.method || ajax.method;
1332      const effect = ajax.getEffect(response);
1333
1334      // Apply any settings from the returned JSON if available.
1335      const settings = response.settings || ajax.settings || drupalSettings;
1336
1337      // Parse response.data into an element collection.
1338      const parseHTML = (htmlString) => {
1339        const fragment = document.createDocumentFragment();
1340        // Create a temporary template element.
1341        const template = fragment.appendChild(
1342          document.createElement('template'),
1343        );
1344
1345        // Set the innerHTML of the template to the provided HTML string.
1346        template.innerHTML = htmlString;
1347
1348        // Return the contents of the temporary template.
1349        return template.content.childNodes;
1350      };
1351
1352      let $newContent = $(parseHTML(response.data));
1353
1354      // For backward compatibility, in some cases a wrapper will be added. This
1355      // behavior will be removed before Drupal 9.0.0. If different behavior is
1356      // needed, the theme functions can be overridden.
1357      // @see https://www.drupal.org/node/2940704
1358      $newContent = Drupal.theme(
1359        'ajaxWrapperNewContent',
1360        $newContent,
1361        ajax,
1362        response,
1363      );
1364
1365      // If removing content from the wrapper, detach behaviors first.
1366      switch (method) {
1367        case 'html':
1368        case 'replaceWith':
1369        case 'replaceAll':
1370        case 'empty':
1371        case 'remove':
1372          Drupal.detachBehaviors($wrapper.get(0), settings);
1373          break;
1374        default:
1375          break;
1376      }
1377
1378      // Add the new content to the page.
1379      $wrapper[method]($newContent);
1380
1381      // Immediately hide the new content if we're using any effects.
1382      if (effect.showEffect !== 'show') {
1383        $newContent.hide();
1384      }
1385
1386      // Determine which effect to use and what content will receive the
1387      // effect, then show the new content.
1388      const $ajaxNewContent = $newContent.find('.ajax-new-content');
1389      if ($ajaxNewContent.length) {
1390        $ajaxNewContent.hide();
1391        $newContent.show();
1392        $ajaxNewContent[effect.showEffect](effect.showSpeed);
1393      } else if (effect.showEffect !== 'show') {
1394        $newContent[effect.showEffect](effect.showSpeed);
1395      }
1396
1397      // Attach behaviors to all element nodes.
1398      $newContent.each((index, element) => {
1399        if (
1400          element.nodeType === Node.ELEMENT_NODE &&
1401          // Attach all JavaScript behaviors to the new content, if it was
1402          // successfully added to the page, this condition allows
1403          // `#ajax['wrapper']` to be optional.
1404          document.documentElement.contains(element)
1405        ) {
1406          Drupal.attachBehaviors(element, settings);
1407        }
1408      });
1409    },
1410
1411    /**
1412     * Command to remove a chunk from the page.
1413     *
1414     * @param {Drupal.Ajax} [ajax]
1415     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1416     * @param {object} response
1417     *   The response from the Ajax request.
1418     * @param {string} response.selector
1419     *   A jQuery selector string.
1420     * @param {object} [response.settings]
1421     *   An optional array of settings that will be used.
1422     * @param {number} [status]
1423     *   The XMLHttpRequest status.
1424     */
1425    remove(ajax, response, status) {
1426      const settings = response.settings || ajax.settings || drupalSettings;
1427      $(response.selector)
1428        .each(function () {
1429          Drupal.detachBehaviors(this, settings);
1430        })
1431        .remove();
1432    },
1433
1434    /**
1435     * Command to mark a chunk changed.
1436     *
1437     * @param {Drupal.Ajax} [ajax]
1438     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1439     * @param {object} response
1440     *   The JSON response object from the Ajax request.
1441     * @param {string} response.selector
1442     *   A jQuery selector string.
1443     * @param {string} [response.asterisk]
1444     *   An optional CSS selector. If specified, an asterisk will be
1445     *   appended to the HTML inside the provided selector.
1446     * @param {number} [status]
1447     *   The request status.
1448     */
1449    changed(ajax, response, status) {
1450      const $element = $(response.selector);
1451      if (!$element.hasClass('ajax-changed')) {
1452        $element.addClass('ajax-changed');
1453        if (response.asterisk) {
1454          $element
1455            .find(response.asterisk)
1456            .append(
1457              ` <abbr class="ajax-changed" title="${Drupal.t(
1458                'Changed',
1459              )}">*</abbr> `,
1460            );
1461        }
1462      }
1463    },
1464
1465    /**
1466     * Command to provide an alert.
1467     *
1468     * @param {Drupal.Ajax} [ajax]
1469     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1470     * @param {object} response
1471     *   The JSON response from the Ajax request.
1472     * @param {string} response.text
1473     *   The text that will be displayed in an alert dialog.
1474     * @param {number} [status]
1475     *   The XMLHttpRequest status.
1476     */
1477    alert(ajax, response, status) {
1478      window.alert(response.text);
1479    },
1480
1481    /**
1482     * Command to provide triggers audio UAs to read the supplied text.
1483     *
1484     * @param {Drupal.Ajax} [ajax]
1485     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1486     * @param {object} response
1487     *   The JSON response from the Ajax request.
1488     * @param {string} [response.text]
1489     *   The text that will be read.
1490     * @param {string} [response.priority]
1491     *   An optional priority that will be used for the announcement.
1492     */
1493    announce(ajax, response) {
1494      if (response.priority) {
1495        Drupal.announce(response.text, response.priority);
1496      } else {
1497        Drupal.announce(response.text);
1498      }
1499    },
1500
1501    /**
1502     * Command to set the window.location, redirecting the browser.
1503     *
1504     * @param {Drupal.Ajax} [ajax]
1505     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1506     * @param {object} response
1507     *   The response from the Ajax request.
1508     * @param {string} response.url
1509     *   The URL to redirect to.
1510     * @param {number} [status]
1511     *   The XMLHttpRequest status.
1512     */
1513    redirect(ajax, response, status) {
1514      window.location = response.url;
1515    },
1516
1517    /**
1518     * Command to provide the jQuery css() function.
1519     *
1520     * @param {Drupal.Ajax} [ajax]
1521     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1522     * @param {object} response
1523     *   The response from the Ajax request.
1524     * @param {string} response.selector
1525     *   A jQuery selector string.
1526     * @param {object} response.argument
1527     *   An array of key/value pairs to set in the CSS for the selector.
1528     * @param {number} [status]
1529     *   The XMLHttpRequest status.
1530     */
1531    css(ajax, response, status) {
1532      // eslint-disable-next-line no-jquery/no-css
1533      $(response.selector).css(response.argument);
1534    },
1535
1536    /**
1537     * Command to set the settings used for other commands in this response.
1538     *
1539     * This method will also remove expired `drupalSettings.ajax` settings.
1540     *
1541     * @param {Drupal.Ajax} [ajax]
1542     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1543     * @param {object} response
1544     *   The response from the Ajax request.
1545     * @param {boolean} response.merge
1546     *   Determines whether the additional settings should be merged to the
1547     *   global settings.
1548     * @param {object} response.settings
1549     *   Contains additional settings to add to the global settings.
1550     * @param {number} [status]
1551     *   The XMLHttpRequest status.
1552     */
1553    settings(ajax, response, status) {
1554      const ajaxSettings = drupalSettings.ajax;
1555
1556      // Clean up drupalSettings.ajax.
1557      if (ajaxSettings) {
1558        Drupal.ajax.expired().forEach((instance) => {
1559          // If the Ajax object has been created through drupalSettings.ajax
1560          // it will have a selector. When there is no selector the object
1561          // has been initialized with a special class name picked up by the
1562          // Ajax behavior.
1563
1564          if (instance.selector) {
1565            const selector = instance.selector.replace('#', '');
1566            if (selector in ajaxSettings) {
1567              delete ajaxSettings[selector];
1568            }
1569          }
1570        });
1571      }
1572
1573      if (response.merge) {
1574        $.extend(true, drupalSettings, response.settings);
1575      } else {
1576        ajax.settings = response.settings;
1577      }
1578    },
1579
1580    /**
1581     * Command to attach data using jQuery's data API.
1582     *
1583     * @param {Drupal.Ajax} [ajax]
1584     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1585     * @param {object} response
1586     *   The response from the Ajax request.
1587     * @param {string} response.name
1588     *   The name or key (in the key value pair) of the data attached to this
1589     *   selector.
1590     * @param {string} response.selector
1591     *   A jQuery selector string.
1592     * @param {string|object} response.value
1593     *   The value of to be attached.
1594     * @param {number} [status]
1595     *   The XMLHttpRequest status.
1596     */
1597    data(ajax, response, status) {
1598      $(response.selector).data(response.name, response.value);
1599    },
1600
1601    /**
1602     * Command to focus the first tabbable element within a container.
1603     *
1604     * If no tabbable elements are found and the container is focusable, then
1605     * focus will move to that container.
1606     *
1607     * @param {Drupal.Ajax} [ajax]
1608     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1609     * @param {object} response
1610     *   The response from the Ajax request.
1611     * @param {string} response.selector
1612     *   A query selector string of the container to focus within.
1613     * @param {number} [status]
1614     *   The XMLHttpRequest status.
1615     */
1616    focusFirst(ajax, response, status) {
1617      let focusChanged = false;
1618      const container = document.querySelector(response.selector);
1619      if (container) {
1620        // Find all tabbable elements within the container.
1621        const tabbableElements = tabbable(container);
1622
1623        // Move focus to the first tabbable item found.
1624        if (tabbableElements.length) {
1625          tabbableElements[0].focus();
1626          focusChanged = true;
1627        } else if (isFocusable(container)) {
1628          // If no tabbable elements are found, but the container is focusable,
1629          // move focus to the container.
1630          container.focus();
1631          focusChanged = true;
1632        }
1633      }
1634
1635      // If no items were available to receive focus, return focus to the
1636      // triggering element.
1637      if (ajax.hasOwnProperty('element') && !focusChanged) {
1638        ajax.element.focus();
1639      }
1640    },
1641
1642    /**
1643     * Command to apply a jQuery method.
1644     *
1645     * @param {Drupal.Ajax} [ajax]
1646     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1647     * @param {object} response
1648     *   The response from the Ajax request.
1649     * @param {Array} response.args
1650     *   An array of arguments to the jQuery method, if any.
1651     * @param {string} response.method
1652     *   The jQuery method to invoke.
1653     * @param {string} response.selector
1654     *   A jQuery selector string.
1655     * @param {number} [status]
1656     *   The XMLHttpRequest status.
1657     */
1658    invoke(ajax, response, status) {
1659      const $element = $(response.selector);
1660      $element[response.method](...response.args);
1661    },
1662
1663    /**
1664     * Command to restripe a table.
1665     *
1666     * @param {Drupal.Ajax} [ajax]
1667     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1668     * @param {object} response
1669     *   The response from the Ajax request.
1670     * @param {string} response.selector
1671     *   A jQuery selector string.
1672     * @param {number} [status]
1673     *   The XMLHttpRequest status.
1674     */
1675    restripe(ajax, response, status) {
1676      // :even and :odd are reversed because jQuery counts from 0 and
1677      // we count from 1, so we're out of sync.
1678      // Match immediate children of the parent element to allow nesting.
1679      $(response.selector)
1680        .find('> tbody > tr:visible, > tr:visible')
1681        .removeClass('odd even')
1682        .filter(':even')
1683        .addClass('odd')
1684        .end()
1685        .filter(':odd')
1686        .addClass('even');
1687    },
1688
1689    /**
1690     * Command to update a form's build ID.
1691     *
1692     * @param {Drupal.Ajax} [ajax]
1693     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1694     * @param {object} response
1695     *   The response from the Ajax request.
1696     * @param {string} response.old
1697     *   The old form build ID.
1698     * @param {string} response.new
1699     *   The new form build ID.
1700     * @param {number} [status]
1701     *   The XMLHttpRequest status.
1702     */
1703    update_build_id(ajax, response, status) {
1704      document
1705        .querySelectorAll(
1706          `input[name="form_build_id"][value="${response.old}"]`,
1707        )
1708        .forEach((item) => {
1709          item.value = response.new;
1710        });
1711    },
1712
1713    /**
1714     * Command to add css.
1715     *
1716     * @param {Drupal.Ajax} [ajax]
1717     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1718     * @param {object} response
1719     *   The response from the Ajax request.
1720     * @param {object[]} response.data
1721     *   An array of styles to be added.
1722     * @param {number} [status]
1723     *   The XMLHttpRequest status.
1724     */
1725    add_css(ajax, response, status) {
1726      const allUniqueBundleIds = response.data.map(function (style) {
1727        const uniqueBundleId = style.href;
1728        // Force file to load as a CSS stylesheet using 'css!' flag.
1729        if (!loadjs.isDefined(uniqueBundleId)) {
1730          loadjs(`css!${style.href}`, uniqueBundleId, {
1731            before(path, styleEl) {
1732              // This allows all attributes to be added, like media.
1733              Object.keys(style).forEach((attributeKey) => {
1734                styleEl.setAttribute(attributeKey, style[attributeKey]);
1735              });
1736            },
1737          });
1738        }
1739        return uniqueBundleId;
1740      });
1741      // Returns the promise so that the next AJAX command waits on the
1742      // completion of this one to execute, ensuring the CSS is loaded before
1743      // executing.
1744      return new Promise((resolve, reject) => {
1745        loadjs.ready(allUniqueBundleIds, {
1746          success() {
1747            // All CSS files were loaded. Resolve the promise and let the
1748            // remaining commands execute.
1749            resolve();
1750          },
1751          error(depsNotFound) {
1752            const message = Drupal.t(
1753              `The following files could not be loaded: @dependencies`,
1754              { '@dependencies': depsNotFound.join(', ') },
1755            );
1756            reject(message);
1757          },
1758        });
1759      });
1760    },
1761
1762    /**
1763     * Command to add a message to the message area.
1764     *
1765     * @param {Drupal.Ajax} [ajax]
1766     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1767     * @param {object} response
1768     *   The response from the Ajax request.
1769     * @param {string} response.messageWrapperQuerySelector
1770     *   The zone where to add the message. If null, the default will be used.
1771     * @param {string} response.message
1772     *   The message text.
1773     * @param {string} response.messageOptions
1774     *   The options argument for Drupal.Message().add().
1775     * @param {boolean} response.clearPrevious
1776     *   If true, clear previous messages.
1777     */
1778    message(ajax, response) {
1779      const messages = new Drupal.Message(
1780        document.querySelector(response.messageWrapperQuerySelector),
1781      );
1782      if (response.clearPrevious) {
1783        messages.clear();
1784      }
1785      messages.add(response.message, response.messageOptions);
1786    },
1787
1788    /**
1789     * Command to add JS.
1790     *
1791     * @param {Drupal.Ajax} [ajax]
1792     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1793     * @param {object} response
1794     *   The response from the Ajax request.
1795     * @param {Array} response.data
1796     *   An array of objects of script attributes.
1797     * @param {number} [status]
1798     *   The XMLHttpRequest status.
1799     */
1800    add_js(ajax, response, status) {
1801      const parentEl = document.querySelector(response.selector || 'body');
1802      const settings = ajax.settings || drupalSettings;
1803      const allUniqueBundleIds = response.data.map((script) => {
1804        const uniqueBundleId = script.src;
1805        if (!loadjs.isDefined(uniqueBundleId)) {
1806          loadjs(script.src, uniqueBundleId, {
1807            // The default loadjs behavior is to load script with async, in Drupal
1808            // we need to explicitly tell scripts to load async, this is set in
1809            // the before callback below if necessary.
1810            async: false,
1811            before(path, scriptEl) {
1812              // This allows all attributes to be added, like defer, async and
1813              // crossorigin.
1814              Object.keys(script).forEach((attributeKey) => {
1815                scriptEl.setAttribute(attributeKey, script[attributeKey]);
1816              });
1817
1818              // By default, loadjs appends the script to the head. When scripts
1819              // are loaded via AJAX, their location has no impact on
1820              // functionality. But, since non-AJAX loaded scripts can choose
1821              // their parent element, we provide that option here for the sake of
1822              // consistency.
1823              parentEl.appendChild(scriptEl);
1824              // Return false to bypass loadjs' default DOM insertion mechanism.
1825              return false;
1826            },
1827          });
1828        }
1829        return uniqueBundleId;
1830      });
1831      // Returns the promise so that the next AJAX command waits on the
1832      // completion of this one to execute, ensuring the JS is loaded before
1833      // executing.
1834      return new Promise((resolve, reject) => {
1835        loadjs.ready(allUniqueBundleIds, {
1836          success() {
1837            Drupal.attachBehaviors(parentEl, settings);
1838            // All JS files were loaded and new and old behaviors have
1839            // been attached. Resolve the promise and let the remaining
1840            // commands execute.
1841            resolve();
1842          },
1843          error(depsNotFound) {
1844            const message = Drupal.t(
1845              `The following files could not be loaded: @dependencies`,
1846              { '@dependencies': depsNotFound.join(', ') },
1847            );
1848            reject(message);
1849          },
1850        });
1851      });
1852    },
1853
1854    /**
1855     * Command to scroll the page to an html element.
1856     *
1857     * @param {Drupal.Ajax} [ajax]
1858     *   A {@link Drupal.ajax} object.
1859     * @param {object} response
1860     *   Ajax response.
1861     * @param {string} response.selector
1862     *   Selector to use.
1863     */
1864    scrollTop(ajax, response) {
1865      document.querySelector(response.selector)?.scrollIntoView();
1866    },
1867  };
1868
1869  /**
1870   * Delay jQuery's global completion events until after commands have executed.
1871   *
1872   * jQuery triggers the ajaxSuccess, ajaxComplete, and ajaxStop events after
1873   * a successful response is returned and local success and complete events
1874   * are triggered. However, Drupal Ajax responses contain commands that run
1875   * asynchronously in a queue, so the following stops these events from getting
1876   * triggered until after the Promise that executes the command queue is
1877   * resolved.
1878   */
1879  const stopEvent = (xhr, settings) => {
1880    return (
1881      // Only interfere with Drupal's Ajax responses.
1882      xhr.getResponseHeader('X-Drupal-Ajax-Token') === '1' &&
1883      // The isInProgress() function might not be defined if the Ajax request
1884      // was initiated without Drupal.ajax() or new Drupal.Ajax().
1885      typeof settings.isInProgress === 'function' &&
1886      // Until this is false, the Ajax request isn't completely done (the
1887      // response's commands might still be running).
1888      settings.isInProgress()
1889    );
1890  };
1891  $.extend(true, $.event.special, {
1892    ajaxSuccess: {
1893      trigger(event, xhr, settings) {
1894        if (stopEvent(xhr, settings)) {
1895          return false;
1896        }
1897      },
1898    },
1899    ajaxComplete: {
1900      trigger(event, xhr, settings) {
1901        if (stopEvent(xhr, settings)) {
1902          // jQuery decrements its internal active ajax counter even when we
1903          // stop the ajaxComplete event, but we don't want that counter
1904          // decremented, because for our purposes this request is still active
1905          // while commands are executing. By incrementing it here, the net
1906          // effect is that it remains unchanged. By remaining above 0, the
1907          // ajaxStop event is also prevented.
1908          $.active++;
1909          return false;
1910        }
1911      },
1912    },
1913  });
1914})(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.