o2.js 37 KB

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