o2.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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.0',
  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*){1}|(;\s*){1}/g
  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/ckeditor462/ckeditor.js"],
  271. "raphael": ["/o2_lib/raphael/raphael.js"],
  272. "d3": ["/o2_lib/d3/d3.min.js"],
  273. "ace": ["/o2_lib/ace/src-noconflict/ace.js","/o2_lib/ace/src-noconflict/ext-language_tools.js"],
  274. "JSBeautifier": ["/o2_lib/JSBeautifier/beautify.js"],
  275. "JSBeautifier_css": ["/o2_lib/JSBeautifier/beautify-css.js"],
  276. "JSBeautifier_html": ["/o2_lib/JSBeautifier/beautify-html.js"],
  277. "JSONTemplate": ["/o2_lib/mootools/plugin/Template.js"],
  278. "kity": ["/o2_lib/kityminder/kity/kity.min.js"],
  279. "kityminder": ["/o2_lib/kityminder/core/dist/kityminder.core.js"]
  280. };
  281. var _loaded = {};
  282. var _loadedCss = {};
  283. var _loadedHtml = {};
  284. var _loadCssRunning = {};
  285. var _loadCssQueue = [];
  286. var _loadSingle = function(module, callback, op){
  287. var url = module;
  288. var uuid = _uuid();
  289. if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uuid : addr_uri+"?v="+uuid;
  290. var key = encodeURIComponent(url+op.doc.unid);
  291. if (!op.reload) if (_loaded[key]){
  292. if (callback)callback(); return;
  293. }
  294. var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
  295. var s = op.doc.createElement('script');
  296. head.appendChild(s);
  297. s.id = uuid;
  298. s.src = url;
  299. var _checkScriptLoaded = function(_, isAbort, err){
  300. if (isAbort || !s.readyState || s.readyState === "loaded" || s.readyState === "complete") {
  301. var scriptObj = {"module": module, "id": uuid, "script": s, "doc": op.doc};
  302. if (!err) _loaded[key] = scriptObj;
  303. _removeListener(s, 'readystatechange', _checkScriptLoaded);
  304. _removeListener(s, 'load', _checkScriptLoaded);
  305. _removeListener(s, 'error', _checkScriptErrorLoaded);
  306. if (!isAbort || err){
  307. if (err){
  308. if (s) head.removeChild(s);
  309. if (callback)callback();
  310. }else{
  311. //head.removeChild(s);
  312. if (callback)callback(scriptObj);
  313. }
  314. }
  315. }
  316. };
  317. var _checkScriptErrorLoaded = function(e, err){
  318. console.log("Error: load javascript module: "+module);
  319. _checkScriptLoaded(e, true, "error");
  320. };
  321. if ('onreadystatechange' in s) _addListener(s, 'readystatechange', _checkScriptLoaded);
  322. _addListener(s, 'load', _checkScriptLoaded);
  323. _addListener(s, 'error', _checkScriptErrorLoaded);
  324. };
  325. var _load = function(urls, options, callback){
  326. var ms = (_typeOf(urls)==="array") ? urls : [urls];
  327. var op = (_typeOf(options)==="object") ? _getJsOptions(options) : _getJsOptions(null);
  328. var cb = (_typeOf(options)==="function") ? options : callback;
  329. var modules = [];
  330. for (var i=0; i<ms.length; i++){
  331. var url = ms[i];
  332. var module = _frameworks[url] || url;
  333. if (_typeOf(module)==="array"){
  334. modules = modules.concat(module)
  335. }else{
  336. modules.push(module)
  337. }
  338. }
  339. var thisLoaded = [];
  340. if (op.sequence){
  341. _loadSequence(modules, cb, op, 0, thisLoaded, _loadSingle);
  342. }else{
  343. _loadDisarray(modules, cb, op, thisLoaded, _loadSingle);
  344. }
  345. };
  346. this.o2.load = _load;
  347. //load css
  348. var _loadSingleCss = function(module, callback, op, uuid){
  349. var url = module;
  350. var uid = _uuid();
  351. if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
  352. var key = encodeURIComponent(url+op.doc.unid);
  353. if (_loadCssRunning[key]){
  354. _loadCssQueue.push(function(){
  355. _loadSingleCss(module, callback, op, uuid);
  356. });
  357. return;
  358. }
  359. if (_loadedCss[key]) uuid = _loadedCss[key]["class"];
  360. if (op.dom) _parseDom(op.dom, function(node){ if (node.className.indexOf(uuid) == -1) node.className += ((node.className) ? " "+uuid : uuid);}, op.doc);
  361. var completed = function(){
  362. if (_loadCssRunning[key]){
  363. _loadCssRunning[key] = false;
  364. delete _loadCssRunning[key];
  365. }
  366. if (_loadCssQueue && _loadCssQueue.length){
  367. (_loadCssQueue.shift())();
  368. }
  369. };
  370. if (_loadedCss[key])if (!op.reload){
  371. if (callback)callback(_loadedCss[key]);
  372. completed();
  373. return;
  374. }
  375. var success = function(xhr){
  376. var cssText = xhr.responseText;
  377. try{
  378. if (cssText){
  379. if (op.bind) cssText = cssText.bindJson(op.bind);
  380. if (op.dom){
  381. var rex = new RegExp("(.+)(?=\\{)", "g");
  382. var match;
  383. while ((match = rex.exec(cssText)) !== null) {
  384. var prefix = "." + uuid + " ";
  385. var rule = prefix + match[0];
  386. cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
  387. rex.lastIndex = rex.lastIndex + prefix.length;
  388. }
  389. }
  390. var style = op.doc.createElement("style");
  391. style.setAttribute("type", "text/css");
  392. var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
  393. head.appendChild(style);
  394. if(style.styleSheet){
  395. var setFunc = function(){
  396. style.styleSheet.cssText = cssText;
  397. };
  398. if(style.styleSheet.disabled){
  399. setTimeout(setFunc, 10);
  400. }else{
  401. setFunc();
  402. }
  403. }else{
  404. var cssTextNode = op.doc.createTextNode(cssText);
  405. style.appendChild(cssTextNode);
  406. }
  407. }
  408. style.id = uid;
  409. var styleObj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid};
  410. _loadedCss[key] = styleObj;
  411. if (callback) callback(styleObj);
  412. }catch (e){
  413. if (callback) callback();
  414. return;
  415. }
  416. };
  417. var failure = function(xhr){
  418. console.log("Error: load css module: "+module);
  419. if (callback) callback();
  420. };
  421. _loadCssRunning[key] = true;
  422. _xhr_get(url, success, failure, completed);
  423. };
  424. var _parseDomString = function(dom, fn, sourceDoc){
  425. var doc = sourceDoc || document;
  426. var list = doc.querySelectorAll(dom);
  427. if (list.length) for (var i=0; i<list.length; i++) _parseDomElement(list[i], fn);
  428. };
  429. var _parseDomElement = function(dom, fn){
  430. if (fn) fn(dom);
  431. };
  432. var _parseDom = function(dom, fn, sourceDoc){
  433. var domType = _typeOf(dom);
  434. if (domType==="string") _parseDomString(dom, fn, sourceDoc);
  435. if (domType==="element") _parseDomElement(dom, fn);
  436. if (domType==="array") for (var i=0; i<dom.length; i++) _parseDom(dom[i], fn, sourceDoc);
  437. };
  438. var _loadCss = function(modules, options, callback){
  439. var ms = (_typeOf(modules)==="array") ? modules : [modules];
  440. var op = (_typeOf(options)==="object") ? _getCssOptions(options) : _getCssOptions(null);
  441. var cb = (_typeOf(options)==="function") ? options : callback;
  442. var uuid = "css"+_uuid();
  443. var thisLoaded = [];
  444. if (op.sequence){
  445. _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleCss, uuid);
  446. }else{
  447. _loadDisarray(ms, cb, op, thisLoaded, _loadSingleCss, uuid);
  448. }
  449. };
  450. var _removeCss = function(modules, doc){
  451. var thisDoc = doc || document;
  452. var ms = (_typeOf(modules)==="array") ? modules : [modules];
  453. for (var i=0; i<ms.length; i++){
  454. var module = modules[i];
  455. var k = encodeURIComponent(module+(thisDoc.unid||""));
  456. var removeCss = _loadedCss[k];
  457. if (!removeCss) for (key in _loadedCss){
  458. if (_loadedCss[key].id==module){
  459. removeCss = _loadedCss[key];
  460. k = key;
  461. break;
  462. }
  463. }
  464. if (removeCss){
  465. delete _loadedCss[k];
  466. var styleNode = removeCss.doc.getElementById(removeCss.id);
  467. if (styleNode) styleNode.parentNode.removeChild(styleNode);
  468. removeCss = null;
  469. }
  470. }
  471. };
  472. this.o2.loadCss = _loadCss;
  473. this.o2.removeCss = _removeCss;
  474. Element.prototype.loadCss = function(modules, options, callback){
  475. var op = (_typeOf(options)==="object") ? options : {};
  476. var cb = (_typeOf(options)==="function") ? options : callback;
  477. op.dom = this;
  478. _loadCss(modules, op, cb);
  479. };
  480. //load html
  481. _loadSingleHtml = function(module, callback, op){
  482. var url = module;
  483. var uid = _uuid();
  484. if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
  485. var key = encodeURIComponent(url+op.doc.unid);
  486. if (!op.reload) if (_loadedHtml[key]){ if (callback)callback(_loadedHtml[key]); return; }
  487. var success = function(xhr){
  488. var htmlObj = {"module": module, "id": uid, "data": xhr.responseText, "doc": op.doc};
  489. _loadedHtml[key] = htmlObj;
  490. if (callback) callback(htmlObj);
  491. };
  492. var failure = function(){
  493. console.log("Error: load html module: "+module);
  494. if (callback) callback();
  495. };
  496. _xhr_get(url, success, failure);
  497. };
  498. var _injectHtml = function(op, data){
  499. if (op.bind) data = data.bindJson(op.bind);
  500. if (op.dom) _parseDom(op.dom, function(node){ node.insertAdjacentHTML(op.position, data) }, op.doc);
  501. };
  502. var _loadHtml = function(modules, options, callback){
  503. var ms = (_typeOf(modules)==="array") ? modules : [modules];
  504. var op = (_typeOf(options)==="object") ? _getHtmlOptions(options) : _getHtmlOptions(null);
  505. var cb = (_typeOf(options)==="function") ? options : callback;
  506. var thisLoaded = [];
  507. if (op.sequence){
  508. _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
  509. }else{
  510. _loadDisarray(ms, cb, op, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
  511. }
  512. };
  513. this.o2.loadHtml = _loadHtml;
  514. Element.prototype.loadHtml = function(modules, options, callback){
  515. var op = (_typeOf(options)==="object") ? options : {};
  516. var cb = (_typeOf(options)==="function") ? options : callback;
  517. op.dom = this;
  518. _loadHtml(modules, op, cb);
  519. };
  520. //load all
  521. _loadAll = function(modules, options, callback){
  522. //var ms = (_typeOf(modules)==="array") ? modules : [modules];
  523. var op = (_typeOf(options)==="object") ? _getAllOptions(options) : _getAllOptions(null);
  524. var cb = (_typeOf(options)==="function") ? options : callback;
  525. var ms, htmls, styles, sctipts;
  526. var _htmlLoaded=(!modules.html), _cssLoaded=(!modules.css), _jsLoaded=(!modules.js);
  527. var _checkloaded = function(){
  528. if (_htmlLoaded && _cssLoaded && _jsLoaded) if (cb) cb(htmls, styles, sctipts);
  529. };
  530. if (modules.html){
  531. _loadHtml(modules.html, op, function(h){
  532. htmls = h;
  533. _htmlLoaded = true;
  534. _checkloaded();
  535. });
  536. }
  537. if (modules.css){
  538. _loadCss(modules.css, op, function(s){
  539. styles = s;
  540. _cssLoaded = true;
  541. _checkloaded();
  542. });
  543. }
  544. if (modules.js){
  545. _load(modules.js, op, function(s){
  546. sctipts = s;
  547. _jsLoaded = true;
  548. _checkloaded();
  549. });
  550. }
  551. };
  552. this.o2.loadAll = _loadAll;
  553. Element.prototype.loadAll = function(modules, options, callback){
  554. var op = (_typeOf(options)==="object") ? options : {};
  555. var cb = (_typeOf(options)==="function") ? options : callback;
  556. op.dom = this;
  557. _loadAll(modules, op, cb);
  558. };
  559. //json template
  560. // _parseText = function(html, json){
  561. // var _ht = html;
  562. // var regexp = /(text\{).+?\}/g;
  563. // var r = _ht.match(regexp);
  564. // if(r) if (r.length){
  565. // for (var i=0; i<r.length; i++){
  566. // var text = r[i].substr(0,r[i].lastIndexOf("}"));
  567. // text = text.substr(text.indexOf("{")+1,text.length);
  568. // var value = _jsonText(json ,text);
  569. // _ht = _ht.replace(/(text\{).+?\}/,value);
  570. // }
  571. // }
  572. // return _ht;
  573. // };
  574. // _parseEach = function(html, json){
  575. // var _ht = html;
  576. // var regexp = /(\{each\([\s\S]+\)\})[\s\S]+?(\{endEach\})/g;
  577. // var r = _ht.match(regexp);
  578. // if(r){
  579. // if (r.length){
  580. // for (var i=0; i<r.length; i++){
  581. // var eachItemsStr = r[i].substr(0,r[i].indexOf(")"));
  582. // eachItemsStr = eachItemsStr.substr(eachItemsStr.indexOf("(")+1,eachItemsStr.length);
  583. // var pars = eachItemsStr.split(/,[\s]*/g);
  584. // eachItemsPar = pars[0];
  585. // eachItemsCount = pars[1].toInt();
  586. //
  587. // var eachItems = _jsonText(json ,eachItemsPar);
  588. // if (eachItems) if (eachItemsCount==0) eachItemsCount = eachItems.length;
  589. //
  590. // var eachContentStr = r[i].substr(0,r[i].lastIndexOf("{endEach}"));
  591. // eachContentStr = eachContentStr.substr(eachContentStr.indexOf("}")+1,eachContentStr.length);
  592. //
  593. // var eachContent = [];
  594. // if (eachItems){
  595. // for (var n=0; n<Math.min(eachItems.length, eachItemsCount); n++){
  596. // var item = eachItems[n];
  597. // if (item){
  598. // var tmpEachContentStr = eachContentStr;
  599. // var textReg = /(eachText\{).+?\}/g;
  600. // texts = tmpEachContentStr.match(textReg);
  601. // if (texts){
  602. // if (texts.length){
  603. // for (var j=0; j<texts.length; j++){
  604. // var text = texts[j].substr(0,texts[j].lastIndexOf("}"));
  605. // text = text.substr(text.indexOf("{")+1,text.length);
  606. //
  607. // var value = _jsonText(item ,text);
  608. // tmpEachContentStr = tmpEachContentStr.replace(/(eachText\{).+?\}/,value);
  609. // }
  610. // }
  611. // }
  612. // eachContent.push(tmpEachContentStr);
  613. // }
  614. // }
  615. // }
  616. // _ht = _ht.replace(/(\{each\([\s\S]+\)\})[\s\S]+?(\{endEach\})/,eachContent.join(""));
  617. // }
  618. // }
  619. // }
  620. // return _ht;
  621. // };
  622. // _jsonText = function(json, text){
  623. // var $ = json;
  624. // var f = eval("(x = function($){\n return "+text+";\n})");
  625. // returnValue = f.apply(json, [$]);
  626. // if (returnValue===undefined) returnValue="";
  627. // returnValue = returnValue.toString();
  628. // return returnValue || "";
  629. // };
  630. // var _bindJson = function(str, json){
  631. // return _parseEach(_parseText(str, json), json);
  632. // };
  633. // o2.bindJson = _bindJson;
  634. // String.prototype.bindJson = function(json){
  635. // return _parseEach(_parseText(this, json), json);
  636. // };
  637. var _getIfBlockEnd = function(v){
  638. var rex = /(\{\{if\s+)|(\{\{\s*end if\s*\}\})/gmi;
  639. var rexEnd = /\{\{\s*end if\s*\}\}/gmi;
  640. var subs = 1;
  641. while ((match = rex.exec(v)) !== null) {
  642. var fullMatch = match[0];
  643. if (fullMatch.search(rexEnd)!==-1){
  644. subs--;
  645. if (subs==0) break;
  646. }else{
  647. subs++
  648. }
  649. }
  650. if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
  651. return {"codeIndex": v.length-1, "lastIndex": v.length-1};
  652. }
  653. var _getEachBlockEnd = function(v){
  654. var rex = /(\{\{each\s+)|(\{\{\s*end each\s*\}\})/gmi;
  655. var rexEnd = /\{\{\s*end each\s*\}\}/gmi;
  656. var subs = 1;
  657. while ((match = rex.exec(v)) !== null) {
  658. var fullMatch = match[0];
  659. if (fullMatch.search(rexEnd)!==-1){
  660. subs--;
  661. if (subs==0) break;
  662. }else{
  663. subs++;
  664. }
  665. }
  666. if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
  667. return {"codeIndex": v.length-1, "lastIndex": v.length-1};
  668. }
  669. var _parseHtml = function(str, json){
  670. var v = str;
  671. var rex = /(\{\{\s*)[\s\S]*?(\s*\}\})/gmi;
  672. var match;
  673. while ((match = rex.exec(v)) !== null) {
  674. var fullMatch = match[0];
  675. var offset = 0;
  676. //if statement begin
  677. if (fullMatch.search(/\{\{if\s+/i)!==-1){
  678. //找到对应的end if
  679. var condition = fullMatch.replace(/^\{\{if\s*/i, "");
  680. condition = condition.replace(/\s*\}\}$/i, "");
  681. var flag = _jsonText(json, condition, "boolean");
  682. var tmpStr = v.substring(rex.lastIndex, v.length);
  683. var endIfIndex = _getIfBlockEnd(tmpStr);
  684. if (flag){ //if 为 true
  685. var parseStr = _parseHtml(tmpStr.substring(0, endIfIndex.codeIndex), json);
  686. var vLeft = v.substring(0, match.index);
  687. var vRight = v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
  688. v = vLeft + parseStr + vRight;
  689. offset = parseStr.length - fullMatch.length;
  690. }else{
  691. v = v.substring(0, match.index) + v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
  692. offset = 0-fullMatch.length;
  693. }
  694. }else if (fullMatch.search(/\{\{each\s+/)!==-1) { //each statement
  695. var itemString = fullMatch.replace(/^\{\{each\s*/, "");
  696. itemString = itemString.replace(/\s*\}\}$/, "");
  697. var eachValue = _jsonText(json, itemString, "object");
  698. var tmpEachStr = v.substring(rex.lastIndex, v.length);
  699. var endEachIndex = _getEachBlockEnd(tmpEachStr);
  700. var parseEachStr = tmpEachStr.substring(0, endEachIndex.codeIndex);
  701. var eachResult = "";
  702. if (eachValue && _typeOf(eachValue)==="array"){
  703. for (var i=0; i<eachValue.length; i++){
  704. eachValue[i]._ = json;
  705. eachResult += _parseHtml(parseEachStr, eachValue[i]);
  706. }
  707. var eLeft = v.substring(0, match.index);
  708. var eRight = v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
  709. v = eLeft + eachResult + eRight;
  710. offset = eachResult.length - fullMatch.length;
  711. }else{
  712. v = v.substring(0, match.index) + v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
  713. offset = 0-fullMatch.length;
  714. }
  715. }else{ //text statement
  716. var text = fullMatch.replace(/^\{\{\s*/, "");
  717. text = text.replace(/\}\}\s*$/, "");
  718. var value = _jsonText(json, text);
  719. offset = value.length-fullMatch.length;
  720. v = v.substring(0, match.index) + value + v.substring(rex.lastIndex, v.length);
  721. }
  722. rex.lastIndex = rex.lastIndex + offset;
  723. }
  724. return v;
  725. };
  726. var _jsonText = function(json, text, type){
  727. try {
  728. var $ = json;
  729. var f = eval("(function($){\n return "+text+";\n})");
  730. returnValue = f.apply(json, [$]);
  731. if (returnValue===undefined) returnValue="";
  732. if (type==="boolean") return (!!returnValue);
  733. if (type==="object") return returnValue;
  734. returnValue = returnValue.toString();
  735. return returnValue || "";
  736. }catch(e){
  737. if (type==="boolean") return false;
  738. if (type==="object") return null;
  739. return "";
  740. }
  741. };
  742. o2.bindJson = function(str, json){
  743. return _parseHtml(str, json);
  744. };
  745. String.prototype.bindJson = function(json){
  746. return _parseHtml(this, json);
  747. };
  748. //dom ready
  749. var _dom = {
  750. ready: false,
  751. loaded: false,
  752. checks: [],
  753. shouldPoll: false,
  754. timer: null,
  755. testElement: document.createElement('div'),
  756. readys: [],
  757. domready: function(){
  758. clearTimeout(_dom.timer);
  759. if (_dom.ready) return;
  760. _dom.loaded = _dom.ready = true;
  761. _removeListener(document, 'DOMContentLoaded', _dom.checkReady);
  762. _removeListener(document, 'readystatechange', _dom.check);
  763. _dom.onReady();
  764. },
  765. check: function(){
  766. for (var i = _dom.checks.length; i--;) if (_dom.checks[i]() && window.MooTools && o2.core && o2.more){
  767. _dom.domready();
  768. return true;
  769. }
  770. return false;
  771. },
  772. poll: function(){
  773. clearTimeout(_dom.timer);
  774. if (!_dom.check()) _dom.timer = setTimeout(_dom.poll, 10);
  775. },
  776. /*<ltIE8>*/
  777. // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
  778. // testElement.doScroll() throws when the DOM is not ready, only in the top window
  779. doScrollWorks: function(){
  780. try {
  781. _dom.testElement.doScroll();
  782. return true;
  783. } catch (e){}
  784. return false;
  785. },
  786. /*</ltIE8>*/
  787. onReady: function(){
  788. for (var i=0; i<_dom.readys.length; i++){
  789. this.readys[i].apply(window);
  790. }
  791. },
  792. addReady: function(fn){
  793. if (_dom.loaded){
  794. if (fn) fn.apply(window);
  795. }else{
  796. if (fn) _dom.readys.push(fn);
  797. }
  798. return _dom;
  799. },
  800. checkReady: function(){
  801. _dom.checks.push(function(){return true});
  802. _dom.check();
  803. }
  804. };
  805. var _loadO2 = function(){
  806. this.o2.load("o2.core", _dom.check);
  807. this.o2.load("o2.more", _dom.check);
  808. };
  809. _addListener(document, 'DOMContentLoaded', _dom.checkReady);
  810. /*<ltIE8>*/
  811. // If doScroll works already, it can't be used to determine domready
  812. // e.g. in an iframe
  813. if (_dom.testElement.doScroll && !_dom.doScrollWorks()){
  814. _dom.checks.push(_dom.doScrollWorks);
  815. _dom.shouldPoll = true;
  816. }
  817. /*</ltIE8>*/
  818. if (document.readyState) _dom.checks.push(function(){
  819. var state = document.readyState;
  820. return (state == 'loaded' || state == 'complete');
  821. });
  822. if ('onreadystatechange' in document) _addListener(document, 'readystatechange', _dom.check);
  823. else _dom.shouldPoll = true;
  824. if (_dom.shouldPoll) _dom.poll();
  825. if (!window.MooTools){
  826. this.o2.load("mootools", function(){ _loadO2(); _dom.check(); });
  827. }else{
  828. _loadO2();
  829. }
  830. this.o2.addReady = function(fn){ _dom.addReady.call(_dom, fn); };
  831. })();