o2.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. /** ***** BEGIN LICENSE BLOCK *****
  2. * |------------------------------------------------------------------------------|
  3. * | O2OA 活力办公 创意无限 o2.js |
  4. * |------------------------------------------------------------------------------|
  5. * | Distributed under the AGPL license: |
  6. * |------------------------------------------------------------------------------|
  7. * | Copyright © 2018, o2oa.net, o2server.io O2 Team |
  8. * | All rights reserved. |
  9. * |------------------------------------------------------------------------------|
  10. *
  11. * This file is part of O2OA.
  12. *
  13. * O2OA is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License as published by
  15. * the Free Software Foundation, either version 3 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * O2OA is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with Foobar. If not, see <https://www.gnu.org/licenses/>.
  25. *
  26. * ***** END LICENSE BLOCK ******/
  27. /* load o2 Core
  28. * |------------------------------------------------------------------------------|
  29. * |addReady: o2.addReady(fn), |
  30. * |------------------------------------------------------------------------------|
  31. * |load: o2.load(urls, callback, reload) |
  32. * |loadCss: o2.loadCss(urls, dom, callback, reload, doc) |
  33. * |------------------------------------------------------------------------------|
  34. * |typeOf: o2.typeOf(o) |
  35. * |------------------------------------------------------------------------------|
  36. * |uuid: o2.uuid() |
  37. * |------------------------------------------------------------------------------|
  38. */
  39. (function(){
  40. var _href = window.location.href;
  41. var _debug = (_href.indexOf("debugger")!==-1);
  42. var _par = _href.substr(_href.lastIndexOf("?")+1, _href.length);
  43. var _lp = "zh-cn";
  44. if (_par){
  45. var _parList = _par.split("&");
  46. for (var i=0; i<_parList.length; i++){
  47. var _v = _parList[i];
  48. var _kv = _v.split("=");
  49. if (_kv[0].toLowerCase()==="lg") _lp = _kv[1];
  50. }
  51. }
  52. this.o2 = {
  53. "version": {
  54. "v": '2.0.9',
  55. "build": "2018.11.22",
  56. "info": "O2OA 活力办公 创意无限. Copyright © 2018, o2oa.net O2 Team All rights reserved."
  57. },
  58. "session": {
  59. "isDebugger": _debug,
  60. "path": "/o2_core/o2"
  61. },
  62. "language": _lp,
  63. "splitStr": /\s*(?:,|;)\s*/
  64. };
  65. var _attempt = function(){
  66. for (var i = 0, l = arguments.length; i < l; i++){
  67. try {
  68. arguments[i]();
  69. return arguments[i];
  70. } catch (e){}
  71. }
  72. return null;
  73. };
  74. var _typeOf = function(item){
  75. if (item == null) return 'null';
  76. if (item.$family != null) return item.$family();
  77. if (item.constructor == window.Array) return "array";
  78. if (item.nodeName){
  79. if (item.nodeType == 1) return 'element';
  80. if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
  81. } else if (typeof item.length == 'number'){
  82. if (item.callee) return 'arguments';
  83. }
  84. return typeof item;
  85. };
  86. this.o2.typeOf = _typeOf;
  87. var _addListener = function(dom, type, fn){
  88. if (type == 'unload'){
  89. var old = fn, self = this;
  90. fn = function(){
  91. _removeListener(dom, 'unload', fn);
  92. old();
  93. };
  94. }
  95. if (dom.addEventListener) dom.addEventListener(type, fn, !!arguments[2]);
  96. else dom.attachEvent('on' + type, fn);
  97. };
  98. var _removeListener = function(dom, type, fn){
  99. if (dom.removeEventListener) dom.removeEventListener(type, fn, !!arguments[2]);
  100. else dom.detachEvent('on' + type, fn);
  101. };
  102. //http request class
  103. var _request = (function(){
  104. var XMLHTTP = function(){ return new XMLHttpRequest(); };
  105. var MSXML2 = function(){ return new ActiveXObject('MSXML2.XMLHTTP'); };
  106. var MSXML = function(){ return new ActiveXObject('Microsoft.XMLHTTP'); };
  107. return _attempt(XMLHTTP, MSXML2, MSXML);
  108. })();
  109. var _returnBase = function(number, base) {
  110. return (number).toString(base).toUpperCase();
  111. };
  112. var _getIntegerBits = function(val, start, end){
  113. var base16 = _returnBase(val, 16);
  114. var quadArray = new Array();
  115. var quadString = '';
  116. var i = 0;
  117. for (i = 0; i < base16.length; i++) {
  118. quadArray.push(base16.substring(i, i + 1));
  119. }
  120. for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) {
  121. if (!quadArray[i] || quadArray[i] == '')
  122. quadString += '0';
  123. else
  124. quadString += quadArray[i];
  125. }
  126. return quadString;
  127. };
  128. var _rand = function(max) {
  129. return Math.floor(Math.random() * (max + 1));
  130. };
  131. this.o2.addListener = _addListener;
  132. this.o2.removeListener = _removeListener;
  133. //uuid
  134. var _uuid = function(){
  135. var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
  136. var dc = new Date();
  137. var t = dc.getTime() - dg.getTime();
  138. var tl = _getIntegerBits(t, 0, 31);
  139. var tm = _getIntegerBits(t, 32, 47);
  140. var thv = _getIntegerBits(t, 48, 59) + '1';
  141. var csar = _getIntegerBits(_rand(4095), 0, 7);
  142. var csl = _getIntegerBits(_rand(4095), 0, 7);
  143. var n = _getIntegerBits(_rand(8191), 0, 7)
  144. + _getIntegerBits(_rand(8191), 8, 15)
  145. + _getIntegerBits(_rand(8191), 0, 7)
  146. + _getIntegerBits(_rand(8191), 8, 15)
  147. + _getIntegerBits(_rand(8191), 0, 15);
  148. return tl + tm + thv + csar + csl + n;
  149. };
  150. this.o2.uuid = _uuid;
  151. var _runCallback = function(callback, key, par){
  152. if (typeOf(callback).toLowerCase() === 'function'){
  153. if (key.toLowerCase()==="success") callback.apply(callback, par);
  154. }else{
  155. if (typeOf(callback).toLowerCase()==='object'){
  156. var name = ("on-"+key).camelCase();
  157. if (callback[name]) callback[name].apply(callback, par);
  158. }
  159. }
  160. };
  161. this.o2.runCallback = _runCallback;
  162. //load js, css, html adn all.
  163. var _getAllOptions = function(options){
  164. var doc = (options && options.doc) || document;
  165. if (!doc.unid) doc.unid = _uuid();
  166. return {
  167. "noCache": !!(options && options.nocache),
  168. "reload": !!(options && options.reload),
  169. "sequence": !!(options && options.sequence),
  170. "doc": doc,
  171. "dom": (options && options.dom) || document.body,
  172. "bind": (options && options.bind) || null,
  173. "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'
  174. }
  175. };
  176. var _getCssOptions = function(options){
  177. var doc = (options && options.doc) || document;
  178. if (!doc.unid) doc.unid = _uuid();
  179. return {
  180. "noCache": !!(options && options.nocache),
  181. "reload": !!(options && options.reload),
  182. "sequence": !!(options && options.sequence),
  183. "doc": doc,
  184. "dom": (options && options.dom) || null
  185. }
  186. };
  187. var _getJsOptions = function(options){
  188. var doc = (options && options.doc) || document;
  189. if (!doc.unid) doc.unid = _uuid();
  190. return {
  191. "noCache": !!(options && options.nocache),
  192. "reload": !!(options && options.reload),
  193. "sequence": (!(options && options.sequence == false)),
  194. "doc": doc
  195. }
  196. };
  197. var _getHtmlOptions = function(options){
  198. var doc = (options && options.doc) || document;
  199. if (!doc.unid) doc.unid = _uuid();
  200. return {
  201. "noCache": !!(options && options.nocache),
  202. "reload": !!(options && options.reload),
  203. "sequence": !!(options && options.sequence),
  204. "doc": doc,
  205. "dom": (options && options.dom) || null,
  206. "bind": (options && options.bind) || null,
  207. "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'
  208. }
  209. };
  210. var _xhr_get = function(url, success, failure, completed){
  211. var xhr = new _request();
  212. xhr.open("GET", url, true);
  213. var _checkCssLoaded= function(_, err){
  214. if (!(xhr.readyState == 4)) return;
  215. if (err){
  216. if (completed) completed(xhr);
  217. return;
  218. }
  219. _removeListener(xhr, 'readystatechange', _checkCssLoaded);
  220. _removeListener(xhr, 'load', _checkCssLoaded);
  221. _removeListener(xhr, 'error', _checkCssErrorLoaded);
  222. if (err) {failure(xhr); return}
  223. var status = xhr.status;
  224. status = (status == 1223) ? 204 : status;
  225. if ((status >= 200 && status < 300))
  226. success(xhr);
  227. else if ((status >= 300 && status < 400))
  228. failure(xhr);
  229. else
  230. failure(xhr);
  231. if (completed) completed(xhr);
  232. };
  233. var _checkCssErrorLoaded= function(err){ _checkCssLoaded(err) };
  234. if ("load" in xhr) _addListener(xhr, "load", _checkCssLoaded);
  235. if ("error" in xhr) _addListener(xhr, "load", _checkCssErrorLoaded);
  236. _addListener(xhr, "readystatechange", _checkCssLoaded);
  237. xhr.send();
  238. };
  239. var _loadSequence = function(ms, cb, op, n, thisLoaded, loadSingle, uuid, fun){
  240. loadSingle(ms[n], function(module){
  241. if (module) thisLoaded.push(module);
  242. n++;
  243. if (fun) fun(module);
  244. if (n===ms.length){
  245. if (cb) cb(thisLoaded);
  246. }else{
  247. _loadSequence(ms, cb, op, n, thisLoaded, loadSingle, uuid, fun);
  248. }
  249. }, op, uuid);
  250. };
  251. var _loadDisarray = function(ms, cb, op, thisLoaded, loadSingle, uuid, fun){
  252. var count=0;
  253. for (var i=0; i<ms.length; i++){
  254. loadSingle(ms[i], function(module){
  255. if (module) thisLoaded.push(module);
  256. count++;
  257. if (fun) fun(module);
  258. if (count===ms.length) if (cb) cb(thisLoaded);
  259. }, op, uuid);
  260. }
  261. };
  262. //load js
  263. //use framework url
  264. var _frameworks = {
  265. "o2.core": ["/o2_core/o2/o2.core.js"],
  266. "o2.more": ["/o2_core/o2/o2.more.js"],
  267. "ie_adapter": ["/o2_lib/o2/ie_adapter.js"],
  268. "jquery": ["/o2_lib/jquery/jquery.min.js"],
  269. "mootools": ["/o2_lib/mootools/mootools-1.6.0_all.js"],
  270. "ckeditor": ["/o2_lib/htmleditor/ckeditor4114/ckeditor.js"],
  271. "ckeditor5": ["/o2_lib/htmleditor/ckeditor5-12-1-0/ckeditor.js"],
  272. "raphael": ["/o2_lib/raphael/raphael.js"],
  273. "d3": ["/o2_lib/d3/d3.min.js"],
  274. "ace": ["/o2_lib/ace/src-noconflict/ace.js","/o2_lib/ace/src-noconflict/ext-language_tools.js"],
  275. "JSBeautifier": ["/o2_lib/JSBeautifier/beautify.js"],
  276. "JSBeautifier_css": ["/o2_lib/JSBeautifier/beautify-css.js"],
  277. "JSBeautifier_html": ["/o2_lib/JSBeautifier/beautify-html.js"],
  278. "JSONTemplate": ["/o2_lib/mootools/plugin/Template.js"],
  279. "kity": ["/o2_lib/kityminder/kity/kity.min.js"],
  280. "kityminder": ["/o2_lib/kityminder/core/dist/kityminder.core.js"]
  281. };
  282. var _loaded = {};
  283. var _loadedCss = {};
  284. var _loadedHtml = {};
  285. var _loadCssRunning = {};
  286. var _loadCssQueue = [];
  287. var _loadSingle = function(module, callback, op){
  288. var url = module;
  289. var uuid = _uuid();
  290. if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uuid : addr_uri+"?v="+uuid;
  291. var key = encodeURIComponent(url+op.doc.unid);
  292. if (!op.reload) if (_loaded[key]){
  293. if (callback)callback(); return;
  294. }
  295. var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
  296. var s = op.doc.createElement('script');
  297. head.appendChild(s);
  298. s.id = uuid;
  299. s.src = url;
  300. var _checkScriptLoaded = function(_, isAbort, err){
  301. if (isAbort || !s.readyState || s.readyState === "loaded" || s.readyState === "complete") {
  302. var scriptObj = {"module": module, "id": uuid, "script": s, "doc": op.doc};
  303. if (!err) _loaded[key] = scriptObj;
  304. _removeListener(s, 'readystatechange', _checkScriptLoaded);
  305. _removeListener(s, 'load', _checkScriptLoaded);
  306. _removeListener(s, 'error', _checkScriptErrorLoaded);
  307. if (!isAbort || err){
  308. if (err){
  309. if (s) head.removeChild(s);
  310. if (callback)callback();
  311. }else{
  312. //head.removeChild(s);
  313. if (callback)callback(scriptObj);
  314. }
  315. }
  316. }
  317. };
  318. var _checkScriptErrorLoaded = function(e, err){
  319. console.log("Error: load javascript module: "+module);
  320. _checkScriptLoaded(e, true, "error");
  321. };
  322. if ('onreadystatechange' in s) _addListener(s, 'readystatechange', _checkScriptLoaded);
  323. _addListener(s, 'load', _checkScriptLoaded);
  324. _addListener(s, 'error', _checkScriptErrorLoaded);
  325. };
  326. var _load = function(urls, options, callback){
  327. var ms = (_typeOf(urls)==="array") ? urls : [urls];
  328. var op = (_typeOf(options)==="object") ? _getJsOptions(options) : _getJsOptions(null);
  329. var cb = (_typeOf(options)==="function") ? options : callback;
  330. var modules = [];
  331. for (var i=0; i<ms.length; i++){
  332. var url = ms[i];
  333. var module = _frameworks[url] || url;
  334. if (_typeOf(module)==="array"){
  335. modules = modules.concat(module)
  336. }else{
  337. modules.push(module)
  338. }
  339. }
  340. var thisLoaded = [];
  341. if (op.sequence){
  342. _loadSequence(modules, cb, op, 0, thisLoaded, _loadSingle);
  343. }else{
  344. _loadDisarray(modules, cb, op, thisLoaded, _loadSingle);
  345. }
  346. };
  347. this.o2.load = _load;
  348. //load css
  349. var _loadSingleCss = function(module, callback, op, uuid){
  350. var url = module;
  351. var uid = _uuid();
  352. if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
  353. var key = encodeURIComponent(url+op.doc.unid);
  354. if (_loadCssRunning[key]){
  355. _loadCssQueue.push(function(){
  356. _loadSingleCss(module, callback, op, uuid);
  357. });
  358. return;
  359. }
  360. if (_loadedCss[key]) uuid = _loadedCss[key]["class"];
  361. if (op.dom) _parseDom(op.dom, function(node){ if (node.className.indexOf(uuid) == -1) node.className += ((node.className) ? " "+uuid : uuid);}, op.doc);
  362. var completed = function(){
  363. if (_loadCssRunning[key]){
  364. _loadCssRunning[key] = false;
  365. delete _loadCssRunning[key];
  366. }
  367. if (_loadCssQueue && _loadCssQueue.length){
  368. (_loadCssQueue.shift())();
  369. }
  370. };
  371. if (_loadedCss[key])if (!op.reload){
  372. if (callback)callback(_loadedCss[key]);
  373. completed();
  374. return;
  375. }
  376. var success = function(xhr){
  377. var cssText = xhr.responseText;
  378. try{
  379. if (cssText){
  380. if (op.bind) cssText = cssText.bindJson(op.bind);
  381. if (op.dom){
  382. var rex = new RegExp("(.+)(?=\\{)", "g");
  383. var match;
  384. while ((match = rex.exec(cssText)) !== null) {
  385. var prefix = "." + uuid + " ";
  386. var rule = prefix + match[0];
  387. cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
  388. rex.lastIndex = rex.lastIndex + prefix.length;
  389. }
  390. }
  391. var style = op.doc.createElement("style");
  392. style.setAttribute("type", "text/css");
  393. var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
  394. head.appendChild(style);
  395. if(style.styleSheet){
  396. var setFunc = function(){
  397. style.styleSheet.cssText = cssText;
  398. };
  399. if(style.styleSheet.disabled){
  400. setTimeout(setFunc, 10);
  401. }else{
  402. setFunc();
  403. }
  404. }else{
  405. var cssTextNode = op.doc.createTextNode(cssText);
  406. style.appendChild(cssTextNode);
  407. }
  408. }
  409. style.id = uid;
  410. var styleObj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid};
  411. _loadedCss[key] = styleObj;
  412. if (callback) callback(styleObj);
  413. }catch (e){
  414. if (callback) callback();
  415. return;
  416. }
  417. };
  418. var failure = function(xhr){
  419. console.log("Error: load css module: "+module);
  420. if (callback) callback();
  421. };
  422. _loadCssRunning[key] = true;
  423. _xhr_get(url, success, failure, completed);
  424. };
  425. var _parseDomString = function(dom, fn, sourceDoc){
  426. var doc = sourceDoc || document;
  427. var list = doc.querySelectorAll(dom);
  428. if (list.length) for (var i=0; i<list.length; i++) _parseDomElement(list[i], fn);
  429. };
  430. var _parseDomElement = function(dom, fn){
  431. if (fn) fn(dom);
  432. };
  433. var _parseDom = function(dom, fn, sourceDoc){
  434. var domType = _typeOf(dom);
  435. if (domType==="string") _parseDomString(dom, fn, sourceDoc);
  436. if (domType==="element") _parseDomElement(dom, fn);
  437. if (domType==="array") for (var i=0; i<dom.length; i++) _parseDom(dom[i], fn, sourceDoc);
  438. };
  439. var _loadCss = function(modules, options, callback){
  440. var ms = (_typeOf(modules)==="array") ? modules : [modules];
  441. var op = (_typeOf(options)==="object") ? _getCssOptions(options) : _getCssOptions(null);
  442. var cb = (_typeOf(options)==="function") ? options : callback;
  443. var uuid = "css"+_uuid();
  444. var thisLoaded = [];
  445. if (op.sequence){
  446. _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleCss, uuid);
  447. }else{
  448. _loadDisarray(ms, cb, op, thisLoaded, _loadSingleCss, uuid);
  449. }
  450. };
  451. var _removeCss = function(modules, doc){
  452. var thisDoc = doc || document;
  453. var ms = (_typeOf(modules)==="array") ? modules : [modules];
  454. for (var i=0; i<ms.length; i++){
  455. var module = modules[i];
  456. var k = encodeURIComponent(module+(thisDoc.unid||""));
  457. var removeCss = _loadedCss[k];
  458. if (!removeCss) for (key in _loadedCss){
  459. if (_loadedCss[key].id==module){
  460. removeCss = _loadedCss[key];
  461. k = key;
  462. break;
  463. }
  464. }
  465. if (removeCss){
  466. delete _loadedCss[k];
  467. var styleNode = removeCss.doc.getElementById(removeCss.id);
  468. if (styleNode) styleNode.parentNode.removeChild(styleNode);
  469. removeCss = null;
  470. }
  471. }
  472. };
  473. this.o2.loadCss = _loadCss;
  474. this.o2.removeCss = _removeCss;
  475. Element.prototype.loadCss = function(modules, options, callback){
  476. var op = (_typeOf(options)==="object") ? options : {};
  477. var cb = (_typeOf(options)==="function") ? options : callback;
  478. op.dom = this;
  479. _loadCss(modules, op, cb);
  480. };
  481. //load html
  482. _loadSingleHtml = function(module, callback, op){
  483. var url = module;
  484. var uid = _uuid();
  485. if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
  486. var key = encodeURIComponent(url+op.doc.unid);
  487. if (!op.reload) if (_loadedHtml[key]){ if (callback)callback(_loadedHtml[key]); return; }
  488. var success = function(xhr){
  489. var htmlObj = {"module": module, "id": uid, "data": xhr.responseText, "doc": op.doc};
  490. _loadedHtml[key] = htmlObj;
  491. if (callback) callback(htmlObj);
  492. };
  493. var failure = function(){
  494. console.log("Error: load html module: "+module);
  495. if (callback) callback();
  496. };
  497. _xhr_get(url, success, failure);
  498. };
  499. var _injectHtml = function(op, data){
  500. if (op.bind) data = data.bindJson(op.bind);
  501. if (op.dom) _parseDom(op.dom, function(node){ node.insertAdjacentHTML(op.position, data) }, op.doc);
  502. };
  503. var _loadHtml = function(modules, options, callback){
  504. var ms = (_typeOf(modules)==="array") ? modules : [modules];
  505. var op = (_typeOf(options)==="object") ? _getHtmlOptions(options) : _getHtmlOptions(null);
  506. var cb = (_typeOf(options)==="function") ? options : callback;
  507. var thisLoaded = [];
  508. if (op.sequence){
  509. _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
  510. }else{
  511. _loadDisarray(ms, cb, op, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
  512. }
  513. };
  514. this.o2.loadHtml = _loadHtml;
  515. Element.prototype.loadHtml = function(modules, options, callback){
  516. var op = (_typeOf(options)==="object") ? options : {};
  517. var cb = (_typeOf(options)==="function") ? options : callback;
  518. op.dom = this;
  519. _loadHtml(modules, op, cb);
  520. };
  521. //load all
  522. _loadAll = function(modules, options, callback){
  523. //var ms = (_typeOf(modules)==="array") ? modules : [modules];
  524. var op = (_typeOf(options)==="object") ? _getAllOptions(options) : _getAllOptions(null);
  525. var cb = (_typeOf(options)==="function") ? options : callback;
  526. var ms, htmls, styles, sctipts;
  527. var _htmlLoaded=(!modules.html), _cssLoaded=(!modules.css), _jsLoaded=(!modules.js);
  528. var _checkloaded = function(){
  529. if (_htmlLoaded && _cssLoaded && _jsLoaded) if (cb) cb(htmls, styles, sctipts);
  530. };
  531. if (modules.html){
  532. _loadHtml(modules.html, op, function(h){
  533. htmls = h;
  534. _htmlLoaded = true;
  535. _checkloaded();
  536. });
  537. }
  538. if (modules.css){
  539. _loadCss(modules.css, op, function(s){
  540. styles = s;
  541. _cssLoaded = true;
  542. _checkloaded();
  543. });
  544. }
  545. if (modules.js){
  546. _load(modules.js, op, function(s){
  547. sctipts = s;
  548. _jsLoaded = true;
  549. _checkloaded();
  550. });
  551. }
  552. };
  553. this.o2.loadAll = _loadAll;
  554. Element.prototype.loadAll = function(modules, options, callback){
  555. var op = (_typeOf(options)==="object") ? options : {};
  556. var cb = (_typeOf(options)==="function") ? options : callback;
  557. op.dom = this;
  558. _loadAll(modules, op, cb);
  559. };
  560. //json template
  561. // _parseText = function(html, json){
  562. // var _ht = html;
  563. // var regexp = /(text\{).+?\}/g;
  564. // var r = _ht.match(regexp);
  565. // if(r) if (r.length){
  566. // for (var i=0; i<r.length; i++){
  567. // var text = r[i].substr(0,r[i].lastIndexOf("}"));
  568. // text = text.substr(text.indexOf("{")+1,text.length);
  569. // var value = _jsonText(json ,text);
  570. // _ht = _ht.replace(/(text\{).+?\}/,value);
  571. // }
  572. // }
  573. // return _ht;
  574. // };
  575. // _parseEach = function(html, json){
  576. // var _ht = html;
  577. // var regexp = /(\{each\([\s\S]+\)\})[\s\S]+?(\{endEach\})/g;
  578. // var r = _ht.match(regexp);
  579. // if(r){
  580. // if (r.length){
  581. // for (var i=0; i<r.length; i++){
  582. // var eachItemsStr = r[i].substr(0,r[i].indexOf(")"));
  583. // eachItemsStr = eachItemsStr.substr(eachItemsStr.indexOf("(")+1,eachItemsStr.length);
  584. // var pars = eachItemsStr.split(/,[\s]*/g);
  585. // eachItemsPar = pars[0];
  586. // eachItemsCount = pars[1].toInt();
  587. //
  588. // var eachItems = _jsonText(json ,eachItemsPar);
  589. // if (eachItems) if (eachItemsCount==0) eachItemsCount = eachItems.length;
  590. //
  591. // var eachContentStr = r[i].substr(0,r[i].lastIndexOf("{endEach}"));
  592. // eachContentStr = eachContentStr.substr(eachContentStr.indexOf("}")+1,eachContentStr.length);
  593. //
  594. // var eachContent = [];
  595. // if (eachItems){
  596. // for (var n=0; n<Math.min(eachItems.length, eachItemsCount); n++){
  597. // var item = eachItems[n];
  598. // if (item){
  599. // var tmpEachContentStr = eachContentStr;
  600. // var textReg = /(eachText\{).+?\}/g;
  601. // texts = tmpEachContentStr.match(textReg);
  602. // if (texts){
  603. // if (texts.length){
  604. // for (var j=0; j<texts.length; j++){
  605. // var text = texts[j].substr(0,texts[j].lastIndexOf("}"));
  606. // text = text.substr(text.indexOf("{")+1,text.length);
  607. //
  608. // var value = _jsonText(item ,text);
  609. // tmpEachContentStr = tmpEachContentStr.replace(/(eachText\{).+?\}/,value);
  610. // }
  611. // }
  612. // }
  613. // eachContent.push(tmpEachContentStr);
  614. // }
  615. // }
  616. // }
  617. // _ht = _ht.replace(/(\{each\([\s\S]+\)\})[\s\S]+?(\{endEach\})/,eachContent.join(""));
  618. // }
  619. // }
  620. // }
  621. // return _ht;
  622. // };
  623. // _jsonText = function(json, text){
  624. // var $ = json;
  625. // var f = eval("(x = function($){\n return "+text+";\n})");
  626. // returnValue = f.apply(json, [$]);
  627. // if (returnValue===undefined) returnValue="";
  628. // returnValue = returnValue.toString();
  629. // return returnValue || "";
  630. // };
  631. // var _bindJson = function(str, json){
  632. // return _parseEach(_parseText(str, json), json);
  633. // };
  634. // o2.bindJson = _bindJson;
  635. // String.prototype.bindJson = function(json){
  636. // return _parseEach(_parseText(this, json), json);
  637. // };
  638. var _getIfBlockEnd = function(v){
  639. var rex = /(\{\{if\s+)|(\{\{\s*end if\s*\}\})/gmi;
  640. var rexEnd = /\{\{\s*end if\s*\}\}/gmi;
  641. var subs = 1;
  642. while ((match = rex.exec(v)) !== null) {
  643. var fullMatch = match[0];
  644. if (fullMatch.search(rexEnd)!==-1){
  645. subs--;
  646. if (subs==0) break;
  647. }else{
  648. subs++
  649. }
  650. }
  651. if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
  652. return {"codeIndex": v.length-1, "lastIndex": v.length-1};
  653. }
  654. var _getEachBlockEnd = function(v){
  655. var rex = /(\{\{each\s+)|(\{\{\s*end each\s*\}\})/gmi;
  656. var rexEnd = /\{\{\s*end each\s*\}\}/gmi;
  657. var subs = 1;
  658. while ((match = rex.exec(v)) !== null) {
  659. var fullMatch = match[0];
  660. if (fullMatch.search(rexEnd)!==-1){
  661. subs--;
  662. if (subs==0) break;
  663. }else{
  664. subs++;
  665. }
  666. }
  667. if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
  668. return {"codeIndex": v.length-1, "lastIndex": v.length-1};
  669. }
  670. var _parseHtml = function(str, json){
  671. var v = str;
  672. var rex = /(\{\{\s*)[\s\S]*?(\s*\}\})/gmi;
  673. var match;
  674. while ((match = rex.exec(v)) !== null) {
  675. var fullMatch = match[0];
  676. var offset = 0;
  677. //if statement begin
  678. if (fullMatch.search(/\{\{if\s+/i)!==-1){
  679. //找到对应的end if
  680. var condition = fullMatch.replace(/^\{\{if\s*/i, "");
  681. condition = condition.replace(/\s*\}\}$/i, "");
  682. var flag = _jsonText(json, condition, "boolean");
  683. var tmpStr = v.substring(rex.lastIndex, v.length);
  684. var endIfIndex = _getIfBlockEnd(tmpStr);
  685. if (flag){ //if 为 true
  686. var parseStr = _parseHtml(tmpStr.substring(0, endIfIndex.codeIndex), json);
  687. var vLeft = v.substring(0, match.index);
  688. var vRight = v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
  689. v = vLeft + parseStr + vRight;
  690. offset = parseStr.length - fullMatch.length;
  691. }else{
  692. v = v.substring(0, match.index) + v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
  693. offset = 0-fullMatch.length;
  694. }
  695. }else if (fullMatch.search(/\{\{each\s+/)!==-1) { //each statement
  696. var itemString = fullMatch.replace(/^\{\{each\s*/, "");
  697. itemString = itemString.replace(/\s*\}\}$/, "");
  698. var eachValue = _jsonText(json, itemString, "object");
  699. var tmpEachStr = v.substring(rex.lastIndex, v.length);
  700. var endEachIndex = _getEachBlockEnd(tmpEachStr);
  701. var parseEachStr = tmpEachStr.substring(0, endEachIndex.codeIndex);
  702. var eachResult = "";
  703. if (eachValue && _typeOf(eachValue)==="array"){
  704. for (var i=0; i<eachValue.length; i++){
  705. eachValue[i]._ = json;
  706. eachResult += _parseHtml(parseEachStr, eachValue[i]);
  707. }
  708. var eLeft = v.substring(0, match.index);
  709. var eRight = v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
  710. v = eLeft + eachResult + eRight;
  711. offset = eachResult.length - fullMatch.length;
  712. }else{
  713. v = v.substring(0, match.index) + v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
  714. offset = 0-fullMatch.length;
  715. }
  716. }else{ //text statement
  717. var text = fullMatch.replace(/^\{\{\s*/, "");
  718. text = text.replace(/\}\}\s*$/, "");
  719. var value = _jsonText(json, text);
  720. offset = value.length-fullMatch.length;
  721. v = v.substring(0, match.index) + value + v.substring(rex.lastIndex, v.length);
  722. }
  723. rex.lastIndex = rex.lastIndex + offset;
  724. }
  725. return v;
  726. };
  727. var _jsonText = function(json, text, type){
  728. try {
  729. var $ = json;
  730. var f = eval("(function($){\n return "+text+";\n})");
  731. returnValue = f.apply(json, [$]);
  732. if (returnValue===undefined) returnValue="";
  733. if (type==="boolean") return (!!returnValue);
  734. if (type==="object") return returnValue;
  735. returnValue = returnValue.toString();
  736. return returnValue || "";
  737. }catch(e){
  738. if (type==="boolean") return false;
  739. if (type==="object") return null;
  740. return "";
  741. }
  742. };
  743. o2.bindJson = function(str, json){
  744. return _parseHtml(str, json);
  745. };
  746. String.prototype.bindJson = function(json){
  747. return _parseHtml(this, json);
  748. };
  749. //dom ready
  750. var _dom = {
  751. ready: false,
  752. loaded: false,
  753. checks: [],
  754. shouldPoll: false,
  755. timer: null,
  756. testElement: document.createElement('div'),
  757. readys: [],
  758. domready: function(){
  759. clearTimeout(_dom.timer);
  760. if (_dom.ready) return;
  761. _dom.loaded = _dom.ready = true;
  762. _removeListener(document, 'DOMContentLoaded', _dom.checkReady);
  763. _removeListener(document, 'readystatechange', _dom.check);
  764. _dom.onReady();
  765. },
  766. check: function(){
  767. for (var i = _dom.checks.length; i--;) if (_dom.checks[i]() && window.MooTools && o2.core && o2.more){
  768. _dom.domready();
  769. return true;
  770. }
  771. return false;
  772. },
  773. poll: function(){
  774. clearTimeout(_dom.timer);
  775. if (!_dom.check()) _dom.timer = setTimeout(_dom.poll, 10);
  776. },
  777. /*<ltIE8>*/
  778. // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
  779. // testElement.doScroll() throws when the DOM is not ready, only in the top window
  780. doScrollWorks: function(){
  781. try {
  782. _dom.testElement.doScroll();
  783. return true;
  784. } catch (e){}
  785. return false;
  786. },
  787. /*</ltIE8>*/
  788. onReady: function(){
  789. for (var i=0; i<_dom.readys.length; i++){
  790. this.readys[i].apply(window);
  791. }
  792. },
  793. addReady: function(fn){
  794. if (_dom.loaded){
  795. if (fn) fn.apply(window);
  796. }else{
  797. if (fn) _dom.readys.push(fn);
  798. }
  799. return _dom;
  800. },
  801. checkReady: function(){
  802. _dom.checks.push(function(){return true});
  803. _dom.check();
  804. }
  805. };
  806. var _loadO2 = function(){
  807. this.o2.load("o2.core", _dom.check);
  808. this.o2.load("o2.more", _dom.check);
  809. };
  810. _addListener(document, 'DOMContentLoaded', _dom.checkReady);
  811. /*<ltIE8>*/
  812. // If doScroll works already, it can't be used to determine domready
  813. // e.g. in an iframe
  814. if (_dom.testElement.doScroll && !_dom.doScrollWorks()){
  815. _dom.checks.push(_dom.doScrollWorks);
  816. _dom.shouldPoll = true;
  817. }
  818. /*</ltIE8>*/
  819. if (document.readyState) _dom.checks.push(function(){
  820. var state = document.readyState;
  821. return (state == 'loaded' || state == 'complete');
  822. });
  823. if ('onreadystatechange' in document) _addListener(document, 'readystatechange', _dom.check);
  824. else _dom.shouldPoll = true;
  825. if (_dom.shouldPoll) _dom.poll();
  826. if (!window.MooTools){
  827. this.o2.load("mootools", function(){ _loadO2(); _dom.check(); });
  828. }else{
  829. _loadO2();
  830. }
  831. this.o2.addReady = function(fn){ _dom.addReady.call(_dom, fn); };
  832. })();