o2.js 39 KB

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