drupal.es6.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. for (const i in behaviors) {
  147. if (behaviors.hasOwnProperty(i) && 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. for (const i in behaviors) {
  206. if (behaviors.hasOwnProperty(i) && 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, '&quot;')
  232. .replace(/</g, '&lt;')
  233. .replace(/>/g, '&gt;');
  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. for (const key in args) {
  261. if (args.hasOwnProperty(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. }
  278. return Drupal.stringReplace(str, processedArgs, null);
  279. };
  280. /**
  281. * Replaces substring.
  282. *
  283. * The longest keys will be tried first. Once a substring has been replaced,
  284. * its new value will not be searched again.
  285. *
  286. * @param {string} str
  287. * A string with placeholders.
  288. * @param {object} args
  289. * Key-value pairs.
  290. * @param {Array|null} keys
  291. * Array of keys from `args`. Internal use only.
  292. *
  293. * @return {string}
  294. * The replaced string.
  295. */
  296. Drupal.stringReplace = function (str, args, keys) {
  297. if (str.length === 0) {
  298. return str;
  299. }
  300. // If the array of keys is not passed then collect the keys from the args.
  301. if (!Array.isArray(keys)) {
  302. keys = [];
  303. for (const k in args) {
  304. if (args.hasOwnProperty(k)) {
  305. keys.push(k);
  306. }
  307. }
  308. // Order the keys by the character length. The shortest one is the first.
  309. keys.sort((a, b) => a.length - b.length);
  310. }
  311. if (keys.length === 0) {
  312. return str;
  313. }
  314. // Take next longest one from the end.
  315. const key = keys.pop();
  316. const fragments = str.split(key);
  317. if (keys.length) {
  318. for (let i = 0; i < fragments.length; i++) {
  319. // Process each fragment with a copy of remaining keys.
  320. fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
  321. }
  322. }
  323. return fragments.join(args[key]);
  324. };
  325. /**
  326. * Translates strings to the page language, or a given language.
  327. *
  328. * See the documentation of the server-side t() function for further details.
  329. *
  330. * @param {string} str
  331. * A string containing the English text to translate.
  332. * @param {Object.<string, string>} [args]
  333. * An object of replacements pairs to make after translation. Incidences
  334. * of any key in this array are replaced with the corresponding value.
  335. * See {@link Drupal.formatString}.
  336. * @param {object} [options]
  337. * Additional options for translation.
  338. * @param {string} [options.context='']
  339. * The context the source string belongs to.
  340. *
  341. * @return {string}
  342. * The formatted string.
  343. * The translated string.
  344. */
  345. Drupal.t = function (str, args, options) {
  346. options = options || {};
  347. options.context = options.context || '';
  348. // Fetch the localized version of the string.
  349. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) {
  350. str = drupalTranslations.strings[options.context][str];
  351. }
  352. if (args) {
  353. str = Drupal.formatString(str, args);
  354. }
  355. return str;
  356. };
  357. /**
  358. * Returns the URL to a Drupal page.
  359. *
  360. * @param {string} path
  361. * Drupal path to transform to URL.
  362. *
  363. * @return {string}
  364. * The full URL.
  365. */
  366. Drupal.url = function (path) {
  367. return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
  368. };
  369. /**
  370. * Returns the passed in URL as an absolute URL.
  371. *
  372. * @param {string} url
  373. * The URL string to be normalized to an absolute URL.
  374. *
  375. * @return {string}
  376. * The normalized, absolute URL.
  377. *
  378. * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
  379. * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
  380. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
  381. */
  382. Drupal.url.toAbsolute = function (url) {
  383. const urlParsingNode = document.createElement('a');
  384. // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
  385. // strings may throw an exception.
  386. try {
  387. url = decodeURIComponent(url);
  388. }
  389. catch (e) {
  390. // Empty.
  391. }
  392. urlParsingNode.setAttribute('href', url);
  393. // IE <= 7 normalizes the URL when assigned to the anchor node similar to
  394. // the other browsers.
  395. return urlParsingNode.cloneNode(false).href;
  396. };
  397. /**
  398. * Returns true if the URL is within Drupal's base path.
  399. *
  400. * @param {string} url
  401. * The URL string to be tested.
  402. *
  403. * @return {bool}
  404. * `true` if local.
  405. *
  406. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
  407. */
  408. Drupal.url.isLocal = function (url) {
  409. // Always use browser-derived absolute URLs in the comparison, to avoid
  410. // attempts to break out of the base path using directory traversal.
  411. let absoluteUrl = Drupal.url.toAbsolute(url);
  412. let protocol = location.protocol;
  413. // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
  414. // as local as well.
  415. if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
  416. protocol = 'https:';
  417. }
  418. let baseUrl = `${protocol}//${location.host}${drupalSettings.path.baseUrl.slice(0, -1)}`;
  419. // Decoding non-UTF-8 strings may throw an exception.
  420. try {
  421. absoluteUrl = decodeURIComponent(absoluteUrl);
  422. }
  423. catch (e) {
  424. // Empty.
  425. }
  426. try {
  427. baseUrl = decodeURIComponent(baseUrl);
  428. }
  429. catch (e) {
  430. // Empty.
  431. }
  432. // The given URL matches the site's base URL, or has a path under the site's
  433. // base URL.
  434. return absoluteUrl === baseUrl || absoluteUrl.indexOf(`${baseUrl}/`) === 0;
  435. };
  436. /**
  437. * Formats a string containing a count of items.
  438. *
  439. * This function ensures that the string is pluralized correctly. Since
  440. * {@link Drupal.t} is called by this function, make sure not to pass
  441. * already-localized strings to it.
  442. *
  443. * See the documentation of the server-side
  444. * \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
  445. * function for more details.
  446. *
  447. * @param {number} count
  448. * The item count to display.
  449. * @param {string} singular
  450. * The string for the singular case. Please make sure it is clear this is
  451. * singular, to ease translation (e.g. use "1 new comment" instead of "1
  452. * new"). Do not use @count in the singular string.
  453. * @param {string} plural
  454. * The string for the plural case. Please make sure it is clear this is
  455. * plural, to ease translation. Use @count in place of the item count, as in
  456. * "@count new comments".
  457. * @param {object} [args]
  458. * An object of replacements pairs to make after translation. Incidences
  459. * of any key in this array are replaced with the corresponding value.
  460. * See {@link Drupal.formatString}.
  461. * Note that you do not need to include @count in this array.
  462. * This replacement is done automatically for the plural case.
  463. * @param {object} [options]
  464. * The options to pass to the {@link Drupal.t} function.
  465. *
  466. * @return {string}
  467. * A translated string.
  468. */
  469. Drupal.formatPlural = function (count, singular, plural, args, options) {
  470. args = args || {};
  471. args['@count'] = count;
  472. const pluralDelimiter = drupalSettings.pluralDelimiter;
  473. const translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
  474. let index = 0;
  475. // Determine the index of the plural form.
  476. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) {
  477. index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula.default;
  478. }
  479. else if (args['@count'] !== 1) {
  480. index = 1;
  481. }
  482. return translations[index];
  483. };
  484. /**
  485. * Encodes a Drupal path for use in a URL.
  486. *
  487. * For aesthetic reasons slashes are not escaped.
  488. *
  489. * @param {string} item
  490. * Unencoded path.
  491. *
  492. * @return {string}
  493. * The encoded path.
  494. */
  495. Drupal.encodePath = function (item) {
  496. return window.encodeURIComponent(item).replace(/%2F/g, '/');
  497. };
  498. /**
  499. * Generates the themed representation of a Drupal object.
  500. *
  501. * All requests for themed output must go through this function. It examines
  502. * the request and routes it to the appropriate theme function. If the current
  503. * theme does not provide an override function, the generic theme function is
  504. * called.
  505. *
  506. * @example
  507. * <caption>To retrieve the HTML for text that should be emphasized and
  508. * displayed as a placeholder inside a sentence.</caption>
  509. * Drupal.theme('placeholder', text);
  510. *
  511. * @namespace
  512. *
  513. * @param {function} func
  514. * The name of the theme function to call.
  515. * @param {...args}
  516. * Additional arguments to pass along to the theme function.
  517. *
  518. * @return {string|object|HTMLElement|jQuery}
  519. * Any data the theme function returns. This could be a plain HTML string,
  520. * but also a complex object.
  521. */
  522. Drupal.theme = function (func) {
  523. const args = Array.prototype.slice.apply(arguments, [1]);
  524. if (func in Drupal.theme) {
  525. return Drupal.theme[func].apply(this, args);
  526. }
  527. };
  528. /**
  529. * Formats text for emphasized display in a placeholder inside a sentence.
  530. *
  531. * @param {string} str
  532. * The text to format (plain-text).
  533. *
  534. * @return {string}
  535. * The formatted text (html).
  536. */
  537. Drupal.theme.placeholder = function (str) {
  538. return `<em class="placeholder">${Drupal.checkPlain(str)}</em>`;
  539. };
  540. }(Drupal, window.drupalSettings, window.drupalTranslations));