ajax.es6.js 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  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. type: 'POST',
  523. };
  524. if (elementSettings.dialog) {
  525. ajax.options.data.dialogOptions = elementSettings.dialog;
  526. }
  527. // Ensure that we have a valid URL by adding ? when no query parameter is
  528. // yet available, otherwise append using &.
  529. if (ajax.options.url.indexOf('?') === -1) {
  530. ajax.options.url += '?';
  531. } else {
  532. ajax.options.url += '&';
  533. }
  534. // If this element has a dialog type use if for the wrapper if not use 'ajax'.
  535. let wrapper = `drupal_${elementSettings.dialogType || 'ajax'}`;
  536. if (elementSettings.dialogRenderer) {
  537. wrapper += `.${elementSettings.dialogRenderer}`;
  538. }
  539. ajax.options.url += `${Drupal.ajax.WRAPPER_FORMAT}=${wrapper}`;
  540. // Bind the ajaxSubmit function to the element event.
  541. $(ajax.element).on(elementSettings.event, function(event) {
  542. if (
  543. !drupalSettings.ajaxTrustedUrl[ajax.url] &&
  544. !Drupal.url.isLocal(ajax.url)
  545. ) {
  546. throw new Error(
  547. Drupal.t('The callback URL is not local and not trusted: !url', {
  548. '!url': ajax.url,
  549. }),
  550. );
  551. }
  552. return ajax.eventResponse(this, event);
  553. });
  554. // If necessary, enable keyboard submission so that Ajax behaviors
  555. // can be triggered through keyboard input as well as e.g. a mousedown
  556. // action.
  557. if (elementSettings.keypress) {
  558. $(ajax.element).on('keypress', function(event) {
  559. return ajax.keypressResponse(this, event);
  560. });
  561. }
  562. // If necessary, prevent the browser default action of an additional event.
  563. // For example, prevent the browser default action of a click, even if the
  564. // Ajax behavior binds to mousedown.
  565. if (elementSettings.prevent) {
  566. $(ajax.element).on(elementSettings.prevent, false);
  567. }
  568. };
  569. /**
  570. * URL query attribute to indicate the wrapper used to render a request.
  571. *
  572. * The wrapper format determines how the HTML is wrapped, for example in a
  573. * modal dialog.
  574. *
  575. * @const {string}
  576. *
  577. * @default
  578. */
  579. Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
  580. /**
  581. * Request parameter to indicate that a request is a Drupal Ajax request.
  582. *
  583. * @const {string}
  584. *
  585. * @default
  586. */
  587. Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
  588. /**
  589. * Execute the ajax request.
  590. *
  591. * Allows developers to execute an Ajax request manually without specifying
  592. * an event to respond to.
  593. *
  594. * @return {object}
  595. * Returns the jQuery.Deferred object underlying the Ajax request. If
  596. * pre-serialization fails, the Deferred will be returned in the rejected
  597. * state.
  598. */
  599. Drupal.Ajax.prototype.execute = function() {
  600. // Do not perform another ajax command if one is already in progress.
  601. if (this.ajaxing) {
  602. return;
  603. }
  604. try {
  605. this.beforeSerialize(this.element, this.options);
  606. // Return the jqXHR so that external code can hook into the Deferred API.
  607. return $.ajax(this.options);
  608. } catch (e) {
  609. // Unset the ajax.ajaxing flag here because it won't be unset during
  610. // the complete response.
  611. this.ajaxing = false;
  612. window.alert(
  613. `An error occurred while attempting to process ${this.options.url}: ${e.message}`,
  614. );
  615. // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
  616. // so that calling code can take appropriate action.
  617. return $.Deferred().reject();
  618. }
  619. };
  620. /**
  621. * Handle a key press.
  622. *
  623. * The Ajax object will, if instructed, bind to a key press response. This
  624. * will test to see if the key press is valid to trigger this event and
  625. * if it is, trigger it for us and prevent other keypresses from triggering.
  626. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
  627. * and 32. RETURN is often used to submit a form when in a textfield, and
  628. * SPACE is often used to activate an element without submitting.
  629. *
  630. * @param {HTMLElement} element
  631. * Element the event was triggered on.
  632. * @param {jQuery.Event} event
  633. * Triggered event.
  634. */
  635. Drupal.Ajax.prototype.keypressResponse = function(element, event) {
  636. // Create a synonym for this to reduce code confusion.
  637. const ajax = this;
  638. // Detect enter key and space bar and allow the standard response for them,
  639. // except for form elements of type 'text', 'tel', 'number' and 'textarea',
  640. // where the spacebar activation causes inappropriate activation if
  641. // #ajax['keypress'] is TRUE. On a text-type widget a space should always
  642. // be a space.
  643. if (
  644. event.which === 13 ||
  645. (event.which === 32 &&
  646. element.type !== 'text' &&
  647. element.type !== 'textarea' &&
  648. element.type !== 'tel' &&
  649. element.type !== 'number')
  650. ) {
  651. event.preventDefault();
  652. event.stopPropagation();
  653. $(element).trigger(ajax.elementSettings.event);
  654. }
  655. };
  656. /**
  657. * Handle an event that triggers an Ajax response.
  658. *
  659. * When an event that triggers an Ajax response happens, this method will
  660. * perform the actual Ajax call. It is bound to the event using
  661. * bind() in the constructor, and it uses the options specified on the
  662. * Ajax object.
  663. *
  664. * @param {HTMLElement} element
  665. * Element the event was triggered on.
  666. * @param {jQuery.Event} event
  667. * Triggered event.
  668. */
  669. Drupal.Ajax.prototype.eventResponse = function(element, event) {
  670. event.preventDefault();
  671. event.stopPropagation();
  672. // Create a synonym for this to reduce code confusion.
  673. const ajax = this;
  674. // Do not perform another Ajax command if one is already in progress.
  675. if (ajax.ajaxing) {
  676. return;
  677. }
  678. try {
  679. if (ajax.$form) {
  680. // If setClick is set, we must set this to ensure that the button's
  681. // value is passed.
  682. if (ajax.setClick) {
  683. // Mark the clicked button. 'form.clk' is a special variable for
  684. // ajaxSubmit that tells the system which element got clicked to
  685. // trigger the submit. Without it there would be no 'op' or
  686. // equivalent.
  687. element.form.clk = element;
  688. }
  689. ajax.$form.ajaxSubmit(ajax.options);
  690. } else {
  691. ajax.beforeSerialize(ajax.element, ajax.options);
  692. $.ajax(ajax.options);
  693. }
  694. } catch (e) {
  695. // Unset the ajax.ajaxing flag here because it won't be unset during
  696. // the complete response.
  697. ajax.ajaxing = false;
  698. window.alert(
  699. `An error occurred while attempting to process ${ajax.options.url}: ${e.message}`,
  700. );
  701. }
  702. };
  703. /**
  704. * Handler for the form serialization.
  705. *
  706. * Runs before the beforeSend() handler (see below), and unlike that one, runs
  707. * before field data is collected.
  708. *
  709. * @param {object} [element]
  710. * Ajax object's `elementSettings`.
  711. * @param {object} options
  712. * jQuery.ajax options.
  713. */
  714. Drupal.Ajax.prototype.beforeSerialize = function(element, options) {
  715. // Allow detaching behaviors to update field values before collecting them.
  716. // This is only needed when field values are added to the POST data, so only
  717. // when there is a form such that this.$form.ajaxSubmit() is used instead of
  718. // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
  719. // isn't called, but don't rely on that: explicitly check this.$form.
  720. if (this.$form && document.body.contains(this.$form.get(0))) {
  721. const settings = this.settings || drupalSettings;
  722. Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
  723. }
  724. // Inform Drupal that this is an AJAX request.
  725. options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
  726. // Allow Drupal to return new JavaScript and CSS files to load without
  727. // returning the ones already loaded.
  728. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator
  729. // @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
  730. // @see system_js_settings_alter()
  731. const pageState = drupalSettings.ajaxPageState;
  732. options.data['ajax_page_state[theme]'] = pageState.theme;
  733. options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
  734. options.data['ajax_page_state[libraries]'] = pageState.libraries;
  735. };
  736. /**
  737. * Modify form values prior to form submission.
  738. *
  739. * @param {Array.<object>} formValues
  740. * Processed form values.
  741. * @param {jQuery} element
  742. * The form node as a jQuery object.
  743. * @param {object} options
  744. * jQuery.ajax options.
  745. */
  746. Drupal.Ajax.prototype.beforeSubmit = function(formValues, element, options) {
  747. // This function is left empty to make it simple to override for modules
  748. // that wish to add functionality here.
  749. };
  750. /**
  751. * Prepare the Ajax request before it is sent.
  752. *
  753. * @param {XMLHttpRequest} xmlhttprequest
  754. * Native Ajax object.
  755. * @param {object} options
  756. * jQuery.ajax options.
  757. */
  758. Drupal.Ajax.prototype.beforeSend = function(xmlhttprequest, options) {
  759. // For forms without file inputs, the jQuery Form plugin serializes the
  760. // form values, and then calls jQuery's $.ajax() function, which invokes
  761. // this handler. In this circumstance, options.extraData is never used. For
  762. // forms with file inputs, the jQuery Form plugin uses the browser's normal
  763. // form submission mechanism, but captures the response in a hidden IFRAME.
  764. // In this circumstance, it calls this handler first, and then appends
  765. // hidden fields to the form to submit the values in options.extraData.
  766. // There is no simple way to know which submission mechanism will be used,
  767. // so we add to extraData regardless, and allow it to be ignored in the
  768. // former case.
  769. if (this.$form) {
  770. options.extraData = options.extraData || {};
  771. // Let the server know when the IFRAME submission mechanism is used. The
  772. // server can use this information to wrap the JSON response in a
  773. // TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
  774. options.extraData.ajax_iframe_upload = '1';
  775. // The triggering element is about to be disabled (see below), but if it
  776. // contains a value (e.g., a checkbox, textfield, select, etc.), ensure
  777. // that value is included in the submission. As per above, submissions
  778. // that use $.ajax() are already serialized prior to the element being
  779. // disabled, so this is only needed for IFRAME submissions.
  780. const v = $.fieldValue(this.element);
  781. if (v !== null) {
  782. options.extraData[this.element.name] = v;
  783. }
  784. }
  785. // Disable the element that received the change to prevent user interface
  786. // interaction while the Ajax request is in progress. ajax.ajaxing prevents
  787. // the element from triggering a new request, but does not prevent the user
  788. // from changing its value.
  789. $(this.element).prop('disabled', true);
  790. if (!this.progress || !this.progress.type) {
  791. return;
  792. }
  793. // Insert progress indicator.
  794. const progressIndicatorMethod = `setProgressIndicator${this.progress.type
  795. .slice(0, 1)
  796. .toUpperCase()}${this.progress.type.slice(1).toLowerCase()}`;
  797. if (
  798. progressIndicatorMethod in this &&
  799. typeof this[progressIndicatorMethod] === 'function'
  800. ) {
  801. this[progressIndicatorMethod].call(this);
  802. }
  803. };
  804. /**
  805. * An animated progress throbber and container element for AJAX operations.
  806. *
  807. * @param {string} [message]
  808. * (optional) The message shown on the UI.
  809. * @return {string}
  810. * The HTML markup for the throbber.
  811. */
  812. Drupal.theme.ajaxProgressThrobber = message => {
  813. // Build markup without adding extra white space since it affects rendering.
  814. const messageMarkup =
  815. typeof message === 'string'
  816. ? Drupal.theme('ajaxProgressMessage', message)
  817. : '';
  818. const throbber = '<div class="throbber">&nbsp;</div>';
  819. return `<div class="ajax-progress ajax-progress-throbber">${throbber}${messageMarkup}</div>`;
  820. };
  821. /**
  822. * An animated progress throbber and container element for AJAX operations.
  823. *
  824. * @return {string}
  825. * The HTML markup for the throbber.
  826. */
  827. Drupal.theme.ajaxProgressIndicatorFullscreen = () =>
  828. '<div class="ajax-progress ajax-progress-fullscreen">&nbsp;</div>';
  829. /**
  830. * Formats text accompanying the AJAX progress throbber.
  831. *
  832. * @param {string} message
  833. * The message shown on the UI.
  834. * @return {string}
  835. * The HTML markup for the throbber.
  836. */
  837. Drupal.theme.ajaxProgressMessage = message =>
  838. `<div class="message">${message}</div>`;
  839. /**
  840. * Provide a wrapper for the AJAX progress bar element.
  841. *
  842. * @param {jQuery} $element
  843. * Progress bar element.
  844. * @return {string}
  845. * The HTML markup for the progress bar.
  846. */
  847. Drupal.theme.ajaxProgressBar = $element =>
  848. $('<div class="ajax-progress ajax-progress-bar"></div>').append($element);
  849. /**
  850. * Sets the progress bar progress indicator.
  851. */
  852. Drupal.Ajax.prototype.setProgressIndicatorBar = function() {
  853. const progressBar = new Drupal.ProgressBar(
  854. `ajax-progress-${this.element.id}`,
  855. $.noop,
  856. this.progress.method,
  857. $.noop,
  858. );
  859. if (this.progress.message) {
  860. progressBar.setProgress(-1, this.progress.message);
  861. }
  862. if (this.progress.url) {
  863. progressBar.startMonitoring(
  864. this.progress.url,
  865. this.progress.interval || 1500,
  866. );
  867. }
  868. this.progress.element = $(
  869. Drupal.theme('ajaxProgressBar', progressBar.element),
  870. );
  871. this.progress.object = progressBar;
  872. $(this.element).after(this.progress.element);
  873. };
  874. /**
  875. * Sets the throbber progress indicator.
  876. */
  877. Drupal.Ajax.prototype.setProgressIndicatorThrobber = function() {
  878. this.progress.element = $(
  879. Drupal.theme('ajaxProgressThrobber', this.progress.message),
  880. );
  881. $(this.element).after(this.progress.element);
  882. };
  883. /**
  884. * Sets the fullscreen progress indicator.
  885. */
  886. Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function() {
  887. this.progress.element = $(Drupal.theme('ajaxProgressIndicatorFullscreen'));
  888. $('body').append(this.progress.element);
  889. };
  890. /**
  891. * Handler for the form redirection completion.
  892. *
  893. * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
  894. * Drupal Ajax response.
  895. * @param {number} status
  896. * XMLHttpRequest status.
  897. */
  898. Drupal.Ajax.prototype.success = function(response, status) {
  899. // Remove the progress element.
  900. if (this.progress.element) {
  901. $(this.progress.element).remove();
  902. }
  903. if (this.progress.object) {
  904. this.progress.object.stopMonitoring();
  905. }
  906. $(this.element).prop('disabled', false);
  907. // Save element's ancestors tree so if the element is removed from the dom
  908. // we can try to refocus one of its parents. Using addBack reverse the
  909. // result array, meaning that index 0 is the highest parent in the hierarchy
  910. // in this situation it is usually a <form> element.
  911. const elementParents = $(this.element)
  912. .parents('[data-drupal-selector]')
  913. .addBack()
  914. .toArray();
  915. // Track if any command is altering the focus so we can avoid changing the
  916. // focus set by the Ajax command.
  917. let focusChanged = false;
  918. Object.keys(response || {}).forEach(i => {
  919. if (response[i].command && this.commands[response[i].command]) {
  920. this.commands[response[i].command](this, response[i], status);
  921. if (
  922. response[i].command === 'invoke' &&
  923. response[i].method === 'focus'
  924. ) {
  925. focusChanged = true;
  926. }
  927. }
  928. });
  929. // If the focus hasn't be changed by the ajax commands, try to refocus the
  930. // triggering element or one of its parents if that element does not exist
  931. // anymore.
  932. if (
  933. !focusChanged &&
  934. this.element &&
  935. !$(this.element).data('disable-refocus')
  936. ) {
  937. let target = false;
  938. for (let n = elementParents.length - 1; !target && n >= 0; n--) {
  939. target = document.querySelector(
  940. `[data-drupal-selector="${elementParents[n].getAttribute(
  941. 'data-drupal-selector',
  942. )}"]`,
  943. );
  944. }
  945. if (target) {
  946. $(target).trigger('focus');
  947. }
  948. }
  949. // Reattach behaviors, if they were detached in beforeSerialize(). The
  950. // attachBehaviors() called on the new content from processing the response
  951. // commands is not sufficient, because behaviors from the entire form need
  952. // to be reattached.
  953. if (this.$form && document.body.contains(this.$form.get(0))) {
  954. const settings = this.settings || drupalSettings;
  955. Drupal.attachBehaviors(this.$form.get(0), settings);
  956. }
  957. // Remove any response-specific settings so they don't get used on the next
  958. // call by mistake.
  959. this.settings = null;
  960. };
  961. /**
  962. * Build an effect object to apply an effect when adding new HTML.
  963. *
  964. * @param {object} response
  965. * Drupal Ajax response.
  966. * @param {string} [response.effect]
  967. * Override the default value of {@link Drupal.Ajax#elementSettings}.
  968. * @param {string|number} [response.speed]
  969. * Override the default value of {@link Drupal.Ajax#elementSettings}.
  970. *
  971. * @return {object}
  972. * Returns an object with `showEffect`, `hideEffect` and `showSpeed`
  973. * properties.
  974. */
  975. Drupal.Ajax.prototype.getEffect = function(response) {
  976. const type = response.effect || this.effect;
  977. const speed = response.speed || this.speed;
  978. const effect = {};
  979. if (type === 'none') {
  980. effect.showEffect = 'show';
  981. effect.hideEffect = 'hide';
  982. effect.showSpeed = '';
  983. } else if (type === 'fade') {
  984. effect.showEffect = 'fadeIn';
  985. effect.hideEffect = 'fadeOut';
  986. effect.showSpeed = speed;
  987. } else {
  988. effect.showEffect = `${type}Toggle`;
  989. effect.hideEffect = `${type}Toggle`;
  990. effect.showSpeed = speed;
  991. }
  992. return effect;
  993. };
  994. /**
  995. * Handler for the form redirection error.
  996. *
  997. * @param {object} xmlhttprequest
  998. * Native XMLHttpRequest object.
  999. * @param {string} uri
  1000. * Ajax Request URI.
  1001. * @param {string} [customMessage]
  1002. * Extra message to print with the Ajax error.
  1003. */
  1004. Drupal.Ajax.prototype.error = function(xmlhttprequest, uri, customMessage) {
  1005. // Remove the progress element.
  1006. if (this.progress.element) {
  1007. $(this.progress.element).remove();
  1008. }
  1009. if (this.progress.object) {
  1010. this.progress.object.stopMonitoring();
  1011. }
  1012. // Undo hide.
  1013. $(this.wrapper).show();
  1014. // Re-enable the element.
  1015. $(this.element).prop('disabled', false);
  1016. // Reattach behaviors, if they were detached in beforeSerialize(), and the
  1017. // form is still part of the document.
  1018. if (this.$form && document.body.contains(this.$form.get(0))) {
  1019. const settings = this.settings || drupalSettings;
  1020. Drupal.attachBehaviors(this.$form.get(0), settings);
  1021. }
  1022. throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
  1023. };
  1024. /**
  1025. * Provide a wrapper for new content via Ajax.
  1026. *
  1027. * Wrap the inserted markup when inserting multiple root elements with an
  1028. * ajax effect.
  1029. *
  1030. * @param {jQuery} $newContent
  1031. * Response elements after parsing.
  1032. * @param {Drupal.Ajax} ajax
  1033. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1034. * @param {object} response
  1035. * The response from the Ajax request.
  1036. *
  1037. * @deprecated in drupal:8.6.0 and is removed from drupal:10.0.0.
  1038. * Use data with desired wrapper.
  1039. *
  1040. * @see https://www.drupal.org/node/2940704
  1041. *
  1042. * @todo Add deprecation warning after it is possible. For more information
  1043. * see: https://www.drupal.org/project/drupal/issues/2973400
  1044. */
  1045. Drupal.theme.ajaxWrapperNewContent = ($newContent, ajax, response) =>
  1046. (response.effect || ajax.effect) !== 'none' &&
  1047. $newContent.filter(
  1048. i =>
  1049. !(
  1050. // We can not consider HTML comments or whitespace text as separate
  1051. // roots, since they do not cause visual regression with effect.
  1052. (
  1053. $newContent[i].nodeName === '#comment' ||
  1054. ($newContent[i].nodeName === '#text' &&
  1055. /^(\s|\n|\r)*$/.test($newContent[i].textContent))
  1056. )
  1057. ),
  1058. ).length > 1
  1059. ? Drupal.theme('ajaxWrapperMultipleRootElements', $newContent)
  1060. : $newContent;
  1061. /**
  1062. * Provide a wrapper for multiple root elements via Ajax.
  1063. *
  1064. * @param {jQuery} $elements
  1065. * Response elements after parsing.
  1066. *
  1067. * @deprecated in drupal:8.6.0 and is removed from drupal:10.0.0.
  1068. * Use data with desired wrapper.
  1069. *
  1070. * @see https://www.drupal.org/node/2940704
  1071. *
  1072. * @todo Add deprecation warning after it is possible. For more information
  1073. * see: https://www.drupal.org/project/drupal/issues/2973400
  1074. */
  1075. Drupal.theme.ajaxWrapperMultipleRootElements = $elements =>
  1076. $('<div></div>').append($elements);
  1077. /**
  1078. * @typedef {object} Drupal.AjaxCommands~commandDefinition
  1079. *
  1080. * @prop {string} command
  1081. * @prop {string} [method]
  1082. * @prop {string} [selector]
  1083. * @prop {string} [data]
  1084. * @prop {object} [settings]
  1085. * @prop {bool} [asterisk]
  1086. * @prop {string} [text]
  1087. * @prop {string} [title]
  1088. * @prop {string} [url]
  1089. * @prop {object} [argument]
  1090. * @prop {string} [name]
  1091. * @prop {string} [value]
  1092. * @prop {string} [old]
  1093. * @prop {string} [new]
  1094. * @prop {bool} [merge]
  1095. * @prop {Array} [args]
  1096. *
  1097. * @see Drupal.AjaxCommands
  1098. */
  1099. /**
  1100. * Provide a series of commands that the client will perform.
  1101. *
  1102. * @constructor
  1103. */
  1104. Drupal.AjaxCommands = function() {};
  1105. Drupal.AjaxCommands.prototype = {
  1106. /**
  1107. * Command to insert new content into the DOM.
  1108. *
  1109. * @param {Drupal.Ajax} ajax
  1110. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1111. * @param {object} response
  1112. * The response from the Ajax request.
  1113. * @param {string} response.data
  1114. * The data to use with the jQuery method.
  1115. * @param {string} [response.method]
  1116. * The jQuery DOM manipulation method to be used.
  1117. * @param {string} [response.selector]
  1118. * A optional jQuery selector string.
  1119. * @param {object} [response.settings]
  1120. * An optional array of settings that will be used.
  1121. */
  1122. insert(ajax, response) {
  1123. // Get information from the response. If it is not there, default to
  1124. // our presets.
  1125. const $wrapper = response.selector
  1126. ? $(response.selector)
  1127. : $(ajax.wrapper);
  1128. const method = response.method || ajax.method;
  1129. const effect = ajax.getEffect(response);
  1130. // Apply any settings from the returned JSON if available.
  1131. const settings = response.settings || ajax.settings || drupalSettings;
  1132. // Parse response.data into an element collection.
  1133. let $newContent = $($.parseHTML(response.data, document, true));
  1134. // For backward compatibility, in some cases a wrapper will be added. This
  1135. // behavior will be removed before Drupal 9.0.0. If different behavior is
  1136. // needed, the theme functions can be overriden.
  1137. // @see https://www.drupal.org/node/2940704
  1138. $newContent = Drupal.theme(
  1139. 'ajaxWrapperNewContent',
  1140. $newContent,
  1141. ajax,
  1142. response,
  1143. );
  1144. // If removing content from the wrapper, detach behaviors first.
  1145. switch (method) {
  1146. case 'html':
  1147. case 'replaceWith':
  1148. case 'replaceAll':
  1149. case 'empty':
  1150. case 'remove':
  1151. Drupal.detachBehaviors($wrapper.get(0), settings);
  1152. break;
  1153. default:
  1154. break;
  1155. }
  1156. // Add the new content to the page.
  1157. $wrapper[method]($newContent);
  1158. // Immediately hide the new content if we're using any effects.
  1159. if (effect.showEffect !== 'show') {
  1160. $newContent.hide();
  1161. }
  1162. // Determine which effect to use and what content will receive the
  1163. // effect, then show the new content.
  1164. const $ajaxNewContent = $newContent.find('.ajax-new-content');
  1165. if ($ajaxNewContent.length) {
  1166. $ajaxNewContent.hide();
  1167. $newContent.show();
  1168. $ajaxNewContent[effect.showEffect](effect.showSpeed);
  1169. } else if (effect.showEffect !== 'show') {
  1170. $newContent[effect.showEffect](effect.showSpeed);
  1171. }
  1172. // Attach all JavaScript behaviors to the new content, if it was
  1173. // successfully added to the page, this if statement allows
  1174. // `#ajax['wrapper']` to be optional.
  1175. if ($newContent.parents('html').length) {
  1176. // Attach behaviors to all element nodes.
  1177. $newContent.each((index, element) => {
  1178. if (element.nodeType === Node.ELEMENT_NODE) {
  1179. Drupal.attachBehaviors(element, settings);
  1180. }
  1181. });
  1182. }
  1183. },
  1184. /**
  1185. * Command to remove a chunk from the page.
  1186. *
  1187. * @param {Drupal.Ajax} [ajax]
  1188. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1189. * @param {object} response
  1190. * The response from the Ajax request.
  1191. * @param {string} response.selector
  1192. * A jQuery selector string.
  1193. * @param {object} [response.settings]
  1194. * An optional array of settings that will be used.
  1195. * @param {number} [status]
  1196. * The XMLHttpRequest status.
  1197. */
  1198. remove(ajax, response, status) {
  1199. const settings = response.settings || ajax.settings || drupalSettings;
  1200. $(response.selector)
  1201. .each(function() {
  1202. Drupal.detachBehaviors(this, settings);
  1203. })
  1204. .remove();
  1205. },
  1206. /**
  1207. * Command to mark a chunk changed.
  1208. *
  1209. * @param {Drupal.Ajax} [ajax]
  1210. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1211. * @param {object} response
  1212. * The JSON response object from the Ajax request.
  1213. * @param {string} response.selector
  1214. * A jQuery selector string.
  1215. * @param {bool} [response.asterisk]
  1216. * An optional CSS selector. If specified, an asterisk will be
  1217. * appended to the HTML inside the provided selector.
  1218. * @param {number} [status]
  1219. * The request status.
  1220. */
  1221. changed(ajax, response, status) {
  1222. const $element = $(response.selector);
  1223. if (!$element.hasClass('ajax-changed')) {
  1224. $element.addClass('ajax-changed');
  1225. if (response.asterisk) {
  1226. $element
  1227. .find(response.asterisk)
  1228. .append(
  1229. ` <abbr class="ajax-changed" title="${Drupal.t(
  1230. 'Changed',
  1231. )}">*</abbr> `,
  1232. );
  1233. }
  1234. }
  1235. },
  1236. /**
  1237. * Command to provide an alert.
  1238. *
  1239. * @param {Drupal.Ajax} [ajax]
  1240. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1241. * @param {object} response
  1242. * The JSON response from the Ajax request.
  1243. * @param {string} response.text
  1244. * The text that will be displayed in an alert dialog.
  1245. * @param {number} [status]
  1246. * The XMLHttpRequest status.
  1247. */
  1248. alert(ajax, response, status) {
  1249. window.alert(response.text, response.title);
  1250. },
  1251. /**
  1252. * Command to provide triggers audio UAs to read the supplied text.
  1253. *
  1254. * @param {Drupal.Ajax} [ajax]
  1255. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1256. * @param {object} response
  1257. * The JSON response from the Ajax request.
  1258. * @param {string} [response.text]
  1259. * The text that will be read.
  1260. * @param {string} [response.priority]
  1261. * An optional priority that will be used for the announcement.
  1262. */
  1263. announce(ajax, response) {
  1264. if (response.priority) {
  1265. Drupal.announce(response.text, response.priority);
  1266. } else {
  1267. Drupal.announce(response.text);
  1268. }
  1269. },
  1270. /**
  1271. * Command to set the window.location, redirecting the browser.
  1272. *
  1273. * @param {Drupal.Ajax} [ajax]
  1274. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1275. * @param {object} response
  1276. * The response from the Ajax request.
  1277. * @param {string} response.url
  1278. * The URL to redirect to.
  1279. * @param {number} [status]
  1280. * The XMLHttpRequest status.
  1281. */
  1282. redirect(ajax, response, status) {
  1283. window.location = response.url;
  1284. },
  1285. /**
  1286. * Command to provide the jQuery css() function.
  1287. *
  1288. * @param {Drupal.Ajax} [ajax]
  1289. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1290. * @param {object} response
  1291. * The response from the Ajax request.
  1292. * @param {string} response.selector
  1293. * A jQuery selector string.
  1294. * @param {object} response.argument
  1295. * An array of key/value pairs to set in the CSS for the selector.
  1296. * @param {number} [status]
  1297. * The XMLHttpRequest status.
  1298. */
  1299. css(ajax, response, status) {
  1300. $(response.selector).css(response.argument);
  1301. },
  1302. /**
  1303. * Command to set the settings used for other commands in this response.
  1304. *
  1305. * This method will also remove expired `drupalSettings.ajax` settings.
  1306. *
  1307. * @param {Drupal.Ajax} [ajax]
  1308. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1309. * @param {object} response
  1310. * The response from the Ajax request.
  1311. * @param {bool} response.merge
  1312. * Determines whether the additional settings should be merged to the
  1313. * global settings.
  1314. * @param {object} response.settings
  1315. * Contains additional settings to add to the global settings.
  1316. * @param {number} [status]
  1317. * The XMLHttpRequest status.
  1318. */
  1319. settings(ajax, response, status) {
  1320. const ajaxSettings = drupalSettings.ajax;
  1321. // Clean up drupalSettings.ajax.
  1322. if (ajaxSettings) {
  1323. Drupal.ajax.expired().forEach(instance => {
  1324. // If the Ajax object has been created through drupalSettings.ajax
  1325. // it will have a selector. When there is no selector the object
  1326. // has been initialized with a special class name picked up by the
  1327. // Ajax behavior.
  1328. if (instance.selector) {
  1329. const selector = instance.selector.replace('#', '');
  1330. if (selector in ajaxSettings) {
  1331. delete ajaxSettings[selector];
  1332. }
  1333. }
  1334. });
  1335. }
  1336. if (response.merge) {
  1337. $.extend(true, drupalSettings, response.settings);
  1338. } else {
  1339. ajax.settings = response.settings;
  1340. }
  1341. },
  1342. /**
  1343. * Command to attach data using jQuery's data API.
  1344. *
  1345. * @param {Drupal.Ajax} [ajax]
  1346. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1347. * @param {object} response
  1348. * The response from the Ajax request.
  1349. * @param {string} response.name
  1350. * The name or key (in the key value pair) of the data attached to this
  1351. * selector.
  1352. * @param {string} response.selector
  1353. * A jQuery selector string.
  1354. * @param {string|object} response.value
  1355. * The value of to be attached.
  1356. * @param {number} [status]
  1357. * The XMLHttpRequest status.
  1358. */
  1359. data(ajax, response, status) {
  1360. $(response.selector).data(response.name, response.value);
  1361. },
  1362. /**
  1363. * Command to apply a jQuery method.
  1364. *
  1365. * @param {Drupal.Ajax} [ajax]
  1366. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1367. * @param {object} response
  1368. * The response from the Ajax request.
  1369. * @param {Array} response.args
  1370. * An array of arguments to the jQuery method, if any.
  1371. * @param {string} response.method
  1372. * The jQuery method to invoke.
  1373. * @param {string} response.selector
  1374. * A jQuery selector string.
  1375. * @param {number} [status]
  1376. * The XMLHttpRequest status.
  1377. */
  1378. invoke(ajax, response, status) {
  1379. const $element = $(response.selector);
  1380. $element[response.method](...response.args);
  1381. },
  1382. /**
  1383. * Command to restripe a table.
  1384. *
  1385. * @param {Drupal.Ajax} [ajax]
  1386. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1387. * @param {object} response
  1388. * The response from the Ajax request.
  1389. * @param {string} response.selector
  1390. * A jQuery selector string.
  1391. * @param {number} [status]
  1392. * The XMLHttpRequest status.
  1393. */
  1394. restripe(ajax, response, status) {
  1395. // :even and :odd are reversed because jQuery counts from 0 and
  1396. // we count from 1, so we're out of sync.
  1397. // Match immediate children of the parent element to allow nesting.
  1398. $(response.selector)
  1399. .find('> tbody > tr:visible, > tr:visible')
  1400. .removeClass('odd even')
  1401. .filter(':even')
  1402. .addClass('odd')
  1403. .end()
  1404. .filter(':odd')
  1405. .addClass('even');
  1406. },
  1407. /**
  1408. * Command to update a form's build ID.
  1409. *
  1410. * @param {Drupal.Ajax} [ajax]
  1411. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1412. * @param {object} response
  1413. * The response from the Ajax request.
  1414. * @param {string} response.old
  1415. * The old form build ID.
  1416. * @param {string} response.new
  1417. * The new form build ID.
  1418. * @param {number} [status]
  1419. * The XMLHttpRequest status.
  1420. */
  1421. update_build_id(ajax, response, status) {
  1422. $(`input[name="form_build_id"][value="${response.old}"]`).val(
  1423. response.new,
  1424. );
  1425. },
  1426. /**
  1427. * Command to add css.
  1428. *
  1429. * @param {Drupal.Ajax} [ajax]
  1430. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1431. * @param {object} response
  1432. * The response from the Ajax request.
  1433. * @param {string} response.data
  1434. * A string that contains the styles to be added.
  1435. * @param {number} [status]
  1436. * The XMLHttpRequest status.
  1437. */
  1438. add_css(ajax, response, status) {
  1439. $('head').prepend(response.data);
  1440. },
  1441. /**
  1442. * Command to add a message to the message area.
  1443. *
  1444. * @param {Drupal.Ajax} [ajax]
  1445. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1446. * @param {object} response
  1447. * The response from the Ajax request.
  1448. * @param {string} response.messageWrapperQuerySelector
  1449. * The zone where to add the message. If null, the default will be used.
  1450. * @param {string} response.message
  1451. * The message text.
  1452. * @param {string} response.messageOptions
  1453. * The options argument for Drupal.Message().add().
  1454. * @param {bool} response.clearPrevious
  1455. * If true, clear previous messages.
  1456. */
  1457. message(ajax, response) {
  1458. const messages = new Drupal.Message(
  1459. document.querySelector(response.messageWrapperQuerySelector),
  1460. );
  1461. if (response.clearPrevious) {
  1462. messages.clear();
  1463. }
  1464. messages.add(response.message, response.messageOptions);
  1465. },
  1466. };
  1467. })(jQuery, window, Drupal, drupalSettings);