PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/misc/drupal.js

https://github.com/zzolo/incl
JavaScript | 402 lines | 308 code | 6 blank | 88 comment | 8 complexity | d4515f21acd461ca04304233bf0daa1e MD5 | raw file
  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. * @return
  173. * The translated string.
  174. */
  175. Drupal.t = function (str, args) {
  176. // Fetch the localized version of the string.
  177. if (Drupal.locale.strings && Drupal.locale.strings[str]) {
  178. str = Drupal.locale.strings[str];
  179. }
  180. if (args) {
  181. str = Drupal.formatString(str, args);
  182. }
  183. return str;
  184. };
  185. /**
  186. * Format a string containing a count of items.
  187. *
  188. * This function ensures that the string is pluralized correctly. Since Drupal.t() is
  189. * called by this function, make sure not to pass already-localized strings to it.
  190. *
  191. * See the documentation of the server-side format_plural() function for further details.
  192. *
  193. * @param count
  194. * The item count to display.
  195. * @param singular
  196. * The string for the singular case. Please make sure it is clear this is
  197. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  198. * Do not use @count in the singular string.
  199. * @param plural
  200. * The string for the plural case. Please make sure it is clear this is plural,
  201. * to ease translation. Use @count in place of the item count, as in "@count
  202. * new comments".
  203. * @param args
  204. * An object of replacements pairs to make after translation. Incidences
  205. * of any key in this array are replaced with the corresponding value.
  206. * See Drupal.formatString().
  207. * Note that you do not need to include @count in this array.
  208. * This replacement is done automatically for the plural case.
  209. * @return
  210. * A translated string.
  211. */
  212. Drupal.formatPlural = function (count, singular, plural, args) {
  213. var args = args || {};
  214. args['@count'] = count;
  215. // Determine the index of the plural form.
  216. var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);
  217. if (index == 0) {
  218. return Drupal.t(singular, args);
  219. }
  220. else if (index == 1) {
  221. return Drupal.t(plural, args);
  222. }
  223. else {
  224. args['@count[' + index + ']'] = args['@count'];
  225. delete args['@count'];
  226. return Drupal.t(plural.replace('@count', '@count[' + index + ']'), args);
  227. }
  228. };
  229. /**
  230. * Generate the themed representation of a Drupal object.
  231. *
  232. * All requests for themed output must go through this function. It examines
  233. * the request and routes it to the appropriate theme function. If the current
  234. * theme does not provide an override function, the generic theme function is
  235. * called.
  236. *
  237. * For example, to retrieve the HTML for text that should be emphasized and
  238. * displayed as a placeholder inside a sentence, call
  239. * Drupal.theme('placeholder', text).
  240. *
  241. * @param func
  242. * The name of the theme function to call.
  243. * @param ...
  244. * Additional arguments to pass along to the theme function.
  245. * @return
  246. * Any data the theme function returns. This could be a plain HTML string,
  247. * but also a complex object.
  248. */
  249. Drupal.theme = function (func) {
  250. var args = Array.prototype.slice.apply(arguments, [1]);
  251. return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
  252. };
  253. /**
  254. * Freeze the current body height (as minimum height). Used to prevent
  255. * unnecessary upwards scrolling when doing DOM manipulations.
  256. */
  257. Drupal.freezeHeight = function () {
  258. Drupal.unfreezeHeight();
  259. $('<div id="freeze-height"></div>').css({
  260. position: 'absolute',
  261. top: '0px',
  262. left: '0px',
  263. width: '1px',
  264. height: $('body').css('height')
  265. }).appendTo('body');
  266. };
  267. /**
  268. * Unfreeze the body height.
  269. */
  270. Drupal.unfreezeHeight = function () {
  271. $('#freeze-height').remove();
  272. };
  273. /**
  274. * Encodes a Drupal path for use in a URL.
  275. *
  276. * For aesthetic reasons slashes are not escaped.
  277. */
  278. Drupal.encodePath = function (item, uri) {
  279. uri = uri || location.href;
  280. return encodeURIComponent(item).replace(/%2F/g, '/');
  281. };
  282. /**
  283. * Get the text selection in a textarea.
  284. */
  285. Drupal.getSelection = function (element) {
  286. if (typeof element.selectionStart != 'number' && document.selection) {
  287. // The current selection.
  288. var range1 = document.selection.createRange();
  289. var range2 = range1.duplicate();
  290. // Select all text.
  291. range2.moveToElementText(element);
  292. // Now move 'dummy' end point to end point of original range.
  293. range2.setEndPoint('EndToEnd', range1);
  294. // Now we can calculate start and end points.
  295. var start = range2.text.length - range1.text.length;
  296. var end = start + range1.text.length;
  297. return { 'start': start, 'end': end };
  298. }
  299. return { 'start': element.selectionStart, 'end': element.selectionEnd };
  300. };
  301. /**
  302. * Build an error message from an Ajax response.
  303. */
  304. Drupal.ajaxError = function (xmlhttp, uri) {
  305. var statusCode, statusText, pathText, responseText, readyStateText, message;
  306. if (xmlhttp.status) {
  307. statusCode = "\n" + Drupal.t("An AJAX HTTP error occurred.") + "\n" + Drupal.t("HTTP Result Code: !status", {'!status': xmlhttp.status});
  308. }
  309. else {
  310. statusCode = "\n" + Drupal.t("An AJAX HTTP request terminated abnormally.");
  311. }
  312. statusCode += "\n" + Drupal.t("Debugging information follows.");
  313. pathText = "\n" + Drupal.t("Path: !uri", {'!uri': uri} );
  314. statusText = '';
  315. // In some cases, when statusCode == 0, xmlhttp.statusText may not be defined.
  316. // Unfortunately, testing for it with typeof, etc, doesn't seem to catch that
  317. // and the test causes an exception. So we need to catch the exception here.
  318. try {
  319. statusText = "\n" + Drupal.t("StatusText: !statusText", {'!statusText': $.trim(xmlhttp.statusText)});
  320. }
  321. catch (e) {}
  322. responseText = '';
  323. // Again, we don't have a way to know for sure whether accessing
  324. // xmlhttp.responseText is going to throw an exception. So we'll catch it.
  325. try {
  326. responseText = "\n" + Drupal.t("ResponseText: !responseText", {'!responseText': $.trim(xmlhttp.responseText) } );
  327. } catch (e) {}
  328. // Make the responseText more readable by stripping HTML tags and newlines.
  329. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,"");
  330. responseText = responseText.replace(/[\n]+\s+/g,"\n");
  331. // We don't need readyState except for status == 0.
  332. readyStateText = xmlhttp.status == 0 ? ("\n" + Drupal.t("ReadyState: !readyState", {'!readyState': xmlhttp.readyState})) : "";
  333. message = statusCode + pathText + statusText + responseText + readyStateText;
  334. return message;
  335. };
  336. // Class indicating that JS is enabled; used for styling purpose.
  337. $('html').addClass('js');
  338. // 'js enabled' cookie.
  339. document.cookie = 'has_js=1; path=/';
  340. /**
  341. * Additions to jQuery.support.
  342. */
  343. $(function () {
  344. /**
  345. * Boolean indicating whether or not position:fixed is supported.
  346. */
  347. if (jQuery.support.positionFixed === undefined) {
  348. var el = $('<div style="position:fixed; top:10px" />').appendTo(document.body);
  349. jQuery.support.positionFixed = el[0].offsetTop === 10;
  350. el.remove();
  351. }
  352. });
  353. //Attach all behaviors.
  354. $(function () {
  355. Drupal.attachBehaviors(document, Drupal.settings);
  356. });
  357. /**
  358. * The default themes.
  359. */
  360. Drupal.theme.prototype = {
  361. /**
  362. * Formats text for emphasized display in a placeholder inside a sentence.
  363. *
  364. * @param str
  365. * The text to format (plain-text).
  366. * @return
  367. * The formatted text (html).
  368. */
  369. placeholder: function (str) {
  370. return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
  371. }
  372. };
  373. })(jQuery);