ajax.es6.js 48 KB

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