ajax.es6.js 52 KB

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