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