PageSourceSearch

https://www.nsws.gov.in/core/misc/ajax.js?v=10.1.6

js nsws.gov.in collected 2026-10-02 05:01:09 UTC 65,621 bytes, 1,889 lines download raw bytes

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