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