drupal.es6.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /**
  2. * @file
  3. * Defines the Drupal JavaScript API.
  4. */
  5. /**
  6. * A jQuery object, typically the return value from a `$(selector)` call.
  7. *
  8. * Holds an HTMLElement or a collection of HTMLElements.
  9. *
  10. * @typedef {object} jQuery
  11. *
  12. * @prop {number} length=0
  13. * Number of elements contained in the jQuery object.
  14. */
  15. /**
  16. * Variable generated by Drupal that holds all translated strings from PHP.
  17. *
  18. * Content of this variable is automatically created by Drupal when using the
  19. * Interface Translation module. It holds the translation of strings used on
  20. * the page.
  21. *
  22. * This variable is used to pass data from the backend to the frontend. Data
  23. * contained in `drupalSettings` is used during behavior initialization.
  24. *
  25. * @global
  26. *
  27. * @var {object} drupalTranslations
  28. */
  29. /**
  30. * Global Drupal object.
  31. *
  32. * All Drupal JavaScript APIs are contained in this namespace.
  33. *
  34. * @global
  35. *
  36. * @namespace
  37. */
  38. window.Drupal = { behaviors: {}, locale: {} };
  39. // JavaScript should be made compatible with libraries other than jQuery by
  40. // wrapping it in an anonymous closure.
  41. (function(Drupal, drupalSettings, drupalTranslations) {
  42. /**
  43. * Helper to rethrow errors asynchronously.
  44. *
  45. * This way Errors bubbles up outside of the original callstack, making it
  46. * easier to debug errors in the browser.
  47. *
  48. * @param {Error|string} error
  49. * The error to be thrown.
  50. */
  51. Drupal.throwError = function(error) {
  52. setTimeout(() => {
  53. throw error;
  54. }, 0);
  55. };
  56. /**
  57. * Custom error thrown after attach/detach if one or more behaviors failed.
  58. * Initializes the JavaScript behaviors for page loads and Ajax requests.
  59. *
  60. * @callback Drupal~behaviorAttach
  61. *
  62. * @param {HTMLDocument|HTMLElement} context
  63. * An element to detach behaviors from.
  64. * @param {?object} settings
  65. * An object containing settings for the current context. It is rarely used.
  66. *
  67. * @see Drupal.attachBehaviors
  68. */
  69. /**
  70. * Reverts and cleans up JavaScript behavior initialization.
  71. *
  72. * @callback Drupal~behaviorDetach
  73. *
  74. * @param {HTMLDocument|HTMLElement} context
  75. * An element to attach behaviors to.
  76. * @param {object} settings
  77. * An object containing settings for the current context.
  78. * @param {string} trigger
  79. * One of `'unload'`, `'move'`, or `'serialize'`.
  80. *
  81. * @see Drupal.detachBehaviors
  82. */
  83. /**
  84. * @typedef {object} Drupal~behavior
  85. *
  86. * @prop {Drupal~behaviorAttach} attach
  87. * Function run on page load and after an Ajax call.
  88. * @prop {Drupal~behaviorDetach} detach
  89. * Function run when content is serialized or removed from the page.
  90. */
  91. /**
  92. * Holds all initialization methods.
  93. *
  94. * @namespace Drupal.behaviors
  95. *
  96. * @type {Object.<string, Drupal~behavior>}
  97. */
  98. /**
  99. * Defines a behavior to be run during attach and detach phases.
  100. *
  101. * Attaches all registered behaviors to a page element.
  102. *
  103. * Behaviors are event-triggered actions that attach to page elements,
  104. * enhancing default non-JavaScript UIs. Behaviors are registered in the
  105. * {@link Drupal.behaviors} object using the method 'attach' and optionally
  106. * also 'detach'.
  107. *
  108. * {@link Drupal.attachBehaviors} is added below to the `jQuery.ready` event
  109. * and therefore runs on initial page load. Developers implementing Ajax in
  110. * their solutions should also call this function after new page content has
  111. * been loaded, feeding in an element to be processed, in order to attach all
  112. * behaviors to the new content.
  113. *
  114. * Behaviors should use `var elements =
  115. * $(context).find(selector).once('behavior-name');` to ensure the behavior is
  116. * attached only once to a given element. (Doing so enables the reprocessing
  117. * of given elements, which may be needed on occasion despite the ability to
  118. * limit behavior attachment to a particular element.)
  119. *
  120. * @example
  121. * Drupal.behaviors.behaviorName = {
  122. * attach: function (context, settings) {
  123. * // ...
  124. * },
  125. * detach: function (context, settings, trigger) {
  126. * // ...
  127. * }
  128. * };
  129. *
  130. * @param {HTMLDocument|HTMLElement} [context=document]
  131. * An element to attach behaviors to.
  132. * @param {object} [settings=drupalSettings]
  133. * An object containing settings for the current context. If none is given,
  134. * the global {@link drupalSettings} object is used.
  135. *
  136. * @see Drupal~behaviorAttach
  137. * @see Drupal.detachBehaviors
  138. *
  139. * @throws {Drupal~DrupalBehaviorError}
  140. */
  141. Drupal.attachBehaviors = function(context, settings) {
  142. context = context || document;
  143. settings = settings || drupalSettings;
  144. const behaviors = Drupal.behaviors;
  145. // Execute all of them.
  146. Object.keys(behaviors || {}).forEach(i => {
  147. if (typeof behaviors[i].attach === 'function') {
  148. // Don't stop the execution of behaviors in case of an error.
  149. try {
  150. behaviors[i].attach(context, settings);
  151. } catch (e) {
  152. Drupal.throwError(e);
  153. }
  154. }
  155. });
  156. };
  157. /**
  158. * Detaches registered behaviors from a page element.
  159. *
  160. * Developers implementing Ajax in their solutions should call this function
  161. * before page content is about to be removed, feeding in an element to be
  162. * processed, in order to allow special behaviors to detach from the content.
  163. *
  164. * Such implementations should use `.findOnce()` and `.removeOnce()` to find
  165. * elements with their corresponding `Drupal.behaviors.behaviorName.attach`
  166. * implementation, i.e. `.removeOnce('behaviorName')`, to ensure the behavior
  167. * is detached only from previously processed elements.
  168. *
  169. * @param {HTMLDocument|HTMLElement} [context=document]
  170. * An element to detach behaviors from.
  171. * @param {object} [settings=drupalSettings]
  172. * An object containing settings for the current context. If none given,
  173. * the global {@link drupalSettings} object is used.
  174. * @param {string} [trigger='unload']
  175. * A string containing what's causing the behaviors to be detached. The
  176. * possible triggers are:
  177. * - `'unload'`: The context element is being removed from the DOM.
  178. * - `'move'`: The element is about to be moved within the DOM (for example,
  179. * during a tabledrag row swap). After the move is completed,
  180. * {@link Drupal.attachBehaviors} is called, so that the behavior can undo
  181. * whatever it did in response to the move. Many behaviors won't need to
  182. * do anything simply in response to the element being moved, but because
  183. * IFRAME elements reload their "src" when being moved within the DOM,
  184. * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
  185. * take some action.
  186. * - `'serialize'`: When an Ajax form is submitted, this is called with the
  187. * form as the context. This provides every behavior within the form an
  188. * opportunity to ensure that the field elements have correct content
  189. * in them before the form is serialized. The canonical use-case is so
  190. * that WYSIWYG editors can update the hidden textarea to which they are
  191. * bound.
  192. *
  193. * @throws {Drupal~DrupalBehaviorError}
  194. *
  195. * @see Drupal~behaviorDetach
  196. * @see Drupal.attachBehaviors
  197. */
  198. Drupal.detachBehaviors = function(context, settings, trigger) {
  199. context = context || document;
  200. settings = settings || drupalSettings;
  201. trigger = trigger || 'unload';
  202. const behaviors = Drupal.behaviors;
  203. // Execute all of them.
  204. Object.keys(behaviors || {}).forEach(i => {
  205. if (typeof behaviors[i].detach === 'function') {
  206. // Don't stop the execution of behaviors in case of an error.
  207. try {
  208. behaviors[i].detach(context, settings, trigger);
  209. } catch (e) {
  210. Drupal.throwError(e);
  211. }
  212. }
  213. });
  214. };
  215. /**
  216. * Encodes special characters in a plain-text string for display as HTML.
  217. *
  218. * @param {string} str
  219. * The string to be encoded.
  220. *
  221. * @return {string}
  222. * The encoded string.
  223. *
  224. * @ingroup sanitization
  225. */
  226. Drupal.checkPlain = function(str) {
  227. str = str
  228. .toString()
  229. .replace(/&/g, '&amp;')
  230. .replace(/</g, '&lt;')
  231. .replace(/>/g, '&gt;')
  232. .replace(/"/g, '&quot;')
  233. .replace(/'/g, '&#39;');
  234. return str;
  235. };
  236. /**
  237. * Replaces placeholders with sanitized values in a string.
  238. *
  239. * @param {string} str
  240. * A string with placeholders.
  241. * @param {object} args
  242. * An object of replacements pairs to make. Incidences of any key in this
  243. * array are replaced with the corresponding value. Based on the first
  244. * character of the key, the value is escaped and/or themed:
  245. * - `'!variable'`: inserted as is.
  246. * - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}).
  247. * - `'%variable'`: escape text and theme as a placeholder for user-
  248. * submitted content ({@link Drupal.checkPlain} +
  249. * `{@link Drupal.theme}('placeholder')`).
  250. *
  251. * @return {string}
  252. * The formatted string.
  253. *
  254. * @see Drupal.t
  255. */
  256. Drupal.formatString = function(str, args) {
  257. // Keep args intact.
  258. const processedArgs = {};
  259. // Transform arguments before inserting them.
  260. Object.keys(args || {}).forEach(key => {
  261. switch (key.charAt(0)) {
  262. // Escaped only.
  263. case '@':
  264. processedArgs[key] = Drupal.checkPlain(args[key]);
  265. break;
  266. // Pass-through.
  267. case '!':
  268. processedArgs[key] = args[key];
  269. break;
  270. // Escaped and placeholder.
  271. default:
  272. processedArgs[key] = Drupal.theme('placeholder', args[key]);
  273. break;
  274. }
  275. });
  276. return Drupal.stringReplace(str, processedArgs, null);
  277. };
  278. /**
  279. * Replaces substring.
  280. *
  281. * The longest keys will be tried first. Once a substring has been replaced,
  282. * its new value will not be searched again.
  283. *
  284. * @param {string} str
  285. * A string with placeholders.
  286. * @param {object} args
  287. * Key-value pairs.
  288. * @param {Array|null} keys
  289. * Array of keys from `args`. Internal use only.
  290. *
  291. * @return {string}
  292. * The replaced string.
  293. */
  294. Drupal.stringReplace = function(str, args, keys) {
  295. if (str.length === 0) {
  296. return str;
  297. }
  298. // If the array of keys is not passed then collect the keys from the args.
  299. if (!Array.isArray(keys)) {
  300. keys = Object.keys(args || {});
  301. // Order the keys by the character length. The shortest one is the first.
  302. keys.sort((a, b) => a.length - b.length);
  303. }
  304. if (keys.length === 0) {
  305. return str;
  306. }
  307. // Take next longest one from the end.
  308. const key = keys.pop();
  309. const fragments = str.split(key);
  310. if (keys.length) {
  311. for (let i = 0; i < fragments.length; i++) {
  312. // Process each fragment with a copy of remaining keys.
  313. fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
  314. }
  315. }
  316. return fragments.join(args[key]);
  317. };
  318. /**
  319. * Translates strings to the page language, or a given language.
  320. *
  321. * See the documentation of the server-side t() function for further details.
  322. *
  323. * @param {string} str
  324. * A string containing the English text to translate.
  325. * @param {Object.<string, string>} [args]
  326. * An object of replacements pairs to make after translation. Incidences
  327. * of any key in this array are replaced with the corresponding value.
  328. * See {@link Drupal.formatString}.
  329. * @param {object} [options]
  330. * Additional options for translation.
  331. * @param {string} [options.context='']
  332. * The context the source string belongs to.
  333. *
  334. * @return {string}
  335. * The formatted string.
  336. * The translated string.
  337. */
  338. Drupal.t = function(str, args, options) {
  339. options = options || {};
  340. options.context = options.context || '';
  341. // Fetch the localized version of the string.
  342. if (
  343. typeof drupalTranslations !== 'undefined' &&
  344. drupalTranslations.strings &&
  345. drupalTranslations.strings[options.context] &&
  346. drupalTranslations.strings[options.context][str]
  347. ) {
  348. str = drupalTranslations.strings[options.context][str];
  349. }
  350. if (args) {
  351. str = Drupal.formatString(str, args);
  352. }
  353. return str;
  354. };
  355. /**
  356. * Returns the URL to a Drupal page.
  357. *
  358. * @param {string} path
  359. * Drupal path to transform to URL.
  360. *
  361. * @return {string}
  362. * The full URL.
  363. */
  364. Drupal.url = function(path) {
  365. return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
  366. };
  367. /**
  368. * Returns the passed in URL as an absolute URL.
  369. *
  370. * @param {string} url
  371. * The URL string to be normalized to an absolute URL.
  372. *
  373. * @return {string}
  374. * The normalized, absolute URL.
  375. *
  376. * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
  377. * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
  378. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
  379. */
  380. Drupal.url.toAbsolute = function(url) {
  381. const urlParsingNode = document.createElement('a');
  382. // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
  383. // strings may throw an exception.
  384. try {
  385. url = decodeURIComponent(url);
  386. } catch (e) {
  387. // Empty.
  388. }
  389. urlParsingNode.setAttribute('href', url);
  390. // IE <= 7 normalizes the URL when assigned to the anchor node similar to
  391. // the other browsers.
  392. return urlParsingNode.cloneNode(false).href;
  393. };
  394. /**
  395. * Returns true if the URL is within Drupal's base path.
  396. *
  397. * @param {string} url
  398. * The URL string to be tested.
  399. *
  400. * @return {bool}
  401. * `true` if local.
  402. *
  403. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
  404. */
  405. Drupal.url.isLocal = function(url) {
  406. // Always use browser-derived absolute URLs in the comparison, to avoid
  407. // attempts to break out of the base path using directory traversal.
  408. let absoluteUrl = Drupal.url.toAbsolute(url);
  409. let { protocol } = window.location;
  410. // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
  411. // as local as well.
  412. if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
  413. protocol = 'https:';
  414. }
  415. let baseUrl = `${protocol}//${
  416. window.location.host
  417. }${drupalSettings.path.baseUrl.slice(0, -1)}`;
  418. // Decoding non-UTF-8 strings may throw an exception.
  419. try {
  420. absoluteUrl = decodeURIComponent(absoluteUrl);
  421. } catch (e) {
  422. // Empty.
  423. }
  424. try {
  425. baseUrl = decodeURIComponent(baseUrl);
  426. } catch (e) {
  427. // Empty.
  428. }
  429. // The given URL matches the site's base URL, or has a path under the site's
  430. // base URL.
  431. return absoluteUrl === baseUrl || absoluteUrl.indexOf(`${baseUrl}/`) === 0;
  432. };
  433. /**
  434. * Formats a string containing a count of items.
  435. *
  436. * This function ensures that the string is pluralized correctly. Since
  437. * {@link Drupal.t} is called by this function, make sure not to pass
  438. * already-localized strings to it.
  439. *
  440. * See the documentation of the server-side
  441. * \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
  442. * function for more details.
  443. *
  444. * @param {number} count
  445. * The item count to display.
  446. * @param {string} singular
  447. * The string for the singular case. Please make sure it is clear this is
  448. * singular, to ease translation (e.g. use "1 new comment" instead of "1
  449. * new"). Do not use @count in the singular string.
  450. * @param {string} plural
  451. * The string for the plural case. Please make sure it is clear this is
  452. * plural, to ease translation. Use @count in place of the item count, as in
  453. * "@count new comments".
  454. * @param {object} [args]
  455. * An object of replacements pairs to make after translation. Incidences
  456. * of any key in this array are replaced with the corresponding value.
  457. * See {@link Drupal.formatString}.
  458. * Note that you do not need to include @count in this array.
  459. * This replacement is done automatically for the plural case.
  460. * @param {object} [options]
  461. * The options to pass to the {@link Drupal.t} function.
  462. *
  463. * @return {string}
  464. * A translated string.
  465. */
  466. Drupal.formatPlural = function(count, singular, plural, args, options) {
  467. args = args || {};
  468. args['@count'] = count;
  469. const pluralDelimiter = drupalSettings.pluralDelimiter;
  470. const translations = Drupal.t(
  471. singular + pluralDelimiter + plural,
  472. args,
  473. options,
  474. ).split(pluralDelimiter);
  475. let index = 0;
  476. // Determine the index of the plural form.
  477. if (
  478. typeof drupalTranslations !== 'undefined' &&
  479. drupalTranslations.pluralFormula
  480. ) {
  481. index =
  482. count in drupalTranslations.pluralFormula
  483. ? drupalTranslations.pluralFormula[count]
  484. : drupalTranslations.pluralFormula.default;
  485. } else if (args['@count'] !== 1) {
  486. index = 1;
  487. }
  488. return translations[index];
  489. };
  490. /**
  491. * Encodes a Drupal path for use in a URL.
  492. *
  493. * For aesthetic reasons slashes are not escaped.
  494. *
  495. * @param {string} item
  496. * Unencoded path.
  497. *
  498. * @return {string}
  499. * The encoded path.
  500. */
  501. Drupal.encodePath = function(item) {
  502. return window.encodeURIComponent(item).replace(/%2F/g, '/');
  503. };
  504. /**
  505. * Generates the themed representation of a Drupal object.
  506. *
  507. * All requests for themed output must go through this function. It examines
  508. * the request and routes it to the appropriate theme function. If the current
  509. * theme does not provide an override function, the generic theme function is
  510. * called.
  511. *
  512. * @example
  513. * <caption>To retrieve the HTML for text that should be emphasized and
  514. * displayed as a placeholder inside a sentence.</caption>
  515. * Drupal.theme('placeholder', text);
  516. *
  517. * @namespace
  518. *
  519. * @param {function} func
  520. * The name of the theme function to call.
  521. * @param {...args}
  522. * Additional arguments to pass along to the theme function.
  523. *
  524. * @return {string|object|HTMLElement|jQuery}
  525. * Any data the theme function returns. This could be a plain HTML string,
  526. * but also a complex object.
  527. */
  528. Drupal.theme = function(func, ...args) {
  529. if (func in Drupal.theme) {
  530. return Drupal.theme[func](...args);
  531. }
  532. };
  533. /**
  534. * Formats text for emphasized display in a placeholder inside a sentence.
  535. *
  536. * @param {string} str
  537. * The text to format (plain-text).
  538. *
  539. * @return {string}
  540. * The formatted text (html).
  541. */
  542. Drupal.theme.placeholder = function(str) {
  543. return `<em class="placeholder">${Drupal.checkPlain(str)}</em>`;
  544. };
  545. })(Drupal, window.drupalSettings, window.drupalTranslations);