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