o2.js 33 KB

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