drupal.js 19 KB

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