drupal.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. 'use strict';
  43. /**
  44. * Helper to rethrow errors asynchronously.
  45. *
  46. * This way Errors bubbles up outside of the original callstack, making it
  47. * easier to debug errors in the browser.
  48. *
  49. * @param {Error|string} error
  50. * The error to be thrown.
  51. */
  52. Drupal.throwError = function (error) {
  53. setTimeout(function () { throw error; }, 0);
  54. };
  55. /**
  56. * Custom error thrown after attach/detach if one or more behaviors failed.
  57. * Initializes the JavaScript behaviors for page loads and Ajax requests.
  58. *
  59. * @callback Drupal~behaviorAttach
  60. *
  61. * @param {HTMLDocument|HTMLElement} context
  62. * An element to detach behaviors from.
  63. * @param {?object} settings
  64. * An object containing settings for the current context. It is rarely used.
  65. *
  66. * @see Drupal.attachBehaviors
  67. */
  68. /**
  69. * Reverts and cleans up JavaScript behavior initialization.
  70. *
  71. * @callback Drupal~behaviorDetach
  72. *
  73. * @param {HTMLDocument|HTMLElement} context
  74. * An element to attach behaviors to.
  75. * @param {object} settings
  76. * An object containing settings for the current context.
  77. * @param {string} trigger
  78. * One of `'unload'`, `'move'`, or `'serialize'`.
  79. *
  80. * @see Drupal.detachBehaviors
  81. */
  82. /**
  83. * @typedef {object} Drupal~behavior
  84. *
  85. * @prop {Drupal~behaviorAttach} attach
  86. * Function run on page load and after an Ajax call.
  87. * @prop {Drupal~behaviorDetach} detach
  88. * Function run when content is serialized or removed from the page.
  89. */
  90. /**
  91. * Holds all initialization methods.
  92. *
  93. * @namespace Drupal.behaviors
  94. *
  95. * @type {Object.<string, Drupal~behavior>}
  96. */
  97. /**
  98. * Defines a behavior to be run during attach and detach phases.
  99. *
  100. * Attaches all registered behaviors to a page element.
  101. *
  102. * Behaviors are event-triggered actions that attach to page elements,
  103. * enhancing default non-JavaScript UIs. Behaviors are registered in the
  104. * {@link Drupal.behaviors} object using the method 'attach' and optionally
  105. * also 'detach'.
  106. *
  107. * {@link Drupal.attachBehaviors} is added below to the `jQuery.ready` event
  108. * and therefore runs on initial page load. Developers implementing Ajax in
  109. * their solutions should also call this function after new page content has
  110. * been loaded, feeding in an element to be processed, in order to attach all
  111. * behaviors to the new content.
  112. *
  113. * Behaviors should use `var elements =
  114. * $(context).find(selector).once('behavior-name');` to ensure the behavior is
  115. * attached only once to a given element. (Doing so enables the reprocessing
  116. * of given elements, which may be needed on occasion despite the ability to
  117. * limit behavior attachment to a particular element.)
  118. *
  119. * @example
  120. * Drupal.behaviors.behaviorName = {
  121. * attach: function (context, settings) {
  122. * // ...
  123. * },
  124. * detach: function (context, settings, trigger) {
  125. * // ...
  126. * }
  127. * };
  128. *
  129. * @param {HTMLDocument|HTMLElement} [context=document]
  130. * An element to attach behaviors to.
  131. * @param {object} [settings=drupalSettings]
  132. * An object containing settings for the current context. If none is given,
  133. * the global {@link drupalSettings} object is used.
  134. *
  135. * @see Drupal~behaviorAttach
  136. * @see Drupal.detachBehaviors
  137. *
  138. * @throws {Drupal~DrupalBehaviorError}
  139. */
  140. Drupal.attachBehaviors = function (context, settings) {
  141. context = context || document;
  142. settings = settings || drupalSettings;
  143. var behaviors = Drupal.behaviors;
  144. // Execute all of them.
  145. for (var i in behaviors) {
  146. if (behaviors.hasOwnProperty(i) && typeof behaviors[i].attach === 'function') {
  147. // Don't stop the execution of behaviors in case of an error.
  148. try {
  149. behaviors[i].attach(context, settings);
  150. }
  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. var behaviors = Drupal.behaviors;
  203. // Execute all of them.
  204. for (var i in behaviors) {
  205. if (behaviors.hasOwnProperty(i) && 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. }
  210. catch (e) {
  211. Drupal.throwError(e);
  212. }
  213. }
  214. }
  215. };
  216. /**
  217. * Encodes special characters in a plain-text string for display as HTML.
  218. *
  219. * @param {string} str
  220. * The string to be encoded.
  221. *
  222. * @return {string}
  223. * The encoded string.
  224. *
  225. * @ingroup sanitization
  226. */
  227. Drupal.checkPlain = function (str) {
  228. str = str.toString()
  229. .replace(/&/g, '&amp;')
  230. .replace(/"/g, '&quot;')
  231. .replace(/</g, '&lt;')
  232. .replace(/>/g, '&gt;');
  233. return str;
  234. };
  235. /**
  236. * Replaces placeholders with sanitized values in a string.
  237. *
  238. * @param {string} str
  239. * A string with placeholders.
  240. * @param {object} args
  241. * An object of replacements pairs to make. Incidences of any key in this
  242. * array are replaced with the corresponding value. Based on the first
  243. * character of the key, the value is escaped and/or themed:
  244. * - `'!variable'`: inserted as is.
  245. * - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}).
  246. * - `'%variable'`: escape text and theme as a placeholder for user-
  247. * submitted content ({@link Drupal.checkPlain} +
  248. * `{@link Drupal.theme}('placeholder')`).
  249. *
  250. * @return {string}
  251. * The formatted string.
  252. *
  253. * @see Drupal.t
  254. */
  255. Drupal.formatString = function (str, args) {
  256. // Keep args intact.
  257. var processedArgs = {};
  258. // Transform arguments before inserting them.
  259. for (var key in args) {
  260. if (args.hasOwnProperty(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. }
  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 = [];
  302. for (var k in args) {
  303. if (args.hasOwnProperty(k)) {
  304. keys.push(k);
  305. }
  306. }
  307. // Order the keys by the character length. The shortest one is the first.
  308. keys.sort(function (a, b) { return a.length - b.length; });
  309. }
  310. if (keys.length === 0) {
  311. return str;
  312. }
  313. // Take next longest one from the end.
  314. var key = keys.pop();
  315. var fragments = str.split(key);
  316. if (keys.length) {
  317. for (var i = 0; i < fragments.length; i++) {
  318. // Process each fragment with a copy of remaining keys.
  319. fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
  320. }
  321. }
  322. return fragments.join(args[key]);
  323. };
  324. /**
  325. * Translates strings to the page language, or a given language.
  326. *
  327. * See the documentation of the server-side t() function for further details.
  328. *
  329. * @param {string} str
  330. * A string containing the English text to translate.
  331. * @param {Object.<string, string>} [args]
  332. * An object of replacements pairs to make after translation. Incidences
  333. * of any key in this array are replaced with the corresponding value.
  334. * See {@link Drupal.formatString}.
  335. * @param {object} [options]
  336. * Additional options for translation.
  337. * @param {string} [options.context='']
  338. * The context the source string belongs to.
  339. *
  340. * @return {string}
  341. * The formatted string.
  342. * The translated string.
  343. */
  344. Drupal.t = function (str, args, options) {
  345. options = options || {};
  346. options.context = options.context || '';
  347. // Fetch the localized version of the string.
  348. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) {
  349. str = drupalTranslations.strings[options.context][str];
  350. }
  351. if (args) {
  352. str = Drupal.formatString(str, args);
  353. }
  354. return str;
  355. };
  356. /**
  357. * Returns the URL to a Drupal page.
  358. *
  359. * @param {string} path
  360. * Drupal path to transform to URL.
  361. *
  362. * @return {string}
  363. * The full URL.
  364. */
  365. Drupal.url = function (path) {
  366. return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
  367. };
  368. /**
  369. * Returns the passed in URL as an absolute URL.
  370. *
  371. * @param {string} url
  372. * The URL string to be normalized to an absolute URL.
  373. *
  374. * @return {string}
  375. * The normalized, absolute URL.
  376. *
  377. * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
  378. * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
  379. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
  380. */
  381. Drupal.url.toAbsolute = function (url) {
  382. var urlParsingNode = document.createElement('a');
  383. // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
  384. // strings may throw an exception.
  385. try {
  386. url = decodeURIComponent(url);
  387. }
  388. catch (e) {
  389. // Empty.
  390. }
  391. urlParsingNode.setAttribute('href', url);
  392. // IE <= 7 normalizes the URL when assigned to the anchor node similar to
  393. // the other browsers.
  394. return urlParsingNode.cloneNode(false).href;
  395. };
  396. /**
  397. * Returns true if the URL is within Drupal's base path.
  398. *
  399. * @param {string} url
  400. * The URL string to be tested.
  401. *
  402. * @return {bool}
  403. * `true` if local.
  404. *
  405. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
  406. */
  407. Drupal.url.isLocal = function (url) {
  408. // Always use browser-derived absolute URLs in the comparison, to avoid
  409. // attempts to break out of the base path using directory traversal.
  410. var absoluteUrl = Drupal.url.toAbsolute(url);
  411. var protocol = location.protocol;
  412. // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
  413. // as local as well.
  414. if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
  415. protocol = 'https:';
  416. }
  417. var baseUrl = protocol + '//' + location.host + drupalSettings.path.baseUrl.slice(0, -1);
  418. // Decoding non-UTF-8 strings may throw an exception.
  419. try {
  420. absoluteUrl = decodeURIComponent(absoluteUrl);
  421. }
  422. catch (e) {
  423. // Empty.
  424. }
  425. try {
  426. baseUrl = decodeURIComponent(baseUrl);
  427. }
  428. catch (e) {
  429. // Empty.
  430. }
  431. // The given URL matches the site's base URL, or has a path under the site's
  432. // base URL.
  433. return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
  434. };
  435. /**
  436. * Formats a string containing a count of items.
  437. *
  438. * This function ensures that the string is pluralized correctly. Since
  439. * {@link Drupal.t} is called by this function, make sure not to pass
  440. * already-localized strings to it.
  441. *
  442. * See the documentation of the server-side
  443. * \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
  444. * function for more details.
  445. *
  446. * @param {number} count
  447. * The item count to display.
  448. * @param {string} singular
  449. * The string for the singular case. Please make sure it is clear this is
  450. * singular, to ease translation (e.g. use "1 new comment" instead of "1
  451. * new"). Do not use @count in the singular string.
  452. * @param {string} plural
  453. * The string for the plural case. Please make sure it is clear this is
  454. * plural, to ease translation. Use @count in place of the item count, as in
  455. * "@count new comments".
  456. * @param {object} [args]
  457. * An object of replacements pairs to make after translation. Incidences
  458. * of any key in this array are replaced with the corresponding value.
  459. * See {@link Drupal.formatString}.
  460. * Note that you do not need to include @count in this array.
  461. * This replacement is done automatically for the plural case.
  462. * @param {object} [options]
  463. * The options to pass to the {@link Drupal.t} function.
  464. *
  465. * @return {string}
  466. * A translated string.
  467. */
  468. Drupal.formatPlural = function (count, singular, plural, args, options) {
  469. args = args || {};
  470. args['@count'] = count;
  471. var pluralDelimiter = drupalSettings.pluralDelimiter;
  472. var translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
  473. var index = 0;
  474. // Determine the index of the plural form.
  475. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) {
  476. index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula['default'];
  477. }
  478. else if (args['@count'] !== 1) {
  479. index = 1;
  480. }
  481. return translations[index];
  482. };
  483. /**
  484. * Encodes a Drupal path for use in a URL.
  485. *
  486. * For aesthetic reasons slashes are not escaped.
  487. *
  488. * @param {string} item
  489. * Unencoded path.
  490. *
  491. * @return {string}
  492. * The encoded path.
  493. */
  494. Drupal.encodePath = function (item) {
  495. return window.encodeURIComponent(item).replace(/%2F/g, '/');
  496. };
  497. /**
  498. * Generates the themed representation of a Drupal object.
  499. *
  500. * All requests for themed output must go through this function. It examines
  501. * the request and routes it to the appropriate theme function. If the current
  502. * theme does not provide an override function, the generic theme function is
  503. * called.
  504. *
  505. * @example
  506. * <caption>To retrieve the HTML for text that should be emphasized and
  507. * displayed as a placeholder inside a sentence.</caption>
  508. * Drupal.theme('placeholder', text);
  509. *
  510. * @namespace
  511. *
  512. * @param {function} func
  513. * The name of the theme function to call.
  514. * @param {...args}
  515. * Additional arguments to pass along to the theme function.
  516. *
  517. * @return {string|object|HTMLElement|jQuery}
  518. * Any data the theme function returns. This could be a plain HTML string,
  519. * but also a complex object.
  520. */
  521. Drupal.theme = function (func) {
  522. var args = Array.prototype.slice.apply(arguments, [1]);
  523. if (func in Drupal.theme) {
  524. return Drupal.theme[func].apply(this, args);
  525. }
  526. };
  527. /**
  528. * Formats text for emphasized display in a placeholder inside a sentence.
  529. *
  530. * @param {string} str
  531. * The text to format (plain-text).
  532. *
  533. * @return {string}
  534. * The formatted text (html).
  535. */
  536. Drupal.theme.placeholder = function (str) {
  537. return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
  538. };
  539. })(Drupal, window.drupalSettings, window.drupalTranslations);