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