drupal.es6.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. }
  152. catch (e) {
  153. Drupal.throwError(e);
  154. }
  155. }
  156. });
  157. };
  158. /**
  159. * Detaches registered behaviors from a page element.
  160. *
  161. * Developers implementing Ajax in their solutions should call this function
  162. * before page content is about to be removed, feeding in an element to be
  163. * processed, in order to allow special behaviors to detach from the content.
  164. *
  165. * Such implementations should use `.findOnce()` and `.removeOnce()` to find
  166. * elements with their corresponding `Drupal.behaviors.behaviorName.attach`
  167. * implementation, i.e. `.removeOnce('behaviorName')`, to ensure the behavior
  168. * is detached only from previously processed elements.
  169. *
  170. * @param {HTMLDocument|HTMLElement} [context=document]
  171. * An element to detach behaviors from.
  172. * @param {object} [settings=drupalSettings]
  173. * An object containing settings for the current context. If none given,
  174. * the global {@link drupalSettings} object is used.
  175. * @param {string} [trigger='unload']
  176. * A string containing what's causing the behaviors to be detached. The
  177. * possible triggers are:
  178. * - `'unload'`: The context element is being removed from the DOM.
  179. * - `'move'`: The element is about to be moved within the DOM (for example,
  180. * during a tabledrag row swap). After the move is completed,
  181. * {@link Drupal.attachBehaviors} is called, so that the behavior can undo
  182. * whatever it did in response to the move. Many behaviors won't need to
  183. * do anything simply in response to the element being moved, but because
  184. * IFRAME elements reload their "src" when being moved within the DOM,
  185. * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
  186. * take some action.
  187. * - `'serialize'`: When an Ajax form is submitted, this is called with the
  188. * form as the context. This provides every behavior within the form an
  189. * opportunity to ensure that the field elements have correct content
  190. * in them before the form is serialized. The canonical use-case is so
  191. * that WYSIWYG editors can update the hidden textarea to which they are
  192. * bound.
  193. *
  194. * @throws {Drupal~DrupalBehaviorError}
  195. *
  196. * @see Drupal~behaviorDetach
  197. * @see Drupal.attachBehaviors
  198. */
  199. Drupal.detachBehaviors = function (context, settings, trigger) {
  200. context = context || document;
  201. settings = settings || drupalSettings;
  202. trigger = trigger || 'unload';
  203. const behaviors = Drupal.behaviors;
  204. // Execute all of them.
  205. Object.keys(behaviors || {}).forEach((i) => {
  206. if (typeof behaviors[i].detach === 'function') {
  207. // Don't stop the execution of behaviors in case of an error.
  208. try {
  209. behaviors[i].detach(context, settings, trigger);
  210. }
  211. catch (e) {
  212. Drupal.throwError(e);
  213. }
  214. }
  215. });
  216. };
  217. /**
  218. * Encodes special characters in a plain-text string for display as HTML.
  219. *
  220. * @param {string} str
  221. * The string to be encoded.
  222. *
  223. * @return {string}
  224. * The encoded string.
  225. *
  226. * @ingroup sanitization
  227. */
  228. Drupal.checkPlain = function (str) {
  229. str = str.toString()
  230. .replace(/&/g, '&amp;')
  231. .replace(/</g, '&lt;')
  232. .replace(/>/g, '&gt;')
  233. .replace(/"/g, '&quot;')
  234. .replace(/'/g, '&#39;');
  235. return str;
  236. };
  237. /**
  238. * Replaces placeholders with sanitized values in a string.
  239. *
  240. * @param {string} str
  241. * A string with placeholders.
  242. * @param {object} args
  243. * An object of replacements pairs to make. Incidences of any key in this
  244. * array are replaced with the corresponding value. Based on the first
  245. * character of the key, the value is escaped and/or themed:
  246. * - `'!variable'`: inserted as is.
  247. * - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}).
  248. * - `'%variable'`: escape text and theme as a placeholder for user-
  249. * submitted content ({@link Drupal.checkPlain} +
  250. * `{@link Drupal.theme}('placeholder')`).
  251. *
  252. * @return {string}
  253. * The formatted string.
  254. *
  255. * @see Drupal.t
  256. */
  257. Drupal.formatString = function (str, args) {
  258. // Keep args intact.
  259. const processedArgs = {};
  260. // Transform arguments before inserting them.
  261. Object.keys(args || {}).forEach((key) => {
  262. switch (key.charAt(0)) {
  263. // Escaped only.
  264. case '@':
  265. processedArgs[key] = Drupal.checkPlain(args[key]);
  266. break;
  267. // Pass-through.
  268. case '!':
  269. processedArgs[key] = args[key];
  270. break;
  271. // Escaped and placeholder.
  272. default:
  273. processedArgs[key] = Drupal.theme('placeholder', args[key]);
  274. break;
  275. }
  276. });
  277. return Drupal.stringReplace(str, processedArgs, null);
  278. };
  279. /**
  280. * Replaces substring.
  281. *
  282. * The longest keys will be tried first. Once a substring has been replaced,
  283. * its new value will not be searched again.
  284. *
  285. * @param {string} str
  286. * A string with placeholders.
  287. * @param {object} args
  288. * Key-value pairs.
  289. * @param {Array|null} keys
  290. * Array of keys from `args`. Internal use only.
  291. *
  292. * @return {string}
  293. * The replaced string.
  294. */
  295. Drupal.stringReplace = function (str, args, keys) {
  296. if (str.length === 0) {
  297. return str;
  298. }
  299. // If the array of keys is not passed then collect the keys from the args.
  300. if (!Array.isArray(keys)) {
  301. keys = Object.keys(args || {});
  302. // Order the keys by the character length. The shortest one is the first.
  303. keys.sort((a, b) => a.length - b.length);
  304. }
  305. if (keys.length === 0) {
  306. return str;
  307. }
  308. // Take next longest one from the end.
  309. const key = keys.pop();
  310. const fragments = str.split(key);
  311. if (keys.length) {
  312. for (let i = 0; i < fragments.length; i++) {
  313. // Process each fragment with a copy of remaining keys.
  314. fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
  315. }
  316. }
  317. return fragments.join(args[key]);
  318. };
  319. /**
  320. * Translates strings to the page language, or a given language.
  321. *
  322. * See the documentation of the server-side t() function for further details.
  323. *
  324. * @param {string} str
  325. * A string containing the English text to translate.
  326. * @param {Object.<string, string>} [args]
  327. * An object of replacements pairs to make after translation. Incidences
  328. * of any key in this array are replaced with the corresponding value.
  329. * See {@link Drupal.formatString}.
  330. * @param {object} [options]
  331. * Additional options for translation.
  332. * @param {string} [options.context='']
  333. * The context the source string belongs to.
  334. *
  335. * @return {string}
  336. * The formatted string.
  337. * The translated string.
  338. */
  339. Drupal.t = function (str, args, options) {
  340. options = options || {};
  341. options.context = options.context || '';
  342. // Fetch the localized version of the string.
  343. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) {
  344. str = drupalTranslations.strings[options.context][str];
  345. }
  346. if (args) {
  347. str = Drupal.formatString(str, args);
  348. }
  349. return str;
  350. };
  351. /**
  352. * Returns the URL to a Drupal page.
  353. *
  354. * @param {string} path
  355. * Drupal path to transform to URL.
  356. *
  357. * @return {string}
  358. * The full URL.
  359. */
  360. Drupal.url = function (path) {
  361. return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
  362. };
  363. /**
  364. * Returns the passed in URL as an absolute URL.
  365. *
  366. * @param {string} url
  367. * The URL string to be normalized to an absolute URL.
  368. *
  369. * @return {string}
  370. * The normalized, absolute URL.
  371. *
  372. * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
  373. * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
  374. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
  375. */
  376. Drupal.url.toAbsolute = function (url) {
  377. const urlParsingNode = document.createElement('a');
  378. // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
  379. // strings may throw an exception.
  380. try {
  381. url = decodeURIComponent(url);
  382. }
  383. catch (e) {
  384. // Empty.
  385. }
  386. urlParsingNode.setAttribute('href', url);
  387. // IE <= 7 normalizes the URL when assigned to the anchor node similar to
  388. // the other browsers.
  389. return urlParsingNode.cloneNode(false).href;
  390. };
  391. /**
  392. * Returns true if the URL is within Drupal's base path.
  393. *
  394. * @param {string} url
  395. * The URL string to be tested.
  396. *
  397. * @return {bool}
  398. * `true` if local.
  399. *
  400. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
  401. */
  402. Drupal.url.isLocal = function (url) {
  403. // Always use browser-derived absolute URLs in the comparison, to avoid
  404. // attempts to break out of the base path using directory traversal.
  405. let absoluteUrl = Drupal.url.toAbsolute(url);
  406. let protocol = location.protocol;
  407. // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
  408. // as local as well.
  409. if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
  410. protocol = 'https:';
  411. }
  412. let baseUrl = `${protocol}//${location.host}${drupalSettings.path.baseUrl.slice(0, -1)}`;
  413. // Decoding non-UTF-8 strings may throw an exception.
  414. try {
  415. absoluteUrl = decodeURIComponent(absoluteUrl);
  416. }
  417. catch (e) {
  418. // Empty.
  419. }
  420. try {
  421. baseUrl = decodeURIComponent(baseUrl);
  422. }
  423. catch (e) {
  424. // Empty.
  425. }
  426. // The given URL matches the site's base URL, or has a path under the site's
  427. // base URL.
  428. return absoluteUrl === baseUrl || absoluteUrl.indexOf(`${baseUrl}/`) === 0;
  429. };
  430. /**
  431. * Formats a string containing a count of items.
  432. *
  433. * This function ensures that the string is pluralized correctly. Since
  434. * {@link Drupal.t} is called by this function, make sure not to pass
  435. * already-localized strings to it.
  436. *
  437. * See the documentation of the server-side
  438. * \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
  439. * function for more details.
  440. *
  441. * @param {number} count
  442. * The item count to display.
  443. * @param {string} singular
  444. * The string for the singular case. Please make sure it is clear this is
  445. * singular, to ease translation (e.g. use "1 new comment" instead of "1
  446. * new"). Do not use @count in the singular string.
  447. * @param {string} plural
  448. * The string for the plural case. Please make sure it is clear this is
  449. * plural, to ease translation. Use @count in place of the item count, as in
  450. * "@count new comments".
  451. * @param {object} [args]
  452. * An object of replacements pairs to make after translation. Incidences
  453. * of any key in this array are replaced with the corresponding value.
  454. * See {@link Drupal.formatString}.
  455. * Note that you do not need to include @count in this array.
  456. * This replacement is done automatically for the plural case.
  457. * @param {object} [options]
  458. * The options to pass to the {@link Drupal.t} function.
  459. *
  460. * @return {string}
  461. * A translated string.
  462. */
  463. Drupal.formatPlural = function (count, singular, plural, args, options) {
  464. args = args || {};
  465. args['@count'] = count;
  466. const pluralDelimiter = drupalSettings.pluralDelimiter;
  467. const translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
  468. let index = 0;
  469. // Determine the index of the plural form.
  470. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) {
  471. index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula.default;
  472. }
  473. else if (args['@count'] !== 1) {
  474. index = 1;
  475. }
  476. return translations[index];
  477. };
  478. /**
  479. * Encodes a Drupal path for use in a URL.
  480. *
  481. * For aesthetic reasons slashes are not escaped.
  482. *
  483. * @param {string} item
  484. * Unencoded path.
  485. *
  486. * @return {string}
  487. * The encoded path.
  488. */
  489. Drupal.encodePath = function (item) {
  490. return window.encodeURIComponent(item).replace(/%2F/g, '/');
  491. };
  492. /**
  493. * Generates the themed representation of a Drupal object.
  494. *
  495. * All requests for themed output must go through this function. It examines
  496. * the request and routes it to the appropriate theme function. If the current
  497. * theme does not provide an override function, the generic theme function is
  498. * called.
  499. *
  500. * @example
  501. * <caption>To retrieve the HTML for text that should be emphasized and
  502. * displayed as a placeholder inside a sentence.</caption>
  503. * Drupal.theme('placeholder', text);
  504. *
  505. * @namespace
  506. *
  507. * @param {function} func
  508. * The name of the theme function to call.
  509. * @param {...args}
  510. * Additional arguments to pass along to the theme function.
  511. *
  512. * @return {string|object|HTMLElement|jQuery}
  513. * Any data the theme function returns. This could be a plain HTML string,
  514. * but also a complex object.
  515. */
  516. Drupal.theme = function (func, ...args) {
  517. if (func in Drupal.theme) {
  518. return Drupal.theme[func](...args);
  519. }
  520. };
  521. /**
  522. * Formats text for emphasized display in a placeholder inside a sentence.
  523. *
  524. * @param {string} str
  525. * The text to format (plain-text).
  526. *
  527. * @return {string}
  528. * The formatted text (html).
  529. */
  530. Drupal.theme.placeholder = function (str) {
  531. return `<em class="placeholder">${Drupal.checkPlain(str)}</em>`;
  532. };
  533. }(Drupal, window.drupalSettings, window.drupalTranslations));