o2.js 35.0 KB
Newer Older
NoSubject's avatar
NoSubject 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
/** ***** BEGIN LICENSE BLOCK *****
 * |------------------------------------------------------------------------------|
 * | O2OA 活力办公 创意无限    o2.js                                                 |
 * |------------------------------------------------------------------------------|
 * | Distributed under the AGPL license:                                          |
 * |------------------------------------------------------------------------------|
 * | Copyright © 2018, o2oa.net, o2server.io O2 Team                              |
 * | All rights reserved.                                                         |
 * |------------------------------------------------------------------------------|
 *
 *  This file is part of O2OA.
 *
 *  O2OA is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  O2OA is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Foobar.  If not, see <https://www.gnu.org/licenses/>.
 *
 * ***** END LICENSE BLOCK ******/


/* load o2 Core
 * |------------------------------------------------------------------------------|
 * |addReady:     o2.addReady(fn),                                                |
 * |------------------------------------------------------------------------------|
 * |load:         o2.load(urls, callback, reload)                                 |
 * |loadCss:      o2.loadCss(urls, dom, callback, reload, doc)                    |
 * |------------------------------------------------------------------------------|
 * |typeOf:       o2.typeOf(o)                                                    |
 * |------------------------------------------------------------------------------|
 * |uuid:         o2.uuid()                                                       |
 * |------------------------------------------------------------------------------|
 */
(function(){
    var _href = window.location.href;
    var _debug = (_href.indexOf("debugger")!==-1);
    var _par = _href.substr(_href.lastIndexOf("?")+1, _href.length);
    var _lp = "zh-cn";
    if (_par){
        var _parList = _par.split("&");
        for (var i=0; i<_parList.length; i++){
            var _v = _parList[i];
            var _kv = _v.split("=");
            if (_kv[0].toLowerCase()==="lg") _lp = _kv[1];
        }
    }
    this.o2 = {
        "version": {
NoSubject's avatar
NoSubject 已提交
56
            "v": '2.0.9',
NoSubject's avatar
NoSubject 已提交
57 58 59 60 61 62 63 64
            "build": "2018.11.22",
            "info": "O2OA 活力办公 创意无限. Copyright © 2018, o2oa.net O2 Team All rights reserved."
        },
        "session": {
            "isDebugger": _debug,
            "path": "/o2_core/o2"
        },
        "language": _lp,
NoSubject's avatar
NoSubject 已提交
65
        "splitStr": /\s*(?:,|;)\s*/
NoSubject's avatar
NoSubject 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    };
    
    var _attempt = function(){
        for (var i = 0, l = arguments.length; i < l; i++){
            try {
                arguments[i]();
                return arguments[i];
            } catch (e){}
        }
        return null;
    };
    var _typeOf = function(item){
        if (item == null) return 'null';
        if (item.$family != null) return item.$family();
        if (item.constructor == window.Array) return "array";

        if (item.nodeName){
            if (item.nodeType == 1) return 'element';
            if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
        } else if (typeof item.length == 'number'){
            if (item.callee) return 'arguments';
        }
        return typeof item;
    };
    this.o2.typeOf = _typeOf;

    var _addListener = function(dom, type, fn){
        if (type == 'unload'){
            var old = fn, self = this;
            fn = function(){
                _removeListener(dom, 'unload', fn);
                old();
            };
        }
        if (dom.addEventListener) dom.addEventListener(type, fn, !!arguments[2]);
        else dom.attachEvent('on' + type, fn);
    };
    var _removeListener = function(dom, type, fn){
        if (dom.removeEventListener) dom.removeEventListener(type, fn, !!arguments[2]);
        else dom.detachEvent('on' + type, fn);
    };

    //http request class
    var _request = (function(){
        var XMLHTTP = function(){ return new XMLHttpRequest(); };
        var MSXML2 = function(){ return new ActiveXObject('MSXML2.XMLHTTP'); };
        var MSXML = function(){ return new ActiveXObject('Microsoft.XMLHTTP'); };
        return _attempt(XMLHTTP, MSXML2, MSXML);
    })();

    var _returnBase = function(number, base) {
        return (number).toString(base).toUpperCase();
    };
    var _getIntegerBits = function(val, start, end){
        var base16 = _returnBase(val, 16);
        var quadArray = new Array();
        var quadString = '';
        var i = 0;
        for (i = 0; i < base16.length; i++) {
            quadArray.push(base16.substring(i, i + 1));
        }
        for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) {
            if (!quadArray[i] || quadArray[i] == '')
                quadString += '0';
            else
                quadString += quadArray[i];
        }
        return quadString;
    };
    var _rand = function(max) {
        return Math.floor(Math.random() * (max + 1));
    };
NoSubject's avatar
NoSubject 已提交
138 139
    this.o2.addListener = _addListener;
    this.o2.removeListener = _removeListener;
NoSubject's avatar
NoSubject 已提交
140 141

    //uuid
NoSubject's avatar
NoSubject 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    var _uuid = function(){
        var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
        var dc = new Date();
        var t = dc.getTime() - dg.getTime();
        var tl = _getIntegerBits(t, 0, 31);
        var tm = _getIntegerBits(t, 32, 47);
        var thv = _getIntegerBits(t, 48, 59) + '1';
        var csar = _getIntegerBits(_rand(4095), 0, 7);
        var csl = _getIntegerBits(_rand(4095), 0, 7);

        var n = _getIntegerBits(_rand(8191), 0, 7)
            + _getIntegerBits(_rand(8191), 8, 15)
            + _getIntegerBits(_rand(8191), 0, 7)
            + _getIntegerBits(_rand(8191), 8, 15)
            + _getIntegerBits(_rand(8191), 0, 15);
        return tl + tm + thv + csar + csl + n;
    };
    this.o2.uuid = _uuid;


    var _runCallback = function(callback, key, par){
        if (typeOf(callback).toLowerCase() === 'function'){
            if (key.toLowerCase()==="success") callback.apply(callback, par);
        }else{
            if (typeOf(callback).toLowerCase()==='object'){
                var name = ("on-"+key).camelCase();
                if (callback[name]) callback[name].apply(callback, par);
            }
        }
    };
    this.o2.runCallback = _runCallback;

NoSubject's avatar
NoSubject 已提交
174 175

    //load js, css, html adn all.
NoSubject's avatar
NoSubject 已提交
176
    var _getAllOptions = function(options){
NoSubject's avatar
NoSubject 已提交
177 178
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
179 180 181 182
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
            "sequence": !!(options && options.sequence),
NoSubject's avatar
NoSubject 已提交
183
            "doc": doc,
NoSubject's avatar
NoSubject 已提交
184
            "dom": (options && options.dom) || document.body,
NoSubject's avatar
NoSubject 已提交
185
            "bind": (options && options.bind) || null,
NoSubject's avatar
NoSubject 已提交
186
            "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'
NoSubject's avatar
NoSubject 已提交
187 188 189
        }
    };
    var _getCssOptions = function(options){
NoSubject's avatar
NoSubject 已提交
190 191
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
192 193 194 195
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
            "sequence": !!(options && options.sequence),
NoSubject's avatar
NoSubject 已提交
196
            "doc": doc,
NoSubject's avatar
NoSubject 已提交
197 198 199 200
            "dom": (options && options.dom) || null
        }
    };
    var _getJsOptions = function(options){
NoSubject's avatar
NoSubject 已提交
201 202
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
203 204 205
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
NoSubject's avatar
NoSubject 已提交
206 207
            "sequence": (!(options && options.sequence == false)),
            "doc": doc
NoSubject's avatar
NoSubject 已提交
208 209 210
        }
    };
    var _getHtmlOptions = function(options){
NoSubject's avatar
NoSubject 已提交
211 212
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
213 214 215 216
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
            "sequence": !!(options && options.sequence),
NoSubject's avatar
NoSubject 已提交
217
            "doc": doc,
NoSubject's avatar
NoSubject 已提交
218
            "dom": (options && options.dom) || null,
NoSubject's avatar
NoSubject 已提交
219
            "bind": (options && options.bind) || null,
NoSubject's avatar
NoSubject 已提交
220
            "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'
NoSubject's avatar
NoSubject 已提交
221 222
        }
    };
NoSubject's avatar
NoSubject 已提交
223
    var _xhr_get = function(url, success, failure, completed){
NoSubject's avatar
NoSubject 已提交
224 225 226 227
        var xhr = new _request();
        xhr.open("GET", url, true);

        var _checkCssLoaded= function(_, err){
NoSubject's avatar
NoSubject 已提交
228 229 230 231 232
            if (!(xhr.readyState == 4)) return;
            if (err){
                if (completed) completed(xhr);
                return;
            }
NoSubject's avatar
NoSubject 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246

            _removeListener(xhr, 'readystatechange', _checkCssLoaded);
            _removeListener(xhr, 'load', _checkCssLoaded);
            _removeListener(xhr, 'error', _checkCssErrorLoaded);

            if (err) {failure(xhr); return}
            var status = xhr.status;
            status = (status == 1223) ? 204 : status;
            if ((status >= 200 && status < 300))
                success(xhr);
            else if ((status >= 300 && status < 400))
                failure(xhr);
            else
                failure(xhr);
NoSubject's avatar
NoSubject 已提交
247
            if (completed) completed(xhr);
NoSubject's avatar
NoSubject 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        };
        var _checkCssErrorLoaded= function(err){ _checkCssLoaded(err) };

        if ("load" in xhr) _addListener(xhr, "load", _checkCssLoaded);
        if ("error" in xhr) _addListener(xhr, "load", _checkCssErrorLoaded);
        _addListener(xhr, "readystatechange", _checkCssLoaded);
        xhr.send();
    };

    var _loadSequence = function(ms, cb, op, n, thisLoaded, loadSingle, uuid, fun){
        loadSingle(ms[n], function(module){
            if (module) thisLoaded.push(module);
            n++;
            if (fun) fun(module);
            if (n===ms.length){
                if (cb) cb(thisLoaded);
            }else{
                _loadSequence(ms, cb, op, n, thisLoaded, loadSingle, uuid, fun);
            }
        }, op, uuid);
    };
    var _loadDisarray = function(ms, cb, op, thisLoaded, loadSingle, uuid, fun){
        var count=0;
        for (var i=0; i<ms.length; i++){
            loadSingle(ms[i], function(module){
                if (module) thisLoaded.push(module);
                count++;
                if (fun) fun(module);
                if (count===ms.length) if (cb) cb(thisLoaded);
            }, op, uuid);
        }
    };

NoSubject's avatar
NoSubject 已提交
281
    //load js
NoSubject's avatar
NoSubject 已提交
282 283 284 285 286 287
    //use framework url
    var _frameworks = {
        "o2.core": ["/o2_core/o2/o2.core.js"],
        "o2.more": ["/o2_core/o2/o2.more.js"],
        "ie_adapter": ["/o2_lib/o2/ie_adapter.js"],
        "jquery": ["/o2_lib/jquery/jquery.min.js"],
NoSubject's avatar
NoSubject 已提交
288
        "mootools": ["/o2_lib/mootools/mootools-1.6.0_all.js"],
NoSubject's avatar
NoSubject 已提交
289 290
        "ckeditor": ["/o2_lib/htmleditor/ckeditor4114/ckeditor.js"],
        "ckeditor5": ["/o2_lib/htmleditor/ckeditor5-12-1-0/ckeditor.js"],
NoSubject's avatar
NoSubject 已提交
291 292 293 294 295
        "raphael": ["/o2_lib/raphael/raphael.js"],
        "d3": ["/o2_lib/d3/d3.min.js"],
        "ace": ["/o2_lib/ace/src-noconflict/ace.js","/o2_lib/ace/src-noconflict/ext-language_tools.js"],
        "JSBeautifier": ["/o2_lib/JSBeautifier/beautify.js"],
        "JSBeautifier_css": ["/o2_lib/JSBeautifier/beautify-css.js"],
NoSubject's avatar
NoSubject 已提交
296 297 298 299
        "JSBeautifier_html": ["/o2_lib/JSBeautifier/beautify-html.js"],
        "JSONTemplate": ["/o2_lib/mootools/plugin/Template.js"],
        "kity": ["/o2_lib/kityminder/kity/kity.min.js"],
        "kityminder": ["/o2_lib/kityminder/core/dist/kityminder.core.js"]
NoSubject's avatar
NoSubject 已提交
300 301 302
    };
    var _loaded = {};
    var _loadedCss = {};
NoSubject's avatar
NoSubject 已提交
303
    var _loadedHtml = {};
NoSubject's avatar
NoSubject 已提交
304 305
    var _loadCssRunning = {};
    var _loadCssQueue = [];
NoSubject's avatar
NoSubject 已提交
306

NoSubject's avatar
NoSubject 已提交
307 308 309 310
    var _loadSingle = function(module, callback, op){
        var url = module;
        var uuid = _uuid();
        if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uuid : addr_uri+"?v="+uuid;
NoSubject's avatar
NoSubject 已提交
311 312 313 314
        var key = encodeURIComponent(url+op.doc.unid);
        if (!op.reload) if (_loaded[key]){
            if (callback)callback(); return;
        }
NoSubject's avatar
NoSubject 已提交
315

NoSubject's avatar
NoSubject 已提交
316 317
        var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
        var s = op.doc.createElement('script');
NoSubject's avatar
NoSubject 已提交
318
        head.appendChild(s);
NoSubject's avatar
NoSubject 已提交
319 320
        s.id = uuid;
        s.src = url;
NoSubject's avatar
NoSubject 已提交
321

NoSubject's avatar
NoSubject 已提交
322
        var _checkScriptLoaded = function(_, isAbort, err){
NoSubject's avatar
NoSubject 已提交
323
            if (isAbort || !s.readyState || s.readyState === "loaded" || s.readyState === "complete") {
NoSubject's avatar
NoSubject 已提交
324 325
                var scriptObj = {"module": module, "id": uuid, "script": s, "doc": op.doc};
                if (!err) _loaded[key] = scriptObj;
NoSubject's avatar
NoSubject 已提交
326
                _removeListener(s, 'readystatechange', _checkScriptLoaded);
NoSubject's avatar
NoSubject 已提交
327 328 329 330 331 332 333
                _removeListener(s, 'load', _checkScriptLoaded);
                _removeListener(s, 'error', _checkScriptErrorLoaded);
                if (!isAbort || err){
                    if (err){
                        if (s) head.removeChild(s);
                        if (callback)callback();
                    }else{
NoSubject's avatar
NoSubject 已提交
334
                        //head.removeChild(s);
NoSubject's avatar
NoSubject 已提交
335 336 337
                        if (callback)callback(scriptObj);
                    }
                }
NoSubject's avatar
NoSubject 已提交
338 339
            }
        };
NoSubject's avatar
NoSubject 已提交
340 341 342 343
        var _checkScriptErrorLoaded = function(e, err){
            console.log("Error: load javascript module: "+module);
            _checkScriptLoaded(e, true, "error");
        };
NoSubject's avatar
NoSubject 已提交
344 345 346

        if ('onreadystatechange' in s) _addListener(s, 'readystatechange', _checkScriptLoaded);
        _addListener(s, 'load', _checkScriptLoaded);
NoSubject's avatar
NoSubject 已提交
347
        _addListener(s, 'error', _checkScriptErrorLoaded);
NoSubject's avatar
NoSubject 已提交
348 349
    };

NoSubject's avatar
NoSubject 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362
    var _load = function(urls, options, callback){
        var ms = (_typeOf(urls)==="array") ? urls : [urls];
        var op =  (_typeOf(options)==="object") ? _getJsOptions(options) : _getJsOptions(null);
        var cb = (_typeOf(options)==="function") ? options : callback;

        var modules = [];
        for (var i=0; i<ms.length; i++){
            var url = ms[i];
            var module = _frameworks[url] || url;
            if (_typeOf(module)==="array"){
                modules = modules.concat(module)
            }else{
                modules.push(module)
NoSubject's avatar
NoSubject 已提交
363 364
            }
        }
NoSubject's avatar
NoSubject 已提交
365 366 367 368 369
        var thisLoaded = [];
        if (op.sequence){
            _loadSequence(modules, cb, op, 0, thisLoaded, _loadSingle);
        }else{
            _loadDisarray(modules, cb, op, thisLoaded, _loadSingle);
NoSubject's avatar
NoSubject 已提交
370 371 372 373
        }
    };
    this.o2.load = _load;

NoSubject's avatar
NoSubject 已提交
374
    //load css
NoSubject's avatar
NoSubject 已提交
375 376 377 378
    var _loadSingleCss = function(module, callback, op, uuid){
        var url = module;
        var uid = _uuid();
        if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
NoSubject's avatar
NoSubject 已提交
379

NoSubject's avatar
NoSubject 已提交
380
        var key = encodeURIComponent(url+op.doc.unid);
NoSubject's avatar
NoSubject 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
        if (_loadCssRunning[key]){
            _loadCssQueue.push(function(){
                _loadSingleCss(module, callback, op, uuid);
            });
            return;
        }

        if (_loadedCss[key]) uuid = _loadedCss[key]["class"];
        if (op.dom) _parseDom(op.dom, function(node){ if (node.className.indexOf(uuid) == -1) node.className += ((node.className) ? " "+uuid : uuid);}, op.doc);

        var completed = function(){
            if (_loadCssRunning[key]){
                _loadCssRunning[key] = false;
                delete _loadCssRunning[key];
            }
            if (_loadCssQueue && _loadCssQueue.length){
                (_loadCssQueue.shift())();
            }
        };

        if (_loadedCss[key])if (!op.reload){
            if (callback)callback(_loadedCss[key]);
            completed();
            return;
        }
NoSubject's avatar
NoSubject 已提交
406 407 408 409 410

        var success = function(xhr){
            var cssText = xhr.responseText;
            try{
                if (cssText){
NoSubject's avatar
NoSubject 已提交
411
                    if (op.bind) cssText = cssText.bindJson(op.bind);
NoSubject's avatar
NoSubject 已提交
412
                    if (op.dom){
NoSubject's avatar
NoSubject 已提交
413 414 415 416 417
                        var rex = new RegExp("(.+)(?=\\{)", "g");
                        var match;
                        while ((match = rex.exec(cssText)) !== null) {
                            var prefix = "." + uuid + " ";
                            var rule = prefix + match[0];
NoSubject's avatar
NoSubject 已提交
418
                            cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
NoSubject's avatar
NoSubject 已提交
419 420 421
                            rex.lastIndex = rex.lastIndex + prefix.length;
                        }
                    }
NoSubject's avatar
NoSubject 已提交
422
                    var style = op.doc.createElement("style");
NoSubject's avatar
NoSubject 已提交
423
                    style.setAttribute("type", "text/css");
NoSubject's avatar
NoSubject 已提交
424
                    var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
NoSubject's avatar
NoSubject 已提交
425 426 427 428 429 430 431 432 433 434 435
                    head.appendChild(style);
                    if(style.styleSheet){
                        var setFunc = function(){
                            style.styleSheet.cssText = cssText;
                        };
                        if(style.styleSheet.disabled){
                            setTimeout(setFunc, 10);
                        }else{
                            setFunc();
                        }
                    }else{
NoSubject's avatar
NoSubject 已提交
436
                        var cssTextNode = op.doc.createTextNode(cssText);
NoSubject's avatar
NoSubject 已提交
437 438 439
                        style.appendChild(cssTextNode);
                    }
                }
NoSubject's avatar
NoSubject 已提交
440
                style.id = uid;
NoSubject's avatar
NoSubject 已提交
441
                var styleObj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid};
NoSubject's avatar
NoSubject 已提交
442 443
                _loadedCss[key] = styleObj;
                if (callback) callback(styleObj);
NoSubject's avatar
NoSubject 已提交
444 445 446 447 448 449
            }catch (e){
                if (callback) callback();
                return;
            }
        };
        var failure = function(xhr){
NoSubject's avatar
NoSubject 已提交
450
            console.log("Error: load css module: "+module);
NoSubject's avatar
NoSubject 已提交
451 452
            if (callback) callback();
        };
NoSubject's avatar
NoSubject 已提交
453 454 455 456

        _loadCssRunning[key] = true;

        _xhr_get(url, success, failure, completed);
NoSubject's avatar
NoSubject 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    };

    var _parseDomString = function(dom, fn, sourceDoc){
        var doc = sourceDoc || document;
        var list = doc.querySelectorAll(dom);
        if (list.length) for (var i=0; i<list.length; i++) _parseDomElement(list[i], fn);
    };
    var _parseDomElement = function(dom, fn){
        if (fn) fn(dom);
    };
    var _parseDom = function(dom, fn, sourceDoc){
        var domType = _typeOf(dom);
        if (domType==="string") _parseDomString(dom, fn, sourceDoc);
        if (domType==="element") _parseDomElement(dom, fn);
        if (domType==="array") for (var i=0; i<dom.length; i++) _parseDom(dom[i], fn, sourceDoc);
    };
NoSubject's avatar
NoSubject 已提交
473 474 475 476 477 478 479 480 481 482 483
    var _loadCss = function(modules, options, callback){
        var ms = (_typeOf(modules)==="array") ? modules : [modules];
        var op =  (_typeOf(options)==="object") ? _getCssOptions(options) : _getCssOptions(null);
        var cb = (_typeOf(options)==="function") ? options : callback;

        var uuid = "css"+_uuid();
        var thisLoaded = [];
        if (op.sequence){
            _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleCss, uuid);
        }else{
            _loadDisarray(ms, cb, op, thisLoaded, _loadSingleCss, uuid);
NoSubject's avatar
NoSubject 已提交
484
        }
NoSubject's avatar
NoSubject 已提交
485
    };
NoSubject's avatar
NoSubject 已提交
486
    var _removeCss = function(modules, doc){
NoSubject's avatar
NoSubject 已提交
487
        var thisDoc = doc || document;
NoSubject's avatar
NoSubject 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        var ms = (_typeOf(modules)==="array") ? modules : [modules];
        for (var i=0; i<ms.length; i++){
            var module = modules[i];

            var k = encodeURIComponent(module+(thisDoc.unid||""));
            var removeCss = _loadedCss[k];
            if (!removeCss) for (key in _loadedCss){
                if (_loadedCss[key].id==module){
                    removeCss = _loadedCss[key];
                    k = key;
                    break;
                }
            }
            if (removeCss){
                delete _loadedCss[k];
                var styleNode = removeCss.doc.getElementById(removeCss.id);
                if (styleNode) styleNode.parentNode.removeChild(styleNode);
                removeCss = null;
NoSubject's avatar
NoSubject 已提交
506 507 508 509
            }
        }
    };
    this.o2.loadCss = _loadCss;
NoSubject's avatar
NoSubject 已提交
510 511 512 513 514 515 516 517
    this.o2.removeCss = _removeCss;
    Element.prototype.loadCss = function(modules, options, callback){
        var op =  (_typeOf(options)==="object") ? options : {};
        var cb = (_typeOf(options)==="function") ? options : callback;
        op.dom = this;
        _loadCss(modules, op, cb);
    };

NoSubject's avatar
NoSubject 已提交
518
    //load html
NoSubject's avatar
NoSubject 已提交
519 520 521 522
    _loadSingleHtml = function(module, callback, op){
        var url = module;
        var uid = _uuid();
        if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
NoSubject's avatar
NoSubject 已提交
523
        var key = encodeURIComponent(url+op.doc.unid);
NoSubject's avatar
NoSubject 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        if (!op.reload) if (_loadedHtml[key]){ if (callback)callback(_loadedHtml[key]); return; }

        var success = function(xhr){
            var htmlObj = {"module": module, "id": uid, "data": xhr.responseText, "doc": op.doc};
            _loadedHtml[key] = htmlObj;
            if (callback) callback(htmlObj);
        };
        var failure = function(){
            console.log("Error: load html module: "+module);
            if (callback) callback();
        };
        _xhr_get(url, success, failure);
    };

    var _injectHtml = function(op, data){
NoSubject's avatar
NoSubject 已提交
539
        if (op.bind) data = data.bindJson(op.bind);
NoSubject's avatar
NoSubject 已提交
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
        if (op.dom) _parseDom(op.dom, function(node){ node.insertAdjacentHTML(op.position, data) }, op.doc);
    };
    var _loadHtml = function(modules, options, callback){
        var ms = (_typeOf(modules)==="array") ? modules : [modules];
        var op =  (_typeOf(options)==="object") ? _getHtmlOptions(options) : _getHtmlOptions(null);
        var cb = (_typeOf(options)==="function") ? options : callback;

        var thisLoaded = [];
        if (op.sequence){
            _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
        }else{
            _loadDisarray(ms, cb, op, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
        }
    };
    this.o2.loadHtml = _loadHtml;
    Element.prototype.loadHtml = function(modules, options, callback){
        var op =  (_typeOf(options)==="object") ? options : {};
        var cb = (_typeOf(options)==="function") ? options : callback;
        op.dom = this;
        _loadHtml(modules, op, cb);
    };
NoSubject's avatar
NoSubject 已提交
561

NoSubject's avatar
NoSubject 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    //load all
    _loadAll = function(modules, options, callback){
        //var ms = (_typeOf(modules)==="array") ? modules : [modules];
        var op =  (_typeOf(options)==="object") ? _getAllOptions(options) : _getAllOptions(null);
        var cb = (_typeOf(options)==="function") ? options : callback;

        var ms, htmls, styles, sctipts;
        var _htmlLoaded=(!modules.html), _cssLoaded=(!modules.css), _jsLoaded=(!modules.js);
        var _checkloaded = function(){
            if (_htmlLoaded && _cssLoaded && _jsLoaded) if (cb) cb(htmls, styles, sctipts);
        };
        if (modules.html){
            _loadHtml(modules.html, op, function(h){
                htmls = h;
                _htmlLoaded = true;
                _checkloaded();
            });
        }
        if (modules.css){
            _loadCss(modules.css, op, function(s){
                styles = s;
                _cssLoaded = true;
                _checkloaded();
            });
        }
        if (modules.js){
            _load(modules.js, op, function(s){
                sctipts = s;
                _jsLoaded = true;
                _checkloaded();
            });
        }
    };
    this.o2.loadAll = _loadAll;
    Element.prototype.loadAll = function(modules, options, callback){
        var op =  (_typeOf(options)==="object") ? options : {};
        var cb = (_typeOf(options)==="function") ? options : callback;
        op.dom = this;
        _loadAll(modules, op, cb);
    };

    //json template
NoSubject's avatar
NoSubject 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    // _parseText = function(html, json){
    //     var _ht = html;
    //     var regexp = /(text\{).+?\}/g;
    //     var r = _ht.match(regexp);
    //     if(r) if (r.length){
    //         for (var i=0; i<r.length; i++){
    //             var text = r[i].substr(0,r[i].lastIndexOf("}"));
    //             text = text.substr(text.indexOf("{")+1,text.length);
    //             var value = _jsonText(json ,text);
    //             _ht = _ht.replace(/(text\{).+?\}/,value);
    //         }
    //     }
    //     return _ht;
    // };
    // _parseEach = function(html, json){
    //     var _ht = html;
    //     var regexp = /(\{each\([\s\S]+\)\})[\s\S]+?(\{endEach\})/g;
    //     var r = _ht.match(regexp);
    //     if(r){
    //         if (r.length){
    //             for (var i=0; i<r.length; i++){
    //                 var eachItemsStr = r[i].substr(0,r[i].indexOf(")"));
    //                 eachItemsStr = eachItemsStr.substr(eachItemsStr.indexOf("(")+1,eachItemsStr.length);
    //                 var pars = eachItemsStr.split(/,[\s]*/g);
    //                 eachItemsPar = pars[0];
    //                 eachItemsCount = pars[1].toInt();
    //
    //                 var eachItems = _jsonText(json ,eachItemsPar);
    //                 if (eachItems) if (eachItemsCount==0) eachItemsCount = eachItems.length;
    //
    //                 var eachContentStr = r[i].substr(0,r[i].lastIndexOf("{endEach}"));
    //                 eachContentStr = eachContentStr.substr(eachContentStr.indexOf("}")+1,eachContentStr.length);
    //
    //                 var eachContent = [];
    //                 if (eachItems){
    //                     for (var n=0; n<Math.min(eachItems.length, eachItemsCount); n++){
    //                         var item = eachItems[n];
    //                         if (item){
    //                             var tmpEachContentStr = eachContentStr;
    //                             var textReg = /(eachText\{).+?\}/g;
    //                             texts = tmpEachContentStr.match(textReg);
    //                             if (texts){
    //                                 if (texts.length){
    //                                     for (var j=0; j<texts.length; j++){
    //                                         var text = texts[j].substr(0,texts[j].lastIndexOf("}"));
    //                                         text = text.substr(text.indexOf("{")+1,text.length);
    //
    //                                         var value = _jsonText(item ,text);
    //                                         tmpEachContentStr = tmpEachContentStr.replace(/(eachText\{).+?\}/,value);
    //                                     }
    //                                 }
    //                             }
    //                             eachContent.push(tmpEachContentStr);
    //                         }
    //                     }
    //                 }
    //                 _ht = _ht.replace(/(\{each\([\s\S]+\)\})[\s\S]+?(\{endEach\})/,eachContent.join(""));
    //             }
    //         }
    //     }
    //     return _ht;
    // };
    // _jsonText = function(json, text){
    //     var $ = json;
    //     var f = eval("(x = function($){\n return "+text+";\n})");
    //     returnValue = f.apply(json, [$]);
    //     if (returnValue===undefined) returnValue="";
    //     returnValue = returnValue.toString();
    //     return returnValue || "";
    // };
    // var _bindJson = function(str, json){
    //     return _parseEach(_parseText(str, json), json);
    // };
    // o2.bindJson = _bindJson;
    // String.prototype.bindJson = function(json){
    //     return _parseEach(_parseText(this, json), json);
    // };

    var _getIfBlockEnd = function(v){
        var rex = /(\{\{if\s+)|(\{\{\s*end if\s*\}\})/gmi;
        var rexEnd = /\{\{\s*end if\s*\}\}/gmi;
        var subs = 1;
        while ((match = rex.exec(v)) !== null) {
            var fullMatch = match[0];
            if (fullMatch.search(rexEnd)!==-1){
                subs--;
                if (subs==0) break;
            }else{
                subs++
NoSubject's avatar
NoSubject 已提交
693 694
            }
        }
NoSubject's avatar
NoSubject 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
        if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
        return {"codeIndex": v.length-1, "lastIndex": v.length-1};
    }
    var _getEachBlockEnd = function(v){
        var rex = /(\{\{each\s+)|(\{\{\s*end each\s*\}\})/gmi;
        var rexEnd = /\{\{\s*end each\s*\}\}/gmi;
        var subs = 1;
        while ((match = rex.exec(v)) !== null) {
            var fullMatch = match[0];
            if (fullMatch.search(rexEnd)!==-1){
                subs--;
                if (subs==0) break;
            }else{
                subs++;
            }
        }
        if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
        return {"codeIndex": v.length-1, "lastIndex": v.length-1};
    }

    var _parseHtml = function(str, json){
        var v = str;
        var rex = /(\{\{\s*)[\s\S]*?(\s*\}\})/gmi;

        var match;
        while ((match = rex.exec(v)) !== null) {
            var fullMatch = match[0];
            var offset = 0;

            //if statement begin
            if (fullMatch.search(/\{\{if\s+/i)!==-1){
                //找到对应的end if
                var condition = fullMatch.replace(/^\{\{if\s*/i, "");
                condition = condition.replace(/\s*\}\}$/i, "");
                var flag = _jsonText(json, condition, "boolean");

                var tmpStr = v.substring(rex.lastIndex, v.length);
                var endIfIndex = _getIfBlockEnd(tmpStr);
                if (flag){ //if 为 true
                    var parseStr = _parseHtml(tmpStr.substring(0, endIfIndex.codeIndex), json);
                    var vLeft = v.substring(0, match.index);
                    var vRight = v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
                    v = vLeft + parseStr + vRight;
                    offset = parseStr.length - fullMatch.length;
                }else{
                    v = v.substring(0, match.index) + v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
                    offset = 0-fullMatch.length;
                }
            }else  if (fullMatch.search(/\{\{each\s+/)!==-1) { //each statement
                var itemString = fullMatch.replace(/^\{\{each\s*/, "");
                itemString = itemString.replace(/\s*\}\}$/, "");
                var eachValue = _jsonText(json, itemString, "object");

                var tmpEachStr = v.substring(rex.lastIndex, v.length);
                var endEachIndex = _getEachBlockEnd(tmpEachStr);

                var parseEachStr = tmpEachStr.substring(0, endEachIndex.codeIndex);
                var eachResult = "";
                if (eachValue && _typeOf(eachValue)==="array"){
                    for (var i=0; i<eachValue.length; i++){
                        eachValue[i]._ = json;
                        eachResult += _parseHtml(parseEachStr, eachValue[i]);
NoSubject's avatar
NoSubject 已提交
757
                    }
NoSubject's avatar
NoSubject 已提交
758 759 760 761 762 763 764
                    var eLeft = v.substring(0, match.index);
                    var eRight = v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
                    v = eLeft + eachResult + eRight;
                    offset = eachResult.length - fullMatch.length;
                }else{
                    v = v.substring(0, match.index) + v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
                    offset = 0-fullMatch.length;
NoSubject's avatar
NoSubject 已提交
765
                }
NoSubject's avatar
NoSubject 已提交
766 767 768 769 770 771 772

            }else{ //text statement
                var text = fullMatch.replace(/^\{\{\s*/, "");
                text = text.replace(/\}\}\s*$/, "");
                var value = _jsonText(json, text);
                offset = value.length-fullMatch.length;
                v = v.substring(0, match.index) + value + v.substring(rex.lastIndex, v.length);
NoSubject's avatar
NoSubject 已提交
773
            }
NoSubject's avatar
NoSubject 已提交
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
            rex.lastIndex = rex.lastIndex + offset;
        }
        return v;
    };
    var _jsonText = function(json, text, type){
        try {
            var $ = json;
            var f = eval("(function($){\n return "+text+";\n})");
            returnValue = f.apply(json, [$]);
            if (returnValue===undefined) returnValue="";
            if (type==="boolean") return (!!returnValue);
            if (type==="object") return returnValue;
            returnValue = returnValue.toString();
            return returnValue || "";
        }catch(e){
            if (type==="boolean") return false;
            if (type==="object") return null;
            return "";
NoSubject's avatar
NoSubject 已提交
792 793 794
        }
    };

NoSubject's avatar
NoSubject 已提交
795 796
    o2.bindJson = function(str, json){
        return _parseHtml(str, json);
NoSubject's avatar
NoSubject 已提交
797 798
    };
    String.prototype.bindJson = function(json){
NoSubject's avatar
NoSubject 已提交
799
        return _parseHtml(this, json);
NoSubject's avatar
NoSubject 已提交
800 801
    };

NoSubject's avatar
NoSubject 已提交
802 803


NoSubject's avatar
NoSubject 已提交
804
    //dom ready
NoSubject's avatar
NoSubject 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
    var _dom = {
        ready: false,
        loaded: false,
        checks: [],
        shouldPoll: false,
        timer: null,
        testElement: document.createElement('div'),
        readys: [],

        domready: function(){
            clearTimeout(_dom.timer);
            if (_dom.ready) return;
            _dom.loaded = _dom.ready = true;
            _removeListener(document, 'DOMContentLoaded', _dom.checkReady);
            _removeListener(document, 'readystatechange', _dom.check);
            _dom.onReady();
        },
        check: function(){
            for (var i = _dom.checks.length; i--;) if (_dom.checks[i]() && window.MooTools && o2.core && o2.more){
                _dom.domready();
                return true;
            }
            return false;
        },
        poll: function(){
            clearTimeout(_dom.timer);
            if (!_dom.check()) _dom.timer = setTimeout(_dom.poll, 10);
        },

        /*<ltIE8>*/
        // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
        // testElement.doScroll() throws when the DOM is not ready, only in the top window
        doScrollWorks: function(){
            try {
                _dom.testElement.doScroll();
                return true;
            } catch (e){}
            return false;
        },
        /*</ltIE8>*/

        onReady: function(){
            for (var i=0; i<_dom.readys.length; i++){
                this.readys[i].apply(window);
            }
        },
        addReady: function(fn){
            if (_dom.loaded){
                if (fn) fn.apply(window);
            }else{
                if (fn) _dom.readys.push(fn);
            }
            return _dom;
        },
        checkReady: function(){
            _dom.checks.push(function(){return true});
            _dom.check();
        }
    };
    var _loadO2 = function(){
        this.o2.load("o2.core", _dom.check);
        this.o2.load("o2.more", _dom.check);
    };

    _addListener(document, 'DOMContentLoaded', _dom.checkReady);

    /*<ltIE8>*/
    // If doScroll works already, it can't be used to determine domready
    //   e.g. in an iframe
    if (_dom.testElement.doScroll && !_dom.doScrollWorks()){
        _dom.checks.push(_dom.doScrollWorks);
        _dom.shouldPoll = true;
    }
    /*</ltIE8>*/

    if (document.readyState) _dom.checks.push(function(){
        var state = document.readyState;
        return (state == 'loaded' || state == 'complete');
    });

    if ('onreadystatechange' in document) _addListener(document, 'readystatechange', _dom.check);
    else _dom.shouldPoll = true;

    if (_dom.shouldPoll) _dom.poll();

NoSubject's avatar
NoSubject 已提交
890 891 892 893 894
    if (!window.MooTools){
        this.o2.load("mootools", function(){ _loadO2(); _dom.check(); });
    }else{
        _loadO2();
    }
NoSubject's avatar
NoSubject 已提交
895 896
    this.o2.addReady = function(fn){ _dom.addReady.call(_dom, fn); };
})();