Version 1
[yaffs-website] / web / core / misc / drupal.js
1 /**
2  * @file
3  * Defines the Drupal JavaScript API.
4  */
5
6 /**
7  * A jQuery object, typically the return value from a `$(selector)` call.
8  *
9  * Holds an HTMLElement or a collection of HTMLElements.
10  *
11  * @typedef {object} jQuery
12  *
13  * @prop {number} length=0
14  *   Number of elements contained in the jQuery object.
15  */
16
17 /**
18  * Variable generated by Drupal that holds all translated strings from PHP.
19  *
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
22  * the page.
23  *
24  * This variable is used to pass data from the backend to the frontend. Data
25  * contained in `drupalSettings` is used during behavior initialization.
26  *
27  * @global
28  *
29  * @var {object} drupalTranslations
30  */
31
32 /**
33  * Global Drupal object.
34  *
35  * All Drupal JavaScript APIs are contained in this namespace.
36  *
37  * @global
38  *
39  * @namespace
40  */
41 window.Drupal = {behaviors: {}, locale: {}};
42
43 // JavaScript should be made compatible with libraries other than jQuery by
44 // wrapping it in an anonymous closure.
45 (function (Drupal, drupalSettings, drupalTranslations) {
46
47   'use strict';
48
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   /**
63    * Custom error thrown after attach/detach if one or more behaviors failed.
64    * Initializes the JavaScript behaviors for page loads and Ajax requests.
65    *
66    * @callback Drupal~behaviorAttach
67    *
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.
72    *
73    * @see Drupal.attachBehaviors
74    */
75
76   /**
77    * Reverts and cleans up JavaScript behavior initialization.
78    *
79    * @callback Drupal~behaviorDetach
80    *
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'`.
87    *
88    * @see Drupal.detachBehaviors
89    */
90
91   /**
92    * @typedef {object} Drupal~behavior
93    *
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.
98    */
99
100   /**
101    * Holds all initialization methods.
102    *
103    * @namespace Drupal.behaviors
104    *
105    * @type {Object.<string, Drupal~behavior>}
106    */
107
108   /**
109    * Defines a behavior to be run during attach and detach phases.
110    *
111    * Attaches all registered behaviors to a page element.
112    *
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
116    * also 'detach'.
117    *
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.
123    *
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.)
129    *
130    * @example
131    * Drupal.behaviors.behaviorName = {
132    *   attach: function (context, settings) {
133    *     // ...
134    *   },
135    *   detach: function (context, settings, trigger) {
136    *     // ...
137    *   }
138    * };
139    *
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.
145    *
146    * @see Drupal~behaviorAttach
147    * @see Drupal.detachBehaviors
148    *
149    * @throws {Drupal~DrupalBehaviorError}
150    */
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.
159         try {
160           behaviors[i].attach(context, settings);
161         }
162         catch (e) {
163           Drupal.throwError(e);
164         }
165       }
166     }
167   };
168
169   /**
170    * Detaches registered behaviors from a page element.
171    *
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.
175    *
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.
180    *
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
197    *     take some action.
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
203    *     bound.
204    *
205    * @throws {Drupal~DrupalBehaviorError}
206    *
207    * @see Drupal~behaviorDetach
208    * @see Drupal.attachBehaviors
209    */
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.
219         try {
220           behaviors[i].detach(context, settings, trigger);
221         }
222         catch (e) {
223           Drupal.throwError(e);
224         }
225       }
226     }
227   };
228
229   /**
230    * Encodes special characters in a plain-text string for display as HTML.
231    *
232    * @param {string} str
233    *   The string to be encoded.
234    *
235    * @return {string}
236    *   The encoded string.
237    *
238    * @ingroup sanitization
239    */
240   Drupal.checkPlain = function (str) {
241     str = str.toString()
242       .replace(/&/g, '&amp;')
243       .replace(/"/g, '&quot;')
244       .replace(/</g, '&lt;')
245       .replace(/>/g, '&gt;');
246     return str;
247   };
248
249   /**
250    * Replaces placeholders with sanitized values in a string.
251    *
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')`).
263    *
264    * @return {string}
265    *   The formatted string.
266    *
267    * @see Drupal.t
268    */
269   Drupal.formatString = function (str, args) {
270     // Keep args intact.
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)) {
276           // Escaped only.
277           case '@':
278             processedArgs[key] = Drupal.checkPlain(args[key]);
279             break;
280
281           // Pass-through.
282           case '!':
283             processedArgs[key] = args[key];
284             break;
285
286           // Escaped and placeholder.
287           default:
288             processedArgs[key] = Drupal.theme('placeholder', args[key]);
289             break;
290         }
291       }
292     }
293
294     return Drupal.stringReplace(str, processedArgs, null);
295   };
296
297   /**
298    * Replaces substring.
299    *
300    * The longest keys will be tried first. Once a substring has been replaced,
301    * its new value will not be searched again.
302    *
303    * @param {string} str
304    *   A string with placeholders.
305    * @param {object} args
306    *   Key-value pairs.
307    * @param {Array|null} keys
308    *   Array of keys from `args`. Internal use only.
309    *
310    * @return {string}
311    *   The replaced string.
312    */
313   Drupal.stringReplace = function (str, args, keys) {
314     if (str.length === 0) {
315       return str;
316     }
317
318     // If the array of keys is not passed then collect the keys from the args.
319     if (!Array.isArray(keys)) {
320       keys = [];
321       for (var k in args) {
322         if (args.hasOwnProperty(k)) {
323           keys.push(k);
324         }
325       }
326
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; });
329     }
330
331     if (keys.length === 0) {
332       return str;
333     }
334
335     // Take next longest one from the end.
336     var key = keys.pop();
337     var fragments = str.split(key);
338
339     if (keys.length) {
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));
343       }
344     }
345
346     return fragments.join(args[key]);
347   };
348
349   /**
350    * Translates strings to the page language, or a given language.
351    *
352    * See the documentation of the server-side t() function for further details.
353    *
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.
364    *
365    * @return {string}
366    *   The formatted string.
367    *   The translated string.
368    */
369   Drupal.t = function (str, args, options) {
370     options = options || {};
371     options.context = options.context || '';
372
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];
376     }
377
378     if (args) {
379       str = Drupal.formatString(str, args);
380     }
381     return str;
382   };
383
384   /**
385    * Returns the URL to a Drupal page.
386    *
387    * @param {string} path
388    *   Drupal path to transform to URL.
389    *
390    * @return {string}
391    *   The full URL.
392    */
393   Drupal.url = function (path) {
394     return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
395   };
396
397   /**
398    * Returns the passed in URL as an absolute URL.
399    *
400    * @param {string} url
401    *   The URL string to be normalized to an absolute URL.
402    *
403    * @return {string}
404    *   The normalized, absolute URL.
405    *
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
409    */
410   Drupal.url.toAbsolute = function (url) {
411     var urlParsingNode = document.createElement('a');
412
413     // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
414     // strings may throw an exception.
415     try {
416       url = decodeURIComponent(url);
417     }
418     catch (e) {
419       // Empty.
420     }
421
422     urlParsingNode.setAttribute('href', url);
423
424     // IE <= 7 normalizes the URL when assigned to the anchor node similar to
425     // the other browsers.
426     return urlParsingNode.cloneNode(false).href;
427   };
428
429   /**
430    * Returns true if the URL is within Drupal's base path.
431    *
432    * @param {string} url
433    *   The URL string to be tested.
434    *
435    * @return {bool}
436    *   `true` if local.
437    *
438    * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
439    */
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;
445
446     // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
447     // as local as well.
448     if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
449       protocol = 'https:';
450     }
451     var baseUrl = protocol + '//' + location.host + drupalSettings.path.baseUrl.slice(0, -1);
452
453     // Decoding non-UTF-8 strings may throw an exception.
454     try {
455       absoluteUrl = decodeURIComponent(absoluteUrl);
456     }
457     catch (e) {
458       // Empty.
459     }
460     try {
461       baseUrl = decodeURIComponent(baseUrl);
462     }
463     catch (e) {
464       // Empty.
465     }
466
467     // The given URL matches the site's base URL, or has a path under the site's
468     // base URL.
469     return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
470   };
471
472   /**
473    * Formats a string containing a count of items.
474    *
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.
478    *
479    * See the documentation of the server-side
480    * \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
481    * function for more details.
482    *
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.
501    *
502    * @return {string}
503    *   A translated string.
504    */
505   Drupal.formatPlural = function (count, singular, plural, args, options) {
506     args = args || {};
507     args['@count'] = count;
508
509     var pluralDelimiter = drupalSettings.pluralDelimiter;
510     var translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
511     var index = 0;
512
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'];
516     }
517     else if (args['@count'] !== 1) {
518       index = 1;
519     }
520
521     return translations[index];
522   };
523
524   /**
525    * Encodes a Drupal path for use in a URL.
526    *
527    * For aesthetic reasons slashes are not escaped.
528    *
529    * @param {string} item
530    *   Unencoded path.
531    *
532    * @return {string}
533    *   The encoded path.
534    */
535   Drupal.encodePath = function (item) {
536     return window.encodeURIComponent(item).replace(/%2F/g, '/');
537   };
538
539   /**
540    * Generates the themed representation of a Drupal object.
541    *
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
545    * called.
546    *
547    * @example
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);
551    *
552    * @namespace
553    *
554    * @param {function} func
555    *   The name of the theme function to call.
556    * @param {...args}
557    *   Additional arguments to pass along to the theme function.
558    *
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.
562    */
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);
567     }
568   };
569
570   /**
571    * Formats text for emphasized display in a placeholder inside a sentence.
572    *
573    * @param {string} str
574    *   The text to format (plain-text).
575    *
576    * @return {string}
577    *   The formatted text (html).
578    */
579   Drupal.theme.placeholder = function (str) {
580     return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
581   };
582
583 })(Drupal, window.drupalSettings, window.drupalTranslations);