util.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. define(function(require, exports, module) {
  2. "use strict";
  3. var SUBSTITUTE_REG = /\\?\{([^{}]+)\}/g,
  4. EMPTY = '';
  5. var RE_TRIM = /^[\s\xa0]+|[\s\xa0]+$/g,
  6. trim = String.prototype.trim;
  7. var _trim = trim ?
  8. function(str) {
  9. return str == null ? EMPTY : trim.call(str);
  10. } : function(str) {
  11. return str == null ? EMPTY : (str + '').replace(RE_TRIM, EMPTY);
  12. };
  13. function upperCase() {
  14. return arguments[1].toUpperCase();
  15. }
  16. function Empty() {}
  17. function createObject(proto, constructor) {
  18. var newProto;
  19. if (Object.create) {
  20. newProto = Object.create(proto);
  21. } else {
  22. Empty.prototype = proto;
  23. newProto = new Empty();
  24. }
  25. newProto.constructor = constructor;
  26. return newProto;
  27. }
  28. function getNodes(node, rootNode) {
  29. if (!node) return;
  30. if (node.nodeType) return [node];
  31. var rootNode = rootNode && rootNode.nodeType ? rootNode : document;
  32. if (node && typeof node === "string") {
  33. return rootNode.querySelectorAll(node);
  34. }
  35. return;
  36. }
  37. // Useful for temporary DOM ids.
  38. var idCounter = 0;
  39. var getOffsetTop = function(el) {
  40. var offset = el.offsetTop;
  41. if (el.offsetParent != null) offset += getOffsetTop(el.offsetParent);
  42. return offset;
  43. };
  44. var getOffsetLeft = function(el) {
  45. var offset = el.offsetLeft;
  46. if (el.offsetParent != null) offset += getOffsetLeft(el.offsetParent);
  47. return offset;
  48. };
  49. var Util = {
  50. // Is a given variable an object?
  51. isObject: function(obj) {
  52. return obj === Object(obj);
  53. },
  54. isArray: Array.isArray || function(obj) {
  55. return toString.call(obj) == '[object Array]';
  56. },
  57. // Is a given array, string, or object empty?
  58. // An "empty" object has no enumerable own-properties.
  59. isEmpty: function(obj) {
  60. if (obj == null) return true;
  61. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  62. for (var key in obj)
  63. if (this.has(obj, key)) return false;
  64. return true;
  65. },
  66. mix: function(to, from, deep) {
  67. for (var i in from) {
  68. to[i] = from[i];
  69. }
  70. return to;
  71. },
  72. extend: function(r, s, px, sx) {
  73. if (!s || !r) {
  74. return r;
  75. }
  76. var sp = s.prototype,
  77. rp;
  78. // add prototype chain
  79. rp = createObject(sp, r);
  80. r.prototype = this.mix(rp, r.prototype);
  81. r.superclass = createObject(sp, s);
  82. // add prototype overrides
  83. if (px) {
  84. this.mix(rp, px);
  85. }
  86. // add object overrides
  87. if (sx) {
  88. this.mix(r, sx);
  89. }
  90. return r;
  91. },
  92. /**
  93. * test whether a string start with a specified substring
  94. * @param {String} str the whole string
  95. * @param {String} prefix a specified substring
  96. * @return {Boolean} whether str start with prefix
  97. * @member util
  98. */
  99. startsWith: function(str, prefix) {
  100. return str.lastIndexOf(prefix, 0) === 0;
  101. },
  102. /**
  103. * test whether a string end with a specified substring
  104. * @param {String} str the whole string
  105. * @param {String} suffix a specified substring
  106. * @return {Boolean} whether str end with suffix
  107. * @member util
  108. */
  109. endsWith: function(str, suffix) {
  110. var ind = str.length - suffix.length;
  111. return ind >= 0 && str.indexOf(suffix, ind) === ind;
  112. },
  113. /**
  114. * Removes the whitespace from the beginning and end of a string.
  115. * @method
  116. * @member util
  117. */
  118. trim: _trim,
  119. /**
  120. * Substitutes keywords in a string using an object/array.
  121. * Removes undef keywords and ignores escaped keywords.
  122. * @param {String} str template string
  123. * @param {Object} o json data
  124. * @member util
  125. * @param {RegExp} [regexp] to match a piece of template string
  126. */
  127. substitute: function(str, o, regexp) {
  128. if (typeof str !== 'string' || !o) {
  129. return str;
  130. }
  131. return str.replace(regexp || SUBSTITUTE_REG, function(match, name) {
  132. if (match.charAt(0) === '\\') {
  133. return match.slice(1);
  134. }
  135. return (o[name] === undefined) ? EMPTY : o[name];
  136. });
  137. },
  138. /**
  139. * vendors
  140. * @return { String } webkit|moz|ms|o
  141. * @memberOf Util
  142. */
  143. vendor: (function() {
  144. var el = document.createElement('div').style;
  145. var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
  146. transform,
  147. i = 0,
  148. l = vendors.length;
  149. for (; i < l; i++) {
  150. transform = vendors[i] + 'ransform';
  151. if (transform in el) return vendors[i].substr(0, vendors[i].length - 1);
  152. }
  153. return false;
  154. })(),
  155. /**
  156. * add vendor to attribute
  157. * @memberOf Util
  158. * @param {String} attrName name of attribute
  159. * @return { String }
  160. **/
  161. prefixStyle: function(attrName) {
  162. if (this.vendor === false) return false;
  163. if (this.vendor === '') return attrName;
  164. return this.vendor + attrName.charAt(0).toUpperCase() + attrName.substr(1);
  165. },
  166. /**
  167. * judge if has class
  168. * @memberOf Util
  169. * @param {HTMLElement} el
  170. * @param {String} className
  171. * @return {Boolean}
  172. */
  173. hasClass: function(el, className) {
  174. return el && el.className && className && el.className.indexOf(className) != -1;
  175. },
  176. /**
  177. * add className for the element
  178. * @memberOf Util
  179. * @param {HTMLElement} el
  180. * @param {String} className
  181. */
  182. addClass: function(el, className) {
  183. if (el && className && !this.hasClass(el, className)) {
  184. el.className += " " + className;
  185. }
  186. },
  187. /**
  188. * remove className for the element
  189. * @memberOf Util
  190. * @param {HTMLElement} el
  191. * @param {String} className
  192. */
  193. removeClass: function(el, className) {
  194. if (el && el.className && className) {
  195. el.className = el.className.replace(className, "");
  196. }
  197. },
  198. /**
  199. * remove an element
  200. * @memberOf Util
  201. * @param {HTMLElement} el
  202. */
  203. remove: function(el) {
  204. if (!el || !el.parentNode) return;
  205. el.parentNode.removeChild(el);
  206. },
  207. /**
  208. * get offset top
  209. * @memberOf Util
  210. * @param {HTMLElement} el
  211. * @return {Number} offsetTop
  212. */
  213. getOffsetTop: getOffsetTop,
  214. /**
  215. * get offset left
  216. * @memberOf Util
  217. * @param {HTMLElement} el
  218. * @return {Number} offsetLeft
  219. */
  220. getOffsetLeft: getOffsetLeft,
  221. /**
  222. * get offset left
  223. * @memberOf Util
  224. * @param {HTMLElement} el
  225. * @param {String} selector
  226. * @param {HTMLElement} rootNode
  227. * @return {HTMLElement} parent element
  228. */
  229. findParentEl: function(el, selector, rootNode) {
  230. var rs = null,
  231. parent = null;
  232. var type = /^#/.test(selector) ? "id" : /^\./.test(selector) ? "class" : "tag";
  233. var sel = selector.replace(/\.|#/g, "");
  234. if (rootNode && typeof rootNode === "string") {
  235. rootNode = document.querySelector(rootNode);
  236. }
  237. rootNode = rootNode || document.body;
  238. if (!el || !selector) return;
  239. if (type == "class" && el.className && el.className.match(sel)) {
  240. return el;
  241. } else if (type == "id" && el.id && _trim(el.id) == sel) {
  242. return el;
  243. } else if (type == "tag" && el.tagName.toLowerCase() == sel) {
  244. return el;
  245. }
  246. while (!rs) {
  247. if (parent == rootNode) break;
  248. parent = el.parentNode;
  249. if (!parent) break;
  250. if ((type == "class" && parent.className && parent.className.match(sel)) || (type == "id" && parent.id && _trim(parent.id) == sel) || (type == "tag" && parent.tagName && parent.tagName.toLowerCase() == sel)) {
  251. rs = parent
  252. return rs;
  253. break;
  254. } else {
  255. el = parent;
  256. }
  257. }
  258. return null;
  259. },
  260. /**
  261. * Generate a unique integer id (unique within the entire client session).
  262. * @param {String} prefix
  263. * @return {String} guid
  264. */
  265. guid: function(prefix) {
  266. var id = ++idCounter + '';
  267. return prefix ? prefix + id : id;
  268. },
  269. /**
  270. * judge if is an android os
  271. * @return {Boolean} [description]
  272. */
  273. isAndroid: function() {
  274. return /Android /.test(window.navigator.appVersion);
  275. },
  276. /**
  277. * judge if is an android device with low performance
  278. * @return {Boolean}
  279. */
  280. isBadAndroid: function() {
  281. return /Android /.test(window.navigator.appVersion) && !(/Chrome\/\d/.test(window.navigator.appVersion))
  282. },
  283. px2Num: function(px) {
  284. return Number(px.replace(/px/, ''));
  285. },
  286. getNodes: getNodes,
  287. getNode: function(node, rootNode) {
  288. var nodes = getNodes(node, rootNode);
  289. return nodes && nodes[0];
  290. },
  291. stringifyStyle: function(style) {
  292. var styleStr = "";
  293. for (var i in style) {
  294. styleStr += [i, ":", style[i], ";"].join("");
  295. }
  296. return styleStr;
  297. }
  298. }
  299. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  300. var names = ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'];
  301. for (var i = 0; i < names.length; i++) {
  302. Util['is' + names[i]] = function(obj) {
  303. return toString.call(obj) == '[object ' + names[i] + ']';
  304. };
  305. }
  306. if (typeof module == 'object' && module.exports) {
  307. module.exports = Util;
  308. }
  309. /** ignored by jsdoc **/
  310. else {
  311. return Util;
  312. }
  313. });