3 * Defines the Drupal JavaScript API.
7 * A jQuery object, typically the return value from a `$(selector)` call.
9 * Holds an HTMLElement or a collection of HTMLElements.
11 * @typedef {object} jQuery
13 * @prop {number} length=0
14 * Number of elements contained in the jQuery object.
18 * Variable generated by Drupal that holds all translated strings from PHP.
20 * Content of this variable is automatically created by Drupal when using the
21 * Interface Translation module. It holds the translation of strings used on
24 * This variable is used to pass data from the backend to the frontend. Data
25 * contained in `drupalSettings` is used during behavior initialization.
29 * @var {object} drupalTranslations
33 * Global Drupal object.
35 * All Drupal JavaScript APIs are contained in this namespace.
41 window.Drupal = {behaviors: {}, locale: {}};
43 // JavaScript should be made compatible with libraries other than jQuery by
44 // wrapping it in an anonymous closure.
45 (function (Drupal, drupalSettings, drupalTranslations) {
50 * Helper to rethrow errors asynchronously.
52 * This way Errors bubbles up outside of the original callstack, making it
53 * easier to debug errors in the browser.
55 * @param {Error|string} error
56 * The error to be thrown.
58 Drupal.throwError = function (error) {
59 setTimeout(function () { throw error; }, 0);
63 * Custom error thrown after attach/detach if one or more behaviors failed.
64 * Initializes the JavaScript behaviors for page loads and Ajax requests.
66 * @callback Drupal~behaviorAttach
68 * @param {HTMLDocument|HTMLElement} context
69 * An element to detach behaviors from.
70 * @param {?object} settings
71 * An object containing settings for the current context. It is rarely used.
73 * @see Drupal.attachBehaviors
77 * Reverts and cleans up JavaScript behavior initialization.
79 * @callback Drupal~behaviorDetach
81 * @param {HTMLDocument|HTMLElement} context
82 * An element to attach behaviors to.
83 * @param {object} settings
84 * An object containing settings for the current context.
85 * @param {string} trigger
86 * One of `'unload'`, `'move'`, or `'serialize'`.
88 * @see Drupal.detachBehaviors
92 * @typedef {object} Drupal~behavior
94 * @prop {Drupal~behaviorAttach} attach
95 * Function run on page load and after an Ajax call.
96 * @prop {Drupal~behaviorDetach} detach
97 * Function run when content is serialized or removed from the page.
101 * Holds all initialization methods.
103 * @namespace Drupal.behaviors
105 * @type {Object.<string, Drupal~behavior>}
109 * Defines a behavior to be run during attach and detach phases.
111 * Attaches all registered behaviors to a page element.
113 * Behaviors are event-triggered actions that attach to page elements,
114 * enhancing default non-JavaScript UIs. Behaviors are registered in the
115 * {@link Drupal.behaviors} object using the method 'attach' and optionally
118 * {@link Drupal.attachBehaviors} is added below to the `jQuery.ready` event
119 * and therefore runs on initial page load. Developers implementing Ajax in
120 * their solutions should also call this function after new page content has
121 * been loaded, feeding in an element to be processed, in order to attach all
122 * behaviors to the new content.
124 * Behaviors should use `var elements =
125 * $(context).find(selector).once('behavior-name');` to ensure the behavior is
126 * attached only once to a given element. (Doing so enables the reprocessing
127 * of given elements, which may be needed on occasion despite the ability to
128 * limit behavior attachment to a particular element.)
131 * Drupal.behaviors.behaviorName = {
132 * attach: function (context, settings) {
135 * detach: function (context, settings, trigger) {
140 * @param {HTMLDocument|HTMLElement} [context=document]
141 * An element to attach behaviors to.
142 * @param {object} [settings=drupalSettings]
143 * An object containing settings for the current context. If none is given,
144 * the global {@link drupalSettings} object is used.
146 * @see Drupal~behaviorAttach
147 * @see Drupal.detachBehaviors
149 * @throws {Drupal~DrupalBehaviorError}
151 Drupal.attachBehaviors = function (context, settings) {
152 context = context || document;
153 settings = settings || drupalSettings;
154 var behaviors = Drupal.behaviors;
155 // Execute all of them.
156 for (var i in behaviors) {
157 if (behaviors.hasOwnProperty(i) && typeof behaviors[i].attach === 'function') {
158 // Don't stop the execution of behaviors in case of an error.
160 behaviors[i].attach(context, settings);
163 Drupal.throwError(e);
170 * Detaches registered behaviors from a page element.
172 * Developers implementing Ajax in their solutions should call this function
173 * before page content is about to be removed, feeding in an element to be
174 * processed, in order to allow special behaviors to detach from the content.
176 * Such implementations should use `.findOnce()` and `.removeOnce()` to find
177 * elements with their corresponding `Drupal.behaviors.behaviorName.attach`
178 * implementation, i.e. `.removeOnce('behaviorName')`, to ensure the behavior
179 * is detached only from previously processed elements.
181 * @param {HTMLDocument|HTMLElement} [context=document]
182 * An element to detach behaviors from.
183 * @param {object} [settings=drupalSettings]
184 * An object containing settings for the current context. If none given,
185 * the global {@link drupalSettings} object is used.
186 * @param {string} [trigger='unload']
187 * A string containing what's causing the behaviors to be detached. The
188 * possible triggers are:
189 * - `'unload'`: The context element is being removed from the DOM.
190 * - `'move'`: The element is about to be moved within the DOM (for example,
191 * during a tabledrag row swap). After the move is completed,
192 * {@link Drupal.attachBehaviors} is called, so that the behavior can undo
193 * whatever it did in response to the move. Many behaviors won't need to
194 * do anything simply in response to the element being moved, but because
195 * IFRAME elements reload their "src" when being moved within the DOM,
196 * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
198 * - `'serialize'`: When an Ajax form is submitted, this is called with the
199 * form as the context. This provides every behavior within the form an
200 * opportunity to ensure that the field elements have correct content
201 * in them before the form is serialized. The canonical use-case is so
202 * that WYSIWYG editors can update the hidden textarea to which they are
205 * @throws {Drupal~DrupalBehaviorError}
207 * @see Drupal~behaviorDetach
208 * @see Drupal.attachBehaviors
210 Drupal.detachBehaviors = function (context, settings, trigger) {
211 context = context || document;
212 settings = settings || drupalSettings;
213 trigger = trigger || 'unload';
214 var behaviors = Drupal.behaviors;
215 // Execute all of them.
216 for (var i in behaviors) {
217 if (behaviors.hasOwnProperty(i) && typeof behaviors[i].detach === 'function') {
218 // Don't stop the execution of behaviors in case of an error.
220 behaviors[i].detach(context, settings, trigger);
223 Drupal.throwError(e);
230 * Encodes special characters in a plain-text string for display as HTML.
232 * @param {string} str
233 * The string to be encoded.
236 * The encoded string.
238 * @ingroup sanitization
240 Drupal.checkPlain = function (str) {
242 .replace(/&/g, '&')
243 .replace(/"/g, '"')
244 .replace(/</g, '<')
245 .replace(/>/g, '>');
250 * Replaces placeholders with sanitized values in a string.
252 * @param {string} str
253 * A string with placeholders.
254 * @param {object} args
255 * An object of replacements pairs to make. Incidences of any key in this
256 * array are replaced with the corresponding value. Based on the first
257 * character of the key, the value is escaped and/or themed:
258 * - `'!variable'`: inserted as is.
259 * - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}).
260 * - `'%variable'`: escape text and theme as a placeholder for user-
261 * submitted content ({@link Drupal.checkPlain} +
262 * `{@link Drupal.theme}('placeholder')`).
265 * The formatted string.
269 Drupal.formatString = function (str, args) {
271 var processedArgs = {};
272 // Transform arguments before inserting them.
273 for (var key in args) {
274 if (args.hasOwnProperty(key)) {
275 switch (key.charAt(0)) {
278 processedArgs[key] = Drupal.checkPlain(args[key]);
283 processedArgs[key] = args[key];
286 // Escaped and placeholder.
288 processedArgs[key] = Drupal.theme('placeholder', args[key]);
294 return Drupal.stringReplace(str, processedArgs, null);
298 * Replaces substring.
300 * The longest keys will be tried first. Once a substring has been replaced,
301 * its new value will not be searched again.
303 * @param {string} str
304 * A string with placeholders.
305 * @param {object} args
307 * @param {Array|null} keys
308 * Array of keys from `args`. Internal use only.
311 * The replaced string.
313 Drupal.stringReplace = function (str, args, keys) {
314 if (str.length === 0) {
318 // If the array of keys is not passed then collect the keys from the args.
319 if (!Array.isArray(keys)) {
321 for (var k in args) {
322 if (args.hasOwnProperty(k)) {
327 // Order the keys by the character length. The shortest one is the first.
328 keys.sort(function (a, b) { return a.length - b.length; });
331 if (keys.length === 0) {
335 // Take next longest one from the end.
336 var key = keys.pop();
337 var fragments = str.split(key);
340 for (var i = 0; i < fragments.length; i++) {
341 // Process each fragment with a copy of remaining keys.
342 fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
346 return fragments.join(args[key]);
350 * Translates strings to the page language, or a given language.
352 * See the documentation of the server-side t() function for further details.
354 * @param {string} str
355 * A string containing the English text to translate.
356 * @param {Object.<string, string>} [args]
357 * An object of replacements pairs to make after translation. Incidences
358 * of any key in this array are replaced with the corresponding value.
359 * See {@link Drupal.formatString}.
360 * @param {object} [options]
361 * Additional options for translation.
362 * @param {string} [options.context='']
363 * The context the source string belongs to.
366 * The formatted string.
367 * The translated string.
369 Drupal.t = function (str, args, options) {
370 options = options || {};
371 options.context = options.context || '';
373 // Fetch the localized version of the string.
374 if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) {
375 str = drupalTranslations.strings[options.context][str];
379 str = Drupal.formatString(str, args);
385 * Returns the URL to a Drupal page.
387 * @param {string} path
388 * Drupal path to transform to URL.
393 Drupal.url = function (path) {
394 return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
398 * Returns the passed in URL as an absolute URL.
400 * @param {string} url
401 * The URL string to be normalized to an absolute URL.
404 * The normalized, absolute URL.
406 * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
407 * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
408 * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
410 Drupal.url.toAbsolute = function (url) {
411 var urlParsingNode = document.createElement('a');
413 // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
414 // strings may throw an exception.
416 url = decodeURIComponent(url);
422 urlParsingNode.setAttribute('href', url);
424 // IE <= 7 normalizes the URL when assigned to the anchor node similar to
425 // the other browsers.
426 return urlParsingNode.cloneNode(false).href;
430 * Returns true if the URL is within Drupal's base path.
432 * @param {string} url
433 * The URL string to be tested.
438 * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
440 Drupal.url.isLocal = function (url) {
441 // Always use browser-derived absolute URLs in the comparison, to avoid
442 // attempts to break out of the base path using directory traversal.
443 var absoluteUrl = Drupal.url.toAbsolute(url);
444 var protocol = location.protocol;
446 // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
448 if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
451 var baseUrl = protocol + '//' + location.host + drupalSettings.path.baseUrl.slice(0, -1);
453 // Decoding non-UTF-8 strings may throw an exception.
455 absoluteUrl = decodeURIComponent(absoluteUrl);
461 baseUrl = decodeURIComponent(baseUrl);
467 // The given URL matches the site's base URL, or has a path under the site's
469 return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
473 * Formats a string containing a count of items.
475 * This function ensures that the string is pluralized correctly. Since
476 * {@link Drupal.t} is called by this function, make sure not to pass
477 * already-localized strings to it.
479 * See the documentation of the server-side
480 * \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
481 * function for more details.
483 * @param {number} count
484 * The item count to display.
485 * @param {string} singular
486 * The string for the singular case. Please make sure it is clear this is
487 * singular, to ease translation (e.g. use "1 new comment" instead of "1
488 * new"). Do not use @count in the singular string.
489 * @param {string} plural
490 * The string for the plural case. Please make sure it is clear this is
491 * plural, to ease translation. Use @count in place of the item count, as in
492 * "@count new comments".
493 * @param {object} [args]
494 * An object of replacements pairs to make after translation. Incidences
495 * of any key in this array are replaced with the corresponding value.
496 * See {@link Drupal.formatString}.
497 * Note that you do not need to include @count in this array.
498 * This replacement is done automatically for the plural case.
499 * @param {object} [options]
500 * The options to pass to the {@link Drupal.t} function.
503 * A translated string.
505 Drupal.formatPlural = function (count, singular, plural, args, options) {
507 args['@count'] = count;
509 var pluralDelimiter = drupalSettings.pluralDelimiter;
510 var translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
513 // Determine the index of the plural form.
514 if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) {
515 index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula['default'];
517 else if (args['@count'] !== 1) {
521 return translations[index];
525 * Encodes a Drupal path for use in a URL.
527 * For aesthetic reasons slashes are not escaped.
529 * @param {string} item
535 Drupal.encodePath = function (item) {
536 return window.encodeURIComponent(item).replace(/%2F/g, '/');
540 * Generates the themed representation of a Drupal object.
542 * All requests for themed output must go through this function. It examines
543 * the request and routes it to the appropriate theme function. If the current
544 * theme does not provide an override function, the generic theme function is
548 * <caption>To retrieve the HTML for text that should be emphasized and
549 * displayed as a placeholder inside a sentence.</caption>
550 * Drupal.theme('placeholder', text);
554 * @param {function} func
555 * The name of the theme function to call.
557 * Additional arguments to pass along to the theme function.
559 * @return {string|object|HTMLElement|jQuery}
560 * Any data the theme function returns. This could be a plain HTML string,
561 * but also a complex object.
563 Drupal.theme = function (func) {
564 var args = Array.prototype.slice.apply(arguments, [1]);
565 if (func in Drupal.theme) {
566 return Drupal.theme[func].apply(this, args);
571 * Formats text for emphasized display in a placeholder inside a sentence.
573 * @param {string} str
574 * The text to format (plain-text).
577 * The formatted text (html).
579 Drupal.theme.placeholder = function (str) {
580 return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
583 })(Drupal, window.drupalSettings, window.drupalTranslations);