UNPKG

iweb-tool

Version:
1,826 lines (1,646 loc) 467 kB
var U_LANGUAGES = "i_languages"; var U_THEME = "u_theme"; var U_LOCALE = "u_locale"; var U_USERCODE = "u_usercode"; var enumerables = true,enumerablesTest = {toString: 1},toString = Object.prototype.toString; for (var i in enumerablesTest) { enumerables = null; } if (enumerables) { enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor']; } window.u = window.u || {}; //window.$ = {} var u = window.u; //var $ = u; u.enumerables = enumerables; /** * 复制对象属性 * * @param {Object} 目标对象 * @param {config} 源对象 */ u.extend = function(object, config) { var args = arguments,options; if(args.length > 1){ for(var len=1; len<args.length; len++){ options = args[len]; if (object && options && typeof options === 'object') { var i, j, k; for (i in options) { object[i] = options[i]; } if (enumerables) { for (j = enumerables.length; j--;) { k = enumerables[j]; if (options.hasOwnProperty(k)) { object[k] = options[k]; } } } } } } return object; }; u.extend(u, { setCookie: function (sName, sValue, oExpires, sPath, sDomain, bSecure) { var sCookie = sName + "=" + encodeURIComponent(sValue); if (oExpires) sCookie += "; expires=" + oExpires.toGMTString(); if (sPath) sCookie += "; path=" + sPath; if (sDomain) sCookie += "; domain=" + sDomain; if (bSecure) sCookie += "; secure=" + bSecure; document.cookie = sCookie; }, getCookie: function (sName) { var sRE = "(?:; )?" + sName + "=([^;]*);?"; var oRE = new RegExp(sRE); if (oRE.test(document.cookie)) { return decodeURIComponent(RegExp["$1"]); } else return null; }, /** * 创建一个带壳的对象,防止外部修改 * @param {Object} proto */ createShellObject: function (proto) { var exf = function () { } exf.prototype = proto; return new exf(); }, execIgnoreError: function (a, b, c) { try { a.call(b, c); } catch (e) { } }, on: function (element, eventName,child,listener) { if(arguments.length < 4){ listener = child; child = undefined; }else{ var childlistener = function(e){ if(!e){ return; } var tmpchildren = element.querySelectorAll(child) tmpchildren.forEach(function(node){ if(node == e.target){ listener.call(e.target,e) } }) } } //capture = capture || false; if(!element["uEvent"]){ //在dom上添加记录区 element["uEvent"] = {} } //判断是否元素上是否用通过on方法填加进去的事件 if(!element["uEvent"][eventName]){ element["uEvent"][eventName] = [child?childlistener:listener] element["uEvent"][eventName+'fn'] = function(){ var e = event?event:window.event; element["uEvent"][eventName].forEach(function(fn){ fn.call(element,e) }) } if (element.addEventListener) { // 用于支持DOM的浏览器 element.addEventListener(eventName, element["uEvent"][eventName+'fn']); } else if (element.attachEvent) { // 用于IE浏览器 element.attachEvent("on" + eventName,element["uEvent"][eventName+'fn'] ); } else { // 用于其它浏览器 element["on" + eventName] = element["uEvent"][eventName+'fn'] } }else{ //如果有就直接往元素的记录区添加事件 element["uEvent"][eventName].push(child?childlistener:listener) } }, off: function(element, eventName, listener){ //删除事件数组 var eventfn = element["uEvent"][eventName+'fn'] if (element.removeEventListener) { // 用于支持DOM的浏览器 element.removeEventListener(eventName,eventfn ); } else if (element.removeEvent) { // 用于IE浏览器 element.removeEvent("on" + eventName, eventfn); } else { // 用于其它浏览器 delete element["on" + eventName] } element["uEvent"][eventName] = undefined element["uEvent"][eventName+'fn'] = undefined }, trigger:function(element,eventName){ if(element["uEvent"] && element["uEvent"][eventName]){ element["uEvent"][eventName+'fn']() } }, /** * 增加样式 * @param value * @returns {*} */ addClass: function (element, value) { if (typeof element.classList === 'undefined') { u._addClass(element, value); } else { element.classList.add(value); } return u; }, removeClass: function (element, value) { if (typeof element.classList === 'undefined') { u._removeClass(element, value); } else { element.classList.remove(value); } return u; }, hasClass: function(element, value){ if (element.nodeName === '#text') return false; if (typeof element.classList === 'undefined') { return u._hasClass(element,value); }else{ return element.classList.contains(value); } }, toggleClass: function(element,value){ if (typeof element.classList === 'undefined') { return u._toggleClass(element,value); }else{ return element.classList.toggle(value); } }, css:function(element,csstext,val){ if(csstext instanceof Object){ for(var k in csstext){ var tmpcss = csstext[k] if(["width","height","top","bottom","left","right"].indexOf(k) > -1 && u.isNumber(tmpcss) ){ tmpcss = tmpcss + "px" } element.style[k] = tmpcss } }else{ if(arguments.length > 2){ element.style[csstext] = val }else{ u.getStyle(element,csstext) } } }, wrap:function(element,parent){ var p = u.makeDOM(parent) element.parentNode.insertBefore(p,element) p.appendChild(element) }, getStyle:function(element,key){ //不要在循环里用 var allCSS if(window.getComputedStyle){ allCSS = window.getComputedStyle(element) }else{ allCSS = element.currentStyle } if(allCSS[key] !== undefined){ return allCSS[key] }else{ return "" } }, /** * 统一zindex值, 不同控件每次显示时都取最大的zindex,防止显示错乱 */ getZIndex: function(){ if (!u.globalZIndex){ u.globalZIndex = 1000; } return u.globalZIndex ++; }, makeDOM: function(htmlString){ var tempDiv = document.createElement("div"); tempDiv.innerHTML = htmlString; var _dom = tempDiv.children[0]; return _dom; }, /** * 阻止冒泡 */ stopEvent: function(e){ if(typeof(e) != "undefined"){ if (e.stopPropagation) e.stopPropagation(); else { e.cancelBubble = true; } } }, getFunction: function(target, val){ if (!val || typeof val == 'function') return val if (typeof target[val] == 'function') return target[val] else if (typeof window[val] == 'function') return window[val] else if (val.indexOf('.') != -1){ var func = u.getJSObject(target, val) if (typeof func == 'function') return func func = u.getJSObject(window, val) if (typeof func == 'function') return func } return val }, getJSObject: function(target, names) { if(!names) { return; } if (typeof names == 'object') return names var nameArr = names.split('.') var obj = target for (var i = 0; i < nameArr.length; i++) { obj = obj[nameArr[i]] if (!obj) return null } return obj }, isDate: function(input){ return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; }, isNumber : function(obj){ return obj === +obj }, isArray: Array.isArray || function (val) { return Object.prototype.toString.call(val) === '[object Array]'; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, inArray :function(node,arr){ if(!arr instanceof Array){ throw "arguments is not Array"; } for(var i=0,k=arr.length;i<k;i++){ if(node==arr[i]){ return true; } } return false; }, each: function(obj,callback){ if(obj.forEach){ obj.forEach(function(v,k){callback(k,v)}) }else if(obj instanceof Object){ for(var k in obj){ callback(k,obj[k]) } }else{ return } } }); //core context (function() { var environment = {}; /** * client attributes */ var clientAttributes = {}; var sessionAttributes = {}; var fn = {}; var maskerMeta = { 'float': { precision: 2 }, 'datetime': { format: 'YYYY-MM-DD hh:mm:ss', metaType: 'DateTimeFormatMeta', speratorSymbol: '-' }, 'time':{ format:'hh:mm:ss' }, 'date':{ format:'YYYY-MM-DD' }, 'currency':{ precision: 2, curSymbol: '¥' }, 'percent':{ } }; /** * 获取环境信息 * @return {environment} */ fn.getEnvironment = function() { return u.createShellObject(environment); }; /** * 获取客户端参数对象 * @return {clientAttributes} */ fn.getClientAttributes = function() { var exf = function() {} return u.createShellObject(clientAttributes); } fn.setContextPath = function(contextPath) { return environment[IWEB_CONTEXT_PATH] = contextPath } fn.getContextPath = function(contextPath) { return environment[IWEB_CONTEXT_PATH] } /** * 设置客户端参数对象 * @param {Object} k 对象名称 * @param {Object} v 对象值(建议使用简单类型) */ fn.setClientAttribute = function(k, v) { clientAttributes[k] = v; } /** * 获取会话级参数对象 * @return {clientAttributes} */ fn.getSessionAttributes = function() { var exf = function() {} return u.createShellObject(sessionAttributes); } /** * 设置会话级参数对象 * @param {Object} k 对象名称 * @param {Object} v 对象值(建议使用简单类型) */ fn.setSessionAttribute = function(k, v) { sessionAttributes[k] = v; setCookie("ISES_" + k, v); } /** * 移除客户端参数 * @param {Object} k 对象名称 */ fn.removeClientAttribute = function(k) { clientAttributes[k] = null; execIgnoreError(function() { delete clientAttributes[k]; }) } /** * 获取多语信息 */ fn.getLanguages = function(){ return this.getEnvironment().languages }; /** * 收集环境信息(包括客户端参数) * @return {Object} */ fn.collectEnvironment = function() { var _env = this.getEnvironment(); var _ses = this.getSessionAttributes(); for (var i in clientAttributes) { _ses[i] = clientAttributes[i]; } _env.clientAttributes = _ses; return _env } /** * 设置数据格式信息 * @param {String} type * @param {Object} meta */ fn.setMaskerMeta = function(type, meta) { if (typeof type == 'function'){ getMetaFunc = type; }else{ if (!maskerMeta[type]) maskerMeta[type] = meta; else{ if (typeof meta != 'object') maskerMeta[type] = meta; else for (var key in meta){ maskerMeta[type][key] = meta[key]; } } } }; fn.getMaskerMeta = function(type) { if (typeof getMetaFunc == 'function'){ var meta = getMetaFunc.call(this); return meta[type]; }else return u.extend({}, maskerMeta[type]); }; environment.languages = u.getCookie(U_LANGUAGES) ? u.getCookie(U_LANGUAGES).split(',') : navigator.language; environment.theme = u.getCookie(U_THEME); environment.locale = u.getCookie(U_LOCALE); //environment.timezoneOffset = (new Date()).getTimezoneOffset() environment.usercode = u.getCookie(U_USERCODE); //init session attribute document.cookie.replace(/ISES_(\w*)=([^;]*);?/ig, function(a, b, c) { sessionAttributes[b] = c; }); var Core = function() {}; Core.prototype = fn; u.core = new Core(); })(); u.extend(u, { isIE: false, isFF: false, isOpera: false, isChrome: false, isSafari: false, isWebkit: false, isIE8_BEFORE: false, isIE8: false, isIE8_CORE: false, isIE9: false, isIE9_CORE: false, isIE10: false, isIE10_ABOVE: false, isIE11: false, isIOS: false, isIphone: false, isIPAD: false, isStandard: false, version: 0 }); (function(){ var userAgent = navigator.userAgent, rMsie = /(msie\s|trident.*rv:)([\w.]+)/, rFirefox = /(firefox)\/([\w.]+)/, rOpera = /(opera).+version\/([\w.]+)/, rChrome = /(chrome)\/([\w.]+)/, rSafari = /version\/([\w.]+).*(safari)/, version, ua = userAgent.toLowerCase(), s, browserMatch = null, match = rMsie.exec(ua); if (match != null) { browserMatch = { browser : "IE", version : match[2] || "0" }; } match = rFirefox.exec(ua); if (match != null) { browserMatch = { browser : match[1] || "", version : match[2] || "0" }; } match = rOpera.exec(ua); if (match != null) { browserMatch = { browser : match[1] || "", version : match[2] || "0" }; } match = rChrome.exec(ua); if (match != null) { browserMatch = { browser : match[1] || "", version : match[2] || "0" }; } match = rSafari.exec(ua); if (match != null) { browserMatch = { browser : match[2] || "", version : match[1] || "0" }; } if (match != null) { browserMatch = { browser : "", version : "0" }; } if (s=ua.match(/opera.([\d.]+)/)) { u.isOpera = true; }else if(browserMatch.browser=="IE"&&browserMatch.version==11){ u.isIE11 = true; u.isIE = true; }else if (s=ua.match(/chrome\/([\d.]+)/)) { u.isChrome = true; u.isStandard = true; } else if (s=ua.match(/version\/([\d.]+).*safari/)) { u.isSafari = true; u.isStandard = true; } else if (s=ua.match(/gecko/)) { //add by licza : support XULRunner u.isFF = true; u.isStandard = true; } else if (s=ua.match(/msie ([\d.]+)/)) { u.isIE = true; } else if (s=ua.match(/firefox\/([\d.]+)/)) { u.isFF = true; u.isStandard = true; } if (ua.match(/webkit\/([\d.]+)/)) { u.isWebkit = true; } if (ua.match(/ipad/i)){ u.isIOS = true; u.isIPAD = true; u.isStandard = true; } if (ua.match(/iphone/i)){ u.isIOS = true; u.isIphone = true; } u.version = version ? (browserMatch.version ? browserMatch.version : 0) : 0; if (u.isIE) { var intVersion = parseInt(u.version); var mode = document.documentMode; if(mode == null){ if (intVersion == 6 || intVersion == 7) { u.isIE8_BEFORE = true; } } else{ if(mode == 7){ u.isIE8_BEFORE = true; } else if (mode == 8) { u.isIE8 = true; } else if (mode == 9) { u.isIE9 = true; u.isSTANDARD = true; } else if (mode == 10) { u.isIE10 = true; u.isSTANDARD = true; u.isIE10_ABOVE = true; } else{ u.isSTANDARD = true; } if (intVersion == 8) { u.isIE8_CORE = true; } else if (intVersion == 9) { u.isIE9_CORE = true; } else if(browserMatch.version==11){ u.isIE11 = true; } else{ } } } })(); if (u.isIE8_BEFORE){ alert('uui 不支持IE8以前的浏览器版本,请更新IE浏览器或使用其它浏览器!') throw new Error('uui 不支持IE8以前的浏览器版本,请更新IE浏览器或使用其它浏览器!'); } if (u.isIE8 && u.polyfill !== true){ alert('IE8浏览器中使用uui 必须在u.js之前引入u-polyfill.js!'); throw new Error('IE8浏览器中使用uui 必须在uui之前引入u-polyfill.js!'); } //TODO 兼容 后面去掉 //u.Core = u.core; window.iweb = {}; window.iweb.Core = u.core; window.iweb.browser = { isIE: u.isIE, isFF: u.isFF, isOpera: u.isOpera, isChrome: u.isChrome, isSafari: u.isSafari, isWebkit: u.isWebkit, isIE8_BEFORE: u.isIE8_BEFORE, isIE8: u.isIE8, isIE8_CORE: u.isIE8_CORE, isIE9: u.isIE9, isIE9_CORE: u.isIE9_CORE, isIE10: u.isIE10, isIE10_ABOVE: u.isIE10_ABOVE, isIE11: u.isIE11, isIOS: u.isIOS, isIphone: u.isIphone, isIPAD: u.isIPAD, isStandard: u.isStandard, version: 0 }; NodeList.prototype.forEach = Array.prototype.forEach; /** * 获得字符串的字节长度 */ String.prototype.lengthb = function() { // var str = this.replace(/[^\x800-\x10000]/g, "***"); var str = this.replace(/[^\x00-\xff]/g, "**"); return str.length; }; /** * 将AFindText全部替换为ARepText */ String.prototype.replaceAll = function(AFindText, ARepText) { //自定义String对象的方法 var raRegExp = new RegExp(AFindText, "g"); return this.replace(raRegExp, ARepText); }; var XmlHttp = { get : "get", post : "post", reqCount : 4, createXhr : function() { var xmlhttp = null; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; }, ajax : function(_json) { var url = _json["url"]; var callback = _json["success"]; var async = (_json["async"] == undefined ? true : _json["async"]); var error = _json["error"]; var params = _json["data"]; var method = (_json["type"] == undefined ? XmlHttp.post : _json["type"]).toLowerCase(); url = XmlHttp.serializeUrl(url); params = XmlHttp.serializeParams(params); if (method == XmlHttp.get && params != null) { url += ("&" + params); params = null; //如果是get请求,保证最终会执行send(null) } var xmlhttp = XmlHttp.createXhr(); xmlhttp.open(method, url, async); if (method == XmlHttp.post) { xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8"); } var execount = 0; // 异步 if (async) { // readyState 从 1~4发生4次变化 xmlhttp.onreadystatechange = function() { execount++; // 等待readyState状态不再变化之后,再执行回调函数 if (execount == XmlHttp.reqCount) { XmlHttp.execBack(xmlhttp, callback, error); } }; // send方法要在在回调函数之后执行 xmlhttp.send(params); } else { // 同步 readyState 直接变为 4 // 并且 send 方法要在回调函数之前执行 xmlhttp.send(params); XmlHttp.execBack(xmlhttp, callback, error); } }, execBack : function(xmlhttp, callback, error) { if (xmlhttp.readyState == 4 && (xmlhttp.status == 200 || xmlhttp.status == 304)) { callback(xmlhttp.responseText,xmlhttp.status, xmlhttp); } else { if (error) { error(xmlhttp.responseText,xmlhttp.status, xmlhttp); } else { var errorMsg = "no error callback function!"; if(xmlhttp.responseText) { errorMsg = xmlhttp.responseText; } alert(errorMsg); // throw errorMsg; } } }, serializeUrl : function(url) { var cache = "cache=" + Math.random(); if (url.indexOf("?") > 0) { url += ("&" + cache); } else { url += ("?" + cache); } return url; }, serializeParams : function(params) { var ud = undefined; if (ud == params || params == null || params == "") { return null; } if (params.constructor == Object) { var result = ""; for ( var p in params) { result += (p + "=" + params[p] + "&"); } return result.substring(0, result.length - 1); } return params; } }; //if ($ && $.ajax) // u.ajax = $.ajax; //else u.ajax = XmlHttp.ajax; var Class = function (o) { if (!(this instanceof Class) && isFunction(o)) { return classify(o) } } // Create a new Class. // // var SuperPig = Class.create({ // Extends: Animal, // Implements: Flyable, // initialize: function() { // SuperPig.superclass.initialize.apply(this, arguments) // }, // Statics: { // COLOR: 'red' // } // }) // Class.create = function (parent, properties) { if (!isFunction(parent)) { properties = parent parent = null } properties || (properties = {}) parent || (parent = properties.Extends || Class) properties.Extends = parent // The created class constructor function SubClass() { // Call the parent constructor. parent.apply(this, arguments) // Only call initialize in self constructor. if (this.constructor === SubClass && this.initialize) { this.initialize.apply(this, arguments) } } // Inherit class (static) properties from parent. if (parent !== Class) { mix(SubClass, parent, parent.StaticsWhiteList) } // Add instance properties to the subclass. implement.call(SubClass, properties) // Make subclass extendable. return classify(SubClass) } function implement(properties) { var key, value for (key in properties) { value = properties[key] if (Class.Mutators.hasOwnProperty(key)) { Class.Mutators[key].call(this, value) } else { this.prototype[key] = value } } } // Create a sub Class based on `Class`. Class.extend = function (properties) { properties || (properties = {}) properties.Extends = this return Class.create(properties) } function classify(cls) { cls.extend = Class.extend cls.implement = implement return cls } // Mutators define special properties. Class.Mutators = { 'Extends': function (parent) { var existed = this.prototype var proto = createProto(parent.prototype) // Keep existed properties. mix(proto, existed) // Enforce the constructor to be what we expect. proto.constructor = this // Set the prototype chain to inherit from `parent`. this.prototype = proto // Set a convenience property in case the parent's prototype is // needed later. this.superclass = parent.prototype }, 'Implements': function (items) { isArray(items) || (items = [items]) var proto = this.prototype, item while (item = items.shift()) { mix(proto, item.prototype || item) } }, 'Statics': function (staticProperties) { mix(this, staticProperties) } } // Shared empty constructor function to aid in prototype-chain creation. function Ctor() { } // See: http://jsperf.com/object-create-vs-new-ctor var createProto = Object.__proto__ ? function (proto) { return { __proto__: proto } } : function (proto) { Ctor.prototype = proto return new Ctor() } // Helpers // ------------ function mix(r, s, wl) { // Copy "all" properties including inherited ones. for (var p in s) { if (s.hasOwnProperty(p)) { if (wl && indexOf(wl, p) === -1) continue // 在 iPhone 1 代等设备的 Safari 中,prototype 也会被枚举出来,需排除 if (p !== 'prototype') { r[p] = s[p] } } } } var toString = Object.prototype.toString var isArray = Array.isArray || function (val) { return toString.call(val) === '[object Array]' } var isFunction = function (val) { return toString.call(val) === '[object Function]' } var indexOf = Array.prototype.indexOf ? function (arr, item) { return arr.indexOf(item) } : function (arr, item) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === item) { return i } } return -1 } u.Class = Class function _findRegisteredClass(name, optReplace) { for (var i = 0; i < CompMgr.registeredControls.length; i++) { if (CompMgr.registeredControls[i].className === name) { if (typeof optReplace !== 'undefined') { CompMgr.registeredControls[i] = optReplace; } return CompMgr.registeredControls[i]; } } return false; } function _getUpgradedListOfElement(element) { var dataUpgraded = element.getAttribute('data-upgraded'); // Use `['']` as default value to conform the `,name,name...` style. return dataUpgraded === null ? [''] : dataUpgraded.split(','); } function _isElementUpgraded(element, jsClass) { var upgradedList = _getUpgradedListOfElement(element); return upgradedList.indexOf(jsClass) != -1; } function _upgradeElement(element, optJsClass) { if (!(typeof element === 'object' && element instanceof Element)) { throw new Error('Invalid argument provided to upgrade MDL element.'); } var upgradedList = _getUpgradedListOfElement(element); var classesToUpgrade = []; if (!optJsClass) { var className = element.className; for(var i=0; i< CompMgr.registeredControls.length; i++){ var component = CompMgr.registeredControls[i] if (className.indexOf(component.cssClass) > -1 && classesToUpgrade.indexOf(component) === -1 && !_isElementUpgraded(element, component.className)) { classesToUpgrade.push(component); } } } else if (!_isElementUpgraded(element, optJsClass)) { classesToUpgrade.push(_findRegisteredClass(optJsClass)); } // Upgrade the element for each classes. for (var i = 0, n = classesToUpgrade.length, registeredClass; i < n; i++) { registeredClass = classesToUpgrade[i]; if (registeredClass) { if (element[registeredClass.className]){ continue; } // Mark element as upgraded. upgradedList.push(registeredClass.className); element.setAttribute('data-upgraded', upgradedList.join(',')); var instance = new registeredClass.classConstructor(element); CompMgr.createdControls.push(instance); // Call any callbacks the user has registered with this component type. for (var j = 0, m = registeredClass.callbacks.length; j < m; j++) { registeredClass.callbacks[j](element); } element[registeredClass.className] = instance; } else { throw new Error('Unable to find a registered component for the given class.'); } } } function _upgradeDomInternal(optJsClass, optCssClass, ele) { if (typeof optJsClass === 'undefined' && typeof optCssClass === 'undefined') { for (var i = 0; i < CompMgr.registeredControls.length; i++) { _upgradeDomInternal(CompMgr.registeredControls[i].className, registeredControls[i].cssClass, ele); } } else { var jsClass = (optJsClass); if (!optCssClass) { var registeredClass = _findRegisteredClass(jsClass); if (registeredClass) { optCssClass = registeredClass.cssClass; } } var _ele = ele ? ele : document; var elements = _ele.querySelectorAll('.' + optCssClass); for (var n = 0; n < elements.length; n++) { _upgradeElement(elements[n], jsClass); } } } var CompMgr = { plugs: {}, dataAdapters:{}, /** 注册的控件*/ registeredControls: [], createdControls: [], /** * * @param options {el:'#content', model:{}} */ apply: function (options) { if(options){ var _el = options.el||document.body; var model = options.model; } if (typeof _el == 'string'){ _el = document.body.querySelector(_el); } if (_el == null || typeof _el != 'object') _el = document.body; var comps =_el.querySelectorAll('[u-meta]'); comps.forEach(function(element){ if (element['comp']) return; var options = JSON.parse(element.getAttribute('u-meta')); if (options && options['type']) { //var comp = CompMgr._createComp({el:element,options:options,model:model}); var comp = CompMgr.createDataAdapter({el:element,options:options,model:model}); if (comp) element['adpt'] = comp; } }); }, addPlug: function (config) { var plug = config['plug'], name = config['name']; this.plugs || (this.plugs = {}); if (this.plugs[name]) { throw new Error('plug has exist:' + name); } plug.compType = name; this.plugs[name] = plug }, addDataAdapter: function(config){ var adapter = config['adapter'], name = config['name']; //dataType = config['dataType'] || '' //var key = dataType ? name + '.' + dataType : name; this.dataAdapters || (dataAdapters = {}); if(this.dataAdapters[name]){ throw new Error('dataAdapter has exist:' + name); } this.dataAdapters[name] = adapter; }, getDataAdapter: function(name){ if (!name) return; this.dataAdapters || (dataAdapters = {}); //var key = dataType ? name + '.' + dataType : name; return this.dataAdapters[name]; }, createDataAdapter: function(options){ var opt = options['options']; var type = opt['type']; var adpt = this.dataAdapters[type]; if (!adpt) return null; var comp = new adpt(options); comp.type = type; return comp; }, _createComp: function (options) { var opt = options['options']; var type = opt['type']; var plug = this.plugs[type]; if (!plug) return null; var comp = new plug(options); comp.type = type; return comp; }, /** * 注册UI控件 */ regComp: function(config){ var newConfig = { classConstructor: config.comp, className: config.compAsString || config['compAsString'], cssClass: config.css || config['css'], callbacks: [] }; for(var i=0; i< this.registeredControls.length; i++){ var item = this.registeredControls[i]; //registeredControls.forEach(function(item) { if (item.cssClass === newConfig.cssClass) { throw new Error('The provided cssClass has already been registered: ' + item.cssClass); } if (item.className === newConfig.className) { throw new Error('The provided className has already been registered'); } }; this.registeredControls.push(newConfig); }, updateComp: function(ele){ for (var n = 0; n < this.registeredControls.length; n++) { _upgradeDomInternal(this.registeredControls[n].className,null ,ele); } } }; u.compMgr = CompMgr; /** * 加载控件 */ u.on(window, 'load', function() { 'use strict'; //扫描并生成控件 u.compMgr.updateComp(); }); if (window.i18n) { var scriptPath = getCurrentJsPath(), _temp = scriptPath.substr(0, scriptPath.lastIndexOf('/')), __FOLDER__ = _temp.substr(0, _temp.lastIndexOf('/')) u.uuii18n = u.extend({}, window.i18n) u.uuii18n.init({ postAsync: false, getAsync: false, fallbackLng: false, ns: {namespaces: ['uui-trans']}, resGetPath: __FOLDER__ + '/locales/__lng__/__ns__.json' }) } window.trans = u.trans = function (key, dftValue) { return u.uuii18n ? u.uuii18n.t('uui-trans:' + key) : dftValue } /* ======================================================================== * UUI: rsautils.js v 1.0.0 * * ======================================================================== * Copyright 2015 yonyou, Inc. * Licensed under MIT () * ======================================================================== */ /* * u.RSAUtils.encryptedString({exponent: 'xxxxx', modulus: 'xxxxx', text: 'xxxxx'}) * u.RSAUtils.decryptedString({exponent: 'xxxxx', modulus: 'xxxxx', text: 'xxxxx'}) */ if (typeof u.RSAUtils === 'undefined') u.RSAUtils = {}; var RSAUtils = u.RSAUtils; var biRadixBase = 2; var biRadixBits = 16; var bitsPerDigit = biRadixBits; var biRadix = 1 << 16; // = 2^16 = 65536 var biHalfRadix = biRadix >>> 1; var biRadixSquared = biRadix * biRadix; var maxDigitVal = biRadix - 1; var maxInteger = 9999999999999998; //maxDigits: //Change this to accommodate your largest number size. Use setMaxDigits() //to change it! // //In general, if you're working with numbers of size N bits, you'll need 2*N //bits of storage. Each digit holds 16 bits. So, a 1024-bit key will need // //1024 * 2 / 16 = 128 digits of storage. // var maxDigits; var ZERO_ARRAY; var bigZero, bigOne; var BigInt = u.BigInt = function (flag) { if (typeof flag == "boolean" && flag == true) { this.digits = null; } else { this.digits = ZERO_ARRAY.slice(0); } this.isNeg = false; }; RSAUtils.setMaxDigits = function (value) { maxDigits = value; ZERO_ARRAY = new Array(maxDigits); for (var iza = 0; iza < ZERO_ARRAY.length; iza++) ZERO_ARRAY[iza] = 0; bigZero = new BigInt(); bigOne = new BigInt(); bigOne.digits[0] = 1; }; RSAUtils.setMaxDigits(20); //The maximum number of digits in base 10 you can convert to an //integer without JavaScript throwing up on you. var dpl10 = 15; RSAUtils.biFromNumber = function (i) { var result = new BigInt(); result.isNeg = i < 0; i = Math.abs(i); var j = 0; while (i > 0) { result.digits[j++] = i & maxDigitVal; i = Math.floor(i / biRadix); } return result; }; //lr10 = 10 ^ dpl10 var lr10 = RSAUtils.biFromNumber(1000000000000000); RSAUtils.biFromDecimal = function (s) { var isNeg = s.charAt(0) == '-'; var i = isNeg ? 1 : 0; var result; // Skip leading zeros. while (i < s.length && s.charAt(i) == '0') ++i; if (i == s.length) { result = new BigInt(); } else { var digitCount = s.length - i; var fgl = digitCount % dpl10; if (fgl == 0) fgl = dpl10; result = RSAUtils.biFromNumber(Number(s.substr(i, fgl))); i += fgl; while (i < s.length) { result = RSAUtils.biAdd(RSAUtils.biMultiply(result, lr10), RSAUtils.biFromNumber(Number(s.substr(i, dpl10)))); i += dpl10; } result.isNeg = isNeg; } return result; }; RSAUtils.biCopy = function (bi) { var result = new BigInt(true); result.digits = bi.digits.slice(0); result.isNeg = bi.isNeg; return result; }; RSAUtils.reverseStr = function (s) { var result = ""; for (var i = s.length - 1; i > -1; --i) { result += s.charAt(i); } return result; }; var hexatrigesimalToChar = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; RSAUtils.biToString = function (x, radix) { // 2 <= radix <= 36 var b = new BigInt(); b.digits[0] = radix; var qr = RSAUtils.biDivideModulo(x, b); var result = hexatrigesimalToChar[qr[1].digits[0]]; while (RSAUtils.biCompare(qr[0], bigZero) == 1) { qr = RSAUtils.biDivideModulo(qr[0], b); digit = qr[1].digits[0]; result += hexatrigesimalToChar[qr[1].digits[0]]; } return (x.isNeg ? "-" : "") + RSAUtils.reverseStr(result); }; RSAUtils.biToDecimal = function (x) { var b = new BigInt(); b.digits[0] = 10; var qr = RSAUtils.biDivideModulo(x, b); var result = String(qr[1].digits[0]); while (RSAUtils.biCompare(qr[0], bigZero) == 1) { qr = RSAUtils.biDivideModulo(qr[0], b); result += String(qr[1].digits[0]); } return (x.isNeg ? "-" : "") + RSAUtils.reverseStr(result); }; var hexToChar = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; RSAUtils.digitToHex = function (n) { var mask = 0xf; var result = ""; for (var i = 0; i < 4; ++i) { result += hexToChar[n & mask]; n >>>= 4; } return RSAUtils.reverseStr(result); }; RSAUtils.biToHex = function (x) { var result = ""; var n = RSAUtils.biHighIndex(x); for (var i = RSAUtils.biHighIndex(x); i > -1; --i) { result += RSAUtils.digitToHex(x.digits[i]); } return result; }; RSAUtils.charToHex = function (c) { var ZERO = 48; var NINE = ZERO + 9; var littleA = 97; var littleZ = littleA + 25; var bigA = 65; var bigZ = 65 + 25; var result; if (c >= ZERO && c <= NINE) { result = c - ZERO; } else if (c >= bigA && c <= bigZ) { result = 10 + c - bigA; } else if (c >= littleA && c <= littleZ) { result = 10 + c - littleA; } else { result = 0; } return result; }; RSAUtils.hexToDigit = function (s) { var result = 0; var sl = Math.min(s.length, 4); for (var i = 0; i < sl; ++i) { result <<= 4; result |= RSAUtils.charToHex(s.charCodeAt(i)); } return result; }; RSAUtils.biFromHex = function (s) { var result = new BigInt(); var sl = s.length; for (var i = sl, j = 0; i > 0; i -= 4, ++j) { result.digits[j] = RSAUtils.hexToDigit(s.substr(Math.max(i - 4, 0), Math.min(i, 4))); } return result; }; RSAUtils.biFromString = function (s, radix) { var isNeg = s.charAt(0) == '-'; var istop = isNeg ? 1 : 0; var result = new BigInt(); var place = new BigInt(); place.digits[0] = 1; // radix^0 for (var i = s.length - 1; i >= istop; i--) { var c = s.charCodeAt(i); var digit = RSAUtils.charToHex(c); var biDigit = RSAUtils.biMultiplyDigit(place, digit); result = RSAUtils.biAdd(result, biDigit); place = RSAUtils.biMultiplyDigit(place, radix); } result.isNeg = isNeg; return result; }; RSAUtils.biDump = function (b) { return (b.isNeg ? "-" : "") + b.digits.join(" "); }; RSAUtils.biAdd = function (x, y) { var result; if (x.isNeg != y.isNeg) { y.isNeg = !y.isNeg; result = RSAUtils.biSubtract(x, y); y.isNeg = !y.isNeg; } else { result = new BigInt(); var c = 0; var n; for (var i = 0; i < x.digits.length; ++i) { n = x.digits[i] + y.digits[i] + c; result.digits[i] = n % biRadix; c = Number(n >= biRadix); } result.isNeg = x.isNeg; } return result; }; RSAUtils.biSubtract = function (x, y) { var result; if (x.isNeg != y.isNeg) { y.isNeg = !y.isNeg; result = RSAUtils.biAdd(x, y); y.isNeg = !y.isNeg; } else { result = new BigInt(); var n, c; c = 0; for (var i = 0; i < x.digits.length; ++i) { n = x.digits[i] - y.digits[i] + c; result.digits[i] = n % biRadix; // Stupid non-conforming modulus operation. if (result.digits[i] < 0) result.digits[i] += biRadix; c = 0 - Number(n < 0); } // Fix up the negative sign, if any. if (c == -1) { c = 0; for (var i = 0; i < x.digits.length; ++i) { n = 0 - result.digits[i] + c; result.digits[i] = n % biRadix; // Stupid non-conforming modulus operation. if (result.digits[i] < 0) result.digits[i] += biRadix; c = 0 - Number(n < 0); } // Result is opposite sign of arguments. result.isNeg = !x.isNeg; } else { // Result is same sign. result.isNeg = x.isNeg; } } return result; }; RSAUtils.biHighIndex = function (x) { var result = x.digits.length - 1; while (result > 0 && x.digits[result] == 0) --result; return result; }; RSAUtils.biNumBits = function (x) { var n = RSAUtils.biHighIndex(x); var d = x.digits[n]; var m = (n + 1) * bitsPerDigit; var result; for (result = m; result > m - bitsPerDigit; --result) { if ((d & 0x8000) != 0) break; d <<= 1; } return result; }; RSAUtils.biMultiply = function (x, y) { var result = new BigInt(); var c; var n = RSAUtils.biHighIndex(x); var t = RSAUtils.biHighIndex(y); var u, uv, k; for (var i = 0; i <= t; ++i) { c = 0; k = i; for (var j = 0; j <= n; ++j, ++k) { uv = result.digits[k] + x.digits[j] * y.digits[i] + c; result.digits[k] = uv & maxDigitVal; c = uv >>> biRadixBits; //c = Math.floor(uv / biRadix); } result.digits[i + n + 1] = c; } // Someone give me a logical xor, please. result.isNeg = x.isNeg != y.isNeg; return result; }; RSAUtils.biMultiplyDigit = function (x, y) { var n, c, uv; var result = new BigInt(); n = RSAUtils.biHighIndex(x); c = 0; for (var j = 0; j <= n; ++j) { uv = result.digits[j] + x.digits[j] * y + c; result.digits[j] = uv & maxDigitVal; c = uv >>> biRadixBits; //c = Math.floor(uv / biRadix); } result.digits[1 + n] = c; return result; }; RSAUtils.arrayCopy = function (src, srcStart, dest, destStart, n) { var m = Math.min(srcStart + n, src.length); for (var i = srcStart, j = destStart; i < m; ++i, ++j) { dest[j] = src[i]; } }; var highBitMasks = [0x0000, 0x8000, 0xC000, 0xE000, 0xF000, 0xF800, 0xFC00, 0xFE00, 0xFF00, 0xFF80, 0xFFC0, 0xFFE0, 0xFFF0, 0xFFF8, 0xFFFC, 0xFFFE, 0xFFFF]; RSAUtils.biShiftLeft = function (x, n) { var digitCount = Math.floor(n / bitsPerDigit); var result = new BigInt(); RSAUtils.arrayCopy(x.digits, 0, result.digits, digitCount, result.digits.length - digitCount); var bits = n % bitsPerDigit; var rightBits = bitsPerDigit - bits; for (var i = result.digits.length - 1, i1 = i - 1; i > 0; --i, --i1) { result.digits[i] = ((result.digits[i] << bits) & maxDigitVal) | ((result.digits[i1] & highBitMasks[bits]) >>> (rightBits)); } result.digits[0] = ((result.digits[i] << bits) & maxDigitVal); result.isNeg = x.isNeg; return result; }; var lowBitMasks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF]; RSAUtils.biShiftRight = function (x, n) { var digitCount = Math.floor(n / bitsPerDigit); var result = new BigInt(); RSAUtils.arrayCopy(x.digits, digitCount, result.digits, 0, x.digits.length - digitCount); var bits = n % bitsPerDigit; var leftBits = bitsPerDigit - bits; for (var i = 0, i1 = i + 1; i < result.digits.length - 1; ++i, ++i1) { result.digits[i] = (result.digits[i] >>> bits) | ((result.digits[i1] & lowBitMasks[bits]) << leftBits); } result.digits[result.digits.length - 1] >>>= bits; result.isNeg = x.isNeg; return result; }; RSAUtils.biMultiplyByRadixPower = function (x, n) { var result = new BigInt(); RSAUtils.arrayCopy(x.digits, 0, result.digits, n, result.digits.length - n); return result; }; RSAUtils.biDivideByRadixPower = function (x, n) { var result = new BigInt(); RSAUtils.arrayCopy(x.digits, n, result.digits, 0, result.digits.length - n); return result; }; RSAUtils.biModuloByRadixPower = function (x, n) { var result = new BigInt(); RSAUtils.arrayCopy(x.digits, 0, result.digits, 0, n); return result; }; RSAUtils.biCompare = function (x, y) { if (x.isNeg != y.isNeg) { return 1 - 2 * Number(x.isNeg); } for (var i = x.digits.length - 1; i >= 0; --i) { if (x.digits[i] != y.digits[i]) { if (x.isNeg) { return 1 - 2 * Number(x.digits[i] > y.digits[i]); } else { return 1 - 2 * Number(x.digits[i] < y.digits[i]); } } } return 0; }; RSAUtils.biDivideModulo = function (x, y) { var nb = RSAUtils.biNumBits(x); var tb = RSAUtils.biNumBits(y); var origYIsNeg = y.isNeg; var q, r; if (nb < tb) { // |x| < |y| if (x.isNeg) { q = RSAUtils.biCopy(bigOne); q.isNeg = !y.isNeg; x.isNeg = false; y.isNeg = false; r = biSubtract(y, x); // Restore signs, 'cause they're references. x.isNeg = true; y.isNeg = origYIsNeg; } else { q = new BigInt(); r = RSAUtils.biCopy(x); } return [q, r]; } q = new BigInt(); r = x; // Normalize Y. var t = Math.ceil(tb / bitsPerDigit) - 1; var lambda = 0; while (y.digits[t] < biHalfRadix) { y = RSAUtils.biShiftLeft(y, 1); ++lambda; ++tb; t = Math.ceil(tb / bitsPerDigit) - 1; } // Shift r over to keep the quotient constant. We'll shift the // remainder back at the end. r = RSAUtils.biShiftLeft(r, lambda); nb += lambda; // Update the bit count for x. var n = Math.ceil(nb / bitsPerDigit) - 1; var b = RSAUtils.biMultiplyByRadixPower(y, n - t); while (RSAUtils.biCompare(r, b) != -1) { ++q.digits[n - t]; r = RSAUtils.biSubtract(r, b); } for (var i = n; i > t; --i) { var ri = (i >= r.digits.length) ? 0 : r.digits[i]; var ri1 = (i - 1 >= r.digits.length) ? 0 : r.digits[i - 1]; var ri2 = (i - 2 >= r.digits.length) ? 0 : r.digits[i - 2]; var yt = (t >= y.digits.length) ? 0 : y.digits[t]; var yt1 = (t - 1 >= y.digits.length) ? 0 : y.digits[t - 1]; if (ri == yt) { q.digits[i - t - 1] = maxDigitVal; } else { q.digits[i - t - 1] = Math.floor((ri * biRadix + ri1) / yt); } var c1 = q.digits[i - t - 1] * ((yt * biRadix) + yt1); var c2 = (ri * biRadixSquared) + ((ri1 * biRadix) + ri2); while (c1 > c2) { --q.digits[i - t - 1]; c1 = q.digits[i - t - 1] * ((yt * biRadix) | yt1); c2 = (ri * biRadix * biRadix) + ((ri1 * biRadix) + ri2); } b = RSAUtils.biMultiplyByRadixPower(y, i - t - 1); r = RSAUtils.biSubtract(r, RSAUtils.biMultiplyDigit(b, q.digits[i - t - 1])); if (r.isNeg) { r = RSAUtils.biAdd(r, b); --q.digits[i - t - 1]; } } r = RSAUtils.biShiftRight(r, lambda); // Fiddle with the signs and stuff to make sure that 0 <= r < y. q.isNeg = x.isNeg != origYIsNeg; if (x.isNeg) { if (origYIsNeg) { q = RSAUtils.biAdd(q, bigOne); } else { q = RSAUtils.biSubtract(q, bigOne); } y = RSAUtils.biShiftRight(y, lambda); r = RSAUtils.biSubtract(y, r); } // Check for the unbelievably stupid degenerate case of r == -0. if (r.digits[0] == 0 && RSAUtils.biHighIndex(r) == 0) r.isNeg = false; return [q, r]; }; RSAUtils.biDivide = function (x, y) { return RSAUtils.biDivideModulo(x, y)[0]; }; RSAUtils.biModulo = function (x, y) { return RSAUtils.biDivideModulo(x, y)[1]; }; RSAUtils.biMultiplyMod = function (x, y, m) { return RSAUtils.biModulo(RSAUtils.biMultiply(x, y), m); }; RSAUtils.biPow = function (x, y) { var result = bigOne; var a = x; while (true) { if ((y & 1) != 0) result = RSAUtils.biMultiply(result, a); y >>= 1; if (y == 0) break; a = RSAUtils.biMultiply(a, a); } return result; }; RSAUtils.biPowMod = function (x, y, m) { var result = bigOne; var a = x; var k = y; while (true) { if ((k.digits[0] & 1) != 0) result = RSAUtils.biMultiplyMod(result, a, m); k = RSAUtils.biShiftRight(k, 1); if (k.digits[0] == 0 && RSAUtils.biHighIndex(k) == 0) break; a = RSAUtils.biMultiplyMod(a, a, m); } return result; }; u.BarrettMu = function (m) { this.modulus = RSAUtils.biCopy(m); this.k = RSAUtils.biHighIndex(this.modulus) + 1; var b2k = new BigInt(); b2k.digits[2 * this.k] = 1; // b2k = b^(2k) this.mu = RSAUtils.biDivide(b2k, this.modulus); this.bkplus1 = new BigInt(); this.bkplus1.digits[this.k + 1] = 1; // bkplus1 = b^(k+1) this.modulo = BarrettMu_modulo; this.multiplyMod = BarrettMu_multiplyMod; this.powMod = BarrettMu_powMod; }; function BarrettMu_modulo(x) { var $dmath = RSAUtils; var q1 = $dmath.biDivideByRadixPower(x, this.k - 1); var q2 = $dmath.biMultiply(q1, this.mu); var q3 = $dmath.biDivideByRadixPower(q2, this.k + 1); var r1 = $dmath.biModuloByRadixPower(x, this.k + 1); var r2term = $dmath.biMultiply(q3, this.modulus); var r2 = $dmath.biModuloByRadixPower(r2term, this.k + 1); var r = $dmath.biSubtract(r1, r2); if (r.isNeg) { r = $dmath.biAdd(r, this.bkplus1); } var rgtem = $dmath.biCompare(r, this.modulus) >= 0; while (rgtem) { r = $dmath.biSubtract(r, this.modulus); rgtem = $dmath.biCompare(r, this.modulus) >= 0; } return r; } function BarrettMu_multiplyMod(x, y) { /* x = this.modulo(x); y = this.modulo(y); */ var xy = RSAUtils.biMultiply(x, y); return this.modulo(xy); } function BarrettMu_powMod(x, y) { var result = new BigInt(); result.digits[0] = 1; var a = x; var k = y; while (true) { if ((k.digits[0] & 1) != 0) result = this.multiplyMod(result, a); k = RSAUtils.biShiftRight(k, 1); if (k.digits[0] == 0 && RSAUtils.biHighIndex(k) == 0) break; a = this.multiplyMod(a, a); } return result; } var RSAKeyPair = function (encryptionExponent, decryptionExponent, modulus) { var $dmath = RSAUtils; this.e = $dmath.biFromHex(encryptionExponent); this.d = $dmath.biFro