ajax.es6.js 51 KB

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