o2.js 37 KB

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