drupal.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };
  2. // Allow other JavaScript libraries to use $.
  3. jQuery.noConflict();
  4. (function ($) {
  5. /**
  6. * Attach all registered behaviors to a page element.
  7. *
  8. * Behaviors are event-triggered actions that attach to page elements, enhancing
  9. * default non-JavaScript UIs. Behaviors are registered in the Drupal.behaviors
  10. * object using the method 'attach' and optionally also 'detach' as follows:
  11. * @code
  12. * Drupal.behaviors.behaviorName = {
  13. * attach: function (context, settings) {
  14. * ...
  15. * },
  16. * detach: function (context, settings, trigger) {
  17. * ...
  18. * }
  19. * };
  20. * @endcode
  21. *
  22. * Drupal.attachBehaviors is added below to the jQuery ready event and so
  23. * runs on initial page load. Developers implementing AHAH/Ajax in their
  24. * solutions should also call this function after new page content has been
  25. * loaded, feeding in an element to be processed, in order to attach all
  26. * behaviors to the new content.
  27. *
  28. * Behaviors should use
  29. * @code
  30. * $(selector).once('behavior-name', function () {
  31. * ...
  32. * });
  33. * @endcode
  34. * to ensure the behavior is attached only once to a given element. (Doing so
  35. * enables the reprocessing of given elements, which may be needed on occasion
  36. * despite the ability to limit behavior attachment to a particular element.)
  37. *
  38. * @param context
  39. * An element to attach behaviors to. If none is given, the document element
  40. * is used.
  41. * @param settings
  42. * An object containing settings for the current context. If none given, the
  43. * global Drupal.settings object is used.
  44. */
  45. Drupal.attachBehaviors = function (context, settings) {
  46. context = context || document;
  47. settings = settings || Drupal.settings;
  48. // Execute all of them.
  49. $.each(Drupal.behaviors, function () {
  50. if ($.isFunction(this.attach)) {
  51. this.attach(context, settings);
  52. }
  53. });
  54. };
  55. /**
  56. * Detach registered behaviors from a page element.
  57. *
  58. * Developers implementing AHAH/Ajax in their solutions should call this
  59. * function before page content is about to be removed, feeding in an element
  60. * to be processed, in order to allow special behaviors to detach from the
  61. * content.
  62. *
  63. * Such implementations should look for the class name that was added in their
  64. * corresponding Drupal.behaviors.behaviorName.attach implementation, i.e.
  65. * behaviorName-processed, to ensure the behavior is detached only from
  66. * previously processed elements.
  67. *
  68. * @param context
  69. * An element to detach behaviors from. If none is given, the document element
  70. * is used.
  71. * @param settings
  72. * An object containing settings for the current context. If none given, the
  73. * global Drupal.settings object is used.
  74. * @param trigger
  75. * A string containing what's causing the behaviors to be detached. The
  76. * possible triggers are:
  77. * - unload: (default) The context element is being removed from the DOM.
  78. * - move: The element is about to be moved within the DOM (for example,
  79. * during a tabledrag row swap). After the move is completed,
  80. * Drupal.attachBehaviors() is called, so that the behavior can undo
  81. * whatever it did in response to the move. Many behaviors won't need to
  82. * do anything simply in response to the element being moved, but because
  83. * IFRAME elements reload their "src" when being moved within the DOM,
  84. * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
  85. * take some action.
  86. * - serialize: When an Ajax form is submitted, this is called with the
  87. * form as the context. This provides every behavior within the form an
  88. * opportunity to ensure that the field elements have correct content
  89. * in them before the form is serialized. The canonical use-case is so
  90. * that WYSIWYG editors can update the hidden textarea to which they are
  91. * bound.
  92. *
  93. * @see Drupal.attachBehaviors
  94. */
  95. Drupal.detachBehaviors = function (context, settings, trigger) {
  96. context = context || document;
  97. settings = settings || Drupal.settings;
  98. trigger = trigger || 'unload';
  99. // Execute all of them.
  100. $.each(Drupal.behaviors, function () {
  101. if ($.isFunction(this.detach)) {
  102. this.detach(context, settings, trigger);
  103. }
  104. });
  105. };
  106. /**
  107. * Encode special characters in a plain-text string for display as HTML.
  108. *
  109. * @ingroup sanitization
  110. */
  111. Drupal.checkPlain = function (str) {
  112. var character, regex,
  113. replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
  114. str = String(str);
  115. for (character in replace) {
  116. if (replace.hasOwnProperty(character)) {
  117. regex = new RegExp(character, 'g');
  118. str = str.replace(regex, replace[character]);
  119. }
  120. }
  121. return str;
  122. };
  123. /**
  124. * Replace placeholders with sanitized values in a string.
  125. *
  126. * @param str
  127. * A string with placeholders.
  128. * @param args
  129. * An object of replacements pairs to make. Incidences of any key in this
  130. * array are replaced with the corresponding value. Based on the first
  131. * character of the key, the value is escaped and/or themed:
  132. * - !variable: inserted as is
  133. * - @variable: escape plain text to HTML (Drupal.checkPlain)
  134. * - %variable: escape text and theme as a placeholder for user-submitted
  135. * content (checkPlain + Drupal.theme('placeholder'))
  136. *
  137. * @see Drupal.t()
  138. * @ingroup sanitization
  139. */
  140. Drupal.formatString = function(str, args) {
  141. // Transform arguments before inserting them.
  142. for (var key in args) {
  143. switch (key.charAt(0)) {
  144. // Escaped only.
  145. case '@':
  146. args[key] = Drupal.checkPlain(args[key]);
  147. break;
  148. // Pass-through.
  149. case '!':
  150. break;
  151. // Escaped and placeholder.
  152. case '%':
  153. default:
  154. args[key] = Drupal.theme('placeholder', args[key]);
  155. break;
  156. }
  157. str = str.replace(key, args[key]);
  158. }
  159. return str;
  160. };
  161. /**
  162. * Translate strings to the page language or a given language.
  163. *
  164. * See the documentation of the server-side t() function for further details.
  165. *
  166. * @param str
  167. * A string containing the English string to translate.
  168. * @param args
  169. * An object of replacements pairs to make after translation. Incidences
  170. * of any key in this array are replaced with the corresponding value.
  171. * See Drupal.formatString().
  172. *
  173. * @param options
  174. * - 'context' (defaults to the empty context): The context the source string
  175. * belongs to.
  176. *
  177. * @return
  178. * The translated string.
  179. */
  180. Drupal.t = function (str, args, options) {
  181. options = options || {};
  182. options.context = options.context || '';
  183. // Fetch the localized version of the string.
  184. if (Drupal.locale.strings && Drupal.locale.strings[options.context] && Drupal.locale.strings[options.context][str]) {
  185. str = Drupal.locale.strings[options.context][str];
  186. }
  187. if (args) {
  188. str = Drupal.formatString(str, args);
  189. }
  190. return str;
  191. };
  192. /**
  193. * Format a string containing a count of items.
  194. *
  195. * This function ensures that the string is pluralized correctly. Since Drupal.t() is
  196. * called by this function, make sure not to pass already-localized strings to it.
  197. *
  198. * See the documentation of the server-side format_plural() function for further details.
  199. *
  200. * @param count
  201. * The item count to display.
  202. * @param singular
  203. * The string for the singular case. Please make sure it is clear this is
  204. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  205. * Do not use @count in the singular string.
  206. * @param plural
  207. * The string for the plural case. Please make sure it is clear this is plural,
  208. * to ease translation. Use @count in place of the item count, as in "@count
  209. * new comments".
  210. * @param args
  211. * An object of replacements pairs to make after translation. Incidences
  212. * of any key in this array are replaced with the corresponding value.
  213. * See Drupal.formatString().
  214. * Note that you do not need to include @count in this array.
  215. * This replacement is done automatically for the plural case.
  216. * @param options
  217. * The options to pass to the Drupal.t() function.
  218. * @return
  219. * A translated string.
  220. */
  221. Drupal.formatPlural = function (count, singular, plural, args, options) {
  222. var args = args || {};
  223. args['@count'] = count;
  224. // Determine the index of the plural form.
  225. var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);
  226. if (index == 0) {
  227. return Drupal.t(singular, args, options);
  228. }
  229. else if (index == 1) {
  230. return Drupal.t(plural, args, options);
  231. }
  232. else {
  233. args['@count[' + index + ']'] = args['@count'];
  234. delete args['@count'];
  235. return Drupal.t(plural.replace('@count', '@count[' + index + ']'), args, options);
  236. }
  237. };
  238. /**
  239. * Generate the themed representation of a Drupal object.
  240. *
  241. * All requests for themed output must go through this function. It examines
  242. * the request and routes it to the appropriate theme function. If the current
  243. * theme does not provide an override function, the generic theme function is
  244. * called.
  245. *
  246. * For example, to retrieve the HTML for text that should be emphasized and
  247. * displayed as a placeholder inside a sentence, call
  248. * Drupal.theme('placeholder', text).
  249. *
  250. * @param func
  251. * The name of the theme function to call.
  252. * @param ...
  253. * Additional arguments to pass along to the theme function.
  254. * @return
  255. * Any data the theme function returns. This could be a plain HTML string,
  256. * but also a complex object.
  257. */
  258. Drupal.theme = function (func) {
  259. var args = Array.prototype.slice.apply(arguments, [1]);
  260. return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
  261. };
  262. /**
  263. * Freeze the current body height (as minimum height). Used to prevent
  264. * unnecessary upwards scrolling when doing DOM manipulations.
  265. */
  266. Drupal.freezeHeight = function () {
  267. Drupal.unfreezeHeight();
  268. $('<div id="freeze-height"></div>').css({
  269. position: 'absolute',
  270. top: '0px',
  271. left: '0px',
  272. width: '1px',
  273. height: $('body').css('height')
  274. }).appendTo('body');
  275. };
  276. /**
  277. * Unfreeze the body height.
  278. */
  279. Drupal.unfreezeHeight = function () {
  280. $('#freeze-height').remove();
  281. };
  282. /**
  283. * Encodes a Drupal path for use in a URL.
  284. *
  285. * For aesthetic reasons slashes are not escaped.
  286. */
  287. Drupal.encodePath = function (item, uri) {
  288. uri = uri || location.href;
  289. return encodeURIComponent(item).replace(/%2F/g, '/');
  290. };
  291. /**
  292. * Get the text selection in a textarea.
  293. */
  294. Drupal.getSelection = function (element) {
  295. if (typeof element.selectionStart != 'number' && document.selection) {
  296. // The current selection.
  297. var range1 = document.selection.createRange();
  298. var range2 = range1.duplicate();
  299. // Select all text.
  300. range2.moveToElementText(element);
  301. // Now move 'dummy' end point to end point of original range.
  302. range2.setEndPoint('EndToEnd', range1);
  303. // Now we can calculate start and end points.
  304. var start = range2.text.length - range1.text.length;
  305. var end = start + range1.text.length;
  306. return { 'start': start, 'end': end };
  307. }
  308. return { 'start': element.selectionStart, 'end': element.selectionEnd };
  309. };
  310. /**
  311. * Build an error message from an Ajax response.
  312. */
  313. Drupal.ajaxError = function (xmlhttp, uri) {
  314. var statusCode, statusText, pathText, responseText, readyStateText, message;
  315. if (xmlhttp.status) {
  316. statusCode = "\n" + Drupal.t("An AJAX HTTP error occurred.") + "\n" + Drupal.t("HTTP Result Code: !status", {'!status': xmlhttp.status});
  317. }
  318. else {
  319. statusCode = "\n" + Drupal.t("An AJAX HTTP request terminated abnormally.");
  320. }
  321. statusCode += "\n" + Drupal.t("Debugging information follows.");
  322. pathText = "\n" + Drupal.t("Path: !uri", {'!uri': uri} );
  323. statusText = '';
  324. // In some cases, when statusCode == 0, xmlhttp.statusText may not be defined.
  325. // Unfortunately, testing for it with typeof, etc, doesn't seem to catch that
  326. // and the test causes an exception. So we need to catch the exception here.
  327. try {
  328. statusText = "\n" + Drupal.t("StatusText: !statusText", {'!statusText': $.trim(xmlhttp.statusText)});
  329. }
  330. catch (e) {}
  331. responseText = '';
  332. // Again, we don't have a way to know for sure whether accessing
  333. // xmlhttp.responseText is going to throw an exception. So we'll catch it.
  334. try {
  335. responseText = "\n" + Drupal.t("ResponseText: !responseText", {'!responseText': $.trim(xmlhttp.responseText) } );
  336. } catch (e) {}
  337. // Make the responseText more readable by stripping HTML tags and newlines.
  338. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,"");
  339. responseText = responseText.replace(/[\n]+\s+/g,"\n");
  340. // We don't need readyState except for status == 0.
  341. readyStateText = xmlhttp.status == 0 ? ("\n" + Drupal.t("ReadyState: !readyState", {'!readyState': xmlhttp.readyState})) : "";
  342. message = statusCode + pathText + statusText + responseText + readyStateText;
  343. return message;
  344. };
  345. // Class indicating that JS is enabled; used for styling purpose.
  346. $('html').addClass('js');
  347. // 'js enabled' cookie.
  348. document.cookie = 'has_js=1; path=/';
  349. /**
  350. * Additions to jQuery.support.
  351. */
  352. $(function () {
  353. /**
  354. * Boolean indicating whether or not position:fixed is supported.
  355. */
  356. if (jQuery.support.positionFixed === undefined) {
  357. var el = $('<div style="position:fixed; top:10px" />').appendTo(document.body);
  358. jQuery.support.positionFixed = el[0].offsetTop === 10;
  359. el.remove();
  360. }
  361. });
  362. //Attach all behaviors.
  363. $(function () {
  364. Drupal.attachBehaviors(document, Drupal.settings);
  365. });
  366. /**
  367. * The default themes.
  368. */
  369. Drupal.theme.prototype = {
  370. /**
  371. * Formats text for emphasized display in a placeholder inside a sentence.
  372. *
  373. * @param str
  374. * The text to format (plain-text).
  375. * @return
  376. * The formatted text (html).
  377. */
  378. placeholder: function (str) {
  379. return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
  380. }
  381. };
  382. })(jQuery);